mirror of https://github.com/vladmandic/human
7873 lines
1.5 MiB
7873 lines
1.5 MiB
/*
|
|
Human
|
|
homepage: <https://github.com/vladmandic/human>
|
|
author: <https://github.com/vladmandic>'
|
|
*/
|
|
|
|
var Human=(()=>{var t2=Object.defineProperty;var LT=(e,t,n)=>t in e?t2(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var BT=e=>t2(e,"__esModule",{value:!0});var Jo=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof require!="undefined"?require:t)[n]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var Mc=(e,t)=>{BT(e);for(var n in t)t2(e,n,{get:t[n],enumerable:!0})};var ve=(e,t,n)=>(LT(e,typeof t!="symbol"?t+"":t,n),n),c5=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var zc=(e,t,n)=>(c5(e,t,"read from private field"),n?n.call(e):t.get(e)),Lc=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},Bc=(e,t,n,s)=>(c5(e,t,"write to private field"),s?s.call(e,n):t.set(e,n),n);var ige={};Mc(ige,{Human:()=>Z8,Models:()=>Mp,default:()=>Z8,defaults:()=>xa,env:()=>ie});function ct(e,t){let n=e.endsWith("/")?"":"/",r=t.startsWith(".")||t.startsWith("/")||t.startsWith("http:")||t.startsWith("https:")||t.startsWith("file:")?`${t}`:`${e}${n}${t}`;if(!r.toLocaleLowerCase().includes(".json"))throw new Error(`modelpath error: ${r} expecting json file`);return r}function ae(...e){let t=new Date,n=`${t.getHours().toString().padStart(2,"0")}:${t.getMinutes().toString().padStart(2,"0")}:${t.getSeconds().toString().padStart(2,"0")}.${t.getMilliseconds().toString().padStart(3,"0")}`;e&&console.log(n,"Human:",...e)}var ot=()=>typeof performance!="undefined"?performance.now():parseInt((Number(process.hrtime.bigint())/1e3/1e3).toString());function n2(e,t,n="config",s=[]){for(let r of Object.keys(t))if(typeof t[r]=="object")n2(e[r],t[r],r,s);else{let a=e&&typeof e[r]!="undefined";a||s.push({reason:"unknown property",where:`${n}.${r} = ${t[r]}`});let o=e&&typeof e[r]==typeof t[r];a&&!o&&s.push({reason:"property type mismatch",where:`${n}.${r} = ${t[r]}`,expected:typeof e[r]})}return t.debug&&n==="config"&&s.length>0&&ae("invalid configuration",s),s}function fn(...e){let t=n=>n&&typeof n=="object";return e.reduce((n,s)=>(Object.keys(s||{}).forEach(r=>{let a=n[r],o=s[r];Array.isArray(a)&&Array.isArray(o)?n[r]=a.concat(...o):t(a)&&t(o)?n[r]=fn(a,o):n[r]=o}),n),{})}var xa={backend:"",modelBasePath:"",wasmPath:"",debug:!0,async:!0,warmup:"full",cacheSensitivity:.75,skipFrame:!1,filter:{enabled:!0,width:0,height:0,flip:!1,return:!0,brightness:0,contrast:0,sharpness:0,blur:0,saturation:0,hue:0,negative:!1,sepia:!1,vintage:!1,kodachrome:!1,technicolor:!1,polaroid:!1,pixelate:0},gesture:{enabled:!0},face:{enabled:!0,detector:{modelPath:"blazeface.json",rotation:!0,maxDetected:1,skipFrames:11,minConfidence:.2,iouThreshold:.1,return:!1},mesh:{enabled:!0,modelPath:"facemesh.json"},iris:{enabled:!0,modelPath:"iris.json"},emotion:{enabled:!0,minConfidence:.1,skipFrames:12,modelPath:"emotion.json"},description:{enabled:!0,modelPath:"faceres.json",skipFrames:13,minConfidence:.1}},body:{enabled:!0,modelPath:"movenet-lightning.json",detector:{modelPath:""},maxDetected:-1,minConfidence:.2,skipFrames:1},hand:{enabled:!0,rotation:!0,skipFrames:2,minConfidence:.5,iouThreshold:.2,maxDetected:-1,landmarks:!0,detector:{modelPath:"handtrack.json"},skeleton:{modelPath:"handskeleton.json"}},object:{enabled:!1,modelPath:"mb3-centernet.json",minConfidence:.2,iouThreshold:.4,maxDetected:10,skipFrames:15},segmentation:{enabled:!1,modelPath:"selfie.json",blur:8}};var Sl={};Mc(Sl,{Abs:()=>ni,Acos:()=>ql,Acosh:()=>Xl,AdadeltaOptimizer:()=>Pf,AdagradOptimizer:()=>Ff,AdamOptimizer:()=>Of,AdamaxOptimizer:()=>Mf,Add:()=>qr,AddN:()=>wa,All:()=>Kl,Any:()=>Zl,ArgMax:()=>ka,ArgMin:()=>Yl,Asin:()=>Jl,Asinh:()=>Ql,Atan:()=>eu,Atan2:()=>nu,Atanh:()=>tu,AvgPool:()=>Ia,AvgPool3D:()=>Hc,AvgPool3DGrad:()=>mh,AvgPoolGrad:()=>fh,BackendWasm:()=>bC,BatchMatMul:()=>Sa,BatchToSpaceND:()=>si,Bincount:()=>gh,BroadcastArgs:()=>u2,BroadcastTo:()=>E5,Callback:()=>Ak,CallbackList:()=>cw,Cast:()=>Ca,Ceil:()=>Ta,ClipByValue:()=>Xr,Complex:()=>jc,ComplexAbs:()=>qc,Concat:()=>ri,Conv2D:()=>Na,Conv2DBackpropFilter:()=>yh,Conv2DBackpropInput:()=>Ea,Conv3D:()=>Xc,Conv3DBackpropFilterV2:()=>Ah,Conv3DBackpropInputV2:()=>xh,Cos:()=>Ra,Cosh:()=>$a,CropAndResize:()=>oi,Cumsum:()=>ai,CustomCallback:()=>pw,DataStorage:()=>Vc,DenseBincount:()=>bh,DepthToSpace:()=>ii,DepthwiseConv2dNative:()=>Da,DepthwiseConv2dNativeBackpropFilter:()=>vh,DepthwiseConv2dNativeBackpropInput:()=>wh,Diag:()=>kh,Dilation2D:()=>Kc,Dilation2DBackpropFilter:()=>Sh,Dilation2DBackpropInput:()=>Ih,ENV:()=>gs,EarlyStopping:()=>bk,Einsum:()=>Zc,Elu:()=>Pa,EluGrad:()=>Ch,Environment:()=>T5,Equal:()=>li,Erf:()=>su,Exp:()=>Fa,ExpandDims:()=>ui,Expm1:()=>ci,FFT:()=>Th,Fill:()=>ru,FlipLeftRight:()=>di,Floor:()=>Oa,FloorDiv:()=>Ma,FromPixels:()=>ad,FusedBatchNorm:()=>za,FusedConv2D:()=>mo,FusedDepthwiseConv2D:()=>go,GPGPUContext:()=>zm,GatherNd:()=>hi,GatherV2:()=>pi,GraphModel:()=>Jk,Greater:()=>fi,GreaterEqual:()=>La,History:()=>dw,IFFT:()=>Nh,Identity:()=>Ba,Imag:()=>Yc,InputSpec:()=>Yt,IsFinite:()=>au,IsInf:()=>ou,IsNan:()=>iu,KernelBackend:()=>Gl,LRN:()=>Qc,LRNGrad:()=>Rh,LayerVariable:()=>aw,LayersModel:()=>aa,LeakyRelu:()=>mi,Less:()=>gi,LessEqual:()=>yi,LinSpace:()=>Eh,Log:()=>Wa,Log1p:()=>lu,LogSoftmax:()=>R5,LogicalAnd:()=>Ai,LogicalNot:()=>uu,LogicalOr:()=>Jc,MathBackendWebGL:()=>ic,Max:()=>Va,MaxPool:()=>Ga,MaxPool3D:()=>ed,MaxPool3DGrad:()=>Dh,MaxPoolGrad:()=>$h,MaxPoolWithArgmax:()=>_h,Maximum:()=>Ua,Mean:()=>Ha,Min:()=>ja,Minimum:()=>qa,MirrorPad:()=>Xa,Mod:()=>cu,MomentumOptimizer:()=>zf,Multinomial:()=>Ph,Multiply:()=>Ka,Neg:()=>xi,NonMaxSuppressionV3:()=>vi,NonMaxSuppressionV4:()=>du,NonMaxSuppressionV5:()=>wi,NotEqual:()=>bi,OP_SCOPE_SUFFIX:()=>H5,OneHot:()=>Ii,OnesLike:()=>ki,Optimizer:()=>na,Pack:()=>Si,PadV2:()=>Za,Pool:()=>ON,Pow:()=>Ya,Prelu:()=>Ja,Prod:()=>Ci,RMSPropOptimizer:()=>Lf,RNN:()=>Fr,Range:()=>pu,Rank:()=>f2,Real:()=>td,RealDiv:()=>_a,Reciprocal:()=>hu,Reduction:()=>Vn,Relu:()=>Qa,Relu6:()=>to,Reshape:()=>Ti,ResizeBilinear:()=>eo,ResizeBilinearGrad:()=>Oh,ResizeNearestNeighbor:()=>fu,ResizeNearestNeighborGrad:()=>Fh,Reverse:()=>Ni,RotateWithOffset:()=>Wi,Round:()=>Ei,Rsqrt:()=>no,SGDOptimizer:()=>Fd,ScatterNd:()=>Ri,Select:()=>$i,Selu:()=>mu,Sequential:()=>qu,Sigmoid:()=>ro,Sign:()=>gu,Sin:()=>so,Sinh:()=>_i,Slice:()=>Di,Softmax:()=>io,Softplus:()=>yu,SpaceToBatchND:()=>Pi,SparseFillEmptyRows:()=>Mh,SparseReshape:()=>zh,SparseSegmentMean:()=>Lh,SparseSegmentSum:()=>Bh,SparseToDense:()=>nd,SplitV:()=>Fi,Sqrt:()=>ao,Square:()=>Au,SquaredDifference:()=>lo,Step:()=>ho,StridedSlice:()=>Oi,StringNGrams:()=>sd,StringSplit:()=>Wh,StringToHashBucketFast:()=>Vh,Sub:()=>uo,Sum:()=>oo,SymbolicTensor:()=>gr,Tan:()=>Mi,Tanh:()=>co,Tensor:()=>Ke,TensorBuffer:()=>tn,Tile:()=>Kr,TopK:()=>xu,Transform:()=>zi,Transpose:()=>po,Unique:()=>Uh,Unpack:()=>Li,UnsortedSegmentSum:()=>rd,Variable:()=>hd,ZerosLike:()=>Bi,_FusedMatMul:()=>fo,abs:()=>Kt,acos:()=>V2,acosh:()=>U2,add:()=>ue,addN:()=>nf,all:()=>sf,any:()=>Ad,argMax:()=>Fs,argMin:()=>G2,asin:()=>H2,asinh:()=>j2,atan:()=>q2,atan2:()=>X2,atanh:()=>K2,avgPool:()=>bd,avgPool3d:()=>J2,backend:()=>Tr,backend_util:()=>E,basicLSTMCell:()=>mR,batchNorm:()=>Yi,batchNorm2d:()=>P3,batchNorm3d:()=>F3,batchNorm4d:()=>O3,batchToSpaceND:()=>vd,bincount:()=>Q2,booleanMaskAsync:()=>w_,broadcastArgs:()=>M3,broadcastTo:()=>Eu,browser:()=>Xs,buffer:()=>We,callbacks:()=>OW,cast:()=>pe,ceil:()=>e1,clipByValue:()=>ss,clone:()=>ir,complex:()=>Ao,concat:()=>kt,concat1d:()=>z3,concat2d:()=>Ru,concat3d:()=>L3,concat4d:()=>B3,constraints:()=>zv,conv1d:()=>af,conv2d:()=>Qr,conv2dTranspose:()=>of,conv3d:()=>n1,conv3dTranspose:()=>V3,copyRegisteredKernels:()=>LN,cos:()=>wd,cosh:()=>lf,cosineWindow:()=>E1,cumsum:()=>uf,customGrad:()=>Er,data:()=>Qk,denseBincount:()=>U3,deprecationWarn:()=>B2,depthToSpace:()=>s1,depthwiseConv2d:()=>$u,deregisterOp:()=>zW,device_util:()=>wu,diag:()=>HR,dilation2d:()=>r1,disableDeprecationWarnings:()=>$E,dispose:()=>te,disposeVariables:()=>DE,div:()=>fe,divNoNan:()=>a1,dot:()=>G3,dropout:()=>dv,einsum:()=>H3,elu:()=>Du,enableDebugMode:()=>RE,enableProdMode:()=>E3,enclosingPowerOfTwo:()=>pv,engine:()=>ts,env:()=>Z,equal:()=>ys,erf:()=>o1,exp:()=>As,expandDims:()=>jt,expm1:()=>i1,eye:()=>l1,fft:()=>Dd,fill:()=>_u,findBackend:()=>W2,findBackendFactory:()=>OE,floor:()=>Pu,floorDiv:()=>tf,forceHalfFloat:()=>S4,fused:()=>So,gather:()=>Ji,gatherND:()=>cv,gather_util:()=>_2,getBackend:()=>lr,getGradient:()=>c2,getKernel:()=>Gh,getKernelsForBackend:()=>Zr,gpgpu_util:()=>QI,grad:()=>v$,grads:()=>w$,greater:()=>rs,greaterEqual:()=>ko,ifft:()=>Lu,imag:()=>cf,image:()=>$e,inTopKAsync:()=>__,initializers:()=>Hv,input:()=>Fw,io:()=>es,irfft:()=>If,isFinite:()=>j3,isInf:()=>q3,isNaN:()=>u1,keep:()=>An,kernel_impls:()=>Zs,layers:()=>nw,leakyRelu:()=>kd,less:()=>df,lessEqual:()=>Io,linalg:()=>Iv,linspace:()=>X3,loadGraphModel:()=>ut,loadLayersModel:()=>jL,localResponseNormalization:()=>c1,log:()=>xs,log1p:()=>Id,logSigmoid:()=>Z3,logSoftmax:()=>hf,logSumExp:()=>h1,logicalAnd:()=>Ks,logicalNot:()=>Sd,logicalOr:()=>ff,logicalXor:()=>ev,losses:()=>mF,matMul:()=>Xe,math:()=>u3,max:()=>Bn,maxPool:()=>Cd,maxPool3d:()=>f1,maxPoolWithArgmax:()=>tv,maximum:()=>Rr,mean:()=>Lt,memory:()=>Qh,meshgrid:()=>G$,metrics:()=>mk,min:()=>Td,minimum:()=>Fu,mirrorPad:()=>m1,mod:()=>g1,model:()=>GL,models:()=>gk,moments:()=>mf,movingAverage:()=>S_,mul:()=>L,multiRNNCell:()=>J$,multinomial:()=>nv,neg:()=>_t,nextFrame:()=>Bf,norm:()=>Nf,notEqual:()=>tl,oneHot:()=>Cu,ones:()=>bs,onesLike:()=>vs,op:()=>U,outerProduct:()=>sD,pad:()=>ur,pad1d:()=>oD,pad2d:()=>lD,pad3d:()=>cD,pad4d:()=>pD,pool:()=>sv,pow:()=>ea,prelu:()=>Ed,print:()=>s3,prod:()=>gf,profile:()=>_E,rand:()=>vD,randomGamma:()=>SD,randomNormal:()=>rv,randomUniform:()=>Ou,range:()=>Mu,ready:()=>ef,real:()=>Rd,reciprocal:()=>x1,registerBackend:()=>Xi,registerCallbackConstructor:()=>qL,registerGradient:()=>$5,registerKernel:()=>Yr,registerOp:()=>MW,regularizers:()=>yk,relu:()=>cr,relu6:()=>yf,removeBackend:()=>FE,reshape:()=>G,reverse:()=>ws,reverse1d:()=>PD,reverse2d:()=>OD,reverse3d:()=>zD,reverse4d:()=>BD,rfft:()=>_d,round:()=>Af,rsqrt:()=>xf,scalar:()=>Ee,scatterND:()=>uv,scatter_util:()=>P2,selu:()=>bf,separableConv2d:()=>b1,sequential:()=>HL,serialization:()=>de,setBackend:()=>R3,setPlatform:()=>ME,setWasmPath:()=>gce,setWasmPaths:()=>wC,setWebGLContext:()=>Em,setdiff1dAsync:()=>av,sigmoid:()=>ns,sign:()=>v1,signal:()=>fF,sin:()=>vf,sinh:()=>wf,slice:()=>_e,slice1d:()=>kf,slice2d:()=>w1,slice3d:()=>zu,slice4d:()=>$d,slice_util:()=>yn,softmax:()=>nl,softplus:()=>Qi,spaceToBatchND:()=>Nd,sparse:()=>Pd,sparseToDense:()=>N1,spectral:()=>hF,split:()=>xn,sqrt:()=>Cn,square:()=>vt,squaredDifference:()=>Sf,squeeze:()=>dt,stack:()=>Tn,step:()=>Bu,stridedSlice:()=>k1,string:()=>_f,sub:()=>xe,sum:()=>ke,sumOutType:()=>fd,tan:()=>I1,tanh:()=>Zi,tensor:()=>nn,tensor1d:()=>Zt,tensor2d:()=>dr,tensor3d:()=>c3,tensor4d:()=>p_,tensor5d:()=>h_,tensor6d:()=>f_,tensor_util:()=>ar,test_util:()=>C3,tidy:()=>j,tile:()=>Os,time:()=>PE,topk:()=>S1,train:()=>rl,transpose:()=>et,truncatedNormal:()=>Cf,unique:()=>Tf,unregisterGradient:()=>zN,unregisterKernel:()=>MN,unsortedSegmentSum:()=>C1,unstack:()=>Wn,upcastType:()=>Ln,util:()=>v,valueAndGrad:()=>k$,valueAndGrads:()=>I$,variable:()=>ov,variableGrads:()=>K3,version:()=>l0e,version_converter:()=>WV,version_core:()=>Jh,version_layers:()=>cy,version_wasm:()=>yce,version_webgl:()=>QY,webgl:()=>eJ,webgl_util:()=>kI,webgpu:()=>a6,where:()=>Pn,whereAsync:()=>T1,zeros:()=>qt,zerosLike:()=>tt});var WT=Object.create,uh=Object.defineProperty,VT=Object.getOwnPropertyDescriptor,UT=Object.getOwnPropertyNames,GT=Object.getPrototypeOf,HT=Object.prototype.hasOwnProperty,d5=e=>uh(e,"__esModule",{value:!0}),Ul=(e=>typeof Jo!="undefined"?Jo:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof Jo!="undefined"?Jo:t)[n]}):e)(function(e){if(typeof Jo!="undefined")return Jo.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')}),Dt=(e,t)=>function(){return t||(0,e[Object.keys(e)[0]])((t={exports:{}}).exports,t),t.exports},Le=(e,t)=>{d5(e);for(var n in t)uh(e,n,{get:t[n],enumerable:!0})},jT=(e,t,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of UT(t))!HT.call(e,s)&&s!=="default"&&uh(e,s,{get:()=>t[s],enumerable:!(n=VT(t,s))||n.enumerable});return e},Qo=e=>jT(d5(uh(e!=null?WT(GT(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e),qT=Dt({"node_modules/.pnpm/long@4.0.0/node_modules/long/src/long.js"(e,t){t.exports=s;var n=null;try{n=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(D){}function s(D,T,O){this.low=D|0,this.high=T|0,this.unsigned=!!O}s.prototype.__isLong__,Object.defineProperty(s.prototype,"__isLong__",{value:!0});function r(D){return(D&&D.__isLong__)===!0}s.isLong=r;var a={},o={};function i(D,T){var O,B,H;return T?(D>>>=0,(H=0<=D&&D<256)&&(B=o[D],B)?B:(O=c(D,(D|0)<0?-1:0,!0),H&&(o[D]=O),O)):(D|=0,(H=-128<=D&&D<128)&&(B=a[D],B)?B:(O=c(D,D<0?-1:0,!1),H&&(a[D]=O),O))}s.fromInt=i;function l(D,T){if(isNaN(D))return T?b:x;if(T){if(D<0)return b;if(D>=g)return $}else{if(D<=-y)return F;if(D+1>=y)return N}return D<0?l(-D,T).neg():c(D%m|0,D/m|0,T)}s.fromNumber=l;function c(D,T,O){return new s(D,T,O)}s.fromBits=c;var u=Math.pow;function d(D,T,O){if(D.length===0)throw Error("empty string");if(D==="NaN"||D==="Infinity"||D==="+Infinity"||D==="-Infinity")return x;if(typeof T=="number"?(O=T,T=!1):T=!!T,O=O||10,O<2||36<O)throw RangeError("radix");var B;if((B=D.indexOf("-"))>0)throw Error("interior hyphen");if(B===0)return d(D.substring(1),T,O).neg();for(var H=l(u(O,8)),z=x,X=0;X<D.length;X+=8){var ee=Math.min(8,D.length-X),J=parseInt(D.substring(X,X+ee),O);if(ee<8){var Q=l(u(O,ee));z=z.mul(Q).add(l(J))}else z=z.mul(H),z=z.add(l(J))}return z.unsigned=T,z}s.fromString=d;function p(D,T){return typeof D=="number"?l(D,T):typeof D=="string"?d(D,T):c(D.low,D.high,typeof T=="boolean"?T:D.unsigned)}s.fromValue=p;var h=1<<16,f=1<<24,m=h*h,g=m*m,y=g/2,A=i(f),x=i(0);s.ZERO=x;var b=i(0,!0);s.UZERO=b;var w=i(1);s.ONE=w;var k=i(1,!0);s.UONE=k;var S=i(-1);s.NEG_ONE=S;var N=c(4294967295|0,2147483647|0,!1);s.MAX_VALUE=N;var $=c(4294967295|0,4294967295|0,!0);s.MAX_UNSIGNED_VALUE=$;var F=c(0,2147483648|0,!1);s.MIN_VALUE=F;var R=s.prototype;R.toInt=function(){return this.unsigned?this.low>>>0:this.low},R.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},R.toString=function(T){if(T=T||10,T<2||36<T)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(F)){var O=l(T),B=this.div(O),H=B.mul(O).sub(this);return B.toString(T)+H.toInt().toString(T)}else return"-"+this.neg().toString(T);for(var z=l(u(T,6),this.unsigned),X=this,ee="";;){var J=X.div(z),Q=X.sub(J.mul(z)).toInt()>>>0,ne=Q.toString(T);if(X=J,X.isZero())return ne+ee;for(;ne.length<6;)ne="0"+ne;ee=""+ne+ee}},R.getHighBits=function(){return this.high},R.getHighBitsUnsigned=function(){return this.high>>>0},R.getLowBits=function(){return this.low},R.getLowBitsUnsigned=function(){return this.low>>>0},R.getNumBitsAbs=function(){if(this.isNegative())return this.eq(F)?64:this.neg().getNumBitsAbs();for(var T=this.high!=0?this.high:this.low,O=31;O>0&&(T&1<<O)==0;O--);return this.high!=0?O+33:O+1},R.isZero=function(){return this.high===0&&this.low===0},R.eqz=R.isZero,R.isNegative=function(){return!this.unsigned&&this.high<0},R.isPositive=function(){return this.unsigned||this.high>=0},R.isOdd=function(){return(this.low&1)==1},R.isEven=function(){return(this.low&1)==0},R.equals=function(T){return r(T)||(T=p(T)),this.unsigned!==T.unsigned&&this.high>>>31==1&&T.high>>>31==1?!1:this.high===T.high&&this.low===T.low},R.eq=R.equals,R.notEquals=function(T){return!this.eq(T)},R.neq=R.notEquals,R.ne=R.notEquals,R.lessThan=function(T){return this.comp(T)<0},R.lt=R.lessThan,R.lessThanOrEqual=function(T){return this.comp(T)<=0},R.lte=R.lessThanOrEqual,R.le=R.lessThanOrEqual,R.greaterThan=function(T){return this.comp(T)>0},R.gt=R.greaterThan,R.greaterThanOrEqual=function(T){return this.comp(T)>=0},R.gte=R.greaterThanOrEqual,R.ge=R.greaterThanOrEqual,R.compare=function(T){if(r(T)||(T=p(T)),this.eq(T))return 0;var O=this.isNegative(),B=T.isNegative();return O&&!B?-1:!O&&B?1:this.unsigned?T.high>>>0>this.high>>>0||T.high===this.high&&T.low>>>0>this.low>>>0?-1:1:this.sub(T).isNegative()?-1:1},R.comp=R.compare,R.negate=function(){return!this.unsigned&&this.eq(F)?F:this.not().add(w)},R.neg=R.negate,R.add=function(T){r(T)||(T=p(T));var O=this.high>>>16,B=this.high&65535,H=this.low>>>16,z=this.low&65535,X=T.high>>>16,ee=T.high&65535,J=T.low>>>16,Q=T.low&65535,ne=0,K=0,oe=0,ce=0;return ce+=z+Q,oe+=ce>>>16,ce&=65535,oe+=H+J,K+=oe>>>16,oe&=65535,K+=B+ee,ne+=K>>>16,K&=65535,ne+=O+X,ne&=65535,c(oe<<16|ce,ne<<16|K,this.unsigned)},R.subtract=function(T){return r(T)||(T=p(T)),this.add(T.neg())},R.sub=R.subtract,R.multiply=function(T){if(this.isZero())return x;if(r(T)||(T=p(T)),n){var O=n.mul(this.low,this.high,T.low,T.high);return c(O,n.get_high(),this.unsigned)}if(T.isZero())return x;if(this.eq(F))return T.isOdd()?F:x;if(T.eq(F))return this.isOdd()?F:x;if(this.isNegative())return T.isNegative()?this.neg().mul(T.neg()):this.neg().mul(T).neg();if(T.isNegative())return this.mul(T.neg()).neg();if(this.lt(A)&&T.lt(A))return l(this.toNumber()*T.toNumber(),this.unsigned);var B=this.high>>>16,H=this.high&65535,z=this.low>>>16,X=this.low&65535,ee=T.high>>>16,J=T.high&65535,Q=T.low>>>16,ne=T.low&65535,K=0,oe=0,ce=0,he=0;return he+=X*ne,ce+=he>>>16,he&=65535,ce+=z*ne,oe+=ce>>>16,ce&=65535,ce+=X*Q,oe+=ce>>>16,ce&=65535,oe+=H*ne,K+=oe>>>16,oe&=65535,oe+=z*Q,K+=oe>>>16,oe&=65535,oe+=X*J,K+=oe>>>16,oe&=65535,K+=B*ne+H*Q+z*J+X*ee,K&=65535,c(ce<<16|he,K<<16|oe,this.unsigned)},R.mul=R.multiply,R.divide=function(T){if(r(T)||(T=p(T)),T.isZero())throw Error("division by zero");if(n){if(!this.unsigned&&this.high===-2147483648&&T.low===-1&&T.high===-1)return this;var O=(this.unsigned?n.div_u:n.div_s)(this.low,this.high,T.low,T.high);return c(O,n.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?b:x;var B,H,z;if(this.unsigned){if(T.unsigned||(T=T.toUnsigned()),T.gt(this))return b;if(T.gt(this.shru(1)))return k;z=b}else{if(this.eq(F)){if(T.eq(w)||T.eq(S))return F;if(T.eq(F))return w;var X=this.shr(1);return B=X.div(T).shl(1),B.eq(x)?T.isNegative()?w:S:(H=this.sub(T.mul(B)),z=B.add(H.div(T)),z)}else if(T.eq(F))return this.unsigned?b:x;if(this.isNegative())return T.isNegative()?this.neg().div(T.neg()):this.neg().div(T).neg();if(T.isNegative())return this.div(T.neg()).neg();z=x}for(H=this;H.gte(T);){B=Math.max(1,Math.floor(H.toNumber()/T.toNumber()));for(var ee=Math.ceil(Math.log(B)/Math.LN2),J=ee<=48?1:u(2,ee-48),Q=l(B),ne=Q.mul(T);ne.isNegative()||ne.gt(H);)B-=J,Q=l(B,this.unsigned),ne=Q.mul(T);Q.isZero()&&(Q=w),z=z.add(Q),H=H.sub(ne)}return z},R.div=R.divide,R.modulo=function(T){if(r(T)||(T=p(T)),n){var O=(this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,T.low,T.high);return c(O,n.get_high(),this.unsigned)}return this.sub(this.div(T).mul(T))},R.mod=R.modulo,R.rem=R.modulo,R.not=function(){return c(~this.low,~this.high,this.unsigned)},R.and=function(T){return r(T)||(T=p(T)),c(this.low&T.low,this.high&T.high,this.unsigned)},R.or=function(T){return r(T)||(T=p(T)),c(this.low|T.low,this.high|T.high,this.unsigned)},R.xor=function(T){return r(T)||(T=p(T)),c(this.low^T.low,this.high^T.high,this.unsigned)},R.shiftLeft=function(T){return r(T)&&(T=T.toInt()),(T&=63)==0?this:T<32?c(this.low<<T,this.high<<T|this.low>>>32-T,this.unsigned):c(0,this.low<<T-32,this.unsigned)},R.shl=R.shiftLeft,R.shiftRight=function(T){return r(T)&&(T=T.toInt()),(T&=63)==0?this:T<32?c(this.low>>>T|this.high<<32-T,this.high>>T,this.unsigned):c(this.high>>T-32,this.high>=0?0:-1,this.unsigned)},R.shr=R.shiftRight,R.shiftRightUnsigned=function(T){if(r(T)&&(T=T.toInt()),T&=63,T===0)return this;var O=this.high;if(T<32){var B=this.low;return c(B>>>T|O<<32-T,O>>>T,this.unsigned)}else return T===32?c(O,0,this.unsigned):c(O>>>T-32,0,this.unsigned)},R.shru=R.shiftRightUnsigned,R.shr_u=R.shiftRightUnsigned,R.toSigned=function(){return this.unsigned?c(this.low,this.high,!1):this},R.toUnsigned=function(){return this.unsigned?this:c(this.low,this.high,!0)},R.toBytes=function(T){return T?this.toBytesLE():this.toBytesBE()},R.toBytesLE=function(){var T=this.high,O=this.low;return[O&255,O>>>8&255,O>>>16&255,O>>>24,T&255,T>>>8&255,T>>>16&255,T>>>24]},R.toBytesBE=function(){var T=this.high,O=this.low;return[T>>>24,T>>>16&255,T>>>8&255,T&255,O>>>24,O>>>16&255,O>>>8&255,O&255]},s.fromBytes=function(T,O,B){return B?s.fromBytesLE(T,O):s.fromBytesBE(T,O)},s.fromBytesLE=function(T,O){return new s(T[0]|T[1]<<8|T[2]<<16|T[3]<<24,T[4]|T[5]<<8|T[6]<<16|T[7]<<24,O)},s.fromBytesBE=function(T,O){return new s(T[4]<<24|T[5]<<16|T[6]<<8|T[7],T[0]<<24|T[1]<<16|T[2]<<8|T[3],O)}}}),XT=Dt({"(disabled):node_modules/.pnpm/node-fetch@2.6.5/node_modules/node-fetch/browser.js"(){}}),KT=Dt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/alea.js"(e,t){(function(n,s,r){function a(c){var u=this,d=l();u.next=function(){var p=2091639*u.s0+u.c*23283064365386963e-26;return u.s0=u.s1,u.s1=u.s2,u.s2=p-(u.c=p|0)},u.c=1,u.s0=d(" "),u.s1=d(" "),u.s2=d(" "),u.s0-=d(c),u.s0<0&&(u.s0+=1),u.s1-=d(c),u.s1<0&&(u.s1+=1),u.s2-=d(c),u.s2<0&&(u.s2+=1),d=null}function o(c,u){return u.c=c.c,u.s0=c.s0,u.s1=c.s1,u.s2=c.s2,u}function i(c,u){var d=new a(c),p=u&&u.state,h=d.next;return h.int32=function(){return d.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,p&&(typeof p=="object"&&o(p,d),h.state=function(){return o(d,{})}),h}function l(){var c=4022871197,u=function(d){d=d.toString();for(var p=0;p<d.length;p++){c+=d.charCodeAt(p);var h=.02519603282416938*c;c=h>>>0,h-=c,h*=c,c=h>>>0,h-=c,c+=h*4294967296}return(c>>>0)*23283064365386963e-26};return u}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.alea=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),ZT=Dt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xor128.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.x=0,c.y=0,c.z=0,c.w=0,c.next=function(){var p=c.x^c.x<<11;return c.x=c.y,c.y=c.z,c.z=c.w,c.w^=c.w>>>19^p^p>>>8},l===(l|0)?c.x=l:u+=l;for(var d=0;d<u.length+64;d++)c.x^=u.charCodeAt(d)|0,c.next()}function o(l,c){return c.x=l.x,c.y=l.y,c.z=l.z,c.w=l.w,c}function i(l,c){var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xor128=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),YT=Dt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xorwow.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.next=function(){var p=c.x^c.x>>>2;return c.x=c.y,c.y=c.z,c.z=c.w,c.w=c.v,(c.d=c.d+362437|0)+(c.v=c.v^c.v<<4^(p^p<<1))|0},c.x=0,c.y=0,c.z=0,c.w=0,c.v=0,l===(l|0)?c.x=l:u+=l;for(var d=0;d<u.length+64;d++)c.x^=u.charCodeAt(d)|0,d==u.length&&(c.d=c.x<<10^c.x>>>4),c.next()}function o(l,c){return c.x=l.x,c.y=l.y,c.z=l.z,c.w=l.w,c.v=l.v,c.d=l.d,c}function i(l,c){var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xorwow=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),JT=Dt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xorshift7.js"(e,t){(function(n,s,r){function a(l){var c=this;c.next=function(){var d=c.x,p=c.i,h,f,m;return h=d[p],h^=h>>>7,f=h^h<<24,h=d[p+1&7],f^=h^h>>>10,h=d[p+3&7],f^=h^h>>>3,h=d[p+4&7],f^=h^h<<7,h=d[p+7&7],h=h^h<<13,f^=h^h<<9,d[p]=f,c.i=p+1&7,f};function u(d,p){var h,f,m=[];if(p===(p|0))f=m[0]=p;else for(p=""+p,h=0;h<p.length;++h)m[h&7]=m[h&7]<<15^p.charCodeAt(h)+m[h+1&7]<<13;for(;m.length<8;)m.push(0);for(h=0;h<8&&m[h]===0;++h);for(h==8?f=m[7]=-1:f=m[h],d.x=m,d.i=0,h=256;h>0;--h)d.next()}u(c,l)}function o(l,c){return c.x=l.x.slice(),c.i=l.i,c}function i(l,c){l==null&&(l=+new Date);var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.x&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xorshift7=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),QT=Dt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xor4096.js"(e,t){(function(n,s,r){function a(l){var c=this;c.next=function(){var d=c.w,p=c.X,h=c.i,f,m;return c.w=d=d+1640531527|0,m=p[h+34&127],f=p[h=h+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,m=p[h]=m^f,c.i=h,m+(d^d>>>16)|0};function u(d,p){var h,f,m,g,y,A=[],x=128;for(p===(p|0)?(f=p,p=null):(p=p+"\0",f=0,x=Math.max(x,p.length)),m=0,g=-32;g<x;++g)p&&(f^=p.charCodeAt((g+32)%p.length)),g===0&&(y=f),f^=f<<10,f^=f>>>15,f^=f<<4,f^=f>>>13,g>=0&&(y=y+1640531527|0,h=A[g&127]^=f+y,m=h==0?m+1:0);for(m>=128&&(A[(p&&p.length||0)&127]=-1),m=127,g=4*128;g>0;--g)f=A[m+34&127],h=A[m=m+1&127],f^=f<<13,h^=h<<17,f^=f>>>15,h^=h>>>12,A[m]=f^h;d.w=y,d.X=A,d.i=m}u(c,l)}function o(l,c){return c.i=l.i,c.w=l.w,c.X=l.X.slice(),c}function i(l,c){l==null&&(l=+new Date);var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.X&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xor4096=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),eN=Dt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/tychei.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.next=function(){var p=c.b,h=c.c,f=c.d,m=c.a;return p=p<<25^p>>>7^h,h=h-f|0,f=f<<24^f>>>8^m,m=m-p|0,c.b=p=p<<20^p>>>12^h,c.c=h=h-f|0,c.d=f<<16^h>>>16^m,c.a=m-p|0},c.a=0,c.b=0,c.c=2654435769|0,c.d=1367130551,l===Math.floor(l)?(c.a=l/4294967296|0,c.b=l|0):u+=l;for(var d=0;d<u.length+20;d++)c.b^=u.charCodeAt(d)|0,c.next()}function o(l,c){return c.a=l.a,c.b=l.b,c.c=l.c,c.d=l.d,c}function i(l,c){var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.tychei=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),p5=Dt({"(disabled):crypto"(){}}),tN=Dt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/seedrandom.js"(e,t){(function(n,s){var r=this,a=256,o=6,i=52,l="random",c=s.pow(a,o),u=s.pow(2,i),d=u*2,p=a-1,h;function f(w,k,S){var N=[];k=k==!0?{entropy:!0}:k||{};var $=A(y(k.entropy?[w,b(n)]:w==null?x():w,3),N),F=new m(N),R=function(){for(var D=F.g(o),T=c,O=0;D<u;)D=(D+O)*a,T*=a,O=F.g(1);for(;D>=d;)D/=2,T/=2,O>>>=1;return(D+O)/T};return R.int32=function(){return F.g(4)|0},R.quick=function(){return F.g(4)/4294967296},R.double=R,A(b(F.S),n),(k.pass||S||function(D,T,O,B){return B&&(B.S&&g(B,F),D.state=function(){return g(F,{})}),O?(s[l]=D,T):D})(R,$,"global"in k?k.global:this==s,k.state)}s["seed"+l]=f;function m(w){var k,S=w.length,N=this,$=0,F=N.i=N.j=0,R=N.S=[];for(S||(w=[S++]);$<a;)R[$]=$++;for($=0;$<a;$++)R[$]=R[F=p&F+w[$%S]+(k=R[$])],R[F]=k;(N.g=function(D){for(var T,O=0,B=N.i,H=N.j,z=N.S;D--;)T=z[B=p&B+1],O=O*a+z[p&(z[B]=z[H=p&H+T])+(z[H]=T)];return N.i=B,N.j=H,O})(a)}function g(w,k){return k.i=w.i,k.j=w.j,k.S=w.S.slice(),k}function y(w,k){var S=[],N=typeof w,$;if(k&&N=="object")for($ in w)try{S.push(y(w[$],k-1))}catch(F){}return S.length?S:N=="string"?w:w+"\0"}function A(w,k){for(var S=w+"",N,$=0;$<S.length;)k[p&$]=p&(N^=k[p&$]*19)+S.charCodeAt($++);return b(k)}function x(){try{var w;return h&&(w=h.randomBytes)?w=w(a):(w=new Uint8Array(a),(r.crypto||r.msCrypto).getRandomValues(w)),b(w)}catch(N){var k=r.navigator,S=k&&k.plugins;return[+new Date,r,S,r.screen,b(n)]}}function b(w){return String.fromCharCode.apply(0,w)}if(A(s.random(),n),typeof t=="object"&&t.exports){t.exports=f;try{h=p5()}catch(w){}}else typeof define=="function"&&define.amd&&define(function(){return f})})([],Math)}}),h5=Dt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/index.js"(e,t){var n=KT(),s=ZT(),r=YT(),a=JT(),o=QT(),i=eN(),l=tN();l.alea=n,l.xor128=s,l.xorwow=r,l.xorshift7=a,l.xor4096=o,l.tychei=i,t.exports=l}}),nN=Dt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js"(e,t){(function(n,s,r){function a(c){var u=this,d=l();u.next=function(){var p=2091639*u.s0+u.c*23283064365386963e-26;return u.s0=u.s1,u.s1=u.s2,u.s2=p-(u.c=p|0)},u.c=1,u.s0=d(" "),u.s1=d(" "),u.s2=d(" "),u.s0-=d(c),u.s0<0&&(u.s0+=1),u.s1-=d(c),u.s1<0&&(u.s1+=1),u.s2-=d(c),u.s2<0&&(u.s2+=1),d=null}function o(c,u){return u.c=c.c,u.s0=c.s0,u.s1=c.s1,u.s2=c.s2,u}function i(c,u){var d=new a(c),p=u&&u.state,h=d.next;return h.int32=function(){return d.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,p&&(typeof p=="object"&&o(p,d),h.state=function(){return o(d,{})}),h}function l(){var c=4022871197,u=function(d){d=String(d);for(var p=0;p<d.length;p++){c+=d.charCodeAt(p);var h=.02519603282416938*c;c=h>>>0,h-=c,h*=c,c=h>>>0,h-=c,c+=h*4294967296}return(c>>>0)*23283064365386963e-26};return u}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.alea=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),sN=Dt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.x=0,c.y=0,c.z=0,c.w=0,c.next=function(){var p=c.x^c.x<<11;return c.x=c.y,c.y=c.z,c.z=c.w,c.w^=c.w>>>19^p^p>>>8},l===(l|0)?c.x=l:u+=l;for(var d=0;d<u.length+64;d++)c.x^=u.charCodeAt(d)|0,c.next()}function o(l,c){return c.x=l.x,c.y=l.y,c.z=l.z,c.w=l.w,c}function i(l,c){var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xor128=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),rN=Dt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.next=function(){var p=c.x^c.x>>>2;return c.x=c.y,c.y=c.z,c.z=c.w,c.w=c.v,(c.d=c.d+362437|0)+(c.v=c.v^c.v<<4^(p^p<<1))|0},c.x=0,c.y=0,c.z=0,c.w=0,c.v=0,l===(l|0)?c.x=l:u+=l;for(var d=0;d<u.length+64;d++)c.x^=u.charCodeAt(d)|0,d==u.length&&(c.d=c.x<<10^c.x>>>4),c.next()}function o(l,c){return c.x=l.x,c.y=l.y,c.z=l.z,c.w=l.w,c.v=l.v,c.d=l.d,c}function i(l,c){var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xorwow=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),aN=Dt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js"(e,t){(function(n,s,r){function a(l){var c=this;c.next=function(){var d=c.x,p=c.i,h,f,m;return h=d[p],h^=h>>>7,f=h^h<<24,h=d[p+1&7],f^=h^h>>>10,h=d[p+3&7],f^=h^h>>>3,h=d[p+4&7],f^=h^h<<7,h=d[p+7&7],h=h^h<<13,f^=h^h<<9,d[p]=f,c.i=p+1&7,f};function u(d,p){var h,f,m=[];if(p===(p|0))f=m[0]=p;else for(p=""+p,h=0;h<p.length;++h)m[h&7]=m[h&7]<<15^p.charCodeAt(h)+m[h+1&7]<<13;for(;m.length<8;)m.push(0);for(h=0;h<8&&m[h]===0;++h);for(h==8?f=m[7]=-1:f=m[h],d.x=m,d.i=0,h=256;h>0;--h)d.next()}u(c,l)}function o(l,c){return c.x=l.x.slice(),c.i=l.i,c}function i(l,c){l==null&&(l=+new Date);var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.x&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xorshift7=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),oN=Dt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js"(e,t){(function(n,s,r){function a(l){var c=this;c.next=function(){var d=c.w,p=c.X,h=c.i,f,m;return c.w=d=d+1640531527|0,m=p[h+34&127],f=p[h=h+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,m=p[h]=m^f,c.i=h,m+(d^d>>>16)|0};function u(d,p){var h,f,m,g,y,A=[],x=128;for(p===(p|0)?(f=p,p=null):(p=p+"\0",f=0,x=Math.max(x,p.length)),m=0,g=-32;g<x;++g)p&&(f^=p.charCodeAt((g+32)%p.length)),g===0&&(y=f),f^=f<<10,f^=f>>>15,f^=f<<4,f^=f>>>13,g>=0&&(y=y+1640531527|0,h=A[g&127]^=f+y,m=h==0?m+1:0);for(m>=128&&(A[(p&&p.length||0)&127]=-1),m=127,g=4*128;g>0;--g)f=A[m+34&127],h=A[m=m+1&127],f^=f<<13,h^=h<<17,f^=f>>>15,h^=h>>>12,A[m]=f^h;d.w=y,d.X=A,d.i=m}u(c,l)}function o(l,c){return c.i=l.i,c.w=l.w,c.X=l.X.slice(),c}function i(l,c){l==null&&(l=+new Date);var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.X&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xor4096=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),iN=Dt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.next=function(){var p=c.b,h=c.c,f=c.d,m=c.a;return p=p<<25^p>>>7^h,h=h-f|0,f=f<<24^f>>>8^m,m=m-p|0,c.b=p=p<<20^p>>>12^h,c.c=h=h-f|0,c.d=f<<16^h>>>16^m,c.a=m-p|0},c.a=0,c.b=0,c.c=2654435769|0,c.d=1367130551,l===Math.floor(l)?(c.a=l/4294967296|0,c.b=l|0):u+=l;for(var d=0;d<u.length+20;d++)c.b^=u.charCodeAt(d)|0,c.next()}function o(l,c){return c.a=l.a,c.b=l.b,c.c=l.c,c.d=l.d,c}function i(l,c){var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.tychei=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),lN=Dt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js"(e,t){(function(n,s,r){var a=256,o=6,i=52,l="random",c=r.pow(a,o),u=r.pow(2,i),d=u*2,p=a-1,h;function f(w,k,S){var N=[];k=k==!0?{entropy:!0}:k||{};var $=A(y(k.entropy?[w,b(s)]:w==null?x():w,3),N),F=new m(N),R=function(){for(var D=F.g(o),T=c,O=0;D<u;)D=(D+O)*a,T*=a,O=F.g(1);for(;D>=d;)D/=2,T/=2,O>>>=1;return(D+O)/T};return R.int32=function(){return F.g(4)|0},R.quick=function(){return F.g(4)/4294967296},R.double=R,A(b(F.S),s),(k.pass||S||function(D,T,O,B){return B&&(B.S&&g(B,F),D.state=function(){return g(F,{})}),O?(r[l]=D,T):D})(R,$,"global"in k?k.global:this==r,k.state)}function m(w){var k,S=w.length,N=this,$=0,F=N.i=N.j=0,R=N.S=[];for(S||(w=[S++]);$<a;)R[$]=$++;for($=0;$<a;$++)R[$]=R[F=p&F+w[$%S]+(k=R[$])],R[F]=k;(N.g=function(D){for(var T,O=0,B=N.i,H=N.j,z=N.S;D--;)T=z[B=p&B+1],O=O*a+z[p&(z[B]=z[H=p&H+T])+(z[H]=T)];return N.i=B,N.j=H,O})(a)}function g(w,k){return k.i=w.i,k.j=w.j,k.S=w.S.slice(),k}function y(w,k){var S=[],N=typeof w,$;if(k&&N=="object")for($ in w)try{S.push(y(w[$],k-1))}catch(F){}return S.length?S:N=="string"?w:w+"\0"}function A(w,k){for(var S=w+"",N,$=0;$<S.length;)k[p&$]=p&(N^=k[p&$]*19)+S.charCodeAt($++);return b(k)}function x(){try{var w;return h&&(w=h.randomBytes)?w=w(a):(w=new Uint8Array(a),(n.crypto||n.msCrypto).getRandomValues(w)),b(w)}catch(N){var k=n.navigator,S=k&&k.plugins;return[+new Date,n,S,n.screen,b(s)]}}function b(w){return String.fromCharCode.apply(0,w)}if(A(r.random(),s),typeof t=="object"&&t.exports){t.exports=f;try{h=p5()}catch(w){}}else typeof define=="function"&&define.amd?define(function(){return f}):r["seed"+l]=f})(typeof self!="undefined"?self:e,[],Math)}}),f5=Dt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/index.js"(e,t){var n=nN(),s=sN(),r=rN(),a=aN(),o=oN(),i=iN(),l=lN();l.alea=n,l.xor128=s,l.xorwow=r,l.xorshift7=a,l.xor4096=o,l.tychei=i,t.exports=l}}),m5=Dt({"(disabled):node_modules/.pnpm/string_decoder@1.1.1/node_modules/string_decoder/lib/string_decoder.js"(){}}),Wc=Dt({"(disabled):path"(){}}),uN=Dt({"(disabled):worker_threads"(){}}),cN=Dt({"(disabled):perf_hooks"(){}}),dN=Dt({"node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.9.0_@tensorflow+tfjs-core@3.9.0/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm-threaded-simd.js"(e,t){var n=function(){var s=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(s=s||__filename),function(r){r=r||{};function a(){return K.buffer!=Ye&&In(K.buffer),Yn}function o(){return K.buffer!=Ye&&In(K.buffer),Mt}function i(){return K.buffer!=Ye&&In(K.buffer),Hs}function l(){return K.buffer!=Ye&&In(K.buffer),Fn}function c(){return K.buffer!=Ye&&In(K.buffer),$s}var u=typeof r!="undefined"?r:{},d,p;u.ready=new Promise(function(C,P){d=C,p=P});var h={},f;for(f in u)u.hasOwnProperty(f)&&(h[f]=u[f]);var m=[],g="./this.program",y=function(C,P){throw P},A=!1,x=!1,b=!1,w=!1;A=typeof window=="object",x=typeof importScripts=="function",b=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",w=!A&&!b&&!x;var k=u.ENVIRONMENT_IS_PTHREAD||!1;k&&(Ye=u.buffer);var S="";function N(C){return u.locateFile?u.locateFile(C,S):S+C}var $,F,R,D,T,O;if(b){x?S=Wc().dirname(S)+"/":S=__dirname+"/",$=function(P,V){return T||(T=Ul("fs")),O||(O=Wc()),P=O.normalize(P),T.readFileSync(P,V?null:"utf8")},R=function(P){var V=$(P,!0);return V.buffer||(V=new Uint8Array(V)),Ae(V.buffer),V},process.argv.length>1&&(g=process.argv[1].replace(/\\/g,"/")),m=process.argv.slice(2),process.on("uncaughtException",function(C){if(!(C instanceof Oc))throw C}),process.on("unhandledRejection",Ur),y=function(C){process.exit(C)},u.inspect=function(){return"[Emscripten Module object]"};var B;try{B=uN()}catch(C){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),C}global.Worker=B.Worker}else w?(typeof read!="undefined"&&($=function(P){return read(P)}),R=function(P){var V;return typeof readbuffer=="function"?new Uint8Array(readbuffer(P)):(V=read(P,"binary"),Ae(typeof V=="object"),V)},typeof scriptArgs!="undefined"?m=scriptArgs:typeof arguments!="undefined"&&(m=arguments),typeof quit=="function"&&(y=function(C){quit(C)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(A||x)&&(x?S=self.location.href:typeof document!="undefined"&&document.currentScript&&(S=document.currentScript.src),typeof s!="undefined"&&s&&(S=s),S.indexOf("blob:")!==0?S=S.substr(0,S.lastIndexOf("/")+1):S="",b?($=function(P,V){return T||(T=Ul("fs")),O||(O=Wc()),P=O.normalize(P),T.readFileSync(P,V?null:"utf8")},R=function(P){var V=$(P,!0);return V.buffer||(V=new Uint8Array(V)),Ae(V.buffer),V}):($=function(C){var P=new XMLHttpRequest;return P.open("GET",C,!1),P.send(null),P.responseText},x&&(R=function(C){var P=new XMLHttpRequest;return P.open("GET",C,!1),P.responseType="arraybuffer",P.send(null),new Uint8Array(P.response)}),F=function(C,P,V){var Y=new XMLHttpRequest;Y.open("GET",C,!0),Y.responseType="arraybuffer",Y.onload=function(){if(Y.status==200||Y.status==0&&Y.response){P(Y.response);return}V()},Y.onerror=V,Y.send(null)}),D=function(C){document.title=C});b&&typeof performance=="undefined"&&(global.performance=cN().performance);var H=u.print||console.log.bind(console),z=u.printErr||console.warn.bind(console);for(f in h)h.hasOwnProperty(f)&&(u[f]=h[f]);h=null,u.arguments&&(m=u.arguments),u.thisProgram&&(g=u.thisProgram),u.quit&&(y=u.quit);var X=Atomics.load,ee=Atomics.store,J=Atomics.compareExchange,Q;u.wasmBinary&&(Q=u.wasmBinary);var ne=u.noExitRuntime||!0;typeof WebAssembly!="object"&&Ur("no native wasm support detected");var K,oe,ce=!1,he;function Ae(C,P){C||Ur("Assertion failed: "+P)}function Se(C){var P=u["_"+C];return Ae(P,"Cannot call unknown function "+C+", make sure it is exported"),P}function Ce(C,P,V,Y,ye){var me={string:function(On){var Vl=0;if(On!=null&&On!==0){var u5=(On.length<<2)+1;Vl=Ll(u5),mt(On,Vl,u5)}return Vl},array:function(On){var Vl=Ll(On.length);return ht(On,Vl),Vl}};function ge(On){return P==="string"?ze(On):P==="boolean"?Boolean(On):On}var Te=Se(C),yt=[],hn=0;if(Y)for(var en=0;en<Y.length;en++){var Aa=me[V[en]];Aa?(hn===0&&(hn=Fc()),yt[en]=Aa(Y[en])):yt[en]=Y[en]}var Wl=Te.apply(null,yt);return Wl=ge(Wl),hn!==0&&zl(hn),Wl}function Oe(C,P,V,Y){V=V||[];var ye=V.every(function(ge){return ge==="number"}),me=P!=="string";return me&&ye&&!Y?Se(C):function(){return Ce(C,P,V,arguments,Y)}}function Ue(C,P,V){for(var Y=P+V,ye="";!(P>=Y);){var me=C[P++];if(!me)return ye;if(!(me&128)){ye+=String.fromCharCode(me);continue}var ge=C[P++]&63;if((me&224)==192){ye+=String.fromCharCode((me&31)<<6|ge);continue}var Te=C[P++]&63;if((me&240)==224?me=(me&15)<<12|ge<<6|Te:me=(me&7)<<18|ge<<12|Te<<6|C[P++]&63,me<65536)ye+=String.fromCharCode(me);else{var yt=me-65536;ye+=String.fromCharCode(55296|yt>>10,56320|yt&1023)}}return ye}function ze(C,P){return C?Ue(o(),C,P):""}function wt(C,P,V,Y){if(!(Y>0))return 0;for(var ye=V,me=V+Y-1,ge=0;ge<C.length;++ge){var Te=C.charCodeAt(ge);if(Te>=55296&&Te<=57343){var yt=C.charCodeAt(++ge);Te=65536+((Te&1023)<<10)|yt&1023}if(Te<=127){if(V>=me)break;P[V++]=Te}else if(Te<=2047){if(V+1>=me)break;P[V++]=192|Te>>6,P[V++]=128|Te&63}else if(Te<=65535){if(V+2>=me)break;P[V++]=224|Te>>12,P[V++]=128|Te>>6&63,P[V++]=128|Te&63}else{if(V+3>=me)break;P[V++]=240|Te>>18,P[V++]=128|Te>>12&63,P[V++]=128|Te>>6&63,P[V++]=128|Te&63}}return P[V]=0,V-ye}function mt(C,P,V){return wt(C,o(),P,V)}function gt(C){for(var P=0,V=0;V<C.length;++V){var Y=C.charCodeAt(V);Y>=55296&&Y<=57343&&(Y=65536+((Y&1023)<<10)|C.charCodeAt(++V)&1023),Y<=127?++P:Y<=2047?P+=2:Y<=65535?P+=3:P+=4}return P}function ht(C,P){a().set(C,P)}function bt(C,P){return C%P>0&&(C+=P-C%P),C}var Ye,Yn,Mt,hs,kn,Hs,Fn,Rs,$s;function In(C){Ye=C,u.HEAP8=Yn=new Int8Array(C),u.HEAP16=hs=new Int16Array(C),u.HEAP32=Hs=new Int32Array(C),u.HEAPU8=Mt=new Uint8Array(C),u.HEAPU16=kn=new Uint16Array(C),u.HEAPU32=Fn=new Uint32Array(C),u.HEAPF32=Rs=new Float32Array(C),u.HEAPF64=$s=new Float64Array(C)}var Ds=u.INITIAL_MEMORY||16777216;if(k)K=u.wasmMemory,Ye=u.buffer;else if(u.wasmMemory)K=u.wasmMemory;else if(K=new WebAssembly.Memory({initial:Ds/65536,maximum:2147483648/65536,shared:!0}),!(K.buffer instanceof SharedArrayBuffer))throw z("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),b&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");K&&(Ye=K.buffer),Ds=Ye.byteLength,In(Ye);var _s,fs=[],wr=[],Wr=[],ha=[],Dl=[],kr=!1,Wp=!1;k||wr.push({func:function(){nh()}});function E0(){if(!k){if(u.preRun)for(typeof u.preRun=="function"&&(u.preRun=[u.preRun]);u.preRun.length;)Up(u.preRun.shift());Pl(fs)}}function Cc(){kr=!0,!k&&Pl(wr)}function R0(){k||Pl(Wr)}function Vp(){k||(Wp=!0)}function Jn(){if(!k){if(u.postRun)for(typeof u.postRun=="function"&&(u.postRun=[u.postRun]);u.postRun.length;)$0(u.postRun.shift());Pl(Dl)}}function Up(C){fs.unshift(C)}function $0(C){Dl.unshift(C)}var Vr=0,fa=null,Ko=null;function D0(C){Ae(!k,"addRunDependency cannot be used in a pthread worker"),Vr++,u.monitorRunDependencies&&u.monitorRunDependencies(Vr)}function _0(C){if(Vr--,u.monitorRunDependencies&&u.monitorRunDependencies(Vr),Vr==0&&(fa!==null&&(clearInterval(fa),fa=null),Ko)){var P=Ko;Ko=null,P()}}u.preloadedImages={},u.preloadedAudios={};function Ur(C){u.onAbort&&u.onAbort(C),k&&console.error("Pthread aborting at "+new Error().stack),C+="",z(C),ce=!0,he=1,C="abort("+C+"). Build with -s ASSERTIONS=1 for more info.";var P=new WebAssembly.RuntimeError(C);throw p(P),P}function Gp(C,P){return String.prototype.startsWith?C.startsWith(P):C.indexOf(P)===0}var _l="data:application/octet-stream;base64,";function Hp(C){return Gp(C,_l)}var P0="file://";function jp(C){return Gp(C,P0)}var Qn="tfjs-backend-wasm-threaded-simd.wasm";Hp(Qn)||(Qn=N(Qn));function qp(C){try{if(C==Qn&&Q)return new Uint8Array(Q);if(R)return R(C);throw"both async and sync fetching of the wasm failed"}catch(P){Ur(P)}}function F0(){if(!Q&&(A||x)){if(typeof fetch=="function"&&!jp(Qn))return fetch(Qn,{credentials:"same-origin"}).then(function(C){if(!C.ok)throw"failed to load wasm binary file at '"+Qn+"'";return C.arrayBuffer()}).catch(function(){return qp(Qn)});if(F)return new Promise(function(C,P){F(Qn,function(V){C(new Uint8Array(V))},P)})}return Promise.resolve().then(function(){return qp(Qn)})}function O0(){var C={a:Cg};function P(ge,Te){var yt=ge.exports;if(u.asm=yt,_s=u.asm.F,oe=Te,!k){var hn=Re.unusedWorkers.length;Re.unusedWorkers.forEach(function(en){Re.loadWasmModuleToWorker(en,function(){--hn||_0("wasm-instantiate")})})}}k||D0("wasm-instantiate");function V(ge){P(ge.instance,ge.module)}function Y(ge){return F0().then(function(Te){return WebAssembly.instantiate(Te,C)}).then(ge,function(Te){z("failed to asynchronously prepare wasm: "+Te),Ur(Te)})}function ye(){return!Q&&typeof WebAssembly.instantiateStreaming=="function"&&!Hp(Qn)&&!jp(Qn)&&typeof fetch=="function"?fetch(Qn,{credentials:"same-origin"}).then(function(ge){var Te=WebAssembly.instantiateStreaming(ge,C);return Te.then(V,function(yt){return z("wasm streaming compile failed: "+yt),z("falling back to ArrayBuffer instantiation"),Y(V)})}):Y(V)}if(u.instantiateWasm)try{var me=u.instantiateWasm(C,P);return me}catch(ge){return z("Module.instantiateWasm callback failed with error: "+ge),!1}return ye().catch(p),{}}var M0={10024:function(){throw"Canceled!"},10042:function(C,P){setTimeout(function(){s5(C,P)},0)}};function Xp(){Re.initRuntime()}function Pl(C){for(;C.length>0;){var P=C.shift();if(typeof P=="function"){P(u);continue}var V=P.func;typeof V=="number"?P.arg===void 0?_s.get(V)():_s.get(V)(P.arg):V(P.arg===void 0?null:P.arg)}}function Tc(C,P){if(C<=0||C>a().length||C&!0||P<0)return-28;if(P==0)return 0;P>=2147483647&&(P=1/0);var V=Atomics.load(i(),Bl>>2),Y=0;if(V==C){var ye=Atomics.compareExchange(i(),Bl>>2,V,0);if(ye==V&&(--P,Y=1,P<=0))return 1}var me=Atomics.notify(i(),C>>2,P);if(me>=0)return me+Y;throw"Atomics.notify returned an unexpected value "+me}u._emscripten_futex_wake=Tc;function z0(C){if(k)throw"Internal Error! killThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in killThread!";i()[C+12>>2]=0;var P=Re.pthreads[C];P.worker.terminate(),Re.freeThreadData(P),Re.runningWorkers.splice(Re.runningWorkers.indexOf(P.worker),1),P.worker.pthread=void 0}function L0(C){if(k)throw"Internal Error! cancelThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in cancelThread!";var P=Re.pthreads[C];P.worker.postMessage({cmd:"cancel"})}function B0(C){if(k)throw"Internal Error! cleanupThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in cleanupThread!";var P=Re.pthreads[C];if(P){i()[C+12>>2]=0;var V=P.worker;Re.returnWorkerToPool(V)}}var Re={unusedWorkers:[],runningWorkers:[],initMainThreadBlock:function(){for(var C=Math.min(4,Math.max(1,(navigator.hardwareConcurrency||1)/2)),P=0;P<C;++P)Re.allocateUnusedWorker()},initRuntime:function(){for(var C=Yo(228),P=0;P<228/4;++P)l()[C/4+P]=0;i()[C+12>>2]=C;var V=C+152;i()[V>>2]=V;for(var Y=Yo(512),P=0;P<128;++P)l()[Y/4+P]=0;Atomics.store(l(),C+100>>2,Y),Atomics.store(l(),C+40>>2,C),Qg(C,!x,1),n5(C)},initWorker:function(){},pthreads:{},threadExitHandlers:[],setThreadStatus:function(){},runExitHandlers:function(){for(;Re.threadExitHandlers.length>0;)Re.threadExitHandlers.pop()();k&&Ml()&&t5()},runExitHandlersAndDeinitThread:function(C,P){Atomics.store(l(),C+56>>2,1),Atomics.store(l(),C+60>>2,0),Re.runExitHandlers(),Atomics.store(l(),C+4>>2,P),Atomics.store(l(),C+0>>2,1),Tc(C+0,2147483647),Qg(0,0,0)},threadExit:function(C){var P=Ml();P&&(Re.runExitHandlersAndDeinitThread(P,C),k&&postMessage({cmd:"exit"}))},threadCancel:function(){Re.runExitHandlersAndDeinitThread(Ml(),-1),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var C in Re.pthreads){var P=Re.pthreads[C];P&&P.worker&&Re.returnWorkerToPool(P.worker)}Re.pthreads={};for(var V=0;V<Re.unusedWorkers.length;++V){var Y=Re.unusedWorkers[V];Y.terminate()}Re.unusedWorkers=[];for(var V=0;V<Re.runningWorkers.length;++V){var Y=Re.runningWorkers[V],P=Y.pthread;Re.freeThreadData(P),Y.terminate()}Re.runningWorkers=[]},freeThreadData:function(C){if(!!C){if(C.threadInfoStruct){var P=i()[C.threadInfoStruct+100>>2];i()[C.threadInfoStruct+100>>2]=0,Pc(P),Pc(C.threadInfoStruct)}C.threadInfoStruct=0,C.allocatedOwnStack&&C.stackBase&&Pc(C.stackBase),C.stackBase=0,C.worker&&(C.worker.pthread=null)}},returnWorkerToPool:function(C){Re.runWithoutMainThreadQueuedCalls(function(){delete Re.pthreads[C.pthread.threadInfoStruct],Re.unusedWorkers.push(C),Re.runningWorkers.splice(Re.runningWorkers.indexOf(C),1),Re.freeThreadData(C.pthread),C.pthread=void 0})},runWithoutMainThreadQueuedCalls:function(C){i()[l5>>2]=0;try{C()}finally{i()[l5>>2]=1}},receiveObjectTransfer:function(C){},loadWasmModuleToWorker:function(C,P){C.onmessage=function(V){var Y=V.data,ye=Y.cmd;if(C.pthread&&(Re.currentProxiedOperationCallerThread=C.pthread.threadInfoStruct),Y.targetThread&&Y.targetThread!=Ml()){var me=Re.pthreads[Y.targetThread];me?me.worker.postMessage(V.data,Y.transferList):console.error('Internal error! Worker sent a message "'+ye+'" to target pthread '+Y.targetThread+", but that thread no longer exists!"),Re.currentProxiedOperationCallerThread=void 0;return}if(ye==="processQueuedMainThreadWork")Yg();else if(ye==="spawnThread")eh(V.data);else if(ye==="cleanupThread")B0(Y.thread);else if(ye==="killThread")z0(Y.thread);else if(ye==="cancelThread")L0(Y.thread);else if(ye==="loaded")C.loaded=!0,P&&P(C),C.runPthread&&(C.runPthread(),delete C.runPthread);else if(ye==="print")H("Thread "+Y.threadId+": "+Y.text);else if(ye==="printErr")z("Thread "+Y.threadId+": "+Y.text);else if(ye==="alert")alert("Thread "+Y.threadId+": "+Y.text);else if(ye==="exit"){var ge=C.pthread&&Atomics.load(l(),C.pthread.threadInfoStruct+64>>2);ge&&Re.returnWorkerToPool(C)}else if(ye==="exitProcess")try{zT(Y.returnCode)}catch(Te){if(Te instanceof Oc)return;throw Te}else ye==="cancelDone"?Re.returnWorkerToPool(C):ye==="objectTransfer"?Re.receiveObjectTransfer(V.data):V.data.target==="setimmediate"?C.postMessage(V.data):z("worker sent an unknown command "+ye);Re.currentProxiedOperationCallerThread=void 0},C.onerror=function(V){z("pthread sent an error! "+V.filename+":"+V.lineno+": "+V.message)},b&&(C.on("message",function(V){C.onmessage({data:V})}),C.on("error",function(V){C.onerror(V)}),C.on("exit",function(V){})),C.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||s,wasmMemory:K,wasmModule:oe})},allocateUnusedWorker:function(){var C=N("tfjs-backend-wasm-threaded-simd.worker.js");Re.unusedWorkers.push(new Worker(C))},getNewWorker:function(){return Re.unusedWorkers.length==0&&(Re.allocateUnusedWorker(),Re.loadWasmModuleToWorker(Re.unusedWorkers[0])),Re.unusedWorkers.length>0?Re.unusedWorkers.pop():null},busySpinWait:function(C){for(var P=performance.now()+C;performance.now()<P;);}};function W0(C,P){o5(C,P),zl(C)}u.establishStackSpace=W0;function V0(){return ne}u.getNoExitRuntime=V0;function U0(C,P){return _s.get(C)(P)}u.invokeEntryPoint=U0;function G0(C,P,V,Y){Ur("Assertion failed: "+ze(C)+", at: "+[P?ze(P):"unknown filename",V,Y?ze(Y):"unknown function"])}function H0(C,P){var V=_main(C,P)}var Zo;b?Zo=function(){var C=process.hrtime();return C[0]*1e3+C[1]/1e6}:k?Zo=function(){return performance.now()-u.__performance_now_clock_drift}:typeof dateNow!="undefined"?Zo=dateNow:Zo=function(){return performance.now()};function j0(C){return i()[Qb()>>2]=C,C}function q0(C,P){if(k)return ma(1,1,C,P)}function X0(C,P){if(C==P)postMessage({cmd:"processQueuedMainThreadWork"});else if(k)postMessage({targetThread:C,cmd:"processThreadQueue"});else{var V=Re.pthreads[C],Y=V&&V.worker;if(!Y)return;Y.postMessage({cmd:"processThreadQueue"})}return 1}function K0(){Ur()}function Z0(C,P,V){var Y=tg(P,V);return M0[C].apply(null,Y)}function Y0(C,P){}function J0(C,P,V){if(C<=0||C>a().length||C&!0)return-28;if(A){if(Atomics.load(i(),C>>2)!=P)return-6;for(var ye=performance.now(),me=ye+V,ge=Atomics.exchange(i(),Bl>>2,C);;){if(ye=performance.now(),ye>me)return ge=Atomics.exchange(i(),Bl>>2,0),-73;if(ge=Atomics.exchange(i(),Bl>>2,0),ge==0)break;if(Yg(),Atomics.load(i(),C>>2)!=P)return-6;ge=Atomics.exchange(i(),Bl>>2,C)}return 0}else{var Y=Atomics.wait(i(),C>>2,P,V);if(Y==="timed-out")return-73;if(Y==="not-equal")return-6;if(Y==="ok")return 0;throw"Atomics.wait returned an unexpected value "+Y}}function Q0(C,P,V){o().copyWithin(C,P,P+V)}function eg(){return b?Ul("os").cpus().length:navigator.hardwareConcurrency}function ma(C,P){for(var V=arguments.length-2,Y=Fc(),ye=V,me=Ll(ye*8),ge=me>>3,Te=0;Te<V;Te++){var yt=arguments[2+Te];c()[ge+Te]=yt}var hn=a5(C,ye,me,P);return zl(Y),hn}var Nc=[],Ec=[];function tg(C,P){Ec.length=0;var V;for(P>>=2;V=o()[C++];){var Y=V<105;Y&&P&1&&P++,Ec.push(Y?c()[P++>>1]:i()[P]),++P}return Ec}function ng(C,P,V){Nc.length=P;for(var Y=V>>3,ye=0;ye<P;ye++)Nc[ye]=c()[Y+ye];var me=C<0,ge=me?M0[-C-1]:Sg[C];return ge.apply(null,Nc)}function sg(){return o().length}function rg(C){try{return K.grow(C-Ye.byteLength+65535>>>16),In(K.buffer),1}catch(P){}}function ag(C){var P=sg();if(C<=P)return!1;var V=2147483648;if(C>V)return!1;for(var Y=1;Y<=4;Y*=2){var ye=P*(1+.2/Y);ye=Math.min(ye,C+100663296);var me=Math.min(V,bt(Math.max(C,ye),65536)),ge=rg(me);if(ge)return!0}return!1}var qe={inEventHandler:0,removeAllEventListeners:function(){for(var C=qe.eventHandlers.length-1;C>=0;--C)qe._removeHandler(C);qe.eventHandlers=[],qe.deferredCalls=[]},registerRemoveEventListeners:function(){qe.removeEventListenersRegistered||(ha.push(qe.removeAllEventListeners),qe.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(C,P,V){function Y(ge,Te){if(ge.length!=Te.length)return!1;for(var yt in ge)if(ge[yt]!=Te[yt])return!1;return!0}for(var ye in qe.deferredCalls){var me=qe.deferredCalls[ye];if(me.targetFunction==C&&Y(me.argsList,V))return}qe.deferredCalls.push({targetFunction:C,precedence:P,argsList:V}),qe.deferredCalls.sort(function(ge,Te){return ge.precedence<Te.precedence})},removeDeferredCalls:function(C){for(var P=0;P<qe.deferredCalls.length;++P)qe.deferredCalls[P].targetFunction==C&&(qe.deferredCalls.splice(P,1),--P)},canPerformEventHandlerRequests:function(){return qe.inEventHandler&&qe.currentEventHandler.allowsDeferredCalls},runDeferredCalls:function(){if(!!qe.canPerformEventHandlerRequests())for(var C=0;C<qe.deferredCalls.length;++C){var P=qe.deferredCalls[C];qe.deferredCalls.splice(C,1),--C,P.targetFunction.apply(null,P.argsList)}},eventHandlers:[],removeAllHandlersOnTarget:function(C,P){for(var V=0;V<qe.eventHandlers.length;++V)qe.eventHandlers[V].target==C&&(!P||P==qe.eventHandlers[V].eventTypeString)&&qe._removeHandler(V--)},_removeHandler:function(C){var P=qe.eventHandlers[C];P.target.removeEventListener(P.eventTypeString,P.eventListenerFunc,P.useCapture),qe.eventHandlers.splice(C,1)},registerOrRemoveHandler:function(C){var P=function(ye){++qe.inEventHandler,qe.currentEventHandler=C,qe.runDeferredCalls(),C.handlerFunc(ye),qe.runDeferredCalls(),--qe.inEventHandler};if(C.callbackfunc)C.eventListenerFunc=P,C.target.addEventListener(C.eventTypeString,P,C.useCapture),qe.eventHandlers.push(C),qe.registerRemoveEventListeners();else for(var V=0;V<qe.eventHandlers.length;++V)qe.eventHandlers[V].target==C.target&&qe.eventHandlers[V].eventTypeString==C.eventTypeString&&qe._removeHandler(V--)},queueEventHandlerOnThread_iiii:function(C,P,V,Y,ye){var me=Fc(),ge=Ll(12);i()[ge>>2]=V,i()[ge+4>>2]=Y,i()[ge+8>>2]=ye,Jg(0,C,637534208,P,Y,ge),zl(me)},getTargetThreadForEventCallback:function(C){switch(C){case 1:return 0;case 2:return Re.currentProxiedOperationCallerThread;default:return C}},getNodeNameForTarget:function(C){return C?C==window?"#window":C==screen?"#screen":C&&C.nodeName?C.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function og(C){var P=gt(C)+1,V=Yo(P);return mt(C,V,P),V}function ig(C,P,V,Y){var ye=Fc(),me=Ll(12),ge=0;P&&(ge=og(P)),i()[me>>2]=ge,i()[me+4>>2]=V,i()[me+8>>2]=Y,Jg(0,C,657457152,0,ge,me),zl(ye)}function lg(C,P,V,Y){P=P?ze(P):"",ig(C,P,V,Y)}function ug(C){return C>2?ze(C):C}var cg=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function dg(C){C=ug(C);var P=cg[C]||(typeof document!="undefined"?document.querySelector(C):void 0);return P}function Rc(C){return dg(C)}function Kp(C,P,V){var Y=Rc(C);if(!Y)return-4;if(Y.canvasSharedPtr&&(i()[Y.canvasSharedPtr>>2]=P,i()[Y.canvasSharedPtr+4>>2]=V),Y.offscreenCanvas||!Y.controlTransferredOffscreen){Y.offscreenCanvas&&(Y=Y.offscreenCanvas);var ye=!1;if(Y.GLctxObject&&Y.GLctxObject.GLctx){var me=Y.GLctxObject.GLctx.getParameter(2978);ye=me[0]===0&&me[1]===0&&me[2]===Y.width&&me[3]===Y.height}Y.width=P,Y.height=V,ye&&Y.GLctxObject.GLctx.viewport(0,0,P,V)}else if(Y.canvasSharedPtr){var ge=i()[Y.canvasSharedPtr+8>>2];return lg(ge,C,P,V),1}else return-4;return 0}function Zp(C,P,V){return k?ma(2,1,C,P,V):Kp(C,P,V)}function pg(C,P,V){var Y=Rc(C);return Y?Kp(C,P,V):Zp(C,P,V)}function hg(C){}function fg(C,P){}function mg(C){var P=C.getExtension("ANGLE_instanced_arrays");if(P)return C.vertexAttribDivisor=function(V,Y){P.vertexAttribDivisorANGLE(V,Y)},C.drawArraysInstanced=function(V,Y,ye,me){P.drawArraysInstancedANGLE(V,Y,ye,me)},C.drawElementsInstanced=function(V,Y,ye,me,ge){P.drawElementsInstancedANGLE(V,Y,ye,me,ge)},1}function gg(C){var P=C.getExtension("OES_vertex_array_object");if(P)return C.createVertexArray=function(){return P.createVertexArrayOES()},C.deleteVertexArray=function(V){P.deleteVertexArrayOES(V)},C.bindVertexArray=function(V){P.bindVertexArrayOES(V)},C.isVertexArray=function(V){return P.isVertexArrayOES(V)},1}function yg(C){var P=C.getExtension("WEBGL_draw_buffers");if(P)return C.drawBuffers=function(V,Y){P.drawBuffersWEBGL(V,Y)},1}function Ag(C){return!!(C.multiDrawWebgl=C.getExtension("WEBGL_multi_draw"))}var ft={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,recordError:function(P){ft.lastError||(ft.lastError=P)},getNewId:function(C){for(var P=ft.counter++,V=C.length;V<P;V++)C[V]=null;return P},getSource:function(C,P,V,Y){for(var ye="",me=0;me<P;++me){var ge=Y?i()[Y+me*4>>2]:-1;ye+=ze(i()[V+me*4>>2],ge<0?void 0:ge)}return ye},createContext:function(C,P){var V=C.getContext("webgl",P);if(!V)return 0;var Y=ft.registerContext(V,P);return Y},registerContext:function(C,P){var V=Yo(8);i()[V+4>>2]=Ml();var Y={handle:V,attributes:P,version:P.majorVersion,GLctx:C};return C.canvas&&(C.canvas.GLctxObject=Y),ft.contexts[V]=Y,(typeof P.enableExtensionsByDefault=="undefined"||P.enableExtensionsByDefault)&&ft.initExtensions(Y),V},makeContextCurrent:function(C){return ft.currentContext=ft.contexts[C],u.ctx=ga=ft.currentContext&&ft.currentContext.GLctx,!(C&&!ga)},getContext:function(C){return ft.contexts[C]},deleteContext:function(C){ft.currentContext===ft.contexts[C]&&(ft.currentContext=null),typeof qe=="object"&&qe.removeAllHandlersOnTarget(ft.contexts[C].GLctx.canvas),ft.contexts[C]&&ft.contexts[C].GLctx.canvas&&(ft.contexts[C].GLctx.canvas.GLctxObject=void 0),Pc(ft.contexts[C].handle),ft.contexts[C]=null},initExtensions:function(C){if(C||(C=ft.currentContext),!C.initExtensionsDone){C.initExtensionsDone=!0;var P=C.GLctx;mg(P),gg(P),yg(P),P.disjointTimerQueryExt=P.getExtension("EXT_disjoint_timer_query"),Ag(P);var V=P.getSupportedExtensions()||[];V.forEach(function(Y){Y.indexOf("lose_context")<0&&Y.indexOf("debug")<0&&P.getExtension(Y)})}},populateUniformTable:function(C){for(var P=ft.programs[C],V=ft.programInfos[C]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},Y=V.uniforms,ye=ga.getProgramParameter(P,35718),me=0;me<ye;++me){var ge=ga.getActiveUniform(P,me),Te=ge.name;V.maxUniformLength=Math.max(V.maxUniformLength,Te.length+1),Te.slice(-1)=="]"&&(Te=Te.slice(0,Te.lastIndexOf("[")));var yt=ga.getUniformLocation(P,Te);if(yt){var hn=ft.getNewId(ft.uniforms);Y[Te]=[ge.size,hn],ft.uniforms[hn]=yt;for(var en=1;en<ge.size;++en){var Aa=Te+"["+en+"]";yt=ga.getUniformLocation(P,Aa),hn=ft.getNewId(ft.uniforms),ft.uniforms[hn]=yt}}}}},xg=["default","low-power","high-performance"];function bg(C,P){var V=P>>2,Y=i()[V+(24>>2)],ye={alpha:!!i()[V+(0>>2)],depth:!!i()[V+(4>>2)],stencil:!!i()[V+(8>>2)],antialias:!!i()[V+(12>>2)],premultipliedAlpha:!!i()[V+(16>>2)],preserveDrawingBuffer:!!i()[V+(20>>2)],powerPreference:xg[Y],failIfMajorPerformanceCaveat:!!i()[V+(28>>2)],majorVersion:i()[V+(32>>2)],minorVersion:i()[V+(36>>2)],enableExtensionsByDefault:i()[V+(40>>2)],explicitSwapControl:i()[V+(44>>2)],proxyContextToMainThread:i()[V+(48>>2)],renderViaOffscreenBackBuffer:i()[V+(52>>2)]},me=Rc(C);if(!me||ye.explicitSwapControl)return 0;var ge=ft.createContext(me,ye);return ge}function vg(C,P){return bg(C,P)}var Fl={mappings:{},buffers:[null,[],[]],printChar:function(C,P){var V=Fl.buffers[C];P===0||P===10?((C===1?H:z)(Ue(V,0)),V.length=0):V.push(P)},varargs:void 0,get:function(){Fl.varargs+=4;var C=i()[Fl.varargs-4>>2];return C},getStr:function(C){var P=ze(C);return P},get64:function(C,P){return C}};function Yp(C){return k?ma(3,1,C):0}function Jp(C,P,V,Y,ye){if(k)return ma(4,1,C,P,V,Y,ye)}function Qp(C,P,V,Y){if(k)return ma(5,1,C,P,V,Y);for(var ye=0,me=0;me<V;me++){for(var ge=i()[P+me*8>>2],Te=i()[P+(me*8+4)>>2],yt=0;yt<Te;yt++)Fl.printChar(C,o()[ge+yt]);ye+=Te}return i()[Y>>2]=ye,0}function wg(C){var P=Re.threadExitHandlers.pop();C&&P()}function kg(C,P){Re.threadExitHandlers.push(function(){_s.get(C)(P)})}function eh(C){if(k)throw"Internal Error! spawnThread() can only ever be called from main application thread!";var P=Re.getNewWorker();if(P.pthread!==void 0)throw"Internal error!";if(!C.pthread_ptr)throw"Internal error, no pthread ptr!";Re.runningWorkers.push(P);for(var V=Yo(128*4),Y=0;Y<128;++Y)i()[V+Y*4>>2]=0;var ye=C.stackBase+C.stackSize,me=Re.pthreads[C.pthread_ptr]={worker:P,stackBase:C.stackBase,stackSize:C.stackSize,allocatedOwnStack:C.allocatedOwnStack,threadInfoStruct:C.pthread_ptr},ge=me.threadInfoStruct>>2;Atomics.store(l(),ge+(64>>2),C.detached),Atomics.store(l(),ge+(100>>2),V),Atomics.store(l(),ge+(40>>2),me.threadInfoStruct),Atomics.store(l(),ge+(80>>2),C.stackSize),Atomics.store(l(),ge+(76>>2),ye),Atomics.store(l(),ge+(104>>2),C.stackSize),Atomics.store(l(),ge+(104+8>>2),ye),Atomics.store(l(),ge+(104+12>>2),C.detached);var Te=e5(),yt=Te+40;Atomics.store(l(),ge+(172>>2),yt),P.pthread=me;var hn={cmd:"run",start_routine:C.startRoutine,arg:C.arg,threadInfoStruct:C.pthread_ptr,stackBase:C.stackBase,stackSize:C.stackSize};P.runPthread=function(){hn.time=performance.now(),P.postMessage(hn,C.transferList)},P.loaded&&(P.runPthread(),delete P.runPthread)}function Ig(C,P,V,Y){if(typeof SharedArrayBuffer=="undefined")return z("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;if(!C)return z("pthread_create called with a null thread pointer!"),28;var ye=[],me=0;if(k&&(ye.length===0||me))return r5(687865856,C,P,V,Y);if(me)return me;var ge=0,Te=0,yt=0;P&&P!=-1?(ge=i()[P>>2],ge+=81920,Te=i()[P+8>>2],yt=i()[P+12>>2]!==0):ge=2097152;var hn=Te==0;hn?Te=i5(16,ge):(Te-=ge,Ae(Te>0));for(var en=Yo(228),Aa=0;Aa<228>>2;++Aa)l()[(en>>2)+Aa]=0;i()[C>>2]=en,i()[en+12>>2]=en;var Wl=en+152;i()[Wl>>2]=Wl;var On={stackBase:Te,stackSize:ge,allocatedOwnStack:hn,detached:yt,startRoutine:V,pthread_ptr:en,arg:Y,transferList:ye};return k?(On.cmd="spawnThread",postMessage(On,ye)):eh(On),0}function th(C){if(k)return ma(6,1,C);switch(C){case 30:return 16384;case 85:var P=2147483648;return P/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return typeof navigator=="object"&&navigator.hardwareConcurrency||1}return j0(28),-1}k||Re.initMainThreadBlock();var ga,Sg=[null,q0,Zp,Yp,Jp,Qp,th],Cg={e:G0,r:H0,x:X0,b:K0,y:Z0,j:Y0,c:J0,d:Tc,f:Zo,p:Q0,z:eg,u:ng,q:ag,v:pg,i:hg,t:fg,w:vg,m:Yp,n:Jp,g:Qp,o:Xp,a:K||u.wasmMemory,k:wg,l:kg,h:Ig,s:th},Jb=O0(),nh=u.___wasm_call_ctors=function(){return(nh=u.___wasm_call_ctors=u.asm.A).apply(null,arguments)},Tg=u._init=function(){return(Tg=u._init=u.asm.B).apply(null,arguments)},Ng=u._register_tensor=function(){return(Ng=u._register_tensor=u.asm.C).apply(null,arguments)},Eg=u._dispose_data=function(){return(Eg=u._dispose_data=u.asm.D).apply(null,arguments)},Rg=u._dispose=function(){return(Rg=u._dispose=u.asm.E).apply(null,arguments)},$g=u._Abs=function(){return($g=u._Abs=u.asm.G).apply(null,arguments)},Dg=u._Add=function(){return(Dg=u._Add=u.asm.H).apply(null,arguments)},_g=u._AddN=function(){return(_g=u._AddN=u.asm.I).apply(null,arguments)},Pg=u._All=function(){return(Pg=u._All=u.asm.J).apply(null,arguments)},Fg=u._Any=function(){return(Fg=u._Any=u.asm.K).apply(null,arguments)},Og=u._ArgMax=function(){return(Og=u._ArgMax=u.asm.L).apply(null,arguments)},Mg=u._AvgPool=function(){return(Mg=u._AvgPool=u.asm.M).apply(null,arguments)},zg=u._BatchMatMul=function(){return(zg=u._BatchMatMul=u.asm.N).apply(null,arguments)},Lg=u._Ceil=function(){return(Lg=u._Ceil=u.asm.O).apply(null,arguments)},Bg=u._ClipByValue=function(){return(Bg=u._ClipByValue=u.asm.P).apply(null,arguments)},Wg=u._Conv2D=function(){return(Wg=u._Conv2D=u.asm.Q).apply(null,arguments)},Vg=u._Conv2DBackpropInput=function(){return(Vg=u._Conv2DBackpropInput=u.asm.R).apply(null,arguments)},Ug=u._Cos=function(){return(Ug=u._Cos=u.asm.S).apply(null,arguments)},Gg=u._Cosh=function(){return(Gg=u._Cosh=u.asm.T).apply(null,arguments)},Hg=u._CropAndResize=function(){return(Hg=u._CropAndResize=u.asm.U).apply(null,arguments)},jg=u._Cumsum=function(){return(jg=u._Cumsum=u.asm.V).apply(null,arguments)},qg=u._DepthToSpace=function(){return(qg=u._DepthToSpace=u.asm.W).apply(null,arguments)},Xg=u._DepthwiseConv2dNative=function(){return(Xg=u._DepthwiseConv2dNative=u.asm.X).apply(null,arguments)},Kg=u._Elu=function(){return(Kg=u._Elu=u.asm.Y).apply(null,arguments)},sh=u._Equal=function(){return(sh=u._Equal=u.asm.Z).apply(null,arguments)},rh=u._Exp=function(){return(rh=u._Exp=u.asm._).apply(null,arguments)},ah=u._FlipLeftRight=function(){return(ah=u._FlipLeftRight=u.asm.$).apply(null,arguments)},$c=u._Floor=function(){return($c=u._Floor=u.asm.aa).apply(null,arguments)},Ol=u._FloorDiv=function(){return(Ol=u._FloorDiv=u.asm.ba).apply(null,arguments)},Zg=u._FusedBatchNorm=function(){return(Zg=u._FusedBatchNorm=u.asm.ca).apply(null,arguments)},Dc=u._FusedConv2D=function(){return(Dc=u._FusedConv2D=u.asm.da).apply(null,arguments)},se=u._FusedDepthwiseConv2D=function(){return(se=u._FusedDepthwiseConv2D=u.asm.ea).apply(null,arguments)},le=u._Gather=function(){return(le=u._Gather=u.asm.fa).apply(null,arguments)},we=u._GatherNd=function(){return(we=u._GatherNd=u.asm.ga).apply(null,arguments)},lt=u._Greater=function(){return(lt=u._Greater=u.asm.ha).apply(null,arguments)},Vt=u._GreaterEqual=function(){return(Vt=u._GreaterEqual=u.asm.ia).apply(null,arguments)},$t=u._LeakyRelu=function(){return($t=u._LeakyRelu=u.asm.ja).apply(null,arguments)},Qe=u._Less=function(){return(Qe=u._Less=u.asm.ka).apply(null,arguments)},st=u._LessEqual=function(){return(st=u._LessEqual=u.asm.la).apply(null,arguments)},Sn=u._Log=function(){return(Sn=u._Log=u.asm.ma).apply(null,arguments)},Gr=u._LogicalAnd=function(){return(Gr=u._LogicalAnd=u.asm.na).apply(null,arguments)},Hr=u._Max=function(){return(Hr=u._Max=u.asm.oa).apply(null,arguments)},oh=u._MaxPool=function(){return(oh=u._MaxPool=u.asm.pa).apply(null,arguments)},_c=u._Maximum=function(){return(_c=u._Maximum=u.asm.qa).apply(null,arguments)},ms=u._Mean=function(){return(ms=u._Mean=u.asm.ra).apply(null,arguments)},ya=u._Min=function(){return(ya=u._Min=u.asm.sa).apply(null,arguments)},ih=u._Minimum=function(){return(ih=u._Minimum=u.asm.ta).apply(null,arguments)},Y8=u._MirrorPad=function(){return(Y8=u._MirrorPad=u.asm.ua).apply(null,arguments)},J8=u._Multiply=function(){return(J8=u._Multiply=u.asm.va).apply(null,arguments)},Q8=u._Neg=function(){return(Q8=u._Neg=u.asm.wa).apply(null,arguments)},eT=u._NonMaxSuppressionV3=function(){return(eT=u._NonMaxSuppressionV3=u.asm.xa).apply(null,arguments)},tT=u._NonMaxSuppressionV4=function(){return(tT=u._NonMaxSuppressionV4=u.asm.ya).apply(null,arguments)},nT=u._NonMaxSuppressionV5=function(){return(nT=u._NonMaxSuppressionV5=u.asm.za).apply(null,arguments)},sT=u._NotEqual=function(){return(sT=u._NotEqual=u.asm.Aa).apply(null,arguments)},rT=u._OneHot=function(){return(rT=u._OneHot=u.asm.Ba).apply(null,arguments)},aT=u._PadV2=function(){return(aT=u._PadV2=u.asm.Ca).apply(null,arguments)},oT=u._Pow=function(){return(oT=u._Pow=u.asm.Da).apply(null,arguments)},iT=u._Prelu=function(){return(iT=u._Prelu=u.asm.Ea).apply(null,arguments)},lT=u._Prod=function(){return(lT=u._Prod=u.asm.Fa).apply(null,arguments)},uT=u._RealDiv=function(){return(uT=u._RealDiv=u.asm.Ga).apply(null,arguments)},cT=u._Relu=function(){return(cT=u._Relu=u.asm.Ha).apply(null,arguments)},dT=u._Relu6=function(){return(dT=u._Relu6=u.asm.Ia).apply(null,arguments)},pT=u._ResizeBilinear=function(){return(pT=u._ResizeBilinear=u.asm.Ja).apply(null,arguments)},hT=u._Reverse=function(){return(hT=u._Reverse=u.asm.Ka).apply(null,arguments)},fT=u._RotateWithOffset=function(){return(fT=u._RotateWithOffset=u.asm.La).apply(null,arguments)},mT=u._Round=function(){return(mT=u._Round=u.asm.Ma).apply(null,arguments)},gT=u._Rsqrt=function(){return(gT=u._Rsqrt=u.asm.Na).apply(null,arguments)},yT=u._ScatterNd=function(){return(yT=u._ScatterNd=u.asm.Oa).apply(null,arguments)},AT=u._SelectV2=function(){return(AT=u._SelectV2=u.asm.Pa).apply(null,arguments)},xT=u._Sigmoid=function(){return(xT=u._Sigmoid=u.asm.Qa).apply(null,arguments)},bT=u._Sin=function(){return(bT=u._Sin=u.asm.Ra).apply(null,arguments)},vT=u._Softmax=function(){return(vT=u._Softmax=u.asm.Sa).apply(null,arguments)},wT=u._Sqrt=function(){return(wT=u._Sqrt=u.asm.Ta).apply(null,arguments)},kT=u._Square=function(){return(kT=u._Square=u.asm.Ua).apply(null,arguments)},IT=u._SquaredDifference=function(){return(IT=u._SquaredDifference=u.asm.Va).apply(null,arguments)},ST=u._Step=function(){return(ST=u._Step=u.asm.Wa).apply(null,arguments)},CT=u._StridedSlice=function(){return(CT=u._StridedSlice=u.asm.Xa).apply(null,arguments)},TT=u._Sub=function(){return(TT=u._Sub=u.asm.Ya).apply(null,arguments)},NT=u._Sum=function(){return(NT=u._Sum=u.asm.Za).apply(null,arguments)},ET=u._Tan=function(){return(ET=u._Tan=u.asm._a).apply(null,arguments)},RT=u._Tanh=function(){return(RT=u._Tanh=u.asm.$a).apply(null,arguments)},$T=u._Tile=function(){return($T=u._Tile=u.asm.ab).apply(null,arguments)},DT=u._TopK=function(){return(DT=u._TopK=u.asm.bb).apply(null,arguments)},_T=u._Transform=function(){return(_T=u._Transform=u.asm.cb).apply(null,arguments)},PT=u._Transpose=function(){return(PT=u._Transpose=u.asm.db).apply(null,arguments)},FT=u.__FusedMatMul=function(){return(FT=u.__FusedMatMul=u.asm.eb).apply(null,arguments)},Yo=u._malloc=function(){return(Yo=u._malloc=u.asm.fb).apply(null,arguments)},Pc=u._free=function(){return(Pc=u._free=u.asm.gb).apply(null,arguments)},Qb=u.___errno_location=function(){return(Qb=u.___errno_location=u.asm.hb).apply(null,arguments)},e5=u._emscripten_get_global_libc=function(){return(e5=u._emscripten_get_global_libc=u.asm.ib).apply(null,arguments)},Ml=u._pthread_self=function(){return(Ml=u._pthread_self=u.asm.jb).apply(null,arguments)},t5=u.___pthread_tsd_run_dtors=function(){return(t5=u.___pthread_tsd_run_dtors=u.asm.kb).apply(null,arguments)},Yg=u._emscripten_main_thread_process_queued_calls=function(){return(Yg=u._emscripten_main_thread_process_queued_calls=u.asm.lb).apply(null,arguments)},OT=u._emscripten_current_thread_process_queued_calls=function(){return(OT=u._emscripten_current_thread_process_queued_calls=u.asm.mb).apply(null,arguments)},n5=u._emscripten_register_main_browser_thread_id=function(){return(n5=u._emscripten_register_main_browser_thread_id=u.asm.nb).apply(null,arguments)},s5=u.__emscripten_do_dispatch_to_thread=function(){return(s5=u.__emscripten_do_dispatch_to_thread=u.asm.ob).apply(null,arguments)},r5=u._emscripten_sync_run_in_main_thread_4=function(){return(r5=u._emscripten_sync_run_in_main_thread_4=u.asm.pb).apply(null,arguments)},a5=u._emscripten_run_in_main_runtime_thread_js=function(){return(a5=u._emscripten_run_in_main_runtime_thread_js=u.asm.qb).apply(null,arguments)},Jg=u.__emscripten_call_on_thread=function(){return(Jg=u.__emscripten_call_on_thread=u.asm.rb).apply(null,arguments)},MT=u._emscripten_tls_init=function(){return(MT=u._emscripten_tls_init=u.asm.sb).apply(null,arguments)},Qg=u.__emscripten_thread_init=function(){return(Qg=u.__emscripten_thread_init=u.asm.tb).apply(null,arguments)},Fc=u.stackSave=function(){return(Fc=u.stackSave=u.asm.ub).apply(null,arguments)},zl=u.stackRestore=function(){return(zl=u.stackRestore=u.asm.vb).apply(null,arguments)},Ll=u.stackAlloc=function(){return(Ll=u.stackAlloc=u.asm.wb).apply(null,arguments)},o5=u._emscripten_stack_set_limits=function(){return(o5=u._emscripten_stack_set_limits=u.asm.xb).apply(null,arguments)},i5=u._memalign=function(){return(i5=u._memalign=u.asm.yb).apply(null,arguments)},l5=u.__emscripten_allow_main_runtime_queued_calls=10016,Bl=u.__emscripten_main_thread_futex=11652;u.cwrap=Oe,u.PThread=Re,u.PThread=Re,u.wasmMemory=K,u.ExitStatus=Oc;var lh;function Oc(C){this.name="ExitStatus",this.message="Program terminated with exit("+C+")",this.status=C}Ko=function C(){lh||e2(),lh||(Ko=C)};function e2(C){if(C=C||m,Vr>0)return;if(k){d(u),Cc(),postMessage({cmd:"loaded"});return}if(E0(),Vr>0)return;function P(){lh||(lh=!0,u.calledRun=!0,!ce&&(Cc(),R0(),d(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),Jn()))}u.setStatus?(u.setStatus("Running..."),setTimeout(function(){setTimeout(function(){u.setStatus("")},1),P()},1)):P()}u.run=e2;function zT(C,P){if(!(P&&ne&&C===0)){if(!P&&k)throw postMessage({cmd:"exitProcess",returnCode:C}),new Oc(C);ne||(Re.terminateAllThreads(),he=C,Vp(),u.onExit&&u.onExit(C),ce=!0),y(C,new Oc(C))}}if(u.preInit)for(typeof u.preInit=="function"&&(u.preInit=[u.preInit]);u.preInit.length>0;)u.preInit.pop()();return k&&(ne=!1,Re.initWorker()),e2(),r.ready}}();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModuleThreadedSimd=n)}}),pN=Dt({"node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.9.0_@tensorflow+tfjs-core@3.9.0/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js"(e,t){var n=function(){var s=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(s=s||__filename),function(r){r=r||{};var a=typeof r!="undefined"?r:{},o,i;a.ready=new Promise(function(se,le){o=se,i=le});var l={},c;for(c in a)a.hasOwnProperty(c)&&(l[c]=a[c]);var u=[],d="./this.program",p=function(se,le){throw le},h=!1,f=!1,m=!1,g=!1;h=typeof window=="object",f=typeof importScripts=="function",m=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g=!h&&!m&&!f;var y="";function A(se){return a.locateFile?a.locateFile(se,y):y+se}var x,b,w,k,S,N;m?(f?y=Wc().dirname(y)+"/":y=__dirname+"/",x=function(le,we){return S||(S=Ul("fs")),N||(N=Wc()),le=N.normalize(le),S.readFileSync(le,we?null:"utf8")},w=function(le){var we=x(le,!0);return we.buffer||(we=new Uint8Array(we)),H(we.buffer),we},process.argv.length>1&&(d=process.argv[1].replace(/\\/g,"/")),u=process.argv.slice(2),process.on("uncaughtException",function(se){if(!(se instanceof Zg))throw se}),process.on("unhandledRejection",kr),p=function(se){process.exit(se)},a.inspect=function(){return"[Emscripten Module object]"}):g?(typeof read!="undefined"&&(x=function(le){return read(le)}),w=function(le){var we;return typeof readbuffer=="function"?new Uint8Array(readbuffer(le)):(we=read(le,"binary"),H(typeof we=="object"),we)},typeof scriptArgs!="undefined"?u=scriptArgs:typeof arguments!="undefined"&&(u=arguments),typeof quit=="function"&&(p=function(se){quit(se)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(h||f)&&(f?y=self.location.href:typeof document!="undefined"&&document.currentScript&&(y=document.currentScript.src),s&&(y=s),y.indexOf("blob:")!==0?y=y.substr(0,y.lastIndexOf("/")+1):y="",x=function(se){var le=new XMLHttpRequest;return le.open("GET",se,!1),le.send(null),le.responseText},f&&(w=function(se){var le=new XMLHttpRequest;return le.open("GET",se,!1),le.responseType="arraybuffer",le.send(null),new Uint8Array(le.response)}),b=function(se,le,we){var lt=new XMLHttpRequest;lt.open("GET",se,!0),lt.responseType="arraybuffer",lt.onload=function(){if(lt.status==200||lt.status==0&<.response){le(lt.response);return}we()},lt.onerror=we,lt.send(null)},k=function(se){document.title=se});var $=a.print||console.log.bind(console),F=a.printErr||console.warn.bind(console);for(c in l)l.hasOwnProperty(c)&&(a[c]=l[c]);l=null,a.arguments&&(u=a.arguments),a.thisProgram&&(d=a.thisProgram),a.quit&&(p=a.quit);var R;a.wasmBinary&&(R=a.wasmBinary);var D=a.noExitRuntime||!0;typeof WebAssembly!="object"&&kr("no native wasm support detected");var T,O=!1,B;function H(se,le){se||kr("Assertion failed: "+le)}function z(se){var le=a["_"+se];return H(le,"Cannot call unknown function "+se+", make sure it is exported"),le}function X(se,le,we,lt,Vt){var $t={string:function(ms){var ya=0;if(ms!=null&&ms!==0){var ih=(ms.length<<2)+1;ya=$c(ih),oe(ms,ya,ih)}return ya},array:function(ms){var ya=$c(ms.length);return ce(ms,ya),ya}};function Qe(ms){return le==="string"?ne(ms):le==="boolean"?Boolean(ms):ms}var st=z(se),Sn=[],Gr=0;if(lt)for(var Hr=0;Hr<lt.length;Hr++){var oh=$t[we[Hr]];oh?(Gr===0&&(Gr=rh()),Sn[Hr]=oh(lt[Hr])):Sn[Hr]=lt[Hr]}var _c=st.apply(null,Sn);return _c=Qe(_c),Gr!==0&&ah(Gr),_c}function ee(se,le,we,lt){we=we||[];var Vt=we.every(function(Qe){return Qe==="number"}),$t=le!=="string";return $t&&Vt&&!lt?z(se):function(){return X(se,le,we,arguments,lt)}}var J=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function Q(se,le,we){for(var lt=le+we,Vt=le;se[Vt]&&!(Vt>=lt);)++Vt;if(Vt-le>16&&se.subarray&&J)return J.decode(se.subarray(le,Vt));for(var $t="";le<Vt;){var Qe=se[le++];if(!(Qe&128)){$t+=String.fromCharCode(Qe);continue}var st=se[le++]&63;if((Qe&224)==192){$t+=String.fromCharCode((Qe&31)<<6|st);continue}var Sn=se[le++]&63;if((Qe&240)==224?Qe=(Qe&15)<<12|st<<6|Sn:Qe=(Qe&7)<<18|st<<12|Sn<<6|se[le++]&63,Qe<65536)$t+=String.fromCharCode(Qe);else{var Gr=Qe-65536;$t+=String.fromCharCode(55296|Gr>>10,56320|Gr&1023)}}return $t}function ne(se,le){return se?Q(Ce,se,le):""}function K(se,le,we,lt){if(!(lt>0))return 0;for(var Vt=we,$t=we+lt-1,Qe=0;Qe<se.length;++Qe){var st=se.charCodeAt(Qe);if(st>=55296&&st<=57343){var Sn=se.charCodeAt(++Qe);st=65536+((st&1023)<<10)|Sn&1023}if(st<=127){if(we>=$t)break;le[we++]=st}else if(st<=2047){if(we+1>=$t)break;le[we++]=192|st>>6,le[we++]=128|st&63}else if(st<=65535){if(we+2>=$t)break;le[we++]=224|st>>12,le[we++]=128|st>>6&63,le[we++]=128|st&63}else{if(we+3>=$t)break;le[we++]=240|st>>18,le[we++]=128|st>>12&63,le[we++]=128|st>>6&63,le[we++]=128|st&63}}return le[we]=0,we-Vt}function oe(se,le,we){return K(se,Ce,le,we)}function ce(se,le){Se.set(se,le)}function he(se,le){return se%le>0&&(se+=le-se%le),se}var Ae,Se,Ce,Oe,Ue,ze,wt,mt,gt;function ht(se){Ae=se,a.HEAP8=Se=new Int8Array(se),a.HEAP16=Oe=new Int16Array(se),a.HEAP32=ze=new Int32Array(se),a.HEAPU8=Ce=new Uint8Array(se),a.HEAPU16=Ue=new Uint16Array(se),a.HEAPU32=wt=new Uint32Array(se),a.HEAPF32=mt=new Float32Array(se),a.HEAPF64=gt=new Float64Array(se)}var bt=a.INITIAL_MEMORY||16777216,Ye,Yn=[],Mt=[],hs=[],kn=[],Hs=!1;Mt.push({func:function(){Xp()}});function Fn(){if(a.preRun)for(typeof a.preRun=="function"&&(a.preRun=[a.preRun]);a.preRun.length;)Ds(a.preRun.shift());fa(Yn)}function Rs(){Hs=!0,fa(Mt)}function $s(){fa(hs)}function In(){if(a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;)_s(a.postRun.shift());fa(kn)}function Ds(se){Yn.unshift(se)}function _s(se){kn.unshift(se)}var fs=0,wr=null,Wr=null;function ha(se){fs++,a.monitorRunDependencies&&a.monitorRunDependencies(fs)}function Dl(se){if(fs--,a.monitorRunDependencies&&a.monitorRunDependencies(fs),fs==0&&(wr!==null&&(clearInterval(wr),wr=null),Wr)){var le=Wr;Wr=null,le()}}a.preloadedImages={},a.preloadedAudios={};function kr(se){a.onAbort&&a.onAbort(se),se+="",F(se),O=!0,B=1,se="abort("+se+"). Build with -s ASSERTIONS=1 for more info.";var le=new WebAssembly.RuntimeError(se);throw i(le),le}function Wp(se,le){return String.prototype.startsWith?se.startsWith(le):se.indexOf(le)===0}var E0="data:application/octet-stream;base64,";function Cc(se){return Wp(se,E0)}var R0="file://";function Vp(se){return Wp(se,R0)}var Jn="tfjs-backend-wasm.wasm";Cc(Jn)||(Jn=A(Jn));function Up(se){try{if(se==Jn&&R)return new Uint8Array(R);if(w)return w(se);throw"both async and sync fetching of the wasm failed"}catch(le){kr(le)}}function $0(){if(!R&&(h||f)){if(typeof fetch=="function"&&!Vp(Jn))return fetch(Jn,{credentials:"same-origin"}).then(function(se){if(!se.ok)throw"failed to load wasm binary file at '"+Jn+"'";return se.arrayBuffer()}).catch(function(){return Up(Jn)});if(b)return new Promise(function(se,le){b(Jn,function(we){se(new Uint8Array(we))},le)})}return Promise.resolve().then(function(){return Up(Jn)})}function Vr(){var se={a:O0};function le(Qe,st){var Sn=Qe.exports;a.asm=Sn,T=a.asm.i,ht(T.buffer),Ye=a.asm.o,Dl("wasm-instantiate")}ha("wasm-instantiate");function we(Qe){le(Qe.instance)}function lt(Qe){return $0().then(function(st){return WebAssembly.instantiate(st,se)}).then(Qe,function(st){F("failed to asynchronously prepare wasm: "+st),kr(st)})}function Vt(){return!R&&typeof WebAssembly.instantiateStreaming=="function"&&!Cc(Jn)&&!Vp(Jn)&&typeof fetch=="function"?fetch(Jn,{credentials:"same-origin"}).then(function(Qe){var st=WebAssembly.instantiateStreaming(Qe,se);return st.then(we,function(Sn){return F("wasm streaming compile failed: "+Sn),F("falling back to ArrayBuffer instantiation"),lt(we)})}):lt(we)}if(a.instantiateWasm)try{var $t=a.instantiateWasm(se,le);return $t}catch(Qe){return F("Module.instantiateWasm callback failed with error: "+Qe),!1}return Vt().catch(i),{}}function fa(se){for(;se.length>0;){var le=se.shift();if(typeof le=="function"){le(a);continue}var we=le.func;typeof we=="number"?le.arg===void 0?Ye.get(we)():Ye.get(we)(le.arg):we(le.arg===void 0?null:le.arg)}}function Ko(){kr()}function D0(se,le,we){Ce.copyWithin(se,le,le+we)}function _0(){return Ce.length}function Ur(se){try{return T.grow(se-Ae.byteLength+65535>>>16),ht(T.buffer),1}catch(le){}}function Gp(se){var le=_0(),we=2147483648;if(se>we)return!1;for(var lt=1;lt<=4;lt*=2){var Vt=le*(1+.2/lt);Vt=Math.min(Vt,se+100663296);var $t=Math.min(we,he(Math.max(se,Vt),65536)),Qe=Ur($t);if(Qe)return!0}return!1}var _l={mappings:{},buffers:[null,[],[]],printChar:function(se,le){var we=_l.buffers[se];le===0||le===10?((se===1?$:F)(Q(we,0)),we.length=0):we.push(le)},varargs:void 0,get:function(){_l.varargs+=4;var se=ze[_l.varargs-4>>2];return se},getStr:function(se){var le=ne(se);return le},get64:function(se,le){return se}};function Hp(se){return 0}function P0(se,le,we,lt,Vt){}function jp(se,le,we,lt){for(var Vt=0,$t=0;$t<we;$t++){for(var Qe=ze[le+$t*8>>2],st=ze[le+($t*8+4)>>2],Sn=0;Sn<st;Sn++)_l.printChar(se,Ce[Qe+Sn]);Vt+=st}return ze[lt>>2]=Vt,0}function Qn(){return 6}function qp(se){return ze[sh()>>2]=se,se}function F0(se){switch(se){case 30:return 16384;case 85:var le=2147483648;return le/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return typeof navigator=="object"&&navigator.hardwareConcurrency||1}return qp(28),-1}var O0={a:Ko,d:D0,e:Gp,f:Hp,c:P0,b:jp,g:Qn,h:F0},M0=Vr(),Xp=a.___wasm_call_ctors=function(){return(Xp=a.___wasm_call_ctors=a.asm.j).apply(null,arguments)},Pl=a._init=function(){return(Pl=a._init=a.asm.k).apply(null,arguments)},Tc=a._register_tensor=function(){return(Tc=a._register_tensor=a.asm.l).apply(null,arguments)},z0=a._dispose_data=function(){return(z0=a._dispose_data=a.asm.m).apply(null,arguments)},L0=a._dispose=function(){return(L0=a._dispose=a.asm.n).apply(null,arguments)},B0=a._Abs=function(){return(B0=a._Abs=a.asm.p).apply(null,arguments)},Re=a._Add=function(){return(Re=a._Add=a.asm.q).apply(null,arguments)},W0=a._AddN=function(){return(W0=a._AddN=a.asm.r).apply(null,arguments)},V0=a._All=function(){return(V0=a._All=a.asm.s).apply(null,arguments)},U0=a._Any=function(){return(U0=a._Any=a.asm.t).apply(null,arguments)},G0=a._ArgMax=function(){return(G0=a._ArgMax=a.asm.u).apply(null,arguments)},H0=a._AvgPool=function(){return(H0=a._AvgPool=a.asm.v).apply(null,arguments)},Zo=a._BatchMatMul=function(){return(Zo=a._BatchMatMul=a.asm.w).apply(null,arguments)},j0=a._Ceil=function(){return(j0=a._Ceil=a.asm.x).apply(null,arguments)},q0=a._ClipByValue=function(){return(q0=a._ClipByValue=a.asm.y).apply(null,arguments)},X0=a._Conv2D=function(){return(X0=a._Conv2D=a.asm.z).apply(null,arguments)},K0=a._Conv2DBackpropInput=function(){return(K0=a._Conv2DBackpropInput=a.asm.A).apply(null,arguments)},Z0=a._Cos=function(){return(Z0=a._Cos=a.asm.B).apply(null,arguments)},Y0=a._Cosh=function(){return(Y0=a._Cosh=a.asm.C).apply(null,arguments)},J0=a._CropAndResize=function(){return(J0=a._CropAndResize=a.asm.D).apply(null,arguments)},Q0=a._Cumsum=function(){return(Q0=a._Cumsum=a.asm.E).apply(null,arguments)},eg=a._DepthToSpace=function(){return(eg=a._DepthToSpace=a.asm.F).apply(null,arguments)},ma=a._DepthwiseConv2dNative=function(){return(ma=a._DepthwiseConv2dNative=a.asm.G).apply(null,arguments)},Nc=a._Elu=function(){return(Nc=a._Elu=a.asm.H).apply(null,arguments)},Ec=a._Equal=function(){return(Ec=a._Equal=a.asm.I).apply(null,arguments)},tg=a._Exp=function(){return(tg=a._Exp=a.asm.J).apply(null,arguments)},ng=a._FlipLeftRight=function(){return(ng=a._FlipLeftRight=a.asm.K).apply(null,arguments)},sg=a._Floor=function(){return(sg=a._Floor=a.asm.L).apply(null,arguments)},rg=a._FloorDiv=function(){return(rg=a._FloorDiv=a.asm.M).apply(null,arguments)},ag=a._FusedBatchNorm=function(){return(ag=a._FusedBatchNorm=a.asm.N).apply(null,arguments)},qe=a._FusedConv2D=function(){return(qe=a._FusedConv2D=a.asm.O).apply(null,arguments)},og=a._FusedDepthwiseConv2D=function(){return(og=a._FusedDepthwiseConv2D=a.asm.P).apply(null,arguments)},ig=a._Gather=function(){return(ig=a._Gather=a.asm.Q).apply(null,arguments)},lg=a._GatherNd=function(){return(lg=a._GatherNd=a.asm.R).apply(null,arguments)},ug=a._Greater=function(){return(ug=a._Greater=a.asm.S).apply(null,arguments)},cg=a._GreaterEqual=function(){return(cg=a._GreaterEqual=a.asm.T).apply(null,arguments)},dg=a._LeakyRelu=function(){return(dg=a._LeakyRelu=a.asm.U).apply(null,arguments)},Rc=a._Less=function(){return(Rc=a._Less=a.asm.V).apply(null,arguments)},Kp=a._LessEqual=function(){return(Kp=a._LessEqual=a.asm.W).apply(null,arguments)},Zp=a._Log=function(){return(Zp=a._Log=a.asm.X).apply(null,arguments)},pg=a._LogicalAnd=function(){return(pg=a._LogicalAnd=a.asm.Y).apply(null,arguments)},hg=a._Max=function(){return(hg=a._Max=a.asm.Z).apply(null,arguments)},fg=a._MaxPool=function(){return(fg=a._MaxPool=a.asm._).apply(null,arguments)},mg=a._Maximum=function(){return(mg=a._Maximum=a.asm.$).apply(null,arguments)},gg=a._Mean=function(){return(gg=a._Mean=a.asm.aa).apply(null,arguments)},yg=a._Min=function(){return(yg=a._Min=a.asm.ba).apply(null,arguments)},Ag=a._Minimum=function(){return(Ag=a._Minimum=a.asm.ca).apply(null,arguments)},ft=a._MirrorPad=function(){return(ft=a._MirrorPad=a.asm.da).apply(null,arguments)},xg=a._Multiply=function(){return(xg=a._Multiply=a.asm.ea).apply(null,arguments)},bg=a._Neg=function(){return(bg=a._Neg=a.asm.fa).apply(null,arguments)},vg=a._NonMaxSuppressionV3=function(){return(vg=a._NonMaxSuppressionV3=a.asm.ga).apply(null,arguments)},Fl=a._NonMaxSuppressionV4=function(){return(Fl=a._NonMaxSuppressionV4=a.asm.ha).apply(null,arguments)},Yp=a._NonMaxSuppressionV5=function(){return(Yp=a._NonMaxSuppressionV5=a.asm.ia).apply(null,arguments)},Jp=a._NotEqual=function(){return(Jp=a._NotEqual=a.asm.ja).apply(null,arguments)},Qp=a._OneHot=function(){return(Qp=a._OneHot=a.asm.ka).apply(null,arguments)},wg=a._PadV2=function(){return(wg=a._PadV2=a.asm.la).apply(null,arguments)},kg=a._Pow=function(){return(kg=a._Pow=a.asm.ma).apply(null,arguments)},eh=a._Prelu=function(){return(eh=a._Prelu=a.asm.na).apply(null,arguments)},Ig=a._Prod=function(){return(Ig=a._Prod=a.asm.oa).apply(null,arguments)},th=a._RealDiv=function(){return(th=a._RealDiv=a.asm.pa).apply(null,arguments)},ga=a._Relu=function(){return(ga=a._Relu=a.asm.qa).apply(null,arguments)},Sg=a._Relu6=function(){return(Sg=a._Relu6=a.asm.ra).apply(null,arguments)},Cg=a._ResizeBilinear=function(){return(Cg=a._ResizeBilinear=a.asm.sa).apply(null,arguments)},Jb=a._Reverse=function(){return(Jb=a._Reverse=a.asm.ta).apply(null,arguments)},nh=a._RotateWithOffset=function(){return(nh=a._RotateWithOffset=a.asm.ua).apply(null,arguments)},Tg=a._Round=function(){return(Tg=a._Round=a.asm.va).apply(null,arguments)},Ng=a._Rsqrt=function(){return(Ng=a._Rsqrt=a.asm.wa).apply(null,arguments)},Eg=a._ScatterNd=function(){return(Eg=a._ScatterNd=a.asm.xa).apply(null,arguments)},Rg=a._SelectV2=function(){return(Rg=a._SelectV2=a.asm.ya).apply(null,arguments)},$g=a._Sigmoid=function(){return($g=a._Sigmoid=a.asm.za).apply(null,arguments)},Dg=a._Sin=function(){return(Dg=a._Sin=a.asm.Aa).apply(null,arguments)},_g=a._Softmax=function(){return(_g=a._Softmax=a.asm.Ba).apply(null,arguments)},Pg=a._Sqrt=function(){return(Pg=a._Sqrt=a.asm.Ca).apply(null,arguments)},Fg=a._Square=function(){return(Fg=a._Square=a.asm.Da).apply(null,arguments)},Og=a._SquaredDifference=function(){return(Og=a._SquaredDifference=a.asm.Ea).apply(null,arguments)},Mg=a._Step=function(){return(Mg=a._Step=a.asm.Fa).apply(null,arguments)},zg=a._StridedSlice=function(){return(zg=a._StridedSlice=a.asm.Ga).apply(null,arguments)},Lg=a._Sub=function(){return(Lg=a._Sub=a.asm.Ha).apply(null,arguments)},Bg=a._Sum=function(){return(Bg=a._Sum=a.asm.Ia).apply(null,arguments)},Wg=a._Tan=function(){return(Wg=a._Tan=a.asm.Ja).apply(null,arguments)},Vg=a._Tanh=function(){return(Vg=a._Tanh=a.asm.Ka).apply(null,arguments)},Ug=a._Tile=function(){return(Ug=a._Tile=a.asm.La).apply(null,arguments)},Gg=a._TopK=function(){return(Gg=a._TopK=a.asm.Ma).apply(null,arguments)},Hg=a._Transform=function(){return(Hg=a._Transform=a.asm.Na).apply(null,arguments)},jg=a._Transpose=function(){return(jg=a._Transpose=a.asm.Oa).apply(null,arguments)},qg=a.__FusedMatMul=function(){return(qg=a.__FusedMatMul=a.asm.Pa).apply(null,arguments)},Xg=a._malloc=function(){return(Xg=a._malloc=a.asm.Qa).apply(null,arguments)},Kg=a._free=function(){return(Kg=a._free=a.asm.Ra).apply(null,arguments)},sh=a.___errno_location=function(){return(sh=a.___errno_location=a.asm.Sa).apply(null,arguments)},rh=a.stackSave=function(){return(rh=a.stackSave=a.asm.Ta).apply(null,arguments)},ah=a.stackRestore=function(){return(ah=a.stackRestore=a.asm.Ua).apply(null,arguments)},$c=a.stackAlloc=function(){return($c=a.stackAlloc=a.asm.Va).apply(null,arguments)};a.cwrap=ee;var Ol;function Zg(se){this.name="ExitStatus",this.message="Program terminated with exit("+se+")",this.status=se}Wr=function se(){Ol||Dc(),Ol||(Wr=se)};function Dc(se){if(se=se||u,fs>0||(Fn(),fs>0))return;function le(){Ol||(Ol=!0,a.calledRun=!0,!O&&(Rs(),$s(),o(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),In()))}a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),le()},1)):le()}if(a.run=Dc,a.preInit)for(typeof a.preInit=="function"&&(a.preInit=[a.preInit]);a.preInit.length>0;)a.preInit.pop()();return Dc(),r.ready}}();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModule=n)}}),hN=1e-7,fN=1e-4,Vc=class{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}},Gl=class{refCount(e){return js("refCount")}incRef(e){return js("incRef")}timerAvailable(){return!0}time(e){return js("time")}read(e){return js("read")}readSync(e){return js("readSync")}numDataIds(){return js("numDataIds")}disposeData(e,t){return js("disposeData")}write(e,t,n){return js("write")}move(e,t,n,s,r){return js("move")}memory(){return js("memory")}floatPrecision(){return js("floatPrecision")}epsilon(){return this.floatPrecision()===32?hN:fN}dispose(){return js("dispose")}};function js(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function g5(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,ch(e,t,n)}function mN(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,s=0;for(;n>0;)s=Math.random()*n|0,n--,ch(e,n,s),ch(t,n,s)}function Uc(e,t,n){return Math.max(e,Math.min(t,n))}function gN(e){return e%2==0?e:e+1}function ch(e,t,n){let s=e[t];e[t]=e[n],e[n]=s}function yN(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function AN(e,t){let n=Math.random();return t*n+(1-n)*e}function xN(e,t){let n=0;for(let s=0;s<e.length;s++){let r=Number(e[s])-Number(t[s]);n+=r*r}return n}function M(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function Mn(e,t,n=""){M(jr(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function ei(e){M(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function ti(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||_n(e)&&!n)for(let s=0;s<e.length;++s)ti(e[s],t,n);else t.push(e);return t}function Ht(e){if(e.length===0)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function bN(e){return e.length===0}function jr(e,t){if(e===t)return!0;if(e==null||t==null||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function mn(e){return e%1==0}function vN(e){if(Math.tanh!=null)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;{let t=Math.exp(2*e);return(t-1)/(t+1)}}function wN(e){let t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function kN(e){let t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return g5(t),t}function Gc(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function IN(e,t=s=>0,n){return new Promise((s,r)=>{let a=0,o=()=>{if(e()){s();return}a++;let i=t(a);if(n!=null&&a>=n){r();return}setTimeout(o,i)};o()})}function SN(e,t){let n=1,s=-1;for(let a=0;a<e.length;++a)if(e[a]>=0)n*=e[a];else if(e[a]===-1){if(s!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${a}`);s=a}else if(e[a]<0)throw Error(`Shapes can not be < 0. Found ${e[a]} at dim ${a}`);if(s===-1){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(n===0)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);let r=e.slice();return r[s]=t/n,r}function qs(e,t){let n=t.length;return e=e==null?t.map((s,r)=>r):[].concat(e),M(e.every(s=>s>=-n&&s<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),M(e.every(s=>mn(s)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(s=>s<0?n+s:s)}function y5(e,t){let n=[],s=[],r=t!=null&&Array.isArray(t)&&t.length===0,a=t==null||r?null:qs(t,e).sort(),o=0;for(let i=0;i<e.length;++i){if(a!=null){if(a[o]===i&&e[i]!==1)throw new Error(`Can't squeeze axis ${i} since its dim '${e[i]}' is not 1`);(a[o]==null||a[o]>i)&&e[i]===1&&(n.push(e[i]),s.push(i)),a[o]<=i&&o++}e[i]!==1&&(n.push(e[i]),s.push(i))}return{newShape:n,keptDims:s}}function A5(e,t){let n=null;if(e==null||e==="float32")n=new Float32Array(t);else if(e==="int32")n=new Int32Array(t);else if(e==="bool")n=new Uint8Array(t);else throw new Error(`Unknown data type ${e}`);return n}function x5(e,t){let n=null;if(e==null||e==="float32")n=new Float32Array(t);else if(e==="int32")n=new Int32Array(t);else if(e==="bool")n=new Uint8Array(t);else if(e==="string")n=new Array(t);else throw new Error(`Unknown data type ${e}`);return n}function b5(e,t){for(let n=0;n<e.length;n++){let s=e[n];if(isNaN(s)||!isFinite(s))throw Error(`A tensor of type ${t} being uploaded contains ${s}.`)}}function v5(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function CN(e,t){return!(t==="complex64"||t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64"||t==="bool"&&e==="bool")}function _n(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function s2(e){if(e==="float32"||e==="int32")return 4;if(e==="complex64")return 8;if(e==="bool")return 1;throw new Error(`Unknown dtype ${e}`)}function w5(e){if(e==null)return 0;let t=0;return e.forEach(n=>t+=n.length),t}function ba(e){return typeof e=="string"||e instanceof String}function k5(e){return typeof e=="boolean"}function I5(e){return typeof e=="number"}function dh(e){return Array.isArray(e)?dh(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":I5(e)?"float32":ba(e)?"string":k5(e)?"bool":"float32"}function va(e){return!!(e&&e.constructor&&e.call&&e.apply)}function ph(e,t){for(let n=t;n<e;++n)if(e%n==0)return n;return e}function Hl(e){let t=e.length;if(t<2)return[];let n=new Array(t-1);n[t-2]=e[t-1];for(let s=t-3;s>=0;--s)n[s]=n[s+1]*e[s+1];return n}function S5(e,t,n,s=!1){let r=new Array;if(t.length===1){let a=t[0]*(s?2:1);for(let o=0;o<a;o++)r[o]=n[e+o]}else{let a=t[0],o=t.slice(1),i=o.reduce((l,c)=>l*c)*(s?2:1);for(let l=0;l<a;l++)r[l]=S5(e+l*i,o,n,s)}return r}function jl(e,t,n=!1){if(e.length===0)return t[0];let s=e.reduce((r,a)=>r*a)*(n?2:1);if(s===0)return[];if(s!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return S5(0,e,t,n)}function r2(e,t){let n=hh(e,t);for(let s=0;s<n.length;s++)n[s]=1;return n}function hh(e,t){if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool")return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function TN(e,t){let n=e.reduce((s,r)=>s*r,1);if(t==null||t==="float32")return jl(e,new Float32Array(n));if(t==="int32")return jl(e,new Int32Array(n));if(t==="bool")return jl(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function a2(e){e.forEach(t=>{M(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function NN(e,t,n){if(t===0)return 0;if(t===1)return e[0];let s=e[e.length-1];for(let r=0;r<e.length-1;++r)s+=n[r]*e[r];return s}function EN(e,t,n){if(t===0)return[];if(t===1)return[e];let s=new Array(t);for(let r=0;r<s.length-1;++r)s[r]=Math.floor(e/n[r]),e-=s[r]*n[r];return s[s.length-1]=e,s}function o2(e){return e&&e.then&&typeof e.then=="function"}function Ir(...e){Z().getBool("IS_TEST")||Z().getBool("PROD")||console.warn(...e)}function RN(...e){Z().getBool("IS_TEST")||Z().getBool("PROD")||console.log(...e)}var C5="tfjsflags",T5=class{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=$N,this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&Ir(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},this.urlFlags[e]!=null){let s=this.urlFlags[e];Ir(`Setting feature override from URL ${e}: ${s}.`),this.set(e,s)}}async getAsync(e){return e in this.flags?this.flags[e]:(this.flags[e]=await this.evaluateFlag(e),this.flags[e])}get(e){if(e in this.flags)return this.flags[e];let t=this.evaluateFlag(e);if(o2(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null)throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(this.flagRegistry[e]==null)throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;let e=this.getQueryParams(this.global.location.search);C5 in e&&e[C5].split(",").forEach(n=>{let[s,r]=n.split(":");this.urlFlags[s]=_N(s,r)})}};function $N(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...s)=>(DN(t,s[0],s[1]),s.join("="))),t}function DN(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function _N(e,t){if(t=t.toLowerCase(),t==="true"||t==="false")return t==="true";if(`${+t}`===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}function Z(){return gs}var gs=null;function PN(e){gs=e}var i2;function N5(){if(i2==null){let e;if(typeof window!="undefined")e=window;else if(typeof global!="undefined")e=global;else if(typeof process!="undefined")e=process;else if(typeof self!="undefined")e=self;else throw new Error("Could not find a global object");i2=e}return i2}function FN(){let e=N5();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function l2(e,t){let n=FN();if(n.has(e))return n.get(e);{let s=t();return n.set(e,s),n.get(e)}}var ni="Abs",ql="Acos",Xl="Acosh",qr="Add",wa="AddN",Kl="All",Zl="Any",ka="ArgMax",Yl="ArgMin",Jl="Asin",Ql="Asinh",eu="Atan",tu="Atanh",nu="Atan2",Ia="AvgPool",fh="AvgPoolGrad",Hc="AvgPool3D",mh="AvgPool3DGrad",Sa="BatchMatMul",si="BatchToSpaceND",gh="Bincount",E5="BroadcastTo",u2="BroadcastArgs",Ca="Cast",Ta="Ceil",Xr="ClipByValue",jc="Complex",qc="ComplexAbs",ri="Concat",Na="Conv2D",yh="Conv2DBackpropFilter",Ea="Conv2DBackpropInput",Xc="Conv3D",Ah="Conv3DBackpropFilterV2",xh="Conv3DBackpropInputV2",Ra="Cos",$a="Cosh",ai="Cumsum",oi="CropAndResize",bh="DenseBincount",ii="DepthToSpace",Da="DepthwiseConv2dNative",vh="DepthwiseConv2dNativeBackpropFilter",wh="DepthwiseConv2dNativeBackpropInput",kh="Diag",Kc="Dilation2D",Ih="Dilation2DBackpropInput",Sh="Dilation2DBackpropFilter",_a="RealDiv",Zc="Einsum",Pa="Elu",Ch="EluGrad",su="Erf",li="Equal",Fa="Exp",ui="ExpandDims",ci="Expm1",Th="FFT",ru="Fill",di="FlipLeftRight",Oa="Floor",Ma="FloorDiv",za="FusedBatchNorm",pi="GatherV2",hi="GatherNd",fi="Greater",La="GreaterEqual",Ba="Identity",Nh="IFFT",Yc="Imag",au="IsFinite",ou="IsInf",iu="IsNan",mi="LeakyRelu",gi="Less",yi="LessEqual",Eh="LinSpace",Wa="Log",lu="Log1p",Ai="LogicalAnd",uu="LogicalNot",Jc="LogicalOr",R5="LogSoftmax",Qc="LRN",Rh="LRNGrad",Va="Max",Ua="Maximum",Ga="MaxPool",$h="MaxPoolGrad",ed="MaxPool3D",Dh="MaxPool3DGrad",_h="MaxPoolWithArgmax",Ha="Mean",ja="Min",qa="Minimum",Xa="MirrorPad",cu="Mod",Ph="Multinomial",Ka="Multiply",xi="Neg",bi="NotEqual",vi="NonMaxSuppressionV3",du="NonMaxSuppressionV4",wi="NonMaxSuppressionV5",ki="OnesLike",Ii="OneHot",Si="Pack",Za="PadV2",ON="Pool",Ya="Pow",Ja="Prelu",Ci="Prod",pu="Range",td="Real",hu="Reciprocal",Qa="Relu",Ti="Reshape",fu="ResizeNearestNeighbor",Fh="ResizeNearestNeighborGrad",eo="ResizeBilinear",Oh="ResizeBilinearGrad",to="Relu6",Ni="Reverse",Ei="Round",no="Rsqrt",Ri="ScatterNd",$i="Select",mu="Selu",Di="Slice",so="Sin",_i="Sinh",gu="Sign",ro="Sigmoid",yu="Softplus",ao="Sqrt",oo="Sum",Pi="SpaceToBatchND",Fi="SplitV",io="Softmax",Mh="SparseFillEmptyRows",zh="SparseReshape",Lh="SparseSegmentMean",Bh="SparseSegmentSum",nd="SparseToDense",lo="SquaredDifference",Au="Square",Oi="StridedSlice",sd="StringNGrams",Wh="StringSplit",Vh="StringToHashBucketFast",uo="Sub",Mi="Tan",co="Tanh",Kr="Tile",xu="TopK",zi="Transform",po="Transpose",Uh="Unique",Li="Unpack",rd="UnsortedSegmentSum",Bi="ZerosLike",ho="Step",ad="FromPixels",Wi="RotateWithOffset",fo="_FusedMatMul",mo="FusedConv2D",go="FusedDepthwiseConv2D",bu=l2("kernelRegistry",()=>new Map),od=l2("gradRegistry",()=>new Map);function Gh(e,t){let n=d2(e,t);return bu.get(n)}function c2(e){return od.get(e)}function Zr(e){let t=bu.entries(),n=[];for(;;){let{done:s,value:r}=t.next();if(s)break;let[a,o]=r,[i]=a.split("_");i===e&&n.push(o)}return n}function Yr(e){let{kernelName:t,backendName:n}=e,s=d2(t,n);bu.has(s)&&Ir(`The kernel '${t}' for backend '${n}' is already registered`),bu.set(s,e)}function $5(e){let{kernelName:t}=e;od.has(t)&&Z().getBool("DEBUG")&&Ir(`Overriding the gradient for '${t}'`),od.set(t,e)}function MN(e,t){let n=d2(e,t);if(!bu.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);bu.delete(n)}function zN(e){if(!od.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);od.delete(e)}function LN(e,t){Zr(e).forEach(s=>{let r=Object.assign({},s,{backendName:t});Yr(r)})}function d2(e,t){return`${t}_${e}`}var v={};Le(v,{arraysEqual:()=>jr,assert:()=>M,assertNonNegativeIntegerDimensions:()=>a2,assertNonNull:()=>ei,assertShapesMatch:()=>Mn,bytesFromStringArray:()=>w5,bytesPerElement:()=>s2,checkConversionForErrors:()=>b5,clamp:()=>Uc,computeStrides:()=>Hl,createScalarValue:()=>HN,createShuffledIndices:()=>kN,decodeString:()=>qh,distSquared:()=>xN,encodeString:()=>ud,fetch:()=>qN,fingerPrint64:()=>GN,flatten:()=>ti,getArrayFromDType:()=>x5,getTypedArrayFromDType:()=>A5,hasEncodingLoss:()=>CN,hexToLong:()=>id,indexToLoc:()=>EN,inferDtype:()=>dh,inferFromImplicitShape:()=>SN,isBoolean:()=>k5,isFunction:()=>va,isInt:()=>mn,isNumber:()=>I5,isPromise:()=>o2,isScalarShape:()=>bN,isString:()=>ba,isTypedArray:()=>_n,isValidDtype:()=>v5,locToIndex:()=>NN,makeOnesTypedArray:()=>r2,makeZerosNestedTypedArray:()=>TN,makeZerosTypedArray:()=>hh,nearestDivisor:()=>ph,nearestLargerEven:()=>gN,now:()=>ld,parseAxisParam:()=>qs,randUniform:()=>AN,repeatedTry:()=>IN,rightPad:()=>Gc,shuffle:()=>g5,shuffleCombo:()=>mN,sizeFromShape:()=>Ht,sizeToSquarishShape:()=>wN,squeezeShape:()=>y5,sum:()=>yN,swap:()=>ch,tanh:()=>vN,toNestedArray:()=>jl,toTypedArray:()=>jh});var D5=Qo(qT()),Vi=D5.default||D5;function id(e){return Vi.fromString(e,!0,16)}var _5=id("c3a5c85c97cb3127"),Ui=id("b492b66fbe98f273"),zn=id("9ae16a3b2f90404f");function p2(e){return e.xor(e.shru(47))}function P5(e,t,n){let s=e.slice(t,t+n);return Vi.fromBytes(Array.from(s),!0,!0)}function Ct(e,t){return P5(e,t,8)}function F5(e,t){return P5(e,t,4)}function gn(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function yo(e,t,n=id("9ddfea08eb382d69")){let s=e.xor(t).mul(n);s=s.xor(s.shru(47));let r=t.xor(s).mul(n);return r=r.xor(r.shru(47)),r=r.mul(n),r}function BN(e,t,n,s,r,a){r=r.add(e),a=gn(a.add(r).add(s),21);let o=r;return r=r.add(t),r=r.add(n),a=a.add(gn(r,44)),[r.add(s),a.add(o)]}function Hh(e,t,n,s){return BN(Ct(e,t),Ct(e,t+8),Ct(e,t+16),Ct(e,t+24),n,s)}function WN(e,t=e.length){if(t>=8){let n=zn.add(t*2),s=Ct(e,0).add(zn),r=Ct(e,t-8),a=gn(r,37).mul(n).add(s),o=gn(s,25).add(r).mul(n);return yo(a,o,n)}if(t>=4){let n=zn.add(t*2),s=F5(e,0);return yo(s.shl(3).add(t),F5(e,t-4),n)}if(t>0){let n=e[0],s=e[t>>1],r=e[t-1],a=n+(s<<8),o=t+(r<<2);return p2(zn.mul(a).xor(_5.mul(o))).mul(zn)}return zn}function VN(e,t=e.length){let n=zn.add(t*2),s=Ct(e,0).mul(Ui),r=Ct(e,8),a=Ct(e,t-8).mul(n),o=Ct(e,t-16).mul(zn);return yo(gn(s.add(r),43).add(gn(a,30)).add(o),s.add(gn(r.add(zn),18)).add(a),n)}function UN(e,t=e.length){let n=zn.add(t*2),s=Ct(e,0).mul(zn),r=Ct(e,8),a=Ct(e,t-8).mul(n),o=Ct(e,t-16).mul(zn),i=gn(s.add(r),43).add(gn(a,30)).add(o),l=yo(i,s.add(gn(r.add(zn),18)).add(a),n),c=Ct(e,16).mul(n),u=Ct(e,24),d=i.add(Ct(e,t-32)).mul(n),p=l.add(Ct(e,t-24)).mul(n);return yo(gn(c.add(u),43).add(gn(d,30)).add(p),c.add(gn(u.add(s),18)).add(d),n)}function GN(e,t=e.length){let n=Vi.fromNumber(81,!0);if(t<=32)return t<=16?WN(e,t):VN(e,t);if(t<=64)return UN(e,t);let s=n,r=n.mul(Ui).add(113),a=p2(r.mul(zn).add(113)).mul(zn),o=[Vi.UZERO,Vi.UZERO],i=[Vi.UZERO,Vi.UZERO];s=s.mul(zn).add(Ct(e,0));let l=0,c=(t-1>>6)*64,u=c+(t-1&63)-63;do s=gn(s.add(r).add(o[0]).add(Ct(e,l+8)),37).mul(Ui),r=gn(r.add(o[1]).add(Ct(e,l+48)),42).mul(Ui),s=s.xor(i[1]),r=r.add(o[0]).add(Ct(e,l+40)),a=gn(a.add(i[0]),33).mul(Ui),o=Hh(e,l,o[1].mul(Ui),s.add(i[0])),i=Hh(e,l+32,a.add(i[1]),r.add(Ct(e,l+16))),[a,s]=[s,a],l+=64;while(l!==c);let d=Ui.add(a.and(255).shl(1));return l=u,i[0]=i[0].add(t-1&63),o[0]=o[0].add(i[0]),i[0]=i[0].add(o[0]),s=gn(s.add(r).add(o[0]).add(Ct(e,l+8)),37).mul(d),r=gn(r.add(o[1]).add(Ct(e,l+48)),42).mul(d),s=s.xor(i[1].mul(9)),r=r.add(o[0].mul(9).add(Ct(e,l+40))),a=gn(a.add(i[0]),33).mul(d),o=Hh(e,l,o[1].mul(d),s.add(i[0])),i=Hh(e,l+32,a.add(i[1]),r.add(Ct(e,l+16))),[a,s]=[s,a],yo(yo(o[0],i[0],d).add(p2(r).mul(_5)).add(a),yo(o[1],i[1],d).add(s),d)}function HN(e,t){return t==="string"?ud(e):jh([e],t)}function jN(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function jh(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=ti(e)),Z().getBool("DEBUG")&&b5(e,t),jN(e,t))return e;if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"){let n=new Uint8Array(e.length);for(let s=0;s<n.length;++s)Math.round(e[s])!==0&&(n[s]=1);return n}else throw new Error(`Unknown data type ${t}`)}function ld(){return Z().platform.now()}function qN(e,t){return Z().platform.fetch(e,t)}function ud(e,t="utf-8"){return t=t||"utf-8",Z().platform.encode(e,t)}function qh(e,t="utf-8"){return t=t||"utf-8",Z().platform.decode(e,t)}var XN=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new ZN)}profileKernel(e,t,n){let s,r=()=>{s=n()},a,o=ld();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(r);else{r();for(let l of s)l.dataSync();a=Promise.resolve({kernelMs:ld()-o})}if(Z().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let l=0;l<s.length;l++){let c=s[l];c.data().then(u=>{KN(u,c.dtype,e)})}return{kernelName:e,outputs:s,inputs:t,timeMs:a.then(l=>l.kernelMs),extraInfo:a.then(l=>l.getExtraProfileInfo!=null?l.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:s,inputs:r,extraInfo:a}=e;n.forEach(o=>{Promise.all([o.data(),s,a]).then(i=>{this.logger.logKernelProfile(t,o,i[0],i[1],r,i[2])})})}};function KN(e,t,n){if(t!=="float32")return!1;for(let s=0;s<e.length;s++){let r=e[s];if(isNaN(r)||!isFinite(r))return console.warn(`Found ${r} in the result of '${n}'`),!0}return!1}var ZN=class{logKernelProfile(e,t,n,s,r,a){let o=typeof s=="number"?Gc(`${s}ms`,9):s.error,i=Gc(e,25),l=t.rank,c=t.size,u=Gc(t.shape.toString(),14),d="";for(let p in r){let h=r[p];if(h!=null){let f=h.shape||t.shape,m=f.length;d+=`${p}: ${m}D ${m>0?f:""} `}}console.log(`%c${i} %c${o} %c${l}D ${u} %c${c} %c${d} %c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function YN(e,t,n){let s={},r={};for(let l=0;l<t.length;l++)s[t[l].id]=!0;for(let l=0;l<e.length;l++){let c=e[l],u=c.inputs;for(let d in u){let p=u[d],h=!1;for(let f=0;f<t.length;f++)if(s[p.id]){c.outputs.forEach(m=>s[m.id]=!0),h=!0,r[c.id]=!0;break}if(h)break}}let a={};a[n.id]=!0;let o={};for(let l=e.length-1;l>=0;l--){let c=e[l],u=c.inputs;for(let d=0;d<c.outputs.length;d++)if(a[c.outputs[d].id]){for(let p in u)a[u[p].id]=!0,o[c.id]=!0;break}}let i=[];for(let l=0;l<e.length;l++){let c=e[l];if(r[c.id]&&o[c.id]){let u={};for(let p in c.inputs){let h=c.inputs[p];s[h.id]&&(u[p]=h)}let d=Object.assign({},c);d.inputs=u,d.outputs=c.outputs,i.push(d)}}return i}function JN(e,t,n,s){for(let r=t.length-1;r>=0;r--){let a=t[r],o=[];if(a.outputs.forEach(l=>{let c=e[l.id];c!=null?o.push(c):o.push(null)}),a.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);let i=a.gradient(o);for(let l in a.inputs){if(!(l in i))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(i)}.`);let c=n(()=>i[l]());if(c.dtype!=="float32")throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${c.dtype}'`);let u=a.inputs[l];if(!jr(c.shape,u.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${l}' has shape '${c.shape}', which does not match the shape of the input '${u.shape}'`);if(e[u.id]==null)e[u.id]=c;else{let d=e[u.id];e[u.id]=s(d,c),d.dispose()}}}}var O5=20,cd=3,h2=7;function QN(e,t,n,s){let r=Hl(t),a=e9(e,t,n,r),o=t.length,i=Xh(e,t,n,r,a),l=["Tensor"];return s&&(l.push(` dtype: ${n}`),l.push(` rank: ${o}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(i.map(c=>" "+c).join(`
|
|
`)),l.join(`
|
|
`)}function e9(e,t,n,s){let r=Ht(t),a=s[s.length-1],o=new Array(a).fill(0),i=t.length,l=n==="complex64"?pd(e):e;if(i>1)for(let c=0;c<r/a;c++){let u=c*a;for(let d=0;d<a;d++)o[d]=Math.max(o[d],dd(l[u+d],0,n).length)}return o}function dd(e,t,n){let s;return Array.isArray(e)?s=`${parseFloat(e[0].toFixed(h2))} + ${parseFloat(e[1].toFixed(h2))}j`:ba(e)?s=`'${e}'`:n==="bool"?s=M5(e):s=parseFloat(e.toFixed(h2)).toString(),Gc(s,t)}function M5(e){return e===0?"false":"true"}function Xh(e,t,n,s,r,a=!0){let o=n==="complex64"?2:1,i=t[0],l=t.length;if(l===0){if(n==="complex64"){let m=pd(e);return[dd(m[0],0,n)]}return n==="bool"?[M5(e[0])]:[e[0].toString()]}if(l===1){if(i>O5){let g=cd*o,y=Array.from(e.slice(0,g)),A=Array.from(e.slice((i-cd)*o,i*o));return n==="complex64"&&(y=pd(y),A=pd(A)),["["+y.map((x,b)=>dd(x,r[b],n)).join(", ")+", ..., "+A.map((x,b)=>dd(x,r[i-cd+b],n)).join(", ")+"]"]}let m=n==="complex64"?pd(e):Array.from(e);return["["+m.map((g,y)=>dd(g,r[y],n)).join(", ")+"]"]}let c=t.slice(1),u=s.slice(1),d=s[0]*o,p=[];if(i>O5){for(let m=0;m<cd;m++){let g=m*d,y=g+d;p.push(...Xh(e.slice(g,y),c,n,u,r,!1))}p.push("...");for(let m=i-cd;m<i;m++){let g=m*d,y=g+d;p.push(...Xh(e.slice(g,y),c,n,u,r,m===i-1))}}else for(let m=0;m<i;m++){let g=m*d,y=g+d;p.push(...Xh(e.slice(g,y),c,n,u,r,m===i-1))}let h=l===2?",":"";p[0]="["+p[0]+h;for(let m=1;m<p.length-1;m++)p[m]=" "+p[m]+h;let f=`,
|
|
`;for(let m=2;m<l;m++)f+=`
|
|
`;return p[p.length-1]=" "+p[p.length-1]+"]"+(a?"":f),p}function pd(e){let t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var tn=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=Ht(e),n!=null){let s=n.length;M(s===this.size,()=>`Length of values '${s}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||x5(t,this.size),this.strides=Hl(e)}set(e,...t){t.length===0&&(t=[0]),M(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let s of e){if(s<0||s>=this.shape[t]){let r=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(r)}t++}let n=e[e.length-1];for(let s=0;s<e.length-1;++s)n+=this.strides[s]*e[s];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Sr().makeTensor(this.values,this.shape,this.dtype)}},Sr=null,vu=null,t9=null;function n9(e){Sr=e}function s9(e){vu=e}function r9(e){t9=e}var Ke=class{constructor(e,t,n,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=Ht(e),this.strides=Hl(e),this.dataId=n,this.id=s,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return vu.buffer(this.shape,this.dtype,e)}bufferSync(){return vu.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return jl(this.shape,e,this.dtype==="complex64")}arraySync(){return jl(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=Sr().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>qh(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();let e=Sr().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>qh(t))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();let e=await Sr().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Sr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return vu.print(this,e)}clone(){return this.throwIfDisposed(),vu.clone(this)}toString(e=!1){let t=this.dataSync();return QN(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),vu.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Sr().makeVariable(this,e,t,n)}};Object.defineProperty(Ke,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function re(){return l2("Tensor",()=>Ke)}re();var hd=class extends Ke{constructor(e,t,n,s){super(e.shape,e.dtype,e.dataId,s);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!jr(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Sr().disposeTensor(this),this.dataId=e.dataId,Sr().incRef(this,null)}dispose(){Sr().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(hd,Symbol.hasInstance,{value:e=>e instanceof Ke&&e.assign!=null&&e.assign instanceof Function});var ar={};Le(ar,{assertTypesMatch:()=>z5,getTensorsInContainer:()=>x2,isTensorInList:()=>o9,makeTypesMatch:()=>zt});var f2;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(f2||(f2={}));var m2;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(m2||(m2={}));var g2;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(g2||(g2={}));var y2;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(y2||(y2={}));var A2;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(A2||(A2={}));var a9={float32:y2,int32:m2,bool:g2,complex64:A2};function Ln(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return a9[e][t]}function fd(e){return Ln(e,"int32")}function zt(e,t){if(e.dtype===t.dtype)return[e,t];let n=Ln(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function z5(e,t){M(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function o9(e,t){return t.some(n=>n.id===e.id)}function x2(e){let t=[],n=new Set;return L5(e,t,n),t}function L5(e,t,n){if(e==null)return;if(e instanceof Ke){t.push(e);return}if(!i9(e))return;let s=e;for(let r in s){let a=s[r];n.has(a)||(n.add(a),L5(a,t,n))}}function i9(e){return Array.isArray(e)||typeof e=="object"}function b2(e){return e.kernelName!=null}var B5=class{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map(e=>e.name)))}}}dispose(){for(let e in this.registeredVariables)this.registeredVariables[e].dispose()}},md=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new B5}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let n=e[t];if(await this.initializeBackend(n).success){await this.setBackend(n);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){let{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry))if(e in this.registryFactory){let{asyncInit:t}=this.initializeBackend(e);if(t)return null}else return null;return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(Ir(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(this.registryFactory[e]==null)throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,this.registry[e]==null){this.backendInstance=null;let{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new XN(this.backendInstance),!0}setupRegisteredKernels(){Zr(this.backendName).forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Zr(e).forEach(n=>{n.disposeFunc!=null&&n.disposeFunc(this.registry[e])})}initializeBackend(e){let t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{let n=t.factory();if(n&&!(n instanceof Gl)&&typeof n.then=="function"){let s=++this.pendingBackendInitId,r=n.then(a=>s<this.pendingBackendInitId?!1:(this.registry[e]=a,this.pendingBackendInit=null,!0)).catch(a=>(s<this.pendingBackendInitId||(this.pendingBackendInit=null,Ir(`Initialization of backend ${e} failed`),Ir(a.stack||a.message)),!1));return this.pendingBackendInit=r,{success:r,asyncInit:!0}}else return this.registry[e]=n,{success:!0,asyncInit:!1}}catch(n){return Ir(`Initialization of backend ${e} failed`),Ir(n.stack||n.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let n=e[t],{success:s,asyncInit:r}=this.initializeBackend(n);if(r||s)return{name:n,asyncInit:r}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){let n=this.state.tensorInfo.get(t),s=n.backend,r=this.readSync(t),a=s.refCount(t);s.disposeData(t,!0),n.backend=e,e.move(t,r,n.shape,n.dtype,a),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n=null;if(t==null){if(typeof e!="function")throw new Error("Please provide a function to tidy()");t=e}else{if(typeof e!="string"&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof t!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");n=e}let s;return this.scopedRun(()=>this.startScope(n),()=>this.endScope(s),()=>(s=t(),s instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),s))}scopedRun(e,t,n){e();try{let s=n();return t(),s}catch(s){throw t(),s}}nextTensorId(){return md.nextTensorId++}nextVariableId(){return md.nextVariableId++}clone(e){let t=W.runKernel(Ba,{x:e}),n={x:e},s=a=>({x:()=>{let o="float32",i={x:a},l={dtype:o};return W.runKernel(Ca,i,l)}}),r=[];return this.addTapeNode(this.state.activeScope.name,n,[t],s,r,{}),t}runKernel(e,t,n){if(this.backendName==null&&this.backend,!(Gh(e,this.backendName)!=null))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){let s=this.backend.numDataIds(),r=0;n.forEach(i=>{r+=i.dtype==="complex64"?3:1});let a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=s-t-r-a;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[],s=this.isTapeOn(),r=this.state.numBytes,a=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let o;this.backendName==null&&this.backend;let i,l=b2(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(b2(e)){let{kernelName:h,inputs:f,attrs:m}=e;this.backendName==null&&this.backend;let g=Gh(h,this.backendName);M(g!=null,()=>`Cannot find registered kernel '${h}' for backend '${this.backendName}'`),o=()=>{let y=this.backend.numDataIds();i=g.kernelFunc({inputs:f,attrs:m,backend:this.backend});let A=Array.isArray(i)?i:[i];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(h,y,A);let x=A.map(b=>{if(b.rank!=null)return b;let{dataId:w,shape:k,dtype:S}=b;return this.makeTensorFromDataId(w,k,S)});if(s){let b=this.getTensorsForGradient(h,f,x);n=this.saveTensorsForBackwardMode(b)}return x}}else{let{forwardFunc:h}=e,f=m=>{!s||(n=m.map(g=>this.keep(this.clone(g))))};o=()=>{let m=this.backend.numDataIds();i=this.tidy(()=>h(this.backend,f));let g=Array.isArray(i)?i:[i];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,m,g),g}}let{inputs:c,attrs:u}=e,d=b2(e)?null:e.backwardsFunc,p;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=o():(p=this.profiler.profileKernel(l,c,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs)}),s&&this.addTapeNode(l,c,t,d,n,u),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map(h=>c[h]!=null?c[h].shape:null),outputShapes:t.map(h=>h.shape),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(i)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(n=>this.keep(this.clone(n)))}getTensorsForGradient(e,t,n){let s=c2(e);if(s!=null){let r=s.inputsToSave||[],a=s.outputsToSave||[],o;s.saveAllInputs?(M(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),o=Object.keys(t).map(l=>t[l])):o=r.map(l=>t[l]);let i=n.filter((l,c)=>a[c]);return o.concat(i)}return[]}makeTensor(e,t,n,s){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",s=s||this.backend;let r=e;n==="string"&&ba(e[0])&&(r=e.map(i=>ud(i)));let a=s.write(r,t,n),o=new Ke(t,n,a,this.nextTensorId());if(this.trackTensor(o,s),n==="string"){let i=this.state.tensorInfo.get(a),l=w5(r);this.state.numBytes+=l-i.bytes,i.bytes=l}return o}makeTensorFromDataId(e,t,n,s){n=n||"float32";let r=new Ke(t,n,e,this.nextTensorId());return this.trackTensor(r,s),r}makeVariable(e,t=!0,n,s){n=n||this.nextVariableId().toString(),s!=null&&s!==e.dtype&&(e=e.cast(s));let r=new hd(e,t,n,this.nextTensorId());if(this.state.registeredVariables[r.name]!=null)throw new Error(`Variable with name ${r.name} was already registered`);return this.state.registeredVariables[r.name]=r,this.incRef(r,this.backend),r}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let n=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(n=e.size*s2(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof hd||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;let t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,e.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),e.dtype!=="complex64"&&e.dtype!=="string"){let n=e.size*s2(e.dtype);this.state.numBytes-=n}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(let e in this.state.registeredVariables){let t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]}memory(){let e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,e.reasons==null&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;let t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(s=>s.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(let s of this.state.activeProfile.kernels)s.kernelTimeMs=await s.kernelTimeMs,s.extraInfo=await s.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,s,r,a){let o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:r},i=c2(e);i!=null&&(s=i.gradFunc),s!=null&&(o.gradient=l=>(l=l.map((c,u)=>{if(c==null){let d=n[u],p=hh(d.size,d.dtype);return this.makeTensor(p,d.shape,d.dtype)}return c}),s(l.length>1?l:l[0],r,a))),this.state.activeTape.push(o)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=x2(e),n=new Set(t.map(r=>r.id));for(let r=0;r<this.state.activeScope.track.length;r++){let a=this.state.activeScope.track[r];!a.kept&&!n.has(a.id)&&a.dispose()}let s=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(r=>{!r.kept&&r.scopeId===s.id&&this.track(r)})}gradients(e,t,n,s=!1){if(M(t.length>0,()=>"gradients() received an empty list of xs."),n!=null&&n.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);let r=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));M(r instanceof Ke,()=>"The result y returned by f() must be a tensor.");let a=YN(this.state.activeTape,t,r);if(!s&&a.length===0&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{let o={};o[r.id]=n==null?l9(r.shape):n,JN(o,a,l=>this.tidy(l),u9);let i=t.map(l=>o[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let c of l.saved)c.dispose()}),this.state.activeTape=null),{value:r,grads:i}})}customGrad(e){return M(va(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{M(t.every(o=>o instanceof Ke),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,s={};t.forEach((o,i)=>{s[i]=o});let r=(o,i)=>(n=e(...t,i),M(n.value instanceof Ke,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),M(va(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),a=(o,i)=>{let l=n.gradFunc(o,i),c=Array.isArray(l)?l:[l];M(c.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),M(c.every(d=>d instanceof Ke),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let u={};return c.forEach((d,p)=>{u[p]=()=>d}),u};return this.runKernelFunc({forwardFunc:r,backwardsFunc:a,inputs:s})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}async time(e){let t=ld(),n=await this.backend.time(e);return n.wallMs=ld()-t,n}track(e){return this.state.activeScope!=null&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new B5;for(let e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}};md.nextTensorId=0;md.nextVariableId=0;function l9(e){let t=r2(Ht(e),"float32");return W.makeTensor(t,e,"float32")}function W5(){let e=N5();if(e._tfengine==null){let t=new T5(e);e._tfengine=new md(t)}return PN(e._tfengine.ENV),n9(()=>e._tfengine),e._tfengine}var W=W5();function u9(e,t){let n={a:e,b:t};return W.runKernel(qr,n)}var wu={};Le(wu,{isBrowser:()=>V5,isMobile:()=>d9});function c9(){return typeof navigator!="undefined"&&navigator!=null}function d9(e){if(e||c9()){if(e||(e=navigator),e.product==="ReactNative")return!0;let t=e.userAgent||e.vendor||(typeof window!="undefined"?window.opera:"");if(!t){let n=e;return n.userAgentData&&n.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}return!1}function V5(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var or=Z();or.registerFlag("DEBUG",()=>!1,e=>{e&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")});or.registerFlag("IS_BROWSER",()=>V5());or.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");or.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));or.registerFlag("PROD",()=>!1);or.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>or.getBool("DEBUG"));or.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);or.registerFlag("IS_TEST",()=>!1);or.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);or.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function Cr(e,t){let n=e;if(_n(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let s=[];for(;Array.isArray(n)||_n(n)&&t!=="string";)s.push(n.length),n=n[0];return Array.isArray(e)&&Z().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&U5(e,s,[]),s}function U5(e,t,n){if(n=n||[],!Array.isArray(e)&&!_n(e)){M(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}M(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),M(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let s=t.slice(1);for(let r=0;r<e.length;++r)U5(e[r],s,n.concat(r))}function G5(e,t,n,s){if(e!=="string_or_numeric"){if(e==null)throw new Error("Expected dtype cannot be null.");if(e!=="numeric"&&e!==t||e==="numeric"&&t==="string")throw new Error(`Argument '${n}' passed to '${s}' must be ${e} tensor, but got ${t} tensor`)}}function _(e,t,n,s="numeric"){if(e instanceof Ke)return G5(s,e.dtype,t,n),e;let r=dh(e);if(r!=="string"&&["bool","int32","float32"].indexOf(s)>=0&&(r=s),G5(s,r,t,n),e==null||!_n(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){let l=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${l}'`)}let a=Cr(e,r);!_n(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?jh(e,r):ti(e,[],!0);return W.makeTensor(i,a,r)}function gd(e,t,n,s="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((a,o)=>_(a,`${t}[${o}]`,n,s))}var H5="__op";function U(e){let t=Object.keys(e);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0],s=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+H5;let r=(...a)=>{W.startScope(n);try{let o=s(...a);return o2(o)&&console.error("Cannot return a Promise inside of tidy."),W.endScope(o),o}catch(o){throw W.endScope(null),o}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}function p9(e,t){let n=_(e,"real","complex"),s=_(t,"imag","complex");Mn(n.shape,s.shape,`real and imag shapes, ${n.shape} and ${s.shape}, must match in call to tf.complex().`);let r={real:n,imag:s};return W.runKernel(jc,r)}var Ao=U({complex_:p9});function xo(e,t,n,s){if(s==null&&(s=dh(e)),s==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!_n(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string")throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(t!=null){a2(t);let r=Ht(t),a=Ht(n);M(r===a,()=>`Based on the provided shape, [${t}], the tensor should have ${r} values but has ${a}`);for(let o=0;o<n.length;++o){let i=n[o],l=o===n.length-1?i!==Ht(t.slice(o)):!0;M(n[o]===t[o]||!l,()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!_n(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=s!=="string"?jh(e,s):ti(e,[],!0),W.makeTensor(e,t,s)}function nn(e,t,n){let s=Cr(e,n);return xo(e,t,s,n)}var v2={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},Kh=4;async function h9(e,t){let n=[],s=[],r=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);for(let o=0;o<r.length;++o){let i=r[o],l=Array.isArray(e)?e[o].tensor:e[i];if(l.dtype!=="float32"&&l.dtype!=="int32"&&l.dtype!=="bool"&&l.dtype!=="string"&&l.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${i}': ${l.dtype}`);let c={name:i,shape:l.shape,dtype:l.dtype};if(l.dtype==="string"){let u=new Promise(async d=>{let p=await l.bytes(),h=p.reduce((g,y)=>g+y.length,0)+Kh*p.length,f=new Uint8Array(h),m=0;for(let g=0;g<p.length;g++){let y=p[g],A=new Uint8Array(new Uint32Array([y.length]).buffer);f.set(A,m),m+=Kh,f.set(y,m),m+=y.length}d(f)});s.push(u)}else s.push(l.data());t!=null&&(c.group=t),n.push(c)}let a=await Promise.all(s);return{data:f9(a),specs:n}}function j5(e,t){let n={},s,r=0;for(let a of t){let o=a.name,i=a.dtype,l=a.shape,c=Ht(l),u;if("quantization"in a){let d=a.quantization;if(d.dtype==="uint8"||d.dtype==="uint16"){if(!("min"in d&&"scale"in d))throw new Error(`Weight ${a.name} with quantization ${d.dtype} doesn't have corresponding metadata min and scale.`)}else if(d.dtype==="float16"){if(i!=="float32")throw new Error(`Weight ${a.name} is quantized with ${d.dtype} which only supports weights of type float32 not ${i}.`)}else throw new Error(`Weight ${a.name} has unknown quantization dtype ${d.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let p=v2[d.dtype],h=e.slice(r,r+c*p),f=d.dtype==="uint8"?new Uint8Array(h):new Uint16Array(h);if(i==="float32")if(d.dtype==="uint8"||d.dtype==="uint16"){u=new Float32Array(f.length);for(let m=0;m<f.length;m++){let g=f[m];u[m]=g*d.scale+d.min}}else if(d.dtype==="float16")s===void 0&&(s=b9()),u=s(f);else throw new Error(`Unsupported quantization type ${d.dtype} for weight type float32.`);else if(i==="int32"){if(d.dtype!=="uint8"&&d.dtype!=="uint16")throw new Error(`Unsupported quantization type ${d.dtype} for weight type int32.`);u=new Int32Array(f.length);for(let m=0;m<f.length;m++){let g=f[m];u[m]=Math.round(g*d.scale+d.min)}}else throw new Error(`Unsupported dtype in weight '${o}': ${i}`);r+=c*p}else if(i==="string"){let d=Ht(a.shape);u=[];for(let p=0;p<d;p++){let h=new Uint32Array(e.slice(r,r+Kh))[0];r+=Kh;let f=new Uint8Array(e.slice(r,r+h));u.push(f),r+=h}}else{let d=v2[i],p=e.slice(r,r+c*d);if(i==="float32")u=new Float32Array(p);else if(i==="int32")u=new Int32Array(p);else if(i==="bool")u=new Uint8Array(p);else if(i==="complex64"){u=new Float32Array(p);let h=new Float32Array(u.length/2),f=new Float32Array(u.length/2);for(let y=0;y<h.length;y++)h[y]=u[y*2],f[y]=u[y*2+1];let m=nn(h,l,"float32"),g=nn(f,l,"float32");n[o]=Ao(m,g),m.dispose(),g.dispose()}else throw new Error(`Unsupported dtype in weight '${o}': ${i}`);r+=c*d}i!=="complex64"&&(n[o]=nn(u,l,i))}return n}function f9(e){if(e===null)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0,n=[];e.forEach(a=>{if(t+=a.byteLength,n.push(a.byteLength===a.buffer.byteLength?a:new a.constructor(a)),!(a instanceof Float32Array||a instanceof Int32Array||a instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${a.constructor.name}`)});let s=new Uint8Array(t),r=0;return n.forEach(a=>{s.set(new Uint8Array(a.buffer),r),r+=a.byteLength}),s.buffer}var w2=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function q5(e){return w2?Buffer.byteLength(e):new Blob([e]).size}function m9(e){if(w2)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),n="";for(let s=0,r=t.length;s<r;s++)n+=String.fromCharCode(t[s]);return btoa(n)}function g9(e){if(w2){let s=Buffer.from(e,"base64");return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)}let t=atob(e),n=new Uint8Array(t.length);for(let s=0;s<t.length;++s)n.set([t.charCodeAt(s)],s);return n.buffer}function k2(e){if(e.length===1)return e[0];let t=0;e.forEach(r=>{t+=r.byteLength});let n=new Uint8Array(t),s=0;return e.forEach(r=>{n.set(new Uint8Array(r),s),s+=r.byteLength}),n.buffer}function X5(e){let t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);let n=e.split(t);return n[n.length-1]}function K5(e,t){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),n}async function I2(e,t){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),e.weightsManifest!=null){let[s,r]=await t(e.weightsManifest);n.weightSpecs=s,n.weightData=r}return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),n}function yd(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:e.modelTopology==null?0:q5(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:q5(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function y9(){let e=n=>{let s=n<<13,r=0;for(;(s&8388608)==0;)r-=8388608,s<<=1;return s&=~8388608,r+=947912704,s|r},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let n=1024;n<2048;n++)t[n]=939524096+(n-1024<<13);return t}function A9(){let e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}function x9(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function b9(){let e=y9(),t=A9(),n=x9();return s=>{let r=new ArrayBuffer(4*s.length),a=new Uint32Array(r);for(let o=0;o<s.length;o++){let i=s[o],l=e[n[i>>10]+(i&1023)]+t[i>>10];a[o]=l}return new Float32Array(r)}}var Ut=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Ut.instance==null&&(Ut.instance=new Ut),Ut.instance}static registerSaveRouter(e){Ut.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Ut.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Ut.getHandlers(e,"save")}static getLoadHandlers(e,t){return Ut.getHandlers(e,"load",t)}static getHandlers(e,t,n){let s=[];return(t==="load"?Ut.getInstance().loadRouters:Ut.getInstance().saveRouters).forEach(a=>{let o=a(e,n);o!==null&&s.push(o)}),s}},v9=e=>Ut.registerSaveRouter(e),w9=e=>Ut.registerLoadRouter(e),k9=e=>Ut.getSaveHandlers(e),I9=(e,t)=>Ut.getLoadHandlers(e,t),S2="tensorflowjs",C2=1,Gi="models_store",bo="model_info_store";function Z5(){if(!Z().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");let e=typeof window=="undefined"?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function T2(e){let t=e.result;t.createObjectStore(Gi,{keyPath:"modelPath"}),t.createObjectStore(bo,{keyPath:"modelPath"})}var Hi=class{constructor(e){if(this.indexedDB=Z5(),e==null||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((n,s)=>{let r=this.indexedDB.open(S2,C2);r.onupgradeneeded=()=>T2(r),r.onsuccess=()=>{let a=r.result;if(t==null){let o=a.transaction(Gi,"readonly"),l=o.objectStore(Gi).get(this.modelPath);l.onsuccess=()=>{if(l.result==null)return a.close(),s(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(l.result.modelArtifacts)},l.onerror=c=>(a.close(),s(l.error)),o.oncomplete=()=>a.close()}else{let o=yd(t),i=a.transaction(bo,"readwrite"),l=i.objectStore(bo),c=l.put({modelPath:this.modelPath,modelArtifactsInfo:o}),u;c.onsuccess=()=>{u=a.transaction(Gi,"readwrite");let p=u.objectStore(Gi).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:o});p.onsuccess=()=>n({modelArtifactsInfo:o}),p.onerror=h=>{l=i.objectStore(bo);let f=l.delete(this.modelPath);f.onsuccess=()=>(a.close(),s(p.error)),f.onerror=m=>(a.close(),s(p.error))}},c.onerror=d=>(a.close(),s(c.error)),i.oncomplete=()=>{u==null?a.close():u.oncomplete=()=>a.close()}}},r.onerror=a=>s(r.error)})}};Hi.URL_SCHEME="indexeddb://";var Y5=e=>Z().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Hi.URL_SCHEME)?S9(e.slice(Hi.URL_SCHEME.length)):null;Ut.registerSaveRouter(Y5);Ut.registerLoadRouter(Y5);function S9(e){return new Hi(e)}function C9(e){return e.startsWith(Hi.URL_SCHEME)?e.slice(Hi.URL_SCHEME.length):e}var T9=class{constructor(){this.indexedDB=Z5()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(S2,C2);n.onupgradeneeded=()=>T2(n),n.onsuccess=()=>{let s=n.result,r=s.transaction(bo,"readonly"),o=r.objectStore(bo).getAll();o.onsuccess=()=>{let i={};for(let l of o.result)i[l.modelPath]=l.modelArtifactsInfo;e(i)},o.onerror=i=>(s.close(),t(o.error)),r.oncomplete=()=>s.close()},n.onerror=s=>t(n.error)})}async removeModel(e){return e=C9(e),new Promise((t,n)=>{let s=this.indexedDB.open(S2,C2);s.onupgradeneeded=()=>T2(s),s.onsuccess=()=>{let r=s.result,a=r.transaction(bo,"readwrite"),o=a.objectStore(bo),i=o.get(e),l;i.onsuccess=()=>{if(i.result==null)return r.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let c=o.delete(e),u=()=>{l=r.transaction(Gi,"readwrite");let p=l.objectStore(Gi).delete(e);p.onsuccess=()=>t(i.result.modelArtifactsInfo),p.onerror=h=>n(i.error)};c.onsuccess=u,c.onerror=d=>(u(),r.close(),n(i.error))}},i.onerror=c=>(r.close(),n(i.error)),a.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},s.onerror=r=>n(s.error)})}},Jr="/",ku="tensorflowjs_models",J5="info",N9="model_topology",E9="weight_specs",R9="weight_data",$9="model_metadata";function Q5(e){return{info:[ku,e,J5].join(Jr),topology:[ku,e,N9].join(Jr),weightSpecs:[ku,e,E9].join(Jr),weightData:[ku,e,R9].join(Jr),modelMetadata:[ku,e,$9].join(Jr)}}function e3(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function D9(e){let t=e.split(Jr);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Jr)}function _9(e){return e.startsWith(ji.URL_SCHEME)?e.slice(ji.URL_SCHEME.length):e}var ji=class{constructor(e){if(!Z().getBool("IS_BROWSER")||typeof window=="undefined"||typeof window.localStorage=="undefined")throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,e==null||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=Q5(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{let t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),s=yd(e);try{this.LS.setItem(this.keys.info,JSON.stringify(s)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,m9(e.weightData));let r={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:e.signature!=null?e.signature:void 0,userDefinedMetadata:e.userDefinedMetadata!=null?e.userDefinedMetadata:void 0,modelInitializer:e.modelInitializer!=null?e.modelInitializer:void 0,trainingConfig:e.trainingConfig!=null?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(r)),{modelArtifactsInfo:s}}catch(r){throw e3(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${s.modelTopologyBytes}, weightSpecsBytes=${s.weightSpecsBytes}, weightDataBytes=${s.weightDataBytes}.`)}}}async load(){let e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");let t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(n==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;let s=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(s==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=s;let r=this.LS.getItem(this.keys.modelMetadata);if(r!=null){let o=JSON.parse(r);t.format=o.format,t.generatedBy=o.generatedBy,t.convertedBy=o.convertedBy,o.signature!=null&&(t.signature=o.signature),o.userDefinedMetadata!=null&&(t.userDefinedMetadata=o.userDefinedMetadata),o.modelInitializer!=null&&(t.modelInitializer=o.modelInitializer),o.trainingConfig!=null&&(t.trainingConfig=o.trainingConfig)}let a=this.LS.getItem(this.keys.weightData);if(a==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=g9(a),t}};ji.URL_SCHEME="localstorage://";var t3=e=>Z().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ji.URL_SCHEME)?P9(e.slice(ji.URL_SCHEME.length)):null;Ut.registerSaveRouter(t3);Ut.registerLoadRouter(t3);function P9(e){return new ji(e)}var F9=class{constructor(){M(Z().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),M(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=ku+Jr,n=Jr+J5;for(let s=0;s<this.LS.length;++s){let r=this.LS.key(s);if(r.startsWith(t)&&r.endsWith(n)){let a=D9(r);e[a]=JSON.parse(this.LS.getItem(r))}}return e}async removeModel(e){e=_9(e);let t=Q5(e);if(this.LS.getItem(t.info)==null)throw new Error(`Cannot find model at path '${e}'`);let n=JSON.parse(this.LS.getItem(t.info));return e3(t),n}},Iu="://",Ps=class{constructor(){this.managers={}}static getInstance(){return Ps.instance==null&&(Ps.instance=new Ps),Ps.instance}static registerManager(e,t){M(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Iu)&&(e=e.slice(0,e.indexOf(Iu))),M(e.length>0,()=>"scheme must not be an empty string.");let n=Ps.getInstance();M(n.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){let t=this.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(this.getInstance().managers)}};function Zh(e){if(e.indexOf(Iu)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Ps.getSchemes().join(",")}`);return{scheme:e.split(Iu)[0],path:e.split(Iu)[1]}}async function n3(e,t,n=!1){M(e!==t,()=>`Old path and new path are the same: '${e}'`);let s=Ut.getLoadHandlers(e);M(s.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),M(s.length<2,()=>`Copying failed because more than one (${s.length}) load handlers for source URL ${e}.`);let r=s[0],a=Ut.getSaveHandlers(t);M(a.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),M(a.length<2,()=>`Copying failed because more than one (${s.length}) save handlers for destination URL ${t}.`);let o=a[0],i=Zh(e).scheme,l=Zh(e).path,c=i===Zh(e).scheme,u=await r.load();n&&c&&await Ps.getManager(i).removeModel(l);let d=await o.save(u);return n&&!c&&await Ps.getManager(i).removeModel(l),d.modelArtifactsInfo}async function O9(){let e=Ps.getSchemes(),t={};for(let n of e){let s=await Ps.getManager(n).listModels();for(let r in s){let a=n+Iu+r;t[a]=s[r]}}return t}async function M9(e){let t=Zh(e);return Ps.getManager(t.scheme).removeModel(t.path)}async function z9(e,t){return n3(e,t,!1)}async function L9(e,t){return n3(e,t,!0)}var B9=class{fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}};if(Z().get("IS_BROWSER")){Z().setPlatform("browser",new B9);try{Ps.registerManager(ji.URL_SCHEME,new F9)}catch(e){}try{Ps.registerManager(Hi.URL_SCHEME,new T9)}catch(e){}}var W9={importFetch:()=>XT()},N2,V9=class{constructor(){this.util=Ul("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return Z().global.fetch!=null?Z().global.fetch(e,t):(N2==null&&(N2=W9.importFetch()),N2(e,t))}now(){let e=process.hrtime();return e[0]*1e3+e[1]/1e6}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return e.length===0?"":new this.util.TextDecoder(t).decode(e)}};Z().get("IS_NODE")&&Z().setPlatform("node",new V9);function We(e,t="float32",n){return t=t||"float32",a2(e),new tn(e,t,n)}function U9(e,t){let n=_(e,"x","cast");if(!v5(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&n.dtype!=="string"||t!=="string"&&n.dtype==="string")throw new Error("Only strings can be casted to strings");let s={x:n},r={dtype:t};return W.runKernel(Ca,s,r)}var pe=U({cast_:U9});function G9(e){let n={x:_(e,"x","clone","string_or_numeric")};return W.runKernel(Ba,n)}var ir=U({clone_:G9});function s3(e,t=!1){console.log(e.toString(t))}W5();var H9={buffer:We,cast:pe,clone:ir,print:s3};s9(H9);var es={};Le(es,{browserFiles:()=>J9,browserHTTPRequest:()=>sE,concatenateArrayBuffers:()=>k2,copyModel:()=>z9,decodeWeights:()=>j5,encodeWeights:()=>h9,fromMemory:()=>aE,getLoadHandlers:()=>I9,getModelArtifactsForJSON:()=>I2,getModelArtifactsInfoForJSON:()=>yd,getSaveHandlers:()=>k9,http:()=>$2,isHTTPScheme:()=>R2,listModels:()=>O9,loadWeights:()=>Q9,moveModel:()=>L9,registerLoadRouter:()=>w9,registerSaveRouter:()=>v9,removeModel:()=>M9,weightsLoaderFactory:()=>i3,withSaveHandler:()=>oE});var j9="model",q9=".json",X9=".weights.bin";function r3(e){return new Promise(t=>setTimeout(t)).then(e)}var Su=class{constructor(e){if(!Z().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Su.URL_SCHEME)&&(e=e.slice(Su.URL_SCHEME.length)),(e==null||e.length===0)&&(e=j9),this.modelJsonFileName=e+q9,this.weightDataFileName=e+X9}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");let t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{let n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],s=K5(e,n),r=window.URL.createObjectURL(new Blob([JSON.stringify(s)],{type:"application/json"})),a=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(a.download=this.modelJsonFileName,a.href=r,await r3(()=>a.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let o=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;o.download=this.weightDataFileName,o.href=t,await r3(()=>o.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:yd(e)}}}};Su.URL_SCHEME="downloads://";var K9=class{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise((e,t)=>{let n=new FileReader;n.onload=s=>{let r=JSON.parse(s.target.result),a=r.modelTopology;if(a==null){t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));return}if(r.weightsManifest==null){t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));return}if(this.weightsFiles.length===0){e({modelTopology:a});return}let i=I2(r,l=>this.loadWeights(l));e(i)},n.onerror=s=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)})}loadWeights(e){let t=[],n=[];for(let a of e)t.push(...a.weights),n.push(...a.paths);let s=this.checkManifestAndWeightFiles(e),r=n.map(a=>this.loadWeightsFile(a,s[a]));return Promise.all(r).then(a=>[t,k2(a)])}loadWeightsFile(e,t){return new Promise((n,s)=>{let r=new FileReader;r.onload=a=>{let o=a.target.result;n(o)},r.onerror=a=>s(`Failed to weights data from file of path '${e}'.`),r.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){let t=[],n=this.weightsFiles.map(r=>X5(r.name)),s={};for(let r of e)r.paths.forEach(a=>{let o=X5(a);if(t.indexOf(o)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${o}'`);if(t.push(o),n.indexOf(o)===-1)throw new Error(`Weight file with basename '${o}' is not provided.`);s[a]=this.weightsFiles[n.indexOf(o)]});if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return s}},Z9=e=>Z().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Su.URL_SCHEME)?Y9(e.slice(Su.URL_SCHEME.length)):null;Ut.registerSaveRouter(Z9);function Y9(e="model"){return new Su(e)}function J9(e){return new K9(e)}function a3(e,t,n,s){o(e),n=n==null?0:n,s=s==null?1:s,i(n,s);let r=0,a=l=>(l.then(c=>{let u=n+ ++r/e.length*(s-n);return t(u),c}),l);function o(l){M(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function i(l,c){M(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),M(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${c}`),M(c>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${c}`)}return Promise.all(e.map(a))}async function o3(e,t){t==null&&(t={});let n=t.fetchFunc==null?Z().platform.fetch:t.fetchFunc,s=e.map(d=>n(d,t.requestInit,{isBinary:!0})),r=0,a=.5,i=(t.onProgress==null?await Promise.all(s):await a3(s,t.onProgress,r,a)).map(d=>d.arrayBuffer()),l=.5,c=1;return t.onProgress==null?await Promise.all(i):await a3(i,t.onProgress,l,c)}async function Q9(e,t="",n,s){return i3(o=>o3(o,{requestInit:s}))(e,t,n)}function i3(e){return async(t,n="",s)=>{let r=t.map(()=>!1),a={},o=s!=null?s.map(()=>!1):[],i=[];if(t.forEach((h,f)=>{let m=0;h.weights.forEach(g=>{let y="quantization"in g?g.quantization.dtype:g.dtype,A=v2[y]*Ht(g.shape),x=()=>{r[f]=!0,a[f]==null&&(a[f]=[]),a[f].push({manifestEntry:g,groupOffset:m,sizeBytes:A})};s!=null?s.forEach((b,w)=>{b===g.name&&(x(),o[w]=!0)}):x(),i.push(g.name),m+=A})}),!o.every(h=>h)){let h=s.filter((f,m)=>!o[m]);throw new Error(`Could not find weights in manifest with names: ${h.join(", ")}.
|
|
Manifest JSON has weights with names: ${i.join(", ")}.`)}let l=r.reduce((h,f,m)=>(f&&h.push(m),h),[]),c=[];l.forEach(h=>{t[h].paths.forEach(f=>{let m=n+(n.endsWith("/")?"":"/")+f;c.push(m)})});let u=await e(c),d={},p=0;return l.forEach(h=>{let f=t[h].paths.length,m=0;for(let b=0;b<f;b++)m+=u[p+b].byteLength;let g=new ArrayBuffer(m),y=new Uint8Array(g),A=0;for(let b=0;b<f;b++){let w=new Uint8Array(u[p+b]);y.set(w,A),A+=w.byteLength}a[h].forEach(b=>{let w=g.slice(b.groupOffset,b.groupOffset+b.sizeBytes),k=j5(w,[b.manifestEntry]);for(let S in k)d[S]=k[S]}),p+=f}),d}}var eE="application/octet-stream",tE="application/json",E2=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(M(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=Z().platform.fetch,M(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&M(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],s=K5(e,n);t.body.append("model.json",new Blob([JSON.stringify(s)],{type:tE}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:eE}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:yd(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async load(){let e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(r){let a=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?a+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":a+=" Please make sure the server is serving valid JSON for this request.",new Error(a)}let n=t.modelTopology,s=t.weightsManifest;if(n==null&&s==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return I2(t,r=>this.loadWeights(r))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=nE(t),r=this.weightPathPrefix||n,a=[];for(let c of e)a.push(...c.weights);let o=[],i=[];for(let c of e)for(let u of c.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(u)):o.push(r+u+s);this.weightUrlConverter&&o.push(...await Promise.all(i));let l=await o3(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,k2(l)]}};E2.URL_SCHEME_REGEX=/^https?:\/\//;function nE(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),s=e.substring(0,t),r=n>t?e.substring(n):"";return[s+"/",r]}function R2(e){return e.match(E2.URL_SCHEME_REGEX)!=null}var l3=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(s=>R2(s)):n=R2(e),n)return $2(e,t)}return null};Ut.registerSaveRouter(l3);Ut.registerLoadRouter(l3);function $2(e,t){return new E2(e,t)}function sE(e,t){return $2(e,t)}var D2=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},rE=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function aE(e,t,n,s){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new D2(e):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new D2({modelTopology:e})):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new D2({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:s}))}function oE(e){return new rE(e)}var u3={};Le(u3,{confusionMatrix:()=>dE});function iE(e,t,n=!1,s=!1){let r=_(e,"a","matMul"),a=_(t,"b","matMul");[r,a]=zt(r,a);let o={a:r,b:a},i={transposeA:n,transposeB:s};return W.runKernel(Sa,o,i)}var Xe=U({matMul_:iE});function lE(e,t,n=1,s=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let a={indices:_(e,"indices","oneHot","int32")},o={depth:t,onValue:n,offValue:s};return W.runKernel(Ii,a,o)}var Cu=U({oneHot_:lE});function uE(e,t){let n=_(e,"x","transpose");if(t==null&&(t=n.shape.map((a,o)=>o).reverse()),M(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(a=>{M(a>=0&&a<n.rank,()=>`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();let s={x:n},r={perm:t};return W.runKernel(po,s,r)}var et=U({transpose_:uE});function cE(e,t,n){let s=_(e,"labels","confusionMatrix"),r=_(t,"predictions","confusionMatrix");M(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),M(s.rank===1,()=>`Expected the rank of labels to be 1, but got ${s.rank}`),M(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),M(s.shape[0]===r.shape[0],()=>`Mismatch in the number of examples: ${s.shape[0]} vs. ${r.shape[0]}. Labels and predictions should have the same number of elements.`),M(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);let a=Cu(pe(s,"int32"),n),o=Cu(pe(r,"int32"),n),i=et(a),l=Xe(i,o);return pe(l,"int32")}var dE=U({confusionMatrix_:cE}),Xs={};Le(Xs,{fromPixels:()=>AE,fromPixelsAsync:()=>gE,toPixels:()=>yE});function c3(e,t,n){if(ei(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let s=Cr(e,n);if(s.length!==3&&s.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return xo(e,t,s,n)}var Tu;function d3(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(e==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,s=!1,r=!1,a=!1,o=!1,i=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)s=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)r=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)a=!0;else if(e.getContext!=null)o=!0;else if(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)i=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);if(r){let f=2;if(r&&e.readyState<f)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}if(Gh(ad,W.backendName)!=null){let f={pixels:e},m={numChannels:t};return W.runKernel(ad,f,m)}let[c,u]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height],d;o?d=e.getContext("2d").getImageData(0,0,c,u).data:s||n?d=e.data:(a||r||i)&&(Tu==null&&(Tu=document.createElement("canvas").getContext("2d")),Tu.canvas.width=c,Tu.canvas.height=u,Tu.drawImage(e,0,0,c,u),d=Tu.getImageData(0,0,c,u).data);let p;if(t===4)p=new Int32Array(d);else{let f=c*u;p=new Int32Array(f*t);for(let m=0;m<f;m++)for(let g=0;g<t;++g)p[m*t+g]=d[m*4+g]}return c3(p,[u,c,t],"int32")}function pE(e){return e!=null&&e.data instanceof Uint8Array}function hE(){return typeof window!="undefined"&&typeof ImageBitmap!="undefined"&&window.hasOwnProperty("createImageBitmap")}function fE(e){return e!=null&&e.width!==0&&e.height!==0}function mE(e){return hE()&&!(e instanceof ImageBitmap)&&fE(e)&&!pE(e)}async function gE(e,t=3){let n=null;if(Z().getBool("WRAP_TO_IMAGEBITMAP")&&mE(e)){let s;try{s=await createImageBitmap(e,{premultiplyAlpha:"none"})}catch(r){s=null}s!=null&&s.width===e.width&&s.height===e.height?n=s:n=e}else n=e;return d3(n,t)}async function yE(e,t){let n=_(e,"img","toPixels");if(!(e instanceof Ke)){let c=n;n=pe(c,"int32"),c.dispose()}if(n.rank!==2&&n.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${n.rank}.`);let[s,r]=n.shape.slice(0,2),a=n.rank===2?1:n.shape[2];if(a>4||a===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${a}`);if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);let o=await n.data(),i=n.dtype==="float32"?255:1,l=new Uint8ClampedArray(r*s*4);for(let c=0;c<s*r;++c){let u=[0,0,0,255];for(let p=0;p<a;p++){let h=o[c*a+p];if(n.dtype==="float32"){if(h<0||h>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${h}.`)}else if(n.dtype==="int32"&&(h<0||h>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${h}.`);a===1?(u[0]=h*i,u[1]=h*i,u[2]=h*i):u[p]=h*i}let d=c*4;l[d+0]=Math.round(u[0]),l[d+1]=Math.round(u[1]),l[d+2]=Math.round(u[2]),l[d+3]=Math.round(u[3])}if(t!=null){t.width=r,t.height=s;let c=t.getContext("2d"),u=new ImageData(l,r,s);c.putImageData(u,0,0)}return n!==e&&n.dispose(),l}var AE=U({fromPixels_:d3}),_2={};Le(_2,{prepareAndValidate:()=>p3});function p3(e,t){let n=e.shape.length,s=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(s<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${s}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[s-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[s-1]} vs. ${n}`);if(Ht(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let r=t.shape,a=r[r.length-1],o=1;for(let d=0;d<r.length-1;++d)o*=r[d];let i=e.shape,l=r.slice();l.pop();let c=1;for(let d=a;d<n;++d)c*=i[d],l.push(i[d]);let u=[...Hl(e.shape).map(d=>d/c),1].slice(0,a);return[l,o,c,u]}var P2={};Le(P2,{calculateShapes:()=>h3,validateInput:()=>O2,validateUpdateShape:()=>F2});function F2(e,t,n){let s=t.rank>1?t.shape[t.rank-1]:1,r=t.rank>1?t.rank-1:1,a=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${s}, and batchDim: ${r}.`;if(n.rank<r)throw new Error(a+` update.rank < ${r}. `);if(e.length<s+(n.rank-r))throw new Error(a+` Output shape length < ${s+(n.rank-r)}`);if(n.rank!==r+e.length-s)throw new Error(a+` update.rank != ${r+e.length-s}`);for(let o=0;o<r;++o)if(n.shape[o]!==t.shape[o])throw new Error(a+` updates.shape[${o}] (${n.shape[o]}) != indices.shape[${o}] (${t.shape[o]}).`);for(let o=0;o<n.rank-r;++o)if(n.shape[o+r]!==e[o+s])throw new Error(a+` updates.shape[${o+r}] (${n.shape[o+r]}) != shape[${o+r}] (${e[o+r]})`)}function O2(e,t,n){if(t.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if(t.dtype!=="int32")throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);if(n.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${n}`);if(n.length===0){if(t.size===0)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(e.size===0)throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}F2(n,t,e)}function h3(e,t,n){let s=t.shape.length,r=s>1?t.shape[s-1]:1,a=n.length,o=1;for(let d=r;d<a;++d)o*=n[d];let i=r<1?1:r,l=Ht(t.shape)/i,c=[...Hl(n.slice(0,r)),1],u=Ht(n);return{sliceRank:r,numUpdates:l,sliceSize:o,strides:c,outputSize:u}}var yn={};Le(yn,{assertParamsValid:()=>xE,computeFlatOffset:()=>vE,computeOutShape:()=>f3,getNormalizedAxes:()=>A3,isSliceContinous:()=>bE,maskToAxes:()=>Yh,parseSliceParams:()=>I3,sliceInfo:()=>wE,startForAxis:()=>w3,startIndicesWithElidedDims:()=>x3,stopForAxis:()=>k3,stopIndicesWithElidedDims:()=>b3,stridesForAxis:()=>v3,stridesWithElidedDims:()=>m3});function xE(e,t,n){let s=e.shape.length;M(s===t.length,()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`),M(s===n.length,()=>`Error in slice${s}D: Length of size ${n} must match the rank of the array (${s}).`);for(let r=0;r<s;++r)M(t[r]+n[r]<=e.shape[r],()=>`Error in slice${s}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`)}function Yh(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function f3(e,t,n){let s=[];for(let r=0;r<e.length;r++)s[r]=Math.ceil((t[r]-e[r])/n[r]);return s}function m3(e,t,n,s){let r=[...e];for(let a=r.length;a<s.length;a++)r.push(1);for(let a=0;a<n;a++)a===0?r[t]=1:(r.splice(t,0,1),r.pop());return r}function g3(e,t,n){return n<=e?n:n-(t-1)}function y3(e,t){let n=[];for(let s=0;s<e;s++)n.push(t+s);return n}function A3(e,t,n,s,r,a,o,i,l){let c=e.length,u=new Array(c),d=new Array(c),p=new Array(c);if(t.length&&n>0){let h=t[0],f=n+1;u=x3(o,h,f,s,e),d=b3(i,h,f,r,e),p=m3(a,h,f,e)}else for(let h=0;h<c;h++)u[h]=w3(o,s,a,e,h,l),d[h]=k3(i,r,a,e,h,l),p[h]=v3(a,h,l);return{begin:u,end:d,strides:p}}function x3(e,t,n,s,r){let a=[...r],o=y3(n,t);for(let i=0;i<a.length;i++)if(o.indexOf(i)>-1)a[i]=0;else{let l=g3(t,n,i),c=s[l];e&1<<l&&(c=0),a[i]=c}return a}function b3(e,t,n,s,r){let a=[...r],o=y3(n,t);for(let i=0;i<a.length;i++)if(o.indexOf(i)>-1)a[i]=Number.MAX_SAFE_INTEGER;else{let l=g3(t,n,i),c=s[l];e&1<<l&&(c=Number.MAX_SAFE_INTEGER),a[i]=c}for(let i=0;i<a.length;i++){let l=r[i];a[i]<0&&(a[i]+=l),a[i]=Uc(0,a[i],r[i])}return a}function v3(e,t,n){let s=e[t];return(n&1<<t||s==null)&&(s=1),s}function w3(e,t,n,s,r,a){let o=t[r],i=n[r]||1;(e&1<<r||a&1<<r||o==null)&&(i>0?o=Number.MIN_SAFE_INTEGER:o=Number.MAX_SAFE_INTEGER);let l=s[r];return o<0&&(o+=l),o=Uc(0,o,l-1),o}function k3(e,t,n,s,r,a){let o=t[r],i=n[r]||1;(e&1<<r||a&1<<r||o==null)&&(i>0?o=Number.MAX_SAFE_INTEGER:o=Number.MIN_SAFE_INTEGER);let l=s[r];return o<0&&(o+=l),i>0?o=Uc(0,o,l):o=Uc(-1,o,l-1),o}function bE(e,t,n){let s=n.length;for(let r=0;r<n.length;r++)if(n[r]>1){s=r;break}for(let r=s+1;r<n.length;r++)if(t[r]>0||n[r]!==e[r])return!1;return!0}function vE(e,t){let n=e.length>0?e[e.length-1]:1;for(let s=0;s<e.length-1;s++)n+=e[s]*t[s];return n}function I3(e,t,n){let s,r=e.shape.length;typeof t=="number"?s=[t,...new Array(r-1).fill(0)]:t.length<r?s=t.concat(new Array(r-t.length).fill(0)):s=t.slice(),s.forEach(o=>{M(o!==-1,()=>"slice() does not support negative begin indexing.")});let a;return n==null?a=new Array(r).fill(-1):typeof n=="number"?a=[n,...new Array(r-1).fill(-1)]:n.length<r?a=n.concat(new Array(r-n.length).fill(-1)):a=n,a=a.map((o,i)=>o>=0?o:(M(o===-1,()=>`Negative size values should be exactly -1 but got ${o} for the slice() size at index ${i}.`),e.shape[i]-s[i])),[s,a]}function wE(e,t,n,s,r,a,o,i,l){let c=t.slice(),u=n.slice(),d=s;s==null&&(d=new Array(c.length));let p=Yh(o);if(p.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(o!==0&&i!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(o!==0&&l!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let h=e.length-c.length,f=Yh(i),m=e.slice();f.forEach(S=>{c[S]=0,u[S]=1,m.splice(S,0,1)});let{begin:g,end:y,strides:A}=A3(m,p,h,c,u,d,r,a,o);c=g,u=y,d=A;let x=Yh(l);x.forEach(S=>{u[S]=c[S]+1,d[S]=1});let b=f3(c,u,d),w=b.filter((S,N)=>x.indexOf(N)===-1);return{nonStrided:d.every(S=>S===1),$begin:c,$end:u,$strides:d,size:b,newShape:m,outShape:w}}var de={};Le(de,{Serializable:()=>S3,SerializationMap:()=>qi,registerClass:()=>vo});var S3=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},qi=class{constructor(){this.classNameMap={}}static getMap(){return qi.instance==null&&(qi.instance=new qi),qi.instance}static register(e){qi.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function vo(e){M(e.className!=null,()=>"Class being registered does not have the static className property defined."),M(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),M(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),qi.register(e)}var C3={};Le(C3,{TEST_EPSILON_FLOAT16:()=>T3,encodeStrings:()=>N3,expectArrayBuffersEqual:()=>EE,expectArraysClose:()=>IE,expectArraysEqual:()=>CE,expectNumbersClose:()=>TE,expectPromiseToFail:()=>SE,expectValuesInRange:()=>NE,testEpsilon:()=>M2});var kE=.001,T3=.1;function IE(e,t,n){return n==null&&(n=M2()),z2(e,t,(s,r)=>L2(s,r,n))}function M2(){return W.backend.floatPrecision()===32?kE:T3}function z2(e,t,n){let s=!0;if((_n(e)||_n(t))&&(s=!1),_n(e)&&_n(t)&&(s=!0),s){let o=e.constructor.name,i=t.constructor.name;if(o!==i)throw new Error(`Arrays are of different type. Actual: ${o}. Expected: ${i}`)}if(Array.isArray(e)&&Array.isArray(t)){let o=Cr(e),i=Cr(t);if(!jr(o,i))throw new Error(`Arrays have different shapes. Actual: [${o}]. Expected: [${i}]`)}let r=_n(e)?e:ti(e),a=_n(t)?t:ti(t);if(r.length!==a.length)throw new Error(`Arrays have different lengths actual: ${r.length} vs expected: ${a.length}.
|
|
Actual: ${r}.
|
|
Expected: ${a}.`);for(let o=0;o<a.length;++o){let i=r[o],l=a[o];if(!n(i,l))throw new Error(`Arrays differ: actual[${o}] = ${i}, expected[${o}] = ${l}.
|
|
Actual: ${r}.
|
|
Expected: ${a}.`)}}function SE(e,t){e().then(()=>t.fail(),()=>t())}function CE(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return ba(e)||ba(e[0])||ba(t)||ba(t[0])?z2(e,n,(s,r)=>s==r):z2(e,t,(s,r)=>L2(s,r,0))}function TE(e,t,n){if(n==null&&(n=M2()),!L2(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function L2(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function NE(e,t,n){for(let s=0;s<e.length;s++)if(e[s]<t||e[s]>n)throw new Error(`Value out of range:${e[s]} low: ${t}, high: ${n}`)}function EE(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function N3(e){for(let t=0;t<e.length;t++){let n=e[t];Array.isArray(n)?N3(n):e[t]=ud(n)}return e}var Jh="3.9.0";function E3(){Z().set("PROD",!0)}function RE(){Z().set("DEBUG",!0)}function $E(){Z().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function B2(e){Z().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}r9(B2);function DE(){W.disposeVariables()}function ts(){return W}function Qh(){return W.memory()}function _E(e){return W.profile(e)}function j(e,t){return W.tidy(e,t)}function te(e){x2(e).forEach(n=>n.dispose())}function An(e){return W.keep(e)}function PE(e){return W.time(e)}function R3(e){return W.setBackend(e)}function ef(){return W.ready()}function lr(){return W.backendName}function FE(e){W.removeBackend(e)}function W2(e){return W.findBackend(e)}function OE(e){return W.findBackendFactory(e)}function Xi(e,t,n=1){return W.registerBackend(e,t,n)}function Tr(){return W.backend}function ME(e,t){Z().setPlatform(e,t)}function zE(e,t){let n=_(e,"a","add"),s=_(t,"b","add");[n,s]=zt(n,s);let r={a:n,b:s};return W.runKernel(qr,r)}var ue=U({add_:zE});function LE(e,t){let n=_(e,"a","floorDiv"),s=_(t,"b","floorDiv");[n,s]=zt(n,s);let r={a:n,b:s};return W.runKernel(Ma,r)}var tf=U({floorDiv_:LE});function BE(e,t){let n=_(e,"a","div"),s=_(t,"b","div");if([n,s]=zt(n,s),n.dtype==="int32"&&s.dtype==="int32")return tf(n,s);let r={a:n,b:s},a={};return W.runKernel(_a,r,a)}var fe=U({div_:BE});function WE(e,t){let n=_(e,"a","mul"),s=_(t,"b","mul");[n,s]=zt(n,s);let r={a:n,b:s};return W.runKernel(Ka,r)}var L=U({mul_:WE});function VE(e){let t=_(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return W.runKernel(qc,n)}else{let n={x:t};return W.runKernel(ni,n)}}var Kt=U({abs_:VE});function UE(e){let n={x:_(e,"x","acos")};return W.runKernel(ql,n)}var V2=U({acos_:UE});function GE(e){let n={x:_(e,"x","acosh")};return W.runKernel(Xl,n)}var U2=U({acosh_:GE});function HE(e){M(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),M(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((r,a)=>_(r,`tensors${a}`,"addN")),n=t[0];t.forEach(r=>{if(r.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!jr(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let s=t;return W.runKernel(wa,s)}var nf=U({addN_:HE});function jE(e,t=null,n=!1){let r={x:_(e,"x","all","bool")},a={axis:t,keepDims:n};return W.runKernel(Kl,r,a)}var sf=U({all_:jE});function qE(e,t=null,n=!1){let r={x:_(e,"x","any","bool")},a={axis:t,keepDims:n};return W.runKernel(Zl,r,a)}var Ad=U({any_:qE});function XE(e,t=0){let s={x:_(e,"x","argMax")},r={axis:t};return W.runKernel(ka,s,r)}var Fs=U({argMax_:XE});function KE(e,t=0){let s={x:_(e,"x","argMin")},r={axis:t};return W.runKernel(Yl,s,r)}var G2=U({argMin_:KE});function ZE(e){let n={x:_(e,"x","asin")};return W.runKernel(Jl,n)}var H2=U({asin_:ZE});function YE(e){let n={x:_(e,"x","asinh")};return W.runKernel(Ql,n)}var j2=U({asinh_:YE});function JE(e){let n={x:_(e,"x","atan")};return W.runKernel(eu,n)}var q2=U({atan_:JE});function QE(e,t){let n=_(e,"a","atan2"),s=_(t,"b","atan2");[n,s]=zt(n,s);let r={a:n,b:s};return W.runKernel(nu,r)}var X2=U({atan2_:QE});function eR(e){let n={x:_(e,"x","atanh")};return W.runKernel(tu,n)}var K2=U({atanh_:eR});function tR(e,t,n,s,r="NHWC",a){let o=e[3],i=[...t,o],l=_3(r);return xd(e,i,n,a,s,null,null,l)}function $3(e,t,n,s,r,a,o="channelsLast"){let[i,l]=rf(t),c;if(o==="channelsLast")c=[i,l,e[3],e[3]];else if(o==="channelsFirst")c=[i,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return xd(e,c,n,s,r,a,!1,o)}function nR(e,t,n,s,r,a,o="NDHWC"){let[i,l,c]=Y2(t),u,d;if(o==="NDHWC")d="channelsLast",u=[i,l,c,e[4],e[4]];else if(o==="NCDHW")d="channelsFirst",u=[i,l,c,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return D3(e,u,n,s,r,!1,d,a)}function xd(e,t,n,s,r,a,o=!1,i="channelsLast"){let[l,c,u,d]=[-1,-1,-1,-1];if(i==="channelsLast")[l,c,u,d]=e;else if(i==="channelsFirst")[l,d,c,u]=e;else throw new Error(`Unknown dataFormat ${i}`);let[p,h,,f]=t,[m,g]=rf(n),[y,A]=rf(s),x=Nu(p,y),b=Nu(h,A),{padInfo:w,outHeight:k,outWidth:S}=aR(r,c,u,m,g,x,b,a,i),N=o?f*d:f,$;return i==="channelsFirst"?$=[l,N,k,S]:i==="channelsLast"&&($=[l,k,S,N]),{batchSize:l,dataFormat:i,inHeight:c,inWidth:u,inChannels:d,outHeight:k,outWidth:S,outChannels:N,padInfo:w,strideHeight:m,strideWidth:g,filterHeight:p,filterWidth:h,effectiveFilterHeight:x,effectiveFilterWidth:b,dilationHeight:y,dilationWidth:A,inShape:e,outShape:$,filterShape:t}}function D3(e,t,n,s,r,a=!1,o="channelsLast",i){let[l,c,u,d,p]=[-1,-1,-1,-1,-1];if(o==="channelsLast")[l,c,u,d,p]=e;else if(o==="channelsFirst")[l,p,c,u,d]=e;else throw new Error(`Unknown dataFormat ${o}`);let[h,f,m,,g]=t,[y,A,x]=Y2(n),[b,w,k]=Y2(s),S=Nu(h,b),N=Nu(f,w),$=Nu(m,k),{padInfo:F,outDepth:R,outHeight:D,outWidth:T}=oR(r,c,u,d,y,A,x,S,N,$,i),O=a?g*p:g,B;return o==="channelsFirst"?B=[l,O,R,D,T]:o==="channelsLast"&&(B=[l,R,D,T,O]),{batchSize:l,dataFormat:o,inDepth:c,inHeight:u,inWidth:d,inChannels:p,outDepth:R,outHeight:D,outWidth:T,outChannels:O,padInfo:F,strideDepth:y,strideHeight:A,strideWidth:x,filterDepth:h,filterHeight:f,filterWidth:m,effectiveFilterDepth:S,effectiveFilterHeight:N,effectiveFilterWidth:$,dilationDepth:b,dilationHeight:w,dilationWidth:k,inShape:e,outShape:B,filterShape:t}}function sR(e,t,n,s,r){s==null&&(s=Z2(e,t,n));let a=e[0],o=e[1],i=Ki((a-t+2*s)/n+1,r),l=Ki((o-t+2*s)/n+1,r);return[i,l]}function rR(e,t,n,s,r,a){r==null&&(r=Z2(e,t,s));let o=e[0],i=e[1],l=e[2],c=Ki((o-t+2*r)/s+1,a),u=Ki((i-t+2*r)/s+1,a),d=Ki((l-t+2*r)/s+1,a);return[c,u,d,n]}function Z2(e,t,n,s=1){let r=Nu(t,s);return Math.floor((e[0]*(n-1)-n+r)/2)}function rf(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function Y2(e){return typeof e=="number"?[e,e,e]:e}function Nu(e,t){return t<=1?e:e+(e-1)*(t-1)}function aR(e,t,n,s,r,a,o,i,l){let c,u,d;if(typeof e=="number"){c={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let h=sR([t,n],a,s,e,i);u=h[0],d=h[1]}else if(e==="same"){u=Math.ceil(t/s),d=Math.ceil(n/r);let p=Math.max(0,(u-1)*s+a-t),h=Math.max(0,(d-1)*r+o-n),f=Math.floor(p/2),m=p-f,g=Math.floor(h/2),y=h-g;c={top:f,bottom:m,left:g,right:y,type:"SAME"}}else if(e==="valid")c={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((t-a+1)/s),d=Math.ceil((n-o+1)/r);else if(typeof e=="object"){let p=l==="channelsLast"?e[1][0]:e[2][0],h=l==="channelsLast"?e[1][1]:e[2][1],f=l==="channelsLast"?e[2][0]:e[3][0],m=l==="channelsLast"?e[2][1]:e[3][1];c={top:p,bottom:h,left:f,right:m,type:p===0&&h===0&&f===0&&m===0?"VALID":"EXPLICIT"},u=Ki((t-a+p+h)/s+1,i),d=Ki((n-o+f+m)/r+1,i)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:c,outHeight:u,outWidth:d}}function oR(e,t,n,s,r,a,o,i,l,c,u){let d,p,h,f;if(typeof e=="number"){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let g=rR([t,n,s,1],i,1,r,e,u);p=g[0],h=g[1],f=g[2]}else if(e==="same"){p=Math.ceil(t/r),h=Math.ceil(n/a),f=Math.ceil(s/o);let m=(p-1)*r+i-t,g=(h-1)*a+l-n,y=(f-1)*o+c-s,A=Math.floor(m/2),x=m-A,b=Math.floor(g/2),w=g-b,k=Math.floor(y/2),S=y-k;d={top:b,bottom:w,left:k,right:S,front:A,back:x,type:"SAME"}}else if(e==="valid")d={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-i+1)/r),h=Math.ceil((n-l+1)/a),f=Math.ceil((s-c+1)/o);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:d,outDepth:p,outHeight:h,outWidth:f}}function Ki(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function wo(e){let[t,n,s]=rf(e);return t===1&&n===1&&s===1}function Nr(e,t){return wo(e)||wo(t)}function _3(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function iR(e,t){let s={x:_(e,"x","reshape","string_or_numeric")},r={shape:t};return W.runKernel(Ti,s,r)}var G=U({reshape_:iR});function lR(e,t,n,s,r){let a=_(e,"x","avgPool","float32"),o=1;M(Nr(n,o),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);let i=a,l=!1;a.rank===3&&(l=!0,i=G(a,[1,a.shape[0],a.shape[1],a.shape[2]])),M(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),r!=null&&M(mn(s),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r},d=W.runKernel(Ia,c,u);return d=pe(d,a.dtype),l?G(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var bd=U({avgPool_:lR});function uR(e,t,n,s,r,a="NDHWC"){let o=_(e,"x","avgPool3d","float32"),i=o,l=!1;o.rank===4&&(l=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),M(i.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`),M(a==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),r!=null&&M(mn(s),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},d=W.runKernel(Hc,c,u);return d=pe(d,i.dtype),l?G(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var J2=U({avgPool3d_:uR});function cR(e,t=0){M(e.length>=1,()=>"Pass at least one tensor to concat");let n=gd(e,"tensors","concat","string_or_numeric");if(n[0].dtype==="complex64"&&n.forEach(a=>{if(a.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
|
|
with dtype ${a.dtype}. `)}),n.length===1)return ir(n[0]);let s=n,r={axis:t};return W.runKernel(ri,s,r)}var kt=U({concat_:cR});function dR(e){let n={x:_(e,"x","sigmoid")};return W.runKernel(ro,n)}var ns=U({sigmoid_:dR});function pR(e,t,n){let s=_(e,"x","slice","string_or_numeric");if(s.rank===0)throw new Error("Slicing scalar is not possible");let r={x:s},a={begin:t,size:n};return W.runKernel(Di,r,a)}var _e=U({slice_:pR});function hR(e){let n={x:_(e,"x","tanh")};return W.runKernel(co,n)}var Zi=U({tanh_:hR});function fR(e,t,n,s,r,a){let o=_(e,"forgetBias","basicLSTMCell"),i=_(t,"lstmKernel","basicLSTMCell"),l=_(n,"lstmBias","basicLSTMCell"),c=_(s,"data","basicLSTMCell"),u=_(r,"c","basicLSTMCell"),d=_(a,"h","basicLSTMCell"),p=kt([c,d],1),h=Xe(p,i),f=ue(h,l),m=f.shape[0],g=f.shape[1]/4,y=[m,g],A=_e(f,[0,0],y),x=_e(f,[0,g],y),b=_e(f,[0,g*2],y),w=_e(f,[0,g*3],y),k=ue(L(ns(A),Zi(x)),L(u,ns(ue(o,b)))),S=L(Zi(k),ns(w));return[k,S]}var mR=U({basicLSTMCell_:fR});function gR(e,t,n){let s=_(e,"x","batchToSpaceND"),r=t.reduce((i,l)=>i*l);M(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),M(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),M(s.shape[0]%r==0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`);let a={x:s},o={blockShape:t,crops:n};return W.runKernel(si,a,o)}var vd=U({batchToSpaceND_:gR});function yR(e){let t;return e.rank===0||e.rank===1?t=G(e,[1,1,1,e.size]):e.rank===2?t=G(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function AR(e,t,n,s,r,a){a==null&&(a=.001);let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),c;r!=null&&(c=_(r,"scale","batchNorm"));let u;s!=null&&(u=_(s,"offset","batchNorm")),M(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),M(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),M(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let p={x:yR(o),scale:c,offset:u,mean:i,variance:l},h={varianceEpsilon:a},f=W.runKernel(za,p,h);return G(f,o.shape)}var Yi=U({batchNorm_:AR});function xR(e,t,n,s,r,a){let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),c;r!=null&&(c=_(r,"scale","batchNorm"));let u;return s!=null&&(u=_(s,"offset","batchNorm")),M(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),M(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),M(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),c!=null&&M(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),u!=null&&M(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`),Yi(o,i,l,u,c,a)}var P3=U({batchNorm2d_:xR});function bR(e,t,n,s,r,a){let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),c;r!=null&&(c=_(r,"scale","batchNorm"));let u;return s!=null&&(u=_(s,"offset","batchNorm")),M(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),M(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),M(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),c!=null&&M(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`),u!=null&&M(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`),Yi(o,i,l,u,c,a)}var F3=U({batchNorm3d_:bR});function vR(e,t,n,s,r,a){let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),c;r!=null&&(c=_(r,"scale","batchNorm"));let u;return s!=null&&(u=_(s,"offset","batchNorm")),M(o.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),M(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),M(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),c!=null&&M(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`),u!=null&&M(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`),Yi(o,i,l,u,c,a)}var O3=U({batchNorm4d_:vR});function wR(e,t,n){let s=_(e,"x","bincount"),r=_(t,"weights","bincount");M(s.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`),M(n>=0,()=>`size must be non-negative, but got ${n}.`),M(r.size===s.size||r.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${r.shape}.`);let a={x:s,weights:r},o={size:n};return W.runKernel(gh,a,o)}var Q2=U({bincount_:wR});function kR(e,t){let n=_(e,"s0","broadcastArgs","int32"),s=_(t,"s1","broadcastArgs","int32");if(n.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(s.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${s.rank}`);let r={s0:n,s1:s};return W.runKernel(u2,r)}var M3=U({broadcastArgs_:kR});function IR(e,t){let n=_(e,"broadcastTo","x"),s=n.shape;if(t.some(c=>!(c>0)||c%1!=0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){let c=n.shape.slice();for(;c.length<t.length;)c.unshift(1);n=G(n,c)}let r=n.shape,a=Array.from(t);for(let c=t.length-1;c>=0;c--)if(r[c]===t[c])a[c]=1;else if(n.shape[c]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);if(a.map((c,u)=>c>1?u:-1).filter(c=>c>=0).length===0)return ir(n);let i={x:n},l={reps:a};return W.runKernel(Kr,i,l)}var Eu=U({broadcastTo_:IR});function SR(e){let n={x:_(e,"x","ceil")};return W.runKernel(Ta,n)}var e1=U({ceil_:SR});function CR(e,t,n){let s=_(e,"x","clipByValue");M(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);let r={x:s},a={clipValueMin:t,clipValueMax:n};return W.runKernel(Xr,r,a)}var ss=U({clipByValue_:CR});function TR(e){return kt(e,0)}var z3=U({concat1d_:TR});function NR(e,t){return kt(e,t)}var Ru=U({concat2d_:NR});function ER(e,t){return kt(e,t)}var L3=U({concat3d_:ER});function RR(e,t){return kt(e,t)}var B3=U({concat4d_:RR});function $R(e,t,n,s,r="NHWC",a=[1,1],o){let i=_(e,"x","conv2d"),l=_(t,"filter","conv2d"),c=i,u=!1;i.rank===3&&(u=!0,c=G(i,[1,i.shape[0],i.shape[1],i.shape[2]])),M(c.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`),M(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),o!=null&&M(mn(s),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let d=r==="NHWC"?c.shape[3]:c.shape[1];M(d===l.shape[2],()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${l.shape[2]}.`),M(Nr(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let p={x:c,filter:l},h={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},f=W.runKernel(Na,p,h);return u?G(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Qr=U({conv2d_:$R});function DR(e,t,n,s,r="NWC",a=1,o){let i=_(e,"x","conv1d"),l=_(t,"filter","conv1d"),c=i,u=!1;i.rank===2&&(u=!0,c=G(i,[1,i.shape[0],i.shape[1]])),M(c.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`),M(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),o!=null&&M(mn(s),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`),M(c.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`),M(Nr(n,a),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`),M(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);let d=G(l,[1,l.shape[0],l.shape[1],l.shape[2]]),p=G(c,[c.shape[0],1,c.shape[1],c.shape[2]]),g=Qr(p,d,[1,n],s,"NHWC",[1,a],o);return u?G(g,[g.shape[2],g.shape[3]]):G(g,[g.shape[0],g.shape[2],g.shape[3]])}var af=U({conv1d_:DR});function _R(e,t,n,s,r,a="NHWC",o){M(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let i=e,l=t,c=!1;t.rank===3&&(c=!0,l=G(t,[1,t.shape[0],t.shape[1],t.shape[2]]),i=[1,e[0],e[1],e[2]]),M(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),M(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),M(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);let u=a==="NHWC"?i[3]:i[1],d=a==="NHWC"?l.shape[3]:l.shape[1];M(u===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[2]}.`),M(d===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${n.shape[3]}.`),o!=null&&M(mn(r),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let p={dy:l,filter:n},h={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,inputShape:i},f=W.runKernel(Ea,p,h);return c?G(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var t1=U({conv2DBackpropInput_:_R});function PR(e,t,n,s,r,a){let o=_(e,"x","conv2dTranspose"),i=_(t,"filter","conv2dTranspose");return t1(n,o,i,s,r,"NHWC",a)}var of=U({conv2dTranspose_:PR});function FR(e,t,n,s,r="NDHWC",a=[1,1,1]){let o=_(e,"x","conv3d"),i=_(t,"filter","conv3d"),l=o,c=!1;o.rank===4&&(c=!0,l=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),M(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),M(i.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`),M(l.shape[4]===i.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${i.shape[3]}.`),M(Nr(n,a),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),M(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`);let u={x:l,filter:i},d={strides:n,pad:s,dataFormat:r,dilations:a},p=W.runKernel(Xc,u,d);return c?G(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var n1=U({conv3d_:FR});function OR(e,t,n,s,r){M(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let a=e,o=t,i=!1;t.rank===4&&(i=!0,o=G(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),a=[1,e[0],e[1],e[2],e[3]]);let l=a[4],c=o.shape[4];M(a.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`),M(o.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),M(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),M(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),M(c===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[4]}.`);let u={dy:o,filter:n},d={pad:r,strides:s,inputShape:a},p=W.runKernel(xh,u,d);return i?G(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var W3=U({conv3DBackpropInput_:OR});function MR(e,t,n,s,r){let a=_(e,"x","conv3dTranspose"),o=_(t,"filter","conv3dTranspose");return W3(n,a,o,s,r)}var V3=U({conv3dTranspose_:MR});function zR(e){let n={x:_(e,"x","cos")};return W.runKernel(Ra,n)}var wd=U({cos_:zR});function LR(e){let n={x:_(e,"x","cosh")};return W.runKernel($a,n)}var lf=U({cosh_:LR});function BR(e,t=0,n=!1,s=!1){let a={x:_(e,"x","cumsum")},o={axis:t,exclusive:n,reverse:s};return W.runKernel(ai,a,o)}var uf=U({cumsum_:BR});function WR(e,t,n,s=!1){let r=_(e,"x","denseBincount"),a=_(t,"weights","denseBincount");M(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),M(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),M(n>=0,()=>`size must be non-negative, but got ${n}.`),M(a.size===r.size||a.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${a.shape}.`);let o={x:r,weights:a},i={size:n,binaryOutput:s};return W.runKernel(bh,o,i)}var U3=U({denseBincount_:WR});function VR(e,t,n="NHWC"){let s=_(e,"x","depthToSpace"),r=n==="NHWC"?s.shape[1]:s.shape[2],a=n==="NHWC"?s.shape[2]:s.shape[3],o=n==="NHWC"?s.shape[3]:s.shape[1];M(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${r} and ${t} for depthToSpace with input shape
|
|
${s.shape}`),M(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${a} and ${t} for depthToSpace with input shape
|
|
${s.shape}`),M(o%(t*t)==0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${s.shape}`);let i={x:s},l={blockSize:t,dataFormat:n};return W.runKernel(ii,i,l)}var s1=U({depthToSpace_:VR});function UR(e,t,n,s,r="NHWC",a=[1,1],o){let i=_(e,"x","depthwiseConv2d"),l=_(t,"filter","depthwiseConv2d"),c=i,u=!1;i.rank===3&&(u=!0,c=G(i,[1,i.shape[0],i.shape[1],i.shape[2]])),M(c.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),M(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),M(c.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),o!=null&&M(mn(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let d={x:c,filter:l},p={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},h=W.runKernel(Da,d,p);return u?G(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var $u=U({depthwiseConv2d_:UR});function GR(e){let n={x:_(e,"x","diag")};return W.runKernel(kh,n)}var HR=U({diag_:GR});function jR(e,t,n,s,r=[1,1],a="NHWC"){let o=_(e,"x","dilation2d"),i=_(t,"filter","dilation2d");M(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),M(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),M(a==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);let l=o,c=!1;o.rank===3&&(l=G(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=!0);let u={x:l,filter:i},d={strides:n,pad:s,dilations:r},p=W.runKernel(Kc,u,d);return c?G(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var r1=U({dilation2d_:jR});function qR(e,t){let n=e.length,s=[];for(let r=0;r<n;r++){let a=n-1-r,o=e[a]||1;(t[t.length-1-r]||1)>1&&o===1&&s.unshift(a)}return s}function sn(e,t){let n=[];for(let s=0;s<t.length;s++){let r=e[e.length-s-1],a=t.length-s-1,o=t[a];(r==null||r===1&&o>1)&&n.unshift(a)}return n}function Tt(e,t){let n=[],s=Math.max(e.length,t.length);for(let r=0;r<s;r++){let a=e[e.length-r-1];a==null&&(a=1);let o=t[t.length-r-1];if(o==null&&(o=1),a===1)n.unshift(o);else if(o===1)n.unshift(a);else if(a!==o){let i=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(i)}else n.unshift(a)}return n}function XR(e,t){let n=_(e,"a","equal","string_or_numeric"),s=_(t,"b","equal","string_or_numeric");[n,s]=zt(n,s),Tt(n.shape,s.shape);let r={a:n,b:s};return W.runKernel(li,r)}var ys=U({equal_:XR});function KR(e,t,n){let s=_(t,"a","where"),r=_(n,"b","where"),a=_(e,"condition","where","bool"),o=Tt(Tt(a.shape,s.shape),r.shape),i=Eu(a,o),l=Eu(s,o),c=Eu(r,o),u={condition:i,t:l,e:c};return W.runKernel($i,u)}var Pn=U({where_:KR});function ZR(e){let n={x:_(e,"x","zerosLike")};return W.runKernel(Bi,n)}var tt=U({zerosLike_:ZR});function YR(e,t){let n=_(e,"a","div"),s=_(t,"b","div");[n,s]=zt(n,s);let r=fe(n,s),a=tt(r),o=ys(s,a);return Pn(o,a,r)}var a1=U({divNoNan_:YR});function JR(e,t){let n=_(e,"t1","dot"),s=_(t,"t2","dot");M((n.rank===1||n.rank===2)&&(s.rank===1||s.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${s.rank}.`);let r=n.rank===1?n.size:n.shape[1],a=s.rank===1?s.size:s.shape[0];if(M(r===a,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${a}.`),n.rank===1&&s.rank===1){let o=G(n,[1,-1]),i=G(s,[-1,1]),l=Xe(o,i);return G(l,[])}else if(n.rank===1&&s.rank===2){let o=G(n,[1,-1]),i=G(s,[s.shape[0],s.shape[1]]),l=Xe(o,i);return G(l,[l.size])}else if(n.rank===2&&s.rank===1){let o=G(s,[-1,1]),i=Xe(n,o);return G(i,[i.size])}else{let o=G(s,[s.shape[0],s.shape[1]]);return Xe(n,o)}}var G3=U({dot_:JR});function QR(e,...t){let n=t.map((r,a)=>_(r,`tensors${a}`,"einsum")),s={equation:e};return W.runKernel(Zc,n,s)}var H3=U({einsum_:QR});function e$(e){let n={x:_(e,"x","elu")};return W.runKernel(Pa,n)}var Du=U({elu_:e$});function t$(e){let t=_(e,"x","erf");M(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=pe(t,"float32"));let n={x:t};return W.runKernel(su,n)}var o1=U({erf_:t$});function n$(e){let n={x:_(e,"x","exp")};return W.runKernel(Fa,n)}var As=U({exp_:n$});function s$(e,t=0){let n=_(e,"x","expandDims","string_or_numeric");M(t<=n.rank,()=>"Axis must be <= rank of the tensor");let s={input:n},r={dim:t};return W.runKernel(ui,s,r)}var jt=U({expandDims_:s$});function r$(e){let n={x:_(e,"x","expm1")};return W.runKernel(ci,n)}var i1=U({expm1_:r$});function a$(e,t){let n=_(e,"x","tile","string_or_numeric");M(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);let s={x:n},r={reps:t};return W.runKernel(Kr,s,r)}var Os=U({tile_:a$});function o$(e,t,n,s="float32"){t==null&&(t=e);let r=We([e,t],s),a=e<=t?e:t;for(let i=0;i<a;++i)r.set(1,i,i);let o=G(r.toTensor(),[e,t]);if(n==null)return o;if(n.length===1)return Os(jt(o,0),[n[0],1,1]);if(n.length===2)return Os(jt(jt(o,0),0),[n[0],n[1],1,1]);if(n.length===3)return Os(jt(jt(jt(o,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`)}var l1=U({eye_:o$});function _u(e,t,n){let s={shape:e,value:t,dtype:n};return W.runKernel(ru,{},s)}function i$(e){let n={x:_(e,"x","floor")};return W.runKernel(Oa,n)}var Pu=U({floor_:i$});function l$(e,t,n=0,s=0){let r=_(e,"x","gather"),a=_(t,"indices","gather","int32"),o={x:r,indices:a},i={axis:n,batchDims:s};return W.runKernel(pi,o,i)}var Ji=U({gather_:l$});function u$(e,t){let n=_(e,"a","greater","string_or_numeric"),s=_(t,"b","greater","string_or_numeric");[n,s]=zt(n,s),Tt(n.shape,s.shape);let r={a:n,b:s};return W.runKernel(fi,r)}var rs=U({greater_:u$});function c$(e,t){let n=_(e,"a","greaterEqual","string_or_numeric"),s=_(t,"b","greaterEqual","string_or_numeric");[n,s]=zt(n,s),Tt(n.shape,s.shape);let r={a:n,b:s};return W.runKernel(La,r)}var ko=U({greaterEqual_:c$});function d$(e){let n={input:_(e,"input","imag")};return W.runKernel(Yc,n)}var cf=U({imag_:d$});function p$(e){let n={x:_(e,"x","isFinite")};return W.runKernel(au,n)}var j3=U({isFinite_:p$});function h$(e){let n={x:_(e,"x","isInf")};return W.runKernel(ou,n)}var q3=U({isInf_:h$});function f$(e){let n={x:_(e,"x","isNaN")};return W.runKernel(iu,n)}var u1=U({isNaN_:f$});function m$(e,t=.2){let s={x:_(e,"x","leakyRelu")},r={alpha:t};return W.runKernel(mi,s,r)}var kd=U({leakyRelu_:m$});function g$(e,t){let n=_(e,"a","less","string_or_numeric"),s=_(t,"b","less","string_or_numeric");[n,s]=zt(n,s),Tt(n.shape,s.shape);let r={a:n,b:s};return W.runKernel(gi,r)}var df=U({less_:g$});function y$(e,t){let n=_(e,"a","lessEqual","string_or_numeric"),s=_(t,"b","lessEqual","string_or_numeric");[n,s]=zt(n,s),Tt(n.shape,s.shape);let r={a:n,b:s};return W.runKernel(yi,r)}var Io=U({lessEqual_:y$});function X3(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");let s={start:e,stop:t,num:n};return W.runKernel(Eh,{},s)}function A$(e,t=5,n=1,s=1,r=.5){let a=_(e,"x","localResponseNormalization");M(a.rank===4||a.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
rank ${a.rank}.`),M(mn(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=a,i=!1;a.rank===3&&(i=!0,o=G(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let l={x:o},c={depthRadius:t,bias:n,alpha:s,beta:r},u=W.runKernel(Qc,l,c);return i?G(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var c1=U({localResponseNormalization_:A$});function x$(e){let n={x:_(e,"x","log")};return W.runKernel(Wa,n)}var xs=U({log_:x$});function b$(e){let n={x:_(e,"x","log1p")};return W.runKernel(lu,n)}var Id=U({log1p_:b$});function v$(e){return M(va(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let s=_(t,"x","tf.grad","string_or_numeric"),r=n!=null?_(n,"dy","tf.grad"):null;return W.tidy(()=>{let{value:a,grads:o}=W.gradients(()=>e(s),[s],r);return r!=null&&Mn(a.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),pf(o),o[0]})}}function w$(e){return M(va(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{M(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let s=gd(t,"args","tf.grads","string_or_numeric"),r=n!=null?_(n,"dy","tf.grads"):null;return W.tidy(()=>{let{value:a,grads:o}=W.gradients(()=>e(...s),s,r);return r!=null&&Mn(a.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),pf(o),o})}}function k$(e){return M(va(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{M(t instanceof Ke,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),M(n==null||n instanceof Ke,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:s,value:r}=W.gradients(()=>e(t),[t],n);return pf(s),{grad:s[0],value:r}}}function I$(e){return M(va(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{M(Array.isArray(t)&&t.every(r=>r instanceof Ke),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),M(n==null||n instanceof Ke,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let s=W.gradients(()=>e(...t),t,n);return n!=null&&Mn(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),pf(s.grads),s}}function K3(e,t){M(va(e),()=>"The f passed in variableGrads(f) must be a function"),M(t==null||Array.isArray(t)&&t.every(c=>c instanceof hd),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let c in W.registeredVariables)t.push(W.registeredVariables[c])}let s=n?t.filter(c=>!c.trainable):null,r=t.length;t=t.filter(c=>c.trainable),M(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);let a=!0,{value:o,grads:i}=W.gradients(e,t,null,a);M(i.some(c=>c!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),M(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);let l={};return t.forEach((c,u)=>{i[u]!=null&&(l[c.name]=i[u])}),s!=null&&s.forEach(c=>l[c.name]=null),{value:o,grads:l}}function Er(e){return W.customGrad(e)}function pf(e){if(e.filter(n=>n==null).length>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
|
|
the f you passed encloses all operations that lead from x to y.`)}function S$(e){let n={x:_(e,"x","neg")};return W.runKernel(xi,n)}var _t=U({neg_:S$});function C$(e){let n={x:_(e,"x","softplus")};return W.runKernel(yu,n)}var Qi=U({softplus_:C$});function T$(e){let t=_(e,"x","logSigmoid");return Er(s=>({value:_t(Qi(_t(s))),gradFunc:o=>L(o,ns(_t(s)))}))(t)}var Z3=U({logSigmoid_:T$});function N$(e,t=null,n=!1){let r={x:_(e,"x","max")},a={reductionIndices:t,keepDims:n};return W.runKernel(Va,r,a)}var Bn=U({max_:N$});function E$(e,t){let n=_(e,"a","sub"),s=_(t,"b","sub");[n,s]=zt(n,s);let r={a:n,b:s};return W.runKernel(uo,r)}var xe=U({sub_:E$});function R$(e,t=null,n=!1){let s=_(e,"x","sum");s.dtype==="bool"&&(s=pe(s,"int32"));let r={x:s},a={axis:t,keepDims:n};return W.runKernel(oo,r,a)}var ke=U({sum_:R$});function $$(e,t=-1){let n=_(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return Er((r,a)=>{let o=!0,i=Bn(r,t,!0),l=xe(r,i),c=xe(pe(l,"float32"),xs(ke(As(l),t,o)));return a([c]),{value:c,gradFunc:(d,p)=>{let[h]=p,f=!0,m=As(h);return xe(d,L(ke(d,t,f),m))}}})(n)}var hf=U({logSoftmax_:$$});function d1(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function Y3(e,t,n){let s=e.length+t.length,r=[],a=0,o=0;for(let i=0;i<s;i++)n.indexOf(i)===-1?r.push(e[a++]):r.push(t[o++]);return r}function J3(e,t){let n=[],s=e.length;for(let a=0;a<s;a++)t.indexOf(a)===-1&&n.push(e[a]);let r=t.map(a=>e[a]);return[n,r]}function el(e,t){let n=t.map(s=>1);return Y3(e,n,t)}function D$(e,t,n){M(d1(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function Q3(e,t){if(d1(e,t))return null;let n=[];for(let s=0;s<t;++s)e.indexOf(s)===-1&&n.push(s);return e.forEach(s=>n.push(s)),n}function p1(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function _$(e,t){let n=[];for(let s=t-e;s<t;++s)n.push(s);return n}function P$(e,t=null,n=!1){let s=_(e,"x","logSumExp"),r=qs(t,s.shape),a=Bn(s,r,!0),o=xe(s,a),i=As(o),l=ke(i,r),c=xs(l),u=ue(G(a,c.shape),c);if(n){let d=el(u.shape,r);return G(u,d)}return u}var h1=U({logSumExp_:P$});function F$(e,t){let n=_(e,"a","logicalAnd","bool"),s=_(t,"b","logicalAnd","bool");Tt(n.shape,s.shape);let r={a:n,b:s};return W.runKernel(Ai,r)}var Ks=U({logicalAnd_:F$});function O$(e){let n={x:_(e,"x","logicalNot","bool")};return W.runKernel(uu,n)}var Sd=U({logicalNot_:O$});function M$(e,t){let n=_(e,"a","logicalOr","bool"),s=_(t,"b","logicalOr","bool");Tt(n.shape,s.shape);let r={a:n,b:s};return W.runKernel(Jc,r)}var ff=U({logicalOr_:M$});function z$(e,t){let n=_(e,"a","logicalXor","bool"),s=_(t,"b","logicalXor","bool");return Tt(n.shape,s.shape),Ks(ff(e,t),Sd(Ks(e,t)))}var ev=U({logicalXor_:z$});function L$(e,t,n,s,r){let a=_(e,"x","maxPool"),o=1,i=a,l=!1;a.rank===3&&(l=!0,i=G(a,[1,a.shape[0],a.shape[1],a.shape[2]])),M(i.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),M(Nr(n,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),r!=null&&M(mn(s),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r},d=W.runKernel(Ga,c,u);return l?G(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Cd=U({maxPool_:L$});function B$(e,t=[1,1,1],n,s,r,a="NDHWC"){let o=_(e,"x","maxPool3d"),i=o,l=!1;o.rank===4&&(l=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),M(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),M(a==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),r!=null&&M(mn(s),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},d=W.runKernel(ed,c,u);return l?G(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var f1=U({maxPool3d_:B$});function W$(e,t,n,s,r=!1){let o={x:_(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:s,includeBatchInIndex:r},l=W.runKernel(_h,o,i);return{result:l[0],indexes:l[1]}}var tv=U({maxPoolWithArgmax_:W$});function V$(e,t){let n=_(e,"a","maximum"),s=_(t,"b","maximum");[n,s]=zt(n,s),n.dtype==="bool"&&(n=pe(n,"int32"),s=pe(s,"int32")),Tt(n.shape,s.shape);let r={a:n,b:s};return W.runKernel(Ua,r)}var Rr=U({maximum_:V$});function U$(e,t=null,n=!1){let r={x:_(e,"x","mean")},a={axis:t,keepDims:n};return W.runKernel(Ha,r,a)}var Lt=U({mean_:U$});function qt(e,t="float32"){if(t==="complex64"){let s=qt(e,"float32"),r=qt(e,"float32");return Ao(s,r)}let n=hh(Ht(e),t);return W.makeTensor(n,e,t)}function bs(e,t="float32"){if(t==="complex64"){let s=bs(e,"float32"),r=qt(e,"float32");return Ao(s,r)}let n=r2(Ht(e),t);return W.makeTensor(n,e,t)}function G$(e,t,{indexing:n="xy"}={}){if(n!=="xy"&&n!=="ij")throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(e===void 0)return[];let s=_(e,"x","meshgrid",e instanceof Ke?e.dtype:"float32");if(t===void 0)return[s];let r=_(t,"y","meshgrid",t instanceof Ke?t.dtype:"float32"),a=Ht(s.shape),o=Ht(r.shape);return n==="xy"?(s=G(s,[1,-1]),r=G(r,[-1,1]),[Xe(bs([o,1],s.dtype),s),Xe(r,bs([1,a],r.dtype))]):(s=G(s,[-1,1]),r=G(r,[1,-1]),[Xe(s,bs([1,o],s.dtype)),Xe(bs([a,1],r.dtype),r)])}function H$(e,t=null,n=!1){let r={x:_(e,"x","min")},a={axis:t,keepDims:n};return W.runKernel(ja,r,a)}var Td=U({min_:H$});function j$(e,t){let n=_(e,"a","minimum"),s=_(t,"b","minimum");[n,s]=zt(n,s),n.dtype==="bool"&&(n=pe(n,"int32"),s=pe(s,"int32")),Tt(n.shape,s.shape);let r={a:n,b:s};return W.runKernel(qa,r)}var Fu=U({minimum_:j$});function q$(e,t,n){M(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let s=_(e,"x","mirrorPad");if(s.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");M(t.length===s.rank,()=>`Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`);let r=n==="reflect"?1:0;for(let i=0;i<s.rank;i++)M(t[i].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),M(t[i][0]>=0&&t[i][0]<=s.shape[i]-r&&t[i][1]>=0&&t[i][1]<=s.shape[i]-r,()=>`Padding in dimension ${i} cannot be greater than or equal to ${s.shape[i]-r} or less than 0 for input of shape ${s.shape}`);let a={paddings:t,mode:n},o={x:s};return W.runKernel(Xa,o,a)}var m1=U({mirrorPad_:q$});function X$(e,t){let n=_(e,"a","mod"),s=_(t,"b","mod");[n,s]=zt(n,s);let r={a:n,b:s};return W.runKernel(cu,r)}var g1=U({mod_:X$});function K$(e){let t=_(e,"x","square"),n={};return W.runKernel("Square",{x:t},n)}var vt=U({square_:K$});function Z$(e,t=null,n=!1){e=_(e,"x","moments");let s=qs(t,e.shape),r=Lt(e,s,n),a=r.shape;n||(a=el(r.shape,s));let o=vt(xe(pe(e,"float32"),G(r,a))),i=Lt(o,s,n);return{mean:r,variance:i}}var mf=U({moments_:Z$});function Y$(e,t,n,s){let r=_(t,"data","multiRNNCell"),a=gd(n,"c","multiRNNCell"),o=gd(s,"h","multiRNNCell"),i=r,l=[];for(let d=0;d<e.length;d++){let p=e[d](i,a[d],o[d]);l.push(p[0]),l.push(p[1]),i=p[1]}let c=[],u=[];for(let d=0;d<l.length;d+=2)c.push(l[d]),u.push(l[d+1]);return[c,u]}var J$=U({multiRNNCell_:Y$});function Q$(e,t,n,s=!1){let r=_(e,"logits","multinomial"),a=r.size,o=r.rank;if(a<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${a}.`);if(o>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);n=n||Math.random();let l={logits:o===1?G(r,[1,-1]):r},c={numSamples:t,seed:n,normalized:s},u=W.runKernel(Ph,l,c);return o===1?G(u,[u.size]):u}var nv=U({multinomial_:Q$});function eD(e,t){let n=_(e,"a","notEqual","string_or_numeric"),s=_(t,"b","notEqual","string_or_numeric");[n,s]=zt(n,s),Tt(n.shape,s.shape);let r={a:n,b:s};return W.runKernel(bi,r)}var tl=U({notEqual_:eD});function tD(e){let n={x:_(e,"x","onesLike")};return W.runKernel(ki,n)}var vs=U({onesLike_:tD});function nD(e,t){let n=_(e,"v1","outerProduct"),s=_(t,"v2","outerProduct");M(n.rank===1&&s.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${s.rank}.`);let r=G(n,[-1,1]),a=G(s,[1,-1]);return Xe(r,a)}var sD=U({outerProduct_:nD});function rD(e,t,n=0){let s=_(e,"x","pad");if(s.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let r={paddings:t,constantValue:n},a={x:s};return W.runKernel(Za,a,r)}var ur=U({pad_:rD});function aD(e,t,n=0){return M(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),ur(e,[t],n)}var oD=U({pad1d_:aD});function iD(e,t,n=0){return M(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),ur(e,t,n)}var lD=U({pad2d_:iD});function uD(e,t,n=0){return M(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),ur(e,t,n)}var cD=U({pad3d_:uD});function dD(e,t,n=0){return M(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),ur(e,t,n)}var pD=U({pad4d_:dD});function hD(e,t,n){let s=_(e,"x","spaceToBatchND");M(s.rank>=1+t.length,()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`),M(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),M(s.shape.reduce((o,i,l)=>l>0&&l<=t.length?o&&(i+n[l-1][0]+n[l-1][1])%t[l-1]==0:o,!0),()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);let r={x:s},a={blockShape:t,paddings:n};return W.runKernel(Pi,r,a)}var Nd=U({spaceToBatchND_:hD});function fD(e,t,n,s,r,a){r==null&&(r=[1,1]),a==null&&(a=1),s===0&&(s="valid");let o=_(e,"x","maxPool"),i=o,l=!1;o.rank===3&&(l=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2]])),M(Nr(a,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${r}'`);let c=$3(i.shape,t,a,r,s),u=[c.dilationHeight,c.dilationWidth],d;s==="same"?d=gD([c.filterHeight,c.filterWidth],u):d=[[0,0],[0,0]];let p=u[0]===1&&u[1]===1,[h,f]=mD([c.inHeight,c.inWidth],u,d),m=p?s:"valid",g=p?i:Nd(i,u,h),A=(n==="avg"?()=>bd(g,t,a,m):()=>Cd(g,t,a,m))(),x=p?A:vd(A,u,f);return l?G(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function mD(e,t,n){let s=n.map(u=>u[0]),r=n.map(u=>u[1]),a=e.concat(s,r),o=t.map((u,d)=>(u-a[d]%u)%u),i=r.map((u,d)=>u+o[d]),l=t.map((u,d)=>[s[d],i[d]]),c=t.map((u,d)=>[0,o[d]]);return[l,c]}function gD(e,t){let s=e.map((o,i)=>o+(o-1)*(t[i]-1)).map(o=>o-1),r=s.map(o=>Math.floor(o/2)),a=s.map((o,i)=>o-r[i]);return s.map((o,i)=>[r[i],a[i]])}var sv=U({pool_:fD});function yD(e,t){let n=_(e,"base","pow"),s=_(t,"exp","pow");[n,s]=zt(n,s);let r={a:n,b:s};return W.runKernel(Ya,r)}var ea=U({pow_:yD});function AD(e,t){let n=_(e,"x","prelu"),s=_(t,"alpha","prelu"),r={x:n,alpha:s};return W.runKernel(Ja,r)}var Ed=U({prelu_:AD});function xD(e,t=null,n=!1){let s=_(e,"x","prod");s.dtype==="bool"&&(s=pe(s,"int32"));let r={x:s},a={axis:t,keepDims:n};return W.runKernel(Ci,r,a)}var gf=U({prod_:xD});function bD(e,t,n){let s=Ht(e),r=null;if(n==null||n==="float32")r=new Float32Array(s);else if(n==="int32")r=new Int32Array(s);else if(n==="bool")r=new Uint8Array(s);else throw new Error(`Unknown data type ${n}`);for(let a=0;a<s;a++)r[a]=t();return W.makeTensor(r,e,n)}var vD=U({rand_:bD}),y1=Qo(h5()),A1=class{constructor(e,t,n,s,r){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=s,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);let a=r||Math.random();this.random=y1.alea(a.toString())}nextValue(){if(!isNaN(this.nextVal)){let s=this.nextVal;return this.nextVal=NaN,s}let e,t,n=!1;for(;!n;){let s,r,a;do s=2*this.random()-1,r=2*this.random()-1,a=s*s+r*r;while(a>=1||a===0);let o=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*s*o,t=this.mean+this.stdDev*r*o,(!this.truncated||this.isValidTruncated(e))&&(n=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}},wD=class{constructor(e,t,n,s){this.alpha=e,this.beta=1/t,this.dtype=n;let r=s||Math.random();this.randu=y1.alea(r.toString()),this.randn=new A1(0,1,n,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,s,r,a;for(;;){do s=this.randn.nextValue(),a=1+this.c*s;while(a<=0);if(a*=a*a,e=s*s,t=1-.331*e*e,n=.5*e+this.d*(1-a+Math.log(a)),r=this.randu(),r<t||Math.log(r)<n)break}return a=1/this.beta*this.d*a,this.alpha<1&&(a*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(a)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}},kD=class{constructor(e=0,t=1,n,s){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,s==null&&(s=Math.random()),typeof s=="number"&&(s=s.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=y1.alea(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function ID(e,t,n=1,s="float32",r){if(n==null&&(n=1),s==null&&(s="float32"),s!=="float32"&&s!=="int32")throw new Error(`Unsupported data type ${s}`);let a=new wD(t,n,s,r),o=We(e,s);for(let i=0;i<o.values.length;i++)o.values[i]=a.nextValue();return o.toTensor()}var SD=U({randomGamma_:ID});function CD(e,t=0,n=1,s,r){if(s!=null&&s==="bool")throw new Error(`Unsupported data type ${s}`);let a=new A1(t,n,s,!1,r),o=We(e,s);for(let i=0;i<o.values.length;i++)o.values[i]=a.nextValue();return o.toTensor()}var rv=U({randomNormal_:CD});function TD(e,t=0,n=1,s="float32",r){let a=We(e,s),o=new kD(t,n,null,r);for(let i=0;i<a.values.length;i++)a.values[i]=o.nextValue();return a.toTensor()}var Ou=U({randomUniform_:TD});function Mu(e,t,n=1,s="float32"){if(n===0)throw new Error("Cannot have a step of zero");let r={start:e,stop:t,step:n,dtype:s};return W.runKernel(pu,{},r)}function ND(e){let n={input:_(e,"input","real")};return W.runKernel(td,n)}var Rd=U({real_:ND});function ED(e){let n={x:_(e,"x","reciprocal")};return W.runKernel(hu,n)}var x1=U({reciprocal_:ED});function RD(e){let n={x:_(e,"x","relu")};return W.runKernel(Qa,n)}var cr=U({relu_:RD});function $D(e){let n={x:_(e,"x","relu6")};return W.runKernel(to,n)}var yf=U({relu6_:$D});function DD(e,t){let s={x:_(e,"x","reverse")},r={dims:t};return W.runKernel(Ni,s,r)}var ws=U({reverse_:DD});function _D(e){let t=_(e,"x","reverse");return M(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),ws(t,0)}var PD=U({reverse1d_:_D});function FD(e,t){let n=_(e,"x","reverse");return M(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),ws(n,t)}var OD=U({reverse2d_:FD});function MD(e,t){let n=_(e,"x","reverse");return M(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),ws(n,t)}var zD=U({reverse3d_:MD});function LD(e,t){let n=_(e,"x","reverse");return M(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),ws(n,t)}var BD=U({reverse4d_:LD});function WD(e){let n={x:_(e,"x","round")};return W.runKernel(Ei,n)}var Af=U({round_:WD});function VD(e){let n={x:_(e,"x","rsqrt")};return W.runKernel(no,n)}var xf=U({rsqrt_:VD});function Ee(e,t){if((_n(e)&&t!=="string"||Array.isArray(e))&&t!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(t==="string"&&_n(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return xo(e,[],[],t)}function UD(e){let n={x:_(e,"x","selu")};return W.runKernel(mu,n)}var bf=U({selu_:UD});function GD(e,t,n,s,r,a=[1,1],o="NHWC"){let i=_(e,"x","separableConv2d"),l=_(t,"depthwiseFilter","separableConv2d"),c=_(n,"pointwiseFilter","separableConv2d"),u=i,d=!1;if(i.rank===3&&(d=!0,u=G(i,[1,i.shape[0],i.shape[1],i.shape[2]])),o==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");M(u.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`),M(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),M(c.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),M(c.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`),M(c.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`);let p=l.shape[2],h=l.shape[3];M(c.shape[2]===p*h,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*h}, but got ${c.shape[2]}.`);let f=$u(u,l,s,r,o,a),g=Qr(f,c,1,"valid",o);return d?G(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var b1=U({separableConv2d_:GD});async function HD(e,t){let n=_(e,"x","setdiff1d"),s=_(t,"y","setdiff1d");M(n.dtype===s.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`),M(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),M(s.rank===1,()=>`y should be 1D tensor, but got y (${s.shape}).`);let r=await n.data(),a=await s.data(),o=new Set(a),i=0;for(let u=0;u<r.length;u++)o.has(r[u])||i++;let l=new tn([i],n.dtype),c=new tn([i],"int32");for(let u=0,d=0;u<r.length;u++)o.has(r[u])||(l.values[d]=r[u],c.values[d]=u,d++);return[l.toTensor(),c.toTensor()]}var av=HD;function jD(e){let n={x:_(e,"x","sign")};return W.runKernel(gu,n)}var v1=U({sign_:jD});function qD(e){let n={x:_(e,"x","sin")};return W.runKernel(so,n)}var vf=U({sin_:qD});function XD(e){let n={x:_(e,"x","sinh")};return W.runKernel(_i,n)}var wf=U({sinh_:XD});function KD(e,t,n){let s=_(e,"x","slice1d");return M(s.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),_e(s,[t],[n])}var kf=U({slice1d_:KD});function ZD(e,t,n){let s=_(e,"x","slice2d");return M(s.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),_e(s,t,n)}var w1=U({slice2d_:ZD});function YD(e,t,n){let s=_(e,"x","slice3d");return M(s.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),_e(s,t,n)}var zu=U({slice3d_:YD});function JD(e,t,n){let s=_(e,"x","slice4d");return M(s.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),_e(s,t,n)}var $d=U({slice4d_:JD});function QD(e,t=-1){let n=_(e,"logits","softmax","float32");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);let s={logits:n},r={dim:t};return W.runKernel(io,s,r)}var nl=U({softmax_:QD});function e_(e){M(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return W.runKernel(Th,t)}var Dd=U({fft_:e_});function t_(e){M(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return W.runKernel(Nh,t)}var Lu=U({ifft_:t_});function n_(e){let t=e.shape[e.shape.length-1],n=e.size/t,s;if(t<=2){let r=G(e,[n,t]);s=Lu(r)}else{let r=[n,2*(t-1)],a=G(Rd(e),[n,t]),o=G(cf(e),[n,t]),i=ws(_e(a,[0,1],[n,t-2]),1),l=L(ws(_e(o,[0,1],[n,t-2]),1),Ee(-1)),c=kt([a,i],1),u=kt([o,l],1),d=G(Ao(c,u),[r[0],r[1]]);s=Lu(d)}if(s=Rd(s),e.rank===3&&e.shape[0]!==0){let r=s,a=e.shape[0];s=G(s,[a,s.shape[0]/a,s.shape[1]]),r.dispose()}return s}var If=U({irfft_:n_});function s_(e,t,n=0){let r={x:_(e,"x","split")},a={numOrSizeSplits:t,axis:n};return W.runKernel(Fi,r,a)}var xn=U({split_:s_});function r_(e,t){M(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1],s=e.size/n,r;if(t!=null&&t<n){let f=e.shape.map(g=>0),m=e.shape.map(g=>g);m[e.shape.length-1]=t,r=_e(e,f,m),n=t}else if(t!=null&&t>n){let f=e.shape.map(m=>m);f[e.shape.length-1]=t-n,r=kt([e,qt(f)],e.shape.length-1),n=t}else r=e;let a=tt(r),o=G(Ao(r,a),[s,n]),i=Dd(o),l=Math.floor(n/2)+1,c=Rd(i),u=cf(i),d=xn(c,[l,n-l],c.shape.length-1),p=xn(u,[l,n-l],u.shape.length-1),h=r.shape.slice();return h[r.shape.length-1]=l,G(Ao(d[0],p[0]),h)}var _d=U({rfft_:r_});function a_(e){let n={x:_(e,"x","sqrt")};return W.runKernel(ao,n)}var Cn=U({sqrt_:a_});function o_(e,t){let n=_(e,"a","squaredDifference"),s=_(t,"b","squaredDifference");[n,s]=zt(n,s),Tt(n.shape,s.shape);let r={a:n,b:s},a={};return W.runKernel(lo,r,a)}var Sf=U({squaredDifference_:o_});function i_(e,t){let n=_(e,"x","squeeze");return G(n,y5(n.shape,t).newShape)}var dt=U({squeeze_:i_});function l_(e,t=0){let n=gd(e,"tensors","stack","string_or_numeric");M(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&M(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let s=n,r={axis:t};return W.runKernel(Si,s,r)}var Tn=U({stack_:l_});function u_(e,t=0){let s={x:_(e,"x","step")},r={alpha:t};return W.runKernel(ho,s,r)}var Bu=U({step_:u_});function c_(e,t,n,s,r=0,a=0,o=0,i=0,l=0){let u={x:_(e,"x","stridedSlice","string_or_numeric")},d={begin:t,end:n,strides:s,beginMask:r,endMask:a,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:l};return W.runKernel(Oi,u,d)}var k1=U({stridedSlice_:c_});function d_(e){let n={x:_(e,"x","tan")};return W.runKernel(Mi,n)}var I1=U({tan_:d_});function Zt(e,t){ei(e);let n=Cr(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return xo(e,null,n,t)}function dr(e,t,n){if(ei(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let s=Cr(e,n);if(s.length!==2&&s.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return xo(e,t,s,n)}function p_(e,t,n){if(ei(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let s=Cr(e,n);if(s.length!==4&&s.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return xo(e,t,s,n)}function h_(e,t,n){if(ei(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let s=Cr(e,n);if(s.length!==5&&s.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return xo(e,t,s,n)}function f_(e,t,n){if(ei(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let s=Cr(e,n);if(s.length!==6&&s.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||s,xo(e,t,s,n)}function m_(e,t=1,n=!0){let s=_(e,"x","topk");if(s.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let r=s.shape[s.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);let a={x:s},o={k:t,sorted:n},[i,l]=W.runKernel(xu,a,o);return{values:i,indices:l}}var S1=U({topk_:m_});function g_(e,t=0,n=1,s,r){if(s!=null&&s==="bool")throw new Error("Unsupported data type $ { dtype }");let a=new A1(t,n,s,!0,r),o=We(e,s);for(let i=0;i<o.values.length;i++)o.values[i]=a.nextValue();return o.toTensor()}var Cf=U({truncatedNormal_:g_});function y_(e,t=0){let n=_(e,"x","unique","string_or_numeric");M(n.rank>0,()=>"The input tensor must be at least 1D");let s={x:n},r={axis:t},[a,o]=W.runKernel(Uh,s,r);return{values:a,indices:o}}var Tf=U({unique_:y_});function A_(e,t,n){let s=_(e,"x","unsortedSegmentSum"),r=_(t,"segmentIds","unsortedSegmentSum","int32");M(mn(n),()=>"numSegments must be of dtype int");let a={x:s,segmentIds:r},o={numSegments:n};return W.runKernel(rd,a,o)}var C1=U({unsortedSegmentSum_:A_});function x_(e,t=0){let n=_(e,"x","unstack","string_or_numeric");M(t>=-n.shape.length&&t<n.shape.length,()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);let s={value:n},r={axis:t};return W.runKernel(Li,s,r)}var Wn=U({unstack_:x_});function ov(e,t=!0,n,s){return W.makeVariable(e,t,n,s)}function iv(e,t){let n=[];for(let a=0;a<t.length;a++)t[a]&&n.push(a);let s=We(e,"int32"),r=We([n.length,e.length],"int32");for(let a=0;a<n.length;a++){let o=s.indexToLoc(n[a]),i=a*e.length;r.values.set(o,i)}return r.toTensor()}async function b_(e){let t=_(e,"condition","whereAsync","bool"),n=await t.data(),s=iv(t.shape,n);return e!==t&&t.dispose(),s}var T1=b_;async function v_(e,t,n){let s=_(e,"tensor","boolMask"),r=_(t,"mask","boolMask","bool"),a=n==null?0:n,o=r.rank,i=s.shape;M(o>0,()=>"mask cannot be scalar"),Mn(i.slice(a,a+o),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let m=a;m<a+o;m++)l*=i[m];let c=i.slice(0,a).concat([l],i.slice(a+o)),u=G(s,c),d=G(r,[-1]),p=await T1(d),h=dt(p,[1]),f=Ji(u,h,a);return e!==s&&s.dispose(),t!==r&&r.dispose(),h.dispose(),u.dispose(),d.dispose(),p.dispose(),f}var w_=v_;function k_(e,t="euclidean",n=null,s=!1){e=_(e,"x","norm");let r=lv(e,t,n),a=r.shape;if(s){let o=qs(n,e.shape);a=el(r.shape,o)}return G(r,a)}function lv(e,t,n=null){if(e.rank===0)return Kt(e);if(e.rank!==1&&n===null)return lv(G(e,[-1]),t,n);if(e.rank===1||typeof n=="number"||Array.isArray(n)&&n.length===1){if(t===1)return ke(Kt(e),n);if(t===1/0)return Bn(Kt(e),n);if(t===-1/0)return Td(Kt(e),n);if(t==="euclidean"||t===2)return Cn(ke(ea(Kt(e),Ee(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&n.length===2){if(t===1)return Bn(ke(Kt(e),n[0]),n[1]-1);if(t===1/0)return Bn(ke(Kt(e),n[1]),n[0]);if(t===-1/0)return Td(ke(Kt(e),n[1]),n[0]);if(t==="fro"||t==="euclidean")return Cn(ke(vt(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}var Nf=U({norm_:k_});function I_(e,t,n,s,r=!0){let a=_(e,"v","movingAverage"),o=_(t,"x","movingAverage"),i=_(n,"decay","movingAverage");z5(a,o),M(jr(a.shape,o.shape),()=>"Shape mismatch in v and x");let l=Ee(1),c=xe(l,i),u=L(xe(o,a),c);if(r){M(s!=null,()=>"When using zeroDebias: true, step is required.");let d=_(s,"step","movingAverage");u=fe(u,xe(l,ea(i,d)))}return ue(a,u)}var S_=U({movingAverage_:I_});function C_(e,t,n){let s=_(e,"indices","scatterND","int32"),r=_(t,"updates","scatterND");O2(r,s,n);let a={indices:s,updates:r},o={shape:n};return W.runKernel(Ri,a,o)}var uv=U({scatterND_:C_});function T_(e,t,n,s){if(e.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);let r=e.rank>0?e.shape[0]:1,a=e.rank>1?e.shape[1]:1;if(n.length!==a)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${a}.`);let o=t.size;if(!(t.rank===0||t.rank===1&&o===r))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${r}]`);if(t.dtype!==s.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function N_(e,t,n,s=0){let r=_(e,"sparseIndices","sparseToDense","int32"),a=_(t,"sparseValues","sparseToDense"),o=_(s,"defaultValue","sparseToDense",a.dtype);T_(r,a,n,o);let i={sparseIndices:r,sparseValues:a,defaultValue:o},l={outputShape:n};return W.runKernel(nd,i,l)}var N1=U({sparseToDense_:N_});function E_(e,t){let n=_(t,"indices","gatherND","int32"),r={params:_(e,"x","gatherND","string_or_numeric"),indices:n};return W.runKernel(hi,r)}var cv=U({gatherND_:E_});function R_(e,t){if(t==null)return e.shape.slice();if(jr(e.shape,t))return t;if(e.shape.length===t.length){let n=[];for(let s=0;s<e.shape.length;s++)t[s]==null&&e.shape[s]!=null?n.push(e.shape[s]):n.push(t[s]);return n}return t}function $_(e,t,n,s){let r=_(e,"x","dropout");if(M(r.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`),M(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof Ke?r.clone():r;let a=R_(r,n),o=1-t,i=fe(Pu(ue(Ou(a,0,1,"float32",s),o)),o);return L(r,i)}var dv=U({dropout_:$_});function pv(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function E1(e,t,n){let s=1-e%2,r=new Float32Array(e);for(let a=0;a<e;++a){let o=2*Math.PI*a/(e+s-1);r[a]=t-n*Math.cos(o)}return Zt(r,"float32")}async function D_(e,t,n=1){let s=_(e,"predictions","inTopK"),r=_(t,"targets","inTopK");M(s.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${s.rank}`),M(s.rank-1===r.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${s.rank} and targets rank ${r.rank}`),Mn(s.shape.slice(0,s.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let a=s.shape[s.shape.length-1];M(n>0&&n<=a,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`);let o=await s.data(),i=await r.data(),[l,c]=[o.length/a,a],u=A5("bool",l);for(let d=0;d<l;d++){let p=d*c,h=o.subarray(p,p+c),f=[];for(let m=0;m<h.length;m++)f.push({value:h[m],index:m});f.sort((m,g)=>g.value-m.value),u[d]=0;for(let m=0;m<n;m++)if(f[m].index===i[d]){u[d]=1;break}}return e!==s&&s.dispose(),t!==r&&r.dispose(),nn(u,r.shape,"bool")}var __=D_,So={};Le(So,{conv2d:()=>O_,depthwiseConv2d:()=>B_,matMul:()=>V_});function P_(e,t,n,s,r,a="NHWC",o){let i=e;e.rank===3&&(i=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=G(t,[1,t.shape[0],t.shape[1],t.shape[2]])),M(i.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),M(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),M(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);let c=a==="NHWC"?i.shape[3]:i.shape[1],u=a==="NHWC"?l.shape[3]:l.shape[1];M(c===n[2],()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${n[2]}.`),M(u===n[3],()=>`Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${n[3]}).`),o!=null&&M(mn(r),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let d={x:i,dy:l},p={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,filterShape:n};return W.runKernel(yh,d,p)}var R1=U({conv2DBackpropFilter_:P_});function Ef(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return L(e,Bu(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Rf(e,t){let n=t,s=sn(e.shape,t.shape);return s.length>0&&(n=ke(n,s)),G(n,e.shape)}function $f(e,t,n,s){if(t==="linear")return e;if(t==="relu")return cr(e);if(t==="elu")return Du(e);if(t==="relu6")return yf(e);if(t==="prelu")return Ed(e,n);if(t==="leakyrelu")return kd(e,s);if(t==="sigmoid")return ns(e);throw new Error(`Unknown fused activation ${t}.`)}var Df=(e,t)=>!(e>0)||t==="linear";function F_({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(l=l||"linear",Df(W.state.gradientDepth,l)===!1){let w=Qr(e,t,n,s,r,a,o);return i!=null&&(w=ue(w,i)),$f(w,l,c,u)}let d=_(e,"x","conv2d"),p=_(t,"filter","conv2d"),h=d,f=!1;d.rank===3&&(f=!0,h=G(d,[1,d.shape[0],d.shape[1],d.shape[2]])),M(h.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`),M(p.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`),o!=null&&M(mn(s),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`),M(h.shape[3]===p.shape[2],()=>`Error in conv2d: depth of input (${h.shape[3]}) must match input depth for filter ${p.shape[2]}.`),M(Nr(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),M(r==="NHWC",()=>`Error in conv2d: got dataFormat of ${r} but only NHWC is currently supported.`);let m=xd(h.shape,p.shape,n,a,s,o),g;i!=null&&(g=_(i,"bias","fused conv2d"),[g]=zt(g,d),Tt(m.outShape,g.shape));let y;c!=null&&(y=_(c,"prelu weights","fused conv2d"));let A=(w,k)=>{let[S,N,$,F]=k,R=Ef(w,$,l);M(wo(a),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);let D=t1(N.shape,R,S,n,s),T=R1(N,R,S.shape,n,s),O=[D,T];if(F!=null){let B=Rf(F,R);O.push(B)}return O},x={x:h,filter:p,bias:g,preluActivationWeights:y},b={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:u};return i==null?Er((k,S,N)=>{let $=W.runKernel(mo,x,b);return N([S,k,$]),f&&($=G($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:A}})(h,p):Er((k,S,N,$)=>{let F=W.runKernel(mo,x,b);return $([S,k,F,N]),f&&(F=G(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:A}})(h,p,g)}var O_=U({fusedConv2d_:F_});function M_(e,t,n,s,r,a=[1,1],o){let i=e;e.rank===3&&(i=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=G(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let c={x:i,dy:l},u={strides:s,pad:r,dimRoundingMode:o,dilations:a,filterShape:n};return W.runKernel(vh,c,u)}var hv=U({depthwiseConv2dNativeBackpropFilter_:M_});function z_(e,t,n,s,r,a=[1,1],o){let i=t,l=!1;t.rank===3&&(l=!0,i=G(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let c={dy:i,filter:n},u={strides:s,pad:r,dimRoundingMode:o,dilations:a,inputShape:e},d=W.runKernel(wh,c,u);return l?G(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var fv=U({depthwiseConv2dNativeBackpropInput_:z_});function L_({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(Df(W.state.gradientDepth,l)===!1){let w=$u(e,t,n,s,r,a,o);return i!=null&&(w=ue(w,i)),$f(w,l,c,u)}let d=_(e,"x","depthwiseConv2d"),p=_(t,"filter","depthwiseConv2d"),h=d,f=!1;d.rank===3&&(f=!0,h=G(d,[1,d.shape[0],d.shape[1],d.shape[2]])),M(h.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`),M(p.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`),M(h.shape[3]===p.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),a==null&&(a=[1,1]),M(Nr(n,a),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o!=null&&M(mn(s),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${o} but got pad ${s}.`);let m=xd(h.shape,p.shape,n,a,s,o,!0),g;i!=null&&(g=_(i,"bias","fused conv2d"),[g]=zt(g,d),Tt(m.outShape,g.shape));let y;c!=null&&(y=_(c,"prelu weights","fused depthwiseConv2d"));let A=(w,k)=>{M(wo(a),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);let[S,N,$,F]=k,R=Ef(w,$,l),D=fv(N.shape,R,S,n,s,a,o),T=hv(N,R,S.shape,n,s,a,o);if(F!=null){let O=Rf(g,R);return[D,T,O]}return[D,T]},x={x:h,filter:p,bias:g,preluActivationWeights:y},b={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:u};return i==null?Er((k,S,N)=>{let $=W.runKernel(go,x,b);return N([S,k,$]),f&&($=G($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:A}})(h,p):Er((k,S,N,$)=>{let F=W.runKernel(go,x,b);return $([S,k,F,N]),f&&(F=G(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:A}})(h,p,g)}var B_=U({fusedDepthwiseConv2d_:L_});function W_({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:r,activation:a="linear",preluActivationWeights:o,leakyreluAlpha:i}){if(Df(W.state.gradientDepth,a)===!1){let F=Xe(e,t,n,s);return r!=null&&(F=ue(F,r)),$f(F,a,o,i)}let l=_(e,"a","fused matMul"),c=_(t,"b","fused matMul");[l,c]=zt(l,c);let u=n?l.shape[l.rank-2]:l.shape[l.rank-1],d=s?c.shape[c.rank-1]:c.shape[c.rank-2],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],h=s?c.shape[c.rank-2]:c.shape[c.rank-1],f=l.shape.slice(0,-2),m=c.shape.slice(0,-2),g=Ht(f),y=Ht(m);M(l.rank>=2&&c.rank>=2&&l.rank===c.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${l.rank} and ${c.rank}.`),M(jr(f,m),()=>`Error in fused matMul: outer dimensions (${f}) and (${m}) of Tensors with shapes ${l.shape} and ${c.shape} must match.`),M(u===d,()=>`Error in fused matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${l.shape} and ${c.shape} and transposeA=${n} and transposeB=${s} must match.`);let A=l.shape.slice(0,-2).concat([p,h]),x=n?G(l,[g,u,p]):G(l,[g,p,u]),b=s?G(c,[y,h,d]):G(c,[y,d,h]),w;r!=null&&(w=_(r,"bias","fused matMul"),[w]=zt(w,l),Tt(A,w.shape));let k;o!=null&&(k=_(o,"prelu weights","fused matMul"));let S=(F,R)=>{let[D,T,O,B]=R,H=Ef(G(F,O.shape),O,a),z,X;if(!n&&!s?(z=Xe(H,T,!1,!0),X=Xe(D,H,!0,!1)):!n&&s?(z=Xe(H,T,!1,!1),X=Xe(H,D,!0,!1)):n&&!s?(z=Xe(T,H,!1,!0),X=Xe(D,H,!1,!1)):(z=Xe(T,H,!0,!0),X=Xe(H,D,!0,!0)),r!=null){let ee=Rf(B,H);return[z,X,ee]}else return[z,X]},N={a:x,b,bias:w,preluActivationWeights:k},$={transposeA:n,transposeB:s,activation:a,leakyreluAlpha:i};return r==null?Er((R,D,T)=>{let O=W.runKernel(fo,N,$);return T([R,D,O]),{value:G(O,A),gradFunc:S}})(x,b):Er((R,D,T,O)=>{let B=W.runKernel(fo,N,$);return O([R,D,B,T]),{value:G(B,A),gradFunc:S}})(x,b,w)}var V_=U({fusedMatMul_:W_});function U_(e){return E1(e,.54,.46)}var G_=U({hammingWindow_:U_});function H_(e){return E1(e,.5,.5)}var mv=U({hannWindow_:H_});function j_(e,t,n,s=!1,r=0){let a=0,o=[];for(;a+t<=e.size;)o.push(_e(e,a,t)),a+=n;if(s)for(;a<e.size;){let i=a+t-e.size,l=kt([_e(e,a,t-i),_u([i],r)]);o.push(l),a+=n}return o.length===0?dr([],[0,t]):G(kt(o),[o.length,t])}var gv=U({frame_:j_});function q_(e,t,n,s,r=mv){s==null&&(s=pv(t));let a=gv(e,t,n),o=L(a,r(t));return _d(o,s)}var X_=U({stft_:q_});function K_(e,t,n,s,r="bilinear",a=0){let o=_(e,"image","cropAndResize"),i=_(t,"boxes","cropAndResize","float32"),l=_(n,"boxInd","cropAndResize","int32"),c=i.shape[0];M(o.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),M(i.rank===2&&i.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${i.shape}.`),M(l.rank===1&&l.shape[0]===c,()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${i.shape}.`),M(s.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),M(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),M(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);let u={image:o,boxes:i,boxInd:l},d={method:r,extrapolationValue:a,cropSize:s};return W.runKernel(oi,u,d)}var Z_=U({cropAndResize_:K_});function Y_(e){let t=_(e,"image","flipLeftRight","float32");M(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return W.runKernel(di,n,{})}var J_=U({flipLeftRight_:Y_});function Q_(e){let t=_(e,"image","grayscaleToRGB"),n=t.rank-1,s=t.shape[n];M(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),M(s===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${s}.`);let r=new Array(t.rank);return r.fill(1,0,n),r[n]=3,Os(t,r)}var eP=U({grayscaleToRGB_:Q_});function tP(e,t,n=0,s=.5){let r=_(e,"image","rotateWithOffset","float32");M(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);let a={image:r},o={radians:t,fillValue:n,center:s};return W.runKernel(Wi,a,o)}var nP=U({rotateWithOffset_:tP});function Wu(e,t,n,s,r,a){s==null&&(s=.5),r==null&&(r=Number.NEGATIVE_INFINITY),a==null&&(a=0);let o=e.shape[0];return n=Math.min(n,o),M(0<=s&&s<=1,()=>`iouThreshold must be in [0, 1], but was '${s}'`),M(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),M(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),M(t.rank===1,()=>"scores must be a 1D tensor"),M(t.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`),M(0<=a&&a<=1,()=>`softNmsSigma must be in [0, 1], but was '${a}'`),{maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a}}function sP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=_(e,"boxes","nonMaxSuppression"),o=_(t,"scores","nonMaxSuppression"),i=Wu(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l={maxOutputSize:n,iouThreshold:s,scoreThreshold:r};return W.runKernel(vi,{boxes:a,scores:o},l)}var rP=U({nonMaxSuppression_:sP});function aP(e,t,n){let s=oP(e,t,n),r=s<0?-(s+1):s;e.splice(r,0,t)}function oP(e,t,n){return lP(e,t,n||iP)}function iP(e,t){return e>t?1:e<t?-1:0}function lP(e,t,n){let s=0,r=e.length,a=0,o=!1;for(;s<r;){a=s+(r-s>>>1);let i=n(t,e[a]);i>0?s=a+1:(r=a,o=!i)}return o?s:-s-1}function yv(e,t,n,s,r){return $1(e,t,n,s,r,0)}function Av(e,t,n,s,r,a){return $1(e,t,n,s,r,0,!1,a,!0)}function xv(e,t,n,s,r,a){return $1(e,t,n,s,r,a,!0)}function $1(e,t,n,s,r,a,o=!1,i=!1,l=!1){let c=[];for(let g=0;g<t.length;g++)t[g]>r&&c.push({score:t[g],boxIndex:g,suppressBeginIndex:0});c.sort(bv);let u=a>0?-.5/a:0,d=[],p=[];for(;d.length<n&&c.length>0;){let g=c.pop(),{score:y,boxIndex:A,suppressBeginIndex:x}=g;if(y<r)break;let b=!1;for(let w=d.length-1;w>=x;--w){let k=uP(e,A,d[w]);if(k>=s){b=!0;break}if(g.score=g.score*cP(s,u,k),g.score<=r)break}g.suppressBeginIndex=d.length,b||(g.score===y?(d.push(A),p.push(g.score)):g.score>r&&aP(c,g,bv))}let h=d.length,f=n-h;i&&f>0&&(d.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));let m={selectedIndices:d};return o&&(m.selectedScores=p),l&&(m.validOutputs=h),m}function uP(e,t,n){let s=e.subarray(t*4,t*4+4),r=e.subarray(n*4,n*4+4),a=Math.min(s[0],s[2]),o=Math.min(s[1],s[3]),i=Math.max(s[0],s[2]),l=Math.max(s[1],s[3]),c=Math.min(r[0],r[2]),u=Math.min(r[1],r[3]),d=Math.max(r[0],r[2]),p=Math.max(r[1],r[3]),h=(i-a)*(l-o),f=(d-c)*(p-u);if(h<=0||f<=0)return 0;let m=Math.max(a,c),g=Math.max(o,u),y=Math.min(i,d),A=Math.min(l,p),x=Math.max(y-m,0)*Math.max(A-g,0);return x/(h+f-x)}function cP(e,t,n){let s=Math.exp(t*n*n);return n<=e?s:0}function bv(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function dP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=_(e,"boxes","nonMaxSuppressionAsync"),o=_(t,"scores","nonMaxSuppressionAsync"),i=Wu(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l=await Promise.all([a.data(),o.data()]),c=l[0],u=l[1],{selectedIndices:d}=yv(c,u,n,s,r);return a!==e&&a.dispose(),o!==t&&o.dispose(),Zt(d,"int32")}var pP=dP;function hP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=_(e,"boxes","nonMaxSuppression"),i=_(t,"scores","nonMaxSuppression"),l=Wu(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let c={boxes:o,scores:i},u={maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a},d=W.runKernel(wi,c,u);return{selectedIndices:d[0],selectedScores:d[1]}}var fP=U({nonMaxSuppressionWithScore_:hP});async function mP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=_(e,"boxes","nonMaxSuppressionAsync"),i=_(t,"scores","nonMaxSuppressionAsync"),l=Wu(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let c=await Promise.all([o.data(),i.data()]),u=c[0],d=c[1],{selectedIndices:p,selectedScores:h}=xv(u,d,n,s,r,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Zt(p,"int32"),selectedScores:Zt(h)}}var gP=mP;function yP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=_(e,"boxes","nonMaxSuppression"),i=_(t,"scores","nonMaxSuppression"),l=Wu(o,i,n,s,r,null),c=l.maxOutputSize,u=l.iouThreshold,d=l.scoreThreshold,p={boxes:o,scores:i},h={maxOutputSize:c,iouThreshold:u,scoreThreshold:d,padToMaxOutputSize:a},f=W.runKernel(du,p,h);return{selectedIndices:f[0],validOutputs:f[1]}}var AP=U({nonMaxSuppressionPadded_:yP});async function xP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=_(e,"boxes","nonMaxSuppressionAsync"),i=_(t,"scores","nonMaxSuppressionAsync"),l=Wu(o,i,n,s,r,null),c=l.maxOutputSize,u=l.iouThreshold,d=l.scoreThreshold,[p,h]=await Promise.all([o.data(),i.data()]),{selectedIndices:f,validOutputs:m}=Av(p,h,c,u,d,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Zt(f,"int32"),validOutputs:Ee(m,"int32")}}var bP=xP;function vP(e,t,n=!1,s=!1){let r=_(e,"images","resizeBilinear");M(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),M(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),M(s===!1||n===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let a=r,o=!1;r.rank===3&&(o=!0,a=G(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},c=W.runKernel(eo,i,l);return o?G(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var vv=U({resizeBilinear_:vP});function wP(e,t,n=!1,s=!1){let r=_(e,"images","resizeNearestNeighbor");M(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),M(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),M(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),M(s===!1||n===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let a=r,o=!1;r.rank===3&&(o=!0,a=G(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},c=W.runKernel(fu,i,l);return o?G(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var wv=U({resizeNearestNeighbor_:wP});function kP(e,t="binary",n=!1,s=.5){let r=_(e,"image","threshold"),a=.2989,o=.587,i=.114,l=r.shape[0]*r.shape[1],c=L(Zt([s]),255),u,d,p,h;if(M(r.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`),M(r.shape[2]===3||r.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`),M(r.dtype==="int32"||r.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`),M(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),r.shape[2]===3){[u,d,p]=xn(r,[1,1,1],-1);let g=L(u,a),y=L(d,o),A=L(p,i);h=ue(ue(g,y),A)}else h=e;if(t==="otsu"){let g=Q2(pe(Af(h),"int32"),nn([]),256);c=IP(g,l)}let f=n?Io(h,c):rs(h,c);return pe(L(f,255),"int32")}function IP(e,t){let n=Zt([-1]),s=Zt([0]),r=Zt([0]),a,o,i,l,c,u;for(let d=0;d<e.size-1;d++){a=_e(e,0,d+1),o=_e(e,d+1),c=fe(ke(a),t),u=fe(ke(o),t);let p=ke(L(a,Mu(0,a.size)));i=fe(p,ke(a));let h=_u(o.shape,a.size),f=ue(Mu(0,o.size),h),m=L(o,f);l=fe(ke(m),ke(o));let g=xe(i,l),y=xe(i,l),A=L(c,u);r=L(L(A,g),y);let x=rs(r,s);s=Pn(x,r,s),n=Pn(x,Zt([d]),n)}return n}var SP=U({threshold_:kP});function CP(e,t,n="nearest",s="constant",r=0,a){let o=_(e,"image","transform","float32"),i=_(t,"transforms","transform","float32");M(o.rank===4,()=>`Error in transform: image must be rank 4,but got rank ${o.rank}.`),M(i.rank===2&&(i.shape[0]===o.shape[0]||i.shape[0]===1)&&i.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),M(a==null||a.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`);let l={image:o,transforms:i},c={interpolation:n,fillMode:s,fillValue:r,outputShape:a};return W.runKernel(zi,l,c)}var TP=U({transform_:CP});function NP(e,t,n){M(t%1==0,()=>`bandPart(): numLower must be an integer, got ${t}.`),M(n%1==0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);let s=_(e,"a","bandPart");M(s.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`);let r=s.shape,[a,o]=s.shape.slice(-2);if(!(t<=a))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`);if(!(n<=o))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`);t<0&&(t=a),n<0&&(n=o);let i=G(Mu(0,a,1,"int32"),[-1,1]),l=Mu(0,o,1,"int32"),c=xe(i,l),u=Ks(Io(c,Ee(+t,"int32")),ko(c,Ee(-n,"int32"))),d=qt([a,o],s.dtype);return G(Tn(Wn(G(s,[-1,a,o])).map(p=>Pn(u,p,d))),r)}var EP=U({bandPart_:NP});function RP(e){let t;if(Array.isArray(e)){t=!1,M(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let r=e[0].shape[0];for(let a=1;a<e.length;++a)M(e[a].shape[0]===r,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[a].shape[0]} vs. ${r})`)}else t=!0,e=xn(e,e.shape[0],0).map(r=>dt(r,[0]));M(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let n=[],s=e;for(let r=0;r<e.length;++r)n.push(W.tidy(()=>{let a=s[r];if(r>0)for(let o=0;o<r;++o){let i=L(ke(L(n[o],a)),n[o]);a=xe(a,i)}return fe(a,Nf(a,"euclidean"))}));return t?Tn(n,0):n}var $P=U({gramSchmidt_:RP});function DP(e,t=!1){if(M(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return kv(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,c)=>l*c),s=Wn(G(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],a=[];s.forEach(l=>{let[c,u]=kv(l,t);r.push(c),a.push(u)});let o=G(Tn(r,0),e.shape),i=G(Tn(a,0),e.shape);return[o,i]}}function kv(e,t=!1){return W.tidy(()=>{M(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let n=e.shape[0],s=e.shape[1],r=l1(n),a=ir(e),o=dr([[1]],[1,1]),i=ir(o),l=n>=s?s:n;for(let c=0;c<l;++c){let u=a,d=i,p=r;[i,a,r]=W.tidy(()=>{let h=_e(a,[c,c],[n-c,1]),f=Nf(h),m=_e(a,[c,c],[1,1]),g=Pn(rs(m,0),dr([[-1]]),dr([[1]])),y=xe(m,L(g,f)),A=fe(h,y);A.shape[0]===1?i=ir(o):i=kt([o,_e(A,[1,0],[A.shape[0]-1,A.shape[1]])],0);let x=_t(fe(Xe(g,y),f)),b=_e(a,[c,0],[n-c,s]),w=L(x,i),k=et(i);if(c===0)a=xe(b,Xe(w,Xe(k,b)));else{let $=xe(b,Xe(w,Xe(k,b)));a=kt([_e(a,[0,0],[c,s]),$],0)}let S=et(w),N=_e(r,[0,c],[n,r.shape[1]-c]);if(c===0)r=xe(N,Xe(Xe(N,i),S));else{let $=xe(N,Xe(Xe(N,i),S));r=kt([_e(r,[0,0],[n,c]),$],1)}return[i,a,r]}),te([u,d,p])}return!t&&n>s&&(r=_e(r,[0,0],[n,s]),a=_e(a,[0,0],[s,s])),[r,a]})}var _P=U({qr_:DP}),Vn;(function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(Vn||(Vn={}));function PP(e,t,n=Vn.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=_(t,"weights","computeWeightedLoss"));let a=r==null?s:L(s,r);if(n===Vn.NONE)return a;if(n===Vn.SUM)return ke(a);if(n===Vn.MEAN){if(r==null)return Lt(a);{let o=s.size/r.size,i=fe(ke(a),ke(r));return o>1?fe(i,Ee(o)):i}}if(n===Vn.SUM_BY_NONZERO_WEIGHTS){if(r==null)return fe(ke(a),Ee(s.size));{let o=L(r,bs(s.shape)),i=pe(ke(tl(o,Ee(0))),"float32");return fe(ke(a),i)}}throw Error(`Unknown reduction: ${n}`)}var ta=U({computeWeightedLoss_:PP});function FP(e,t,n,s=Vn.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","absoluteDifference"),a=_(t,"predictions","absoluteDifference"),o=null;n!=null&&(o=_(n,"weights","absoluteDifference")),Mn(r.shape,a.shape,"Error in absoluteDifference: ");let i=Kt(xe(r,a));return ta(i,o,s)}var OP=U({absoluteDifference_:FP});function MP(e,t,n,s,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"labels","cosineDistance"),o=_(t,"predictions","cosineDistance"),i=null;s!=null&&(i=_(s,"weights","cosineDistance")),Mn(a.shape,o.shape,"Error in cosineDistance: ");let l=Ee(1),c=xe(l,ke(L(a,o),n,!0));return ta(c,i,r)}var zP=U({cosineDistance_:MP});function LP(e,t,n,s=Vn.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","hingeLoss"),a=_(t,"predictions","hingeLoss"),o=null;n!=null&&(o=_(n,"weights","hingeLoss")),Mn(r.shape,a.shape,"Error in hingeLoss: ");let i=Ee(1);r=xe(L(Ee(2),r),i);let l=cr(xe(i,L(r,a)));return ta(l,o,s)}var BP=U({hingeLoss_:LP});function WP(e,t,n,s=1,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"labels","huberLoss"),o=_(t,"predictions","huberLoss"),i=null;n!=null&&(i=_(n,"weights","huberLoss")),Mn(a.shape,o.shape,"Error in huberLoss: ");let l=Ee(s),c=Kt(xe(o,a)),u=Fu(c,l),d=xe(c,u),p=ue(L(Ee(.5),vt(u)),L(l,d));return ta(p,i,r)}var VP=U({huberLoss_:WP});function UP(e,t,n,s=1e-7,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"labels","logLoss"),o=_(t,"predictions","logLoss"),i=null;n!=null&&(i=_(n,"weights","logLoss")),Mn(a.shape,o.shape,"Error in logLoss: ");let l=Ee(1),c=Ee(s),u=_t(L(a,xs(ue(o,c)))),d=L(xe(l,a),xs(ue(xe(l,o),c))),p=xe(u,d);return ta(p,i,r)}var GP=U({logLoss_:UP});function HP(e,t,n,s=Vn.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","meanSquaredError"),a=_(t,"predictions","meanSquaredError"),o=null;n!=null&&(o=_(n,"weights","meanSquaredError")),Mn(r.shape,a.shape,"Error in meanSquaredError: ");let i=Sf(r,a);return ta(i,o,s)}var jP=U({meanSquaredError_:HP});function qP(e,t){let n=_(e,"labels","sigmoidCrossEntropyWithLogits"),s=_(t,"logits","sigmoidCrossEntropyWithLogits");Mn(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=cr(s),a=L(s,n),o=Id(As(_t(Kt(s))));return ue(xe(r,a),o)}function XP(e,t,n,s=0,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"multiClassLabels","sigmoidCrossEntropy"),o=_(t,"logits","sigmoidCrossEntropy"),i=null;if(n!=null&&(i=_(n,"weights","sigmoidCrossEntropy")),Mn(a.shape,o.shape,"Error in sigmoidCrossEntropy: "),s>0){let c=Ee(s),u=Ee(1),d=Ee(.5);a=ue(L(a,xe(u,c)),L(d,c))}let l=qP(a,o);return ta(l,i,r)}var KP=U({sigmoidCrossEntropy_:XP});function ZP(e,t,n=-1){if(n===-1&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);return Er((r,a,o)=>{let l=h1(a,[n],!0),c=xe(pe(a,"float32"),l);o([r,c]);let u=_t(L(c,r));return{value:ke(u,[n]),gradFunc:(h,f)=>{let[m,g]=f,y=el(h.shape,[n]);return[L(G(h,y),xe(pe(m,"float32"),As(g))),L(G(h,y),xe(As(g),pe(m,"float32")))]}}})(e,t)}function YP(e,t,n,s=0,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"onehotLabels","softmaxCrossEntropy"),o=_(t,"logits","softmaxCrossEntropy"),i=null;if(n!=null&&(i=_(n,"weights","softmaxCrossEntropy")),Mn(a.shape,o.shape,"Error in softmaxCrossEntropy: "),s>0){let c=Ee(s),u=Ee(1),d=Ee(a.shape[1]);a=ue(L(a,xe(u,c)),fe(c,d))}let l=ZP(a,o);return ta(l,i,r)}var JP=U({softmaxCrossEntropy_:YP});function QP(e,t,n,s){let r=_(e,"indices","sparseFillEmptyRows"),a=_(t,"values","sparseFillEmptyRows"),o=_(n,"denseShape","sparseFillEmptyRows"),i=_(s,"defaultValue","sparseFillEmptyRows",a.dtype);if(r.rank!==2)throw new Error(`Indices should be Tensor2D but received shape
|
|
${r.shape}`);if(a.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(o.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(i.rank!==0)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);let l={indices:r,values:a,denseShape:o,defaultValue:i},c=W.runKernel(Mh,l);return{outputIndices:c[0],outputValues:c[1],emptyRowIndicator:c[2],reverseIndexMap:c[3]}}var eF=U({sparseFillEmptyRows_:QP});function tF(e,t,n){let s=_(e,"inputIndices","sparseReshape"),r=_(t,"inputShape","sparseReshape"),a=_(n,"newShape","sparseReshape");if(s.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
|
|
${s.shape}`);if(r.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${r.shape}`);if(a.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);let o={inputIndices:s,inputShape:r,newShape:a},i=W.runKernel(zh,o);return{outputIndices:i[0],outputShape:i[1]}}var nF=U({sparseReshape_:tF});function sF(e,t,n){let s=_(e,"data","sparseSegmentMean"),r=_(t,"indices","sparseSegmentMean"),a=_(n,"segmentIds","sparseSegmentMean");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${r.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${a.shape}`);let o={data:s,indices:r,segmentIds:a};return W.runKernel(Lh,o)}var rF=U({sparseSegmentMean_:sF});function aF(e,t,n){let s=_(e,"data","sparseSegmentSum"),r=_(t,"indices","sparseSegmentSum"),a=_(n,"segmentIds","sparseSegmentSum");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${r.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${a.shape}`);let o={data:s,indices:r,segmentIds:a};return W.runKernel(Bh,o)}var oF=U({sparseSegmentSum_:aF});function iF(e,t,n,s,r,a,o,i){let l=_(e,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);let c=_(t,"dataSplits","stringNGrams");if(c.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let u={separator:n,nGramWidths:s,leftPad:r,rightPad:a,padWidth:o,preserveShortSequences:i},d={data:l,dataSplits:c},p=W.runKernel(sd,d,u);return{nGrams:p[0],nGramsSplits:p[1]}}var lF=U({stringNGrams_:iF});function uF(e,t,n=!0){let s=_(e,"input","stringSplit","string"),r=_(t,"delimiter","stringSplit","string");if(s.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${s.shape}`);if(r.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);let a={skipEmpty:n},o={input:s,delimiter:r},i=W.runKernel(Wh,o,a);return{indices:i[0],values:i[1],shape:i[2]}}var cF=U({stringSplit_:uF});function dF(e,t){let n=_(e,"input","stringToHashBucketFast","string"),s={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let r={input:n};return W.runKernel(Vh,r,s)}var pF=U({stringToHashBucketFast_:dF}),hF={fft:Dd,ifft:Lu,rfft:_d,irfft:If},fF={hammingWindow:G_,hannWindow:mv,frame:gv,stft:X_},$e={flipLeftRight:J_,grayscaleToRGB:eP,resizeNearestNeighbor:wv,resizeBilinear:vv,rotateWithOffset:nP,cropAndResize:Z_,nonMaxSuppression:rP,nonMaxSuppressionAsync:pP,nonMaxSuppressionWithScore:fP,nonMaxSuppressionWithScoreAsync:gP,nonMaxSuppressionPadded:AP,nonMaxSuppressionPaddedAsync:bP,threshold:SP,transform:TP},Iv={bandPart:EP,gramSchmidt:$P,qr:_P},mF={absoluteDifference:OP,computeWeightedLoss:ta,cosineDistance:zP,hingeLoss:BP,huberLoss:VP,logLoss:GP,meanSquaredError:jP,sigmoidCrossEntropy:KP,softmaxCrossEntropy:JP},Pd={sparseFillEmptyRows:eF,sparseReshape:nF,sparseSegmentMean:rF,sparseSegmentSum:oF},_f={stringNGrams:lF,stringSplit:cF,stringToHashBucketFast:pF},na=class extends S3{minimize(e,t=!1,n){let{value:s,grads:r}=this.computeGradients(e,n);if(n!=null){let a=n.map(o=>({name:o.name,tensor:r[o.name]}));this.applyGradients(a)}else this.applyGradients(r);return te(r),t?s:(s.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return K3(e,t)}dispose(){this.iterations_!=null&&te(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Ee(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}};Object.defineProperty(na,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var Pf=class extends na{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=W.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=W.registeredVariables[n],a=!1;this.accumulatedGrads[s]==null&&(this.accumulatedGrads[s]={originalName:`${n}/accum_grad`,variable:j(()=>tt(r).variable(a))}),this.accumulatedUpdates[s]==null&&(this.accumulatedUpdates[s]={originalName:`${n}/accum_var`,variable:j(()=>tt(r).variable(a))});let o=Array.isArray(e)?e[s].tensor:e[n];if(o==null)return;let i=this.accumulatedGrads[s].variable,l=this.accumulatedUpdates[s].variable;j(()=>{let c=ue(L(i,this.rho),L(vt(o),1-this.rho)),u=L(fe(Cn(ue(l,this.epsilon)),Cn(ue(i,this.epsilon))),o),d=ue(L(l,this.rho),L(vt(u),1-this.rho));i.assign(c),l.assign(d);let p=ue(L(u,-this.learningRate),r);r.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(te(this.accumulatedGrads.map(e=>e.variable)),te(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){let e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}};Pf.className="Adadelta";vo(Pf);var Ff=class extends na{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=W.registeredVariables[n];if(this.accumulatedGrads[s]==null){let i=!1;this.accumulatedGrads[s]={originalName:`${n}/accumulator`,variable:j(()=>_u(r.shape,this.initialAccumulatorValue).variable(i))}}let a=Array.isArray(e)?e[s].tensor:e[n];if(a==null)return;let o=this.accumulatedGrads[s].variable;j(()=>{let i=ue(o,vt(a));o.assign(i);let l=ue(L(fe(a,Cn(ue(i,W.backend.epsilon()))),-this.learningRate),r);r.assign(l)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&te(this.accumulatedGrads.map(e=>e.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=!1;this.accumulatedGrads=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}};Ff.className="Adagrad";vo(Ff);var Of=class extends na{constructor(e,t,n,s=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],j(()=>{this.accBeta1=Ee(t).variable(),this.accBeta2=Ee(n).variable()}),s==null&&(this.epsilon=W.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);j(()=>{let n=xe(1,this.accBeta1),s=xe(1,this.accBeta2);t.forEach((r,a)=>{let o=W.registeredVariables[r],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${r}/m`,variable:j(()=>tt(o).variable(i))}),this.accumulatedSecondMoment[a]==null&&(this.accumulatedSecondMoment[a]={originalName:`${r}/v`,variable:j(()=>tt(o).variable(i))});let l=Array.isArray(e)?e[a].tensor:e[r];if(l==null)return;let c=this.accumulatedFirstMoment[a].variable,u=this.accumulatedSecondMoment[a].variable,d=ue(L(c,this.beta1),L(l,1-this.beta1)),p=ue(L(u,this.beta2),L(vt(l),1-this.beta2)),h=fe(d,n),f=fe(p,s);c.assign(d),u.assign(p);let m=ue(L(fe(h,ue(Cn(f),this.epsilon)),-this.learningRate),o);o.assign(m)}),this.accBeta1.assign(L(this.accBeta1,this.beta1)),this.accBeta2.assign(L(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&te(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&te(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){let e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e),j(()=>{this.accBeta1.assign(ea(this.beta1,this.iterations_+1)),this.accBeta2.assign(ea(this.beta2,this.iterations_+1))});let t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}};Of.className="Adam";vo(Of);var Mf=class extends na{constructor(e,t,n,s=null,r=0){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],j(()=>{this.iteration=Ee(0).variable(),this.accBeta1=Ee(t).variable()}),s==null&&(this.epsilon=W.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);j(()=>{let n=xe(1,this.accBeta1),s=fe(-this.learningRate,ue(L(this.iteration,this.decay),1));t.forEach((r,a)=>{let o=W.registeredVariables[r],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${r}/m`,variable:tt(o).variable(i)}),this.accumulatedWeightedInfNorm[a]==null&&(this.accumulatedWeightedInfNorm[a]={originalName:`${r}/v`,variable:tt(o).variable(i)});let l=Array.isArray(e)?e[a].tensor:e[r];if(l==null)return;let c=this.accumulatedFirstMoment[a].variable,u=this.accumulatedWeightedInfNorm[a].variable,d=ue(L(c,this.beta1),L(l,1-this.beta1)),p=L(u,this.beta2),h=Kt(l),f=Rr(p,h);c.assign(d),u.assign(f);let m=ue(L(fe(s,n),fe(d,ue(f,this.epsilon))),o);o.assign(m)}),this.iteration.assign(ue(this.iteration,1)),this.accBeta1.assign(L(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&te(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&te(this.accumulatedWeightedInfNorm.map(e=>e.variable))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}};Mf.className="Adamax";vo(Mf);var Fd=class extends na{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=Array.isArray(e)?e[s].tensor:e[n];if(r==null)return;let a=W.registeredVariables[n];j(()=>{let o=ue(L(this.c,r),a);a.assign(o)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=An(Ee(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(e=await this.extractIterations(e),e.length!==0)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}};Fd.className="SGD";vo(Fd);var zf=class extends Fd{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ee(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=W.registeredVariables[n];if(this.accumulations[s]==null){let i=!1;this.accumulations[s]={originalName:`${n}/momentum`,variable:j(()=>tt(r).variable(i))}}let a=this.accumulations[s].variable,o=Array.isArray(e)?e[s].tensor:e[n];o!=null&&j(()=>{let i,l=ue(L(this.m,a),o);this.useNesterov?i=ue(L(this.c,ue(o,L(l,this.m))),r):i=ue(L(this.c,l),r),a.assign(l),r.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&te(this.accumulations.map(e=>e.variable))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=!1;this.accumulations=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}};zf.className="Momentum";vo(zf);var Lf=class extends na{constructor(e,t=.9,n=0,s=null,r=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=s,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,s==null&&(this.epsilon=W.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=W.registeredVariables[n],a=!1;this.accumulatedMeanSquares[s]==null&&(this.accumulatedMeanSquares[s]={originalName:`${n}/rms`,variable:j(()=>tt(r).variable(a))}),this.accumulatedMoments[s]==null&&(this.accumulatedMoments[s]={originalName:`${n}/momentum`,variable:j(()=>tt(r).variable(a))}),this.accumulatedMeanGrads[s]==null&&this.centered&&(this.accumulatedMeanGrads[s]={originalName:`${n}/mg`,variable:j(()=>tt(r).variable(a))});let o=Array.isArray(e)?e[s].tensor:e[n];if(o==null)return;let i=this.accumulatedMeanSquares[s].variable,l=this.accumulatedMoments[s].variable;j(()=>{let c=ue(L(i,this.decay),L(vt(o),1-this.decay));if(this.centered){let u=this.accumulatedMeanGrads[s].variable,d=ue(L(u,this.decay),L(o,1-this.decay)),p=fe(L(o,this.learningRate),Cn(xe(c,ue(vt(d),this.epsilon)))),h=ue(L(l,this.momentum),p);i.assign(c),u.assign(d),l.assign(h);let f=xe(r,h);r.assign(f)}else{let u=ue(L(i,this.decay),L(vt(o),1-this.decay)),d=ue(L(l,this.momentum),fe(L(o,this.learningRate),Cn(ue(u,this.epsilon))));i.assign(u),l.assign(d);let p=xe(r,d);r.assign(p)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&te(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&te(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&te(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){let e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}};Lf.className="RMSProp";vo(Lf);var sl=class{static sgd(e){return new Fd(e)}static momentum(e,t,n=!1){return new zf(e,t,n)}static rmsprop(e,t=.9,n=0,s=null,r=!1){return new Lf(e,t,n,s,r)}static adam(e=.001,t=.9,n=.999,s=null){return new Of(e,t,n,s)}static adadelta(e=.001,t=.95,n=null){return new Pf(e,t,n)}static adamax(e=.002,t=.9,n=.999,s=null,r=0){return new Mf(e,t,n,s,r)}static adagrad(e,t=.1){return new Ff(e,t)}},rl={sgd:sl.sgd,momentum:sl.momentum,adadelta:sl.adadelta,adagrad:sl.adagrad,rmsprop:sl.rmsprop,adamax:sl.adamax,adam:sl.adam},gF=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function Bf(){return new Promise(e=>gF(()=>e()))}var E={};Le(E,{ERF_A1:()=>TF,ERF_A2:()=>NF,ERF_A3:()=>EF,ERF_A4:()=>RF,ERF_A5:()=>$F,ERF_P:()=>CF,PARALLELIZE_THRESHOLD:()=>D1,SELU_SCALE:()=>Cv,SELU_SCALEALPHA:()=>Sv,applyActivation:()=>$f,assertAndGetBroadcastShape:()=>Tt,assertAxesAreInnerMostDims:()=>D$,assertParamsConsistent:()=>yF,assignToTypedArray:()=>MF,axesAreInnerMostDims:()=>d1,calculateShapes:()=>h3,checkEinsumDimSizes:()=>UF,combineLocations:()=>Y3,complexWithEvenIndex:()=>PF,complexWithOddIndex:()=>FF,computeConv2DInfo:()=>xd,computeConv3DInfo:()=>D3,computeDefaultPad:()=>Z2,computeDilation2DInfo:()=>tR,computeOptimalWindowSize:()=>xF,computeOutAndReduceShapes:()=>J3,computeOutShape:()=>AF,computePool2DInfo:()=>$3,computePool3DInfo:()=>nR,convertConv2DDataFormat:()=>_3,decodeEinsumEquation:()=>WF,eitherStridesOrDilationsAreOne:()=>Nr,expandShapeToKeepDim:()=>el,exponent:()=>LF,exponents:()=>zF,fromStringArrayToUint8:()=>JF,fromUint8ToStringArray:()=>YF,getAxesPermutation:()=>Q3,getBroadcastDims:()=>qR,getComplexWithIndex:()=>OF,getEinsumComputePath:()=>GF,getEinsumPermutation:()=>VF,getFusedBiasGradient:()=>Rf,getFusedDyActivation:()=>Ef,getImageCenter:()=>bF,getInnerMostAxes:()=>_$,getPermuted:()=>wF,getReductionAxes:()=>sn,getReshaped:()=>vF,getReshapedPermuted:()=>kF,getSliceBeginCoords:()=>IF,getSliceSize:()=>SF,getUndoAxesPermutation:()=>p1,isIdentityPermutation:()=>HF,log:()=>RN,mergeRealAndImagArrays:()=>DF,prepareAndValidate:()=>p3,prepareSplitSize:()=>qF,segment_util:()=>Ev,shouldFuse:()=>Df,slice_util:()=>yn,splitRealAndImagArrays:()=>_F,tupleValuesAreOne:()=>wo,upcastType:()=>Ln,validateInput:()=>O2,validateUpdateShape:()=>F2,warn:()=>Ir});function yF(e,t){let n=e[0].length;e.forEach((r,a)=>{M(r.length===n,()=>`Error in concat${n}D: rank of tensors[${a}] must be the same as the rank of the rest (${n})`)}),M(t>=0&&t<n,()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`);let s=e[0];e.forEach((r,a)=>{for(let o=0;o<n;o++)M(o===t||r[o]===s[o],()=>`Error in concat${n}D: Shape of tensors[${a}] (${r}) does not match the shape of the rest (${s}) along the non-concatenated axis ${a}.`)})}function AF(e,t){let n=e[0].slice();for(let s=1;s<e.length;s++)n[t]+=e[s][t];return n}var D1=30;function xF(e){return e<=D1?e:ph(e,Math.floor(Math.sqrt(e)))}function bF(e,t,n){let s=n*(typeof e=="number"?e:e[0]),r=t*(typeof e=="number"?e:e[1]);return[s,r]}function vF(e,t,n,s=!0){let r=[];if(s)r=r.concat(t.slice(0)),r.push(e[0]/n),r=r.concat(e.slice(1));else{r=r.concat(e[0]);let a=t.length;for(let o=0;o<a;++o)r=r.concat([e[o+1]/t[o],t[o]]);r=r.concat(e.slice(a+1))}return r}function wF(e,t,n=!0){let s=[];if(n){s.push(t);for(let r=t+1;r<e;++r)r<=2*t?(s.push(r),s.push(r-(t+1))):s.push(r)}else{let r=[],a=[];for(let o=1;o<e;++o)o>=t*2+1||o%2==1?a.push(o):r.push(o);s.push(...r),s.push(0),s.push(...a)}return s}function kF(e,t,n,s=!0){let r=[];s?r.push(e[0]/n):r.push(e[0]*n);for(let a=1;a<e.length;++a)a<=t.length?s?r.push(t[a-1]*e[a]):r.push(e[a]/t[a-1]):r.push(e[a]);return r}function IF(e,t){let n=[0];for(let s=0;s<t;++s)n.push(e[s][0]);return n}function SF(e,t,n){let s=e.slice(0,1);for(let r=0;r<n;++r)s.push(e[r+1]-t[r][0]-t[r][1]);return s}var Sv=1.7580993408473768,Cv=1.0507009873554805,CF=.3275911,TF=.254829592,NF=-.284496736,EF=1.421413741,RF=-1.453152027,$F=1.061405429;function DF(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);let n=new Float32Array(e.length*2);for(let s=0;s<n.length;s+=2)n[s]=e[s/2],n[s+1]=t[s/2];return n}function _F(e){let t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let s=0;s<e.length;s+=2)t[s/2]=e[s],n[s/2]=e[s+1];return{real:t,imag:n}}function PF(e){let t=Math.ceil(e.length/4),n=new Float32Array(t),s=new Float32Array(t);for(let r=0;r<e.length;r+=4)n[Math.floor(r/4)]=e[r],s[Math.floor(r/4)]=e[r+1];return{real:n,imag:s}}function FF(e){let t=Math.floor(e.length/4),n=new Float32Array(t),s=new Float32Array(t);for(let r=2;r<e.length;r+=4)n[Math.floor(r/4)]=e[r],s[Math.floor(r/4)]=e[r+1];return{real:n,imag:s}}function OF(e,t){let n=e[t*2],s=e[t*2+1];return{real:n,imag:s}}function MF(e,t,n,s){e[s*2]=t,e[s*2+1]=n}function zF(e,t){let n=new Float32Array(e/2),s=new Float32Array(e/2);for(let r=0;r<Math.ceil(e/2);r++){let a=(t?2:-2)*Math.PI*(r/e);n[r]=Math.cos(a),s[r]=Math.sin(a)}return{real:n,imag:s}}function LF(e,t,n){let s=(n?2:-2)*Math.PI*(e/t),r=Math.cos(s),a=Math.sin(s);return{real:r,imag:a}}var _1="->",BF=/->/g,Tv=",",Nv="...";function WF(e,t){e=e.replace(/\s/g,"");let n=(e.length-e.replace(BF,"").length)/_1.length;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error(`Equation must contain exactly one arrow ("${_1}").`);let[s,r]=e.split(_1);M(s.indexOf(Nv)===-1,()=>`The ellipsis notation ("${Nv}") is not supported yet.`);let a=s.split(Tv),o=a.length;if(t!==o)throw new Error(`Expected ${o} input tensors, received ${t}`);if(o>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let i=[];for(let p=0;p<r.length;++p){let h=r[p];if(!a.some(f=>f.indexOf(h)!==-1))throw new Error(`Output subscripts contain the label ${h} not present in the input subscripts.`);i.indexOf(h)===-1&&i.push(h)}for(let p=0;p<s.length;++p){let h=s[p];i.indexOf(h)===-1&&h!==Tv&&i.push(h)}let l=new Array(a.length);for(let p=0;p<o;++p){if(new Set(a[p].split("")).size!==a[p].length)throw new Error(`Found duplicate axes in input component ${a[p]}. Support for duplicate axes in input is not implemented yet.`);l[p]=[];for(let h=0;h<a[p].length;++h)l[p].push(i.indexOf(a[p][h]))}let c=i.length,u=r.length,d=[];for(let p=u;p<c;++p)d.push(p);return{allDims:i,summedDims:d,idDims:l}}function VF(e,t){let n=new Array(e);n.fill(-1);for(let r=0;r<t.length;++r)n[t[r]]=r;let s=[];for(let r=0;r<e;++r)n[r]===-1&&s.push(r);return n=n.filter(r=>r!==-1),{permutationIndices:n,expandDims:s}}function UF(e,t,n){let s=new Array(e);for(let r=0;r<n.length;++r){let a=n[r].shape;for(let o=0;o<t[r].length;++o)s[t[r][o]]===void 0?s[t[r][o]]=a[o]:M(s[t[r][o]]===a[o],()=>`Expected dimension ${s[t[r][o]]} at axis ${o} of input shaped ${JSON.stringify(a)}, but got dimension ${a[o]}`)}}function GF(e,t){let n=e,s=[],r=0;e.length===0&&n.push(-1),r=e.length+1;for(let o=0;o<r;++o)s.push([]);let a=[];for(let o=0;o<n.length;++o){let i=n[o],l=jF(t,i);for(let c of l)a.indexOf(c)===-1&&(s[o].push(c),a.push(c))}return{path:n,steps:s}}function HF(e){return e.every((t,n)=>t===n)}function jF(e,t){let n=[];for(let s=0;s<e.length;++s)(e[s].length===0||e[s].indexOf(t)!==-1||t===-1)&&n.push(s);return n}function qF(e,t,n=0){let s=[];if(typeof t=="number")M(e.shape[n]%t==0,()=>"Number of splits must evenly divide the axis."),s=new Array(t).fill(e.shape[n]/t);else{let r=t.reduce((o,i)=>(i===-1&&(o+=1),o),0);M(r<=1,()=>"There should be only one negative value in split array.");let a=t.indexOf(-1);if(a!==-1){let o=t.reduce((i,l)=>l>0?i+l:i);t[a]=e.shape[n]-o}M(e.shape[n]===t.reduce((o,i)=>o+i),()=>"The sum of sizes must match the size of the axis dimension."),s=t}return s}var Ev={};Le(Ev,{collectGatherOpShapeInfo:()=>ZF,computeOutShape:()=>KF,segOpComputeOptimalWindowSize:()=>XF});function XF(e,t){let n=!1,s;for(e<=D1?(s=e,n=!0):s=ph(e,Math.floor(Math.sqrt(e)));!n;)s>t||s===e?n=!0:s=ph(e,s+1);return s}function KF(e,t,n){let s=[],r=e.length;for(let a=0;a<r;a++)a!==t?s.push(e[a]):s.push(n);return s}function ZF(e,t,n,s){let r=t.shape.length,a=e.shape.length;if(s!==0&&(s<-r||s>r))throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${s}`);if(s<0&&(s+=r),s>a)throw new Error(`batchDims (${s}) must be less than rank(x) (
|
|
${a}).`);if(n<s)throw new Error(`batchDims (${s}) must be less than or equal to axis (${n}).`);for(let d=0;d<s;++d)if(e.shape[d]!==t.shape[d])throw new Error(`x.shape[${d}]: ${e.shape[d]} should be equal to indices.shape[${d}]: ${t.shape[d]}.`);let o=e.shape[n],i=[],l=1,c=1,u=1;for(let d=0;d<s;++d)i.push(e.shape[d]),l*=e.shape[d];for(let d=s;d<n;d++)i.push(e.shape[d]),c*=e.shape[d];for(let d=s;d<r;d++)i.push(t.shape[d]);for(let d=n+1;d<a;d++)i.push(e.shape[d]),u*=e.shape[d];return{batchSize:l,sliceSize:u,outerSize:c,dimSize:o,outputShape:i}}function YF(e){try{return e.map(t=>qh(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function JF(e){return e.map(t=>ud(t))}var Zs={};Le(Zs,{nonMaxSuppressionV3Impl:()=>yv,nonMaxSuppressionV4Impl:()=>Av,nonMaxSuppressionV5Impl:()=>xv,whereImpl:()=>iv});var Rv={kernelName:ni,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,Bu(pe(n,"float32"),-1))}}},QF={kernelName:ql,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=vt(pe(n,"float32")),r=Cn(xe(Ee(1),s));return _t(fe(e,r))}}}},eO={kernelName:Xl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=Cn(xe(vt(pe(n,"float32")),1));return fe(e,s)}}}},tO={kernelName:qr,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=Tt(n.shape,s.shape);return{a:()=>{let i=e,l=sn(n.shape,r);return l.length>0&&(i=ke(i,l)),G(i,n.shape)},b:()=>{let i=e,l=sn(s.shape,r);return l.length>0&&(i=ke(i,l)),G(i,s.shape)}}}},nO={kernelName:wa,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((s,r)=>{n[r]=()=>e.clone()}),n}},sO={kernelName:ka,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>tt(n)}}},rO={kernelName:Yl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>tt(n)}}},aO={kernelName:Jl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,Cn(xe(Ee(1),vt(pe(n,"float32")))))}}},oO={kernelName:Ql,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=Cn(ue(Ee(1),vt(pe(n,"float32"))));return fe(e,s)}}}},iO={kernelName:nu,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=Tt(n.shape,s.shape);return{a:()=>{let i=ue(vt(n),vt(s)),l=L(e,fe(s,i)),c=sn(n.shape,r);return c.length>0&&(l=ke(l,c)),G(l,n.shape)},b:()=>{let i=ue(vt(n),vt(s)),l=_t(L(e,fe(n,i))),c=sn(s.shape,r);return c.length>0&&(l=ke(l,c)),G(l,s.shape)}}}},lO={kernelName:eu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,ue(vt(pe(n,"float32")),1))}}},uO={kernelName:tu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,xe(Ee(1),vt(pe(n,"float32"))))}}};function cO(e,t,n,s,r,a){let o=_(e,"dy","avgPool3dGrad"),i=_(t,"input","avgPool3dGrad"),l=o,c=i,u=!1;i.rank===4&&(u=!0,l=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),c=G(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),M(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),M(c.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${c.rank}.`),a!=null&&M(mn(r),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`);let d={dy:l,input:c},p={filterSize:n,strides:s,pad:r,dimRoundingMode:a},h=W.runKernel(mh,d,p);return u?G(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var dO=U({avgPool3dGrad_:cO}),pO={kernelName:Hc,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{filterSize:r,strides:a,pad:o,dimRoundingMode:i}=n;return{x:()=>dO(e,s,r,a,o,i)}}};function hO(e,t,n,s,r){let a=_(e,"dy","avgPoolGrad"),o=_(t,"input","avgPoolGrad");M(o.rank===a.rank,()=>`Rank of input (${o.rank}) does not match rank of dy (${a.rank})`);let i=o,l=a,c=!1;o.rank===3&&(c=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2]]),l=G(a,[1,a.shape[0],a.shape[1],a.shape[2]])),M(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),M(i.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${i.rank}.`);let u={dy:l,input:i},d={filterSize:n,strides:s,pad:r},p=W.runKernel(fh,u,d);return c?G(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var fO=U({avgPoolGrad_:hO}),mO={kernelName:Ia,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{filterSize:r,strides:a,pad:o}=n;return{x:()=>fO(e,s,r,a,o)}}},gO={kernelName:Sa,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{let[s,r]=t,{transposeA:a,transposeB:o}=n;return!a&&!o?{a:()=>Xe(e,r,!1,!0),b:()=>Xe(s,e,!0,!1)}:!a&&o?{a:()=>Xe(e,r,!1,!1),b:()=>Xe(e,s,!0,!1)}:a&&!o?{a:()=>Xe(r,e,!1,!0),b:()=>Xe(s,e,!1,!1)}:{a:()=>Xe(r,e,!0,!0),b:()=>Xe(e,s,!0,!0)}}},yO={kernelName:si,gradFunc:(e,t,n)=>{let{blockShape:s,crops:r}=n;return{x:()=>Nd(e,s,r)}}},AO={kernelName:E5,gradFunc:(e,t,n)=>{let s=n,r=s.inputShape,a=s.shape,o=Array.from(a);for(let l=r.length-1;l>=0;l--)if(r[l]===a[l])o[l]=1;else if(r[l]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${a}].`);let i=[];for(let l=0;l<o.length;l++)o[l]>1&&i.push(l);return{x:()=>ke(e,i,!0)}}},xO={kernelName:Ca,gradFunc:e=>({x:()=>e.clone()})},bO={kernelName:Ta,gradFunc:e=>({x:()=>tt(e)})},vO={kernelName:Xr,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{clipValueMin:r,clipValueMax:a}=n;return{x:()=>Pn(Ks(ko(s,r),Io(s,a)),e,tt(e))}}},wO={kernelName:qc,inputsToSave:["x"],gradFunc:Rv.gradFunc},kO={kernelName:ri,saveAllInputs:!0,gradFunc:(e,t,n)=>{let s=t.map(l=>l.shape),{axis:r}=n,a=qs(r,t[0].shape)[0],o=s.map(l=>l[a]);return xn(e,o,a).map(l=>()=>l)}},IO={kernelName:Na,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[s,r]=t,{dilations:a,strides:o,pad:i,dataFormat:l}=n;return M(wo(a),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`),{x:()=>t1(s.shape,e,r,o,i,l),filter:()=>R1(s,e,r.shape,o,i,l)}}},SO={kernelName:Ea,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{let[s,r]=t,{strides:a,pad:o,dataFormat:i,dimRoundingMode:l}=n;return{dy:()=>Qr(e,r,a,o,i,1,l),filter:()=>R1(e,s,r.shape,a,o,i,l)}}};function CO(e,t,n,s,r){let a=e;e.rank===4&&(a=G(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let o=t;o.rank===4&&(o=G(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),M(a.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${a.shape}.`),M(o.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${o.shape}.`),M(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),M(a.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${a.shape[4]}) must match input depth in filter (${n[3]}.`),M(o.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${o.shape[4]}) must match output depth for filter (${n[4]}).`);let i={x:a,dy:o},l={strides:s,pad:r,filterShape:n};return W.runKernel(Ah,i,l)}var TO=U({conv3DBackpropFilter_:CO}),NO={kernelName:Xc,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:s,strides:r,pad:a}=n;M(wo(s),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let[o,i]=t;return{x:()=>W3(o.shape,e,i,r,a),filter:()=>TO(o,e,i.shape,r,a)}}},EO={kernelName:Ra,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(_t(vf(pe(n,"float32"))),e)}}},RO={kernelName:$a,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(wf(pe(n,"float32")),e)}}},$O={kernelName:ai,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{axis:r,exclusive:a,reverse:o}=n;return{x:()=>{let i=Q3([r],s.rank),l=uf(e,r,a,!o);return i!=null&&(l=et(l,i)),l}}}},DO={kernelName:Da,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:s,strides:r,pad:a,dimRoundingMode:o}=n,i=s==null?[1,1]:s;M(wo(i),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);let[l,c]=t;return M(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),M(c.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${c.rank}.`),M(l.shape[3]===c.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),M(Nr(r,i),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'.`),o!=null&&M(mn(a),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`),{x:()=>fv(l.shape,e,c,r,a,i,o),filter:()=>hv(l,e,c.shape,r,a,i,o)}}},_O={kernelName:Kc,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[s,r]=t,a={x:s,filter:r,dy:e},o={x:s,filter:r,dy:e};return{x:()=>W.runKernel(Ih,a,n),filter:()=>W.runKernel(Sh,o,n)}}},PO={kernelName:Pa,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t,s={dy:e,y:n};return{x:()=>W.runKernel(Ch,s)}}},FO={kernelName:su,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,s=L(As(_t(vt(n))),2/Math.sqrt(Math.PI));return{x:()=>L(e,s)}}},OO={kernelName:Fa,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,n)}}},MO={kernelName:ui,inputsToSave:["input"],gradFunc:(e,t)=>{let[n]=t;return{input:()=>G(e,n.shape)}}},zO={kernelName:ci,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,As(n))}}},LO={kernelName:Oa,gradFunc:e=>({x:()=>tt(e)})},BO={kernelName:Ma,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=Tt(n.shape,s.shape);return{a:()=>{let i=fe(e,pe(s,"float32")),l=sn(n.shape,r);return l.length>0?G(ke(i,l),n.shape):i},b:()=>{let i=L(e,pe(n,"float32")),l=sn(s.shape,r);l.length>0&&(i=G(ke(i,l),s.shape));let c=vt(s);return _t(fe(i,pe(c,"float32")))}}}},WO={kernelName:za,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{let{varianceEpsilon:s}=n,[r,a,o,i]=t,l=i==null?Ee(1):i,c=sn(a.shape,r.shape),u=[];if(a.rank===1){for(let b=0;b<r.shape.length-1;++b)u.push(r.shape[b]);u.push(1)}let d=xe(r,a),p=L(e,l),h=xf(ue(o,Ee(s))),f=L(L(L(h,h),h),Ee(-.5));return{x:()=>a.rank===1?G(L(L(e,Os(G(h,[1,1,1,a.shape[0]]),u)),l),r.shape):G(L(L(e,h),l),r.shape),mean:()=>{let b=L(L(h,Ee(-1)),p);return a.rank===1&&(b=ke(b,c)),G(b,a.shape)},variance:()=>{let b=L(L(f,d),p);return a.rank===1&&(b=ke(b,c)),G(b,a.shape)},scale:()=>{let b=L(d,h),w=L(e,b);return a.rank===1&&(w=ke(w,c)),G(w,a.shape)},offset:()=>{let b=e;return a.rank===1&&(b=ke(b,c)),G(b,a.shape)}}}},VO={kernelName:pi,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{let[s,r]=t,{axis:a}=n,o=qs(a,s.shape)[0];return{x:()=>{let l=s.shape,c=r.size,u=l.slice(0,o),d=u.length,p=l.slice(a,l.length).slice(1),h=p.length,f=$v(0,d),m=$v(d+1,d+1+h),g=Dv([u,[c],p]),y=G(e,g),A=G(r,[c]),x=Dv([[d],f,m]),b=et(y,x),w=C1(b,A,s.shape[o]),k=p1(x);return w=et(w,k),w},indices:()=>r}}};function $v(e,t){let n=[];for(let s=e;s<t;++s)n.push(s);return n}function Dv(e){let t=[];for(let n=0;n<e.length;++n)for(let s=0;s<e[n].length;++s)t.push(e[n][s]);return t}var UO={kernelName:La,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t;return{a:()=>tt(n),b:()=>tt(s)}}},GO={kernelName:Ba,gradFunc:e=>({x:()=>pe(e,"float32")})},HO={kernelName:au,gradFunc:e=>({x:()=>tt(e)})},jO={kernelName:ou,gradFunc:e=>({x:()=>tt(e)})},qO={kernelName:iu,gradFunc:e=>({x:()=>tt(e)})},XO={kernelName:mi,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{alpha:r}=n,a=rs(s,0);return{x:()=>Pn(a,e,L(e,r))}}},KO={kernelName:lu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,ue(n,1))}}},ZO={kernelName:Wa,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,pe(n,"float32"))}}},YO={kernelName:R5,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s]=t,{axis:r}=n;return{logits:()=>{let a=!0,o=As(s);return xe(e,L(ke(e,r,a),o))}}}};function JO(e,t,n,s=5,r=1,a=1,o=.5){let i={x:e,y:t,dy:n},l={depthRadius:s,bias:r,alpha:a,beta:o};return W.runKernel(Rh,i,l)}var QO=U({localResponseNormalizationBackprop_:JO}),eM={kernelName:Qc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{depthRadius:a,bias:o,alpha:i,beta:l}=n;return{x:()=>QO(s,r,e,a,o,i,l)}}};function _v(e,t,n,s){return t.rank<n.rank&&(t=G(t,el(t.shape,s))),e.rank<n.rank&&(e=G(e,el(e.shape,s))),{x:()=>L(e,pe(ys(n,t),e.dtype))}}var Pv={kernelName:Va,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let s=n,{reductionIndices:r}=s,a=t[0],o=t[1],i=qs(r,a.shape),l=_v(e,o,a,i);return{x:()=>l.x()}}},tM={kernelName:Ua,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t;return{a:()=>L(e,pe(ko(n,s),"float32")),b:()=>L(e,pe(df(n,s),"float32"))}}};function nM(e,t,n,s,r,a,o){let i=_(e,"dy","maxPool3dGrad"),l=_(t,"input","maxPool3dGrad"),c=_(n,"output","maxPool3dGrad"),u=i,d=l,p=c,h=!1;l.rank===4&&(h=!0,u=G(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),d=G(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),p=G(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),M(u.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`),M(d.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${d.rank}.`),M(p.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${p.rank}.`),o!=null&&M(mn(a),()=>`Error in maxPool3dGrad: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`);let f={dy:u,input:d,output:p},m={filterSize:s,strides:r,pad:a,dimRoundingMode:o},g=W.runKernel(Dh,f,m);return h?G(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var sM=U({maxPool3dGrad_:nM}),rM={kernelName:ed,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=n;return{x:()=>sM(e,s,r,a,o,i,l)}}};function aM(e,t,n,s,r,a,o){let i=_(e,"dy","maxPoolGrad"),l=_(t,"input","maxPoolGrad"),c=_(n,"output","maxPoolGrad");M(l.rank===i.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${i.rank})`),M(i.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${i.rank}.`),M(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),o!=null&&M(mn(a),()=>`Error in maxPoolGrad: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`);let u={dy:i,input:l,output:c},d={filterSize:s,strides:r,pad:a,dimRoundingMode:o};return W.runKernel($h,u,d)}var oM=U({maxPoolGrad_:aM}),iM={kernelName:Ga,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{filterSize:a,strides:o,pad:i}=n;return{x:()=>oM(e,s,r,a,o,i)}}},lM={kernelName:Ha,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{axis:r}=n,a=qs(r,s.shape),i=J3(s.shape,a)[1],l=Ht(i);return{x:()=>{let u=s.shape.slice();a.forEach(h=>{u[h]=1});let d=G(e,u);return fe(L(d,bs(s.shape,"float32")),l)}}}},uM={kernelName:ja,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let s=n,{axis:r}=s,[a,o]=t,i=qs(r,a.shape),l=_v(e,o,a,i);return{x:()=>l.x()}}},cM={kernelName:qa,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t;return{a:()=>L(e,pe(Io(n,s),"float32")),b:()=>L(e,pe(rs(n,s),"float32"))}}},dM={kernelName:Xa,inputsToSave:["x"],gradFunc:(e,t,n)=>{let s=t[0],{paddings:r}=n,a=r.map(o=>o[0]);return{x:()=>_e(e,a,s.shape)}}},pM={kernelName:cu,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=Tt(n.shape,s.shape);return{a:()=>{let i=sn(n.shape,r);return i.length>0?G(ke(e,i),n.shape):e},b:()=>{let i=L(e,_t(Pu(fe(n,s)))),l=sn(s.shape,r);return l.length>0?G(ke(i,l),s.shape):i}}}},hM={kernelName:Ka,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=Tt(n.shape,s.shape);return{a:()=>{let i=L(e,pe(s,"float32")),l=sn(n.shape,r);return l.length>0?G(ke(i,l),n.shape):i},b:()=>{let i=L(e,pe(n,"float32")),l=sn(s.shape,r);return l.length>0?G(ke(i,l),s.shape):i}}}},fM={kernelName:xi,gradFunc:e=>({x:()=>_t(e)})},mM={kernelName:Ii,inputsToSave:["indices"],gradFunc:(e,t)=>{let n=t[0];return{indices:()=>qt(n.shape,"float32")}}},gM={kernelName:ki,gradFunc:e=>({x:()=>tt(e)})},yM={kernelName:Si,saveAllInputs:!0,gradFunc:(e,t,n)=>{let{axis:s}=n;return Wn(e,s).map(a=>()=>a)}},Fv={kernelName:Za,inputsToSave:["x"],gradFunc:(e,t,n)=>{let s=t[0],{paddings:r}=n,a=r.map(o=>o[0]);return{x:()=>_e(e,a,s.shape)}}},AM={kernelName:Ya,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[n,s,r]=t,a=n,o=s,i=Tt(a.shape,o.shape);return{a:()=>{let u=pe(o,"float32"),d=L(e,L(u,ea(a,xe(u,Ee(1))))),p=sn(a.shape,i);return p.length>0&&(d=ke(d,p)),G(d,a.shape)},b:()=>{let u=rs(a,0),d=Pn(u,xs(a),tt(a)),p=L(e,L(r,d)),h=sn(o.shape,i);return h.length>0&&(p=ke(p,h)),G(p,o.shape)}}}},xM={kernelName:Ja,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[n,s]=t,r=rs(n,0);return{x:()=>Pn(r,e,L(e,s)),alpha:()=>{let a=Pn(r,tt(e),L(e,n)),o=sn(s.shape,e.shape);return o.length>0&&(a=ke(a,o)),G(a,s.shape)}}}},bM={kernelName:_a,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=Tt(n.shape,s.shape);return{a:()=>{let i=fe(e,pe(s,"float32")),l=sn(n.shape,r);return l.length>0?G(ke(i,l),n.shape):i},b:()=>{let i=L(e,pe(n,"float32")),l=sn(s.shape,r);l.length>0&&(i=G(ke(i,l),s.shape));let c=vt(s);return _t(fe(i,pe(c,"float32")))}}}},vM={kernelName:hu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,_t(vt(n)))}}},wM={kernelName:to,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,s=L(Io(n,6),Bu(n));return{x:()=>L(e,pe(s,"float32"))}}},kM={kernelName:Qa,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,pe(Bu(n),"float32"))}}},IM={kernelName:Ti,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>G(e,n.shape)}}},SM={kernelName:eo,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[s]=t,r={dy:e,images:s};return{images:()=>W.runKernel(Oh,r,n)}}},CM={kernelName:fu,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[s]=t,r={dy:e,images:s};return{images:()=>W.runKernel(Fh,r,n)}}},TM={kernelName:Ni,gradFunc:(e,t,n)=>{let{dims:s}=n,r=qs(s,e.shape);return{x:()=>ws(e,r)}}},NM={kernelName:Ei,gradFunc:e=>({x:()=>tt(e)})},EM={kernelName:no,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>_t(fe(e,L(ea(n,1.5),2)))}}},RM={kernelName:$i,inputsToSave:["condition"],gradFunc:(e,t)=>{let[n]=t;return{condition:()=>pe(tt(n),"float32"),t:()=>L(e,pe(n,e.dtype)),e:()=>L(e,pe(Sd(n),e.dtype))}}},$M={kernelName:mu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=rs(n,Ee(0)),r=Ee(Sv),a=Ee(Cv),o=L(e,a),i=L(L(e,r),As(pe(n,"float32")));return Pn(s,o,i)}}}},DM={kernelName:ro,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,L(n,xe(Ee(1),n)))}}},_M={kernelName:gu,gradFunc:e=>({x:()=>tt(e)})},PM={kernelName:so,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(wd(pe(n,"float32")),e)}}},FM={kernelName:_i,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(lf(pe(n,"float32")),e)}}},OM={kernelName:Di,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{begin:r,size:a}=n,o=s.shape,[i,l]=I3(s,r,a),c=[];for(let u=0;u<e.rank;u++)c.push([i[u],o[u]-i[u]-l[u]]);return{x:()=>ur(e,c)}}},MM={kernelName:io,outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s]=t,{dim:r}=n,a=!0,o=L(e,s);return{logits:()=>xe(o,L(ke(o,[r],a),s))}}},zM={kernelName:yu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,ns(n))}}},Ov={kernelName:Pi,gradFunc:(e,t,n)=>{let{blockShape:s,paddings:r}=n;return{x:()=>vd(e,s,r)}}},Mv={kernelName:Fi,gradFunc:(e,t,n)=>{let{axis:s}=n;return{x:()=>kt(e,s)}}},LM={kernelName:ao,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,L(Cn(pe(n,"float32")),2))}}},BM={kernelName:Au,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,L(pe(n,"float32"),2))}}},WM={kernelName:lo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=Ee(2);return{a:()=>L(e,L(r,xe(n,s))),b:()=>L(e,L(r,xe(s,n)))}}},VM={kernelName:ho,gradFunc:e=>({x:()=>tt(e)})},UM={kernelName:uo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=Tt(n.shape,s.shape);return{a:()=>{let i=e,l=sn(n.shape,r);return l.length>0&&(i=ke(i,l)),G(i,n.shape)},b:()=>{let i=e,l=sn(s.shape,r);return l.length>0&&(i=ke(i,l)),G(_t(i),s.shape)}}}},GM={kernelName:oo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,r=s.shape.slice(),{axis:a}=n;qs(a,s.shape).forEach(c=>{r[c]=1});let i=G(e,r),l=L(i,bs(s.shape,"float32"));return{x:()=>l}}},HM={kernelName:Mi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>fe(e,vt(wd(n)))}}},jM={kernelName:co,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(xe(Ee(1),vt(n)),e)}}},qM={kernelName:Kr,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{reps:r}=n;return{x:()=>{let o=tt(s);if(s.rank===1)for(let i=0;i<r[0];++i)o=ue(o,_e(e,[i*s.shape[0]],[s.shape[0]]));else if(s.rank===2)for(let i=0;i<r[0];++i)for(let l=0;l<r[1];++l)o=ue(o,_e(e,[i*s.shape[0],l*s.shape[1]],[s.shape[0],s.shape[1]]));else if(s.rank===3)for(let i=0;i<r[0];++i)for(let l=0;l<r[1];++l)for(let c=0;c<r[2];++c)o=ue(o,_e(e,[i*s.shape[0],l*s.shape[1],c*s.shape[2]],[s.shape[0],s.shape[1],s.shape[2]]));else if(s.rank===4)for(let i=0;i<r[0];++i)for(let l=0;l<r[1];++l)for(let c=0;c<r[2];++c)for(let u=0;u<r[3];++u)o=ue(o,_e(e,[i*s.shape[0],l*s.shape[1],c*s.shape[2],u*s.shape[3]],[s.shape[0],s.shape[1],s.shape[2],s.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${s.rank} tensors yet.`);return o}}}},XM={kernelName:po,gradFunc:(e,t,n)=>{let s=n,{perm:r}=s,a=p1(r);return{x:()=>et(e,a)}}},KM={kernelName:Li,gradFunc:(e,t,n)=>{let s=n,{axis:r}=s;return{value:()=>Tn(e,r)}}},ZM={kernelName:rd,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>YM(e,n)}}};function YM(e,t){let n=Rr(t,tt(t)),s=Ji(e,n),r=ko(t,Ee(0,"int32")),a=s.rank-r.rank;for(let i=0;i<a;++i)r=jt(r,i+1);r=Ks(r,bs(s.shape,"bool"));let o=tt(s);return Pn(r,s,o)}var JM={kernelName:Bi,gradFunc:e=>({x:()=>tt(e)})},QM=[Rv,QF,eO,tO,nO,sO,rO,aO,oO,iO,lO,uO,pO,mO,gO,yO,AO,xO,bO,vO,wO,kO,SO,IO,NO,EO,RO,$O,DO,_O,bM,PO,FO,OO,MO,zO,BO,LO,WO,VO,UO,GO,HO,jO,qO,XO,KO,ZO,YO,eM,Pv,Pv,tM,rM,iM,lM,uM,cM,dM,pM,hM,fM,mM,gM,yM,Fv,Fv,AM,xM,vM,wM,kM,IM,SM,CM,TM,NM,EM,RM,$M,DM,_M,PM,FM,OM,MM,zM,Ov,Ov,Mv,Mv,LM,WM,BM,VM,UM,GM,HM,jM,qM,XM,KM,ZM,JM];for(let e of QM)$5(e);re().prototype.abs=function(){return this.throwIfDisposed(),Kt(this)};re().prototype.acos=function(){return this.throwIfDisposed(),V2(this)};re().prototype.acosh=function(){return this.throwIfDisposed(),U2(this)};re().prototype.add=function(e){return this.throwIfDisposed(),ue(this,e)};re().prototype.all=function(e,t){return this.throwIfDisposed(),sf(this,e,t)};re().prototype.any=function(e,t){return this.throwIfDisposed(),Ad(this,e,t)};re().prototype.argMax=function(e){return this.throwIfDisposed(),Fs(this,e)};re().prototype.argMin=function(e){return this.throwIfDisposed(),G2(this,e)};re().prototype.asScalar=function(){return this.throwIfDisposed(),M(this.size===1,()=>"The array must have only 1 element."),G(this,[])};re().prototype.asType=function(e){return this.throwIfDisposed(),pe(this,e)};re().prototype.as1D=function(){return this.throwIfDisposed(),G(this,[this.size])};re().prototype.as2D=function(e,t){return this.throwIfDisposed(),G(this,[e,t])};re().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),G(this,[e,t,n])};re().prototype.as4D=function(e,t,n,s){return this.throwIfDisposed(),G(this,[e,t,n,s])};re().prototype.as5D=function(e,t,n,s,r){return this.throwIfDisposed(),G(this,[e,t,n,s,r])};re().prototype.asin=function(){return this.throwIfDisposed(),H2(this)};re().prototype.asinh=function(){return this.throwIfDisposed(),j2(this)};re().prototype.atan=function(){return this.throwIfDisposed(),q2(this)};re().prototype.atan2=function(e){return this.throwIfDisposed(),X2(this,e)};re().prototype.atanh=function(){return this.throwIfDisposed(),K2(this)};re().prototype.avgPool=function(e,t,n,s){return this.throwIfDisposed(),bd(this,e,t,n,s)};re().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),vd(this,e,t)};re().prototype.batchNorm=function(e,t,n,s,r){return this.throwIfDisposed(),Yi(this,e,t,n,s,r)};re().prototype.broadcastTo=function(e){return this.throwIfDisposed(),Eu(this,e)};re().prototype.cast=function(e){return this.throwIfDisposed(),pe(this,e)};re().prototype.ceil=function(){return this.throwIfDisposed(),e1(this)};re().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),ss(this,e,t)};re().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof Ke&&(e=[e]),kt([this,...e],t)};re().prototype.conv1d=function(e,t,n,s,r,a){return this.throwIfDisposed(),af(this,e,t,n,s,r,a)};re().prototype.conv2dTranspose=function(e,t,n,s,r){return this.throwIfDisposed(),of(this,e,t,n,s,r)};re().prototype.conv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),Qr(this,e,t,n,s,r,a)};re().prototype.cos=function(){return this.throwIfDisposed(),wd(this)};re().prototype.cosh=function(){return this.throwIfDisposed(),lf(this)};re().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),uf(this,e,t,n)};re().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),s1(this,e,t)};re().prototype.depthwiseConv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),$u(this,e,t,n,s,r,a)};re().prototype.dilation2d=function(e,t,n,s,r){return this.throwIfDisposed(),r1(this,e,t,n,s,r)};re().prototype.divNoNan=function(e){return this.throwIfDisposed(),a1(this,e)};re().prototype.div=function(e){return this.throwIfDisposed(),fe(this,e)};re().prototype.dot=function(e){return this.throwIfDisposed(),G3(this,e)};re().prototype.elu=function(){return this.throwIfDisposed(),Du(this)};re().prototype.equal=function(e){return this.throwIfDisposed(),ys(this,e)};re().prototype.erf=function(){return this.throwIfDisposed(),o1(this)};re().prototype.exp=function(){return this.throwIfDisposed(),As(this)};re().prototype.expandDims=function(e){return this.throwIfDisposed(),jt(this,e)};re().prototype.expm1=function(){return this.throwIfDisposed(),i1(this)};re().prototype.fft=function(){return this.throwIfDisposed(),Dd(this)};re().prototype.flatten=function(){return this.throwIfDisposed(),G(this,[this.size])};re().prototype.floor=function(){return this.throwIfDisposed(),Pu(this)};re().prototype.floorDiv=function(e){return this.throwIfDisposed(),tf(this,e)};re().prototype.gather=function(e,t){return this.throwIfDisposed(),Ji(this,e,t)};re().prototype.greaterEqual=function(e){return this.throwIfDisposed(),ko(this,e)};re().prototype.greater=function(e){return this.throwIfDisposed(),rs(this,e)};re().prototype.ifft=function(){return this.throwIfDisposed(),Lu(this)};re().prototype.irfft=function(){return this.throwIfDisposed(),If(this)};re().prototype.isFinite=function(){return this.throwIfDisposed(),j3(this)};re().prototype.isInf=function(){return this.throwIfDisposed(),q3(this)};re().prototype.isNaN=function(){return this.throwIfDisposed(),u1(this)};re().prototype.leakyRelu=function(e){return this.throwIfDisposed(),kd(this,e)};re().prototype.lessEqual=function(e){return this.throwIfDisposed(),Io(this,e)};re().prototype.less=function(e){return this.throwIfDisposed(),df(this,e)};re().prototype.localResponseNormalization=function(e,t,n,s){return this.throwIfDisposed(),c1(this,e,t,n,s)};re().prototype.logSigmoid=function(){return this.throwIfDisposed(),Z3(this)};re().prototype.logSoftmax=function(e){return this.throwIfDisposed(),hf(this,e)};re().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),h1(this,e,t)};re().prototype.log=function(){return this.throwIfDisposed(),xs(this)};re().prototype.log1p=function(){return this.throwIfDisposed(),Id(this)};re().prototype.logicalAnd=function(e){return this.throwIfDisposed(),Ks(this,e)};re().prototype.logicalNot=function(){return this.throwIfDisposed(),Sd(this)};re().prototype.logicalOr=function(e){return this.throwIfDisposed(),ff(this,e)};re().prototype.logicalXor=function(e){return this.throwIfDisposed(),ev(this,e)};re().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),Xe(this,e,t,n)};re().prototype.maxPool=function(e,t,n,s){return this.throwIfDisposed(),Cd(this,e,t,n,s)};re().prototype.max=function(e,t){return this.throwIfDisposed(),Bn(this,e,t)};re().prototype.maximum=function(e){return this.throwIfDisposed(),Rr(this,e)};re().prototype.mean=function(e,t){return this.throwIfDisposed(),Lt(this,e,t)};re().prototype.min=function(e,t){return this.throwIfDisposed(),Td(this,e,t)};re().prototype.minimum=function(e){return this.throwIfDisposed(),Fu(this,e)};re().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),m1(this,e,t)};re().prototype.mod=function(e){return this.throwIfDisposed(),g1(this,e)};re().prototype.mul=function(e){return this.throwIfDisposed(),L(this,e)};re().prototype.neg=function(){return this.throwIfDisposed(),_t(this)};re().prototype.norm=function(e,t,n){return this.throwIfDisposed(),Nf(this,e,t,n)};re().prototype.notEqual=function(e){return this.throwIfDisposed(),tl(this,e)};re().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),Cu(this,e,t,n)};re().prototype.onesLike=function(){return this.throwIfDisposed(),vs(this)};re().prototype.pad=function(e,t){return this.throwIfDisposed(),ur(this,e,t)};re().prototype.pool=function(e,t,n,s,r){return this.throwIfDisposed(),sv(this,e,t,n,s,r)};re().prototype.pow=function(e){return this.throwIfDisposed(),ea(this,e)};re().prototype.prelu=function(e){return this.throwIfDisposed(),Ed(this,e)};re().prototype.prod=function(e,t){return this.throwIfDisposed(),gf(this,e,t)};re().prototype.reciprocal=function(){return this.throwIfDisposed(),x1(this)};re().prototype.relu=function(){return this.throwIfDisposed(),cr(this)};re().prototype.relu6=function(){return this.throwIfDisposed(),yf(this)};re().prototype.reshapeAs=function(e){return this.throwIfDisposed(),G(this,e.shape)};re().prototype.reshape=function(e){return this.throwIfDisposed(),G(this,e)};re().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),vv(this,e,t,n)};re().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),wv(this,e,t,n)};re().prototype.reverse=function(e){return this.throwIfDisposed(),ws(this,e)};re().prototype.rfft=function(){return this.throwIfDisposed(),_d(this)};re().prototype.round=function(){return this.throwIfDisposed(),Af(this)};re().prototype.rsqrt=function(){return this.throwIfDisposed(),xf(this)};re().prototype.selu=function(){return this.throwIfDisposed(),bf(this)};re().prototype.separableConv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),b1(this,e,t,n,s,r,a)};re().prototype.sigmoid=function(){return this.throwIfDisposed(),ns(this)};re().prototype.sign=function(){return this.throwIfDisposed(),v1(this)};re().prototype.sin=function(){return this.throwIfDisposed(),vf(this)};re().prototype.sinh=function(){return this.throwIfDisposed(),wf(this)};re().prototype.slice=function(e,t){return this.throwIfDisposed(),_e(this,e,t)};re().prototype.softmax=function(e){return this.throwIfDisposed(),nl(this,e)};re().prototype.softplus=function(){return this.throwIfDisposed(),Qi(this)};re().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),Nd(this,e,t)};re().prototype.split=function(e,t){return this.throwIfDisposed(),xn(this,e,t)};re().prototype.sqrt=function(){return this.throwIfDisposed(),Cn(this)};re().prototype.square=function(){return this.throwIfDisposed(),vt(this)};re().prototype.squaredDifference=function(e){return this.throwIfDisposed(),Sf(this,e)};re().prototype.squeeze=function(e){return this.throwIfDisposed(),dt(this,e)};re().prototype.stack=function(e,t){this.throwIfDisposed();let n=e instanceof Ke?[this,e]:[this,...e];return Tn(n,t)};re().prototype.step=function(e){return this.throwIfDisposed(),Bu(this,e)};re().prototype.stridedSlice=function(e,t,n,s,r,a,o,i){return this.throwIfDisposed(),k1(this,e,t,n,s,r,a,o,i)};re().prototype.sub=function(e){return this.throwIfDisposed(),xe(this,e)};re().prototype.sum=function(e,t){return this.throwIfDisposed(),ke(this,e,t)};re().prototype.tan=function(){return this.throwIfDisposed(),I1(this)};re().prototype.tanh=function(){return this.throwIfDisposed(),Zi(this)};re().prototype.tile=function(e){return this.throwIfDisposed(),Os(this,e)};re().prototype.toBool=function(){return this.throwIfDisposed(),pe(this,"bool")};re().prototype.toFloat=function(){return this.throwIfDisposed(),pe(this,"float32")};re().prototype.toInt=function(){return this.throwIfDisposed(),pe(this,"int32")};re().prototype.topk=function(e,t){return this.throwIfDisposed(),S1(this,e,t)};re().prototype.transpose=function(e){return this.throwIfDisposed(),et(this,e)};re().prototype.unique=function(e){return this.throwIfDisposed(),Tf(this,e)};re().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),C1(this,e,t)};re().prototype.unstack=function(e){return this.throwIfDisposed(),Wn(this,e)};re().prototype.where=function(e,t){return this.throwIfDisposed(),Pn(e,this,t)};re().prototype.zerosLike=function(){return this.throwIfDisposed(),tt(this)};var zv={};Le(zv,{maxNorm:()=>sz,minMaxNorm:()=>oz,nonNeg:()=>az,unitNorm:()=>rz});var P1;function rn(){return P1==null&&(P1=Tr().epsilon()),P1}function pr(){return"channelsLast"}var sa=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,sa.prototype)}},hr=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,hr.prototype)}},q=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,q.prototype)}},Ve=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Ve.prototype)}},Lv=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Lv.prototype)}};function al(e,t){if(Array.isArray(e)){let n=[];for(let s=0;s<t;s++)n=n.concat(e);return n}else{let n=new Array(t);return n.fill(e),n}}function $r(e,t){if(!e)throw new Lv(t)}function Bv(e,t){let n=0;for(let s of e)s===t&&n++;return n}function as(e){return e.length===1?e[0]:e}function Nt(e){return Array.isArray(e)?e:[e]}function ra(e){let n=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return n[0]!=="_"?n:"private"+n}function ol(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,n)=>n.toUpperCase())}var Ys={};function F1(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function O1(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>O1(t));else{let t=Object.keys(e);for(let n of t){let s=e[n];s!=null&&typeof s=="object"&&(!Array.isArray(s)&&s.type==="ndarray"&&typeof s.value=="number"?e[n]=s.value:O1(s))}}}function Od(e,t={},n={},s="object",r=!1){if(typeof e=="string"){let a=e,o;if(a in n)o=n[a];else if(a in Ys)o=Ys[a];else if(o=t[a],o==null)throw new q(`Unknown ${s}: ${e}. This may be due to one of the following reasons:
|
|
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return o}else{let a=e;if(a.className==null||a.config==null)throw new q(`${s}: Improper config format: ${JSON.stringify(a)}.
|
|
'className' and 'config' must set.`);let o=a.className,i,l;if(o in n?[i,l]=n[o]:o in Ys?[i,l]=Ys.className:o in t&&([i,l]=t[o]),i==null)throw new q(`Unknown ${s}: ${o}. This may be due to one of the following reasons:
|
|
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){let c={};for(let h of Object.keys(Ys))c[h]=Ys[h];for(let h of Object.keys(n))c[h]=n[h];let u=a.config;u.customObjects=c;let d=Object.assign({},Ys);for(let h of Object.keys(n))Ys[h]=n[h];O1(a.config);let p=l(i,a.config,n,r);return Ys=Object.assign({},d),p}else{let c=Object.assign({},Ys);for(let d of Object.keys(n))Ys[d]=n[d];let u=new i(a.config);return Ys=Object.assign({},c),u}}}function ez(e,t){return e<t?-1:e>t?1:0}function Wf(e,t){return-1*ez(e,t)}function Co(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function tz(e){if(e==null)throw new q(`Invalid value in obj: ${JSON.stringify(e)}`);for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function il(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new q(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function M1(e,t,n=0,s=1/0){return $r(n>=0),$r(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every(r=>typeof r===t)}function bn(e,t){Array.isArray(e)?(v.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,s)=>bn(n,`element ${s+1} of ${t}`))):v.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${Wv(e)}.`)}function Wv(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>Wv(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function nz(e,t){let n=v.now(),s;return(...a)=>{let o=v.now();return o-n<t||(n=o,s=e(...a)),s}}function Vv(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function z1(e,t){return j(()=>Cn(ke(L(e,e),t,!0)))}var Md=class extends de.Serializable{getConfig(){return{}}},L1=class extends Md{constructor(e){super();this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return j(()=>{let t=z1(e,this.axis),n=ss(t,0,this.maxValue);return L(e,fe(n,ue(rn(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};L1.className="MaxNorm";de.registerClass(L1);var B1=class extends Md{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return j(()=>fe(e,ue(rn(),z1(e,this.axis))))}getConfig(){return{axis:this.axis}}};B1.className="UnitNorm";de.registerClass(B1);var W1=class extends Md{apply(e){return cr(e)}};W1.className="NonNeg";de.registerClass(W1);var V1=class extends Md{constructor(e){super();this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return j(()=>{let t=z1(e,this.axis),n=ue(L(this.rate,ss(t,this.minValue,this.maxValue)),L(1-this.rate,t));return L(e,fe(n,ue(rn(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};V1.className="MinMaxNorm";de.registerClass(V1);var Uv={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function an(e){return F1(e)}function Gv(e,t={}){return Od(e,de.SerializationMap.getMap().classNameMap,t,"constraint")}function on(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in Uv?Uv[e]:e,config:{}};return Gv(n)}else return e instanceof Md?e:Gv(e)}function sz(e){return new L1(e)}function rz(e){return new B1(e)}function az(){return new W1}function oz(e){return new V1(e)}var Hv={};Le(Hv,{constant:()=>Ez,glorotNormal:()=>Oz,glorotUniform:()=>Fz,heNormal:()=>Mz,heUniform:()=>zz,identity:()=>_z,leCunNormal:()=>Lz,leCunUniform:()=>Bz,ones:()=>Nz,orthogonal:()=>Wz,randomNormal:()=>$z,randomUniform:()=>Rz,truncatedNormal:()=>Dz,varianceScaling:()=>Pz,zeros:()=>Tz});var iz=["channelsFirst","channelsLast"],lz=["nearest","bilinear"],uz=["valid","same","causal"],cz=["max","avg"],dz=["sum","mul","concat","ave"],Vu=new Map;function Xt(e){il(iz,"DataFormat",e)}function pz(e){il(lz,"InterpolationFormat",e)}function Ms(e){il(uz,"PaddingMode",e)}function jv(e){il(cz,"PoolMode",e)}var zd=[],qv="/";function ll(e,t){zd.push(e);try{let n=t();return zd.pop(),n}catch(n){throw zd.pop(),n}}function hz(){return zd.length===0?"":zd.join(qv)+qv}function Xv(e){if(!Zv(e))throw new Error("Not a valid tensor name: '"+e+"'");return hz()+e}function Kv(e){if(!Zv(e))throw new Error("Not a valid tensor name: '"+e+"'");Vu.has(e)||Vu.set(e,0);let t=Vu.get(e);if(Vu.set(e,Vu.get(e)+1),t>0){let n=`${e}_${t}`;return Vu.set(n,1),n}else return e}var fz=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Zv(e){return!!e.match(fz)}function mz(e){return e===parseInt(e.toString(),10)}function To(e,t,n){t==null&&(t=0),n==null&&(n=e.length);let s=1;for(let r=t;r<n;++r)s*=e[r];return s}function Uu(e){if(e.length===0)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let n=0;n<e.length;n++){let s=e[n];s<t&&(t=s)}return t}function No(e){if(e.length===0)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let n=0;n<e.length;n++){let s=e[n];s>t&&(t=s)}return t}function fr(e,t){if(t<e)throw new q(`end (${t}) < begin (${e}) is forbidden.`);let n=[];for(let s=e;s<t;++s)n.push(s);return n}function Vf(e,t){return pe(e,t)}function Ld(e,t=-1){let n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),G(e,n)}function gz(e,t){return j(()=>{if(e.shape.length!==2)throw new q(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let n=Ld(e,1);return H1(n,[1,t,1])})}function yz(e){let t=[To(e.shape)];return G(e,t)}function Az(e){if(e.rank<=1)throw new q(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);let t=[e.shape[0],To(e.shape,1)];return G(e,t)}function ul(e,t,n){return j(()=>{switch(e.rank){case 1:return kf(e,t,n);case 2:return w1(e,[t,0],[n,e.shape[1]]);case 3:return zu(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return $d(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return _e(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return _e(e,[t,0,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new q(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function U1(e,t,n){return j(()=>{switch(e.rank){case 1:return kf(e,t,n);case 2:return w1(e,[0,t],[e.shape[0],n]);case 3:return zu(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return $d(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new q(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Uf(e,t,n,s){return j(()=>{switch(e.rank){case 1:return kf(e,t,n);case 2:switch(s){case 1:return ul(e,t,n);case 2:return U1(e,t,n);default:throw new q(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return ul(e,t,n);case 2:return zu(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return U1(e,t,n);default:throw new q(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return ul(e,t,n);case 2:return $d(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return $d(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return U1(e,t,n);default:throw new q(`The axis is not within the rank of the tensor ${s}`)}default:throw new q(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function G1(e,t=-1){let n;return t<0&&(n=e[0].rank,n!==0?t=n:t=0),t===e[0].rank&&(t=-1),kt(e,t)}function Yv(e,t){switch(e.rank){case 1:return z3([e,t]);case 2:return Ru([e,t],0);case 3:return L3([e,t],0);case 4:return B3([e,t],0);default:throw new q(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function H1(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new q(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Os(e,t)}function Gf(e,t=0,n=1,s,r){return rv(e,t,n,s,r)}function Dr(e,t,n,s){if(e.rank<2||t.rank<2)throw new Ve(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){let r=e.shape.slice(-1)[0],a=t.shape.slice(-2)[0];if(r!==a)throw new Ve(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and y shape = ${t.shape}`)}if(e.rank===2&&t.rank===2){let r=!1,a=!1;return So.matMul({a:e,b:t,transposeA:r,transposeB:a,bias:s?j1(e.rank,s,pr()):null,activation:n})}else{let r=e.shape.slice(),a=r.pop();e=G(e,[-1,a]);let o=t.shape.slice(),i=o.pop(),l=o.pop(),c=[...o,i],u=Array.from({length:t.rank},(f,m)=>m===0?t.rank-2:m<=t.rank-2?m-1:m);t=G(et(t,u),[l,-1]);let d=[...r,...c],p=!1,h=!1;return G(So.matMul({a:e,b:t,transposeA:p,transposeB:h,bias:s?j1(e.rank,s,pr()):null,activation:n}),d)}}function Jv(e,t,n){return j(()=>(Array.isArray(t)?t=Zt(t,"int32"):t=pe(t,"int32"),Ji(e,t,n)))}function Bd(e){return L(e,e)}function j1(e,t,n){let s=t.shape;if(t.rank!==1&&t.rank!==e)throw new q(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(n==="channelsFirst")return s.length===1?G(t,[1,s[0],1,1,1]):G(t,[1,s[3],s[0],s[1],s[2]]);if(n==="channelsLast")return s.length===1?G(t,[1,1,1,1,s[0]]):G(t,[1].concat(s))}else if(e===4){if(n==="channelsFirst")return s.length===1?G(t,[1,s[0],1,1]):G(t,[1,s[2],s[0],s[1]]);if(n==="channelsLast")return s.length===1?G(t,[1,1,1,s[0]]):G(t,[1].concat(s))}else if(e===3){if(n==="channelsFirst")return s.length===1?G(t,[1,s[0],1]):G(t,[1,s[1],s[0]]);if(n==="channelsLast")return s.length===1?G(t,[1,1,s[0]]):G(t,[1].concat(s))}else if(e<3)return t;throw new q(`Unsupported input rank by biasAdd: ${t.rank}`)}function mr(e,t,n){return j(()=>(n==null&&(n=pr()),Xt(n),ue(e,j1(e.rank,t,n))))}function xz(e,t=1){if(t!==1)throw new Ve(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Du(e)}function bz(e){return j(()=>fe(e,ue(Kt(e),1)))}function Qv(e,t,n,s){return j(()=>dv(e,t,n,s))}function vz(e){return j(()=>{let t=ue(.5,L(.2,e));return ss(t,0,1)})}function Wd(e,t,n=!1){return n?e():t()}var wz=["fanIn","fanOut","fanAvg"],kz=["normal","uniform","truncatedNormal"];function Iz(e){il(wz,"FanMode",e)}function Sz(e){il(kz,"Distribution",e)}var Js=class extends de.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},q1=class extends Js{apply(e,t){return qt(e,t)}};q1.className="Zeros";de.registerClass(q1);var Hf=class extends Js{apply(e,t){return bs(e,t)}};Hf.className="Ones";de.registerClass(Hf);var X1=class extends Js{constructor(e){super();if(typeof e!="object")throw new q(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new q(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return j(()=>L(Ee(this.value),bs(e,t)))}getConfig(){return{value:this.value}}};X1.className="Constant";de.registerClass(X1);var K1=class extends Js{constructor(e){super();this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return Ou(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};K1.className="RandomUniform";de.registerClass(K1);var Z1=class extends Js{constructor(e){super();this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Ve(`randomNormal does not support dType ${t}.`);return Gf(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};Z1.className="RandomNormal";de.registerClass(Z1);var Y1=class extends Js{constructor(e){super();this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Ve(`truncatedNormal does not support dType ${t}.`);return Cf(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};Y1.className="TruncatedNormal";de.registerClass(Y1);var J1=class extends Js{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return j(()=>{if(e.length!==2||e[0]!==e[1])throw new q("Identity matrix initializer can only be used for 2D square matrices.");return L(this.gain,l1(e[0]))})}getConfig(){return{gain:this.gain}}};J1.className="Identity";de.registerClass(J1);function Cz(e,t="channelsLast"){let n,s;if(Xt(t),e.length===2)n=e[0],s=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let r=To(e,2);n=e[1]*r,s=e[0]*r}else if(t==="channelsLast"){let r=To(e,0,e.length-2);n=e[e.length-2]*r,s=e[e.length-1]*r}}else{let r=To(e);n=Math.sqrt(r),s=Math.sqrt(r)}return[n,s]}var os=class extends Js{constructor(e){super();if(e.scale<0)throw new q(`scale must be a positive float. Got: ${e.scale}`);this.scale=e.scale==null?1:e.scale,this.mode=e.mode==null?"fanIn":e.mode,Iz(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,Sz(this.distribution),this.seed=e.seed}apply(e,t){let n=Cz(e),s=n[0],r=n[1],a=this.scale;if(this.mode==="fanIn"?a/=Math.max(1,s):this.mode==="fanOut"?a/=Math.max(1,r):a/=Math.max(1,(s+r)/2),this.distribution==="normal"){let o=Math.sqrt(a);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Ve(`${this.getClassName()} does not support dType ${t}.`);return Cf(e,0,o,t,this.seed)}else{let o=Math.sqrt(3*a);return Ou(e,-o,o,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};os.className="VarianceScaling";de.registerClass(os);var jf=class extends os{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return os.className}};jf.className="GlorotUniform";de.registerClass(jf);var qf=class extends os{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return os.className}};qf.className="GlorotNormal";de.registerClass(qf);var Xf=class extends os{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return os.className}};Xf.className="HeNormal";de.registerClass(Xf);var Kf=class extends os{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return os.className}};Kf.className="HeUniform";de.registerClass(Kf);var Zf=class extends os{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return os.className}};Zf.className="LeCunNormal";de.registerClass(Zf);var Yf=class extends os{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return os.className}};Yf.className="LeCunNormal";de.registerClass(Yf);var Q1=class extends Js{constructor(e){super();if(this.DEFAULT_GAIN=1,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,this.seed!=null)throw new Ve("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return j(()=>{if(e.length<2)throw new Ve("Shape must be at least 2D.");e[0]*e[1]>2e3&&console.warn(`Orthogonal initializer is being called on a matrix with more than 2000 (${e[0]*e[1]}) elements: Slowness may result.`);let n=e[0]>e[1]?[e[1],e[0]]:e,s=Gf(n,0,1,"float32"),r=Iv.gramSchmidt(s);return e[0]>e[1]&&(r=et(r)),L(this.gain,r)})}getConfig(){return{gain:this.gain,seed:this.seed}}};Q1.className="Orthogonal";de.registerClass(Q1);var ew={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function tw(e,t={}){return Od(e,de.SerializationMap.getMap().classNameMap,t,"initializer")}function Bt(e){return F1(e)}function Pt(e){if(typeof e=="string"){let t=e in ew?ew[e]:e;if(t==="GlorotNormal")return new qf;if(t==="GlorotUniform")return new jf;if(t==="HeNormal")return new Xf;if(t==="HeUniform")return new Kf;if(t==="LeCunNormal")return new Zf;if(t==="LeCunUniform")return new Yf;{let n={};return n.className=t,n.config={},tw(n)}}else return e instanceof Js?e:tw(e)}function Tz(){return new q1}function Nz(){return new Hf}function Ez(e){return new X1(e)}function Rz(e){return new K1(e)}function $z(e){return new Z1(e)}function Dz(e){return new Y1(e)}function _z(e){return new J1(e)}function Pz(e){return new os(e)}function Fz(e){return new jf(e)}function Oz(e){return new qf(e)}function Mz(e){return new Xf(e)}function zz(e){return new Kf(e)}function Lz(e){return new Zf(e)}function Bz(e){return new Yf(e)}function Wz(e){return new Q1(e)}var nw={};Le(nw,{Layer:()=>rt,RNN:()=>Fr,RNNCell:()=>Zd,activation:()=>kB,add:()=>DB,alphaDropout:()=>mW,average:()=>_B,averagePooling1d:()=>yA,averagePooling2d:()=>AA,averagePooling3d:()=>xA,avgPool1d:()=>VB,avgPool2d:()=>GB,avgPool3d:()=>jB,avgPooling1d:()=>UB,avgPooling2d:()=>HB,avgPooling3d:()=>qB,batchNormalization:()=>LB,bidirectional:()=>iW,concatenate:()=>PB,conv1d:()=>fB,conv2d:()=>mB,conv2dTranspose:()=>gB,conv3d:()=>yB,conv3dTranspose:()=>AB,convLstm2d:()=>sW,convLstm2dCell:()=>rW,cropping2D:()=>bB,dense:()=>IB,depthwiseConv2d:()=>wB,dot:()=>zB,dropout:()=>SB,elu:()=>lB,embedding:()=>$B,flatten:()=>TB,gaussianDropout:()=>fW,gaussianNoise:()=>hW,globalAveragePooling1d:()=>XB,globalAveragePooling2d:()=>KB,globalMaxPool1d:()=>uW,globalMaxPool2d:()=>cW,globalMaxPooling1d:()=>dk,globalMaxPooling2d:()=>pk,gru:()=>YB,gruCell:()=>JB,input:()=>Fw,inputLayer:()=>iB,layerNormalization:()=>BB,leakyReLU:()=>cB,lstm:()=>QB,lstmCell:()=>eW,masking:()=>gW,maxPool1d:()=>dW,maxPool2d:()=>pW,maxPooling1d:()=>hk,maxPooling2d:()=>fk,maxPooling3d:()=>ZB,maximum:()=>FB,minimum:()=>OB,multiply:()=>MB,permute:()=>RB,prelu:()=>dB,reLU:()=>uB,repeatVector:()=>NB,reshape:()=>EB,rnn:()=>aW,separableConv2d:()=>xB,simpleRNN:()=>tW,simpleRNNCell:()=>nW,softmax:()=>pB,spatialDropout1d:()=>CB,stackedRNNCells:()=>oW,thresholdedReLU:()=>hB,timeDistributed:()=>lW,upSampling2d:()=>vB,zeroPadding2d:()=>WB});var Vz=0;function sw(){return Vz++}var Jf={};function Qf(e=""){return e in Jf||(Jf[e]=0),Jf[e]+=1,e+Jf[e].toString()}function ey(e){return Array.isArray(e)&&Array.isArray(e[0])}function em(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Ge(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new q(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function At(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new q(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function tm(e){let t=0;for(let n of e)n.shape.length===0?t+=1:t+=n.shape.reduce((s,r)=>s*r);return t}var rw="Variable",aw=class{constructor(e,t="float32",n=rw,s=!0,r=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=sw(),n=n==null?rw:n,this.originalName=Xv(n),this.name=Kv(this.originalName),this.trainable_=s,this.constraint=r,this.val=ov(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),Uz(this.val,e),this.val.id!==e.id&&(this.val.assign(e),this.constraint!=null&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}};function Uz(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function ty(e){return e.map(t=>t.read())}function ny(e){e.forEach(t=>{t[0].write(t[1])})}var Yt=class{constructor(e){this.dtype=e.dtype,this.shape=e.shape,e.shape!=null?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}},gr=class{constructor(e,t,n,s,r,a,o){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=s,this.callArgs=r,this.outputTensorIndex=o,this.id=sw(),a!=null&&(this.originalName=Xv(a),this.name=Kv(this.originalName)),this.rank=t.length}},Gz=0,nm=class{constructor(e,t){this.callArgs=t,this.id=Gz++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(let n of e.inboundLayers)n!=null&&n.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){let e=[];for(let t of this.inboundLayers)t!=null?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}},Hz=0,rt=class extends de.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=Hz++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){let n=this.getClassName();t=ra(n)+"_"+Qf(n)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let n;if(e.batchInputShape!=null)n=e.batchInputShape;else if(e.inputShape!=null){let r=null;e.batchSize!=null&&(r=e.batchSize),n=[r].concat(e.inputShape)}this.batchInputShape=n;let s=e.dtype;s==null&&(s=e.inputDType),s==null&&(s="float32"),this.dtype=s}e.weights!=null?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(this.inboundNodes.length===0)throw new hr(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new q(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return as(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return as(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new sa(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(this.inboundNodes.length===0)throw new sa(`Layer ${this.name} is not connected, no input to return.`);return as(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new sa(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new sa(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return as(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(e=>e())}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach(t=>t.trainable=e),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(e=>e.trainable):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(e=>!e.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){if(e=Nt(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=Nt(this.inputSpec);if(e.length!==t.length)throw new q(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;n<e.length;n++){let s=e[n],r=t[n];if(r==null)continue;let a=s.rank;if(r.ndim!=null&&a!==r.ndim)throw new q(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${r.ndim}, found ndim=${a}`);if(r.maxNDim!=null&&a>r.maxNDim)throw new q(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${r.maxNDim}, found ndim=${a}`);if(r.minNDim!=null&&a<r.minNDim)throw new q(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${r.minNDim}, found ndim=${a}.`);if(r.dtype!=null&&s.dtype!==r.dtype)throw new q(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${r.dtype}, found dtype=${s.dtype}.`);if(r.axes){let o=s.shape;for(let i in r.axes){let l=Number(i),c=r.axes[i],u=l>=0?o[l]:o[o.length+l];if(c!=null&&[c,null].indexOf(u)===-1)throw new q(`Input ${n} is incompatible with layer ${this.name}: expected axis ${l} of input shape to have value ${c} but got shape ${o}.`)}}if(r.shape!=null)for(let o=0;o<r.shape.length;++o){let i=r.shape[o],l=s.shape[o];if(i!=null&&l!=null&&i!==l)throw new q(`Input ${n} is incompatible with layer ${this.name}: expected shape=${r.shape}, found shape=${s.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){this._callHook!=null&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();let n=Nt(e),s=!0;for(let a of n)if(!(a instanceof gr)){s=!1;break}let r=!0;for(let a of n)if(a instanceof gr){r=!1;break}if(s===r)throw new q("Arguments to apply() must be all SymbolicTensors or all Tensors");return ll(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);let a=[];for(let o of Nt(e))a.push(o.shape);this.build(as(a)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&r&&(this._refCount=1)}if(this.assertInputCompatibility(e),r){let a=this.call(e,t),o=Nt(a),i=[];for(let l of o)n.indexOf(l)!==-1&&(l=l.clone()),i.push(l);if(a=as(i),this.activityRegularizer!=null)throw new Ve("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}else{let a=jz(e),o=this.computeOutputShape(a),i,l=qz(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?a[0]:a),o!=null&&o.length>0&&Array.isArray(o[0])?i=o.map((c,u)=>new gr(l,c,this,Nt(e),t,this.name,u)):i=new gr(l,o,this,Nt(e),t,this.name),this.addInboundNode(e,i,null,null,a,o,t),this._refCount++,this.activityRegularizer!=null)throw new Ve("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape!=null)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach((n,s)=>{n!=null&&e[s]!=null&&e[s]!==n&&(t=!0)}),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new sa(`The layer ${this.name} has never been called and thus has no defined output shape.`);let e=[];for(let t of this.inboundNodes){let n=JSON.stringify(t.outputShapes);e.indexOf(n)===-1&&e.push(n)}if(e.length===1){let t=this.inboundNodes[0].outputShapes;return Array.isArray(t)&&Array.isArray(t[0])&&t.length===1?t[0]:t}else throw new sa(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new hr(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return tm(this.weights)}build(e){this.built=!0}getWeights(e=!1){return ty(e?this.trainableWeights:this.weights)}setWeights(e){j(()=>{let t=this.weights;if(t.length!==e.length)throw new q(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(t.length===0)return;let n=[],s=ty(t);for(let r=0;r<s.length;++r){let a=s[r],o=t[r],i=e[r];if(!v.arraysEqual(a.shape,i.shape))throw new q(`Layer weight shape ${a.shape} not compatible with provided weight shape ${i.shape}`);n.push([o,i])}ny(n)})}addWeight(e,t,n,s,r,a,o){if(this._addedWeightNames.indexOf(e)!==-1)throw new q(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),n==null&&(n="float32"),this.fastWeightInitDuringBuild&&(s=Pt("zeros"));let i=s.apply(t,n),l=new aw(i,n,e,a,o);return i.dispose(),r!=null&&this.addLoss(()=>r.apply(l.read())),a==null&&(a=!0),a?this._trainableWeights.push(l):this._nonTrainableWeights.push(l),l}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=Nt(e),this._losses!==void 0&&this._losses!==null&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(t!=null)if(Array.isArray(t))t.forEach(n=>{if(n!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)});else throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);return null}return t}addInboundNode(e,t,n,s,r,a,o=null){let i=Nt(e);t=Nt(t),n=Nt(n),s=Nt(s),r=em(r),a=em(a);let l=[],c=[],u=[];for(let d of i)l.push(d.sourceLayer),c.push(d.nodeIndex),u.push(d.tensorIndex);new nm({outboundLayer:this,inboundLayers:l,nodeIndices:c,tensorIndices:u,inputTensors:i,outputTensors:t,inputMasks:n,outputMasks:s,inputShapes:r,outputShapes:a},o);for(let d=0;d<t.length;d++)t[d].sourceLayer=this,t[d].nodeIndex=this.inboundNodes.length-1,t[d].tensorIndex=d}getConfig(){let e={name:this.name,trainable:this.trainable};return this.batchInputShape!=null&&(e.batchInputShape=this.batchInputShape),this.dtype!=null&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach(e=>e.dispose()),this.weights.length}assertNotDisposed(){if(this._refCount===0)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(this._refCount===null)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return--this._refCount==0&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}};function jz(e){e=Nt(e);let t=[];for(let n of e)t.push(n.shape);return as(t)}function qz(e){return"float32"}function ow(e,t,n){if((t==null||n!=null&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),t.inboundNodes.length===0)return[e];{let s=t.inboundNodes[n];if(s.inboundLayers.length===0)return s.inputTensors;{let r=[];for(let a=0;a<s.inboundLayers.length;a++){let o=s.inputTensors[a],i=s.inboundLayers[a],l=s.nodeIndices[a],c=ow(o,i,l);for(let u of c)r.indexOf(u)===-1&&r.push(u)}return r}}}var Gu=class extends rt{constructor(e){super({dtype:e.dtype,name:e.name!=null?e.name:Qf("input").toString()});if(e.batchSize==null&&(e.batchSize=null),e.sparse==null&&(e.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=e.sparse,e.inputShape!=null&&e.batchInputShape!=null)throw new q("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let t=e.batchInputShape;if(t==null){if(e.inputShape==null)throw new q("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new q("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");let n=e.dtype||"float32";this.batchInputShape=t,this.dtype=n,this.inputSpec=[{shape:t}];let s=new gr(this.dtype,this.batchInputShape,this,[],{},this.name);s.nodeIndex=0,s.tensorIndex=0,new nm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[s],outputTensors:[s],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new q(`Cannot pass any input to an InputLayer's apply() method. InputLayer name: ${this.name}`)}dispose(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}}getConfig(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}}};Gu.className="InputLayer";de.registerClass(Gu);function iw(e){if(e.batchShape==null&&e.shape==null)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(e.batchShape!=null&&e.shape!=null)throw new q("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;e.shape!=null&&t==null&&(t=[null].concat(e.shape));let n=e.dtype;return n==null&&(n="float32"),new Gu({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}async function Eo(e){if(e==null)return;let t=[],n=[],s=[];for(let r in e){let a=e[r];if(typeof a!="number"){let o=a;t.push(o.data()),n.push(r),s.push(o)}}if(t.length>0){let r=await Promise.all(t);for(let a=0;a<r.length;++a)e[n[a]]=r[a][0];te(s)}}function lw(e){if(e!=null)for(let t in e){let n=e[t];typeof n!="number"&&n.dispose()}}var uw;(function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"})(uw||(uw={}));var Xz=125,Hu=class{constructor(){this.validationData=null}setParams(e){this.params=e}async onEpochBegin(e,t){}async onEpochEnd(e,t){}async onBatchBegin(e,t){}async onBatchEnd(e,t){}async onTrainBegin(e){}async onTrainEnd(e){}setModel(e){}},cw=class{constructor(e,t=10){e==null&&(e=[]),this.callbacks=e,this.queueLength=t}append(e){this.callbacks.push(e)}setParams(e){for(let t of this.callbacks)t.setParams(e)}setModel(e){for(let t of this.callbacks)t.setModel(e)}async onEpochBegin(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onEpochBegin(e,t)}async onEpochEnd(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onEpochEnd(e,t)}async onBatchBegin(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onBatchBegin(e,t)}async onBatchEnd(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onBatchEnd(e,t)}async onTrainBegin(e){e==null&&(e={});for(let t of this.callbacks)await t.onTrainBegin(e)}async onTrainEnd(e){e==null&&(e={});for(let t of this.callbacks)await t.onTrainEnd(e)}},Kz=class extends Hu{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){t==null&&(t={});let n=t.size==null?0:t.size;this.seen+=n;for(let s in t){let r=t[s];if(typeof r=="number")this.totals.hasOwnProperty(s)||(this.totals[s]=0),this.totals[s]=this.totals[s]+r*n;else{let a;s in this.totals?a=this.totals[s]:this.totals[s]=0;let o=j(()=>ue(this.totals[s],L(r,n)));this.totals[s]=o,a!=null&&a.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(let n of this.params.metrics)this.totals[n]!=null&&(typeof this.totals[n]=="number"?t[n]=this.totals[n]/this.seen:j(()=>{let s=L(fe(1,this.seen),this.totals[n]);t[n]=s,this.totals[n].dispose(),An(t[n])}))}},dw=class extends Hu{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(let n in t)this.history[n]==null&&(this.history[n]=[]),this.history[n].push(t[n])}async syncData(){let e=[],t=[],n=[];for(let r in this.history){let a=this.history[r];for(let o=0;o<a.length;++o)if(typeof a[o]!="number"){let i=a[o];e.push(i.data()),t.push(r),n.push(o)}}let s=await Promise.all(e);for(let r=0;r<s.length;++r)this.history[t[r]][n[r]].dispose(),this.history[t[r]][n[r]]=s[r][0]}},pw=class extends Hu{constructor(e,t){super();if(this.currentEpoch=0,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=Xz),this.yieldEvery==="never"&&e.onYield!=null)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");v.isNumber(this.yieldEvery)&&(this.maybeWait=nz(this.maybeWait.bind(this),this.yieldEvery)),this.trainBegin=e.onTrainBegin,this.trainEnd=e.onTrainEnd,this.epochBegin=e.onEpochBegin,this.epochEnd=e.onEpochEnd,this.batchBegin=e.onBatchBegin,this.batchEnd=e.onBatchEnd,this.yield=e.onYield}async maybeWait(e,t,n){let s=[];this.yield!=null&&(await Eo(n),s.push(this.yield(e,t,n))),s.push(Bf()),await Promise.all(s)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await Eo(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){let n=[];this.epochEnd!=null&&(await Eo(t),n.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&n.push(Bf()),await Promise.all(n)}async onBatchBegin(e,t){this.batchBegin!=null&&(await Eo(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){let n=[];this.batchEnd!=null&&(await Eo(t),n.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?n.push(Bf()):v.isNumber(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){this.trainBegin!=null&&(await Eo(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await Eo(e),await this.trainEnd(e))}};function hw(e,t){return e==null&&(e={}),e instanceof Hu?[e]:Array.isArray(e)&&e[0]instanceof Hu?e:Nt(e).map(s=>new pw(s,t))}var Qs=class{constructor(){}static registerCallbackConstructor(e,t){v.assert(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),Qs.checkForDuplicate(t),Qs.constructors[e]==null&&(Qs.constructors[e]=[]),Qs.constructors[e].push(t)}static checkForDuplicate(e){for(let t in Qs.constructors)Qs.constructors[+t].forEach(s=>{if(s===e)throw new q("Duplicate callback constructor.")})}static clear(){Qs.constructors={}}static createCallbacks(e){let t=[];for(let n in Qs.constructors){let s=+n;e>=s&&t.push(...Qs.constructors[s])}return t.map(n=>new n)}};Qs.constructors={};function fw(e,t,n,s,r,a,o,i,l){let c=new dw,u=[new Kz,...Qs.createCallbacks(t)];e!=null&&u.push(...e),u.push(c);let d=new cw(u);return d.setParams({epochs:n,initialEpoch:s,samples:r,steps:a,batchSize:o,verbose:t,doValidation:i,metrics:l}),{callbackList:d,history:c}}function yr(e,t={},n=!1){return Od(e,de.SerializationMap.getMap().classNameMap,t,"layer",n)}function sm(e,t){return j(()=>{e.dtype!=="float32"&&(e=pe(e,"float32"));let n=ke(Bd(e),t,!0),s=_u(n.shape,rn()),r=Cn(Rr(n,s));return fe(e,r)})}function cl(e,t){return j(()=>Lt(Bd(xe(t,e)),-1))}function rm(e,t){return j(()=>Lt(Kt(xe(t,e)),-1))}function ju(e,t){return j(()=>{let n=xe(e,t),s=ss(Kt(e),rn(),Number.MAX_VALUE),r=Kt(fe(n,s));return L(100,Lt(r,-1))})}function Zz(e,t){return j(()=>{let n=ss(t,rn(),Number.MAX_VALUE),s=xs(ue(1,n)),r=ss(e,rn(),Number.MAX_VALUE),a=xs(ue(1,r));return Lt(Bd(xe(s,a)),-1)})}function Yz(e,t){return j(()=>{let n=Rr(0,xe(1,L(e,t)));return Lt(Bd(n),-1)})}function Jz(e,t){return j(()=>{let n=Rr(0,xe(1,L(e,t)));return Lt(n,-1)})}function Qz(e,t){return j(()=>{let n=ke(L(e,t),-1),s=Bn(L(xe(1,e),t),-1);return Rr(0,ue(1,xe(s,n)))})}function eL(e,t){return j(()=>{let n=Math.log(2),s=xe(t,e),r=xe(ue(s,Qi(L(-2,s))),n);return Lt(r,-1)})}function Vd(e,t,n=!1){return j(()=>{if(n)t=nl(t);else{let s=ke(t,t.shape.length-1,!0);t=fe(t,s)}return t=ss(t,rn(),1-rn()),_t(ke(L(pe(e,"float32"),xs(t)),t.shape.length-1))})}function am(e,t,n=!1){return j(()=>{let s=pe(Pu(yz(e)),"int32");t=ss(t,rn(),1-rn());let r=t.shape,a=G(Cu(s,r[r.length-1]),r);return Vd(a,t,n)})}function tL(e,t){if(!v.arraysEqual(e.shape,t.shape))throw new q(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return j(()=>{let n=cr(t),s=_t(Kt(t));return ue(xe(n,L(t,e)),Id(As(s)))})}function om(e,t){return j(()=>{let n;return n=ss(t,rn(),1-rn()),n=xs(fe(n,xe(1,n))),Lt(tL(e,n),-1)})}function nL(e,t){return j(()=>{let n=ss(e,rn(),1),s=ss(t,rn(),1);return ke(L(e,xs(fe(n,s))),-1)})}function sL(e,t){return j(()=>{let n=xs(ue(rn(),t));return Lt(xe(t,L(e,n)),-1)})}function sy(e,t){return j(()=>{let n=sm(e,-1),s=sm(t,-1),r=L(n,s);return _t(ke(r,-1))})}var im={meanSquaredError:cl,meanAbsoluteError:rm,meanAbsolutePercentageError:ju,meanSquaredLogarithmicError:Zz,squaredHinge:Yz,hinge:Jz,categoricalHinge:Qz,logcosh:eL,categoricalCrossentropy:Vd,sparseCategoricalCrossentropy:am,binaryCrossentropy:om,kullbackLeiblerDivergence:nL,poisson:sL,cosineProximity:sy};function ry(e){if(typeof e=="string"){if(e in im)return im[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new q(t)}else return e}function ay(e,t){return j(()=>{let n=L(.5,vs(t)),s=Vf(rs(t,n),e.dtype);return Lt(ys(e,s),-1)})}function oy(e,t){return j(()=>Vf(ys(Fs(e,-1),Fs(t,-1)),"float32"))}function mw(e,t){return j(()=>pe(ke(Ks(ys(e,1),ys(t,1))),"float32"))}function rL(e,t){return j(()=>pe(ke(Ks(ys(e,1),ys(t,0))),"float32"))}function aL(e,t){return j(()=>pe(ke(Ks(ys(e,0),ys(t,1))),"float32"))}function gw(e,t){return j(()=>{let n=mw(e,t),s=aL(e,t),r=ue(n,s);return pe(Pn(rs(r,0),fe(n,r),0),"float32")})}function oL(e,t){return j(()=>{let n=mw(e,t),s=rL(e,t),r=ue(n,s);return pe(Pn(rs(r,0),fe(n,r),0),"float32")})}function yw(e,t){return om(e,t)}function Aw(e,t){return e.rank===t.rank&&(e=dt(e,[e.rank-1])),t=Fs(t,-1),t.dtype!==e.dtype&&(t=pe(t,e.dtype)),pe(ys(e,t),"float32")}var iL=cl,lL=cl,uL=rm,cL=rm,dL=ju,pL=ju,iy=Vd,hL=sy,xw=am,lm={binaryAccuracy:ay,categoricalAccuracy:oy,precision:gw,categoricalCrossentropy:iy,sparseCategoricalCrossentropy:xw,mse:iL,MSE:lL,mae:uL,MAE:cL,mape:dL,MAPE:pL,cosine:hL};function fL(e){if(typeof e=="string"&&e in lm)return lm[e];if(typeof e!="string"&&e!=null)return e;throw new q(`Unknown metric ${e}`)}function um(e){if($r(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let n of Object.keys(im))if(im[n]===e){t=n;break}if(t!==void 0)return t;for(let n of Object.keys(lm))if(lm[n]===e){t=n;break}return t!==void 0?t:e.name}}function mL(e){let t={Adagrad:()=>rl.adagrad(.01),Adadelta:()=>rl.adadelta(1,.95,rn()),Adam:()=>rl.adam(.001,.9,.999,rn()),Adamax:()=>rl.adamax(.002,.9,.999,rn(),0),RMSProp:()=>rl.rmsprop(.001,.9,0,rn()),SGD:()=>rl.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new q(`Unknown Optimizer ${e}`)}var bw=1*1024*1024;function vw(e,t,n=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!ly(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){let s=JSON.stringify(e);s.length>bw&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${s.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${bw}.`)}}function ly(e){if(e===null)return!0;if(typeof e=="object")if(Object.getPrototypeOf(e)===Object.prototype){let t=Object.keys(e);for(let n of t)if(typeof n!="string"||!ly(e[n]))return!1;return!0}else if(Array.isArray(e)){for(let t of e)if(!ly(t))return!1;return!0}else return!1;else{let t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function gL(e,t,n,s=console.log){let r=AL(e),a=["Layer (type)","Output shape","Param #"];r?(t=t||65,n=n||[.45,.85,1]):(t=t||98,n=n||[.33,.55,.67,1]),n[n.length-1]<=1&&(n=n.map(u=>Math.floor(t*u)));let o;if(!r){a.push("Receives inputs"),o=[];for(let u in e.nodesByDepth)o.push(...e.nodesByDepth[u])}s("_".repeat(t)),cm(a,n,s),s("=".repeat(t));let i=e.layers;for(let u=0;u<i.length;++u)r?xL(i[u],n,s):bL(i[u],n,o,s),s((u===i.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();let l=yL(e),c=tm(e.nonTrainableWeights);s(`Total params: ${l+c}`),s(`Trainable params: ${l}`),s(`Non-trainable params: ${c}`),s("_".repeat(t))}function yL(e){let t;return e.collectedTrainableWeights!=null?t=tm(e.collectedTrainableWeights):t=tm(e.trainableWeights),t}function AL(e){let t=!0,n=[],s=[];for(let r in e.nodesByDepth)n.push(e.nodesByDepth[r]);for(let r of n){if(r.length>1||r.length===1&&r[0].inboundLayers.length>1){t=!1;break}s.push(...r)}if(t)for(let r of e.layers){let a=!1;for(let o of r.inboundNodes)if(s.indexOf(o)!==-1)if(a){t=!1;break}else a=!0;if(!t)break}return t}function cm(e,t,n=console.log){let s="";for(let r=0;r<e.length;++r)r>0&&(s=s.slice(0,s.length-1)+" "),s+=e[r],s=s.slice(0,t[r]),s+=" ".repeat(t[r]-s.length);n(s)}function xL(e,t,n){let s;try{s=JSON.stringify(e.outputShape)}catch(i){s="multiple"}let r=e.name,a=e.getClassName(),o=[`${r} (${a})`,s,e.countParams().toString()];cm(o,t,n)}function bL(e,t,n,s){let r;try{r=JSON.stringify(e.outputShape)}catch(u){r="multiple"}let a=[];for(let u of e.inboundNodes)if(!(n!=null&&n.length>0&&n.indexOf(u)===-1))for(let d=0;d<u.inboundLayers.length;++d){let p=u.inboundLayers[d].name,h=u.nodeIndices[d],f=u.tensorIndices[d];a.push(`${p}[${h}][${f}]`)}let o=e.name,i=e.getClassName(),l=a.length===0?"":a[0],c=[`${o} (${i})`,r,e.countParams().toString(),l];cm(c,t,s);for(let u=1;u<a.length;++u)cm(["","","",a[u]],t,s)}function ww(e,t,n){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof n=="string"}function Ud(e,t){if(e===null)return null;if(typeof e=="string")return ol(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let n=[],s=e.length;for(let r=0;r<s;++r){let a=e[r];ww(t,r,a)?n.push(a):n.push(Ud(a,t))}return n}else{let n={};for(let s of Object.keys(e)){let r=e[s];if(s==="name"&&typeof r=="string")n[s]=r;else{let a=ol(s);n[a]=Ud(r,a)}}return n}}function uy(e,t){if(e==null)return null;if(typeof e=="string")return ra(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let n=[],s=e.length;for(let r=0;r<s;++r){let a=e[r];ww(t,r,a)?n.push(a):n.push(uy(a,t))}return n}else{let n={};for(let s of Object.keys(e)){let r=e[s],a=ra(s);(s==="name"||s==="className")&&typeof r=="string"?n[a]=r:n[a]=uy(r,s)}return n}}var cy="3.9.0";function vL(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return pe(t,e.dtype)}catch(n){throw new q(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}var dl=class{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof dl)for(let t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(e==null)return;for(let t of e)this.add(t.key,t.value)}}add(e,t,n){if(this.id2Value[e.id]==null)this.id2Value[e.id]=vL(e,t),this.name2Id[e.name]=e.id,n!=null&&(this.id2Mask[e.id]=n);else throw new q(`Duplicate key: name=${e.name}, id=${e.id}`);return this}addFeed(e){this.add(e.key,e.value)}hasKey(e){return this.id2Value[e.id]!=null}names(){return Object.keys(this.name2Id)}getValue(e){if(e instanceof gr){if(this.id2Value[e.id]==null)throw new q(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{let t=this.name2Id[e];if(t==null)throw new q(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof gr){if(this.id2Value[e.id]==null)throw new q(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{let t=this.name2Id[e];if(t==null)throw new q(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&te(this.id2Mask)}},dy={},kw={};function Gd(e,t,n,s){let r=n==null?!1:n.training,a=Array.isArray(e),o=a?e:[e],i=o.map(f=>f.name),l=[],c=t.names();for(let f of i)c.indexOf(f)!==-1?l.push(t.getValue(f)):l.push(null);s!=null&&(s.maxNumTensors=-1/0,s.minNumTensors=1/0);let u=i.join(",")+"|"+t.names().join(","),d,p;if(dy[u]==null){let f=wL(o,t);d=f.sorted,p=f.recipientCounts,dy[u]=d,kw[u]=p}d=dy[u],p={},r||Object.assign(p,kw[u]);let h=new dl(t);for(let f=0;f<d.length;++f){if(s!=null){let $=Qh().numTensors;$>s.maxNumTensors&&(s.maxNumTensors=$),$<s.minNumTensors&&(s.minNumTensors=$)}let m=d[f],g=m.sourceLayer;if(g instanceof Gu)continue;let y=[],A=[],x=[],b=!1;for(let $ of m.inputs){let F=h.getValue($),R=h.getMask($);y.push(F),A.push(R),R!=null&&(b=!0),r||(p[$.name]--,p[$.name]===0&&!t.hasKey($)&&i.indexOf($.name)===-1&&!F.isDisposed&&$.sourceLayer.stateful!==!0&&x.push(F))}b&&(n=n||{},n.mask=A[0]);let w=Nt(g.apply(y,n)),k=null;g.supportsMasking&&(k=g.computeMask(y,A));let S=IL(m),N=Array.isArray(S)?S:[S];for(let $=0;$<N.length;++$){h.hasKey(N[$])||h.add(N[$],w[$],Array.isArray(k)?k[0]:k);let F=i.indexOf(N[$].name);F!==-1&&(l[F]=w[$])}r||te(x)}return h.disposeMasks(),a?l:l[0]}function wL(e,t){v.assert(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let n=[],s={};if(e.length===1){let r=Iw(e[0],t);n=r.sorted,s=r.recipientMap}else{let r=new Set;for(let a of e){let{sorted:o,recipientMap:i}=Iw(a,t);for(let l of o)r.has(l.name)||(n.push(l),r.add(l.name));for(let l in i)s[l]==null&&(s[l]=new Set),i[l].forEach(c=>s[l].add(c))}}return{sorted:n,recipientCounts:kL(s)}}function kL(e){let t={};for(let n in e)t[n]=e[n].size;return t}function Iw(e,t){let n=new Set,s=[],r={};for(let i of t.names())n.add(i);let a=[],o=[];for(a.push(e);a.length>0;){let i=a[a.length-1];if(n.has(i.name)){a.pop();continue}let l=o[o.length-1]===a.length-1;if(i.inputs.length===0||l)a.pop(),s.push(i),n.add(i.name),l&&o.pop();else{o.push(a.length-1);for(let c of i.inputs)r[c.name]==null&&(r[c.name]=new Set),r[c.name].add(i.name),!n.has(c.name)&&a.push(c)}}return{sorted:s,recipientMap:r}}function IL(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let n=null;for(let s=0;s<e.sourceLayer.inboundNodes.length;++s)for(let r of e.sourceLayer.inboundNodes[s].outputTensors)if(r.id===e.id){n=s;break}t=e.sourceLayer.getOutputAt(n)}return t}var _r=class extends rt{constructor(e){super({});if(this.containerNodes=new Set,this.name=e.name,this.name==null){let y=this.getClassName().toLowerCase();this.name=Qf(y)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],Co(this.inputs).length!==this.inputs.length)throw new q(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(y=>y.name)}`);Co(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(y=>y.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(let y of this.outputs){let A=y.sourceLayer,x=y.nodeIndex,b=y.tensorIndex;this.outputLayers.push(A),this.outputLayersNodeIndices.push(x),this.outputLayersTensorIndices.push(b)}for(let y of this.inputs){let A=y.sourceLayer,x=y.nodeIndex,b=y.tensorIndex;$r(x===0,"input layer has >1 nodes"),$r(b===0,"input layer has >1 tensors"),this.inputLayers.push(A),this.inputLayersNodeIndices.push(x),this.inputLayersTensorIndices.push(b)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let y=0;y<this.inputLayers.length;y++){let A=this.inputLayers[y];if(!(A instanceof Gu))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${y} (0-based) originates from layer type ${A.getClassName()}.`);this.inputNames.push(A.name),this.feedInputShapes.push(A.batchInputShape),this.feedInputNames.push(A.name)}for(let y of this.outputLayers)this.outputNames.push(y.name);this.internalInputShapes=this.inputs.map(y=>y.shape),this.internalOutputShapes=this.outputs.map(y=>y.shape);let t={},n={},s={},r={},a={},o=[],i=(y,A,x,b,w,k)=>{(b==null||w==null||k==null)&&(b=y.sourceLayer,w=y.nodeIndex,k=y.tensorIndex);let S=b.inboundNodes[w];if(x.indexOf(S)!==-1)throw new hr(`The tensor ${y.name} at layer "${b.name}" is part of a cycle.`);if(A.indexOf(S)!==-1)return;this.containerNodes.add(_r.nodeKey(b,w)),b.id in a||(a[b.id]=Object.keys(a).length),x.indexOf(S)===-1&&x.push(S);let N=S.inboundLayers.length;for(let $=0;$<N;$++){let F=S.inputTensors[$],R=S.inboundLayers[$],D=S.nodeIndices[$],T=S.tensorIndices[$];i(F,A,x,R,D,T)}for(A.push(S);x.indexOf(S)>=0;)x.splice(x.indexOf(S),1);o.push(S)},l=[],c=[];for(let y of this.outputs)i(y,l,c);let u=o.slice().reverse();for(let y of u){n[y.id]=y,y.id in t||(t[y.id]=0);let A=t[y.id],x=s[y.outboundLayer.id]==null?0:s[y.outboundLayer.id];A=Math.max(A,x),s[y.outboundLayer.id]=A,r[y.outboundLayer.id]=y.outboundLayer,t[y.id]=A;for(let b=0;b<y.inboundLayers.length;b++){let w=y.inboundLayers[b],k=y.nodeIndices[b],S=w.inboundNodes[k],N=t[S.id]==null?0:t[S.id];t[S.id]=Math.max(A+1,N),n[S.id]=S}}let d={};for(let y in t){let A=t[y];A in d||(d[A]=[]),d[A].push(n[y])}let p={};for(let y in s){let A=s[y];A in p||(p[A]=[]),p[A].push(r[y])}let h=Object.keys(p).map(y=>parseInt(y,10)).sort(Wf);this.layers=[];for(let y of h){let A=p[y];A.sort((x,b)=>{let w=a[x.id],k=a[b.id];return w<k?-1:w>k?1:0});for(let x of A)x instanceof _r&&this.internalContainerRefs.push(x),this.layers.push(x)}this.layersByDepth=p,h=Object.keys(d).map(y=>parseInt(y,10)).sort(Wf);let f=this.inputs.slice(),m=[];for(let y of h)for(let A of d[y]){let x=A.outboundLayer;if(x!=null){for(let b of A.inputTensors)if(f.indexOf(b)===-1)throw new hr(`Graph disconnected: cannot obtain value for tensor ${b} at layer "${x.name}". The following previous layers were accessed without issue: ${m}`);for(let b of A.outputTensors)f.push(b);m.push(x.name)}}this.nodesByDepth=d;let g=this.layers.map(y=>y.name);for(let y of g){let A=g.filter(x=>x===y).length;if(A!==1)throw new hr(`The name "${y}" is used ${A} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new nm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(y=>null),outputMasks:this.outputs.map(y=>null),inputShapes:this.inputs.map(y=>y.shape),outputShapes:this.outputs.map(y=>y.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();let e={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount==0){for(let t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(let t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach(t=>{t._trainableWeights.forEach(n=>n.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new q("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(let t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.layers)t.push(...n.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){let n={},s=0;for(let a of this.layers)for(let o of a.weights){if(n[o.originalName]!=null)throw new q(`Duplicate weight name: ${o.originalName}`);n[o.originalName]=o,s++}let r=[];for(let a in e){let o=a;if(n[a]==null){let i=a.split("/");o=i.slice(0,-2).concat([i[i.length-1]]).join("/")}if(n[o]!=null)r.push([n[o],e[a]]);else if(t)throw new q(`Provided weight data has no target variable: ${a}`);delete n[o]}if(t){let a=[];for(let o in n)a.push(o);if(a.length>0)throw new q(`${a.length} of ${s} weights are not set: ${a}`)}ny(r)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${cy}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let n=uy(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return j(()=>{e=Nt(e);let n=new dl;for(let s=0;s<this.inputs.length;++s)n.add(this.inputs[s],e[s]);return Gd(this.outputs,n,t)})}computeMask(e,t){return j(()=>{e=Nt(e);let n;return t==null?n=al(null,e.length):n=Nt(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){let t=em(e);if(t.length!==this.inputLayers.length)throw new q(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let n={};for(let o=0;o<t.length;o++){let i=this.inputLayers[o],l=t[o],c=i.name+"_0_0";n[c]=l}let s=Object.keys(this.nodesByDepth).map(o=>parseInt(o,10)).sort(Wf);if(s.length>1)for(let o of s){let i=this.nodesByDepth[o];for(let l of i){let c=l.outboundLayer;if(this.inputLayers.map(f=>f.id).indexOf(c.id)!==-1)continue;let u=[];for(let f=0;f<l.inboundLayers.length;f++){let m=l.inboundLayers[f],g=l.nodeIndices[f],y=l.tensorIndices[f],A=`${m.name}_${g}_${y}`,x=n[A];u.push(x)}let d=c.computeOutputShape(as(u)),p=em(d),h=c.inboundNodes.indexOf(l);for(let f=0;f<p.length;f++){let m=`${c.name}_${h}_${f}`;n[m]=p[f]}}}let r=[],a=[];for(let o=0;o<this.outputLayers.length;o++){let i=this.outputLayers[o],l=this.outputLayersNodeIndices[o],c=this.outputLayersTensorIndices[o],u=`${i.name}_${l}_${c}`;a.push(u)}for(let o=0;o<a.length;o++){let i=a[o];$r(i in n),r.push(n[i])}return as(r)}runInternalGraph(e,t){t==null&&(t=al(null,e.length));let n={};for(let i=0;i<this.inputs.length;++i){let l=this.inputs[i],c=e[i],u=t[i];n[l.id]=[c,u]}let s=Object.keys(this.nodesByDepth).map(i=>parseInt(i,10)).sort(Wf);for(let i of s){let l=this.nodesByDepth[i];for(let c of l){let u=c.outboundLayer,d=c.inputTensors,p=c.outputTensors,h=new Array;for(let f of d)f.id in n&&h.push(n[f.id]);if(h.length===d.length){let f={},m,g,y,A;if(c.callArgs!=null&&(f=c.callArgs),h.length===1){let[x,b]=h[0];f.mask==null&&(f.mask=b),y=Nt(u.call(x,f)),A=Nt(u.computeMask(x,b)),m=[x],g=[b]}else m=h.map(x=>x[0]),g=h.map(x=>x[1]),f.mask==null&&(f.mask=g),y=Nt(u.call(m,f)),A=Nt(u.computeMask(m,g));if(u.activityRegularizer)throw new Ve("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let x=0;x<p.length;++x){let b=p[x],w=y[x],k=A[x];n[b.id]=[w,k]}}}}let r=[],a=[],o=[];for(let i of this.outputs){$r(i.id in n,`Could not compute output ${i.name} : ${i.id}`);let[l,c]=n[i.id];o.push(l.shape),r.push(l),a.push(c)}return[r,a,o]}buildNodeConversionMap(e){let t={},n;for(let s of this.layers){n=s instanceof _r?1:0;for(let r=0;r<s.inboundNodes.length;r++){let a=_r.nodeKey(s,r);this.containerNodes.has(a)&&(t[a]=n,n+=1)}}return t}getLayer(e,t){if(t!=null){if(this.layers.length<=t)throw new q(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);return this.layers[t]}else if(e==null)throw new q("Provide either a layer name or layer index");for(let n of this.layers)if(n.name===e)return n;throw new q(`No such layer: ${e}`)}calculateLosses(){return j(()=>{let e=[];for(let t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){let s=_r.nodeKey(t,n);this.containerNodes.has(s)&&e.push(...t.calculateLosses())}return e})}getConfig(){let e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(let a of this.layers){let o=a.getClassName(),i=a.getConfig(),l=[];for(let u=0;u<a.inboundNodes.length;u++){let d=a.inboundNodes[u],p=_r.nodeKey(a,u),h={};if(this.containerNodes.has(p)){if(d.callArgs)try{JSON.stringify(d.callArgs),h=d.callArgs}catch(f){console.warn(`Layer ${a.name} was passed non-serializable keyword arguments: ${d.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),h={}}if(d.inboundLayers.length>0){let f=[];for(let m=0;m<d.inboundLayers.length;m++){let g=d.inboundLayers[m],y=d.nodeIndices[m],A=d.tensorIndices[m],x=_r.nodeKey(g,y),b=t[x];b==null&&(b=0),f.push([g.name,b,A,h])}l.push(f)}}}let c={};c.name=a.name,c.className=o,c.config=i,c.inboundNodes=l,n.push(c)}e.layers=n;let s=[];for(let a=0;a<this.inputLayers.length;a++){let o=this.inputLayers[a],i=this.inputLayersNodeIndices[a],l=_r.nodeKey(o,i);if(!this.containerNodes.has(l))continue;let c=t[l];c==null&&(c=0);let u=this.inputLayersTensorIndices[a];s.push([o.name,c,u])}e.inputLayers=s;let r=[];for(let a=0;a<this.outputLayers.length;a++){let o=this.outputLayers[a],i=this.outputLayersNodeIndices[a],l=_r.nodeKey(o,i);if(!this.containerNodes.has(l))continue;let c=t[l];c==null&&(c=0);let u=this.outputLayersTensorIndices[a];r.push([o.name,c,u])}return e.outputLayers=r,e}static fromConfig(e,t,n={},s=!1){let r={},a={};function o(m,g){m.name in a?a[m.name].push(g):a[m.name]=[g]}function i(m,g){let y=[],A;for(let x of g){let b=x[0],w=x[1],k=x[2];if(A=x[3]==null?{}:x[3],!(b in r)){o(m,g);return}let S=r[b];if(S.inboundNodes.length<=w){o(m,g);return}let N=S.inboundNodes[w];y.push(N.outputTensors[k])}y.length>0&&m.apply(as(y),A)}function l(m){let g=m.name,y=yr(m,t.customObjects!=null?t.customObjects:{});y.setFastWeightInitDuringBuild(s),r[g]=y,m.inboundNodes.forEach(x=>{if(!(x instanceof Array))throw new q(`Corrupted configuration, expected array for nodeData: ${x}`);o(y,x)})}let c=t.name,u=t.layers;for(let m of u)l(m);for(;!tz(a);)for(let m of u){let g=r[m.name];if(g.name in a){let y=a[g.name];delete a[g.name];for(let A of y)i(g,A)}}let d=[],p=[],h=t.inputLayers;for(let m of h){let g=m[0],y=m[1],A=m[2];$r(g in r);let b=r[g].inboundNodes[y].outputTensors;d.push(b[A])}let f=t.outputLayers;for(let m of f){let g=m[0],y=m[1],A=m[2];$r(g in r);let b=r[g].inboundNodes[y].outputTensors;p.push(b[A])}return new e({inputs:d,outputs:p,name:c})}get stateful(){if(this._stateful)throw new q("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(let e of this.layers)if(e.stateful)return!0;return!1}resetStates(){j(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}};function SL(e,t,n){let s=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(r=>null);if(s===1)return Array.isArray(e)&&e.length===1?e:typeof e=="object"&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==s)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);return e}else if(typeof e=="object"&&Object.keys(e).length>0&&typeof e[Object.keys(e)[0]]=="object"){let r=[];return t.forEach(a=>{a in e?r.push(e[a]):r.push(null)}),r}else throw new Error(`The model has multiple (${s}) outputs, so ${n} must be either an array with ${s} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}function Sw(e,t){return SL(e,t,"classWeight")}async function Cw(e,t,n,s){if(t!=null||s!=null)throw new Error("Support sampleWeight is not implemented yet");if(n!=null){let r=j(()=>{if(e.shape.length===1)return ir(e);if(e.shape.length===2){if(e.shape[1]>1)return Fs(e,1);if(e.shape[1]===1)return G(e,[e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),a=Array.from(await r.data());te(r);let o=[];return a.forEach(i=>{if(n[i]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${i} exists in the data but not in classWeight`);o.push(n[i])}),Zt(o,"float32")}else return null}function CL(e,t){return L(e,t)}var TL=32;function Tw(e,t){let n,s,r=t;n=r.xs,s=r.ys,v.assert(n!=null&&s!=null,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`);let a=Nw("input",e.inputNames,n),o=Nw("output",e.outputNames,s),i=a[0].shape[0];v.assert(a.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${a.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`),v.assert(o.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${o.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let l=0;l<a.length;l++)v.assert(a[l].shape[0]===i,()=>`Batch size mismatch: input ${e.inputNames[l]} has ${a[l].shape[0]}; expected ${i} based on input ${e.inputNames[0]}.`);for(let l=0;l<o.length;l++)v.assert(o[l].shape[0]===i,()=>`Batch size mismatch: output ${e.outputNames[l]} has ${o[l].shape[0]}; expected ${i} based on input ${e.inputNames[0]}.`);return{xs:a,ys:o}}function Nw(e,t,n){if(n instanceof Ke)return[n];if(Array.isArray(n))return v.assert(n.length===t.length,()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),n;{let s=[];for(let r of t){if(n[r]==null)throw new q(`The feature data generated by the dataset lacks the required ${e} key '${r}'.`);s.push(n[r])}return s}}function NL(e){if(e.length===3)throw new Ve("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function EL(e,t,n){let s=n.batchesPerEpoch!=null;if(v.assert(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),v.assert(n!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),v.assert(n.epochs!=null&&n.epochs>0&&Number.isInteger(n.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`),v.assert(!s||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`),v.assert(n.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{let r=n.validationData!=null,a,o;if(r)if(Ew(n.validationData))v.assert(n.validationBatches==null||n.validationBatches>0&&Number.isInteger(n.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`);else{let g=NL(n.validationData);a=g.xs,o=g.ys}let i=e.makeTrainFunction(),l=e.getDedupedMetricsNames(),c;r?c=l.slice().concat(l.map(g=>"val_"+g)):c=l.slice();let u=hw(n.callbacks,n.yieldEvery),d=n.verbose==null?1:n.verbose,{callbackList:p,history:h}=fw(u,d,n.epochs,null,null,RL(t,n),null,r,c);p.setModel(e),e.history=h,await p.onTrainBegin(),e.stopTraining_=!1;let f=n.initialEpoch==null?0:n.initialEpoch,m=await t.iterator();for(;f<n.epochs;){let g={};await p.onEpochBegin(f);let y=0,A=0;for(s||(m=await t.iterator());s?y<n.batchesPerEpoch:!0;){let x=await m.next();if(s&&x.done){console.warn(`You provided \`batchesPerEpoch\` as ${n.batchesPerEpoch}, but your dataset iterator ran out of data after ${y} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${n.batchesPerEpoch*n.epochs} batches). You may need to use the repeat() function when building your dataset.`);break}if(x.value!=null){let{xs:b,ys:w}=Tw(e,x.value),k={};k.batch=A,k.size=b[0].shape[0],await p.onBatchBegin(A,k);let S=[];if(n.classWeight!=null){let F=Sw(n.classWeight,e.outputNames);for(let R=0;R<F.length;++R)S.push(await Cw(w[R],null,F[R]))}let N=b.concat(w).concat(S),$=i(N);te(N);for(let F=0;F<l.length;++F){let R=l[F],D=$[F];k[R]=D,An(D)}await p.onBatchEnd(A,k),lw(k),A++,y++}if(s?y>=n.batchesPerEpoch:x.done){if(r){let b;Ew(n.validationData)?b=Nt(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):b=Nt(e.evaluate(a,o,{batchSize:n.validationBatchSize==null?TL:n.validationBatchSize,verbose:0}));for(let w=0;w<e.metricsNames.length;++w)g[`val_${e.metricsNames[w]}`]=b[w]}break}if(e.stopTraining_)break}if(await p.onEpochEnd(f,g),f++,e.stopTraining_)break}return await p.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function RL(e,t){let n=null;return t.batchesPerEpoch!=null?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size),n}function Ew(e){return typeof e.iterator=="function"}function $L(e){return typeof e.next=="function"}async function DL(e,t,n){n=n||{};let s=n.batches!=null,r=e.testFunction,a=[];if(n.verbose>0)throw new Ve("Verbose mode is not implemented yet.");v.assert(!s||n.batches>0&&Number.isInteger(n.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`);let o=$L(t)?t:await t.iterator(),i=0,l=0;for(;s?l<n.batches:!0;){let c=await o.next();if(a=j(()=>{if(c.value){let{xs:u,ys:d}=Tw(e,c.value),p=u.concat(d),h=j(()=>r(p));if(te(p),l===0)for(let m=0;m<h.length;++m)a.push(Ee(0));let f=p[0].shape[0];for(let m=0;m<h.length;++m){let g=h[m],y=a[m];a[m]=j(()=>ue(a[m],L(f,g))),l>0&&te(y)}te(h),i+=f,++l}return a}),c.done){s&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let c=0;c<a.length;++c){let u=a[c];a[c]=fe(a[c],i),te(u)}return as(a)}function py(e){v.assert(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function Hd(e,t,n){return e==null?[null]:Array.isArray(e)?e.map(s=>ul(s,t,n-t)):ul(e,t,n-t)}function hy(e,t){return j(()=>e==null?null:Array.isArray(e)?e.map(n=>hy(n,t)):Jv(e,t.dtype==="int32"?t:pe(t,"int32")))}function fy(e,t){let n=[],s=0,r=null;for(;s<e;)r=s+t,r>=e&&(r=e),n.push([s,r]),s=r;return n}async function _L(e,t,n,s,r,a,o,i,l,c,u,d,p,h,f){r==null&&(r=32),a==null&&(a=1),u==null&&(u=!0),p==null&&(p=0);let m=!1;if(l!=null&&c!=null&&(m=!0),f!=null&&(m=!0,h==null))throw new q("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let g=e.checkNumSamples(n,r,h,"steps_per_epoch"),y;g!=null&&(y=fr(0,g)),o==null&&(o=1);let{callbackList:A,history:x}=fw(i,o,a,p,g,h,r,m,d);A.setModel(e),e.history=x,await A.onTrainBegin(),e.stopTraining_=!1;for(let b=p;b<a;++b){await A.onEpochBegin(b);let w={};if(h!=null)throw new Ve("stepsPerEpoch mode is not implemented yet.");{if(u==="batch")throw new Ve("batch shuffling is not implemneted yet");u&&v.shuffle(y);let k=Zt(y),S=fy(g,r);for(let N=0;N<S.length;++N){let $={};if(await A.onBatchBegin(N,$),j(()=>{let F=S[N][0],R=S[N][1],D=ul(k,F,R-F);$.batch=N,$.size=R-F;let T=hy(n,D),O=t(T);for(let B=0;B<s.length;++B){let H=s[B],z=O[B];$[H]=z,An(z)}if(N===S.length-1&&m){let B=e.testLoop(l,c,r);for(let H=0;H<s.length;++H){let z=s[H],X=B[H];An(X),w["val_"+z]=X}}}),await A.onBatchEnd(N,$),lw($),e.stopTraining_)break}k.dispose()}if(await A.onEpochEnd(b,w),e.stopTraining_)break}return await A.onTrainEnd(),await e.history.syncData(),e.history}async function PL(e,t,n,s={}){if(e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;let r,a,o,i,l,c,u;try{let d=s.batchSize==null?32:s.batchSize;py(d);let p=!1,h=await e.standardizeUserData(t,n,s.sampleWeight,s.classWeight,p,d);r=h[0],a=h[1],u=h[2];let f=!1,m;if(s.validationData!=null&&s.validationData.length>0){if(f=!0,s.validationData.length===2)o=s.validationData[0],i=s.validationData[1];else throw s.validationData.length===3?new Ve("validationData including sample weights is not supported yet."):new q(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${s.validationData} is invalid.`);let S=!0,N=await e.standardizeUserData(o,i,null,null,S,d);l=N[0],c=N[1],m=l.concat(c)}else if(s.validationSplit!=null&&s.validationSplit>0&&s.validationSplit<1){f=!0;let S=Math.floor(r[0].shape[0]*(1-s.validationSplit)),N=r[0].shape[0];l=Hd(r,S,N),r=Hd(r,0,S),c=Hd(a,S,N),a=Hd(a,0,S),m=l.concat(c)}else s.validationSteps!=null&&(f=!0);let g=r.concat(a).concat(u);e.checkTrainableWeightsConsistency();let y=e.makeTrainFunction(),A=e.getDedupedMetricsNames(),x,b;f?(e.makeTestFunction(),x=e.testFunction,b=A.slice().concat(A.map(S=>"val_"+S))):(x=null,m=[],b=A.slice());let w=hw(s.callbacks,s.yieldEvery);return await _L(e,y,g,A,d,s.epochs,s.verbose,w,x,m,s.shuffle,b,s.initialEpoch,null,null)}finally{e.isTraining=!1,pl(r,t),pl(a,n),pl(l,o),pl(c,i),u!=null&&te(u)}}function Rw(e){let t=[];e instanceof Ke&&(e=[e]);for(let n=0;n<e.length;++n){let s=e[n];if(s.rank===1)t.push(Ld(s,1));else{if(s.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(s)}}return t}function pl(e,t){if(e==null)return;let n=[];if(t instanceof Ke)n.push(t.id);else if(Array.isArray(t))t.forEach(r=>n.push(r.id));else if(t!=null)for(let r in t){let a=t[r];n.push(a.id)}let s=[];if(e instanceof Ke)n.indexOf(e.id)===-1&&s.push(e);else if(Array.isArray(e))e.forEach(r=>{n.indexOf(r.id)===-1&&s.push(r)});else if(e!=null)for(let r in e){let a=e[r];n.indexOf(a.id)===-1&&s.push(a)}s.forEach(r=>{r.isDisposed||r.dispose()})}function FL(e){return e instanceof Ke}function my(e){return Array.isArray(e)}function $w(e){return!FL(e)&&!my(e)}function Dw(e,t,n,s=!0,r=""){if(t==null||t.length===0){if(e!=null){let o=!1;if(my(e)&&e.length>0)o=!0;else if($w(e)){for(let i in e)if(e.hasOwnProperty(i)){o=!0;break}}else o=!0;if(o)throw new q(`Error when checking model ${r} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(o=>null);let a;if($w(e)){e=e,a=[];for(let o of t){if(e[o]==null)throw new q(`No data provided for "${o}". Need data for each key in: ${t}`);a.push(e[o])}}else if(my(e)){if(e=e,e.length!==t.length)throw new q(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);a=e}else{if(e=e,t.length>1)throw new q(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);a=[e]}if(a=Rw(a),n!=null)for(let o=0;o<t.length;++o){if(n[o]==null)continue;let i=a[o];if(i.shape.length!==n[o].length)throw new q(`Error when checking ${r}: expected ${t[o]} to have ${n[o].length} dimension(s). but got array with shape ${i.shape}`);for(let l=0;l<n[o].length;++l){if(l===0&&!s)continue;let c=i.shape[l],u=n[o][l];if(u!=null&&u>=0&&c!==u)throw new q(`${r} expected a batch of elements where each example has shape [${n[o].slice(1,n[o].length)}] (i.e.,tensor shape [*,${n[o].slice(1,n[o].length)}]) but the ${r} received an input with ${i.shape[0]} examples, each with shape [${i.shape.slice(1,i.shape.length)}] (tensor shape [${i.shape}])`)}}return a}function OL(e,t,n){let s=Co(e.map(a=>a.shape[0]));s.sort();let r=Co(t.map(a=>a.shape[0]));if(r.sort(),s.length>1)throw new q(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(a=>a.shape))}`);if(r.length>1)throw new q(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(a=>a.shape))}`);if(s.length>0&&r.length>0&&!v.arraysEqual(s,r))throw new q(`Input Tensors should have the same number of samples as target Tensors. Found ${s[0]} input sample(s) and ${r[0]} target sample(s).`)}function ML(e,t,n){let s=[cl,om,Vd];for(let r=0;r<e.length;++r){let a=e[r],o=t[r],i=n[r];if(o!=null){if(o===Vd&&a.shape[a.shape.length-1]===1)throw new q(`You are passing a target array of shape ${a.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(s.indexOf(o)!==-1){let l=a.shape.slice(1),c=i.slice(1);for(let u=0;u<l.length;++u){let d=l[u],p=c[u];if(p!=null&&d!==p)throw new q(`A target Tensor with shape ${a.shape} was passed for an output of shape ${i}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}function _w(e,t,n,s=!0,r=""){let a;if(Array.isArray(e)){if(e.length!==t.length)throw new q(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);a=e}else{if(t.length>1)throw new q(`The model expects ${t.length} ${r} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);a=[e]}if(n!=null)for(let o=0;o<t.length;++o){if(n[o]==null)continue;let i=a[o];if(i.shape.length!==n[o].length)throw new q(`Error when checking ${r}: expected ${t[o]} to have ${n[o].length} dimension(s), but got array with shape ${JSON.stringify(i.shape)}`);for(let l=0;l<n[o].length;++l){if(l===0&&!s)continue;let c=i.shape[l],u=n[o][l];if(u!=null&&u!==c)throw new q(`Error when checking ${r}: expected ${t[o]} to have shape ${JSON.stringify(n[o])} but got array with shape ${JSON.stringify(i.shape)}.`)}}}function zL(e,t){if(e==null||Array.isArray(e)&&e.length===0)return t.map(s=>[]);let n;if(typeof e=="string"||typeof e=="function")n=[e];else if(Array.isArray(e)||typeof e=="object")n=e;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);if(Array.isArray(n))return t.map(s=>n);{let s=[];for(let r of t){let a=n.hasOwnProperty(r)?n[r]:[];Array.isArray(a)||(a=[a]),s.push(a)}return s}}var LL="layers-model",aa=class extends _r{constructor(e){super(e);this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new q("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");gL(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=mL(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof na))throw new q("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(!Array.isArray(e.loss)&&typeof e.loss!="string"&&typeof e.loss!="function"){e.loss=e.loss;for(let a in e.loss)if(this.outputNames.indexOf(a)===-1)throw new q(`Unknown entry in loss dictionary: "${a}". Only expected the following keys: ${this.outputNames}`);for(let a of this.outputNames)e.loss[a]==null&&console.warn(`Output "${a}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${a} during training`),t.push(ry(e.loss[a]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new q(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);t=e.loss.map(o=>ry(o))}else{let a=ry(e.loss);this.outputs.forEach(o=>{t.push(a)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let a=0;a<this.outputs.length;++a){let o=this.internalOutputShapes[a],i=this.outputNames[a];this.feedOutputNames.push(i),this.feedOutputShapes.push(o),this.feedLossFns.push(this.lossFunctions[a])}let n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],ll("loss",()=>{for(let a=0;a<this.outputs.length;++a){if(n.indexOf(a)!==-1)continue;let o=this.lossFunctions[a];this.outputs.length>1&&(this.metricsTensors.push([o,a]),this.metricsNames.push(this.outputNames[a]+"_loss"))}});let s=zL(e.metrics,this.outputNames),r=(a,o,i)=>{this.outputNames.length>1&&(o=this.outputNames[a]+"_"+o),this.metricsNames.push(o),this.metricsTensors.push([i,a])};ll("metric",()=>{for(let a=0;a<this.outputs.length;++a){if(n.indexOf(a)!==-1)continue;let o=s[a];(l=>{let c="",u,d,p;for(let h of l){if(typeof h=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(h)!==-1){let m=this.internalOutputShapes[a];m[m.length-1]===1||this.lossFunctions[a]===om?["accuracy","acc"].indexOf(h)!==-1?d=ay:["crossentropy","ce"].indexOf(h)!==-1&&(d=yw):this.lossFunctions[a]===am?["accuracy","acc"].indexOf(h)!==-1?d=Aw:["crossentropy","ce"].indexOf(h)!==-1&&(d=xw):["accuracy","acc"].indexOf(h)!==-1?d=oy:["crossentropy","ce"].indexOf(h)!==-1&&(d=iy);let g;["accuracy","acc"].indexOf(h)!==-1?g="acc":["crossentropy","ce"].indexOf(h)!==-1&&(g="ce"),p=d,u=c+g}else p=fL(h),u=c+um(h);let f;ll(u,()=>{f=p}),r(a,u,f)}})(o)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){this.collectedTrainableWeights!=null&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){let s=n.batchSize==null?32:n.batchSize;py(s);let r=!0,a=this.standardizeUserDataXY(e,t,r,s);try{let o=a[0].concat(a[1]);this.makeTestFunction();let i=this.testFunction,l=this.testLoop(i,o,s,n.verbose,n.steps);return as(l)}finally{pl(a[0],e),pl(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),DL(this,e,t)}checkNumSamples(e,t,n,s="steps"){let r;if(n!=null){if(r=null,t!=null)throw new q(`If ${s} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?r=e[0].shape[0]:r=e.shape[0];else throw new q(`Either the input data should have a defined shape, or ${s} shoud be specified.`);return r}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new q("`outputs` is an empty Array, which is not allowed.");let n=Array.isArray(t),s=n?t:[t],r=this.retrieveSymbolicTensors(s),a=new dl;if(e instanceof Ke&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new q(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let i=0;i<this.inputs.length;++i)a.add(this.inputs[i],e[i])}else for(let i of this.inputs){let l=e[i.name];if(l==null)throw new q(`No value is provided for the model's input ${i.name}`);a.add(i,l)}let o=Gd(r,a);return n?o:o[0]}retrieveSymbolicTensors(e){let t=al(null,e.length),n=e.length;for(let s of this.layers){let r=Array.isArray(s.output)?s.output:[s.output],a=r.map(o=>o.name);for(let o=0;o<e.length;++o){let i=a.indexOf(e[o]);if(i!==-1&&(t[o]=r[i],n--),n===0)break}if(n===0)break}if(n>0){let s=[];throw t.forEach((r,a)=>{r==null&&s.push(e[a])}),new q(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(s)}`)}return t}predictLoop(e,t=32,n=!1){return j(()=>{let s=this.checkNumSamples(e);if(n)throw new Ve("Verbose predictLoop() is not implemented yet.");let r=fy(s,t),a=this.outputs.map(o=>[]);for(let o=0;o<r.length;++o)j(()=>{let l=r[o][0],c=r[o][1],u=Hd(e,l,c),d=[];if(Array.isArray(u))for(let h=0;h<u.length;++h)d.push({key:this.inputs[h],value:u[h]});else d.push({key:this.inputs[0],value:u});let p=new dl(d);return Gd(this.outputs,p)}).forEach((l,c)=>a[c].push(l));return as(a.map(o=>kt(o,0)))})}predict(e,t={}){let n=Rw(e);_w(n,this.inputNames,this.feedInputShapes,!1);try{let s=t.batchSize==null?32:t.batchSize;return py(s),this.predictLoop(n,s)}finally{pl(n,e)}}predictOnBatch(e){_w(e,this.inputNames,this.feedInputShapes,!0);let t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,s){if(this.optimizer_==null)throw new hr("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let r=[];for(let a=0;a<this.feedOutputShapes.length;++a){let o=this.feedOutputShapes[a];this.feedLossFns[a]===am?r.push(o.slice(0,o.length-1).concat([1])):r.push(o)}if(e=Dw(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=Dw(t,this.feedOutputNames,r,!1,"target"),OL(e,t,null),ML(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&s!=null&&s>0&&e[0].shape[0]%s!=0)throw new q(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${s}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,s,r=!0,a){let[o,i]=this.standardizeUserDataXY(e,t,r,a);if(n!=null)throw new Error("sample weight is not supported yet.");let l=null;if(s!=null){let c=Sw(s,this.outputNames);l=[];for(let u=0;u<c.length;++u)l.push(await Cw(i[u],null,c[u]))}return[o,i,l]}testLoop(e,t,n,s=0,r){return j(()=>{let a=this.checkNumSamples(t,n,r,"steps"),o=[];if(s>0)throw new Ve("Verbose mode is not implemented yet.");if(r!=null)throw new Ve("steps mode in testLoop() is not implemented yet");{let i=fy(a,n),l=Zt(fr(0,a));for(let c=0;c<i.length;++c){let u=i[c][0],d=i[c][1],p=ul(l,u,d-u),h=hy(t,p),f=e(h);if(c===0)for(let m=0;m<f.length;++m)o.push(Ee(0));for(let m=0;m<f.length;++m){let g=f[m];o[m]=ue(o[m],L(d-u,g))}}for(let c=0;c<o.length;++c)o[c]=fe(o[c],a)}return o})}getDedupedMetricsNames(){let e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){let s=e[n],r=s;Bv(e,s)>1&&(r+=`_${Bv(e.slice(0,n),s)}`),t.push(r)}return t}makeTrainFunction(){return e=>{let t=[],n=e.slice(0,this.inputs.length),s=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),r=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),a=[],o=()=>{let u=[];for(let f=0;f<this.inputs.length;++f)u.push({key:this.inputs[f],value:n[f]});let d=new dl(u),p=Gd(this.outputs,d,{training:!0}),h;for(let f=0;f<this.lossFunctions.length;++f){let g=this.lossFunctions[f](s[f],p[f]);r[f]!=null&&(g=CL(g,r[f]));let y=Lt(g);t.push(y),f===0?h=g:h=ue(h,g)}for(let f=0;f<this.metricsTensors.length;++f){let m;if(this.outputs.length>1&&f<this.outputs.length)m=t[f];else{let g=this.metricsTensors[f][0],y=this.metricsTensors[f][1];m=Lt(g(s[y],p[y]))}An(m),a.push(m)}return h=Lt(h),this.calculateLosses().forEach(f=>{h=ue(h,f)}),h},i=this.collectedTrainableWeights.map(u=>u.read()),l=!0;return[this.optimizer_.minimize(o,l,i)].concat(a)}}makeTestFunction(){this.testFunction=e=>j(()=>{let t=[],n,s=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=[];for(let l=0;l<this.inputs.length;++l)a.push({key:this.inputs[l],value:s[l]});let o=new dl(a),i=Gd(this.outputs,o);for(let l=0;l<this.lossFunctions.length;++l){let c=this.lossFunctions[l],u=Lt(c(r[l],i[l]));l===0?n=u:n=ue(n,u),t.push(n)}for(let l=0;l<this.metricsTensors.length;++l){let c=this.metricsTensors[l][0],u=this.metricsTensors[l][1],d=Lt(c(r[u],i[u]));t.push(d)}return t})}async fit(e,t,n={}){return PL(this,e,t,n)}async fitDataset(e,t){return EL(this,e,t)}async trainOnBatch(e,t){let n=await this.standardizeUserData(e,t),s=n[0],r=n[1],o=this.makeTrainFunction()(s.concat(r)),i=[];for(let l of o){let c=await l.data();i.push(c[0])}return te(o),as(i)}getNamedWeights(e){let t=[],n=e!=null&&e.trainableOnly,s=n?this.trainableWeights:this.weights,r=this.getWeights(n);for(let a=0;a<s.length;++a)n&&!s[a].trainable||t.push({name:s[a].originalName,tensor:r[a]});return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){let e=super.dispose();if(e.refCountAfterDispose===0&&this.optimizer!=null&&this.isOptimizerOwned){let t=Qh().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-Qh().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=ra(this.loss);else if(Array.isArray(this.loss)){for(let t of this.loss)if(typeof t!="string")throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map(t=>ra(t))}else{let t=Object.keys(this.loss);e={};let n=this.loss;for(let s of t)if(typeof n[s]=="string")e[s]=ra(n[s]);else throw new Error("Serialization of non-string loss is not supported.")}return e}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[ra(um(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>ra(um(e)));{let e={};for(let t in this.metrics)e[t]=ra(um(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(e.weighted_metrics!=null)throw new Error("Loading weight_metrics is not supported yet.");if(e.loss_weights!=null)throw new Error("Loading loss_weights is not supported yet.");if(e.sample_weight_mode!=null)throw new Error("Loading sample_weight_mode is not supported yet.");let t=Ud(e.optimizer_config),n=yr(t),s;if(typeof e.loss=="string")s=ol(e.loss);else if(Array.isArray(e.loss))s=e.loss.map(a=>ol(a));else if(e.loss!=null){s={};for(let a in e.loss)s[a]=ol(e.loss[a])}let r;if(Array.isArray(e.metrics))r=e.metrics.map(a=>ol(a));else if(e.metrics!=null){r={};for(let a in e.metrics)r[a]=ol(e.metrics[a])}this.compile({loss:s,metrics:r,optimizer:n})}async save(e,t){if(typeof e=="string"){let l=es.getSaveHandlers(e);if(l.length===0)throw new q(`Cannot find any save handlers for URL '${e}'`);if(l.length>1)throw new q(`Found more than one (${l.length}) save handlers for URL '${e}'`);e=l[0]}if(e.save==null)throw new q("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let n=await es.encodeWeights(this.getNamedWeights(t)),s=!1,r=null,o={modelTopology:this.toJSON(r,s),format:LL,generatedBy:`TensorFlow.js tfjs-layers v${cy}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){o.trainingConfig=this.getTrainingConfig();let l="optimizer",{data:c,specs:u}=await es.encodeWeights(await this.optimizer.getWeights(),l);n.specs.push(...u),n.data=es.concatenateArrayBuffers([n.data,c])}if(this.userDefinedMetadata!=null){let l=!0;vw(this.userDefinedMetadata,this.name,l),o.userDefinedMetadata=this.userDefinedMetadata}return o.weightData=n.data,o.weightSpecs=n.specs,e.save(o)}setUserDefinedMetadata(e){vw(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};aa.className="Model";de.registerClass(aa);var Pw=class extends aa{};Pw.className="Functional";de.registerClass(Pw);async function BL(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);let s=Ud(n),r=yr(s,t);if(e.weightsManifest!=null){let a=await es.loadWeights(e.weightsManifest,e.pathPrefix,r.weights.map(i=>i.originalName)),o={};for(let i of r.weights)o[i.originalName]=a[i.originalName];r.loadWeights(o),te(a)}return r}async function WL(e,t){if(t==null&&(t={}),typeof e=="string"){let n=es.getLoadHandlers(e,t);if(n.length===0)n.push(es.browserHTTPRequest(e,t));else if(n.length>1)throw new q(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return VL(e,void 0,t)}async function VL(e,t,n){if(n==null&&(n={}),e.load==null)throw new q("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let s=await e.load(),r=s.modelTopology;r.model_config!=null&&(r=r.model_config);let a=n.strict==null?!0:n.strict,o=s.weightData!=null&&s.weightSpecs!=null&&a,i=yr(Ud(r),t,o),l=s.trainingConfig;if(l!=null&&i.loadTrainingConfig(l),s.userDefinedMetadata!=null&&i.setUserDefinedMetadata(s.userDefinedMetadata),s.weightData!=null){if(s.weightSpecs==null)throw new q("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:c,optimizerWeights:u}=UL(s.weightData,s.weightSpecs);i.loadWeights(c,a),i.optimizer!=null&&u.length>0&&await i.optimizer.setWeights(u),te(c),te(u.map(d=>d.tensor))}return i}function UL(e,t){let n=es.decodeWeights(e,t),s={},r=[];return t.forEach(a=>{a.group==="optimizer"?r.push({name:a.name,tensor:n[a.name]}):s[a.name]=n[a.name]}),{modelWeights:s,optimizerWeights:r}}var qu=class extends aa{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:Qf("sequential_"),e.layers!=null)for(let t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(n=>n<0))throw new q(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof qu||e instanceof aa,n;if(t){if(n=e,n.outputs.length!==1)throw new q("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(n.inputs.length!==1)throw new q("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(this.outputs.length===0){if(e.inboundNodes.length===0){if(e.batchInputShape==null)throw new q("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let s=iw({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(s)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(e.inboundNodes.length!==1)throw new q(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(e.inboundNodes[0].outputTensors.length!==1)throw new q("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=ow(this.outputs[0])}this.inboundNodes=[],new nm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:al(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(s=>s.shape),outputShapes:this.outputs[0].shape})}else{let s=e.apply(this.outputs[0]);if(Array.isArray(s))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[s],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{let e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return this.model==null&&this.build(),this.model.call(e,t)}build(e){if(At(e),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new aa({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new hr("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new hr("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return this.model==null&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return this.model==null&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return this.model==null?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new hr("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new hr("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},s=!1){let r,a={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new q("Legacy serialization format not supported yet.");r=t}else v.assert(t.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),r=t.layers,delete t.layers,a=t;let o=new e(a);if(!(o instanceof qu))throw new Ve(`Sequential.fromConfig called on non-Sequential input: ${o}`);for(let i of r){let c=yr(i,void 0,s);s&&c.setFastWeightInitDuringBuild(!0),o.add(c)}return o}set stopTraining(e){if(this.model==null)throw new q("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(this.model==null)throw new q("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){let e=[];for(let t of this.layers){let n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}};qu.className="Sequential";de.registerClass(qu);function GL(e){return new aa(e)}function HL(e){return new qu(e)}function jL(e,t){return t==null&&(t={}),WL(e,t)}function Fw(e){return iw(e)}function qL(e,t){Qs.registerCallbackConstructor(e,t)}var is=class extends de.Serializable{getConfig(){return{}}},Ow=class extends is{apply(e,t=1){return xz(e,t)}};Ow.className="elu";de.registerClass(Ow);var Mw=class extends is{apply(e){return bf(e)}};Mw.className="selu";de.registerClass(Mw);var zw=class extends is{apply(e){return cr(e)}};zw.className="relu";de.registerClass(zw);var Lw=class extends is{apply(e){return j(()=>Fu(6,cr(e)))}};Lw.className="relu6";de.registerClass(Lw);var Bw=class extends is{apply(e){return e}};Bw.className="linear";de.registerClass(Bw);var Ww=class extends is{apply(e){return ns(e)}};Ww.className="sigmoid";de.registerClass(Ww);var Vw=class extends is{apply(e){return vz(e)}};Vw.className="hardSigmoid";de.registerClass(Vw);var Uw=class extends is{apply(e){return Qi(e)}};Uw.className="softplus";de.registerClass(Uw);var Gw=class extends is{apply(e){return bz(e)}};Gw.className="softsign";de.registerClass(Gw);var Hw=class extends is{apply(e){return Zi(e)}};Hw.className="tanh";de.registerClass(Hw);var gy=class extends is{apply(e,t=-1){return nl(e,t)}};gy.className="softmax";de.registerClass(gy);var jw=class extends is{apply(e,t=-1){return hf(e,t)}};jw.className="logSoftmax";de.registerClass(jw);var qw=class extends is{apply(e,t=1){return j(()=>L(ns(L(e,t)),e))}};qw.className="swish";de.registerClass(qw);var Xw=class extends is{apply(e){return j(()=>L(e,Zi(Qi(e))))}};Xw.className="mish";de.registerClass(Xw);function Ro(e){return e.getClassName()}function yy(e,t={}){return Od(e,de.SerializationMap.getMap().classNameMap,t,"activation")}function $o(e){if(e==null){let t={};return t.className="linear",t.config={},yy(t)}if(typeof e=="string"){let t={};return t.className=e,t.config={},yy(t)}else return e instanceof is?e:yy(e)}function Ay(e){if(e!=null&&typeof e!="object")throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}var Kw=class extends de.Serializable{},jd=class extends Kw{constructor(e){super();Ay(e),this.l1=e==null||e.l1==null?.01:e.l1,this.l2=e==null||e.l2==null?.01:e.l2,this.hasL1=this.l1!==0,this.hasL2=this.l2!==0}apply(e){return j(()=>{let t=qt([1]);return this.hasL1&&(t=ue(t,ke(L(this.l1,Kt(e))))),this.hasL2&&(t=ue(t,ke(L(this.l2,Bd(e))))),G(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};jd.className="L1L2";de.registerClass(jd);function XL(e){return Ay(e),new jd({l1:e!=null?e.l1:null,l2:0})}function KL(e){return Ay(e),new jd({l2:e!=null?e.l2:null,l1:0})}var Zw={l1l2:"L1L2"};function It(e){return F1(e)}function Yw(e,t={}){return Od(e,de.SerializationMap.getMap().classNameMap,t,"regularizer")}function Ft(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in Zw?Zw[e]:e,config:{}};return Yw(n)}else return e instanceof Kw?e:Yw(e)}var xy=class extends rt{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Ge(e);let n=cr(e);return this.maxValue!=null&&(n=ss(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};xy.className="ReLU";de.registerClass(xy);var by=class extends rt{constructor(e){super(e==null?{}:e);this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let n=Ge(e);return kd(n,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};by.className="LeakyReLU";de.registerClass(by);var vy=class extends rt{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Pt(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Ft(e.alphaRegularizer),this.alphaConstraint=on(e.alphaConstraint),e.sharedAxes==null)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else if(typeof e.sharedAxes=="number")this.sharedAxes=[e.sharedAxes];else throw new q(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=At(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let s of this.sharedAxes)t[s-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let n={};if(this.sharedAxes!=null)for(let s=1;s<e.length;++s)n[s]=e[s];this.inputSpec=[new Yt({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=Ge(e),Ed(e,this.alpha.read())}getConfig(){let e={alphaInitializer:Bt(this.alphaInitializer),alphaRegularizer:It(this.alphaRegularizer),alphaConstraint:an(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}};vy.className="PReLU";de.registerClass(vy);var wy=class extends rt{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new Ve(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let n=Ge(e);return Du(n)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};wy.className="ELU";de.registerClass(wy);var ky=class extends rt{constructor(e){super(e==null?{}:e);this.DEFAULT_THETA=1,e==null&&(e={}),this.theta=e.theta==null?this.DEFAULT_THETA:e.theta}call(e,t){let n=Ge(e);return L(n,pe(rs(n,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){let e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}};ky.className="ThresholdedReLU";de.registerClass(ky);var Iy=class extends rt{constructor(e){super(e==null?{}:e);this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new gy().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){let n=Ge(e);return this.softmax(n,this.axis)}computeOutputShape(e){return e}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};Iy.className="Softmax";de.registerClass(Iy);function Xu(e,t,n){if(typeof e=="number")return al(e,t);if(e.length!==t)throw new q(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let s=0;s<t;++s){let r=e[s];if(!mz(r))throw new q(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${r}`)}return e}function Ar(e,t,n,s,r=1){if(e==null)return e;let a=t+(t-1)*(r-1),o;return n==="same"?o=e:o=e-a+1,Math.floor((o+s-1)/s)}function Pr(e,t,n,s){if(e==null)return null;if(s==="valid")e=e*t+No([n-t,0]);else if(s==="same")e=e*t;else throw new q(`Unsupport padding mode: ${s}.`);return e}function Sy(e,t){return j(()=>(Xt(t),t==="channelsFirst"?et(e,[0,2,3,1]):e))}function Jw(e,t){return j(()=>(Xt(t),t==="channelsFirst"?et(e,[0,2,3,4,1]):e))}function ZL(e,t,n,s=1,r="valid",a,o=1){return j(()=>{if(a==null&&(a=pr()),Xt(a),e.shape.length!==3)throw new q(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new q(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new q(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(a==="channelsFirst"&&(e=et(e,[0,2,1])),r==="causal")throw new Ve("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let i=af(e,t,s,r==="same"?"same":"valid","NWC",o);return n!=null&&(i=mr(i,n)),i})}function Qw(e,t,n,s=[1,1],r="valid",a,o,i=null){return j(()=>{if(a==null&&(a=pr()),Xt(a),e.rank!==3&&e.rank!==4)throw new q(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new q(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=Sy(e,a);if(r==="causal")throw new Ve("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=So.conv2d({x:l,filter:t,strides:s,pad:r==="same"?"same":"valid",dilations:o,dataFormat:"NHWC",bias:n,activation:i}),a==="channelsFirst"&&(l=et(l,[0,3,1,2])),l})}function YL(e,t,n,s=[1,1,1],r="valid",a,o){return j(()=>{if(a==null&&(a=pr()),Xt(a),e.rank!==4&&e.rank!==5)throw new q(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new q(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let i=Jw(e,a);if(r==="causal")throw new Ve("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return i=n1(i,t,s,r==="same"?"same":"valid","NDHWC",o),n!=null&&(i=mr(i,n)),a==="channelsFirst"&&(i=et(i,[0,4,1,2,3])),i})}var Cy=class extends rt{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",Cy.verifyArgs(t),this.rank=e,bn(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Ve(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Xu(t.kernelSize,e,"kernelSize"),this.strides=Xu(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,Ms(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Xt(this.dataFormat),this.activation=$o(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=Pt(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=on(t.biasConstraint),this.biasRegularizer=Ft(t.biasRegularizer),this.activityRegularizer=Ft(t.activityRegularizer),this.dilationRate=Xu(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new q(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(this.rank===2){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==2)throw new q(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(this.rank===3){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==3)throw new q(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if($r("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!M1(e.kernelSize,"number",1,3))throw new q(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){let e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Ro(this.activation),useBias:this.useBias,biasInitializer:Bt(this.biasInitializer),biasRegularizer:It(this.biasRegularizer),activityRegularizer:It(this.activityRegularizer),biasConstraint:an(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},qd=class extends Cy{constructor(e,t){super(e,t);this.kernel=null,qd.verifyArgs(t),this.filters=t.filters,bn(this.filters,"filters"),this.kernelInitializer=Pt(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=on(t.kernelConstraint),this.kernelRegularizer=Ft(t.kernelRegularizer)}build(e){e=At(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new q(`The channel dimension of the input should be defined. Found ${e[t]}`);let n=e[t],s=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return j(()=>{e=Ge(e);let n,s=this.bias==null?null:this.bias.read(),r=Vv(this.activation.getClassName());if(r!=null&&this.rank===2)n=Qw(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(this.rank===1)n=ZL(e,this.kernel.read(),s,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=Qw(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=YL(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Ve("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(e){e=At(e);let t=[],n=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let r=0;r<n.length;++r){let a=Ar(n[r],this.kernelSize[r],this.padding,this.strides[r],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[r]);t.push(a)}let s=[e[0]];return this.dataFormat==="channelsLast"?(s=s.concat(t),s.push(this.filters)):(s.push(this.filters),s=s.concat(t)),s}getConfig(){let e={filters:this.filters,kernelInitializer:Bt(this.kernelInitializer),kernelRegularizer:It(this.kernelRegularizer),kernelConstraint:an(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||typeof e.filters!="number"||e.filters<1)throw new q(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}},Xd=class extends qd{constructor(e){super(2,e);Xd.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!M1(e.kernelSize,"number",1,2))throw new q(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}};Xd.className="Conv2D";de.registerClass(Xd);var Kd=class extends qd{constructor(e){super(3,e);Kd.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!(Array.isArray(e.kernelSize)&&(e.kernelSize.length===1||e.kernelSize.length===3)))throw new q(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}};Kd.className="Conv3D";de.registerClass(Kd);var Ty=class extends Xd{constructor(e){super(e);if(this.inputSpec=[new Yt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new q(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=At(e),e.length!==4)throw new q("Input should have rank 4; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new q("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],s=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Yt({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return j(()=>{let n=Ge(e);if(n.shape.length!==4)throw new q(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let s=n.shape,r=s[0],a,o;this.dataFormat==="channelsFirst"?(a=2,o=3):(a=1,o=2);let i=s[a],l=s[o],c=this.kernelSize[0],u=this.kernelSize[1],d=this.strides[0],p=this.strides[1],h=Pr(i,d,c,this.padding),f=Pr(l,p,u,this.padding),m=[r,h,f,this.filters];this.dataFormat!=="channelsLast"&&(n=et(n,[0,2,3,1]));let g=of(n,this.kernel.read(),m,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=et(g,[0,3,1,2])),this.bias!=null&&(g=mr(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=At(e);let t=e.slice(),n,s,r;this.dataFormat==="channelsFirst"?(n=1,s=2,r=3):(n=3,s=1,r=2);let a=this.kernelSize[0],o=this.kernelSize[1],i=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[s]=Pr(t[s],i,a,this.padding),t[r]=Pr(t[r],l,o,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};Ty.className="Conv2DTranspose";de.registerClass(Ty);var Ny=class extends Kd{constructor(e){super(e);if(this.inputSpec=[new Yt({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new q(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=At(e),e.length!==5)throw new q("Input should have rank 5; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new q("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],s=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Yt({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return j(()=>{let n=Ge(e);if(n.shape.length!==5)throw new q(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let s=n.shape,r=s[0],a,o,i;this.dataFormat==="channelsFirst"?(i=2,a=3,o=4):(i=1,a=2,o=3);let l=s[i],c=s[a],u=s[o],d=this.kernelSize[0],p=this.kernelSize[1],h=this.kernelSize[2],f=this.strides[0],m=this.strides[1],g=this.strides[2],y=Pr(l,f,d,this.padding),A=Pr(c,m,p,this.padding),x=Pr(u,g,h,this.padding),b=[r,y,A,x,this.filters];this.dataFormat!=="channelsLast"&&(n=et(n,[0,2,3,4,1]));let w=V3(n,this.kernel.read(),b,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(w=et(w,[0,4,1,2,3])),this.bias!==null&&(w=mr(w,this.bias.read(),this.dataFormat)),this.activation!==null&&(w=this.activation.apply(w)),w})}computeOutputShape(e){e=At(e);let t=e.slice(),n,s,r,a;this.dataFormat==="channelsFirst"?(n=1,s=2,r=3,a=4):(n=4,s=1,r=2,a=3);let o=this.kernelSize[0],i=this.kernelSize[1],l=this.kernelSize[2],c=this.strides[0],u=this.strides[1],d=this.strides[2];return t[n]=this.filters,t[s]=Pr(t[s],c,o,this.padding),t[r]=Pr(t[r],u,i,this.padding),t[a]=Pr(t[a],d,l,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};Ny.className="Conv3DTranspose";de.registerClass(Ny);var ek=class extends qd{constructor(e,t){super(e,t);if(this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new q("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new q("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(t.padding!=null&&t.padding!=="same"&&t.padding!=="valid")throw new q(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=Pt(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Ft(t.depthwiseRegularizer),this.depthwiseConstraint=on(t.depthwiseConstraint),this.pointwiseInitializer=Pt(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Ft(t.pointwiseRegularizer),this.pointwiseConstraint=on(t.pointwiseConstraint)}build(e){if(e=At(e),e.length<this.rank+2)throw new q(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null||e[t]<0)throw new q(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);let n=e[t],s=this.kernelSize.concat([n,this.depthMultiplier]),r=[];for(let o=0;o<this.rank;++o)r.push(1);r.push(n*this.depthMultiplier,this.filters);let a=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",s,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,a,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",r,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,a,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,a,this.biasConstraint):this.bias=null,this.inputSpec=[new Yt({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return j(()=>{e=Ge(e);let n;if(this.rank===1)throw new Ve("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=et(e,[0,2,3,1])),n=b1(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=mr(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=et(n,[0,3,1,2])),n})}getConfig(){let e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Bt(this.depthwiseInitializer),e.pointwiseInitializer=Bt(this.pointwiseInitializer),e.depthwiseRegularizer=It(this.depthwiseRegularizer),e.pointwiseRegularizer=It(this.pointwiseRegularizer),e.depthwiseConstraint=an(this.depthwiseConstraint),e.pointwiseConstraint=an(this.pointwiseConstraint),e}};ek.className="SeparableConv";var Ey=class extends ek{constructor(e){super(2,e)}};Ey.className="SeparableConv2D";de.registerClass(Ey);var dm=class extends qd{constructor(e){super(1,e);dm.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){let e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!M1(e.kernelSize,"number",1,1))throw new q(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}};dm.className="Conv1D";de.registerClass(dm);var Ry=class extends rt{constructor(e){super(e);typeof e.cropping=="number"?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:typeof e.cropping[0]=="number"?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=e.dataFormat===void 0?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return this.dataFormat==="channelsFirst"?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return j(()=>{if(e=Ge(e),this.dataFormat==="channelsLast"){let n=Uf(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Uf(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let n=Uf(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Uf(n,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){let e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};Ry.className="Cropping2D";de.registerClass(Ry);var $y=class extends rt{constructor(e){super(e);this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=e.size==null?this.DEFAULT_SIZE:e.size,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Xt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,pz(this.interpolation)}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){let t=e[2]==null?null:this.size[0]*e[2],n=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,n]}else{let t=e[1]==null?null:this.size[0]*e[1],n=e[2]==null?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return j(()=>{let n=Ge(e),s=n.shape;if(this.dataFormat==="channelsFirst"){n=et(n,[0,2,3,1]);let r=this.size[0]*s[2],a=this.size[1]*s[3],o=this.interpolation==="nearest"?$e.resizeNearestNeighbor(n,[r,a]):$e.resizeBilinear(n,[r,a]);return et(o,[0,3,1,2])}else{let r=this.size[0]*s[1],a=this.size[1]*s[2];return this.interpolation==="nearest"?$e.resizeNearestNeighbor(n,[r,a]):$e.resizeBilinear(n,[r,a])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};$y.className="UpSampling2D";de.registerClass($y);function JL(e,t,n=[1,1],s="valid",r,a){return j(()=>{r==null&&(r=pr()),Xt(r);let o=Sy(e,r);if(e.rank!==4)throw new q(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new q(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return o=$u(o,t,n,s==="same"?"same":"valid","NHWC",a),r==="channelsFirst"&&(o=et(o,[0,3,1,2])),o})}var Dy=class extends Cy{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=Pt(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=on(e.depthwiseConstraint),this.depthwiseRegularizer=Ft(e.depthwiseRegularizer)}build(e){if(e=At(e),e.length<4)throw new q(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);let t=this.dataFormat==="channelsFirst"?1:3;if(e[t]==null||e[t]<0)throw new q(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);let n=e[t],s=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",s,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return j(()=>{e=Ge(e);let n=JL(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=mr(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=At(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],s=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,r=Ar(t,this.kernelSize[0],this.padding,this.strides[0]),a=Ar(n,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],s,r,a]:[e[0],r,a,s]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Bt(this.depthwiseInitializer),e.depthwiseRegularizer=It(this.depthwiseRegularizer),e.depthwiseConstraint=an(this.depthwiseRegularizer),e}};Dy.className="DepthwiseConv2D";de.registerClass(Dy);function tk(e,t,n,s){if(Array.isArray(e)){if(t!=null||n!=null)throw new q("When inputs is an array, neither initialState or constants should be provided");s!=null&&(n=e.slice(e.length-s,e.length),e=e.slice(0,e.length-s)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function r(a){return a==null||Array.isArray(a)?a:[a]}return t=r(t),n=r(n),{inputs:e,initialState:t,constants:n}}function nk(e,t,n,s=!1,r,a,o=!1,i=!1){return j(()=>{let l=t.shape.length;if(l<3)throw new q(`Input should be at least 3D, but is ${l}D.`);let c=[1,0].concat(fr(2,l));if(t=et(t,c),a!=null)throw new Ve("The rnn() functoin of the deeplearn.js backend does not support constants yet.");o&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),r!=null&&(r=pe(pe(r,"bool"),"float32"),r.rank===l-1&&(r=jt(r,-1)),r=et(r,c)),s&&(t=ws(t,0),r!=null&&(r=ws(r,0)));let u=[],d,p=n,h=t.shape[0],f=Wn(t),m;r!=null&&(m=Wn(r));for(let y=0;y<h;++y){let A=f[y],x=j(()=>e(A,p));if(r==null)d=x[0],p=x[1];else{let b=j(()=>{let w=m[y],k=xe(vs(w),w),S=ue(L(x[0],w),L(p[0],k)),N=p.map(($,F)=>ue(L(x[1][F],w),L($,k)));return{output:S,newStates:N}});d=b.output,p=b.newStates}i&&u.push(d)}let g;return i&&(g=Tn(u,1)),[d,g,p]})}var Fr=class extends rt{constructor(e){super(e);let t;if(e.cell==null)throw new q("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new fm({cells:e.cell}):t=e.cell,t.stateSize==null)throw new q("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=e.returnSequences==null?!1:e.returnSequences,this.returnState=e.returnState==null?!1:e.returnState,this.goBackwards=e.goBackwards==null?!1:e.goBackwards,this._stateful=e.stateful==null?!1:e.stateful,this.unroll=e.unroll==null?!1:e.unroll,this.supportsMasking=!0,this.inputSpec=[new Yt({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return fr(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){ey(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);let n=t[0],s;if(this.returnSequences?s=[e[0],e[1],n]:s=[e[0],n],this.returnState){let r=[];for(let a of t)r.push([e[0],a]);return[s].concat(r)}else return s}computeMask(e,t){return j(()=>{Array.isArray(t)&&(t=t[0]);let n=this.returnSequences?t:null;if(this.returnState){let s=this.states.map(r=>null);return[n].concat(s)}else return n})}get states(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;n<e;++n)t.push(null);return t}else return this.states_}set states(e){this.states_=e}build(e){let t=null;if(this.numConstants!=null)throw new Ve("Constants support is not implemented in RNN yet.");ey(e)&&(e=e[0]),e=e;let n=this.stateful?e[0]:null,s=e.slice(2);this.inputSpec[0]=new Yt({shape:[n,null,...s]});let r=[e[0]].concat(e.slice(2));if(t!=null)throw new Ve("Constants support is not implemented in RNN yet.");this.cell.build(r);let a;if(Array.isArray(this.cell.stateSize)?a=this.cell.stateSize:a=[this.cell.stateSize],this.stateSpec!=null){if(!v.arraysEqual(this.stateSpec.map(o=>o.shape[o.shape.length-1]),a))throw new q(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=a.map(o=>new Yt({shape:[null,o]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){j(()=>{if(!this.stateful)throw new sa("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape[0];if(n==null)throw new q("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(s=>qt([n,s])):this.states_=[qt([n,this.cell.stateSize])];else if(e==null)te(this.states_),this.keptStates!=null&&(te(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(s=>qt([n,s])):this.states_[0]=qt([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new q(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t===!0?this.keptStates.push(this.states_.slice()):te(this.states_);for(let s=0;s<this.states_.length;++s){let r=e[s],a=Array.isArray(this.cell.stateSize)?this.cell.stateSize[s]:this.cell.stateSize,o=[n,a];if(!v.arraysEqual(r.shape,o))throw new q(`State ${s} is incompatible with layer ${this.name}: expected shape=${o}, received shape=${r.shape}`);this.states_[s]=r}}this.states_=this.states_.map(s=>An(s.clone()))})}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});let r=tk(e,n,s,this.numConstants);e=r.inputs,n=r.initialState,s=r.constants;let a=[],o=[];if(n!=null){t.initialState=n,a=a.concat(n),this.stateSpec=[];for(let l of n)this.stateSpec.push(new Yt({shape:l.shape}));o=o.concat(this.stateSpec)}if(s!=null&&(t.constants=s,a=a.concat(s),this.numConstants=s.length),a[0]instanceof gr){let l=[e].concat(a),c=this.inputSpec.concat(o),u=this.inputSpec;this.inputSpec=c;let d=super.apply(l,t);return this.inputSpec=u,d}else return super.apply(e,t)}call(e,t){return j(()=>{let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;e=Ge(e),r==null&&(this.stateful?r=this.states_:r=this.getInitialState(e));let a=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(r.length!==a)throw new q(`RNN Layer has ${a} state(s) but was passed ${r.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");let o={training:s},l=nk((h,f)=>{let m=this.cell.call([h].concat(f),o);return[m[0],m.slice(1)]},e,r,this.goBackwards,n,null,this.unroll,this.returnSequences),c=l[0],u=l[1],d=l[2];this.stateful&&this.resetStates(d,s);let p=this.returnSequences?u:c;return this.returnState?[p].concat(d):p})}getInitialState(e){return j(()=>{let t=qt(e.shape);return t=ke(t,[1,2]),t=Ld(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?H1(t,[1,n]):t):this.cell.stateSize>1?[H1(t,[1,this.cell.stateSize])]:[t]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){let e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(t.numConstants=this.numConstants);let n=this.cell.getConfig();return this.getClassName()===Fr.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign({},n,e,t)}static fromConfig(e,t,n={}){let s=t.cell,r=yr(s,n);return new e(Object.assign(t,{cell:r}))}};Fr.className="RNN";de.registerClass(Fr);var Zd=class extends rt{},pm=class extends Zd{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,bn(this.units,"units"),this.activation=$o(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Pt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Ft(e.kernelRegularizer),this.recurrentRegularizer=Ft(e.recurrentRegularizer),this.biasRegularizer=Ft(e.biasRegularizer),this.kernelConstraint=on(e.kernelConstraint),this.recurrentConstraint=on(e.recurrentConstraint),this.biasConstraint=on(e.biasConstraint),this.dropout=Uu([1,No([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Uu([1,No([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=At(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return j(()=>{if(e=e,e.length!==2)throw new q(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];let s=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Do({ones:()=>vs(e),rate:this.dropout,training:s})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Do({ones:()=>vs(n),rate:this.recurrentDropout,training:s}));let r,a=this.dropoutMask,o=this.recurrentDropoutMask;a!=null?r=Dr(L(e,a),this.kernel.read()):r=Dr(e,this.kernel.read()),this.bias!=null&&(r=mr(r,this.bias.read())),o!=null&&(n=L(n,o));let i=ue(r,Dr(n,this.recurrentKernel.read()));return this.activation!=null&&(i=this.activation.apply(i)),[i,i]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Ro(this.activation),useBias:this.useBias,kernelInitializer:Bt(this.kernelInitializer),recurrentInitializer:Bt(this.recurrentInitializer),biasInitializer:Bt(this.biasInitializer),kernelRegularizer:It(this.kernelRegularizer),recurrentRegularizer:It(this.recurrentRegularizer),biasRegularizer:It(this.biasRegularizer),activityRegularizer:It(this.activityRegularizer),kernelConstraint:an(this.kernelConstraint),recurrentConstraint:an(this.recurrentConstraint),biasConstraint:an(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}};pm.className="SimpleRNNCell";de.registerClass(pm);var _y=class extends Fr{constructor(e){e.cell=new pm(e);super(e)}call(e,t){return j(()=>{this.cell.dropoutMask!=null&&(te(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(te(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})})}static fromConfig(e,t){return new e(t)}};_y.className="SimpleRNN";de.registerClass(_y);var hm=class extends Zd{constructor(e){super(e);if(this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new q("GRUCell does not support reset_after parameter set to true.");this.units=e.units,bn(this.units,"units"),this.activation=$o(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=$o(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Pt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Ft(e.kernelRegularizer),this.recurrentRegularizer=Ft(e.recurrentRegularizer),this.biasRegularizer=Ft(e.biasRegularizer),this.kernelConstraint=on(e.kernelConstraint),this.recurrentConstraint=on(e.recurrentConstraint),this.biasConstraint=on(e.biasConstraint),this.dropout=Uu([1,No([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Uu([1,No([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=At(e);let t=e[e.length-1];this.kernel=this.addWeight("kernel",[t,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return j(()=>{if(e=e,e.length!==2)throw new q(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training==null?!1:t.training,s=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Do({ones:()=>vs(e),rate:this.dropout,training:n,count:3})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Do({ones:()=>vs(s),rate:this.recurrentDropout,training:n,count:3}));let r=this.dropoutMask,a=this.recurrentDropoutMask,o,i,l;0<this.dropout&&this.dropout<1&&(e=L(e,r[0]));let c=Dr(e,this.kernel.read());this.useBias&&(c=mr(c,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(s=L(s,a[0]));let u=this.recurrentKernel.read(),[d,p]=xn(u,[2*this.units,this.units],u.rank-1),h=Dr(s,d),[f,m,g]=xn(c,3,c.rank-1),[y,A]=xn(h,2,h.rank-1);o=this.recurrentActivation.apply(ue(f,y)),i=this.recurrentActivation.apply(ue(m,A));let x=Dr(L(i,s),p);l=this.activation.apply(ue(g,x));let b=ue(L(o,s),L(ue(1,_t(o)),l));return[b,b]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Ro(this.activation),recurrentActivation:Ro(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Bt(this.kernelInitializer),recurrentInitializer:Bt(this.recurrentInitializer),biasInitializer:Bt(this.biasInitializer),kernelRegularizer:It(this.kernelRegularizer),recurrentRegularizer:It(this.recurrentRegularizer),biasRegularizer:It(this.biasRegularizer),activityRegularizer:It(this.activityRegularizer),kernelConstraint:an(this.kernelConstraint),recurrentConstraint:an(this.recurrentConstraint),biasConstraint:an(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign({},e,t)}};hm.className="GRUCell";de.registerClass(hm);var Py=class extends Fr{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new hm(e);super(e)}call(e,t){return j(()=>{this.cell.dropoutMask!=null&&(te(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(te(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};Py.className="GRU";de.registerClass(Py);var Yd=class extends Zd{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,bn(this.units,"units"),this.activation=$o(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=$o(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Pt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Ft(e.kernelRegularizer),this.recurrentRegularizer=Ft(e.recurrentRegularizer),this.biasRegularizer=Ft(e.biasRegularizer),this.kernelConstraint=on(e.kernelConstraint),this.recurrentConstraint=on(e.recurrentConstraint),this.biasConstraint=on(e.biasConstraint),this.dropout=Uu([1,No([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Uu([1,No([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;e=At(e);let n=e[e.length-1];this.kernel=this.addWeight("kernel",[n,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let s;if(this.useBias){if(this.unitForgetBias){let r=this.biasInitializer,a=this.units;s=new(t=class extends Js{apply(i,l){let c=r.apply([a]),u=new Hf().apply([a]),d=r.apply([a*2]);return Yv(Yv(c,u),d)}},t.className="CustomInit",t)}else s=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,s,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return j(()=>{let n=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new q(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let s=e[1],r=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Do({ones:()=>vs(e),rate:this.dropout,training:n,count:4})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Do({ones:()=>vs(s),rate:this.recurrentDropout,training:n,count:4}));let a=this.dropoutMask,o=this.recurrentDropoutMask,i,l,c,u;0<this.dropout&&this.dropout<1&&(e=L(e,a[0]));let d=Dr(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(s=L(s,o[0])),d=ue(d,Dr(s,this.recurrentKernel.read())),this.useBias&&(d=mr(d,this.bias.read()));let[p,h,f,m]=xn(d,4,d.rank-1);i=this.recurrentActivation.apply(p),l=this.recurrentActivation.apply(h),c=ue(L(l,r),L(i,this.activation.apply(f))),u=this.recurrentActivation.apply(m);let g=L(u,this.activation.apply(c));return[g,g,c]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Ro(this.activation),recurrentActivation:Ro(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Bt(this.kernelInitializer),recurrentInitializer:Bt(this.recurrentInitializer),biasInitializer:Bt(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:It(this.kernelRegularizer),recurrentRegularizer:It(this.recurrentRegularizer),biasRegularizer:It(this.biasRegularizer),activityRegularizer:It(this.activityRegularizer),kernelConstraint:an(this.kernelConstraint),recurrentConstraint:an(this.recurrentConstraint),biasConstraint:an(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign({},e,t)}};Yd.className="LSTMCell";de.registerClass(Yd);var Fy=class extends Fr{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Yd(e);super(e)}call(e,t){return j(()=>{this.cell.dropoutMask!=null&&(te(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(te(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};Fy.className="LSTM";de.registerClass(Fy);var fm=class extends Zd{constructor(e){super(e);this.cells=e.cells}get stateSize(){let e=[];for(let t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return j(()=>{e=e;let n=e.slice(1),s=[];for(let o of this.cells.slice().reverse())Array.isArray(o.stateSize)?s.push(n.splice(0,o.stateSize.length)):s.push(n.splice(0,1));s.reverse();let r=[],a;for(let o=0;o<this.cells.length;++o){let i=this.cells[o];n=s[o],o===0?a=[e[0]].concat(n):a=[a[0]].concat(n),a=i.call(a,t),r.push(a.slice(1))}n=[];for(let o of r.slice().reverse())n.push(...o);return[a[0]].concat(n)})}build(e){ey(e)&&(e=e[0]),e=e;let t;this.cells.forEach((n,s)=>{ll(`RNNCell_${s}`,()=>{n.build(e),Array.isArray(n.stateSize)?t=n.stateSize[0]:t=n.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){let e=super.getConfig(),t=r=>({className:r.getClassName(),config:r.getConfig()}),s={cells:this.cells.map(t)};return Object.assign({},e,s)}static fromConfig(e,t,n={}){let s=[];for(let r of t.cells)s.push(yr(r,n));return new e({cells:s})}get trainableWeights(){if(!this.trainable)return[];let e=[];for(let t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.cells)t.push(...n.trainableWeights);return t.concat(e)}return e}getWeights(){let e=[];for(let t of this.cells)e.push(...t.weights);return ty(e)}setWeights(e){let t=[];for(let n of this.cells){let s=n.weights.length,r=e.splice(s);for(let a=0;a<n.weights.length;++a)t.push([n.weights[a],r[a]])}ny(t)}};fm.className="StackedRNNCells";de.registerClass(fm);function Do(e){let{ones:t,rate:n,training:s=!1,count:r=1}=e,a=()=>Qv(t(),n),o=()=>Wd(a,t,s);return!r||r<=1?An(o().clone()):Array(r).fill(void 0).map(o).map(l=>An(l.clone()))}var QL=function(e,t){var n={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(e);r<s.length;r++)t.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(e,s[r])&&(n[s[r]]=e[s[r]]);return n},sk=class extends Fr{constructor(e){if(e.unroll)throw new Ve("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Ve("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new Yt({ndim:5})]}call(e,t){return j(()=>{if(this.cell.dropoutMask!=null&&(te(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(te(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new q("ConvRNN2D cell does not support constants");let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})})}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return j(()=>{let{stateSize:t}=this.cell,n=e.shape,s=this.computeSingleOutputShape(n),r=[s[0],...s.slice(2)],a=qt(r);return Array.isArray(t)?Array(t.length).fill(a):[a]})}resetStates(e,t=!1){j(()=>{if(!this.stateful)throw new sa("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape,s=this.computeSingleOutputShape(n),r=[s[0],...s.slice(2)];if(n[0]==null)throw new q("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.getStates()==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>qt(r)):this.states_=[qt(r)];else if(e==null)te(this.states_),this.keptStates!=null&&(te(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>qt(r)):this.states_[0]=qt(r);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new q(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):te(this.states_);for(let o=0;o<this.states_.length;++o){let i=e[o],l=r;if(!v.arraysEqual(i.shape,l))throw new q(`State ${o} is incompatible with layer ${this.name}: expected shape=${l}, received shape=${i.shape}`);this.states_[o]=i}}this.states_=this.states_.map(o=>An(o.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:n,kernelSize:s,padding:r,strides:a,dilationRate:o}=this.cell,i=t==="channelsFirst",l=e[i?3:2],c=e[i?4:3],u=Ar(l,s[0],r,a[0],o[0]),d=Ar(c,s[1],r,a[1],o[1]);return[...e.slice(0,2),...i?[n,u,d]:[u,d,n]]}};sk.className="ConvRNN2D";var mm=class extends Yd{constructor(e){let{filters:t,kernelSize:n,strides:s,padding:r,dataFormat:a,dilationRate:o}=e;super(Object.assign({},e,{units:t}));this.filters=t,bn(this.filters,"filters"),this.kernelSize=Xu(n,2,"kernelSize"),this.kernelSize.forEach(i=>bn(i,"kernelSize")),this.strides=Xu(s||1,2,"strides"),this.strides.forEach(i=>bn(i,"strides")),this.padding=r||"valid",Ms(this.padding),this.dataFormat=a||"channelsLast",Xt(this.dataFormat),this.dilationRate=Xu(o||1,2,"dilationRate"),this.dilationRate.forEach(i=>bn(i,"dilationRate"))}build(e){var t;e=At(e);let n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new q(`The channel dimension of the input should be defined. Found ${e[n]}`);let s=e[n],r=4,a=this.kernelSize.concat([s,this.filters*r]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let o=this.kernelSize.concat([this.filters,this.filters*r]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",o,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let i;if(this.unitForgetBias){let l=this.biasInitializer,c=this.filters;i=new(t=class extends Js{apply(d,p){let h=l.apply([c]),f=bs([c]),m=l.apply([c*2]);return G1([h,f,m])}},t.className="CustomInit",t)}else i=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*r],null,i,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return j(()=>{if(e.length!==3)throw new q(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training||!1,s=e[0],r=e[1],a=e[2],o=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Do({ones:()=>vs(s),rate:this.dropout,training:n,count:o}));let i=this.dropoutMask,l=(ee,J,Q)=>!J||!J[Q]?ee:L(J[Q],ee),c=l(s,i,0),u=l(s,i,1),d=l(s,i,2),p=l(s,i,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Do({ones:()=>vs(r),rate:this.recurrentDropout,training:n,count:o}));let h=this.recurrentDropoutMask,f=l(r,h,0),m=l(r,h,1),g=l(r,h,2),y=l(r,h,3),A=3,[x,b,w,k]=xn(this.kernel.read(),o,A),[S,N,$,F]=this.useBias?xn(this.bias.read(),o):[null,null,null,null];c=this.inputConv(c,x,S,this.padding),u=this.inputConv(u,b,N,this.padding),d=this.inputConv(d,w,$,this.padding),p=this.inputConv(p,k,F,this.padding);let[R,D,T,O]=xn(this.recurrentKernel.read(),o,A);f=this.recurrentConv(f,R),m=this.recurrentConv(m,D),g=this.recurrentConv(g,T),y=this.recurrentConv(y,O);let B=this.recurrentActivation.apply(ue(c,f)),H=this.recurrentActivation.apply(ue(u,m)),z=ue(L(H,a),L(B,this.activation.apply(ue(d,g)))),X=L(this.recurrentActivation.apply(ue(p,y)),this.activation.apply(z));return[X,X,z]})}getConfig(){let e=super.getConfig(),{units:t}=e,n=QL(e,["units"]),s={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign({},n,s)}inputConv(e,t,n,s){let r=Qr(e,t,this.strides,s||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?mr(r,n,this.dataFormat):r}recurrentConv(e,t){return Qr(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};mm.className="ConvLSTM2DCell";de.registerClass(mm);var Oy=class extends sk{constructor(e){let t=new mm(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}};Oy.className="ConvLSTM2D";de.registerClass(Oy);var gm=class extends rt{constructor(e){super(e);this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(this.noiseShape==null)return this.noiseShape;let t=e.shape,n=[];for(let s=0;s<this.noiseShape.length;++s)n.push(this.noiseShape[s]==null?t[s]:this.noiseShape[s]);return n}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ge(e);if(0<this.rate&&this.rate<1){let s=t.training==null?!1:t.training,r=this.getNoiseShape(n);return Wd(()=>Qv(n,this.rate,r,this.seed),()=>n,s)}return e})}getConfig(){let e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}};gm.className="Dropout";de.registerClass(gm);var My=class extends gm{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};My.className="SpatialDropout1D";de.registerClass(My);var zy=class extends rt{constructor(e){super(e);if(this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,bn(this.units,"units"),this.activation=$o(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=Pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=on(e.kernelConstraint),this.biasConstraint=on(e.biasConstraint),this.kernelRegularizer=Ft(e.kernelRegularizer),this.biasRegularizer=Ft(e.biasRegularizer),this.activityRegularizer=Ft(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=At(e);let t=e[e.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){e=At(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ge(e),s=Vv(this.activation.getClassName()),r;return s!=null?r=Dr(n,this.kernel.read(),s,this.bias?this.bias.read():null):(r=Dr(n,this.kernel.read()),this.bias!=null&&(r=mr(r,this.bias.read())),this.activation!=null&&(r=this.activation.apply(r))),r})}getConfig(){let e={units:this.units,activation:Ro(this.activation),useBias:this.useBias,kernelInitializer:Bt(this.kernelInitializer),biasInitializer:Bt(this.biasInitializer),kernelRegularizer:It(this.kernelRegularizer),biasRegularizer:It(this.biasRegularizer),activityRegularizer:It(this.activityRegularizer),kernelConstraint:an(this.kernelConstraint),biasConstraint:an(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};zy.className="Dense";de.registerClass(zy);var Ly=class extends rt{constructor(e){e=e||{};super(e);this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=At(e);for(let t of e.slice(1))if(t==null)throw new q(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],To(e,1)]}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ge(e);if(this.dataFormat==="channelsFirst"&&n.rank>1){let s=[0];for(let r=2;r<n.rank;++r)s.push(r);s.push(1),n=et(n,s)}return Az(n)})}getConfig(){let e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);let t=super.getConfig();return Object.assign(e,t),e}};Ly.className="Flatten";de.registerClass(Ly);var By=class extends rt{constructor(e){super(e);this.supportsMasking=!0,this.activation=$o(e.activation)}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ge(e);return this.activation.apply(n)})}getConfig(){let e={activation:Ro(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};By.className="Activation";de.registerClass(By);var Wy=class extends rt{constructor(e){super(e);this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return j(()=>(e=Ge(e),gz(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};Wy.className="RepeatVector";de.registerClass(Wy);var Vy=class extends rt{constructor(e){super(e);this.targetShape=e.targetShape;for(let t=0;t<this.targetShape.length;++t)this.isUnknown(this.targetShape[t])&&(this.targetShape[t]=null)}isUnknown(e){return e<0||e==null}fixUnknownDimension(e,t){let n="Total size of new array must be unchanged.",s=t.slice(),r=1,a=null;for(let i=0;i<s.length;++i){let l=s[i];if(this.isUnknown(l))if(a===null)a=i;else throw new q("Can only specifiy one unknown dimension.");else r*=l}let o=To(e);if(a!==null){if(r===0||o%r!=0)throw new q(n);s[a]=o/r}else if(o!==r)throw new q(n);return s}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ge(e),s=n.shape,r=s.slice(0,1).concat(this.fixUnknownDimension(s.slice(1),this.targetShape));return G(n,r)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};Vy.className="Reshape";de.registerClass(Vy);var Uy=class extends rt{constructor(e){super(e);if(e.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);let t=fr(1,e.dims.length+1);if(!v.arraysEqual(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new Yt({ndim:this.dims.length+1})]}computeOutputShape(e){e=At(e);let t=e.slice();return this.dims.forEach((n,s)=>{t[s+1]=e[n]}),t}call(e,t){return et(Ge(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};Uy.className="Permute";de.registerClass(Uy);var Gy=class extends rt{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null?this.maskValue=e.maskValue==null?0:e.maskValue:this.maskValue=0}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){let n=Ge(e),s=-1;return Ad(tl(n,this.maskValue),s)}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ge(e),s=-1,r=!0,a=Ad(tl(n,this.maskValue),s,r);return L(n,pe(a,n.dtype))})}};Gy.className="Masking";de.registerClass(Gy);var Hy=class extends rt{constructor(e){super(e);if(this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(Nt(e.inputLength))}this.inputDim=e.inputDim,bn(this.inputDim,"inputDim"),this.outputDim=e.outputDim,bn(this.outputDim,"outputDim"),this.embeddingsInitializer=Pt(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Ft(e.embeddingsRegularizer),this.activityRegularizer=Ft(e.activityRegularizer),this.embeddingsConstraint=on(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return j(()=>this.maskZero?(e=Ge(e),tl(e,tt(e))):null)}computeOutputShape(e){if(e=At(e),this.inputLength==null)return[...e,this.outputDim];let t=Nt(this.inputLength);if(t.length!==e.length-1)throw new q(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let s=0;s<t.length;++s){let r=t[s],a=e[s+1];if(r!=null&&a!=null&&r!==a)throw new q(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);r==null&&(t[n]=a),n++}}return[e[0],...t,this.outputDim]}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ge(e);n.dtype!=="int32"&&(n=Vf(n,"int32"));let s=Jv(this.embeddings.read(),G(n,[n.size]));return G(s,At(this.computeOutputShape(n.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Bt(this.embeddingsInitializer),embeddingsRegularizer:It(this.embeddingsRegularizer),activityRegularizer:It(this.activityRegularizer),embeddingsConstraint:an(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};Hy.className="Embedding";de.registerClass(Hy);var hl=class extends rt{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new Ve}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(t.length===0)return e;let n=e.slice(0,e.length-t.length);for(let s=0;s<t.length;++s){let r=e[e.length-t.length+s],a=t[s];if(r==null||a==null||r<0||a<0)n.push(null);else if(r===1)n.push(a);else if(a===1)n.push(r);else{if(r!==a)throw new q("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(r)}}return n}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[At(e)]),e=e,e.length<2)throw new q(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(let r of e)r!=null&&r[0]!==null&&t.push(r[0]);if(t=Co(t),t.length>1)throw new q(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=e[0]==null?null:e[0].slice(1);for(let r=1;r<e.length;++r){let a=e[r]==null?null:e[r].slice(1);n=this.computeElementwiseOpOutputShape(n,a)}let s=e.map(r=>r.length);e.indexOf(null)===-1&&Co(s).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return j(()=>{if(e=e,this.reshapeRequired){let n=[],s=e.map(r=>r.rank);if(s.indexOf(null)===-1){let r=No(s);for(let a of e){let o=a.rank;for(let i=0;i<r-o;++i)a=Ld(a,1);n.push(a)}return this.mergeFunction(n)}else{let r=!1;for(let i of e){let l=i.rank;if(l==null){let c=i.shape,u=c[0],d=c.slice(1).concat([u]),p=G(i,[u].concat(To(c.slice(1))));p=et(p,[1,0]),p=G(p,d),n.push(p),r=!0}else if(l>1){let c=fr(1,l).concat([0]);n.push(et(i,c)),r=!0}else n.push(i)}let a=this.mergeFunction(n),o=a.rank;if(r){if(o==null){let i=a.shape,l=i.length,c=i[l-1],u=[c].concat(i.slice(0,i.length-1));a=G(et(G(a,[-1,c]),[1,0]),u)}else if(o>1){let i=[o-1].concat(fr(0,o-1));a=et(a,i)}}return a}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let s=1;s<e.length;++s){let r=e[s]==null?null:e[s].slice(1);t=this.computeElementwiseOpOutputShape(t,r)}let n=[];for(let s of e)s!=null&&s[0]!==null&&n.push(s[0]);return n=Co(n),n.length===1?t=n.concat(t):t=[null].concat(t),t}computeMask(e,t){return j(()=>{if(t==null)return null;if(!Array.isArray(t))throw new q("`mask` should be an Array");if(!Array.isArray(e))throw new q("`inputs` should be an Array");if(t.length!==e.length)throw new q(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(s=>s==null))return null;t=t.map(s=>s==null?s:jt(s,0));let n=t[0];for(let s=1;s<t.length-1;++s)n=Ks(n,t[s]);return n})}},jy=class extends hl{constructor(e){super(e)}mergeFunction(e){return j(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=ue(t,e[n]);return t})}};jy.className="Add";de.registerClass(jy);var qy=class extends hl{constructor(e){super(e)}mergeFunction(e){return j(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=L(t,e[n]);return t})}};qy.className="Multiply";de.registerClass(qy);var Xy=class extends hl{constructor(e){super(e)}mergeFunction(e){return j(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=ue(t,e[n]);return L(1/e.length,t)})}};Xy.className="Average";de.registerClass(Xy);var Ky=class extends hl{constructor(e){super(e)}mergeFunction(e){return j(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Rr(t,e[n]);return t})}};Ky.className="Maximum";de.registerClass(Ky);var Zy=class extends hl{constructor(e){super(e)}mergeFunction(e){return j(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Fu(t,e[n]);return t})}};Zy.className="Minimum";de.registerClass(Zy);var Yy=class extends hl{constructor(e){super(e);this.DEFAULT_AXIS=-1,e==null&&(e={}),this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){if(!(Array.isArray(e)&&Array.isArray(e[0]))||e.length===1)throw new q("A `Concatenate` layer should be called on a list of at least 2 inputs");e=e;let t=!0;for(let s of e)if(s!=null){t=!1;break}if(t)return;let n=[];for(let s=0;s<e.length;++s){let r=e[s].slice();r.splice(this.axis,1);let a=!1;for(let o of n)if(v.arraysEqual(o,r)){a=!0;break}a||n.push(r)}if(n.length>1)throw new q("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return j(()=>G1(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new q("A `Concatenate` layer should be called on a list of inputs.");let t=e,n=t[0].slice(),s=this.axis<0?n.length+this.axis:this.axis;for(let r of t.slice(1)){if(n[s]==null||r[s]==null){n[s]=null;break}n[s]+=r[s]}return n}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new q("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new q("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new q(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return j(()=>{let n=!0;if(t.forEach(a=>{if(a!=null){n=!1;return}}),n)return null;let s=[];for(let a=0;a<e.length;++a)t[a]==null?s.push(pe(vs(e[a]),"bool")):t[a].rank<e[a].rank?s.push(jt(t[a],-1)):s.push(t[a]);let r=kt(s,this.axis);return sf(r,-1,!1)})}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};Yy.className="Concatenate";de.registerClass(Yy);function Jd(e,t){for(;e<0;)e+=t;return e}function eB(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new Ve("batchDot is not implemented for tensors of 4D or higher rank yet");if(v.assert(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),v.assert(e.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`),typeof n=="number"&&(n=[n,n]),e.dtype==="complex64"||t.dtype==="complex64")throw new Ve("batchDot is not implemented for complex64-type Tensors yet.");let s=e.shape.length,r=t.shape.length;n==null&&(n=[s-1,r-2]);let a=n;return j(()=>{let o;if(s>r){o=s-r;let l=[];for(let c=0;c<o;++c)l.push(1);t=G(t,t.shape.concat(l))}else if(r>s){o=r-s;let l=[];for(let c=0;c<o;++c)l.push(1);e=G(e,e.shape.concat(l))}else o=0;let i;if(e.shape.length===2&&t.shape.length===2)a[0]===a[1]?i=ke(L(e,t),a[0]):i=ke(L(et(e,[1,0]),t),a[1]);else{let l=a[0]!==e.shape.length-1,c=a[1]===t.shape.length-1;i=Xe(e,t,l,c)}if(o>0){let l;s>r?l=s+r-3:l=s-1;let c=[];for(let u=l;u<l+o;++u)c.push(u);i=dt(i,c)}return i.shape.length===1&&(i=jt(i,1)),i})}var Jy=class extends hl{constructor(e){super(e);this.axes=e.axes,this.normalize=e.normalize==null?!1:e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){v.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0],n=e[1];if(t.length>3||n.length>3)throw new Ve("Dot layer does not support tensors of 4D or higher rank yet.");let s=this.interpretAxes(t,n);if(t[s[0]]!==n[s[1]])throw new q(`Dimension incompatibility: ${t[s[0]]} !== ${n[s[1]]}`)}mergeFunction(e){if(e.length!==2)throw new q(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],n=e[1],s;return Array.isArray(this.axes)?s=this.axes.map((r,a)=>Jd(r,e[a].shape.length)):s=[Jd(this.axes,t.shape.length),Jd(this.axes,n.shape.length)],this.normalize&&(t=sm(t,s[0]),n=sm(n,s[1])),eB(t,n,s)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[Jd(this.axes,e.length),Jd(this.axes,t.length)],n}computeOutputShape(e){v.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new Ve("Dot layer does not support tensors of 4D or higher rank yet.");let s=this.interpretAxes(t,n);t.splice(s[0],1),n.splice(s[1],1),n.splice(0,1);let r=t.concat(n);return r.length===1&&r.push(1),r}computeMask(e,t){return null}getConfig(){let e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}};Jy.className="Dot";de.registerClass(Jy);var Qy=class extends rt{constructor(e){super(e);this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ge(e);return Wd(()=>ue(Gf(n.shape,0,this.stddev),n),()=>n,t.training||!1)})}};Qy.className="GaussianNoise";de.registerClass(Qy);var eA=class extends rt{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ge(e);return this.rate>0&&this.rate<1?Wd(()=>{let r=Math.sqrt(this.rate/(1-this.rate));return L(n,Gf(n.shape,1,r))},()=>n,t.training||!1):n})}};eA.className="GaussianDropout";de.registerClass(eA);var tA=class extends rt{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Ge(e).shape}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return j(()=>{if(this.rate<1&&this.rate>0){let n=this._getNoiseShape(e);return Wd(()=>{let r=Ge(e),a=1.6732632423543772,o=1.0507009873554805,i=-a*o,l=ko(Ou(n),this.rate);l=Vf(l,"float32");let c=((1-this.rate)*(1+this.rate*i**2))**-.5,u=-c*i*this.rate,d=ue(L(r,l),L(ue(l,-1),i));return ue(L(d,c),u)},()=>Ge(e),t.training||!1)}return e})}};tA.className="AlphaDropout";de.registerClass(tA);function Qd(e,t,n,s,r,a=.001){let o;if(e.rank===2)o=P3(e,t,n,s,r,a);else if(e.rank===3)o=F3(e,t,n,s,r,a);else if(e.rank===4)o=O3(e,t,n,s,r,a);else throw new Ve(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return o}function tB(e,t,n,s,r=.001){return j(()=>{let a=mf(e,s),o=a.mean,i=a.variance;return[Qd(e,o,i,n,t,r),o,i]})}function nB(e,t,n,s,r=.001){return j(()=>{let a=mf(e,s),o=a.mean,i=a.variance,l=[];for(let f of fr(0,e.rank))s.indexOf(f)!==-1?l.push(1):l.push(e.shape[f]);let c=G(o,l),u=G(i,l),d=t==null?null:G(t,l),p=n==null?null:G(n,l);return[Qd(e,c,u,p,d,r),o,i]})}function sB(e,t,n,s,r=.001){return v.arraysEqual(s.slice().sort(),fr(0,e.rank-1))?tB(e,t,n,s,r):nB(e,t,n,s,r)}var nA=class extends rt{constructor(e){e==null&&(e={});super(e);this.supportsMasking=!0,this.axis=e.axis==null?-1:e.axis,this.momentum=e.momentum==null?.99:e.momentum,this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=Pt(e.betaInitializer||"zeros"),this.gammaInitializer=Pt(e.gammaInitializer||"ones"),this.movingMeanInitializer=Pt(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Pt(e.movingVarianceInitializer||"ones"),this.betaConstraint=on(e.betaConstraint),this.gammaConstraint=on(e.gammaConstraint),this.betaRegularizer=Ft(e.betaRegularizer),this.gammaRegularizer=Ft(e.gammaRegularizer)}build(e){e=At(e);let t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new q(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Yt({ndim:e.length,axes:{[t]:n}})];let s=[n];this.scale&&(this.gamma=this.addWeight("gamma",s,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",s,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",s,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",s,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return j(()=>{let n=t.training==null?!1:t.training,s=Ge(e),r=s.shape,a=r.length,o=fr(0,a),i=this.axis>=0?this.axis:this.axis+a;o.splice(i,1);let l=al(1,a);l[i]=r[i];let c=o.slice();c.sort();let u=!v.arraysEqual(c,fr(0,a).slice(0,a-1)),d=()=>{if(u){let y=G(this.movingMean.read(),l),A=G(this.movingVariance.read(),l),x=this.center?G(this.beta.read(),l):null,b=this.scale?G(this.gamma.read(),l):null;return Qd(s,y,A,x,b,this.epsilon)}else return Qd(s,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!n)return d();let[p,h,f]=sB(s,this.gamma.read(),this.beta.read(),o,this.epsilon),m=(y,A,x)=>{j(()=>{let b=1-x,w=y.read(),k=L(xe(w,A),b);y.write(xe(w,k))})};return(()=>{m(this.movingMean,h,this.momentum),m(this.movingVariance,f,this.momentum)})(),p})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Bt(this.betaInitializer),gammaInitializer:Bt(this.gammaInitializer),movingMeanInitializer:Bt(this.movingMeanInitializer),movingVarianceInitializer:Bt(this.movingVarianceInitializer),betaRegularizer:It(this.betaRegularizer),gammaRegularizer:It(this.gammaRegularizer),betaConstraint:an(this.betaConstraint),gammaConstraint:an(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};nA.className="BatchNormalization";de.registerClass(nA);var sA=class extends rt{constructor(e){e==null&&(e={});super(e);if(this.axis=e.axis==null?-1:e.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(let t of this.axis)if(!Number.isInteger(t))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=Pt(e.betaInitializer||"zeros"),this.gammaInitializer=Pt(e.gammaInitializer||"ones"),this.betaRegularizer=Ft(e.betaRegularizer),this.gammaRegularizer=Ft(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=At(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let r=0;r<this.axis.length;++r)this.axis[r]<0&&(this.axis[r]+=t);for(let r of this.axis)if(r<0||r>=t)throw new Error(`Invalid axis: ${r}`);if(this.axis.length!==Co(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);let n=this.axis.map(r=>e[r]),s=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,s):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,s):this.beta=null,this.built=!0}call(e,t){let n=Ge(e),s=n.shape,r=s.length;return j(()=>{let a=!0,{mean:o,variance:i}=mf(n,this.axis,a),l=al(1,r);for(let f of this.axis)l[f]=s[f];let c=f=>f!=null&&f.shape.length!==r&&this.axis!==[r-1]?G(f,l):f,u=c(this.gamma.read()),d=c(this.beta.read()),p=[],h=[];for(let f=0;f<r;++f)this.axis.indexOf(f)!==-1?(p.push(s[f]),h.push(1)):(p.push(1),h.push(s[f]));return o=Os(o,p),i=Os(i,p),u=Os(u,h),d=Os(d,h),Qd(n,o,i,d,u,this.epsilon)})}getConfig(){let e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Bt(this.betaInitializer),gammaInitializer:Bt(this.gammaInitializer),betaRegularizer:It(this.betaRegularizer),gammaRegularizer:It(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}};sA.className="LayerNormalization";de.registerClass(sA);function rB(e,t,n){return j(()=>{if(e.rank!==4)throw new q(`temporalPadding expects input tensor to be 4-D, but received a ${e.rank}-D tensor.`);if(t==null&&(t=[[1,1],[1,1]]),t.length!==2||t[0].length!==2||t[1].length!==2)throw new q("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=pr()),n!=="channelsLast"&&n!=="channelsFirst")throw new q(`Unknown data format: ${n}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let s;return n==="channelsFirst"?s=[[0,0],[0,0],t[0],t[1]]:s=[[0,0],t[0],t[1],[0,0]],ur(e,s)})}var rA=class extends rt{constructor(e){e==null&&(e={});super(e);if(this.dataFormat=e.dataFormat==null?pr():e.dataFormat,e.padding==null)this.padding=[[1,1],[1,1]];else if(typeof e.padding=="number")this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,e.padding.length!==2)throw new q(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new q(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],e.padding[1].length!==2)throw new q(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);n=e.padding[1]}this.padding=[t,n]}this.inputSpec=[new Yt({ndim:4})]}computeOutputShape(e){e=At(e);let t,n;return this.dataFormat==="channelsFirst"?(e[2]!=null&&e[2]>=0?t=e[2]+this.padding[0][0]+this.padding[0][1]:t=null,e[3]!=null&&e[3]>=0?n=e[3]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],e[1],t,n]):(e[1]!=null&&e[1]>=0?t=e[1]+this.padding[0][0]+this.padding[0][1]:t=null,e[2]!=null&&e[2]>=0?n=e[2]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],t,n,e[3]])}call(e,t){return j(()=>rB(Ge(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};rA.className="ZeroPadding2D";de.registerClass(rA);function ym(e,t,n,s,r,a){return j(()=>{Xt(r),jv(a),Ms(s),n==null&&(n=[1,1]),s==null&&(s="valid"),r==null&&(r=pr()),a==null&&(a="max"),e=Sy(e,r);let o,i=s==="same"?"same":"valid";return a==="max"?o=Cd(e,t,n,i):o=bd(e,t,n,i),r==="channelsFirst"&&(o=et(o,[0,3,1,2])),o})}function rk(e,t,n,s,r,a){return j(()=>{Xt(r),jv(a),Ms(s),n==null&&(n=[1,1,1]),s==null&&(s="valid"),r==null&&(r=pr()),a==null&&(a="max"),e=Jw(e,r);let o,i=s==="same"?"same":"valid";return a==="max"?o=f1(e,t,n,i):o=J2(e,t,n,i),r==="channelsFirst"&&(o=et(o,[0,4,1,2,3])),o})}var ak=class extends rt{constructor(e){e.poolSize==null&&(e.poolSize=2);super(e);if(typeof e.poolSize=="number")this.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")this.poolSize=e.poolSize;else throw new q(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(bn(this.poolSize,"poolSize"),e.strides==null)this.strides=this.poolSize;else if(typeof e.strides=="number")this.strides=[e.strides];else if(Array.isArray(e.strides)&&e.strides.length===1&&typeof e.strides[0]=="number")this.strides=e.strides;else throw new q(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);bn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,Ms(this.padding),this.inputSpec=[new Yt({ndim:3})]}computeOutputShape(e){e=At(e);let t=Ar(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return j(()=>{this.invokeCallHook(e,t),e=Ld(Ge(e),2);let n=this.poolingFunction(Ge(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return dt(n,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},aA=class extends ak{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return Xt(r),Ms(s),ym(e,t,n,s,r,"max")}};aA.className="MaxPooling1D";de.registerClass(aA);var oA=class extends ak{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return Xt(r),Ms(s),ym(e,t,n,s,r,"avg")}};oA.className="AveragePooling1D";de.registerClass(oA);var ok=class extends rt{constructor(e){e.poolSize==null&&(e.poolSize=[2,2]);super(e);if(this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new q(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];bn(this.poolSize,"poolSize"),bn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Xt(this.dataFormat),Ms(this.padding),this.inputSpec=[new Yt({ndim:4})]}computeOutputShape(e){e=At(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=Ar(t,this.poolSize[0],this.padding,this.strides[0]),n=Ar(n,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return j(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ge(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},iA=class extends ok{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return Xt(r),Ms(s),ym(e,t,n,s,r,"max")}};iA.className="MaxPooling2D";de.registerClass(iA);var lA=class extends ok{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return Xt(r),Ms(s),ym(e,t,n,s,r,"avg")}};lA.className="AveragePooling2D";de.registerClass(lA);var ik=class extends rt{constructor(e){e.poolSize==null&&(e.poolSize=[2,2,2]);super(e);if(this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new q(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];bn(this.poolSize,"poolSize"),bn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Xt(this.dataFormat),Ms(this.padding),this.inputSpec=[new Yt({ndim:5})]}computeOutputShape(e){e=At(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],s=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=Ar(t,this.poolSize[0],this.padding,this.strides[0]),n=Ar(n,this.poolSize[1],this.padding,this.strides[1]),s=Ar(s,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n,s]:[e[0],t,n,s,e[4]]}call(e,t){return j(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ge(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},uA=class extends ik{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return Xt(r),Ms(s),rk(e,t,n,s,r,"max")}};uA.className="MaxPooling3D";de.registerClass(uA);var cA=class extends ik{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return Xt(r),Ms(s),rk(e,t,n,s,r,"avg")}};cA.className="AveragePooling3D";de.registerClass(cA);var lk=class extends rt{constructor(e){super(e);this.inputSpec=[new Yt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Ve}},dA=class extends lk{constructor(e){super(e||{})}call(e,t){return j(()=>{let n=Ge(e);return Lt(n,1)})}};dA.className="GlobalAveragePooling1D";de.registerClass(dA);var pA=class extends lk{constructor(e){super(e||{})}call(e,t){return j(()=>{let n=Ge(e);return Bn(n,1)})}};pA.className="GlobalMaxPooling1D";de.registerClass(pA);var uk=class extends rt{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Xt(this.dataFormat),this.inputSpec=[new Yt({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Ve}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},hA=class extends uk{call(e,t){return j(()=>{let n=Ge(e);return this.dataFormat==="channelsLast"?Lt(n,[1,2]):Lt(n,[2,3])})}};hA.className="GlobalAveragePooling2D";de.registerClass(hA);var fA=class extends uk{call(e,t){return j(()=>{let n=Ge(e);return this.dataFormat==="channelsLast"?Bn(n,[1,2]):Bn(n,[2,3])})}};fA.className="GlobalMaxPooling2D";de.registerClass(fA);var ck=class extends rt{constructor(e){super(e);this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(e){this.layer!=null&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){let e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){let s=t.layer,r=yr(s,n);delete t.layer;let a={layer:r};return Object.assign(a,t),new e(a)}},mA=class extends ck{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=At(e),e.length<3)throw new q(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];let t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=At(e);let t=[e[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),s=e[1];return[n[0],s].concat(n.slice(1))}call(e,t){return j(()=>(e=Ge(e),nk((a,o)=>[Ge(this.layer.call(a,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};mA.className="TimeDistributed";de.registerClass(mA);function aB(e){il(dz,"BidirectionalMergeMode",e)}var oB="concat",gA=class extends ck{constructor(e){super(e);let t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=yr(n),t.goBackwards=t.goBackwards!==!0;let s={};if(s.className=e.layer.getClassName(),s.config=t,this.backwardLayer=yr(s),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?oB:e.mergeMode,aB(this.mergeMode),e.weights)throw new Ve("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){let t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let n,s,r;return this.returnState&&(r=t.slice(1)),n=t[0],n=n,this.mergeMode==="concat"?(n[n.length-1]*=2,s=[n]):this.mergeMode==null?s=[n,n.slice()]:s=[n],this.returnState?this.mergeMode==null?s.concat(r).concat(r.slice()):[n].concat(r).concat(r.slice()):as(s)}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});let r=tk(e,n,s,this.numConstants);if(e=r.inputs,n=r.initialState,s=r.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(n==null||n.length===0)&&s==null)return super.apply(e,t);let a=[],o=[];if(n!=null){let l=n.length;if(l%2>0)throw new q("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,a.push(...n);let c=n.map(u=>new Yt({shape:u.shape}));this.forwardLayer.stateSpec=c.slice(0,l/2),this.backwardLayer.stateSpec=c.slice(l/2),o.push(...c)}if(s!=null)throw new Ve("Support for constants in Bidirectional layers is not implemented yet.");let i=a[0]instanceof gr;for(let l of a)if(l instanceof gr!==i)throw new q("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(i){let l=[e].concat(a),c=this.inputSpec.concat(o),u=this.inputSpec;this.inputSpec=c;let d=super.apply(l,t);return this.inputSpec=u,d}else return super.apply(e,t)}call(e,t){return j(()=>{let n=t.initialState,s,r;if(n==null)s=this.forwardLayer.call(e,t),r=this.backwardLayer.call(e,t);else{let i=n.slice(0,n.length/2),l=n.slice(n.length/2);s=this.forwardLayer.call(e,Object.assign(t,{initialState:i})),r=this.backwardLayer.call(e,Object.assign(t,{initialState:l}))}let a;this.returnState&&(Array.isArray(s)&&(a=s.slice(1).concat(r.slice(1))),s=s[0],r=r[0]),this.returnSequences&&(r=ws(r,1));let o;return this.mergeMode==="concat"?o=G1([s,r]):this.mergeMode==="sum"?o=ue(s,r):this.mergeMode==="ave"?o=L(.5,ue(s,r)):this.mergeMode==="mul"?o=L(s,r):this.mergeMode==null&&(o=[s,r]),this.returnState?this.mergeMode==null?o.concat(a):[o].concat(a):o})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){ll(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),ll(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let n;if(this.returnSequences?this.mergeMode==null?n=[t,t]:n=t:this.mergeMode==null?n=[null,null]:n=null,this.returnState){let r=this.forwardLayer.states.map(a=>null);return Array.isArray(n)?n.concat(r).concat(r):[n].concat(r).concat(r)}else return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(e),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){let e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){let n=yr(t.layer);if(delete t.layer,t.numConstants!=null)throw new Ve("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let s=t;return s.layer=n,new e(s)}};gA.className="Bidirectional";de.registerClass(gA);function iB(e){return new Gu(e)}function lB(e){return new wy(e)}function uB(e){return new xy(e)}function cB(e){return new by(e)}function dB(e){return new vy(e)}function pB(e){return new Iy(e)}function hB(e){return new ky(e)}function fB(e){return new dm(e)}function mB(e){return new Xd(e)}function gB(e){return new Ty(e)}function yB(e){return new Kd(e)}function AB(e){return new Ny(e)}function xB(e){return new Ey(e)}function bB(e){return new Ry(e)}function vB(e){return new $y(e)}function wB(e){return new Dy(e)}function kB(e){return new By(e)}function IB(e){return new zy(e)}function SB(e){return new gm(e)}function CB(e){return new My(e)}function TB(e){return new Ly(e)}function NB(e){return new Wy(e)}function EB(e){return new Vy(e)}function RB(e){return new Uy(e)}function $B(e){return new Hy(e)}function DB(e){return new jy(e)}function _B(e){return new Xy(e)}function PB(e){return new Yy(e)}function FB(e){return new Ky(e)}function OB(e){return new Zy(e)}function MB(e){return new qy(e)}function zB(e){return new Jy(e)}function LB(e){return new nA(e)}function BB(e){return new sA(e)}function WB(e){return new rA(e)}function yA(e){return new oA(e)}function VB(e){return yA(e)}function UB(e){return yA(e)}function AA(e){return new lA(e)}function GB(e){return AA(e)}function HB(e){return AA(e)}function xA(e){return new cA(e)}function jB(e){return xA(e)}function qB(e){return xA(e)}function XB(e){return new dA(e)}function KB(e){return new hA(e)}function dk(e){return new pA(e)}function pk(e){return new fA(e)}function hk(e){return new aA(e)}function fk(e){return new iA(e)}function ZB(e){return new uA(e)}function YB(e){return new Py(e)}function JB(e){return new hm(e)}function QB(e){return new Fy(e)}function eW(e){return new Yd(e)}function tW(e){return new _y(e)}function nW(e){return new pm(e)}function sW(e){return new Oy(e)}function rW(e){return new mm(e)}function aW(e){return new Fr(e)}function oW(e){return new fm(e)}function iW(e){return new gA(e)}function lW(e){return new mA(e)}var uW=dk,cW=pk,dW=hk,pW=fk;function hW(e){return new Qy(e)}function fW(e){return new eA(e)}function mW(e){return new tA(e)}function gW(e){return new Gy(e)}var mk={};Le(mk,{MAPE:()=>TW,MSE:()=>RW,binaryAccuracy:()=>yW,binaryCrossentropy:()=>AW,categoricalAccuracy:()=>bW,categoricalCrossentropy:()=>vW,cosineProximity:()=>IW,mape:()=>NW,meanAbsoluteError:()=>SW,meanAbsolutePercentageError:()=>CW,meanSquaredError:()=>EW,mse:()=>$W,precision:()=>wW,recall:()=>kW,sparseCategoricalAccuracy:()=>xW});function yW(e,t){return ay(e,t)}function AW(e,t){return yw(e,t)}function xW(e,t){return Aw(e,t)}function bW(e,t){return oy(e,t)}function vW(e,t){return iy(e,t)}function wW(e,t){return gw(e,t)}function kW(e,t){return oL(e,t)}function IW(e,t){return sy(e,t)}function SW(e,t){return rm(e,t)}function CW(e,t){return ju(e,t)}function TW(e,t){return ju(e,t)}function NW(e,t){return ju(e,t)}function EW(e,t){return cl(e,t)}function RW(e,t){return cl(e,t)}function $W(e,t){return cl(e,t)}var gk={};Le(gk,{modelFromJSON:()=>BL});var yk={};Le(yk,{l1:()=>_W,l1l2:()=>DW,l2:()=>PW});function DW(e){return new jd(e)}function _W(e){return XL(e)}function PW(e){return KL(e)}var Ak=class extends Hu{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof aa))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function Am(e,t){return e<t}function xk(e,t){return e>t}var bk=class extends Ak{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new Ve("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=e.monitor||"val_loss",this.minDelta=Math.abs(e.minDelta||0),this.patience=e.patience||0,this.verbose=e.verbose||0,this.mode=e.mode||"auto",this.baseline=e.baseline,["auto","min","max"].indexOf(this.mode)===-1&&(console.warn(`EarlyStopping mode '${this.mode}' is invalid. Falling back to mode 'auto'.`),this.mode="auto"),this.mode==="min"?this.monitorFunc=Am:this.mode==="max"?this.monitorFunc=xk:this.monitor.indexOf("acc")!==-1?this.monitorFunc=xk:this.monitorFunc=Am,this.monitorFunc===Am&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Am?1/0:-1/0}async onEpochEnd(e,t){await Eo(t);let n=this.getMonitorValue(t);n!=null&&(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){e==null&&(e={});let t=e[this.monitor];return t==null&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}};function FW(e){return new bk(e)}var OW={earlyStopping:FW},xr;(function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF"})(xr||(xr={}));var vk;(function(e){let t;(function(n){n[n.LEGACY=0]="LEGACY",n[n.V1=1]="V1",n[n.V2=2]="V2"})(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(vk||(vk={}));var bA={};function MW(e,t){let n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};bA[e]=n}function wk(e){return bA[e]}function zW(e){delete bA[e]}function I(e,t,n,s,r){let a=t.inputParams[e];if(a&&a.inputIndexStart!==void 0){let i=a.inputIndexStart,l=a.inputIndexEnd===0?void 0:a.inputIndexEnd===void 0?i+1:a.inputIndexEnd;if(a.type==="tensor")return Un(t.inputNames[a.inputIndexStart],n,s,r);if(a.type==="tensors")return t.inputNames.slice(i,l).map(p=>Un(p,n,s,r));let c=Un(t.inputNames.slice(i)[0],n,s,r),u=c.dataSync();return a.type==="number"?u[0]:v.toNestedArray(c.shape,u)}let o=t.attrParams[e];return o&&o.value}function Un(e,t,n,s){let[r,a]=ks(e);if(s!=null){let i=s.getHashTableHandleByName(r);if(i!=null)return i}let o=n.currentContextIds.find(i=>!!t[xm(r,i)]);return o!==void 0?t[xm(r,o)][a]:void 0}function LW(e,t,n){return t[xm(e,n.currentContextId)]}function oa(e,t){let[n,s,r]=ks(e);return[xm(n,t&&t.currentContextId),s,r]}function xm(e,t){return t?`${e}-${t}`:e}function ks(e){let t=e.split(":");if(t.length===1)return[e,0,void 0];let n=t[0],s=t.length===3?t[1]:void 0,r=Number(t[t.length-1]);return[n,r,s]}function bm(e,t,n){let s=I("pad",e,t,n);if(s==="explicit"){s=I("explicitPaddings",e,t,n);let r=[[0,0],[0,0],[0,0],[0,0]];for(let a=0;a<4;a++)r[a][0]=s[a*2],r[a][1]=s[a*2+1];return r}return s}function ia(e){return e.kept?e:ir(e)}var kk={};Le(kk,{json:()=>BW});var BW=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],Ik={};Le(Ik,{json:()=>WW});var WW=[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],Sk={};Le(Sk,{json:()=>VW});var VW=[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]}],Ck={};Le(Ck,{json:()=>UW});var UW=[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number"}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}],Tk={};Le(Tk,{json:()=>GW});var GW=[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}],Nk={};Le(Nk,{json:()=>HW});var HW=[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],Ek={};Le(Ek,{json:()=>jW});var jW=[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}],Rk={};Le(Rk,{json:()=>qW});var qW=[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}],$k={};Le($k,{json:()=>XW});var XW=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]}],Dk={};Le(Dk,{json:()=>KW});var KW=[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]}],_k={};Le(_k,{json:()=>ZW});var ZW=[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],Pk={};Le(Pk,{json:()=>YW});var YW=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]}],Fk={};Le(Fk,{json:()=>JW});var JW=[{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}],Ok={};Le(Ok,{json:()=>QW});var QW=[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}],Mk={};Le(Mk,{json:()=>eV});var eV=[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}],zk={};Le(zk,{json:()=>tV});var tV=[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}],Lk={};Le(Lk,{json:()=>nV});var nV=[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}],Bk={};Le(Bk,{json:()=>sV});var sV=[{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}],Wk={};Le(Wk,{json:()=>rV});var rV=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}],Vk=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[kk,Ik,Sk,Ck,Tk,Nk,Ek,Rk,$k,Dk,_k,Pk,Fk,Ok,Mk,zk,Lk,Bk,Wk],t=[].concat(...e.map(n=>n.json));this.opMappers=t.reduce((n,s)=>(n[s.tfOpName]=s,n),{})}transformGraph(e,t={}){let n=e.node,s=[],r=[],a=[],o=n.reduce((f,m)=>(f[m.name]=this.mapNode(m),m.op.startsWith("Placeholder")?s.push(f[m.name]):m.op==="Const"?r.push(f[m.name]):(m.input==null||m.input.length===0)&&a.push(f[m.name]),f),{}),i=[],l=[],c={},u={};t!=null&&(c=this.mapSignatureEntries(t.inputs),u=this.mapSignatureEntries(t.outputs));let d=Object.keys(o);d.forEach(f=>{let m=o[f];m.inputNames.forEach((g,y)=>{let[A,,x]=oa(g),b=o[A];if(b.outputs!=null){let w=b.outputs.indexOf(x);if(w!==-1){let k=`${A}:${w}`;m.inputNames[y]=k}}m.inputs.push(b),b.children.push(m)})}),Object.keys(u).length===0?d.forEach(f=>{let m=o[f];m.children.length===0&&l.push(m)}):Object.keys(u).forEach(f=>{let[m]=oa(f),g=o[m];g!=null&&(g.signatureKey=u[f],l.push(g))}),Object.keys(c).length>0?Object.keys(c).forEach(f=>{let[m]=oa(f),g=o[m];g&&(g.signatureKey=c[f],i.push(g))}):i=s;let p={};e.library!=null&&e.library.function!=null&&(p=e.library.function.reduce((f,m)=>(f[m.signature.name]=this.mapFunction(m),f),{}));let h={nodes:o,inputs:i,outputs:l,weights:r,placeholders:s,signature:t,functions:p};return a.length>0&&(h.initNodes=a),h}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){let t=wk(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});let n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(s=>s.startsWith("^")?s.substr(1):s),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return t.inputs!=null&&(n.inputParams=t.inputs.reduce((s,r)=>(s[r.name]={type:r.type,inputIndexStart:r.start,inputIndexEnd:r.end},s),{})),t.attrs!=null&&(n.attrParams=t.attrs.reduce((s,r)=>{let a=r.type,o;switch(r.type){case"string":o=vA(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=vA(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"string[]":o=EA(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=EA(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number":o=kA(e.attr,r.tfName,r.defaultValue||0),o===void 0&&!!r.tfDeprecatedName&&(o=kA(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number[]":o=NA(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=NA(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool":o=wA(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=wA(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool[]":o=$A(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=$A(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape":o=TA(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=TA(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape[]":o=RA(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=RA(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype":o=SA(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=SA(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype[]":o=CA(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=CA(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"func":o=Gk(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=Gk(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${r.type} for op: ${e.op}`)}return s[r.name]={value:o,type:a},s},{})),n}mapFunction(e){let t=e.nodeDef,n=[],s=[],r={};t!=null&&(r=t.reduce((u,d)=>(u[d.name]=this.mapNode(d),d.op==="Const"&&s.push(u[d.name]),u),{}));let a=[],o=[];e.signature.inputArg.forEach(u=>{let[d]=oa(u.name),p={name:d,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:IA(u.type),type:"dtype"}},children:[]};p.signatureKey=u.name,a.push(p),r[d]=p}),Object.keys(r).forEach(u=>{let d=r[u];d.inputNames.forEach((p,h)=>{let[f,,m]=oa(p),g=r[f];if(g.outputs!=null){let y=g.outputs.indexOf(m);if(y!==-1){let A=`${f}:${y}`;d.inputNames[h]=A}}d.inputs.push(g),g.children.push(d)})});let l=e.ret;e.signature.outputArg.forEach(u=>{let[d,p]=oa(l[u.name]),h=r[d];h!=null&&(h.defaultOutput=p,o.push(h))});let c=this.mapArgsToSignature(e);return{nodes:r,inputs:a,outputs:o,weights:s,placeholders:n,signature:c}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n),t),{}),outputs:e.signature.outputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t),{})}}mapArgToTensorInfo(e,t){let n=e.name;return t!=null&&(n=t[n]),{name:n,dtype:e.type}}};function aV(e){let t=Z().global;if(typeof t.atob!="undefined")return t.atob(e);if(typeof Buffer!="undefined")return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function Uk(e,t){let n=Array.isArray(e)?String.fromCharCode.apply(null,e):aV(e);return t?n:n.toLowerCase()}function vA(e,t,n,s=!1){let r=e[t];return r!=null?Uk(r.s,s):n}function wA(e,t,n){let s=e[t];return s?s.b:n}function kA(e,t,n){let s=e[t]||{},r=s.i!=null?s.i:s.f!=null?s.f:n;return typeof r=="number"?r:parseInt(r,10)}function IA(e){switch(typeof e=="string"&&(e=xr[e]),e){case xr.DT_FLOAT:return"float32";case xr.DT_INT32:case xr.DT_INT64:case xr.DT_INT8:case xr.DT_UINT8:return"int32";case xr.DT_BOOL:return"bool";case xr.DT_DOUBLE:return"float32";case xr.DT_STRING:return"string";default:return null}}function Gk(e,t,n){let s=e[t];return s&&s.func?s.func.name:n}function SA(e,t,n){let s=e[t];return s&&s.type?IA(s.type):n}function CA(e,t,n){let s=e[t];return s&&s.list&&s.list.type?s.list.type.map(r=>IA(r)):n}function Hk(e){if(!e.unknownRank)return e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function TA(e,t,n){let s=e[t];return s&&s.shape?Hk(s.shape):n}function NA(e,t,n){let s=e[t];return s?((s.list.f&&s.list.f.length?s.list.f:s.list.i)||[]).map(r=>typeof r=="number"?r:parseInt(r,10)):n}function EA(e,t,n,s=!1){let r=e[t];return r&&r.list&&r.list.s?r.list.s.map(a=>Uk(a,s)):n}function RA(e,t,n){let s=e[t];return s&&s.list&&s.list.shape?s.list.shape.map(r=>Hk(r)):n}function $A(e,t,n){let s=e[t];return s&&s.list&&s.list.b?s.list.b:n}var oV=class{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(s=>this.getInput(s)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((s,r)=>(s[r]=this.getAttr(r),s),{}))}getInput(e){return Un(e,this.tensorMap,this.context)}getAttr(e,t){let n=this.node.rawAttrs[e];if(n.tensor!=null)return Un(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return kA(this.node.rawAttrs,e,t);if(n.s!=null)return vA(this.node.rawAttrs,e,t);if(n.b!=null)return wA(this.node.rawAttrs,e,t);if(n.shape!=null)return TA(this.node.rawAttrs,e,t);if(n.type!=null)return SA(this.node.rawAttrs,e,t);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return NA(this.node.rawAttrs,e,t);if(n.list.s!=null)return EA(this.node.rawAttrs,e,t);if(n.list.shape!=null)return RA(this.node.rawAttrs,e,t);if(n.list.b!=null)return $A(this.node.rawAttrs,e,t);if(n.list.type!=null)return CA(this.node.rawAttrs,e,t)}return t}},iV=(e,t,n)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[ue(I("a",e,t,n),I("b",e,t,n))];case"AddN":return[nf(I("tensors",e,t,n))];case"FloorMod":case"Mod":return[g1(I("a",e,t,n),I("b",e,t,n))];case"Mul":return[L(I("a",e,t,n),I("b",e,t,n))];case"RealDiv":case"Div":return[fe(I("a",e,t,n),I("b",e,t,n))];case"DivNoNan":return[a1(I("a",e,t,n),I("b",e,t,n))];case"FloorDiv":return[tf(I("a",e,t,n),I("b",e,t,n))];case"Sub":return[xe(I("a",e,t,n),I("b",e,t,n))];case"Minimum":return[Fu(I("a",e,t,n),I("b",e,t,n))];case"Maximum":return[Rr(I("a",e,t,n),I("b",e,t,n))];case"Pow":return[ea(I("a",e,t,n),I("b",e,t,n))];case"SquaredDifference":return[Sf(I("a",e,t,n),I("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},lV=(e,t,n)=>{switch(e.op){case"Abs":case"ComplexAbs":return[Kt(I("x",e,t,n))];case"Acos":return[V2(I("x",e,t,n))];case"Acosh":return[U2(I("x",e,t,n))];case"Asin":return[H2(I("x",e,t,n))];case"Asinh":return[j2(I("x",e,t,n))];case"Atan":return[q2(I("x",e,t,n))];case"Atan2":return[X2(I("x",e,t,n),I("y",e,t,n))];case"Atanh":return[K2(I("x",e,t,n))];case"Ceil":return[e1(I("x",e,t,n))];case"Complex":return[Ao(I("real",e,t,n),I("imag",e,t,n))];case"Cos":return[wd(I("x",e,t,n))];case"Cosh":return[lf(I("x",e,t,n))];case"Elu":return[Du(I("x",e,t,n))];case"Erf":return[o1(I("x",e,t,n))];case"Exp":return[As(I("x",e,t,n))];case"Expm1":return[i1(I("x",e,t,n))];case"Floor":return[Pu(I("x",e,t,n))];case"Log":return[xs(I("x",e,t,n))];case"Log1p":return[Id(I("x",e,t,n))];case"Imag":return[cf(I("x",e,t,n))];case"Neg":return[_t(I("x",e,t,n))];case"Reciprocal":return[x1(I("x",e,t,n))];case"Real":return[Rd(I("x",e,t,n))];case"Relu":return[cr(I("x",e,t,n))];case"Round":return[Af(I("x",e,t,n))];case"Selu":return[bf(I("x",e,t,n))];case"Sigmoid":return[ns(I("x",e,t,n))];case"Sin":return[vf(I("x",e,t,n))];case"Sign":return[v1(I("x",e,t,n))];case"Sinh":return[wf(I("x",e,t,n))];case"Softplus":return[Qi(I("x",e,t,n))];case"Sqrt":return[Cn(I("x",e,t,n))];case"Square":return[vt(I("x",e,t,n))];case"Tanh":return[Zi(I("x",e,t,n))];case"Tan":return[I1(I("x",e,t,n))];case"ClipByValue":return[ss(I("x",e,t,n),I("clipValueMin",e,t,n),I("clipValueMax",e,t,n))];case"Relu6":return[yf(I("x",e,t,n))];case"Rsqrt":return[xf(Un(e.inputNames[0],t,n))];case"Prod":return[gf(I("x",e,t,n),I("axes",e,t,n))];case"LeakyRelu":return[kd(I("x",e,t,n),I("alpha",e,t,n))];case"Prelu":return[Ed(I("x",e,t,n),I("alpha",e,t,n))];case"IsNan":return[u1(Un(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function er(e,t,n=""){if(!(typeof e=="number"||typeof t=="number")){v.assert(e.length===t.length,()=>n+` Shapes ${e} and ${t} must match`);for(let s=0;s<e.length;s++){let r=e[s],a=t[s];v.assert(r<0||a<0||r===a,()=>n+` Shapes ${e} and ${t} must match`)}}}function jk(e){return!(typeof e=="number"||e.some(t=>t<0))}function ep(e,t,n){let s=DA(e,n),r=!jk(s);if(r&&t.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${s}`);if(r&&t.forEach(a=>{s=DA(a.shape,s)}),!jk(s))throw new Error(`Non-fully-defined elementShape: ${s}`);return s}function DA(e,t){if(typeof e=="number")return t;if(typeof t=="number")return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);let n=[];for(let s=0;s<e.length;++s){let r=e[s],a=t[s];if(r>=0&&a>=0&&r!==a)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[s]=r>=0?r:a}return n}var uV=class{constructor(e,t,n,s,r,a,o){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=s,this.identicalElementShapes=r,this.dynamicSize=a,this.clearAfterRead=o,this.tensors=[],this.closed_=!1,this.idTensor=Ee(0),An(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.tensor.id))&&t.tensor.dispose()}),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);let t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map(t=>this.read(t))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);let n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},
|
|
because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),er(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,An(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((n,s)=>this.write(n,t[s]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let s=0;s<this.size();s++)e.push(s)}if(e.length===0)return nn([],[0].concat(this.elementShape));let n=this.readMany(e);return er(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Tn(n,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return nn([],[0].concat(this.elementShape));let t=[];for(let s=0;s<this.size();s++)t.push(s);let n=this.readMany(t);return er(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),kt(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);let n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,Wn(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0,s=e.map(i=>(n+=i,n));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
|
|
tensor.shape[0], but sum of lengths is
|
|
${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);let r=n===0?0:t.size/n,a=[];j(()=>{t=G(t,[1,n,r]);for(let i=0;i<e.length;++i){let l=i===0?0:s[i-1],c=[0,l,0],u=[1,e[i],r];a[i]=G(_e(t,c,u),this.elementShape)}return a});let o=[];for(let i=0;i<e.length;i++)o[i]=i;this.writeMany(o,a)}},tp=class{constructor(e,t,n,s=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,e!=null&&e.forEach(r=>{if(n!==r.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${r.dtype}`);er(t,r.shape,"TensorList shape mismatch: "),An(r)}),this.idTensor=Ee(0),this.maxNumElements=s,An(this.idTensor)}get id(){return this.idTensor.id}copy(){return new tp([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(n!==-1&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);er(e,this.elementShape,"TensorList shape mismatch: ");let s=ep(this.elementShape,this.tensors,e);return j(()=>{let r=this.tensors.map(a=>G(a,s));return Tn(r,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n=ep(this.elementShape,this.tensors,e),s=this.tensors.pop();return er(s.shape,e,"TensorList shape mismatch: "),G(s,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(er(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");An(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);this.tensors.length=e}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);er(this.tensors[e].shape,t,"TensorList shape mismatch: ");let s=ep(this.elementShape,this.tensors,t);return G(this.tensors[e],s)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);er(this.elementShape,t.shape,"TensorList shape mismatch: "),An(t),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);er(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let s=ep(this.elementShape,this.tensors,n);return e.length===0?nn([],[0].concat(s)):j(()=>{let r=e.map(a=>G(this.tensors[a],s));return Tn(r,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);er(this.elementShape,t,"TensorList shape mismatch: ");let n=ep(this.elementShape,this.tensors,t);return this.size()===0?nn([],[0].concat(n)):j(()=>{let s=this.tensors.map(r=>G(r,n));return kt(s,0)})}};function cV(e,t,n){let s=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);let r=e.shape.slice(1);er(r,t,"TensorList shape mismatch: ");let a=Wn(e);return new tp(a,t,s)}function dV(e,t,n){return new tp([],e,t,n)}function pV(e,t,n,s){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);let r=Math.max(...t);if(s!=null&&s!==-1&&r>=s)throw new Error(`Max index must be < array size (${r} vs. ${s})`);let a=new tp([],n,e.dtype,s),o=Wn(e,0);return t.forEach((i,l)=>{a.setItem(i,o[l])}),a}function hV(e,t,n){let s=0,r=t.map(u=>(s+=u,s));if(s!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to
|
|
tensor.shape[0], but sum of lengths is
|
|
${s}, and tensor's shape is: ${e.shape}`);let a=e.shape.slice(1),o=DA(a,n),i=s===0?0:e.size/s,l=j(()=>{let u=[];e=G(e,[1,s,i]);for(let d=0;d<t.length;++d){let p=d===0?0:r[d-1],h=[0,p,0],f=[1,t[d],i];u[d]=G(_e(e,h,f),o)}return e.dispose(),u}),c=new tp([],n,e.dtype,t.length);for(let u=0;u<l.length;u++)c.setItem(u,l[u]);return c}var fV=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{let s=I("thenBranch",e,t,n),r=I("elseBranch",e,t,n),a=I("cond",e,t,n),o=I("args",e,t,n);return(await a.data())[0]?n.functionMap[s].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap):n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{let s=I("body",e,t,n),r=I("cond",e,t,n),a=I("args",e,t,n),o=await n.functionMap[r].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),i=a.map(u=>u.id),l=await o[0].data();o.forEach(u=>{!u.kept&&i.indexOf(u.id)===-1&&u.dispose()});let c=a;for(;l[0];){let u=c;c=await n.functionMap[s].executeFunctionAsync(c,n.tensorArrayMap,n.tensorListMap);let d=c.map(h=>h.id);u.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()});let p=await n.functionMap[r].executeFunctionAsync(c,n.tensorArrayMap,n.tensorListMap);l=await p[0].data(),p.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()})}return c}case"LoopCond":{let s=I("pred",e,t,n);return[ia(s)]}case"Switch":{let s=I("pred",e,t,n),r=I("data",e,t,n);return r.kept||(r=ia(r)),(await s.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{let s=e.inputNames.find(r=>Un(r,t,n)!==void 0);if(s){let r=Un(s,t,n);return[ia(r)]}return}case"Enter":{let s=I("frameName",e,t,n),r=I("tensor",e,t,n);return n.enterFrame(s),[ia(r)]}case"Exit":{let s=I("tensor",e,t,n);return n.exitFrame(),[ia(s)]}case"NextIteration":{let s=I("tensor",e,t,n);return n.nextIteration(),[ia(s)]}case"TensorArrayV3":{let s=I("size",e,t,n),r=I("dtype",e,t,n),a=I("elementShape",e,t,n),o=I("dynamicSize",e,t,n),i=I("clearAfterRead",e,t,n),l=I("identicalElementShapes",e,t,n),c=I("name",e,t,n),u=new uV(c,r,s,a,l,o,i);return n.addTensorArray(u),[u.idTensor,Ee(1)]}case"TensorArrayWriteV3":{let s=I("tensorArrayId",e,t,n),r=I("index",e,t,n),a=I("tensor",e,t,n),o=n.getTensorArray(s.id);return o.write(r,a),[o.idTensor]}case"TensorArrayReadV3":{let s=I("tensorArrayId",e,t,n),r=I("index",e,t,n);return[n.getTensorArray(s.id).read(r)]}case"TensorArrayGatherV3":{let s=I("tensorArrayId",e,t,n),r=I("indices",e,t,n),a=I("dtype",e,t,n);return[n.getTensorArray(s.id).gather(r,a)]}case"TensorArrayScatterV3":{let s=I("tensorArrayId",e,t,n),r=I("indices",e,t,n),a=I("tensor",e,t,n),o=n.getTensorArray(s.id);return o.scatter(r,a),[o.idTensor]}case"TensorArrayConcatV3":{let s=I("tensorArrayId",e,t,n),r=n.getTensorArray(s.id),a=I("dtype",e,t,n);return[r.concat(a)]}case"TensorArraySplitV3":{let s=I("tensorArrayId",e,t,n),r=I("tensor",e,t,n),a=I("lengths",e,t,n),o=n.getTensorArray(s.id);return o.split(a,r),[o.idTensor]}case"TensorArraySizeV3":{let s=I("tensorArrayId",e,t,n),r=n.getTensorArray(s.id);return[Ee(r.size(),"int32")]}case"TensorArrayCloseV3":{let s=I("tensorArrayId",e,t,n),r=n.getTensorArray(s.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{let s=I("tensorListId",e,t,n),r=I("index",e,t,n),a=I("tensor",e,t,n),o=n.getTensorList(s.id);return o.setItem(r,a),[o.idTensor]}case"TensorListGetItem":{let s=I("tensorListId",e,t,n),r=I("index",e,t,n),a=I("elementShape",e,t,n),o=I("elementDType",e,t,n);return[n.getTensorList(s.id).getItem(r,a,o)]}case"TensorListScatterV2":case"TensorListScatter":{let s=I("indices",e,t,n),r=I("tensor",e,t,n),a=I("elementShape",e,t,n),o=I("numElements",e,t,n),i=pV(r,s,a,o);return n.addTensorList(i),[i.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let s=I("elementShape",e,t,n),r=I("elementDType",e,t,n),a;e.op==="TensorListReserve"?a="numElements":a="maxNumElements";let o=I(a,e,t,n),i=dV(s,r,o);return n.addTensorList(i),[i.idTensor]}case"TensorListGather":{let s=I("tensorListId",e,t,n),r=I("indices",e,t,n),a=I("elementShape",e,t,n),o=I("elementDType",e,t,n);return[n.getTensorList(s.id).gather(r,o,a)]}case"TensorListStack":{let s=I("tensorListId",e,t,n),r=I("elementShape",e,t,n),a=I("elementDType",e,t,n),o=I("numElements",e,t,n);return[n.getTensorList(s.id).stack(r,a,o)]}case"TensorListFromTensor":{let s=I("tensor",e,t,n),r=I("elementShape",e,t,n),a=I("elementDType",e,t,n),o=cV(s,r,a);return n.addTensorList(o),[o.idTensor]}case"TensorListConcat":{let s=I("tensorListId",e,t,n),r=n.getTensorList(s.id),a=I("dtype",e,t,n),o=I("elementShape",e,t,n);return[r.concat(a,o)]}case"TensorListPushBack":{let s=I("tensorListId",e,t,n),r=I("tensor",e,t,n),a=n.getTensorList(s.id);return a.pushBack(r),[a.idTensor]}case"TensorListPopBack":{let s=I("tensorListId",e,t,n),r=I("elementShape",e,t,n),a=I("elementDType",e,t,n);return[n.getTensorList(s.id).popBack(r,a)]}case"TensorListSplit":{let s=I("tensor",e,t,n),r=I("elementShape",e,t,n),a=I("lengths",e,t,n),o=hV(s,a,r);return n.addTensorList(o),[o.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function qk(e,t,n){let[s,r]=I("fusedOps",e,t,n),a=s==="biasadd",o=!a,i=r==="prelu",l=s==="fusedbatchnorm",c=I("numArgs",e,t,n);if(a){if(i&&c!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&a&&c!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");let u=I("strides",e,t,n),d=bm(e,t,n),p=I("dataFormat",e,t,n).toUpperCase(),h=I("dilations",e,t,n),[f,m]=I("args",e,t,n);o&&(m=f,f=void 0);let g=I("leakyreluAlpha",e,t,n);return{stride:u,pad:d,dataFormat:p,dilations:h,biasArg:f,preluArg:m,activationFunc:r,leakyreluAlpha:g}}var mV=(e,t,n)=>{switch(e.op){case"Conv1D":{let s=I("stride",e,t,n),r=I("pad",e,t,n),a=I("dataFormat",e,t,n).toUpperCase(),o=I("dilation",e,t,n);return[af(I("x",e,t,n),I("filter",e,t,n),s,r,a,o)]}case"Conv2D":{let s=I("strides",e,t,n),r=bm(e,t,n),a=I("dataFormat",e,t,n).toUpperCase(),o=I("dilations",e,t,n);return[Qr(I("x",e,t,n),I("filter",e,t,n),[s[1],s[2]],r,a,[o[1],o[2]])]}case"_FusedConv2D":{let{stride:s,pad:r,dataFormat:a,dilations:o,biasArg:i,preluArg:l,activationFunc:c,leakyreluAlpha:u}=qk(e,t,n);return[So.conv2d({x:I("x",e,t,n),filter:I("filter",e,t,n),strides:[s[1],s[2]],pad:r,dataFormat:a,dilations:[o[1],o[2]],bias:i,activation:c,preluActivationWeights:l,leakyreluAlpha:u})]}case"FusedDepthwiseConv2dNative":{let{stride:s,pad:r,dataFormat:a,dilations:o,biasArg:i,preluArg:l,activationFunc:c,leakyreluAlpha:u}=qk(e,t,n);return[So.depthwiseConv2d({x:I("x",e,t,n),filter:I("filter",e,t,n),strides:[s[1],s[2]],pad:r,dataFormat:a,dilations:[o[1],o[2]],bias:i,activation:c,preluActivationWeights:l,leakyreluAlpha:u})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let s=I("outputShape",e,t,n),r=I("strides",e,t,n),a=bm(e,t,n);return[of(I("x",e,t,n),I("filter",e,t,n),s,[r[1],r[2]],a)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let s=I("strides",e,t,n),r=bm(e,t,n),a=I("dilations",e,t,n),o=I("dataFormat",e,t,n).toUpperCase();return[$u(I("input",e,t,n),I("filter",e,t,n),[s[1],s[2]],r,o,[a[1],a[2]])]}case"Conv3D":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("dataFormat",e,t,n).toUpperCase(),o=I("dilations",e,t,n);return[n1(I("x",e,t,n),I("filter",e,t,n),[s[1],s[2],s[3]],r,a,[o[1],o[2],o[3]])]}case"AvgPool":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("kernelSize",e,t,n);return[bd(I("x",e,t,n),[a[1],a[2]],[s[1],s[2]],r)]}case"MaxPool":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("kernelSize",e,t,n);return[Cd(I("x",e,t,n),[a[1],a[2]],[s[1],s[2]],r)]}case"MaxPoolWithArgmax":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("kernelSize",e,t,n),o=I("includeBatchInIndex",e,t,n),{result:i,indexes:l}=tv(I("x",e,t,n),[a[1],a[2]],[s[1],s[2]],r,o);return[i,l]}case"AvgPool3D":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("kernelSize",e,t,n);return[J2(I("x",e,t,n),[a[1],a[2],a[3]],[s[1],s[2],s[3]],r)]}case"MaxPool3D":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("kernelSize",e,t,n);return[f1(I("x",e,t,n),[a[1],a[2],a[3]],[s[1],s[2],s[3]],r)]}case"Dilation2D":{let s=I("strides",e,t,n),r=I("pad",e,t,n),a=I("dilations",e,t,n),o=s[1],i=s[2],l=a[1],c=a[2];return[r1(I("x",e,t,n),I("filter",e,t,n),[o,i],r,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},gV=(e,t,n)=>{switch(e.op){case"Fill":{let s=I("shape",e,t,n),r=I("dtype",e,t,n),a=I("value",e,t,n);return[_u(s,a,r)]}case"LinSpace":{let s=I("start",e,t,n),r=I("stop",e,t,n),a=I("num",e,t,n);return[X3(s,r,a)]}case"Multinomial":{let s=I("logits",e,t,n),r=I("numSamples",e,t,n),a=I("seed",e,t,n);return[nv(s,r,a)]}case"OneHot":{let s=I("indices",e,t,n),r=I("depth",e,t,n),a=I("onValue",e,t,n),o=I("offValue",e,t,n);return[Cu(s,r,a,o)]}case"Ones":return[bs(I("shape",e,t,n),I("dtype",e,t,n))];case"OnesLike":return[vs(I("x",e,t,n))];case"RandomUniform":return[Ou(I("shape",e,t,n),I("minval",e,t,n),I("maxval",e,t,n),I("dtype",e,t,n))];case"Range":{let s=I("start",e,t,n),r=I("stop",e,t,n),a=I("step",e,t,n);return[Mu(s,r,a,I("dtype",e,t,n))]}case"TruncatedNormal":{let s=I("shape",e,t,n),r=I("mean",e,t,n),a=I("stdDev",e,t,n),o=I("seed",e,t,n);return[Cf(s,r,a,I("dtype",e,t,n),o)]}case"Zeros":return[qt(I("shape",e,t,n),I("dtype",e,t,n))];case"ZerosLike":return[tt(I("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function _A(e,t,n){let s=I("boxes",e,t,n),r=I("scores",e,t,n),a=I("maxOutputSize",e,t,n),o=I("iouThreshold",e,t,n),i=I("scoreThreshold",e,t,n),l=I("softNmsSigma",e,t,n);return{boxes:s,scores:r,maxOutputSize:a,iouThreshold:o,scoreThreshold:i,softNmsSigma:l}}var yV=async(e,t,n)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:s,scores:r,maxOutputSize:a,iouThreshold:o,scoreThreshold:i,softNmsSigma:l}=_A(e,t,n),c=await $e.nonMaxSuppressionWithScoreAsync(s,r,a,o,i,l);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:s,scores:r,maxOutputSize:a,iouThreshold:o,scoreThreshold:i}=_A(e,t,n),l=I("padToMaxOutputSize",e,t,n),c=await $e.nonMaxSuppressionPaddedAsync(s,r,a,o,i,l);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:s,scores:r,maxOutputSize:a,iouThreshold:o,scoreThreshold:i}=_A(e,t,n);return[await $e.nonMaxSuppressionAsync(s,r,a,o,i)]}case"Where":{let s=pe(I("condition",e,t,n),"bool"),r=[await T1(s)];return s.dispose(),r}case"ListDiff":return av(I("x",e,t,n),I("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}},AV=(e,t,n)=>{switch(e.op){case"TopKV2":{let s=I("x",e,t,n),r=I("k",e,t,n),a=I("sorted",e,t,n),o=S1(s,r,a);return[o.values,o.indices]}case"Unique":{let s=I("x",e,t,n),r=Tf(s);return[r.values,r.indices]}case"UniqueV2":{let s=I("x",e,t,n),r=I("axis",e,t,n),a=Tf(s,r);return[a.values,a.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},xV=(e,t,n)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let s=I("default",e,t,n);return[Un(e.name,t,n)||s];case"Placeholder":return[Un(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let c=I("x",e,t,n);return[ia(c)]}case"IdentityN":return I("x",e,t,n).map(c=>ia(c));case"Snapshot":let r=I("x",e,t,n);return[ia(r)];case"Shape":return[Zt(I("x",e,t,n).shape,"int32")];case"ShapeN":return I("x",e,t,n).map(c=>Zt(c.shape));case"Size":return[Ee(I("x",e,t,n).size,"int32")];case"Rank":return[Ee(I("x",e,t,n).rank,"int32")];case"NoOp":return[Ee(1)];case"Print":let a=I("x",e,t,n),o=I("data",e,t,n),i=I("message",e,t,n),l=I("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(i);for(let c=0;c<o.length;c++)console.log(Array.prototype.slice.call(o[c].dataSync()).slice(0,l));return[a];default:throw TypeError(`Node type ${e.op} is not implemented`)}},bV=class{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Ee(0),this.tensorMap=new Map,An(this.handle)}get id(){return this.handle.id}clearAndClose(){this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Ee(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return this.tensorMap.forEach(s=>s.dispose()),this.tensorMap.clear(),j(()=>{let s=Wn(t),r=n.length,a=s.length;v.assert(r===a,()=>`The number of elements doesn't match, keys has ${r} elements, the values has ${a} elements.`);for(let o=0;o<r;o++){let i=n[o],l=s[o];An(l),this.tensorMap.set(i,l)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return j(()=>{let s=[];for(let r=0;r<n.length;r++){let a=n[r],o=this.findWithDefault(a,t);s.push(o)}return Tn(s)})}findWithDefault(e,t){let n=this.tensorMap.get(e);return n!=null?n:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}},vV=async(e,t,n,s)=>{switch(e.op){case"HashTable":case"HashTableV2":{let r=I("keyDType",e,t,n),a=I("valueDType",e,t,n),o=new bV(r,a);return s.addHashTable(e.name,o),[o.handle]}case"LookupTableImport":case"LookupTableImportV2":{let r=I("tableHandle",e,t,n,s),a=I("keys",e,t,n),o=I("values",e,t,n);return[await s.getHashTableById(r.id).import(a,o)]}case"LookupTableFind":case"LookupTableFindV2":{let r=I("tableHandle",e,t,n,s),a=I("keys",e,t,n),o=I("defaultValue",e,t,n);return[await s.getHashTableById(r.id).find(a,o)]}case"LookupTableSize":case"LookupTableSizeV2":{let r=I("tableHandle",e,t,n,s);return[s.getHashTableById(r.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},wV=(e,t,n)=>{switch(e.op){case"ResizeBilinear":{let s=I("images",e,t,n),r=I("size",e,t,n),a=I("alignCorners",e,t,n),o=I("halfPixelCenters",e,t,n);return[$e.resizeBilinear(s,[r[0],r[1]],a,o)]}case"ResizeNearestNeighbor":{let s=I("images",e,t,n),r=I("size",e,t,n),a=I("alignCorners",e,t,n),o=I("halfPixelCenters",e,t,n);return[$e.resizeNearestNeighbor(s,[r[0],r[1]],a,o)]}case"CropAndResize":{let s=I("image",e,t,n),r=I("boxes",e,t,n),a=I("boxInd",e,t,n),o=I("cropSize",e,t,n),i=I("method",e,t,n),l=I("extrapolationValue",e,t,n);return[$e.cropAndResize(s,r,a,o,i,l)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},kV=(e,t,n)=>{switch(e.op){case"Equal":return[ys(I("a",e,t,n),I("b",e,t,n))];case"NotEqual":return[tl(I("a",e,t,n),I("b",e,t,n))];case"Greater":return[rs(I("a",e,t,n),I("b",e,t,n))];case"GreaterEqual":return[ko(I("a",e,t,n),I("b",e,t,n))];case"Less":return[df(I("a",e,t,n),I("b",e,t,n))];case"LessEqual":return[Io(I("a",e,t,n),I("b",e,t,n))];case"LogicalAnd":return[Ks(I("a",e,t,n),I("b",e,t,n))];case"LogicalNot":return[Sd(I("a",e,t,n))];case"LogicalOr":return[ff(I("a",e,t,n),I("b",e,t,n))];case"Select":case"SelectV2":return[Pn(I("condition",e,t,n),I("a",e,t,n),I("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},IV=(e,t,n)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[Xe(I("a",e,t,n),I("b",e,t,n),I("transposeA",e,t,n),I("transposeB",e,t,n))];case"Einsum":return[H3(I("equation",e,t,n),...I("tensors",e,t,n))];case"Transpose":return[et(I("x",e,t,n),I("perm",e,t,n))];case"_FusedMatMul":let[s,r]=I("fusedOps",e,t,n),a=s==="biasadd",o=r==="prelu",i=I("numArgs",e,t,n),l=I("leakyreluAlpha",e,t,n);if(a){if(o&&i!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&i!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[c,u]=I("args",e,t,n);return[So.matMul({a:I("a",e,t,n),b:I("b",e,t,n),transposeA:I("transposeA",e,t,n),transposeB:I("transposeB",e,t,n),bias:c,activation:r,preluActivationWeights:u,leakyreluAlpha:l})];default:throw TypeError(`Node type ${e.op} is not implemented`)}},SV=(e,t,n)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[Yi(I("x",e,t,n),I("mean",e,t,n),I("variance",e,t,n),I("offset",e,t,n),I("scale",e,t,n),I("epsilon",e,t,n))];case"FusedBatchNormV3":return[Yi(I("x",e,t,n),I("mean",e,t,n),I("variance",e,t,n),I("offset",e,t,n),I("scale",e,t,n),I("epsilon",e,t,n))];case"LRN":return[c1(I("x",e,t,n),I("radius",e,t,n),I("bias",e,t,n),I("alpha",e,t,n),I("beta",e,t,n))];case"Softmax":return[nl(I("x",e,t,n))];case"LogSoftmax":return[hf(I("x",e,t,n))];case"SparseToDense":return[N1(I("sparseIndices",e,t,n),I("outputShape",e,t,n),I("sparseValues",e,t,n),I("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},CV=(e,t,n)=>{switch(e.op){case"Max":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[Bn(I("x",e,t,n),o,i)]}case"Mean":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[Lt(I("x",e,t,n),o,i)]}case"Min":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[Td(I("x",e,t,n),o,i)]}case"Sum":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[ke(I("x",e,t,n),o,i)]}case"All":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[sf(I("x",e,t,n),o,i)]}case"Any":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[Ad(I("x",e,t,n),o,i)]}case"ArgMax":{let o=I("axis",e,t,n);return[Fs(I("x",e,t,n),o)]}case"ArgMin":{let o=I("axis",e,t,n);return[G2(I("x",e,t,n),o)]}case"Prod":{let o=I("axis",e,t,n),i=I("keepDims",e,t,n);return[gf(I("x",e,t,n),o,i)]}case"Cumsum":{let o=I("axis",e,t,n),i=I("exclusive",e,t,n),l=I("reverse",e,t,n);return[uf(I("x",e,t,n),o,i,l)]}case"Bincount":let s=I("x",e,t,n),r=I("weights",e,t,n),a=I("size",e,t,n);return[Q2(s,r,a)];case"DenseBincount":{let o=I("x",e,t,n),i=I("weights",e,t,n),l=I("size",e,t,n),c=I("binaryOutput",e,t,n);return[U3(o,i,l,c)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},TV=(e,t,n)=>{switch(e.op){case"ConcatV2":case"Concat":{let s=I("n",e,t,n),r=I("axis",e,t,n),a=I("tensors",e,t,n);return a=a.slice(0,s),[kt(a,r)]}case"Gather":{let s=I("x",e,t,n),r=I("indices",e,t,n);return[Ji(s,pe(r,"int32"),0)]}case"GatherV2":{let s=I("axis",e,t,n),r=I("batchDims",e,t,n),a=I("x",e,t,n),o=I("indices",e,t,n);return[Ji(a,pe(o,"int32"),s,r)]}case"Reverse":{let s=I("dims",e,t,n),r=[];for(let o=0;o<s.length;o++)s[o]&&r.push(o);let a=I("x",e,t,n);return[ws(a,r)]}case"ReverseV2":{let s=I("axis",e,t,n),r=I("x",e,t,n);return[ws(r,s)]}case"Slice":{let s=I("begin",e,t,n),r=I("size",e,t,n);return[_e(I("x",e,t,n),s,r)]}case"StridedSlice":{let s=I("begin",e,t,n),r=I("end",e,t,n),a=I("strides",e,t,n),o=I("beginMask",e,t,n),i=I("endMask",e,t,n),l=I("ellipsisMask",e,t,n),c=I("newAxisMask",e,t,n),u=I("shrinkAxisMask",e,t,n),d=I("x",e,t,n);return[k1(d,s,r,a,o,i,l,c,u)]}case"Pack":return j(()=>{let s=I("axis",e,t,n),r=I("tensors",e,t,n),a=r[0].shape,o=dt(r[0]).shape,i=r.map(l=>{let c=v.arraysEqual(l.shape,a);if(!c&&!v.arraysEqual(dt(l).shape,o))throw new Error("the input tensors shape does not match");return c?l:G(l,a)});return[Tn(i,s)]});case"Unpack":{let s=I("axis",e,t,n),r=I("tensor",e,t,n);return Wn(r,s)}case"Tile":{let s=I("reps",e,t,n);return[Os(I("x",e,t,n),s)]}case"Split":case"SplitV":{let s=I("axis",e,t,n),r=I("numOrSizeSplits",e,t,n),a=I("x",e,t,n);return xn(a,r,s)}case"ScatterNd":{let s=I("indices",e,t,n),r=I("values",e,t,n),a=I("shape",e,t,n);return[uv(s,r,a)]}case"GatherNd":{let s=I("x",e,t,n),r=I("indices",e,t,n);return[cv(s,r)]}case"SparseToDense":{let s=I("sparseIndices",e,t,n),r=I("outputShape",e,t,n),a=I("sparseValues",e,t,n),o=I("defaultValue",e,t,n);return[N1(s,a,r,a.dtype===o.dtype?o:pe(o,a.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},NV=(e,t,n)=>{switch(e.op){case"SparseFillEmptyRows":{let{outputIndices:s,outputValues:r,emptyRowIndicator:a,reverseIndexMap:o}=Pd.sparseFillEmptyRows(I("indices",e,t,n),I("values",e,t,n),I("denseShape",e,t,n),I("defaultValue",e,t,n));return[s,r,a,o]}case"SparseReshape":{let{outputIndices:s,outputShape:r}=Pd.sparseReshape(I("inputIndices",e,t,n),I("inputShape",e,t,n),I("newShape",e,t,n));return[s,r]}case"SparseSegmentMean":return[Pd.sparseSegmentMean(I("data",e,t,n),I("indices",e,t,n),I("segmentIds",e,t,n))];case"SparseSegmentSum":return[Pd.sparseSegmentSum(I("data",e,t,n),I("indices",e,t,n),I("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},EV=(e,t,n)=>{switch(e.op){case"FFT":return[Dd(I("x",e,t,n))];case"IFFT":return[Lu(I("x",e,t,n))];case"RFFT":return[_d(I("x",e,t,n))];case"IRFFT":return[If(I("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},RV=(e,t,n)=>{switch(e.op){case"StringNGrams":{let{nGrams:s,nGramsSplits:r}=_f.stringNGrams(I("data",e,t,n),I("dataSplits",e,t,n),I("separator",e,t,n),I("nGramWidths",e,t,n),I("leftPad",e,t,n),I("rightPad",e,t,n),I("padWidth",e,t,n),I("preserveShortSequences",e,t,n));return[s,r]}case"StringSplit":{let{indices:s,values:r,shape:a}=_f.stringSplit(I("input",e,t,n),I("delimiter",e,t,n),I("skipEmpty",e,t,n));return[s,r,a]}case"StringToHashBucketFast":return[_f.stringToHashBucketFast(I("input",e,t,n),I("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},$V=(e,t,n)=>{switch(e.op){case"Cast":return[pe(I("x",e,t,n),I("dtype",e,t,n))];case"ExpandDims":{let s=I("axis",e,t,n);return[jt(I("x",e,t,n),s)]}case"Squeeze":{let s=I("axis",e,t,n);return[dt(I("x",e,t,n),s)]}case"Reshape":return[G(I("x",e,t,n),I("shape",e,t,n))];case"MirrorPad":return[m1(I("x",e,t,n),I("padding",e,t,n),I("mode",e,t,n))];case"PadV2":case"Pad":return[ur(I("x",e,t,n),I("padding",e,t,n),I("constantValue",e,t,n))];case"SpaceToBatchND":{let s=I("blockShape",e,t,n),r=I("paddings",e,t,n);return[Nd(I("x",e,t,n),s,r)]}case"BatchToSpaceND":{let s=I("blockShape",e,t,n),r=I("crops",e,t,n);return[vd(I("x",e,t,n),s,r)]}case"DepthToSpace":{let s=I("blockSize",e,t,n),r=I("dataFormat",e,t,n).toUpperCase();return[s1(I("x",e,t,n),s,r)]}case"BroadcastTo":return[Eu(I("x",e,t,n),I("shape",e,t,n))];case"BroadcastArgs":return[M3(I("s0",e,t,n),I("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Xk(e,t,n,s){let r=((a,o,i)=>{switch(a.category){case"arithmetic":return j(()=>iV(a,o,i));case"basic_math":return j(()=>lV(a,o,i));case"control":return fV(a,o,i);case"convolution":return j(()=>mV(a,o,i));case"creation":return j(()=>gV(a,o,i));case"dynamic":return yV(a,o,i);case"evaluation":return j(()=>AV(a,o,i));case"image":return j(()=>wV(a,o,i));case"graph":return j(()=>xV(a,o,i));case"logical":return j(()=>kV(a,o,i));case"matrices":return j(()=>IV(a,o,i));case"normalization":return j(()=>SV(a,o,i));case"reduction":return j(()=>CV(a,o,i));case"slice_join":return j(()=>TV(a,o,i));case"sparse":return j(()=>NV(a,o,i));case"spectral":return j(()=>EV(a,o,i));case"string":return j(()=>RV(a,o,i));case"transformation":return j(()=>$V(a,o,i));case"hash_table":return vV(a,o,i,s);case"custom":let l=wk(a.op);if(l&&l.customExecutor)return l.customExecutor(new oV(a,o,i));throw TypeError(`Custom op ${a.op} is not registered.`);default:throw TypeError(`Unknown op '${a.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return v.isPromise(r)?r.then(a=>[].concat(a)):[].concat(r)}var Kk=class{constructor(e={},t={},n={},s={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=s,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){let e=[];for(let t=0;t<this.contexts.length-1;t++){let n=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(n))}e.push(""),this._currentContextIds=e}contextIdforContexts(e){return e?e.map(t=>t.id===0&&t.iterationId===0?"":`${t.frameName}-${t.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(this.contexts&&this.contexts.length>1)this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();else throw new Error("Cannot exit frame, the context is empty")}nextIteration(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice(),this.lastId++;let e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else throw new Error("Cannot increase frame iteration, the context is empty")}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(let t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(let t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}};function Zk(e,t,n,s){let r=new Set,a=[],o=null,i=null,l=new Set,c=Object.keys(e).map(p=>ks(p)[0]),u=[];s!=null&&(u=s.map(p=>ks(p.name)[0]));let d=[...t];for(;d.length>0;){let p=d.pop();if((Yk(p)||OV(p)||MV(p))&&o==null&&(o=p,i=o.children.map(h=>h.name).filter(h=>r.has(h))),r.add(p.name),n[p.name]==null&&c.indexOf(p.name)===-1&&u.indexOf(p.name)===-1){if(p.inputs.length===0){a.push(p.name);continue}p.inputs.forEach(h=>{l.has(h.name)||(l.add(h.name),d.push(h))})}}return{inputs:e,outputs:t,usedNodes:r,missingInputs:a,dynamicNode:o,syncInputs:i}}function DV(e,t,n){let{usedNodes:s,inputs:r}=n,a=[],o=Object.keys(r).map(u=>ks(u)[0]).map(u=>e.nodes[u]),i=e.initNodes;o.forEach(u=>{s.has(u.name)&&a.push(u)}),e.weights.forEach(u=>{s.has(u.name)&&a.push(u)}),i!=null&&i.forEach(u=>{s.has(u.name)&&a.push(u)});let l=new Set,c=[];for(;a.length>0;){let u=a.pop();l.add(u.name),t[u.name]||c.push(u),u.children.forEach(d=>{!l.has(d.name)&&s.has(d.name)&&d.inputs.every(p=>l.has(p.name))&&a.push(d)})}return c}var _V=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],PV=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],FV=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function Yk(e){return _V.indexOf(e.op)>=0}function OV(e){return PV.indexOf(e.op)>=0}function MV(e){return FV.indexOf(e.op)>=0}var PA=class{constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,e.functions!=null&&Object.keys(e.functions).forEach(n=>{this._functionExecutorMap[n]=new PA(e.functions[n],this)})}get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){let t=Object.keys(e).map(n=>e[n].map(s=>s.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{let t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}getCompilationKey(e,t){let n=e.map(r=>r.name).sort(),s=t.map(r=>r.name).sort();return n.join(this.SEPERATOR)+"--"+s.join(this.SEPERATOR)}compile(e,t){let n=Zk(e,t,this.weightMap,this._initNodes),{missingInputs:s,dynamicNode:r,syncInputs:a}=n;if(r!=null)throw new Error(`This execution contains the node '${r.name}', which has the dynamic op '${r.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${a}]`);if(s.length>0){let o=t.map(l=>l.name),i=Object.keys(e);throw new Error(`Cannot compute the outputs [${o}] from the provided inputs [${i}]. Missing the following inputs: [${s}]`)}return DV(this.graph,this.weightMap,n)}execute(e,t){e=this.mapInputs(e);let n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);let s=n.map(u=>this.graph.nodes[ks(u)[0]]),r=t.map(u=>ks(u)[0]),a=r.map(u=>this.graph.nodes[u]);a.length===0&&(a=this._outputs);let o=this.getCompilationKey(s,a),i=this.compiledMap.get(o);i==null&&(i=this.compile(e,a),this.compiledMap.set(o,i));let l={},c={};return j(()=>{let u=new Kk(this.weightMap,l,c,this.functionExecutorMap),d=Object.assign({},this.weightMap);Object.keys(e).forEach(f=>{let[m,g]=ks(f),y=[];y[g]=e[f],d[m]=y});let p=this.getFrozenTensorIds(d),h={};for(let f=0;f<i.length;f++){let m=i[f];if(!d[m.name]){let g=Xk(m,d,u,this._resourceManager);if(v.isPromise(g))throw new Error(`The execution of the op '${m.op}' returned a promise. Please use model.executeAsync() instead.`);d[m.name]=g,this.checkTensorForDisposal(m.name,m,d,u,p,r,h)}}return this.parent==null&&u.dispose(p),t.map(f=>Un(f,d,u))})}getFrozenTensorIds(e){let t=[].concat.apply([],Object.keys(e).map(n=>e[n]).map(n=>n.map(s=>s.id)));return new Set(t)}checkTensorForDisposal(e,t,n,s,r,a,o){t.category==="control"||a.indexOf(e)!==-1||(n[e].forEach(i=>{i!=null&&(o[i.id]=(o[i.id]||0)+t.children.length)}),t.inputs.forEach(i=>{if(i.category!=="control"){let l=LW(i.name,n,s);l!=null&&l.forEach(c=>{if(c&&!c.kept&&!r.has(c.id)){let u=o[c.id];u===1?(c.dispose(),delete o[c.id]):u!=null&&o[c.id]--}})}}))}async executeAsync(e,t){return this._executeAsync(e,t)}async _executeAsync(e,t,n=!1,s={},r={}){n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));let a=new Kk(this.weightMap,s,r,this.functionExecutorMap),o=await this.executeWithControlFlow(e,a,t,n),i=t.map(d=>Un(d,o,a)),l=i.map(d=>d.id),c=Object.keys(e).map(d=>e[d].id),u=new Set([...l,...c,...this.weightIds]);return Object.keys(o).forEach(d=>{o[d].forEach(h=>{h&&!h.kept&&!h.isDisposed&&!u.has(h.id)&&h.dispose()})}),this.parent==null&&a.dispose(u),i}async executeFunctionAsync(e,t,n){let s=e.reduce((r,a,o)=>(r[this.inputs[o].name]=a,r),{});return this._executeAsync(s,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,s){let r=Object.keys(e),a=r.map(A=>this.graph.nodes[ks(A)[0]]),o=n.map(A=>ks(A)[0]),i=o.map(A=>this.graph.nodes[A]);i.length===0&&(i=this._outputs);let{usedNodes:l,missingInputs:c,dynamicNode:u,syncInputs:d}=Zk(e,i,this.weightMap,this._initNodes),p=[...a,...this.graph.weights,...this._initNodes||[]].map(A=>({node:A,contexts:t.currentContext})),h=Object.assign({},this.weightMap);Object.keys(e).forEach(A=>{let[x,b]=ks(A),w=[];w[b]=e[A],h[x]=w});let f={},m=this.getFrozenTensorIds(h),g={};for(;p.length>0;){let A=this.processStack(a,p,t,h,g,m,o,f,l);await Promise.all(A)}u==null&&!s&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let y=i.filter(A=>!Yk(A)&&!Un(A.name,h,t)).map(A=>A.name);if(y.length>0){let A="";throw u!=null&&(A=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${d}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${r}]. Consider providing the following inputs: [${c}]. ${A}`)}return h}processStack(e,t,n,s,r,a,o,i,l){let c=[];for(;t.length>0;){let u=t.pop();n.currentContext=u.contexts;let d="";if(u.node.op==="Enter"&&I("isConstant",u.node,s,n)&&([d]=oa(u.node.name,n)),s[u.node.name]==null){let p=Xk(u.node,s,n,this._resourceManager);d||([d]=oa(u.node.name,n));let h=n.currentContext;v.isPromise(p)?c.push(p.then(f=>(s[d]=f,n.currentContext=h,this.checkTensorForDisposal(d,u.node,s,n,a,o,i),this.processChildNodes(u.node,t,n,s,r,l),f))):(s[d]=p,this.checkTensorForDisposal(d,u.node,s,n,a,o,i),this.processChildNodes(u.node,t,n,s,r,l))}else this.processChildNodes(u.node,t,n,s,r,l)}return c}processChildNodes(e,t,n,s,r,a){e.children.forEach(o=>{let[i]=oa(o.name,n);r[i]||!a.has(o.name)||(o.op==="Merge"?o.inputNames.some(l=>!!Un(l,s,n))&&(r[i]=!0,t.push({contexts:n.currentContext,node:o})):o.inputNames.every(l=>!!Un(l,s,n))&&(r[i]=!0,t.push({contexts:n.currentContext,node:o})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{let n=e[t],[s]=ks(t),r=this.graph.nodes[s];if(r.attrParams.shape&&r.attrParams.shape.value){let a=r.attrParams.shape.value,o=a.length===n.shape.length&&n.shape.every((i,l)=>a[l]===-1||a[l]===i);v.assert(o,()=>`The shape of dict['${r.name}'] provided in model.execute(dict) must be [${a}], but was [${n.shape}]`)}r.attrParams.dtype&&r.attrParams.dtype.value&&v.assert(n.dtype===r.attrParams.dtype.value,()=>`The dtype of dict['${r.name}'] provided in model.execute(dict) must be ${r.attrParams.dtype.value}, but was ${n.dtype}`)})}mapInputs(e){let t={};for(let n in e)if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[n]!=null){let s=this._signature.inputs[n];t[s.name]=e[n]}else t[n]=e[n];return t}checkInputs(e){let t=Object.keys(e).filter(n=>{let[s]=ks(n);return this.graph.nodes[s]==null});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(t=>this._signature!=null&&this._signature.outputs!=null&&this._signature.outputs[t]!=null?this._signature.outputs[t].name:t,{})}checkOutputs(e){e.forEach(t=>{let[n]=ks(t);if(!this.graph.nodes[n])throw new Error(`The output '${t}' is not found in the graph`)})}},zV=class{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(let e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(let e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}},LV="?tfjs-format=file",BV="model.json",Jk=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new zV}get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}findIOHandler(){let e=this.modelUrl;if(e.load!=null)this.handler=e;else if(this.loadOptions.requestInit!=null)this.handler=es.browserHTTPRequest(e,this.loadOptions);else{let t=es.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(es.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}async load(){if(this.findIOHandler(),this.handler.load==null)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let e=await this.handler.load();return this.loadSync(e)}loadSync(e){this.artifacts=e;let t=this.artifacts.modelTopology,n;this.artifacts.userDefinedMetadata!=null&&this.artifacts.userDefinedMetadata.signature!=null?n=this.artifacts.userDefinedMetadata.signature:n=this.artifacts.signature,this.signature=n,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;let s=es.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new PA(Vk.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(s),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){let r=Vk.Instance.transformGraph(e.modelInitializer);this.initializer=new PA(r),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializer.executeAsync({},[])}return!0}async save(e,t){if(typeof e=="string"){let n=es.getSaveHandlers(e);if(n.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(n.length>1)throw new Error(`Found more than one (${n.length}) save handlers for URL '${e}'`);e=n[0]}if(e.save==null)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}predict(e,t){return this.execute(e,this.outputNodes)}normalizeInputs(e){if(!(e instanceof Ke)&&!Array.isArray(e))return e;if(e=Array.isArray(e)?e:[e],e.length!==this.inputNodes.length)throw new Error(`Input tensor count mismatch,the graph model has ${this.inputNodes.length} placeholders, while there are ${e.length} input tensors.`);return this.inputNodes.reduce((t,n,s)=>(t[n]=e[s],t),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}execute(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,n)=>(t[n]=[e[n]],t),{})}dispose(){this.executor.dispose(),this.initializer&&this.initializer.dispose(),this.resourceManager.dispose()}};async function ut(e,t={}){if(e==null)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");t==null&&(t={}),t.fromTFHub&&e.load==null&&(e.endsWith("/")||(e=e+"/"),e=`${e}${BV}${LV}`);let n=new Jk(e,t);return await n.load(),n}var WV="3.9.0",Qk={};Le(Qk,{CSVDataset:()=>d7,Dataset:()=>Zu,FileDataSource:()=>A7,TextLineDataset:()=>l7,URLDataSource:()=>x7,array:()=>cU,csv:()=>vU,func:()=>wU,generator:()=>kU,microphone:()=>SU,version_data:()=>CU,webcam:()=>IU,zip:()=>dU});var VV=Qo(f5()),UV=Qo(f5());function GV(e,t){return vm(e,t)}function vm(e,t,n=new Map,s=new Set){if(e==null)return null;if(s.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);let r=t(e);if(r.recurse&&r.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(r.recurse)if(Ku(e)){let a=Array.isArray(e)?[]:{};s.add(e);for(let o in e){let i=e[o],l=vm(i,t,n,s);a[o]=l}return s.delete(e),a}else throw new Error(`Can't recurse into non-iterable type: ${e}`);else return n.set(e,r.value),r.value}function HV(e,t=t7){return e7(e,t)}function e7(e,t,n=new Set){let s=e[0];if(n.has(s))throw new Error("Circular references are not supported.");let r=t(e);if(r.recurse&&r.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(r.recurse)if(Ku(s)){let a=Array.isArray(s)?[]:{};n.add(s);for(let o in s){let i=e.map(c=>c[o]),l=e7(i,t,n);a[o]=l}return n.delete(s),a}else throw new Error(`Can't recurse into non-iterable type: ${s}`);else return r.value}function t7(e){return e===null?null:Ku(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function n7(e,t){let n=new Map;vm(e,t,n);for(let r of Array.from(n.keys())){let a=n.get(r);if(v.isPromise(a)){let o=await a;n.set(r,o)}}return vm(e,t,n)}function Ku(e){let t=!1;if(Z().get("IS_BROWSER"))t=e instanceof TextDecoder;else{let{StringDecoder:n}=m5();t=e instanceof n}return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof Ke)&&!(e instanceof Promise)&&!t)}function jV(e){return e==null||qV(e)||Array.isArray(e)||typeof e=="object"&&e instanceof Ke||v.isTypedArray(e)}function qV(e){return e===null||typeof e!="object"&&typeof e!="function"}function XV(e){return GV(e,KV)}function KV(e){return e instanceof Ke?{value:e.clone(),recurse:!1}:Ku(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}var s7=class{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,e==null)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return this.length()===0}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(let t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);let e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");let e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");let t=this.wrap(this.begin+e),n=this.get(t);return this.set(t,this.pop()),n}},FA=class extends s7{constructor(){super(FA.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){let e=this.capacity*2,t=new Array(e),n=this.length();for(let s=0;s<n;s++)t[s]=this.get(this.wrap(this.begin+s));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n}};FA.INITIAL_CAPACITY=32;function r7(e){return new JV(e)}function OA(e){return new QV(e)}function ZV(e,t){return new o7(e,t)}function YV(e,t=_o.FAIL){return new lU(e,t)}var vn=class{async toArray(){let e=[],t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){let e=this.prefetch(100),t=[],n=await e.next();for(;!n.done;)t.push(n.value),n=await e.next();return t}async resolveFully(){let e=await this.next();for(;!e.done;)e=await this.next()}async resolveWhile(e){let t=await this.next(),n=e(t.value);for(;!t.done&&n;)t=await this.next(),n=e(t.value)}handleErrors(e){return new oU(this,e)}filter(e){return new rU(this,e)}map(e){return new aU(this,e)}mapAsync(e){return new a7(this,e)}serialMapAsync(e){return new a7(this,e).serial()}flatmap(e){return new iU(this,e)}async forEachAsync(e){return this.map(e).resolveFully()}async serialForEach(e){return this.serialMapAsync(e).resolveWhile(t=>t===!0)}rowMajorBatch(e,t=!0){return new sU(this,e,t)}columnMajorBatch(e,t=!0,n=t7){return this.rowMajorBatch(e,t).map(r=>HV(r,n))}concatenate(e,t){return new o7(r7([this,e]),t)}take(e){return e<0||e==null?this:new nU(this,e)}skip(e){return e<0||e==null?this:new tU(this,e)}prefetch(e){return new i7(this,e)}shuffle(e,t){return new uU(this,e,t)}serial(){return new eU(this)}},JV=class extends vn{constructor(e){super();this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};let e=this.items[this.trav];return this.trav++,{value:XV(e),done:!1}}},QV=class extends vn{constructor(e){super();this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}},eU=class extends vn{constructor(e){super();this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){return this.upstream.next()}},tU=class extends vn{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.count++<this.maxCount;){let e=await this.upstream.next();if(e.done)return e;te(e.value)}return this.upstream.next()}},nU=class extends vn{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0}summary(){return`${this.upstream.summary()} -> Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}},sU=class extends vn{constructor(e,t,n=!0){super();this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=n,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){let e=[];for(;e.length<this.batchSize;){let t=await this.upstream.next();if(t.done)return this.enableSmallLastBatch&&e.length>0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}},rU=class extends vn{constructor(e,t){super();this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;){let e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;te(e.value)}}},aU=class extends vn{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=ar.getTensorsInContainer(e.value),n=this.transform(e.value),s=ar.getTensorsInContainer(n);for(let r of t)ar.isTensorInList(r,s)||r.dispose();return{value:n,done:!1}}},oU=class extends vn{constructor(e,t){super();this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}},a7=class extends vn{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=ar.getTensorsInContainer(e.value),n=await this.transform(e.value),s=ar.getTensorsInContainer(n);for(let r of t)ar.isTensorInList(r,s)||r.dispose();return{value:n,done:!1}}},MA=class extends vn{constructor(){super();this.outputQueue=new FA,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.outputQueue.length()===0;)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}},iU=class extends MA{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){let e=await this.upstream.next();if(e.done)return!1;let t=ar.getTensorsInContainer(e.value),n=this.transform(e.value),s=ar.getTensorsInContainer(n);this.outputQueue.pushAll(n);for(let r of t)ar.isTensorInList(r,s)||r.dispose();return!0}},o7=class extends vn{constructor(e,t){super();this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,this.iterator==null){let n=await this.moreIterators.next();if(n.done)return{value:null,done:!0};this.iterator=n.value,this.baseErrorHandler!=null&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}let t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}},_o;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(_o||(_o={}));var lU=class extends vn{constructor(e,t=_o.FAIL){super();this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){return"{TODO: fill in upstream of zip summaries} -> Zip"}async nextState(e){await e;let t=0,n=0;function s(a){return a instanceof vn?{value:a.next().then(i=>(t++,i.done&&n++,i.value)),recurse:!1}:{value:null,recurse:!0}}let r=await n7(this.iterators,s);if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case _o.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case _o.SHORTEST:return{value:null,done:!0};case _o.LONGEST:default:}return this.count++,{value:r,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},i7=class extends vn{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new s7(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){let e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}},uU=class extends i7{constructor(e,t,n){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=UV.alea(n||v.now().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){let e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(t.done)this.upstreamExhausted=!0;else return this.refill(),t}return{value:null,done:!0}}},Zu=class{constructor(){this.size=null}batch(e,t=!0){let n=this;v.assert(e>0,()=>`batchSize needs to be positive, but it is
|
|
${e}`);let s;return this.size===1/0||this.size==null?s=this.size:t?s=Math.ceil(this.size/e):s=Math.floor(this.size/e),Is(async()=>(await n.iterator()).columnMajorBatch(e,t,pU),s)}concatenate(e){let t=this,n;return this.size===1/0||e.size===1/0?n=1/0:this.size!=null&&e.size!=null?n=this.size+e.size:n=null,Is(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){let t=this,n;return this.size===1/0?n=1/0:n=null,Is(async()=>(await t.iterator()).filter(s=>j(()=>e(s))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return Is(async()=>(await t.iterator()).map(n=>j(()=>e(n))),this.size)}mapAsync(e){let t=this;return Is(async()=>(await t.iterator()).mapAsync(e),this.size)}prefetch(e){if(e==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");let t=this;return Is(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){let t=this,n;return this.size!=null&&e>0?n=this.size*e:e===0?n=0:this.size!=null&&(e===void 0||e<0)?n=1/0:n=null,Is(async()=>{let s=OA(async()=>({value:await t.iterator(),done:!1}));return ZV(s.take(e))},n)}skip(e){let t=this,n;return this.size!=null&&e>=0&&this.size>=e?n=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?n=0:n=null,Is(async()=>(await t.iterator()).skip(e),n)}shuffle(e,t,n=!0){if(e==null||e<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);let s=this,r=VV.alea(t||v.now().toString());return Is(async()=>{let a=r.int32();return n&&(a+=r.int32()),(await s.iterator()).shuffle(e,a.toString())},this.size)}take(e){let t=this,n;return this.size!=null&&this.size>e?n=e:this.size!=null&&this.size<=e?n=this.size:n=null,Is(async()=>(await t.iterator()).take(e),n)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}};Zu.MAX_BUFFER_SIZE=1e4;function Is(e,t=null){return new class extends Zu{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function cU(e){return Is(async()=>r7(e),e.length)}function dU(e){if(!Ku(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let n=0;n<e.length;n++)t=t==null?e[n].size:Math.min(t,e[n].size);else if(e instanceof Object)for(let n in e)t=t==null?e[n].size:Math.min(t,e[n].size);return Is(async()=>{let n=await n7(e,s=>{if(s instanceof Zu)return{value:s.iterator(),recurse:!1};if(Ku(s))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return YV(n,_o.SHORTEST)},t)}function pU(e){if(e===null)return null;let t=e[0];return jV(t)?{value:hU(e),recurse:!1}:{value:null,recurse:!0}}function hU(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Ke?Tn(e):nn(e)}var l7=class extends Zu{constructor(e){super();this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split(`
|
|
`).map(s=>(s.endsWith("\r")&&(s=s.slice(0,-1)),s))}},wm='"',np=Symbol("out"),u7=Symbol("field"),km=Symbol("quote"),zA=Symbol("quoteafterquote"),c7=Symbol("quoteinquote"),d7=class extends Zu{constructor(e,t){super();this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new l7(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(v.assert(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&v.assert(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);let t=this.fullColumnNames.reduce((s,r)=>(s[r]=s[r]+1||1,s),{}),n=Object.keys(t).filter(s=>t[s]>1);if(v.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let s of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(s)===-1)throw new Error('The key "'+s+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let t=await(await this.base.iterator()).next();if(t.done)throw new Error("No data was found for CSV parsing.");let n=t.value;return this.parseRow(n,!1)}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){let t=this.parseRow(e),n={},s={};for(let r=0;r<this.fullColumnNames.length;r++){let a=this.fullColumnNames[r],o=this.columnConfigs?this.columnConfigs[a]:null;if(!(this.configuredColumnsOnly&&!o)){let i=t[r],l=null;if(i==="")if(o&&o.default!==void 0)l=o.default;else{if(o&&(o.required||o.isLabel))throw new Error(`Required column ${a} is empty in this line: ${e}`);l=void 0}else{let c=Number(i);if(isNaN(c))o&&o.dtype==="bool"?l=this.getBoolean(i):l=i;else if(!o||!o.dtype)l=c;else switch(o.dtype){case"float32":l=c;break;case"int32":l=Math.floor(c);break;case"bool":l=this.getBoolean(i);break;default:l=c}}o&&o.isLabel?s[a]=l:n[a]=l}}return Object.keys(s).length===0?n:{xs:n,ys:s}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let n=[],s=0,r=e.length,a=np;for(let o=0;o<r;o++)switch(a){case np:switch(e.charAt(o)){case wm:s=o+1,a=km;break;case this.delimiter:if(s=o+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),a=np;break;default:a=u7,s=o;break}break;case u7:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(s,o)),a=np,s=o+1;break;default:}break;case km:switch(e.charAt(o)){case wm:a=zA;break;default:}break;case zA:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(s,o-1)),a=np,s=o+1;break;case wm:a=km;break;default:a=c7;break}break;case c7:switch(e.charAt(o)){case wm:a=km;break;default:}break;default:}if(a===zA?n.push(e.substring(s,r-1)):n.push(e.substring(s)),t&&n.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);return n}},p7=class extends vn{constructor(e){super();this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;let t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=e.includeSpectrogram!==!1,this.includeWaveform=e.includeWaveform===!0,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(Z().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");let t=new p7(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?!0:this.audioTrackConstraints,video:!1})}catch(n){throw new Error(`Error thrown while initializing video stream: ${n.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");let e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,!this.sampleRateHz)this.sampleRateHz=this.audioContext.sampleRate;else if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`);let t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.fftSize*2,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize)}async next(){if(this.isClosed)return{value:null,done:!0};let e,t,n=await this.getAudioData();if(this.includeSpectrogram){let s=this.flattenQueue(n.freqDataQueue);e=this.getTensorFromAudioDataArray(s,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){let s=this.flattenQueue(n.timeDataQueue);t=this.getTensorFromAudioDataArray(s,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){let e=[],t=[],n=0;return new Promise(s=>{let r=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&s({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(r),s({freqDataQueue:e,timeDataQueue:t}))},this.fftSize/this.sampleRateHz*1e3)})}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),this.stream!=null&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){let t=e[0].length,n=new Float32Array(e.length*t);return e.forEach((s,r)=>n.set(s,r*t)),n}getTensorFromAudioDataArray(e,t){let n=new Float32Array(v.sizeFromShape(t));return n.set(e,n.length-e.length),nn(n,t)}},h7=class extends vn{constructor(e,t){super();if(this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=Zt([0],"int32"),this.webcamConfig.centerCrop){let n=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,s=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,r=(1-n)/2,a=(1-s)/2,o=r+n,i=s+a;this.cropBox=dr([a,r,i,o],[1,4])}else this.cropBox=dr([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(Z().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}let n=new h7(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&v.assert(this.webcamConfig.facingMode==="user"||this.webcamConfig.facingMode==="environment",()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`);try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}})}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=Xs.fromPixels(this.webcamVideoElement)}catch(t){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(t)}`)}if(this.resize)try{return{value:this.cropAndResizeFrame(e),done:!1}}catch(t){throw new Error(`Error thrown cropping the video: ${t.message}`)}finally{e.dispose()}else return{value:e,done:!1}}needToResize(){return!!(this.webcamConfig.resizeWidth&&this.webcamConfig.resizeHeight&&(this.webcamVideoElement.width!==this.webcamConfig.resizeWidth||this.webcamVideoElement.height!==this.webcamConfig.resizeHeight))}cropAndResizeFrame(e){return j(()=>{let t=jt(pe(e,"float32"),0),n;n=$e.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let s=n.shape;return G(n,s.slice(1))})}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach(t=>t.stop());try{this.webcamVideoElement.srcObject=null}catch(t){console.log(t),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}},f7=class{},m7=class extends vn{split(e){return new fU(this,e)}},fU=class extends m7{constructor(e,t){super();this.upstream=e,this.impl=new mU(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},mU=class extends MA{constructor(e,t){super();this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){let e=await this.upstream.next();if(e.done)return this.carryover===""?!1:(this.outputQueue.push(this.carryover),this.carryover="",!0);let t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(let n of t.slice(0,-1))this.outputQueue.push(n);return this.carryover=t[t.length-1],!0}},gU=class extends vn{decodeUTF8(){return new yU(this)}},yU=class extends m7{constructor(e){super();this.upstream=e,this.impl=new AU(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},AU=class extends MA{constructor(e){super();if(this.upstream=e,Z().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=m5();this.decoder=new t("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){let e=await this.upstream.next(),t;if(e.done)return!1;t=e.value;let n;return Z().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}},g7=class extends gU{constructor(e,t={}){super();this.file=e,this.options=t,v.assert(e instanceof Uint8Array||(Z().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1024*1024}summary(){return`FileChunks ${this.file}`}async next(){return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?{value:null,done:!0}:{value:await new Promise((t,n)=>{let s=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)t(new Uint8Array(this.file.slice(this.offset,s)));else{let r=new FileReader;r.onload=o=>{let i=r.result;if(i instanceof ArrayBuffer&&(i=new Uint8Array(i)),!(i instanceof Uint8Array))return n(new TypeError("FileReader returned unknown type."));t(i)},r.onabort=o=>n(new Error("Aborted")),r.onerror=o=>n(new Error(o.type));let a=this.file.slice(this.offset,s);r.readAsArrayBuffer(a)}this.offset=s}),done:!1}}};async function xU(e,t={}){let n,s;typeof e=="string"?n=e:(n=e.url,s=bU(e));let r=await v.fetch(n,s);if(r.ok){let a=new Uint8Array(await r.arrayBuffer());return new g7(a,t)}else throw new Error(r.statusText)}var bU=e=>({method:e.method,headers:e.headers,body:e.body,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,integrity:e.integrity});function y7(e){return typeof e=="string"&&e.substr(0,7)==="file://"}var A7=class extends f7{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(y7(this.input)&&Z().get("IS_NODE")){let e=Ul("fs");this.input=e.readFileSync(this.input.substr(7))}return new g7(this.input,this.options)}},x7=class extends f7{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return y7(this.url)?new A7(this.url,this.fileOptions).iterator():xU(this.url,this.fileOptions)}};function vU(e,t={}){return new d7(new x7(e),t)}function wU(e){let t=OA(e);return Is(async()=>t)}function kU(e){return Is(async()=>{let t=await e();return OA(()=>t.next())})}async function IU(e,t){return h7.create(e,t)}async function SU(e){return p7.create(e)}var CU="3.9.0";function Ne(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&v.assert(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}var TU=Zs.whereImpl,LA=class extends Gl{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new Vc(this,ts())}nextDataId(){return LA.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,Z().get("IS_NODE")&&E.warn(`
|
|
============================
|
|
Hi there \u{1F44B}. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.
|
|
============================`));let s={id:this.nextDataId()};return this.data.set(s,{values:e,dtype:n,refCount:1}),s}makeTensorInfo(e,t,n){let s;if(t==="string"&&n!=null&&n.length>0&&v.isString(n[0])){let r=n.map(a=>v.encodeString(a));s=this.write(r,e,t)}else s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,n,s,r){this.data.set(e,{values:t,dtype:s,refCount:r})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){let s=this.readSync(n.real.dataId),r=this.readSync(n.imag.dataId);return E.mergeRealAndImagArrays(s,r)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(s=>v.decodeString(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return We(e.shape,e.dtype,n)}makeOutput(e,t,n){let s=this.write(e,t,n);return ts().makeTensorFromDataId(s,t,n,this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(e);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){let t=v.now();return e(),{kernelMs:v.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){Ne([e],"where");let t=this.readSync(e.dataId);return TU(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};LA.nextDataId=0;var BA={};Le(BA,{addImpl:()=>v7,bincountImpl:()=>VA,bincountReduceImpl:()=>w7,ceilImpl:()=>k7,concatImpl:()=>UA,equalImpl:()=>I7,expImpl:()=>C7,expm1Impl:()=>N7,floorImpl:()=>E7,gatherNdImpl:()=>R7,gatherV2Impl:()=>$7,greaterEqualImpl:()=>_7,greaterImpl:()=>D7,lessEqualImpl:()=>F7,lessImpl:()=>P7,linSpaceImpl:()=>O7,logImpl:()=>M7,maxImpl:()=>z7,maximumImpl:()=>L7,minimumImpl:()=>B7,multiplyImpl:()=>GA,negImpl:()=>W7,notEqualImpl:()=>V7,prodImpl:()=>U7,rangeImpl:()=>jA,rsqrtImpl:()=>G7,sigmoidImpl:()=>mG,simpleAbsImpl:()=>b7,sliceImpl:()=>Cm,sparseFillEmptyRowsImpl:()=>j7,sparseReshapeImpl:()=>q7,sparseSegmentReductionImpl:()=>qA,sqrtImpl:()=>AG,squaredDifferenceImpl:()=>X7,stridedSliceImpl:()=>K7,stringNGramsImpl:()=>Z7,stringSplitImpl:()=>Y7,stringToHashBucketFastImpl:()=>J7,subImpl:()=>Q7,tileImpl:()=>eI,topKImpl:()=>nI,transposeImpl:()=>HA,uniqueImpl:()=>sI});function b7(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}var NU=e=>{let{x:t}=e.inputs,n=e.backend;Ne(t,"abs");let s=new Float32Array(v.sizeFromShape(t.shape)),r=n.data.get(t.dataId).values;return s=b7(r),n.makeOutput(s,t.shape,"float32")},EU={kernelName:ni,backendName:"cpu",kernelFunc:NU};function Jt(e){return(t,n,s,r,a)=>{let o=E.assertAndGetBroadcastShape(t,n),i=o.length,l=v.computeStrides(o),c=v.sizeFromShape(o),u=v.getTypedArrayFromDType(a,c),d=t.length,p=n.length,h=v.computeStrides(t),f=v.computeStrides(n),m=E.getBroadcastDims(t,o),g=E.getBroadcastDims(n,o);if(m.length+g.length===0)for(let y=0;y<u.length;++y)u[y]=e(s[y%s.length],r[y%r.length]);else for(let y=0;y<u.length;++y){let A=v.indexToLoc(y,i,l),x=A.slice(-d);m.forEach(S=>x[S]=0);let b=v.locToIndex(x,d,h),w=A.slice(-p);g.forEach(S=>w[S]=0);let k=v.locToIndex(w,p,f);u[y]=e(s[b],r[k])}return[u,o]}}function Ss(e){let{inputs:t,backend:n}=e,{real:s,imag:r}=t,a=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,i=n.makeTensorInfo(s.shape,"complex64"),l=n.data.get(i.dataId);return l.complexTensorInfos={real:n.makeTensorInfo(s.shape,"float32",a),imag:n.makeTensorInfo(r.shape,"float32",o)},i}var RU={kernelName:jc,backendName:"cpu",kernelFunc:Ss};function Im(e,t,n="float32"){if(n==="complex64"){let r=Im(e,t,"float32"),a=Im(e,t,"float32");return Ss({inputs:{real:r,imag:a},backend:e})}let s=v.makeZerosTypedArray(v.sizeFromShape(t),n);return e.makeTensorInfo(t,n,s)}function Or(e){let{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}var $U={kernelName:Ba,backendName:"cpu",kernelFunc:Or};function fl(e){let{inputs:t,backend:n}=e,{input:s}=t,r=n.data.get(s.dataId).complexTensorInfos.real,a=n.data.get(r.dataId).values;return n.makeTensorInfo(r.shape,r.dtype,a)}var DU={kernelName:td,backendName:"cpu",kernelFunc:fl};function Po(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dtype:a}=s;if(a==="complex64"){if(r.dtype==="complex64")return Or({inputs:{x:r},backend:n});let o=Im(n,r.shape,r.dtype),i=Po({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=Ss({inputs:{real:i,imag:o},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),l}if(r.dtype==="complex64"){let o=fl({inputs:{input:r},backend:n}),i=Po({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(o),i}if(!v.hasEncodingLoss(r.dtype,a)){let o=Or({inputs:{x:r},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32"){let o=n.data.get(r.dataId).values,i=Int32Array.from(o);return n.makeTensorInfo(r.shape,"int32",i)}if(a==="bool"){let o=n.data.get(r.dataId).values,i=v.toTypedArray([0],r.dtype),[l,c]=Jt((u,d)=>u!==d?1:0)(r.shape,[],o,i,"bool");return n.makeTensorInfo(c,"bool",l)}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${a}`)}var _U={kernelName:Ca,backendName:"cpu",kernelFunc:Po};function wn(e,t,n,s){return n==null?({inputs:r,backend:a})=>{let{a:o,b:i}=r,l=a;Ne([o,i],e);let c=l.data.get(o.dataId).values,u=l.data.get(i.dataId).values,d=o.dtype==="string"?E.fromUint8ToStringArray(c):c,p=o.dtype==="string"?E.fromUint8ToStringArray(u):u,h=s||o.dtype,[f,m]=t(o.shape,i.shape,d,p,h);return l.makeTensorInfo(m,h,f)}:({inputs:r,backend:a})=>{let{a:o,b:i}=r,l=a;if(o.dtype==="complex64"||i.dtype==="complex64"){let c=Po({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),u=l.data.get(c.dataId),d=u.complexTensorInfos.real,p=u.complexTensorInfos.imag,h=l.data.get(d.dataId).values,f=l.data.get(p.dataId).values,m=Po({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(m.dataId),y=g.complexTensorInfos.real,A=g.complexTensorInfos.imag,x=l.data.get(y.dataId).values,b=l.data.get(A.dataId).values,[w,k,S]=n(o.shape,i.shape,h,f,x,b),N=l.makeTensorInfo(S,"float32",w),$=l.makeTensorInfo(S,"float32",k),F=Ss({inputs:{real:N,imag:$},backend:l});return l.disposeIntermediateTensorInfo(c),l.disposeIntermediateTensorInfo(m),l.disposeIntermediateTensorInfo(N),l.disposeIntermediateTensorInfo($),F}else{let c=l.data.get(o.dataId).values,u=l.data.get(i.dataId).values,d=s||o.dtype,[p,h]=t(o.shape,i.shape,c,u,d);return l.makeTensorInfo(h,d,p)}}}function WA(e){return(t,n,s,r,a,o)=>{let i=E.assertAndGetBroadcastShape(t,n),l=v.sizeFromShape(i),c=i.length,u=v.computeStrides(i),d=v.getTypedArrayFromDType("float32",l),p=v.getTypedArrayFromDType("float32",l),h=E.getBroadcastDims(t,i),f=E.getBroadcastDims(n,i),m=E.mergeRealAndImagArrays(s,r),g=E.mergeRealAndImagArrays(a,o),y=t.length,A=v.computeStrides(t),x=n.length,b=v.computeStrides(n);if(h.length+f.length===0)for(let w=0;w<d.length;w++){let k=w%m.length,S=w%g.length,N=e(m[k*2],m[k*2+1],g[S*2],g[S*2+1]);d[w]=N.real,p[w]=N.imag}else for(let w=0;w<d.length;w++){let k=v.indexToLoc(w,c,u),S=k.slice(-y);h.forEach(D=>S[D]=0);let N=v.locToIndex(S,y,A),$=k.slice(-x);f.forEach(D=>$[D]=0);let F=v.locToIndex($,x,b),R=e(m[N*2],m[N*2+1],g[F*2],g[F*2+1]);d[w]=R.real,p[w]=R.imag}return[d,p,i]}}var v7=Jt((e,t)=>e+t),PU=WA((e,t,n,s)=>({real:e+n,imag:t+s})),sp=wn(qr,v7,PU),FU={kernelName:qr,backendName:"cpu",kernelFunc:sp};function VA(e,t,n,s,r){let a=v.sizeFromShape(s),o=v.makeZerosTypedArray(r,n);for(let i=0;i<e.length;i++){let l=e[i];if(l<0)throw new Error("Input x must be non-negative!");l>=r||(a>0?o[l]+=t[i]:o[l]+=1)}return o}function w7(e,t,n,s=!1){let r=e.shape[0],a=e.shape[1],o=We([r,n],t.dtype);for(let i=0;i<r;i++)for(let l=0;l<a;l++){let c=e.get(i,l);if(c<0)throw new Error("Input x must be non-negative!");c>=n||(s?o.set(1,i,c):t.size>0?o.set(o.get(i,c)+t.get(i,l),i,c):o.set(o.get(i,c)+1,i,c))}return o}function Fo(e){return(t,n,s)=>{let r=v.getTypedArrayFromDType(n,t.length);for(let a=0;a<t.length;++a)r[a]=e(t[a],s);return r}}function xt(e,t,n){return({inputs:s,attrs:r,backend:a})=>{let{x:o}=s;if(Ne(o,e),o.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");let i=a,l=i.data.get(o.dataId).values,c=v.sizeFromShape(o.shape),u=n||o.dtype,d=v.getArrayFromDType(u,c);for(let p=0;p<c;++p)d[p]=t(l[p],r);return i.makeTensorInfo(o.shape,u,d)}}function Yu(e,t,n){return({inputs:s,attrs:r,backend:a})=>{let{x:o}=s;if(Ne(o,e),o.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");let i=a,l=i.data.get(o.dataId).values,c=n||o.dtype,u=t(l,c,r);return i.makeTensorInfo(o.shape,c,u)}}var k7=Fo(e=>Math.ceil(e)),OU=Yu(Ta,k7),MU={kernelName:Ta,backendName:"cpu",kernelFunc:OU};function UA(e,t,n,s){let r=v.getArrayFromDType(n,v.sizeFromShape(t));if(s&&n!=="string"){let a=0;e.forEach(o=>{let i=v.sizeFromShape(o.shape);r.set(o.vals,a),a+=i})}else{let a=0;e.forEach(o=>{let i=n==="string"?E.fromUint8ToStringArray(o.vals):o.vals,l=0;for(let c=0;c<o.shape[0];++c){let u=c*t[1]+a;for(let d=0;d<o.shape[1];++d)r[u+d]=i[l++]}a+=o.shape[1]})}return r}var I7=Jt((e,t)=>e===t?1:0),S7=wn(li,I7,null,"bool"),zU={kernelName:li,backendName:"cpu",kernelFunc:S7},C7=Fo(e=>Math.exp(e)),T7=Yu(Fa,C7),LU={kernelName:Fa,backendName:"cpu",kernelFunc:T7},N7=Fo(e=>Math.expm1(e)),BU=Yu(ci,N7),WU={kernelName:ci,backendName:"cpu",kernelFunc:BU},E7=Fo(e=>Math.floor(e)),VU=Yu(Oa,E7),UU={kernelName:Oa,backendName:"cpu",kernelFunc:VU};function R7(e,t,n,s,r,a,o,i,l){let c=We([s,a],n);for(let u=0;u<s;u++){let d=[],p=0;for(let h=0;h<r;h++){let f=e[u*r+h];p+=f*o[h],d.push(f)}if(p<0||p>=l/a)throw new Error(`Invalid indices: ${d} does not index into ${i}`);for(let h=0;h<a;h++)c.values[u*a+h]=t.get(...t.indexToLoc(p*a+h))}return c}function $7(e,t,n){let s=We(n,e.dtype);for(let r=0;r<s.size;++r){let o=s.indexToLoc(r).slice(),i=o[0],l=o[2],c=t.locToIndex([i,l]);o[2]=t.values[c];let u=e.locToIndex(o);s.values[r]=e.values[u]}return s}var D7=Jt((e,t)=>e>t?1:0),GU=wn(fi,D7,null,"bool"),HU={kernelName:fi,backendName:"cpu",kernelFunc:GU},_7=Jt((e,t)=>e>=t?1:0),jU=wn(La,_7,null,"bool"),qU={kernelName:La,backendName:"cpu",kernelFunc:jU},P7=Jt((e,t)=>e<t?1:0),XU=wn(gi,P7,null,"bool"),KU={kernelName:gi,backendName:"cpu",kernelFunc:XU},F7=Jt((e,t)=>e<=t?1:0),ZU=wn(yi,F7,null,"bool"),YU={kernelName:yi,backendName:"cpu",kernelFunc:ZU};function O7(e,t,n){let s=(t-e)/(n-1),r=v.makeZerosTypedArray(n,"float32");r[0]=e;for(let a=1;a<r.length;a++)r[a]=r[a-1]+s;return r}var M7=Fo(e=>Math.log(e)),JU=Yu(Wa,M7),QU={kernelName:Wa,backendName:"cpu",kernelFunc:JU};function z7(e,t,n,s){let r=v.getTypedArrayFromDType(s,v.sizeFromShape(n));for(let a=0;a<r.length;++a){let o=a*t,i=e[o];for(let l=0;l<t;++l){let c=e[o+l];(Number.isNaN(c)||c>i)&&(i=c)}r[a]=i}return r}var L7=Jt((e,t)=>Math.max(e,t)),eG=wn(Ua,L7),tG={kernelName:Ua,backendName:"cpu",kernelFunc:eG},B7=Jt((e,t)=>Math.min(e,t)),nG=wn(qa,B7),sG={kernelName:qa,backendName:"cpu",kernelFunc:nG},GA=Jt((e,t)=>e*t),rG=WA((e,t,n,s)=>({real:e*n-t*s,imag:e*s+t*n})),Sm=wn(Ka,GA,rG),aG={kernelName:Ka,backendName:"cpu",kernelFunc:Sm};function W7(e,t,n){let s=v.createScalarValue(-1,n);return GA([],t,s,e,n)}function oG(e){let{inputs:t,backend:n}=e,{x:s}=t;Ne(s,"neg");let r=n.data.get(s.dataId).values,[a,o]=W7(r,s.shape,s.dtype);return n.makeTensorInfo(o,s.dtype,a)}var iG={kernelName:xi,backendName:"cpu",kernelFunc:oG},V7=Jt((e,t)=>e!==t?1:0),lG=wn(bi,V7,null,"bool"),uG={kernelName:bi,backendName:"cpu",kernelFunc:lG};function HA(e,t,n,s,r){let a=t.length,o=v.sizeFromShape(t),i=v.computeStrides(t),l=v.computeStrides(r),c=v.getTypedArrayFromDType(n,v.sizeFromShape(r));for(let u=0;u<o;++u){let d=v.indexToLoc(u,a,i),p=new Array(d.length);for(let f=0;f<p.length;f++)p[f]=d[s[f]];let h=v.locToIndex(p,a,l);c[h]=e[u]}return c}function zs(e){let{inputs:t,attrs:n,backend:s}=e,{x:r}=t,{perm:a}=n;Ne(r,"transpose");let o=r.shape.length,i=new Array(o);for(let d=0;d<i.length;d++)i[d]=r.shape[a[d]];let l=s.data.get(r.dataId).values,c=HA(l,r.shape,r.dtype,a,i);return{dataId:s.write(c,i,r.dtype),shape:i,dtype:r.dtype}}var cG={kernelName:po,backendName:"cpu",kernelFunc:zs};function U7(e,t,n,s){let[r,a]=E.computeOutAndReduceShapes(e,s),o=Ln(t,"int32"),i=v.makeZerosTypedArray(v.sizeFromShape(r),o),l=v.sizeFromShape(a);for(let c=0;c<i.length;++c){let u=c*l,d=1;for(let p=0;p<l;++p)d*=n[u+p];i[c]=d}return{outVals:i,outShape:r,outDtype:o}}function dG(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;Ne(r,"prod");let i=r.shape.length,l=v.parseAxisParam(a,r.shape),c=E.getAxesPermutation(l,i),u=l,d=r,p=[];c!=null&&(d=zs({inputs:{x:r},backend:n,attrs:{perm:c}}),p.push(d),u=E.getInnerMostAxes(u.length,i));let h=n.data.get(d.dataId).values,{outVals:f,outShape:m,outDtype:g}=U7(d.shape,d.dtype,h,u),y=m;return o&&(y=E.expandShapeToKeepDim(m,l)),p.forEach(A=>n.disposeIntermediateTensorInfo(A)),n.makeTensorInfo(y,g,f)}var pG={kernelName:Ci,backendName:"cpu",kernelFunc:dG};function jA(e,t,n,s){let r=e===t,a=e<t&&n<0,o=t<e&&n>1;if(r||a||o)return v.makeZerosTypedArray(0,s);let i=Math.abs(Math.ceil((t-e)/n)),l=v.makeZerosTypedArray(i,s);t<e&&n===1&&(n=-1),l[0]=e;for(let c=1;c<l.length;c++)l[c]=l[c-1]+n;return l}var G7=Fo(e=>1/Math.sqrt(e)),hG=Yu(no,G7),fG={kernelName:no,backendName:"cpu",kernelFunc:hG},mG=Fo(e=>1/(1+Math.exp(-e))),H7=xt(ro,e=>1/(1+Math.exp(-e))),gG={kernelName:ro,backendName:"cpu",kernelFunc:H7};function Cm(e,t,n,s,r){let a=yn.isSliceContinous(s,t,n),o=v.sizeFromShape(n),i=v.computeStrides(s);if(a){let d=yn.computeFlatOffset(t,i);return r==="string"?e.slice(d,d+o):e.subarray(d,d+o)}let l=r==="string"?E.fromUint8ToStringArray(e):e,c=We(s,r,l),u=We(n,r);for(let d=0;d<u.size;++d){let p=u.indexToLoc(d),h=p.map((f,m)=>f+t[m]);u.set(c.get(...h),...p)}return r==="string"?E.fromStringArrayToUint8(u.values):u.values}function ml(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:o}=s;Ne(r,"slice");let[i,l]=yn.parseSliceParams(r,a,o);yn.assertParamsValid(r,i,l);let c=n.data.get(r.dataId).values,u=Cm(c,i,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,u)}var yG={kernelName:Di,backendName:"cpu",kernelFunc:ml};function j7(e,t,n,s,r,a,o){let i=t[0],l=a[0],c=new Array(l),u=new Array(i),d=t[1];if(l===0){if(i!==0)throw new Error(`Received SparseTensor with denseShape[0] = 0 but
|
|
indices.shape[0] = ${i}`);let g=v.getArrayFromDType(n,0),y=v.getArrayFromDType(r,0);return[g,[0,d],y,c,u]}let p=!0,h=0,f=new Array(l).fill(0);for(let g=0;g<i;++g){let y=e[g*d];if(y<0)throw new Error(`indices(${g}, 0) is invalid: ${y} < 0`);if(y>=l)throw new Error(`indices(${g}, 0) is invalid: ${y} >= ${l}`);++f[y],p=p&&y>=h,h=y}let m=!0;for(let g=0;g<l;++g){let y=f[g]===0;c[g]=y,m=m&&!y,f[g]=Math.max(f[g],1),g>0&&(f[g]+=f[g-1])}if(m&&p){let g=e,y=s;for(let A=0;A<i;++A)u[A]=A;return[g,[i,d],y,c,u]}else{let g=f[l-1],y=v.getArrayFromDType(n,g*d),A=v.getArrayFromDType(r,g),x=new Array(l).fill(0);for(let b=0;b<i;++b){let w=e[b*d],k=x[w],S=(w===0?0:f[w-1])+k;x[w]++;for(let N=0;N<d;++N)y[S*d+N]=e[b*d+N];A[S]=s[b],u[b]=S}for(let b=0;b<l;++b)if(x[b]===0){let k=b===0?0:f[b-1];y[k*d+0]=b;for(let S=1;S<d;++S)y[k*d+S]=0;A[k]=o}return[y,[g,d],A,c,u]}}function q7(e,t,n,s,r){let a=v.sizeFromShape(s),o=t[0],i=r.length,l=[],c=1,u=-1;for(let g=0;g<i;++g){let y=r[g];if(y===-1){if(u!==-1)throw new Error(`only one output dimension may be -1, not both ${u} and ${g}`);u=g,l.push(1)}else{if(y<0)throw new Error(`size ${g} must be non-negative, not ${y}`);c*=y,l.push(y)}}if(u!==-1){if(c<=0)throw new Error("reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero");let g=Math.trunc(a/c);if(c*g!==a)throw new Error(`Input to reshape is a SparseTensor with ${a}
|
|
dense values, but the requested shape requires a multiple of ${c}. inputShape=${s} outputShape= ${l}`);l[u]=g}let d=v.sizeFromShape(l);if(d!==a)throw new Error(`Input to reshape is a tensor with ${a} dense values, but the requested shape has ${d}. inputShape=${s} outputShape=${l}`);let p=s.length,h=[];if(p>0){h[p-1]=1;for(let g=p-2;g>=0;--g)h[g]=h[g+1]*s[g+1]}let f=[];if(i>0){f[i-1]=1;for(let g=i-2;g>=0;--g)f[g]=f[g+1]*l[g+1]}let m=v.getArrayFromDType(n,o*i);for(let g=0;g<o;++g){let y=0;for(let A=0;A<p;++A)y+=e[g*p+A]*h[A];for(let A=0;A<i;++A)m[g*i+A]=Math.trunc(y/f[A]),y%=f[A]}return[m,[o,i],l]}function qA(e,t,n,s,r,a=!1,o=0){let i=s.length;if(i!==r.length)throw new Error("segmentIds and indices should have same size.");let l=[t[0],e.length/t[0]],c=l[1],d=i>0?r[i-1]+1:0;if(d<0)throw new Error("segment ids must be >= 0");let p=t.slice();p[0]=d;let h=p.reduce((x,b)=>x*b,1),f=v.getArrayFromDType(n,h);if(i===0)return d>0&&f.fill(o),[f,p];if(d<=0)throw new Error("segment ids must be >= 0");let m=0,g=1,y=0,A=r[m];for(;;){let x=0;if(g<i){if(x=r[g],A===x){++g;continue}if(A>=x)throw new Error("segment ids are not increasing")}if(A<0||A>=d)throw new Error(`Segment id ${A} out of range [0, ${d}), possibly because segmentIds input is not sorted.`);A>y&&f.fill(o,y*c,A*c);for(let b=m;b<g;++b){let w=s[b];if(w<0||w>=l[0])throw new Error(`Bad: indices[${b}] == ${s[b]} out of range [0, ${l[0]})`);for(let k=0;k<c;k++)f[A*c+k]+=e[w*c+k]}if(a)for(let b=0;b<c;b++)f[A*c+b]/=g-m;if(m=g,++g,y=A+1,A=x,g>i)break}return y<d&&f.fill(o,y*c,d*c),[f,p]}var AG=Fo(e=>Math.sqrt(e)),xG=xt(ao,e=>Math.sqrt(e)),bG={kernelName:ao,backendName:"cpu",kernelFunc:xG},X7=Jt((e,t)=>{let n=e-t;return n*n}),vG=wn(lo,X7),wG={kernelName:lo,backendName:"cpu",kernelFunc:vG};function K7(e,t,n,s){let r=We(e,t.dtype);for(let a=0;a<r.size;a++){let o=r.indexToLoc(a),i=new Array(o.length);for(let l=0;l<i.length;l++)i[l]=o[l]*n[l]+s[l];r.set(t.get(...i),...o)}return r}var kG=class{constructor(e,t,n,s,r,a){this.separator=v.encodeString(e),this.nGramWidths=t,this.leftPad=v.encodeString(n),this.rightPad=v.encodeString(s),this.padWidth=r,this.preserveShort=a}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){let n=this.getPadWidth(t);return Math.max(0,e+2*n-t+1)}createNGrams(e,t,n,s,r,a){for(let o=0;o<r;++o){let i=this.getPadWidth(a),l=Math.max(0,i-o),c=Math.max(0,i-(r-(o+1))),u=a-(l+c),d=t+(l>0?0:o-i),p=0;p+=l*this.leftPad.length;for(let y=0;y<u;++y)p+=e[d+y].length;p+=c*this.rightPad.length,p+=(l+c+u-1)*this.separator.length,n[s+o]=new Uint8Array(p);let f=n[s+o],m=0,g=y=>y.forEach(A=>f[m++]=A);for(let y=0;y<l;++y)g(this.leftPad),g(this.separator);for(let y=0;y<u-1;++y)g(e[d+y]),g(this.separator);if(u>0){g(e[d+u-1]);for(let y=0;y<c;++y)g(this.separator),g(this.rightPad)}else{for(let y=0;y<c-1;++y)g(this.rightPad),g(this.separator);g(this.rightPad)}}}compute(e,t){let n=e.length,s=t.length;if(s>0){let i=t[0];if(i!==0)throw new Error(`First split value must be 0, got ${i}`);for(let l=1;l<s;++l){let c=t[l]>=i;if(c=c&&t[l]<=n,!c)throw new Error(`Invalid split value ${t[l]}, must be in [${i}, ${n}]`);i=t[l]}if(i!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${i}`)}let r=s-1,a=v.getArrayFromDType("int32",s);if(n===0||s===0){let i=new Array(n);for(let l=0;l<=r;++l)a[l]=0;return[i,a]}a[0]=0;for(let i=1;i<=r;++i){let l=t[i]-t[i-1],c=0;this.nGramWidths.forEach(u=>{c+=this.getNumNGrams(l,u)}),this.preserveShort&&l>0&&c===0&&(c=1),a[i]=a[i-1]+c}let o=new Array(a[r]);for(let i=0;i<r;++i){let l=t[i],c=a[i];if(this.nGramWidths.forEach(u=>{let d=t[i+1]-t[i],p=this.getNumNGrams(d,u);this.createNGrams(e,l,o,c,p,u),c+=p}),this.preserveShort&&c===a[i]){let u=t[i+1]-t[i];if(u===0)continue;let d=u+2*this.padWidth,p=1;this.createNGrams(e,l,o,c,p,d)}}return[o,a]}};function Z7(e,t,n,s,r,a,o,i){return new kG(n,s,r,a,o,i).compute(e,t)}function IG(e,t,n,s){if(!e.length)return;if(t.length===0){for(let a=0;a<e.length;++a)s.push(e.subarray(a,a+1));return}if(t.length===1){let a=t[0],o=e.indexOf(a);for(;o!==-1;){let i=e.subarray(0,o);(!n||i.length!==0)&&s.push(i),e=e.subarray(o+1),o=e.indexOf(a)}(!n||e.length!==0)&&s.push(e);return}let r=0;for(let a=0;a<e.length+1;a++)if(a===e.length||t.indexOf(e[a])!==-1){let o=e.subarray(r,a);(!n||o.length!==0)&&s.push(o),r=a+1}}function Y7(e,t,n){let s=e.length,r=[],a=0,o=0,i=new Array(s);for(let p=0;p<s;++p){let h=r.length;IG(e[p],t,n,r);let f=r.length-h;i[p]=f,a+=f,o=Math.max(o,f)}let l=v.getArrayFromDType("int32",a*2),c=new Array(a),u=[s,o],d=0;for(let p=0;p<s;++p)for(let h=0;h<i[p];++h)l[d*2]=p,l[d*2+1]=h,c[d]=r[d],++d;return[l,c,u]}function J7(e,t){let n=v.getArrayFromDType("int32",e.length);for(let s=0;s<e.length;++s)n[s]=v.fingerPrint64(e[s]).modulo(t).getLowBitsUnsigned();return n}var Q7=Jt((e,t)=>e-t),SG=WA((e,t,n,s)=>({real:e-n,imag:t-s})),XA=wn(uo,Q7,SG),CG={kernelName:uo,backendName:"cpu",kernelFunc:XA};function eI(e,t){let n=new Array(e.rank);for(let r=0;r<n.length;r++)n[r]=e.shape[r]*t[r];let s=We(n,e.dtype);for(let r=0;r<s.values.length;++r){let a=s.indexToLoc(r),o=new Array(e.rank);for(let l=0;l<o.length;l++)o[l]=a[l]%e.shape[l];let i=e.locToIndex(o);s.values[r]=e.values[i]}return s}var rp=(e,t)=>{let n=t.value-e.value;return n===0?e.index-t.index:n};function tI(e,t,n=0,s=e.length-1){for(;s>n;){if(s-n>600){let i=s-n+1,l=t-n+1,c=Math.log(i),u=.5*Math.exp(2*c/3),d=.5*Math.sqrt(c*u*(i-u)/i)*Math.sign(l-i/2),p=Math.max(n,Math.floor(t-l*u/i+d)),h=Math.min(s,Math.floor(t+(i-l)*u/i+d));tI(e,t,p,h)}let r=e[t],a=n,o=s;for(v.swap(e,n,t),rp(e[s],r)>0&&v.swap(e,n,s);a<o;){for(v.swap(e,a,o),a++,o--;rp(e[a],r)<0;)a=a+1;for(;rp(e[o],r)>0;)o=o-1}rp(e[n],r)===0?v.swap(e,n,o):(o=o+1,v.swap(e,o,s)),o<=t&&(n=o+1),t<=o&&(s=o-1)}}function nI(e,t,n,s,r){let a=t[t.length-1],[o,i]=[e.length/a,a],l=v.getTypedArrayFromDType(n,o*s),c=v.getTypedArrayFromDType("int32",o*s);for(let d=0;d<o;d++){let p=d*i,h=e.subarray(p,p+i),f=new Array(h.length);h.forEach((A,x)=>f[x]={value:A,index:x}),s<f.length&&(tI(f,s),f=f.slice(0,s)),r&&f.sort(rp);let m=d*s,g=l.subarray(m,m+s),y=c.subarray(m,m+s);for(let A=0;A<s;A++)g[A]=f[A].value,y[A]=f[A].index}let u=t.slice();return u[u.length-1]=s,[We(u,n,l),We(u,"int32",c)]}function sI(e,t,n,s){let r=v.parseAxisParam(t,n)[0],a=[1,n[0],1];for(let f=0;f<r;f++)a[0]*=n[f];a[1]=n[r];for(let f=r+1;f<n.length;f++)a[2]*=n[f];let o={},i=new Int32Array(n[r]),l=new tn(a,s,e),c=[],u=a[0]===1&&a[2]===1;for(let f=0;f<n[r];f++){let m;if(u)m=e[f].toString();else{let g=[];for(let y=0;y<a[0];y++)for(let A=0;A<a[2];A++)g.push(l.get(y,f,A));m=g.join(",")}if(o[m]!==void 0)i[f]=o[m];else{let g=Object.keys(o).length;o[m]=g,i[f]=g,c.push(f)}}let d=a.slice();d[1]=Object.keys(o).length;let p=new tn(d,s);c.forEach((f,m)=>{for(let g=0;g<a[0];g++)for(let y=0;y<a[2];y++)p.set(l.get(g,f,y),g,m,y)});let h=n.slice();return h[r]=d[1],{outputValues:p.values,outputShape:h,indices:i}}Xi("cpu",()=>new LA,1);var rI=xt(Pa,e=>e>=0?e:Math.exp(e)-1),TG={kernelName:Pa,backendName:"cpu",kernelFunc:rI};function aI(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{alpha:a}=s;Ne([r],"leakyRelu");let o=v.sizeFromShape(r.shape),i=n.data.get(r.dataId).values,l=v.getTypedArrayFromDType("float32",o);for(let c=0;c<i.length;c++)l[c]=i[c]<0?a*i[c]:i[c];return n.makeTensorInfo(r.shape,"float32",l)}var NG={kernelName:mi,backendName:"cpu",kernelFunc:aI},EG=Jt((e,t)=>e<0?t*e:e);function oI(e){let{inputs:t,backend:n}=e,{x:s,alpha:r}=t;Ne([s,r],"prelu");let a=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,[i,l]=EG(s.shape,r.shape,a,o,s.dtype);return n.makeTensorInfo(l,s.dtype,i)}var RG={kernelName:Ja,backendName:"cpu",kernelFunc:oI},iI=xt(Qa,e=>Math.max(0,e)),$G={kernelName:Qa,backendName:"cpu",kernelFunc:iI},lI=xt(to,e=>Math.min(Math.max(0,e),6)),DG={kernelName:to,backendName:"cpu",kernelFunc:lI};function KA(e,t,n,s,r){if(n==="linear")return Or({inputs:{x:t},backend:e});if(n==="relu")return iI({inputs:{x:t},backend:e});if(n==="elu")return rI({inputs:{x:t},backend:e});if(n==="relu6")return lI({inputs:{x:t},backend:e});if(n==="prelu")return oI({inputs:{x:t,alpha:s},backend:e});if(n==="leakyrelu")return aI({inputs:{x:t},backend:e,attrs:{alpha:r}});if(n==="sigmoid")return H7({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function Et(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{shape:a}=s,o=v.sizeFromShape(r.shape),i=v.inferFromImplicitShape(a,o),l=v.sizeFromShape(i);v.assert(o===l,()=>`The new shape (${i}) has ${l} elements and the old shape (${r.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`),n.incRef(r.dataId);let c=n.data.get(r.dataId);if(c.complexTensorInfos!=null){let u=c.complexTensorInfos.real,d=c.complexTensorInfos.imag;u.shape=i,d.shape=i}return{dataId:r.dataId,shape:i,dtype:r.dtype}}var _G={kernelName:Ti,backendName:"cpu",kernelFunc:Et};function uI(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:o,transposeB:i}=s;Ne([r,a],"matMul");let l=r.shape.length,c=a.shape.length,u=o?r.shape[l-2]:r.shape[l-1],d=i?a.shape[c-1]:a.shape[c-2],p=o?r.shape[l-1]:r.shape[l-2],h=i?a.shape[c-2]:a.shape[c-1],f=r.shape.slice(0,-2),m=a.shape.slice(0,-2),g=v.sizeFromShape(f),y=v.sizeFromShape(m),A=g===y||g===1||y===1;v.assert(l>=2&&c>=2&&A,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${f}) and (${m}).`);let b=(g>y?r.shape.slice(0,-2):a.shape.slice(0,-2)).concat([p,h]);v.assert(u===d,()=>`Error in matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${r.shape} and ${a.shape} and transposeA=${o} and transposeB=${i} must match.`);let w=o?[g,u,p]:[g,p,u],k=i?[y,h,d]:[y,d,h],S=Et({inputs:{x:r},backend:n,attrs:{shape:w}}),N=Et({inputs:{x:a},backend:n,attrs:{shape:k}}),$=o?S.shape[1]:S.shape[2],F=o?S.shape[2]:S.shape[1],R=i?N.shape[1]:N.shape[2],D=Math.max(g,y),T=n.data.get(S.dataId).values,O=n.data.get(N.dataId).values,B=v.computeStrides(S.shape),H=v.computeStrides(N.shape),[z,X,ee]=o?[B[0],1,B[1]]:[B[0],B[1],1],[J,Q,ne]=i?[1,H[1],H[0]]:[H[1],1,H[0]],K=F*R,oe=We([D,F,R],S.dtype),ce=oe.values,he=n.blockSize;for(let Ae=0;Ae<D;Ae++)for(let Se=0;Se<F;Se+=he)for(let Ce=0;Ce<R;Ce+=he)for(let Oe=0;Oe<$;Oe+=he){let Ue=Math.min(Se+he,F),ze=Math.min(Ce+he,R),wt=Math.min(Oe+he,$);for(let mt=Se;mt<Ue;mt++)for(let gt=Ce;gt<ze;gt++){let ht=0;for(let bt=Oe;bt<wt;bt++){let Ye=Math.min(Ae,g-1)*z,Yn=Math.min(Ae,y-1)*ne,Mt=T[Ye+mt*X+bt*ee],hs=O[bt*J+gt*Q+Yn];ht+=Mt*hs}ce[Ae*K+(mt*R+gt)]+=ht}}return n.disposeIntermediateTensorInfo(S),n.disposeIntermediateTensorInfo(N),n.makeTensorInfo(b,oe.dtype,oe.values)}var PG={kernelName:Sa,backendName:"cpu",kernelFunc:uI};function FG(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:d}=s,p,h,f,m=[];p=uI({inputs:{a:r,b:a},attrs:{transposeA:l,transposeB:c},backend:n}),o&&(h=sp({inputs:{a:p,b:o},backend:n}),m.push(p),p=h),u&&(f=KA(n,p,u,i,d),m.push(p),p=f);for(let y of m)n.disposeIntermediateTensorInfo(y);return p}var OG={kernelName:fo,backendName:"cpu",kernelFunc:FG},MG=xt(ql,e=>Math.acos(e)),zG={kernelName:ql,backendName:"cpu",kernelFunc:MG},LG=xt(Xl,e=>Math.acosh(e)),BG={kernelName:Xl,backendName:"cpu",kernelFunc:LG};function WG(e){let{inputs:t,backend:n}=e,s=t;Ne(t,"addN");let r=s.map(i=>n.data.get(i.dataId).values),a=We(s[0].shape,s[0].dtype),o=a.values;for(let i=0;i<s.length;i++){let l=r[i];for(let c=0;c<o.length;c++)o[c]+=l[c]}return n.makeTensorInfo(a.shape,a.dtype,a.values)}var VG={kernelName:wa,backendName:"cpu",kernelFunc:WG};function UG(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;Ne(r,"all");let i=v.parseAxisParam(a,r.shape),l=i,c=E.getAxesPermutation(l,r.shape.length),u=r;c!=null&&(u=zs({inputs:{x:r},backend:n,attrs:{perm:c}}),l=E.getInnerMostAxes(l.length,r.shape.length)),E.assertAxesAreInnerMostDims("all",l,u.shape.length);let[d,p]=E.computeOutAndReduceShapes(u.shape,l),h=v.sizeFromShape(p),f=v.makeZerosTypedArray(v.sizeFromShape(d),u.dtype),m=n.data.get(u.dataId).values;for(let y=0;y<f.length;++y){let A=y*h,x=m[A];for(let b=0;b<h;++b){let w=m[A+b];x=x&&w}f[y]=x}c!=null&&n.disposeIntermediateTensorInfo(u);let g=n.makeTensorInfo(d,u.dtype,f);if(o){let y=E.expandShapeToKeepDim(d,i),A=Et({inputs:{x:g},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(g),A}return g}var GG={kernelName:Kl,backendName:"cpu",kernelFunc:UG};function HG(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;Ne(r,"any");let i=v.parseAxisParam(a,r.shape),l=i,c=E.getAxesPermutation(l,r.shape.length),u=r;c!=null&&(u=zs({inputs:{x:r},backend:n,attrs:{perm:c}}),l=E.getInnerMostAxes(l.length,r.shape.length)),E.assertAxesAreInnerMostDims("any",l,u.shape.length);let[d,p]=E.computeOutAndReduceShapes(u.shape,l),h=v.sizeFromShape(p),f=v.makeZerosTypedArray(v.sizeFromShape(d),u.dtype),m=n.data.get(u.dataId).values;for(let y=0;y<f.length;++y){let A=y*h,x=m[A];for(let b=0;b<h;++b){let w=m[A+b];x=x||w}f[y]=x}c!=null&&n.disposeIntermediateTensorInfo(u);let g=n.makeTensorInfo(d,u.dtype,f);if(o){let y=E.expandShapeToKeepDim(d,i),A=Et({inputs:{x:g},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(g),A}return g}var jG={kernelName:Zl,backendName:"cpu",kernelFunc:HG};function qG(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;Ne(r,"argMax");let o=v.parseAxisParam(a,r.shape),i=E.getAxesPermutation(o,r.shape.length),l=r,c=[];i!=null&&(l=zs({inputs:{x:r},backend:n,attrs:{perm:i}}),c.push(l),o=E.getInnerMostAxes(o.length,l.shape.length)),o=[o[0]],E.assertAxesAreInnerMostDims("argMax",o,l.shape.length);let[u,d]=E.computeOutAndReduceShapes(l.shape,o),p=v.sizeFromShape(u),h=v.makeZerosTypedArray(p,"int32"),f=v.sizeFromShape(d),m=n.data.get(l.dataId).values;for(let g=0;g<h.length;++g){let y=g*f,A=m[y],x=0;for(let b=0;b<f;++b){let w=m[y+b];w>A&&(A=w,x=b)}h[g]=x}return c.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(u,"int32",h)}var XG={kernelName:ka,backendName:"cpu",kernelFunc:qG};function KG(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;Ne(r,"argMin");let o=v.parseAxisParam(a,r.shape),i=E.getAxesPermutation(o,r.shape.length),l=r,c=[];i!=null&&(l=zs({inputs:{x:r},backend:n,attrs:{perm:i}}),c.push(l),o=E.getInnerMostAxes(o.length,l.shape.length)),o=[o[0]],E.assertAxesAreInnerMostDims("argMin",o,l.shape.length);let[u,d]=E.computeOutAndReduceShapes(l.shape,o),p=v.sizeFromShape(u),h=v.makeZerosTypedArray(p,"int32"),f=v.sizeFromShape(d),m=n.data.get(l.dataId).values;for(let g=0;g<h.length;++g){let y=g*f,A=m[y],x=0;for(let b=0;b<f;++b){let w=m[y+b];w<A&&(A=w,x=b)}h[g]=x}return c.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(u,"int32",h)}var ZG={kernelName:Yl,backendName:"cpu",kernelFunc:KG},YG=xt(Jl,e=>Math.asin(e)),JG={kernelName:Jl,backendName:"cpu",kernelFunc:YG},QG=xt(Ql,e=>Math.asinh(e)),eH={kernelName:Ql,backendName:"cpu",kernelFunc:QG},tH=xt(eu,e=>Math.atan(e)),nH={kernelName:eu,backendName:"cpu",kernelFunc:tH},sH=Jt((e,t)=>Math.atan2(e,t)),rH=wn(nu,sH),aH={kernelName:nu,backendName:"cpu",kernelFunc:rH},oH=xt(tu,e=>Math.atanh(e)),iH={kernelName:tu,backendName:"cpu",kernelFunc:oH};function ZA(e,t,n,s,r,a){let o=r.strideHeight,i=r.strideWidth,l=r.dilationHeight,c=r.dilationWidth,u=r.effectiveFilterHeight,d=r.effectiveFilterWidth,p=r.padInfo.top,h=r.padInfo.left,f=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=We(r.outShape,n),g=m.values,y=r.outShape[1]*r.outShape[2]*r.outShape[3],A=r.outShape[2]*r.outShape[3],x=r.outShape[3];for(let b=0;b<r.batchSize;++b){let w=b*y,k=b*s[0];for(let S=0;S<r.inChannels;++S)for(let N=0;N<r.outHeight;++N){let $=N*o-p,F=Math.max(0,$),R=Math.min(r.inHeight,u+$),D=w+N*A;for(let T=0;T<r.outWidth;++T){let O=T*i-h,B=Math.max(0,O),H=Math.min(r.inWidth,d+O),z=f,X=0,ee=0;for(let Q=F;Q<R;Q+=l){let ne=k+Q*s[1];for(let K=B;K<H;K+=c){let oe=ne+K*s[2],ce=e[oe+S];a==="max"&&ce>z?z=ce:a==="avg"&&(X+=ce,ee++)}if(isNaN(z))break}let J=D+T*x+S;g[J]=a==="avg"?X/ee:z}}}return m}function cI(e,t,n,s,r=!1,a=!1){let o=We(s.outShape,"int32"),i=s.strideHeight,l=s.strideWidth,c=s.dilationHeight,u=s.dilationWidth,d=s.effectiveFilterHeight,p=s.effectiveFilterWidth,h=s.padInfo.top,f=s.padInfo.left,m=We(t,n,e);for(let g=0;g<s.batchSize;++g)for(let y=0;y<s.inChannels;++y)for(let A=0;A<s.outHeight;++A){let x=A*i-h,b=x;for(;b<0;)b+=c;let w=Math.min(s.inHeight,d+x);for(let k=0;k<s.outWidth;++k){let S=k*l-f,N=S;for(;N<0;)N+=u;let $=Math.min(s.inWidth,p+S),F=Number.NEGATIVE_INFINITY,R=-1;for(let D=b;D<w;D+=c){let T=D-x;for(let O=N;O<$;O+=u){let B=O-S,H=m.get(g,D,O,y);H>F&&(F=H,r?R=a?((g*s.inHeight+D)*s.inWidth+O)*s.inChannels+y:(D*s.inWidth+O)*s.inChannels+y:R=T*p+B)}}o.set(R,g,A,k,y)}}return o}function dI(e,t,n,s,r,a){let o=r.strideDepth,i=r.strideHeight,l=r.strideWidth,c=r.dilationDepth,u=r.dilationHeight,d=r.dilationWidth,p=r.effectiveFilterDepth,h=r.effectiveFilterHeight,f=r.effectiveFilterWidth,m=r.padInfo.front,g=r.padInfo.top,y=r.padInfo.left,A=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=We(r.outShape,n),b=x.values,w=r.outShape[1]*r.outShape[2]*r.outShape[3]*r.outShape[4],k=r.outShape[2]*r.outShape[3]*r.outShape[4],S=r.outShape[3]*r.outShape[4],N=r.outShape[4];for(let $=0;$<r.batchSize;++$){let F=$*w,R=$*s[0];for(let D=0;D<r.inChannels;++D)for(let T=0;T<r.outDepth;++T){let O=T*o-m,B=O;for(;B<0;)B+=c;let H=Math.min(r.inDepth,p+O),z=F+T*k;for(let X=0;X<r.outHeight;++X){let ee=X*i-g,J=ee;for(;J<0;)J+=u;let Q=Math.min(r.inHeight,h+ee),ne=z+X*S;for(let K=0;K<r.outWidth;++K){let oe=K*l-y,ce=oe;for(;ce<0;)ce+=d;let he=Math.min(r.inWidth,f+oe),Ae=ne+K*N,Se=A,Ce=0,Oe=0;for(let ze=B;ze<H;ze+=c){let wt=R+ze*s[1];for(let mt=J;mt<Q;mt+=u){let gt=wt+mt*s[2];for(let ht=ce;ht<he;ht+=d){let bt=gt+ht*s[3],Ye=e[bt+D];if(a==="max"&&Ye>Se?Se=Ye:a==="avg"&&(Ce+=Ye,Oe++),isNaN(Se))break}if(isNaN(Se))break}if(isNaN(Se))break}let Ue=Ae+D;b[Ue]=a==="avg"?Ce/Oe:Se}}}}return x}function lH(e,t){let n=We(t.outShape,"int32"),s=t.strideDepth,r=t.strideHeight,a=t.strideWidth,o=t.dilationDepth,i=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,u=t.effectiveFilterHeight,d=t.effectiveFilterWidth,p=t.padInfo.front,h=t.padInfo.top,f=t.padInfo.left;for(let m=0;m<t.batchSize;++m)for(let g=0;g<t.inChannels;++g)for(let y=0;y<t.outDepth;++y){let A=y*s-p,x=A;for(;x<0;)x+=o;let b=Math.min(t.inDepth,c+A);for(let w=0;w<t.outHeight;++w){let k=w*r-h,S=k;for(;S<0;)S+=i;let N=Math.min(t.inHeight,u+k);for(let $=0;$<t.outWidth;++$){let F=$*a-f,R=F;for(;R<0;)R+=l;let D=Math.min(t.inWidth,d+F),T=Number.NEGATIVE_INFINITY,O=-1;for(let B=x;B<b;B+=o){let H=B-A;for(let z=S;z<N;z+=i){let X=z-k;for(let ee=R;ee<D;ee+=l){let J=ee-F,Q=e.get(m,B,z,ee,g);Q>=T&&(T=Q,O=H*u*d+X*u+J)}}}n.set(O,m,y,w,$,g)}}}return n}function uH(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t;Ne(r,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,c=1;v.assert(E.eitherStridesOrDilationsAreOne(o,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);let u=E.computePool2DInfo(r.shape,a,o,c,i,l),d;if(u.filterWidth===1&&u.filterHeight===1&&v.arraysEqual(u.inShape,u.outShape))d=Or({inputs:{x:r},backend:n});else{let p=n.data.get(r.dataId).values,h=v.computeStrides(r.shape),f=ZA(p,r.shape,r.dtype,h,u,"avg");d=n.makeTensorInfo(u.outShape,r.dtype,f.values)}return d}var cH={kernelName:Ia,backendName:"cpu",kernelFunc:uH};function dH(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l,dataFormat:c}=s;Ne(r,"avgPool3d");let u=E.computePool3DInfo(r.shape,a,o,1,i,l,c),d=n.data.get(r.dataId).values,p=dI(d,r.shape,r.dtype,v.computeStrides(r.shape),u,"avg");return n.makeTensorInfo(p.shape,"float32",p.values)}var pH={kernelName:Hc,backendName:"cpu",kernelFunc:dH};function hH(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,{filterSize:o,strides:i,pad:l,dimRoundingMode:c}=s;Ne([r,a],"avgPool3DGrad");let u=E.computePool3DInfo(a.shape,o,i,1,l,c),d=u.strideDepth,p=u.strideHeight,h=u.strideWidth,f=u.filterDepth,m=u.filterHeight,g=u.filterWidth,y=u.dilationDepth,A=u.dilationHeight,x=u.dilationWidth,b=u.effectiveFilterDepth,w=u.effectiveFilterHeight,k=u.effectiveFilterWidth,S=b-1-u.padInfo.front,N=k-1-u.padInfo.left,$=w-1-u.padInfo.top,F=We(a.shape,"float32"),R=1/(f*m*g),D=n.bufferSync(r);for(let T=0;T<u.batchSize;++T)for(let O=0;O<u.inChannels;++O)for(let B=0;B<u.inDepth;++B)for(let H=0;H<u.inHeight;++H)for(let z=0;z<u.inWidth;++z){let X=B-S,ee=H-$,J=z-N,Q=0;for(let ne=0;ne<b;ne+=y){let K=(X+ne)/d;if(!(K<0||K>=u.outDepth||Math.floor(K)!==K))for(let oe=0;oe<w;oe+=A){let ce=(ee+oe)/p;if(!(ce<0||ce>=u.outHeight||Math.floor(ce)!==ce))for(let he=0;he<k;he+=x){let Ae=(J+he)/h;if(Ae<0||Ae>=u.outWidth||Math.floor(Ae)!==Ae)continue;Q+=D.get(T,K,ce,Ae,O)}}}F.set(Q*R,T,B,H,z,O)}return n.makeTensorInfo(F.shape,F.dtype,F.values)}var fH={kernelName:mh,backendName:"cpu",kernelFunc:hH};function mH(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,o=a;Ne([r,a],"avgPoolGrad");let{filterSize:i,strides:l,pad:c}=s,u=E.computePool2DInfo(o.shape,i,l,1,c),d=u.strideHeight,p=u.strideWidth,h=u.filterHeight,f=u.filterWidth,m=u.dilationHeight,g=u.dilationWidth,y=u.effectiveFilterHeight,A=u.effectiveFilterWidth,x=A-1-u.padInfo.left,b=y-1-u.padInfo.top,w=We(o.shape,"float32"),k=1/(h*f),S=n.data.get(r.dataId).values,N=We(r.shape,"float32",S);for(let $=0;$<u.batchSize;++$)for(let F=0;F<u.inChannels;++F)for(let R=0;R<u.inHeight;++R)for(let D=0;D<u.inWidth;++D){let T=R-b,O=D-x,B=0;for(let H=0;H<y;H+=m){let z=(T+H)/d;if(!(z<0||z>=u.outHeight||Math.floor(z)!==z))for(let X=0;X<A;X+=g){let ee=(O+X)/p;if(ee<0||ee>=u.outWidth||Math.floor(ee)!==ee)continue;B+=N.get($,z,ee,F)}}w.set(B*k,$,R,D,F)}return n.makeTensorInfo(w.shape,w.dtype,w.values)}var gH={kernelName:fh,backendName:"cpu",kernelFunc:mH};function yH(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,scale:a,offset:o,mean:i,variance:l}=t;v.assert(i.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),v.assert(o==null||i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),v.assert(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),Ne([r,i,l,a,o],"batchNorm");let{varianceEpsilon:c}=s;c==null&&(c=.001);let u=n.data.get(r.dataId).values,d=n.data.get(i.dataId).values,p=n.data.get(l.dataId).values,h=a?n.data.get(a.dataId).values:new Float32Array([1]),f=o?n.data.get(o.dataId).values:new Float32Array([0]),m=new Float32Array(u.length),g=f.length,y=h.length,A=p.length,x=d.length,b=0,w=0,k=0,S=0;for(let N=0;N<u.length;++N)m[N]=f[b++]+(u[N]-d[w++])*h[k++]/Math.sqrt(p[S++]+c),b>=g&&(b=0),w>=x&&(w=0),k>=y&&(k=0),S>=A&&(S=0);return n.makeTensorInfo(r.shape,r.dtype,m)}var AH={kernelName:za,backendName:"cpu",kernelFunc:yH};function xH(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:o}=s;Ne([r],"batchToSpaceND");let i=a.reduce((y,A)=>y*A),l=E.getReshaped(r.shape,a,i),c=E.getPermuted(l.length,a.length),u=E.getReshapedPermuted(r.shape,a,i),d=E.getSliceBeginCoords(o,a.length),p=E.getSliceSize(u,o,a.length),h=Et({inputs:{x:r},backend:n,attrs:{shape:l}}),f=zs({inputs:{x:h},backend:n,attrs:{perm:c}}),m=Et({inputs:{x:f},backend:n,attrs:{shape:u}}),g=ml({inputs:{x:m},backend:n,attrs:{begin:d,size:p}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}var bH={kernelName:si,backendName:"cpu",kernelFunc:xH};function vH(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:o}=s,i=n.data.get(r.dataId).values,l=n.data.get(a.dataId).values,c=VA(i,l,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,c)}var wH={kernelName:gh,backendName:"cpu",kernelFunc:vH};function kH(e){let{inputs:t,backend:n}=e,{s0:s,s1:r}=t,a=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,i=E.assertAndGetBroadcastShape(Array.from(a),Array.from(o));return n.makeTensorInfo([i.length],"int32",Int32Array.from(i))}var IH={kernelName:u2,backendName:"cpu",kernelFunc:kH},SH=xt(Xr,(e,t)=>{let n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e}),CH={kernelName:Xr,backendName:"cpu",kernelFunc:SH},TH=e=>{let{x:t}=e.inputs,n=e.backend,s=new Float32Array(v.sizeFromShape(t.shape)),r=n.data.get(t.dataId),a=r.complexTensorInfos.real,o=r.complexTensorInfos.imag,i=n.data.get(a.dataId).values,l=n.data.get(o.dataId).values;for(let c=0;c<i.length;c++){let u=i[c],d=l[c];s[c]=Math.hypot(u,d)}return n.makeOutput(s,t.shape,"float32")},NH={kernelName:qc,backendName:"cpu",kernelFunc:TH};function Ju(e){let{inputs:t,backend:n}=e,{input:s}=t,r=n.data.get(s.dataId).complexTensorInfos.imag,a=n.data.get(r.dataId).values;return n.makeTensorInfo(r.shape,r.dtype,a)}var EH={kernelName:Yc,backendName:"cpu",kernelFunc:Ju};function Qu(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s,a=v.parseAxisParam(r,t[0].shape)[0],o=E.computeOutShape(t.map(m=>m.shape),a);if(v.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(m=>v.sizeFromShape(m.shape)>0);if(i.length===1)return Or({inputs:{x:i[0]},backend:n});let l=i.map(m=>m.shape);if(E.assertParamsConsistent(l,a),i[0].dtype==="complex64"){let m=i.map(b=>fl({inputs:{input:b},backend:n})),g=i.map(b=>Ju({inputs:{input:b},backend:n})),y=Qu({inputs:m,backend:n,attrs:{axis:a}}),A=Qu({inputs:g,backend:n,attrs:{axis:a}}),x=Ss({inputs:{real:y,imag:A},backend:n});return m.forEach(b=>n.disposeIntermediateTensorInfo(b)),g.forEach(b=>n.disposeIntermediateTensorInfo(b)),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(A),x}let c=i.map(m=>{let g=v.sizeFromShape(m.shape.slice(a));return Et({inputs:{x:m},backend:n,attrs:{shape:[-1,g]}})}),u=c.map(m=>({vals:n.data.get(m.dataId).values,shape:m.shape}));o=E.computeOutShape(c.map(m=>m.shape),1);let d=c[0].shape[0]===1,p=UA(u,o,t[0].dtype,d),h=E.computeOutShape(i.map(m=>m.shape),a),f=n.makeTensorInfo(h,t[0].dtype,p);return c.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}var RH={kernelName:ri,backendName:"cpu",kernelFunc:Qu};function pI(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dataFormat:l,dilations:c,dimRoundingMode:u}=s;Ne([r,a],"conv2d");let d=E.convertConv2DDataFormat(l),p=E.computeConv2DInfo(r.shape,a.shape,o,c,i,u,!1,d),h=p.filterHeight,f=p.filterWidth,m=p.dilationHeight,g=p.dilationWidth,y=p.padInfo.left,A=p.padInfo.top,x=p.dataFormat==="channelsLast",b=new tn(p.outShape,r.dtype),w=v.computeStrides(r.shape),k=v.computeStrides(a.shape),S=w[0],N=x?w[1]:w[2],$=x?w[2]:1,F=x?1:w[1],R=b.strides[0],D=x?b.strides[1]:b.strides[2],T=x?b.strides[2]:1,O=x?1:b.strides[1],B=n.data.get(r.dataId).values,H=n.data.get(a.dataId).values,z=b.values;for(let X=0;X<p.batchSize;++X){let ee=X*S,J=X*R;for(let Q=0;Q<p.outHeight;++Q){let ne=J+Q*D,K=Q*p.strideHeight-A;for(let oe=0;oe<h;++oe){let ce=K+oe*m;if(ce<0||ce>=p.inHeight)continue;let he=oe*k[0],Ae=ee+ce*N;for(let Se=0;Se<p.outWidth;++Se){let Ce=ne+Se*T,Oe=Se*p.strideWidth-y;for(let Ue=0;Ue<f;++Ue){let ze=Oe+Ue*g;if(ze<0||ze>=p.inWidth)continue;let wt=he+Ue*k[1],mt=Ae+ze*$,gt=wt;for(let ht=0;ht<p.inChannels;++ht){let bt=B[mt+ht*F];for(let Ye=0;Ye<p.outChannels;++Ye)z[Ce+Ye*O]+=bt*H[gt+Ye];gt+=p.outChannels}}}}}}return n.makeTensorInfo(b.shape,b.dtype,z)}var $H={kernelName:Na,backendName:"cpu",kernelFunc:pI};function DH(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:o,pad:i,dataFormat:l,dimRoundingMode:c,filterShape:u}=s;Ne([r,a],"conv2dBackpropFilter");let d=E.convertConv2DDataFormat(l),p=E.computeConv2DInfo(r.shape,u,o,1,i,c,!1,d),{strideHeight:h,strideWidth:f,filterHeight:m,filterWidth:g}=p,y=p.dataFormat==="channelsLast",A=new tn(p.filterShape,"float32"),x=p.padInfo.left,b=p.padInfo.top,w=n.data.get(r.dataId).values,k=n.data.get(a.dataId).values,S=new tn(r.shape,r.dtype,w),N=new tn(a.shape,a.dtype,k);for(let $=0;$<m;++$){let F=Math.max(0,Math.ceil((b-$)/h)),R=Math.min(p.outHeight,(p.inHeight+b-$)/h);for(let D=0;D<g;++D){let T=Math.max(0,Math.ceil((x-D)/f)),O=Math.min(p.outWidth,(p.inWidth+x-D)/f);for(let B=0;B<p.inChannels;++B)for(let H=0;H<p.outChannels;++H){let z=0;for(let X=0;X<p.batchSize;++X)for(let ee=F;ee<R;++ee){let J=$+ee*h-b;for(let Q=T;Q<O;++Q){let ne=D+Q*f-x;y?z+=S.get(X,J,ne,B)*N.get(X,ee,Q,H):z+=S.get(X,B,J,ne)*N.get(X,H,ee,Q)}}A.set(z,$,D,B,H)}}}return n.makeTensorInfo(A.shape,A.dtype,A.values)}var _H={kernelName:yh,backendName:"cpu",kernelFunc:DH};function PH(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{inputShape:o,strides:i,pad:l,dataFormat:c,dimRoundingMode:u}=s;Ne([r,a],"conv2dBackpropInput");let d=v.computeStrides(a.shape),p=v.computeStrides(r.shape),h=E.convertConv2DDataFormat(c),f=E.computeConv2DInfo(o,a.shape,i,1,l,u,!1,h),m=new tn(f.inShape,"float32"),g=m.values,y=n.data.get(r.dataId).values,A=n.data.get(a.dataId).values,[x,b,w]=d,{batchSize:k,filterHeight:S,filterWidth:N,inChannels:$,inHeight:F,inWidth:R,outChannels:D,outHeight:T,outWidth:O,strideHeight:B,strideWidth:H}=f;h=f.dataFormat;let z=S-1-f.padInfo.top,X=N-1-f.padInfo.left,ee=h==="channelsLast",J=m.strides[0],Q=ee?m.strides[1]:m.strides[2],ne=ee?m.strides[2]:1,K=ee?1:m.strides[1],oe=p[0],ce=ee?p[1]:p[2],he=ee?p[2]:1,Ae=ee?1:p[1];for(let Se=0;Se<k;++Se)for(let Ce=0;Ce<$;++Ce)for(let Oe=0;Oe<F;++Oe){let Ue=Oe-z,ze=Math.max(0,Math.ceil(Ue/B)),wt=Math.min(T,(S+Ue)/B);for(let mt=0;mt<R;++mt){let gt=mt-X,ht=Math.max(0,Math.ceil(gt/H)),bt=Math.min(O,(N+gt)/H),Ye=0;for(let Mt=ze;Mt<wt;++Mt){let hs=Mt*B-Ue;for(let kn=ht;kn<bt;++kn){let Hs=kn*H-gt,Fn=oe*Se+ce*Mt+he*kn,Rs=x*(S-1-hs)+b*(N-1-Hs)+w*Ce;for(let $s=0;$s<D;++$s){let In=y[Fn+Ae*$s],Ds=A[Rs+$s];Ye+=In*Ds}}}let Yn=J*Se+Q*Oe+ne*mt+K*Ce;g[Yn]=Ye}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}var FH={kernelName:Ea,backendName:"cpu",kernelFunc:PH};function OH(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dilations:l}=s;Ne([r,a],"conv3d");let c=E.computeConv3DInfo(r.shape,a.shape,o,l,i),{filterDepth:u,filterHeight:d,filterWidth:p,dilationDepth:h,dilationHeight:f,dilationWidth:m,padInfo:g}=c,y=g.front,A=g.left,x=g.top,b=new tn(c.outShape,r.dtype),w=n.data.get(r.dataId).values,k=n.data.get(a.dataId).values,S=b.values,N=v.computeStrides(r.shape),$=v.computeStrides(a.shape);for(let F=0;F<c.batchSize;++F){let R=F*N[0],D=F*b.strides[0];for(let T=0;T<c.outDepth;++T){let O=D+T*b.strides[1],B=T*c.strideDepth-y;for(let H=0;H<u;++H){let z=B+H*h;if(z<0||z>=c.inDepth)continue;let X=H*$[0],ee=R+z*N[1];for(let J=0;J<c.outHeight;++J){let Q=O+J*b.strides[2],ne=J*c.strideHeight-x;for(let K=0;K<d;++K){let oe=ne+K*f;if(oe<0||oe>=c.inHeight)continue;let ce=X+K*$[1],he=ee+oe*N[2];for(let Ae=0;Ae<c.outWidth;++Ae){let Se=Q+Ae*c.outChannels,Ce=Ae*c.strideWidth-A;for(let Oe=0;Oe<p;++Oe){let Ue=Ce+Oe*m;if(Ue<0||Ue>=c.inWidth)continue;let ze=ce+Oe*$[2],wt=he+Ue*c.inChannels,mt=ze;for(let gt=0;gt<c.inChannels;++gt){let ht=w[wt+gt];for(let bt=0;bt<c.outChannels;++bt)S[Se+bt]+=ht*k[mt+bt];mt+=c.outChannels}}}}}}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}var MH={kernelName:Xc,backendName:"cpu",kernelFunc:OH};function zH(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:o,pad:i,filterShape:l}=s;Ne([r,a],"conv3dBackpropFilterV2");let c=v.computeStrides(r.shape),u=v.computeStrides(a.shape),d=E.computeConv3DInfo(r.shape,l,o,1,i),p=d.strideDepth,h=d.strideHeight,f=d.strideWidth,m=d.filterDepth,g=d.filterHeight,y=d.filterWidth,A=new tn(d.filterShape,"float32"),x=A.values,[b,w,k,S]=A.strides,N=n.data.get(a.dataId).values,[$,F,R,D]=u,T=n.data.get(r.dataId).values,[O,B,H,z]=c,X=d.padInfo.front,ee=d.padInfo.left,J=d.padInfo.top;for(let Q=0;Q<m;++Q){let ne=Math.max(0,Math.ceil((X-Q)/p)),K=Math.min(d.outDepth,(d.inDepth+X-Q)/p),oe=Q*b;for(let ce=0;ce<g;++ce){let he=Math.max(0,Math.ceil((J-ce)/h)),Ae=Math.min(d.outHeight,(d.inHeight+J-ce)/h),Se=ce*w+oe;for(let Ce=0;Ce<y;++Ce){let Oe=Math.max(0,Math.ceil((ee-Ce)/f)),Ue=Math.min(d.outWidth,(d.inWidth+ee-Ce)/f),ze=Ce*k+Se;for(let wt=0;wt<d.inChannels;++wt){let mt=wt*S+ze;for(let gt=0;gt<d.outChannels;++gt){let ht=0;for(let bt=0;bt<d.batchSize;++bt){let Ye=bt*O,Yn=bt*$;for(let Mt=ne;Mt<K;++Mt){let kn=(Q+Mt*p-X)*B+Ye,Hs=Mt*F+Yn;for(let Fn=he;Fn<Ae;++Fn){let $s=(ce+Fn*h-J)*H+kn,In=Fn*R+Hs;for(let Ds=Oe;Ds<Ue;++Ds){let fs=(Ce+Ds*f-ee)*z+$s,wr=Ds*D+In;ht+=T[fs+wt]*N[wr+gt]}}}}x[mt+gt]=ht}}}}}return n.makeTensorInfo(A.shape,A.dtype,A.values)}var LH={kernelName:Ah,backendName:"cpu",kernelFunc:zH};function BH(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{pad:o,strides:i,inputShape:l}=s;Ne([r],"conv3dBackpropInputV2");let c=v.computeStrides(r.shape),u=v.computeStrides(a.shape),d=E.computeConv3DInfo(l,a.shape,i,1,o),p=new tn(d.inShape,"float32"),h=p.values,[f,m,g,y]=p.strides,A=n.data.get(r.dataId).values,[x,b,w,k]=c,S=n.data.get(a.dataId).values,[N,$,F,R]=u,{batchSize:D,filterDepth:T,filterHeight:O,filterWidth:B,inChannels:H,inDepth:z,inHeight:X,inWidth:ee,outChannels:J,outDepth:Q,outHeight:ne,outWidth:K,strideDepth:oe,strideHeight:ce,strideWidth:he}=d,Ae=T-1-d.padInfo.front,Se=O-1-d.padInfo.top,Ce=B-1-d.padInfo.left;for(let Oe=0;Oe<D;++Oe)for(let Ue=0;Ue<H;++Ue)for(let ze=0;ze<z;++ze){let wt=ze-Ae,mt=Math.max(0,Math.ceil(wt/oe)),gt=Math.min(Q,(T+wt)/oe);for(let ht=0;ht<X;++ht){let bt=ht-Se,Ye=Math.max(0,Math.ceil(bt/ce)),Yn=Math.min(ne,(O+bt)/ce);for(let Mt=0;Mt<ee;++Mt){let hs=Mt-Ce,kn=Math.max(0,Math.ceil(hs/he)),Hs=Math.min(K,(B+hs)/he),Fn=0;for(let Rs=mt;Rs<gt;++Rs){let $s=Rs*oe-wt;for(let In=Ye;In<Yn;++In){let Ds=In*ce-bt;for(let _s=kn;_s<Hs;++_s){let fs=_s*he-hs,wr=x*Oe+b*Rs+w*In+k*_s,Wr=N*(T-1-$s)+$*(O-1-Ds)+F*(B-1-fs)+R*Ue;for(let ha=0;ha<J;++ha){let Dl=A[wr+ha],kr=S[Wr+ha];Fn+=Dl*kr}}}}h[f*Oe+m*ze+g*ht+y*Mt+Ue]=Fn}}}return n.makeTensorInfo(p.shape,p.dtype,p.values)}var WH={kernelName:xh,backendName:"cpu",kernelFunc:BH},VH=xt(Ra,e=>Math.cos(e)),UH={kernelName:Ra,backendName:"cpu",kernelFunc:VH},GH=xt($a,e=>Math.cosh(e)),HH={kernelName:$a,backendName:"cpu",kernelFunc:GH};function jH(e){let{inputs:t,backend:n,attrs:s}=e,{image:r,boxes:a,boxInd:o}=t,{cropSize:i,method:l,extrapolationValue:c}=s,[u,d,p,h]=r.shape,f=a.shape[0],[m,g]=i,y=We([f,m,g,h],"float32"),A=n.data.get(a.dataId).values,x=n.data.get(o.dataId).values,b=n.data.get(r.dataId).values,w=v.computeStrides(r.shape),k=v.computeStrides(y.shape);for(let S=0;S<f;S++){let N=S*4,$=A[N],F=A[N+1],R=A[N+2],D=A[N+3],T=x[S];if(T>=u)continue;let O=m>1?(R-$)*(d-1)/(m-1):0,B=g>1?(D-F)*(p-1)/(g-1):0;for(let H=0;H<m;H++){let z=m>1?$*(d-1)+H*O:.5*($+R)*(d-1);if(z<0||z>d-1){for(let X=0;X<g;X++)for(let ee=0;ee<h;ee++){let J=ee+X*k[2]+H*k[1]+S*k[0];y.values[J]=c}continue}if(l==="bilinear"){let X=Math.floor(z),ee=Math.ceil(z),J=z-X;for(let Q=0;Q<g;Q++){let ne=g>1?F*(p-1)+Q*B:.5*(F+D)*(p-1);if(ne<0||ne>p-1){for(let he=0;he<h;he++){let Ae=he+Q*k[2]+H*k[1]+S*k[0];y.values[Ae]=c}continue}let K=Math.floor(ne),oe=Math.ceil(ne),ce=ne-K;for(let he=0;he<h;he++){let Ae=he+K*w[2]+X*w[1]+T*w[0],Se=b[Ae];Ae=he+oe*w[2]+X*w[1]+T*w[0];let Ce=b[Ae];Ae=he+K*w[2]+ee*w[1]+T*w[0];let Oe=b[Ae];Ae=he+oe*w[2]+ee*w[1]+T*w[0];let Ue=b[Ae],ze=Se+(Ce-Se)*ce,wt=Oe+(Ue-Oe)*ce;Ae=he+Q*k[2]+H*k[1]+S*k[0],y.values[Ae]=ze+(wt-ze)*J}}}else for(let X=0;X<g;++X){let ee=g>1?F*(p-1)+X*B:.5*(F+D)*(p-1);if(ee<0||ee>p-1){for(let ne=0;ne<h;ne++){let K=ne+X*k[2]+H*k[1]+S*k[0];y.values[K]=c}continue}let J=Math.round(ee),Q=Math.round(z);for(let ne=0;ne<h;ne++){let K=ne+J*w[2]+Q*w[1]+T*w[0],oe=ne+X*k[2]+H*k[1]+S*k[0];y.values[oe]=b[K]}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}var qH={kernelName:oi,backendName:"cpu",kernelFunc:jH};function XH(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:o,reverse:i}=s;Ne(r,"cumsum");let l=E.getAxesPermutation([a],r.shape.length),c=r;l!=null&&(c=zs({inputs:{x:r},backend:n,attrs:{perm:l}}));let u=E.getInnerMostAxes(1,r.shape.length)[0];if(u!==c.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${c.shape.length-1} but got axis=${u}`);let d=Ln(c.dtype,"int32"),p=v.makeZerosTypedArray(v.sizeFromShape(c.shape),d),h=n.data.get(c.dataId).values,f=c.shape[c.shape.length-1],m=i?(y,A)=>y+f-A-1:(y,A)=>y+A;for(let y=0;y<h.length;y+=f)for(let A=0;A<f;A++){let x=m(y,A);if(A===0)p[x]=o?0:h[x];else{let b=m(y,A-1);p[x]=o?h[b]+p[b]:h[x]+p[b]}}let g=n.makeTensorInfo(c.shape,d,p);if(l!=null){let y=E.getUndoAxesPermutation(l),A=zs({inputs:{x:g},backend:n,attrs:{perm:y}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(c),A}return g}var KH={kernelName:ai,backendName:"cpu",kernelFunc:XH};function ZH(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:o,binaryOutput:i}=s;if(r.shape.length===1){let l=n.data.get(r.dataId).values,c=n.data.get(a.dataId).values,u=VA(l,c,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,u)}else if(r.shape.length===2){let l=n.bufferSync(r),c=n.bufferSync(a),u=w7(l,c,o,i);return n.makeTensorInfo(u.shape,a.dtype,u.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}var YH={kernelName:bh,backendName:"cpu",kernelFunc:ZH};function JH(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockSize:a,dataFormat:o}=s;v.assert(o==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${o}`),v.assert(a>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${a}`);let i=r.shape[0],l=r.shape[1],c=r.shape[2],u=r.shape[3],d=l*a,p=c*a,h=u/(a*a),f=n.data.get(r.dataId).values,m=new Float32Array(i*d*p*h),g=0;for(let y=0;y<i;++y)for(let A=0;A<d;++A){let x=Math.floor(A/a),b=A%a;for(let w=0;w<p;++w){let k=Math.floor(w/a),S=w%a,N=(b*a+S)*h;for(let $=0;$<h;++$){let R=$+N+u*(k+c*(x+l*y));m[g++]=f[R]}}}return n.makeTensorInfo([i,d,p,h],r.dtype,m)}var QH={kernelName:ii,backendName:"cpu",kernelFunc:JH};function hI(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dilations:l,dimRoundingMode:c}=s;Ne([r,a],"depthwiseConv2DNative");let u=v.computeStrides(r.shape),d=v.computeStrides(a.shape),p=l;p==null&&(p=[1,1]),v.assert(E.eitherStridesOrDilationsAreOne(o,p),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${p}'`);let h=E.computeConv2DInfo(r.shape,a.shape,o,p,i,c,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:y,padInfo:A}=h,x=A.left,b=A.top,w=h.outChannels/h.inChannels,k=new tn(h.outShape,r.dtype),S=n.data.get(r.dataId).values,N=n.data.get(a.dataId).values,$=k.values;for(let F=0;F<h.batchSize;++F){let R=F*u[0],D=F*k.strides[0];for(let T=0;T<h.outHeight;++T){let O=D+T*k.strides[1],B=T*h.strideHeight-b;for(let H=0;H<f;++H){let z=B+H*g;if(z<0||z>=h.inHeight)continue;let X=H*d[0],ee=R+z*u[1];for(let J=0;J<h.outWidth;++J){let Q=O+J*k.strides[2],ne=J*h.strideWidth-x;for(let K=0;K<m;++K){let oe=ne+K*y;if(oe<0||oe>=h.inWidth)continue;let ce=X+K*d[1],he=ee+oe*h.inChannels,Ae=Q,Se=ce;for(let Ce=0;Ce<h.inChannels;++Ce){let Oe=S[he+Ce];for(let Ue=0;Ue<w;++Ue)$[Ae+Ue]+=Oe*N[Se+Ue];Ae+=w,Se+=w}}}}}}return n.makeTensorInfo(k.shape,k.dtype,k.values)}var ej={kernelName:Da,backendName:"cpu",kernelFunc:hI};function tj(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:o,dilations:i,pad:l,dimRoundingMode:c,filterShape:u}=s;Ne([r,a],"depthwiseConv2dNativeBackpropFilter");let d=E.computeConv2DInfo(r.shape,u,o,i,l,c,!0),{strideHeight:p,strideWidth:h,filterHeight:f,filterWidth:m}=d,g=new tn(d.filterShape,"float32"),y=d.padInfo.left,A=d.padInfo.top,x=d.outChannels/d.inChannels,b=n.data.get(r.dataId).values,w=new tn(r.shape,r.dtype,b),k=n.data.get(a.dataId).values,S=new tn(a.shape,a.dtype,k);for(let N=0;N<f;++N){let $=Math.max(0,Math.ceil((A-N)/p)),F=Math.min(d.outHeight,(d.inHeight+A-N)/p);for(let R=0;R<m;++R){let D=Math.max(0,Math.ceil((y-R)/h)),T=Math.min(d.outWidth,(d.inWidth+y-R)/h);for(let O=0;O<d.outChannels;++O){let B=Math.trunc(O/x),H=O%x,z=0;for(let X=0;X<d.batchSize;++X)for(let ee=$;ee<F;++ee){let J=N+ee*p-A;for(let Q=D;Q<T;++Q){let ne=R+Q*h-y;z+=w.get(X,J,ne,B)*S.get(X,ee,Q,O)}}g.set(z,N,R,B,H)}}}return n.makeTensorInfo(g.shape,g.dtype,g.values)}var nj={kernelName:vh,backendName:"cpu",kernelFunc:tj};function sj(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{strides:o,dilations:i,pad:l,dimRoundingMode:c,inputShape:u}=s;Ne([r,a],"depthwiseConv2DNativeBackpropInput");let d=v.computeStrides(r.shape),p=v.computeStrides(a.shape),h=E.computeConv2DInfo(u,a.shape,o,i,l,c,!0),f=new tn(h.inShape,"float32"),m=f.values,[g,y,A]=f.strides,x=n.data.get(r.dataId).values,[b,w,k]=d,S=n.data.get(a.dataId).values,[N,$,F]=p,{batchSize:R,filterHeight:D,filterWidth:T,inChannels:O,inHeight:B,inWidth:H,outChannels:z,outHeight:X,outWidth:ee,strideHeight:J,strideWidth:Q}=h,ne=D-1-h.padInfo.top,K=T-1-h.padInfo.left,oe=z/O;for(let ce=0;ce<R;++ce)for(let he=0;he<O;++he)for(let Ae=0;Ae<B;++Ae){let Se=Ae-ne,Ce=Math.max(0,Math.ceil(Se/J)),Oe=Math.min(X,(D+Se)/J);for(let Ue=0;Ue<H;++Ue){let ze=Ue-K,wt=Math.max(0,Math.ceil(ze/Q)),mt=Math.min(ee,(T+ze)/Q),gt=0;for(let ht=Ce;ht<Oe;++ht){let bt=ht*J-Se;for(let Ye=wt;Ye<mt;++Ye){let Yn=Ye*Q-ze,Mt=b*ce+w*ht+k*Ye,hs=N*(D-1-bt)+$*(T-1-Yn)+F*he;for(let kn=0;kn<oe;++kn){let Hs=he*oe+kn,Fn=x[Mt+Hs],Rs=S[hs+kn];gt+=Fn*Rs}}}m[g*ce+y*Ae+A*Ue+he]=gt}}return n.makeTensorInfo(f.shape,f.dtype,f.values)}var rj={kernelName:wh,backendName:"cpu",kernelFunc:sj};function aj(e){let{inputs:t,backend:n}=e,{x:s}=t,r=v.sizeFromShape(s.shape),a=n.data.get(s.dataId).values,o=We([r,r],s.dtype),i=o.values;for(let c=0;c<a.length;c++)i[c*r+c]=a[c];let l=[...s.shape,...s.shape];return n.makeTensorInfo(l,o.dtype,o.values)}var oj={kernelName:kh,backendName:"cpu",kernelFunc:aj},ij={kernelName:Kc,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:s,filter:r}=e,{strides:a,pad:o,dilations:i}=n,l=t,c=l.data.get(s.dataId).values,u=s.shape.length,d=l.data.get(r.dataId).values,p=r.shape.length,{batchSize:h,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:A,padInfo:x,strideHeight:b,strideWidth:w,filterHeight:k,filterWidth:S,dilationHeight:N,dilationWidth:$,outShape:F}=E.computeDilation2DInfo(s.shape,r.shape,a,o,"NHWC",i),R=v.sizeFromShape(F),D=F.length,T=v.getArrayFromDType(s.dtype,R);for(let B=0;B<h;++B)for(let H=0;H<y;++H){let z=H*b-x.top;for(let X=0;X<A;++X){let ee=X*w-x.left;for(let J=0;J<g;++J){let Q=Number.MIN_SAFE_INTEGER;for(let K=0;K<k;++K){let oe=z+K*N;if(oe>=0&&oe<f)for(let ce=0;ce<S;++ce){let he=ee+ce*$;if(he>=0&&he<m){let Ae=v.locToIndex([B,oe,he,J],u,v.computeStrides(s.shape)),Se=v.locToIndex([K,ce,J],p,v.computeStrides(r.shape)),Ce=c[Ae]+d[Se];Ce>Q&&(Q=Ce)}}}let ne=v.locToIndex([B,H,X,J],D,v.computeStrides(F));T[ne]=Q}}}return{dataId:l.write(v.toTypedArray(T,s.dtype),F,s.dtype),shape:F,dtype:s.dtype}}},lj={kernelName:Sh,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:s,filter:r,dy:a}=e,{strides:o,pad:i,dilations:l}=n,c=t,u=v.toNestedArray(s.shape,c.data.get(s.dataId).values),d=v.toNestedArray(r.shape,c.data.get(r.dataId).values),{batchSize:p,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:A,strideHeight:x,strideWidth:b,filterHeight:w,filterWidth:k,dilationHeight:S,dilationWidth:N,outShape:$}=E.computeDilation2DInfo(s.shape,r.shape,o,i,"NHWC",l);v.assert(a.rank===$.length,()=>`Error in ${Sh}, dy must have the same rank as output ${$.length}, but got ${a.rank}`);let F=v.toNestedArray($,c.data.get(a.dataId).values),R=v.makeZerosNestedTypedArray(r.shape,r.dtype);for(let T=0;T<p;++T)for(let O=0;O<g;++O){let B=O*x-A.top;for(let H=0;H<y;++H){let z=H*b-A.left;for(let X=0;X<m;++X){let ee=Number.MIN_SAFE_INTEGER,J=0,Q=0;for(let ne=0;ne<w;++ne){let K=B+ne*S;if(K>=0&&K<h)for(let oe=0;oe<k;++oe){let ce=z+oe*N;if(ce>=0&&ce<f){let he=u[T][K][ce][X]+d[ne][oe][X];he>ee&&(ee=he,J=ne,Q=oe)}}}R[J][Q][X]+=F[T][O][H][X]}}}return{dataId:c.write(v.toTypedArray(R,s.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},uj={kernelName:Ih,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:s,filter:r,dy:a}=e,{strides:o,pad:i,dilations:l}=n,c=t,u=v.toNestedArray(s.shape,c.data.get(s.dataId).values),d=v.toNestedArray(r.shape,c.data.get(r.dataId).values),{batchSize:p,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:A,strideHeight:x,strideWidth:b,filterHeight:w,filterWidth:k,dilationHeight:S,dilationWidth:N,outShape:$}=E.computeDilation2DInfo(s.shape,r.shape,o,i,"NHWC",l);v.assert(a.rank===$.length,()=>`Error in ${Ih}, dy must have the same rank as output ${$.length}, but got ${a.rank}`);let F=v.toNestedArray($,c.data.get(a.dataId).values),R=v.makeZerosNestedTypedArray(s.shape,s.dtype);for(let T=0;T<p;++T)for(let O=0;O<g;++O){let B=O*x-A.top;for(let H=0;H<y;++H){let z=H*b-A.left;for(let X=0;X<m;++X){let ee=Number.MIN_SAFE_INTEGER,J=B<0?0:B,Q=z<0?0:z;for(let ne=0;ne<w;++ne){let K=B+ne*S;if(K>=0&&K<h)for(let oe=0;oe<k;++oe){let ce=z+oe*N;if(ce>=0&&ce<f){let he=u[T][K][ce][X]+d[ne][oe][X];he>ee&&(ee=he,J=K,Q=ce)}}}R[T][J][Q][X]+=F[T][O][H][X]}}}return{dataId:c.write(v.toTypedArray(R,s.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}};function ap(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;Ne(r,"sum");let i;r.dtype==="bool"?i=Po({inputs:{x:r},backend:n,attrs:{dtype:"int32"}}):i=Or({inputs:{x:r},backend:n});let l=i.shape.length,c=v.parseAxisParam(a,i.shape),u=E.getAxesPermutation(c,l),d=c,p=i;u!=null&&(p=zs({inputs:{x:i},backend:n,attrs:{perm:u}}),d=E.getInnerMostAxes(d.length,l)),E.assertAxesAreInnerMostDims("sum",d,p.shape.length);let[h,f]=E.computeOutAndReduceShapes(p.shape,d),m=E.upcastType(p.dtype,"int32"),g=Im(n,h,m),y=v.sizeFromShape(f),A=n.data.get(g.dataId).values,x=n.data.get(p.dataId).values;for(let b=0;b<A.length;++b){let w=b*y,k=0;for(let S=0;S<y;++S)k+=x[w+S];A[b]=k}if(o){let b=E.expandShapeToKeepDim(g.shape,c),w=g;g=Et({inputs:{x:g},backend:n,attrs:{shape:b}}),n.disposeIntermediateTensorInfo(w)}return n.disposeIntermediateTensorInfo(i),u!=null&&n.disposeIntermediateTensorInfo(p),g}var cj={kernelName:oo,backendName:"cpu",kernelFunc:ap};function dj(e){let{inputs:t,backend:n,attrs:s}=e,{equation:r}=s,a=t,{allDims:o,summedDims:i,idDims:l}=E.decodeEinsumEquation(r,a.length);E.checkEinsumDimSizes(o.length,l,a);let{path:c,steps:u}=E.getEinsumComputePath(i,l),d=u.length,p=null,h=o.length,f=[];for(let m=0;m<d;++m){for(let g of u[m]){let{permutationIndices:y,expandDims:A}=E.getEinsumPermutation(h,l[g]),x;E.isIdentityPermutation(y)?x=a[g]:(x=zs({inputs:{x:a[g]},backend:n,attrs:{perm:y}}),f.push(x));let b=x.shape.slice();for(let w=0;w<A.length;++w)b.splice(A[w],0,1);v.arraysEqual(x.shape,b)||(x=Et({inputs:{x},backend:n,attrs:{shape:b}}),f.push(x)),p===null?p=x:(p=Sm({inputs:{a:x,b:p},backend:n}),f.push(p))}m<d-1&&(c[m]>=0&&(p=ap({inputs:{x:p},backend:n,attrs:{axis:c[m]-(o.length-h),keepDims:!1}}),f.push(p)),h--)}for(let m of f)m!==p&&n.disposeIntermediateTensorInfo(m);return p}var pj={kernelName:Zc,backendName:"cpu",kernelFunc:dj};function hj(e){let{inputs:t,backend:n}=e,{dy:s,y:r}=t;Ne([s,r],"eluGrad");let a=new Float32Array(v.sizeFromShape(r.shape)),o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values;for(let l=0;l<o.length;++l){let c=o[l];c>=1?a[l]=i[l]:a[l]=i[l]*(c+1)}return n.makeTensorInfo(r.shape,"float32",a)}var fj={kernelName:Ch,backendName:"cpu",kernelFunc:hj},mj=E.ERF_P,gj=E.ERF_A1,yj=E.ERF_A2,Aj=E.ERF_A3,xj=E.ERF_A4,bj=E.ERF_A5,vj=xt(su,e=>{let t=Math.sign(e),n=Math.abs(e),s=1/(1+mj*n);return t*(1-((((bj*s+xj)*s+Aj)*s+yj)*s+gj)*s*Math.exp(-n*n))}),wj={kernelName:su,backendName:"cpu",kernelFunc:vj};function Tm(e){let{inputs:t,backend:n,attrs:s}=e,{input:r}=t,{dim:a}=s,o=r.shape.length,i=r.shape.slice(),l=a;return a<0&&(v.assert(-(o+1)<=a,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+a+1),i.splice(l,0,1),Et({inputs:{x:r},backend:n,attrs:{shape:i}})}var kj={kernelName:ui,backendName:"cpu",kernelFunc:Tm},Ij=Jt((e,t)=>e/t),YA=wn(_a,Ij),JA={kernelName:_a,backendName:"cpu",kernelFunc:YA};function fI(e,t,n){let s=e.shape,r=s[0],a=s[1],o=n.data.get(e.dataId),i=o.complexTensorInfos.real,l=o.complexTensorInfos.imag,c=[r,a],u=v.sizeFromShape(c),d=v.getTypedArrayFromDType("float32",u),p=v.getTypedArrayFromDType("float32",u);for(let g=0;g<r;g++){let y=ml({inputs:{x:i},backend:n,attrs:{begin:[g,0],size:[1,a]}}),A=ml({inputs:{x:l},backend:n,attrs:{begin:[g,0],size:[1,a]}}),x=Ss({inputs:{real:y,imag:A},backend:n}),{real:b,imag:w}=Sj(x,t,n),k=E.mergeRealAndImagArrays(b,w);for(let S=0;S<a;S++){let N=E.getComplexWithIndex(k,S);d[g*a+S]=N.real,p[g*a+S]=N.imag}n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(A),n.disposeIntermediateTensorInfo(x)}let h=n.makeTensorInfo(c,"float32",d),f=n.makeTensorInfo(c,"float32",p),m=Ss({inputs:{real:h,imag:f},backend:n});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),m}function Sj(e,t,n){let s=v.sizeFromShape(e.shape),r=n.data.get(e.dataId),a=n.data.get(r.complexTensorInfos.real.dataId).values,o=n.data.get(r.complexTensorInfos.imag.dataId).values;if(Cj(s)){let i=QA(a,o,s,t,n),l=[e.shape[0],e.shape[1]];if(t){let c=n.makeTensorInfo(l,"float32",i.real),u=n.makeTensorInfo(l,"float32",i.imag),d=n.makeTensorInfo([],"float32",v.createScalarValue(s,"float32")),p=Or({inputs:{x:d},backend:n}),h=JA.kernelFunc({inputs:{a:c,b:d},backend:n}),f=JA.kernelFunc({inputs:{a:u,b:p},backend:n}),m=n.data.get(h.dataId).values,g=n.data.get(f.dataId).values;return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),{real:m,imag:g}}return i}else{let i=E.mergeRealAndImagArrays(a,o),l=Tj(i,s,t);return E.splitRealAndImagArrays(l)}}function Cj(e){return(e&e-1)==0}function QA(e,t,n,s,r){if(n===1)return{real:e,imag:t};let a=E.mergeRealAndImagArrays(e,t),o=n/2,i=E.complexWithEvenIndex(a),l=i.real,c=i.imag,u=[l.length],d=r.makeTensorInfo(u,"float32",l),p=r.makeTensorInfo(u,"float32",c),h=Ss({inputs:{real:d,imag:p},backend:r}),f=E.complexWithOddIndex(a),m=f.real,g=f.imag,y=[m.length],A=r.makeTensorInfo(y,"float32",m),x=r.makeTensorInfo(y,"float32",g),b=Ss({inputs:{real:A,imag:x},backend:r}),w=QA(l,c,o,s,r),k=w.real,S=w.imag,N=[k.length],$=r.makeTensorInfo(N,"float32",k),F=r.makeTensorInfo(N,"float32",S),R=Ss({inputs:{real:$,imag:F},backend:r}),D=QA(m,g,o,s,r),T=D.real,O=D.imag,B=[T.length],H=r.makeTensorInfo(B,"float32",T),z=r.makeTensorInfo(B,"float32",O),X=Ss({inputs:{real:H,imag:z},backend:r}),ee=E.exponents(n,s),J=[ee.real.length],Q=r.makeTensorInfo(J,"float32",ee.real),ne=r.makeTensorInfo(J,"float32",ee.imag),K=Ss({inputs:{real:Q,imag:ne},backend:r}),oe=Sm({inputs:{a:K,b:X},backend:r}),ce=sp({inputs:{a:R,b:oe},backend:r}),he=XA({inputs:{a:R,b:oe},backend:r}),Ae=fl({inputs:{input:ce},backend:r}),Se=fl({inputs:{input:he},backend:r}),Ce=Ju({inputs:{input:ce},backend:r}),Oe=Ju({inputs:{input:he},backend:r}),Ue=Qu({inputs:[Ae,Se],backend:r,attrs:{axis:0}}),ze=Qu({inputs:[Ce,Oe],backend:r,attrs:{axis:0}}),wt=r.data.get(Ue.dataId).values,mt=r.data.get(ze.dataId).values;return r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(A),r.disposeIntermediateTensorInfo(x),r.disposeIntermediateTensorInfo(b),r.disposeIntermediateTensorInfo($),r.disposeIntermediateTensorInfo(F),r.disposeIntermediateTensorInfo(R),r.disposeIntermediateTensorInfo(H),r.disposeIntermediateTensorInfo(z),r.disposeIntermediateTensorInfo(X),r.disposeIntermediateTensorInfo(Q),r.disposeIntermediateTensorInfo(ne),r.disposeIntermediateTensorInfo(K),r.disposeIntermediateTensorInfo(oe),r.disposeIntermediateTensorInfo(ce),r.disposeIntermediateTensorInfo(he),r.disposeIntermediateTensorInfo(Ae),r.disposeIntermediateTensorInfo(Ce),r.disposeIntermediateTensorInfo(Se),r.disposeIntermediateTensorInfo(Oe),r.disposeIntermediateTensorInfo(Ue),r.disposeIntermediateTensorInfo(ze),{real:wt,imag:mt}}function Tj(e,t,n){let s=new Float32Array(t*2);for(let r=0;r<t;r++){let a=0,o=0;for(let i=0;i<t;i++){let l=E.exponent(r*i,t,n),c=E.getComplexWithIndex(e,i);a+=c.real*l.real-c.imag*l.imag,o+=c.real*l.imag+c.imag*l.real}n&&(a/=t,o/=t),E.assignToTypedArray(s,a,o,r)}return s}function Nj(e){let{inputs:t,backend:n}=e,{input:s}=t,r=v.sizeFromShape(s.shape),a=s.shape[s.shape.length-1],o=r/a,i=Et({inputs:{x:s},backend:n,attrs:{shape:[o,a]}}),l=fI(i,!1,n),c=Et({inputs:{x:l},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),c}var Ej={kernelName:Th,backendName:"cpu",kernelFunc:Nj};function ex(e){let{backend:t,attrs:n}=e,{shape:s,value:r,dtype:a}=n,o=a||v.inferDtype(r),i=v.getArrayFromDType(o,v.sizeFromShape(s));return $j(i,r,o),t.makeTensorInfo(s,o,i)}var Rj={kernelName:ru,backendName:"cpu",kernelFunc:ex};function $j(e,t,n){e.fill(t)}var Dj={kernelName:di,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:s}=e,r=n,a=v.getTypedArrayFromDType(s.dtype,v.sizeFromShape(s.shape)),[o,i,l,c]=s.shape,u=r.data.get(s.dataId).values;for(let p=0;p<o;p++){let h=p*l*i*c;for(let f=0;f<i;f++){let m=f*(l*c);for(let g=0;g<l;g++){let y=g*c;for(let A=0;A<c;A++){let x=Math.round(l-g-1),b=h+m+y+A,w=u[b];if(x>=0&&x<l){let k=x*c,S=h+m+k+A;w=u[S]}a[b]=w}}}}return{dataId:r.write(a,s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}},_j=Jt((e,t)=>Math.floor(e/t)),Pj=wn(Ma,_j,null,"int32"),Fj={kernelName:Ma,backendName:"cpu",kernelFunc:Pj};function Oj(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=s,m=pI({inputs:{x:r,filter:a},backend:n,attrs:{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p}});if(o){let g=m;m=sp({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=m;m=KA(n,m,h,i,f),n.disposeIntermediateTensorInfo(g)}return m}var Mj={kernelName:mo,backendName:"cpu",kernelFunc:Oj};function zj(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=s,m=hI({inputs:{x:r,filter:a},backend:n,attrs:{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p}});if(o){let g=m;m=sp({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=m;m=KA(n,m,h,i,f),n.disposeIntermediateTensorInfo(g)}return m}var Lj={kernelName:go,backendName:"cpu",kernelFunc:zj};function Bj(e){let{inputs:t,backend:n}=e,{params:s,indices:r}=t,a=v.sizeFromShape(s.shape),o=r.shape,i=o[o.length-1],[l,c,u,d]=E.prepareAndValidate(s,r);if(c===0)return n.makeTensorInfo(l,s.dtype,[]);let p=n.data.get(r.dataId).values,h=n.bufferSync(s),f=R7(p,h,s.dtype,c,i,u,d,s.shape,a);return n.makeTensorInfo(l,s.dtype,f.values)}var Wj={kernelName:hi,backendName:"cpu",kernelFunc:Bj};function Vj(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,indices:a}=t,{axis:o,batchDims:i}=s;Ne([r,a],"gatherV2");let l=i;i==null&&(l=0);let c=v.sizeFromShape(a.shape),u=v.parseAxisParam(o,r.shape)[0],d=E.segment_util.collectGatherOpShapeInfo(r,a,u,l),p=Et({inputs:{x:r},backend:n,attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]}}),h=Et({inputs:{x:a},backend:n,attrs:{shape:[d.batchSize,c/d.batchSize]}}),f=[d.batchSize,d.outerSize,c/d.batchSize,d.sliceSize],m=n.bufferSync(h),g=n.bufferSync(p),y=$7(g,m,f);return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.makeTensorInfo(d.outputShape,y.dtype,y.values)}var Uj={kernelName:pi,backendName:"cpu",kernelFunc:Vj};function Gj(e){let{inputs:t,backend:n}=e,{input:s}=t,r=v.sizeFromShape(s.shape),a=s.shape[s.shape.length-1],o=r/a,i=Et({inputs:{x:s},backend:n,attrs:{shape:[o,a]}}),l=fI(i,!0,n),c=Et({inputs:{x:l},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),c}var Hj={kernelName:Nh,backendName:"cpu",kernelFunc:Gj},jj=xt(au,e=>Number.isFinite(e)?1:0,"bool"),qj={kernelName:au,backendName:"cpu",kernelFunc:jj},Xj=xt(ou,e=>Math.abs(e)===1/0?1:0,"bool"),Kj={kernelName:ou,backendName:"cpu",kernelFunc:Xj},Zj=xt(iu,e=>Number.isNaN(e)?1:0,"bool"),Yj={kernelName:iu,backendName:"cpu",kernelFunc:Zj};function Jj(e){let{backend:t,attrs:n}=e,{start:s,stop:r,num:a}=n,o=O7(s,r,a);return t.makeTensorInfo([o.length],"float32",o)}var Qj={kernelName:Eh,backendName:"cpu",kernelFunc:Jj},eq=xt(lu,e=>Math.log1p(e)),tq={kernelName:lu,backendName:"cpu",kernelFunc:eq},nq=Jt((e,t)=>e&&t),sq=wn(Ai,nq,null,"bool"),rq={kernelName:Ai,backendName:"cpu",kernelFunc:sq},aq=xt(uu,e=>e?0:1,"bool"),oq={kernelName:uu,backendName:"cpu",kernelFunc:aq},iq=Jt((e,t)=>e||t),lq=wn(Jc,iq,null,"bool"),uq={kernelName:Jc,backendName:"cpu",kernelFunc:lq};function cq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{depthRadius:a,bias:o,alpha:i,beta:l}=s;Ne(r,"LRN");let c=r.shape[3],u=c-1,d=n.data.get(r.dataId).values,p=v.sizeFromShape(r.shape),h=new Float32Array(p);function f(m){let g=m%c,y=m-g+Math.max(0,g-a),A=m-g+Math.min(g+a,u),x=0;for(;y<=A;y++){let b=d[y];x+=b*b}return x}for(let m=0;m<p;m++){let g=f(m),y=d[m]*Math.pow(o+i*g,-l);h[m]=y}return n.makeTensorInfo(r.shape,r.dtype,h)}var dq={kernelName:Qc,backendName:"cpu",kernelFunc:cq};function pq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,y:a,dy:o}=t,{depthRadius:i,bias:l,alpha:c,beta:u}=s;Ne(o,"LRNGrad");let d=v.sizeFromShape(o.shape),p=o.shape[3],h=n.data.get(o.dataId).values,f=n.data.get(r.dataId).values,m=n.data.get(a.dataId).values,g=new Float32Array(d),y=d;for(let A=0;A<y;A++){let x=A%p,b=A-x+Math.max(0,x-i),w=A-x+Math.min(p,x+i+1),k=0;for(let S=b;S<w;S++)k+=Math.pow(f[S],2);k=c*k+l;for(let S=b;S<w;S++){let N=-2*c*u*f[S]*m[A]/k;A===S&&(N+=Math.pow(k,-u)),N*=h[A],g[S]+=N}}return n.makeTensorInfo(o.shape,r.dtype,g)}var hq={kernelName:Rh,backendName:"cpu",kernelFunc:pq};function mI(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reductionIndices:a,keepDims:o}=s,i=n,l=r.shape,c=l.length,u=v.parseAxisParam(a,l),d=u,p=E.getAxesPermutation(d,c),h=i.data.get(r.dataId).values;if(p!=null){let b=new Array(c);for(let w=0;w<b.length;w++)b[w]=l[p[w]];h=HA(h,l,r.dtype,p,b),d=E.getInnerMostAxes(d.length,c),l=b}Ne(r,"max"),E.assertAxesAreInnerMostDims("max",d,c);let[f,m]=E.computeOutAndReduceShapes(l,d),g=v.sizeFromShape(m),y=z7(h,g,f,r.dtype),A=i.write(y,f,r.dtype),x=f;return o&&(x=E.expandShapeToKeepDim(f,u)),{dataId:A,shape:x,dtype:r.dtype}}var fq={kernelName:Va,backendName:"cpu",kernelFunc:mI};function mq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t;Ne(r,"maxPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,c=1;v.assert(E.eitherStridesOrDilationsAreOne(o,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);let u=E.computePool2DInfo(r.shape,a,o,c,i,l),d;if(u.filterWidth===1&&u.filterHeight===1&&v.arraysEqual(u.inShape,u.outShape))d=Or({inputs:{x:r},backend:n});else{let p=n.data.get(r.dataId).values,h=v.computeStrides(r.shape),f=ZA(p,r.shape,r.dtype,h,u,"max");d=n.makeTensorInfo(u.outShape,r.dtype,f.values)}return d}var gq={kernelName:Ga,backendName:"cpu",kernelFunc:mq};function yq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l,dataFormat:c}=s;Ne(r,"maxPool3d");let u=E.computePool3DInfo(r.shape,a,o,1,i,l,c),d=n.data.get(r.dataId).values,p=dI(d,r.shape,r.dtype,v.computeStrides(r.shape),u,"max");return n.makeTensorInfo(p.shape,"float32",p.values)}var Aq={kernelName:ed,backendName:"cpu",kernelFunc:yq};function xq(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,{filterSize:o,strides:i,pad:l,dimRoundingMode:c}=s;Ne([r,a],"maxPool3DGrad");let u=E.computePool3DInfo(a.shape,o,i,1,l,c),d=n.bufferSync(a),p=lH(d,u),h=u.strideDepth,f=u.strideHeight,m=u.strideWidth,g=u.dilationDepth,y=u.dilationHeight,A=u.dilationWidth,x=u.effectiveFilterDepth,b=u.effectiveFilterHeight,w=u.effectiveFilterWidth,k=x-1-u.padInfo.front,S=w-1-u.padInfo.left,N=b-1-u.padInfo.top,$=We(a.shape,"float32"),F=n.bufferSync(r);for(let R=0;R<u.batchSize;++R)for(let D=0;D<u.inChannels;++D)for(let T=0;T<u.inDepth;++T)for(let O=0;O<u.inHeight;++O)for(let B=0;B<u.inWidth;++B){let H=T-k,z=O-N,X=B-S,ee=0;for(let J=0;J<x;J+=g){let Q=(H+J)/h;if(!(Q<0||Q>=u.outDepth||Math.floor(Q)!==Q))for(let ne=0;ne<b;ne+=y){let K=(z+ne)/f;if(!(K<0||K>=u.outHeight||Math.floor(K)!==K))for(let oe=0;oe<w;oe+=A){let ce=(X+oe)/m;if(ce<0||ce>=u.outWidth||Math.floor(ce)!==ce)continue;let he=x*b*w-1-p.get(R,Q,K,ce,D),Ae=J*b*w+ne*w+oe,Se=he===Ae?1:0;if(Se===0)continue;ee+=F.get(R,Q,K,ce,D)*Se}}}$.set(ee,R,T,O,B,D)}return n.makeTensorInfo($.shape,$.dtype,$.values)}var bq={kernelName:Dh,backendName:"cpu",kernelFunc:xq};function vq(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a,output:o}=t,i=a;Ne([a,o],"maxPoolGrad");let{filterSize:l,strides:c,pad:u,dimRoundingMode:d}=s,p=E.computePool2DInfo(i.shape,l,c,1,u,d),h=n.data.get(i.dataId).values,f=We(p.outShape,i.dtype,cI(h,i.shape,i.dtype,p).values),m=p.strideHeight,g=p.strideWidth,y=p.dilationHeight,A=p.dilationWidth,x=p.effectiveFilterHeight,b=p.effectiveFilterWidth,w=b-1-p.padInfo.left,k=x-1-p.padInfo.top,S=We(i.shape,"float32"),N=n.data.get(r.dataId).values,$=We(r.shape,"float32",N);for(let F=0;F<p.batchSize;++F)for(let R=0;R<p.inChannels;++R)for(let D=0;D<p.inHeight;++D)for(let T=0;T<p.inWidth;++T){let O=D-k,B=T-w,H=0;for(let z=0;z<x;z+=y){let X=(O+z)/m;if(!(X<0||X>=p.outHeight||Math.floor(X)!==X))for(let ee=0;ee<b;ee+=A){let J=(B+ee)/g;if(J<0||J>=p.outWidth||Math.floor(J)!==J)continue;let Q=x*b-1-f.get(F,X,J,R),ne=z*b+ee,K=Q===ne?1:0;if(K===0)continue;H+=$.get(F,X,J,R)*K}}S.set(H,F,D,T,R)}return n.makeTensorInfo(S.shape,S.dtype,S.values)}var wq={kernelName:$h,backendName:"cpu",kernelFunc:vq};function kq(e,t,n,s,r){let a=v.computeStrides(t),o=ZA(e,t,n,a,r,"max"),i=cI(e,t,n,r,!0,s);return[o.values,i.values]}var Iq={kernelName:_h,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:s}=e,{filterSize:r,strides:a,pad:o,includeBatchInIndex:i}=t,l=n;Ne(s,"MaxPoolWithArgmax");let c=l.data.get(s.dataId).values,u=E.computePool2DInfo(s.shape,r,a,[1,1],o),[d,p]=kq(c,s.shape,s.dtype,i,u),h=l.write(d,u.outShape,s.dtype),f=l.write(p,u.outShape,s.dtype);return[{dataId:h,shape:u.outShape,dtype:s.dtype},{dataId:f,shape:u.outShape,dtype:"int32"}]}};function Sq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s,i=v.parseAxisParam(a,r.shape),c=E.computeOutAndReduceShapes(r.shape,i)[1],u=v.sizeFromShape(c),d=[],p=n.makeTensorInfo([],"float32",new Float32Array([u]));d.push(p);let h=Po({inputs:{x:r},backend:n,attrs:{dtype:"float32"}});d.push(h);let f=YA({inputs:{a:h,b:p},backend:n});d.push(f);let m=ap({inputs:{x:f},backend:n,attrs:{axis:a,keepDims:o}});return d.forEach(g=>n.disposeIntermediateTensorInfo(g)),m}var Cq={kernelName:Ha,backendName:"cpu",kernelFunc:Sq};function Tq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;Ne(r,"min");let i=v.parseAxisParam(a,r.shape),l=i,c=E.getAxesPermutation(l,r.shape.length),u=r;c!=null&&(u=zs({inputs:{x:r},backend:n,attrs:{perm:c}}),l=E.getInnerMostAxes(l.length,r.shape.length)),E.assertAxesAreInnerMostDims("min",l,u.shape.length);let[d,p]=E.computeOutAndReduceShapes(u.shape,l),h=v.sizeFromShape(p),f=v.makeZerosTypedArray(v.sizeFromShape(d),u.dtype),m=n.data.get(u.dataId).values;for(let y=0;y<f.length;++y){let A=y*h,x=m[A];for(let b=0;b<h;++b){let w=m[A+b];(Number.isNaN(w)||w<x)&&(x=w)}f[y]=x}c!=null&&n.disposeIntermediateTensorInfo(u);let g=n.makeTensorInfo(d,u.dtype,f);if(o){let y=E.expandShapeToKeepDim(d,i),A=Et({inputs:{x:g},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(g),A}return g}var Nq={kernelName:ja,backendName:"cpu",kernelFunc:Tq};function Eq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,mode:o}=s;Ne(r,"mirrorPad");let i=a.map((x,b)=>x[0]+r.shape[b]+x[1]),l=a.map(x=>x[0]),c=a.map((x,b)=>x[0]+r.shape[b]),u=o==="reflect"?0:1,d=n.data.get(r.dataId).values,p=r.shape.length,h=v.computeStrides(r.shape),f=v.sizeFromShape(i),m=i.length,g=v.computeStrides(i),y=v.getTypedArrayFromDType(r.dtype,f);for(let x=0;x<f;x++){let b=v.indexToLoc(x,m,g);for(let k=0;k<m;k++)b[k]<l[k]?b[k]=l[k]*2-b[k]-u:b[k]>=c[k]&&(b[k]=(c[k]-1)*2-b[k]+u);b=b.map((k,S)=>k-l[S]);let w=v.locToIndex(b,p,h);y[x]=d[w]}return{dataId:n.write(y,i,r.dtype),shape:i,dtype:r.dtype}}var Rq={kernelName:Xa,backendName:"cpu",kernelFunc:Eq},$q=Jt((e,t)=>{let n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}),Dq=wn(cu,$q),_q={kernelName:cu,backendName:"cpu",kernelFunc:Dq},Pq=Qo(h5());function gI(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{dim:a}=s,o=r.shape.length,i=a;if(i===-1&&(i=o-1),i!==o-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${o} and dim was ${i}`);let l=v.parseAxisParam([i],r.shape),c=mI({inputs:{x:r},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),u=E.expandShapeToKeepDim(c.shape,l),d=Et({inputs:{x:c},backend:n,attrs:{shape:u}}),p=XA({inputs:{a:r,b:d},backend:n}),h=T7({inputs:{x:p},backend:n}),f=ap({inputs:{x:h},backend:n,attrs:{axis:l,keepDims:!1}}),m=Et({inputs:{x:f},backend:n,attrs:{shape:u}}),g=YA({inputs:{a:h,b:m},backend:n});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}var Fq={kernelName:io,backendName:"cpu",kernelFunc:gI};function Oq(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{numSamples:a,seed:o,normalized:i}=s;Ne(r,"multinomial");let l=i?r:gI({inputs:{logits:r},backend:n,attrs:{dim:-1}}),c=l.shape[0],u=l.shape[1],d=n.data.get(l.dataId).values,p=[c,a],h=v.makeZerosTypedArray(v.sizeFromShape(p),"int32");for(let f=0;f<c;++f){let m=f*u,g=new Float32Array(u-1);g[0]=d[m];for(let x=1;x<g.length;++x)g[x]=g[x-1]+d[m+x];let y=Pq.alea(o.toString()),A=f*a;for(let x=0;x<a;++x){let b=y();h[A+x]=g.length;for(let w=0;w<g.length;w++)if(b<g[w]){h[A+x]=w;break}}}return i||n.disposeIntermediateTensorInfo(l),n.makeTensorInfo(p,"int32",h)}var Mq={kernelName:Ph,backendName:"cpu",kernelFunc:Oq},zq=Zs.nonMaxSuppressionV3Impl;function Lq(e){let{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l}=s;Ne(r,"NonMaxSuppression");let c=n.data.get(r.dataId).values,u=n.data.get(a.dataId).values,{selectedIndices:d}=zq(c,u,o,i,l);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}var Bq={kernelName:vi,backendName:"cpu",kernelFunc:Lq},Wq=Zs.nonMaxSuppressionV4Impl;function Vq(e){let{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l,padToMaxOutputSize:c}=s;Ne(r,"NonMaxSuppressionPadded");let u=n.data.get(r.dataId).values,d=n.data.get(a.dataId).values,{selectedIndices:p,validOutputs:h}=Wq(u,d,o,i,l,c);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var Uq={kernelName:du,backendName:"cpu",kernelFunc:Vq},Gq=Zs.nonMaxSuppressionV5Impl;function Hq(e){let{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l,softNmsSigma:c}=s;Ne(r,"NonMaxSuppressionWithScore");let u=n.data.get(r.dataId).values,d=n.data.get(a.dataId).values,p=o,h=i,f=l,m=c,{selectedIndices:g,selectedScores:y}=Gq(u,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var jq={kernelName:wi,backendName:"cpu",kernelFunc:Hq};function qq(e){let{inputs:t,backend:n,attrs:s}=e,{indices:r}=t,{depth:a,onValue:o,offValue:i}=s;Ne(r,"oneHot");let l=v.sizeFromShape(r.shape),c=new Float32Array(l*a);c.fill(i);let u=n.data.get(r.dataId).values;for(let d=0;d<l;++d)u[d]>=0&&u[d]<a&&(c[d*a+u[d]]=o);return n.makeTensorInfo([...r.shape,a],"int32",c)}var Xq={kernelName:Ii,backendName:"cpu",kernelFunc:qq};function Nm(e){let{inputs:t,backend:n}=e,{x:s}=t;if(s.dtype==="string")throw new Error("zerosLike is not supported for string tensors");if(s.dtype==="complex64"){let r=fl({inputs:{input:s},backend:n}),a=Nm({inputs:{x:r},backend:n}),o=Ju({inputs:{input:s},backend:n}),i=Nm({inputs:{x:o},backend:n}),l=Ss({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),l}else return ex({backend:n,attrs:{shape:s.shape,value:0,dtype:s.dtype}})}var Kq={kernelName:Bi,backendName:"cpu",kernelFunc:Nm};function yI(e){let{inputs:t,backend:n}=e,{x:s}=t;if(s.dtype==="string")throw new Error("onesLike is not supported for string tensors");if(s.dtype==="complex64"){let r=fl({inputs:{input:s},backend:n}),a=yI({inputs:{x:r},backend:n}),o=Ju({inputs:{input:s},backend:n}),i=Nm({inputs:{x:o},backend:n}),l=Ss({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),l}else return ex({backend:n,attrs:{shape:s.shape,value:1,dtype:s.dtype}})}var Zq={kernelName:ki,backendName:"cpu",kernelFunc:yI};function AI(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(t.length===1)return Tm({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let a=t[0].shape,o=t[0].dtype;t.forEach(u=>{v.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),v.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(u=>{let d=Tm({inputs:{input:u},backend:n,attrs:{dim:r}});return i.push(d),d}),c=Qu({inputs:l,backend:n,attrs:{axis:r}});return i.forEach(u=>n.disposeIntermediateTensorInfo(u)),c}var Yq={kernelName:Si,backendName:"cpu",kernelFunc:AI};function Jq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,constantValue:o}=s;Ne(r,"pad");let i=a.map((A,x)=>A[0]+r.shape[x]+A[1]),l=a.map(A=>A[0]),c=n.data.get(r.dataId).values,u=v.sizeFromShape(r.shape),d=r.shape.length,p=v.computeStrides(r.shape),h=v.sizeFromShape(i),f=i.length,m=v.computeStrides(i),g=v.getTypedArrayFromDType(r.dtype,h);o!==0&&g.fill(o);for(let A=0;A<u;A++){let b=v.indexToLoc(A,d,p).map((k,S)=>k+l[S]),w=v.locToIndex(b,f,m);g[w]=c[A]}return{dataId:n.write(g,i,r.dtype),shape:i,dtype:r.dtype}}var xI={kernelName:Za,backendName:"cpu",kernelFunc:Jq},Qq=Jt((e,t)=>Math.pow(e,t)),eX=wn(Ya,Qq),tX={kernelName:Ya,backendName:"cpu",kernelFunc:eX};function nX(e){let{backend:t,attrs:n}=e,{start:s,stop:r,dtype:a,step:o}=n,i=jA(s,r,o,a);return t.makeTensorInfo([i.length],a,i)}var sX={kernelName:pu,backendName:"cpu",kernelFunc:nX},rX=xt(hu,e=>1/e),aX={kernelName:hu,backendName:"cpu",kernelFunc:rX};function oX(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:o,size:i}=s;Ne(r,"resizeBilinear");let l=v.computeStrides(r.shape),[c,u]=i,[d,p,h,f]=r.shape,m=n.data.get(r.dataId).values,g=new Float32Array(v.sizeFromShape([d,c,u,f])),y=[a&&c>1?p-1:p,a&&u>1?h-1:h],A=[a&&c>1?c-1:c,a&&u>1?u-1:u],x=0,b=y[0]/A[0],w=y[1]/A[1];for(let k=0;k<d;k++)for(let S=0;S<c;S++){let N;o?N=b*(S+.5)-.5:N=b*S;let $=Math.max(0,Math.floor(N)),F=N-$,R=Math.min(p-1,Math.ceil(N)),D=k*l[0]+$*l[1],T=k*l[0]+R*l[1];for(let O=0;O<u;O++){let B;o?B=w*(O+.5)-.5:B=w*O;let H=Math.max(0,Math.floor(B)),z=B-H,X=Math.min(h-1,Math.ceil(B)),ee=D+H*l[2],J=T+H*l[2],Q=D+X*l[2],ne=T+X*l[2];for(let K=0;K<f;K++){let oe=m[ee+K],ce=m[J+K],he=m[Q+K],Ae=m[ne+K],Se=oe+(he-oe)*z,Ce=ce+(Ae-ce)*z,Oe=Se+(Ce-Se)*F;g[x++]=Oe}}}return n.makeTensorInfo([d,c,u,f],"float32",g)}var iX={kernelName:eo,backendName:"cpu",kernelFunc:oX};function lX(e){let{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:o}=s;Ne([a,r],"resizeBilinearGrad");let i=v.computeStrides(r.shape),[l,c,u,d]=r.shape,[,p,h]=a.shape,f=new Float32Array(l*c*u*d),m=[o&&p>1?c-1:c,o&&h>1?u-1:u],g=[o&&p>1?p-1:p,o&&h>1?h-1:h],y=m[0]/g[0],A=m[1]/g[1],x=n.data.get(a.dataId).values,b=0;for(let w=0;w<l;w++){let k=w*i[0];for(let S=0;S<p;S++){let N=S*y,$=Math.floor(N),F=Math.min(Math.ceil(N),c-1),R=k+$*i[1],D=k+F*i[1],T=N-$,O=1-T;for(let B=0;B<h;B++){let H=B*A,z=Math.floor(H),X=Math.min(Math.ceil(H),u-1),ee=H-z,J=1-ee,Q=R+z*i[2],ne=R+X*i[2],K=D+z*i[2],oe=D+X*i[2],ce=O*J,he=O*ee,Ae=T*J,Se=T*ee;for(let Ce=0;Ce<d;Ce++){let Oe=x[b++];f[Q+Ce]+=Oe*ce,f[ne+Ce]+=Oe*he,f[K+Ce]+=Oe*Ae,f[oe+Ce]+=Oe*Se}}}}return n.makeTensorInfo([l,u,c,d],"float32",f)}var uX={kernelName:Oh,backendName:"cpu",kernelFunc:lX};function cX(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:o,size:i}=s;Ne(r,"resizeNearestNeighbor");let l=v.computeStrides(r.shape),[c,u]=i,[d,p,h,f]=r.shape,m=n.data.get(r.dataId).values,g=new Float32Array(d*c*u*f),y=[a&&c>1?p-1:p,a&&u>1?h-1:h],A=[a&&c>1?c-1:c,a&&u>1?u-1:u],x=y[0]/A[0],b=y[1]/A[1],w=0;for(let k=0;k<d;k++){let S=k*l[0];for(let N=0;N<c;N++){let $=o?x*(N+.5):x*N,F=Math.min(p-1,a?Math.round($):Math.floor($));o&&(F=Math.max(0,F));let R=S+F*l[1];for(let D=0;D<u;D++){let T=o?b*(D+.5):b*D,O=Math.min(h-1,a?Math.round(T):Math.floor(T));o&&(O=Math.max(0,O));let B=R+O*l[2];for(let H=0;H<f;H++){let z=m[B+H];g[w++]=z}}}}return n.makeTensorInfo([d,c,u,f],r.dtype,g)}var dX={kernelName:fu,backendName:"cpu",kernelFunc:cX};function pX(e){let{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:o}=s;Ne([a,r],"resizeNearestNeighborGrad");let i=v.computeStrides(r.shape),l=v.computeStrides(a.shape),[c,u,d,p]=r.shape,[,h,f]=a.shape,m=new Float32Array(c*u*d*p),g=n.data.get(a.dataId).values,y=[o&&h>1?u-1:u,o&&f>1?d-1:d],A=[o&&h>1?h-1:h,o&&f>1?f-1:f],x=y[0]/A[0],b=y[1]/A[1],w=1/x,k=1/b,S=Math.ceil(w)*2+2,N=Math.ceil(k)*2+2;for(let $=0;$<c;$++){let F=$*i[0];for(let R=0;R<u;R++){let D=F+R*i[1],T=Math.floor(R*w),O=Math.floor(T-S/2);for(let B=0;B<d;B++){let H=D+B*i[2],z=Math.floor(B*k),X=Math.floor(z-N/2);for(let ee=0;ee<p;ee++){let J=0;for(let Q=0;Q<S;Q++){let ne=Q+O;if(ne<0||ne>=h)continue;let K=F+ne*l[1],oe=ne*x,ce=Math.min(u-1,o?Math.round(oe):Math.floor(oe));if(R===ce)for(let he=0;he<N;he++){let Ae=he+X;if(Ae<0||Ae>=f)continue;let Se=K+Ae*l[2],Ce=Ae*b,Oe=Math.min(d-1,o?Math.round(Ce):Math.floor(Ce));B===Oe&&(J+=g[Se+ee])}}m[H+ee]=J}}}}return n.makeTensorInfo(r.shape,r.dtype,m)}var hX={kernelName:Fh,backendName:"cpu",kernelFunc:pX};function fX(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s;Ne(r,"reverse");let o=r.shape.length,i=v.parseAxisParam(a,r.shape);if(o===0)return Or({inputs:{x:r},backend:n});let l=new tn(r.shape,r.dtype),c=n.bufferSync(r);for(let u=0;u<l.size;u++){let d=l.indexToLoc(u),p=d.slice();i.forEach(h=>p[h]=r.shape[h]-1-p[h]),l.set(c.get(...p),...d)}return n.makeTensorInfo(l.shape,l.dtype,l.values)}var mX={kernelName:Ni,backendName:"cpu",kernelFunc:fX},gX={kernelName:Wi,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:s}=e,{radians:r,fillValue:a,center:o}=t,i=n,l=v.getTypedArrayFromDType(s.dtype,v.sizeFromShape(s.shape)),[c,u,d,p]=s.shape,[h,f]=E.getImageCenter(o,u,d),m=255,g=Math.sin(r),y=Math.cos(r),A=i.data.get(s.dataId).values;for(let b=0;b<c;b++){let w=b*d*u*p;for(let k=0;k<u;k++){let S=k*(d*p);for(let N=0;N<d;N++){let $=N*p;for(let F=0;F<p;F++){let R=[c,k,N,F],D=R[2],T=R[1],O=(D-h)*y-(T-f)*g,B=(D-h)*g+(T-f)*y;O=Math.round(O+h),B=Math.round(B+f);let H=a;if(typeof a!="number"&&(F===3?H=m:H=a[F]),O>=0&&O<d&&B>=0&&B<u){let X=B*(d*p),ee=O*p,J=w+X+ee+F;H=A[J]}let z=w+S+$+F;l[z]=H}}}}return{dataId:i.write(l,s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}},yX=xt(Ei,e=>{let t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2==0?t:t+1}),AX={kernelName:Ei,backendName:"cpu",kernelFunc:yX};function bI(e,t,n,s,r,a,o,i,l,c){let u=[s/r,r],d=e.values,p=t.values;if(s===0)return We(n,t.dtype);let h=We(u,t.dtype);h.values.fill(l);for(let f=0;f<a;f++){let m=[],g=0;for(let y=0;y<o;y++){let A=d[f*o+y];m.push(A),g+=A*i[y]}if(g<0||g>=s/r)throw new Error(`Invalid indices: ${m} does not index into ${n}`);for(let y=0;y<r;y++)c?h.values[g*r+y]+=p[f*r+y]:h.values[g*r+y]=t.rank===0?p[0]:p[f*r+y]}return h}function xX(e){let{inputs:t,backend:n,attrs:s}=e,{indices:r,updates:a}=t,{shape:o}=s,{sliceRank:i,numUpdates:l,sliceSize:c,strides:u,outputSize:d}=E.calculateShapes(a,r,o),p=!0,h=n.bufferSync(r),f=n.bufferSync(a),m=bI(h,f,o,d,c,l,i,u,0,p);return n.makeTensorInfo(o,m.dtype,m.values)}var bX={kernelName:Ri,backendName:"cpu",kernelFunc:xX};function vX(e){let{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t;Ne([s,r,a],"select");let o=s.shape.length,i=n.data.get(s.dataId).values,l=n.data.get(r.dataId).values,c=n.data.get(a.dataId).values,u=Ln(r.dtype,a.dtype),d=v.makeZerosTypedArray(v.sizeFromShape(r.shape),u),p=0,h=o===0||o>1||r.shape.length===1?1:v.sizeFromShape(r.shape.slice(1));for(let f=0;f<i.length;f++)for(let m=0;m<h;m++)i[f]===1?d[p++]=l[f]:d[p++]=c[f];return n.makeTensorInfo(r.shape,u,d)}var wX={kernelName:$i,backendName:"cpu",kernelFunc:vX},kX=E.SELU_SCALEALPHA,IX=E.SELU_SCALE,SX=xt(mu,e=>e>=0?IX*e:kX*(Math.exp(e)-1)),CX={kernelName:mu,backendName:"cpu",kernelFunc:SX},TX=xt(gu,e=>e<0?-1:e>0?1:0),NX={kernelName:gu,backendName:"cpu",kernelFunc:TX},EX=xt(so,e=>Math.sin(e)),RX={kernelName:so,backendName:"cpu",kernelFunc:EX},$X=xt(_i,e=>Math.sinh(e)),DX={kernelName:_i,backendName:"cpu",kernelFunc:$X},_X=11920928955078125e-23,vI=Math.log(_X)+2,PX=xt(yu,e=>{let t=e>-vI,n=e<vI,s=Math.exp(e),r;return n?r=s:t?r=e:r=Math.log(1+s),r}),FX={kernelName:yu,backendName:"cpu",kernelFunc:PX};function OX(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:o}=s;Ne([r],"spaceToBatchND");let i=v.sizeFromShape(a),l=[[0,0]];l.push(...o);for(let k=1+a.length;k<r.shape.length;++k)l.push([0,0]);let c=xI.kernelFunc({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),u=E.getReshaped(c.shape,a,i,!1),d=E.getPermuted(u.length,a.length,!1),p=E.getReshapedPermuted(c.shape,a,i,!1),m=Et({inputs:{x:c},backend:n,attrs:{shape:u}}),A=zs({inputs:{x:m},backend:n,attrs:{perm:d}}),w=Et({inputs:{x:A},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(A),w}var MX={kernelName:Pi,backendName:"cpu",kernelFunc:OX};function zX(e){let{inputs:t,backend:n}=e,{indices:s,values:r,denseShape:a,defaultValue:o}=t;if(a.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
|
|
${a.shape}`);if(s.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
|
|
${s.shape}`);if(r.shape.length!==1)throw new Error(`Values must be a vector, saw:
|
|
${r.shape}`);if(o.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${o.shape}`);let i=n.data.get(s.dataId).values,l=n.data.get(r.dataId).values,c=n.data.get(a.dataId).values,u=n.data.get(o.dataId).values[0],[d,p,h,f,m]=j7(i,s.shape,s.dtype,l,r.dtype,c,u);return[n.makeTensorInfo(p,s.dtype,d),n.makeTensorInfo([p[0]],r.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),n.makeTensorInfo([m.length],s.dtype,new Int32Array(m))]}var LX={kernelName:Mh,backendName:"cpu",kernelFunc:zX};function BX(e){let{inputs:t,backend:n}=e,{inputIndices:s,inputShape:r,newShape:a}=t;if(s.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
|
|
${s.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
|
|
${r.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);let o=Array.from(n.data.get(r.dataId).values),i=n.data.get(s.dataId).values,l=Array.from(n.data.get(a.dataId).values),[c,u,d]=q7(i,s.shape,s.dtype,o,l);return[n.makeTensorInfo(u,s.dtype,c),n.makeTensorInfo([d.length],a.dtype,new Int32Array(d))]}var WX={kernelName:zh,backendName:"cpu",kernelFunc:BX};function VX(e){let{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${r.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${a.shape}`);let o=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values,l=n.data.get(a.dataId).values,[c,u]=qA(o,s.shape,s.dtype,i,l,!0);return n.makeTensorInfo(u,s.dtype,c)}var UX={kernelName:Lh,backendName:"cpu",kernelFunc:VX};function GX(e){let{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${r.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${a.shape}`);let o=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values,l=n.data.get(a.dataId).values,[c,u]=qA(o,s.shape,s.dtype,i,l);return n.makeTensorInfo(u,s.dtype,c)}var HX={kernelName:Bh,backendName:"cpu",kernelFunc:GX};function jX(e){let{inputs:t,backend:n,attrs:s}=e,{sparseIndices:r,sparseValues:a,defaultValue:o}=t,{outputShape:i}=s,{sliceRank:l,numUpdates:c,sliceSize:u,strides:d,outputSize:p}=E.calculateShapes(a,r,i),h=!1,f=n.bufferSync(r),m=n.bufferSync(a),g=n.data.get(o.dataId).values[0],y=bI(f,m,i,p,u,c,l,d,g,h);return n.makeTensorInfo(i,y.dtype,y.values)}var qX={kernelName:nd,backendName:"cpu",kernelFunc:jX};function XX(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{numOrSizeSplits:a,axis:o}=s,i=v.parseAxisParam(o,r.shape)[0],l=E.prepareSplitSize(r,a,i),c=new Array(r.shape.length).fill(0),u=r.shape.slice();return l.map(d=>{let p=[...u];p[i]=d;let h=ml({inputs:{x:r},backend:n,attrs:{begin:c,size:p}});return c[i]+=d,h})}var KX={kernelName:Fi,backendName:"cpu",kernelFunc:XX},ZX={kernelName:Au,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,s=t;Ne(n,"square");let r=s.data.get(n.dataId).values,a=new Float32Array(r.length);for(let i=0;i<r.length;++i){let l=r[i];a[i]=l*l}return{dataId:s.write(a,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},YX=xt(ho,(e,t)=>{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),JX={kernelName:ho,backendName:"cpu",kernelFunc:YX};function QX(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=s;Ne(r,"stridedSlice");let{nonStrided:h,$begin:f,$strides:m,size:g,newShape:y,outShape:A}=yn.sliceInfo(r.shape,a,o,i,l,c,u,d,p),x=Et({inputs:{x:r},backend:n,attrs:{shape:y}}),b;if(h){let k=ml({inputs:{x},backend:n,attrs:{begin:f,size:g}});b=Et({inputs:{x:k},backend:n,attrs:{shape:A}}),n.disposeIntermediateTensorInfo(k)}else if(A.some(k=>k===0))b=n.makeTensorInfo(A,r.dtype,[]);else{let k=n.bufferSync(x),S=K7(A,k,m,f);b=n.makeTensorInfo(S.shape,S.dtype,S.values)}let w=Et({inputs:{x:b},backend:n,attrs:{shape:A}});return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(b),w}var eK={kernelName:Oi,backendName:"cpu",kernelFunc:QX};function tK(e){let{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:c}=s,{data:u,dataSplits:d}=t,p=n.data.get(u.dataId).values,h=n.data.get(d.dataId).values,[f,m]=Z7(p,h,r,a,o,i,l,c);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var nK={kernelName:sd,backendName:"cpu",kernelFunc:tK};function sK(e){let{inputs:t,backend:n,attrs:s}=e,{skipEmpty:r}=s,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.data.get(a.dataId).values,l=n.data.get(o.dataId).values[0],[c,u,d]=Y7(i,l,r),p=u.length;return[n.makeTensorInfo([p,2],"int32",c),n.makeTensorInfo([p],"string",u),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var rK={kernelName:Wh,backendName:"cpu",kernelFunc:sK};function aK(e){let{inputs:t,backend:n,attrs:s}=e,{numBuckets:r}=s,{input:a}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");let o=n.data.get(a.dataId).values,i=J7(o,r);return n.makeTensorInfo(a.shape,"int32",i)}var oK={kernelName:Vh,backendName:"cpu",kernelFunc:aK},iK=xt(Mi,e=>Math.tan(e)),lK={kernelName:Mi,backendName:"cpu",kernelFunc:iK},uK=xt(co,e=>Math.tanh(e)),cK={kernelName:co,backendName:"cpu",kernelFunc:uK};function dK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reps:a}=s;Ne(r,"tile");let o=eI(n.bufferSync(r),a);return n.makeTensorInfo(o.shape,o.dtype,o.values)}var pK={kernelName:Kr,backendName:"cpu",kernelFunc:dK};function hK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{k:a,sorted:o}=s;Ne(r,"topk");let i=n.data.get(r.dataId).values,[l,c]=nI(i,r.shape,r.dtype,a,o);return[n.makeTensorInfo(l.shape,l.dtype,l.values),n.makeTensorInfo(c.shape,c.dtype,c.values)]}var fK={kernelName:xu,backendName:"cpu",kernelFunc:hK};function mK(e){let{inputs:t,attrs:n,backend:s}=e,{image:r,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:l,outputShape:c}=n,[u,d,p,h]=r.shape,[f,m]=c!=null?c:[d,p],g=[u,f,m,h],y=v.computeStrides(r.shape),A=y[0],x=y[1],b=y[2],w=v.getTypedArrayFromDType(r.dtype,v.sizeFromShape(g));w.fill(l);let k=s.data.get(r.dataId).values,S=s.data.get(a.dataId).values;for(let $=0;$<u;++$){let F=a.shape[0]===1?S:S.subarray($*8,$*8+8);for(let R=0;R<f;++R)for(let D=0;D<m;++D)for(let T=0;T<h;++T){let O,B=F[6]*D+F[7]*R+1;if(B===0)continue;let H=(F[0]*D+F[1]*R+F[2])/B,z=(F[3]*D+F[4]*R+F[5])/B,X=wI(H,p,i),ee=wI(z,d,i);switch(o){case"nearest":O=vK(k,d,p,A,x,b,$,ee,X,T,l);break;case"bilinear":O=wK(k,d,p,A,x,b,$,ee,X,T,l);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${o}`)}let J=$*A+R*x+D*b+T;w[J]=O}return s.makeTensorInfo(g,r.dtype,w)}return{dataId:s.write(w,g,r.dtype),shape:r.shape,dtype:r.dtype}}var gK={kernelName:zi,backendName:"cpu",kernelFunc:mK};function wI(e,t,n){switch(n){case"reflect":return yK(e,t);case"wrap":return AK(e,t);case"nearest":return bK(e,t);case"constant":default:return xK(e,t)}}function yK(e,t){let n=e;if(n<0)if(t<=1)n=0;else{let s=2*t;n<s&&(n=s*Math.trunc(-n/s)+n),n=n<-t?n+s:-n-1}else if(n>t-1)if(t<=1)n=0;else{let s=2*t;n-=s*Math.trunc(n/s),n>=t&&(n=s-n-1)}return v.clamp(0,n,t-1)}function AK(e,t){let n=e;if(n<0)if(t<=1)n=0;else{let s=t-1;n+=t*(Math.trunc(-n/s)+1)}else if(n>t-1)if(t<=1)n=0;else{let s=t-1;n-=t*Math.trunc(n/s)}return v.clamp(0,n,t-1)}function xK(e,t){return e}function bK(e,t){return v.clamp(0,e,t-1)}function op(e,t,n,s,r,a,o,i,l,c,u){let d=o*s+i*r+l*a+c;return 0<=i&&i<t&&0<=l&&l<n?e[d]:u}function vK(e,t,n,s,r,a,o,i,l,c,u){let d=Math.round(i),p=Math.round(l);return op(e,t,n,s,r,a,o,d,p,c,u)}function wK(e,t,n,s,r,a,o,i,l,c,u){let d=Math.floor(i),p=Math.floor(l),h=d+1,f=p+1,m=(f-l)*op(e,t,n,s,r,a,o,d,p,c,u)+(l-p)*op(e,t,n,s,r,a,o,d,f,c,u),g=(f-l)*op(e,t,n,s,r,a,o,h,p,c,u)+(l-p)*op(e,t,n,s,r,a,o,h,f,c,u);return(h-i)*m+(i-d)*g}function kK(e){let{inputs:t,attrs:n,backend:s}=e,{axis:r}=n,{x:a}=t;Ne(a,"unique");let o=s.data.get(a.dataId).values,{outputValues:i,outputShape:l,indices:c}=sI(o,r,a.shape,a.dtype);return[s.makeTensorInfo(l,a.dtype,i),s.makeTensorInfo([c.length],"int32",c)]}var IK={kernelName:Uh,backendName:"cpu",kernelFunc:kK};function SK(e){let{inputs:t,backend:n,attrs:s}=e,{value:r}=t,{axis:a}=s;a<0&&(a+=r.shape.length);let o=r.shape.length,i=r.shape[a],l=new Array(o-1),c=0;for(let h=0;h<o;h++)h!==a&&(l[c++]=r.shape[h]);let u=new Array(o).fill(0),d=r.shape.slice();d[a]=1;let p=new Array(i);for(let h=0;h<p.length;h++){u[a]=h;let f=ml({inputs:{x:r},backend:n,attrs:{begin:u,size:d}});p[h]=Et({inputs:{x:f},backend:n,attrs:{shape:l}}),n.disposeIntermediateTensorInfo(f)}return p}var CK={kernelName:Li,backendName:"cpu",kernelFunc:SK};function TK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,segmentIds:a}=t,{numSegments:o}=s;Ne(r,"unsortedSegmentSum");let i=r.shape.length,l=a.shape.length,c=[],u=[],d=i-l,p=a;for(let f=0;f<d;++f){let m=Tm({inputs:{input:p},backend:n,attrs:{dim:f+1}});p=m,u.push(m)}for(let f=0;f<o;++f){let m=v.createScalarValue(f,"int32"),g=n.makeTensorInfo([],"int32",m),y=S7({inputs:{a:g,b:p},backend:n}),A=Po({inputs:{x:y},backend:n,attrs:{dtype:"float32"}}),x=Sm({inputs:{a:A,b:r},backend:n}),b=ap({inputs:{x},backend:n,attrs:{axis:0,keepDims:!1}});c.push(b),u.push(g),u.push(y),u.push(A),u.push(x),u.push(b)}let h=AI({inputs:c,backend:n,attrs:{axis:0}});return u.forEach(f=>n.disposeIntermediateTensorInfo(f)),h}var NK={kernelName:rd,backendName:"cpu",kernelFunc:TK},EK=[OG,EU,zG,BG,FU,VG,GG,jG,XG,ZG,JG,eH,nH,aH,iH,cH,pH,fH,gH,PG,AH,bH,wH,IH,_U,MU,CH,RU,NH,RH,_H,FH,$H,LH,WH,MH,UH,HH,qH,KH,YH,QH,ej,nj,rj,oj,ij,uj,lj,JA,pj,TG,fj,zU,wj,LU,kj,WU,Ej,Rj,Dj,UU,Fj,Mj,Lj,Wj,Uj,HU,qU,$U,Hj,EH,qj,Kj,Yj,NG,KU,YU,Qj,QU,tq,rq,oq,uq,dq,hq,tG,gq,Aq,bq,wq,Iq,fq,Cq,Nq,sG,Rq,_q,Mq,aG,iG,Bq,Uq,jq,uG,Xq,Zq,Yq,xI,tX,RG,pG,sX,DU,aX,$G,DG,_G,iX,uX,dX,hX,mX,gX,AX,fG,bX,wX,CX,gG,NX,RX,DX,yG,Fq,FX,MX,LX,WX,UX,HX,qX,KX,bG,ZX,wG,JX,eK,nK,rK,oK,CG,cj,lK,cK,pK,fK,cG,gK,IK,CK,NK,Kq];for(let e of EK)Yr(e);var kI={};Le(kI,{assertNotComplex:()=>tc,bindCanvasToFramebuffer:()=>WK,bindColorTextureToFramebuffer:()=>Dm,bindTextureToProgramUniformSampler:()=>zI,bindTextureUnit:()=>FI,bindVertexBufferToProgramAttribute:()=>sx,callAndCheck:()=>Ie,canBeRepresented:()=>II,createFragmentShader:()=>TI,createFramebuffer:()=>PI,createProgram:()=>NI,createStaticIndexBuffer:()=>$I,createStaticVertexBuffer:()=>RI,createTexture:()=>DI,createVertexShader:()=>CI,getBatchDim:()=>yl,getExtensionOrThrow:()=>up,getFramebufferErrorMessage:()=>LI,getMaxTexturesInShader:()=>UI,getNumChannels:()=>LK,getProgramUniformLocation:()=>MI,getProgramUniformLocationOrThrow:()=>OI,getRowsCols:()=>Al,getShapeAs3D:()=>_m,getTextureShapeFromLogicalShape:()=>WI,getWebGLDisjointQueryTimerVersion:()=>GI,getWebGLErrorMessage:()=>SI,getWebGLMaxTextureSize:()=>VI,hasExtension:()=>Bs,isCapableOfRenderingToFloatTexture:()=>HI,isDownloadFloatTextureEnabled:()=>jI,isReshapeFree:()=>dp,isWebGLFenceEnabled:()=>qI,isWebGLVersionEnabled:()=>ax,linkProgram:()=>EI,resetMaxTextureSize:()=>VK,resetMaxTexturesInShader:()=>UK,unbindColorTextureFromFramebuffer:()=>rx,unbindTextureUnit:()=>BK,validateFramebuffer:()=>cp,validateProgram:()=>$m,validateTextureSize:()=>_I});var gl={},tx={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Em(e,t){gl[e]=t}function Mr(e){if(!(e in gl)){let n=$K(e);if(n!==null)gl[e]=n;else return console.log("Could not get context for WebGL version",e),null}let t=gl[e];return t.isContextLost()?(delete gl[e],Mr(e)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),gl[e])}function RK(e){if(typeof OffscreenCanvas!="undefined"&&e===2)return new OffscreenCanvas(300,150);if(typeof document!="undefined")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function $K(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let t=RK(e);return t.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete gl[e]},!1),e===1?t.getContext("webgl",tx)||t.getContext("experimental-webgl",tx):t.getContext("webgl2",tx)}var ip;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(ip||(ip={}));var Ls;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(Ls||(Ls={}));var Nn;(function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(Nn||(Nn={}));function lp(e,t){return[t,e]}function DK(e,t){return e*t}function Rm(e){let t=v.sizeFromShape(e),n=Math.ceil(t/4);return v.sizeToSquarishShape(n)}function ec(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function _K(e,t){let[n,s]=ec(e,t);return n*s*4}function nx(e,t){let n=e,s,r,a,o,i,l,c,u,d,p;return Z().getNumber("WEBGL_VERSION")===2?(s=n.R32F,r=n.R16F,a=n.RGBA16F,o=n.RGBA32F,i=n.RED,c=4,u=1,d=n.HALF_FLOAT,p=n.FLOAT):(s=e.RGBA,r=e.RGBA,a=e.RGBA,o=n.RGBA,i=e.RGBA,c=4,u=4,d=t!=null?t.HALF_FLOAT_OES:null,p=e.FLOAT),l=e.RGBA,{internalFormatFloat:s,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:o,textureFormatFloat:i,downloadTextureFormat:l,downloadUnpackNumChannels:c,defaultNumChannels:u,textureTypeHalfFloat:d,textureTypeFloat:p}}function Ie(e,t){let n=t();return Z().getBool("DEBUG")&&PK(e),n}function PK(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+SI(e,t))}var FK=596e-10,OK=65504;function II(e){return!!(Z().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||FK<Math.abs(e)&&Math.abs(e)<OK)}function SI(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}function up(e,t){return la(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function CI(e,t){let n=la(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(Ie(e,()=>e.shaderSource(n,t)),Ie(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}function TI(e,t){let n=la(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(Ie(e,()=>e.shaderSource(n,t)),Ie(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw zK(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}var MK=/ERROR: [0-9]+:([0-9]+):/g;function zK(e,t){let n=MK.exec(t);if(n==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}let s=+n[1],r=e.split(`
|
|
`),a=r.length.toString().length+2,o=r.map((d,p)=>v.rightPad((p+1).toString(),a)+d),i=0;for(let d=0;d<o.length;d++)i=Math.max(o[d].length,i);let l=o.slice(0,s-1),c=o.slice(s-1,s),u=o.slice(s);console.log(l.join(`
|
|
`)),console.log(t.split(`
|
|
`)[0]),console.log(`%c ${v.rightPad(c[0],i)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(u.join(`
|
|
`))}function NI(e){return la(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function EI(e,t){if(Ie(e,()=>e.linkProgram(t)),e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function $m(e,t){if(Ie(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function RI(e,t){let n=la(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Ie(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Ie(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function $I(e,t){let n=la(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Ie(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),Ie(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function LK(){return Z().getNumber("WEBGL_VERSION")===2?1:4}function DI(e){return la(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function _I(e,t){let n=Z().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let s=`[${e}x${t}]`;throw new Error("Requested texture size "+s+" is invalid.")}if(e>n||t>n){let s=`[${e}x${t}]`,r=`[${n}x${n}]`;throw new Error("Requested texture size "+s+" greater than WebGL maximum on this browser / GPU "+r+".")}}function PI(e){return la(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function sx(e,t,n,s,r,a,o){let i=e.getAttribLocation(t,n);return i===-1?!1:(Ie(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s)),Ie(e,()=>e.vertexAttribPointer(i,r,e.FLOAT,!1,a,o)),Ie(e,()=>e.enableVertexAttribArray(i)),!0)}function FI(e,t,n){BI(e,n),Ie(e,()=>e.activeTexture(e.TEXTURE0+n)),Ie(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function BK(e,t){BI(e,t),Ie(e,()=>e.activeTexture(e.TEXTURE0+t)),Ie(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function OI(e,t,n){return la(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function MI(e,t,n){return e.getUniformLocation(t,n)}function zI(e,t,n,s){Ie(e,()=>FI(e,t,s)),Ie(e,()=>e.uniform1i(n,s))}function WK(e){Ie(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Ie(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),Ie(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function Dm(e,t,n){Ie(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),Ie(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function rx(e,t){Ie(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),Ie(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function cp(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+LI(e,t))}function LI(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function la(e,t,n){let s=Ie(e,()=>t());if(s==null)throw new Error(n);return s}function BI(e,t){let n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,s=t+e.TEXTURE0;if(s<e.TEXTURE0||s>n){let r=`[gl.TEXTURE0, gl.TEXTURE${n}]`;throw new Error(`textureUnit must be in ${r}.`)}}function yl(e,t=2){return v.sizeFromShape(e.slice(0,e.length-t))}function Al(e){if(e.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function _m(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[yl(e),...Al(e)]),t}function WI(e,t=!1){let n=Z().getNumber("WEBGL_MAX_TEXTURE_SIZE");t&&(n=n*2,e=e.map((r,a)=>a>=e.length-2?v.nearestLargerEven(e[a]):e[a]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=v.squeezeShape(e).newShape);let s=v.sizeFromShape(e);if(e.length<=1&&s<=n)return[1,s];if(e.length===2&&e[0]<=n&&e[1]<=n)return e;if(e.length===3&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=n&&e[3]<=n)return[e[0]*e[1]*e[2],e[3]];if(e.length===4&&e[0]<=n&&e[1]*e[2]*e[3]<=n)return[e[0],e[1]*e[2]*e[3]];if(t){let r=yl(e),a=2,o=2;return e.length&&([a,o]=Al(e)),s=r*(a/2)*(o/2),v.sizeToSquarishShape(s).map(i=>i*2)}return v.sizeToSquarishShape(s)}function Pm(e){return e%2==0}function dp(e,t){if(e=e.slice(-2),t=t.slice(-2),v.arraysEqual(e,t)||!e.length||!t.length||e[0]===0||e[1]===0||t[0]===0||t[1]===0)return!0;if(e.length!==t.length){let n=e.slice(-1)[0],s=t.slice(-1)[0];if(n===s||Pm(n)&&Pm(s)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&Pm(e[0])&&Pm(t[0])}var Fm,Om;function VI(e){if(Fm==null){let t=Mr(e);Fm=t.getParameter(t.MAX_TEXTURE_SIZE)}return Fm}function VK(){Fm=null}function UK(){Om=null}function UI(e){if(Om==null){let t=Mr(e);Om=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Om)}function GI(e){if(e===0)return 0;let t,n=Mr(e);return Bs(n,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:Bs(n,"EXT_disjoint_timer_query")?t=1:t=0,t}function Bs(e,t){return e.getExtension(t)!=null}function ax(e){try{if(Mr(e)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function HI(e){if(e===0)return!1;let t=Mr(e);if(e===1){if(!Bs(t,"OES_texture_float"))return!1}else if(!Bs(t,"EXT_color_buffer_float"))return!1;return ox(t)}function jI(e){if(e===0)return!1;let t=Mr(e);if(e===1){if(!Bs(t,"OES_texture_float")||!Bs(t,"WEBGL_color_buffer_float"))return!1}else{if(Bs(t,"EXT_color_buffer_float"))return ox(t);let s="EXT_color_buffer_half_float";if(Bs(t,s)){let r=t.getExtension(s);return GK(t,r)}return!1}return ox(t)}function ox(e){let t=nx(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);let s=1,r=1;e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,s,r,0,t.textureFormatFloat,t.textureTypeFloat,null);let a=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,a),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);let o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(a),o}function GK(e,t){let n=nx(e,t),s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s);let r=1,a=1;e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,r,a,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);let o=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,o),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);let i=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(s),e.deleteFramebuffer(o),i}function qI(e){return e!==2?!1:Mr(e).fenceSync!=null}function tc(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&v.assert(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}var De=Z();De.registerFlag("HAS_WEBGL",()=>De.getNumber("WEBGL_VERSION")>0);De.registerFlag("WEBGL_VERSION",()=>ax(2)?2:ax(1)?1:0);De.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);De.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>De.get("WEBGL_VERSION")===2);De.registerFlag("WEBGL_CPU_FORWARD",()=>!0);De.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);De.registerFlag("WEBGL_PACK",()=>De.getBool("HAS_WEBGL"));De.registerFlag("WEBGL_PACK_NORMALIZATION",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_PACK_CLIP",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_PACK_REDUCE",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_LAZILY_UNPACK",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_CONV_IM2COL",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>VI(De.getNumber("WEBGL_VERSION")));De.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>UI(De.getNumber("WEBGL_VERSION")));De.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let e=De.getNumber("WEBGL_VERSION");return e===0?0:GI(e)});De.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>De.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!wu.isMobile());De.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>HI(De.getNumber("WEBGL_VERSION")));De.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>De.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:De.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));De.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>jI(De.getNumber("WEBGL_VERSION")));De.registerFlag("WEBGL_FENCE_API_ENABLED",()=>qI(De.getNumber("WEBGL_VERSION")));De.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>De.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);De.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,e=>{if(e<0&&e!==-1)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)});De.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>wu.isMobile()&&De.getBool("IS_CHROME")?1:-1,e=>{if(e<0&&e!==-1)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`)});De.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);De.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1);De.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5);De.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128);function Gn(){let e,t,n,s,r,a,o,i,l,c;return Z().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",n="out",s="in",r="texture",a="outputColor",o="out vec4 outputColor;",i=`
|
|
bool isnan_custom(float val) {
|
|
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
|
|
}
|
|
|
|
bvec4 isnan_custom(vec4 val) {
|
|
return bvec4(isnan_custom(val.x),
|
|
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
|
|
}
|
|
|
|
#define isnan(value) isnan_custom(value)
|
|
`,l="",c=`
|
|
#define round(value) newRound(value)
|
|
int newRound(float value) {
|
|
return int(floor(value + 0.5));
|
|
}
|
|
|
|
ivec4 newRound(vec4 value) {
|
|
return ivec4(floor(value + vec4(0.5)));
|
|
}
|
|
`):(e="",t="attribute",n="varying",s="varying",r="texture2D",a="gl_FragColor",o="",i=`
|
|
#define isnan(value) isnan_custom(value)
|
|
bool isnan_custom(float val) {
|
|
return (val > 0. || val < 1. || val == 0.) ? false : true;
|
|
}
|
|
bvec4 isnan_custom(vec4 val) {
|
|
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
|
|
}
|
|
`,l=`
|
|
uniform float INFINITY;
|
|
|
|
bool isinf(float val) {
|
|
return abs(val) == INFINITY;
|
|
}
|
|
bvec4 isinf(vec4 val) {
|
|
return equal(abs(val), vec4(INFINITY));
|
|
}
|
|
`,c=`
|
|
int round(float value) {
|
|
return int(floor(value + 0.5));
|
|
}
|
|
|
|
ivec4 round(vec4 value) {
|
|
return ivec4(floor(value + vec4(0.5)));
|
|
}
|
|
`),{version:e,attribute:t,varyingVs:n,varyingFs:s,texture2D:r,output:a,defineOutput:o,defineSpecialNaN:i,defineSpecialInf:l,defineRound:c}}function xl(e,t,n="index"){let s=v.computeStrides(t);return s.map((r,a)=>{let o=`int ${e[a]} = ${n} / ${r}`,i=a===s.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * ${r}`:`index -= ${e[a]} * ${r}`;return`${o}; ${i};`}).join("")}function Mm(e,t,n="index"){let s=v.computeStrides(t);return s.map((r,a)=>{let o=`int ${e[a]} = ${n} / outShapeStrides[${a}]`,i=a===s.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * outShapeStrides[${a}]`:`index -= ${e[a]} * outShapeStrides[${a}]`;return`${o}; ${i};`}).join("")}function HK(e,t){let n=e.length,s=e.map(a=>`${t}[${a}]`),r=new Array(n-1);r[n-2]=s[n-1];for(let a=n-3;a>=0;--a)r[a]=`(${r[a+1]} * ${s[a+1]})`;return r}function jK(e,t,n="index"){let s=e.map((a,o)=>o),r=HK(s,t);return r.map((a,o)=>{let i=`int ${e[o]} = ${n} / ${r[o]}`,l=o===r.length-1?`int ${e[o+1]} = ${n} - ${e[o]} * ${r[o]}`:`index -= ${e[o]} * ${r[o]}`;return`${i}; ${l};`}).join("")}function ix(e){let t=v.computeStrides(e).map(n=>n.toString());return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
|
|
}
|
|
`}function lx(){return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
|
|
}
|
|
`}var XI=`
|
|
const float FLOAT_MAX = 1.70141184e38;
|
|
const float FLOAT_MIN = 1.17549435e-38;
|
|
|
|
lowp vec4 encode_float(highp float v) {
|
|
if (isnan(v)) {
|
|
return vec4(255, 255, 255, 255);
|
|
}
|
|
|
|
highp float av = abs(v);
|
|
|
|
if(av < FLOAT_MIN) {
|
|
return vec4(0.0, 0.0, 0.0, 0.0);
|
|
} else if(v > FLOAT_MAX) {
|
|
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
|
|
} else if(v < -FLOAT_MAX) {
|
|
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
|
|
}
|
|
|
|
highp vec4 c = vec4(0,0,0,0);
|
|
|
|
highp float e = floor(log2(av));
|
|
highp float m = exp2(fract(log2(av))) - 1.0;
|
|
|
|
c[2] = floor(128.0 * m);
|
|
m -= c[2] / 128.0;
|
|
c[1] = floor(32768.0 * m);
|
|
m -= c[1] / 32768.0;
|
|
c[0] = floor(8388608.0 * m);
|
|
|
|
highp float ebias = e + 127.0;
|
|
c[3] = floor(ebias / 2.0);
|
|
ebias -= c[3] * 2.0;
|
|
c[2] += floor(ebias) * 128.0;
|
|
|
|
c[3] += 128.0 * step(0.0, -v);
|
|
|
|
return c / 255.0;
|
|
}
|
|
`,{getBroadcastDims:KI}=E;function qK(e,t,n){let s=[];if(e.forEach(h=>{let f=v.sizeFromShape(h.shapeInfo.logicalShape);if(h.shapeInfo.isUniform?s.push(`uniform float ${h.name}${f>1?`[${f}]`:""};`):(s.push(`uniform sampler2D ${h.name};`),s.push(`uniform int offset${h.name};`)),n.enableShapeUniforms){let{uniformShape:m}=ux(n.packedInputs,h.shapeInfo.logicalShape,h.shapeInfo.texShape);switch(m.length){case 1:s.push(`uniform int ${h.name}Shape;`);break;case 2:s.push(`uniform ivec2 ${h.name}Shape;`);break;case 3:s.push(`uniform ivec3 ${h.name}Shape;`);break;case 4:s.push(`uniform ivec4 ${h.name}Shape;`);break;default:break}s.push(`uniform ivec2 ${h.name}TexShape;`)}}),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:s.push("uniform int outShape;");break;case 2:s.push("uniform ivec2 outShape;"),s.push("uniform int outShapeStrides;");break;case 3:s.push("uniform ivec3 outShape;"),s.push("uniform ivec2 outShapeStrides;");break;case 4:s.push("uniform ivec4 outShape;"),s.push("uniform ivec3 outShapeStrides;");break;default:break}s.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach(h=>{s.push(`uniform ${h.type} ${h.name}${h.arrayIndex?`[${h.arrayIndex}]`:""};`)});let r=s.join(`
|
|
`),a=e.map(h=>XK(h,t,n.packedInputs,n.enableShapeUniforms)).join(`
|
|
`),o=t.texShape,i=Gn(),l=YK(i),c,u,d=eZ(i);return t.isPacked?(c=KK(t.logicalShape,o,n.enableShapeUniforms),u=QK(i)):(c=ZK(t.logicalShape,o,n.enableShapeUniforms),u=JK(i)),n.packedInputs&&(d+=rZ),[d,l,u,r,c,a,n.userCode].join(`
|
|
`)}function nc(e,t=!1){let n=e.shapeInfo.logicalShape;switch(n.length){case 0:return gZ(e,t);case 1:return AZ(e,t);case 2:return bZ(e,t);case 3:return wZ(e,t);case 4:return IZ(e,t);case 5:return SZ(e);case 6:return CZ(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function ZI(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return mZ(e);case 1:return yZ(e,t);case 2:return xZ(e,t);case 3:return vZ(e,t);default:return kZ(e,t)}}function XK(e,t,n=!1,s){let r="";n?r+=ZI(e,s):r+=nc(e,s);let a=e.shapeInfo.logicalShape,o=t.logicalShape;return a.length<=o.length&&(n?r+=TZ(e,t):r+=NZ(e,t)),r}function KK(e,t,n){switch(e.length){case 0:return YI();case 1:return aZ(e,t,n);case 2:return hZ(e,t,n);case 3:return iZ(e,t,n);default:return uZ(e,t,n)}}function ZK(e,t,n){switch(e.length){case 0:return YI();case 1:return oZ(e,t,n);case 2:return fZ(e,t,n);case 3:return lZ(e,t,n);case 4:return cZ(e,t,n);case 5:return dZ(e,t);case 6:return pZ(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function YK(e){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return ${e.texture2D}(textureSampler, uv).r;
|
|
}
|
|
`}function JK(e){return`
|
|
void setOutput(float val) {
|
|
${e.output} = vec4(val, 0, 0, 0);
|
|
}
|
|
`}function QK(e){return`
|
|
void setOutput(vec4 val) {
|
|
${e.output} = val;
|
|
}
|
|
`}function eZ(e){return`${e.version}
|
|
precision highp float;
|
|
precision highp int;
|
|
precision highp sampler2D;
|
|
${e.varyingFs} vec2 resultUV;
|
|
${e.defineOutput}
|
|
const vec2 halfCR = vec2(0.5, 0.5);
|
|
|
|
struct ivec5
|
|
{
|
|
int x;
|
|
int y;
|
|
int z;
|
|
int w;
|
|
int u;
|
|
};
|
|
|
|
struct ivec6
|
|
{
|
|
int x;
|
|
int y;
|
|
int z;
|
|
int w;
|
|
int u;
|
|
int v;
|
|
};
|
|
|
|
uniform float NAN;
|
|
${e.defineSpecialNaN}
|
|
${e.defineSpecialInf}
|
|
${e.defineRound}
|
|
|
|
int imod(int x, int y) {
|
|
return x - y * (x / y);
|
|
}
|
|
|
|
int idiv(int a, int b, float sign) {
|
|
int res = a / b;
|
|
int mod = imod(a, b);
|
|
if (sign < 0. && mod != 0) {
|
|
res -= 1;
|
|
}
|
|
return res;
|
|
}
|
|
|
|
//Based on the work of Dave Hoskins
|
|
//https://www.shadertoy.com/view/4djSRW
|
|
#define HASHSCALE1 443.8975
|
|
float random(float seed){
|
|
vec2 p = resultUV * seed;
|
|
vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
|
|
p3 += dot(p3, p3.yzx + 19.19);
|
|
return fract((p3.x + p3.y) * p3.z);
|
|
}
|
|
|
|
${tZ}
|
|
${nZ}
|
|
${sZ}
|
|
`}var tZ=`
|
|
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
|
|
int texR = index / texNumC;
|
|
int texC = index - texR * texNumC;
|
|
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
|
|
}
|
|
vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
|
|
int texelIndex = index / 2;
|
|
int texR = texelIndex / texNumC;
|
|
int texC = texelIndex - texR * texNumC;
|
|
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
|
|
}
|
|
`,nZ=`
|
|
vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
|
|
int texNumC, int row, int col) {
|
|
int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
|
|
int texR = texelIndex / texNumC;
|
|
int texC = texelIndex - texR * texNumC;
|
|
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
|
|
}
|
|
`,sZ=`
|
|
vec2 packedUVfrom3D(int texNumR, int texNumC,
|
|
int texelsInBatch, int texelsInLogicalRow, int b,
|
|
int row, int col) {
|
|
int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
|
|
int texR = index / texNumC;
|
|
int texC = index - texR * texNumC;
|
|
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
|
|
}
|
|
`,rZ=`
|
|
float getChannel(vec4 frag, vec2 innerDims) {
|
|
vec2 modCoord = mod(innerDims, 2.);
|
|
return modCoord.x == 0. ?
|
|
(modCoord.y == 0. ? frag.r : frag.g) :
|
|
(modCoord.y == 0. ? frag.b : frag.a);
|
|
}
|
|
float getChannel(vec4 frag, int dim) {
|
|
float modCoord = mod(float(dim), 2.);
|
|
return modCoord == 0. ? frag.r : frag.g;
|
|
}
|
|
`;function YI(){return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`}function aZ(e,t,n){let s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return s[0]===1?n?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * ${s[1]}.0);
|
|
}
|
|
`:s[1]===1?n?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * ${s[0]}.0);
|
|
}
|
|
`:n?`
|
|
int getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(packedTexShape[0], packedTexShape[1]));
|
|
return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${s[0]}, ${s[1]}));
|
|
return 2 * (resTexRC.x * ${s[1]} + resTexRC.y);
|
|
}
|
|
`}function oZ(e,t,n){return t[0]===1?n?`
|
|
int getOutputCoords() {
|
|
return int(resultUV.x * float(outTexShape[1]));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return int(resultUV.x * ${t[1]}.0);
|
|
}
|
|
`:t[1]===1?n?`
|
|
int getOutputCoords() {
|
|
return int(resultUV.y * float(outTexShape[0]));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return int(resultUV.y * ${t[0]}.0);
|
|
}
|
|
`:n?`
|
|
int getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
return resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
return resTexRC.x * ${t[1]} + resTexRC.y;
|
|
}
|
|
`}function iZ(e,t,n){if(n)return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));
|
|
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(packedTexShape[0], packedTexShape[1]));
|
|
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
|
|
|
|
int b = index / texelsInBatch;
|
|
index -= b * texelsInBatch;
|
|
|
|
int r = 2 * (index / texelsInLogicalRow);
|
|
int c = imod(index, texelsInLogicalRow) * 2;
|
|
|
|
return ivec3(b, r, c);
|
|
}
|
|
`;let s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[2]/2),a=r*Math.ceil(e[1]/2);return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${s[0]}, ${s[1]}));
|
|
int index = resTexRC.x * ${s[1]} + resTexRC.y;
|
|
|
|
int b = index / ${a};
|
|
index -= b * ${a};
|
|
|
|
int r = 2 * (index / ${r});
|
|
int c = imod(index, ${r}) * 2;
|
|
|
|
return ivec3(b, r, c);
|
|
}
|
|
`}function lZ(e,t,n){if(n)return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
${Mm(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`;let s=xl(["r","c","d"],e);return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
${s}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}function uZ(e,t,n){if(n)return`
|
|
ivec4 getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(packedTexShape[0], packedTexShape[1]));
|
|
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
|
|
|
|
int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));
|
|
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));
|
|
int texelsInBatchN = texelsInBatch * outShape[1];
|
|
|
|
int b2 = index / texelsInBatchN;
|
|
index -= b2 * texelsInBatchN;
|
|
|
|
int b = index / texelsInBatch;
|
|
index -= b * texelsInBatch;
|
|
|
|
int r = 2 * (index / texelsInLogicalRow);
|
|
int c = imod(index, texelsInLogicalRow) * 2;
|
|
|
|
return ivec4(b2, b, r, c);
|
|
}
|
|
`;let s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[e.length-1]/2),a=r*Math.ceil(e[e.length-2]/2),o=a,i="",l="b, r, c";for(let c=2;c<e.length-1;c++)o*=e[e.length-c-1],i=`
|
|
int b${c} = index / ${o};
|
|
index -= b${c} * ${o};
|
|
`+i,l=`b${c}, `+l;return`
|
|
ivec${e.length} getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${s[0]}, ${s[1]}));
|
|
int index = resTexRC.x * ${s[1]} + resTexRC.y;
|
|
|
|
${i}
|
|
|
|
int b = index / ${a};
|
|
index -= b * ${a};
|
|
|
|
int r = 2 * (index / ${r});
|
|
int c = imod(index, ${r}) * 2;
|
|
|
|
return ivec${e.length}(${l});
|
|
}
|
|
`}function cZ(e,t,n){if(n)return`
|
|
ivec4 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
${Mm(["r","c","d","d2"],e)}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`;let s=xl(["r","c","d","d2"],e);return`
|
|
ivec4 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
${s}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`}function dZ(e,t){let n=xl(["r","c","d","d2","d3"],e);return`
|
|
ivec5 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
|
|
${t[1]}));
|
|
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
|
|
${n}
|
|
|
|
ivec5 outShape = ivec5(r, c, d, d2, d3);
|
|
return outShape;
|
|
}
|
|
`}function pZ(e,t){let n=xl(["r","c","d","d2","d3","d4"],e);return`
|
|
ivec6 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
|
|
${n}
|
|
|
|
ivec6 result = ivec6(r, c, d, d2, d3, d4);
|
|
return result;
|
|
}
|
|
`}function hZ(e,t,n){let s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(v.arraysEqual(e,t))return n?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
return 2 * ivec2(resultUV.yx * vec2(${s[0]}, ${s[1]}));
|
|
}
|
|
`;let r=Math.ceil(e[1]/2);return n?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(packedTexShape[0], packedTexShape[1]));
|
|
|
|
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
|
|
int r = 2 * (index / texelsInLogicalRow);
|
|
int c = imod(index, texelsInLogicalRow) * 2;
|
|
|
|
return ivec2(r, c);
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${s[0]}, ${s[1]}));
|
|
|
|
int index = resTexRC.x * ${s[1]} + resTexRC.y;
|
|
int r = 2 * (index / ${r});
|
|
int c = imod(index, ${r}) * 2;
|
|
|
|
return ivec2(r, c);
|
|
}
|
|
`}function fZ(e,t,n){return v.arraysEqual(e,t)?n?`
|
|
ivec2 getOutputCoords() {
|
|
return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
|
|
}
|
|
`:e[1]===1?n?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
return ivec2(index, 0);
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
return ivec2(index, 0);
|
|
}
|
|
`:e[0]===1?n?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
return ivec2(0, index);
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
return ivec2(0, index);
|
|
}
|
|
`:n?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
int r = index / outShape[1];
|
|
int c = index - r * outShape[1];
|
|
return ivec2(r, c);
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
int r = index / ${e[1]};
|
|
int c = index - r * ${e[1]};
|
|
return ivec2(r, c);
|
|
}
|
|
`}function bl(e){return`offset${e}`}function mZ(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),s=Gn();return`
|
|
vec4 ${n}() {
|
|
return ${s.texture2D}(${t}, halfCR);
|
|
}
|
|
`}function gZ(e,t){let n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`float ${s}() {return ${n};}`;let[r,a]=e.shapeInfo.texShape;if(r===1&&a===1)return`
|
|
float ${s}() {
|
|
return sampleTexture(${n}, halfCR);
|
|
}
|
|
`;let o=bl(n);if(t)return`
|
|
float ${s}() {
|
|
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], ${o});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let[i,l]=e.shapeInfo.texShape;return`
|
|
float ${s}() {
|
|
vec2 uv = uvFromFlat(${i}, ${l}, ${o});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function yZ(e,t){let n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),r=e.shapeInfo.texShape,a=Gn();if(t)return`
|
|
vec4 ${s}(int index) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom1D(
|
|
packedTexShape[0], packedTexShape[1], index);
|
|
return ${a.texture2D}(${n}, uv);
|
|
}
|
|
`;let o=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)];return`
|
|
vec4 ${s}(int index) {
|
|
vec2 uv = packedUVfrom1D(
|
|
${o[0]}, ${o[1]}, index);
|
|
return ${a.texture2D}(${n}, uv);
|
|
}
|
|
`}function AZ(e,t){let n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`
|
|
float ${s}(int index) {
|
|
${sc(e)}
|
|
}
|
|
`;let r=e.shapeInfo.texShape,a=r[0],o=r[1];if(o===1&&a===1)return`
|
|
float ${s}(int index) {
|
|
return sampleTexture(${n}, halfCR);
|
|
}
|
|
`;let i=bl(n);return o===1?t?`
|
|
float ${s}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / float(${n}TexShape[0]));
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / ${a}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:a===1?t?`
|
|
float ${s}(int index) {
|
|
vec2 uv = vec2((float(index + ${i}) + 0.5) / float(${n}TexShape[1]), 0.5);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int index) {
|
|
vec2 uv = vec2((float(index + ${i}) + 0.5) / ${o}.0, 0.5);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:t?`
|
|
float ${s}(int index) {
|
|
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${i});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int index) {
|
|
vec2 uv = uvFromFlat(${a}, ${o}, index + ${i});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function xZ(e,t){let n=e.shapeInfo.logicalShape,s=e.name,r="get"+s.charAt(0).toUpperCase()+s.slice(1),a=e.shapeInfo.texShape,o=a[0],i=a[1],l=Gn();if(a!=null&&v.arraysEqual(n,a))return t?`
|
|
vec4 ${r}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);
|
|
|
|
return ${l.texture2D}(${s}, uv);
|
|
}
|
|
`:`
|
|
vec4 ${r}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${i}.0, ${o}.0);
|
|
|
|
return ${l.texture2D}(${s}, uv);
|
|
}
|
|
`;if(t)return`
|
|
vec4 ${r}(int row, int col) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${s}TexShape[0]) / 2.0), ceil(float(${s}TexShape[1]) / 2.0));
|
|
int valuesPerRow = int(ceil(float(${s}Shape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
|
|
return ${l.texture2D}(${s}, uv);
|
|
}
|
|
`;let c=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],u=Math.ceil(n[1]/2);return`
|
|
vec4 ${r}(int row, int col) {
|
|
vec2 uv = packedUVfrom2D(${u}, ${c[0]}, ${c[1]}, row, col);
|
|
return ${l.texture2D}(${s}, uv);
|
|
}
|
|
`}function bZ(e,t){let n=e.shapeInfo.logicalShape,s=e.name,r="get"+s.charAt(0).toUpperCase()+s.slice(1),a=e.shapeInfo.texShape;if(a!=null&&v.arraysEqual(n,a)){if(t)return`
|
|
float ${r}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`;let p=a[0],h=a[1];return`
|
|
float ${r}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${h}.0, ${p}.0);
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`}let{newShape:o,keptDims:i}=v.squeezeShape(n),l=o;if(l.length<n.length){let p=rc(e,l),h=["row","col"];return`
|
|
${nc(p,t)}
|
|
float ${r}(int row, int col) {
|
|
return ${r}(${ac(h,i)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${r}(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(${n[1]}, 1)));
|
|
${sc(e)}
|
|
}
|
|
`;let c=a[0],u=a[1],d=bl(s);return u===1?t?`
|
|
float ${r}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${d}), vec3(${s}Shape[1], 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / float(${s}TexShape[0]));
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${d}), vec3(${n[1]}, 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / ${c}.0);
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`:c===1?t?`
|
|
float ${r}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${d}), vec3(${s}Shape[1], 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / float(${s}TexShape[1]), 0.5);
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${d}), vec3(${n[1]}, 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / ${u}.0, 0.5);
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`:t?`
|
|
float ${r}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${s}Shape[1] + col + ${d};
|
|
vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index);
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${n[1]} + col + ${d};
|
|
vec2 uv = uvFromFlat(${c}, ${u}, index);
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`}function vZ(e,t){let n=e.shapeInfo.logicalShape,s=e.name,r="get"+s.charAt(0).toUpperCase()+s.slice(1),a=e.shapeInfo.texShape,o=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];if(n[0]===1){let p=n.slice(1),h=[1,2],f=rc(e,p),m=["b","row","col"];return`
|
|
${ZI(f,t)}
|
|
vec4 ${r}(int b, int row, int col) {
|
|
return ${r}(${ac(m,h)});
|
|
}
|
|
`}let i=Gn();if(t)return`
|
|
vec4 ${r}(int b, int row, int col) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${s}TexShape[0]) / 2.0), ceil(float(${s}TexShape[1]) / 2.0));
|
|
int valuesPerRow = int(ceil(float(${s}Shape[2]) / 2.0));
|
|
int texelsInBatch = valuesPerRow * int(ceil(float(${s}Shape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom3D(
|
|
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
|
|
return ${i.texture2D}(${s}, uv);
|
|
}
|
|
`;let l=o[0],c=o[1],u=Math.ceil(n[2]/2),d=u*Math.ceil(n[1]/2);return`
|
|
vec4 ${r}(int b, int row, int col) {
|
|
vec2 uv = packedUVfrom3D(
|
|
${l}, ${c}, ${d}, ${u}, b, row, col);
|
|
return ${i.texture2D}(${s}, uv);
|
|
}
|
|
`}function wZ(e,t){let n=e.shapeInfo.logicalShape,s=e.name,r="get"+s.charAt(0).toUpperCase()+s.slice(1),a=n[1]*n[2],o=n[2],{newShape:i,keptDims:l}=v.squeezeShape(n),c=i;if(c.length<n.length){let m=rc(e,c),g=["row","col","depth"];return`
|
|
${nc(m,t)}
|
|
float ${r}(int row, int col, int depth) {
|
|
return ${r}(${ac(g,l)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${r}(int row, int col, int depth) {
|
|
int index = round(dot(vec3(row, col, depth),
|
|
vec3(${a}, ${o}, 1)));
|
|
${sc(e)}
|
|
}
|
|
`;let u=e.shapeInfo.texShape,d=u[0],p=u[1],h=e.shapeInfo.flatOffset;if(p===a&&h==null)return t?`
|
|
float ${r}(int row, int col, int depth) {
|
|
int stride1 = ${s}Shape[2];
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(stride1, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${s}TexShape[1], ${s}TexShape[0]);
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int row, int col, int depth) {
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(${o}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${p}.0, ${d}.0);
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`;if(p===o&&h==null)return t?`
|
|
float ${r}(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(${s}Shape[1], 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(${n[1]}, 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}.0, ${d}.0);
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`;let f=bl(s);return t?`
|
|
float ${r}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int stride0 = ${s}Shape[1] * ${s}Shape[2];
|
|
int stride1 = ${s}Shape[2];
|
|
int index = row * ${a} + col * ${o} + depth + ${f};
|
|
vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index);
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${a} + col * ${o} + depth + ${f};
|
|
vec2 uv = uvFromFlat(${d}, ${p}, index);
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`}function kZ(e,t){let n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),r=Gn();if(t)return`
|
|
vec4 ${s}(int b2, int b, int row, int col) {
|
|
int valuesPerRow = int(ceil(float(${n}Shape[3]) / 2.0));
|
|
int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[2]) / 2.0));
|
|
int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
|
|
texelsInBatch *= ${n}Shape[1];
|
|
index = b2 * texelsInBatch + index;
|
|
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
|
|
int texR = index / packedTexShape[1];
|
|
int texC = index - texR * packedTexShape[1];
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${r.texture2D}(${n}, uv);
|
|
}
|
|
`;let a=e.shapeInfo.logicalShape,o=a.length,i=e.shapeInfo.texShape,l=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],c=l[0],u=l[1],d=Math.ceil(a[o-1]/2),p=d*Math.ceil(a[o-2]/2),h="int b, int row, int col",f=`b * ${p} + (row / 2) * ${d} + (col / 2)`;for(let m=2;m<o-1;m++)h=`int b${m}, `+h,p*=a[o-m-1],f=`b${m} * ${p} + `+f;return`
|
|
vec4 ${s}(${h}) {
|
|
int index = ${f};
|
|
int texR = index / ${u};
|
|
int texC = index - texR * ${u};
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${u}, ${c});
|
|
return ${r.texture2D}(${n}, uv);
|
|
}
|
|
`}function IZ(e,t){let n=e.shapeInfo.logicalShape,s=e.name,r="get"+s.charAt(0).toUpperCase()+s.slice(1),a=n[3],o=n[2]*a,i=n[1]*o,{newShape:l,keptDims:c}=v.squeezeShape(n);if(l.length<n.length){let A=rc(e,l),x=["row","col","depth","depth2"];return`
|
|
${nc(A,t)}
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
return ${r}(${ac(x,c)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
int index = round(dot(vec4(row, col, depth, depth2),
|
|
vec4(${i}, ${o}, ${a}, 1)));
|
|
${sc(e)}
|
|
}
|
|
`;let u=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],h=d[1],f=`int stride2 = ${s}Shape[3];`,m=`int stride1 = ${s}Shape[2] * stride2;`,g=`int stride0 = ${s}Shape[1] * stride1;`;if(h===i&&u==null)return t?`
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
${f}
|
|
${m}
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(stride1, stride2, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${s}TexShape[1], ${s}TexShape[0]);
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(${o}, ${a}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${p}.0);
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`;if(h===a&&u==null)return t?`
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(${s}Shape[1] * ${s}Shape[2], ${s}Shape[2], 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${s}TexShape[1], ${s}TexShape[0]);
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(${n[1]*n[2]}, ${n[2]}, 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${p}.0);
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`;let y=bl(s);return t?`
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
${f}
|
|
${m}
|
|
${g}
|
|
int index = row * stride0 + col * stride1 +
|
|
depth * stride2 + depth2;
|
|
vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index + ${y});
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${i} + col * ${o} +
|
|
depth * ${a} + depth2;
|
|
vec2 uv = uvFromFlat(${p}, ${h}, index + ${y});
|
|
return sampleTexture(${s}, uv);
|
|
}
|
|
`}function SZ(e){let t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),r=t[4],a=t[3]*r,o=t[2]*a,i=t[1]*o,{newShape:l,keptDims:c}=v.squeezeShape(t);if(l.length<t.length){let m=rc(e,l),g=["row","col","depth","depth2","depth3"];return`
|
|
${nc(m)}
|
|
float ${s}(int row, int col, int depth, int depth2, int depth3) {
|
|
return ${s}(${ac(g,c)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${s}(int row, int col, int depth, int depth2, int depth3) {
|
|
float index = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${i}, ${o}, ${a}, ${r})) +
|
|
depth3;
|
|
${sc(e)}
|
|
}
|
|
`;let u=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],h=d[1];if(h===i&&u==null)return`
|
|
float ${s}(int row, int col, int depth, int depth2, int depth3) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${o}, ${a}, ${r}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(h===r&&u==null)return`
|
|
float ${s}(int row, int col, int depth, int depth2, int depth3) {
|
|
float texR = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${t[1]*t[2]*t[3]},
|
|
${t[2]*t[3]}, ${t[3]}, 1));
|
|
int texC = depth3;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let f=bl(n);return`
|
|
float ${s}(int row, int col, int depth, int depth2, int depth3) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${i} + col * ${o} + depth * ${a} +
|
|
depth2 * ${r} + depth3 + ${f};
|
|
vec2 uv = uvFromFlat(${p}, ${h}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function CZ(e){let t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:r,keptDims:a}=v.squeezeShape(t);if(r.length<t.length){let g=rc(e,r),y=["row","col","depth","depth2","depth3","depth4"];return`
|
|
${nc(g)}
|
|
float ${s}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return ${s}(${ac(y,a)});
|
|
}
|
|
`}let o=t[5],i=t[4]*o,l=t[3]*i,c=t[2]*l,u=t[1]*c;if(e.shapeInfo.isUniform)return`
|
|
float ${s}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int index = round(dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${u}, ${c}, ${l}, ${i})) +
|
|
dot(
|
|
vec2(depth3, depth4),
|
|
vec2(${o}, 1)));
|
|
${sc(e)}
|
|
}
|
|
`;let d=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],f=p[1];if(f===u&&d==null)return`
|
|
float ${s}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${c}, ${l}, ${i}, ${o})) +
|
|
float(depth4);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${f}.0, ${h}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(f===o&&d==null)return`
|
|
float ${s}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
float texR = dot(vec4(row, col, depth, depth2),
|
|
vec4(${t[1]*t[2]*t[3]*t[4]},
|
|
${t[2]*t[3]*t[4]},
|
|
${t[3]*t[4]},
|
|
${t[4]})) + float(depth3);
|
|
int texC = depth4;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${f}.0, ${h}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let m=bl(n);return`
|
|
float ${s}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${u} + col * ${c} + depth * ${l} +
|
|
depth2 * ${i} + depth3 * ${o} + depth4 + ${m};
|
|
vec2 uv = uvFromFlat(${h}, ${f}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function sc(e){let t=e.name,n=v.sizeFromShape(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`
|
|
for (int i = 0; i < ${n}; i++) {
|
|
if (i == index) {
|
|
return ${t}[i];
|
|
}
|
|
}
|
|
`}function TZ(e,t){let n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),r="get"+s+"AtOutCoords",a=e.shapeInfo.logicalShape.length,o=t.logicalShape.length,i=KI(e.shapeInfo.logicalShape,t.logicalShape),l=St(o),c=o-a,u,d=["x","y","z","w","u","v"];a===0?u="":o<2&&i.length>=1?u="coords = 0;":u=i.map(A=>`coords.${d[A+c]} = 0;`).join(`
|
|
`);let p="";o<2&&a>0?p="coords":p=e.shapeInfo.logicalShape.map((A,x)=>`coords.${d[x+c]}`).join(", ");let h="return outputValue;",m=v.sizeFromShape(e.shapeInfo.logicalShape)===1,y=v.sizeFromShape(t.logicalShape)===1;if(a===1&&!m&&!y)h=`
|
|
return vec4(outputValue.xy, outputValue.xy);
|
|
`;else if(m&&!y)o===1?h=`
|
|
return vec4(outputValue.x, outputValue.x, 0., 0.);
|
|
`:h=`
|
|
return vec4(outputValue.x);
|
|
`;else if(i.length){let A=a-2,x=a-1;i.indexOf(A)>-1&&i.indexOf(x)>-1?h="return vec4(outputValue.x);":i.indexOf(A)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(x)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return`
|
|
vec4 ${r}() {
|
|
${l} coords = getOutputCoords();
|
|
${u}
|
|
vec4 outputValue = get${s}(${p});
|
|
${h}
|
|
}
|
|
`}function NZ(e,t){let n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),r="get"+s+"AtOutCoords",a=t.texShape,o=e.shapeInfo.texShape,i=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&i===l&&e.shapeInfo.flatOffset==null&&v.arraysEqual(o,a))return`
|
|
float ${r}() {
|
|
return sampleTexture(${n}, resultUV);
|
|
}
|
|
`;let c=St(l),u=KI(e.shapeInfo.logicalShape,t.logicalShape),d=l-i,p,h=["x","y","z","w","u","v"];i===0?p="":l<2&&u.length>=1?p="coords = 0;":p=u.map(m=>`coords.${h[m+d]} = 0;`).join(`
|
|
`);let f="";return l<2&&i>0?f="coords":f=e.shapeInfo.logicalShape.map((m,g)=>`coords.${h[g+d]}`).join(", "),`
|
|
float ${r}() {
|
|
${c} coords = getOutputCoords();
|
|
${p}
|
|
return get${s}(${f});
|
|
}
|
|
`}function St(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function ux(e,t,n){let{newShape:s,keptDims:r}=v.squeezeShape(t),a=t.length,o=e&&a===3&&t[0]===1,i=o?t.slice(1):s,l=!e&&a>1&&!v.arraysEqual(t,n)&&s.length<a||o;return{useSqueezeShape:l,uniformShape:l?i:t,keptDims:r}}function rc(e,t){let n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function ac(e,t){return t.map(n=>e[n]).join(", ")}function EZ(e,t,n,s){let r=n.map((x,b)=>{let w={logicalShape:x.shape,texShape:x.isUniform?null:x.texData.texShape,isUniform:x.isUniform,isPacked:x.isUniform?!1:x.texData.isPacked,flatOffset:null};return x.texData!=null&&x.texData.slice!=null&&x.texData.slice.flatOffset>0&&(w.flatOffset=x.texData.slice.flatOffset),{name:t.variableNames[b],shapeInfo:w}}),a=r.map(x=>x.shapeInfo),o={logicalShape:s.shape,texShape:s.texData.texShape,isUniform:!1,isPacked:s.texData.isPacked,flatOffset:null},i=qK(r,o,t),l=e.createProgram(i),c=null,u=e.getUniformLocation(l,"NAN",!1);Z().getNumber("WEBGL_VERSION")===1&&(c=e.getUniformLocation(l,"INFINITY",!1));let d=!1,p={},h={},f={};for(let x=0;x<t.variableNames.length;x++){let b=t.variableNames[x];p[b]=e.getUniformLocation(l,b,d),p[`offset${b}`]=e.getUniformLocation(l,`offset${b}`,d),t.enableShapeUniforms&&(h[`${b}Shape`]=e.getUniformLocation(l,`${b}Shape`,d),f[`${b}TexShape`]=e.getUniformLocation(l,`${b}TexShape`,d))}let m,g,y;t.enableShapeUniforms&&(m=e.getUniformLocation(l,"outShape",d),y=e.getUniformLocation(l,"outShapeStrides",d),g=e.getUniformLocation(l,"outTexShape",d));let A=[];return t.customUniforms&&t.customUniforms.forEach((x,b)=>{A[b]=e.getUniformLocation(l,x.name,d)}),{program:t,source:i,webGLProgram:l,uniformLocations:p,customUniformLocations:A,inShapeInfos:a,outShapeInfo:o,infLoc:c,nanLoc:u,inShapesLocations:h,inTexShapesLocations:f,outShapeLocation:m,outShapeStridesLocation:y,outTexShapeLocation:g}}function JI(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach((n,s)=>{let r=n.logicalShape,a=t[s],o=a.shape;if(!v.arraysEqual(r,o))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${r} and ${o} must match`);if(n.isUniform&&a.isUniform)return;let i=n.texShape,l=a.isUniform?null:a.texData.texShape;if(!v.arraysEqual(i,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${l} must match`)})}function RZ(e,t,n,s,r){t.program.enableShapeUniforms||(JI(t.inShapeInfos,n),JI([t.outShapeInfo],[s]));let a=s.texData.texture,o=s.texData.texShape;s.texData.isPacked?e.setOutputPackedMatrixTexture(a,o[0],o[1]):e.setOutputMatrixTexture(a,o[0],o[1]),e.setProgram(t.webGLProgram),Z().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach((l,c)=>{let u=t.program.variableNames[c],d=t.uniformLocations[u],p=t.uniformLocations[`offset${u}`],h=t.inShapesLocations[`${u}Shape`],f=t.inTexShapesLocations[`${u}TexShape`];if(h){let{uniformShape:m}=ux(t.program.packedInputs,l.shape,l.texData.texShape);switch(m.length){case 1:e.gl.uniform1iv(h,new Int32Array(m));break;case 2:e.gl.uniform2iv(h,new Int32Array(m));break;case 3:e.gl.uniform3iv(h,new Int32Array(m));break;case 4:e.gl.uniform4iv(h,new Int32Array(m));break;default:break}}if(f&&e.gl.uniform2i(f,l.texData.texShape[0],l.texData.texShape[1]),d!=null){if(l.isUniform){if(v.sizeFromShape(l.shape)<2)e.gl.uniform1f(d,l.uniformValues[0]);else{let m=l.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),e.gl.uniform1fv(d,m)}return}l.texData.slice!=null&&p!=null&&e.gl.uniform1i(p,l.texData.slice.flatOffset),e.setInputMatrixTexture(l.texData.texture,d,c)}});let i=t.outShapeLocation;if(i)switch(s.shape.length){case 1:e.gl.uniform1iv(i,new Int32Array(s.shape));break;case 2:e.gl.uniform2iv(i,new Int32Array(s.shape));break;case 3:e.gl.uniform3iv(i,new Int32Array(s.shape));break;case 4:e.gl.uniform4iv(i,new Int32Array(s.shape));break;default:break}if(t.outShapeStridesLocation){let l=v.computeStrides(s.shape);switch(s.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(l));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(l));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(l));break;default:break}}t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,s.texData.texShape[0],s.texData.texShape[1]),t.program.customUniforms&&r&&t.program.customUniforms.forEach((l,c)=>{let u=t.customUniformLocations[c],d=r[c];if(l.type==="float")e.gl.uniform1fv(u,d);else if(l.type==="vec2")e.gl.uniform2fv(u,d);else if(l.type==="vec3")e.gl.uniform3fv(u,d);else if(l.type==="vec4")e.gl.uniform4fv(u,d);else if(l.type==="int")e.gl.uniform1iv(u,d);else if(l.type==="ivec2")e.gl.uniform2iv(u,d);else if(l.type==="ivec3")e.gl.uniform3iv(u,d);else if(l.type==="ivec4")e.gl.uniform4iv(u,d);else throw Error(`uniform type ${l.type} is not supported yet.`)}),e.executeProgram()}function $Z(e,t,n){let s="";t.concat(n).forEach(o=>{let i=o.texData!=null&&o.texData.slice!=null&&o.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!o.isUniform){let l=o.texData.texShape,{useSqueezeShape:c,uniformShape:u,keptDims:d}=ux(e.packedInputs,o.shape,l),p="",h="",f="";if(u.length===1&&e.packedInputs){let w=[Math.ceil(l[0]/2),Math.ceil(l[1]/2)];p=`${w[0]>1}_${w[1]>1}`}else if(u.length===2&&!e.packedInputs)h=`${u[0]>1}_${u[1]>1}`;else if(u.length>2&&!e.packedInputs){let w=v.computeStrides(u);f=`${w[0]===l[1]}_${w[w.length-1]===l[1]}`}let m=o.shape.length,g=u.length===2&&v.arraysEqual(o.shape,l),y=v.sizeFromShape(o.shape)===1,A=E.getBroadcastDims(o.shape,n.shape),x=!e.packedInputs&&m===n.shape.length&&v.arraysEqual(l,n.texData.texShape),b=e.packedInputs||u.length>2?"":`${l[0]>1}_${l[1]>1}`;s+=`${m}_${x}_${c?d:""}_${u.length}_${y}_${A}_${g}_${p}_${h}_${f}_${b}_${i}`}else{let l=o.isUniform?"uniform":o.texData.texShape;s+=`${o.shape}_${l}_${i}`}});let r=e.userCode,a=e.constructor.name;return a+="_"+s+"_"+r+`${Z().getNumber("WEBGL_VERSION")}`,a}function Ws(e){return Z().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}var DZ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=ip.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Gn();this.outputShape=e,this.enableShapeUniforms=Ws(this.outputShape.length),this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms?Mm(["r","c","d"],e):xl(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
|
|
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
for (int i=0; i<4; i++) {
|
|
int flatIndex = index + i;
|
|
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
|
|
result[i] = getA(rc.x, rc.y, rc.z);
|
|
}
|
|
|
|
${t.output} = result;
|
|
}
|
|
`}},_Z=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=ip.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Gn();this.outputShape=e,this.enableShapeUniforms=Ws(this.outputShape.length),this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms?Mm(["r","c","d"],e):xl(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
|
|
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
for (int i=0; i<4; i++) {
|
|
int flatIndex = index + i;
|
|
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
|
|
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
|
|
}
|
|
|
|
${t.output} = result;
|
|
}
|
|
`}},PZ=class{constructor(e){this.variableNames=["A"],this.outTexUsage=Ls.DOWNLOAD;let t=Gn();this.outputShape=e,this.userCode=`
|
|
${XI}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},FZ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Ls.DOWNLOAD;let t=Gn();this.outputShape=e,this.userCode=`
|
|
${XI}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},OZ=class{constructor(e,t=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Gn();this.outputShape=e,this.enableShapeUniforms=Ws(this.outputShape.length);let s="result";t&&(s="floor(result * 255. + 0.5)"),this.userCode=`
|
|
${this.enableShapeUniforms?lx():ix(e)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
int flatIndex = getFlatIndex(coords);
|
|
int offset = imod(flatIndex, 4);
|
|
|
|
flatIndex = idiv(flatIndex, 4, 1.);
|
|
|
|
int r = flatIndex / texShape[1];
|
|
int c = imod(flatIndex, texShape[1]);
|
|
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
|
|
vec4 values = ${n.texture2D}(A, uv);
|
|
|
|
float result;
|
|
|
|
if(offset == 0) {
|
|
result = values[0];
|
|
} else if(offset == 1) {
|
|
result = values[1];
|
|
} else if(offset == 2) {
|
|
result = values[2];
|
|
} else {
|
|
result = values[3];
|
|
}
|
|
|
|
${n.output} = vec4(${s}, 0., 0., 0.);
|
|
}
|
|
`}},MZ=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Gn();this.outputShape=e,this.enableShapeUniforms=Ws(this.outputShape.length);let s="",r="result";t&&(r="floor(result * 255. + 0.5)");for(let a=0;a<=1;a++)for(let o=0;o<=1;o++){let i=a*2+o;s+=`
|
|
localCoords = coords;
|
|
if(localCoords[2] + ${o} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {
|
|
localCoords[2] += ${o};
|
|
if (localCoords[1] + ${a} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {
|
|
localCoords[1] += ${a};
|
|
|
|
flatIndex = getFlatIndex(localCoords);
|
|
offset = imod(flatIndex, 4);
|
|
|
|
flatIndex = idiv(flatIndex, 4, 1.);
|
|
|
|
int r = flatIndex / texShape[1];
|
|
int c = imod(flatIndex, texShape[1]);
|
|
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
|
|
values = ${n.texture2D}(A, uv);
|
|
|
|
if (offset == 0) {
|
|
result[${i}] = values[0];
|
|
} else if (offset == 1) {
|
|
result[${i}] = values[1];
|
|
} else if (offset == 2) {
|
|
result[${i}] = values[2];
|
|
} else {
|
|
result[${i}] = values[3];
|
|
}
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
${this.enableShapeUniforms?lx():ix(e)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
int flatIndex, r, c, offset;
|
|
ivec3 localCoords;
|
|
vec2 uv;
|
|
vec4 values;
|
|
|
|
${s}
|
|
|
|
${n.output} = ${r};
|
|
}
|
|
`}},QI={};Le(QI,{bindVertexProgramAttributeStreams:()=>l4,createBufferFromOutputTexture:()=>d4,createFloat16MatrixTexture:()=>r4,createFloat16PackedMatrixTexture:()=>i4,createFloat32MatrixTexture:()=>s4,createIndexBuffer:()=>n4,createPackedMatrixTexture:()=>o4,createUnsignedBytesMatrixTexture:()=>a4,createVertexBuffer:()=>t4,createVertexShader:()=>e4,downloadByteEncodedFloatMatrixFromOutputTexture:()=>h4,downloadFloat32MatrixFromBuffer:()=>p4,downloadMatrixFromPackedOutputTexture:()=>m4,downloadPackedMatrixFromBuffer:()=>f4,getInternalFormatForFloat16MatrixTexture:()=>dx,getInternalFormatForFloat16PackedMatrixTexture:()=>fx,getInternalFormatForFloat32MatrixTexture:()=>cx,getInternalFormatForPackedMatrixTexture:()=>hx,getInternalFormatForUnsignedBytesMatrixTexture:()=>px,uploadDenseMatrixToTexture:()=>u4,uploadPixelDataToTexture:()=>c4});function e4(e){let t=Gn(),n=`${t.version}
|
|
precision highp float;
|
|
${t.attribute} vec3 clipSpacePos;
|
|
${t.attribute} vec2 uv;
|
|
${t.varyingVs} vec2 resultUV;
|
|
|
|
void main() {
|
|
gl_Position = vec4(clipSpacePos, 1);
|
|
resultUV = uv;
|
|
}`;return CI(e,n)}function t4(e){let t=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return RI(e,t)}function n4(e){let t=new Uint16Array([0,1,2,2,1,3]);return $I(e,t)}function pp(e,t,n,s,r,a){_I(t,n);let o=DI(e),i=e.TEXTURE_2D;return Ie(e,()=>e.bindTexture(i,o)),Ie(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),Ie(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),Ie(e,()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST)),Ie(e,()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST)),Ie(e,()=>e.texImage2D(i,0,s,t,n,0,r,a,null)),Ie(e,()=>e.bindTexture(e.TEXTURE_2D,null)),o}function cx(e){return e.internalFormatFloat}function s4(e,t,n,s){let[r,a]=lp(t,n);return pp(e,r,a,cx(s),s.textureFormatFloat,e.FLOAT)}function dx(e){return e.internalFormatHalfFloat}function r4(e,t,n,s){let[r,a]=lp(t,n);return pp(e,r,a,dx(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function px(e){return e.downloadTextureFormat}function a4(e,t,n,s){let[r,a]=lp(t,n);return pp(e,r,a,px(s),e.RGBA,e.UNSIGNED_BYTE)}function hx(e){return e.internalFormatPackedFloat}function o4(e,t,n,s){let[r,a]=ec(t,n);return pp(e,r,a,hx(s),e.RGBA,e.FLOAT)}function fx(e){return e.internalFormatPackedHalfFloat}function i4(e,t,n,s){let[r,a]=ec(t,n);return pp(e,r,a,fx(s),e.RGBA,s.textureTypeHalfFloat)}function l4(e,t,n){let s=0,r=3*4,a=3*4+2*4;return Ie(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),sx(e,t,"clipSpacePos",n,3,a,s)&&sx(e,t,"uv",n,2,a,r)}function u4(e,t,n,s,r,a){Ie(e,()=>e.bindTexture(e.TEXTURE_2D,t));let o,i,l;r instanceof Uint8Array?(o=new Uint8Array(n*s*4),i=e.UNSIGNED_BYTE,l=e.RGBA):(o=new Float32Array(n*s*4),i=e.FLOAT,l=a.internalFormatPackedFloat),o.set(r),Ie(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,n,s,0,e.RGBA,i,o)),Ie(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function c4(e,t,n){Ie(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?Ie(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):Ie(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),Ie(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function d4(e,t,n,s){let r=e.createBuffer();Ie(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,r));let i=4*4*t*n;return Ie(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,i,e.STREAM_READ)),Ie(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),Ie(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),r}function p4(e,t,n){let s=e,r=new Float32Array(n);return s.bindBuffer(s.PIXEL_PACK_BUFFER,t),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,r),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),r}function h4(e,t,n,s){let[r,a]=lp(t,n),o=4,i=new Uint8Array(DK(t*n,o));return Ie(e,()=>e.readPixels(0,0,r,a,s.downloadTextureFormat,e.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function f4(e,t,n,s,r,a,o,i){let l=e,c=new Float32Array(_K(a,o));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,c),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),c}function m4(e,t,n){let s=new Float32Array(t*n*4);return Ie(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,s)),s}var zm=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=Z().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,Em(t,e)):this.gl=Mr(t);let n="WEBGL_color_buffer_float",s="EXT_color_buffer_half_float";if(Z().getNumber("WEBGL_VERSION")===1){let r="OES_texture_float",a="OES_texture_half_float";if(this.textureFloatExtension=up(this.gl,r),Bs(this.gl,a))this.textureHalfFloatExtension=up(this.gl,a);else if(Z().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Bs(this.gl,s))this.colorBufferHalfFloatExtension=up(this.gl,s);else if(Z().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Bs(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(Bs(this.gl,s))this.colorBufferHalfFloatExtension=this.gl.getExtension(s);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=t4(this.gl),this.indexBuffer=n4(this.gl),this.framebuffer=PI(this.gl),this.textureConfig=nx(this.gl,this.textureHalfFloatExtension)}get debug(){return Z().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");let e=this.gl;Ie(e,()=>e.finish()),Ie(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Ie(e,()=>e.deleteFramebuffer(this.framebuffer)),Ie(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),Ie(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),Ie(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),s4(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),r4(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),a4(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),c4(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,s){this.throwIfDisposed(),u4(this.gl,e,t,n,s,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),i4(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),o4(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(rx(this.gl,this.framebuffer),this.outputTexture=null),Ie(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>h4(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,s,r,a){return f4(this.gl,e,t,n,s,r,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return p4(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);let s=d4(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),s}createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(Z().getBool("WEBGL_FENCE_API_ENABLED")){let s=e,r=s.fenceSync(s.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{let a=s.clientWaitSync(r,0,0);return a===s.ALREADY_SIGNALED||a===s.CONDITION_SATISFIED},t=r}else Z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,Z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>m4(this.gl,t,n))}createProgram(e){this.throwIfDisposed();let t=this.gl,n=TI(t,e);this.vertexShader==null&&(this.vertexShader=e4(t));let s=NI(t);return Ie(t,()=>t.attachShader(s,this.vertexShader)),Ie(t,()=>t.attachShader(s,n)),EI(t,s),this.debug&&$m(t,s),this.vertexAttrsAreBound||(this.setProgram(s),this.vertexAttrsAreBound=l4(t,this.program,this.vertexBuffer)),s}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&Ie(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&$m(this.gl,this.program),Ie(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?OI(this.gl,e,t):MI(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),Ie(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),zI(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();let[s,r]=ec(t,n);this.setOutputMatrixTextureDriver(e,s,r)}setOutputMatrixWriteRegion(e,t,n,s){this.setOutputMatrixWriteRegionDriver(n,e,s,t)}setOutputPackedMatrixWriteRegion(e,t,n,s){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&$m(this.gl,this.program),cp(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;this.debug&&this.debugValidate(),Ie(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Ie(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=up(this.gl,Z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(Z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let n=this.gl,s=this.getQueryTimerExtensionWebGL2(),r=n.createQuery();return n.beginQuery(s.TIME_ELAPSED_EXT,r),r}let e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(Z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let t=this.gl,n=this.getQueryTimerExtensionWebGL2();t.endQuery(n.TIME_ELAPSED_EXT);return}let e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await v.repeatedTry(()=>this.disposed||this.isQueryAvailable(e,Z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,Z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){let n=this.gl;return n.getQueryParameter(e,n.QUERY_RESULT)/1e6}else{let n=this.getQueryTimerExtensionWebGL1();return n.getQueryObjectEXT(e,n.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){let n=this.gl,s=this.getQueryTimerExtensionWebGL2(),r=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(s.GPU_DISJOINT_EXT)),r&&!this.disjoint}else{let n=this.getQueryTimerExtensionWebGL1(),s=n.getQueryObjectEXT(e,n.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),s&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=zZ(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){let{resolveFn:n}=this.itemsToPoll[t];n()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),!(this.itemsToPoll.length>1)&&v.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),Dm(this.gl,e,this.framebuffer),this.debug&&cp(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(Dm(this.gl,this.outputTexture,this.framebuffer),this.debug&&cp(this.gl)):rx(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);let n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();let s=this.gl;Dm(s,e,this.framebuffer),this.debug&&cp(s),this.outputTexture=e,Ie(s,()=>s.viewport(0,0,t,n)),Ie(s,()=>s.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,s){this.throwIfDisposed(),Ie(this.gl,()=>this.gl.scissor(e,t,n,s))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}};function zZ(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}var{addImpl:LZ,bincountImpl:g4,bincountReduceImpl:BZ,ceilImpl:WZ,concatImpl:VZ,equalImpl:UZ,expImpl:GZ,expm1Impl:HZ,floorImpl:jZ,gatherNdImpl:qZ,gatherV2Impl:XZ,greaterImpl:KZ,greaterEqualImpl:ZZ,lessImpl:YZ,lessEqualImpl:JZ,linSpaceImpl:QZ,logImpl:eY,maxImpl:tY,maximumImpl:nY,minimumImpl:sY,multiplyImpl:rY,negImpl:aY,notEqualImpl:oY,prodImpl:iY,rangeImpl:lY,rsqrtImpl:uY,sigmoidImpl:cY,simpleAbsImpl:y4,sliceImpl:dY,sparseFillEmptyRowsImpl:pY,sparseReshapeImpl:hY,sparseSegmentReductionImpl:A4,sqrtImpl:fY,stridedSliceImpl:mY,stringNGramsImpl:gY,stringSplitImpl:yY,stringToHashBucketFastImpl:AY,subImpl:xY,tileImpl:bY,topKImpl:vY,transposeImpl:mx,uniqueImpl:wY}=BA;function x4(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=>`${e}.${n}`)}function Hn(e,t){return t===1?[e]:x4(e,t)}function kY(e,t){if(e===1)return"rc";let n="";for(let s=0;s<e;s++)n+=t[s],s<e-1&&(n+=",");return n}var IY=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e;let t=e.length;if(t===0)this.userCode=`
|
|
void main() {
|
|
setOutput(vec4(getA(), 0., 0., 0.));
|
|
}
|
|
`;else{let n=Hn("rc",t),s=St(t),r=CY(t,e,n),a=TY(t,e[e.length-1],e[e.length-2],n),o=NY(e,n);this.userCode=`
|
|
void main() {
|
|
${s} rc = getOutputCoords();
|
|
|
|
if(${r}) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
${a}
|
|
|
|
setOutput(vec4(${o}));
|
|
}
|
|
}
|
|
`}}};function SY(e,t){let n=[];for(let s=0;s<=1;s++)for(let r=0;r<=1;r++){let a=`${s===0?"r":"rp1"}, ${r===0?"c":"cp1"}`;for(let o=2;o<e;o++)a=`${t[t.length-1-o]},`+a;n.push(a)}return n}function CY(e,t,n){if(e===1)return`rc > ${t[0]}`;let s="";for(let r=e-2;r<e;r++)s+=`${n[r]} >= ${t[r]}`,r<e-1&&(s+="||");return s}function TY(e,t,n,s){if(e===1)return"";let r=s.slice(-2);return`
|
|
int r = ${r[0]};
|
|
int c = ${r[1]};
|
|
int rp1 = r + 1;
|
|
int cp1 = c + 1;
|
|
|
|
bool cEdge = cp1 >= ${t};
|
|
bool rEdge = rp1 >= ${n};
|
|
`}function NY(e,t){let n=e.length,s=SY(n,t);return n===1?`getA(rc),
|
|
rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),
|
|
0, 0`:`getA(${s[0]}),
|
|
cEdge ? 0. : getA(${s[1]}),
|
|
rEdge ? 0. : getA(${s[2]}),
|
|
rEdge || cEdge ? 0. : getA(${s[3]})`}var b4=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=Ws(this.outputShape.length);let n="";for(let s=0;s<4;s++){let r="thisRC = rc;";s%2==1&&(r+="thisRC.z += 1;"),s>1&&(r+="thisRC.y += 1;"),n+=`
|
|
${r}
|
|
${s>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
|
|
int flatIndex = getFlatIndex(thisRC);
|
|
|
|
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
|
|
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
|
|
|
|
result[${s}] =
|
|
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
|
|
${s>0?"}":""}
|
|
`}this.userCode=`
|
|
${EY(t,this.enableShapeUniforms)}
|
|
${this.enableShapeUniforms?lx():ix(e)}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
ivec3 thisRC;
|
|
int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};
|
|
int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};
|
|
|
|
${n}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function EY(e,t){return`
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${t?jK(["r","c","d"],"inputShape"):xl(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}var RY=class{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){let s=w4(t,n),r=k4(e,s,n);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);let a=v4(e,s,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[r].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();let i=this.freeTextures[r].shift();return this.usedTextures[r].push(i),i}let o;return s===Nn.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===Nn.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===Nn.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===Nn.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===Nn.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[r].push(o),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),o}releaseTexture(e,t,n,s){if(this.freeTextures==null)return;let r=w4(n,s),a=k4(t,r,s);a in this.freeTextures||(this.freeTextures[a]=[]);let o=v4(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,s),i=Z().get("WEBGL_DELETE_TEXTURE_THRESHOLD");i!==-1&&this._numBytesAllocated>i?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=o):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;let l=this.usedTextures[a],c=l.indexOf(e);if(c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(c,1),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);let t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function $Y(e,t){let n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;throw new Error(`Unknown internal format ${t}`)}function v4(e,t,n,s,r){let a=DY(t,s),o;if(r){let[l,c]=ec(e[0],e[1]);o=l*c}else{let[l,c]=lp(e[0],e[1]);o=l*c}let i=$Y(n,a);return o*i}function DY(e,t){switch(e){case Nn.PACKED_2X2_FLOAT32:return hx(t);case Nn.PACKED_2X2_FLOAT16:return fx(t);case Nn.UNPACKED_FLOAT32:return cx(t);case Nn.UNPACKED_FLOAT16:return dx(t);case Nn.PACKED_4X1_UNSIGNED_BYTE:return px(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function _Y(e){return Z().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Nn.PACKED_2X2_FLOAT32:Nn.UNPACKED_FLOAT32:e?Nn.PACKED_2X2_FLOAT16:Nn.UNPACKED_FLOAT16}function w4(e,t){if(e===Ls.UPLOAD)return Nn.PACKED_2X2_FLOAT32;if(e===Ls.RENDER||e==null)return _Y(t);if(e===Ls.DOWNLOAD||e===Ls.PIXELS)return Nn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function k4(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}var Oo=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=Ws(this.outputShape.length),this.userCode=`
|
|
float unaryOperation(float x) {
|
|
${t}
|
|
}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
float y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`}},br="if (isnan(x)) return x;",PY="return x;",I4="return abs(x);",FY="return (x >= 0.0) ? x : (exp(x) - 1.0);",OY=br+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,MY=br+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,Lm="return x;",zY="return 1.0 / (1.0 + exp(-1.0 * x));",LY="return x;",BY=`
|
|
vec4 result;
|
|
|
|
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
|
|
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
|
|
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
|
|
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
|
|
|
|
return result;
|
|
`,WY=`
|
|
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
|
|
bvec4 isNaN = isnan(x);
|
|
|
|
result.r = isNaN.r ? x.r : result.r;
|
|
result.g = isNaN.g ? x.g : result.g;
|
|
result.b = isNaN.b ? x.b : result.b;
|
|
result.a = isNaN.a ? x.a : result.a;
|
|
|
|
return result;
|
|
`,VY=`
|
|
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
|
|
bvec4 isNaN = isnan(x);
|
|
|
|
result.r = isNaN.r ? x.r : result.r;
|
|
result.g = isNaN.g ? x.g : result.g;
|
|
result.b = isNaN.b ? x.b : result.b;
|
|
result.a = isNaN.a ? x.a : result.a;
|
|
|
|
return result;
|
|
`,UY="return 1.0 / (1.0 + exp(-1.0 * x));",oc=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=Ws(this.outputShape.length),this.userCode=`
|
|
vec4 unaryOperation(vec4 x) {
|
|
${t}
|
|
}
|
|
|
|
void main() {
|
|
vec4 x = getAAtOutCoords();
|
|
vec4 y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`}},GY=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;let t=e.length,n=Hn("rc",t),s=St(t),r=kY(t,n),a=n.slice(-2),o=t<=1?"rc":`vec2(${a.join(",")})`;this.userCode=`
|
|
void main() {
|
|
${s} rc = getOutputCoords();
|
|
vec4 packedInput = getA(${r});
|
|
|
|
setOutput(getChannel(packedInput, ${o}));
|
|
}
|
|
`}},HY=Zs.whereImpl,jY=1e-7,qY=1e-4,Bm={};function XY(e){return e in Bm||(Bm[e]={}),Bm[e]}var KY=Z().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),ZY=600;function YY(){return Z().global.screen==null?1024:Z().global.screen.height*Z().global.screen.width*window.devicePixelRatio*ZY/1024/1024}var ic=class extends Gl{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!Z().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){let t=Mr(Z().getNumber("WEBGL_VERSION"));this.binaryCache=XY(Z().getNumber("WEBGL_VERSION")),this.gpgpu=new zm(t),this.canvas=t.canvas,this.gpgpuCreatedLocally=!0}else this.gpgpu=e,this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=e.gl.canvas;this.textureManager=new RY(this.gpgpu),this.numMBBeforeWarning=YY(),this.texData=new Vc(this,ts())}nextDataId(){return ic.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}write(e,t,n){if((Z().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||Z().getBool("DEBUG"))&&this.checkNumericalProblems(e),n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let s={id:this.nextDataId()};return this.texData.set(s,{shape:t,dtype:n,values:e,usage:Ls.UPLOAD,refCount:1}),s}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,n,s,r){if(Z().getBool("DEBUG")&&this.checkNumericalProblems(t),s==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:s,values:t,usage:Ls.UPLOAD,refCount:r})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){let t=this.texData.get(e),{values:n,dtype:s,complexTensorInfos:r,slice:a,shape:o,isPacked:i}=t;if(a!=null){let d;i?d=new oc(o,Lm):d=new Oo(o,Lm);let p=this.runWebGLProgram(d,[{dataId:e,shape:o,dtype:s}],s),h=this.readSync(p.dataId);return this.disposeIntermediateTensorInfo(p),h}if(n!=null)return this.convertAndCacheOnCPU(e);if(s==="string")return n;let l=this.activeTimers!=null,c;l&&(c=v.now());let u;if(s==="complex64"){let d=this.readSync(r.real.dataId),p=this.readSync(r.imag.dataId);u=E.mergeRealAndImagArrays(d,p)}else u=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=v.now()-c),this.convertAndCacheOnCPU(e,u)}async read(e){if(this.pendingRead.has(e)){let h=this.pendingRead.get(e);return new Promise(f=>h.push(f))}let t=this.texData.get(e),{values:n,shape:s,slice:r,dtype:a,complexTensorInfos:o,isPacked:i}=t;if(r!=null){let h;i?h=new oc(s,Lm):h=new Oo(s,Lm);let f=this.runWebGLProgram(h,[{dataId:e,shape:s,dtype:a}],a),m=this.read(f.dataId);return this.disposeIntermediateTensorInfo(f),m}if(n!=null)return this.convertAndCacheOnCPU(e);if(!Z().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&Z().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l=null,c;if(a!=="complex64"&&Z().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(e);let h=this.texData.get(c.dataId);l=this.gpgpu.createBufferFromTexture(h.texture,...Rm(s))}this.pendingRead.set(e,[]),a!=="complex64"&&await this.gpgpu.createAndWaitForFence();let u;if(a==="complex64"){let h=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]),f=h[0],m=h[1];u=E.mergeRealAndImagArrays(f,m)}else if(l==null)u=this.getValuesFromTexture(e);else{let h=v.sizeFromShape(s);u=this.gpgpu.downloadFloat32MatrixFromBuffer(l,h)}if(c!=null&&this.disposeIntermediateTensorInfo(c),l!=null){let h=this.gpgpu.gl;Ie(h,()=>h.deleteBuffer(l))}let d=this.convertAndCacheOnCPU(e,u),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach(h=>h(d)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&ts().removeDataId(e,this),this.pendingDeletes--),d}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(s=>v.decodeString(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return We(e.shape,e.dtype,n)}checkNumericalProblems(e){if(e!=null)for(let t=0;t<e.length;t++){let n=e[t];if(!II(n))throw Z().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${n} cannot be represented on this device.`)}}getValuesFromTexture(e){let{shape:t,dtype:n,isPacked:s}=this.texData.get(e),r=v.sizeFromShape(t);if(Z().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let d=this.decode(e),p=this.texData.get(d.dataId),h=this.gpgpu.downloadMatrixFromPackedTexture(p.texture,...Rm(t)).subarray(0,r);return this.disposeIntermediateTensorInfo(d),h}let a=Z().getBool("WEBGL_PACK")&&s===!0,o=a?_m(t):t,i=a?new FZ(o):new PZ(o),l=this.runWebGLProgram(i,[{shape:o,dtype:n,dataId:e}],"float32"),c=this.texData.get(l.dataId),u=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(c.texture,c.texShape[0],c.texShape[1]).subarray(0,r);return this.disposeIntermediateTensorInfo(l),u}timerAvailable(){return Z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}async time(e){let t=this.activeTimers,n=[],s=!1;this.programTimersStack==null?(this.programTimersStack=n,s=!0):this.activeTimers.push(n),this.activeTimers=n,e();let r=v.flatten(this.activeTimers.map(i=>i.query)).filter(i=>i!=null),a=v.flatten(this.activeTimers.map(i=>i.name)).filter(i=>i!=null);this.activeTimers=t,s&&(this.programTimersStack=null);let o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};if(Z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let i=await Promise.all(r);o.kernelMs=v.sum(i),o.getExtraProfileInfo=()=>i.map((l,c)=>({name:a[c],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", ")}else o.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,o}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return Z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:v.now(),endMs:null}}endTimer(e){return Z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=v.now(),e)}async getQueryTime(e){if(Z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);let t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);let{complexTensorInfos:n}=this.texData.get(e);return n!=null&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){let{texture:t,dtype:n,texShape:s,usage:r,isPacked:a,slice:o}=this.texData.get(e),i=o&&o.origDataId||e,l=this.dataRefCount.get(i);l>1?this.dataRefCount.set(i,l-1):(this.dataRefCount.delete(i),t!=null&&(this.numBytesInGPU-=this.computeBytes(s,n),this.textureManager.releaseTexture(t,s,r,a)));let c=this.texData.get(e);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=KY){return Z().getBool("WEBGL_CPU_FORWARD")&&e.every(n=>this.texData.get(n.dataId).texture==null&&v.sizeFromShape(n.shape)<t)}getGPGPUContext(){return this.gpgpu}where(e){E.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let t=e.dataSync();return HY(e.shape,t)}packedUnaryOp(e,t,n){let s=new oc(e.shape,t),r=this.compileAndRun(s,[e],n);return ts().makeTensorFromDataId(r.dataId,r.shape,r.dtype)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){let s=y4(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,s)}if(Z().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,I4,e.dtype);let t=new Oo(e.shape,I4),n=this.compileAndRun(t,[e]);return ts().makeTensorFromDataId(n.dataId,n.shape,n.dtype)}makeTensorInfo(e,t,n){let s;if(t==="string"&&n!=null&&n.length>0&&v.isString(n[0])){let r=n.map(a=>v.encodeString(a));s=this.write(r,e,t)}else s=this.write(n,e,t);return this.texData.get(s).usage=null,{dataId:s,shape:e,dtype:t}}makeOutput(e,t,n){let{dataId:s}=this.makeTensorInfo(e,t,n);return ts().makeTensorFromDataId(s,e,t,this)}unpackTensor(e){let t=new GY(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new IY(e.shape),n=!0;return this.runWebGLProgram(t,[e],e.dtype,null,n)}packedReshape(e,t){let n=[yl(e.shape),...Al(e.shape)],s={dtype:e.dtype,shape:n,dataId:e.dataId},r=[yl(t),...Al(t)],a=new b4(r,n),o=!0,i=[n],l=this.runWebGLProgram(a,[s],e.dtype,i,o);return{dataId:l.dataId,shape:t,dtype:l.dtype}}decode(e){let t=this.texData.get(e),{isPacked:n,shape:s,dtype:r}=t,a=_m(s),o,i=Rm(a);n?o=new _Z(a):o=new DZ(a);let l=!0,c=[i],u=this.runWebGLProgram(o,[{shape:a,dtype:r,dataId:e}],r,c,l);return{dtype:r,shape:s,dataId:u.dataId}}runWebGLProgram(e,t,n,s,r=!1){let a=this.makeTensorInfo(e.outputShape,n),o=this.texData.get(a.dataId);if(e.packedOutput&&(o.isPacked=!0),e.outPackingScheme===ip.DENSE){let m=Rm(e.outputShape);o.texShape=m.map(g=>g*2)}if(e.outTexUsage!=null&&(o.usage=e.outTexUsage),v.sizeFromShape(a.shape)===0)return o.values=v.getTypedArrayFromDType(a.dtype,0),a;let i=[],l=t.map(m=>{if(m.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let g=this.texData.get(m.dataId);if(g.texture==null){if(!e.packedInputs&&v.sizeFromShape(m.shape)<=Z().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:m.shape,texData:null,isUniform:!0,uniformValues:g.values};e.packedInputs&&(g.isPacked=!0,g.shape=m.shape)}else if(!!g.isPacked!=!!e.packedInputs)m=g.isPacked?this.unpackTensor(m):this.packTensor(m),i.push(m),g=this.texData.get(m.dataId);else if(g.isPacked&&!dp(g.shape,m.shape)){let y=m,A=m.shape;m.shape=g.shape,m=this.packedReshape(m,A),i.push(m),g=this.texData.get(m.dataId),y.shape=A}return this.uploadToGPU(m.dataId),{shape:m.shape,texData:g,isUniform:!1}});this.uploadToGPU(a.dataId);let c={shape:a.shape,texData:o,isUniform:!1},u=$Z(e,l,c),d=this.getAndSaveBinary(u,()=>EZ(this.gpgpu,e,l,c)),p=this.activeTimers!=null,h;p&&(h=this.startTimer()),RZ(this.gpgpu,d,l,c,s),i.forEach(m=>this.disposeIntermediateTensorInfo(m)),p&&(h=this.endTimer(h),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(h)}));let f=Z().get("WEBGL_FLUSH_THRESHOLD");if(f>0){let m=v.now();m-this.lastGlFlushTime>f&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=m)}if(!Z().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&r===!1){let m=this.unpackTensor(a);return this.disposeIntermediateTensorInfo(a),m}return a}compileAndRun(e,t,n,s,r=!1){return n=n||t[0].dtype,this.runWebGLProgram(e,t,n,s,r)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(Z().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(t=>{this.gpgpu.deleteProgram(this.binaryCache[t].webGLProgram),delete this.binaryCache[t]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=j(()=>{if(!Z().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=Z().getBool("DEBUG");Z().set("DEBUG",!1);let t=this.abs(Ee(1e-8)).dataSync()[0];if(Z().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?jY:qY}uploadToGPU(e){let t=this.texData.get(e),{shape:n,dtype:s,values:r,texture:a,usage:o,isPacked:i}=t;if(a!=null)return;let l=this.activeTimers!=null,c;l&&(c=v.now());let u=t.texShape;if(u==null&&(u=WI(n,i),t.texShape=u),r!=null){let d=_m(n),p,h=u[1],f=u[0],m=r instanceof Uint8Array;i?([h,f]=ec(u[0],u[1]),p=new MZ(d,m)):p=new OZ(d,m);let g=this.makeTensorInfo([f,h],s);m?this.texData.get(g.dataId).usage=Ls.PIXELS:this.texData.get(g.dataId).usage=Ls.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(g.dataId),h,f,r);let y=[[f,h]],A=!0,x=this.runWebGLProgram(p,[g],s,y,A),b=this.texData.get(x.dataId);t.texture=b.texture,t.texShape=b.texShape,t.isPacked=b.isPacked,t.usage=b.usage,this.disposeIntermediateTensorInfo(g),this.texData.delete(x.dataId),t.values=null,l&&(this.uploadWaitMs+=v.now()-c)}else{let d=this.acquireTexture(u,o,s,i);t.texture=d}}convertAndCacheOnCPU(e,t){let n=this.texData.get(e),{dtype:s}=n;return this.releaseGPUData(e),t!=null&&(n.values=JY(t,s)),n.values}acquireTexture(e,t,n,s){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){let r=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${r} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,s)}computeBytes(e,t){return e[0]*e[1]*v.bytesPerElement(t)}};ic.nextDataId=0;function JY(e,t){if(t==="float32"||t==="complex64")return e;if(t==="int32"||t==="bool"){let n=t==="int32"?new Int32Array(e.length):new Uint8Array(e.length);for(let s=0;s<n.length;++s)n[s]=Math.round(e[s]);return n}else throw new Error(`Unknown dtype ${t}`)}var QY="3.9.0";function S4(){Z().set("WEBGL_FORCE_F16_TEXTURES",!0)}wu.isBrowser()&&Xi("webgl",()=>new ic,2);var eJ={forceHalfFloat:S4},C4=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,lc=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=E.assertAndGetBroadcastShape(t,n),this.enableShapeUniforms=Ws(this.outputShape.length),this.userCode=`
|
|
float binaryOperation(float a, float b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float a = getAAtOutCoords();
|
|
float b = getBAtOutCoords();
|
|
setOutput(binaryOperation(a, b));
|
|
}
|
|
`}},Wm=`
|
|
result.r = isNaN.r > 0. ? NAN : result.r;
|
|
result.g = isNaN.g > 0. ? NAN : result.g;
|
|
result.b = isNaN.b > 0. ? NAN : result.b;
|
|
result.a = isNaN.a > 0. ? NAN : result.a;
|
|
`,hp=class{constructor(e,t,n,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=E.assertAndGetBroadcastShape(t,n);let r=this.outputShape.length;this.enableShapeUniforms=Ws(r);let a="";if(s)if(r===0||v.sizeFromShape(this.outputShape)===1)a=`
|
|
result.y = 0.;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else if(a=`
|
|
${St(r)} coords = getOutputCoords();
|
|
`,r===1)this.enableShapeUniforms?a+=`
|
|
result.y = (coords + 1) >= outShape ? 0. : result.y;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`:a+=`
|
|
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else{let i=Hn("coords",r);this.enableShapeUniforms?a+=`
|
|
bool nextRowOutOfBounds =
|
|
(${i[r-2]} + 1) >= outShape[${r} - 2];
|
|
bool nextColOutOfBounds =
|
|
(${i[r-1]} + 1) >= outShape[${r} - 1];
|
|
result.y = nextColOutOfBounds ? 0. : result.y;
|
|
result.z = nextRowOutOfBounds ? 0. : result.z;
|
|
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
|
|
`:a+=`
|
|
bool nextRowOutOfBounds =
|
|
(${i[r-2]} + 1) >= ${this.outputShape[r-2]};
|
|
bool nextColOutOfBounds =
|
|
(${i[r-1]} + 1) >= ${this.outputShape[r-1]};
|
|
result.y = nextColOutOfBounds ? 0. : result.y;
|
|
result.z = nextRowOutOfBounds ? 0. : result.z;
|
|
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
|
|
`}this.userCode=`
|
|
vec4 binaryOperation(vec4 a, vec4 b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
vec4 a = getAAtOutCoords();
|
|
vec4 b = getBAtOutCoords();
|
|
|
|
vec4 result = binaryOperation(a, b);
|
|
${a}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function Cs(e){let{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}var tJ={kernelName:Ba,backendName:"webgl",kernelFunc:Cs};function Mo(e){let{inputs:t,backend:n}=e,{real:s,imag:r}=t,a=n.makeTensorInfo(s.shape,"complex64"),o=n.texData.get(a.dataId),i=Cs({inputs:{x:s},backend:n}),l=Cs({inputs:{x:r},backend:n});return o.complexTensorInfos={real:i,imag:l},a}var nJ={kernelName:jc,backendName:"webgl",kernelFunc:Mo},T4="return (a < 0.) ? b * a : a;",N4=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function sJ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{alpha:a}=s,o=n.makeTensorInfo([],"float32",v.createScalarValue(a,"float32")),i=Z().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new hp(N4,r.shape,o.shape):new lc(T4,r.shape,o.shape),l=n.runWebGLProgram(i,[r,o],r.dtype);return n.disposeIntermediateTensorInfo(o),l}var rJ={kernelName:mi,backendName:"webgl",kernelFunc:sJ},E4="return (a < 0.) ? b * a : a;",R4=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function aJ(e){let{inputs:t,backend:n}=e,{x:s,alpha:r}=t,a=Z().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new hp(R4,s.shape,r.shape):new lc(E4,s.shape,r.shape);return n.runWebGLProgram(a,[s,r],s.dtype)}var oJ={kernelName:Ja,backendName:"webgl",kernelFunc:aJ},$4="if (isnan(x)) return x;",iJ=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,lJ=`
|
|
result.r = isNaN.r > 0. ? NAN : result.r;
|
|
result.g = isNaN.g > 0. ? NAN : result.g;
|
|
result.b = isNaN.b > 0. ? NAN : result.b;
|
|
result.a = isNaN.a > 0. ? NAN : result.a;
|
|
`;function it({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:s}){return({inputs:r,backend:a})=>{let{x:o}=r,i=a,l=s||o.dtype;if(i.shouldExecuteOnCPU([o])&&n!=null){let d=i.texData.get(o.dataId),p=n(d.values,l);return i.makeTensorInfo(o.shape,l,p)}let c=Z().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,u;return c?u=new oc(o.shape,t):u=new Oo(o.shape,e),i.runWebGLProgram(u,[o],l)}}function En({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:s=!1,cpuKernelImpl:r,dtype:a}){return({inputs:o,backend:i})=>{let{a:l,b:c}=o,u=i;if(s&&l.dtype==="complex64"){let f=u.texData.get(l.dataId),m=u.texData.get(c.dataId),[g,y]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(x=>{let[b,w]=x,k={dataId:b.dataId,dtype:b.dtype,shape:l.shape},S={dataId:w.dataId,dtype:w.dtype,shape:c.shape},N=new lc(e,l.shape,c.shape);return u.runWebGLProgram(N,[k,S],Ln(b.dtype,w.dtype))}),A=Mo({inputs:{real:g,imag:y},backend:u});return u.disposeIntermediateTensorInfo(g),u.disposeIntermediateTensorInfo(y),A}let d=a||Ln(l.dtype,c.dtype);if((l.dtype==="string"||c.dtype==="string"||u.shouldExecuteOnCPU([l,c]))&&r!=null){let f=u.texData.get(l.dataId).values,m=u.texData.get(c.dataId).values,g=l.dtype==="string"?E.fromUint8ToStringArray(f):f,y=l.dtype==="string"?E.fromUint8ToStringArray(m):m,[A,x]=r(l.shape,c.shape,g,y,d),b=u.makeTensorInfo(x,d),w=u.texData.get(b.dataId);return w.values=A,b}let p=Z().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return p?h=new hp(t,l.shape,c.shape,n):h=new lc(e,l.shape,c.shape),u.runWebGLProgram(h,[l,c],d)}}function Vm(e,t=!1){if(e==="linear")return t?LY:PY;if(e==="relu")return t?WY:OY;if(e==="elu")return t?BY:FY;if(e==="relu6")return t?VY:MY;if(e==="prelu")return t?R4:E4;if(e==="leakyrelu")return t?N4:T4;if(e==="sigmoid")return t?UY:zY;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var D4=class{constructor(e,t,n,s=!1,r=!1,a=!1,o=null,i=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=Ws(this.outputShape.length);let c=s?e[1]:e[2],u=Math.ceil(c/2),d=s?"i * 2, rc.y":"rc.y, i * 2",p=r?"rc.z, i * 2":"i * 2, rc.z",h=s?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],m="",g="";o&&(i?m=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${o}
|
|
}`:l?m=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${o}
|
|
}`:m=`vec4 activation(vec4 x) {
|
|
${o}
|
|
}`,g="result = activation(result);");let y=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let A="rc.x",x="rc.x";e[0]<t[0]?A=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(x=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`
|
|
${m}
|
|
// Don't use uniform for sharedDimensionPacked for performance.
|
|
const float sharedDimension = ${u}.0;
|
|
|
|
vec4 dot2x2ARowBCol(ivec3 rc) {
|
|
vec4 result = vec4(0);
|
|
for (int i = 0; i < ${u}; i++) {
|
|
int batchA = ${A};
|
|
int batchB = ${x};
|
|
vec4 a = getMatrixA(batchA, ${d});
|
|
vec4 b = getMatrixB(batchB, ${p});
|
|
|
|
// These swizzled products need to be separately added.
|
|
// See: https://github.com/tensorflow/tfjs/issues/1735
|
|
result += (${h[0]} * ${f[0]});
|
|
result += (${h[1]} * ${f[1]});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
vec4 result = dot2x2ARowBCol(rc);
|
|
|
|
${y}
|
|
|
|
${g}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}},_4={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},P4=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=E.assertAndGetBroadcastShape(t,n),this.userCode=`
|
|
float binaryOpComplex(
|
|
float areal, float aimag, float breal, float bimag) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float areal = getARealAtOutCoords();
|
|
float aimag = getAImagAtOutCoords();
|
|
float breal = getBRealAtOutCoords();
|
|
float bimag = getBImagAtOutCoords();
|
|
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
|
|
}
|
|
`}},F4="return a * b;";function gx(e){let{inputs:t,backend:n}=e,{a:s,b:r}=t,a=E.upcastType(s.dtype,r.dtype);if(s.dtype==="complex64"){let i=n.texData.get(s.dataId),l=n.texData.get(r.dataId),c=new P4(_4.REAL,s.shape,r.shape),u=new P4(_4.IMAG,s.shape,r.shape),d=[{dataId:i.complexTensorInfos.real.dataId,dtype:i.complexTensorInfos.real.dtype,shape:s.shape},{dataId:i.complexTensorInfos.imag.dataId,dtype:i.complexTensorInfos.imag.dtype,shape:s.shape},{dataId:l.complexTensorInfos.real.dataId,dtype:l.complexTensorInfos.real.dtype,shape:r.shape},{dataId:l.complexTensorInfos.imag.dataId,dtype:l.complexTensorInfos.imag.dtype,shape:r.shape}],p=n.runWebGLProgram(c,d,"float32"),h=n.runWebGLProgram(u,d,"float32"),f=Mo({inputs:{real:p,imag:h},backend:n});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}if(n.shouldExecuteOnCPU([s,r])){let i=n.texData.get(s.dataId),l=n.texData.get(r.dataId),[c,u]=rY(s.shape,r.shape,i.values,l.values,a),d=n.makeTensorInfo(u,a),p=n.texData.get(d.dataId);return p.values=c,d}let o;return Z().getBool("WEBGL_PACK_BINARY_OPERATIONS")?o=new hp(F4,s.shape,r.shape):o=new lc(F4,s.shape,r.shape),n.runWebGLProgram(o,[s,r],a)}var uJ={kernelName:Ka,backendName:"webgl",kernelFunc:gx};function cJ(e,t,n){let s=[yl(e.shape),...Al(e.shape)],r={dtype:e.dtype,shape:s,dataId:e.dataId},a=[yl(t),...Al(t)],o=new b4(a,s),i=!0,l=[s],c=n.runWebGLProgram(o,[r],e.dtype,l,i);return{dataId:c.dataId,shape:t,dtype:c.dtype}}function be(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{shape:a}=s,o=n,i=v.sizeFromShape(r.shape),l=v.inferFromImplicitShape(a,i),c=v.sizeFromShape(l);v.assert(i===c,()=>`The new shape (${l}) has ${c} elements and the old shape (${r.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);let u=o.texData.get(r.dataId);return u.isPacked&&!dp(r.shape,l)&&!(u.texture!==null&&dp(u.shape,l))?cJ(r,l,o):(o.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype})}var dJ={kernelName:Ti,backendName:"webgl",kernelFunc:be},O4=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:s,inSize:r,outSize:a}=e;this.outputShape=[s,a];let o=Math.floor(n/4)*4,i=n%4,l="sumValue += dot(values, ones);";if(t!=null){let u=1/t;l=`sumValue += dot(values * ${v.isInt(u)?u.toPrecision(2):u}, ones);`}let c="";r%n>0&&(c=`
|
|
if (inIdx < 0 || inIdx >= ${r}) {
|
|
return 0.0;
|
|
}
|
|
`),this.userCode=`
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${c}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${n};
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < ${o}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${l}
|
|
}
|
|
|
|
int inIdx = inOffset + ${o};
|
|
if (${i===1}) {
|
|
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
|
|
|
|
${l}
|
|
} else if (${i===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1), 0.0, 0.0);
|
|
|
|
${l}
|
|
} else if (${i===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2), 0.0);
|
|
|
|
${l}
|
|
}
|
|
setOutput(sumValue);
|
|
}
|
|
`}},pJ=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:s,inSize:r,outSize:a}=e;this.outputShape=[s,a];let o="0.0",i="";t==="prod"?o="1.0":t==="min"?(o="1.0 / 1e-20",i="min"):t==="max"&&(o="-1.0 / 1e-20",i="max");let l=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?l="sumValue":t==="prod"?l="prodValue":t==="all"?l="allValue":t==="any"&&(l="anyValue");let c=Math.floor(n/4)*4,u=n%4,d=`
|
|
if (${t==="sum"}) {
|
|
sumValue += dot(values, ones);
|
|
} else if (${t==="prod"}) {
|
|
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
|
|
prodValue *= tmp[0] * tmp[1];
|
|
} else {
|
|
minMaxValue = ${i}(values, minMaxValue);
|
|
if (${t==="min"} || ${t==="max"}) {
|
|
minMaxValue = ${i}(values, minMaxValue);
|
|
bvec4 isNaN = isnan(values);
|
|
if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
|
|
minMaxValue = vec4(NAN);
|
|
}
|
|
}
|
|
}
|
|
`,p="vec4";t==="all"?(o="1.0",d=`
|
|
bool reducedAllValue = all(values);
|
|
float floatedReducedAllValue = float(reducedAllValue);
|
|
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
|
|
`,p="bvec4"):t==="any"&&(o="0.0",d=`
|
|
bool reducedAnyValue = any(values);
|
|
float floatedReducedAnyValue = float(reducedAnyValue);
|
|
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
|
|
`,p="bvec4");let h="";r%n>0&&(h=`
|
|
if (inIdx < 0 || inIdx >= ${r}) {
|
|
return initializationValue;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = ${o};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${h}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${n};
|
|
|
|
vec4 minMaxValue = vec4(${o});
|
|
float prodValue = 1.0;
|
|
float sumValue = 0.0;
|
|
float allValue = 1.0;
|
|
float anyValue = 0.0;
|
|
|
|
for (int i = 0; i < ${c}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${d}
|
|
}
|
|
|
|
int inIdx = inOffset + ${c};
|
|
if (${u===1}) {
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${d}
|
|
} else if (${u===2}) {
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${d}
|
|
} else if (${u===3}) {
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
${d}
|
|
}
|
|
setOutput(${l});
|
|
}
|
|
`}};function hJ(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let n=t.length?t[t.length-1].outSize:e[1],s=E.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:s,outSize:Math.ceil(n/s)})}return t}function vl(e,t,n,s){let r=hJ(e.shape),a=e;for(let o=0;o<r.length;o++){let{inSize:i,windowSize:l,outSize:c}=r[o],u,d;n==="mean"?u=o===0?new O4({windowSize:l,inSize:i,batchSize:e.shape[0],outSize:c},i):new O4({windowSize:l,inSize:i,batchSize:e.shape[0],outSize:c}):u=new pJ({windowSize:l,inSize:i,batchSize:e.shape[0],outSize:c},n),d=a,a=s.runWebGLProgram(u,[a],t),d.dataId!==e.dataId&&s.disposeIntermediateTensorInfo(d)}return a}var fJ=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[t[a]];this.outputShape=n,this.rank=n.length;let s=St(this.rank),r=mJ(t);this.userCode=`
|
|
void main() {
|
|
${s} resRC = getOutputCoords();
|
|
setOutput(getA(${r}));
|
|
}
|
|
`}};function mJ(e){let t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],s=new Array(t);for(let r=0;r<e.length;r++)s[e[r]]=n[r];return s.join()}var gJ=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let n=new Array(e.length);for(let c=0;c<n.length;c++)n[c]=e[t[c]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let s=St(this.rank),r=x4("rc",this.rank),a=new Array(this.rank);for(let c=0;c<t.length;c++)a[t[c]]=r[c];let o=`vec2(${a.slice(-2).join()})`,i=`++${r[this.rank-1]} < ${n[this.rank-1]}`,l=`getChannel(getA(${a.join()}), ${o})`;this.userCode=`
|
|
void main() {
|
|
${s} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result[0] = ${l};
|
|
if(${i}) {
|
|
result[1] = ${l};
|
|
}
|
|
--${r[this.rank-1]};
|
|
if(++${r[this.rank-2]} < ${n[this.rank-2]}) {
|
|
result[2] = ${l};
|
|
if(${i}) {
|
|
result[3] = ${l};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function Um(e,t,n){let s=Z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new gJ(e.shape,t):new fJ(e.shape,t);return n.runWebGLProgram(s,[e],e.dtype)}function yJ(e,t,n,s){let r=t,a=e.shape.length,o=v.parseAxisParam(r,e.shape),i=o,l=E.getAxesPermutation(i,a),c=l!=null,u=e;c&&(u=Um(e,l,s),i=E.getInnerMostAxes(i.length,a)),E.assertAxesAreInnerMostDims("sum",i,a);let[d,p]=E.computeOutAndReduceShapes(u.shape,i),h=d;n&&(h=E.expandShapeToKeepDim(d,o));let f=v.sizeFromShape(p),g=v.sizeFromShape(e.shape)/f,y=be({inputs:{x:u},attrs:{shape:[g,f]},backend:s}),A=fd(e.dtype),x=vl(y,A,"sum",s),b=be({inputs:{x},attrs:{shape:h},backend:s});return s.disposeIntermediateTensorInfo(y),s.disposeIntermediateTensorInfo(x),c&&s.disposeIntermediateTensorInfo(u),b}function Gm(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;return yJ(r,a,o,n)}var AJ={kernelName:oo,backendName:"webgl",kernelFunc:Gm};function jn(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{perm:a}=s,o=n,i=r.shape.length,l=new Array(i);for(let u=0;u<l.length;u++)l[u]=r.shape[a[u]];let c;if(o.shouldExecuteOnCPU([r])){let d=o.texData.get(r.dataId).values,p=mx(d,r.shape,r.dtype,a,l);c=o.makeTensorInfo(l,r.dtype);let h=o.texData.get(c.dataId);h.values=p}else c=Um(r,a,o);return c}var xJ={kernelName:po,backendName:"webgl",kernelFunc:jn},M4=1e3;function Hm({a:e,b:t,transposeA:n,transposeB:s,backend:r,bias:a=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:l=null}){let c=e.shape.length,u=t.shape.length,d=n?e.shape[c-2]:e.shape[c-1],p=s?t.shape[u-1]:t.shape[u-2],h=n?e.shape[c-1]:e.shape[c-2],f=s?t.shape[u-2]:t.shape[u-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=v.sizeFromShape(m),A=v.sizeFromShape(g),x=y===A||y===1||A===1;v.assert(c>=2&&u>=2&&x,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${m}) and (${g}).`);let w=(y>A?e.shape.slice(0,-2):t.shape.slice(0,-2)).concat([h,f]);v.assert(d===p,()=>`Error in matMul: inner shapes (${d}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${s} must match.`);let k=n?[y,d,h]:[y,h,d],S=s?[A,f,p]:[A,p,f],N=be({inputs:{x:e},backend:r,attrs:{shape:k}}),$=be({inputs:{x:t},backend:r,attrs:{shape:S}}),F=[N,$],R=Math.max(y,A),D=n?N.shape[1]:N.shape[2],T=a!=null,O=o!=null,B=l==="leakyrelu",H=l!=null?Vm(l,!0):null,z=T||O||B||H!=null,X;if((h===1||f===1)&&D>M4&&z===!1){let J=N,Q=$;n&&(J=jn({inputs:{x:N},backend:r,attrs:{perm:[0,2,1]}}),F.push(J)),s&&(Q=jn({inputs:{x:$},backend:r,attrs:{perm:[0,2,1]}}),F.push(Q));let ne=f!==1,K=f===1,oe=J;ne&&(oe=be({inputs:{x:J},backend:r,attrs:{shape:[R,D,1]}}),F.push(oe));let ce=f===1?2:1,he=Q;K&&(he=be({inputs:{x:Q},backend:r,attrs:{shape:[R,1,D]}}),F.push(he));let Ae=gx({inputs:{a:oe,b:he},backend:r});X=Gm({inputs:{x:Ae},backend:r,attrs:{axis:ce,keepDims:!0}}),F.push(Ae)}else{let J=Ln(e.dtype,t.dtype),Q=new D4(k,S,[R,h,f],n,s,T,H,O,B),ne=[N,$];if(a!=null&&ne.push(a),O&&ne.push(o),B){let K=r.makeTensorInfo([],"float32",v.createScalarValue(i,"float32"));ne.push(K),F.push(K)}X=r.runWebGLProgram(Q,ne,J)}let ee=be({inputs:{x:X},backend:r,attrs:{shape:w}});F.push(X);for(let J of F)r.disposeIntermediateTensorInfo(J);return ee}function bJ(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:d}=s;return Hm({a:r,b:a,transposeA:l,transposeB:c,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:d,activation:u})}var vJ={kernelName:fo,backendName:"webgl",kernelFunc:bJ},z4="return abs(x);";function wJ(e){let{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])&&s.dtype!=="complex64"){let a=n.texData.get(s.dataId),o=y4(a.values);return n.makeTensorInfo(s.shape,s.dtype,o)}let r;return Z().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new oc(s.shape,z4):r=new Oo(s.shape,z4),n.runWebGLProgram(r,[s],s.dtype)}var kJ={kernelName:ni,backendName:"webgl",kernelFunc:wJ},IJ=br+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,SJ=it({opSnippet:IJ}),CJ={kernelName:ql,backendName:"webgl",kernelFunc:SJ},TJ=br+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,NJ=it({opSnippet:TJ}),EJ={kernelName:Xl,backendName:"webgl",kernelFunc:NJ},L4="return a + b;",RJ=En({opSnippet:L4,packedOpSnippet:L4,supportsComplex:!0,cpuKernelImpl:LZ}),$J={kernelName:qr,backendName:"webgl",kernelFunc:RJ},DJ=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((r,a)=>`T${a}`);let n=[];this.variableNames.forEach(r=>{n.push(`float v${r} = get${r}AtOutCoords();`)});let s=this.variableNames.map(r=>`v${r}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${n.join(`
|
|
`)}
|
|
|
|
float result = ${s};
|
|
setOutput(result);
|
|
}
|
|
`}},_J=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((r,a)=>`T${a}`);let n=[];this.variableNames.forEach(r=>{n.push(`vec4 v${r} = get${r}AtOutCoords();`)});let s=this.variableNames.map(r=>`v${r}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${n.join(`
|
|
`)}
|
|
|
|
vec4 result = ${s};
|
|
setOutput(result);
|
|
}
|
|
`}};function jm(e){let{inputs:t,backend:n}=e,s=t;if(s.length===1)return Cs({inputs:{x:s[0]},backend:n});if(s.length>Z().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let l=Math.floor(s.length/2),c=jm({inputs:s.slice(0,l),backend:n}),u=jm({inputs:s.slice(l),backend:n});return jm({inputs:[c,u],backend:n})}let r=s.map(l=>l.dtype).reduce((l,c)=>Ln(l,c)),a=s.map(l=>l.shape),i=Z().getBool("WEBGL_PACK")?new _J(s[0].shape,a):new DJ(s[0].shape,a);return n.runWebGLProgram(i,s,r)}var PJ={kernelName:wa,backendName:"webgl",kernelFunc:jm};function FJ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s,i=r.shape.length,l=v.parseAxisParam(a,r.shape),c=l,u=E.getAxesPermutation(c,i),d=r;u!=null&&(d=jn({inputs:{x:r},backend:n,attrs:{perm:u}}),c=E.getInnerMostAxes(c.length,i)),E.assertAxesAreInnerMostDims("all",c,i);let[p,h]=E.computeOutAndReduceShapes(d.shape,c),f=v.sizeFromShape(h),m=be({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=vl(m,m.dtype,"all",n),y;if(o){let A=E.expandShapeToKeepDim(p,l);y=be({inputs:{x:g},backend:n,attrs:{shape:A}})}else y=be({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(d),y}var OJ={kernelName:Kl,backendName:"webgl",kernelFunc:FJ};function MJ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s,i=r.shape.length,l=v.parseAxisParam(a,r.shape),c=l,u=E.getAxesPermutation(c,i),d=r;u!=null&&(d=jn({inputs:{x:r},backend:n,attrs:{perm:u}}),c=E.getInnerMostAxes(c.length,i)),E.assertAxesAreInnerMostDims("any",c,i);let[p,h]=E.computeOutAndReduceShapes(d.shape,c),f=v.sizeFromShape(h),m=be({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=vl(m,m.dtype,"any",n),y;if(o){let A=E.expandShapeToKeepDim(p,l);y=be({inputs:{x:g},backend:n,attrs:{shape:A}})}else y=be({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(d),y}var zJ={kernelName:Zl,backendName:"webgl",kernelFunc:MJ},LJ=class{constructor(e,t,n){this.variableNames=["A"];let{windowSize:s,batchSize:r,outSize:a}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[r,a];let o=t==="max"?">":"<",i=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${s};
|
|
|
|
int bestIndex = inOffset;
|
|
float bestValue = getA(batch, bestIndex);
|
|
|
|
for (int i = 0; i < ${s}; i++) {
|
|
int inIdx = ${i};
|
|
float candidate = getA(batch, inIdx);
|
|
if (candidate ${o} bestValue) {
|
|
bestValue = candidate;
|
|
bestIndex = inIdx;
|
|
}
|
|
}
|
|
setOutput(float(bestIndex));
|
|
}
|
|
`}},BJ=class{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,v.assert(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);let r=e[e.length-1],a=Math.ceil(r/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),s||this.variableNames.push("bestIndicesA");let o=this.outputShape,i=o.length,l=St(i),c=Hn("coords",i),u,d;if(a===1){d=i+1;let S=St(d);u=`
|
|
${S} sourceLocR = ${S}(${c.join()}, 0);
|
|
++${c[i-1]};
|
|
${S} sourceLocG = ${S}(${c.join()}, 0);
|
|
++${c[i-2]};
|
|
${S} sourceLocA = ${S}(${c.join()}, 0);
|
|
--${c[i-1]};
|
|
${S} sourceLocB = ${S}(${c.join()}, 0);
|
|
--${c[i-2]};`}else d=i,u=`
|
|
${l} sourceLocR = coords;
|
|
++${c[i-1]};
|
|
${l} sourceLocG = coords;
|
|
++${c[i-2]};
|
|
${l} sourceLocA = coords;
|
|
--${c[i-1]};
|
|
${l} sourceLocB = coords;
|
|
--${c[i-2]};`;let p=["x","y","z","w","u","v"].slice(0,d),h="."+p[d-1],f=p.map(S=>"int "+S),m=Hn("sourceLocR",d-1).concat("inIdx.r"),g=Hn("sourceLocG",d-1).concat("inIdx.g"),y=Hn("sourceLocB",d-1).concat("inIdx.b"),A=Hn("sourceLocA",d-1).concat("inIdx.a"),x=n==="max"?"greaterThan":"lessThan",b=s?"":`
|
|
inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),
|
|
getBestIndicesAChannel(${g.join()}),
|
|
getBestIndicesAChannel(${y.join()}),
|
|
getBestIndicesAChannel(${A.join()})));`,w=`vec4(
|
|
getAChannel(${m.join()}),
|
|
hasNextCol ? getAChannel(${g.join()}) : 0.,
|
|
hasNextRow ? getAChannel(${y.join()}) : 0.,
|
|
hasNextRow && hasNextCol ? getAChannel(${A.join()}) : 0.)`,k=s?"":`
|
|
float getBestIndicesAChannel(${f.join()}) {
|
|
return getChannel(getBestIndicesA(${p.join()}),
|
|
vec2(${p.slice(-2).join()}));
|
|
}`;this.userCode=`
|
|
float getAChannel(${f.join()}) {
|
|
return getChannel(getA(${p.join()}),
|
|
vec2(${p.slice(-2).join()}));
|
|
}
|
|
${k}
|
|
void main() {
|
|
${l} coords = getOutputCoords();
|
|
bool hasNextCol = ${c[i-1]} < ${o[i-1]-1};
|
|
bool hasNextRow = ${c[i-2]} < ${o[i-2]-1};
|
|
${u}
|
|
ivec4 srcIdx = ivec4(sourceLocR${h}, sourceLocG${h},
|
|
sourceLocB${h}, sourceLocA${h}) * ${t};
|
|
ivec4 inIdx = srcIdx;
|
|
vec4 bestIndex = vec4(inIdx);
|
|
vec4 bestValue = ${w};
|
|
|
|
for (int i = 0; i < ${t}; i++) {
|
|
inIdx = srcIdx;
|
|
${b}
|
|
vec4 candidate = ${w};
|
|
bvec4 nan = isnan(candidate);
|
|
bvec4 replace = bvec4(
|
|
vec4(${x}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
|
|
|
|
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
|
|
replace.y ? candidate.y : bestValue.y,
|
|
replace.z ? candidate.z : bestValue.z,
|
|
replace.w ? candidate.w : bestValue.w);
|
|
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
|
|
srcIdx++;
|
|
}
|
|
setOutput(bestIndex);
|
|
}
|
|
`}};function B4(e,t,n,s=null){let r=t.shape[0],a=t.shape[1];s!=null&&(r=s.shape[0],a=s.shape[1]);let o=E.computeOptimalWindowSize(a),i={windowSize:o,inSize:a,batchSize:r,outSize:Math.ceil(a/o)},l=new LJ(i,n,s==null),c=[t];s!=null&&c.push(s);let u=e.runWebGLProgram(l,c,"int32");if(u.shape[1]===1)return u;let d=B4(e,t,n,u);return e.disposeIntermediateTensorInfo(u),d}function W4(e,t,n,s=null){let r=s!=null?s.shape:t.shape,a=r[r.length-1],o=E.computeOptimalWindowSize(a),i=new BJ(r,o,n,s==null),l=s==null?[t]:[t,s],c=e.runWebGLProgram(i,l,"int32");if(c.shape.length===t.shape.length){let u=W4(e,t,n,c);return e.disposeIntermediateTensorInfo(c),u}return c}function V4(e,t,n,s){let r=[n];if(E.assertAxesAreInnerMostDims("arg"+s.charAt(0).toUpperCase()+s.slice(1),r,t.shape.length),!Z().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let a=[],o=e.texData.get(t.dataId),i=o!==null&&o.isPacked,l=t;i&&(l=e.unpackTensor(t),a.push(l));let[c,u]=E.computeOutAndReduceShapes(l.shape,r),d=v.sizeFromShape(u),p=be({inputs:{x:l},backend:e,attrs:{shape:[-1,d]}});a.push(p);let h=B4(e,p,s);a.push(h);let f=be({inputs:{x:h},backend:e,attrs:{shape:c}});return a.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}return W4(e,t,s)}function WJ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s,o=v.parseAxisParam(a,r.shape),i=E.getAxesPermutation(o,r.shape.length),l=r,c=[];i!=null&&(l=jn({inputs:{x:r},backend:n,attrs:{perm:i}}),c.push(l),o=E.getInnerMostAxes(o.length,l.shape.length)),E.assertAxesAreInnerMostDims("argMax",[o[0]],l.shape.length);let u=V4(n,l,o[0],"max");return c.forEach(d=>n.disposeIntermediateTensorInfo(d)),u}var VJ={kernelName:ka,backendName:"webgl",kernelFunc:WJ};function UJ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s,o=v.parseAxisParam(a,r.shape),i=E.getAxesPermutation(o,r.shape.length),l=r,c=[];i!=null&&(l=jn({inputs:{x:r},backend:n,attrs:{perm:i}}),c.push(l),o=E.getInnerMostAxes(o.length,l.shape.length)),E.assertAxesAreInnerMostDims("argMin",[o[0]],l.shape.length);let u=V4(n,l,o[0],"min");return c.forEach(d=>n.disposeIntermediateTensorInfo(d)),u}var GJ={kernelName:Yl,backendName:"webgl",kernelFunc:UJ},HJ=br+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,jJ=it({opSnippet:HJ}),qJ={kernelName:Jl,backendName:"webgl",kernelFunc:jJ},XJ=br+"return log(x + sqrt(x * x + 1.0));",KJ=it({opSnippet:XJ}),ZJ={kernelName:Ql,backendName:"webgl",kernelFunc:KJ},YJ=br+`
|
|
return atan(x);
|
|
`,JJ=it({opSnippet:YJ}),QJ={kernelName:eu,backendName:"webgl",kernelFunc:JJ},eQ=iJ+`
|
|
return atan(a, b);
|
|
`,tQ=`
|
|
vec4 result = atan(a, b);
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+lJ+`
|
|
return result;
|
|
`,nQ=En({opSnippet:eQ,packedOpSnippet:tQ}),sQ={kernelName:nu,backendName:"webgl",kernelFunc:nQ},rQ=br+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,aQ=it({opSnippet:rQ}),oQ={kernelName:tu,backendName:"webgl",kernelFunc:aQ},fp=class{constructor(e,t,n,s=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideHeight,i=e.strideWidth,l=e.dilationHeight,c=e.dilationWidth,u=e.effectiveFilterHeight,d=e.effectiveFilterWidth,p=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;let f=t==="avg",m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,y="0.0";if(f||(y="-1.0 / 1e-20"),n){let S=">=";this.userCode=`
|
|
const ivec2 strides = ivec2(${o}, ${i});
|
|
const ivec2 pads = ivec2(${p}, ${h});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// max/min x(?, ?, d) to get y(yR, yC, d).
|
|
// ? = to be determined
|
|
float minMaxValue = 0.0;
|
|
float minMaxValueFound = 0.0;
|
|
int minMaxPosition = 0;
|
|
float avgValue = 0.0;
|
|
|
|
for (int wR = 0; wR < ${u};
|
|
wR += ${l}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${d};
|
|
wC += ${c}) {
|
|
int xC = xCCorner + wC;
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float value = getX(batch, xR, xC, d);
|
|
|
|
// If a min / max value has already been found, use it. If not,
|
|
// use the current value.
|
|
float currMinMaxValue = mix(
|
|
value, minMaxValue, minMaxValueFound);
|
|
if (value ${S} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${s?r?m:g:`wR * ${d} + wC`};
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let A="max",x=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(x="avgValue / count");let b=Math.floor(a/4)*4,w=a%4,k=`
|
|
if (${f}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${A}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec2 strides = ivec2(${o}, ${i});
|
|
const ivec2 pads = ivec2(${p}, ${h});
|
|
const float initializationValue = ${y};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float count = 0.0;
|
|
|
|
float getValue(int batch, int xR, int xC, int d) {
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
return initializationValue;
|
|
}
|
|
count += 1.0;
|
|
return getX(batch, xR, xC, d);
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// max/min x(?, ?, d) to get y(yR, yC, d).
|
|
// ? = to be determined
|
|
vec4 minMaxValue = vec4(${y});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wR = 0; wR < ${u};
|
|
wR += ${l}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${b}; wC += 4) {
|
|
int xC = xCCorner + wC * ${c};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${c}, d),
|
|
getValue(batch, xR, xC + 2 * ${c}, d),
|
|
getValue(batch, xR, xC + 3 * ${c}, d)
|
|
);
|
|
|
|
${k}
|
|
}
|
|
|
|
int xC = xCCorner + ${b};
|
|
if (${w===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${k}
|
|
} else if (${w===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${c}, d),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${k}
|
|
} else if (${w===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${c}, d),
|
|
getValue(batch, xR, xC + 2 * ${c}, d),
|
|
initializationValue
|
|
);
|
|
|
|
${k}
|
|
}
|
|
}
|
|
setOutput(${x});
|
|
}
|
|
`}},yx=class{constructor(e,t,n,s=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideDepth,i=e.strideHeight,l=e.strideWidth,c=e.dilationDepth,u=e.dilationHeight,d=e.dilationWidth,p=e.effectiveFilterDepth,h=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;let A=t==="avg",x="0.0";if(A||(x="-1.0 / 1e-20"),n){let $=">=";this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${o}, ${i}, ${l});
|
|
const ivec3 pads = ivec3(${m}, ${g}, ${y});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xDCorner = xCorner.x;
|
|
int xRCorner = xCorner.y;
|
|
int xCCorner = xCorner.z;
|
|
|
|
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
|
|
// ? = to be determined
|
|
float minMaxValue = 0.0;
|
|
float minMaxValueFound = 0.0;
|
|
int minMaxPosition = 0;
|
|
|
|
for (int wD = 0; wD < ${p};
|
|
wD += ${c}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${h};
|
|
wR += ${u}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${f};
|
|
wC += ${d}) {
|
|
int xC = xCCorner + wC;
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float value = getX(batch, xD, xR, xC, ch);
|
|
|
|
// If a min / max value has already been found, use it. If not,
|
|
// use the current value.
|
|
float currMinMaxValue = mix(
|
|
value, minMaxValue, minMaxValueFound);
|
|
if (value ${$} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${s?r?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${h} * ${f} +
|
|
wR * ${f} + wC`};
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let b="max",w=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(w="avgValue / count");let k=Math.floor(a/4)*4,S=a%4,N=`
|
|
if (${A}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${b}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${o}, ${i}, ${l});
|
|
const ivec3 pads = ivec3(${m}, ${g}, ${y});
|
|
const float initializationValue = ${x};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float count = 0.0;
|
|
|
|
float getValue(int batch, int xD, int xR, int xC, int ch) {
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
return initializationValue;
|
|
}
|
|
count += 1.0;
|
|
return getX(batch, xD, xR, xC, ch);
|
|
}
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xDCorner = xCorner.x;
|
|
int xRCorner = xCorner.y;
|
|
int xCCorner = xCorner.z;
|
|
|
|
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
|
|
// ? = to be determined
|
|
vec4 minMaxValue = vec4(${x});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wD = 0; wD < ${p};
|
|
wD += ${c}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${h};
|
|
wR += ${u}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${k}; wC += 4) {
|
|
int xC = xCCorner + wC * ${d};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${d}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${d}, ch),
|
|
getValue(batch, xD, xR, xC + 3 * ${d}, ch)
|
|
);
|
|
|
|
${N}
|
|
}
|
|
|
|
int xC = xCCorner + ${k};
|
|
if (${S===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${N}
|
|
} else if (${S===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${d}, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${N}
|
|
} else if (${S===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${d}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${d}, ch),
|
|
initializationValue
|
|
);
|
|
|
|
${N}
|
|
}
|
|
}
|
|
setOutput(${w});
|
|
}
|
|
}
|
|
`}};function iQ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t;tc(r,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,c=1;v.assert(E.eitherStridesOrDilationsAreOne(o,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);let u=E.computePool2DInfo(r.shape,a,o,c,i,l);if(u.filterWidth===1&&u.filterHeight===1&&v.arraysEqual(u.inShape,u.outShape))return Cs({inputs:{x:r},backend:n});let d=new fp(u,"avg",!1);return n.runWebGLProgram(d,[r],"float32")}var lQ={kernelName:Ia,backendName:"webgl",kernelFunc:iQ};function uQ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l,dataFormat:c}=s,u=[1,1,1],d=E.computePool3DInfo(r.shape,a,o,u,i,l,c),p=new yx(d,"avg",!1);return n.runWebGLProgram(p,[r],"float32")}var cQ={kernelName:Hc,backendName:"webgl",kernelFunc:uQ},dQ=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,r=e.strideWidth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterHeight,l=e.effectiveFilterWidth,c=i-1-e.padInfo.top,u=l-1-e.padInfo.left,d=1/(t*n);this.userCode=`
|
|
const ivec2 pads = ivec2(${c}, ${u});
|
|
const float avgMultiplier = float(${d});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 dyRCCorner = coords.yz - pads;
|
|
int dyRCorner = dyRCCorner.x;
|
|
int dyCCorner = dyRCCorner.y;
|
|
|
|
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${i};
|
|
wR += ${a}) {
|
|
float dyR = float(dyRCorner + wR) / ${s}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${l};
|
|
wC+= ${o}) {
|
|
float dyC = float(dyCCorner + wC) / ${r}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(b, idyR, idyC, d);
|
|
|
|
dotProd += dyValue * avgMultiplier;
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},pQ=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,r=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,l=e.dilationHeight,c=e.dilationWidth,u=e.effectiveFilterDepth,d=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=u-1-e.padInfo.front,f=d-1-e.padInfo.top,m=p-1-e.padInfo.left,g=1/(t*n*s);this.userCode=`
|
|
const ivec3 pads = ivec3(${h}, ${f}, ${m});
|
|
const float avgMultiplier = float(${g});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
|
|
// dx(xD, xR, xC, ch).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int wD = 0; wD < ${u};
|
|
wD += ${i}) {
|
|
float dyD = float(dyDCorner + wD) / ${r}.0;
|
|
|
|
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyD = int(dyD);
|
|
|
|
for (int wR = 0; wR < ${d};
|
|
wR += ${l}) {
|
|
float dyR = float(dyRCorner + wR) / ${a}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${p};
|
|
wC += ${c}) {
|
|
float dyC = float(dyCCorner + wC) / ${o}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
|
|
dotProd += dyValue * avgMultiplier;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function hQ(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,o=a,{filterSize:i,strides:l,pad:c,dimRoundingMode:u}=s,d=[1,1,1],p=E.computePool3DInfo(o.shape,i,l,d,c,u),h=new pQ(p);return n.runWebGLProgram(h,[r],o.dtype)}var fQ={kernelName:mh,backendName:"webgl",kernelFunc:hQ};function mQ(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,o=a;tc([r,a],"avgPoolGrad");let{filterSize:i,strides:l,pad:c}=s,u=E.computePool2DInfo(o.shape,i,l,1,c),d=new dQ(u);return n.runWebGLProgram(d,[r],o.dtype)}var gQ={kernelName:fh,backendName:"webgl",kernelFunc:mQ};function yQ(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:o,transposeB:i}=s;return Hm({a:r,b:a,transposeA:o,transposeB:i,backend:n})}var AQ={kernelName:Sa,backendName:"webgl",kernelFunc:yQ},xQ=class{constructor(e,t,n,s,r,a){this.outputShape=[],this.variableNames=["x","mean","variance"],E.assertAndGetBroadcastShape(e,t),E.assertAndGetBroadcastShape(e,n);let o="0.0";s!=null&&(E.assertAndGetBroadcastShape(e,s),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="1.0";r!=null&&(E.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
float x = getXAtOutCoords();
|
|
float mean = getMeanAtOutCoords();
|
|
float variance = getVarianceAtOutCoords();
|
|
float offset = ${o};
|
|
float scale = ${i};
|
|
float inv = scale * inversesqrt(variance + float(${a}));
|
|
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
|
|
}
|
|
`}},bQ=class{constructor(e,t,n,s,r,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],E.assertAndGetBroadcastShape(e,t),E.assertAndGetBroadcastShape(e,n);let o="vec4(0.0)";s!=null&&(E.assertAndGetBroadcastShape(e,s),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="vec4(1.0)";r!=null&&(E.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
vec4 offset = ${o};
|
|
vec4 scale = ${i};
|
|
|
|
vec4 x = getXAtOutCoords();
|
|
vec4 mean = getMeanAtOutCoords();
|
|
vec4 variance = getVarianceAtOutCoords();
|
|
|
|
vec4 inv = scale * inversesqrt(variance + vec4(${a}));
|
|
|
|
setOutput((x - mean) * inv + offset);
|
|
}
|
|
`}},vQ=({inputs:e,backend:t,attrs:n})=>{let{x:s,mean:r,variance:a,offset:o,scale:i}=e;v.assert(r.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),v.assert(o==null||r.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),v.assert(i==null||r.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=n;l==null&&(l=.001);let c=[s,r,a],u=null;o!=null&&(u=o.shape,c.push(o));let d=null;i!=null&&(d=i.shape,c.push(i));let p=Z().getBool("WEBGL_PACK_NORMALIZATION")?new bQ(s.shape,r.shape,a.shape,u,d,l):new xQ(s.shape,r.shape,a.shape,u,d,l);return t.runWebGLProgram(p,c,c[0].dtype)},wQ={kernelName:za,backendName:"webgl",kernelFunc:vQ},kQ=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=St(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let n=IQ(this.rank),s,r=e.map((a,o)=>`sourceLoc.${Ax[o]} = start[${o}] + coords.${Ax[o]};`);s=`
|
|
${t} sourceLoc;
|
|
${t} coords = getOutputCoords();
|
|
${r.join(`
|
|
`)}
|
|
`,this.userCode=`
|
|
void main() {
|
|
${s}
|
|
setOutput(getSource(${n}));
|
|
}
|
|
`}},Ax=["x","y","z","w","u","v"];function IQ(e){if(e===1)return"sourceLoc";if(e<=6)return Ax.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var SQ=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let t=St(this.rank),n=Hn("coords",this.rank),s=Hn("sourceLoc",this.rank),r=this.rank===1?"sourceLoc":`vec2(${s.slice(-2).join()})`,a=`getChannel(getSource(${s.join()}), ${r})`,o=`
|
|
result.x = ${a};
|
|
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${s[this.rank-1]};
|
|
result.y = ${a};
|
|
--${s[this.rank-1]};
|
|
}
|
|
`,i=this.rank===1?"":`
|
|
--${n[this.rank-1]};
|
|
if (++${n[this.rank-2]} < ${e[this.rank-2]}) {
|
|
++${s[this.rank-2]};
|
|
result.z = ${a};
|
|
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${s[this.rank-1]};
|
|
result.w = ${a};
|
|
}
|
|
}
|
|
`,l=this.rank<=4?`sourceLoc = coords +
|
|
${t}(${e.map((c,u)=>`start[${u}]`).join()});`:e.map((c,u)=>`${s[u]} = ${n[u]} + start[${u}];`).join(`
|
|
`);this.userCode=`
|
|
void main() {
|
|
${t} coords = getOutputCoords();
|
|
${t} sourceLoc;
|
|
${l}
|
|
vec4 result = vec4(0.);
|
|
${o}
|
|
${i}
|
|
setOutput(result);
|
|
}
|
|
`}};function CQ(e,t,n,s){let r=s.texData.get(e.dataId),a=s.makeTensorInfo(n,e.dtype),o=s.texData.get(a.dataId);Object.assign(o,r),o.refCount=1,o.shape=n,o.dtype=e.dtype;let i=yn.computeFlatOffset(t,v.computeStrides(e.shape));r.slice&&(i+=r.slice.flatOffset),o.slice={flatOffset:i,origDataId:r.slice&&r.slice.origDataId||e.dataId};let l=s.dataRefCount.get(o.slice.origDataId)||1;return s.dataRefCount.set(o.slice.origDataId,l+1),a}function uc(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:o}=s,[i,l]=yn.parseSliceParams(r,a,o);if(yn.assertParamsValid(r,i,l),v.sizeFromShape(l)===0)return n.makeTensorInfo(l,r.dtype,[]);if(n.shouldExecuteOnCPU([r])||r.dtype==="string"){let d=n.texData.get(r.dataId),p=dY(d.values,i,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,p)}let{isPacked:c}=n.texData.get(r.dataId),u=yn.isSliceContinous(r.shape,i,l);if(c||!u){let d=Z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new SQ(l):new kQ(l),p=[i];return n.runWebGLProgram(d,[r],r.dtype,p)}return n.uploadToGPU(r.dataId),CQ(r,i,l,n)}var TQ={kernelName:Di,backendName:"webgl",kernelFunc:uc},NQ=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:o}=s;v.assert(r.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((A,x)=>A*x),l=E.getReshaped(r.shape,a,i),c=E.getPermuted(l.length,a.length),u=E.getReshapedPermuted(r.shape,a,i),d=E.getSliceBeginCoords(o,a.length),p=E.getSliceSize(u,o,a.length),h=[],f=be({inputs:{x:r},backend:n,attrs:{shape:l}}),m=jn({inputs:{x:f},backend:n,attrs:{perm:c}}),g=be({inputs:{x:m},backend:n,attrs:{shape:u}}),y=uc({inputs:{x:g},backend:n,attrs:{begin:d,size:p}});return h.push(f),h.push(m),h.push(g),h.forEach(A=>n.disposeIntermediateTensorInfo(A)),y},EQ={kernelName:si,backendName:"webgl",kernelFunc:NQ};function RQ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:o}=s,i=n.readSync(r.dataId),l=n.readSync(a.dataId),c=g4(i,l,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,c)}var $Q={kernelName:gh,backendName:"webgl",kernelFunc:RQ},DQ="return float(a != b);",U4=En({opSnippet:DQ,cpuKernelImpl:oY,dtype:"bool"}),_Q={kernelName:bi,backendName:"webgl",kernelFunc:U4};function mp(e){let{inputs:t,backend:n}=e,{input:s}=t,r=n.texData.get(s.dataId);return Cs({inputs:{x:r.complexTensorInfos.real},backend:n})}var PQ={kernelName:td,backendName:"webgl",kernelFunc:mp},FQ="return float(int(x));";function OQ(e,t){let n=new Oo(e.shape,FQ),s=t.runWebGLProgram(n,[e],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}function xx(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dtype:a}=s;if(a==="complex64"){if(r.dtype==="complex64")return Cs({inputs:{x:r},backend:n});let o=qt(r.shape),i=xx({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=Mo({inputs:{real:i,imag:o},backend:n});return o.dispose(),n.disposeIntermediateTensorInfo(i),l}if(r.dtype==="complex64"){let o=mp({inputs:{input:r},backend:n}),i=xx({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(o),i}if(!v.hasEncodingLoss(r.dtype,a)){let o=Cs({inputs:{x:r},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32")return OQ(r,n);if(a==="bool"){let o=n.makeTensorInfo([],"bool",v.getTypedArrayFromDType("bool",1)),l=U4({inputs:{a:r,b:o},backend:n});return n.disposeIntermediateTensorInfo(o),l}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${a}`)}var MQ={kernelName:Ca,backendName:"webgl",kernelFunc:xx},G4="return ceil(x);",zQ=it({opSnippet:G4,packedOpSnippet:G4,cpuKernelImpl:WZ}),LQ={kernelName:Ta,backendName:"webgl",kernelFunc:zQ},BQ=class{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=`
|
|
|
|
void main() {
|
|
float value = getAAtOutCoords();
|
|
if (isnan(value)) {
|
|
setOutput(value);
|
|
return;
|
|
}
|
|
|
|
setOutput(clamp(value, minVal, maxVal));
|
|
}
|
|
`}},WQ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
vec4 value = getAAtOutCoords();
|
|
|
|
if (any(isnan(value))) {
|
|
setOutput(value);
|
|
return;
|
|
}
|
|
|
|
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
|
|
}
|
|
`}};function VQ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{clipValueMin:a,clipValueMax:o}=s,i;Z().getBool("WEBGL_PACK_CLIP")?i=new WQ(r.shape):i=new BQ(r.shape);let l=[[a],[o]];return n.runWebGLProgram(i,[r],r.dtype,l)}var UQ={kernelName:Xr,backendName:"webgl",kernelFunc:VQ},GQ=class{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
float re = abs(getRealAtOutCoords());
|
|
float im = abs(getImagAtOutCoords());
|
|
float mx = max(re, im);
|
|
|
|
// sadly the length function in glsl is not underflow-safe
|
|
// (at least not on Intel GPUs). So the safe solution is
|
|
// to ensure underflow-safety in all cases.
|
|
setOutput(
|
|
mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
|
|
);
|
|
}
|
|
`}};function H4(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function HQ(e){let{inputs:t,backend:n}=e,{x:s}=t,r=n.texData.get(s.dataId),a=new GQ(s.shape),o=[H4(s,r.complexTensorInfos.real),H4(s,r.complexTensorInfos.imag)];return n.runWebGLProgram(a,o,o[0].dtype)}var jQ={kernelName:qc,backendName:"webgl",kernelFunc:HQ},qQ=class{constructor(e){this.outputShape=[],this.outputShape=E.computeOutShape(e,1),this.variableNames=e.map((a,o)=>`T${o}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let a=1;a<t.length;a++)t[a]=t[a-1]+e[a][1];let n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let a=1;a<t.length;a++){let o=t[a-1];n.push(`else if (yC < ${t[a]}) setOutput(getT${a}(yR, yC-${o}));`)}let s=t.length,r=t[t.length-1];n.push(`else setOutput(getT${s}(yR, yC-${r}));`),this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int yR = coords.x;
|
|
int yC = coords.y;
|
|
|
|
${n.join(`
|
|
`)}
|
|
}
|
|
`}},XQ=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=E.computeOutShape(e,t);let n=this.outputShape,s=n.length,r=St(s),a=Hn("coords",s),o=["x","y","z","w","u","v"].slice(0,s);this.variableNames=e.map((f,m)=>`T${m}`);let i=new Array(e.length-1);i[0]=e[0][t];for(let f=1;f<i.length;f++)i[f]=i[f-1]+e[f][t];let l=o[t],c=o.slice(-2),u=o.join(),d=`if (${l} < ${i[0]}) {
|
|
return getChannel(
|
|
getT0(${u}), vec2(${c.join()}));
|
|
}`;for(let f=1;f<i.length;f++){let m=i[f-1];d+=`
|
|
if (${l} < ${i[f]} && ${l} >= ${i[f-1]}) {
|
|
return getChannel(
|
|
getT${f}(${qm(o,l,m)}),
|
|
vec2(${qm(c,l,m)}));
|
|
}`}let p=i.length,h=i[i.length-1];d+=`
|
|
return getChannel(
|
|
getT${p}(${qm(o,l,h)}),
|
|
vec2(${qm(c,l,h)}));`,this.userCode=`
|
|
float getValue(${o.map(f=>"int "+f)}) {
|
|
${d}
|
|
}
|
|
|
|
void main() {
|
|
${r} coords = getOutputCoords();
|
|
vec4 result = vec4(getValue(${a}), 0., 0., 0.);
|
|
|
|
${a[s-1]} = ${a[s-1]} + 1;
|
|
if (${a[s-1]} < ${n[s-1]}) {
|
|
result.g = getValue(${a});
|
|
}
|
|
|
|
${a[s-2]} = ${a[s-2]} + 1;
|
|
if (${a[s-2]} < ${n[s-2]}) {
|
|
result.a = getValue(${a});
|
|
}
|
|
|
|
${a[s-1]} = ${a[s-1]} - 1;
|
|
if (${a[s-2]} < ${n[s-2]} &&
|
|
${a[s-1]} < ${n[s-1]}) {
|
|
result.b = getValue(${a});
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function qm(e,t,n){let s=e.indexOf(t);return e.map((a,o)=>o===s?`${a} - ${n}`:a).join()}function Xm(e){let{inputs:t,backend:n}=e,{input:s}=t,r=n.texData.get(s.dataId);return Cs({inputs:{x:r.complexTensorInfos.imag},backend:n})}var KQ={kernelName:Yc,backendName:"webgl",kernelFunc:Xm};function cc(e,t,n){let s=e[0].dtype;if(s==="complex64"){let u=e.map(m=>mp({inputs:{input:m},backend:n})),d=e.map(m=>Xm({inputs:{input:m},backend:n})),p=cc(u,t,n),h=cc(d,t,n),f=Mo({inputs:{real:p,imag:h},backend:n});return u.forEach(m=>n.disposeIntermediateTensorInfo(m)),d.forEach(m=>n.disposeIntermediateTensorInfo(m)),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}let r=n.shouldExecuteOnCPU(e);if(s==="string"&&(r=!0),r){let u=e.map(y=>{let A=v.sizeFromShape(y.shape.slice(t));return be({inputs:{x:y},backend:n,attrs:{shape:[-1,A]}})}),d=u.map(y=>({vals:n.readSync(y.dataId),shape:y.shape})),p=E.computeOutShape(u.map(y=>y.shape),1),h=u[0].shape[0]===1,f=VZ(d,p,s,h),m=E.computeOutShape(e.map(y=>y.shape),t),g=n.makeTensorInfo(m,s,f);return u.forEach(y=>n.disposeIntermediateTensorInfo(y)),g}if(e.length>Z().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let u=Math.floor(e.length/2),d=cc(e.slice(0,u),t,n),p=cc(e.slice(u),t,n),h=cc([d,p],t,n);return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),h}if(Z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){let u=new XQ(e.map(d=>d.shape),t);return n.runWebGLProgram(u,e,s)}let{tensors2D:a,outShape:o}=ZQ(e,t,n),i=new qQ(a.map(u=>u.shape)),l=n.runWebGLProgram(i,a,s);a.forEach(u=>n.disposeIntermediateTensorInfo(u));let c=be({inputs:{x:l},attrs:{shape:o},backend:n});return n.disposeIntermediateTensorInfo(l),c}function ZQ(e,t,n){let s=E.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>be({inputs:{x:a},attrs:{shape:[-1,v.sizeFromShape(a.shape.slice(t))]},backend:n})),outShape:s}}function j4(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s,a=v.parseAxisParam(r,t[0].shape)[0],o=E.computeOutShape(t.map(c=>c.shape),a);if(v.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(c=>v.sizeFromShape(c.shape)>0);if(i.length===1)return Cs({inputs:{x:i[0]},backend:n});let l=i.map(c=>c.shape);return E.assertParamsConsistent(l,a),cc(i,a,n)}var YQ={kernelName:ri,backendName:"webgl",kernelFunc:j4},q4=class{constructor(e,t=!1,n=null,s=!1,r=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let a=e.padInfo.top,o=e.padInfo.left,i=e.strideHeight,l=e.strideWidth,c=e.dilationHeight,u=e.dilationWidth,d=e.filterHeight,p=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4,m=e.dataFormat==="channelsLast",g=m?1:2,y=m?2:3,A=m?3:1,x="",b="";n&&(s?x=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:r?x=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:x=`
|
|
float activation(float x) {
|
|
${n}
|
|
}
|
|
`,b="result = activation(result);");let w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${x}
|
|
|
|
const ivec2 strides = ivec2(${i}, ${l});
|
|
const ivec2 pads = ivec2(${a}, ${o});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d2 = coords[${A}];
|
|
|
|
ivec2 xRCCorner =
|
|
ivec2(coords[${g}], coords[${y}]) * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${d}; wR++) {
|
|
int xR = xRCorner + wR * ${c};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${p}; wC++) {
|
|
int xC = xCCorner + wC * ${u};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${h}; d1 += 4) {
|
|
vec4 wValues = vec4(
|
|
getW(wR, wC, d1, d2),
|
|
getW(wR, wC, d1 + 1, d2),
|
|
getW(wR, wC, d1 + 2, d2),
|
|
getW(wR, wC, d1 + 3, d2)
|
|
);
|
|
|
|
if (${m}) {
|
|
vec4 xValues = vec4(
|
|
getX(batch, xR, xC, d1),
|
|
getX(batch, xR, xC, d1 + 1),
|
|
getX(batch, xR, xC, d1 + 2),
|
|
getX(batch, xR, xC, d1 + 3)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec4 xValues = vec4(
|
|
getX(batch, d1, xR, xC),
|
|
getX(batch, d1 + 1, xR, xC),
|
|
getX(batch, d1 + 2, xR, xC),
|
|
getX(batch, d1 + 3, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
}
|
|
|
|
if (${f===1}) {
|
|
|
|
if (${m}) {
|
|
dotProd +=
|
|
getX(batch, xR, xC, ${h}) *
|
|
getW(wR, wC, ${h}, d2);
|
|
} else {
|
|
dotProd +=
|
|
getX(batch, ${h}, xR, xC) *
|
|
getW(wR, wC, ${h}, d2);
|
|
}
|
|
|
|
} else if (${f===2}) {
|
|
vec2 wValues = vec2(
|
|
getW(wR, wC, ${h}, d2),
|
|
getW(wR, wC, ${h} + 1, d2)
|
|
);
|
|
|
|
if (${m}) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xR, xC, ${h}),
|
|
getX(batch, xR, xC, ${h} + 1)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec2 xValues = vec2(
|
|
getX(batch, ${h}, xR, xC),
|
|
getX(batch, ${h} + 1, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
} else if (${f===3}) {
|
|
vec3 wValues = vec3(
|
|
getW(wR, wC, ${h}, d2),
|
|
getW(wR, wC, ${h} + 1, d2),
|
|
getW(wR, wC, ${h} + 2, d2)
|
|
);
|
|
|
|
if (${m}) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xR, xC, ${h}),
|
|
getX(batch, xR, xC, ${h} + 1),
|
|
getX(batch, xR, xC, ${h} + 2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec3 xValues = vec3(
|
|
getX(batch, ${h}, xR, xC),
|
|
getX(batch, ${h} + 1, xR, xC),
|
|
getX(batch, ${h} + 2, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
${w}
|
|
${b}
|
|
setOutput(result);
|
|
}
|
|
`}},JQ=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,n=e.padInfo.top,s=e.padInfo.left,r=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,l=e.dilationHeight,c=e.dilationWidth,u=e.filterDepth,d=e.filterHeight,p=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4;this.userCode=`
|
|
const ivec3 strides = ivec3(${r}, ${a}, ${o});
|
|
const ivec3 pads = ivec3(${t}, ${n}, ${s});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d2 = coords.u;
|
|
|
|
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xFCorner = xFRCCorner.x;
|
|
int xRCorner = xFRCCorner.y;
|
|
int xCCorner = xFRCCorner.z;
|
|
|
|
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
|
|
// y(yF, yR, yC, d2). ? = to be determined. : = across all
|
|
// values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wF = 0; wF < ${u}; wF++) {
|
|
int xF = xFCorner + wF * ${i};
|
|
|
|
if (xF < 0 || xF >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${d}; wR++) {
|
|
int xR = xRCorner + wR * ${l};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${p}; wC++) {
|
|
int xC = xCCorner + wC * ${c};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${h}; d1 += 4) {
|
|
vec4 xValues = vec4(
|
|
getX(batch, xF, xR, xC, d1),
|
|
getX(batch, xF, xR, xC, d1 + 1),
|
|
getX(batch, xF, xR, xC, d1 + 2),
|
|
getX(batch, xF, xR, xC, d1 + 3)
|
|
);
|
|
vec4 wValues = vec4(
|
|
getW(wF, wR, wC, d1, d2),
|
|
getW(wF, wR, wC, d1 + 1, d2),
|
|
getW(wF, wR, wC, d1 + 2, d2),
|
|
getW(wF, wR, wC, d1 + 3, d2)
|
|
);
|
|
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
if (${f===1}) {
|
|
dotProd +=
|
|
getX(batch, xF, xR, xC, ${h}) *
|
|
getW(wF, wR, wC, ${h}, d2);
|
|
} else if (${f===2}) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xF, xR, xC, ${h}),
|
|
getX(batch, xF, xR, xC, ${h} + 1)
|
|
);
|
|
vec2 wValues = vec2(
|
|
getW(wF, wR, wC, ${h}, d2),
|
|
getW(wF, wR, wC, ${h} + 1, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else if (${f===3}) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xF, xR, xC, ${h}),
|
|
getX(batch, xF, xR, xC, ${h} + 1),
|
|
getX(batch, xF, xR, xC, ${h} + 2)
|
|
);
|
|
vec3 wValues = vec3(
|
|
getW(wF, wR, wC, ${h}, d2),
|
|
getW(wF, wR, wC, ${h} + 1, d2),
|
|
getW(wF, wR, wC, ${h} + 2, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},QQ=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=Ws(this.outputShape.length);let{dataFormat:n}=t,s=Gn(),r=n==="channelsLast",a=r?0:1,o=r?1:2,i=this.enableShapeUniforms?"if(blockIndex < outShape[1] && pos < outShape[0]) {":`if(blockIndex < ${e[1]} && pos < ${e[0]}) {`,l="";for(let c=0;c<=1;c++)for(let u=0;u<=1;u++)l+=`
|
|
blockIndex = rc.y + ${u};
|
|
pos = rc.x + ${c};
|
|
|
|
${i}
|
|
offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
|
|
d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
|
|
|
|
if(d0 < inputShape[${a}] && d0 >= 0) {
|
|
// Use custom imod instead mod. On Intel GPU, mod may generate
|
|
// unexpected value.
|
|
// https://github.com/tensorflow/tfjs/issues/5447
|
|
offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];
|
|
d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /
|
|
inChannels);
|
|
|
|
if(d1 < inputShape[${o}] && d1 >= 0) {
|
|
|
|
ch = imod(pos, inChannels);
|
|
|
|
if (${r}) {
|
|
innerDims = vec2(d1, ch);
|
|
result[${c*2+u}] = getChannel(
|
|
getA(d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[${c*2+u}] = getChannel(
|
|
getA(ch, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
`;this.userCode=`
|
|
void main() {
|
|
ivec2 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0);
|
|
|
|
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
|
|
vec2 innerDims;
|
|
|
|
${l}
|
|
|
|
${s.output} = result;
|
|
}
|
|
`}};function X4({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let l=e.shape,c=s.texData.get(e.dataId),u=n.inChannels,d=l[0]*l[1]*l[2],p=n.outChannels,h=n.dataFormat==="channelsLast",f=!1,m=!1,g,y=[];if(!((d===1||p===1)&&u>M4)&&c.isPacked&&h&&c.texture!=null&&l[2]%2!=0&&v.arraysEqual(c.shape.slice(-3),l.slice(-3))){let b=l[0]*l[1]*(l[2]+1),w={dataId:e.dataId,shape:[1,b,n.inChannels],dtype:e.dtype},k=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,v.assert(dp(c.shape,w.shape),()=>`packed reshape ${c.shape} to ${w.shape} isn't free`);let S=be({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}});y.push(S);let N=Hm({a:w,b:S,backend:s,transposeA:f,transposeB:m,bias:r,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),$=s.texData.get(N.dataId);v.assert($.isPacked,()=>"batchMatMul result is expected to be packed"),c.shape=k,$.shape=n.outShape,g=Cs({inputs:{x:N},backend:s}),g.shape=n.outShape,y.push(N)}else{let b=h?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],w=be({inputs:{x:e},backend:s,attrs:{shape:[1,b,n.inChannels]}}),k=be({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}}),S=Hm({a:w,b:k,transposeA:f,transposeB:m,backend:s,bias:r,activation:i,preluActivationWeights:a,leakyreluAlpha:o});g=be({inputs:{x:S},backend:s,attrs:{shape:n.outShape}}),y.push(w),y.push(k),y.push(S)}for(let b of y)s.disposeIntermediateTensorInfo(b);return g}function K4({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:l,filterHeight:c,inChannels:u,outWidth:d,outHeight:p,dataFormat:h}=n,f=h==="channelsLast",m=l*c*u,g=p*d,y=[m,g],A=!0,x=!1,b=[],w=be({inputs:{x:e},backend:s,attrs:{shape:e.shape.slice(1)}}),k=be({inputs:{x:t},backend:s,attrs:{shape:[1,m,v.sizeFromShape(t.shape)/m]}});b.push(w),b.push(k);let S=new QQ(y,n),N=[w.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],$=s.runWebGLProgram(S,[w],"float32",N),F=be({inputs:{x:$},backend:s,attrs:{shape:[1,y[0],y[1]]}});b.push($),b.push(F);let R=r!=null,D=a!=null,T=i==="leakyrelu",O=i?Vm(i,!0):null,B=new D4(F.shape,k.shape,[1,g,n.outChannels],A,x,R,O,D,T),H=[F,k];if(r&&H.push(r),D&&H.push(a),T){let J=s.makeTensorInfo([],"float32",v.createScalarValue(o,"float32"));H.push(J),b.push(J)}let z=s.runWebGLProgram(B,H,"float32"),X=f?[1,p,d,n.outChannels]:[1,n.outChannels,p,d],ee=be({inputs:{x:z},backend:s,attrs:{shape:X}});b.push(z);for(let J of b)s.disposeIntermediateTensorInfo(J);return ee}function eee(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dataFormat:l,dilations:c,dimRoundingMode:u}=s,d=E.convertConv2DDataFormat(l),p=E.computeConv2DInfo(r.shape,a.shape,o,c,i,u,!1,d),h;if(p.filterHeight===1&&p.filterWidth===1&&p.dilationHeight===1&&p.dilationWidth===1&&p.strideHeight===1&&p.strideWidth===1&&(p.padInfo.type==="SAME"||p.padInfo.type==="VALID"))h=X4({x:r,filter:a,convInfo:p,backend:n});else if(Z().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)h=K4({x:r,filter:a,convInfo:p,backend:n});else{let m=new q4(p);h=n.runWebGLProgram(m,[r,a],"float32")}let f=be({inputs:{x:h},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(h),f}var tee={kernelName:Na,backendName:"webgl",kernelFunc:eee},nee=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,r=e.padInfo.left,a=e.dataFormat==="channelsLast";this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int wR = coords.x;
|
|
int wC = coords.y;
|
|
int d1 = coords.z;
|
|
int d2 = coords.w;
|
|
|
|
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int b = 0; b < ${e.batchSize}; b++) {
|
|
for (int yR = 0; yR < ${e.outHeight}; yR++) {
|
|
int xR = wR + yR * ${t} - ${s};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${n} - ${r};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
if (${a}) {
|
|
float dyValue = getDy(b, yR, yC, d2);
|
|
float xValue = getX(b, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);
|
|
} else {
|
|
float dyValue = getDy(b, d2, yR, yC);
|
|
float xValue = getX(b, d1, xR, xC);
|
|
dotProd += (xValue * dyValue);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},see=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,r=e.strideWidth,a=e.dataFormat==="channelsLast",o=t-1-e.padInfo.top,i=n-1-e.padInfo.left,l=a?1:2,c=a?2:3,u=a?3:1;this.userCode=`
|
|
const ivec2 pads = ivec2(${o}, ${i});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[${u}];
|
|
|
|
ivec2 dyCorner = ivec2(coords[${l}], coords[${c}]) - pads;
|
|
int dyRCorner = dyCorner.x;
|
|
int dyCCorner = dyCorner.y;
|
|
|
|
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${t}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / ${s}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${t} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${n}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${r}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${n} - 1 - wC;
|
|
|
|
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
|
|
|
|
if (${a}) {
|
|
float xValue = getDy(batch, idyR, idyC, d2);
|
|
float wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
} else {
|
|
float xValue = getDy(batch, d2, idyR, idyC);
|
|
float wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},ree=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,r=e.padInfo.front,a=e.padInfo.top,o=e.padInfo.left;this.userCode=`
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int wF = coords.x;
|
|
int wR = coords.y;
|
|
int wC = coords.z;
|
|
int d1 = coords.w;
|
|
int d2 = coords.u;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
for (int b = 0; b < ${e.batchSize}; b++) {
|
|
for (int yF = 0; yF < ${e.outDepth}; yF++) {
|
|
int xF = wF + yF * ${t} - ${r};
|
|
|
|
if (xF < 0 || xF >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yR = 0; yR < ${e.outHeight}; yR++) {
|
|
int xR = wR + yR * ${n} - ${a};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${s} - ${o};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float dyValue = getDy(b, yF, yR, yC, d2);
|
|
float xValue = getX(b, xF, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},aee=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,r=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=t-1-e.padInfo.front,l=n-1-e.padInfo.top,c=s-1-e.padInfo.left;this.userCode=`
|
|
const ivec3 pads = ivec3(${i}, ${l}, ${c});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d1 = coords.u;
|
|
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyFCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
float dotProd = 0.0;
|
|
for (int wF = 0; wF < ${t}; wF++) {
|
|
float dyF = float(dyFCorner + wF) / ${r}.0;
|
|
|
|
if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyF = int(dyF);
|
|
|
|
int wFPerm = ${t} - 1 - wF;
|
|
|
|
for (int wR = 0; wR < ${n}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / ${a}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${n} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${s}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${o}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${s} - 1 - wC;
|
|
|
|
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
|
|
float xValue = getDy(batch, idyF, idyR, idyC, d2);
|
|
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function oee(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:o,pad:i,dataFormat:l,dimRoundingMode:c,filterShape:u}=s,d=E.convertConv2DDataFormat(l),p=E.computeConv2DInfo(r.shape,u,o,1,i,c,!1,d),h=new nee(p);return n.runWebGLProgram(h,[r,a],"float32")}var iee={kernelName:yh,backendName:"webgl",kernelFunc:oee};function lee(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{inputShape:o,strides:i,pad:l,dataFormat:c,dimRoundingMode:u}=s,d=E.convertConv2DDataFormat(c),p=E.computeConv2DInfo(o,a.shape,i,1,l,u,!1,d),h=new see(p);return n.runWebGLProgram(h,[r,a],"float32")}var uee={kernelName:Ea,backendName:"webgl",kernelFunc:lee};function cee(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dilations:l}=s,c=E.computeConv3DInfo(r.shape,a.shape,o,l,i),u=new JQ(c);return n.runWebGLProgram(u,[r,a],"float32")}var dee={kernelName:Xc,backendName:"webgl",kernelFunc:cee};function pee(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:o,pad:i,filterShape:l}=s,c=E.computeConv3DInfo(r.shape,l,o,1,i),u=new ree(c);return n.runWebGLProgram(u,[r,a],"float32")}var hee={kernelName:Ah,backendName:"webgl",kernelFunc:pee};function fee(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{pad:o,strides:i,inputShape:l}=s,c=E.computeConv3DInfo(l,a.shape,i,1,o),u=new aee(c);return n.runWebGLProgram(u,[r,a],"float32")}var mee={kernelName:xh,backendName:"webgl",kernelFunc:fee},gee=$4+`
|
|
return cos(x);
|
|
`,yee=it({opSnippet:gee}),Aee={kernelName:Ra,backendName:"webgl",kernelFunc:yee},xee=`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,bee=it({opSnippet:xee}),vee={kernelName:$a,backendName:"webgl",kernelFunc:bee},wee=class{constructor(e,t,n,s,r){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[a,o,i,l]=e,[c]=t,[u,d]=n;this.outputShape=[c,u,d,l];let p=s==="bilinear"?1:0,[h,f]=[`${o-1}.0`,`${i-1}.0`],[m,g,y]=u>1?[`${(o-1)/(u-1)}`,"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${h}`],[A,x,b]=d>1?[`${(i-1)/(d-1)}`,"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=`
|
|
const float height_ratio = float(${m});
|
|
const float width_ratio = float(${A});
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int y = coords[1];
|
|
int x = coords[2];
|
|
int d = coords[3];
|
|
|
|
// get box vals
|
|
float y1 = getBoxes(b,0);
|
|
float x1 = getBoxes(b,1);
|
|
float y2 = getBoxes(b,2);
|
|
float x2 = getBoxes(b,3);
|
|
|
|
// get image in batch index
|
|
int bInd = round(getBoxInd(b));
|
|
if(bInd < 0 || bInd >= ${a}) {
|
|
return;
|
|
}
|
|
|
|
float height_scale = ${g};
|
|
float width_scale = ${x};
|
|
|
|
float in_y = ${y};
|
|
if( in_y < 0.0 || in_y > ${h} ) {
|
|
setOutput(float(${r}));
|
|
return;
|
|
}
|
|
float in_x = ${b};
|
|
if( in_x < 0.0 || in_x > ${f} ) {
|
|
setOutput(float(${r}));
|
|
return;
|
|
}
|
|
|
|
vec2 sourceFracIndexCR = vec2(in_x,in_y);
|
|
if(${p} == 1) {
|
|
// Compute the four integer indices.
|
|
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
|
|
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
|
|
|
|
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
|
|
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
|
|
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
|
|
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
|
|
|
|
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
|
|
|
|
float top = topLeft + (topRight - topLeft) * fracCR.x;
|
|
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
|
|
float newValue = top + (bottom - top) * fracCR.y;
|
|
setOutput(newValue);
|
|
} else {
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec2 sourceNearestCR = ivec2(floor(
|
|
sourceFracIndexCR + vec2(0.5,0.5)));
|
|
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
|
|
setOutput(newValue);
|
|
}
|
|
}
|
|
`}},kee=e=>{let{inputs:t,backend:n,attrs:s}=e,{image:r,boxes:a,boxInd:o}=t,{cropSize:i,method:l,extrapolationValue:c}=s,u=new wee(r.shape,a.shape,i,l,c);return n.runWebGLProgram(u,[r,a,o],"float32")},Iee={kernelName:oi,backendName:"webgl",kernelFunc:kee},Z4=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}],this.outputShape=e;let s=e.length,r=t?"0.0":`getX(${Y4(s,"coords")})`,a=e[e.length-1],o="",i="";t?(o=n?`end != ${a-1}`:"end != 0",i=n?"end + 1":"end - 1"):(o=n?`end + pow2 < ${a}`:"end >= pow2",i=n?"end + pow2":"end - pow2"),this.userCode=`
|
|
void main() {
|
|
${St(s)} coords = getOutputCoords();
|
|
int end = ${J4(s,"coords")};
|
|
float val = ${r};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${o}) {
|
|
int idx = ${i};
|
|
${J4(s,"coords")} = idx;
|
|
val += getX(${Y4(s,"coords")});
|
|
}
|
|
setOutput(val);
|
|
}
|
|
`}};function Y4(e,t){if(e===1)return`${t}`;if(e===2)return`${t}.x, ${t}.y`;if(e===3)return`${t}.x, ${t}.y, ${t}.z`;if(e===4)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}function J4(e,t){if(e===1)return`${t}`;if(e===2)return`${t}.y`;if(e===3)return`${t}.z`;if(e===4)return`${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}function See(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:o,reverse:i}=s,l=r.shape.length,c=E.getAxesPermutation([a],l),u=r;c!=null&&(u=jn({inputs:{x:r},backend:n,attrs:{perm:c}}));let d=E.getInnerMostAxes(1,l)[0];if(d!==l-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${r.shape.length-1} but got axis=${a}`);let p=u.shape[d],h=Cs({inputs:{x:u},backend:n});for(let f=0;f<=Math.ceil(Math.log2(p))-1;f++){let m=new Z4(u.shape,!1,i),g=[[f]],y=h;h=n.runWebGLProgram(m,[h],h.dtype,g),n.disposeIntermediateTensorInfo(y)}if(o){let f=new Z4(u.shape,o,i),m=h;h=n.runWebGLProgram(f,[h],h.dtype),n.disposeIntermediateTensorInfo(m)}if(c!=null){let f=E.getUndoAxesPermutation(c),m=jn({inputs:{x:h},backend:n,attrs:{perm:f}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(u),m}return h}var Cee={kernelName:ai,backendName:"webgl",kernelFunc:See};function Tee(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:o,binaryOutput:i}=s;if(r.shape.length===1){let l=n.readSync(r.dataId),c=n.readSync(a.dataId),u=g4(l,c,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,u)}else if(r.shape.length===2){let l=n.bufferSync(r),c=n.bufferSync(a),u=BZ(l,c,o,i);return n.makeTensorInfo(u.shape,a.dtype,u.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}var Nee={kernelName:bh,backendName:"webgl",kernelFunc:Tee},Eee=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int h = ${this.getHeightCoordString()};
|
|
int w = ${this.getWidthCoordString()};
|
|
int d = ${this.getDepthCoordString()};
|
|
|
|
int in_h = h / ${t};
|
|
int offset_h = imod(h, ${t});
|
|
int in_w = w / ${t};
|
|
int offset_w = imod(w, ${t});
|
|
int offset_d = (offset_h * ${t} + offset_w) *
|
|
${this.getOutputDepthSize()};
|
|
int in_d = d + offset_d;
|
|
|
|
float result = ${this.getInputSamplingString()};
|
|
setOutput(result);
|
|
}
|
|
`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}};function Ree(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockSize:a,dataFormat:o}=s;v.assert(a>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${a}`);let i=r.shape[0],l=o==="NHWC"?r.shape[1]:r.shape[2],c=o==="NHWC"?r.shape[2]:r.shape[3],u=o==="NHWC"?r.shape[3]:r.shape[1],d=l*a,p=c*a,h=u/(a*a),f=o==="NHWC"?[i,d,p,h]:[i,h,d,p],m=new Eee(f,a,o);return n.runWebGLProgram(m,[r],r.dtype)}var $ee={kernelName:ii,backendName:"webgl",kernelFunc:Ree},Q4=class{constructor(e,t=!1,n=null,s=!1,r=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Ws(this.outputShape.length);let a=e.filterHeight,o=e.filterWidth,i=e.outChannels/e.inChannels,l="",c="";n&&(s?l=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:r?l=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:l=`
|
|
float activation(float x) {
|
|
${n}
|
|
}
|
|
`,c="result = activation(result);");let u=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${l}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int d2 = coords.w;
|
|
int d1 = d2 / ${i};
|
|
int q = d2 - d1 * ${i};
|
|
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
|
|
for (int wR = 0; wR < ${a}; wR++) {
|
|
int xR = xRCorner + wR * dilations[0];
|
|
|
|
if (xR < 0 || xR >= inDims[0]) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${o}; wC++) {
|
|
int xC = xCCorner + wC * dilations[1];
|
|
|
|
if (xC < 0 || xC >= inDims[1]) {
|
|
continue;
|
|
}
|
|
|
|
float xVal = getX(batch, xR, xC, d1);
|
|
float wVal = getW(wR, wC, d1, q);
|
|
dotProd += xVal * wVal;
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
${u}
|
|
${c}
|
|
setOutput(result);
|
|
}
|
|
`}},eS=class{constructor(e,t=!1,n=null,s=!1,r=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Ws(this.outputShape.length);let a=e.outChannels/e.inChannels,o=e.padInfo.left,i=e.strideWidth,l=e.dilationWidth,c=e.filterHeight,u=e.filterWidth,d=u,p=`
|
|
int xR; int xC; int xCOffset;
|
|
vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<u;g++)p+=`
|
|
vec4 xTexelC${g*2};
|
|
int xTexelC${g*2}Ready;
|
|
vec4 xTexelC${g*2+1};
|
|
int xTexelC${g*2+1}Ready;
|
|
vec4 xC${g};`;for(let g=0;g<c;g++){for(let y=0;y<u;y++)p+=`
|
|
xTexelC${y*2} = vec4(0.0);
|
|
xTexelC${y*2}Ready = 0;
|
|
xTexelC${y*2+1} = vec4(0.0);
|
|
xTexelC${y*2+1}Ready = 0;
|
|
xC${y} = vec4(0.0);`;p+=`
|
|
xR = xRCorner + ${g} * dilations[0];
|
|
if (xR >=0 && xR < inDims[0]) {
|
|
`;for(let y=0;y<(d+1)/2;y++){let A=y*2;if(p+=`
|
|
xC = xCCorner + ${A*l};
|
|
`,i===1){if(A<u&&(o%2==1?(p+=`
|
|
xCOffset = xC + 1;
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${A}Ready == 0) {
|
|
xTexelC${A} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${A}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${A}Ready = 1;
|
|
}
|
|
`,l===1&&A>0?p+=`
|
|
xC${A} = vec4(xTexelC${A-2}.zw, xTexelC${A}.xy);
|
|
`:p+=`
|
|
xCOffset = xC + 1 - 2;
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
previous = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
previous.zw = vec2(0.0);
|
|
}
|
|
|
|
xC${A} = vec4(previous.zw, xTexelC${A}.xy);
|
|
} else {
|
|
xC${A} = vec4(0.0, 0.0, xTexelC${A}.xy);
|
|
}
|
|
`):p+=`
|
|
if (xC >= 0 && xC < inDims[1] && xTexelC${A}Ready == 0) {
|
|
xTexelC${A} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${A}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${A}Ready = 1;
|
|
}
|
|
|
|
xC${A} = xTexelC${A};
|
|
`,A+1<u)){let x=o%2==0?v.nearestLargerEven(l):l;l%2==0&&o%2==1||l%2!=0&&o%2!=1?(p+=`
|
|
xCOffset = xC + imod(pads[1], 2) + ${x};
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${A+1}Ready == 0) {
|
|
xTexelC${A+1} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${A+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${A+1}Ready = 1;
|
|
}
|
|
`,l>1&&(p+=`
|
|
xCOffset -= 2;
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${A}Ready == 0) {
|
|
xTexelC${A} = getX(batch, xR, xCOffset, d1);
|
|
xTexelC${A}Ready = 1;
|
|
}
|
|
`),p+=`
|
|
xC${A+1} = vec4(xTexelC${A}.zw, xTexelC${A+1}.xy);
|
|
`):x===1?p+=`
|
|
xC${A+1} = xTexelC${A};
|
|
`:p+=`
|
|
xCOffset = xC + ${x};
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${A+1}Ready == 0) {
|
|
xTexelC${A+1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${A+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${A+1}Ready = 1;
|
|
}
|
|
|
|
xC${A+1} = xTexelC${A+1};
|
|
`}}else A<u&&(o%2==1?(p+=`
|
|
xCOffset = xC + 1 - strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${A}Ready == 0) {
|
|
xTexelC${A} = getX(batch, xR, xCOffset, d1);
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${A}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${A}Ready = 1;
|
|
}
|
|
|
|
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${A+1}Ready == 0) {
|
|
xTexelC${A+1} = getX(batch, xR, xC + 1, d1);
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xC + 2 >= inDims[1]) {
|
|
xTexelC${A+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${A+1}Ready = 1;
|
|
}
|
|
|
|
xC${A} = vec4(xTexelC${A}.zw, xTexelC${A+1}.zw);
|
|
`,A+1<u&&(p+=`
|
|
final = vec4(0.0);
|
|
xCOffset = xC + 1 + strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
final = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
xC${A+1} = vec4(xTexelC${A+1}.xy, final.xy);
|
|
`)):(p+=`
|
|
if(xC >= 0 && xC < inDims[1] && xTexelC${A}Ready == 0) {
|
|
xTexelC${A} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${A}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${A}Ready = 1;
|
|
}
|
|
|
|
xCOffset = xC + strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${A+1}Ready == 0) {
|
|
xTexelC${A+1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${A+1}.zw = vec2(0.);
|
|
}
|
|
xTexelC${A+1}Ready = 1;
|
|
}
|
|
|
|
xC${A} = vec4(
|
|
xTexelC${A}.xy, xTexelC${A+1}.xy);
|
|
`,A+1<u&&(p+=`
|
|
xC${A+1} = vec4(xTexelC${A}.zw, xTexelC${A+1}.zw);
|
|
`)));A<u&&(p+=`
|
|
wTexel = getW(${g}, ${A}, d1, q);
|
|
dotProd += xC${A} * vec4(wTexel.xz, wTexel.xz);
|
|
`,A+1<u&&(p+=`
|
|
wTexel = getW(${g}, ${A+1}, d1, q);
|
|
dotProd += xC${A+1} * vec4(wTexel.xz, wTexel.xz);
|
|
`))}p+=`
|
|
}
|
|
`}let h="",f="";n&&(s?h=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:r?h=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:h=`vec4 activation(vec4 x) {
|
|
${n}
|
|
}`,f="result = activation(result);");let m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${h}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int d2 = coords.w;
|
|
int d1 = d2 / ${a};
|
|
int q = d2 - d1 * ${a};
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
|
|
vec4 dotProd = vec4(0.000000000000001);
|
|
|
|
${p}
|
|
|
|
vec4 result = dotProd - vec4(0.000000000000001);
|
|
${m}
|
|
${f}
|
|
setOutput(result);
|
|
}
|
|
`}};function Dee(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dilations:l,dimRoundingMode:c}=s,u=l;u==null&&(u=[1,1]),v.assert(E.eitherStridesOrDilationsAreOne(o,u),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);let d=E.computeConv2DInfo(r.shape,a.shape,o,u,i,c,!0),p;Z().getBool("WEBGL_PACK_DEPTHWISECONV")&&d.strideWidth<=2&&d.outChannels/d.inChannels==1?p=new eS(d):p=new Q4(d);let h=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];return n.runWebGLProgram(p,[r,a],"float32",h)}var _ee={kernelName:Da,backendName:"webgl",kernelFunc:Dee},Pee=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,r=e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int wR = coords.x;
|
|
int wC = coords.y;
|
|
int d1 = coords.z;
|
|
int dm = coords.w;
|
|
int d2 = d1 * ${a} + dm;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
// TO DO: Vec4 over the batch size
|
|
for (int b = 0; b < ${e.batchSize}; b++) {
|
|
for (int yR = 0; yR < ${e.outHeight}; yR++) {
|
|
int xR = wR + yR * ${t} - ${s};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${n} - ${r};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float dyValue = getDy(b, yR, yC, d2);
|
|
float xValue = getX(b, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},Fee=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,r=e.strideWidth,a=t-1-e.padInfo.top,o=n-1-e.padInfo.left,i=e.outChannels/e.inChannels;this.userCode=`
|
|
const ivec2 pads = ivec2(${a}, ${o});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[3];
|
|
ivec2 dyCorner = coords.yz - pads;
|
|
int dyRCorner = dyCorner.x;
|
|
int dyCCorner = dyCorner.y;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
for (int wR = 0; wR < ${t}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / ${s}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${t} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${n}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${r}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${n} - 1 - wC;
|
|
|
|
// TO DO: Vec4 over the channelMul
|
|
for (int dm = 0; dm < ${i}; dm++) {
|
|
int d2 = d1 * ${i} + dm;
|
|
float xValue = getDy(batch, idyR, idyC, d2);
|
|
float wValue = getW(wRPerm, wCPerm, d1, dm);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function Oee(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:o,dilations:i,pad:l,dimRoundingMode:c,filterShape:u}=s,d=E.computeConv2DInfo(r.shape,u,o,i,l,c,!0),p=new Pee(d);return n.runWebGLProgram(p,[r,a],"float32")}var Mee={kernelName:vh,backendName:"webgl",kernelFunc:Oee};function zee(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{strides:o,dilations:i,pad:l,dimRoundingMode:c,inputShape:u}=s,d=E.computeConv2DInfo(u,a.shape,o,i,l,c,!0),p=new Fee(d);return n.runWebGLProgram(p,[r,a],"float32")}var Lee={kernelName:wh,backendName:"webgl",kernelFunc:zee},Bee=class{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
|
|
setOutput(val);
|
|
}
|
|
`}};function Wee(e){let{inputs:t,backend:n}=e,{x:s}=t,r=[...s.shape,...s.shape],a=v.sizeFromShape(s.shape),o=be({inputs:{x:s},backend:n,attrs:{shape:[a]}}),i=new Bee(a),l=n.runWebGLProgram(i,[o],o.dtype),c=be({inputs:{x:l},backend:n,attrs:{shape:r}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),c}var Vee={kernelName:kh,backendName:"webgl",kernelFunc:Wee},Uee=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:n,padInfo:s,strideHeight:r,strideWidth:a,filterHeight:o,filterWidth:i,dilationHeight:l,dilationWidth:c}=e,{top:u,left:d}=s;this.userCode=`
|
|
const ivec2 strides = ivec2(${r}, ${a});
|
|
const ivec2 pads = ivec2(${u}, ${d});
|
|
const float neg_infinity = -3.4e38;
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d1 = coords.w;
|
|
ivec2 outTopLeftCorner =
|
|
coords.yz * strides - pads;
|
|
int hBeg = outTopLeftCorner.x;
|
|
int wBeg = outTopLeftCorner.y;
|
|
|
|
float curVal = neg_infinity;
|
|
for (int h = 0; h < ${o}; h++) {
|
|
int hIn = hBeg + h * ${l};
|
|
|
|
if (hIn >= 0 && hIn < ${t}) {
|
|
for (int w = 0; w < ${i}; w++) {
|
|
int wIn = wBeg + w * ${c};
|
|
|
|
if (wIn >= 0 && wIn < ${n}) {
|
|
float xVal = getX(batch, hIn, wIn, d1);
|
|
float wVal = getW(h, w, d1);
|
|
|
|
float val = xVal + wVal;
|
|
if (val > curVal) {
|
|
curVal = val;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
float result = curVal;
|
|
setOutput(result);
|
|
}
|
|
`}};function Gee(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dilations:l}=s,c=E.computeDilation2DInfo(r.shape,a.shape,o,i,"NHWC",l),u,d=new Uee(c);u=n.runWebGLProgram(d,[r,a],"float32");let p=be({inputs:{x:u},backend:n,attrs:{shape:c.outShape}});return n.disposeIntermediateTensorInfo(u),p}var Hee={kernelName:Kc,backendName:"webgl",kernelFunc:Gee};function jee(e){let{inputs:t,backend:n,attrs:s}=e,{equation:r}=s,a=t,{allDims:o,summedDims:i,idDims:l}=E.decodeEinsumEquation(r,a.length);E.checkEinsumDimSizes(o.length,l,a);let{path:c,steps:u}=E.getEinsumComputePath(i,l),d=u.length,p=null,h=o.length,f=[];for(let m=0;m<d;++m){for(let g of u[m]){let{permutationIndices:y,expandDims:A}=E.getEinsumPermutation(h,l[g]),x;E.isIdentityPermutation(y)?x=a[g]:(x=jn({inputs:{x:a[g]},backend:n,attrs:{perm:y}}),f.push(x));let b=x.shape.slice();for(let w=0;w<A.length;++w)b.splice(A[w],0,1);v.arraysEqual(x.shape,b)||(x=be({inputs:{x},backend:n,attrs:{shape:b}}),f.push(x)),p===null?p=x:(p=gx({inputs:{a:x,b:p},backend:n}),f.push(p))}m<d-1&&(c[m]>=0&&(p=Gm({inputs:{x:p},backend:n,attrs:{axis:c[m]-(o.length-h),keepDims:!1}}),f.push(p)),h--)}for(let m of f)m!==p&&n.disposeIntermediateTensorInfo(m);return p}var qee={kernelName:Zc,backendName:"webgl",kernelFunc:jee},Xee="return (x >= 0.0) ? x : (exp(x) - 1.0);",Kee=`
|
|
vec4 result;
|
|
|
|
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
|
|
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
|
|
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
|
|
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
|
|
|
|
return result;
|
|
`,Zee=it({opSnippet:Xee,packedOpSnippet:Kee}),Yee={kernelName:Pa,backendName:"webgl",kernelFunc:Zee},Jee="return (b >= 1.0) ? a : a * (b + 1.0);",Qee=`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,ete=e=>{let{inputs:t,backend:n}=e,{dy:s,y:r}=t,a=Z().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new hp(Qee,s.shape,r.shape):new lc(Jee,s.shape,r.shape);return n.runWebGLProgram(a,[s,r],s.dtype)},tte={kernelName:Ch,backendName:"webgl",kernelFunc:ete},nte=`
|
|
return vec4(equal(a, b));
|
|
`,ste="return float(a == b);",rte=En({opSnippet:ste,packedOpSnippet:nte,dtype:"bool",cpuKernelImpl:UZ}),ate={kernelName:li,backendName:"webgl",kernelFunc:rte},ote=`
|
|
// Error function is calculated approximately with elementary function.
|
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
float p = ${E.ERF_P};
|
|
float a1 = ${E.ERF_A1};
|
|
float a2 = ${E.ERF_A2};
|
|
float a3 = ${E.ERF_A3};
|
|
float a4 = ${E.ERF_A4};
|
|
float a5 = ${E.ERF_A5};
|
|
|
|
float sign = sign(x);
|
|
x = abs(x);
|
|
float t = 1.0 / (1.0 + p * x);
|
|
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
|
|
`,ite=it({opSnippet:ote}),lte={kernelName:su,backendName:"webgl",kernelFunc:ite},tS="return exp(x);",nS=it({opSnippet:tS,packedOpSnippet:tS,cpuKernelImpl:GZ}),ute={kernelName:Fa,backendName:"webgl",kernelFunc:nS};function bx(e){let{inputs:t,attrs:n,backend:s}=e,{dim:r}=n,{input:a}=t,o=a.shape.length,i=a.shape.slice(),l=r;return r<0&&(v.assert(-(o+1)<=r,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+r+1),i.splice(l,0,1),be({inputs:{x:a},backend:s,attrs:{shape:i}})}var cte={kernelName:ui,backendName:"webgl",kernelFunc:bx},sS="return exp(x) - 1.0;",dte=it({opSnippet:sS,packedOpSnippet:sS,cpuKernelImpl:HZ}),pte={kernelName:ci,backendName:"webgl",kernelFunc:dte},rS=class{constructor(e,t,n){this.variableNames=["real","imag"];let s=t[1];this.outputShape=t;let r=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,a=n?`${s}.0`:"1.0",o;if(e==="real")o="return real * expR - imag * expI;";else if(e==="imag")o="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=`
|
|
const float exponentMultiplier = ${r};
|
|
|
|
float unaryOpComplex(float real, float expR, float imag, float expI) {
|
|
${o}
|
|
}
|
|
|
|
float mulMatDFT(int batch, int index) {
|
|
float indexRatio = float(index) / float(${s});
|
|
float exponentMultiplierTimesIndexRatio =
|
|
exponentMultiplier * indexRatio;
|
|
|
|
float result = 0.0;
|
|
|
|
for (int i = 0; i < ${s}; i++) {
|
|
// x = (-2|2 * PI / N) * index * i;
|
|
float x = exponentMultiplierTimesIndexRatio * float(i);
|
|
float expR = cos(x);
|
|
float expI = sin(x);
|
|
float real = getReal(batch, i);
|
|
float imag = getImag(batch, i);
|
|
|
|
result +=
|
|
unaryOpComplex(real, expR, imag, expI) / ${a};
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
setOutput(mulMatDFT(coords[0], coords[1]));
|
|
}
|
|
`}};function aS(e,t,n){let s=n.texData.get(e.dataId),r=v.sizeFromShape(e.shape),a=e.shape[e.shape.length-1],o=r/a,i=be({inputs:{x:e},backend:n,attrs:{shape:[o,a]}}),l=i.shape,c=new rS("real",l,t),u=new rS("imag",l,t),d=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:l},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:l}],p=n.runWebGLProgram(c,d,"float32"),h=n.runWebGLProgram(u,d,"float32"),f=Mo({inputs:{real:p,imag:h},backend:n});n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h);let m=be({inputs:{x:f},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(f),m}function hte(e){let{inputs:t,backend:n}=e,{input:s}=t;return aS(s,!1,n)}var fte={kernelName:Th,backendName:"webgl",kernelFunc:hte},mte=class{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
// Input can be obtained from uniform value.
|
|
setOutput(value);
|
|
}
|
|
`}};function gp(e){let{backend:t,attrs:n}=e,{shape:s,value:r}=n,{dtype:a}=n;if(a=a||v.inferDtype(r),a==="string"){let o=v.getArrayFromDType(a,v.sizeFromShape(s));return o.fill(r),t.makeTensorInfo(s,a,o)}else{let o=new mte(s,r),i=[[r]];return t.runWebGLProgram(o,[],a,i)}}var gte={kernelName:ru,backendName:"webgl",kernelFunc:gp},yte=class{constructor(e){this.variableNames=["Image"],this.outputShape=[];let t=e[2];this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int x = coords[2];
|
|
|
|
int coordX = ${t} - x - 1;
|
|
float outputValue;
|
|
if(coordX >= 0 && coordX < ${t}) {
|
|
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
|
|
} else {
|
|
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}},Ate={kernelName:di,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,s=t,r=new yte(n.shape);return s.runWebGLProgram(r,[n],n.dtype)}},oS="return floor(x);",xte=it({opSnippet:oS,packedOpSnippet:oS,cpuKernelImpl:jZ}),bte={kernelName:Oa,backendName:"webgl",kernelFunc:xte},vte=`
|
|
float s = sign(a) * sign(b);
|
|
int ia = round(a);
|
|
int ib = round(b);
|
|
if (ib != 0) {
|
|
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
|
|
return float(idiv(ia, ib, s));
|
|
} else {
|
|
return NAN;
|
|
}
|
|
`,wte=`
|
|
ivec4 ia = round(a);
|
|
ivec4 ib = round(b);
|
|
bvec4 cond = notEqual(ib, ivec4(0));
|
|
ivec4 result = ivec4(0);
|
|
vec4 s = sign(a) * sign(b);
|
|
|
|
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
|
|
if (cond[0]) {
|
|
result[0] = idiv(ia[0], ib[0], s[0]);
|
|
}
|
|
if (cond[1]) {
|
|
result[1] = idiv(ia[1], ib[1], s[1]);
|
|
}
|
|
if (cond[2]) {
|
|
result[2] = idiv(ia[2], ib[2], s[2]);
|
|
}
|
|
if (cond[3]) {
|
|
result[3] = idiv(ia[3], ib[3], s[3]);
|
|
}
|
|
return vec4(result);
|
|
`,kte=En({opSnippet:vte,packedOpSnippet:wte,dtype:"int32"}),Ite={kernelName:Ma,backendName:"webgl",kernelFunc:kte},Ste=class{constructor(e){this.variableNames=["A"];let t=Gn(),[n,s]=e;this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
int texR = coords[0];
|
|
int texC = coords[1];
|
|
int depth = coords[2];
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}.0, ${n}.0);
|
|
|
|
vec4 values = ${t.texture2D}(A, uv);
|
|
float value;
|
|
if (depth == 0) {
|
|
value = values.r;
|
|
} else if (depth == 1) {
|
|
value = values.g;
|
|
} else if (depth == 2) {
|
|
value = values.b;
|
|
} else if (depth == 3) {
|
|
value = values.a;
|
|
}
|
|
|
|
setOutput(floor(value * 255.0 + 0.5));
|
|
}
|
|
`}},Cte=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=Gn(),[n,s]=e;this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
int texR = coords[0];
|
|
int texC = coords[1];
|
|
int depth = coords[2];
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
for(int row=0; row<=1; row++) {
|
|
for(int col=0; col<=1; col++) {
|
|
texC = coords[1] + row;
|
|
depth = coords[2] + col;
|
|
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${s}.0, ${n}.0);
|
|
vec4 values = ${t.texture2D}(A, uv);
|
|
float value;
|
|
if (depth == 0) {
|
|
value = values.r;
|
|
} else if (depth == 1) {
|
|
value = values.g;
|
|
} else if (depth == 2) {
|
|
value = values.b;
|
|
} else if (depth == 3) {
|
|
value = values.a;
|
|
}
|
|
|
|
result[row * 2 + col] = floor(value * 255.0 + 0.5);
|
|
}
|
|
}
|
|
|
|
${t.output} = result;
|
|
}
|
|
`}},Tte={kernelName:ad,backendName:"webgl",kernelFunc:Nte},dc;function Nte(e){let{inputs:t,backend:n,attrs:s}=e,{pixels:r}=t,{numChannels:a}=s,o=typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement,[l,c]=o?[r.videoWidth,r.videoHeight]:[r.width,r.height],u=[c,l],d=[c,l,a];(i||o)&&(dc==null&&(dc=document.createElement("canvas").getContext("2d")),dc.canvas.width=l,dc.canvas.height=c,dc.drawImage(r,0,0,l,c),r=dc.canvas);let p=n.makeTensorInfo(u,"int32");n.texData.get(p.dataId).usage=Ls.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),r);let h=Z().getBool("WEBGL_PACK")?new Cte(d):new Ste(d),f=n.runWebGLProgram(h,[p],"int32");return n.disposeData(p.dataId),f}function Ete(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=s,m=E.convertConv2DDataFormat(u),g=E.computeConv2DInfo(r.shape,a.shape,l,d,c,p,!1,m),y,A=[];if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))y=X4({x:r,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else if(Z().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)y=K4({x:r,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else{let b=o!=null,w=i!=null,k=h==="leakyrelu",S=h?Vm(h,!1):null,N=new q4(g,b,S,w,k),$=[r,a];if(o&&$.push(o),i&&$.push(i),k){let F=n.makeTensorInfo([],"float32",v.createScalarValue(f,"float32"));$.push(F),A.push(F)}y=n.runWebGLProgram(N,$,"float32")}let x=be({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return A.push(y),A.forEach(b=>n.disposeIntermediateTensorInfo(b)),x}var Rte={kernelName:mo,backendName:"webgl",kernelFunc:Ete};function $te(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dilations:u,dimRoundingMode:d,activation:p,leakyreluAlpha:h}=s,f=[],m=u;m==null&&(m=[1,1]),v.assert(E.eitherStridesOrDilationsAreOne(l,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`);let g=E.computeConv2DInfo(r.shape,a.shape,l,m,c,d,!0),y=Z().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,A=p?Vm(p,y):null,x=[r,a],b=o!=null,w=i!=null,k=p==="leakyrelu";if(b&&x.push(o),w&&x.push(i),k){let F=n.makeTensorInfo([],"float32",v.createScalarValue(h,"float32"));x.push(F),f.push(F)}let S;y?S=new eS(g,b,A,w,k):S=new Q4(g,b,A,w,k);let N=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],$=n.runWebGLProgram(S,x,"float32",N);return f.forEach(F=>n.disposeIntermediateTensorInfo(F)),$}var Dte={kernelName:go,backendName:"webgl",kernelFunc:$te},_te=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let s=St(t.length),r=St(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
|
|
${s} strides = ${s}(${this.strides});
|
|
void main() {
|
|
${r} coords = getOutputCoords();
|
|
int flattenIndex = 0;
|
|
for (int j = 0; j < ${this.sliceDim}; j++) {
|
|
int index = round(getIndices(coords[0], j));
|
|
flattenIndex += index * ${a};
|
|
}
|
|
setOutput(getX(flattenIndex, coords[1]));
|
|
}
|
|
`}};function Pte(e){let{inputs:t,backend:n}=e,{params:s,indices:r}=t,a=r.shape,o=a[a.length-1],i=v.sizeFromShape(s.shape),[l,c,u,d]=E.prepareAndValidate(s,r),p=be({inputs:{x:r},backend:n,attrs:{shape:[c,o]}}),h=be({inputs:{x:s},backend:n,attrs:{shape:[v.sizeFromShape(s.shape)/u,u]}});if(n.shouldExecuteOnCPU([s,r])||s.dtype==="string"){let y=n.readSync(r.dataId),A=n.bufferSync(s),x=qZ(y,A,s.dtype,c,o,u,d,s.shape,i);return n.makeTensorInfo(l,s.dtype,x.values)}let f=new _te(o,d,[c,u]),m=n.runWebGLProgram(f,[h,p],h.dtype),g=be({inputs:{x:m},backend:n,attrs:{shape:l}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),g}var Fte={kernelName:hi,backendName:"webgl",kernelFunc:Pte},Ote=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=St(this.rank),s=Mte(e,2);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${s}));
|
|
}
|
|
`}};function Mte(e,t){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let r=0;r<e.length;r++)r===2?s.push("int(getIndices(resRC.x, resRC.z))"):s.push(`${n[r]}`);return s.join()}function iS(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,indices:a}=t,{axis:o,batchDims:i}=s,l=v.parseAxisParam(o,r.shape)[0],c=E.segment_util.collectGatherOpShapeInfo(r,a,l,i),u=v.sizeFromShape(a.shape),d=[],p=be({inputs:{x:r},backend:n,attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]}}),h=be({inputs:{x:a},backend:n,attrs:{shape:[c.batchSize,u/c.batchSize]}});d.push(p),d.push(h);let f=[c.batchSize,c.outerSize,u/c.batchSize,c.sliceSize];if(n.shouldExecuteOnCPU([r,a])||r.dtype==="string"){let A=n.bufferSync(h),x=n.bufferSync(p),b=XZ(x,A,f);return d.forEach(w=>n.disposeIntermediateTensorInfo(w)),n.makeTensorInfo(c.outputShape,b.dtype,b.values)}let m=new Ote(p.shape,f),g=n.runWebGLProgram(m,[p,h],p.dtype);d.push(g);let y=be({inputs:{x:g},backend:n,attrs:{shape:c.outputShape}});return d.forEach(A=>n.disposeIntermediateTensorInfo(A)),y}var zte={kernelName:pi,backendName:"webgl",kernelFunc:iS},Lte="return float(a > b);",Bte=`
|
|
return vec4(greaterThan(a, b));
|
|
`,Wte=En({opSnippet:Lte,packedOpSnippet:Bte,cpuKernelImpl:KZ,dtype:"bool"}),Vte={kernelName:fi,backendName:"webgl",kernelFunc:Wte},Ute="return float(a >= b);",Gte=`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,Hte=En({opSnippet:Ute,packedOpSnippet:Gte,dtype:"bool",cpuKernelImpl:ZZ}),jte={kernelName:La,backendName:"webgl",kernelFunc:Hte};function qte(e){let{inputs:t,backend:n}=e,{input:s}=t;return aS(s,!0,n)}var Xte={kernelName:Nh,backendName:"webgl",kernelFunc:qte},Kte="return float(!isnan(x) && !isinf(x));",Zte=it({opSnippet:Kte,dtype:"bool"}),Yte={kernelName:au,backendName:"webgl",kernelFunc:Zte},Jte="return float(isinf(x));",Qte=it({opSnippet:Jte,dtype:"bool"}),ene={kernelName:ou,backendName:"webgl",kernelFunc:Qte},tne="return float(isnan(x));",nne=it({opSnippet:tne,dtype:"bool"}),sne={kernelName:iu,backendName:"webgl",kernelFunc:nne},rne="return float(a < b);",ane=`
|
|
return vec4(lessThan(a, b));
|
|
`,one=En({opSnippet:rne,packedOpSnippet:ane,cpuKernelImpl:YZ,dtype:"bool"}),ine={kernelName:gi,backendName:"webgl",kernelFunc:one},lne="return float(a <= b);",une=`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,cne=En({opSnippet:lne,packedOpSnippet:une,cpuKernelImpl:JZ,dtype:"bool"}),dne={kernelName:yi,backendName:"webgl",kernelFunc:cne};function pne(e){let{backend:t,attrs:n}=e,{start:s,stop:r,num:a}=n,o=QZ(s,r,a);return t.makeTensorInfo([o.length],"float32",o)}var hne={kernelName:Eh,backendName:"webgl",kernelFunc:pne},fne=`if (x < 0.0) return NAN;
|
|
return log(x);`,mne=`
|
|
vec4 result = log(x);
|
|
vec4 isNaN = vec4(lessThan(x, vec4(0.0)));
|
|
result.r = isNaN.r == 1.0 ? NAN : result.r;
|
|
result.g = isNaN.g == 1.0 ? NAN : result.g;
|
|
result.b = isNaN.b == 1.0 ? NAN : result.b;
|
|
result.a = isNaN.a == 1.0 ? NAN : result.a;
|
|
|
|
return result;
|
|
`,gne=it({opSnippet:fne,packedOpSnippet:mne,cpuKernelImpl:eY}),yne={kernelName:Wa,backendName:"webgl",kernelFunc:gne},Ane="return log(1.0 + x);",xne=it({opSnippet:Ane}),bne={kernelName:lu,backendName:"webgl",kernelFunc:xne},vne="return float(a >= 1.0 && b >= 1.0);",wne=`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,kne=En({opSnippet:vne,packedOpSnippet:wne,dtype:"bool"}),Ine={kernelName:Ai,backendName:"webgl",kernelFunc:kne},Sne="return float(!(x >= 1.0));",Cne=it({opSnippet:Sne}),Tne={kernelName:uu,backendName:"webgl",kernelFunc:Cne},Nne="return float(a >= 1.0 || b >= 1.0);",Ene=`
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`,Rne=En({opSnippet:Nne,packedOpSnippet:Ene,dtype:"bool"}),$ne={kernelName:Jc,backendName:"webgl",kernelFunc:Rne},Dne=class{constructor(e,t,n,s,r){this.variableNames=["x"],this.outputShape=[];let a=t,o=e[3]-1;this.outputShape=e;let i,l=`float(${n}) + float(${s}) * sum`;r===.5?i=`inversesqrt(${l})`:r===1?i=`1.0/(${l})`:i=`exp(log(${l}) * float(-${r}));`,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
int d = coords[3];
|
|
float x = getX(b, r, c, d);
|
|
float sum = 0.0;
|
|
for (int j = -${a}; j <= ${a}; j++) {
|
|
int idx = d + j;
|
|
if (idx >= 0 && idx <= ${o}) {
|
|
float z = getX(b, r, c, idx);
|
|
sum += z * z;
|
|
}
|
|
}
|
|
float val = x * ${i};
|
|
setOutput(val);
|
|
}
|
|
`}},_ne=class{constructor(e,t,n,s,r){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let a=t,o=e[3]-1;this.outputShape=e;let i,l=`float(${n}) + float(${s}) * sum`;r===.5?i=`inversesqrt(${l})`:r===1?i=`1.0/(${l})`:i=`exp(log(${l}) * float(-${r}));`,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords.x;
|
|
int r = coords.y;
|
|
int c = coords.z;
|
|
int d = coords.w;
|
|
|
|
bool hasNextCol = d < ${this.outputShape[3]};
|
|
bool hasNextRow = c < ${this.outputShape[2]};
|
|
|
|
vec4 sum = vec4(0.);
|
|
vec4 xFragAtOutputCoords = getX(b, r, c, d);
|
|
|
|
vec4 xAtOutputCoords = vec4(
|
|
getChannel(xFragAtOutputCoords, vec2(c, d)),
|
|
hasNextCol ?
|
|
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
|
|
hasNextRow ?
|
|
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
|
|
);
|
|
|
|
int firstChannel = d - ${a};
|
|
vec2 cache = vec2(0.);
|
|
if(firstChannel >= 0){
|
|
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
|
|
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
|
|
if(hasNextRow){
|
|
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
|
|
}
|
|
}
|
|
|
|
ivec2 depth = ivec2(d, d + 1);
|
|
for (int j = - ${a}; j <= ${a}; j++) {
|
|
ivec2 idx = depth + j;
|
|
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
|
|
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${o}));
|
|
|
|
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
|
|
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
|
|
|
|
if(depthInRange || depthPlusOneInRange){
|
|
vec4 z = vec4(0.);
|
|
vec4 xFragAtCurrentDepth;
|
|
z.xz = cache.xy;
|
|
if(depthPlusOneInRange && hasNextCol){
|
|
xFragAtCurrentDepth = idx.y != d ?
|
|
getX(b, r, c, idx.y) : xFragAtOutputCoords;
|
|
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
|
|
if(hasNextRow){
|
|
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
|
|
}
|
|
}
|
|
cache.xy = z.yw;
|
|
sum += z * z;
|
|
}
|
|
}
|
|
vec4 result = xAtOutputCoords * ${i};
|
|
setOutput(result);
|
|
}
|
|
`}},Pne=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{depthRadius:a,bias:o,alpha:i,beta:l}=s,c=Z().getBool("WEBGL_PACK_NORMALIZATION")?new _ne(r.shape,a,o,i,l):new Dne(r.shape,a,o,i,l);return n.runWebGLProgram(c,[r],r.dtype)},Fne={kernelName:Qc,backendName:"webgl",kernelFunc:Pne},One=class{constructor(e,t,n,s,r){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=s,this.beta=r,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float result = 0.0;
|
|
for (int d = 0; d < ${this.depth}; ++d) {
|
|
int depthBegin = int(max(0.0, float(d - ${t})));
|
|
int depthEnd = int(min(float(${this.depth}),
|
|
float(d + ${t} + 1)));
|
|
|
|
const int MIN_DEPTH_BEGIN = 0;
|
|
const int MAX_DEPTH_END = ${this.depth};
|
|
|
|
float norm = 0.0;
|
|
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
|
|
if (k < depthBegin){
|
|
continue;
|
|
}
|
|
else if (k >= depthBegin && k < depthEnd) {
|
|
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
|
|
}
|
|
else {
|
|
break;
|
|
}
|
|
}
|
|
|
|
norm = float(${s}) * norm + float(${n});
|
|
|
|
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
|
|
if (k < depthBegin){
|
|
continue;
|
|
}
|
|
else if (k >= depthBegin && k < depthEnd){
|
|
float dyi = -2.0 * float(${s})
|
|
* float(${r})
|
|
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
|
|
/ norm;
|
|
if (k == d) {
|
|
dyi += pow(norm, -1.0 * ${r});
|
|
}
|
|
if (k == coords[3]) {
|
|
dyi *= getDy(b, r, c, d);
|
|
result += dyi;
|
|
}
|
|
}
|
|
else {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}},Mne=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r,y:a,dy:o}=t,{depthRadius:i,bias:l,alpha:c,beta:u}=s,d=new One(r.shape,i,l,c,u);return n.runWebGLProgram(d,[r,a,o],r.dtype)},zne={kernelName:Rh,backendName:"webgl",kernelFunc:Mne};function Lne(e,t,n,s){let r=v.sizeFromShape(t),o=v.sizeFromShape(e.shape)/r,i=be({inputs:{x:e},attrs:{shape:[o,r]},backend:s}),l=vl(i,e.dtype,"max",s),c=be({inputs:{x:l},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(i),s.disposeIntermediateTensorInfo(l),c}function lS(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reductionIndices:a,keepDims:o}=s,i=r.shape.length,l=v.parseAxisParam(a,r.shape),c=l,u=E.getAxesPermutation(c,i),d=u!=null,p=n.shouldExecuteOnCPU([r]),h=r;if(d){if(p){let x=n.texData.get(h.dataId).values,b=new Array(i);for(let S=0;S<b.length;S++)b[S]=r.shape[u[S]];let w=mx(x,r.shape,r.dtype,u,b);h=n.makeTensorInfo(b,r.dtype);let k=n.texData.get(h.dataId);k.values=w}else h=Um(r,u,n);c=E.getInnerMostAxes(c.length,i)}E.assertAxesAreInnerMostDims("max",c,i);let[f,m]=E.computeOutAndReduceShapes(h.shape,c),g=f;o&&(g=E.expandShapeToKeepDim(f,l));let y;if(p){let x=n.texData.get(h.dataId).values,b=tY(x,v.sizeFromShape(m),g,r.dtype);y=n.makeTensorInfo(g,r.dtype);let w=n.texData.get(y.dataId);w.values=b}else y=Lne(h,m,g,n);return d&&n.disposeIntermediateTensorInfo(h),y}var Bne={kernelName:Va,backendName:"webgl",kernelFunc:lS},Wne=C4+`
|
|
return max(a, b);
|
|
`,Vne=`
|
|
vec4 result = vec4(max(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Wm+`
|
|
return result;
|
|
`,Une=En({opSnippet:Wne,packedOpSnippet:Vne,cpuKernelImpl:nY}),Gne={kernelName:Ua,backendName:"webgl",kernelFunc:Une};function Hne(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t;tc(r,"maxPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,c=1;v.assert(E.eitherStridesOrDilationsAreOne(o,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);let u=E.computePool2DInfo(r.shape,a,o,c,i,l);if(u.filterWidth===1&&u.filterHeight===1&&v.arraysEqual(u.inShape,u.outShape))return Cs({inputs:{x:r},backend:n});let d=new fp(u,"max",!1);return n.runWebGLProgram(d,[r],r.dtype)}var jne={kernelName:Ga,backendName:"webgl",kernelFunc:Hne};function qne(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dataFormat:l,dimRoundingMode:c}=s,u=[1,1,1],d=E.computePool3DInfo(r.shape,a,o,u,i,c,l),p=new yx(d,"max",!1);return n.runWebGLProgram(p,[r],r.dtype)}var Xne={kernelName:ed,backendName:"webgl",kernelFunc:qne},Kne=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,n=e.strideWidth,s=e.dilationHeight,r=e.effectiveFilterHeight,a=e.effectiveFilterWidth,o=r-1-e.padInfo.top,i=a-1-e.padInfo.left,l=r*a-1;this.userCode=`
|
|
const ivec2 pads = ivec2(${o}, ${i});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 dyRCCorner = coords.yz - pads;
|
|
int dyRCorner = dyRCCorner.x;
|
|
int dyCCorner = dyRCCorner.y;
|
|
|
|
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${r};
|
|
wR += ${s}) {
|
|
float dyR = float(dyRCorner + wR) / ${t}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${a}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${n}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(b, idyR, idyC, d);
|
|
int maxPosValue = ${l} - int(getMaxPos(b, idyR, idyC, d));
|
|
|
|
// Get the current value, check it against the value from the
|
|
// position matrix.
|
|
int curPosValue = wR * ${a} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},Zne=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,r=e.dilationDepth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterDepth,l=e.effectiveFilterHeight,c=e.effectiveFilterWidth,u=i-1-e.padInfo.front,d=l-1-e.padInfo.top,p=c-1-e.padInfo.left,h=i*l*c-1;this.userCode=`
|
|
const ivec3 pads = ivec3(${u}, ${d}, ${p});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
|
|
// dx(xD, xR, xC, ch).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int wD = 0; wD < ${i};
|
|
wD += ${r}) {
|
|
float dyD = float(dyDCorner + wD) / ${t}.0;
|
|
|
|
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyD = int(dyD);
|
|
|
|
for (int wR = 0; wR < ${l};
|
|
wR += ${a}) {
|
|
float dyR = float(dyRCorner + wR) / ${n}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${c};
|
|
wC += ${o}) {
|
|
float dyC = float(dyCCorner + wC) / ${s}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
int maxPosValue = ${h} -
|
|
int(getMaxPos(batch, idyD, idyR, idyC, ch));
|
|
|
|
// Get the current value, check it against the value from the
|
|
// position matrix.
|
|
int curPosValue =
|
|
wD * ${l} * ${c} +
|
|
wR * ${c} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function Yne(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,o=a,{filterSize:i,strides:l,pad:c,dimRoundingMode:u}=s,d=[1,1,1],p=E.computePool3DInfo(o.shape,i,l,d,c,u),h=new yx(p,"max",!0),f=n.runWebGLProgram(h,[o],o.dtype),m=new Zne(p),g=n.runWebGLProgram(m,[r,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}var Jne={kernelName:Dh,backendName:"webgl",kernelFunc:Yne};function Qne(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a,output:o}=t,i=a;tc([a,o],"maxPoolGrad");let{filterSize:l,strides:c,pad:u,dimRoundingMode:d}=s,p=E.computePool2DInfo(i.shape,l,c,1,u,d),h=!0,f=new fp(p,"max",h),m=n.runWebGLProgram(f,[i],i.dtype),g=new Kne(p),y=n.runWebGLProgram(g,[r,m],i.dtype);return n.disposeIntermediateTensorInfo(m),y}var ese={kernelName:$h,backendName:"webgl",kernelFunc:Qne};function tse(e,t,n,s){let r=new fp(n,"max",!1),a=s.runWebGLProgram(r,[e],"float32");r=new fp(n,"max",!0,!0,t);let o=s.runWebGLProgram(r,[e],"float32");return[a,o]}var nse={kernelName:_h,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:s}=e,{filterSize:r,strides:a,pad:o,includeBatchInIndex:i}=t,l=n;v.assert(s.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);let c=[1,1];v.assert(E.eitherStridesOrDilationsAreOne(a,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${c}'`);let u=E.computePool2DInfo(s.shape,r,a,c,o),[d,p]=tse(s,i,u,l);return[d,p]}};function sse(e,t,n,s){let r=v.sizeFromShape(t),o=v.sizeFromShape(e.shape)/r,i=be({inputs:{x:e},attrs:{shape:[o,r]},backend:s}),l=vl(i,"float32","mean",s),c=be({inputs:{x:l},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(i),s.disposeIntermediateTensorInfo(l),c}var rse={kernelName:Ha,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:s}=e,{keepDims:r,axis:a}=t,o=n,i=s.shape.length,l=v.parseAxisParam(a,s.shape),c=l,u=E.getAxesPermutation(c,i),d=u!=null,p=o.shouldExecuteOnCPU([s]),h=[],f=s;if(d){if(p){let b=o.texData.get(f.dataId).values,w=new Array(i);for(let N=0;N<w.length;N++)w[N]=s.shape[u[N]];let k=mx(b,s.shape,s.dtype,u,w);f=o.makeTensorInfo(w,s.dtype);let S=o.texData.get(f.dataId);S.values=k}else f=Um(s,u,o);h.push(f),c=E.getInnerMostAxes(c.length,i)}E.assertAxesAreInnerMostDims("sum",c,i);let[m,g]=E.computeOutAndReduceShapes(f.shape,c),y=m;r&&(y=E.expandShapeToKeepDim(m,l));let A=sse(f,g,y,o);for(let x of h)o.disposeIntermediateTensorInfo(x);return A}};function ase(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s,i=r.shape.length,l=v.parseAxisParam(a,r.shape),c=l,u=E.getAxesPermutation(c,i),d=r;u!=null&&(d=jn({inputs:{x:r},backend:n,attrs:{perm:u}}),c=E.getInnerMostAxes(c.length,r.shape.length)),E.assertAxesAreInnerMostDims("min",c,i);let[p,h]=E.computeOutAndReduceShapes(d.shape,c),f=v.sizeFromShape(h),m=be({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=vl(m,m.dtype,"min",n),y;if(o){let A=E.expandShapeToKeepDim(p,l);y=be({inputs:{x:g},backend:n,attrs:{shape:A}})}else y=be({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(d),y}var ose={kernelName:ja,backendName:"webgl",kernelFunc:ase},ise=C4+`
|
|
return min(a, b);
|
|
`,lse=`
|
|
vec4 result = vec4(min(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Wm+`
|
|
return result;
|
|
`,use=En({opSnippet:ise,packedOpSnippet:lse,cpuKernelImpl:sY}),cse={kernelName:qa,backendName:"webgl",kernelFunc:use},dse=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((c,u)=>c[0]+e[u]+c[1]);let s=e.length,r=St(s),a=t.map(c=>c[0]).join(","),o=t.map((c,u)=>c[0]+e[u]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s),l=n==="reflect"?0:1;if(s===1){this.userCode=`
|
|
int start = ${a};
|
|
int end = ${o};
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start) {
|
|
outC = start * 2 - outC - ${l};
|
|
} else if(outC >= end) {
|
|
outC = (end - 1) * 2 - outC + ${l};
|
|
}
|
|
setOutput(getX(outC - start));
|
|
}
|
|
`;return}this.userCode=`
|
|
${r} start = ${r}(${a});
|
|
${r} end = ${r}(${o});
|
|
|
|
void main() {
|
|
${r} outC = getOutputCoords();
|
|
for (int i = 0; i < ${s}; i++) {
|
|
if (outC[i] < start[i]) {
|
|
outC[i] = start[i] * 2 - outC[i] - ${l};
|
|
} else if(outC[i] >= end[i]) {
|
|
outC[i] = (end[i] - 1) * 2 - outC[i] + ${l};
|
|
}
|
|
}
|
|
${r} coords = outC - start;
|
|
setOutput(getX(${i}));
|
|
}
|
|
`}},pse=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,f)=>h[0]+e[f]+h[1]);let s=e.length,r=St(s),a=t.map(h=>h[0]).join(","),o=t.map((h,f)=>h[0]+e[f]).join(","),i=Hn("rc",s),l=Hn("source",s),c=`${i[s-1]} < ${this.outputShape[s-1]}`,u=s===1?"source":`vec2(${l.slice(-2).join()})`,d=n==="reflect"?0:1,p="";if(s===1){let h=`
|
|
${r} source = rc;
|
|
if (source < start) {
|
|
source = start * 2 - source - ${d};
|
|
} else if (source >= end) {
|
|
source = (end - 1) * 2 - source + ${d};
|
|
}
|
|
source -= start;
|
|
`;p=`
|
|
${r} rc = outputLoc;
|
|
${h}
|
|
result[0] = getChannel(getX(${l.join()}), ${u});
|
|
${i[s-1]} += 1;
|
|
if(${c}) {
|
|
${h}
|
|
result[1] = getChannel(getX(${l.join()}), ${u});
|
|
}
|
|
`}else{let h=`
|
|
${r} source = rc;
|
|
${r} lt = ${r}(lessThan(source, start));
|
|
${r} gte = ${r}(greaterThanEqual(source, end));
|
|
${r} orig = 1 - (lt + gte);
|
|
source = orig * source +
|
|
lt * (start * 2 - source - ${d}) +
|
|
gte * ((end - 1) * 2 - source + ${d});
|
|
source -= start;
|
|
`;p=`
|
|
${r} rc = outputLoc;
|
|
${h}
|
|
result[0] = getChannel(getX(${l.join()}), ${u});
|
|
${i[s-1]} += 1;
|
|
if(${c}) {
|
|
${h}
|
|
result[1] = getChannel(getX(${l.join()}), ${u});
|
|
}
|
|
rc = outputLoc;
|
|
${i[s-2]} += 1;
|
|
if(${i[s-2]} < ${this.outputShape[s-2]}) {
|
|
${h}
|
|
result[2] = getChannel(getX(${l.join()}), ${u});
|
|
${i[s-1]} += 1;
|
|
if(${c}) {
|
|
${h}
|
|
result[3] = getChannel(getX(${l.join()}), ${u});
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
const ${r} start = ${r}(${a});
|
|
const ${r} end = ${r}(${o});
|
|
|
|
void main() {
|
|
${r} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${p}
|
|
setOutput(result);
|
|
}
|
|
`}},hse=({inputs:e,backend:t,attrs:n})=>{let{x:s}=e,{paddings:r,mode:a}=n,o=Z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new pse(s.shape,r,a):new dse(s.shape,r,a);return t.runWebGLProgram(o,[s],s.dtype)},fse={kernelName:Xa,backendName:"webgl",kernelFunc:hse},mse=`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,gse=`
|
|
vec4 result = mod(a, b);
|
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
|
`+Wm+`
|
|
return result;
|
|
`,yse=En({opSnippet:mse,packedOpSnippet:gse}),Ase={kernelName:cu,backendName:"webgl",kernelFunc:yse},xse=class{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,n],this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
|
|
float r = random(seed);
|
|
float cdf = 0.0;
|
|
|
|
for (int i = 0; i < ${t-1}; i++) {
|
|
cdf += getProbs(batch, i);
|
|
|
|
if (r < cdf) {
|
|
setOutput(float(i));
|
|
return;
|
|
}
|
|
}
|
|
|
|
// If no other event happened, last event happened.
|
|
setOutput(float(${t-1}));
|
|
}
|
|
`}},bse=`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,vse=`
|
|
// vec4 one = vec4(equal(a, b));
|
|
// return one + (vec4(1.0) - one) * a / b;
|
|
vec4 result = a / b;
|
|
if(a.x == b.x) {
|
|
result.x = 1.;
|
|
}
|
|
if(a.y == b.y) {
|
|
result.y = 1.;
|
|
}
|
|
if(a.z == b.z) {
|
|
result.z = 1.;
|
|
}
|
|
if(a.w == b.w) {
|
|
result.w = 1.;
|
|
}
|
|
|
|
return result;
|
|
`,uS=En({opSnippet:bse,packedOpSnippet:vse,checkOutOfBounds:!0}),wse={kernelName:_a,backendName:"webgl",kernelFunc:uS},cS="return a - b;",dS=En({opSnippet:cS,packedOpSnippet:cS,supportsComplex:!0,cpuKernelImpl:xY}),kse={kernelName:uo,backendName:"webgl",kernelFunc:dS};function pS(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{dim:a}=s,o=v.parseAxisParam([a],r.shape),i=lS({inputs:{x:r},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),l=E.expandShapeToKeepDim(i.shape,o),c=be({inputs:{x:i},backend:n,attrs:{shape:l}}),u=dS({inputs:{a:r,b:c},backend:n}),d=nS({inputs:{x:u},backend:n}),p=Gm({inputs:{x:d},backend:n,attrs:{axis:o,keepDims:!1}}),h=be({inputs:{x:p},backend:n,attrs:{shape:l}}),f=uS({inputs:{a:d,b:h},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}var Ise={kernelName:io,backendName:"webgl",kernelFunc:pS};function Sse(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{numSamples:a,seed:o,normalized:i}=s,l=i?r:pS({inputs:{logits:r},backend:n,attrs:{dim:r.shape.length-1}}),c=l.shape[0],u=l.shape[1],d=new xse(c,u,a),p=[[o]],h=n.runWebGLProgram(d,[l],"int32",p);return i||n.disposeIntermediateTensorInfo(l),h}var Cse={kernelName:Ph,backendName:"webgl",kernelFunc:Sse},hS="return -x;";function Tse(e){let{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])){let a=n.texData.get(s.dataId),[o,i]=aY(a.values,s.shape,s.dtype);return n.makeTensorInfo(i,s.dtype,o)}let r;return Z().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new oc(s.shape,hS):r=new Oo(s.shape,hS),n.runWebGLProgram(r,[s],s.dtype)}var Nse={kernelName:xi,backendName:"webgl",kernelFunc:Tse},Ese=Zs.nonMaxSuppressionV3Impl;function Rse(e){E.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l}=s,c=n.readSync(r.dataId),u=n.readSync(a.dataId),{selectedIndices:d}=Ese(c,u,o,i,l);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}var $se={kernelName:vi,backendName:"webgl",kernelFunc:Rse},Dse=Zs.nonMaxSuppressionV4Impl;function _se(e){E.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l,padToMaxOutputSize:c}=s,u=n.readSync(r.dataId),d=n.readSync(a.dataId),{selectedIndices:p,validOutputs:h}=Dse(u,d,o,i,l,c);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var Pse={kernelName:du,backendName:"webgl",kernelFunc:_se},Fse=Zs.nonMaxSuppressionV5Impl;function Ose(e){E.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l,softNmsSigma:c}=s,u=n.readSync(r.dataId),d=n.readSync(a.dataId),p=o,h=i,f=l,m=c,{selectedIndices:g,selectedScores:y}=Fse(u,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var Mse={kernelName:wi,backendName:"webgl",kernelFunc:Ose},zse=class{constructor(e,t,n,s){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int index = round(getIndices(coords.x));
|
|
setOutput(mix(float(${s}), float(${n}),
|
|
float(index == coords.y)));
|
|
}
|
|
`}},Lse=e=>{let{inputs:t,backend:n,attrs:s}=e,{indices:r}=t,{depth:a,onValue:o,offValue:i}=s,l=v.sizeFromShape(r.shape),c=new zse(l,a,o,i),u=be({inputs:{x:r},backend:n,attrs:{shape:[l]}}),d=n.runWebGLProgram(c,[u],r.dtype);n.disposeIntermediateTensorInfo(u);let p=[...r.shape,a],h=be({inputs:{x:d},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(d),h},Bse={kernelName:Ii,backendName:"webgl",kernelFunc:Lse};function Km(e){let{inputs:t,backend:n}=e,{x:s}=t;if(s.dtype==="complex64"){let r=mp({inputs:{input:s},backend:n}),a=Km({inputs:{x:r},backend:n}),o=Xm({inputs:{input:s},backend:n}),i=Km({inputs:{x:o},backend:n}),l=Mo({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),l}else return gp({attrs:{shape:s.shape,dtype:s.dtype,value:s.dtype==="string"?"":0},backend:n})}var Wse={kernelName:Bi,backendName:"webgl",kernelFunc:Km};function fS(e){let{inputs:t,backend:n}=e,{x:s}=t;if(s.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(s.dtype==="complex64"){let r=mp({inputs:{input:s},backend:n}),a=fS({inputs:{x:r},backend:n}),o=Xm({inputs:{input:s},backend:n}),i=Km({inputs:{x:o},backend:n}),l=Mo({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),l}else return gp({attrs:{shape:s.shape,dtype:s.dtype,value:1},backend:n})}var Vse={kernelName:ki,backendName:"webgl",kernelFunc:fS};function Use(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(t.length===1)return bx({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let a=t[0].shape,o=t[0].dtype;t.forEach(u=>{v.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),v.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(u=>{let d=bx({inputs:{input:u},backend:n,attrs:{dim:r}});return i.push(d),d}),c=j4({inputs:l,backend:n,attrs:{axis:r}});return i.forEach(u=>n.disposeIntermediateTensorInfo(u)),c}var Gse={kernelName:Si,backendName:"webgl",kernelFunc:Use},Hse=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((l,c)=>l[0]+e[c]+l[1]);let s=e.length,r=St(s),a=t.map(l=>l[0]).join(","),o=t.map((l,c)=>l[0]+e[c]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s);if(s===1){this.userCode=`
|
|
int start = ${a};
|
|
int end = ${o};
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start || outC >= end) {
|
|
setOutput(value);
|
|
} else {
|
|
setOutput(getX(outC - start));
|
|
}
|
|
}
|
|
`;return}this.userCode=`
|
|
${r} start = ${r}(${a});
|
|
${r} end = ${r}(${o});
|
|
|
|
void main() {
|
|
${r} outC = getOutputCoords();
|
|
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
|
|
setOutput(value);
|
|
} else {
|
|
${r} coords = outC - start;
|
|
setOutput(getX(${i}));
|
|
}
|
|
}
|
|
`}},jse=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((f,m)=>f[0]+e[m]+f[1]);let s=e.length,r=St(s),a=t.map(f=>f[0]).join(","),o=t.map((f,m)=>f[0]+e[m]).join(","),i=Hn("rc",s),l=Hn("source",s),c=`${i[s-1]} < ${this.outputShape[s-1]}`,u=s===1?"source":`vec2(${l.slice(-2).join()})`,d=[`${r} rc = outputLoc;`,`${i[s-1]} += 1;
|
|
if(${c}) {
|
|
`,s===1?"":`}
|
|
rc = outputLoc;
|
|
${i[s-2]} += 1;
|
|
if(${i[s-2]} < ${this.outputShape[s-2]}) {`,s===1?"":` ${i[s-1]} += 1;
|
|
if(${c}) {`],p=s===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="";for(let f=0,m=s===1?2:4;f<m;f++)h+=`
|
|
${d[f]}
|
|
if (${p}) {
|
|
result[${f}] = float(value);
|
|
} else {
|
|
${r} source = rc - start;
|
|
result[${f}] = getChannel(getX(${l.join()}), ${u});
|
|
}
|
|
`;h+=s===1?"} ":"}}",this.userCode=`
|
|
const ${r} start = ${r}(${a});
|
|
const ${r} end = ${r}(${o});
|
|
|
|
void main() {
|
|
${r} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${h}
|
|
setOutput(result);
|
|
}
|
|
`}},mS=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,constantValue:o}=s;if(v.sizeFromShape(r.shape)===0){let c=a.map((u,d)=>u[0]+r.shape[d]+u[1]);return gp({backend:n,attrs:{shape:c,value:o,dtype:r.dtype}})}let i=Z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new jse(r.shape,a,o):new Hse(r.shape,a,o),l=[[o]];return n.runWebGLProgram(i,[r],r.dtype,l)},qse={kernelName:Za,backendName:"webgl",kernelFunc:mS},Xse=`
|
|
if(a < 0.0 && floor(b) < b){
|
|
return NAN;
|
|
}
|
|
if (b == 0.0) {
|
|
return 1.0;
|
|
}
|
|
return (round(mod(b, 2.0)) != 1) ?
|
|
pow(abs(a), b) : sign(a) * pow(abs(a), b);
|
|
`,Kse=`
|
|
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
|
|
vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
|
|
vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
|
|
vec4 result = multiplier * pow(abs(a), b);
|
|
|
|
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
|
|
bvec4 isExpZero = equal(b, vec4(0.0));
|
|
result.r = isExpZero.r ? 1.0 : result.r;
|
|
result.g = isExpZero.g ? 1.0 : result.g;
|
|
result.b = isExpZero.b ? 1.0 : result.b;
|
|
result.a = isExpZero.a ? 1.0 : result.a;
|
|
|
|
vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));
|
|
`+Wm+`
|
|
return result;
|
|
`,Zse=En({opSnippet:Xse,packedOpSnippet:Kse}),Yse={kernelName:Ya,backendName:"webgl",kernelFunc:Zse};function Jse(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s,i=r.shape.length,l=[],c=v.parseAxisParam(a,r.shape),u=c,d=E.getAxesPermutation(u,i),p=r;d!=null&&(p=jn({inputs:{x:r},backend:n,attrs:{perm:d}}),u=E.getInnerMostAxes(u.length,i),l.push(p)),E.assertAxesAreInnerMostDims("prod",u,i);let h;if(n.shouldExecuteOnCPU([p])){let f=n.texData.get(p.dataId).values,{outVals:m,outShape:g,outDtype:y}=iY(p.shape,p.dtype,f,u);h=n.makeTensorInfo(g,y,m)}else{let[f,m]=E.computeOutAndReduceShapes(p.shape,u),g=v.sizeFromShape(m),y=be({inputs:{x:p},backend:n,attrs:{shape:[-1,g]}}),A=fd(r.dtype),x=vl(y,A,"prod",n);h=be({inputs:{x},backend:n,attrs:{shape:f}}),l.push(y),l.push(x)}if(o){l.push(h);let f=E.expandShapeToKeepDim(h.shape,c);h=be({inputs:{x:h},backend:n,attrs:{shape:f}})}return l.forEach(f=>n.disposeIntermediateTensorInfo(f)),h}var Qse={kernelName:Ci,backendName:"webgl",kernelFunc:Jse},gS=e=>{let{backend:t,attrs:n}=e,{start:s,stop:r,step:a,dtype:o}=n,i=lY(s,r,a,o);return t.makeTensorInfo([i.length],o,i)},ere={kernelName:pu,backendName:"webgl",kernelFunc:gS},tre="return 1.0 / x;",nre=it({opSnippet:tre}),sre={kernelName:hu,backendName:"webgl",kernelFunc:nre},rre=br+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,are=`
|
|
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
|
|
bvec4 isNaN = isnan(x);
|
|
|
|
result.r = isNaN.r ? x.r : result.r;
|
|
result.g = isNaN.g ? x.g : result.g;
|
|
result.b = isNaN.b ? x.b : result.b;
|
|
result.a = isNaN.a ? x.a : result.a;
|
|
|
|
return result;
|
|
`,ore=it({opSnippet:rre,packedOpSnippet:are}),ire={kernelName:Qa,backendName:"webgl",kernelFunc:ore},lre=br+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,ure=`
|
|
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
|
|
bvec4 isNaN = isnan(x);
|
|
|
|
result.r = isNaN.r ? x.r : result.r;
|
|
result.g = isNaN.g ? x.g : result.g;
|
|
result.b = isNaN.b ? x.b : result.b;
|
|
result.a = isNaN.a ? x.a : result.a;
|
|
|
|
return result;
|
|
`,cre=it({opSnippet:lre,packedOpSnippet:ure}),dre={kernelName:to,backendName:"webgl",kernelFunc:cre},pre=class{constructor(e,t,n,s,r){this.variableNames=["A"],this.outputShape=[];let[a,o,i,l]=e;this.outputShape=[a,t,n,l];let c=[s&&t>1?o-1:o,s&&n>1?i-1:i],u=[s&&t>1?t-1:t,s&&n>1?n-1:n],d;r?d="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${c[0]/u[0]},
|
|
${c[1]/u[1]});
|
|
const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
ivec2 yRC = coords.yz;
|
|
|
|
// Fractional source index.
|
|
vec2 sourceFracIndexRC = ${d};
|
|
|
|
// Compute the four integer indices.
|
|
ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));
|
|
ivec2 sourceCeilRC = ivec2(
|
|
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
|
|
|
|
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
|
|
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
|
|
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
|
|
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
|
|
|
|
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
|
|
|
|
float top = topLeft + (topRight - topLeft) * fracRC.y;
|
|
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
|
|
float newValue = top + (bottom - top) * fracRC.x;
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}},hre=class{constructor(e,t,n,s,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,l]=e;this.outputShape=[a,t,n,l];let c=[s&&t>1?o-1:o,s&&n>1?i-1:i],u=[s&&t>1?t-1:t,s&&n>1?n-1:n],d;r?d="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${c[0]/u[0]},
|
|
${c[1]/u[1]},
|
|
${c[1]/u[1]});
|
|
const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,
|
|
${i}.0);
|
|
|
|
float getAValue(int b, int r, int c, int d) {
|
|
return getChannel(getA(b, r, c, d), vec2(c, d));
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
// Calculate values for next column in yRC.z.
|
|
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
|
|
|
|
// Fractional source index.
|
|
vec3 sourceFracIndexRC = ${d};
|
|
|
|
// Compute the four integer indices.
|
|
ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));
|
|
ivec3 sourceCeilRC = ivec3(
|
|
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
|
|
|
|
// Should we calculate next column and row elements in 2x2 packed cell.
|
|
bool hasNextCol = d < ${l-1};
|
|
bool hasNextRow = coords.z < ${n-1};
|
|
|
|
// In parallel, construct four corners for all four components in
|
|
// packed 2x2 cell.
|
|
vec4 topLeft = vec4(
|
|
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
|
|
|
|
vec4 bottomLeft = vec4(
|
|
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
|
|
|
|
vec4 topRight = vec4(
|
|
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
|
|
|
|
vec4 bottomRight = vec4(
|
|
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
|
|
|
|
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
|
|
|
|
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
|
|
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
|
|
vec4 newValue = mix(top, bottom, fracRC.x);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}};function fre(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:o,size:i}=s,[l,c]=i,u=Z().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new hre(r.shape,l,c,a,o):new pre(r.shape,l,c,a,o);return n.runWebGLProgram(u,[r],"float32")}var mre={kernelName:eo,backendName:"webgl",kernelFunc:fre},gre=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,s,r]=t,[,a,o]=e,i=[n&&a>1?s-1:s,n&&o>1?r-1:r],l=[n&&a>1?a-1:a,n&&o>1?o-1:o],c=i[0]/l[0],u=i[1]/l[1],d=1/c,p=1/u,h=Math.ceil(d)*2+2,f=Math.ceil(p)*2+2;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float accumulator = 0.0;
|
|
|
|
const float heightScale = float(${c});
|
|
const float widthScale = float(${u});
|
|
|
|
const float invHeightScale = float(${d});
|
|
const float invWidthScale = float(${p});
|
|
|
|
const int winHeight = int(${h});
|
|
const int winWidth = int(${f});
|
|
|
|
// Compute bounds for where in dy we will look
|
|
float startRLerp = floor(float(r) * invHeightScale);
|
|
int startDyR = int(startRLerp - float(winHeight / 2));
|
|
|
|
float startCLerp = floor(float(c) * invWidthScale);
|
|
int startDyC = int(startCLerp - float(winWidth / 2));
|
|
|
|
// Loop over dy
|
|
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
|
|
int dyR = dyROffset + startDyR;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyR < 0 || dyR >= ${a}) {
|
|
continue;
|
|
}
|
|
|
|
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
|
|
int dyC = dyCOffset + startDyC;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= ${o}) {
|
|
continue;
|
|
}
|
|
|
|
float dxR = float(dyR) * heightScale;
|
|
int topDxRIndex = int(floor(dxR));
|
|
int bottomDxRIndex = int(min(ceil(dxR), ${s-1}.0));
|
|
float dxRLerp = dxR - float(topDxRIndex);
|
|
float inverseDxRLerp = 1.0 - dxRLerp;
|
|
|
|
float dxC = float(dyC) * widthScale;
|
|
int leftDxCIndex = int(floor(dxC));
|
|
int rightDxCIndex = int(min(ceil(dxC), ${r-1}.0));
|
|
float dxCLerp = dxC - float(leftDxCIndex);
|
|
float inverseDxCLerp = 1.0 - dxCLerp;
|
|
|
|
if (r == topDxRIndex && c == leftDxCIndex) {
|
|
// topLeft
|
|
accumulator +=
|
|
getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
|
|
}
|
|
|
|
if (r == topDxRIndex && c == rightDxCIndex) {
|
|
// topRight
|
|
accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
|
|
}
|
|
|
|
if (r == bottomDxRIndex && c == leftDxCIndex) {
|
|
// bottomLeft
|
|
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
|
|
}
|
|
|
|
if (r == bottomDxRIndex && c == rightDxCIndex) {
|
|
// bottomRight
|
|
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
|
|
}
|
|
}
|
|
}
|
|
// End loop over dy
|
|
|
|
setOutput(accumulator);
|
|
}
|
|
`}};function yre(e){let{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:o}=s,i=new gre(a.shape,r.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var Are={kernelName:Oh,backendName:"webgl",kernelFunc:yre},xre=class{constructor(e,t,n,s,r){this.variableNames=["A"],this.outputShape=[];let[a,o,i,l]=e;this.outputShape=[a,t,n,l];let c=[s&&t>1?o-1:o,s&&n>1?i-1:i],u=[s&&t>1?t-1:t,s&&n>1?n-1:n],d=s?"0.5":"0.0",p;r?p="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${c[0]/u[0]},
|
|
${c[1]/u[1]});
|
|
const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
ivec2 yRC = coords.yz;
|
|
|
|
// Fractional source index.
|
|
vec2 sourceFracIndexRC = ${p};
|
|
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec2 sourceNearestRC = ivec2(
|
|
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
|
|
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}},bre=class{constructor(e,t,n,s,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,l]=e;this.outputShape=[a,t,n,l];let c=[s&&t>1?o-1:o,s&&n>1?i-1:i],u=[s&&t>1?t-1:t,s&&n>1?n-1:n],d=s?"0.5":"0.0",p;r?p="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${c[0]/u[0]},
|
|
${c[1]/u[1]},
|
|
${c[1]/u[1]});
|
|
const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,
|
|
${i}.0);
|
|
|
|
float getAValue(int b, int r, int c, int d) {
|
|
return getChannel(getA(b, r, c, d), vec2(c, d));
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
// Calculate values for next column in yRC.z.
|
|
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
|
|
|
|
// Fractional source index.
|
|
vec3 sourceFracIndexRC = ${p};
|
|
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec3 sourceNearestRC = ivec3(
|
|
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
|
|
|
|
// Should we calculate next column and row elements in 2x2 packed cell.
|
|
bool hasNextCol = d < ${l-1};
|
|
bool hasNextRow = coords.z < ${n-1};
|
|
|
|
vec4 newValue = vec4(
|
|
getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}};function vre(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:o,size:i}=s,[l,c]=i,u=Z().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new bre(r.shape,l,c,a,o):new xre(r.shape,l,c,a,o);return n.runWebGLProgram(u,[r],r.dtype)}var wre={kernelName:fu,backendName:"webgl",kernelFunc:vre},kre=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,s,r]=t,[,a,o]=e,i=[n&&a>1?s-1:s,n&&o>1?r-1:r],l=[n&&a>1?a-1:a,n&&o>1?o-1:o],c=i[0]/l[0],u=i[1]/l[1],d=1/c,p=1/u,h=Math.ceil(d)*2+2,f=Math.ceil(p)*2+2;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float accumulator = 0.0;
|
|
|
|
const float heightScale = float(${c});
|
|
const float widthScale = float(${u});
|
|
|
|
const float invHeightScale = float(${d});
|
|
const float invWidthScale = float(${p});
|
|
|
|
const int winHeight = int(${h});
|
|
const int winWidth = int(${f});
|
|
|
|
// Compute bounds for where in dy we will look
|
|
float startRLerp = floor(float(r) * invHeightScale);
|
|
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
|
|
|
|
float startCLerp = floor(float(c) * invWidthScale);
|
|
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
|
|
|
|
// Loop over dy
|
|
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
|
|
int dyR = dyROffset + startDyR;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyR < 0 || dyR >= ${a}) {
|
|
continue;
|
|
}
|
|
|
|
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
|
|
int dyC = dyCOffset + startDyC;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= ${o}) {
|
|
continue;
|
|
}
|
|
|
|
float sourceFracRow =
|
|
float(${i[0]}) *
|
|
(float(dyR) / float(${l[0]}));
|
|
|
|
float sourceFracCol =
|
|
float(${i[1]}) *
|
|
(float(dyC) / float(${l[1]}));
|
|
|
|
int sourceNearestRow = int(min(
|
|
float(int(${s}) - 1),
|
|
${n} ? float(round(sourceFracRow)) :
|
|
float(floor(sourceFracRow))));
|
|
|
|
int sourceNearestCol = int(min(
|
|
float(int(${r}) - 1),
|
|
${n} ? float(round(sourceFracCol)) :
|
|
float(floor(sourceFracCol))));
|
|
|
|
if (r == sourceNearestRow && c == sourceNearestCol) {
|
|
accumulator += getDy(b, dyR, dyC, d);
|
|
}
|
|
}
|
|
}
|
|
// End loop over dy
|
|
|
|
setOutput(accumulator);
|
|
}
|
|
`}};function Ire(e){let{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:o}=s,i=new kre(a.shape,r.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var Sre={kernelName:Fh,backendName:"webgl",kernelFunc:Ire},Cre=class{constructor(e,t){this.variableNames=["x"];let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,n===1){this.userCode=`
|
|
void main() {
|
|
int coord = getOutputCoords();
|
|
setOutput(getX(${e[0]} - coord - 1));
|
|
}
|
|
`;return}let s=o=>t.indexOf(o)!==-1&&e[o]!==1?`${e[o]} - coords[${o}] - 1`:`coords[${o}]`,r=e.map((o,i)=>s(i)).join(","),a=St(n);this.userCode=`
|
|
void main() {
|
|
${a} coords = getOutputCoords();
|
|
setOutput(getX(${r}));
|
|
}
|
|
`}},Tre=class{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;let s=Hn("rc",n),r=`${s[n-1]} + 1 < ${this.outputShape[n-1]}`,a=`${s[n-2]} + 1 < ${this.outputShape[n-2]}`,o=St(n);n===1?this.userCode=`
|
|
void main(){
|
|
int rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result.r = getChannel(getX(${e[0]} - rc - 1),
|
|
${e[0]} - rc - 1);
|
|
if(${r}){
|
|
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
|
|
${e[0]} - (rc + 1) - 1);
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`:this.userCode=`
|
|
void main() {
|
|
${o} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result.r = ${i(s.slice())};
|
|
if(${r}){
|
|
result.g = ${l(s.slice())};
|
|
}
|
|
if(${a}) {
|
|
result.b = ${c(s.slice())};
|
|
if(${r}) {
|
|
result.a = ${u(s.slice())};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`;function i(h){return d(h)}function l(h){return h[n-1]="("+h[n-1]+" + 1)",d(h)}function c(h){return h[n-2]="("+h[n-2]+" + 1)",d(h)}function u(h){return h[n-1]="("+h[n-1]+" + 1)",h[n-2]="("+h[n-2]+" + 1)",d(h)}function d(h){let f=e.map((y,A)=>p(A,h)),m=f.join(","),g=f.slice(-2).join(",");return`getChannel(getX(${m}), vec2(${g}))`}function p(h,f){return t.indexOf(h)!==-1&&e[h]!==1?`${e[h]} - ${f[h]} - 1`:`${f[h]}`}}};function Nre(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s,o=r.shape.length,i=v.parseAxisParam(a,r.shape);if(o===0)return Cs({inputs:{x:r},backend:n});let l=Z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Tre(r.shape,i):new Cre(r.shape,i);return n.runWebGLProgram(l,[r],r.dtype)}var Ere={kernelName:Ni,backendName:"webgl",kernelFunc:Nre},Rre=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let n=e[1],s=e[2];this.outputShape=e;let r="";typeof t=="number"?r=`float outputValue = ${t.toFixed(2)};`:r=`
|
|
vec3 fill = vec3(${t.join(",")});
|
|
float outputValue = fill[coords[3]];`,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int x = coords[2];
|
|
int y = coords[1];
|
|
float coordXFloat = (float(x) - params[0]) * params[3] -
|
|
(float(y) - params[1]) * params[2];
|
|
float coordYFloat = (float(x) - params[0]) * params[2] +
|
|
(float(y) - params[1]) * params[3];
|
|
int coordX = int(round(coordXFloat + params[0]));
|
|
int coordY = int(round(coordYFloat + params[1]));
|
|
${r}
|
|
if(coordX >= 0 && coordX < ${s} && coordY >= 0 && coordY < ${n}) {
|
|
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}},$re={kernelName:Wi,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:s}=e,{radians:r,fillValue:a,center:o}=t,i=n,l=new Rre(s.shape,a),[c,u]=E.getImageCenter(o,s.shape[1],s.shape[2]),d=[[c,u,Math.sin(r),Math.cos(r)]];return i.runWebGLProgram(l,[s],s.dtype,d)}},Dre=`
|
|
// OpenGL ES does not support round function.
|
|
// The algorithm is based on banker's rounding.
|
|
float base = floor(x);
|
|
if ((x - base) < 0.5) {
|
|
return floor(x);
|
|
} else if ((x - base) > 0.5) {
|
|
return ceil(x);
|
|
} else {
|
|
if (mod(base, 2.0) == 0.0) {
|
|
return base;
|
|
} else {
|
|
return base + 1.0;
|
|
}
|
|
}
|
|
`,_re=it({opSnippet:Dre}),Pre={kernelName:Ei,backendName:"webgl",kernelFunc:_re},Fre="return inversesqrt(x);",Ore=it({opSnippet:Fre,cpuKernelImpl:uY}),Mre={kernelName:no,backendName:"webgl",kernelFunc:Ore},yS=class{constructor(e,t,n,s,r,a,o=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;let i=St(r.length),l=St(a.length),c="";n===1?c="i":n===2&&(c="i, j");let u=`getIndices(${c})`,d="";s===1?d="i":s===2&&(d="i, coords[1]");let p=`getUpdates(${d})`,h=t>1?"strides[j]":"strides";this.userCode=`
|
|
${i} strides = ${i}(${r});
|
|
|
|
void main() {
|
|
${l} coords = getOutputCoords();
|
|
float sum = 0.0;
|
|
bool found = false;
|
|
for (int i = 0; i < ${e}; i++) {
|
|
int flattenedIndex = 0;
|
|
for (int j = 0; j < ${t}; j++) {
|
|
int index = round(${u});
|
|
flattenedIndex += index * ${h};
|
|
}
|
|
if (flattenedIndex == coords[0]) {
|
|
sum += ${p};
|
|
found = true;
|
|
}
|
|
}
|
|
setOutput(mix(getDefaultValue(), sum, float(found)));
|
|
}
|
|
`}};function zre(e){let{inputs:t,backend:n,attrs:s}=e,{indices:r,updates:a}=t,{shape:o}=s,{sliceRank:i,numUpdates:l,sliceSize:c,strides:u,outputSize:d}=E.calculateShapes(a,r,o),p=[d/c,c];if(d===0)return n.makeTensorInfo(o,r.dtype);let h=be({inputs:{x:r},backend:n,attrs:{shape:[l,i]}}),f=be({inputs:{x:a},backend:n,attrs:{shape:[l,c]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new yS(l,i,h.shape.length,f.shape.length,u,p),y=n.runWebGLProgram(g,[f,h,m],f.dtype),A=be({inputs:{x:y},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(m),A}var Lre={kernelName:Ri,backendName:"webgl",kernelFunc:zre},Bre=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let s,r;if(n>4)throw Error(`Where for rank ${n} is not yet supported`);if(n===1)r="resRC",s="resRC";else{let o=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],l=[];for(let c=0;c<t.length;c++)l.push(`${o[c]}`),c<e&&i.push(`${o[c]}`);s=i.join(),r=l.join()}let a=St(n);this.userCode=`
|
|
void main() {
|
|
${a} resRC = getOutputCoords();
|
|
float cVal = getC(${s});
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(${r}));
|
|
} else {
|
|
setOutput(getB(${r}));
|
|
}
|
|
}
|
|
`}};function Wre(e){let{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t,o=new Bre(s.shape.length,r.shape,r.shape.length);return n.runWebGLProgram(o,[s,r,a],Ln(r.dtype,a.dtype))}var Vre={kernelName:$i,backendName:"webgl",kernelFunc:Wre},Ure=`
|
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
|
// see: https://arxiv.org/abs/1706.02515
|
|
float scaleAlpha = ${E.SELU_SCALEALPHA};
|
|
float scale = ${E.SELU_SCALE};
|
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
|
`,Gre=it({opSnippet:Ure}),Hre={kernelName:mu,backendName:"webgl",kernelFunc:Gre},AS="return 1.0 / (1.0 + exp(-1.0 * x));",jre=it({opSnippet:AS,packedOpSnippet:AS,cpuKernelImpl:cY}),qre={kernelName:ro,backendName:"webgl",kernelFunc:jre},Xre=`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`,Kre=it({opSnippet:Xre}),Zre={kernelName:gu,backendName:"webgl",kernelFunc:Kre},Yre=$4+`
|
|
return sin(x);
|
|
`,Jre=it({opSnippet:Yre}),Qre={kernelName:so,backendName:"webgl",kernelFunc:Jre},eae=`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,tae=it({opSnippet:eae}),nae={kernelName:_i,backendName:"webgl",kernelFunc:tae},sae=`
|
|
float epsilon = 1.1920928955078125e-7;
|
|
float threshold = log(epsilon) + 2.0;
|
|
|
|
bool too_large = x > -threshold;
|
|
bool too_small = x < threshold;
|
|
|
|
float result;
|
|
float exp_x = exp(x);
|
|
|
|
if (too_large){
|
|
result = x;
|
|
}
|
|
else if (too_small){
|
|
result = exp_x;
|
|
}
|
|
else{
|
|
result = log(exp_x + 1.0);
|
|
}
|
|
return result;
|
|
`,rae=it({opSnippet:sae}),aae={kernelName:yu,backendName:"webgl",kernelFunc:rae},oae=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:o}=s;v.assert(r.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((y,A)=>y*A),l=[[0,0]];l.push(...o);for(let y=1+a.length;y<r.shape.length;++y)l.push([0,0]);let c=[],u=mS({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),d=E.getReshaped(u.shape,a,i,!1),p=E.getPermuted(d.length,a.length,!1),h=E.getReshapedPermuted(u.shape,a,i,!1),f=be({inputs:{x:u},backend:n,attrs:{shape:d}}),m=jn({inputs:{x:f},backend:n,attrs:{perm:p}}),g=be({inputs:{x:m},backend:n,attrs:{shape:h}});return c.push(u),c.push(f),c.push(m),c.forEach(y=>n.disposeIntermediateTensorInfo(y)),g},iae={kernelName:Pi,backendName:"webgl",kernelFunc:oae};function lae(e){let{inputs:t,backend:n}=e,{indices:s,values:r,denseShape:a,defaultValue:o}=t;if(a.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
|
|
${a.shape}`);if(s.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
|
|
${s.shape}`);if(r.shape.length!==1)throw new Error(`Values must be a vector, saw:
|
|
${r.shape}`);if(o.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${o.shape}`);let i=n.readSync(s.dataId),l=n.readSync(r.dataId),c=n.readSync(a.dataId),u=n.readSync(o.dataId)[0],[d,p,h,f,m]=pY(i,s.shape,s.dtype,l,r.dtype,c,u);return[n.makeTensorInfo(p,s.dtype,d),n.makeTensorInfo([p[0]],r.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),n.makeTensorInfo([m.length],s.dtype,new Int32Array(m))]}var uae={kernelName:Mh,backendName:"webgl",kernelFunc:lae};function cae(e){let{inputs:t,backend:n}=e,{inputIndices:s,inputShape:r,newShape:a}=t;if(s.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${s.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${r.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);let o=Array.from(n.readSync(r.dataId)),i=n.readSync(s.dataId),l=Array.from(n.readSync(a.dataId)),[c,u,d]=hY(i,s.shape,s.dtype,o,l);return[n.makeTensorInfo(u,s.dtype,c),n.makeTensorInfo([d.length],a.dtype,new Int32Array(d))]}var dae={kernelName:zh,backendName:"webgl",kernelFunc:cae};function pae(e){let{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${r.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${a.shape}`);let o=n.readSync(s.dataId),i=n.readSync(r.dataId),l=n.readSync(a.dataId),[c,u]=A4(o,s.shape,s.dtype,i,l,!0);return n.makeTensorInfo(u,s.dtype,c)}var hae={kernelName:Lh,backendName:"webgl",kernelFunc:pae};function fae(e){let{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${r.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${a.shape}`);let o=n.readSync(s.dataId),i=n.readSync(r.dataId),l=n.readSync(a.dataId),[c,u]=A4(o,s.shape,s.dtype,i,l);return n.makeTensorInfo(u,s.dtype,c)}var mae={kernelName:Bh,backendName:"webgl",kernelFunc:fae};function gae(e){let{inputs:t,backend:n,attrs:s}=e,{sparseIndices:r,sparseValues:a,defaultValue:o}=t,{outputShape:i}=s,{sliceRank:l,numUpdates:c,strides:u,outputSize:d}=E.calculateShapes(a,r,i),p=!1,h=new yS(c,l,r.shape.length,a.shape.length,u,[d,1],p),f=n.runWebGLProgram(h,[a,r,o],a.dtype),m=be({inputs:{x:f},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(f),m}var yae={kernelName:nd,backendName:"webgl",kernelFunc:gae};function Aae(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{numOrSizeSplits:a,axis:o}=s,i=v.parseAxisParam(o,r.shape)[0],l=E.prepareSplitSize(r,a,i),c=r.shape.length,u=new Array(c).fill(0),d=r.shape.slice();return l.map(p=>{let h=[...d];h[i]=p;let f=uc({inputs:{x:r},backend:n,attrs:{begin:u,size:h}});return u[i]+=p,f})}var xae={kernelName:Fi,backendName:"webgl",kernelFunc:Aae},xS="return sqrt(x);",bae=it({opSnippet:xS,packedOpSnippet:xS,cpuKernelImpl:fY}),vae={kernelName:ao,backendName:"webgl",kernelFunc:bae},wae="return x * x;",kae=it({opSnippet:wae}),Iae={kernelName:Au,backendName:"webgl",kernelFunc:kae},bS="return (a - b) * (a - b);",Sae=En({opSnippet:bS,packedOpSnippet:bS}),Cae={kernelName:lo,backendName:"webgl",kernelFunc:Sae};function Tae({inputs:e,attrs:t,backend:n}){let{x:s}=e,r=br+`
|
|
return x > 0.0 ? 1.0 : float(${t.alpha});
|
|
`,a=new Oo(s.shape,r);return n.runWebGLProgram(a,[s],s.dtype)}var Nae={kernelName:ho,backendName:"webgl",kernelFunc:Tae},Eae=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let s=n.length,r=St(n.length),a=St(n.length),o="";if(s===1)o="coords * strides + begin";else{let i=0;o=n.map((l,c)=>(i++,n.length===1?`coords * strides[${c}] + begin[${c}]`:`coords[${i-1}] * strides[${c}] + begin[${c}]`)).join(",")}this.userCode=`
|
|
${r} begin = ${r}(${e});
|
|
${r} strides = ${r}(${t});
|
|
|
|
void main() {
|
|
${a} coords = getOutputCoords();
|
|
setOutput(getX(${o}));
|
|
}
|
|
`}};function Rae(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=s,{nonStrided:h,$begin:f,$strides:m,size:g,newShape:y,outShape:A}=yn.sliceInfo(r.shape,a,o,i,l,c,u,d,p),x=be({inputs:{x:r},backend:n,attrs:{shape:y}}),b;if(h){let k=uc({inputs:{x},backend:n,attrs:{begin:f,size:g}});b=be({inputs:{x:k},backend:n,attrs:{shape:A}}),n.disposeIntermediateTensorInfo(k)}else if(A.some(k=>k===0))b=n.makeTensorInfo(A,r.dtype,[]);else if(n.shouldExecuteOnCPU([x])){let N=n.texData.get(x.dataId).values,$=We(x.shape,x.dtype,N),F=mY(A,$,m,f);b=n.makeTensorInfo(A,x.dtype,F.values)}else{let S=new Eae(f,m,A);b=n.runWebGLProgram(S,[x],x.dtype)}let w=be({inputs:{x:b},backend:n,attrs:{shape:A}});return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(b),w}var $ae={kernelName:Oi,backendName:"webgl",kernelFunc:Rae};function Dae(e){let{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:c}=s,{data:u,dataSplits:d}=t,p=n.readSync(u.dataId),h=n.readSync(d.dataId),[f,m]=gY(p,h,r,a,o,i,l,c);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var _ae={kernelName:sd,backendName:"webgl",kernelFunc:Dae};function Pae(e){let{inputs:t,backend:n,attrs:s}=e,{skipEmpty:r}=s,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.readSync(a.dataId),l=n.readSync(o.dataId)[0],[c,u,d]=yY(i,l,r),p=u.length;return[n.makeTensorInfo([p,2],"int32",c),n.makeTensorInfo([p],"string",u),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var Fae={kernelName:Wh,backendName:"webgl",kernelFunc:Pae};function Oae(e){let{inputs:t,backend:n,attrs:s}=e,{numBuckets:r}=s,{input:a}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");let o=n.readSync(a.dataId),i=AY(o,r);return n.makeTensorInfo(a.shape,"int32",i)}var Mae={kernelName:Vh,backendName:"webgl",kernelFunc:Oae},zae="return tan(x);",Lae=it({opSnippet:zae}),Bae={kernelName:Mi,backendName:"webgl",kernelFunc:Lae},Wae=`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,Vae=it({opSnippet:Wae}),Uae={kernelName:co,backendName:"webgl",kernelFunc:Vae},Gae=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[a]*t[a];this.outputShape=n,this.rank=n.length;let s=St(this.rank),r=Hae(e);this.userCode=`
|
|
void main() {
|
|
${s} resRC = getOutputCoords();
|
|
setOutput(getA(${r}));
|
|
}
|
|
`}};function Hae(e){let t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${e[0]})`;let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],s=[];for(let r=0;r<e.length;r++)s.push(`imod(${n[r]}, ${e[r]})`);return s.join()}function vS(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reps:a}=s;if(r.dtype==="string"||r.shape.length>5){let l=n.readSync(r.dataId),c=r.dtype==="string"?l.map(p=>v.decodeString(p)):l,u=We(r.shape,r.dtype,c),d=bY(u,a);return n.makeTensorInfo(d.shape,d.dtype,d.values)}let o=new Gae(r.shape,a);return n.runWebGLProgram(o,[r],r.dtype)}var jae={kernelName:Kr,backendName:"webgl",kernelFunc:vS},qae=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int elemIdx = coords[1];
|
|
|
|
// We compare elements pair-wise within a group of size 2 * inc.
|
|
// The comparing rule for each group alternates between ascending
|
|
// and descending. Within each group, we compare each pair at
|
|
// positions i and i+inc. To decide whether an element at position i
|
|
// is x0 or x1, we mod it by 2 * inc, if the result is smaller than
|
|
// inc, it is in the first half of the group, we denote it as x0,
|
|
// otherwise we denote it as x1.
|
|
// For example, as shown in the Bitonic top K paper referenced above,
|
|
// Figure5(a) shows that element[1] is in the
|
|
// second half of the group when group size is 2, but it is in the
|
|
// first half of the group when group size is 4.
|
|
|
|
bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;
|
|
int i = isFirstInPair ? elemIdx : elemIdx - inc;
|
|
|
|
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
|
|
int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));
|
|
float x0 = i0 < n ? getX(batch, i0) : negativeInf;
|
|
float x1 = i1 < n ? getX(batch, i1) : negativeInf;
|
|
|
|
// Denotes which direction indices are in (ascending or descending).
|
|
bool reverse = imod(elemIdx, 2 * dir) >= dir;
|
|
bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);
|
|
if (reverse == isGreater) { // Elements in opposite order of direction
|
|
int iTemp = i0;
|
|
i0 = i1;
|
|
i1 = iTemp;
|
|
}
|
|
if (isFirstInPair) {
|
|
setOutput(float(i0));
|
|
} else {
|
|
setOutput(float(i1));
|
|
}
|
|
}
|
|
`}},Xae=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
// Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int elemIdx = coords[1];
|
|
|
|
// The output size is half of the previous size.
|
|
// If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),
|
|
// we only need to output the indices at positions |, the indices at
|
|
// positions _ can be thrown away, see Figure5(b) After Phase 2
|
|
// (Merge phase) in the Bitonic Top K paper referenced above.
|
|
// For example, the paper shows we only need to output the orange bars.
|
|
// The output sequence should look like this | | | | | | | |.
|
|
// Because the sequence is halved, to map the output index back
|
|
// to the previous sequence to find the corresponding value,
|
|
// we need to double the index. When we double the index,
|
|
// we basically interpolate a position, so 2i looks like
|
|
// | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position
|
|
// of each 2k positions by - elemIdx % k. E.g. for output at
|
|
// index 4,5,6,7, we want to get the corresponding element at
|
|
// original index 8,9,10,11, for output at index 8,9,10,11,
|
|
// we want to get the corresponding element at original index
|
|
// 16,17,18,19, so on and so forth.
|
|
|
|
int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));
|
|
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
|
|
int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));
|
|
|
|
float x0 = getX(batch, i0);
|
|
float x1 = i1 < n ? getX(batch, i1) : x0;
|
|
|
|
setOutput(x0 >= x1 ? float(i0) : float(i1));
|
|
}
|
|
`}};function wl(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function wS(e){let t=1;for(;t<e;)t*=2;return t}function Kae(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{k:a,sorted:o}=s,i=Z().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),l=Z().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),c=r.shape,u=c[c.length-1];if(n.shouldExecuteOnCPU([r])||u<i||a>l){let F=n.readSync(r.dataId),[R,D]=vY(F,c,r.dtype,a,o);return[n.makeTensorInfo(R.shape,R.dtype,R.values),n.makeTensorInfo(D.shape,D.dtype,D.values)]}if(a===0)return c[c.length-1]=0,[n.makeTensorInfo(c,r.dtype,[]),n.makeTensorInfo(c,"int32",[])];if(u===1)return[r,gp({attrs:{shape:c,dtype:"int32",value:0},backend:n})];let d=n.texData.get(r.dataId),p=d!==null&&d.isPacked,h=p?n.unpackTensor(r):r,m=v.sizeFromShape(c)/u,g=be({inputs:{x:h},attrs:{shape:[m,u]},backend:n});p&&wl(n,h);let y=wS(a),A=wS(u),x=null,b=()=>x===null?[g,g]:[g,x],w=(F,R,D)=>{let T=b(),O=new qae(D),H=[[u],[x===null?1:0],[Number.NEGATIVE_INFINITY],[F],[R]],z=x;x=n.runWebGLProgram(O,T,"int32",H),wl(n,z)};for(let F=1;F<y;F*=2){let R=F*2;for(let D=F;D>=1;D/=2)w(R,D,[m,A])}for(let F=A;F>y;F/=2){let R=b(),D=new Xae([m,F/2]),O=[[u],[x===null?1:0],[y]],B=x;x=n.runWebGLProgram(D,R,"int32",O),wl(n,B);let H=y/2,z=H*2;for(let X=H;X>=1;X/=2)w(z,X,x.shape)}let k=x;x=uc({inputs:{x},backend:n,attrs:{begin:0,size:[m,a]}}),wl(n,k);let S=iS({inputs:{x:g,indices:x},backend:n,attrs:{axis:1,batchDims:1}});wl(n,g);let N=c.slice(0,-1);N.push(a),k=x,x=be({inputs:{x},attrs:{shape:N},backend:n}),wl(n,k);let $=S;return S=be({inputs:{x:S},attrs:{shape:N},backend:n}),wl(n,$),[S,x]}var Zae={kernelName:xu,backendName:"webgl",kernelFunc:Kae},Yae=class{constructor(e,t,n,s,r,a){this.variableNames=["Image","Transforms"],this.outputShape=a;let o=n==="nearest"?1:2,i;switch(s){case"constant":i=1;break;case"reflect":i=2;break;case"wrap":i=3;break;case"nearest":i=4;break;default:i=1;break}this.userCode=`
|
|
float mapCoord(float outCoord, float len) {
|
|
float inCoord = outCoord;
|
|
if(${i} == 2) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz2 = 2.0 * len;
|
|
if (inCoord < sz2) {
|
|
inCoord = sz2 * float(int(float(-inCoord / sz2))) +
|
|
inCoord;
|
|
}
|
|
inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz2 = 2.0 * len;
|
|
inCoord -= sz2 * float(int(float(inCoord / sz2)));
|
|
if (inCoord >= len) {
|
|
inCoord = sz2 - inCoord - 1.0;
|
|
}
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (${i} == 3) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz = len - 1.0;
|
|
inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz = len - 1.0;
|
|
inCoord -= len * float(int(float(inCoord / sz)));
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (${i} == 4) {
|
|
return clamp(outCoord, 0.0, len - 1.0);
|
|
} else {
|
|
return outCoord;
|
|
}
|
|
}
|
|
|
|
float readWithFillValue(int batch, int coordY, int coordX,
|
|
int channel) {
|
|
float outputValue;
|
|
if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {
|
|
outputValue = getImage(batch, coordY, coordX, channel);
|
|
} else {
|
|
outputValue = float(${r});
|
|
}
|
|
return outputValue;
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
float outputValue;
|
|
int batch = coords[0];
|
|
int x = coords[2];
|
|
int y = coords[1];
|
|
int channel = coords[3];
|
|
float xf = float(x);
|
|
float yf = float(y);
|
|
float a1 = getTransforms(batch, 0);
|
|
float a2 = getTransforms(batch, 1);
|
|
float a3 = getTransforms(batch, 2);
|
|
float b1 = getTransforms(batch, 3);
|
|
float b2 = getTransforms(batch, 4);
|
|
float b3 = getTransforms(batch, 5);
|
|
float c1 = getTransforms(batch, 6);
|
|
float c2 = getTransforms(batch, 7);
|
|
float projection = c1 * xf + c2 * yf + 1.0;
|
|
if (projection == 0.0) {
|
|
outputValue = float(${r});
|
|
} else {
|
|
float inX = (a1 * xf + a2 * yf + a3) / projection;
|
|
float inY = (b1 * xf + b2 * yf + b3) / projection;
|
|
float mapX = mapCoord(inX, float(${t}));
|
|
float mapY = mapCoord(inY, float(${e}));
|
|
|
|
if (${o} == 1) {
|
|
int coordY = int(round(mapY));
|
|
int coordX = int(round(mapX));
|
|
outputValue = readWithFillValue(batch, coordY, coordX,
|
|
channel);
|
|
} else {
|
|
float yFloor = floor(mapY);
|
|
float xFloor = floor(mapX);
|
|
float yCeil = yFloor + 1.0;
|
|
float xCeil = xFloor + 1.0;
|
|
float valueYFloor = (xCeil - mapX) *
|
|
readWithFillValue(batch, int(yFloor), int(xFloor), channel) +
|
|
(mapX - xFloor) *
|
|
readWithFillValue(batch, int(yFloor), int(xCeil), channel);
|
|
float valueYCeil = (xCeil - mapX) *
|
|
readWithFillValue(batch, int(yCeil), int(xFloor), channel) +
|
|
(mapX - xFloor) *
|
|
readWithFillValue(batch, int(yCeil), int(xCeil), channel);
|
|
outputValue = (yCeil - mapY) * valueYFloor +
|
|
(mapY - yFloor) * valueYCeil;
|
|
}
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}};function Jae(e){let{inputs:t,backend:n,attrs:s}=e,{image:r,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:l,outputShape:c}=s,[u,d,p,h]=r.shape,[f,m]=c!=null?c:[d,p],g=[u,f,m,h],y=new Yae(d,p,o,i,l,g);return n.runWebGLProgram(y,[r,a],"float32")}var Qae={kernelName:zi,backendName:"webgl",kernelFunc:Jae};function eoe(e){let{inputs:t,attrs:n,backend:s}=e,{axis:r}=n,{x:a}=t;tc(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let o=s.readSync(a.dataId),{outputValues:i,outputShape:l,indices:c}=wY(o,r,a.shape,a.dtype);return[s.makeTensorInfo(l,a.dtype,i),s.makeTensorInfo([c.length],"int32",c)]}var toe={kernelName:Uh,backendName:"webgl",kernelFunc:eoe};function noe(e){let{inputs:t,backend:n,attrs:s}=e,{value:r}=t,{axis:a}=s;a<0&&(a+=r.shape.length);let o=r,i=o.shape.length,l=r.shape[a],c=new Array(i-1),u=0;for(let m=0;m<i;m++)m!==a&&(c[u++]=o.shape[m]);let d=[],p=new Array(i).fill(0),h=o.shape.slice();h[a]=1;let f=new Array(l);for(let m=0;m<f.length;m++){p[a]=m;let g=uc({inputs:{x:o},backend:n,attrs:{begin:p,size:h}}),y=be({inputs:{x:g},backend:n,attrs:{shape:c}});f[m]=y,d.push(g)}return d.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}var soe={kernelName:Li,backendName:"webgl",kernelFunc:noe},roe=class{constructor(e,t){this.variableNames=["x","segmentIds"];let n=e.windowSize,s=e.batchSize,r=e.inSize,a=e.numSegments,o=a*Math.ceil(r/n);this.outputShape=[s,o];let i="0.0",l="sumValue",c=Math.floor(n/4)*4,u=n%4,d=`
|
|
sumValue += dot(values, segFilter);
|
|
`,p="";r%n>0&&(p=`
|
|
if (inIdx < 0 || inIdx >= ${r}) {
|
|
return initializationValue;
|
|
}
|
|
`);let h="";r%n>0&&(h=`
|
|
if (inIdx < 0 || inIdx >= ${r}) {
|
|
return -1.0;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = ${i};
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${p}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
float getSegmentIdAtIndex(int inIdx) {
|
|
${h}
|
|
return getSegmentIds(inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = int(floor(float(outIdx) / float(
|
|
${a})) * float(${n}));
|
|
int currentSeg = int(mod(float(outIdx), float(${a})));
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < ${c}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
|
|
);
|
|
|
|
${d}
|
|
}
|
|
|
|
int inIdx = inOffset + ${c};
|
|
if (${u===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
0,
|
|
0,
|
|
0
|
|
);
|
|
|
|
${d}
|
|
} else if (${u===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
0,
|
|
0
|
|
);
|
|
|
|
${d}
|
|
} else if (${u===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
|
|
0
|
|
);
|
|
|
|
${d}
|
|
}
|
|
setOutput(${l});
|
|
}
|
|
`}};function aoe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,segmentIds:a}=t,{numSegments:o}=s,i=r.shape.length,l=[],c=0,u=E.getAxesPermutation([c],i),d=r;u!=null&&(d=jn({inputs:{x:r},backend:n,attrs:{perm:u}}),l.push(d),c=E.getInnerMostAxes(1,i)[0]);let p=E.segment_util.computeOutShape(d.shape,c,o),h=v.sizeFromShape([d.shape[c]]),f=be({inputs:{x:d},backend:n,attrs:{shape:[-1,h]}});l.push(f);let m=fd(r.dtype),g=(b,w,k,S,N)=>{let $=b.shape[0],F=b.shape[1],R=E.segment_util.segOpComputeOptimalWindowSize(F,N),D={windowSize:R,inSize:F,batchSize:$,numSegments:N},T=new roe(D,w),O=n.compileAndRun(T,[b,k],S);if(l.push(O),O.shape[1]===N)return O;let B=gS({backend:n,attrs:{start:0,stop:N,step:1,dtype:"float32"}}),H=vS({inputs:{x:B},backend:n,attrs:{reps:[F/R]}});return l.push(B),l.push(H),g(O,w,H,S,N)},y=g(f,"unsortedSegmentSum",a,m,o),A=be({inputs:{x:y},backend:n,attrs:{shape:p}}),x=A;if(u!=null){l.push(A);let b=E.getUndoAxesPermutation(u);x=jn({inputs:{x},backend:n,attrs:{perm:b}})}return l.forEach(b=>n.disposeIntermediateTensorInfo(b)),x}var ooe={kernelName:rd,backendName:"webgl",kernelFunc:aoe},ioe=[Fne,zne,vJ,kJ,CJ,EJ,$J,PJ,OJ,zJ,VJ,GJ,qJ,ZJ,sQ,QJ,oQ,cQ,lQ,fQ,gQ,AQ,wQ,EQ,$Q,MQ,LQ,UQ,jQ,nJ,YQ,iee,uee,tee,hee,mee,dee,Aee,vee,Iee,Cee,Nee,$ee,Mee,Lee,_ee,Vee,Hee,qee,Yee,tte,ate,lte,ute,cte,pte,fte,gte,Ate,bte,Ite,Tte,Rte,Dte,Fte,zte,Vte,jte,tJ,Xte,KQ,Yte,ene,sne,rJ,ine,dne,hne,bne,yne,Ine,Tne,$ne,Bne,Xne,jne,Jne,ese,nse,Gne,rse,ose,cse,fse,Ase,Cse,uJ,Nse,$se,Pse,Mse,_Q,Bse,Vse,Gse,qse,Yse,oJ,Qse,ere,PQ,wse,sre,dre,ire,dJ,mre,Are,wre,Sre,Ere,$re,Pre,Mre,Lre,Vre,Hre,qre,Zre,Qre,nae,TQ,Ise,aae,iae,uae,dae,hae,mae,yae,xae,vae,Iae,Cae,Nae,$ae,_ae,Fae,Mae,kse,AJ,Bae,Uae,jae,Zae,Qae,xJ,toe,soe,ooe,Wse];for(let e of ioe)Yr(e);var ls;(function(e){e[e.float32=0]="float32",e[e.int32=1]="int32",e[e.bool=2]="bool",e[e.string=3]="string",e[e.complex64=4]="complex64"})(ls||(ls={}));var yp;(function(e){e[e.linear=0]="linear",e[e.relu=1]="relu",e[e.relu6=2]="relu6",e[e.prelu=3]="prelu",e[e.leakyrelu=4]="leakyrelu",e[e.sigmoid=5]="sigmoid",e[e.elu=6]="elu"})(yp||(yp={}));var kS;function loe(e){kS=e.wasm.cwrap(fo,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function uoe(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:o,preluActivationWeights:i}=t;if(r.dtype!=="float32"||a.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:d}=s,p=n.dataIdMap.get(r.dataId).id,h=n.dataIdMap.get(a.dataId).id,f=0;if(o!=null){let N=n.dataIdMap.get(o.dataId);if(N.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${N.shape.length}.`);f=N.id}let m=i==null?0:n.dataIdMap.get(i.dataId).id,g=yp[u];if(g==null)throw new Error(`${u} activation not yet supported for FusedConv2D in the wasm backend.`);let y=l?r.shape[2]:r.shape[1],A=c?a.shape[1]:a.shape[2],x=r.shape[0],b=n.makeOutput([x,y,A],r.dtype),w=n.dataIdMap.get(b.dataId).id,k=new Uint8Array(new Int32Array(r.shape).buffer),S=new Uint8Array(new Int32Array(a.shape).buffer);return kS(p,k,r.shape.length,h,S,a.shape.length,l,c,g,f,m,d||0,w),b}var coe={kernelName:fo,backendName:"wasm",setupFunc:loe,kernelFunc:uoe};function Rn(e){let t;function n(r){t=r.wasm.cwrap(e,null,["number","number"])}function s(r){let{backend:a,inputs:{x:o}}=r,i=a.dataIdMap.get(o.dataId).id,l=a.makeOutput(o.shape,o.dtype),c=a.dataIdMap.get(l.dataId).id;return v.sizeFromShape(l.shape)===0||t(i,c),l}return{kernelName:e,backendName:"wasm",setupFunc:n,kernelFunc:s}}var doe=Rn(ni);function qn(e,t,n){let s;function r(o){s=o.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function a(o){let{backend:i,inputs:l}=o,{a:c,b:u}=l,d=i.dataIdMap.get(c.dataId).id,p=i.dataIdMap.get(u.dataId).id,h=n!=null?n:c.dtype,f=E.assertAndGetBroadcastShape(c.shape,u.shape),m=i.makeOutput(f,h);if(v.sizeFromShape(f)===0)return m;let g=new Uint8Array(new Int32Array(c.shape).buffer),y=new Uint8Array(new Int32Array(u.shape).buffer),A=i.dataIdMap.get(m.dataId).id,x=()=>s(d,g,c.shape.length,p,y,u.shape.length,ls[c.dtype],A);if(t&&c.dtype==="float32")return x(),m;let b=E.getBroadcastDims(c.shape,f),w=E.getBroadcastDims(u.shape,f),k=b.every((N,$)=>N===$),S=w.every((N,$)=>N===$);if(k&&S)return x(),m;throw new Error(`Broadcasting along outer dims is not yet supported for ${c.dtype} ${e}.`)}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:a}}var poe=!0,hoe=qn(qr,poe),IS;function foe(e){IS=e.wasm.cwrap(wa,null,["array","number","number","number"])}function moe(e){let{inputs:t,backend:n}=e,s=n.makeOutput(t[0].shape,t[0].dtype);if(v.sizeFromShape(s.shape)===0)return s;let r=t.map(i=>n.dataIdMap.get(i.dataId).id),a=new Uint8Array(new Int32Array(r).buffer),o=n.dataIdMap.get(s.dataId).id;return IS(a,r.length,ls[s.dtype],o),s}var goe={kernelName:wa,backendName:"wasm",setupFunc:foe,kernelFunc:moe};function Zm(e){let{inputs:{x:t},backend:n}=e,s=n.makeOutput(t.shape,t.dtype),r=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(s).set(r),s}var yoe={kernelName:Ba,backendName:"wasm",kernelFunc:Zm},SS;function Aoe(e){SS=e.wasm.cwrap(po,null,["number","array","number","number","number","array","number"])}function pc(e){let{inputs:t,backend:n,attrs:s}=e,[r,a]=boe(t.x.shape,s.perm),o=!0;for(let f=0;f<a.length;f++)a[f]!==f&&(o=!1);let i=xoe(t.x.shape,s.perm),l={dataId:t.x.dataId,shape:r,dtype:t.x.dtype};if(o){let f=Zm({inputs:t,backend:n});return f.shape=i,f}let c=n.makeOutput(i,l.dtype),u=n.dataIdMap.get(l.dataId).id,d=n.dataIdMap.get(c.dataId).id,p=new Uint8Array(new Int32Array(a).buffer),h=new Uint8Array(new Int32Array(l.shape).buffer);return SS(u,h,l.shape.length,ls[l.dtype],d,p,a.length),c}function xoe(e,t){let n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[t[s]];return n}function boe(e,t){let n=[],s=[];for(let r=0;r<e.length;++r)e[r]!==1&&n.push(e[r]),e[t[r]]!==1&&s.push(t[r]);for(let r=0;r<s.length;++r){let a=-1;for(let o=0;o<s.length;++o)s[o]>=r&&(a===-1||s[a]>s[o])&&(a=o);s[a]=r}return[n,s]}var voe={kernelName:po,backendName:"wasm",kernelFunc:pc,setupFunc:Aoe};function zo(e,t,n){let s=e.shape,r=e.shape.length,a=v.parseAxisParam(t,s),o=a,i=E.getAxesPermutation(o,r),l=null,c=!1;if(i!=null){let u=new Array(r);for(let h=0;h<u.length;h++)u[h]=s[i[h]];o=E.getInnerMostAxes(o.length,r),l=pc({inputs:{x:e},attrs:{perm:i},backend:n});let d=n.dataIdMap.get(e.dataId).id;n.dataIdMap.get(l.dataId).id!==d&&(c=!0)}return{transposed:l,originalAxes:a,axes:o,inputWasTransposed:c}}var CS;function woe(e){CS=e.wasm.cwrap(Kl,null,["number, number, number"])}function koe(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,l=t.dataIdMap.get(o.dataId).id,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=zo(o,r,t);if(h){let x=t.dataIdMap.get(u.dataId).id;c=u,l=x}let f=c.shape.length;E.assertAxesAreInnerMostDims("all",d,f);let[m,g]=E.computeOutAndReduceShapes(c.shape,d),y=v.sizeFromShape(g),A=t.makeOutput(m,o.dtype);if(v.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;CS(l,y,x)}if(h&&t.disposeData(u.dataId),a){let x=E.expandShapeToKeepDim(A.shape,p);A.shape=x}return A}var Ioe={kernelName:Kl,backendName:"wasm",setupFunc:woe,kernelFunc:koe},TS;function Soe(e){TS=e.wasm.cwrap(Zl,null,["number, number, number"])}function Coe(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,l=t.dataIdMap.get(o.dataId).id,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=zo(o,r,t);if(h){let x=t.dataIdMap.get(u.dataId).id;c=u,l=x}let f=c.shape.length;E.assertAxesAreInnerMostDims("any",d,f);let[m,g]=E.computeOutAndReduceShapes(c.shape,d),y=v.sizeFromShape(g),A=t.makeOutput(m,o.dtype);if(v.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;TS(l,y,x)}if(h&&t.disposeData(u.dataId),a){let x=E.expandShapeToKeepDim(A.shape,p);A.shape=x}return A}var Toe={kernelName:Zl,backendName:"wasm",setupFunc:Soe,kernelFunc:Coe},NS;function Noe(e){NS=e.wasm.cwrap(ka,null,["number","number","number","number","number"])}function Eoe(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r}=s,{x:a}=n,o=t.dataIdMap.get(a.dataId).id,i=o,l=a,{transposed:c,axes:u,inputWasTransposed:d}=zo(a,r,t);if(d){let y=t.dataIdMap.get(c.dataId).id;y!==o&&(l=c,i=y)}let p=l.shape.slice(0,-1),h=t.makeOutput(p,"int32"),f=t.dataIdMap.get(h.dataId).id,m=v.sizeFromShape(h.shape),g=l.shape[u[0]];return NS(i,ls[l.dtype],m,g,f),d&&t.disposeData(c.dataId),h}var Roe={kernelName:ka,backendName:"wasm",kernelFunc:Eoe,setupFunc:Noe},ES;function $oe(e){ES=e.wasm.cwrap(Ia,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Doe(e){let{inputs:t,attrs:n,backend:s}=e,r=t.x,a=s.dataIdMap.get(r.dataId).id,{filterSize:o,strides:i,pad:l,dimRoundingMode:c}=n,u=E.computePool2DInfo(r.shape,o,i,1,l,c),d=u.filterHeight,p=u.filterWidth,h=u.padInfo.top,f=u.padInfo.right,m=u.padInfo.bottom,g=u.padInfo.left,y=u.strideHeight,A=u.strideWidth,x=u.inChannels;if(u.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${u.dataFormat}'. Please use 'channelsLast'.`);if(u.dilationWidth!==1||u.dilationHeight!==1)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${u.dilationHeight}, ${u.dilationWidth}].`);let b=s.makeOutput(u.outShape,"float32"),w=s.dataIdMap.get(b.dataId).id;return ES(a,r.shape[0],r.shape[1],r.shape[2],d,p,h,f,m,g,y,A,x,w),b}var _oe={kernelName:Ia,backendName:"wasm",setupFunc:$oe,kernelFunc:Doe};function us(e){let{inputs:t,attrs:n}=e,{x:s}=t,{shape:r}=n,a=v.sizeFromShape(s.shape),o=v.inferFromImplicitShape(r,a);return v.assert(a===v.sizeFromShape(o),()=>`new shape: ${o}, old shape: ${s.shape}. New shape and old shape must have the same number of elements.`),e.backend.incRef(s.dataId),{dataId:s.dataId,shape:o,dtype:s.dtype}}var Poe={kernelName:Ti,backendName:"wasm",kernelFunc:us},RS;function Foe(e){RS=e.wasm.cwrap(Sa,null,["number","array","number","number","array","number","number","number","number"])}function Ooe(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:o,transposeB:i}=s;if(r.dtype!=="float32"||a.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let l=r.shape.length,c=a.shape.length,u=o?r.shape[l-2]:r.shape[l-1],d=i?a.shape[c-1]:a.shape[c-2],p=o?r.shape[l-1]:r.shape[l-2],h=i?a.shape[c-2]:a.shape[c-1],f=r.shape.slice(0,-2),m=a.shape.slice(0,-2),g=v.sizeFromShape(f),y=v.sizeFromShape(m),A=g===y||g===1||y===1;v.assert(l>=2&&c>=2&&A,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${f}) and (${m}).`);let b=(g>y?r.shape.slice(0,-2):a.shape.slice(0,-2)).concat([p,h]);v.assert(u===d,()=>`Error in matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${r.shape} and ${a.shape} and transposeA=${o} and transposeB=${i} must match.`);let w=o?[g,u,p]:[g,p,u],k=i?[y,h,d]:[y,d,h],S=us({inputs:{x:r},backend:n,attrs:{shape:w}}),N=us({inputs:{x:a},backend:n,attrs:{shape:k}}),$=n.dataIdMap.get(S.dataId).id,F=n.dataIdMap.get(N.dataId).id,R=o?S.shape[2]:S.shape[1],D=i?N.shape[1]:N.shape[2],T=Math.max(g,y),O=n.makeOutput([T,R,D],S.dtype),B=n.dataIdMap.get(O.dataId).id,H=new Uint8Array(new Int32Array(S.shape).buffer),z=new Uint8Array(new Int32Array(N.shape).buffer);return RS($,H,S.shape.length,F,z,N.shape.length,o,i,B),n.disposeData(S.dataId),n.disposeData(N.dataId),O.shape=b,O}var Moe={kernelName:Sa,backendName:"wasm",setupFunc:Foe,kernelFunc:Ooe};function Ap(e){let{inputs:{x:t},attrs:{begin:n,size:s},backend:r}=e,[a,o]=yn.parseSliceParams(t,n,s),i=yn.isSliceContinous(t.shape,a,o),l=r.readSync(t.dataId),c=r.makeOutput(o,t.dtype),u=v.computeStrides(t.shape),d=r.dataIdMap.get(c.dataId);if(i){let f=yn.computeFlatOffset(a,u);return t.dtype==="string"?d.stringBytes=l.slice(f,f+v.sizeFromShape(o)):r.typedArrayFromHeap(c).set(l.subarray(f,f+v.sizeFromShape(o))),c}if(t.dtype==="string"){let f=Cm(l,a,o,t.shape,t.dtype);return d.stringBytes=f,c}let p=r.typedArrayFromHeap(c),h=t.shape.length;if(h===2)zoe(l,u[0],p,a,o);else if(h===3)Loe(l,u[0],u[1],p,a,o);else if(h===4)Boe(l,u[0],u[1],u[2],p,a,o);else{let f=Cm(l,a,o,t.shape,t.dtype);p.set(f)}return c}function zoe(e,t,n,s,r){let a=0,o=s[0],i=s[1],l=o+r[0];for(let c=o;c<l;c++){let u=c*t+i;n.set(e.subarray(u,u+r[1]),a),a+=r[1]}}function Loe(e,t,n,s,r,a){let o=0,i=r[0],l=r[1],c=r[2],u=i+a[0],d=l+a[1];for(let p=i;p<u;p++)for(let h=l;h<d;h++){let f=p*t+h*n+c;s.set(e.subarray(f,f+a[2]),o),o+=a[2]}}function Boe(e,t,n,s,r,a,o){let i=0,l=a[0],c=a[1],u=a[2],d=l+o[0],p=c+o[1],h=u+o[2],f=a[3];for(let m=l;m<d;m++)for(let g=c;g<p;g++)for(let y=u;y<h;y++){let A=m*t+g*n+y*s+f;r.set(e.subarray(A,A+o[3]),i),i+=o[3]}}var Woe={kernelName:Di,backendName:"wasm",kernelFunc:Ap};function Voe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:o}=s,i=a.reduce((y,A)=>y*A),l=E.getReshaped(r.shape,a,i),c=E.getPermuted(l.length,a.length),u=E.getReshapedPermuted(r.shape,a,i),d=E.getSliceBeginCoords(o,a.length),p=E.getSliceSize(u,o,a.length),h=us({inputs:{x:r},backend:n,attrs:{shape:l}}),f=pc({inputs:{x:h},backend:n,attrs:{perm:c}}),m=us({inputs:{x:f},backend:n,attrs:{shape:u}}),g=Ap({inputs:{x:m},backend:n,attrs:{begin:d,size:p}});return n.disposeData(h.dataId),n.disposeData(f.dataId),n.disposeData(h.dataId),g}var Uoe={kernelName:si,backendName:"wasm",kernelFunc:Voe};function Ym(e){let{inputs:{x:t},attrs:{dtype:n},backend:s}=e,r=s.makeOutput(t.shape,n),a=s.typedArrayFromHeap(t);return s.typedArrayFromHeap(r).set(a),r}var Goe={kernelName:Ca,backendName:"wasm",kernelFunc:Ym},Hoe=Rn(Ta),$S;function joe(e){$S=e.wasm.cwrap(Xr,null,["number","number","number","number"])}function qoe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{clipValueMin:a,clipValueMax:o}=s,i=n.dataIdMap.get(r.dataId).id,l=n.makeOutput(r.shape,r.dtype),c=n.dataIdMap.get(l.dataId).id;return $S(i,a,o,c),l}var Xoe={kernelName:Xr,backendName:"wasm",setupFunc:joe,kernelFunc:qoe};function DS(e){let{inputs:t,backend:n}=e,s=v.parseAxisParam(e.attrs.axis,t[0].shape)[0],r=E.computeOutShape(t.map(h=>h.shape),s),a=t.filter(h=>v.sizeFromShape(h.shape)>0);if(a.length===1)return Zm({inputs:{x:a[0]},backend:n});let o=n.makeOutput(r,t[0].dtype);if(v.sizeFromShape(r)===0)return o;let i=a.map(h=>h.shape);if(E.assertParamsConsistent(i,s),a[0].dtype==="string"){let h=a.map(x=>{let b=v.sizeFromShape(x.shape.slice(s));return us({inputs:{x},backend:n,attrs:{shape:[-1,b]}})}),f=h.map(x=>({vals:n.readSync(x.dataId),shape:x.shape}));r=E.computeOutShape(h.map(x=>x.shape),1);let m=h[0].shape[0]===1,g=UA(f,r,t[0].dtype,m),y=E.computeOutShape(a.map(x=>x.shape),s);o.shape=y;let A=n.dataIdMap.get(o.dataId);return A.stringBytes=E.fromStringArrayToUint8(g),h.forEach(x=>n.disposeData(x.dataId)),o}let l=v.sizeFromShape(a[0].shape.slice(0,s)),c=0,u=a.map(h=>{let f=v.sizeFromShape(h.shape.slice(s));return c+=f,f}),d=a.map(h=>n.typedArrayFromHeap(h)),p=n.typedArrayFromHeap(o);for(let h=0;h<l;h++){let f=h*c;for(let m=0;m<d.length;m++){let g=u[m],y=h*g,A=d[m].subarray(y,y+g);p.set(A,f),f+=g}}return o}var Koe={kernelName:ri,backendName:"wasm",kernelFunc:DS},_S;function Zoe(e){_S=e.wasm.cwrap(Na,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Yoe(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a}=t,o=s.dataIdMap.get(r.dataId).id,i=s.dataIdMap.get(a.dataId).id,{strides:l,dilations:c,pad:u,dimRoundingMode:d,dataFormat:p}=n,h=E.convertConv2DDataFormat(p),f=E.computeConv2DInfo(r.shape,a.shape,l,c,u,d,!1,h),m=f.filterHeight,g=f.filterWidth,y=f.padInfo.top,A=f.padInfo.right,x=f.padInfo.bottom,b=f.padInfo.left,w=f.dilationHeight,k=f.dilationWidth,S=f.strideHeight,N=f.strideWidth,$=f.inChannels,F=f.outChannels,R=f.padInfo.type==="SAME"?1:0;if(f.dataFormat!=="channelsLast")throw new Error(`wasm backend Conv2D does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);let D=s.makeOutput(f.outShape,"float32"),T=s.dataIdMap.get(D.dataId).id;return _S(o,r.shape[0],r.shape[1],r.shape[2],i,m,g,y,A,x,b,R,w,k,S,N,$,F,T),D}var Joe={kernelName:Na,backendName:"wasm",setupFunc:Zoe,kernelFunc:Yoe},PS;function Qoe(e){PS=e.wasm.cwrap(Ea,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function eie(e){let{backend:t,inputs:n,attrs:s}=e,{dy:r,filter:a}=n,{strides:o,pad:i,dataFormat:l,dimRoundingMode:c,inputShape:u}=s,d=1,p=E.convertConv2DDataFormat(l),h=E.computeConv2DInfo(u,a.shape,o,d,i,c,!1,p),{batchSize:f,filterHeight:m,filterWidth:g,inChannels:y,inHeight:A,inWidth:x,outChannels:b,outHeight:w,outWidth:k,strideHeight:S,strideWidth:N}=h,$=m-1-h.padInfo.top,F=g-1-h.padInfo.left,R=h.dataFormat==="channelsLast",D=v.computeStrides(h.inShape),T=v.computeStrides(r.shape),[O,B,H]=v.computeStrides(a.shape),z=D[0],X=R?D[1]:D[2],ee=R?D[2]:1,J=R?1:D[1],Q=T[0],ne=R?T[1]:T[2],K=R?T[2]:1,oe=R?1:T[1],ce=t.makeOutput(h.inShape,"float32"),he=t.dataIdMap.get(ce.dataId).id,Ae=t.dataIdMap.get(r.dataId).id,Se=t.dataIdMap.get(a.dataId).id;return PS(Ae,Se,f,m,g,A,x,y,w,k,b,S,N,$,F,O,B,H,z,X,ee,J,Q,ne,K,oe,he),ce}var tie={kernelName:Ea,backendName:"wasm",setupFunc:Qoe,kernelFunc:eie},nie=Rn(Ra),sie=Rn($a),vx;(function(e){e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest"})(vx||(vx={}));var FS;function rie(e){FS=e.wasm.cwrap(oi,null,["number","number","number","number","array","number","number","number","number","number"])}function aie(e){let{backend:t,inputs:n,attrs:s}=e,{method:r,extrapolationValue:a,cropSize:o}=s,{image:i,boxes:l,boxInd:c}=n,u=l.shape[0],[d,p]=o,h=[u,d,p,i.shape[3]],f=t.dataIdMap.get(i.dataId),m;i.dtype!=="float32"&&(m=Ym({backend:t,inputs:{x:i},attrs:{dtype:"float32"}}),f=t.dataIdMap.get(m.dataId));let g=f.id,y=t.dataIdMap.get(l.dataId).id,A=t.dataIdMap.get(c.dataId).id,x=t.makeOutput(h,"float32"),b=t.dataIdMap.get(x.dataId).id,w=new Uint8Array(new Int32Array(i.shape).buffer);return FS(g,y,A,u,w,d,p,vx[r],a,b),m!=null&&t.disposeData(m.dataId),x}var oie={kernelName:oi,backendName:"wasm",setupFunc:rie,kernelFunc:aie},OS;function iie(e){OS=e.wasm.cwrap(ai,null,["number","number","number","number","number","number"])}function lie(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:o,reverse:i}=s,l=r.shape.length;v.assert(r.dtype==="float32"||r.dtype==="int32",()=>`cumsum does not support ${r.dtype} tensors in the WASM backend`);let c=E.getAxesPermutation([a],l),u=r;c!==null&&(u=pc({inputs:{x:r},attrs:{perm:c},backend:n}));let d=E.getInnerMostAxes(1,l)[0];E.assertAxesAreInnerMostDims("cumsum",[d],l);let p=n.makeOutput(u.shape,u.dtype),h=u.shape[d],f=n.dataIdMap.get(u.dataId).id,m=n.dataIdMap.get(p.dataId).id;OS(f,o?1:0,i?1:0,h,m,ls[r.dtype]);let g=p;if(c!==null){let y=E.getUndoAxesPermutation(c);g=pc({inputs:{x:p},attrs:{perm:y},backend:n}),n.disposeData(u.dataId),n.disposeData(p.dataId)}return g}var uie={kernelName:ai,backendName:"wasm",setupFunc:iie,kernelFunc:lie},MS;function cie(e){MS=e.wasm.cwrap(ii,null,["number","number","number","array","number","array","array","number","number"])}function die(e){let{backend:t,inputs:n,attrs:s}=e,{x:r}=n,{blockSize:a,dataFormat:o}=s;v.assert(a>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${a}`);let i=r.shape[0],l=o==="NHWC"?r.shape[1]:r.shape[2],c=o==="NHWC"?r.shape[2]:r.shape[3],u=o==="NHWC"?r.shape[3]:r.shape[1],d=l*a,p=c*a,h=u/(a*a),f=o==="NHWC"?[i,d,p,h]:[i,h,d,p],m=t.makeOutput(f,"float32"),y=t.dataIdMap.get(r.dataId).id,A=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),x=new Uint8Array(new Int32Array(f).buffer),b=new Uint8Array(new Int32Array(v.computeStrides(f)).buffer),w=t.dataIdMap.get(m.dataId).id;return MS(y,a,o==="NHWC"?1:0,A,r.shape.length-1,x,b,f.length,w),m}var pie={kernelName:ii,backendName:"wasm",setupFunc:cie,kernelFunc:die},zS;function hie(e){zS=e.wasm.cwrap(Da,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function fie(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a}=t,o=s.dataIdMap.get(r.dataId).id,i=s.dataIdMap.get(a.dataId).id,{strides:l,dilations:c,pad:u,dimRoundingMode:d}=n,p=c==null?[1,1]:c,h=E.computeConv2DInfo(r.shape,a.shape,l,p,u,d,!0),f=h.filterHeight,m=h.filterWidth,g=h.padInfo.top,y=h.padInfo.right,A=h.padInfo.bottom,x=h.padInfo.left,b=h.dilationHeight,w=h.dilationWidth,k=h.strideHeight,S=h.strideWidth,N=h.inChannels,$=h.outChannels,F=h.padInfo.type==="SAME"?1:0;if(h.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${h.dataFormat}'. Please use 'channelsLast'.`);let R=s.makeOutput(h.outShape,"float32"),D=s.dataIdMap.get(R.dataId).id;return zS(o,r.shape[0],r.shape[1],r.shape[2],i,f,m,g,y,A,x,F,b,w,k,S,N,$,D),R}var mie={kernelName:Da,backendName:"wasm",setupFunc:hie,kernelFunc:fie},gie=Rn(Pa),yie=!1,Aie=qn(li,yie,"bool"),xie=Rn(Fa);function wx(e){let{inputs:t,attrs:n,backend:s}=e,{input:r}=t,{dim:a}=n,o=r.shape.length,i=r.shape.slice(),l=a;return a<0&&(v.assert(-(o+1)<=a,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+a+1),i.splice(l,0,1),us({inputs:{x:r},backend:s,attrs:{shape:i}})}var bie={kernelName:ui,backendName:"wasm",kernelFunc:wx};function LS(e){let{attrs:{shape:t,value:n,dtype:s},backend:r}=e,a=r.makeOutput(t,s);return r.typedArrayFromHeap(a).fill(n),a}var vie={kernelName:ru,backendName:"wasm",kernelFunc:LS},BS;function wie(e){BS=e.wasm.cwrap(di,null,["number","number","number","number","number","number"])}function kie(e){let{inputs:t,backend:n}=e,{image:s}=t,r=n.makeOutput(s.shape,s.dtype),a=n.dataIdMap.get(s.dataId).id,o=n.dataIdMap.get(r.dataId).id,[i,l,c,u]=s.shape;return BS(a,i,l,c,u,o),r}var Iie={kernelName:di,backendName:"wasm",kernelFunc:kie,setupFunc:wie},Sie=Rn(Oa),Cie=!1,Tie=qn(Ma,Cie),WS;function Nie(e){WS=e.wasm.cwrap(za,null,["number","number","number","number","number","number","number"])}function Eie(e){let{backend:t,inputs:n,attrs:s}=e,{varianceEpsilon:r}=s,{x:a,mean:o,variance:i,offset:l,scale:c}=n,u=t.dataIdMap.get(a.dataId).id,d=t.dataIdMap.get(o.dataId).id,p=t.dataIdMap.get(i.dataId).id,h=l!=null?t.dataIdMap.get(l.dataId).id:0,f=c!=null?t.dataIdMap.get(c.dataId).id:0,m=t.makeOutput(a.shape,a.dtype);if(v.sizeFromShape(a.shape)===0)return m;let g=t.dataIdMap.get(m.dataId).id;return WS(u,d,p,h,f,r,g),m}var Rie={kernelName:za,backendName:"wasm",setupFunc:Nie,kernelFunc:Eie},VS;function $ie(e){VS=e.wasm.cwrap(mo,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Die(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dilations:u,dataFormat:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=n,m=E.computeConv2DInfo(r.shape,a.shape,l,u,c,p),g=yp[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedConv2D in the wasm backend.`);let y=s.dataIdMap.get(r.dataId).id,A=s.dataIdMap.get(a.dataId).id,x=m.outChannels,b=0;if(o!=null){let K=s.dataIdMap.get(o.dataId);if(K.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${K.shape.length}.`);if(K.shape[0]!==x)throw new Error(`FusedConv2D bias shape (${K.shape}) does not match the number of output channels (${x})`);b=K.id}let w=m.filterHeight,k=m.filterWidth,S=m.padInfo.top,N=m.padInfo.right,$=m.padInfo.bottom,F=m.padInfo.left,R=m.dilationHeight,D=m.dilationWidth,T=m.strideHeight,O=m.strideWidth,B=m.inChannels,H=m.padInfo.type==="SAME"?1:0,z=m.batchSize,X=m.inHeight,ee=m.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);let J=s.makeOutput(m.outShape,"float32"),Q=s.dataIdMap.get(J.dataId).id,ne=i==null?0:s.dataIdMap.get(i.dataId).id;return VS(y,z,X,ee,A,w,k,b,S,N,$,F,H,R,D,T,O,B,x,g,ne,f||0,Q),J}var _ie={kernelName:mo,backendName:"wasm",setupFunc:$ie,kernelFunc:Die},US;function Pie(e){US=e.wasm.cwrap(go,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Fie(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dilations:u,dataFormat:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=n,m=E.computeConv2DInfo(r.shape,a.shape,l,u,c,p,!0),g=yp[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let y=s.dataIdMap.get(r.dataId).id,A=s.dataIdMap.get(a.dataId).id,x=m.outChannels,b=0;if(o!=null){let K=s.dataIdMap.get(o.dataId);if(K.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${K.shape.length}.`);if(K.shape[0]!==x)throw new Error(`FusedDepthwiseConv2D bias shape (${K.shape}) does not match the number of output channels (${x})`);b=K.id}let w=m.filterHeight,k=m.filterWidth,S=m.padInfo.top,N=m.padInfo.right,$=m.padInfo.bottom,F=m.padInfo.left,R=m.dilationHeight,D=m.dilationWidth,T=m.strideHeight,O=m.strideWidth,B=m.inChannels,H=m.padInfo.type==="SAME"?1:0,z=m.batchSize,X=m.inHeight,ee=m.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);let J=s.makeOutput(m.outShape,"float32"),Q=s.dataIdMap.get(J.dataId).id,ne=i==null?0:s.dataIdMap.get(i.dataId).id;return US(y,z,X,ee,A,w,k,b,S,N,$,F,H,R,D,T,O,B,x,g,ne,f||0,Q),J}var Oie={kernelName:go,backendName:"wasm",setupFunc:Pie,kernelFunc:Fie},GS;function Mie(e){GS=e.wasm.cwrap(hi,null,["number","number","number","number","number","number","array","number"])}function zie(e){let{backend:t,inputs:n}=e,{params:s,indices:r}=n,[a,o,i,l]=_2.prepareAndValidate(s,r),c=t.makeOutput(a,s.dtype);if(o===0)return c;let u=r.shape,d=u[u.length-1],h=t.dataIdMap.get(s.dataId).id,m=t.dataIdMap.get(r.dataId).id,g=new Uint8Array(new Int32Array(l).buffer),y=t.dataIdMap.get(c.dataId).id;return GS(h,ls[s.dtype],m,o,d,i,g,y),c}var Lie={kernelName:hi,backendName:"wasm",setupFunc:Mie,kernelFunc:zie},HS;function Bie(e){HS=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function Wie(e){let{backend:t,inputs:n,attrs:s}=e,{x:r,indices:a}=n,{axis:o,batchDims:i}=s,l=v.parseAxisParam(o,r.shape)[0],c=E.segment_util.collectGatherOpShapeInfo(r,a,l,i),u=us({inputs:{x:r},attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]},backend:t}),d=v.sizeFromShape(a.shape),p=us({inputs:{x:a},attrs:{shape:[c.batchSize,d/c.batchSize]},backend:t}),h=[c.batchSize,c.outerSize,d/c.batchSize,c.sliceSize],f=t.makeOutput(h,r.dtype);if(v.sizeFromShape(r.shape)===0)return f;let m=u.shape.length-1,y=t.dataIdMap.get(u.dataId).id,x=t.dataIdMap.get(p.dataId).id,b=t.dataIdMap.get(f.dataId).id,w=new Uint8Array(new Int32Array(v.computeStrides(u.shape)).buffer),k=new Uint8Array(new Int32Array(v.computeStrides(h)).buffer);return HS(y,ls[r.dtype],w,m,x,c.batchSize,k,b),t.disposeData(u.dataId),t.disposeData(p.dataId),f.shape=c.outputShape,f}var Vie={kernelName:pi,backendName:"wasm",setupFunc:Bie,kernelFunc:Wie},Uie=!1,Gie=qn(fi,Uie,"bool"),Hie=!1,jie=qn(La,Hie,"bool"),jS;function qie(e){jS=e.wasm.cwrap(mi,null,["number","number","number"])}function Xie(e){let{inputs:{x:t},attrs:{alpha:n},backend:s}=e,r=s.dataIdMap.get(t.dataId).id,a=s.makeOutput(t.shape,t.dtype);if(v.sizeFromShape(t.shape)!==0){let o=s.dataIdMap.get(a.dataId).id;jS(r,n,o)}return a}var Kie={kernelName:mi,backendName:"wasm",setupFunc:qie,kernelFunc:Xie},Zie=!1,Yie=qn(gi,Zie,"bool"),Jie=!1,Qie=qn(yi,Jie,"bool"),ele=Rn(Wa),tle=!1,nle=qn(Ai,tle,"bool"),qS;function sle(e){qS=e.wasm.cwrap(Va,null,["number, number, number"])}function rle(e){let{backend:t,inputs:n,attrs:s}=e,{reductionIndices:r,keepDims:a}=s,{x:o}=n,l=t.dataIdMap.get(o.dataId).id,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=zo(o,r,t);if(h){let x=t.dataIdMap.get(u.dataId).id;c=u,l=x}let f=c.shape.length;E.assertAxesAreInnerMostDims("max",d,f);let[m,g]=E.computeOutAndReduceShapes(c.shape,d),y=v.sizeFromShape(g),A=t.makeOutput(m,o.dtype);if(v.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;qS(l,y,x)}if(h&&t.disposeData(u.dataId),a){let x=E.expandShapeToKeepDim(A.shape,p);A.shape=x}return A}var ale={kernelName:Va,backendName:"wasm",setupFunc:sle,kernelFunc:rle},ole=!1,ile=qn(Ua,ole),XS;function lle(e){XS=e.wasm.cwrap(Ga,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function ule(e){let{inputs:t,attrs:n,backend:s}=e,r=t.x,a=s.dataIdMap.get(r.dataId).id,{filterSize:o,strides:i,pad:l,dimRoundingMode:c}=n,u=E.computePool2DInfo(r.shape,o,i,1,l,c),d=u.filterHeight,p=u.filterWidth,h=u.padInfo.top,f=u.padInfo.right,m=u.padInfo.bottom,g=u.padInfo.left,y=u.dilationHeight,A=u.dilationWidth,x=u.strideHeight,b=u.strideWidth,w=u.inChannels,k=u.outChannels;if(u.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${u.dataFormat}'. Please use 'channelsLast'.`);let S=s.makeOutput(u.outShape,"float32"),N=s.dataIdMap.get(S.dataId).id;return XS(a,r.shape[0],r.shape[1],r.shape[2],d,p,h,f,m,g,y,A,x,b,w,k,N),S}var cle={kernelName:Ga,backendName:"wasm",setupFunc:lle,kernelFunc:ule},KS;function dle(e){KS=e.wasm.cwrap(Ha,null,["number, number, number"])}function ple(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=zo(o,r,t),f=d;if(h){let b=t.dataIdMap.get(u.dataId).id;b!==i&&(c=u,l=b,f=E.getInnerMostAxes(f.length,c.shape.length))}E.assertAxesAreInnerMostDims("mean",f,c.shape.length);let[m,g]=E.computeOutAndReduceShapes(c.shape,f),y=v.sizeFromShape(g),A=c;c.dtype!=="float32"&&(A=Ym({backend:t,inputs:{x:c},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(A.dataId).id);let x=t.makeOutput(m,"float32");if(v.sizeFromShape(c.shape)!==0){let b=t.dataIdMap.get(x.dataId).id;KS(l,y,b)}if(h&&t.disposeData(u.dataId),a){let b=E.expandShapeToKeepDim(x.shape,p);x.shape=b}return c.dtype!=="float32"&&t.disposeData(A.dataId),x}var hle={kernelName:Ha,backendName:"wasm",setupFunc:dle,kernelFunc:ple},ZS;function fle(e){ZS=e.wasm.cwrap(ja,null,["number, number, number"])}function mle(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=zo(o,r,t);if(h){let x=t.dataIdMap.get(u.dataId).id;x!==i&&(c=u,l=x)}let f=c.shape.length;E.assertAxesAreInnerMostDims("min",d,f);let[m,g]=E.computeOutAndReduceShapes(c.shape,d),y=v.sizeFromShape(g),A=t.makeOutput(m,c.dtype);if(v.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;ZS(l,y,x)}if(h&&t.disposeData(u.dataId),a){let x=E.expandShapeToKeepDim(A.shape,p);A.shape=x}return A}var gle={kernelName:ja,backendName:"wasm",setupFunc:fle,kernelFunc:mle},yle=!1,Ale=qn(qa,yle),kx;(function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"})(kx||(kx={}));var YS;function xle(e){YS=e.wasm.cwrap(Xa,null,["number","array","number","number","array","array","number","number"])}function ble(e){let{inputs:{x:t},backend:n,attrs:{paddings:s,mode:r}}=e,a=s.map((f,m)=>f[0]+t.shape[m]+f[1]),o=n.dataIdMap.get(t.dataId).id,i=n.makeOutput(a,t.dtype),l=n.dataIdMap.get(i.dataId).id,c=new Uint8Array(new Int32Array(t.shape).buffer),u=s.map(f=>f[0]),d=s.map(f=>f[1]),p=new Uint8Array(new Int32Array(u).buffer),h=new Uint8Array(new Int32Array(d).buffer);return YS(o,c,t.shape.length,ls[t.dtype],p,h,kx[r],l),i}var vle={kernelName:Xa,backendName:"wasm",kernelFunc:ble,setupFunc:xle},wle=!0,kle=qn(Ka,wle),Ile=Rn(xi);function Ix(e,t){let n=new Int32Array(e.wasm.HEAPU8.buffer,t,4),s=n[0],r=n[1],a=n[2],o=n[3];return e.wasm._free(t),{pSelectedIndices:s,selectedSize:r,pSelectedScores:a,pValidOutputs:o}}var JS;function Sle(e){JS=e.wasm.cwrap(vi,"number",["number","number","number","number","number"])}function Cle(e){let{backend:t,inputs:n,attrs:s}=e,{iouThreshold:r,maxOutputSize:a,scoreThreshold:o}=s,{boxes:i,scores:l}=n,c=t.dataIdMap.get(i.dataId).id,u=t.dataIdMap.get(l.dataId).id,d=JS(c,u,a,r,o),{pSelectedIndices:p,selectedSize:h,pSelectedScores:f,pValidOutputs:m}=Ix(t,d);return t.wasm._free(f),t.wasm._free(m),t.makeOutput([h],"int32",p)}var Tle={kernelName:vi,backendName:"wasm",setupFunc:Sle,kernelFunc:Cle},QS;function Nle(e){QS=e.wasm.cwrap(du,"number",["number","number","number","number","number","bool"])}function Ele(e){let{backend:t,inputs:n,attrs:s}=e,{iouThreshold:r,maxOutputSize:a,scoreThreshold:o,padToMaxOutputSize:i}=s,{boxes:l,scores:c}=n,u=t.dataIdMap.get(l.dataId).id,d=t.dataIdMap.get(c.dataId).id,p=QS(u,d,a,r,o,i),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=Ix(t,p);t.wasm._free(m);let y=t.makeOutput([f],"int32",h),A=t.makeOutput([],"int32",g);return[y,A]}var Rle={kernelName:du,backendName:"wasm",setupFunc:Nle,kernelFunc:Ele},eC;function $le(e){eC=e.wasm.cwrap(wi,"number",["number","number","number","number","number","number"])}function Dle(e){let{backend:t,inputs:n,attrs:s}=e,{iouThreshold:r,maxOutputSize:a,scoreThreshold:o,softNmsSigma:i}=s,{boxes:l,scores:c}=n,u=t.dataIdMap.get(l.dataId).id,d=t.dataIdMap.get(c.dataId).id,p=eC(u,d,a,r,o,i),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=Ix(t,p);t.wasm._free(g);let y=t.makeOutput([f],"int32",h),A=t.makeOutput([f],"float32",m);return[y,A]}var _le={kernelName:wi,backendName:"wasm",setupFunc:$le,kernelFunc:Dle},Ple=!1,Fle=qn(bi,Ple,"bool"),tC;function Ole(e){tC=e.wasm.cwrap(Ii,null,["number","number","number","number","number"])}function Mle(e){let{inputs:t,backend:n,attrs:s}=e,{indices:r}=t,{depth:a,onValue:o,offValue:i}=s,l=n.makeOutput([...r.shape,a],"int32"),c=n.dataIdMap.get(l.dataId).id,d=n.dataIdMap.get(r.dataId).id;return tC(d,a,o,i,c),l}var zle={kernelName:Ii,backendName:"wasm",setupFunc:Ole,kernelFunc:Mle};function Lle(e){let{inputs:{x:t},backend:n}=e,s=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(s).fill(1),s}var Ble={kernelName:ki,backendName:"wasm",kernelFunc:Lle};function Wle(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(t.length===1)return wx({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let a=t[0].shape,o=t[0].dtype;t.forEach(u=>{v.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),v.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(u=>{let d=wx({inputs:{input:u},backend:n,attrs:{dim:r}});return i.push(d),d}),c=DS({inputs:l,backend:n,attrs:{axis:r}});return i.forEach(u=>n.disposeData(u.dataId)),c}var Vle={kernelName:Si,backendName:"wasm",kernelFunc:Wle},nC;function Ule(e){nC=e.wasm.cwrap(Za,null,["number","array","number","number","array","array","number","number"])}function Gle(e){let{inputs:{x:t},backend:n,attrs:{paddings:s,constantValue:r}}=e,a=s.map((m,g)=>m[0]+t.shape[g]+m[1]);if(v.sizeFromShape(t.shape)===0)return LS({backend:n,attrs:{shape:a,value:r,dtype:t.dtype}});let o=n.dataIdMap.get(t.dataId).id,i=n.makeOutput(a,t.dtype),c=n.dataIdMap.get(i.dataId).id,u=new Uint8Array(new Int32Array(t.shape).buffer),d=s.map(m=>m[0]),p=s.map(m=>m[1]),h=new Uint8Array(new Int32Array(d).buffer),f=new Uint8Array(new Int32Array(p).buffer);return nC(o,u,t.shape.length,ls[t.dtype],h,f,r,c),i}var sC={kernelName:Za,backendName:"wasm",kernelFunc:Gle,setupFunc:Ule},Hle=!1,jle=qn(Ya,Hle),rC;function qle(e){rC=e.wasm.cwrap(Ja,null,["number","number","number"])}function Xle(e){let{inputs:t,backend:n}=e,{x:s,alpha:r}=t,a=n.dataIdMap.get(s.dataId).id,o=n.dataIdMap.get(r.dataId).id,i=n.makeOutput(s.shape,"float32"),l=n.dataIdMap.get(i.dataId).id;return rC(a,o,l),i}var Kle={kernelName:Ja,backendName:"wasm",setupFunc:qle,kernelFunc:Xle},aC;function Zle(e){aC=e.wasm.cwrap(Ci,null,["number","number","number","number"])}function Yle(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=zo(o,r,t),f=d;if(h){let x=t.dataIdMap.get(u.dataId).id;x!==i&&(c=u,l=x,f=E.getInnerMostAxes(f.length,c.shape.length))}E.assertAxesAreInnerMostDims("prod",f,c.shape.length);let[m,g]=E.computeOutAndReduceShapes(c.shape,f),y=v.sizeFromShape(g),A=t.makeOutput(m,c.dtype);if(v.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;aC(l,y,ls[A.dtype],x)}if(h&&t.disposeData(u.dataId),a){let x=E.expandShapeToKeepDim(A.shape,p);A.shape=x}return A}var Jle={kernelName:Ci,backendName:"wasm",setupFunc:Zle,kernelFunc:Yle},Qle=e=>{let{backend:t,attrs:n}=e,{start:s,stop:r,step:a,dtype:o}=n,i=jA(s,r,a,o),l=t.makeOutput([i.length],o);return t.typedArrayFromHeap(l).set(i),l},eue={kernelName:pu,backendName:"wasm",kernelFunc:Qle},tue=!0,nue=qn(_a,tue),sue=Rn(Qa),rue=Rn(to),oC;function aue(e){oC=e.wasm.cwrap(eo,null,["number","number","number","number","number","number","number","number","number","number"])}function oue(e){let{backend:t,inputs:n,attrs:s}=e,{images:r}=n,{alignCorners:a,halfPixelCenters:o,size:i}=s,[l,c]=i,[u,d,p,h]=r.shape,f=[u,l,c,h],m=t.dataIdMap.get(r.dataId),g;m.dtype!=="float32"&&(g=Ym({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(g.dataId));let y=m.id,A=t.makeOutput(f,"float32");if(v.sizeFromShape(r.shape)===0)return A;let x=t.dataIdMap.get(A.dataId).id;return oC(y,u,d,p,h,l,c,a?1:0,o?1:0,x),g!=null&&t.disposeData(g.dataId),A}var iue={kernelName:eo,backendName:"wasm",setupFunc:aue,kernelFunc:oue},iC;function lue(e){iC=e.wasm.cwrap(Ni,null,["number","array","number","array","number","number"])}function uue(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s,o=v.parseAxisParam(a,r.shape);if(r.shape.length===0)return Zm({inputs:{x:r},backend:n});let i=n.makeOutput(r.shape,r.dtype),l=n.dataIdMap.get(r.dataId).id,c=n.dataIdMap.get(i.dataId).id,u=new Uint8Array(new Int32Array(o).buffer),d=new Uint8Array(new Int32Array(r.shape).buffer);iC(l,u,o.length,d,r.shape.length,c);let p=us({inputs:{x:i},attrs:{shape:r.shape},backend:n});return n.disposeData(i.dataId),p}var cue={kernelName:Ni,backendName:"wasm",kernelFunc:uue,setupFunc:lue},lC;function due(e){lC=e.wasm.cwrap(Wi,null,["number","number","number","number","number","number","number","number","array","number","number"])}function pue(e){let{inputs:t,backend:n,attrs:s}=e,{image:r}=t,{radians:a,fillValue:o,center:i}=s,l=n.makeOutput(r.shape,r.dtype),c=n.dataIdMap.get(r.dataId).id,u=n.dataIdMap.get(l.dataId).id,[d,p,h,f]=r.shape,[m,g]=E.getImageCenter(i,p,h),y=o===0,A=255,x=typeof o=="number"?[o,o,o,y?0:A]:[...o,A],b=new Uint8Array(new Int32Array(x).buffer);return lC(c,d,p,h,f,a,m,g,b,x.length,u),l}var hue={kernelName:Wi,backendName:"wasm",kernelFunc:pue,setupFunc:due},fue=Rn(Ei),mue=Rn(no),uC;function gue(e){uC=e.wasm.cwrap(Ri,null,["number","number","number","number","number","number","array","number","number"])}function yue(e){let{backend:t,inputs:n,attrs:s}=e,{indices:r,updates:a}=n,{shape:o}=s,i=t.makeOutput(o,a.dtype);if(v.sizeFromShape(o)===0)return i;let{sliceRank:l,numUpdates:c,sliceSize:u,strides:d,outputSize:p}=P2.calculateShapes(a,r,o),f=t.dataIdMap.get(r.dataId).id,g=t.dataIdMap.get(a.dataId).id,y=new Uint8Array(new Int32Array(d).buffer),A=t.dataIdMap.get(i.dataId).id;return uC(f,g,ls[a.dtype],l,c,u,y,p,A),i}var Aue={kernelName:Ri,backendName:"wasm",setupFunc:gue,kernelFunc:yue},cC;function xue(e){cC=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function bue(e){let{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t,o=n.dataIdMap.get(s.dataId).id,i=n.dataIdMap.get(r.dataId).id,l=n.dataIdMap.get(a.dataId).id,c=n.makeOutput(r.shape,r.dtype),u=n.dataIdMap.get(c.dataId).id,d=s.shape.length,p=r.shape.length,h=d===0||d>1||p===1?1:v.sizeFromShape(r.shape.slice(1));return cC(o,i,l,h,u),c}var vue={kernelName:$i,backendName:"wasm",kernelFunc:bue,setupFunc:xue},dC;function wue(e){dC=e.wasm.cwrap(ro,null,["number","number"])}function kue(e){let{backend:t,inputs:{x:n}}=e,s=t.dataIdMap.get(n.dataId).id,r=t.makeOutput(n.shape,n.dtype),a=t.dataIdMap.get(r.dataId).id;return v.sizeFromShape(r.shape)===0||dC(s,a),r}var Iue={kernelName:"Sigmoid",backendName:"wasm",setupFunc:wue,kernelFunc:kue},Sue=Rn(so),pC;function Cue(e){pC=e.wasm.cwrap(io,null,["number","number","number","number"])}function Tue(e){let{backend:t,inputs:{logits:n},attrs:{dim:s}}=e,r=t.dataIdMap.get(n.dataId).id,a=t.makeOutput(n.shape,n.dtype),o=t.dataIdMap.get(a.dataId).id,i=n.shape[s],l=v.sizeFromShape(n.shape)/i;return v.sizeFromShape(a.shape)===0||pC(r,o,i,l),a}var Nue={kernelName:io,backendName:"wasm",setupFunc:Cue,kernelFunc:Tue};function Eue(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:o}=s,i=v.sizeFromShape(a),l=[[0,0]];l.push(...o);for(let k=1+a.length;k<r.shape.length;++k)l.push([0,0]);let c=sC.kernelFunc({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),u=E.getReshaped(c.shape,a,i,!1),d=E.getPermuted(u.length,a.length,!1),p=E.getReshapedPermuted(c.shape,a,i,!1),m=us({inputs:{x:c},backend:n,attrs:{shape:u}}),A=pc({inputs:{x:m},backend:n,attrs:{perm:d}}),w=us({inputs:{x:A},backend:n,attrs:{shape:p}});return n.disposeData(c.dataId),n.disposeData(m.dataId),n.disposeData(A.dataId),w}var Rue={kernelName:Pi,backendName:"wasm",kernelFunc:Eue};function $ue(e){let{inputs:t,attrs:n,backend:s}=e,{x:r}=t,{numOrSizeSplits:a,axis:o}=n,i=v.parseAxisParam(o,r.shape)[0],l=E.prepareSplitSize(r,a,i),c=new Array(r.shape.length).fill(0),u=r.shape.slice();return l.map(d=>{let p=[...u];p[i]=d;let h=Ap({inputs:{x:r},attrs:{begin:c,size:p},backend:s});return c[i]+=d,h})}var Due={kernelName:Fi,backendName:"wasm",kernelFunc:$ue},_ue=Rn(ao),Pue=Rn(Au),Fue=!0,Oue=qn(lo,Fue),hC;function Mue(e){hC=e.wasm.cwrap(ho,null,["number","number","number"])}function zue(e){let{backend:t,inputs:n,attrs:s}=e,{alpha:r}=s,{x:a}=n,o=t.dataIdMap.get(a.dataId).id,i=t.makeOutput(a.shape,a.dtype),l=t.dataIdMap.get(i.dataId).id;return hC(o,r,l),i}var Lue={kernelName:ho,backendName:"wasm",setupFunc:Mue,kernelFunc:zue},fC;function Bue(e){fC=e.wasm.cwrap(Oi,null,["number","array","number","array","array","array","array","array","number","number"])}function Wue(e){let{backend:t,inputs:n,attrs:s}=e,{x:r}=n,{begin:a,end:o,strides:i}=s;i==null&&(i=new Array(a.length));let{beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=s,h=E.slice_util.maskToAxes(u);if(h.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(u!==0&&d!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(u!==0&&p!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let f=r.shape.length-a.length,m=E.slice_util.maskToAxes(d),g=r.shape.slice();m.forEach(R=>{a[R]=0,o[R]=1,g.splice(R,0,1)});let y=us({inputs:{x:r},attrs:{shape:g},backend:t}),{begin:A,end:x,strides:b}=E.slice_util.getNormalizedAxes(y.shape,h,f,a,o,i,l,c,u);a=A,o=x,i=b;let w=E.slice_util.maskToAxes(p);w.forEach(R=>{o[R]=a[R]+1,i[R]=1});let k=E.slice_util.computeOutShape(a,o,i),S=k.filter((R,D)=>w.indexOf(D)===-1);if(i.every(R=>R===1)){let R=Ap({inputs:{x:y},attrs:{begin:a,size:k},backend:t});t.disposeData(y.dataId);let D=us({inputs:{x:R},attrs:{shape:S},backend:t});return t.disposeData(R.dataId),D}let $=t.makeOutput(S,"float32");if(!S.some(R=>R===0)){let R=t.dataIdMap.get(y.dataId).id,D=new Uint8Array(new Int32Array(v.computeStrides(y.shape)).buffer),T=new Uint8Array(new Int32Array(a).buffer),O=new Uint8Array(new Int32Array(o).buffer),B=new Uint8Array(new Int32Array(i).buffer),H=new Uint8Array(new Int32Array(S).buffer),z=new Uint8Array(new Int32Array(v.computeStrides(S)).buffer),X=t.dataIdMap.get($.dataId).id;fC(R,D,y.shape.length,T,O,B,H,z,S.length,X)}t.disposeData(y.dataId);let F=us({inputs:{x:$},attrs:{shape:S},backend:t});return t.disposeData($.dataId),F}var Vue={kernelName:Oi,backendName:"wasm",setupFunc:Bue,kernelFunc:Wue},Uue=!0,Gue=qn(uo,Uue),mC;function Hue(e){mC=e.wasm.cwrap(oo,null,["number, number, number"])}function jue(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=zo(o,r,t),f=d;if(h){let x=t.dataIdMap.get(u.dataId).id;x!==i&&(c=u,l=x,f=E.getInnerMostAxes(f.length,c.shape.length))}E.assertAxesAreInnerMostDims("sum",f,c.shape.length);let[m,g]=E.computeOutAndReduceShapes(c.shape,f),y=v.sizeFromShape(g),A=t.makeOutput(m,c.dtype);if(v.sizeFromShape(c.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;mC(l,y,x)}if(h&&t.disposeData(u.dataId),a){let x=E.expandShapeToKeepDim(A.shape,p);A.shape=x}return A}var que={kernelName:oo,backendName:"wasm",setupFunc:Hue,kernelFunc:jue},Xue=Rn(Mi),Kue=Rn(co),gC;function Zue(e){gC=e.wasm.cwrap(Kr,null,["number","array","number","array","number","number"])}function Yue(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,a=n.dataIdMap.get(r.dataId).id,{reps:o}=s,i=new Array(r.shape.length);for(let p=0;p<i.length;p++)i[p]=r.shape[p]*o[p];let l=new Uint8Array(new Int32Array(r.shape).buffer),c=new Uint8Array(new Int32Array(i).buffer),u=n.makeOutput(i,r.dtype),d=n.dataIdMap.get(u.dataId).id;return gC(a,l,r.shape.length,c,i.length,ls[u.dtype],d),u}var Jue={kernelName:Kr,backendName:"wasm",setupFunc:Zue,kernelFunc:Yue},yC;function Que(e){yC=e.wasm.cwrap(xu,null,["number","array","number","number","number","bool","number","number"])}var ece=({inputs:e,backend:t,attrs:n})=>{let{x:s}=e,{k:r,sorted:a}=n,o=t.dataIdMap.get(s.dataId).id,i=new Uint8Array(new Int32Array(s.shape).buffer),l=s.shape.slice();l[l.length-1]=r;let c=t.makeOutput(l,s.dtype),u=t.dataIdMap.get(c.dataId).id,d=t.makeOutput(l,"int32"),p=t.dataIdMap.get(d.dataId).id;return yC(o,i,s.shape.length,ls[s.dtype],r,a,u,p),[c,d]},tce={kernelName:xu,backendName:"wasm",setupFunc:Que,kernelFunc:ece},AC;function nce(e){AC=e.wasm.cwrap(zi,null,["number","number","bool","number","number","number","number","number","number","array","number","number","number","number","number"])}function sce(e){let{backend:t,inputs:n,attrs:s}=e,{image:r,transforms:a}=n,{interpolation:o,fillMode:i,fillValue:l,outputShape:c}=s,[u,d,p,h]=r.shape,[f,m]=c!=null?c:[d,p],g=[u,f,m,h],y=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),A=t.makeOutput(g,r.dtype),x=t.dataIdMap.get(A.dataId).id,w=t.dataIdMap.get(r.dataId).id,S=t.dataIdMap.get(a.dataId).id,N=o==="nearest"?1:2,$;switch(i){case"constant":$=1;break;case"reflect":$=2;break;case"wrap":$=3;break;case"nearest":$=4;break;default:$=1;break}return AC(w,S,a.shape[0]>1,u,f,m,h,p,d,y,r.shape.length-1,N,$,l,x),A}var rce={kernelName:zi,backendName:"wasm",setupFunc:nce,kernelFunc:sce};function ace(e){let{inputs:t,backend:n,attrs:s}=e,{value:r}=t,{axis:a}=s;a<0&&(a+=r.shape.length);let o=r.shape[a],i=r.shape.length,l=new Array(i-1),c=0;for(let h=0;h<i;h++)h!==a&&(l[c++]=r.shape[h]);let u=new Array(o),d=new Array(i).fill(0),p=r.shape.slice();p[a]=1;for(let h=0;h<u.length;h++)d[a]=h,u[h]=Ap({inputs:{x:r},attrs:{begin:d,size:p},backend:n});return u.map(({dataId:h,dtype:f})=>({dataId:h,dtype:f,shape:l}))}var oce={kernelName:Li,backendName:"wasm",kernelFunc:ace};function ice(e){let{inputs:{x:t},backend:n}=e,s=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(s).fill(0),s}var lce={kernelName:Bi,backendName:"wasm",kernelFunc:ice},uce=[doe,hoe,goe,Ioe,Toe,Roe,_oe,Moe,Uoe,Goe,Hoe,Xoe,Koe,Joe,tie,nie,sie,oie,uie,pie,mie,gie,Aie,xie,bie,vie,Iie,Sie,Tie,coe,Rie,_ie,Oie,Lie,Vie,Gie,jie,yoe,Kie,Yie,Qie,ele,nle,ale,ile,cle,hle,gle,Ale,vle,kle,Ile,Tle,Rle,_le,Fle,zle,Ble,Vle,sC,jle,Kle,Jle,eue,nue,sue,rue,Poe,iue,cue,hue,mue,fue,Aue,vue,Iue,Sue,Woe,Nue,Rue,Due,_ue,Pue,Oue,Lue,Vue,Gue,que,Xue,Kue,Jue,tce,rce,voe,oce,lce];for(let e of uce)Yr(e);var Sx=Z();Sx.registerFlag("WASM_HAS_SIMD_SUPPORT",async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,9,1,7,0,65,0,253,15,26,11])));Sx.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(Sx.get("IS_NODE"))return!1;try{return new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch(e){return!1}});var xC=Qo(dN()),cce='var Module={};function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;this.alert=threadAlert;Module["instantiateWasm"]=function(info,receiveInstance){var instance=new WebAssembly.Instance(Module["wasmModule"],info);Module["wasmModule"]=null;receiveInstance(instance);return instance.exports};function moduleLoaded(){}this.onmessage=function(e){try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob==="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["_emscripten_tls_init"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].setThreadStatus(Module["_pthread_self"](),1);try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(!Module["getNoExitRuntime"]())Module["PThread"].threadExit(result)}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["getNoExitRuntime"]()){}else{Module["PThread"].threadExit(ex.status)}}else{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}};if(typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string"){self={location:{href:__filename}};var onmessage=this.onmessage;var nodeWorkerThreads=require("worker_threads");global.Worker=nodeWorkerThreads.Worker;var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",function(data){onmessage({data:data})});var nodeFS=require("fs");var nodeRead=function(filename){return nodeFS.readFileSync(filename,"utf8")};function globalEval(x){global.require=require;global.Module=Module;eval.call(null,x)}importScripts=function(f){globalEval(nodeRead(f))};postMessage=function(msg){parentPort.postMessage(msg)};if(typeof performance==="undefined"){performance={now:function(){return Date.now()}}}}',dce=Qo(pN()),bC=class extends Gl{constructor(e){super();this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.init(),this.dataIdMap=new Vc(this,ts())}write(e,t,n){let s={id:this.dataIdNextNumber++};return this.move(s,e,t,n,1),s}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=v.now();return e(),{kernelMs:v.now()-t}}move(e,t,n,s,r){let a=this.dataIdNextNumber++;if(s==="string"){let c=t;this.dataIdMap.set(e,{id:a,stringBytes:c,shape:n,dtype:s,memoryOffset:null,refCount:r});return}let o=v.sizeFromShape(n),i=o*v.bytesPerElement(s),l=this.wasm._malloc(i);this.dataIdMap.set(e,{id:a,memoryOffset:l,shape:n,dtype:s,refCount:r}),this.wasm.tfjs.registerTensor(a,o,l),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,i),l)}async read(e){return this.readSync(e)}readSync(e){let{memoryOffset:t,dtype:n,shape:s,stringBytes:r}=this.dataIdMap.get(e);if(n==="string")return r;let a=this.wasm.HEAPU8.slice(t,t+v.sizeFromShape(s)*v.bytesPerElement(n));return fce(a.buffer,n)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){let n=this.dataIdMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;this.wasm._free(n.memoryOffset),this.wasm.tfjs.disposeData(n.id),this.dataIdMap.delete(e)}return!0}refCount(e){return this.dataIdMap.has(e)?this.dataIdMap.get(e).refCount:0}incRef(e){let t=this.dataIdMap.get(e);t!=null&&t.refCount++}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose(),"PThread"in this.wasm&&this.wasm.PThread.terminateAllThreads(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(e,t,n){let s;if(n==null)s=this.write(null,e,t);else{let r=this.dataIdNextNumber++;s={id:r},this.dataIdMap.set(s,{id:r,memoryOffset:n,shape:e,dtype:t,refCount:1});let a=v.sizeFromShape(e);this.wasm.tfjs.registerTensor(r,a,n)}return{dataId:s,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:n}){let s=this.wasm.HEAPU8.buffer,{memoryOffset:r}=this.dataIdMap.get(n),a=v.sizeFromShape(e);switch(t){case"float32":return new Float32Array(s,r,a);case"int32":return new Int32Array(s,r,a);case"bool":return new Uint8Array(s,r,a);default:throw new Error(`Unknown dtype ${t}`)}}};function pce(e){return(t,n)=>(v.fetch(e,{credentials:"same-origin"}).then(s=>{s.ok||t.env.a(`failed to load wasm binary file at '${e}'`),s.arrayBuffer().then(r=>{WebAssembly.instantiate(r,t).then(a=>{n(a.instance,a.module)})})}),{})}function vC(e,t,n){if(Jm!=null)return Jm;let s="tfjs-backend-wasm.wasm";return e&&t?s="tfjs-backend-wasm-threaded-simd.wasm":e&&(s="tfjs-backend-wasm-simd.wasm"),bp!=null&&bp[s]!=null?bp[s]:n+s}async function hce(){let[e,t]=await Promise.all([Z().getAsync("WASM_HAS_SIMD_SUPPORT"),Z().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((n,s)=>{let r={};r.locateFile=(i,l)=>{if(i.endsWith(".worker.js")){let c=cce,u=new Blob([c],{type:"application/javascript"});return URL.createObjectURL(u)}return i.endsWith(".wasm")?vC(e,t,xp!=null?xp:l):l+i},Cx&&(r.instantiateWasm=pce(vC(e,t,xp!=null?xp:"")));let a=!1;r.onAbort=()=>{if(a||vp)return;vp=!0,s({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"})};let o;t&&e&&Jm==null?(r.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+xC.default.toString()],{type:"text/javascript"}),o=(0,xC.default)(r)):o=(0,dce.default)(r),o.then(i=>{a=!0,vp=!1;let l=null;i.tfjs={init:i.cwrap("init",null,[]),registerTensor:i.cwrap("register_tensor",null,["number","number","number"]),disposeData:i.cwrap("dispose_data",l,["number"]),dispose:i.cwrap("dispose",l,[])},n({wasm:i})})})}function fce(e,t){switch(t){case"float32":return new Float32Array(e);case"int32":return new Int32Array(e);case"bool":return new Uint8Array(e);default:throw new Error(`Unknown dtype ${t}`)}}var mce=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],Jm=null,xp=null,bp={},vp=!1,Cx=!1;function gce(e,t=!1){if(B2("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),vp)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");Jm=e,Cx=t}function wC(e,t=!1){if(vp)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPaths()` before you call `tf.setBackend()` or `tf.ready()`");if(typeof e=="string")xp=e;else{bp=e;let n=mce.filter(s=>bp[s]==null);if(n.length>0)throw new Error(`There were no entries found for the following binaries: ${n.join(",")}. Please either call setWasmPaths with a map providing a path for each binary, or with a string indicating the directory where all the binaries can be found.`)}Cx=t}var yce="3.9.0",Ace=2;Xi("wasm",async()=>{let{wasm:e}=await hce();return new bC(e)},Ace);var zr=Z();zr.registerFlag("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE",()=>15);zr.registerFlag("WEBGPU_CPU_FORWARD",()=>!0);zr.registerFlag("WEBGPU_MATMUL_WORK_PER_THREAD",()=>4);zr.registerFlag("WEBGPU_USE_NAIVE_CONV2D",()=>!1);zr.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE",()=>!1);zr.registerFlag("WEBGPU_CONV_SEPARATE_IM2COL_SHADER",()=>!1);zr.registerFlag("WEBGPU_USE_LOW_POWER_GPU",()=>!1);zr.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e3);zr.registerFlag("WEBGPU_USE_PROFILE_TOOL",()=>!1);zr.registerFlag("WEBGPU_USE_IMPORT",()=>!1);function xce(e,t){if(Math.max(...e)>3)throw new Error("Cannot symbolically compute strides for rank > 4 tensor.");let n=e.length,s=e.map(a=>`${t}[${a}]`),r=new Array(n-1);r[n-2]=s[n-1];for(let a=n-3;a>=0;--a)r[a]=`(${r[a+1]} * ${s[a+1]})`;return r}function ln(e){if(e<=1)return"i32";if(e===2)return"vec2<i32>";if(e===3)return"vec3<i32>";if(e===4)return"vec4<i32>";throw Error(`GPU for rank ${e} is not yet supported`)}function Qm(e,t){return e==="float32"?t?"vec4<f32>":"f32":e==="int32"||e==="bool"?t?"vec4<i32>":"i32":e}function He(){return`
|
|
let index = getGlobalIndex(globalId, localId);
|
|
`}function Me(){return`
|
|
[[stage(compute), workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)]]
|
|
fn main([[builtin(local_invocation_id)]] localId : vec3<u32>, [[builtin(global_invocation_id)]] globalId : vec3<u32>)
|
|
`}function bce(e,t,n,s=!1){let r=`
|
|
let workGroupSizeX = ${n.workGroupSize[0]}u;
|
|
let workGroupSizeY = ${n.workGroupSize[1]}u;
|
|
let workGroupSizeZ = ${n.workGroupSize[2]}u;`;if(s===!0){let h=SC(t.shape),f=`
|
|
[[block]] struct Matrix0 {
|
|
numbers: array<${Qm(t.dtype,n.isVec4)}>;
|
|
};
|
|
[[block]] struct Uniform {
|
|
size : i32;
|
|
numChannels : i32;
|
|
outShapeStrides : vec2<i32>;
|
|
dispatchSize : vec3<u32>;
|
|
};
|
|
|
|
[[group(0), binding(0)]] var<storage, write> result : Matrix0;
|
|
[[group(0), binding(2)]] var<uniform> uniforms: Uniform;
|
|
`;return[kC,f,r,IC,h,n.getUserCode()].join(`
|
|
`)}let a=[],o="[[block]] struct Uniforms { NAN : f32; ";n.variableNames.forEach((h,f)=>{o+=`${h.charAt(0).toLowerCase()+h.slice(1)}Shape : ${ln(e[f].shape.length)}; `}),o+=`outShape : ${ln(t.shape.length)} ; `;let i=t.shape.length-1;o+=`
|
|
outShapeStrides: ${ln(i)}; `,n.size!=null&&(o+="size : i32; "),o+="dispatchSize : vec3<u32>; ",n.uniforms&&(o+=n.uniforms),o+="};",a.push(o),a.push(`
|
|
[[block]] struct Matrix0 {
|
|
numbers: array<${Qm(t.dtype,n.isVec4)}>;
|
|
};
|
|
|
|
[[group(0), binding(0)]] var<storage, write> result : Matrix0;
|
|
`),n.variableNames.forEach((h,f)=>{a.push(`
|
|
[[block]] struct Matrix${1+f} {
|
|
numbers: array<${Qm(e[f].dtype,n.isVec4)}>;
|
|
};
|
|
[[group(0), binding(${1+f})]] var<storage, read> ${h} : Matrix${1+f};
|
|
`)}),o!==""&&a.push(`
|
|
[[group(0), binding(${1+n.variableNames.length})]] var<uniform> uniforms : Uniforms;
|
|
`),a.push(r);let[l,c]=Sce(t.shape,n.dispatchLayout),u=SC(t.shape),d=[kC,a.join(`
|
|
`),IC,u,l,vce(t.shape,t.dtype,n.isVec4)];if(c===t.shape.length){let h=e.map(f=>wce(f,t.shape,n.isVec4,n.dispatchLayout.x.length===t.shape.length)).join(`
|
|
`);d.push(h)}return d.push(n.getUserCode()),d.join(`
|
|
`)}var kC=`
|
|
fn idiv(a: i32, b: i32, sign: f32) -> i32 {
|
|
var res: i32 = a / b;
|
|
let mod: i32 = a % b;
|
|
if (sign < 0. && mod != 0) {
|
|
res = res - 1;
|
|
}
|
|
return res;
|
|
}
|
|
|
|
fn isNanCustom(val : f32) -> bool {
|
|
if (val > 0.0) {
|
|
return false;
|
|
}
|
|
if (val < 0.0) {
|
|
return false;
|
|
}
|
|
if (val == 0.0) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
fn isNanCustomVec4F32(val : vec4<f32>) -> vec4<f32> {
|
|
var res = vec4<f32> (0.0);
|
|
for (var i = 0u; i < 4u; i = i + 1u) {
|
|
if (isNanCustom(val[i])) {
|
|
res[i] = 1.0;
|
|
} else {
|
|
res[i] = 0.0;
|
|
}
|
|
}
|
|
return res;
|
|
}
|
|
|
|
// Checks whether coordinates lie within the bounds of the shape.
|
|
fn coordsInBounds4D(coord : vec4<i32>, shape : vec4<i32>) -> bool {
|
|
return all(coord >= vec4<i32>(0)) &&
|
|
all(coord < shape);
|
|
}
|
|
|
|
fn coordsInBounds3D(coord : vec3<i32>, shape : vec3<i32>) -> bool {
|
|
return all(coord >= vec3<i32>(0)) &&
|
|
all(coord < shape);
|
|
}
|
|
|
|
fn coordsInBounds2D(coord : vec2<i32>, shape : vec2<i32>) -> bool {
|
|
return all(coord >= vec2<i32>(0)) &&
|
|
all(coord < shape);
|
|
}
|
|
`,IC=`
|
|
fn getFlatIndex1D(coord : i32, shape : i32) -> i32 {
|
|
return coord;
|
|
}
|
|
|
|
fn getFlatIndex2D(coords : vec2<i32>, shape : vec2<i32>) -> i32 {
|
|
return i32(dot(vec2<f32>(coords), vec2<f32>(f32(shape.y), 1.0)));
|
|
}
|
|
|
|
fn getFlatIndex3D(coords : vec3<i32>, shape : vec3<i32>) -> i32 {
|
|
return i32(dot(vec3<f32>(coords), vec3<f32>(f32(shape.y) * f32(shape.z), f32(shape.z), 1.0)));
|
|
}
|
|
|
|
fn getFlatIndex4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {
|
|
return i32(dot(vec4<f32>(coords), vec4<f32>(
|
|
f32(shape.y) * f32(shape.z) * f32(shape.w), f32(shape.z) * f32(shape.w), f32(shape.w), 1.0)));
|
|
}
|
|
|
|
// Only used when the y/z dimension of workgroup size is 1.
|
|
fn getGlobalIndex(globalId : vec3<u32>, localId : vec3<u32>) -> i32 {
|
|
if (uniforms.dispatchSize.y == 1u && uniforms.dispatchSize.z == 1u) {
|
|
return i32(globalId.x);
|
|
}
|
|
let localInvocationIndex = localId.z * workGroupSizeX * workGroupSizeY +
|
|
localId.y * workGroupSizeX + localId.x;
|
|
let workGroupID = (globalId - localId)/vec3<u32>(
|
|
workGroupSizeX, workGroupSizeY, workGroupSizeZ);
|
|
return i32((workGroupID.z * uniforms.dispatchSize.x * uniforms.dispatchSize.y +
|
|
workGroupID.y * uniforms.dispatchSize.x + workGroupID.x) *
|
|
(workGroupSizeX * workGroupSizeY * workGroupSizeZ) +
|
|
localInvocationIndex);
|
|
}
|
|
`;function vce(e,t,n){let s=e.length,r=Qm(t,n),a;if(n?a=`fn setOutputFlat(flatIndex : i32, value : vec4<f32>) {
|
|
result.numbers[flatIndex] = ${r}(value);
|
|
}
|
|
fn setOutputFlatI32(flatIndex : i32, value : vec4<i32>) {
|
|
result.numbers[flatIndex] = ${r}(value);
|
|
}`:a=`fn setOutputFlat(flatIndex : i32, value : f32) {
|
|
result.numbers[flatIndex] = ${r}(value);
|
|
}
|
|
fn setOutputFlatI32(flatIndex : i32, value : i32) {
|
|
result.numbers[flatIndex] = ${r}(value);
|
|
}`,s>=2){switch(s){case 2:a+=`
|
|
fn getOutputFlatIndex(coords : vec2<i32>) -> i32 {
|
|
return i32(dot(vec2<f32>(coords), vec2<f32>(f32(uniforms.outShapeStrides), 1.0)));
|
|
}
|
|
`;break;case 3:a+=`
|
|
fn getOutputFlatIndex(coords : vec3<i32>) -> i32 {
|
|
return i32(dot(vec3<f32>(coords), vec3<f32>(f32(uniforms.outShapeStrides.x), f32(uniforms.outShapeStrides.y), 1.0)));
|
|
}
|
|
`;break;case 4:a+=`
|
|
fn getOutputFlatIndex(coords : vec4<i32>) -> i32 {
|
|
return i32(dot(vec4<f32>(coords), vec4<f32>(
|
|
f32(uniforms.outShapeStrides.x), f32(uniforms.outShapeStrides.y), f32(uniforms.outShapeStrides.z), 1.0)));
|
|
}
|
|
`;break;default:v.assert(!1,()=>`Unsupported ${s}D shape`);break}let o=["d0","d1","d2","d3"].slice(0,s),i=ln(s);n?a+=`
|
|
fn setOutput(${o.map(l=>`${l} : i32`).join(", ")}, value : vec4<f32>) {
|
|
let flatIndex = getOutputFlatIndex(${i}(${o.join(", ")}));
|
|
setOutputFlat(flatIndex / 4, value);
|
|
}
|
|
fn setOutputI32(${o.map(l=>`${l} : i32`).join(", ")}, value : vec4<i32>) {
|
|
let flatIndex = getOutputFlatIndex(${i}(${o.join(", ")}));
|
|
setOutputFlatI32(flatIndex / 4, value);
|
|
}
|
|
`:a+=`
|
|
fn setOutput(${o.map(l=>`${l} : i32`).join(", ")}, value : f32) {
|
|
let flatIndex = getOutputFlatIndex(${i}(${o.join(", ")}));
|
|
setOutputFlat(flatIndex, value);
|
|
}
|
|
fn setOutputI32(${o.map(l=>`${l} : i32`).join(", ")}, value : i32) {
|
|
let flatIndex = getOutputFlatIndex(${i}(${o.join(", ")}));
|
|
setOutputFlatI32(flatIndex, value);
|
|
}
|
|
`}return a}function wce(e,t,n,s){let r=kce(e,n);return e.shape.length<=t.length&&(r+=Ice(e,t,n,s)),r}function kce(e,t){let n=e.name,s=e.shape.length,r=ln(s),a="get"+n.charAt(0).toUpperCase()+n.slice(1),o=["d0","d1","d2","d3"].slice(0,s),i=o.map(u=>`${u} : i32`).join(", ");if(s<1)return t?`
|
|
fn ${a}() -> vec4<f32> {
|
|
return vec4<f32>(${n}.numbers[0]);
|
|
}
|
|
`:`
|
|
fn ${a}() ->f32 {
|
|
return f32(${n}.numbers[0]);
|
|
}
|
|
`;let l=`uniforms.${n.charAt(0).toLowerCase()+n.slice(1)}Shape`,c=`${s}D`;return s===0&&(c="1D"),t?`
|
|
fn ${a}(${i}) -> vec4<f32> {
|
|
return vec4<f32>(${n}.numbers[getFlatIndex${c}(${r}(${o.join(",")}),
|
|
${l}) / 4]);
|
|
}
|
|
`:`
|
|
fn ${a}(${i}) -> f32 {
|
|
return f32(${n}.numbers[getFlatIndex${c}(${r}(${o.join(",")}),
|
|
${l})]);
|
|
}
|
|
`}function Ice(e,t,n,s){let r=e.name,a=r.charAt(0).toUpperCase()+r.slice(1),o="get"+a+"AtOutCoords",i=e.shape.length,l=t.length,c=ln(l);if(v.arraysEqual(e.shape,t)&&s)return n?`
|
|
fn ${o}ByGlobalId(globalId : vec3<u32>, globalIndex : i32) -> vec4<f32> {
|
|
return vec4<f32>(${r}.numbers[globalIndex]);
|
|
}
|
|
|
|
fn ${o}ByCoords(coords : ${c}) -> vec4<f32> {
|
|
return vec4<f32>(${r}.numbers[${l>1?"getOutputFlatIndex(coords)":"coords"} / 4]);
|
|
}
|
|
`:`
|
|
fn ${o}ByGlobalId(globalId : vec3<u32>, globalIndex : i32) -> f32 {
|
|
return f32(${r}.numbers[globalIndex]);
|
|
}
|
|
|
|
fn ${o}ByCoords(coords : ${c}) -> f32 {
|
|
return f32(${r}.numbers[${l>1?"getOutputFlatIndex(coords)":"coords"}]);
|
|
}
|
|
`;let u=E.getBroadcastDims(e.shape,t),d=l-i,p="";if(i===0)return n?`
|
|
fn ${o}ByGlobalId(globalId : vec3<u32>, globalIndex : i32) -> vec4<f32> {
|
|
return get${a}();
|
|
}
|
|
|
|
fn ${o}ByCoords(coords : ${c}) -> vec4<f32> {
|
|
return get${a}();
|
|
}
|
|
`:`
|
|
fn ${o}ByGlobalId(globalId : vec3<u32>, globalIndex : i32) -> f32{
|
|
return get${a}();
|
|
}
|
|
|
|
fn ${o}ByCoords(coords : ${c}) -> f32{
|
|
return get${a}();
|
|
}
|
|
`;l<2&&u.length>=1?p="coords = 0;":p=u.map(g=>`coords[${g+d}] = 0;`).join(`
|
|
`);let h="";if(l<2&&i>0)h="coords";else if(l>1){let g=ln(i),y=e.shape.map((A,x)=>`coords[${x+d}]`).join(", ");h=`${g}(${y})`}else h="coords";let f=`uniforms.${r.charAt(0).toLowerCase()+r.slice(1)}Shape`,m=`${i}D`;return n?`
|
|
fn ${o}ByGlobalId(globalId : vec3<u32>, globalIndex : i32) -> vec4<f32> {
|
|
var coords = getOutputCoords(globalId, globalIndex);
|
|
${p}
|
|
return ${r}.numbers[getFlatIndex${m}(${h}, ${f}) / 4];
|
|
}
|
|
|
|
fn ${o}ByCoords(coordsIn : ${c}) -> vec4<f32> {
|
|
var coords = coordsIn;
|
|
${p}
|
|
return ${r}.numbers[getFlatIndex${m}(${h}, ${f}) / 4];
|
|
}
|
|
`:`
|
|
fn ${o}ByGlobalId(globalId : vec3<u32>, globalIndex : i32) -> f32 {
|
|
var coords = getOutputCoords(globalId, globalIndex);
|
|
${p}
|
|
return f32(${r}.numbers[getFlatIndex${m}(${h}, ${f})]);
|
|
}
|
|
|
|
fn ${o}ByCoords(coordsIn : ${c}) -> f32 {
|
|
var coords = coordsIn;
|
|
${p}
|
|
return f32(${r}.numbers[getFlatIndex${m}(${h}, ${f})]);
|
|
}
|
|
`}function Sce(e,t){let{x:n,y:s=[],z:r=[]}=t,a=e.length;if(n.length===a)return[`fn getOutputCoords(globalId : vec3<u32>, globalIndex : i32) -> ${ln(a)}{
|
|
return getCoordsFromFlatIndex(i32(globalIndex));
|
|
}
|
|
`,a];let o="",i=[n,s,r],l=0;for(let p=0;p<i.length;p++){let h=i[p];if(h.length!==0)if(l+=h.length,h.length===1)o+=`let d${h[0]} = i32(globalId[${p}]);`;else{let f=xce(h,"uniforms.outShape");o+=`var index${p} = i32(globalId[${p}]);`;for(let m=0;m<f.length;m++)o+=`let d${h[m]} = index${p} / ${f[m]};`,m===f.length-1?o+=`let d${h[m+1]} = index${p} - d${h[m]} * ${f[m]};`:o+=`index${p} = index${p} - d${h[m]} * ${f[m]};`}}let c=[];for(let p=0;p<l;p++)c.push(`d${p}`);let u=ln(l),d=`fn getOutputCoords(globalId : vec3<u32>, globalIndex : i32) -> ${u} {
|
|
${o}
|
|
`;return c.length===0?d+=`return ${u}(0); }`:d+=`return ${u}(${c.join(",")}); }`,[d,l]}function SC(e){let t=e.length;if(t<=1)return"fn getCoordsFromFlatIndex(index : i32) -> i32 { return index; }";let n=v.computeStrides(e),s=ln(t),r=[];for(let o=0;o<t;o++)r.push(`d${o}`);if(n.length===1)return` fn getCoordsFromFlatIndex(index : i32) -> vec2<i32> {
|
|
let d0 = index / uniforms.outShapeStrides; let d1 = index - d0 * uniforms.outShapeStrides;
|
|
return vec2<i32>(d0, d1);
|
|
}`;let a="var index2 = index;"+n.map((o,i)=>{let l=`let ${r[i]} = index2 / uniforms.outShapeStrides[${i}]`,c=i===n.length-1?`let ${r[i+1]} = index2 - ${r[i]} * uniforms.outShapeStrides[${i}]`:`index2 = index2 - ${r[i]} * uniforms.outShapeStrides[${i}]`;return`${l}; ${c};`}).join("");return`
|
|
fn getCoordsFromFlatIndex(index : i32) -> ${s} {
|
|
${a}
|
|
return ${s}(${r.join(",")});
|
|
}
|
|
`}var CC={};Le(CC,{ArrayBufferToTypedArray:()=>TC,GPUBytesPerElement:()=>Rx,computeDispatch:()=>Be,computeWorkGroupSizeForConv2d:()=>Tx,computeWorkGroupSizeForMatMul:()=>Nx,computeWorkPerThreadForConv2d:()=>Ex,flatDispatchLayout:()=>at,isWebGPUSupported:()=>$x,tilesFitEvenlyIntoShape:()=>ua});var hc=65535,kl=e=>{let t=1;for(let n=0;n<e.length;n++)t*=e[n];return t};function ua(e,t){if(e.length!==t.length)throw new Error(`Cannot compute whether rank ${e.length} tiles fit evenly into rank ${t.length} shape - ranks must match.`);return t.every((n,s)=>n%e[s]==0)}function Be(e,t,n=[1,1,1],s=[1,1,1]){let[r,a,o]=[Math.ceil(kl(e.x.map(l=>t[l]))/(n[0]*s[0])),e.y?Math.ceil(kl(e.y.map(l=>t[l]))/(n[1]*s[1])):1,e.z?Math.ceil(kl(e.z.map(l=>t[l]))/(n[2]*s[2])):1];if(r<=hc&&a<=hc&&o<=hc)return[r,a,o];v.assert(r>hc&&e.y===void 0&&e.z===void 0,()=>"Dispatch size exceeds WebGPU limits in Y or Z dimension.");let i=Math.ceil(Math.sqrt(r));return i>hc?(i=Math.ceil(Math.cbrt(r)),v.assert(i<=hc,()=>"Total dispatch size exceeds WebGPU maximum."),[i,i,i]):[i,i,1]}function Tx(e,t){let n=kl(e.x.map(r=>t[r])),s=kl(e.y.map(r=>t[r]));return n<=4?[4,16,1]:s<=4?[16,4,1]:[16,16,1]}function Nx(e,t,n){return e===1?[32,1,1]:n===1?[1,32,1]:[8,8,1]}function Ex(e,t){let n=kl(e.x.map(r=>t[r])),s=kl(e.y.map(r=>t[r]));return n<=4?[1,2,1]:s<=4?[2,1,1]:[2,2,1]}function at(e){return{x:e.map((t,n)=>n)}}function Rx(e){if(e==="float32"||e==="int32"||e==="bool"||e==="string")return 4;if(e==="complex64")return 8;throw new Error(`Unknown dtype ${e}`)}function TC(e,t){if(t==="float32")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"||t==="string"){let n=new Int32Array(e),s=new ArrayBuffer(n.length),r=new Uint8Array(s);for(let a=0;a<n.length;a++)r[a]=n[a];return r}else throw new Error(`Unknown dtype ${t}`)}function $x(){return!!navigator.gpu}var je;(function(e){e[e.MUL=0]="MUL",e[e.ADD=1]="ADD",e[e.SUB=2]="SUB",e[e.DIV=3]="DIV",e[e.EQUAL=4]="EQUAL",e[e.GREATER=5]="GREATER",e[e.GREATER_EQUAL=6]="GREATER_EQUAL",e[e.LESS=7]="LESS",e[e.LESS_EQUAL=8]="LESS_EQUAL",e[e.LOGICAL_AND=9]="LOGICAL_AND",e[e.NOT_EQUAL=10]="NOT_EQUAL",e[e.SQUARED_DIFFERENCE=11]="SQUARED_DIFFERENCE",e[e.INT_DIV=12]="INT_DIV",e[e.POW=13]="POW",e[e.PRELU=14]="PRELU",e[e.MAX=15]="MAX",e[e.MIN=16]="MIN",e[e.COMPLEX_MULTIPLY_REAL=17]="COMPLEX_MULTIPLY_REAL",e[e.COMPLEX_MULTIPLY_IMAG=18]="COMPLEX_MULTIPLY_IMAG"})(je||(je={}));var Cce="return a + b;",Tce="return areal * breal - aimag * bimag;",Nce="return areal * bimag + aimag * breal;",Ece="return a / b;",Rce="return a * b;",$ce="return (a - b) * (a - b);",Dce="return a - b;",_ce="return f32(a == b);",Pce="return vec4<f32>(a == b);",Fce="return f32(a > b);",Oce="return vec4<f32>(a > b);",Mce="return f32(a >= b);",zce="return vec4<f32>(a >= b);",Lce="return f32(a < b);",Bce="return vec4<f32>(a < b);",Wce="return f32(a <= b);",Vce="return vec4<f32>(a <= b);",Uce="return f32(f32(a) >= 1.0 && f32(b) >= 1.0);",Gce=`return (vec4<f32>(a >= vec4<f32>(1.0)) *
|
|
vec4<f32>(b >= vec4<f32>(1.0)));`,Hce=`
|
|
if (isNanCustom(a)) { return a; }
|
|
if (isNanCustom(b)) { return b; }
|
|
`,NC=`
|
|
if (isNaN.r > 0.) {
|
|
resultTemp.r = uniforms.NAN;
|
|
}
|
|
if (isNaN.g > 0.) {
|
|
resultTemp.g = uniforms.NAN;
|
|
}
|
|
if (isNaN.b > 0.) {
|
|
resultTemp.b = uniforms.NAN;
|
|
}
|
|
if (isNaN.a > 0.) {
|
|
resultTemp.a = uniforms.NAN;
|
|
}
|
|
`,jce=`
|
|
let s = sign(a) * sign(b);
|
|
let ia = i32(round(a));
|
|
let ib = i32(round(b));
|
|
return f32(idiv(ia, ib, s));
|
|
`,qce=`
|
|
let ia = vec4<i32>(round(a));
|
|
let ib = vec4<i32>(round(b));
|
|
let cond = ib != vec4<i32>(0);
|
|
var resultTemp = vec4<i32>(0);
|
|
let s = sign(a) * sign(b);
|
|
|
|
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
|
|
if (cond[0]) {
|
|
resultTemp[0] = idiv(ia[0], ib[0], s[0]);
|
|
}
|
|
if (cond[1]) {
|
|
resultTemp[1] = idiv(ia[1], ib[1], s[1]);
|
|
}
|
|
if (cond[2]) {
|
|
resultTemp[2] = idiv(ia[2], ib[2], s[2]);
|
|
}
|
|
if (cond[3]) {
|
|
resultTemp[3] = idiv(ia[3], ib[3], s[3]);
|
|
}
|
|
return vec4<f32>(resultTemp);
|
|
`,Xce="return f32(a != b);",Kce="return vec4<f32>(a != b);",Zce=`
|
|
if(a < 0.0 && floor(b) < b) {
|
|
return uniforms.NAN;
|
|
}
|
|
if (b == 0.0) {
|
|
return 1.0;
|
|
}
|
|
if (round(abs(b) % 2.0) != 1.0) {
|
|
return pow(abs(a), b);
|
|
}
|
|
return sign(a) * pow(abs(a), b);
|
|
`,Yce=`
|
|
let isModRound1Bool = vec4<i32>(round(abs(b) % vec4<f32>(2.0))) == vec4<i32>(1);
|
|
let isModRound1 = vec4<f32>(isModRound1Bool);
|
|
let multiplier = sign(a) * isModRound1 + (vec4<f32>(1.0) - isModRound1);
|
|
var resultTemp = multiplier * pow(abs(a), b);
|
|
|
|
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
|
|
let isExpZero = b == vec4<f32>(0.0);
|
|
if (isExpZero.r) {
|
|
resultTemp.r = 1.0;
|
|
}
|
|
if (isExpZero.g) {
|
|
resultTemp.g = 1.0;
|
|
}
|
|
if (isExpZero.b) {
|
|
resultTemp.b = 1.0;
|
|
}
|
|
if (isExpZero.a) {
|
|
resultTemp.a = 1.0;
|
|
}
|
|
let isNaN = vec4<f32>(a < vec4<f32>(0.0)) * vec4<f32>(floor(b) < b);
|
|
${NC}
|
|
return resultTemp;
|
|
`,Jce="if (a < 0.0) { return b * a; } return a;",Qce=`
|
|
let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
|
|
return (aLessThanZero * (b * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
|
|
`;function EC(e,t){let n=t?NC:Hce;return t?`
|
|
var resultTemp = vec4<f32>(${e}(a, b));
|
|
let isNaN = min(vec4<f32>(isNanCustomVec4F32(a)) + vec4<f32>(isNanCustomVec4F32(b)), vec4<f32>(1.0));
|
|
`+n+`
|
|
return resultTemp;
|
|
`:n+`
|
|
return ${e}(a, b);
|
|
`}function wp(e,t){switch(e){case je.MUL:return Rce;case je.ADD:return Cce;case je.SUB:return Dce;case je.DIV:return Ece;case je.EQUAL:return t?Pce:_ce;case je.GREATER:return t?Oce:Fce;case je.GREATER_EQUAL:return t?zce:Mce;case je.LESS:return t?Bce:Lce;case je.LESS_EQUAL:return t?Vce:Wce;case je.LOGICAL_AND:return t?Gce:Uce;case je.NOT_EQUAL:return t?Kce:Xce;case je.SQUARED_DIFFERENCE:return $ce;case je.INT_DIV:return t?qce:jce;case je.PRELU:return t?Qce:Jce;case je.MAX:return EC("max",t);case je.MIN:return EC("min",t);case je.POW:return t?Yce:Zce;case je.COMPLEX_MULTIPLY_REAL:return Tce;case je.COMPLEX_MULTIPLY_IMAG:return Nce;default:throw new Error(`BinaryType ${e} is not implemented!`)}}var Fe;(function(e){e[e.ABS=0]="ABS",e[e.CEIL=1]="CEIL",e[e.COS=2]="COS",e[e.COSH=3]="COSH",e[e.ELU=4]="ELU",e[e.EXP=5]="EXP",e[e.EXPM1=6]="EXPM1",e[e.FLOOR=7]="FLOOR",e[e.LINEAR=8]="LINEAR",e[e.LOG=9]="LOG",e[e.LOGICAL_NOT=10]="LOGICAL_NOT",e[e.NEG=11]="NEG",e[e.PRELU=12]="PRELU",e[e.RELU=13]="RELU",e[e.RELU6=14]="RELU6",e[e.RSQRT=15]="RSQRT",e[e.SIN=16]="SIN",e[e.SINH=17]="SINH",e[e.SIGMOID=18]="SIGMOID",e[e.SQRT=19]="SQRT",e[e.SQUARE=20]="SQUARE",e[e.TANH=21]="TANH",e[e.TO_INT=22]="TO_INT"})(Fe||(Fe={}));var ede="return abs(a);",tde="return ceil(a);",nde="return cos(a);",sde=`
|
|
let e2x = exp(-a);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,rde="return exp(a) - 1.0;",ade="if (a >= 0.0) { return a; } return (exp(a) - 1.0);",ode=`
|
|
var resFloat = exp(a) - vec4<f32>(1.0);
|
|
if (a.r >= 0.0) {
|
|
resFloat.r = a.r;
|
|
}
|
|
if (a.g >= 0.0) {
|
|
resFloat.g = a.g;
|
|
}
|
|
if (a.b >= 0.0) {
|
|
resFloat.b = a.b;
|
|
}
|
|
if (a.a >= 0.0) {
|
|
resFloat.a = a.a;
|
|
}
|
|
return resFloat;
|
|
`,ide="return exp(a);",lde="return floor(a);",ude="return a;",cde=`if (a < 0.0) { return 1.0/0.0; }
|
|
return log(a);`,dde="return f32(!(a >= 1.0));",pde="return -a;",hde="return (a < 0.0) ? b * a : a;",fde="return max(a, 0.0);",mde="return clamp(a, 0.0, 6.0);",gde="return clamp(a, vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<f32>(6.0, 6.0, 6.0, 6.0));",yde=`
|
|
var resFloat = a * vec4<f32>(a >= vec4<f32>(0.0));
|
|
let isNaN = isNan(a);
|
|
|
|
if (isNaN.r) {
|
|
resFloat.r = a.r;
|
|
}
|
|
if (isNaN.g) {
|
|
resFloat.g = a.g;
|
|
}
|
|
if (isNaN.b) {
|
|
resFloat.b = a.b;
|
|
}
|
|
if (isNaN.a) {
|
|
resFloat.a = a.a;
|
|
}
|
|
return resFloat;
|
|
`,Ade="return 1.0/sqrt(a);",xde="return 1.0 / (1.0 + exp(-1.0 * a));",bde="return sin(a);",vde=`
|
|
let e2x = exp(a);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,wde="return sqrt(a);",kde="return a * a;",Ide=`
|
|
let e2x = exp(-2.0 * abs(a));
|
|
return sign(a) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,Sde="return f32(i32((a)));";function fc(e,t){switch(e){case Fe.ABS:return ede;case Fe.COS:return nde;case Fe.COSH:return sde;case Fe.CEIL:return tde;case Fe.ELU:return t?ode:ade;case Fe.EXP:return ide;case Fe.EXPM1:return rde;case Fe.FLOOR:return lde;case Fe.LINEAR:return ude;case Fe.LOG:return cde;case Fe.LOGICAL_NOT:return dde;case Fe.NEG:return pde;case Fe.PRELU:return hde;case Fe.RELU:return t?yde:fde;case Fe.RELU6:return t?gde:mde;case Fe.RSQRT:return Ade;case Fe.SIGMOID:return xde;case Fe.SIN:return bde;case Fe.SINH:return vde;case Fe.SQRT:return wde;case Fe.SQUARE:return kde;case Fe.TANH:return Ide;case Fe.TO_INT:return Sde;default:throw new Error(`BinaryType ${e} is not implemented!`)}}function Lo(e,t=!1){if(e===null)return null;if(e==="linear")return fc(Fe.LINEAR);if(e==="relu")return fc(Fe.RELU,t);if(e==="elu")return fc(Fe.ELU,t);if(e==="relu6")return fc(Fe.RELU6,t);if(e==="prelu")return wp(je.PRELU,t);if(e==="sigmoid")return fc(Fe.SIGMOID);throw new Error(`Activation ${e} has not been implemented for the WebGPU backend.`)}function RC(e,t){let n={RowPerThread:e[1],ColPerThread:e[0],TileAOuter:t[1]*e[1],TileBOuter:t[0]*e[0],TileInner:t[0]*e[0]};return`
|
|
var<workgroup> mm_Asub : array<array<vec4<f32>, ${n.TileInner/n.ColPerThread}>, ${n.TileAOuter}>;
|
|
var<workgroup> mm_Bsub : array<array<vec4<f32>, ${n.TileBOuter/n.ColPerThread}>, ${n.TileInner}>;
|
|
|
|
let RowPerThread = ${n.RowPerThread};
|
|
let ColPerThread = ${n.ColPerThread}; // only support ColPerThread = 4
|
|
let TileAOuter = ${n.TileAOuter};
|
|
let TileBOuter = ${n.TileBOuter};
|
|
let TileInner = ${n.TileInner};
|
|
|
|
${Me()} {
|
|
|
|
let tileRow = i32(localId.y) * RowPerThread;
|
|
let tileCol = i32(localId.x);
|
|
|
|
let globalRow = i32(globalId.y) * RowPerThread;
|
|
let globalCol = i32(globalId.x);
|
|
let numTiles = (uniforms.dimInner - 1) / TileInner + 1;
|
|
|
|
var acc: array<vec4<f32>, ${n.RowPerThread}>;
|
|
var ACached : vec4<f32>;
|
|
var BCached : array<vec4<f32>, 4>;
|
|
|
|
// Loop over shared dimension.
|
|
var globalColA = tileCol;
|
|
let RowPerThreadB = TileInner / ${t[1]};
|
|
let tileRowB = i32(localId.y) * RowPerThreadB;
|
|
for (var t = 0; t < numTiles; t = t + 1) {
|
|
// Load one tile of A into local memory.
|
|
for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) {
|
|
let inputRow = tileRow + innerRow;
|
|
let inputCol = tileCol;
|
|
mm_Asub[inputRow][inputCol] = mm_readA(globalRow + innerRow, globalColA, globalId);
|
|
}
|
|
globalColA = globalColA + TileInner / ColPerThread;
|
|
|
|
// Load one tile of B into local memory.
|
|
for (var innerRow = 0; innerRow < RowPerThreadB; innerRow = innerRow + 1) {
|
|
let inputRow = tileRowB + innerRow;
|
|
let inputCol = tileCol;
|
|
mm_Bsub[inputRow][inputCol] = mm_readB(t * TileInner + inputRow, globalCol, globalId);
|
|
}
|
|
|
|
workgroupBarrier();
|
|
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < TileInner / ColPerThread; k = k + 1) {
|
|
BCached[0] = mm_Bsub[k * ColPerThread][tileCol];
|
|
BCached[1] = mm_Bsub[k * ColPerThread + 1][tileCol];
|
|
BCached[2] = mm_Bsub[k * ColPerThread + 2][tileCol];
|
|
BCached[3] = mm_Bsub[k * ColPerThread + 3][tileCol];
|
|
|
|
for (var i = 0; i < RowPerThread; i = i + 1) {
|
|
ACached = mm_Asub[tileRow + i][k];
|
|
acc[i] = BCached[0] * ACached.x + acc[i];
|
|
acc[i] = BCached[1] * ACached.y + acc[i];
|
|
acc[i] = BCached[2] * ACached.z + acc[i];
|
|
acc[i] = BCached[3] * ACached.w + acc[i];
|
|
}
|
|
}
|
|
|
|
workgroupBarrier();
|
|
}
|
|
|
|
for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) {
|
|
mm_write(globalRow + innerRow,
|
|
globalCol,
|
|
acc[innerRow], globalId);
|
|
}
|
|
}`}function Cde(e){return`
|
|
var<workgroup> mm_Asub : array<vec4<f32>, ${e[0]}>;
|
|
let tileSize = ${e[0]*4};
|
|
${Me()} {
|
|
let tileCol = i32(localId.x);
|
|
let globalCol = i32(globalId.x);
|
|
let globalRow = i32(globalId.y);
|
|
|
|
let numTiles = (uniforms.dimInner - 1) / tileSize + 1;
|
|
|
|
// Without this initialization strange values show up in acc.
|
|
var acc = vec4<f32>(0.0);
|
|
|
|
// Loop over shared dimension.
|
|
for (var t = 0; t < numTiles; t = t + 1) {
|
|
// Load one tile of A into local memory.
|
|
let colA = t * tileSize / 4 + tileCol;
|
|
mm_Asub[tileCol] = mm_readA(globalRow, colA, globalId);
|
|
|
|
workgroupBarrier();
|
|
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < tileSize / 4; k = k + 1) {
|
|
let rowB = t * tileSize + k * 4;
|
|
let BCached0 = mm_readB(rowB, globalCol, globalId);
|
|
let BCached1 = mm_readB(rowB + 1, globalCol, globalId);
|
|
let BCached2 = mm_readB(rowB + 2, globalCol, globalId);
|
|
let BCached3 = mm_readB(rowB + 3, globalCol, globalId);
|
|
|
|
let ACached = mm_Asub[k];
|
|
acc = acc + BCached0 * ACached.x;
|
|
acc = acc + BCached1 * ACached.y;
|
|
acc = acc + BCached2 * ACached.z;
|
|
acc = acc + BCached3 * ACached.w;
|
|
}
|
|
|
|
workgroupBarrier();
|
|
}
|
|
|
|
if (globalRow < uniforms.dimAOuter && globalCol < uniforms.dimBOuter) {
|
|
mm_write(globalRow, globalCol, acc, globalId);
|
|
}
|
|
}
|
|
`}var Tde=class{constructor(e,t,n,s=null,r=null,a=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32; dimBOuter : i32; dimInner : i32;",this.workGroupSize=[16,16,1],this.isVec4=!0,this.vecSize=4,this.outputShape=t,this.workGroupSize=Nx(t[1],e[2],t[2]),this.dispatchLayout={x:[2],y:[1],z:[0]},t[1]===1&&(n=1),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.vecSize,n,1]);let o=s!=null,i=a!=null;o&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.workPerThread=n,this.aShape=e,this.addBias=o,this.activation=r,this.hasPreluActivationWeights=i,[this.fitA,this.fitB]=this.getShapeFit(),this.shaderKey=`matMulPackedVec4_${n}_${this.activation}_${this.fitA}_${this.fitB}_${this.outputShape[1]>1}`}getShapeFit(){let e=this.aShape[2],t=this.outputShape[2],n=[this.outputShape[0],e,t],s=this.workGroupSize[1]*this.workPerThread,r=this.workGroupSize[0]*this.vecSize,a=r,o=[s,a],i=[a,r];return[ua(o,this.aShape.slice(1)),ua(i,n.slice(1))]}getUserCode(){let e=this.fitA?"return A.numbers[batch * batchASize + row * uniforms.dimInner / 4 + col]":`if (coordsInBounds2D(vec2<i32>(row, col * 4), vec2<i32>(uniforms.dimAOuter, uniforms.dimInner))) {
|
|
return A.numbers[batch * batchASize + row * uniforms.dimInner / 4 + col];
|
|
}
|
|
return vec4<f32>(0.0)`,t=this.fitB?"return B.numbers[batch * batchBSize + row * uniforms.dimBOuter / 4 + col]":`if(coordsInBounds2D(vec2<i32>(row, col * 4), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return B.numbers[batch * batchBSize + row * uniforms.dimBOuter / 4 + col];
|
|
}
|
|
return vec4<f32>(0.0)`,n="",s="";if(this.activation){let o=Lo(this.activation,this.isVec4);this.hasPreluActivationWeights?n=`fn activation(a : vec4<f32>, outCoord : vec3<i32>) -> vec4<f32> {
|
|
let b = getPreluActivationWeightsAtOutCoordsByCoords(outCoord);
|
|
${o}
|
|
}`:n=`
|
|
fn activation(a : vec4<f32>, outCoord : vec3<i32>) -> vec4<f32> {
|
|
${o}
|
|
}`,s="value = activation(value, outCoord);"}let r=this.addBias?"value = value + getBiasAtOutCoordsByCoords(outCoord);":"";return`
|
|
${n}
|
|
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> vec4<f32> {
|
|
let batchASize = uniforms.aShape[1] * uniforms.aShape[2] / ${this.vecSize};
|
|
let batch = i32(globalId.z);
|
|
${e};
|
|
}
|
|
|
|
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> vec4<f32> {
|
|
let batchBSize = uniforms.bShape[1] * uniforms.bShape[2] / ${this.vecSize};
|
|
let batch = i32(globalId.z);
|
|
${t};
|
|
}
|
|
|
|
fn mm_write(row : i32, col : i32, valueIn : vec4<f32>, globalId : vec3<u32>) {
|
|
if (row < uniforms.aShape[1] && col * 4 < uniforms.bShape[2])
|
|
{
|
|
var value = valueIn;
|
|
let batch = i32(globalId.z);
|
|
let outCoord = vec3<i32>(batch, row, col * 4);
|
|
${r}
|
|
${s}
|
|
setOutput(outCoord[0], outCoord[1], outCoord[2], value);
|
|
}
|
|
}
|
|
${this.outputShape[1]>1?RC([this.vecSize,this.workPerThread,1],this.workGroupSize):Cde(this.workGroupSize)}
|
|
|
|
`}};function Dx(e,t){let n=t[1]*e[1],s=t[0]*e[0],r=n>s?n:s;return`
|
|
var<workgroup> mm_Asub : array<array<f32, ${r}>, ${n}>;
|
|
var<workgroup> mm_Bsub : array<array<f32, ${s}>, ${r}>;
|
|
${Me()} {
|
|
let tileRow = i32(localId.y) * ${e[1]};
|
|
let tileCol = i32(localId.x) * ${e[0]};
|
|
|
|
let globalRow = i32(globalId.y) * ${e[1]};
|
|
let globalCol = i32(globalId.x) * ${e[0]};
|
|
|
|
let numTiles = (uniforms.dimInner - 1) / ${r} + 1;
|
|
|
|
var acc : array<array<f32, ${e[0]}>, ${e[1]}>;
|
|
var ACached : f32;
|
|
var BCached : array<f32, ${e[0]}>;
|
|
|
|
// Without this initialization strange values show up in acc.
|
|
for (var innerRow = 0; innerRow < ${e[1]}; innerRow = innerRow + 1) {
|
|
for (var innerCol = 0; innerCol < ${e[0]}; innerCol = innerCol + 1) {
|
|
acc[innerRow][innerCol] = 0.0;
|
|
}
|
|
}
|
|
|
|
let ColPerThreadA = ${r} / ${t[0]};
|
|
let tileColA = i32(localId.x) * ColPerThreadA;
|
|
let RowPerThreadB = ${r} / ${t[1]};
|
|
let tileRowB = i32(localId.y) * RowPerThreadB;
|
|
|
|
// Loop over shared dimension.
|
|
for (var t = 0; t < numTiles; t = t + 1) {
|
|
// Load one tile of A into local memory.
|
|
for (var innerRow = 0; innerRow < ${e[1]}; innerRow = innerRow + 1) {
|
|
for (var innerCol = 0; innerCol < ColPerThreadA; innerCol = innerCol + 1) {
|
|
let inputRow = tileRow + innerRow;
|
|
let inputCol = tileColA + innerCol;
|
|
|
|
mm_Asub[inputRow][inputCol] = mm_readA(
|
|
globalRow + innerRow,
|
|
t * ${r} + inputCol, globalId);
|
|
}
|
|
}
|
|
// Load one tile of B into local memory.
|
|
for (var innerRow = 0; innerRow < RowPerThreadB; innerRow = innerRow + 1) {
|
|
for (var innerCol = 0; innerCol < ${e[0]}; innerCol = innerCol + 1) {
|
|
let inputRow = tileRowB + innerRow;
|
|
let inputCol = tileCol + innerCol;
|
|
|
|
mm_Bsub[inputRow][inputCol] = mm_readB(
|
|
t * ${r} + inputRow,
|
|
globalCol + innerCol, globalId);
|
|
}
|
|
}
|
|
|
|
workgroupBarrier();
|
|
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < ${r}; k = k + 1) {
|
|
for (var inner = 0; inner < ${e[0]}; inner = inner + 1) {
|
|
BCached[inner] = mm_Bsub[k][tileCol + inner];
|
|
}
|
|
|
|
for (var innerRow = 0; innerRow < ${e[1]}; innerRow = innerRow + 1) {
|
|
ACached = mm_Asub[tileRow + innerRow][k];
|
|
for (var innerCol = 0; innerCol < ${e[0]}; innerCol = innerCol + 1) {
|
|
acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];
|
|
}
|
|
}
|
|
}
|
|
|
|
workgroupBarrier();
|
|
}
|
|
|
|
for (var innerRow = 0; innerRow < ${e[1]}; innerRow = innerRow + 1) {
|
|
for (var innerCol = 0; innerCol < ${e[0]}; innerCol = innerCol + 1) {
|
|
|
|
if ((globalCol + innerCol) < uniforms.dimBOuter &&
|
|
(globalRow + innerRow) < uniforms.dimAOuter) {
|
|
mm_write(globalRow + innerRow,
|
|
globalCol + innerCol,
|
|
acc[innerRow][innerCol], globalId);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
`}function Nde(e){return`
|
|
let TileSize = ${e[0]*4};
|
|
var<workgroup> mm_Asub : array<vec4<f32>, ${e[0]}>;
|
|
|
|
${Me()} {
|
|
let tileCol = i32(localId.x);
|
|
let globalCol = i32(globalId.x);
|
|
let globalRow = i32(globalId.y);
|
|
|
|
let numTiles = (uniforms.dimInner - 1) / TileSize + 1;
|
|
|
|
// Without this initialization strange values show up in acc.
|
|
var acc = 0.0;
|
|
|
|
// Loop over shared dimension.
|
|
for (var t = 0; t < numTiles; t = t + 1) {
|
|
// Load one tile of A into local memory.
|
|
let colA = t * TileSize + tileCol * 4;
|
|
mm_Asub[tileCol] = vec4<f32>(mm_readA(globalRow, colA, globalId),
|
|
mm_readA(globalRow, colA + 1, globalId),
|
|
mm_readA(globalRow, colA + 2, globalId),
|
|
mm_readA(globalRow, colA + 3, globalId));
|
|
workgroupBarrier();
|
|
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < TileSize / 4; k = k + 1) {
|
|
let rowB = t * TileSize + k * 4;
|
|
let BCached = vec4<f32>(mm_readB(rowB, globalCol, globalId),
|
|
mm_readB(rowB + 1, globalCol, globalId),
|
|
mm_readB(rowB + 2, globalCol, globalId),
|
|
mm_readB(rowB + 3, globalCol, globalId));
|
|
|
|
let ACached = mm_Asub[k];
|
|
acc = acc + dot(ACached, BCached);
|
|
}
|
|
|
|
workgroupBarrier();
|
|
}
|
|
|
|
if (globalRow < uniforms.dimAOuter && globalCol < uniforms.dimBOuter) {
|
|
mm_write(globalRow, globalCol, acc, globalId);
|
|
}
|
|
}
|
|
`}var $C=class{constructor(e,t,n,s=!1,r=!1,a=null,o=null,i=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32; dimBOuter : i32; dimInner : i32;",this.workGroupSize=[16,16,1],this.outputShape=t,this.dispatchLayout={x:[2],y:[1],z:[0]};let l=s?e[1]:e[2];this.workGroupSize=Nx(t[1],l,t[2]),(t[1]===1||t[2]===1)&&(n=1),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[n,n,1]),v.arraysEqual(this.dispatch,[1,1,1])&&(n=1,this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[n,n,1]));let c=a!=null,u=i!=null;c&&this.variableNames.push("bias"),u&&this.variableNames.push("preluActivationWeights"),this.workPerThread=n,this.aShape=e,this.transposeA=s,this.transposeB=r,this.addBias=c,this.activation=o,this.hasPreluActivationWeights=u;let d=this.outputShape[2],p=this.transposeB?[this.outputShape[0],d,l]:[this.outputShape[0],l,d];[this.fitA,this.fitB]=this.getShapeFit(p),this.shaderKey=`matMulPacked_${this.workPerThread}_${s}_${r}_${this.activation}_${this.fitA}_${this.fitB}_${this.outputShape[1]>1}`}getShapeFit(e){let t=this.workGroupSize[1]*this.workPerThread,n=this.workGroupSize[0]*this.workPerThread,s=t>n?t:n;this.outputShape[1]===1&&(s*=4),v.assert(s%this.workGroupSize[0]==0&&s%this.workGroupSize[1]==0,()=>"tileInner must be multiple of workgroupsize.x and workgroupsize.y");let r=[t,s],a=[s,n];return[ua(r,this.aShape.slice(1)),ua(a,e.slice(1))]}getUserCode(){let e;this.transposeA===!1?e=this.fitA?"return A.numbers[batch * batchASize + row * uniforms.dimInner + col];":`if(coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimAOuter, uniforms.dimInner))) {
|
|
return A.numbers[batch * batchASize + row * uniforms.dimInner + col];
|
|
}
|
|
return 0.0;`:e=this.fitA?"return A.numbers[batch * batchASize + col * uniforms.dimAOuter + row];":`if(coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimAOuter, uniforms.dimInner))) {
|
|
return A.numbers[batch* batchASize + col * uniforms.dimAOuter + row];
|
|
}
|
|
return 0.0;`;let t;this.transposeB===!1?t=this.fitB?"return B.numbers[batch * batchBSize + row * uniforms.dimBOuter + col];":`if(coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return B.numbers[batch * batchBSize + row * uniforms.dimBOuter + col];
|
|
}
|
|
return 0.0;`:t=this.fitB?"return B.numbers[batch * batchBSize + col * uniforms.dimInner + row];":`if(coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return B.numbers[batch * batchBSize + col * uniforms.dimInner + row];
|
|
}
|
|
return 0.0;`;let n="",s="";if(this.activation){let o=Lo(this.activation,!1);this.hasPreluActivationWeights?n=`fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsAtOutCoordsByCoords(outCoord);
|
|
${o}
|
|
}`:n=`
|
|
fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
${o}
|
|
}
|
|
`,s="value = activation(value, outCoord);"}let r=this.addBias?"value = value + getBiasAtOutCoordsByCoords(outCoord);":"";return`
|
|
${n}
|
|
|
|
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
let batchASize = uniforms.aShape[1] * uniforms.aShape[2];
|
|
let batch = i32(globalId.z);
|
|
${e}
|
|
}
|
|
|
|
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
let batch = i32(globalId.z);
|
|
let batchBSize = uniforms.bShape[1] * uniforms.bShape[2];
|
|
${t}
|
|
}
|
|
|
|
fn mm_write(row : i32, col : i32, valueIn : f32, globalId : vec3<u32>) {
|
|
var value = valueIn;
|
|
let batch = i32(globalId.z);
|
|
let outCoord = vec3<i32>(batch, row, col);
|
|
${r}
|
|
${s}
|
|
setOutput(batch, row, col, value);
|
|
}
|
|
${this.outputShape[1]>1?Dx([this.workPerThread,this.workPerThread,1],this.workGroupSize):Nde(this.workGroupSize)}
|
|
`}};function Ede(e){let t=e[1]/2,n=e[0],s=t>n?t:n;return`
|
|
var<workgroup> mm_Asub1 : array<array<f32, ${s}>, ${t}>;
|
|
var<workgroup> mm_Bsub1 : array<array<f32, ${n}>, ${s}>;
|
|
var<workgroup> mm_Asub2 : array<array<f32, ${s}>, ${t}>;
|
|
var<workgroup> mm_Bsub2 : array<array<f32, ${n}>, ${s}>;
|
|
|
|
// If the output size is small for matrix multiplication, avoid to use vec4
|
|
// and handle some elements per thread to optimally utilize the ALU.
|
|
// Introduces two shared memory buffers, some logical threads could handle
|
|
// arithmetic operations and others handle IO operations between barrier api,
|
|
// makes ALUs and load/store units work simultaneously, could improves
|
|
// the performance.
|
|
${Me()} {
|
|
let tileRow = i32(localId.y);
|
|
let tileCol = i32(localId.x);
|
|
let globalRow = i32(globalId.y);
|
|
let globalCol = i32(globalId.x);
|
|
|
|
// uniforms.dimInner should be greater than 0.
|
|
let numTiles = (uniforms.dimInner - 1) / ${s} + 1;
|
|
var acc = 0.0;
|
|
|
|
var globalColA = tileCol;
|
|
var globalRowB = tileRow;
|
|
for (var t = 0; t < numTiles; t = t + 1) {
|
|
if (t == 0) {
|
|
if (tileRow < ${t}) {
|
|
// Load one tile of A and B into local memory.
|
|
// globalRow is always greater than or equal tileRow.
|
|
mm_Asub1[tileRow][tileCol] =
|
|
mm_readA((globalRow - tileRow) / 2 + tileRow, globalColA, globalId);
|
|
globalColA = globalColA + ${s};
|
|
mm_Bsub1[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
|
|
globalRowB = globalRowB + ${s};
|
|
}
|
|
} else {
|
|
if (tileRow < ${t}) {
|
|
// Load one tile of A and B into local memory.
|
|
// globalRow is always greater than or equal tileRow.
|
|
mm_Asub1[tileRow][tileCol] =
|
|
mm_readA((globalRow - tileRow) / 2 + tileRow, globalColA, globalId);
|
|
globalColA = globalColA + ${s};
|
|
mm_Bsub1[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
|
|
globalRowB = globalRowB + ${s};
|
|
} else {
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < ${s}; k = k + 1) {
|
|
let subRow = tileRow - ${t};
|
|
if (subRow < 0) {
|
|
continue;
|
|
}
|
|
acc = acc + mm_Asub2[subRow][k] * mm_Bsub2[k][tileCol];
|
|
}
|
|
}
|
|
}
|
|
workgroupBarrier();
|
|
if (t != 0) {
|
|
t = t + 1;
|
|
}
|
|
|
|
if (t < numTiles) {
|
|
if (tileRow < ${t}) {
|
|
// Load one tile of A and B into local memory.
|
|
// globalRow is always greater than or equal tileRow.
|
|
mm_Asub2[tileRow][tileCol] =
|
|
mm_readA((globalRow - tileRow) / 2 + tileRow, globalColA, globalId);
|
|
globalColA = globalColA + ${s};
|
|
mm_Bsub2[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
|
|
globalRowB = globalRowB + ${s};
|
|
} else {
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < ${s}; k = k + 1) {
|
|
let subRow = tileRow - ${t};
|
|
if (subRow < 0) {
|
|
continue;
|
|
}
|
|
acc = acc + mm_Asub1[subRow][k] * mm_Bsub1[k][tileCol];
|
|
}
|
|
}
|
|
}
|
|
workgroupBarrier();
|
|
}
|
|
let writeCol = (globalRow - tileRow) / 2 + tileRow - ${t};
|
|
if (tileRow >= ${t} && writeCol >= 0) {
|
|
mm_write(writeCol, globalCol, acc, globalId);
|
|
}
|
|
}
|
|
`}var Rde=class{constructor(e,t,n,s=null,r=null,a=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32; dimBOuter : i32; dimInner : i32;",this.workGroupSize=[8,16,1],v.assert(e[1]<=16||t[2]<=16,()=>"This program can be only used when A width or B Height are small"),this.outputShape=n,this.dispatchLayout={x:[2],y:[1],z:[0]},this.dispatch=[Math.ceil(n[2]/this.workGroupSize[0]),Math.ceil(n[1]*2/this.workGroupSize[1]),n[0]];let o=s!=null;o&&this.variableNames.push("bias");let i=a!=null;i&&this.variableNames.push("preluActivationWeights"),this.addBias=o,this.activation=r,this.hasPreluActivationWeights=i,this.shaderKey=`matMulSmallOutputSize_${this.activation}`}getUserCode(){let e=`if (coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimAOuter, uniforms.dimInner))) {
|
|
return A.numbers[batch * batchASize + row * uniforms.dimInner + col];
|
|
}
|
|
return 0.0;`,t=`if (coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return B.numbers[batch * batchBSize + row * uniforms.dimBOuter + col];
|
|
}
|
|
return 0.0;`,n="",s="";if(this.activation){let o=Lo(this.activation,!1);this.hasPreluActivationWeights?n=`fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsAtOutCoordsByCoords(outCoord);
|
|
${o}
|
|
}`:n=`fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
${o}
|
|
}`,s="value = activation(value, outCoord);"}let r=this.addBias?"value = value + getBiasAtOutCoordsByCoords(outCoord);":"";return`
|
|
${n}
|
|
|
|
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
let batchASize = uniforms.aShape[1] * uniforms.aShape[2];
|
|
let batch = i32(globalId.z);
|
|
${e}
|
|
}
|
|
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
let batch = i32(globalId.z);
|
|
let batchBSize = uniforms.bShape[1] * uniforms.bShape[2];
|
|
${t}
|
|
}
|
|
fn mm_write(row : i32, col : i32, valueIn : f32, globalId : vec3<u32>) {
|
|
if (coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimAOuter, uniforms.dimBOuter))) {
|
|
let batch = i32(globalId.z);
|
|
let outCoord = vec3<i32>(batch, row, col);
|
|
var value = valueIn;
|
|
${r}
|
|
${s}
|
|
setOutput(batch, row, col, value);
|
|
}
|
|
}
|
|
${Ede(this.workGroupSize)}
|
|
`}};function nt(e){let{inputs:t,attrs:n}=e,{x:s}=t,{shape:r}=n,a=v.sizeFromShape(s.shape),o=v.inferFromImplicitShape(r,a),i=v.sizeFromShape(o);return v.assert(a===i,()=>`The new shape (${o}) has ${i} elements and the old shape (${s.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`),e.backend.incRef(s.dataId),{dataId:s.dataId,shape:o,dtype:s.dtype}}var $de={kernelName:Ti,backendName:"webgpu",kernelFunc:nt};function _x({a:e,b:t,transposeA:n,transposeB:s,backend:r,bias:a=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:l=null}){let c=e.shape.length,u=t.shape.length,d=n?e.shape[c-2]:e.shape[c-1],p=s?t.shape[u-1]:t.shape[u-2],h=n?e.shape[c-1]:e.shape[c-2],f=s?t.shape[u-2]:t.shape[u-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=v.sizeFromShape(m),A=v.sizeFromShape(g),x=y===A||y===1||A===1;v.assert(c>=2&&u>=2&&x,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${m}) and (${g}).`);let w=(y>A?e.shape.slice(0,-2):t.shape.slice(0,-2)).concat([h,f]);v.assert(d===p,()=>`Error in matMul: inner shapes (${d}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${s} must match.`);let k=n?[y,d,h]:[y,h,d],S=s?[A,f,p]:[A,p,f],N=nt({inputs:{x:e},backend:r,attrs:{shape:k}}),$=nt({inputs:{x:t},backend:r,attrs:{shape:S}}),F=[N,$],R=Math.max(y,A),D=d%4==0&&f%4==0&&!n&&!s&&f>=32,T;!n&&!s&&(h<=16&&(f<=512||p>=2*f)||f<=16&&(h<=512||d>=2*h))?T=new Rde(k,S,[R,h,f],a,l,o):D?T=new Tde(k,[R,h,f],Z().get("WEBGPU_MATMUL_WORK_PER_THREAD"),a,l,o):T=new $C(k,[R,h,f],Z().get("WEBGPU_MATMUL_WORK_PER_THREAD"),n,s,a,l,o);let O=[N,$];a&&O.push(a),o&&O.push(o);let B=[{type:"int32",data:[h]},{type:"int32",data:[f]},{type:"int32",data:[d]}],H=r.runWebGPUProgram(T,O,e.dtype,B),z=nt({inputs:{x:H},backend:r,attrs:{shape:w}});F.push(H);for(let X of F)r.disposeData(X.dataId);return z}function Dde(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:d}=s;return _x({a:r,b:a,transposeA:l,transposeB:c,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:d,activation:u})}var _de={kernelName:fo,backendName:"webgpu",kernelFunc:Dde},DC=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.workGroupSize=[128,1,1],this.outputShape=E.assertAndGetBroadcastShape(t,n),this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`binaryOpComplex_${e}`,this.op=e,this.size=v.sizeFromShape(this.outputShape)}getUserCode(){return`
|
|
fn binaryOpComplex(
|
|
areal : f32, aimag : f32, breal : f32, bimag : f32) -> f32 {
|
|
${wp(this.op,!1)}
|
|
}
|
|
|
|
${Me()} {
|
|
${He()}
|
|
if(index < uniforms.size) {
|
|
let areal = getARealAtOutCoordsByGlobalId(globalId, index);
|
|
let aimag = getAImagAtOutCoordsByGlobalId(globalId, index);
|
|
let breal = getBRealAtOutCoordsByGlobalId(globalId, index);
|
|
let bimag = getBImagAtOutCoordsByGlobalId(globalId, index);
|
|
setOutputFlat(index, binaryOpComplex(areal, aimag, breal, bimag));
|
|
}
|
|
}
|
|
`}},Pde=class{constructor(e,t,n,s){this.variableNames=["A","B"];let r=256;this.workGroupSize=[r,1,1],this.outputShape=E.assertAndGetBroadcastShape(t,n),this.dispatchLayout=at(this.outputShape),this.lastDimensionSize=s?n[0]:t[0],this.lastDimensionSize<256?this.workPerThread=1:this.lastDimensionSize<512?this.workPerThread=2:this.workPerThread=4,this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.useSharedMemoryWithB=s,this.op=e,this.size=v.sizeFromShape(this.outputShape),this.sizeFit=this.size%(this.workGroupSize[0]*this.workPerThread)==0,this.shaderKey=`binaryShared_${e}_${this.lastDimensionSize}_${this.useSharedMemoryWithB}_${this.sizeFit}`}getUserCode(){let e=this.lastDimensionSize>1?`coords[${this.outputShape.length-1}]`:"0",t=this.useSharedMemoryWithB?`let a = getAAtOutCoordsByCoords(coords);
|
|
let b = sharedBuf[${e}];`:`let a = sharedBuf[${e}];
|
|
let b = getBAtOutCoordsByCoords(coords);`,n=this.sizeFit?`let coords = getCoordsFromFlatIndex(flatIndex);
|
|
|
|
${t}
|
|
setOutputFlat(flatIndex, binaryOperation(a, b));`:`if(flatIndex < uniforms.size) {
|
|
let coords = getCoordsFromFlatIndex(flatIndex);
|
|
|
|
${t}
|
|
setOutputFlat(flatIndex, binaryOperation(a, b));
|
|
}`;return`
|
|
fn binaryOperation(a : f32, b : f32) -> f32 {
|
|
${wp(this.op,!1)}
|
|
}
|
|
var<workgroup> sharedBuf : array<f32, ${this.lastDimensionSize}>;
|
|
${Me()} {
|
|
${He()}
|
|
|
|
// Fill in the shared memory buffer. Here we need a loop to make sure
|
|
// that all data in A|B are uploaded when |sharedMemorySize| is larger
|
|
// than work group size.
|
|
for(var localIndex = i32(localId.x); localIndex < ${this.lastDimensionSize}; localIndex = localIndex + ${this.workGroupSize[0]}) {
|
|
sharedBuf[localIndex] = f32(${this.useSharedMemoryWithB?"B":"A"}.numbers[localIndex]);
|
|
}
|
|
workgroupBarrier();
|
|
|
|
for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
|
|
let flatIndex = index * ${this.workPerThread} + i;
|
|
|
|
${n}
|
|
}
|
|
}
|
|
`}},Fde=class{constructor(e,t,n){this.variableNames=["A","B"],this.workPerThread=4,this.isVec4=!0;let s=128;this.workGroupSize=[s,1,1],this.outputShape=E.assertAndGetBroadcastShape(t,n),this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.op=e,this.fitShape=this.size%this.workGroupSize[0]==0,this.shaderKey=`binaryVec4_${e}_${this.fitShape}`,this.size=v.sizeFromShape(this.outputShape)/this.workPerThread}getUserCode(){let e,n=`fn binaryOperation(a : vec4<f32>, b : vec4<f32>) -> vec4<f32> {
|
|
${wp(this.op,this.isVec4)}
|
|
}`;return this.fitShape?e=`
|
|
${n}
|
|
${Me()} {
|
|
${He()}
|
|
let a = vec4<f32>(A.numbers[index]);
|
|
let b = vec4<f32>(B.numbers[index]);
|
|
setOutputFlat(index, binaryOperation(a, b));
|
|
}
|
|
`:e=`
|
|
${n}
|
|
${Me()} {
|
|
${He()}
|
|
if (index < uniforms.size) {
|
|
let a = vec4<f32>(A.numbers[index]);
|
|
let b = vec4<f32>(B.numbers[index]);
|
|
setOutputFlat(index, binaryOperation(a, b));
|
|
}
|
|
}
|
|
`,e}},_C=class{constructor(e,t,n){this.variableNames=["A","B"];let s=128;this.workGroupSize=[s,1,1],this.outputShape=E.assertAndGetBroadcastShape(t,n),this.dispatchLayout=at(this.outputShape),this.size=v.sizeFromShape(this.outputShape),this.sizeFit=this.size%s==0,this.shapesFit=v.arraysEqual(t,n)&&this.sizeFit,this.workPerThread=this.sizeFit||this.shapesFit?1:2,this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.shaderKey=`binary_${e}_${this.sizeFit}_${this.shapesFit}`,this.op=e}getUserCode(){let e,n=` fn binaryOperation(a : f32, b : f32) -> f32 {
|
|
${wp(this.op,!1)}
|
|
}`;return this.shapesFit?e=`
|
|
${n}
|
|
${Me()} {
|
|
${He()}
|
|
|
|
let a = f32(A[index]);
|
|
let b = f32(B[index]);
|
|
setOutputFlat(index, binaryOperation(a, b));
|
|
}
|
|
`:this.sizeFit?e=`
|
|
${n}
|
|
${Me()} {
|
|
${He()}
|
|
|
|
let coords = getCoordsFromFlatIndex(index);
|
|
|
|
let a = getAAtOutCoordsByCoords(coords);
|
|
let b = getBAtOutCoordsByCoords(coords);
|
|
setOutputFlat(index, binaryOperation(a, b));
|
|
}
|
|
`:e=`
|
|
${n}
|
|
${Me()} {
|
|
${He()}
|
|
for (var i = 0; i < ${this.workPerThread}; i = i + 1 ) {
|
|
let flatIndex = index * ${this.workPerThread} + i;
|
|
|
|
if(flatIndex < uniforms.size) {
|
|
let coords = getCoordsFromFlatIndex(flatIndex);
|
|
|
|
let a = getAAtOutCoordsByCoords(coords);
|
|
let b = getBAtOutCoordsByCoords(coords);
|
|
setOutputFlat(flatIndex, binaryOperation(a, b));
|
|
}
|
|
}
|
|
}
|
|
`,e}};function PC(e,t,n){if(v.arraysEqual(t,n)&&v.sizeFromShape(t)%4==0)return new Fde(e,t,n);let r=t.length===1&&n.length>1&&t[0]<1024,a=n.length===1&&t.length>1&&n[0]<1024;return r||a?new Pde(e,t,n,a):new _C(e,t,n)}function tr(e){let{inputs:t}=e,{x:n}=t;return e.backend.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}var Ode={kernelName:Ba,backendName:"webgpu",kernelFunc:tr};function mc(e){let{inputs:t,backend:n}=e,{real:s,imag:r}=t,a=n.makeTensorInfo(s.shape,"complex64"),o=n.tensorMap.get(a.dataId),i=tr({inputs:{x:s},backend:n}),l=tr({inputs:{x:r},backend:n});return o.complexTensorInfos={real:i,imag:l},a}var Mde={kernelName:jc,backendName:"webgpu",kernelFunc:mc},e0=class{constructor(e,t){this.variableNames=["A"];let n=128;this.workGroupSize=[n,1,1],this.outputShape=e,this.size=v.sizeFromShape(this.outputShape),this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.op=t,this.shaderKey=`unary_${t}`}getUserCode(){return`
|
|
fn unaryOperation(a : f32) -> f32 {
|
|
${fc(this.op,!1)}
|
|
}
|
|
${Me()} {
|
|
${He()}
|
|
if (index < uniforms.size) {
|
|
let a = getAAtOutCoordsByGlobalId(globalId, index);
|
|
setOutputFlat(index, unaryOperation(a));
|
|
}
|
|
}
|
|
`}};function $n({opType:e,cpuKernelImpl:t,dtype:n}){return({inputs:s,backend:r})=>{let{x:a}=s,o=r,i=n||a.dtype;if(o.shouldExecuteOnCPU([a])&&t!=null){let c=o.tensorMap.get(a.dataId),u=t(c.values,i);return o.makeTensorInfo(a.shape,i,u)}let l=new e0(a.shape,e);return o.runWebGPUProgram(l,[a],i)}}function Xn({opSnippet:e,cpuKernelImpl:t,supportsComplex:n=!1,dtype:s}){return({inputs:r,backend:a})=>{let{a:o,b:i}=r,l=a;if(n&&o.dtype==="complex64"){let d=l.tensorMap.get(o.dataId),p=l.tensorMap.get(i.dataId),h,f;if(e!==je.MUL)[h,f]=[[d.complexTensorInfos.real,p.complexTensorInfos.real],[d.complexTensorInfos.imag,p.complexTensorInfos.imag]].map(g=>{let[y,A]=g,x={dataId:y.dataId,dtype:y.dtype,shape:o.shape},b={dataId:A.dataId,dtype:A.dtype,shape:i.shape},w=PC(e,o.shape,i.shape);return l.runWebGPUProgram(w,[x,b],Ln(y.dtype,A.dtype))});else{let g=new DC(je.COMPLEX_MULTIPLY_REAL,o.shape,i.shape),y=new DC(je.COMPLEX_MULTIPLY_IMAG,o.shape,i.shape),A=[{dataId:d.complexTensorInfos.real.dataId,dtype:d.complexTensorInfos.real.dtype,shape:o.shape},{dataId:d.complexTensorInfos.imag.dataId,dtype:d.complexTensorInfos.imag.dtype,shape:o.shape},{dataId:p.complexTensorInfos.real.dataId,dtype:p.complexTensorInfos.real.dtype,shape:i.shape},{dataId:p.complexTensorInfos.imag.dataId,dtype:p.complexTensorInfos.imag.dtype,shape:i.shape}];h=l.runWebGPUProgram(g,A,"float32"),f=l.runWebGPUProgram(y,A,"float32")}let m=mc({inputs:{real:h,imag:f},backend:l});return l.disposeData(h.dataId),l.disposeData(f.dataId),m}let c=s||Ln(o.dtype,i.dtype);if((o.dtype==="string"||i.dtype==="string"||l.shouldExecuteOnCPU([o,i]))&&t!=null){let d=l.tensorMap.get(o.dataId).values,p=l.tensorMap.get(i.dataId).values,h=o.dtype==="string"?E.fromUint8ToStringArray(d):d,f=o.dtype==="string"?E.fromUint8ToStringArray(p):p,[m,g]=t(o.shape,i.shape,h,f,c);return l.makeTensorInfo(g,c,m)}let u=PC(e,o.shape,i.shape);return l.runWebGPUProgram(u,[o,i],c)}}var{addImpl:zde,ceilImpl:Lde,concatImpl:Bde,equalImpl:Wde,expImpl:Vde,expm1Impl:Ude,floorImpl:Gde,gatherNdImpl:Hde,gatherV2Impl:jde,greaterEqualImpl:qde,greaterImpl:Xde,lessEqualImpl:Kde,lessImpl:Zde,logImpl:Yde,maxImpl:Jde,maximumImpl:Qde,minimumImpl:epe,multiplyImpl:tpe,negImpl:npe,notEqualImpl:spe,prodImpl:rpe,rangeImpl:ape,rsqrtImpl:ope,simpleAbsImpl:ipe,sliceImpl:lpe,stridedSliceImpl:upe,stringNGramsImpl:cpe,subImpl:dpe,tileImpl:ppe,transposeImpl:hpe,uniqueImpl:hge}=BA,fpe=$n({opType:Fe.ABS,cpuKernelImpl:ipe}),mpe={kernelName:ni,backendName:"webgpu",kernelFunc:fpe},gpe=Xn({opSnippet:je.ADD,cpuKernelImpl:zde,supportsComplex:!0}),ype={kernelName:qr,backendName:"webgpu",kernelFunc:gpe},Ape=class{constructor(e){this.workPerThread=4,this.workGroupSize=[64,1,1],this.outputShape=e[0],this.variableNames=e.map((t,n)=>`T${n}`),this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.shaderKey="addN",this.size=v.sizeFromShape(this.outputShape)}getUserCode(){let e=[];this.variableNames.forEach(s=>{e.push(`let v${s} = get${s}AtOutCoordsByCoords(coords);`)});let t=this.variableNames.map(s=>`v${s}`).join(" + ");return`
|
|
${Me()} {
|
|
${He()}
|
|
for (var i = 0; i < ${this.workPerThread}; i = i + 1) {
|
|
let flatIndex = index * ${this.workPerThread} + i;
|
|
if (flatIndex < uniforms.size) {
|
|
let coords = getCoordsFromFlatIndex(flatIndex);
|
|
${e.join(`
|
|
`)}
|
|
setOutputFlat(flatIndex, ${t});
|
|
}
|
|
}
|
|
}
|
|
`}};function xpe(e){let{inputs:t,backend:n}=e,s=t;if(s.length===1)return tr({inputs:{x:s[0]},backend:n});let r=s.map(i=>i.dtype).reduce((i,l)=>Ln(i,l)),a=s.map(i=>i.shape),o=new Ape(a);return n.runWebGPUProgram(o,s,r)}var bpe={kernelName:wa,backendName:"webgpu",kernelFunc:xpe},FC=class{constructor(e,t,n){this.variableNames=["x"],this.uniforms="axis : i32;";let s=[t];E.assertAxesAreInnerMostDims("arg"+n.charAt(0).toUpperCase()+n.slice(1),s,e.length),this.op=n==="min"?"<":">";let[r,a]=E.computeOutAndReduceShapes(e,s);this.outputShape=r.length===0?[1]:r;let o=v.sizeFromShape(a);this.reductionFactor=2;let i=256,l=Math.min(Math.ceil(o/this.reductionFactor),i);this.workGroupSize=[l,1,1],this.dispatchLayout={x:[],y:this.outputShape.map((c,u)=>u)},this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.inputShape=e,this.shaderKey=`argMinMax${this.op}`}getUserCode(){let e=this.workGroupSize[0]>1,t=`
|
|
var<workgroup> xBestIndices : array<i32, ${this.workGroupSize[0]}>;
|
|
var<workgroup> xBestValues : array<f32, ${this.workGroupSize[0]}>;
|
|
`,n=`
|
|
xBestIndices[localId.x] = bestIndex;
|
|
xBestValues[localId.x] = bestValue;
|
|
|
|
for(var currentSize = WorkGroupSize; currentSize > 1; currentSize = DIV_CEIL(currentSize, ${this.reductionFactor})) {
|
|
workgroupBarrier();
|
|
|
|
for (var w = 0; w < ${this.reductionFactor}; w = w + 1) {
|
|
let i = i32(localId.x) * ${this.reductionFactor} + w;
|
|
if (i < currentSize) {
|
|
let candidateIndex = xBestIndices[i];
|
|
let candidate = xBestValues[i];
|
|
if(candidate ${this.op} bestValue && !isNanCustom(candidate)) {
|
|
bestValue = candidate;
|
|
bestIndex = candidateIndex;
|
|
}
|
|
}
|
|
}
|
|
|
|
xBestIndices[localId.x] = bestIndex;
|
|
xBestValues[localId.x] = bestValue;
|
|
}
|
|
|
|
if (localId.x == 0u) {
|
|
setOutputFlatI32(flatOutputIndex, i32(bestIndex));
|
|
}
|
|
`,s=ln(this.outputShape.length),r=(i,l)=>this.outputShape.length===1?i:`${i}[${l}]`,a=i=>this.inputShape.length===1?"uniforms.xShape":`uniforms.xShape[${i}]`;return`
|
|
fn DIV_CEIL(a : i32, b : i32) -> i32 {
|
|
return ((a - 1) / b + 1);
|
|
}
|
|
|
|
let WorkGroupSize = ${this.workGroupSize[0]};
|
|
|
|
${e?t:""}
|
|
|
|
// In order to get a flattened index into the input tensor, we need to
|
|
// add back the index along the reduced dimension to |outputCoords|.
|
|
// This function outputs the offset to the first value along
|
|
// |axis| and the stride to get the next value of the input along |axis|.
|
|
fn getInputCoordInfo(globalId : vec3<u32>, globalIndex : i32) -> vec2<i32>{
|
|
let outputCoords : ${s} = getOutputCoords(globalId, globalIndex);
|
|
var i = ${this.outputShape.length-1};
|
|
|
|
var stride = 1;
|
|
var inputStride = 1;
|
|
var offset = 0;
|
|
|
|
for (var r = 1; r <= ${this.inputShape.length}; r = r + 1) {
|
|
let length = ${a(`${this.inputShape.length} - r`)};
|
|
if (${this.inputShape.length} - r == uniforms.axis) {
|
|
inputStride = stride;
|
|
} else {
|
|
offset = offset + ${r("outputCoords","i")} * stride;
|
|
i = i - 1;
|
|
}
|
|
stride = stride * length;
|
|
}
|
|
|
|
return vec2<i32>(offset, inputStride);
|
|
}
|
|
|
|
fn getInputIndex(coordInfo : vec2<i32>, index : i32) -> i32{
|
|
return coordInfo[0] + coordInfo[1] * index;
|
|
}
|
|
|
|
${Me()} {
|
|
${He()}
|
|
let coordInfo = getInputCoordInfo(globalId, index);
|
|
|
|
var bestIndex = 0;
|
|
var bestValue = x.numbers[getInputIndex(coordInfo, bestIndex)];
|
|
|
|
let Length = ${a("uniforms.axis")};
|
|
let WorkPerThread = DIV_CEIL(Length, WorkGroupSize);
|
|
|
|
for (var w = 0; w < WorkPerThread; w = w + 1) {
|
|
let i = i32(globalId.x) * WorkPerThread + w;
|
|
if (i < Length) {
|
|
let candidate = x.numbers[getInputIndex(coordInfo, i)];
|
|
if (candidate ${this.op} bestValue && !isNanCustom(f32(candidate))) {
|
|
bestValue = candidate;
|
|
bestIndex = i;
|
|
}
|
|
}
|
|
}
|
|
|
|
let flatOutputIndex = i32(globalId.y);
|
|
${e?n:"setOutputFlatI32(flatOutputIndex, bestIndex);"}
|
|
}
|
|
`}},vpe=class{constructor(e,t){this.variableNames=["A"],this.workGroupSize=[16,16,1];let n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[t[s]];this.outputShape=n,this.dispatchLayout={x:[0],y:[1]},this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[1,1,1]),this.shaderKey="transposeShared"}getUserCode(){return`
|
|
let TILE_DIM = ${this.workGroupSize[0]};
|
|
var<workgroup> tile : array<array<f32, ${this.workGroupSize[0]+1}>, ${this.workGroupSize[0]}>;
|
|
${Me()} {
|
|
${He()}
|
|
let workGroupID = (globalId - localId)/vec3<u32>(${this.workGroupSize[0]}u, ${this.workGroupSize[1]}u, ${this.workGroupSize[2]}u);
|
|
var x = i32(workGroupID.x) * TILE_DIM + i32(localId.x);
|
|
var y = i32(workGroupID.y) * TILE_DIM + i32(localId.y);
|
|
let width = uniforms.outShape[0];
|
|
let height = uniforms.outShape[1];
|
|
if (x < width && y < height) {
|
|
tile[localId.y][localId.x] =
|
|
A.numbers[y * width + x];
|
|
}
|
|
workgroupBarrier();
|
|
|
|
x = i32(workGroupID.y) * TILE_DIM + i32(localId.x);
|
|
y = i32(workGroupID.x) * TILE_DIM + i32(localId.y);
|
|
if (x < height && y < width) {
|
|
setOutputFlat((y * height + x), tile[localId.x]
|
|
[localId.y]);
|
|
}
|
|
}
|
|
`}},wpe=class{constructor(e,t){this.variableNames=["A"],this.workPerThread=4,this.workGroupSize=[64,1,1];let n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[t[s]];this.outputShape=n,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.newDim=t,this.shaderKey=`transpose_${t}`,this.size=v.sizeFromShape(this.outputShape)}getUserCode(){let e=ln(this.outputShape.length),t=kpe(this.newDim);return`
|
|
${Me()} {
|
|
${He()}
|
|
|
|
for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
|
|
let flatIndex = index * ${this.workPerThread} + i;
|
|
if(flatIndex < uniforms.size) {
|
|
let resRC = getCoordsFromFlatIndex(flatIndex);
|
|
setOutputFlat(flatIndex, A.numbers[getFlatIndex${this.outputShape.length}D(
|
|
${e}(${t}), uniforms.aShape)]);
|
|
}
|
|
}
|
|
}
|
|
`}};function kpe(e){let t=e.length;if(t>4)throw Error(`Transpose for rank ${t} is not yet supported`);let n=new Array(t);for(let s=0;s<e.length;s++)n[e[s]]=`resRC[${s}]`;return n.join()}function Il(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{perm:a}=s,o=n,i=r.shape.length,l=new Array(i);for(let u=0;u<l.length;u++)l[u]=r.shape[a[u]];if(n.shouldExecuteOnCPU([r])){let d=o.tensorMap.get(r.dataId).values,p=hpe(d,r.shape,r.dtype,a,l);return n.makeTensorInfo(l,r.dtype,p)}if(r.shape.length===2&&v.arraysEqual(a,[1,0])){let u=new vpe(r.shape,a);return o.runWebGPUProgram(u,[r],r.dtype)}let c=new wpe(r.shape,a);return o.runWebGPUProgram(c,[r],r.dtype)}var Ipe={kernelName:po,backendName:"webgpu",kernelFunc:Il};function Spe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s,o=v.parseAxisParam(a,r.shape),i=E.getAxesPermutation(o,r.shape.length),l=r,c=[];i!=null&&(l=Il({inputs:{x:r},backend:n,attrs:{perm:i}}),c.push(l),o=E.getInnerMostAxes(o.length,l.shape.length)),E.assertAxesAreInnerMostDims("argMax",[o[0]],l.shape.length);let u=new FC(l.shape,o[0],"max"),d=[{type:"int32",data:[o[0]]}],p=n.runWebGPUProgram(u,[l],"int32",d);return c.forEach(h=>n.disposeData(h.dataId)),p}var Cpe={kernelName:ka,backendName:"webgpu",kernelFunc:Spe};function Tpe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s,o=v.parseAxisParam(a,r.shape),i=E.getAxesPermutation(o,r.shape.length),l=r,c=[];i!=null&&(l=Il({inputs:{x:r},backend:n,attrs:{perm:i}}),c.push(l),o=E.getInnerMostAxes(o.length,l.shape.length)),E.assertAxesAreInnerMostDims("argMin",[o[0]],l.shape.length);let u=new FC(l.shape,o[0],"min"),d=[{type:"int32",data:[o[0]]}],p=n.runWebGPUProgram(u,[l],"int32",d);return c.forEach(h=>n.disposeData(h.dataId)),p}var Npe={kernelName:Yl,backendName:"webgpu",kernelFunc:Tpe},OC=class{constructor(e,t){this.variableNames=["x"],this.uniforms="stride : vec2<i32>; pad : vec2<i32>; dilation : vec2<i32>; convDims : vec2<i32>; filterDims : vec2<i32>;",this.workGroupSize=[128,1,1],this.outputShape=e.outShape,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`pool2D_${t}`,this.poolType=t}getUserCode(){let e="resultValue = max(value, resultValue);";this.poolType==="avg"&&(e="resultValue = resultValue + value; count = count + 1.0;");let t="resultValue";return this.poolType==="avg"&&(t="resultValue / count"),`
|
|
${Me()} {
|
|
${He()}
|
|
let coords = getOutputCoords(globalId, index);
|
|
if (coordsInBounds4D(coords, uniforms.outShape)) {
|
|
let batch = coords[0];
|
|
let xRCCorner = vec2<i32>(coords.yz) * uniforms.stride - uniforms.pad;
|
|
let xRCorner = xRCCorner.x;
|
|
let xCCorner = xRCCorner.y;
|
|
|
|
var resultValue = ${this.poolType==="avg"?"0.0":"-1.0 / pow(10.0, -20.0)"};
|
|
var count = 0.0;
|
|
|
|
for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + uniforms.dilation.x) {
|
|
let xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= uniforms.convDims.x) {
|
|
continue;
|
|
}
|
|
|
|
for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + uniforms.dilation.y) {
|
|
let xC = xCCorner + wC;
|
|
if (xC < 0 || xC >= uniforms.convDims.y) {
|
|
continue;
|
|
}
|
|
|
|
let value = getX(batch, xR, xC, coords[3]);
|
|
${e}
|
|
}
|
|
}
|
|
|
|
setOutput(batch, coords[1], coords[2], coords[3], ${t});
|
|
}
|
|
}
|
|
`}},MC=class{constructor(e){this.variableNames=["x"],this.uniforms="stride : vec2<i32>;",this.workGroupSize=[256,1,1],this.outputShape=e.outShape,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="poolWithFilterSizeEqualsOne"}getUserCode(){return`
|
|
${Me()} {
|
|
${He()}
|
|
let coords = getOutputCoords(globalId, index);
|
|
let batch = coords[0];
|
|
let d = coords[3];
|
|
|
|
if (all(coords < uniforms.outShape)) {
|
|
let xRCCorner = coords.yz * uniforms.stride;
|
|
let xRCorner = xRCCorner.x;
|
|
let xCCorner = xRCCorner.y;
|
|
|
|
let value = getX(batch, xRCorner, xCCorner, d);
|
|
setOutput(batch, coords[1], coords[2], d, value);
|
|
}
|
|
}
|
|
`}};function Epe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,c=1,u=E.computePool2DInfo(r.shape,a,o,c,i,l);if(u.filterWidth===1&&u.filterHeight===1&&v.arraysEqual(u.inShape,u.outShape))return tr({inputs:{x:r},backend:n});let d,p=[{type:"int32",data:[u.strideHeight,u.strideWidth]}];return u.filterHeight===1&&u.filterWidth===1?d=new MC(u):(d=new OC(u,"avg"),p.push({type:"int32",data:[u.padInfo.top,u.padInfo.left]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]},{type:"int32",data:[u.inHeight,u.inWidth]},{type:"int32",data:[u.effectiveFilterHeight,u.effectiveFilterWidth]})),n.runWebGPUProgram(d,[r],r.dtype,p)}var Rpe={kernelName:Ia,backendName:"webgpu",kernelFunc:Epe};function $pe(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:o,transposeB:i}=s;return _x({a:r,b:a,transposeA:o,transposeB:i,backend:n})}var Dpe={kernelName:Sa,backendName:"webgpu",kernelFunc:$pe},_pe=class{constructor(e,t){this.variableNames=["source"],this.workPerThread=1,this.workGroupSize=[64,1,1],this.outputShape=t,this.rank=t.length,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.start=e,this.uniforms=`start : ${ln(e.length)}; `,this.shaderKey="slice",this.size=v.sizeFromShape(this.outputShape)}getUserCode(){let e=ln(this.rank),t=Ppe(this.rank),n;return this.start.length===1?n=this.outputShape.map((r,a)=>"sourceLoc = uniforms.start + coords;"):n=this.outputShape.map((r,a)=>`sourceLoc.${Px[a]} = uniforms.start[${a}] + coords.${Px[a]};`),`
|
|
${Me()} {
|
|
${He()}
|
|
if (index < uniforms.size) {
|
|
var sourceLoc : ${e};
|
|
let coords = getOutputCoords(globalId, index);
|
|
${n.join(`
|
|
`)}
|
|
setOutputFlat(index, getSource(${t}));
|
|
}
|
|
}
|
|
`}},Px=["x","y","z","w","u","v"];function Ppe(e){if(e===1)return"sourceLoc";if(e<=6)return Px.slice(0,e).map(t=>`sourceLoc.${t}`).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}function kp(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:o}=s,[i,l]=yn.parseSliceParams(r,a,o);if(yn.assertParamsValid(r,i,l),n.shouldExecuteOnCPU([r])||r.dtype==="string"){let d=n.tensorMap.get(r.dataId),p=lpe(d.values,i,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,p)}if(v.sizeFromShape(l)===0)return n.makeTensorInfo(l,r.dtype,[]);let c=new _pe(i,l),u=[{type:"int32",data:i}];return n.runWebGPUProgram(c,[r],r.dtype,u)}var Fpe={kernelName:Di,backendName:"webgpu",kernelFunc:kp},Ope=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:o}=s;v.assert(r.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGPU backend not implemented yet");let i=a.reduce((A,x)=>A*x),l=E.getReshaped(r.shape,a,i),c=E.getPermuted(l.length,a.length),u=E.getReshapedPermuted(r.shape,a,i),d=E.getSliceBeginCoords(o,a.length),p=E.getSliceSize(u,o,a.length),h=[],f=nt({inputs:{x:r},backend:n,attrs:{shape:l}}),m=Il({inputs:{x:f},backend:n,attrs:{perm:c}}),g=nt({inputs:{x:m},backend:n,attrs:{shape:u}}),y=kp({inputs:{x:g},backend:n,attrs:{begin:d,size:p}});return h.push(f),h.push(m),h.push(g),h.forEach(A=>n.disposeData(A.dataId)),y},Mpe={kernelName:si,backendName:"webgpu",kernelFunc:Ope},zC=Xn({opSnippet:je.NOT_EQUAL,dtype:"bool",cpuKernelImpl:spe}),zpe={kernelName:bi,backendName:"webgpu",kernelFunc:zC};function Ip(e){let{inputs:t,backend:n}=e,{input:s}=t,r=n.tensorMap.get(s.dataId);return tr({inputs:{x:r.complexTensorInfos.real},backend:n})}var Lpe={kernelName:td,backendName:"webgpu",kernelFunc:Ip};function Bpe(e,t){let n=new e0(e.shape,Fe.TO_INT),s=t.runWebGPUProgram(n,[e],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}function Fx(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dtype:a}=s;if(a==="complex64"){if(r.dtype==="complex64")return tr({inputs:{x:r},backend:n});let o=qt(r.shape),i=Fx({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=mc({inputs:{real:i,imag:o},backend:n});return o.dispose(),n.disposeData(i.dataId),l}if(r.dtype==="complex64"){let o=Ip({inputs:{input:r},backend:n}),i=Fx({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeData(o.dataId),i}if(!v.hasEncodingLoss(r.dtype,a)){let o=tr({inputs:{x:r},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32")return Bpe(r,n);if(a==="bool"){let o=n.makeTensorInfo([],"bool",v.getTypedArrayFromDType("bool",1)),l=zC({inputs:{a:r,b:o},backend:n});return n.disposeData(o.dataId),l}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${a}`)}var Wpe={kernelName:Ca,backendName:"webgpu",kernelFunc:Fx},Vpe=$n({opType:Fe.CEIL,cpuKernelImpl:Lde}),Upe={kernelName:Ta,backendName:"webgpu",kernelFunc:Vpe},Gpe=class{constructor(e){this.variableNames=["A"],this.uniforms="minVal : f32; maxVal : f32;",this.workPerThread=4,this.workGroupSize=[64,1,1],this.isVec4=!0,this.outputShape=e,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.shaderKey="clipVec4",this.size=v.sizeFromShape(this.outputShape)/4}getUserCode(){return`
|
|
${Me()} {
|
|
${He()}
|
|
if(index < uniforms.size) {
|
|
let value = getAAtOutCoordsByGlobalId(globalId, index);
|
|
var clampedValue : vec4<f32>;
|
|
for (var i = 0; i < 4; i = i + 1) {
|
|
if (isNanCustom(value[i])) {
|
|
clampedValue[i] = value[i];
|
|
} else {
|
|
clampedValue[i] = clamp(value[i], uniforms.minVal, uniforms.maxVal);
|
|
}
|
|
}
|
|
|
|
setOutputFlat(index, clampedValue);
|
|
}
|
|
}
|
|
`}},Hpe=class{constructor(e){this.variableNames=["A"],this.uniforms="minVal : f32; maxVal : f32;",this.workGroupSize=[64,1,1],this.outputShape=e,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="clip",this.size=v.sizeFromShape(this.outputShape)}getUserCode(){return`
|
|
${Me()} {
|
|
${He()}
|
|
if(index < uniforms.size) {
|
|
let value = getAAtOutCoordsByGlobalId(globalId, index);
|
|
if (isNanCustom(value)) {
|
|
setOutputFlat(index, value);
|
|
return;
|
|
}
|
|
setOutputFlat(index, clamp(value, uniforms.minVal, uniforms.maxVal));
|
|
}
|
|
}
|
|
`}};function jpe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{clipValueMin:a,clipValueMax:o}=s,i,l=[{type:"float32",data:[a]},{type:"float32",data:[o]}];return v.sizeFromShape(r.shape)%4==0?i=new Gpe(r.shape):i=new Hpe(r.shape),n.runWebGPUProgram(i,[r],r.dtype,l)}var qpe={kernelName:Xr,backendName:"webgpu",kernelFunc:jpe},Xpe=class{constructor(e){this.workPerThread=4,this.workGroupSize=[64,1,1],this.outputShape=E.computeOutShape(e,1),this.variableNames=e.map((t,n)=>`T${n}`),this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.shapes=e,this.shaderKey=`concat${e}`,this.size=v.sizeFromShape(this.outputShape)}getUserCode(){let e=new Array(this.shapes.length-1),t=[];if(e.length>0){e[0]=this.shapes[0][1];for(let a=1;a<e.length;a++)e[a]=e[a-1]+this.shapes[a][1];t.push(`if (yC < ${e[0]}){ setOutput(coords.x, coords.y, getT0(yR, yC)); }`);for(let a=1;a<e.length;a++){let o=e[a-1];t.push(`elseif (yC < ${e[a]}){ setOutput(coords.x, coords.y, getT${a}(yR, yC - ${o})); }`)}let s=e.length,r=e[e.length-1];t.push(`else { setOutput(coords.x, coords.y, getT${s}(yR, yC - ${r})); }`)}else t.push("setOutput(coords.x, coords.y, getT0(yR, yC));");return`
|
|
${Me()} {
|
|
${He()}
|
|
for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
|
|
let flatIndex = index * ${this.workPerThread} + i;
|
|
if(flatIndex < uniforms.size) {
|
|
let coords = getCoordsFromFlatIndex(flatIndex);
|
|
let yR = coords.x;
|
|
let yC = coords.y;
|
|
|
|
${t.join(`
|
|
`)}
|
|
}
|
|
}
|
|
}
|
|
`}};function t0(e){let{inputs:t,backend:n}=e,{input:s}=t,r=n.tensorMap.get(s.dataId);return tr({inputs:{x:r.complexTensorInfos.imag},backend:n})}var Kpe={kernelName:Yc,backendName:"webgpu",kernelFunc:t0};function Ox(e,t,n){let s=e[0].dtype;if(s==="complex64"){let u=e.map(m=>Ip({inputs:{input:m},backend:n})),d=e.map(m=>t0({inputs:{input:m},backend:n})),p=Ox(u,t,n),h=Ox(d,t,n),f=mc({inputs:{real:p,imag:h},backend:n});return u.forEach(m=>n.disposeData(m.dataId)),d.forEach(m=>n.disposeData(m.dataId)),n.disposeData(p.dataId),n.disposeData(h.dataId),f}let r=n.shouldExecuteOnCPU(e);if(s==="string"&&(r=!0),r){let u=e.map(y=>{let A=v.sizeFromShape(y.shape.slice(t));return nt({inputs:{x:y},backend:n,attrs:{shape:[-1,A]}})}),d=u.map(y=>({vals:n.readSync(y.dataId),shape:y.shape})),p=E.computeOutShape(u.map(y=>y.shape),1),h=u[0].shape[0]===1,f=Bde(d,p,s,h),m=E.computeOutShape(e.map(y=>y.shape),t),g=n.makeTensorInfo(m,s,f);return u.forEach(y=>n.disposeData(y.dataId)),g}let{tensors2D:a,outShape:o}=Zpe(e,t,n),i=new Xpe(a.map(u=>u.shape)),l=n.runWebGPUProgram(i,a,a[0].dtype);a.forEach(u=>n.disposeData(u.dataId));let c=nt({inputs:{x:l},backend:n,attrs:{shape:o}});return n.disposeData(l.dataId),c}function Zpe(e,t,n){let s=E.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>nt({inputs:{x:a},backend:n,attrs:{shape:[v.sizeFromShape(a.shape.slice(0,t)),v.sizeFromShape(a.shape.slice(t))]}})),outShape:s}}function LC(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s,a=v.parseAxisParam(r,t[0].shape)[0],o=E.computeOutShape(t.map(c=>c.shape),a);if(v.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(c=>v.sizeFromShape(c.shape)>0);if(i.length===1)return tr({inputs:{x:i[0]},backend:n});let l=i.map(c=>c.shape);return E.assertParamsConsistent(l,a),Ox(i,a,n)}var Ype={kernelName:ri,backendName:"webgpu",kernelFunc:LC},Jpe=class{constructor(e,t){this.variableNames=["A"],this.uniforms=`pad : vec2<i32>; stride : vec2<i32>; dilation : vec2<i32>; outWidth : i32; itemsPerBlockRow : i32;
|
|
inChannels : i32;`,this.workPerThread=4,this.workGroupSize=[64,1,1],this.outputShape=e,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.isChannelsLast=t,this.shaderKey=`im2col_${this.isChannelsLast}`,this.size=v.sizeFromShape(this.outputShape)}getUserCode(){let e=this.isChannelsLast?0:1,t=this.isChannelsLast?1:2;return`
|
|
${Me()} {
|
|
${He()}
|
|
|
|
for(var i = 0; i<${this.workPerThread}; i = i + 1) {
|
|
let flatIndex = index * ${this.workPerThread} + i;
|
|
|
|
let rc = getCoordsFromFlatIndex(flatIndex);
|
|
|
|
if(flatIndex < uniforms.size) {
|
|
let blockIndex = rc[0];
|
|
let pos = rc[1];
|
|
|
|
let offsetY = blockIndex / uniforms.outWidth * uniforms.stride[1] - uniforms.pad[1];
|
|
let d0 = offsetY + uniforms.dilation[1] * pos / uniforms.itemsPerBlockRow;
|
|
var value = 0.0;
|
|
if(d0 < uniforms.aShape[${e}] && d0 >= 0) {
|
|
let offsetX = (blockIndex % uniforms.outWidth) * uniforms.stride[0] -
|
|
uniforms.pad[0];
|
|
let d1 = offsetX + uniforms.dilation[0] * ((pos %
|
|
uniforms.itemsPerBlockRow) / uniforms.inChannels);
|
|
let ch = pos % uniforms.inChannels;
|
|
if(d1 < uniforms.aShape[${t}] && d1 >= 0) {
|
|
value = getA(d0, d1, ch);
|
|
}
|
|
}
|
|
setOutputFlat(flatIndex, value);
|
|
}
|
|
}
|
|
}
|
|
`}};function BC({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let l=e.shape,c=n.dataFormat==="channelsLast",u=!1,d=!1,p=c?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],h=nt({inputs:{x:e},backend:s,attrs:{shape:[1,p,n.inChannels]}}),f=nt({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}}),m=_x({a:h,b:f,transposeA:u,transposeB:d,backend:s,bias:r,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),g=nt({inputs:{x:m},backend:s,attrs:{shape:n.outShape}});return s.disposeData(h.dataId),s.disposeData(f.dataId),s.disposeData(m.dataId),g}function Qpe({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:l,filterHeight:c,inChannels:u,strideWidth:d,strideHeight:p,padInfo:h,outWidth:f,outHeight:m,dilationWidth:g,dilationHeight:y,dataFormat:A}=n,x=A==="channelsLast",b=l*c*u,w=m*f,k=[w,b],S=!1,N=!1,$=[],F=nt({inputs:{x:e},backend:s,attrs:{shape:e.shape.slice(1)}}),R=nt({inputs:{x:t},backend:s,attrs:{shape:[1,b,-1]}});$.push(F),$.push(R);let D=new Jpe(k,x),T=[{type:"int32",data:[h.left,h.top]},{type:"int32",data:[d,p]},{type:"int32",data:[g,y]},{type:"int32",data:[f]},{type:"int32",data:[u*l]},{type:"int32",data:[u]}],O=s.runWebGPUProgram(D,[F],F.dtype,T),B=nt({inputs:{x:O},backend:s,attrs:{shape:[1,k[0],k[1]]}});$.push(O),$.push(B);let H=[1,k[0],k[1]],z=new $C(H,[1,w,n.outChannels],Z().get("WEBGPU_MATMUL_WORK_PER_THREAD"),S,N),X=H[1],ee=H[2],J=n.outChannels,Q=[{type:"int32",data:[X]},{type:"int32",data:[J]},{type:"int32",data:[ee]}],ne=s.runWebGPUProgram(z,[B,R],B.dtype,Q),K=x?[1,m,f,n.outChannels]:[1,n.outChannels,m,f],oe=nt({inputs:{x:ne},backend:s,attrs:{shape:K}});$.push(ne);for(let ce of $)s.disposeData(ce.dataId);return oe}var WC=class{constructor(e,t=!1,n=null,s=!1,r=!1){this.variableNames=["x","W"],this.uniforms=`filterDims : vec2<i32>; pad : vec2<i32>; stride : vec2<i32>; dilation : vec2<i32>;
|
|
dimAOuter : i32; dimBOuter : i32; dimInner : i32;`,this.isVec4=!0,this.outputShape=e.outShape,v.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),this.dispatchLayout={x:[3],y:[1,2],z:[0]},this.workGroupSize=[8,8,1];let a=[4,4,1];this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,a),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivationWeights=s,this.hasLeakyreluAlpha=r,this.addBias&&this.variableNames.push("bias"),this.hasPreluActivationWeights&&this.variableNames.push("preluActivationWeights"),this.hasLeakyreluAlpha&&this.variableNames.push("leakyreluAlpha"),[this.fitA,this.fitB]=this.getShapeFit(a),this.shaderKey=`conv2DMMVec4_${this.activation}_${this.fitA}_${this.fitB}`}getShapeFit(e){let t=this.workGroupSize[1]*e[1],n=this.workGroupSize[0]*e[0],s=n,r=[t,s],a=[s,n],o=this.outputShape[1]*this.outputShape[2],i=this.outputShape[3],l=this.convInfo.filterHeight*this.convInfo.filterWidth*this.convInfo.inChannels;return[ua(r,[o,l]),ua(a,[l,i])]}getSampleAWithRemainder(e){return`let flatIndex${e} = getFlatIndex4D(coord, uniforms.xShape);
|
|
let divBy4Remainder${e} = flatIndex${e} % 4;
|
|
let divBy4Index${e} = flatIndex${e} / 4;
|
|
let curData${e} = x.numbers[divBy4Index${e}];
|
|
if (divBy4Remainder${e} == 0) {
|
|
temp = curData${e};
|
|
} else {
|
|
// TODO: This could end up being a redundant load with another one in
|
|
// the same shader invocation. Perhaps there's an opportunity for
|
|
// optimization
|
|
let nextData${e} = x.numbers[divBy4Index${e} + 1];
|
|
if (divBy4Remainder${e} == 1) {
|
|
temp = vec4<f32>(curData${e}.yzw, nextData${e}.x);
|
|
} elseif (divBy4Remainder${e} == 2) {
|
|
temp = vec4<f32>(curData${e}.zw, nextData${e}.xy);
|
|
} elseif (divBy4Remainder${e} == 3) {
|
|
temp = vec4<f32>(curData${e}.w, nextData${e}.xyz);
|
|
}
|
|
}
|
|
`}getUserCode(){let t=RC([4,4,1],this.workGroupSize),r=`let outRow = r / uniforms.outShape[2];
|
|
let outCol = r % uniforms.outShape[2];
|
|
let WRow = c / (uniforms.filterDims[1] * uniforms.xShape[3]);
|
|
let WCol = c / uniforms.xShape[3] % uniforms.filterDims[1];
|
|
let inChCoord = c % uniforms.xShape[3];
|
|
var coord = vec4<i32>(
|
|
batch,
|
|
outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0],
|
|
outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1],
|
|
inChCoord);
|
|
var resData = vec4<f32>(0.0);
|
|
${this.convInfo.inChannels%4===0?`// The bounds checking is always needed since we use it to pad zero for
|
|
// the 'same' padding type.
|
|
if (coordsInBounds4D(coord, uniforms.xShape)) {
|
|
resData = x.numbers[getFlatIndex4D(coord, uniforms.xShape) / 4];
|
|
} else {
|
|
resData = vec4<f32>(0.0); }`:`var temp = vec4<f32>(0.0);
|
|
${this.getSampleAWithRemainder(1)}
|
|
resData = temp;
|
|
if (WCol == (uniforms.filterDims[1] - 1)) {
|
|
coord = vec4<i32>(
|
|
coord.x, coord.y + 1, coord.z + 1 - uniforms.filterDims[1], 0);
|
|
${this.getSampleAWithRemainder(2)}
|
|
if (inChCoord == 0) {
|
|
resData = vec4<f32>(resData.xyz, temp.x);
|
|
} elseif (inChCoord == 1) {
|
|
resData = vec4<f32>(resData.xy, temp.xy);
|
|
} else {
|
|
resData = vec4<f32>(resData.x, temp.xyz);
|
|
}
|
|
}
|
|
`}
|
|
return resData;`,a=this.fitA?`${r}`:`if (r < uniforms.dimAOuter && c < uniforms.dimInner) {
|
|
${r}
|
|
}
|
|
return vec4<f32>(0.0);
|
|
`,o=this.fitB?"return W.numbers[row * uniforms.dimBOuter / 4 + col];":`if(coordsInBounds2D(vec2<i32>(row, col * 4), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return W.numbers[row * uniforms.dimBOuter / 4 + col];
|
|
}
|
|
return vec4<f32>(0.0);
|
|
`,i="",l="";if(this.activation){let d=Lo(this.activation,this.isVec4);if(this.hasPreluActivationWeights)i=`fn activation(a : vec4<f32>, outCoord : vec4<i32>) -> vec4<f32> {
|
|
let b = getPreluActivationWeightsAtOutCoordsByCoords(outCoord);
|
|
${d}
|
|
}`;else{if(this.hasLeakyreluAlpha)throw i=`fn activation(a: vec4<f32>) -> vec4<f32> {
|
|
let b = getLeakyreluAlphaAtOutCoords();
|
|
${d}
|
|
}`,new Error("Leakyrelu is not supported.");i=`
|
|
fn activation(a : vec4<f32>, outCoord : vec4<i32>) -> vec4<f32> {
|
|
${d}
|
|
}`}l="value = activation(value, outCoord);"}let c=this.addBias?"value = value + getBiasAtOutCoordsByCoords(outCoord);":"";return`
|
|
${i}
|
|
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> vec4<f32> {
|
|
let r = row;
|
|
let c = col * 4;
|
|
var batch = i32(globalId.z);
|
|
${a}
|
|
}
|
|
|
|
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> vec4<f32> {
|
|
${o}
|
|
}
|
|
|
|
fn mm_write(row : i32, col : i32, valueInput : vec4<f32>, globalId : vec3<u32>) {
|
|
var batch = i32(globalId.z);
|
|
var value = valueInput;
|
|
if (row < uniforms.dimAOuter && col * 4 < uniforms.dimBOuter)
|
|
{
|
|
let outCoord = vec4<i32>(
|
|
batch,
|
|
row / uniforms.outShape[2],
|
|
row % uniforms.outShape[2],
|
|
col * 4);
|
|
${c}
|
|
${l}
|
|
setOutput(outCoord[0], outCoord[1], outCoord[2], outCoord[3],
|
|
value);
|
|
}
|
|
}
|
|
${t}
|
|
`}},VC=class{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.uniforms="filterDims : vec2<i32>; pad : vec2<i32>; stride : vec2<i32>; dilation : vec2<i32>; dimAOuter : i32; dimBOuter : i32; dimInner : i32;",this.outputShape=e.outShape,v.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),this.dispatchLayout={x:[3],y:[1,2],z:[0]},this.workGroupSize=Tx(this.dispatchLayout,this.outputShape),this.elementsPerThread=Ex(this.dispatchLayout,this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread),t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivationWeights=s,[this.fitA,this.fitB]=this.getShapeFit(),this.shaderKey=`conv2DMM_${this.elementsPerThread}_${this.activation}_${this.fitA}_${this.fitB}`}getShapeFit(){let e=this.workGroupSize[1]*this.elementsPerThread[1],t=this.workGroupSize[0]*this.elementsPerThread[0],n=e>t?e:t;v.assert(n%this.workGroupSize[0]==0&&n%this.workGroupSize[1]==0,()=>"tileInner must be multiple of workgroupsize.x and workgroupsize.y");let s=[e,n],r=[n,t],a=this.outputShape[1]*this.outputShape[2],o=this.outputShape[3],i=this.convInfo.filterHeight*this.convInfo.filterWidth*this.convInfo.inChannels;return[ua(s,[a,i]),ua(r,[i,o])]}getUserCode(){let e=Dx(this.elementsPerThread,this.workGroupSize),t=`
|
|
let outRow = row / uniforms.outShape[2];
|
|
let outCol = row % uniforms.outShape[2];
|
|
|
|
let WRow = col / (uniforms.filterDims[1] * uniforms.xShape[3]);
|
|
let WCol = col / uniforms.xShape[3] % uniforms.filterDims[1];
|
|
let coord = vec4<i32>(
|
|
batch,
|
|
outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0],
|
|
outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1],
|
|
col % uniforms.xShape[3]);
|
|
// The bounds checking is always needed since we use it to pad zero for the
|
|
// 'same' padding type.
|
|
if(coordsInBounds4D(coord, uniforms.xShape)) {
|
|
return x.numbers[getFlatIndex4D(coord, uniforms.xShape)];
|
|
}
|
|
return 0.0;`,n=this.fitA?`${t}`:`if (row < uniforms.dimAOuter && col < uniforms.dimInner) {
|
|
${t}
|
|
}
|
|
return 0.0;
|
|
`,s=this.fitB?"return W.numbers[row * uniforms.dimBOuter + col];":`if(coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return W.numbers[row * uniforms.dimBOuter + col];
|
|
}
|
|
return 0.0;
|
|
`,r="",a="";if(this.activation){let l=Lo(this.activation,!1);this.hasPreluActivationWeights?r=`fn activation(a: f32, outCoord : vec4<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsAtOutCoordsByCoords(outCoord);
|
|
${l}
|
|
}`:r=`
|
|
fn activation(a : f32, outCoord : vec4<i32>) -> f32 {
|
|
${l}
|
|
}
|
|
`,a="value = activation(value, outCoord);"}let o=this.addBias?"value = value + getBiasAtOutCoordsByCoords(outCoord);":"";return`
|
|
${r}
|
|
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
var batch = i32(globalId.z);
|
|
${n}
|
|
}
|
|
|
|
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
${s}
|
|
}
|
|
|
|
fn mm_write(row : i32, col : i32, valueInput : f32, globalId : vec3<u32>) {
|
|
var batch = i32(globalId.z);
|
|
var value = valueInput;
|
|
let outCoord = vec4<i32>(
|
|
batch,
|
|
row / uniforms.outShape[2],
|
|
row % uniforms.outShape[2],
|
|
col);
|
|
${o}
|
|
${a}
|
|
result.numbers[getFlatIndex4D(outCoord, uniforms.outShape)] = value;
|
|
}
|
|
${e}
|
|
`}},UC=class{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.uniforms="filterDims : vec2<i32>; pad : vec2<i32>; stride : vec2<i32>; dilation : vec2<i32>;",this.workGroupSize=[128,1,1],this.outputShape=e.outShape,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),v.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivationWeights=s,this.shaderKey=`conv2DNaive_${this.activation}`}getUserCode(){let e="",t="";if(this.activation){let r=Lo(this.activation);this.hasPreluActivationWeights?e=`fn activation(a : f32, outCoord : vec4<i32>) -> f32{
|
|
let b = getPreluActivationWeightsAtOutCoordsByCoords(outCoord);
|
|
${r}
|
|
}`:e=`
|
|
fn activation(a : f32, outCoord : vec4<i32>) -> f32{
|
|
${r}
|
|
}
|
|
`,t="value = activation(value, outCoord);"}let n=this.addBias?"value = value + getBiasAtOutCoordsByCoords(outCoord);":"";return`
|
|
${e}
|
|
fn readInp(batch : i32, row : i32, col : i32, chan : i32) -> f32 {
|
|
let coord = vec4<i32>(batch, row, col, chan);
|
|
if(coordsInBounds4D(coord, uniforms.xShape)) {
|
|
return getX(batch, row, col, chan);
|
|
}
|
|
return 0.0;
|
|
}
|
|
|
|
fn readFilt(row : i32, col : i32, xChannel : i32, outChannel : i32) -> f32{
|
|
let coord = vec4<i32>(row, col, xChannel, outChannel);
|
|
if(coordsInBounds4D(coord, uniforms.wShape)) {
|
|
return getW(row, col, xChannel, outChannel);
|
|
}
|
|
return 0.0;
|
|
}
|
|
|
|
fn writeResult(batch : i32, row : i32, col : i32, chan : i32, value : f32) {
|
|
let coord = vec4<i32>(batch, row, col, chan);
|
|
if (coordsInBounds4D(coord, uniforms.outShape)) {
|
|
${n}
|
|
${t}
|
|
setOutput(batch, row, col, chan, value);
|
|
}
|
|
}
|
|
|
|
${Me()} {
|
|
${He()}
|
|
let coords = getOutputCoords(globalId, index);
|
|
let batch = coords[0];
|
|
let outChannel = coords[3];
|
|
|
|
var acc = 0.0;
|
|
|
|
for (var row = 0; row < uniforms.filterDims[0]; row = row + 1) {
|
|
for (var col = 0; col < uniforms.filterDims[1]; col = col + 1) {
|
|
for (var xChannel = 0; xChannel < uniforms.xShape[3]; xChannel = xChannel + 1) {
|
|
let coordRow = coords[1] * uniforms.stride[0] + uniforms.dilation[0] * row - uniforms.pad[0];
|
|
let coordCol = coords[2] * uniforms.stride[1] + uniforms.dilation[1] * col - uniforms.pad[1];
|
|
let v = readInp(batch, coordRow, coordCol, xChannel);
|
|
let f = readFilt(row, col, xChannel, outChannel);
|
|
acc = acc + v * f;
|
|
}
|
|
}
|
|
}
|
|
|
|
writeResult(batch, coords[1], coords[2], outChannel, acc);
|
|
}
|
|
`}};function ehe(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dataFormat:l,dilations:c,dimRoundingMode:u}=n,d=E.convertConv2DDataFormat(l),p=E.computeConv2DInfo(r.shape,a.shape,o,c,i,u,!1,d);if(p.filterHeight===1&&p.filterWidth===1&&p.dilationHeight===1&&p.dilationWidth===1&&p.strideHeight===1&&p.strideWidth===1&&(p.padInfo.type==="SAME"||p.padInfo.type==="VALID"))return BC({x:r,filter:a,convInfo:p,backend:s});if(Z().getBool("WEBGPU_CONV_SEPARATE_IM2COL_SHADER")&&r.shape[0]===1)return Qpe({x:r,filter:a,convInfo:p,backend:s});let h,f=[p.padInfo.top,p.padInfo.left],m=[{type:"int32",data:[p.filterHeight,p.filterWidth]},{type:"int32",data:[...f]},{type:"int32",data:[p.strideHeight,p.strideWidth]},{type:"int32",data:[p.dilationHeight,p.dilationWidth]}],g=Z().getBool("WEBGPU_USE_NAIVE_CONV2D");if(g?h=new UC(p):(p.inChannels%4==0||p.inChannels===3&&p.padInfo.type==="VALID")&&p.outChannels%4==0&&p.outChannels>=64?h=new WC(p):h=new VC(p),!g){let y=p.outShape[1]*p.outShape[2],A=p.outShape[3],x=p.filterHeight*p.filterWidth*p.inShape[3];m.push({type:"int32",data:[y]},{type:"int32",data:[A]},{type:"int32",data:[x]})}return s.runWebGPUProgram(h,[r,a],r.dtype,m)}var the={kernelName:Na,backendName:"webgpu",kernelFunc:ehe},nhe=class{constructor(e){this.variableNames=["x","W"],this.uniforms="filterDims : vec2<i32>; pads : vec2<i32>; stride : vec2<i32>; outBackprop : vec4<i32>; dimAOuter : i32; dimBOuter : i32; dimInner : i32;",this.outputShape=e.inShape,v.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),this.dispatchLayout={x:[3],y:[1,2],z:[0]},this.workGroupSize=Tx(this.dispatchLayout,this.outputShape),this.elementsPerThread=Ex(this.dispatchLayout,this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread),this.shaderKey=`conv2DDerInputMM_${this.elementsPerThread}`}getUserCode(){return`
|
|
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
var batch = i32(globalId.z);
|
|
if (row < uniforms.dimAOuter && col < uniforms.dimInner) {
|
|
|
|
let outRow = row / uniforms.outShape[2];
|
|
let outCol = row % uniforms.outShape[2];
|
|
|
|
let WRow = col / (uniforms.filterDims[1] * uniforms.outBackprop[3]);
|
|
let WCol = col / uniforms.outBackprop[3] % uniforms.filterDims[1];
|
|
let xR = f32(outRow - uniforms.pads[0] + WRow) / f32(uniforms.stride[0]);
|
|
let xC = f32(outCol - uniforms.pads[1] + WCol) / f32(uniforms.stride[1]);
|
|
if (xR < 0.0 || xR >= f32(uniforms.outBackprop[1]) || fract(xR) > 0.0) {
|
|
return 0.0;
|
|
}
|
|
if (xC < 0.0 || xC >= f32(uniforms.outBackprop[2]) || fract(xC) > 0.0) {
|
|
return 0.0;
|
|
}
|
|
let coord = vec4<i32>(
|
|
batch,
|
|
i32(xR),
|
|
i32(xC),
|
|
col % uniforms.outBackprop[3]);
|
|
return x.numbers[getFlatIndex4D(coord, uniforms.xShape)];
|
|
}
|
|
return 0.0;
|
|
}
|
|
|
|
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
let coordX = uniforms.filterDims.x - 1 -
|
|
row / (uniforms.filterDims[1] * uniforms.outBackprop[3]);
|
|
let coordY = uniforms.filterDims.y - 1 -
|
|
(row / uniforms.outBackprop[3]) % uniforms.filterDims[1];
|
|
if (row < uniforms.dimInner && col < uniforms.dimBOuter &&
|
|
coordX >= 0 && coordY >= 0) {
|
|
let coord = vec4<i32>(coordX, coordY, col,
|
|
row % uniforms.outBackprop[3]);
|
|
return W.numbers[getFlatIndex4D(coord, uniforms.wShape)];
|
|
}
|
|
return 0.0;
|
|
}
|
|
|
|
fn mm_write(row : i32, col : i32, valueInput : f32, globalId : vec3<u32>) {
|
|
var batch = i32(globalId.z);
|
|
var value = valueInput;
|
|
let outCoord = vec4<i32>(
|
|
batch,
|
|
row / uniforms.outShape[2],
|
|
row % uniforms.outShape[2],
|
|
col);
|
|
result.numbers[getFlatIndex4D(outCoord, uniforms.outShape)] = value;
|
|
}
|
|
|
|
${Dx(this.elementsPerThread,this.workGroupSize)}
|
|
`}},she=class{constructor(e){this.variableNames=["dy","W"],this.uniforms="filterDims : vec2<i32>; pads : vec2<i32>; stride : vec2<i32>; outBackprop : vec4<i32>;",this.workGroupSize=[64,1,1],this.outputShape=e.inShape,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.isChannelsLast=e.dataFormat==="channelsLast",this.shaderKey=`conv2DDerInput_${this.isChannelsLast}`}getUserCode(){let e=this.isChannelsLast?1:2,t=this.isChannelsLast?2:3,n=this.isChannelsLast?3:1;return`
|
|
${Me()} {
|
|
${He()}
|
|
let coords = getOutputCoords(globalId, index);
|
|
if (coordsInBounds4D(coords, uniforms.outShape)) {
|
|
let batch = coords[0];
|
|
let d1 = coords[${n}];
|
|
|
|
let dyCorner = vec2<i32>(coords[${e}]), coords[${t}]) - uniforms.pads;
|
|
let dyRCorner = dyCorner.x;
|
|
let dyCCorner = dyCorner.y;
|
|
|
|
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
var dotProd = 0.0;
|
|
for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + 1) {
|
|
let dyR = (f32(dyRCorner) + f32(wR)) / f32(uniforms.stride.x);
|
|
let wRPerm = uniforms.filterDims.x - 1 - wR;
|
|
if (dyR < 0.0 || dyR >= f32(uniforms.outBackprop[1]) || fract(dyR) > 0.0 ||
|
|
wRPerm < 0) {
|
|
continue;
|
|
}
|
|
let idyR = dyR;
|
|
|
|
for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + 1) {
|
|
let dyC = (f32(dyCCorner) + f32(wC)) / f32(uniforms.stride.y);
|
|
let wCPerm = uniforms.filterDims.y - 1 - wC;
|
|
if (dyC < 0.0 || dyC >= f32(uniforms.outBackprop[2]) ||
|
|
fract(dyC) > 0.0 || wCPerm < 0) {
|
|
continue;
|
|
}
|
|
let idyC = dyC;
|
|
|
|
for (var d2 = 0; d2 < uniforms.outBackprop[3]; d2 = d2 + 1) {
|
|
if (${this.isChannelsLast}) {
|
|
let xValue = getDy(batch, idyR, idyC, d2);
|
|
let wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
dotProd = dotProd + xValue * wValue;
|
|
} else {
|
|
let xValue = getDy(batch, d2, idyR, idyC);
|
|
let wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
dotProd = dotProd + xValue * wValue;
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
setOutput(coords[0], coords[1], coords[2], coords[3], dotProd);
|
|
}
|
|
}
|
|
`}};function rhe(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{inputShape:o,strides:i,pad:l,dataFormat:c,dimRoundingMode:u}=s,d=E.convertConv2DDataFormat(c),p=E.computeConv2DInfo(o,a.shape,i,1,l,u,!1,d),h=[{type:"int32",data:[p.filterHeight,p.filterWidth]},{type:"int32",data:[p.filterHeight-1-p.padInfo.top,p.filterWidth-1-p.padInfo.left]},{type:"int32",data:[p.strideHeight,p.strideWidth]},{type:"int32",data:[p.batchSize,p.outHeight,p.outWidth,p.outChannels]}],f;if(Z().getBool("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE"))f=new she(p);else{f=new nhe(p);let m=p.inShape[1]*p.inShape[2],g=p.inShape[3],y=p.filterHeight*p.filterWidth*p.outChannels;h.push({type:"uint32",data:[m]},{type:"uint32",data:[g]},{type:"uint32",data:[y]})}return n.runWebGPUProgram(f,[r,a],"float32",h)}var ahe={kernelName:Ea,backendName:"webgpu",kernelFunc:rhe},ohe=$n({opType:Fe.COS}),ihe={kernelName:Ra,backendName:"webgpu",kernelFunc:ohe},lhe=$n({opType:Fe.COSH}),uhe={kernelName:$a,backendName:"webgpu",kernelFunc:lhe},che=class{constructor(e,t,n,s){this.variableNames=["Image","Boxes","BoxInd"],this.uniforms="extrapolationValue : f32;",this.workGroupSize=[64,1,1];let[r]=t;this.outputShape=[r,n[0],n[1],e],this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.methodId=s==="bilinear"?1:0,this.cropHeightBiggerThan1=this.outputShape[1]>1,this.cropWidthBiggerThan1=this.outputShape[2]>1,this.shaderKey=`cropAndResize_${this.methodId}_${this.cropHeightBiggerThan1}_${this.cropWidthBiggerThan1}`}getUserCode(){let[e,t]=["f32(uniforms.imageShape[1] - 1)","f32(uniforms.imageShape[2] - 1)"],[n,s,r]=this.cropHeightBiggerThan1?[`(${e} / f32(uniforms.outShape[1] - 1))`,"(y2-y1) * height_ratio",`y1*${e} + f32(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${e}`],[a,o,i]=this.cropWidthBiggerThan1?[`(${t} / f32(uniforms.outShape[2] - 1))`,"(x2-x1) * width_ratio",`x1*${t} + f32(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${t}`];return`
|
|
fn writeResult(coords : vec4<i32>, value : f32) {
|
|
if (coordsInBounds4D(coords, uniforms.outShape)) {
|
|
setOutput(coords[0], coords[1], coords[2], coords[3], value);
|
|
}
|
|
}
|
|
${Me()} {
|
|
${He()}
|
|
let height_ratio = f32(${n});
|
|
let width_ratio = f32(${a});
|
|
let coords = getOutputCoords(globalId, index);
|
|
let b = coords[0];
|
|
let y = coords[1];
|
|
let x = coords[2];
|
|
let d = coords[3];
|
|
// get box vals
|
|
let y1 = getBoxes(b, 0);
|
|
let x1 = getBoxes(b, 1);
|
|
let y2 = getBoxes(b, 2);
|
|
let x2 = getBoxes(b, 3);
|
|
// get image in batch index
|
|
let bInd = i32(round(getBoxInd(b)));
|
|
if(bInd < 0 || bInd >= uniforms.outShape[0]) {
|
|
return;
|
|
}
|
|
let height_scale = ${s};
|
|
let width_scale = ${o};
|
|
let in_y = ${r};
|
|
if( in_y < 0.0 || in_y > ${e} ) {
|
|
writeResult(coords, uniforms.extrapolationValue);
|
|
return;
|
|
}
|
|
let in_x = ${i};
|
|
if( in_x < 0.0 || in_x > ${t} ) {
|
|
writeResult(coords, uniforms.extrapolationValue);
|
|
return;
|
|
}
|
|
let sourceFracIndexCR = vec2<f32>(in_x,in_y);
|
|
if(${this.methodId} == 1) {
|
|
// Compute the four integer indices.
|
|
let sourceFloorCR = vec2<i32>(sourceFracIndexCR);
|
|
let sourceCeilCR = vec2<i32>(ceil(sourceFracIndexCR));
|
|
let topLeft = getImage(bInd, sourceFloorCR.y, sourceFloorCR.x, d);
|
|
let bottomLeft = getImage(bInd, sourceCeilCR.y, sourceFloorCR.x, d);
|
|
let topRight = getImage(bInd, sourceFloorCR.y, sourceCeilCR.x, d);
|
|
let bottomRight = getImage(bInd, sourceCeilCR.y, sourceCeilCR.x, d);
|
|
let fracCR = sourceFracIndexCR - vec2<f32>(sourceFloorCR);
|
|
let top = topLeft + (topRight - topLeft) * fracCR.x;
|
|
let bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
|
|
let newValue = top + (bottom - top) * fracCR.y;
|
|
writeResult(coords, newValue);
|
|
} else {
|
|
// Compute the coordinators of nearest neighbor point.
|
|
let sourceNearestCR = vec2<i32>(floor(
|
|
sourceFracIndexCR + vec2<f32>(0.5,0.5)));
|
|
let newValue = getImage(
|
|
bInd, sourceNearestCR.y, sourceNearestCR.x, d);
|
|
writeResult(coords,newValue);
|
|
}
|
|
}
|
|
`}},dhe=e=>{let{inputs:t,backend:n,attrs:s}=e,{image:r,boxes:a,boxInd:o}=t,{cropSize:i,method:l,extrapolationValue:c}=s,u=new che(r.shape[3],a.shape,i,l),d=[{type:"float32",data:[c]}];return n.runWebGPUProgram(u,[r,a,o],"float32",d)},phe={kernelName:oi,backendName:"webgpu",kernelFunc:dhe},hhe=class{constructor(e,t){this.variableNames=["x"],this.workGroupSize=[64,1,1],this.uniforms="blockSize : i32;",this.outputShape=e,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`depthToSpace_${t}`,this.size=v.sizeFromShape(this.outputShape),this.dataFormat=t}getUserCode(){return`
|
|
${Me()} {
|
|
${He()}
|
|
if (index < uniforms.size) {
|
|
let coords = getOutputCoords(globalId, index);
|
|
let b = coords[0];
|
|
let h = ${this.getHeightCoordString()};
|
|
let w = ${this.getWidthCoordString()};
|
|
let d = ${this.getDepthCoordString()};
|
|
|
|
let in_h = h / uniforms.blockSize;
|
|
let offset_h = h % uniforms.blockSize;
|
|
let in_w = w / uniforms.blockSize;
|
|
let offset_w = w % uniforms.blockSize;
|
|
let offset_d = (offset_h * uniforms.blockSize + offset_w) *
|
|
${this.getOutputDepthSize()};
|
|
let in_d = d + offset_d;
|
|
|
|
let rlt = ${this.getInputSamplingString()};
|
|
setOutputFlat(index, rlt);
|
|
}
|
|
}`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?"uniforms.outShape[3]":"uniforms.outShape[1]"}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}};function fhe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockSize:a,dataFormat:o}=s,i=r.shape[0],l=o==="NHWC"?r.shape[1]:r.shape[2],c=o==="NHWC"?r.shape[2]:r.shape[3],u=o==="NHWC"?r.shape[3]:r.shape[1],d=l*a,p=c*a,h=u/(a*a),f=o==="NHWC"?[i,d,p,h]:[i,h,d,p],m=[{type:"int32",data:[a]}],g=new hhe(f,o);return n.runWebGPUProgram(g,[r],r.dtype,m)}var mhe={kernelName:ii,backendName:"webgpu",kernelFunc:fhe},GC=class{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.uniforms="pad : vec2<i32>; stride : vec2<i32>; dilation : vec2<i32>; inDims : vec2<i32>;",this.workGroupSize=[4,4,4],this.isVec4=!0,this.outputShape=e.outShape,this.dispatchLayout={x:[0,1],y:[2],z:[3]},this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[1,4,4]),v.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivation=s,this.shaderKey=`depthwise3x3_${n}`}getUserCode(){let e="",t="";if(this.activation){let r=Lo(this.activation,this.isVec4);this.hasPreluActivation?e=`fn activation(a : vec4<f32>, globalId : vec3<u32>, globalIndex : i32) -> vec4<f32> {
|
|
let b = getPreluActivationWeightsAtOutCoordsByGlobalId(globalId, globalIndex);
|
|
${r}
|
|
}`:e=`
|
|
fn activation(a : vec4<f32>, globalId : vec3<u32>, globalIndex : i32) -> vec4<f32> {
|
|
${r}
|
|
}
|
|
`,t="dotProd[i] = activation(dotProd[i], globalId, index);"}let n=this.addBias?"dotProd[i] = dotProd[i] + getBiasAtOutCoordsByCoords(coords);":"";return`
|
|
${e}
|
|
|
|
${Me()} {
|
|
${He()}
|
|
let batch = 0;
|
|
let r = i32(globalId.x);
|
|
let c = i32(globalId.y) * 4;
|
|
let d2 = i32(globalId.z) * 4;
|
|
let xRCCorner = vec2<i32>(r, c) * uniforms.stride - uniforms.pad;
|
|
let d1 = d2;
|
|
let q = 0;
|
|
|
|
let xRCorner = xRCCorner.x;
|
|
let xCCorner = xRCCorner.y;
|
|
|
|
var wVals : array<vec4<f32>, 9>;
|
|
wVals[0] = getW(0, 0, d1, q);
|
|
wVals[1] = getW(0, 1, d1, q);
|
|
wVals[2] = getW(0, 2, d1, q);
|
|
wVals[3] = getW(1, 0, d1, q);
|
|
wVals[4] = getW(1, 1, d1, q);
|
|
wVals[5] = getW(1, 2, d1, q);
|
|
wVals[6] = getW(2, 0, d1, q);
|
|
wVals[7] = getW(2, 1, d1, q);
|
|
wVals[8] = getW(2, 2, d1, q);
|
|
|
|
var xVals : array<array<vec4<f32>, 6>, 3>;
|
|
for (var wR = 0; wR < 3; wR = wR + 1) {
|
|
let xR = xRCorner + wR * uniforms.dilation[0];
|
|
for (var wC = 0; wC < 6; wC = wC + 1) {
|
|
let xC = xCCorner + wC * uniforms.dilation[1];
|
|
if (xR < 0 || xR >= uniforms.inDims[0] || xC < 0 || xC >= uniforms.inDims[1]) {
|
|
xVals[wR][wC] = vec4<f32>(0.0);
|
|
} else {
|
|
xVals[wR][wC] = getX(batch, xR, xC, d1);
|
|
}
|
|
}
|
|
}
|
|
|
|
var dotProd : array<vec4<f32>, 4>;
|
|
dotProd[0] = vec4<f32>(0.0);
|
|
dotProd[1] = vec4<f32>(0.0);
|
|
dotProd[2] = vec4<f32>(0.0);
|
|
dotProd[3] = vec4<f32>(0.0);
|
|
|
|
for (var wR = 0; wR < 3; wR = wR + 1) {
|
|
for (var wC = 0; wC < 3; wC = wC + 1) {
|
|
let indexW = wR * 3 + wC;
|
|
dotProd[0] = dotProd[0] + xVals[wR][0 + wC] * wVals[indexW];
|
|
dotProd[1] = dotProd[1] + xVals[wR][1 + wC] * wVals[indexW];
|
|
dotProd[2] = dotProd[2] + xVals[wR][2 + wC] * wVals[indexW];
|
|
dotProd[3] = dotProd[3] + xVals[wR][3 + wC] * wVals[indexW];
|
|
}
|
|
}
|
|
|
|
for (var i = 0; i < 4; i = i + 1) {
|
|
let coords = vec4<i32>(batch, r, c + i, d2);
|
|
if (coordsInBounds4D(coords, uniforms.outShape)) {
|
|
${n}
|
|
${t}
|
|
setOutput(coords[0], coords[1], coords[2], coords[3], dotProd[i]);
|
|
}
|
|
}
|
|
}
|
|
`}},HC=class{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.uniforms="pad : vec2<i32>; stride : vec2<i32>; dilation : vec2<i32>; inDims : vec2<i32>;",this.workGroupSize=[256,1,1],this.outputShape=e.outShape,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),v.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivation=s,this.shaderKey=`depthwise_${this.convInfo.filterHeight}_${this.convInfo.filterWidth}_${this.activation}_${this.convInfo.outChannels/this.convInfo.inChannels}`}getUserCode(){let e=this.convInfo.outChannels/this.convInfo.inChannels,t="",n="";if(this.activation){let a=Lo(this.activation,!1);this.hasPreluActivation?t=`fn activation(a : f32, globalId : vec3<u32>, index : i32) -> f32 {
|
|
let b = getPreluActivationWeightsAtOutCoordsByGlobalId(globalId, index);
|
|
${a}
|
|
}`:t=`
|
|
fn activation(a : f32, globalId : vec3<u32>, index : i32) -> f32 {
|
|
${a}
|
|
}
|
|
`,n="dotProd = activation(dotProd, globalId, index);"}let s=this.addBias?"dotProd = dotProd + getBiasAtOutCoordsByGlobalId(globalId, index);":"";return`
|
|
${t}
|
|
|
|
fn writeResult(batch : i32, row : i32, col : i32, chan : i32, value : f32) {
|
|
let coord = vec4<i32>(batch, row, col, chan);
|
|
if (coordsInBounds4D(coord, uniforms.outShape)) {
|
|
setOutput(batch, row, col, chan, value);
|
|
}
|
|
}
|
|
|
|
${Me()} {
|
|
${He()}
|
|
let coords = getOutputCoords(globalId, index);
|
|
let batch = coords[0];
|
|
let xRCCorner = vec2<i32>(coords.yz) * uniforms.stride - uniforms.pad;
|
|
let d2 = coords[3];
|
|
let d1 = d2 / ${e};
|
|
let q = d2 - d1 * ${e};
|
|
|
|
let inputRowStart = xRCCorner.x;
|
|
let inputColStart = xRCCorner.y;
|
|
let inputRowEnd = inputRowStart + ${this.convInfo.filterHeight} * uniforms.dilation[0];
|
|
let inputColEnd = inputColStart + ${this.convInfo.filterWidth} * uniforms.dilation[1];
|
|
|
|
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
var dotProd = 0.0;
|
|
|
|
// Extract if checking out of for loop for performance.
|
|
if (inputRowStart >= 0 && inputColStart >= 0 &&
|
|
inputRowEnd < uniforms.inDims[0] && inputColEnd < uniforms.inDims[1]) {
|
|
// Here using a constant value |this.convInfo.filterHeight| instead
|
|
// of uniform value is in order to loop unrolling.
|
|
for (var wR = 0; wR < ${this.convInfo.filterHeight}; wR = wR + 1) {
|
|
let xR = inputRowStart + wR * uniforms.dilation[0];
|
|
|
|
for (var wC = 0; wC < ${this.convInfo.filterWidth}; wC = wC + 1) {
|
|
let xC = inputColStart + wC * uniforms.dilation[1];
|
|
|
|
let xVal = getX(batch, xR, xC, d1);
|
|
let wVal = getW(wR, wC, d1, q);
|
|
dotProd = dotProd + xVal * wVal;
|
|
}
|
|
}
|
|
} else {
|
|
for (var wR = 0; wR < ${this.convInfo.filterHeight}; wR = wR + 1) {
|
|
let xR = inputRowStart + wR * uniforms.dilation[0];
|
|
|
|
if (xR < 0 || xR >= uniforms.inDims[0]) {
|
|
continue;
|
|
}
|
|
|
|
for (var wC = 0; wC < ${this.convInfo.filterWidth}; wC = wC + 1) {
|
|
let xC = inputColStart + wC * uniforms.dilation[1];
|
|
|
|
if (xC < 0 || xC >= uniforms.inDims[1]) {
|
|
continue;
|
|
}
|
|
|
|
let xVal = getX(batch, xR, xC, d1);
|
|
let wVal = getW(wR, wC, d1, q);
|
|
dotProd = dotProd + xVal * wVal;
|
|
}
|
|
}
|
|
}
|
|
|
|
${s}
|
|
${n}
|
|
writeResult(batch, coords[1], coords[2], d2, dotProd);
|
|
}
|
|
`}};function ghe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dilations:l,dimRoundingMode:c}=s,u=l;u==null&&(u=[1,1]);let d=E.computeConv2DInfo(r.shape,a.shape,o,u,i,c,!0),p;d.batchSize===1&&d.inHeight===d.outHeight&&d.inWidth===d.outWidth&&d.strideHeight===1&&d.strideWidth===1&&d.filterHeight===d.filterWidth&&d.inChannels===d.outChannels&&d.filterHeight===3&&d.inChannels%4==0?p=new GC(d):p=new HC(d);let h=[{type:"int32",data:[d.padInfo.top,d.padInfo.left]},{type:"int32",data:[d.strideHeight,d.strideWidth]},{type:"int32",data:[d.dilationHeight,d.dilationWidth]},{type:"int32",data:[d.inHeight,d.inWidth]}];return n.runWebGPUProgram(p,[r,a],r.dtype,h)}var yhe={kernelName:Da,backendName:"webgpu",kernelFunc:ghe},jC=Xn({opSnippet:je.MUL,cpuKernelImpl:tpe,supportsComplex:!0}),Ahe={kernelName:Ka,backendName:"webgpu",kernelFunc:jC},xhe=class{constructor(e,t,n){this.variableNames=["x"],this.uniforms="reduceSize : i32;",this.inputShape=[e.batchSize,e.inSize];let[s]=E.computeOutAndReduceShapes(this.inputShape,[1]);this.outputShape=s.length===0?[1]:s,this.reductionFactor=2;let r=256,a=Math.min(Math.ceil(e.inSize/this.reductionFactor),r);this.workGroupSize=[a,1,1],this.dispatchLayout={x:[],y:this.outputShape.map((o,i)=>i)},this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.reduceType=t,this.shaderKey=`reduce_${t}_${n}`}getUserCode(){let e=this.workGroupSize[0]>1,t="",n="0.0";this.reduceType==="min"||this.reduceType==="max"?(t=`
|
|
if (isNanCustom(candidate)) {
|
|
bestValue = uniforms.NAN;
|
|
} elseif (candidate ${this.reduceType==="min"?"<":">"}
|
|
bestValue)
|
|
{ bestValue = candidate; }`,n="f32(x.numbers[offset])"):this.reduceType==="sum"||this.reduceType==="mean"?t=" bestValue = bestValue + candidate; ":this.reduceType==="prod"&&(t=" bestValue = bestValue * candidate; ",n="1.0");let s=this.reduceType==="mean"?"setOutputFlat(flatOutputIndex, bestValue / f32(uniforms.reduceSize));":"setOutputFlat(flatOutputIndex, bestValue);",r=`
|
|
var<workgroup> xBestValues : array<f32, ${this.workGroupSize[0]}>;
|
|
`,a=`
|
|
xBestValues[localId.x] = bestValue;
|
|
${this.reduceType==="sum"||this.reduceType==="mean"||this.reduceType==="prod"?`bestValue = ${n};`:" "}
|
|
var currentSize = WorkGroupSize;
|
|
for(; currentSize > 1;) {
|
|
workgroupBarrier();
|
|
for (var w = 0; w < ${this.reductionFactor}; w = w + 1) {
|
|
let i = i32(localId.x) * ${this.reductionFactor} + w;
|
|
if (i < currentSize) {
|
|
let candidate = xBestValues[i];
|
|
${t}
|
|
}
|
|
}
|
|
workgroupBarrier();
|
|
xBestValues[localId.x] = bestValue;
|
|
currentSize = DIV_CEIL(currentSize, ${this.reductionFactor});
|
|
${this.reduceType==="sum"||this.reduceType==="mean"||this.reduceType==="prod"?`if(currentSize > 1) { bestValue = ${n}; }`:""}
|
|
}
|
|
if (localId.x == 0u) {
|
|
${s}
|
|
}
|
|
`;return`
|
|
fn DIV_CEIL(a : i32, b : i32) -> i32 {
|
|
return ((a - 1) / b + 1);
|
|
}
|
|
let WorkGroupSize = ${this.workGroupSize[0]};
|
|
${e?r:""}
|
|
fn getOffset(globalId : vec3<u32>, index : i32) -> i32 {
|
|
let outputCoords = getOutputCoords(globalId, index);
|
|
let offset = ${this.outputShape.length===1?"outputCoords":"outputCoords[0]"} * uniforms.reduceSize;
|
|
return offset;
|
|
}
|
|
${Me()} {
|
|
${He()}
|
|
let offset= getOffset(globalId, index);
|
|
var bestValue = ${n};
|
|
let Length = uniforms.reduceSize;
|
|
let WorkPerThread = DIV_CEIL(Length, WorkGroupSize);
|
|
for (var w = 0; w < WorkPerThread; w = w + 1) {
|
|
let i = i32(globalId.x) * WorkPerThread + w;
|
|
if (i < Length) {
|
|
let candidate = f32(x.numbers[offset + i]);
|
|
${t}
|
|
}
|
|
}
|
|
let flatOutputIndex = i32(globalId.y);
|
|
${e?a:s}
|
|
}
|
|
`}};function Sp(e,t,n,s,r){let a=e.shape.length,o=[],i=v.parseAxisParam(t,e.shape),l=i,c=E.getAxesPermutation(l,a),u=e;c!=null&&(u=Il({inputs:{x:e},attrs:{perm:c},backend:r}),l=E.getInnerMostAxes(l.length,a),o.push(u)),E.assertAxesAreInnerMostDims(s,l,a);let[d,p]=E.computeOutAndReduceShapes(u.shape,l),h=d;n&&(h=E.expandShapeToKeepDim(d,i));let f;if((s==="max"||s==="prod")&&r.shouldExecuteOnCPU([u])){let m=r.tensorMap.get(u.dataId).values;switch(s){case"max":let g=Jde(m,v.sizeFromShape(p),h,e.dtype);f=r.makeTensorInfo(h,e.dtype,g);break;case"prod":let{outVals:y,outShape:A,outDtype:x}=rpe(u.shape,u.dtype,m,l);f=r.makeTensorInfo(A,x,y);break;default:throw new Error(`${s} CPU implementation is not yet supported.`)}}else{let m=v.sizeFromShape(p),y=v.sizeFromShape(u.shape)/m,A={windowSize:m,inSize:m,batchSize:y,outSize:1},x=s==="mean"?"float32":fd(e.dtype),b=[{type:"int32",data:[m]}],w=new xhe(A,s,x),k=r.runWebGPUProgram(w,[u],x,b);o.push(k),f=nt({inputs:{x:k},attrs:{shape:h},backend:r})}return o.forEach(m=>r.disposeData(m.dataId)),f}function Mx(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;return Sp(r,a,o,"sum",n)}var bhe={kernelName:oo,backendName:"webgpu",kernelFunc:Mx};function vhe(e){let{inputs:t,backend:n,attrs:s}=e,{equation:r}=s,a=t,{allDims:o,summedDims:i,idDims:l}=E.decodeEinsumEquation(r,a.length);E.checkEinsumDimSizes(o.length,l,a);let{path:c,steps:u}=E.getEinsumComputePath(i,l),d=u.length,p=null,h=o.length,f=[];for(let m=0;m<d;++m){for(let g of u[m]){let{permutationIndices:y,expandDims:A}=E.getEinsumPermutation(h,l[g]),x;E.isIdentityPermutation(y)?x=a[g]:(x=Il({inputs:{x:a[g]},backend:n,attrs:{perm:y}}),f.push(x));let b=x.shape.slice();for(let w=0;w<A.length;++w)b.splice(A[w],0,1);v.arraysEqual(x.shape,b)||(x=nt({inputs:{x},backend:n,attrs:{shape:b}}),f.push(x)),p===null?p=x:(p=jC({inputs:{a:x,b:p},backend:n}),f.push(p))}m<d-1&&(c[m]>=0&&(p=Mx({inputs:{x:p},backend:n,attrs:{axis:c[m]-(o.length-h),keepDims:!1}}),f.push(p)),h--)}for(let m of f)m!==p&&n.disposeData(m.dataId);return p}var whe={kernelName:Zc,backendName:"webgpu",kernelFunc:vhe},khe=$n({opType:Fe.ELU}),Ihe={kernelName:Pa,backendName:"webgpu",kernelFunc:khe},She=Xn({opSnippet:je.EQUAL,dtype:"bool",cpuKernelImpl:Wde}),Che={kernelName:li,backendName:"webgpu",kernelFunc:She},qC=$n({opType:Fe.EXP,cpuKernelImpl:Vde,dtype:"float32"}),The={kernelName:Fa,backendName:"webgpu",kernelFunc:qC};function zx(e){let{inputs:t,attrs:n,backend:s}=e,{dim:r}=n,{input:a}=t,o=a.shape.length,i=a.shape.slice(),l=r;return r<0&&(v.assert(-(o+1)<=r,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+r+1),i.splice(l,0,1),nt({inputs:{x:a},backend:s,attrs:{shape:i}})}var Nhe={kernelName:ui,backendName:"webgpu",kernelFunc:zx},Ehe=$n({opType:Fe.EXPM1,cpuKernelImpl:Ude}),Rhe={kernelName:ci,backendName:"webgpu",kernelFunc:Ehe},$he=class{constructor(e){this.variableNames=[],this.outputShape=[],this.uniforms="value : f32;",this.workPerThread=4,this.workGroupSize=[16,1,1],this.outputShape=e,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.shaderKey="fill",this.size=v.sizeFromShape(this.outputShape)}getUserCode(){return`
|
|
${Me()} {
|
|
${He()}
|
|
for (var i = 0; i < ${this.workPerThread}; i = i + 1) {
|
|
let flatIndex = index * ${this.workPerThread} + i;
|
|
if (flatIndex < uniforms.size) {
|
|
setOutputFlat(flatIndex, uniforms.value);
|
|
}
|
|
}
|
|
}
|
|
`}};function n0(e){let{backend:t,attrs:n}=e,{shape:s,value:r}=n,{dtype:a}=n;if(a=a||v.inferDtype(r),a==="string"){let o=v.getArrayFromDType(a,v.sizeFromShape(s));return o.fill(r),t.makeTensorInfo(s,a,o)}else{let o=new $he(s),i=[{type:"float32",data:[r]}];return t.runWebGPUProgram(o,[],a,i)}}var Dhe={kernelName:ru,backendName:"webgpu",kernelFunc:n0},_he=class{constructor(e){this.outputShape=[],this.variableNames=["x"],this.workGroupSize=[64,1,1],this.outputShape=e,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="flipLeftRight",this.size=v.sizeFromShape(this.outputShape)}getUserCode(){return`
|
|
${Me()} {
|
|
${He()}
|
|
|
|
if (index < uniforms.size) {
|
|
let coords = getOutputCoords(globalId, index);
|
|
let coordX = uniforms.xShape[2] - coords[2] - 1;
|
|
let outputValue = getX(coords[0], coords[1], coordX, coords[3]);
|
|
setOutputFlat(index, outputValue);
|
|
}
|
|
}
|
|
`}},Phe={kernelName:di,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,s=t,r=new _he(n.shape);return s.runWebGPUProgram(r,[n],n.dtype)}},Fhe=$n({opType:Fe.FLOOR,cpuKernelImpl:Gde}),Ohe={kernelName:Oa,backendName:"webgpu",kernelFunc:Fhe},Mhe=Xn({opSnippet:je.INT_DIV,dtype:"int32"}),zhe={kernelName:Ma,backendName:"webgpu",kernelFunc:Mhe},Lhe=(e,t,n,s,r)=>{let a=[s,...n];return r&&a.push(r),e.createBindGroup({layout:t,entries:a.map((o,i)=>({binding:i,resource:o}))})},XC=(e,t,n,s,r,a=!1)=>{let o={dtype:r.dtype,shape:r.shape},i=bce(s,o,t,a),l=e.createShaderModule({code:i});return e.createComputePipeline({layout:n,compute:{module:l,entryPoint:"main"}})};function KC(e,t,n,s="",r=""){return(e.workGroupSize?e.workGroupSize.join(","):"")+t.map(o=>o.length).join(",")+n.join(",")+e.variableNames.join(",")+s+r+e.shaderKey}function ZC(e){let{externalImage:t,backend:n,attrs:s,outShape:r,useImport:a}=e,{numChannels:o}=s,i=v.sizeFromShape(r),l=v.computeStrides(r),c=n.makeTensorInfo(r,"int32"),u=n.getFromPixelsProgram(a?"import":"copyExternal");u.updateOutputShape(r);let d=[c.shape],p=[c.dtype,a?"import":"copyExternal"],h=KC(u,d,p),f=u.getLayout(n.device),m=n.getAndSavePipeline(h,()=>XC(n.device,u,f.pipelineLayout,[],c,!0));u.setPipeline(m),a||n.queue.copyExternalImageToTexture({source:t,origin:{x:0,y:0}},{texture:u.makeInputTexture(n.device,r[1],r[0])},[r[1],r[0]]);let g=n.tensorMap.get(c.dataId);g.bufferInfo.buffer=n.acquireBuffer(g.bufferInfo.byteSize);let y=[i,o,...l,...u.dispatch];u.setUniform(n.device,y);let A;if(a){let x={source:t};A=n.device.importExternalTexture(x)}else A=u.inputTexture.createView();return n.runFromPixelsProgram(u,g.bufferInfo.buffer,f,A,c.dataId),c}var Bhe={kernelName:ad,backendName:"webgpu",kernelFunc:Whe},gc;function Whe(e){let{inputs:t,backend:n,attrs:s}=e,{pixels:r}=t,{numChannels:a}=s;if(r==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let o=typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement,l=typeof HTMLCanvasElement!="undefined"&&r instanceof HTMLCanvasElement,c=typeof ImageBitmap!="undefined"&&r instanceof ImageBitmap,[u,d]=o?[r.videoWidth,r.videoHeight]:[r.width,r.height],p=[d,u,a];if(Z().getBool("WEBGPU_USE_IMPORT")&&o)return ZC({externalImage:r,backend:n,attrs:s,outShape:p,useImport:!0});if((o||i)&&(gc==null&&(gc=document.createElement("canvas").getContext("2d")),gc.canvas.width=u,gc.canvas.height=d,gc.drawImage(r,0,0,u,d),r=gc.canvas),c||l||o||i)return ZC({externalImage:r,backend:n,attrs:s,outShape:p,useImport:!1});let h=r.data,f=h;if(a!=null&&a!==4){f=new Uint8Array(r.width*r.height*a);let y=h.length,A=0;for(let x=0;x<y;x++)x%4<a&&(f[A++]=h[x])}let m=n.makeTensorInfo(p,"int32"),g=n.tensorMap.get(m.dataId);return g.values=new Int32Array(f),n.maybeReleaseBuffer(m.dataId),n.uploadToGPU(m.dataId),m}var Vhe=class{constructor(e,t,n,s,r){this.uniforms="varianceEpsilon : f32;",this.workGroupSize=[128,1,1],this.variableNames=["x","mean","variance"],E.assertAndGetBroadcastShape(e,t),E.assertAndGetBroadcastShape(e,n),this.outputShape=e,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),s!=null&&(E.assertAndGetBroadcastShape(e,s),this.variableNames.push("offset")),r!=null&&(E.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale")),this.offsetShape=s,this.scaleShape=r,this.shaderKey="batchNorm"}getUserCode(){let e="0.0";this.offsetShape!=null&&(e="getOffsetAtOutCoordsByGlobalId(globalId, index)");let t="1.0";this.scaleShape!=null&&(t="getScaleAtOutCoordsByGlobalId(globalId, index)");let n=this.outputShape.length,s=ln(n),r="setOutput(coords[0], coords[1], coords[2], coords[3], value);";return n===2&&(r="setOutput(coords[0], coords[1], value);"),n===3&&(r="setOutput(coords[0], coords[1], coords[2], value);"),`
|
|
fn writeResult(coords : ${s}, value : f32) {
|
|
if (coordsInBounds${n}D(coords, uniforms.outShape)) {
|
|
${r}
|
|
}
|
|
}
|
|
${Me()} {
|
|
${He()}
|
|
let coords = getOutputCoords(globalId, index);
|
|
let xValue = getXAtOutCoordsByGlobalId(globalId, index);
|
|
let meanValue = getMeanAtOutCoordsByGlobalId(globalId, index);
|
|
let varianValue = getVarianceAtOutCoordsByGlobalId(globalId, index);
|
|
let offsetValue = ${e};
|
|
let scaleValue = ${t};
|
|
let inv = scaleValue * inverseSqrt(varianValue + f32(uniforms.varianceEpsilon));
|
|
writeResult(coords,dot(vec3<f32>(xValue, -meanValue, offsetValue), vec3<f32>(inv, inv, 1.0)));
|
|
}
|
|
`}},Uhe={kernelName:za,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:s,scale:r,offset:a,mean:o,variance:i}=e,{varianceEpsilon:l}=t,c=n,u=[s,o,i],d=null;a!=null&&(d=a.shape,u.push(a));let p=null;r!=null&&(p=r.shape,u.push(r));let h=new Vhe(s.shape,o.shape,i.shape,d,p),f=[{type:"float32",data:[l]}];return c.runWebGPUProgram(h,u,s.dtype,f)}};function Ghe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=s,m=E.convertConv2DDataFormat(u),g=E.computeConv2DInfo(r.shape,a.shape,l,d,c,p,!1,m),y=o!=null,A=i!=null,x;if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))return BC({x:r,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});let b=Z().getBool("WEBGPU_USE_NAIVE_CONV2D"),w=g.inChannels%4==0&&g.outChannels%4==0,k=[g.padInfo.top,g.padInfo.left],S=[{type:"int32",data:[g.filterHeight,g.filterWidth]},{type:"int32",data:[...k]},{type:"int32",data:[g.strideHeight,g.strideWidth]},{type:"int32",data:[g.dilationHeight,g.dilationWidth]}];if(b)x=new UC(g,y,h,A);else{w?x=new WC(g,y,h,A):x=new VC(g,y,h,A);let $=g.outShape[1]*g.outShape[2],F=g.outShape[3],R=g.filterHeight*g.filterWidth*g.inShape[3];S.push({type:"int32",data:[$]},{type:"int32",data:[F]},{type:"int32",data:[R]})}let N=[r,a];return y&&N.push(o),A&&N.push(i),n.runWebGPUProgram(x,N,r.dtype,S)}var Hhe={kernelName:mo,backendName:"webgpu",kernelFunc:Ghe};function jhe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dilations:u,dimRoundingMode:d,activation:p}=s,h=u;h==null&&(h=[1,1]),v.assert(E.eitherStridesOrDilationsAreOne(l,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${h}'`);let f=E.computeConv2DInfo(r.shape,a.shape,l,h,c,d,!0),m=[r,a],g=o!=null,y=i!=null;g&&m.push(o),y&&m.push(i);let A;f.batchSize===1&&f.inHeight===f.outHeight&&f.inWidth===f.outWidth&&f.strideHeight===1&&f.strideWidth===1&&f.filterHeight===f.filterWidth&&f.inChannels===f.outChannels&&f.filterHeight===3&&f.inChannels%4==0?A=new GC(f,g,p,y):A=new HC(f,g,p,y);let x=[{type:"int32",data:[f.padInfo.top,f.padInfo.left]},{type:"int32",data:[f.strideHeight,f.strideWidth]},{type:"int32",data:[f.dilationHeight,f.dilationWidth]},{type:"int32",data:[f.inHeight,f.inWidth]}];return n.runWebGPUProgram(A,m,"float32",x)}var qhe={kernelName:go,backendName:"webgpu",kernelFunc:jhe},Xhe=class{constructor(e,t){this.variableNames=["A","indices"],this.workGroupSize=[64,1,1],this.outputShape=t,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`gathernd_${e}`,this.size=v.sizeFromShape(this.outputShape),this.sliceDim=e,this.uniforms=`sliceDim : i32; strides : ${ln(e)};`}getUserCode(){let e;return this.sliceDim>1?e="uniforms.strides[j]":e="uniforms.strides",`
|
|
${Me()} {
|
|
${He()}
|
|
let coords = getOutputCoords(globalId, index);
|
|
var flattenIndex = 0;
|
|
for (var j = 0; j < uniforms.sliceDim; j = j + 1) {
|
|
let indexTemp = i32(round(getIndices(coords[0], j)));
|
|
let strideNum = ${e};
|
|
flattenIndex = flattenIndex + indexTemp * strideNum;
|
|
}
|
|
if (index < uniforms.size) {
|
|
setOutputFlat(index, getA(flattenIndex, coords[1]));
|
|
}
|
|
}
|
|
`}};function Khe(e){let{inputs:t,backend:n}=e,{params:s,indices:r}=t,a=r.shape,o=a[a.length-1],i=v.sizeFromShape(s.shape),[l,c,u,d]=E.prepareAndValidate(s,r),p=nt({inputs:{x:r},backend:n,attrs:{shape:[c,o]}}),h=nt({inputs:{x:s},backend:n,attrs:{shape:[v.sizeFromShape(s.shape)/u,u]}});if(n.shouldExecuteOnCPU([s,r])||s.dtype==="string"){let A=n.readSync(r.dataId),x=n.bufferSync(s),b=Hde(A,x,s.dtype,c,o,u,d,s.shape,i);return n.makeTensorInfo(l,s.dtype,b.values)}let f=new Xhe(o,[c,u]),m=[{type:"int32",data:[o]},{type:"int32",data:d}],g=n.runWebGPUProgram(f,[h,p],h.dtype,m),y=nt({inputs:{x:g},backend:n,attrs:{shape:l}});return n.disposeData(p.dataId),n.disposeData(h.dataId),n.disposeData(g.dataId),y}var Zhe={kernelName:hi,backendName:"webgpu",kernelFunc:Khe},Yhe=class{constructor(e,t){this.variableNames=["A","indices"],this.workGroupSize=[64,1,1],this.outputShape=e.slice(),this.aShape=e,this.outputShape=t,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="gather",this.size=v.sizeFromShape(this.outputShape)}getUserCode(){let e=Jhe(this.aShape,"i32");return`
|
|
${Me()} {
|
|
${He()}
|
|
let resRC = getOutputCoords(globalId, index);
|
|
if (index < uniforms.size) {
|
|
setOutputFlat(index, getA(${e}));
|
|
}
|
|
}
|
|
`}};function Jhe(e,t="int"){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let r=0;r<e.length;r++)r===2?s.push(`${t}(getIndices(resRC.x, resRC.z))`):s.push(`${n[r]}`);return s.join()}function Qhe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,indices:a}=t,{axis:o,batchDims:i}=s,l=v.parseAxisParam(o,r.shape)[0],c=n.readSync(a.dataId),u=r.shape[l];for(let b=0;b<c.length;++b){let w=c[b];v.assert(w<=u-1&&w>=0,()=>`GatherV2: the index value ${w} is not in [0, ${u-1}]`)}let d=E.segment_util.collectGatherOpShapeInfo(r,a,l,i),p=v.sizeFromShape(a.shape),h=[],f=nt({inputs:{x:r},backend:n,attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]}}),m=nt({inputs:{x:a},backend:n,attrs:{shape:[d.batchSize,p/d.batchSize]}});h.push(f),h.push(m);let g=[d.batchSize,d.outerSize,p/d.batchSize,d.sliceSize];if(n.shouldExecuteOnCPU([r,a])){let w=n.tensorMap.get(m.dataId).values,k=We(m.shape,m.dtype,w),N=n.tensorMap.get(f.dataId).values,$=We(f.shape,f.dtype,N),F=jde($,k,g);return h.forEach(R=>n.disposeData(R.dataId)),n.makeTensorInfo(d.outputShape,F.dtype,F.values)}let y=new Yhe(f.shape,g),A=n.runWebGPUProgram(y,[f,m],f.dtype);h.push(A);let x=nt({inputs:{x:A},backend:n,attrs:{shape:d.outputShape}});return h.forEach(b=>n.disposeData(b.dataId)),x}var efe={kernelName:pi,backendName:"webgpu",kernelFunc:Qhe},tfe=Xn({opSnippet:je.GREATER,cpuKernelImpl:Xde,dtype:"bool"}),nfe={kernelName:fi,backendName:"webgpu",kernelFunc:tfe},sfe=Xn({opSnippet:je.GREATER_EQUAL,dtype:"bool",cpuKernelImpl:qde}),rfe={kernelName:La,backendName:"webgpu",kernelFunc:sfe},afe=Xn({opSnippet:je.LESS,dtype:"bool",cpuKernelImpl:Zde}),ofe={kernelName:gi,backendName:"webgpu",kernelFunc:afe},ife=Xn({opSnippet:je.LESS_EQUAL,dtype:"bool",cpuKernelImpl:Kde}),lfe={kernelName:yi,backendName:"webgpu",kernelFunc:ife},ufe=$n({opType:Fe.LOG,cpuKernelImpl:Yde}),cfe={kernelName:Wa,backendName:"webgpu",kernelFunc:ufe},dfe=Xn({opSnippet:je.LOGICAL_AND,dtype:"bool"}),pfe={kernelName:Ai,backendName:"webgpu",kernelFunc:dfe},hfe=$n({opType:Fe.LOGICAL_NOT}),ffe={kernelName:uu,backendName:"webgpu",kernelFunc:hfe};function YC(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reductionIndices:a,keepDims:o}=s;return Sp(r,a,o,"max",n)}var mfe={kernelName:Va,backendName:"webgpu",kernelFunc:YC},gfe=Xn({opSnippet:je.MAX,cpuKernelImpl:Qde}),yfe={kernelName:Ua,backendName:"webgpu",kernelFunc:gfe};function Afe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,c=1,u=E.computePool2DInfo(r.shape,a,o,c,i,l),d,p=[];if(u.filterHeight===1&&u.filterWidth===1){if(v.arraysEqual(u.inShape,u.outShape))return tr({inputs:{x:r},backend:n});d=new MC(u),p.push({type:"int32",data:[u.strideHeight,u.strideWidth]})}else d=new OC(u,"max"),p.push({type:"int32",data:[u.strideHeight,u.strideWidth]},{type:"int32",data:[u.padInfo.top,u.padInfo.left]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]},{type:"int32",data:[u.inHeight,u.inWidth]},{type:"int32",data:[u.effectiveFilterHeight,u.effectiveFilterWidth]});return n.runWebGPUProgram(d,[r],r.dtype,p)}var xfe={kernelName:Ga,backendName:"webgpu",kernelFunc:Afe};function bfe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{keepDims:a,axis:o}=s;return Sp(r,o,a,"mean",n)}var vfe={kernelName:Ha,backendName:"webgpu",kernelFunc:bfe};function wfe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;return Sp(r,a,o,"min",n)}var kfe={kernelName:ja,backendName:"webgpu",kernelFunc:wfe},Ife=Xn({opSnippet:je.MIN,cpuKernelImpl:epe}),Sfe={kernelName:qa,backendName:"webgpu",kernelFunc:Ife},Cfe=class{constructor(e,t,n){this.uniforms="",this.variableNames=["x"],this.workGroupSize=[64,1,1],this.outputShape=t.map((s,r)=>s[0]+e[r]+s[1]),this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.xShape=e,t.map((s,r)=>{this.uniforms+=` pad${r} : vec2<i32>;`}),this.offset=n==="reflect"?0:1,this.shaderKey=`mirrorPad_${n}`,this.size=v.sizeFromShape(this.outputShape)}getUserCode(){let e=this.xShape.length,t=this.xShape.map((l,c)=>`uniforms.pad${c}[0]`).join(","),n=this.xShape.map((l,c)=>`uniforms.pad${c}[0] + uniforms.xShape${e>1?`[${c}]`:""}`).join(","),s=e===1?"start":"start[i]",r=e===1?"end":"end[i]",a=e===1?"outC":"outC[i]",o=ln(e),i=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return`
|
|
${Me()} {
|
|
${He()}
|
|
let start = ${o}(${t});
|
|
let end = ${o}(${n});
|
|
var outC = getOutputCoords(globalId, index);
|
|
if (index < uniforms.size) {
|
|
for (var i = 0; i < ${e}; i = i + 1) {
|
|
if (${a} < ${s}) {
|
|
${a} = ${s} * 2 - ${a} - ${this.offset};
|
|
} elseif(${a} >= ${r}) {
|
|
${a} = (${r} - 1) * 2 - ${a} + ${this.offset};
|
|
}
|
|
}
|
|
let coords = outC - start;
|
|
setOutputFlat(index, getX(${i}));
|
|
}
|
|
}
|
|
`}},Tfe={kernelName:Xa,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:s}=e,{paddings:r,mode:a}=t,o=n,i=r.map(u=>({type:"int32",data:[u[0],u[1]]})),l=new Cfe(s.shape,r,a);return o.runWebGPUProgram(l,[s],s.dtype,i)}};function Nfe(e){let{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])){let a=n.tensorMap.get(s.dataId),[o,i]=npe(a.values,s.shape,s.dtype);return n.makeTensorInfo(i,s.dtype,o)}let r=new e0(s.shape,Fe.NEG);return n.runWebGPUProgram(r,[s],s.dtype)}var Efe={kernelName:xi,backendName:"webgpu",kernelFunc:Nfe};function Rfe(e){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l}=s,c=n.readSync(r.dataId),u=n.readSync(a.dataId),{selectedIndices:d}=Zs.nonMaxSuppressionV3Impl(c,u,o,i,l);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}var $fe={kernelName:vi,backendName:"webgpu",kernelFunc:Rfe};function Dfe(e){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l,softNmsSigma:c}=s,u=n.readSync(r.dataId),d=n.readSync(a.dataId),p=o,h=i,f=l,m=c,{selectedIndices:g,selectedScores:y}=Zs.nonMaxSuppressionV5Impl(u,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var _fe={kernelName:wi,backendName:"webgpu",kernelFunc:Dfe};function s0(e){let{inputs:t,backend:n}=e,{x:s}=t;if(s.dtype==="complex64"){let r=Ip({inputs:{input:s},backend:n}),a=s0({inputs:{x:r},backend:n}),o=t0({inputs:{input:s},backend:n}),i=s0({inputs:{x:o},backend:n}),l=mc({inputs:{real:a,imag:i},backend:n});return n.disposeData(r.dataId),n.disposeData(a.dataId),n.disposeData(o.dataId),n.disposeData(i.dataId),l}else return n0({attrs:{shape:s.shape,dtype:s.dtype,value:s.dtype==="string"?"":0},backend:n})}var Pfe={kernelName:Bi,backendName:"webgpu",kernelFunc:s0};function JC(e){let{inputs:t,backend:n}=e,{x:s}=t;if(s.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(s.dtype==="complex64"){let r=Ip({inputs:{input:s},backend:n}),a=JC({inputs:{x:r},backend:n}),o=t0({inputs:{input:s},backend:n}),i=s0({inputs:{x:o},backend:n}),l=mc({inputs:{real:a,imag:i},backend:n});return n.disposeData(r.dataId),n.disposeData(a.dataId),n.disposeData(o.dataId),n.disposeData(i.dataId),l}else return n0({attrs:{shape:s.shape,dtype:s.dtype,value:1},backend:n})}var Ffe={kernelName:ki,backendName:"webgpu",kernelFunc:JC};function Ofe(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(t.length===1)return zx({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let a=t[0].shape,o=t[0].dtype;t.forEach(u=>{v.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),v.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(u=>{let d=zx({inputs:{input:u},backend:n,attrs:{dim:r}});return i.push(d),d}),c=LC({inputs:l,backend:n,attrs:{axis:r}});return i.forEach(u=>n.disposeData(u.dataId)),c}var Mfe={kernelName:Si,backendName:"webgpu",kernelFunc:Ofe},zfe=class{constructor(e,t){this.variableNames=["x"],this.uniforms="constantValue : f32;",this.workGroupSize=[64,1,1],this.outputShape=t.map((n,s)=>n[0]+e[s]+n[1]),this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),t.map((n,s)=>{this.uniforms+=` pad${s} : vec2<i32>;`}),this.xShape=e,this.shaderKey="pad",this.size=v.sizeFromShape(this.outputShape)}getUserCode(){let e=this.xShape.length,t=ln(e),n=this.xShape.map((u,d)=>`uniforms.pad${d}[0]`).join(","),s=this.xShape.map((u,d)=>`uniforms.pad${d}[0] + uniforms.xShape${e>1?`[${d}]`:""}`).join(","),r=e>1?`${t}(${n})`:`${n}`,a=e>1?`${t}(${s})`:`${s}`,o=e>1?"any(outC < start)":"outC < start",i=e>1?"any(outC >= end)":"outC >= end",l=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return`
|
|
${Me()} {
|
|
${He()}
|
|
let start = ${r};
|
|
let end = ${a};
|
|
if (index < uniforms.size) {
|
|
let outC = getOutputCoords(globalId, index);
|
|
|
|
if (${o} || ${i}) {
|
|
setOutputFlat(index, uniforms.constantValue);
|
|
} else {
|
|
let coords = outC - start;
|
|
setOutputFlat(index, getX(${l}));
|
|
}
|
|
}
|
|
}
|
|
`}},QC=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,constantValue:o}=s;if(a.every(c=>v.arraysEqual(c,[0,0])))return tr({inputs:{x:r},backend:n});if(v.sizeFromShape(r.shape)===0){let c=a.map((u,d)=>u[0]+r.shape[d]+u[1]);return n0({backend:n,attrs:{shape:c,value:o,dtype:r.dtype}})}let i=[{type:"float32",data:[o]}];a.map(c=>i.push({type:"int32",data:[c[0],c[1]]}));let l=new zfe(r.shape,a);return n.runWebGPUProgram(l,[r],r.dtype,i)},Lfe={kernelName:Za,backendName:"webgpu",kernelFunc:QC},Bfe=Xn({opSnippet:je.POW}),Wfe={kernelName:Ya,backendName:"webgpu",kernelFunc:Bfe};function Vfe(e){let{inputs:t,backend:n}=e,{x:s,alpha:r}=t,a=new _C(je.PRELU,s.shape,r.shape);return n.runWebGPUProgram(a,[s,r],"float32")}var Ufe={kernelName:Ja,backendName:"webgpu",kernelFunc:Vfe};function Gfe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;return Sp(r,a,o,"prod",n)}var Hfe={kernelName:Ci,backendName:"webgpu",kernelFunc:Gfe},jfe=e=>{let{backend:t,attrs:n}=e,{start:s,stop:r,step:a,dtype:o}=n,i=ape(s,r,a,o);return t.makeTensorInfo([i.length],o,i)},qfe={kernelName:pu,backendName:"webgpu",kernelFunc:jfe},e6=Xn({opSnippet:je.DIV}),Xfe={kernelName:_a,backendName:"webgpu",kernelFunc:e6},Kfe=$n({opType:Fe.RELU}),Zfe={kernelName:Qa,backendName:"webgpu",kernelFunc:Kfe},Yfe=$n({opType:Fe.RELU6}),Jfe={kernelName:to,backendName:"webgpu",kernelFunc:Yfe},Qfe=class{constructor(e,t,n,s,r){this.variableNames=["x"],this.workGroupSize=[64,1,1],this.outputShape=[e[0],t,n,e[3]],this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.alignCorners=s,this.halfPixelCenters=r,this.shaderKey=`resizeBilinear_${s}_${r}_${this.outputShape[1]>1}_${this.outputShape[2]>1}`}getUserCode(){let e=this.alignCorners&&this.outputShape[1]>1,t=this.alignCorners&&this.outputShape[2]>1;return`
|
|
${Me()} {
|
|
${He()}
|
|
let coords = getOutputCoords(globalId, index);
|
|
if (all(coords < uniforms.outShape)) {
|
|
let b = coords[0];
|
|
let d = coords[3];
|
|
let rc = coords.yz;
|
|
|
|
let effectiveInSize = vec2<f32>(
|
|
${e?"f32(uniforms.xShape.y) - 1.0":"f32(uniforms.xShape.y)"},
|
|
${t?"f32(uniforms.xShape.z) - 1.0":"f32(uniforms.xShape.z)"});
|
|
|
|
let effectiveOutSize = vec2<f32>(
|
|
${e?"f32(uniforms.outShape.y) - 1.0":"f32(uniforms.outShape.y)"},
|
|
${t?"f32(uniforms.outShape.z) - 1.0":"f32(uniforms.outShape.z)"});
|
|
|
|
let effectiveInputOverOutputRatioRC =
|
|
effectiveInSize / effectiveOutSize;
|
|
|
|
// Fractional source index
|
|
let sourceFracIndexRC = ${this.halfPixelCenters?"(vec2<f32>(rc) + vec2<f32>(0.5)) * effectiveInputOverOutputRatioRC - vec2<f32>(0.5)":"vec2<f32>(rc) * effectiveInputOverOutputRatioRC"};
|
|
|
|
// Compute the four integer indices.
|
|
let sourceFloorRC = vec2<i32>(sourceFracIndexRC);
|
|
let sourceCeilRC = vec2<i32>(
|
|
min(vec2<f32>(uniforms.xShape.yz) - vec2<f32>(1.0), ceil(sourceFracIndexRC)));
|
|
|
|
let topLeft = getX(b, sourceFloorRC.x, sourceFloorRC.y, d);
|
|
let bottomLeft = getX(b, sourceCeilRC.x, sourceFloorRC.y, d);
|
|
let topRight = getX(b, sourceFloorRC.x, sourceCeilRC.y, d);
|
|
let bottomRight = getX(b, sourceCeilRC.x, sourceCeilRC.y, d);
|
|
|
|
let fracRC = sourceFracIndexRC - vec2<f32>(sourceFloorRC);
|
|
|
|
let top = topLeft + (topRight - topLeft) * fracRC.y;
|
|
let bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
|
|
let newValue = top + (bottom - top) * fracRC.x;
|
|
|
|
setOutput(b, coords[1], coords[2], d, newValue);
|
|
}
|
|
}
|
|
`}};function eme(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,size:o,halfPixelCenters:i}=s,[l,c]=o,u=new Qfe(r.shape,l,c,a,i);return n.runWebGPUProgram(u,[r],"float32")}var tme={kernelName:eo,backendName:"webgpu",kernelFunc:eme},nme=class{constructor(e,t,n,s,r){this.variableNames=["x"],this.workGroupSize=[64,1,1],this.outputShape=[e[0],t,n,e[3]],this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.alignCorners=s,this.halfPixelCenters=r,this.shaderKey=`resizeNearest_${s}_${this.outputShape[1]>1}_${this.outputShape[2]>1}_${r}`}getUserCode(){let e=this.alignCorners?"0.5":"0.0",t;this.halfPixelCenters?t="max((vec2<f32>(rc) + vec2<f32>(0.5)) * effectiveInputOverOutputRatioRC, vec2<f32>(0.0))":t="vec2<f32>(rc) * effectiveInputOverOutputRatioRC";let n=this.alignCorners&&this.outputShape[1]>1,s=this.alignCorners&&this.outputShape[2]>1;return`
|
|
${Me()} {
|
|
${He()}
|
|
let coords = getOutputCoords(globalId, index);
|
|
if (all(coords < uniforms.outShape)) {
|
|
let b = coords[0];
|
|
let d = coords[3];
|
|
let rc = coords.yz;
|
|
|
|
let effectiveInSize = vec2<f32>(
|
|
${n?"f32(uniforms.xShape.y) - 1.0":"f32(uniforms.xShape.y)"},
|
|
${s?"f32(uniforms.xShape.z) - 1.0":"f32(uniforms.xShape.z)"});
|
|
|
|
let effectiveOutSize = vec2<f32>(
|
|
${n?"f32(uniforms.outShape.y) - 1.0":"f32(uniforms.outShape.y)"},
|
|
${s?"f32(uniforms.outShape.z) - 1.0":"f32(uniforms.outShape.z)"});
|
|
|
|
let effectiveInputOverOutputRatioRC =
|
|
effectiveInSize / effectiveOutSize;
|
|
|
|
// Fractional source index
|
|
let sourceFracIndexRC = ${t};
|
|
|
|
// Compute the coordinators of nearest neighbor point.
|
|
let inputShapeRC = vec2<f32>(f32(uniforms.xShape.y), f32(uniforms.xShape.z));
|
|
let sourceNearestRC = vec2<i32>(
|
|
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${e})));
|
|
let newValue = getX(b, sourceNearestRC.x, sourceNearestRC.y, d);
|
|
|
|
setOutput(b, coords[1], coords[2], d, newValue);
|
|
}
|
|
}
|
|
`}};function sme(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:o,size:i}=s,[l,c]=i,u=new nme(r.shape,l,c,a,o);return n.runWebGPUProgram(u,[r],r.dtype)}var rme={kernelName:fu,backendName:"webgpu",kernelFunc:sme},ame=class{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.workGroupSize=[64,1,1],this.outputShape=e,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms=`centerX : f32; centerY : f32; sinRadians : f32;
|
|
cosRadians : f32;`,this.shaderKey="rotate",this.size=v.sizeFromShape(this.outputShape),this.outputShape=e,typeof t=="number"?(this.uniforms+=" fillValue : f32;",this.fillSnippet="var outputValue = uniforms.fillValue;",this.shaderKey+="_float"):(this.uniforms+=" fillValue : vec3<f32>;",this.fillSnippet="var outputValue = uniforms.fillValue[coords[3]];",this.shaderKey+="_vec3")}getUserCode(){return`
|
|
${Me()} {
|
|
${He()}
|
|
|
|
if (index < uniforms.size) {
|
|
let coords = getOutputCoords(globalId, index);
|
|
let coordXFloat = (f32(coords[2]) - uniforms.centerX) *
|
|
uniforms.cosRadians - (f32(coords[1]) - uniforms.centerY) *
|
|
uniforms.sinRadians;
|
|
let coordYFloat = (f32(coords[2]) - uniforms.centerX) *
|
|
uniforms.sinRadians + (f32(coords[1]) - uniforms.centerY) *
|
|
uniforms.cosRadians;
|
|
let coordX = i32(round(coordXFloat + uniforms.centerX));
|
|
let coordY = i32(round(coordYFloat + uniforms.centerY));
|
|
${this.fillSnippet}
|
|
if(coordX >= 0 && coordX < uniforms.xShape[2] && coordY >= 0 &&
|
|
coordY < uniforms.xShape[1]) {
|
|
outputValue = getX(coords[0], coordY, coordX, coords[3]);
|
|
}
|
|
setOutputFlat(index, outputValue);
|
|
}
|
|
}
|
|
`}},ome={kernelName:Wi,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:s}=e,{radians:r,fillValue:a,center:o}=t,i=n,l=new ame(s.shape,a),[c,u]=E.getImageCenter(o,s.shape[1],s.shape[2]),d=[{type:"float32",data:[c]},{type:"float32",data:[u]},{type:"float32",data:[Math.sin(r)]},{type:"float32",data:[Math.cos(r)]}];return typeof a=="number"?d.push({type:"float32",data:[Number.parseFloat(a.toFixed(2))]}):d.push({type:"float32",data:a}),i.runWebGPUProgram(l,[s],s.dtype,d)}},ime=$n({opType:Fe.RSQRT,cpuKernelImpl:ope}),lme={kernelName:no,backendName:"webgpu",kernelFunc:ime},t6=class{constructor(e,t,n,s,r,a,o=!0){this.variableNames=["updates","indices","defaultValue"],this.workGroupSize=[64,1,1],this.workPerThread=4,this.outputShape=a,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]);let i=t>1;this.shaderKey=`scatter_${n}_${s}_${i}`,this.size=v.sizeFromShape(this.outputShape);let l=ln(r.length);this.uniforms=`updateSize : i32; sliceDim : i32; strides: ${l};`;let c="";n===1?c="i":n===2&&(c="i, j"),this.indicesSnippet=`getIndices(${c})`;let u="";s===1?u="i":s===2&&(u="i, coords[1]"),this.updatesSnippet=`getUpdates(${u})`,this.strideString=i?"uniforms.strides[j]":"uniforms.strides"}getUserCode(){return`
|
|
${Me()} {
|
|
${He()}
|
|
|
|
let globalIndex = index * ${this.workPerThread};
|
|
if (globalIndex < uniforms.size) {
|
|
var sum = vec4<f32>(0.0);
|
|
var found = vec4<bool>(false);
|
|
for (var i = 0; i < uniforms.updateSize; i = i + 1) {
|
|
var flattenedIndex = 0;
|
|
for (var j = 0; j < uniforms.sliceDim; j = j + 1) {
|
|
let indexInside = i32(round(${this.indicesSnippet}));
|
|
flattenedIndex = flattenedIndex + indexInside * ${this.strideString};
|
|
}
|
|
for (var innerIndex = 0; innerIndex < ${this.workPerThread}; innerIndex = innerIndex + 1) {
|
|
let curIndex = globalIndex + innerIndex;
|
|
let coords = getCoordsFromFlatIndex(curIndex);
|
|
if (flattenedIndex == coords[0]) {
|
|
sum[innerIndex] = sum[innerIndex] + ${this.updatesSnippet};
|
|
found[innerIndex] = true;
|
|
}
|
|
}
|
|
}
|
|
for (var innerIndex = 0; innerIndex < ${this.workPerThread}; innerIndex = innerIndex + 1) {
|
|
let curIndex = globalIndex + innerIndex;
|
|
if (curIndex < uniforms.size)
|
|
{
|
|
setOutputFlat(curIndex, mix(getDefaultValue(), sum[innerIndex], f32(found[innerIndex])));
|
|
}
|
|
}
|
|
}
|
|
}`}};function ume(e){let{inputs:t,backend:n,attrs:s}=e,{indices:r,updates:a}=t,{shape:o}=s,{sliceRank:i,numUpdates:l,sliceSize:c,strides:u,outputSize:d}=E.calculateShapes(a,r,o),p=[d/c,c];if(d===0)return n.makeTensorInfo(o,r.dtype);let h=nt({inputs:{x:r},backend:n,attrs:{shape:[l,i]}}),f=nt({inputs:{x:a},backend:n,attrs:{shape:[l,c]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0])),g=[{type:"int32",data:[l]},{type:"int32",data:[i]},{type:"int32",data:u}],y=new t6(l,i,h.shape.length,f.shape.length,u,p),A=n.runWebGPUProgram(y,[f,h,m],f.dtype,g),x=nt({inputs:{x:A},backend:n,attrs:{shape:o}});return n.disposeData(h.dataId),n.disposeData(f.dataId),n.disposeData(A.dataId),n.disposeData(m.dataId),x}var cme={kernelName:Ri,backendName:"webgpu",kernelFunc:ume},dme=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.workGroupSize=[64,1,1],this.outputShape=t,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.cRank=e,this.rank=n,this.shaderKey="select",this.size=v.sizeFromShape(this.outputShape)}getUserCode(){let e,t;if(this.rank>4)throw Error(`Where for rank ${this.rank} is not yet supported`);if(this.rank===1)t="resRC",e="resRC";else{let s=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[],a=[];for(let o=0;o<this.outputShape.length;o++)a.push(`${s[o]}`),o<this.cRank&&r.push(`${s[o]}`);e=r.join(),t=a.join()}return`
|
|
${Me()} {
|
|
${He()}
|
|
if (index < uniforms.size) {
|
|
let resRC = getOutputCoords(globalId, index);
|
|
let cVal = getC(${e});
|
|
if (cVal >= 1.0) {
|
|
setOutputFlat(index, getA(${t}));
|
|
} else {
|
|
setOutputFlat(index, getB(${t}));
|
|
}
|
|
}
|
|
}
|
|
`}};function pme(e){let{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t,o=new dme(s.shape.length,r.shape,r.shape.length);return n.runWebGPUProgram(o,[s,r,a],Ln(r.dtype,a.dtype))}var hme={kernelName:$i,backendName:"webgpu",kernelFunc:pme},fme=$n({opType:Fe.SIGMOID}),mme={kernelName:ro,backendName:"webgpu",kernelFunc:fme},gme=$n({opType:Fe.SIN}),yme={kernelName:so,backendName:"webgpu",kernelFunc:gme},Ame=$n({opType:Fe.SINH}),xme={kernelName:_i,backendName:"webgpu",kernelFunc:Ame},n6=Xn({opSnippet:je.SUB,cpuKernelImpl:dpe,supportsComplex:!0}),bme={kernelName:uo,backendName:"webgpu",kernelFunc:n6};function vme(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{dim:a}=s,o=v.parseAxisParam([a],r.shape),i=YC({inputs:{x:r},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),l=E.expandShapeToKeepDim(i.shape,o),c=nt({inputs:{x:i},backend:n,attrs:{shape:l}}),u=n6({inputs:{a:r,b:c},backend:n}),d=qC({inputs:{x:u},backend:n}),p=Mx({inputs:{x:d},backend:n,attrs:{axis:o,keepDims:!1}}),h=nt({inputs:{x:p},backend:n,attrs:{shape:l}}),f=e6({inputs:{a:d,b:h},backend:n});return n.disposeData(i.dataId),n.disposeData(c.dataId),n.disposeData(u.dataId),n.disposeData(d.dataId),n.disposeData(p.dataId),n.disposeData(h.dataId),f}var wme={kernelName:io,backendName:"webgpu",kernelFunc:vme},kme=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:o}=s;v.assert(r.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGPU backend not implemented yet");let i=a.reduce((y,A)=>y*A),l=[[0,0]];l.push(...o);for(let y=1+a.length;y<r.shape.length;++y)l.push([0,0]);let c=[],u=QC({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),d=E.getReshaped(u.shape,a,i,!1),p=E.getPermuted(d.length,a.length,!1),h=E.getReshapedPermuted(u.shape,a,i,!1),f=nt({inputs:{x:u},backend:n,attrs:{shape:d}}),m=Il({inputs:{x:f},backend:n,attrs:{perm:p}}),g=nt({inputs:{x:m},backend:n,attrs:{shape:h}});return c.push(u),c.push(f),c.push(m),c.forEach(y=>n.disposeData(y.dataId)),g},Ime={kernelName:Pi,backendName:"webgpu",kernelFunc:kme};function Sme(e){let{inputs:t,backend:n,attrs:s}=e,{sparseIndices:r,sparseValues:a,defaultValue:o}=t,{outputShape:i}=s,{sliceRank:l,numUpdates:c,strides:u,outputSize:d}=E.calculateShapes(a,r,i),p=!1,h=[{type:"int32",data:[c]},{type:"int32",data:[l]},{type:"int32",data:u}],f=new t6(c,l,r.shape.length,a.shape.length,u,[d,1],p),m=n.runWebGPUProgram(f,[a,r,o],a.dtype,h),g=nt({inputs:{x:m},backend:n,attrs:{shape:i}});return n.disposeData(m.dataId),g}var Cme={kernelName:nd,backendName:"webgpu",kernelFunc:Sme};function Tme(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{numOrSizeSplits:a,axis:o}=s,i=v.parseAxisParam(o,r.shape)[0],l=E.prepareSplitSize(r,a,i),c=r.shape.length,u=new Array(c).fill(0),d=r.shape.slice();return l.map(p=>{let h=[...d];h[i]=p;let f=kp({inputs:{x:r},backend:n,attrs:{begin:u,size:h}});return u[i]+=p,f})}var Nme={kernelName:Fi,backendName:"webgpu",kernelFunc:Tme},Eme=$n({opType:Fe.SQRT}),Rme={kernelName:ao,backendName:"webgpu",kernelFunc:Eme},$me={kernelName:Au,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,s=t,r=new e0(n.shape,Fe.SQUARE);return s.runWebGPUProgram(r,[n],n.dtype)}},Dme=Xn({opSnippet:je.SQUARED_DIFFERENCE}),_me={kernelName:lo,backendName:"webgpu",kernelFunc:Dme},Pme=class{constructor(e){this.variableNames=["x"],this.workPerThread=1,this.workGroupSize=[64,1,1],this.outputShape=e,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]);let t=ln(this.outputShape.length);this.uniforms=`begin : ${t}; strides : ${t}; `,this.shaderKey="stridedSlice",this.size=v.sizeFromShape(this.outputShape)}getUserCode(){let e=this.outputShape.length,t="";if(e===1)t="coords * uniforms.strides + uniforms.begin";else{let s=0;t=this.outputShape.map((r,a)=>(s++,this.outputShape.length===1?`coords * uniforms.strides[${a}] + uniforms.begin[${a}]`:`coords[${s-1}] * uniforms.strides[${a}] + uniforms.begin[${a}]`)).join(",")}return`
|
|
${Me()} {
|
|
${He()}
|
|
if (index < uniforms.size) {
|
|
let coords = getOutputCoords(globalId, index);
|
|
setOutputFlat(index, getX(${t}));
|
|
}
|
|
}
|
|
`}};function Fme(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=s,{nonStrided:h,$begin:f,$strides:m,size:g,newShape:y,outShape:A}=yn.sliceInfo(r.shape,a,o,i,l,c,u,d,p),x=nt({inputs:{x:r},backend:n,attrs:{shape:y}}),b;if(h){let k=kp({inputs:{x},backend:n,attrs:{begin:f,size:g}});b=nt({inputs:{x:k},backend:n,attrs:{shape:A}}),n.disposeData(k.dataId)}else if(A.some(k=>k===0))b=n.makeTensorInfo(A,r.dtype,[]);else if(n.shouldExecuteOnCPU([x])){let N=n.tensorMap.get(x.dataId).values,$=We(x.shape,x.dtype,N),F=upe(A,$,m,f);b=n.makeTensorInfo(A,x.dtype,F.values)}else{let S=new Pme(A),N=[{type:"int32",data:f},{type:"int32",data:m}];b=n.runWebGPUProgram(S,[x],x.dtype,N)}let w=nt({inputs:{x:b},backend:n,attrs:{shape:A}});return n.disposeData(x.dataId),n.disposeData(b.dataId),w}var Ome={kernelName:Oi,backendName:"webgpu",kernelFunc:Fme};function Mme(e){let{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:c}=s,{data:u,dataSplits:d}=t,p=n.readSync(u.dataId),h=n.readSync(d.dataId),[f,m]=cpe(p,h,r,a,o,i,l,c);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var zme={kernelName:sd,backendName:"webgpu",kernelFunc:Mme},Lme=$n({opType:Fe.TANH}),Bme={kernelName:co,backendName:"webgpu",kernelFunc:Lme},Wme=class{constructor(e,t){this.variableNames=["A"],this.workGroupSize=[64,1,1];let n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[s]*t[s];this.outputShape=n,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.rank=this.outputShape.length,this.size=v.sizeFromShape(this.outputShape),this.shaderKey="tile"}getUserCode(){let e=Vme(this.rank,"uniforms.");return`
|
|
${Me()} {
|
|
${He()}
|
|
if (index < uniforms.size) {
|
|
let resRC = getOutputCoords(globalId, index);
|
|
setOutputFlat(index, getA(${e}));
|
|
}
|
|
}
|
|
`}};function Vme(e,t=""){if(e>=5)throw Error(`Tile for rank ${e} is not yet supported`);if(e===1)return`(resRC % ${t}aShape)`;let n=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let r=0;r<e;r++)s.push(`(${n[r]} % ${t}aShape[${r}])`);return s.join()}function Ume(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reps:a}=s;if(n.shouldExecuteOnCPU([r])||r.dtype==="string"||r.shape.length>=5){let l=n.readSync(r.dataId),c=r.dtype==="string"?l.map(p=>v.decodeString(p)):l,u=We(r.shape,r.dtype,c),d=ppe(u,a);return n.makeTensorInfo(d.shape,d.dtype,d.values)}let o=new Wme(r.shape,a);return n.runWebGPUProgram(o,[r],r.dtype)}var Gme={kernelName:Kr,backendName:"webgpu",kernelFunc:Ume},Hme=class{constructor(e){this.variableNames=["Image","Transforms"],this.uniforms="interpolationModeId : i32; fillModeId : i32; fillValue : f32;",this.workGroupSize=[64,1,1],this.outputShape=e,this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="transform"}getUserCode(){return`
|
|
fn mapCoord(outCoord : f32, len : f32) -> f32{
|
|
var inCoord = outCoord;
|
|
if(uniforms.fillModeId == 2) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
let sz2 = 2.0 * len;
|
|
if (inCoord < sz2) {
|
|
inCoord = sz2 * f32(i32(f32(-inCoord / sz2))) +
|
|
inCoord;
|
|
}
|
|
if (inCoord < -len) {
|
|
inCoord = inCoord + sz2;
|
|
} else {
|
|
inCoord = -inCoord - 1.0;
|
|
}
|
|
}
|
|
} elseif (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
let sz2 = 2.0 * len;
|
|
inCoord = inCoord - sz2 * f32(i32(f32(inCoord / sz2)));
|
|
if (inCoord >= len) {
|
|
inCoord = sz2 - inCoord - 1.0;
|
|
}
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} elseif (uniforms.fillModeId == 3) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
let sz = len - 1.0;
|
|
inCoord = inCoord + len * (f32(i32(f32(-inCoord / sz))) + 1.0);
|
|
}
|
|
} elseif (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
let sz = len - 1.0;
|
|
inCoord = inCoord - len * f32(i32(f32(inCoord / sz)));
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} elseif (uniforms.fillModeId == 4) {
|
|
return clamp(outCoord, 0.0, len - 1.0);
|
|
}
|
|
return outCoord;
|
|
}
|
|
fn readWithFillValue(batch : i32, coordY : i32, coordX : i32,
|
|
channel : i32) -> f32 {
|
|
var outputValue : f32;
|
|
if (0 <= coordY && coordY < uniforms.imageShape[1] && 0 <= coordX && coordX < uniforms.imageShape[2]) {
|
|
outputValue = getImage(batch, coordY, coordX, channel);
|
|
} else {
|
|
outputValue = uniforms.fillValue;
|
|
}
|
|
return outputValue;
|
|
}
|
|
|
|
${Me()} {
|
|
${He()}
|
|
let coords = getOutputCoords(globalId, index);
|
|
if (coordsInBounds4D(coords, uniforms.outShape)) {
|
|
var outputValue : f32;
|
|
let batch = coords[0];
|
|
let x = coords[2];
|
|
let y = coords[1];
|
|
let channel = coords[3];
|
|
let xf = f32(x);
|
|
let yf = f32(y);
|
|
let a1 = getTransforms(batch, 0);
|
|
let a2 = getTransforms(batch, 1);
|
|
let a3 = getTransforms(batch, 2);
|
|
let b1 = getTransforms(batch, 3);
|
|
let b2 = getTransforms(batch, 4);
|
|
let b3 = getTransforms(batch, 5);
|
|
let c1 = getTransforms(batch, 6);
|
|
let c2 = getTransforms(batch, 7);
|
|
let projection = c1 * xf + c2 * yf + 1.0;
|
|
if (projection == 0.0) {
|
|
outputValue = uniforms.fillValue;
|
|
} else {
|
|
let inX = (a1 * xf + a2 * yf + a3) / projection;
|
|
let inY = (b1 * xf + b2 * yf + b3) / projection;
|
|
let mapX = mapCoord(inX, f32(uniforms.imageShape[2]));
|
|
let mapY = mapCoord(inY, f32(uniforms.imageShape[1]));
|
|
|
|
if (uniforms.interpolationModeId == 1) {
|
|
let coordY = i32(round(mapY));
|
|
let coordX = i32(round(mapX));
|
|
outputValue = readWithFillValue(batch, coordY, coordX,
|
|
channel);
|
|
} else {
|
|
let yFloor = floor(mapY);
|
|
let xFloor = floor(mapX);
|
|
let yCeil = yFloor + 1.0;
|
|
let xCeil = xFloor + 1.0;
|
|
let valueYFloor = (xCeil - mapX) *
|
|
readWithFillValue(batch, i32(yFloor), i32(xFloor), channel) +
|
|
(mapX - xFloor) *
|
|
readWithFillValue(batch, i32(yFloor), i32(xCeil), channel);
|
|
let valueYCeil = (xCeil - mapX) *
|
|
readWithFillValue(batch, i32(yCeil), i32(xFloor), channel) +
|
|
(mapX - xFloor) *
|
|
readWithFillValue(batch, i32(yCeil), i32(xCeil), channel);
|
|
outputValue = (yCeil - mapY) * valueYFloor +
|
|
(mapY - yFloor) * valueYCeil;
|
|
}
|
|
}
|
|
setOutput(coords[0], coords[1], coords[2], coords[3], outputValue);
|
|
}
|
|
}
|
|
`}};function jme(e){let{inputs:t,backend:n,attrs:s}=e,{image:r,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:l,outputShape:c}=s,[u,d,p,h]=r.shape,[f,m]=c!=null?c:[d,p],g=[u,f,m,h],y=new Hme(g),A=o==="nearest"?1:2,x;switch(i){case"constant":x=1;break;case"reflect":x=2;break;case"wrap":x=3;break;case"nearest":x=4;break;default:x=1;break}let b=[{type:"int32",data:[A]},{type:"int32",data:[x]},{type:"float32",data:[l]}];return n.runWebGPUProgram(y,[r,a],"float32",b)}var qme={kernelName:zi,backendName:"webgpu",kernelFunc:jme};function Xme(e){let{inputs:t,backend:n,attrs:s}=e,{value:r}=t,{axis:a}=s;a<0&&(a+=r.shape.length);let o=r,i=o.shape.length,l=r.shape[a],c=new Array(i-1),u=0;for(let m=0;m<i;m++)m!==a&&(c[u++]=o.shape[m]);let d=[],p=new Array(i).fill(0),h=o.shape.slice();h[a]=1;let f=new Array(l);for(let m=0;m<f.length;m++){p[a]=m;let g=kp({inputs:{x:o},backend:n,attrs:{begin:p,size:h}}),y=nt({inputs:{x:g},backend:n,attrs:{shape:c}});f[m]=y,d.push(g)}return d.forEach(m=>n.disposeData(m.dataId)),f}var Kme={kernelName:Li,backendName:"webgpu",kernelFunc:Xme},Zme=[_de,mpe,ype,bpe,Cpe,Npe,Rpe,Dpe,Mpe,Wpe,Upe,qpe,Mde,Ype,the,ahe,ihe,uhe,phe,mhe,yhe,whe,Ihe,Che,Nhe,The,Rhe,Dhe,Phe,Bhe,Ohe,zhe,Uhe,Hhe,qhe,Zhe,efe,nfe,rfe,Ode,Kpe,ofe,lfe,cfe,pfe,ffe,mfe,yfe,xfe,vfe,kfe,Sfe,Tfe,Ahe,Efe,$fe,_fe,zpe,Ffe,Mfe,Lfe,Ufe,Hfe,Wfe,qfe,Lpe,Xfe,Zfe,Jfe,$de,tme,rme,ome,lme,cme,hme,mme,yme,xme,Fpe,Ome,zme,wme,Ime,Nme,Cme,Rme,$me,_me,bme,bhe,Bme,Gme,qme,Ipe,Kme,Pfe];for(let e of Zme)Yr(e);var Yme=class{constructor(e){this.device=e,this.numUsedBuffers=0,this.numFreeBuffers=0,this.freeBuffers=new Map,this.usedBuffers=new Map,this.numBytesUsed=0,this.numBytesAllocated=0}acquireBuffer(e,t){let n=s6(e,t);if(this.freeBuffers.has(n)||this.freeBuffers.set(n,[]),this.usedBuffers.has(n)||this.usedBuffers.set(n,[]),this.numBytesUsed+=e,this.numUsedBuffers++,this.freeBuffers.get(n).length>0){this.numFreeBuffers--;let r=this.freeBuffers.get(n).shift();return this.usedBuffers.get(n).push(r),r}this.numBytesAllocated+=e;let s=this.device.createBuffer({size:e,usage:t});return this.usedBuffers.get(n).push(s),s}releaseBuffer(e,t,n){if(this.freeBuffers==null)return;let s=s6(t,n);this.freeBuffers.has(s)||this.freeBuffers.set(s,[]),this.freeBuffers.get(s).push(e),this.numFreeBuffers++,this.numUsedBuffers--;let r=this.usedBuffers.get(s),a=r.indexOf(e);if(a<0)throw new Error("Cannot release a buffer that was never provided by this buffer manager");r.splice(a,1),this.numBytesUsed-=t}getNumUsedBuffers(){return this.numUsedBuffers}getNumFreeBuffers(){return this.numFreeBuffers}reset(){this.freeBuffers=new Map,this.usedBuffers=new Map,this.numUsedBuffers=0,this.numFreeBuffers=0,this.numBytesUsed=0,this.numBytesAllocated=0}dispose(){this.freeBuffers==null&&this.usedBuffers==null||(this.freeBuffers.forEach((e,t)=>{e.forEach(n=>{n.destroy()})}),this.usedBuffers.forEach((e,t)=>{e.forEach(n=>{n.destroy()})}),this.freeBuffers=null,this.usedBuffers=null,this.numUsedBuffers=0,this.numFreeBuffers=0,this.numBytesUsed=0,this.numBytesAllocated=0)}};function s6(e,t){return`${e}_${t}`}var r6=class{constructor(){this.outputShape=[0],this.variableNames=[],this.workGroupSize=[256,1,1],this.lastUniformData=[],this.inputTexture=null,this.layout=null,this.lastPixelSize={width:0,height:0},this.disposed=!1,this.shaderKey="fromPixels",this.useImport=!1}updateOutputShape(e){v.arraysEqual(this.outputShape,e)||(this.outputShape=e,this.workPerThread=e[2],this.dispatchLayout=at(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]))}makeFromPixelsSource(){let e=this.useImport?"textureLoad(src, vec2<i32>(coords.yx));":"textureLoad(src, vec2<i32>(coords.yx), 0)";return`
|
|
[[binding(1), group(0)]] var src: ${this.useImport?"texture_external":"texture_2d<f32>"};
|
|
|
|
${Me()} {
|
|
${He()}
|
|
let flatIndexBase = index * uniforms.numChannels;
|
|
let coords = getCoordsFromFlatIndex(flatIndexBase);
|
|
let values = ${e};
|
|
for (var i = 0; i < uniforms.numChannels; i = i + 1) {
|
|
let flatIndex = flatIndexBase + i;
|
|
if (flatIndex < uniforms.size) {
|
|
result.numbers[flatIndex] = i32(floor(255.0 * values[i]));
|
|
}
|
|
}
|
|
}
|
|
`}getUserCode(){return this.makeFromPixelsSource()}setPipeline(e){this.pipeline=e}setUniform(e,t){if(!this.uniform){let n=e.createBuffer({size:t.length*4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.uniform=n}!t||t.length===this.lastUniformData.length&&t.every((n,s)=>n===this.lastUniformData[s])||(e.queue.writeBuffer(this.uniform,0,new Uint32Array(t)),this.lastUniformData=t)}makeInputTexture(e,t,n){return(!this.inputTexture||this.lastPixelSize.width!==t||this.lastPixelSize.height!==n)&&(this.inputTexture&&this.inputTexture.destroy(),this.inputTexture=e.createTexture({size:[t,n],format:"rgba8unorm",usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),this.lastPixelSize.width=t,this.lastPixelSize.height=n),this.inputTexture}dispose(){this.disposed||(this.uniform&&this.uniform.destroy(),this.inputTexture&&this.inputTexture.destroy(),this.disposed=!0)}getLayout(e){return this.layout===null&&(this.layout=this.createTextureLayout(e)),this.layout}createTextureLayout(e){let t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}),t.push({binding:1,visibility:GPUShaderStage.COMPUTE,texture:{}}),t.push({binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{}});let n=e.createBindGroupLayout({entries:t}),s=e.createPipelineLayout({bindGroupLayouts:[n]});return{bindGroupLayout:n,pipelineLayout:s}}},Jme=class extends r6{constructor(){super(...arguments);this.layout=null,this.useImport=!0}getUserCode(){return this.makeFromPixelsSource()}getLayout(e){return this.layout===null&&(this.layout=this.createTextureImportLayout(e)),this.layout}createTextureImportLayout(e){let t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}),t.push({binding:1,visibility:GPUShaderStage.COMPUTE,externalTexture:{}}),t.push({binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{}});let n=e.createBindGroupLayout({entries:t}),s=e.createPipelineLayout({bindGroupLayouts:[n]});return{bindGroupLayout:n,pipelineLayout:s}}},Qme=Z().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD"),r0=class extends Gl{constructor(e,t=!1){super();if(this.commandQueueOwnedIds=new WeakSet,this.tensorDisposalQueue=[],this.uniformDisposalQueue=[],this.disposed=!1,this.uploadWaitMs=0,this.downloadWaitMs=0,this.dispatchNumberInEncoder=0,!$x())throw new Error("WebGPU is not supported on this device");this.layoutCache={},this.pipelineCache={},this.device=e,this.queue=e.queue,this.currentCommandEncoder=null,this.currentComputePass=null,this.supportTimeQuery=t,this.bufferManager=new Yme(this.device),this.tensorMap=new Vc(this,ts()),this.supportTimeQuery&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:2})),Z().getBool("WEBGPU_USE_PROFILE_TOOL")&&(this.dummyCanvas=document.createElement("canvas"),this.dummyCanvas.width=1,this.dummyCanvas.height=1,this.dummyContext=this.dummyCanvas.getContext("webgpu"),this.dummyContext.configure({device:e,format:"bgra8unorm"}),document.body.appendChild(this.dummyCanvas))}nextDataId(){return r0.nextDataId++}floatPrecision(){return 32}defaultGpuBufferUsage(){return GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}flushDisposalQueue(){this.tensorDisposalQueue.forEach(e=>{this.maybeReleaseBuffer(e),this.tensorMap.delete(e)}),this.uniformDisposalQueue.forEach(e=>this.bufferManager.releaseBuffer(e.buffer,e.byteSize,e.usage)),this.tensorDisposalQueue=[],this.uniformDisposalQueue=[]}disposeData(e,t=!1){if(this.tensorMap.has(e)){let n=this.tensorMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;if(this.commandQueueOwnedIds.has(e))return this.tensorDisposalQueue.push(e),!1;this.maybeReleaseBuffer(e);let{complexTensorInfos:s}=this.tensorMap.get(e);s!=null&&(this.disposeData(s.real.dataId,!0),this.disposeData(s.imag.dataId,!0)),this.tensorMap.delete(e)}return!0}memory(){return{numBytesInGPU:this.bufferManager.numBytesUsed,numBytesAllocatedInGPU:this.bufferManager.numBytesAllocated,unreliable:!1}}getBufferManager(){return this.bufferManager}acquireBuffer(e,t=this.defaultGpuBufferUsage()){return this.bufferManager.acquireBuffer(e,t)}maybeReleaseBuffer(e){let t=this.tensorMap.get(e);t!=null&&t.bufferInfo.buffer!=null&&(this.bufferManager.releaseBuffer(t.bufferInfo.buffer,t.bufferInfo.byteSize,t.bufferInfo.usage),t.bufferInfo.buffer=null)}refCount(e){return this.tensorMap.has(e)?this.tensorMap.get(e).refCount:0}incRef(e){let t=this.tensorMap.get(e);t.refCount++}decRef(e){if(this.tensorMap.has(e)){let t=this.tensorMap.get(e);t.refCount--}}write(e,t,n){if(n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let s={id:this.nextDataId()},r=v.sizeFromShape(t)*Rx(n);return n==="bool"&&e instanceof Uint8Array&&(e=Int32Array.from(e)),this.tensorMap.set(s,{dtype:n,values:e,bufferInfo:{byteSize:r,usage:this.defaultGpuBufferUsage()},refCount:1}),s}move(e,t,n,s,r){if(s==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let a=v.sizeFromShape(n)*Rx(s);this.tensorMap.set(e,{dtype:s,values:t,bufferInfo:{byteSize:a,usage:this.defaultGpuBufferUsage()},refCount:r})}submitQueue(){this.ensureComputePassEnded(),this.queue.submit([this.currentCommandEncoder.finish()]),this.currentCommandEncoder=null,this.dispatchNumberInEncoder=0,this.commandQueueOwnedIds=new WeakSet,this.flushDisposalQueue()}getBuffer(e){return this.uploadToGPU(e),this.tensorMap.get(e).bufferInfo.buffer}getFromPixelsProgram(e){switch(e){case"copyExternal":return this.fromPixelProgram||(this.fromPixelProgram=new r6),this.fromPixelProgram;case"import":return this.fromPixelImportProgram||(this.fromPixelImportProgram=new Jme),this.fromPixelImportProgram;default:v.assert(!1,()=>"Unsupported fromPixels shape");return}}ensureCommandEncoderReady(){this.currentCommandEncoder||(this.currentCommandEncoder=this.device.createCommandEncoder())}ensureComputePassEnded(){this.currentComputePass&&(this.currentComputePass.endPass(),this.currentComputePass=null)}getComputePass(){return this.currentComputePass||(this.currentComputePass=this.currentCommandEncoder.beginComputePass()),this.currentComputePass}async getBufferData(e){if(e.values!=null)return e.values;let t=this.acquireBuffer(e.bufferInfo.byteSize,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(e.bufferInfo.buffer,0,t,0,e.bufferInfo.byteSize),this.submitQueue(),await t.mapAsync(GPUMapMode.READ);let n=t.getMappedRange().slice(0);return t.unmap(),t!=null&&this.bufferManager.releaseBuffer(t,e.bufferInfo.byteSize,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ),Z().getBool("WEBGPU_USE_PROFILE_TOOL")&&(v.assert(this.dummyContext!==void 0,()=>"Fail to get context for profiling tool"),this.dummyContext.getCurrentTexture()),n}convertAndCacheOnCPU(e,t){let n=this.tensorMap.get(e);return this.maybeReleaseBuffer(e),n.values=t,n.values}readSync(e){let t=this.tensorMap.get(e),{values:n}=t;if(n==null)throw new Error("WebGPU readSync is only available for CPU-resident tensors.");return n}async read(e){if(!this.tensorMap.has(e))throw new Error(`Tensor ${e} was not registered!`);let t=this.tensorMap.get(e),{values:n}=t;if(n!=null)return this.convertAndCacheOnCPU(e,n);let s;if(t.dtype==="complex64"){let r=await Promise.all([this.read(t.complexTensorInfos.real.dataId),this.read(t.complexTensorInfos.imag.dataId)]),a=r[0],o=r[1];s=E.mergeRealAndImagArrays(a,o)}else{let r=await this.getBufferData(t);s=TC(r,t.dtype)}return this.convertAndCacheOnCPU(e,s),s}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(s=>v.decodeString(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return We(e.shape,e.dtype,n)}async time(e){let t=this.activeTimers,n=[],s=!1;this.programTimersStack==null?(this.programTimersStack=n,s=!0):this.activeTimers.push(n),this.activeTimers=n,e();let r=v.flatten(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),a=v.flatten(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=t,s&&(this.programTimersStack=null);let o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},i=await Promise.all(r);return o.kernelMs=v.sum(i),o.getExtraProfileInfo=()=>i.map((l,c)=>({name:a[c],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", "),this.uploadWaitMs=0,this.downloadWaitMs=0,o}getAndSavePipeline(e,t){return e in this.pipelineCache||(this.pipelineCache[e]=t()),this.pipelineCache[e]}makeTensorInfo(e,t,n){let s;if(t==="string"&&n!=null&&n.length>0&&v.isString(n[0])){let r=n.map(a=>v.encodeString(a));s=this.write(r,e,t)}else s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}tensorToBinding(e){if(!e)return null;let t=this.tensorMap.get(e.dataId);return{offset:0,size:t.bufferInfo.byteSize,buffer:t.bufferInfo.buffer}}async getQueryTime(e){return this.supportTimeQuery?this.getTimeFromQuerySet(e):0}uploadToGPU(e){let t=this.tensorMap.get(e);t.bufferInfo.buffer==null&&(t.bufferInfo.buffer=this.acquireBuffer(t.bufferInfo.byteSize),t.values&&this.queue.writeBuffer(t.bufferInfo.buffer,0,t.values))}makeUniformsDataView(e){let t=this.acquireBuffer(e.byteLength,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);return this.queue.writeBuffer(t,0,e),{offset:0,size:e.byteLength,buffer:t}}arrayToDataView(e,t){let n=4,s=new DataView(new ArrayBuffer(t*n)),r=0;return e.forEach(a=>{let o=a.data;if(a.type!=="int32"&&a.type!=="float32"&&a.type!=="uint32")throw new Error(`${a.type} not supported!`);a.type==="int32"?o.forEach(i=>{s.setInt32(r*n,i,!0),r++}):a.type==="uint32"?o.forEach(i=>{s.setUint32(r*n,i,!0),r++}):o.forEach(i=>{s.setFloat32(r*n,i,!0),r++})}),s}computePadding(e){let t=0,n=0,s=0,r=[];return e.forEach((a,o)=>{a.data.length===0&&(a.data=[1]);let i;switch(a.data.length){case 0:i=1;break;case 1:i=1;break;case 2:i=2;break;case 3:i=4;break;case 4:i=4;break;default:v.assert(!1,()=>`Unsupported ${a.data.length}D shape`)}n=Math.ceil(t/i)*i-t;for(let l=0;l<n;++l)r.push({type:a.type,data:[0]}),s++;r.push({type:a.type,data:a.data}),s=s+a.data.length,t+=a.data.length+n}),this.arrayToDataView(r,s)}createLayout(e){let t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}});for(let r=0;r<e;r++)t.push({binding:r+1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}});t.push({binding:e+1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}});let n=this.device.createBindGroupLayout({entries:t}),s=this.device.createPipelineLayout({bindGroupLayouts:[n]});return{bindGroupLayout:n,pipelineLayout:s}}getCachedOrCreateLayout(e){return e in this.layoutCache||(this.layoutCache[e]=this.createLayout(e)),this.layoutCache[e]}runWebGPUProgram(e,t,n,s){let r=this.makeTensorInfo(e.outputShape,n),a=this.tensorMap.get(r.dataId);if(v.sizeFromShape(r.shape)===0)return a.values=v.getTypedArrayFromDType(r.dtype,0),r;let o=[{type:"float32",data:[NaN]}],i=t.concat(r).map($=>$.shape),l="int32";i.map($=>{o.push({type:l,data:$})});let c=v.computeStrides(r.shape);o.push({type:l,data:c}),e.size!=null&&o.push({type:l,data:[e.size]}),o.push({type:"uint32",data:e.dispatch}),s&&(o=[...o,...s]);let u=null,d=this.computePadding(o),p=d.byteLength;u=this.makeUniformsDataView(d);let h=t.map(($,F)=>{if($.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");return this.uploadToGPU($.dataId),{dtype:this.tensorMap.get($.dataId).dtype,shape:$.shape,name:e.variableNames[F]}});this.uploadToGPU(r.dataId);let f=h.map($=>$.dtype).concat(r.dtype),m=h.map($=>E.getBroadcastDims($.shape,r.shape)),g=h.map($=>v.arraysEqual($.shape,r.shape)).join("_"),y=m.map($=>$.join("_")).join(";"),A=KC(e,i,f,y,g),{bindGroupLayout:x,pipelineLayout:b}=this.getCachedOrCreateLayout(e.variableNames.length),w=this.getAndSavePipeline(A,()=>XC(this.device,e,b,h,r)),k=this.activeTimers!=null,S=Lhe(this.device,x,t.map($=>this.tensorToBinding($)),this.tensorToBinding(r),u);this.ensureCommandEncoderReady();let N=this.getComputePass();if(k&&this.supportTimeQuery&&N.writeTimestamp(this.querySet,0),N.setPipeline(w),N.setBindGroup(0,S),N.dispatch(e.dispatch[0],e.dispatch[1],e.dispatch[2]),k&&this.supportTimeQuery&&N.writeTimestamp(this.querySet,1),this.dispatchNumberInEncoder++,t.forEach($=>{this.commandQueueOwnedIds.add($.dataId)}),this.commandQueueOwnedIds.add(r.dataId),u){let $={byteSize:p,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM,buffer:u.buffer};this.uniformDisposalQueue.push($)}return Z().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE")<=this.dispatchNumberInEncoder&&this.submitQueue(),k&&this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(this.querySet)}),r}runFromPixelsProgram(e,t,n,s,r){let a=this.device.createBindGroup({layout:n.bindGroupLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:s},{binding:2,resource:{buffer:e.uniform}}]});this.ensureCommandEncoderReady();let o=this.getComputePass(),i=this.activeTimers!=null;i&&this.supportTimeQuery&&o.writeTimestamp(this.querySet,0),o.setPipeline(e.pipeline),o.setBindGroup(0,a),o.dispatch(e.dispatch[0],e.dispatch[1],e.dispatch[2]),i&&this.supportTimeQuery&&o.writeTimestamp(this.querySet,1),this.commandQueueOwnedIds.add(r),this.submitQueue(),i&&this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(this.querySet)})}async getTimeFromQuerySet(e){let t=this.acquireBuffer(16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),n=this.acquireBuffer(16,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.resolveQuerySet(e,0,2,t,0),this.currentCommandEncoder.copyBufferToBuffer(t,0,n,0,16),this.submitQueue(),await n.mapAsync(GPUMapMode.READ);let s=new BigUint64Array(n.getMappedRange()),r=Number(s[1]-s[0]);return n.unmap(),this.bufferManager.releaseBuffer(n,16,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST),this.bufferManager.releaseBuffer(t,16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),r/1e6}shouldExecuteOnCPU(e,t=Qme){return Z().getBool("WEBGPU_CPU_FORWARD")&&e.every(n=>this.tensorMap.get(n.dataId).bufferInfo.buffer==null&&v.sizeFromShape(n.shape)<t)}numDataIds(){return this.tensorMap.numDataIds()-this.tensorDisposalQueue.length}dispose(){this.disposed||(this.bufferManager.dispose(),this.fromPixelProgram&&this.fromPixelProgram.dispose(),this.fromPixelImportProgram&&this.fromPixelImportProgram.dispose(),this.disposed=!0)}};r0.nextDataId=0;var a6={};Le(a6,{WebGPUBackend:()=>r0,webgpu_util:()=>CC});wu.isBrowser()&&$x()&&Xi("webgpu",async()=>{Z().set("CHECK_COMPUTATION_FOR_ERRORS",!1);let e={powerPreference:Z().get("WEBGPU_USE_LOW_POWER_GPU")?"low-power":"high-performance"},t=await navigator.gpu.requestAdapter(e),n={},s=t.features.has("timestamp-query");s?n={requiredFeatures:["timestamp-query"]}:console.warn("This device doesn't support timestamp-query extension. Start Chrome browser with flag --disable-dawn-features=disallow_unsafe_apis then try again. Or zero will shown for the kernel time when profiling mode isenabled. Using performance.now is not workable for webgpu sinceit doesn't support synchronously to read data from GPU.");let r=await t.requestDevice(n);return new r0(r,s)},3);var e0e="3.9.0",t0e="3.9.0",n0e="3.9.0",s0e="3.9.0",r0e="3.9.0",a0e="3.9.0",o0e="3.9.0",i0e="3.9.0",l0e={tfjs:e0e,"tfjs-core":t0e,"tfjs-data":n0e,"tfjs-layers":s0e,"tfjs-converter":r0e,"tfjs-backend-cpu":a0e,"tfjs-backend-webgl":o0e,"tfjs-backend-wasm":i0e};var Lx="2.3.3";var o6=`
|
|
precision highp float;
|
|
attribute vec2 pos;
|
|
attribute vec2 uv;
|
|
varying vec2 vUv;
|
|
uniform float flipY;
|
|
void main(void) {
|
|
vUv = uv;
|
|
gl_Position = vec4(pos.x, pos.y*flipY, 0.0, 1.);
|
|
}
|
|
`;var i6=`
|
|
precision highp float;
|
|
varying vec2 vUv;
|
|
uniform sampler2D texture;
|
|
uniform float m[20];
|
|
void main(void) {
|
|
vec4 c = texture2D(texture, vUv);
|
|
gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[3] * c.a + m[4];
|
|
gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[8] * c.a + m[9];
|
|
gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[13] * c.a + m[14];
|
|
gl_FragColor.a = m[15] * c.r + m[16] * c.g + m[17] * c.b + m[18] * c.a + m[19];
|
|
}
|
|
`,l6=`
|
|
precision highp float;
|
|
varying vec2 vUv;
|
|
uniform sampler2D texture;
|
|
uniform float m[20];
|
|
void main(void) {
|
|
vec4 c = texture2D(texture, vUv);
|
|
gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[4];
|
|
gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[9];
|
|
gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[14];
|
|
gl_FragColor.a = c.a;
|
|
}
|
|
`,u6=`
|
|
precision highp float;
|
|
varying vec2 vUv;
|
|
uniform vec2 size;
|
|
uniform sampler2D texture;
|
|
vec2 pixelate(vec2 coord, vec2 size) {
|
|
return floor( coord / size ) * size;
|
|
}
|
|
void main(void) {
|
|
gl_FragColor = vec4(0.0);
|
|
vec2 coord = pixelate(vUv, size);
|
|
gl_FragColor += texture2D(texture, coord);
|
|
}
|
|
`,c6=`
|
|
precision highp float;
|
|
varying vec2 vUv;
|
|
uniform sampler2D texture;
|
|
uniform vec2 px;
|
|
void main(void) {
|
|
gl_FragColor = vec4(0.0);
|
|
gl_FragColor += texture2D(texture, vUv + vec2(-7.0*px.x, -7.0*px.y))*0.0044299121055113265;
|
|
gl_FragColor += texture2D(texture, vUv + vec2(-6.0*px.x, -6.0*px.y))*0.00895781211794;
|
|
gl_FragColor += texture2D(texture, vUv + vec2(-5.0*px.x, -5.0*px.y))*0.0215963866053;
|
|
gl_FragColor += texture2D(texture, vUv + vec2(-4.0*px.x, -4.0*px.y))*0.0443683338718;
|
|
gl_FragColor += texture2D(texture, vUv + vec2(-3.0*px.x, -3.0*px.y))*0.0776744219933;
|
|
gl_FragColor += texture2D(texture, vUv + vec2(-2.0*px.x, -2.0*px.y))*0.115876621105;
|
|
gl_FragColor += texture2D(texture, vUv + vec2(-1.0*px.x, -1.0*px.y))*0.147308056121;
|
|
gl_FragColor += texture2D(texture, vUv )*0.159576912161;
|
|
gl_FragColor += texture2D(texture, vUv + vec2( 1.0*px.x, 1.0*px.y))*0.147308056121;
|
|
gl_FragColor += texture2D(texture, vUv + vec2( 2.0*px.x, 2.0*px.y))*0.115876621105;
|
|
gl_FragColor += texture2D(texture, vUv + vec2( 3.0*px.x, 3.0*px.y))*0.0776744219933;
|
|
gl_FragColor += texture2D(texture, vUv + vec2( 4.0*px.x, 4.0*px.y))*0.0443683338718;
|
|
gl_FragColor += texture2D(texture, vUv + vec2( 5.0*px.x, 5.0*px.y))*0.0215963866053;
|
|
gl_FragColor += texture2D(texture, vUv + vec2( 6.0*px.x, 6.0*px.y))*0.00895781211794;
|
|
gl_FragColor += texture2D(texture, vUv + vec2( 7.0*px.x, 7.0*px.y))*0.0044299121055113265;
|
|
}
|
|
`,d6=`
|
|
precision highp float;
|
|
varying vec2 vUv;
|
|
uniform sampler2D texture;
|
|
uniform vec2 px;
|
|
uniform float m[9];
|
|
void main(void) {
|
|
vec4 c11 = texture2D(texture, vUv - px); // top left
|
|
vec4 c12 = texture2D(texture, vec2(vUv.x, vUv.y - px.y)); // top center
|
|
vec4 c13 = texture2D(texture, vec2(vUv.x + px.x, vUv.y - px.y)); // top right
|
|
vec4 c21 = texture2D(texture, vec2(vUv.x - px.x, vUv.y) ); // mid left
|
|
vec4 c22 = texture2D(texture, vUv); // mid center
|
|
vec4 c23 = texture2D(texture, vec2(vUv.x + px.x, vUv.y) ); // mid right
|
|
vec4 c31 = texture2D(texture, vec2(vUv.x - px.x, vUv.y + px.y) ); // bottom left
|
|
vec4 c32 = texture2D(texture, vec2(vUv.x, vUv.y + px.y) ); // bottom center
|
|
vec4 c33 = texture2D(texture, vUv + px ); // bottom right
|
|
gl_FragColor =
|
|
c11 * m[0] + c12 * m[1] + c22 * m[2] +
|
|
c21 * m[3] + c22 * m[4] + c23 * m[5] +
|
|
c31 * m[6] + c32 * m[7] + c33 * m[8];
|
|
gl_FragColor.a = c22.a;
|
|
}
|
|
`;var Bx=(e,t,n)=>{let s=new RegExp("\\b"+t+" \\w+ (\\w+)","ig");e.replace(s,(r,a)=>(n[a]=0,r))},p6=class{constructor(t,n,s){ve(this,"uniform",{});ve(this,"attribute",{});ve(this,"gl");ve(this,"id");ve(this,"compile",(t,n)=>{let s=this.gl.createShader(n);if(this.gl.shaderSource(s,t),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw new Error(`filter: gl compile failed: ${this.gl.getShaderInfoLog(s)}`);return s});this.gl=t;let r=this.compile(n,this.gl.VERTEX_SHADER),a=this.compile(s,this.gl.FRAGMENT_SHADER);if(this.id=this.gl.createProgram(),this.gl.attachShader(this.id,r),this.gl.attachShader(this.id,a),this.gl.linkProgram(this.id),!this.gl.getProgramParameter(this.id,this.gl.LINK_STATUS))throw new Error(`filter: gl link failed: ${this.gl.getProgramInfoLog(this.id)}`);this.gl.useProgram(this.id),Bx(n,"attribute",this.attribute);for(let o in this.attribute)this.attribute[o]=this.gl.getAttribLocation(this.id,o);Bx(n,"uniform",this.uniform),Bx(s,"uniform",this.uniform);for(let o in this.uniform)this.uniform[o]=this.gl.getUniformLocation(this.id,o)}};function h6(e={}){let t=0,n=null,s=!1,r=-1,a=[null,null],o=[],i=null,l=null,c=e.canvas||typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(100,100):document.createElement("canvas"),u={},d={INTERMEDIATE:1},p=c.getContext("webgl");if(!p)throw new Error("filter: cannot get webgl context");function h(x,b){if(!(x===c.width&&b===c.height)){if(c.width=x,c.height=b,!i){let w=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,-1,1,0,0,1,-1,1,1,1,1,1,0]);i=p.createBuffer(),p.bindBuffer(p.ARRAY_BUFFER,i),p.bufferData(p.ARRAY_BUFFER,w,p.STATIC_DRAW),p.pixelStorei(p.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0)}p.viewport(0,0,c.width,c.height),a=[null,null]}}function f(x,b){let w=p.createFramebuffer();p.bindFramebuffer(p.FRAMEBUFFER,w);let k=p.createRenderbuffer();p.bindRenderbuffer(p.RENDERBUFFER,k);let S=p.createTexture();return p.bindTexture(p.TEXTURE_2D,S),p.texImage2D(p.TEXTURE_2D,0,p.RGBA,x,b,0,p.RGBA,p.UNSIGNED_BYTE,null),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.LINEAR),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.LINEAR),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE),p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_2D,S,0),p.bindTexture(p.TEXTURE_2D,null),p.bindFramebuffer(p.FRAMEBUFFER,null),{fbo:w,texture:S}}function m(x){return a[x]=a[x]||f(c.width,c.height),a[x]}function g(x=0){var S,N;if(!l)return;let b=null,w=null,k=!1;t===0?b=n:b=((S=m(r))==null?void 0:S.texture)||null,t++,s&&!(x&d.INTERMEDIATE)?(w=null,k=t%2==0):(r=(r+1)%2,w=((N=m(r))==null?void 0:N.fbo)||null),p.bindTexture(p.TEXTURE_2D,b),p.bindFramebuffer(p.FRAMEBUFFER,w),p.uniform1f(l.uniform.flipY,k?-1:1),p.drawArrays(p.TRIANGLES,0,6)}function y(x){if(u[x])return l=u[x],p.useProgram((l==null?void 0:l.id)||null),l;l=new p6(p,o6,x);let b=Float32Array.BYTES_PER_ELEMENT,w=4*b;return p.enableVertexAttribArray(l.attribute.pos),p.vertexAttribPointer(l.attribute.pos,2,p.FLOAT,!1,w,0*b),p.enableVertexAttribArray(l.attribute.uv),p.vertexAttribPointer(l.attribute.uv,2,p.FLOAT,!1,w,2*b),u[x]=l,l}let A={colorMatrix:x=>{let b=new Float32Array(x);b[4]/=255,b[9]/=255,b[14]/=255,b[19]/=255;let w=b[18]===1&&b[3]===0&&b[8]===0&&b[13]===0&&b[15]===0&&b[16]===0&&b[17]===0&&b[19]===0?l6:i6,k=y(w);p.uniform1fv(k==null?void 0:k.uniform.m,b),g()},brightness:x=>{let b=(x||0)+1;A.colorMatrix([b,0,0,0,0,0,b,0,0,0,0,0,b,0,0,0,0,0,1,0])},saturation:x=>{let b=(x||0)*2/3+1,w=(b-1)*-.5;A.colorMatrix([b,w,w,0,0,w,b,w,0,0,w,w,b,0,0,0,0,0,1,0])},desaturate:()=>{A.saturation(-1)},contrast:x=>{let b=(x||0)+1,w=-128*(b-1);A.colorMatrix([b,0,0,0,w,0,b,0,0,w,0,0,b,0,w,0,0,0,1,0])},negative:()=>{A.contrast(-2)},hue:x=>{x=(x||0)/180*Math.PI;let b=Math.cos(x),w=Math.sin(x),k=.213,S=.715,N=.072;A.colorMatrix([k+b*(1-k)+w*-k,S+b*-S+w*-S,N+b*-N+w*(1-N),0,0,k+b*-k+w*.143,S+b*(1-S)+w*.14,N+b*-N+w*-.283,0,0,k+b*-k+w*-(1-k),S+b*-S+w*S,N+b*(1-N)+w*N,0,0,0,0,0,1,0])},desaturateLuminance:()=>{A.colorMatrix([.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,0,0,0,1,0])},sepia:()=>{A.colorMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0])},brownie:()=>{A.colorMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0])},vintagePinhole:()=>{A.colorMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0])},kodachrome:()=>{A.colorMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0])},technicolor:()=>{A.colorMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0])},polaroid:()=>{A.colorMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0])},shiftToBGR:()=>{A.colorMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0])},convolution:x=>{let b=new Float32Array(x),w=1/c.width,k=1/c.height,S=y(d6);p.uniform1fv(S==null?void 0:S.uniform.m,b),p.uniform2f(S==null?void 0:S.uniform.px,w,k),g()},detectEdges:()=>{A.convolution.call(this,[0,1,0,1,-4,1,0,1,0])},sobelX:()=>{A.convolution.call(this,[-1,0,1,-2,0,2,-1,0,1])},sobelY:()=>{A.convolution.call(this,[-1,-2,-1,0,0,0,1,2,1])},sharpen:x=>{let b=x||1;A.convolution.call(this,[0,-1*b,0,-1*b,1+4*b,-1*b,0,-1*b,0])},emboss:x=>{let b=x||1;A.convolution.call(this,[-2*b,-1*b,0,-1*b,1,1*b,0,1*b,2*b])},blur:x=>{let b=x/7/c.width,w=x/7/c.height,k=y(c6);p.uniform2f(k==null?void 0:k.uniform.px,0,w),g(d.INTERMEDIATE),p.uniform2f(k==null?void 0:k.uniform.px,b,0),g()},pixelate:x=>{let b=x/c.width,w=x/c.height,k=y(u6);p.uniform2f(k==null?void 0:k.uniform.size,b,w),g()}};this.add=function(x){let b=Array.prototype.slice.call(arguments,1),w=A[x];o.push({func:w,args:b})},this.reset=function(){o=[]},this.get=function(){return o},this.apply=function(x){h(x.width,x.height),t=0,n||(n=p.createTexture()),p.bindTexture(p.TEXTURE_2D,n),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.NEAREST),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.NEAREST),p.texImage2D(p.TEXTURE_2D,0,p.RGBA,p.RGBA,p.UNSIGNED_BYTE,x);for(let b=0;b<o.length;b++){s=b===o.length-1;let w=o[b];w.func.apply(this,w.args||[])}return c},this.draw=function(x){return this.add("brightness",0),this.apply(x)}}var ie={browser:void 0,node:void 0,worker:void 0,platform:void 0,agent:void 0,initial:!0,backends:[],offscreen:void 0,filter:void 0,tfjs:{version:void 0},wasm:{supported:void 0,backend:void 0,simd:void 0,multithread:void 0},webgl:{supported:void 0,backend:void 0,version:void 0,renderer:void 0},webgpu:{supported:void 0,backend:void 0,adapter:void 0},kernels:[],Canvas:void 0,Image:void 0,ImageData:void 0};async function c0e(){var n;ie.backends=Object.keys(ts().registryFactory),ie.wasm.supported=typeof WebAssembly!="undefined",ie.wasm.backend=ie.backends.includes("wasm"),ie.wasm.supported&&ie.wasm.backend&&lr()==="wasm"&&(ie.wasm.simd=await Z().getAsync("WASM_HAS_SIMD_SUPPORT"),ie.wasm.multithread=await Z().getAsync("WASM_HAS_MULTITHREAD_SUPPORT"));let e=Ts(100,100),t=e?e.getContext("webgl2"):void 0;if(ie.webgl.supported=typeof t!="undefined",ie.webgl.backend=ie.backends.includes("webgl"),ie.webgl.supported&&ie.webgl.backend&&(lr()==="webgl"||lr()==="humangl")){let s=Tr().gpgpu!=="undefined"?await Tr().getGPGPUContext().gl:null;s&&(ie.webgl.version=s.getParameter(s.VERSION),ie.webgl.renderer=s.getParameter(s.RENDERER))}ie.webgpu.supported=ie.browser&&typeof navigator.gpu!="undefined",ie.webgpu.backend=ie.backends.includes("webgpu"),ie.webgpu.supported&&(ie.webgpu.adapter=(n=await navigator.gpu.requestAdapter())==null?void 0:n.name),ie.kernels=Zr(lr()).map(s=>s.kernelName.toLowerCase())}async function a0(){if(ie.browser=typeof navigator!="undefined",ie.node=typeof process!="undefined",ie.tfjs.version=Jh,ie.offscreen=typeof ie.offscreen=="undefined"?typeof OffscreenCanvas!="undefined":ie.offscreen,typeof navigator!="undefined"){let e=navigator.userAgent.match(/\(([^()]+)\)/g);if(e&&e[0]){let t=e[0].match(/\(([^()]+)\)/g);ie.platform=t&&t[0]?t[0].replace(/\(|\)/g,""):"",ie.agent=navigator.userAgent.replace(e[0],""),ie.platform[1]&&(ie.agent=ie.agent.replace(e[1],"")),ie.agent=ie.agent.replace(/ /g," ")}}else typeof process!="undefined"&&(ie.platform=`${process.platform} ${process.arch}`,ie.agent=`NodeJS ${process.version}`);ie.worker=ie.browser&&ie.offscreen?typeof WorkerGlobalScope!="undefined":void 0,await c0e()}async function f6(e){ie=fn(ie,e)}var o0=2048,pt=null,Gt=null,Bo=null,Ot;function Ts(e,t){let n;if(ie.browser)if(ie.offscreen)n=new OffscreenCanvas(e,t);else{if(typeof document=="undefined")throw new Error("attempted to run in web worker but offscreenCanvas is not supported");n=document.createElement("canvas"),n.width=e,n.height=t}else typeof ie.Canvas!="undefined"?n=new ie.Canvas(e,t):typeof globalThis.Canvas!="undefined"&&(n=new globalThis.Canvas(e,t));return n}function Wx(e,t){let n=t||Ts(e.width,e.height);return n.getContext("2d").drawImage(e,0,0),n}function yc(e,t,n=!0){if(!e)return t.debug&&ae("input is missing"),{tensor:null,canvas:null};if(!(e instanceof Ke)&&!(typeof Image!="undefined"&&e instanceof Image)&&!(typeof ie.Canvas!="undefined"&&e instanceof ie.Canvas)&&!(typeof globalThis.Canvas!="undefined"&&e instanceof globalThis.Canvas)&&!(typeof ImageData!="undefined"&&e instanceof ImageData)&&!(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)&&!(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)&&!(typeof HTMLMediaElement!="undefined"&&e instanceof HTMLMediaElement)&&!(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)&&!(typeof HTMLCanvasElement!="undefined"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas!="undefined"&&e instanceof OffscreenCanvas))throw new Error("input type is not recognized");if(e instanceof Ke){if(e.isDisposedInternal)throw new Error("input tensor is disposed");if(!e.shape||e.shape.length!==4||e.shape[0]!==1||e.shape[3]!==3)throw new Error(`input tensor shape must be [1, height, width, 3] and instead was ${e.shape}`);return{tensor:ir(e),canvas:t.filter.return?Gt:null}}else{if(typeof e.readyState!="undefined"&&e.readyState<=2)return t.debug&&ae("input stream is not ready"),{tensor:null,canvas:pt};let s=e.naturalWidth||e.videoWidth||e.width||e.shape&&e.shape[1]>0,r=e.naturalHeight||e.videoHeight||e.height||e.shape&&e.shape[2]>0;if(!s||!r)return t.debug&&ae("cannot determine input dimensions"),{tensor:null,canvas:pt};let a=s,o=r;if(a>o0&&(a=o0,o=Math.trunc(a*r/s)),o>o0&&(o=o0,a=Math.trunc(o*s/r)),(t.filter.width||0)>0?a=t.filter.width:(t.filter.height||0)>0&&(a=s*((t.filter.height||0)/r)),(t.filter.height||0)>0?o=t.filter.height:(t.filter.width||0)>0&&(o=r*((t.filter.width||0)/s)),!a||!o)throw new Error("input cannot determine dimension");(!pt||(pt==null?void 0:pt.width)!==a||(pt==null?void 0:pt.height)!==o)&&(pt=Ts(a,o));let i=pt.getContext("2d");if(typeof ImageData!="undefined"&&e instanceof ImageData?i.putImageData(e,0,0):t.filter.flip&&typeof i.translate!="undefined"?(i.translate(s,0),i.scale(-1,1),i.drawImage(e,0,0,s,r,0,0,pt==null?void 0:pt.width,pt==null?void 0:pt.height),i.setTransform(1,0,0,1,0,0)):i.drawImage(e,0,0,s,r,0,0,pt==null?void 0:pt.width,pt==null?void 0:pt.height),(!Gt||pt.width!==Gt.width||(pt==null?void 0:pt.height)!==(Gt==null?void 0:Gt.height))&&(Gt=Ts(pt.width,pt.height)),t.filter.enabled&&ie.webgl.supported){if(Ot||(Ot=ie.browser?new h6({canvas:Gt}):null),ie.filter=!!Ot,!Ot)return{tensor:null,canvas:pt};Ot.reset(),t.filter.brightness!==0&&Ot.add("brightness",t.filter.brightness),t.filter.contrast!==0&&Ot.add("contrast",t.filter.contrast),t.filter.sharpness!==0&&Ot.add("sharpen",t.filter.sharpness),t.filter.blur!==0&&Ot.add("blur",t.filter.blur),t.filter.saturation!==0&&Ot.add("saturation",t.filter.saturation),t.filter.hue!==0&&Ot.add("hue",t.filter.hue),t.filter.negative&&Ot.add("negative"),t.filter.sepia&&Ot.add("sepia"),t.filter.vintage&&Ot.add("brownie"),t.filter.sepia&&Ot.add("sepia"),t.filter.kodachrome&&Ot.add("kodachrome"),t.filter.technicolor&&Ot.add("technicolor"),t.filter.polaroid&&Ot.add("polaroid"),t.filter.pixelate!==0&&Ot.add("pixelate",t.filter.pixelate),Ot.get()>0?Gt=Ot.apply(pt):Gt=Ot.draw(pt)}else Wx(pt,Gt),Ot&&(Ot=null),ie.filter=!!Ot;if(!n)return{tensor:null,canvas:Gt};if(!Gt)throw new Error("cannot create output canvas");let l,c=3;if(typeof ImageData!="undefined"&&e instanceof ImageData||e.data&&e.width&&e.height)if(ie.browser&&Xs)l=Xs?Xs.fromPixels(e):null;else{c=e.data.length/e.height/e.width;let p=new Uint8Array(e.data.buffer);l=nn(p,[e.height,e.width,c],"int32")}else if((!Bo||Gt.width!==Bo.width||(Gt==null?void 0:Gt.height)!==(Bo==null?void 0:Bo.height))&&(Bo=Ts(Gt.width,Gt.height)),Xs&&ie.browser)t.backend==="webgl"||t.backend==="humangl"||t.backend==="webgpu"?l=Xs.fromPixels(Gt):(Bo=Wx(Gt),l=Xs.fromPixels(Bo));else{let f=Wx(Gt).getContext("2d").getImageData(0,0,a,o);c=f.data.length/a/o;let m=new Uint8Array(f.data.buffer);l=nn(m,[a,o,c])}if(c===4){let p=zu(l,[0,0,0],[-1,-1,3]);te(l),l=p}if(!l)throw new Error("cannot create tensor from input");let u=pe(l,"float32"),d=jt(u,0);return te([l,u]),{tensor:d,canvas:t.filter.return?Gt:null}}}var Vx=0,Ux=1,Gx=0,d0e=async e=>{let t=48,n=$e.resizeBilinear(e,[Math.trunc((e.shape[1]||1)/t),Math.trunc((e.shape[2]||1)/t)]),s=async()=>{let o=ke(n),i=await o.data();return te(o),i[0]},r=async()=>{let o=await n.data(),i=0;for(let l=0;l<o.length/3;l++)i+=o[3*l+2];return i};if(Gx===0){let o=performance.now();await r();let i=performance.now();await s();let l=performance.now();Gx=i-o<l-i?1:2}let a=Gx===1?await r():await s();return te(n),a};async function m6(e,t){if(e.cacheSensitivity===0)return!1;let n=await d0e(t),s=100*(Math.max(n,Vx)/Math.min(n,Vx)-1);Vx=n;let r=s<Math.max(e.cacheSensitivity,Ux);return Ux=s>10*e.cacheSensitivity?0:s,r=r&&Ux>0,r}var Lr={silhouette:[10,338,297,332,284,251,389,356,454,323,361,288,397,365,379,378,400,377,152,148,176,149,150,136,172,58,132,93,234,127,162,21,54,103,67,109],lipsUpperOuter:[61,185,40,39,37,0,267,269,270,409,291],lipsLowerOuter:[146,91,181,84,17,314,405,321,375,291],lipsUpperInner:[78,191,80,81,82,13,312,311,310,415,308],lipsLowerInner:[78,95,88,178,87,14,317,402,318,324,308],rightEyeUpper0:[246,161,160,159,158,157,173],rightEyeLower0:[33,7,163,144,145,153,154,155,133],rightEyeUpper1:[247,30,29,27,28,56,190],rightEyeLower1:[130,25,110,24,23,22,26,112,243],rightEyeUpper2:[113,225,224,223,222,221,189],rightEyeLower2:[226,31,228,229,230,231,232,233,244],rightEyeLower3:[143,111,117,118,119,120,121,128,245],rightEyebrowUpper:[156,70,63,105,66,107,55,193],rightEyebrowLower:[35,124,46,53,52,65],rightEyeIris:[473,474,475,476,477],leftEyeUpper0:[466,388,387,386,385,384,398],leftEyeLower0:[263,249,390,373,374,380,381,382,362],leftEyeUpper1:[467,260,259,257,258,286,414],leftEyeLower1:[359,255,339,254,253,252,256,341,463],leftEyeUpper2:[342,445,444,443,442,441,413],leftEyeLower2:[446,261,448,449,450,451,452,453,464],leftEyeLower3:[372,340,346,347,348,349,350,357,465],leftEyebrowUpper:[383,300,293,334,296,336,285,417],leftEyebrowLower:[265,353,276,283,282,295],leftEyeIris:[468,469,470,471,472],midwayBetweenEyes:[168],noseTip:[1],noseBottom:[2],noseRightCorner:[98],noseLeftCorner:[327],rightCheek:[205],leftCheek:[425]},Hx={count:468,mouth:13,symmetryLine:[13,Lr.midwayBetweenEyes[0]]},Cp={leftEye:0,rightEye:1,nose:2,mouth:3,leftEar:4,rightEar:5,symmetryLine:[3,2]},jx=[{key:"EyeUpper0",indices:[9,10,11,12,13,14,15]},{key:"EyeUpper1",indices:[25,26,27,28,29,30,31]},{key:"EyeUpper2",indices:[41,42,43,44,45,46,47]},{key:"EyeLower0",indices:[0,1,2,3,4,5,6,7,8]},{key:"EyeLower1",indices:[16,17,18,19,20,21,22,23,24]},{key:"EyeLower2",indices:[32,33,34,35,36,37,38,39,40]},{key:"EyeLower3",indices:[54,55,56,57,58,59,60,61,62]}],Tp=[[.499976992607117,.652534008026123],[.500025987625122,.547487020492554],[.499974012374878,.602371990680695],[.482113003730774,.471979022026062],[.500150978565216,.527155995368958],[.499909996986389,.498252987861633],[.499523013830185,.40106201171875],[.289712011814117,.380764007568359],[.499954998493195,.312398016452789],[.499987006187439,.269918978214264],[.500023007392883,.107050001621246],[.500023007392883,.666234016418457],[.5000159740448,.679224014282227],[.500023007392883,.692348003387451],[.499976992607117,.695277988910675],[.499976992607117,.70593398809433],[.499976992607117,.719385027885437],[.499976992607117,.737019002437592],[.499967992305756,.781370997428894],[.499816000461578,.562981009483337],[.473773002624512,.573909997940063],[.104906998574734,.254140973091125],[.365929991006851,.409575998783112],[.338757991790771,.41302502155304],[.311120003461838,.409460008144379],[.274657994508743,.389131009578705],[.393361985683441,.403706014156342],[.345234006643295,.344011008739471],[.370094001293182,.346076011657715],[.319321990013123,.347265005111694],[.297903001308441,.353591024875641],[.24779200553894,.410809993743896],[.396889001131058,.842755019664764],[.280097991228104,.375599980354309],[.106310002505779,.399955987930298],[.2099249958992,.391353011131287],[.355807989835739,.534406006336212],[.471751004457474,.65040397644043],[.474155008792877,.680191993713379],[.439785003662109,.657229006290436],[.414617002010345,.66654098033905],[.450374007225037,.680860996246338],[.428770989179611,.682690978050232],[.374971002340317,.727805018424988],[.486716985702515,.547628998756409],[.485300987958908,.527395009994507],[.257764995098114,.314490020275116],[.401223003864288,.455172002315521],[.429818987846375,.548614978790283],[.421351999044418,.533740997314453],[.276895999908447,.532056987285614],[.483370006084442,.499586999416351],[.33721199631691,.282882988452911],[.296391993761063,.293242990970612],[.169294998049736,.193813979625702],[.447580009698868,.302609980106354],[.392390012741089,.353887975215912],[.354490011930466,.696784019470215],[.067304998636246,.730105042457581],[.442739009857178,.572826027870178],[.457098007202148,.584792017936707],[.381974011659622,.694710969924927],[.392388999462128,.694203019142151],[.277076005935669,.271932005882263],[.422551989555359,.563233017921448],[.385919004678726,.281364023685455],[.383103013038635,.255840003490448],[.331431001424789,.119714021682739],[.229923993349075,.232002973556519],[.364500999450684,.189113974571228],[.229622006416321,.299540996551514],[.173287004232407,.278747975826263],[.472878992557526,.666198015213013],[.446828007698059,.668527007102966],[.422762006521225,.673889994621277],[.445307999849319,.580065965652466],[.388103008270264,.693961024284363],[.403039008378983,.706539988517761],[.403629004955292,.693953037261963],[.460041999816895,.557139039039612],[.431158006191254,.692366003990173],[.452181994915009,.692366003990173],[.475387006998062,.692366003990173],[.465828001499176,.779190003871918],[.472328990697861,.736225962638855],[.473087012767792,.717857003211975],[.473122000694275,.704625964164734],[.473033010959625,.695277988910675],[.427942007780075,.695277988910675],[.426479011774063,.703539967536926],[.423162013292313,.711845993995667],[.4183090031147,.720062971115112],[.390094995498657,.639572978019714],[.013953999616206,.560034036636353],[.499913990497589,.58014702796936],[.413199990987778,.69539999961853],[.409626007080078,.701822996139526],[.468080013990402,.601534962654114],[.422728985548019,.585985004901886],[.463079988956451,.593783974647522],[.37211999297142,.47341400384903],[.334562003612518,.496073007583618],[.411671012639999,.546965003013611],[.242175996303558,.14767599105835],[.290776997804642,.201445996761322],[.327338010072708,.256527006626129],[.399509996175766,.748921036720276],[.441727995872498,.261676013469696],[.429764986038208,.187834024429321],[.412198007106781,.108901023864746],[.288955003023148,.398952007293701],[.218936994671822,.435410976409912],[.41278201341629,.398970007896423],[.257135003805161,.355440020561218],[.427684992551804,.437960982322693],[.448339998722076,.536936044692993],[.178560003638268,.45755398273468],[.247308000922203,.457193970680237],[.286267012357712,.467674970626831],[.332827985286713,.460712015628815],[.368755996227264,.447206974029541],[.398963987827301,.432654976844788],[.476410001516342,.405806005001068],[.189241006970406,.523923993110657],[.228962004184723,.348950982093811],[.490725994110107,.562400996685028],[.404670000076294,.485132992267609],[.019469000399113,.401564002037048],[.426243007183075,.420431017875671],[.396993011236191,.548797011375427],[.266469985246658,.376977026462555],[.439121007919312,.51895797252655],[.032313998788595,.644356966018677],[.419054001569748,.387154996395111],[.462783008813858,.505746960639954],[.238978996872902,.779744982719421],[.198220998048782,.831938028335571],[.107550002634525,.540755033493042],[.183610007166862,.740257024765015],[.134409993886948,.333683013916016],[.385764002799988,.883153975009918],[.490967005491257,.579378008842468],[.382384985685349,.508572995662689],[.174399003386497,.397670984268188],[.318785011768341,.39623498916626],[.343364000320435,.400596976280212],[.396100014448166,.710216999053955],[.187885001301765,.588537991046906],[.430987000465393,.944064974784851],[.318993002176285,.898285031318665],[.266247987747192,.869701027870178],[.500023007392883,.190576016902924],[.499976992607117,.954452991485596],[.366169989109039,.398822009563446],[.393207013607025,.39553701877594],[.410373002290726,.391080021858215],[.194993004202843,.342101991176605],[.388664990663528,.362284004688263],[.365961998701096,.355970978736877],[.343364000320435,.355356991291046],[.318785011768341,.35834002494812],[.301414996385574,.363156020641327],[.058132998645306,.319076001644135],[.301414996385574,.387449026107788],[.499987989664078,.618434011936188],[.415838003158569,.624195992946625],[.445681989192963,.566076993942261],[.465844005346298,.620640993118286],[.49992299079895,.351523995399475],[.288718998432159,.819945991039276],[.335278987884521,.852819979190826],[.440512001514435,.902418971061707],[.128294005990028,.791940987110138],[.408771991729736,.373893976211548],[.455606997013092,.451801002025604],[.499877005815506,.908990025520325],[.375436991453171,.924192011356354],[.11421000212431,.615022003650665],[.448662012815475,.695277988910675],[.4480200111866,.704632043838501],[.447111994028091,.715808033943176],[.444831997156143,.730794012546539],[.430011987686157,.766808986663818],[.406787008047104,.685672998428345],[.400738000869751,.681069016456604],[.392399996519089,.677703022956848],[.367855995893478,.663918972015381],[.247923001646996,.601333022117615],[.452769994735718,.420849978923798],[.43639200925827,.359887003898621],[.416164010763168,.368713974952698],[.413385987281799,.692366003990173],[.228018000721931,.683571994304657],[.468268007040024,.352671027183533],[.411361992359161,.804327011108398],[.499989002943039,.469825029373169],[.479153990745544,.442654013633728],[.499974012374878,.439637005329132],[.432112008333206,.493588984012604],[.499886006116867,.866917014122009],[.49991300702095,.821729004383087],[.456548988819122,.819200992584229],[.344549000263214,.745438992977142],[.37890899181366,.574010014533997],[.374292999505997,.780184984207153],[.319687992334366,.570737957954407],[.357154995203018,.604269981384277],[.295284003019333,.621580958366394],[.447750002145767,.862477004528046],[.410986006259918,.508723020553589],[.31395098567009,.775308012962341],[.354128003120422,.812552988529205],[.324548006057739,.703992962837219],[.189096003770828,.646299958229065],[.279776990413666,.71465802192688],[.1338230073452,.682700991630554],[.336768001317978,.644733011722565],[.429883986711502,.466521978378296],[.455527991056442,.548622965812683],[.437114000320435,.558896005153656],[.467287987470627,.529924988746643],[.414712011814117,.335219979286194],[.37704598903656,.322777986526489],[.344107985496521,.320150971412659],[.312875986099243,.32233202457428],[.283526003360748,.333190023899078],[.241245999932289,.382785975933075],[.102986000478268,.468762993812561],[.267612010240555,.424560010433197],[.297879010438919,.433175981044769],[.333433985710144,.433878004550934],[.366427004337311,.426115989685059],[.396012008190155,.416696012020111],[.420121014118195,.41022801399231],[.007561000064015,.480777025222778],[.432949006557465,.569517970085144],[.458638995885849,.479089021682739],[.473466008901596,.545744001865387],[.476087987422943,.563830018043518],[.468472003936768,.555056989192963],[.433990985155106,.582361996173859],[.483518004417419,.562983989715576],[.482482999563217,.57784903049469],[.42645001411438,.389798998832703],[.438998997211456,.39649498462677],[.450067013502121,.400434017181396],[.289712011814117,.368252992630005],[.276670008897781,.363372981548309],[.517862021923065,.471948027610779],[.710287988185883,.380764007568359],[.526226997375488,.573909997940063],[.895093023777008,.254140973091125],[.634069979190826,.409575998783112],[.661242008209229,.41302502155304],[.688880026340485,.409460008144379],[.725341975688934,.389131009578705],[.606630027294159,.40370500087738],[.654766023159027,.344011008739471],[.629905998706818,.346076011657715],[.680678009986877,.347265005111694],[.702096998691559,.353591024875641],[.75221198797226,.410804986953735],[.602918028831482,.842862963676453],[.719901978969574,.375599980354309],[.893692970275879,.399959981441498],[.790081977844238,.391354024410248],[.643998026847839,.534487962722778],[.528249025344849,.65040397644043],[.525849997997284,.680191040039062],[.560214996337891,.657229006290436],[.585384011268616,.66654098033905],[.549625992774963,.680860996246338],[.57122802734375,.682691991329193],[.624852001667023,.72809898853302],[.513050019741058,.547281980514526],[.51509702205658,.527251958847046],[.742246985435486,.314507007598877],[.598631024360657,.454979002475739],[.570338010787964,.548575043678284],[.578631997108459,.533622980117798],[.723087012767792,.532054007053375],[.516445994377136,.499638974666595],[.662801027297974,.282917976379395],[.70362401008606,.293271005153656],[.830704987049103,.193813979625702],[.552385985851288,.302568018436432],[.607609987258911,.353887975215912],[.645429015159607,.696707010269165],[.932694971561432,.730105042457581],[.557260990142822,.572826027870178],[.542901992797852,.584792017936707],[.6180260181427,.694710969924927],[.607590973377228,.694203019142151],[.722943007946014,.271963000297546],[.577413976192474,.563166975975037],[.614082992076874,.281386971473694],[.616907000541687,.255886018276215],[.668509006500244,.119913995265961],[.770092010498047,.232020974159241],[.635536015033722,.189248979091644],[.77039098739624,.299556016921997],[.826722025871277,.278755009174347],[.527121007442474,.666198015213013],[.553171992301941,.668527007102966],[.577238023281097,.673889994621277],[.554691970348358,.580065965652466],[.611896991729736,.693961024284363],[.59696102142334,.706539988517761],[.596370995044708,.693953037261963],[.539958000183105,.557139039039612],[.568841993808746,.692366003990173],[.547818005084991,.692366003990173],[.52461302280426,.692366003990173],[.534089982509613,.779141008853912],[.527670979499817,.736225962638855],[.526912987232208,.717857003211975],[.526877999305725,.704625964164734],[.526966989040375,.695277988910675],[.572058022022247,.695277988910675],[.573521018028259,.703539967536926],[.57683801651001,.711845993995667],[.581691026687622,.720062971115112],[.609944999217987,.639909982681274],[.986046016216278,.560034036636353],[.5867999792099,.69539999961853],[.590372025966644,.701822996139526],[.531915009021759,.601536989212036],[.577268004417419,.585934996604919],[.536915004253387,.593786001205444],[.627542972564697,.473352015018463],[.665585994720459,.495950996875763],[.588353991508484,.546862006187439],[.757824003696442,.14767599105835],[.709249973297119,.201507985591888],[.672684013843536,.256581008434296],[.600408971309662,.74900496006012],[.55826598405838,.261672019958496],[.570303976535797,.187870979309082],[.588165998458862,.109044015407562],[.711045026779175,.398952007293701],[.781069993972778,.435405015945435],[.587247014045715,.398931980133057],[.742869973182678,.355445981025696],[.572156012058258,.437651991844177],[.55186802148819,.536570012569427],[.821442008018494,.457556009292603],[.752701997756958,.457181990146637],[.71375697851181,.467626988887787],[.66711300611496,.460672974586487],[.631101012229919,.447153985500336],[.6008620262146,.432473003864288],[.523481011390686,.405627012252808],[.810747981071472,.523926019668579],[.771045982837677,.348959028720856],[.509127020835876,.562718033790588],[.595292985439301,.485023975372314],[.980530977249146,.401564002037048],[.573499977588654,.420000016689301],[.602994978427887,.548687994480133],[.733529984951019,.376977026462555],[.560611009597778,.519016981124878],[.967685997486115,.644356966018677],[.580985009670258,.387160003185272],[.537728011608124,.505385041236877],[.760966002941132,.779752969741821],[.801778972148895,.831938028335571],[.892440974712372,.54076099395752],[.816350996494293,.740260004997253],[.865594983100891,.333687007427216],[.614073991775513,.883246004581451],[.508952975273132,.579437971115112],[.617941975593567,.508316040039062],[.825608015060425,.397674977779388],[.681214988231659,.39623498916626],[.656635999679565,.400596976280212],[.603900015354156,.710216999053955],[.81208598613739,.588539004325867],[.56801301240921,.944564998149872],[.681007981300354,.898285031318665],[.733752012252808,.869701027870178],[.633830010890961,.398822009563446],[.606792986392975,.39553701877594],[.589659988880157,.391062021255493],[.805015981197357,.342108011245728],[.611334979534149,.362284004688263],[.634037971496582,.355970978736877],[.656635999679565,.355356991291046],[.681214988231659,.35834002494812],[.698584973812103,.363156020641327],[.941866993904114,.319076001644135],[.698584973812103,.387449026107788],[.584177017211914,.624107003211975],[.554318010807037,.566076993942261],[.534153997898102,.62064003944397],[.711217999458313,.819975018501282],[.664629995822906,.852871000766754],[.559099972248077,.902631998062134],[.871706008911133,.791940987110138],[.591234028339386,.373893976211548],[.544341027736664,.451583981513977],[.624562978744507,.924192011356354],[.88577002286911,.615028977394104],[.551338016986847,.695277988910675],[.551980018615723,.704632043838501],[.552887976169586,.715808033943176],[.555167973041534,.730794012546539],[.569944024085999,.767035007476807],[.593203008174896,.685675978660583],[.599261999130249,.681069016456604],[.607599973678589,.677703022956848],[.631937980651855,.663500010967255],[.752032995223999,.601315021514893],[.547226011753082,.420395016670227],[.563543975353241,.359827995300293],[.583841025829315,.368713974952698],[.586614012718201,.692366003990173],[.771915018558502,.683578014373779],[.531597018241882,.352482974529266],[.588370978832245,.804440975189209],[.52079701423645,.442565023899078],[.567984998226166,.493479013442993],[.543282985687256,.819254994392395],[.655317008495331,.745514988899231],[.621008992195129,.574018001556396],[.625559985637665,.78031200170517],[.680198013782501,.570719003677368],[.64276397228241,.604337990283966],[.704662978649139,.621529996395111],[.552012026309967,.862591981887817],[.589071989059448,.508637011051178],[.685944974422455,.775357007980347],[.645735025405884,.812640011310577],[.675342977046967,.703978002071381],[.810858011245728,.646304965019226],[.72012197971344,.714666962623596],[.866151988506317,.682704985141754],[.663187026977539,.644596993923187],[.570082008838654,.466325998306274],[.544561982154846,.548375964164734],[.562758982181549,.558784961700439],[.531987011432648,.530140042304993],[.585271000862122,.335177004337311],[.622952997684479,.32277899980545],[.655896008014679,.320163011550903],[.687132000923157,.322345972061157],[.716481983661652,.333200991153717],[.758756995201111,.382786989212036],[.897013008594513,.468769013881683],[.732392013072968,.424547016620636],[.70211398601532,.433162987232208],[.66652500629425,.433866024017334],[.633504986763,.426087975502014],[.603875994682312,.416586995124817],[.579657971858978,.409945011138916],[.992439985275269,.480777025222778],[.567192018032074,.569419980049133],[.54136598110199,.478899002075195],[.526564002037048,.546118021011353],[.523913025856018,.563830018043518],[.531529009342194,.555056989192963],[.566035985946655,.582329034805298],[.51631098985672,.563053965568542],[.5174720287323,.577877044677734],[.573594987392426,.389806985855103],[.560697972774506,.395331978797913],[.549755990505219,.399751007556915],[.710287988185883,.368252992630005],[.723330020904541,.363372981548309]],Cl=[127,34,139,11,0,37,232,231,120,72,37,39,128,121,47,232,121,128,104,69,67,175,171,148,157,154,155,118,50,101,73,39,40,9,151,108,48,115,131,194,204,211,74,40,185,80,42,183,40,92,186,230,229,118,202,212,214,83,18,17,76,61,146,160,29,30,56,157,173,106,204,194,135,214,192,203,165,98,21,71,68,51,45,4,144,24,23,77,146,91,205,50,187,201,200,18,91,106,182,90,91,181,85,84,17,206,203,36,148,171,140,92,40,39,193,189,244,159,158,28,247,246,161,236,3,196,54,68,104,193,168,8,117,228,31,189,193,55,98,97,99,126,47,100,166,79,218,155,154,26,209,49,131,135,136,150,47,126,217,223,52,53,45,51,134,211,170,140,67,69,108,43,106,91,230,119,120,226,130,247,63,53,52,238,20,242,46,70,156,78,62,96,46,53,63,143,34,227,173,155,133,123,117,111,44,125,19,236,134,51,216,206,205,154,153,22,39,37,167,200,201,208,36,142,100,57,212,202,20,60,99,28,158,157,35,226,113,160,159,27,204,202,210,113,225,46,43,202,204,62,76,77,137,123,116,41,38,72,203,129,142,64,98,240,49,102,64,41,73,74,212,216,207,42,74,184,169,170,211,170,149,176,105,66,69,122,6,168,123,147,187,96,77,90,65,55,107,89,90,180,101,100,120,63,105,104,93,137,227,15,86,85,129,102,49,14,87,86,55,8,9,100,47,121,145,23,22,88,89,179,6,122,196,88,95,96,138,172,136,215,58,172,115,48,219,42,80,81,195,3,51,43,146,61,171,175,199,81,82,38,53,46,225,144,163,110,246,33,7,52,65,66,229,228,117,34,127,234,107,108,69,109,108,151,48,64,235,62,78,191,129,209,126,111,35,143,163,161,246,117,123,50,222,65,52,19,125,141,221,55,65,3,195,197,25,7,33,220,237,44,70,71,139,122,193,245,247,130,33,71,21,162,153,158,159,170,169,150,188,174,196,216,186,92,144,160,161,2,97,167,141,125,241,164,167,37,72,38,12,145,159,160,38,82,13,63,68,71,226,35,111,158,153,154,101,50,205,206,92,165,209,198,217,165,167,97,220,115,218,133,112,243,239,238,241,214,135,169,190,173,133,171,208,32,125,44,237,86,87,178,85,86,179,84,85,180,83,84,181,201,83,182,137,93,132,76,62,183,61,76,184,57,61,185,212,57,186,214,207,187,34,143,156,79,239,237,123,137,177,44,1,4,201,194,32,64,102,129,213,215,138,59,166,219,242,99,97,2,94,141,75,59,235,24,110,228,25,130,226,23,24,229,22,23,230,26,22,231,112,26,232,189,190,243,221,56,190,28,56,221,27,28,222,29,27,223,30,29,224,247,30,225,238,79,20,166,59,75,60,75,240,147,177,215,20,79,166,187,147,213,112,233,244,233,128,245,128,114,188,114,217,174,131,115,220,217,198,236,198,131,134,177,132,58,143,35,124,110,163,7,228,110,25,356,389,368,11,302,267,452,350,349,302,303,269,357,343,277,452,453,357,333,332,297,175,152,377,384,398,382,347,348,330,303,304,270,9,336,337,278,279,360,418,262,431,304,408,409,310,415,407,270,409,410,450,348,347,422,430,434,313,314,17,306,307,375,387,388,260,286,414,398,335,406,418,364,367,416,423,358,327,251,284,298,281,5,4,373,374,253,307,320,321,425,427,411,421,313,18,321,405,406,320,404,405,315,16,17,426,425,266,377,400,369,322,391,269,417,465,464,386,257,258,466,260,388,456,399,419,284,332,333,417,285,8,346,340,261,413,441,285,327,460,328,355,371,329,392,439,438,382,341,256,429,420,360,364,394,379,277,343,437,443,444,283,275,440,363,431,262,369,297,338,337,273,375,321,450,451,349,446,342,467,293,334,282,458,461,462,276,353,383,308,324,325,276,300,293,372,345,447,382,398,362,352,345,340,274,1,19,456,248,281,436,427,425,381,256,252,269,391,393,200,199,428,266,330,329,287,273,422,250,462,328,258,286,384,265,353,342,387,259,257,424,431,430,342,353,276,273,335,424,292,325,307,366,447,345,271,303,302,423,266,371,294,455,460,279,278,294,271,272,304,432,434,427,272,407,408,394,430,431,395,369,400,334,333,299,351,417,168,352,280,411,325,319,320,295,296,336,319,403,404,330,348,349,293,298,333,323,454,447,15,16,315,358,429,279,14,15,316,285,336,9,329,349,350,374,380,252,318,402,403,6,197,419,318,319,325,367,364,365,435,367,397,344,438,439,272,271,311,195,5,281,273,287,291,396,428,199,311,271,268,283,444,445,373,254,339,263,466,249,282,334,296,449,347,346,264,447,454,336,296,299,338,10,151,278,439,455,292,407,415,358,371,355,340,345,372,390,249,466,346,347,280,442,443,282,19,94,370,441,442,295,248,419,197,263,255,359,440,275,274,300,383,368,351,412,465,263,467,466,301,368,389,380,374,386,395,378,379,412,351,419,436,426,322,373,390,388,2,164,393,370,462,461,164,0,267,302,11,12,374,373,387,268,12,13,293,300,301,446,261,340,385,384,381,330,266,425,426,423,391,429,355,437,391,327,326,440,457,438,341,382,362,459,457,461,434,430,394,414,463,362,396,369,262,354,461,457,316,403,402,315,404,403,314,405,404,313,406,405,421,418,406,366,401,361,306,408,407,291,409,408,287,410,409,432,436,410,434,416,411,264,368,383,309,438,457,352,376,401,274,275,4,421,428,262,294,327,358,433,416,367,289,455,439,462,370,326,2,326,370,305,460,455,254,449,448,255,261,446,253,450,449,252,451,450,256,452,451,341,453,452,413,464,463,441,413,414,258,442,441,257,443,442,259,444,443,260,445,444,467,342,445,459,458,250,289,392,290,290,328,460,376,433,435,250,290,392,411,416,433,341,463,464,453,464,465,357,465,412,343,412,399,360,363,440,437,399,456,420,456,363,401,435,288,372,383,353,339,255,249,448,261,255,133,243,190,133,155,112,33,246,247,33,130,25,398,384,286,362,398,414,362,463,341,263,359,467,263,249,255,466,467,260,75,60,166,238,239,79,162,127,139,72,11,37,121,232,120,73,72,39,114,128,47,233,232,128,103,104,67,152,175,148,173,157,155,119,118,101,74,73,40,107,9,108,49,48,131,32,194,211,184,74,185,191,80,183,185,40,186,119,230,118,210,202,214,84,83,17,77,76,146,161,160,30,190,56,173,182,106,194,138,135,192,129,203,98,54,21,68,5,51,4,145,144,23,90,77,91,207,205,187,83,201,18,181,91,182,180,90,181,16,85,17,205,206,36,176,148,140,165,92,39,245,193,244,27,159,28,30,247,161,174,236,196,103,54,104,55,193,8,111,117,31,221,189,55,240,98,99,142,126,100,219,166,218,112,155,26,198,209,131,169,135,150,114,47,217,224,223,53,220,45,134,32,211,140,109,67,108,146,43,91,231,230,120,113,226,247,105,63,52,241,238,242,124,46,156,95,78,96,70,46,63,116,143,227,116,123,111,1,44,19,3,236,51,207,216,205,26,154,22,165,39,167,199,200,208,101,36,100,43,57,202,242,20,99,56,28,157,124,35,113,29,160,27,211,204,210,124,113,46,106,43,204,96,62,77,227,137,116,73,41,72,36,203,142,235,64,240,48,49,64,42,41,74,214,212,207,183,42,184,210,169,211,140,170,176,104,105,69,193,122,168,50,123,187,89,96,90,66,65,107,179,89,180,119,101,120,68,63,104,234,93,227,16,15,85,209,129,49,15,14,86,107,55,9,120,100,121,153,145,22,178,88,179,197,6,196,89,88,96,135,138,136,138,215,172,218,115,219,41,42,81,5,195,51,57,43,61,208,171,199,41,81,38,224,53,225,24,144,110,105,52,66,118,229,117,227,34,234,66,107,69,10,109,151,219,48,235,183,62,191,142,129,126,116,111,143,7,163,246,118,117,50,223,222,52,94,19,141,222,221,65,196,3,197,45,220,44,156,70,139,188,122,245,139,71,162,145,153,159,149,170,150,122,188,196,206,216,92,163,144,161,164,2,167,242,141,241,0,164,37,11,72,12,144,145,160,12,38,13,70,63,71,31,226,111,157,158,154,36,101,205,203,206,165,126,209,217,98,165,97,237,220,218,237,239,241,210,214,169,140,171,32,241,125,237,179,86,178,180,85,179,181,84,180,182,83,181,194,201,182,177,137,132,184,76,183,185,61,184,186,57,185,216,212,186,192,214,187,139,34,156,218,79,237,147,123,177,45,44,4,208,201,32,98,64,129,192,213,138,235,59,219,141,242,97,97,2,141,240,75,235,229,24,228,31,25,226,230,23,229,231,22,230,232,26,231,233,112,232,244,189,243,189,221,190,222,28,221,223,27,222,224,29,223,225,30,224,113,247,225,99,60,240,213,147,215,60,20,166,192,187,213,243,112,244,244,233,245,245,128,188,188,114,174,134,131,220,174,217,236,236,198,134,215,177,58,156,143,124,25,110,7,31,228,25,264,356,368,0,11,267,451,452,349,267,302,269,350,357,277,350,452,357,299,333,297,396,175,377,381,384,382,280,347,330,269,303,270,151,9,337,344,278,360,424,418,431,270,304,409,272,310,407,322,270,410,449,450,347,432,422,434,18,313,17,291,306,375,259,387,260,424,335,418,434,364,416,391,423,327,301,251,298,275,281,4,254,373,253,375,307,321,280,425,411,200,421,18,335,321,406,321,320,405,314,315,17,423,426,266,396,377,369,270,322,269,413,417,464,385,386,258,248,456,419,298,284,333,168,417,8,448,346,261,417,413,285,326,327,328,277,355,329,309,392,438,381,382,256,279,429,360,365,364,379,355,277,437,282,443,283,281,275,363,395,431,369,299,297,337,335,273,321,348,450,349,359,446,467,283,293,282,250,458,462,300,276,383,292,308,325,283,276,293,264,372,447,346,352,340,354,274,19,363,456,281,426,436,425,380,381,252,267,269,393,421,200,428,371,266,329,432,287,422,290,250,328,385,258,384,446,265,342,386,387,257,422,424,430,445,342,276,422,273,424,306,292,307,352,366,345,268,271,302,358,423,371,327,294,460,331,279,294,303,271,304,436,432,427,304,272,408,395,394,431,378,395,400,296,334,299,6,351,168,376,352,411,307,325,320,285,295,336,320,319,404,329,330,349,334,293,333,366,323,447,316,15,315,331,358,279,317,14,316,8,285,9,277,329,350,253,374,252,319,318,403,351,6,419,324,318,325,397,367,365,288,435,397,278,344,439,310,272,311,248,195,281,375,273,291,175,396,199,312,311,268,276,283,445,390,373,339,295,282,296,448,449,346,356,264,454,337,336,299,337,338,151,294,278,455,308,292,415,429,358,355,265,340,372,388,390,466,352,346,280,295,442,282,354,19,370,285,441,295,195,248,197,457,440,274,301,300,368,417,351,465,251,301,389,385,380,386,394,395,379,399,412,419,410,436,322,387,373,388,326,2,393,354,370,461,393,164,267,268,302,12,386,374,387,312,268,13,298,293,301,265,446,340,380,385,381,280,330,425,322,426,391,420,429,437,393,391,326,344,440,438,458,459,461,364,434,394,428,396,262,274,354,457,317,316,402,316,315,403,315,314,404,314,313,405,313,421,406,323,366,361,292,306,407,306,291,408,291,287,409,287,432,410,427,434,411,372,264,383,459,309,457,366,352,401,1,274,4,418,421,262,331,294,358,435,433,367,392,289,439,328,462,326,94,2,370,289,305,455,339,254,448,359,255,446,254,253,449,253,252,450,252,256,451,256,341,452,414,413,463,286,441,414,286,258,441,258,257,442,257,259,443,259,260,444,260,467,445,309,459,250,305,289,290,305,290,460,401,376,435,309,250,392,376,411,433,453,341,464,357,453,465,343,357,412,437,343,399,344,360,440,420,437,456,360,420,363,361,401,288,265,372,353,390,339,249,339,448,255];var p0e=[127,234,132,58,172,150,149,148,152,377,378,379,397,288,361,454,356,70,63,105,66,107,336,296,334,293,300,168,6,195,4,98,97,2,326,327,33,160,158,133,153,144,362,385,387,263,373,380,57,40,37,0,267,270,287,321,314,17,84,91,78,81,13,311,308,402,14,178],h0e=[33,133,362,263,1,62,308,159,145,386,374,6,102,331,2,13,14,70,105,107,336,334,300,54,10,284,50,280,234,454,58,288,152],f0e=[33,133,362,263,1,78,308],Tge=p0e.map(e=>Tp[e]),Nge=h0e.map(e=>Tp[e]),Ege=f0e.map(e=>Tp[e]);var g6=e=>({startPoint:_e(e,[0,0],[-1,2]),endPoint:_e(e,[0,2],[-1,2])});var Np=e=>[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])],i0=e=>[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2],qx=(e,t)=>e?[Math.trunc(Math.max(0,e.startPoint[0])),Math.trunc(Math.max(0,e.startPoint[1])),Math.trunc(Math.min(t.shape[2]||0,e.endPoint[0])-Math.max(0,e.startPoint[0])),Math.trunc(Math.min(t.shape[1]||0,e.endPoint[1])-Math.max(0,e.startPoint[1]))]:[0,0,0,0],Xx=(e,t)=>e?[e.startPoint[0]/(t.shape[2]||0),e.startPoint[1]/(t.shape[1]||0),(e.endPoint[0]-e.startPoint[0])/(t.shape[2]||0),(e.endPoint[1]-e.startPoint[1])/(t.shape[1]||0)]:[0,0,0,0],y6=(e,t)=>{let n=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],s=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]];return{startPoint:n,endPoint:s}},Kx=(e,t,n)=>{let s=t.shape[1],r=t.shape[2];return $e.cropAndResize(t,[[e.startPoint[1]/s,e.startPoint[0]/r,e.endPoint[1]/s,e.endPoint[0]/r]],[0],n)},Ep=(e,t=1.5)=>{let n=i0(e),s=Np(e),r=[t*s[0]/2,t*s[1]/2];return{startPoint:[n[0]-r[0],n[1]-r[1]],endPoint:[n[0]+r[0],n[1]+r[1]],landmarks:e.landmarks}},Rp=e=>{let t=i0(e),n=Np(e),s=Math.max(...n)/2;return{startPoint:[Math.round(t[0]-s),Math.round(t[1]-s)],endPoint:[Math.round(t[0]+s),Math.round(t[1]+s)],landmarks:e.landmarks}},l0=e=>{let t=e.map(s=>s[0]),n=e.map(s=>s[1]);return{startPoint:[Math.min(...t),Math.min(...n)],endPoint:[Math.max(...t),Math.max(...n)],landmarks:e}},u0=[[1,0,0],[0,1,0],[0,0,1]],m0e=e=>e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI)),g0e=(e,t)=>m0e(Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]));var A6=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]],Tl=(e,t)=>{let n=0;for(let s=0;s<e.length;s++)n+=e[s]*t[s];return n},y0e=(e,t)=>{let n=[];for(let s=0;s<e.length;s++)n.push(e[s][t]);return n},x6=(e,t)=>{let n=[],s=e.length;for(let r=0;r<s;r++){n.push([]);for(let a=0;a<s;a++)n[r].push(Tl(e[r],y0e(t,a)))}return n},b6=(e,t)=>{let n=Math.cos(e),s=Math.sin(e),r=[[n,-s,0],[s,n,0],[0,0,1]],a=A6(t[0],t[1]),o=x6(a,r),i=A6(-t[0],-t[1]);return x6(o,i)},A0e=e=>{let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],n=[e[0][2],e[1][2]],s=[-Tl(t[0],n),-Tl(t[1],n)];return[t[0].concat(s[0]),t[1].concat(s[1]),[0,0,1]]},x0e=(e,t)=>[Tl(e,t[0]),Tl(e,t[1])];function v6(e){let t={strides:[e/16,e/8],anchors:[2,6]},n=[];for(let s=0;s<t.strides.length;s++){let r=t.strides[s],a=Math.floor((e+r-1)/r),o=Math.floor((e+r-1)/r),i=t.anchors[s];for(let l=0;l<a;l++){let c=r*(l+.5);for(let u=0;u<o;u++){let d=r*(u+.5);for(let p=0;p<i;p++)n.push([d,c])}}}return n}function w6(e,t,n,s,r){let a=Np({startPoint:t.startPoint,endPoint:t.endPoint}),o=e.map(d=>[a[0]/r*(d[0]-r/2),a[1]/r*(d[1]-r/2),d[2]||0]),i=n!==0?b6(n,[0,0]):u0,l=n!==0?o.map(d=>[...x0e(d,i),d[2]]):o,c=n!==0?A0e(s):u0,u=[...i0({startPoint:t.startPoint,endPoint:t.endPoint}),1];return l.map(d=>[Math.round(d[0]+Tl(u,c[0])),Math.round(d[1]+Tl(u,c[1])),Math.round(d[2]||0)])}function Zx(e,t,n){let s=e.landmarks.length>=Hx.count?Hx.symmetryLine:Cp.symmetryLine,r=g0e(e.landmarks[s[0]],e.landmarks[s[1]]),a=i0({startPoint:e.startPoint,endPoint:e.endPoint}),o=[a[0]/t.shape[2],a[1]/t.shape[1]],i=$e.rotateWithOffset(t,r,0,o),l=b6(-r,a),c=Kx({startPoint:e.startPoint,endPoint:e.endPoint},i,[n,n]),u=fe(c,255);return te(c),te(i),[r,l,u]}var k6=6,Vs,Yx=[],I6=null,Us=0,$p=()=>Us;async function S6(e){var t;return ie.initial&&(Vs=null),Vs?e.debug&&ae("cached model:",Vs.modelUrl):(Vs=await ut(ct(e.modelBasePath,((t=e.face.detector)==null?void 0:t.modelPath)||"")),!Vs||!Vs.modelUrl?ae("load model failed:",e.body.modelPath):e.debug&&ae("load model:",Vs.modelUrl)),Us=Vs.inputs[0].shape?Vs.inputs[0].shape[2]:0,Us===-1&&(Us=64),Yx=v6(Us),I6=dr(Yx),Vs}function b0e(e){let t=_e(e,[0,1],[-1,2]),n=ue(t,I6),s=_e(e,[0,3],[-1,2]),r=fe(s,Us),a=fe(n,Us),o=fe(r,2),i=xe(a,o),l=ue(a,o),c=L(i,Us),u=L(l,Us);return Ru([c,u],1)}async function C6(e,t){var c,u,d,p;if(!e||e.isDisposedInternal||e.shape.length!==4||e.shape[1]<1||e.shape[2]<1)return{boxes:[]};let[n,s,r]=j(()=>{let h=$e.resizeBilinear(e,[Us,Us]),f=xe(fe(h,127.5),.5),m=Vs==null?void 0:Vs.execute(f),g;if(Array.isArray(m)){let b=m.sort((N,$)=>N.size-$.size),w=kt([b[0],b[2]],2),k=kt([b[1],b[3]],2),S=kt([k,w],1);g=dt(S,0)}else g=dt(m);let y=b0e(g),A=_e(g,[0,0],[-1,1]),x=dt(ns(A));return[g,y,x]}),a=await $e.nonMaxSuppressionAsync(s,r,((c=t.face.detector)==null?void 0:c.maxDetected)||0,((u=t.face.detector)==null?void 0:u.iouThreshold)||0,((d=t.face.detector)==null?void 0:d.minConfidence)||0),o=await a.array();te(a);let i=[],l=await r.data();for(let h=0;h<o.length;h++){let f=l[o[h]];if(f>(((p=t.face.detector)==null?void 0:p.minConfidence)||0)){let m=_e(s,[o[h],0],[1,-1]),g=j(()=>G(dt(_e(n,[o[h],k6-1],[1,-1])),[k6,-1]));i.push({box:g6(m),landmarks:g,anchor:Yx[o[h]],confidence:f}),te(m)}}return te(n),te(s),te(r),{boxes:i,scaleFactor:[e.shape[2]/Us,e.shape[1]/Us]}}var nr,Wo=0,v0e=2.3,Jx=Lr.leftEyeLower0,Qx=Lr.rightEyeLower0,Ac={leftBounds:[Jx[0],Jx[Jx.length-1]],rightBounds:[Qx[0],Qx[Qx.length-1]]},xc={upperCenter:3,lowerCenter:4,index:71,numCoordinates:76};async function T6(e){var t;return ie.initial&&(nr=null),nr?e.debug&&ae("cached model:",nr.modelUrl):(nr=await ut(ct(e.modelBasePath,((t=e.face.iris)==null?void 0:t.modelPath)||"")),!nr||!nr.modelUrl?ae("load model failed:",e.body.modelPath):e.debug&&ae("load model:",nr.modelUrl)),Wo=nr.inputs[0].shape?nr.inputs[0].shape[2]:0,Wo===-1&&(Wo=64),nr}function c0(e,t,n,s){for(let r=0;r<jx.length;r++){let{key:a,indices:o}=jx[r],i=Lr[`${n}${a}`];if(!s||s.includes(a))for(let l=0;l<o.length;l++){let c=o[l];e[i[l]]=[t[c][0],t[c][1],(t[c][2]+e[i[l]][2])/2]}}}var w0e=e=>{let t=e[Ac.leftBounds[0]][2],n=e[Ac.rightBounds[0]][2];return t-n},N6=(e,t,n,s,r=!1,a)=>{let o=Rp(Ep(l0([e[n],e[s]]),v0e)),i=Np(o),l=$e.cropAndResize(t,[[o.startPoint[1]/a,o.startPoint[0]/a,o.endPoint[1]/a,o.endPoint[0]/a]],[0],[Wo,Wo]);if(r&&ie.kernels.includes("flipleftright")){let c=$e.flipLeftRight(l);te(l),l=c}return{box:o,boxSize:i,crop:l}},E6=(e,t,n,s=!1)=>{let r=[];for(let a=0;a<xc.numCoordinates;a++){let o=e[a*3],i=e[a*3+1],l=e[a*3+2];r.push([(s?1-o/Wo:o/Wo)*n[0]+t.startPoint[0],i/Wo*n[1]+t.startPoint[1],l])}return{rawCoords:r,iris:r.slice(xc.index)}},R6=(e,t,n)=>{let s=e[Lr[`${n}EyeUpper0`][xc.upperCenter]][2],r=e[Lr[`${n}EyeLower0`][xc.lowerCenter]][2],a=(s+r)/2;return t.map((o,i)=>{let l=a;return i===2?l=s:i===4&&(l=r),[o[0],o[1],l]})};async function $6(e,t,n,s){if(!nr)return n.debug&&ae("face mesh iris detection requested, but model is not loaded"),e;let{box:r,boxSize:a,crop:o}=N6(e,t,Ac.leftBounds[0],Ac.leftBounds[1],!0,s),{box:i,boxSize:l,crop:c}=N6(e,t,Ac.rightBounds[0],Ac.rightBounds[1],!0,s),u=kt([o,c]);te(o),te(c);let d=nr.predict(u);te(u);let p=await d.data();te(d);let h=p.slice(0,xc.numCoordinates*3),{rawCoords:f,iris:m}=E6(h,r,a,!0),g=p.slice(xc.numCoordinates*3),{rawCoords:y,iris:A}=E6(g,i,l),x=w0e(e);Math.abs(x)<30?(c0(e,f,"left",null),c0(e,y,"right",null)):x<1?c0(e,f,"left",["EyeUpper0","EyeLower0"]):c0(e,y,"right",["EyeUpper0","EyeLower0"]);let b=R6(e,m,"left"),w=R6(e,A,"right");return e.concat(b).concat(w)}var Br=[],sr=null,vr=0,eb=Number.MAX_SAFE_INTEGER,D6=0;async function _6(e,t){var a,o,i,l,c,u,d,p,h,f,m,g;if(!t.skipFrame||(D6!==((a=t.face.detector)==null?void 0:a.maxDetected)||!((o=t.face.mesh)==null?void 0:o.enabled))&&eb>(((i=t.face.detector)==null?void 0:i.skipFrames)||0)){let y=await C6(e,t);Br=[];for(let A of y.boxes){let x=await A.box.startPoint.data(),b=await A.box.endPoint.data(),w=await A.landmarks.array();Br.push({startPoint:x,endPoint:b,landmarks:w,confidence:A.confidence})}y.boxes.forEach(A=>te([A.box.startPoint,A.box.endPoint,A.landmarks]));for(let A=0;A<Br.length;A++){let x=y6({startPoint:Br[A].startPoint,endPoint:Br[A].endPoint},y.scaleFactor),b=Ep(x),w=Rp(b);Br[A]={...w,confidence:Br[A].confidence,landmarks:Br[A].landmarks}}eb=0}else eb++;let n=[],s=[],r=0;for(let y of Br){let A=0,x,b={id:r++,mesh:[],meshRaw:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,boxScore:0,faceScore:0,annotations:{}};if(((l=t.face.detector)==null?void 0:l.rotation)&&((c=t.face.mesh)==null?void 0:c.enabled)&&ie.kernels.includes("rotatewithoffset"))[A,x,b.tensor]=Zx(y,e,vr);else{x=u0;let w=Kx({startPoint:y.startPoint,endPoint:y.endPoint},e,((u=t.face.mesh)==null?void 0:u.enabled)?[vr,vr]:[$p(),$p()]);b.tensor=fe(w,255),te(w)}if(b.boxScore=Math.round(100*y.confidence)/100,(d=t.face.mesh)==null?void 0:d.enabled)if(!sr)t.debug&&ae("face mesh detection requested, but model is not loaded");else{let[w,k,S]=sr.execute(b.tensor);te(w);let N=(await k.data())[0];te(k);let $=G(S,[-1,3]),F=await $.array();if(te(S),te($),N<(((p=t.face.detector)==null?void 0:p.minConfidence)||1))y.confidence=N;else{((h=t.face.iris)==null?void 0:h.enabled)&&(F=await $6(F,b.tensor,t,vr)),b.mesh=w6(F,y,A,x,vr),b.meshRaw=b.mesh.map(R=>[R[0]/(e.shape[2]||0),R[1]/(e.shape[1]||0),(R[2]||0)/vr]),y={...Ep(l0(b.mesh),1.5),confidence:y.confidence};for(let R of Object.keys(Lr))b.annotations[R]=Lr[R].map(D=>b.mesh[D]);((f=t.face.detector)==null?void 0:f.rotation)&&t.face.mesh.enabled&&((m=t.face.description)==null?void 0:m.enabled)&&ie.kernels.includes("rotatewithoffset")&&(te(b.tensor),[A,x,b.tensor]=Zx(y,e,vr)),b.box=qx(y,e),b.boxRaw=Xx(y,e),b.score=Math.round(100*N||100*y.confidence||0)/100,b.faceScore=Math.round(100*N)/100,y={...Rp(y),confidence:y.confidence,faceConfidence:N}}}else{b.box=qx(y,e),b.boxRaw=Xx(y,e),b.score=Math.round(100*y.confidence||0)/100,b.mesh=y.landmarks.map(w=>[(y.startPoint[0]+y.endPoint[0])/2+(y.endPoint[0]+y.startPoint[0])*w[0]/$p(),(y.startPoint[1]+y.endPoint[1])/2+(y.endPoint[1]+y.startPoint[1])*w[1]/$p()]),b.meshRaw=b.mesh.map(w=>[w[0]/(e.shape[2]||0),w[1]/(e.shape[1]||0),(w[2]||0)/vr]);for(let w of Object.keys(Cp))b.annotations[w]=[b.mesh[Cp[w]]]}n.push(b),s.push(y)}return((g=t.face.mesh)==null?void 0:g.enabled)&&(Br=s.filter(y=>{var A;return y.confidence>(((A=t.face.detector)==null?void 0:A.minConfidence)||0)})),D6=n.length,n}async function P6(e){var t;return ie.initial&&(sr=null),sr?e.debug&&ae("cached model:",sr.modelUrl):(sr=await ut(ct(e.modelBasePath,((t=e.face.mesh)==null?void 0:t.modelPath)||"")),!sr||!sr.modelUrl?ae("load model failed:",e.body.modelPath):e.debug&&ae("load model:",sr.modelUrl)),vr=sr.inputs[0].shape?sr.inputs[0].shape[2]:0,vr===-1&&(vr=64),sr}var F6=Cl,O6=Tp;var Kn,d0=[],M6=0,tb=Number.MAX_SAFE_INTEGER;async function z6(e){var n,s;let t=ct(e.modelBasePath,((n=e.face.description)==null?void 0:n.modelPath)||"");return ie.initial&&(Kn=null),Kn?e.debug&&ae("cached model:",t):(Kn=await ut(t),Kn?e.debug&&ae("load model:",t):ae("load model failed:",((s=e.face.description)==null?void 0:s.modelPath)||"")),Kn}function nb(e){return j(()=>{let n=e.image||e.tensor||e;if(!(n instanceof Ke))return null;let s=[[.05,.15,.85,.85]];if(!(Kn==null?void 0:Kn.inputs[0].shape))return null;let r=n.shape.length===3?$e.cropAndResize(jt(n,0),s,[0],[Kn.inputs[0].shape[2],Kn.inputs[0].shape[1]]):$e.cropAndResize(n,s,[0],[Kn.inputs[0].shape[2],Kn.inputs[0].shape[1]]);return L(r,255)})}async function sb(e,t,n,s){var r,a,o;return Kn?tb<(((r=t.face.description)==null?void 0:r.skipFrames)||0)&&t.skipFrame&&M6===s&&((a=d0[n])==null?void 0:a.age)&&((o=d0[n])==null?void 0:o.age)>0?(tb++,d0[n]):(tb=0,new Promise(async i=>{var d,p;let l=nb(e),c,u={age:0,gender:"unknown",genderScore:0,descriptor:[]};if(((d=t.face.description)==null?void 0:d.enabled)&&(c=await(Kn==null?void 0:Kn.predict(l))),te(l),c){let h=await c.find(b=>b.shape[1]===1).data(),f=Math.trunc(200*Math.abs(h[0]-.5))/100;f>(((p=t.face.description)==null?void 0:p.minConfidence)||0)&&(u.gender=h[0]<=.5?"female":"male",u.genderScore=Math.min(.99,f));let m=Fs(c.find(b=>b.shape[1]===100),1),g=(await m.data())[0];te(m);let y=await c.find(b=>b.shape[1]===100).data();u.age=Math.round(y[g-1]>y[g+1]?10*g-100*y[g-1]:10*g+100*y[g+1])/10;let x=await c.find(b=>b.shape[1]===1024).data();u.descriptor=[...x],c.forEach(b=>te(b))}d0[n]=u,M6=s,i(u)})):null}var k0e=["angry","disgust","fear","happy","sad","surprise","neutral"],un,p0=[],L6=0,rb=Number.MAX_SAFE_INTEGER,ab=[.2989,.587,.114];async function B6(e){var t;return ie.initial&&(un=null),un?e.debug&&ae("cached model:",un.modelUrl):(un=await ut(ct(e.modelBasePath,((t=e.face.emotion)==null?void 0:t.modelPath)||"")),!un||!un.modelUrl?ae("load model failed:",e.body.modelPath):e.debug&&ae("load model:",un.modelUrl)),un}async function ob(e,t,n,s){var r;return un?rb<(((r=t.face.emotion)==null?void 0:r.skipFrames)||0)&&t.skipFrame&&L6===s&&p0[n]&&p0[n].length>0?(rb++,p0[n]):(rb=0,new Promise(async a=>{var g,y;let o=$e.resizeBilinear(e,[(un==null?void 0:un.inputs[0].shape)?un.inputs[0].shape[2]:0,(un==null?void 0:un.inputs[0].shape)?un.inputs[0].shape[1]:0],!1),[i,l,c]=xn(o,3,3);te(o);let u=L(i,ab[0]),d=L(l,ab[1]),p=L(c,ab[2]);te(i),te(l),te(c);let h=nf([u,d,p]);te(u),te(d),te(p);let f=j(()=>L(xe(h,.5),2));te(h);let m=[];if((g=t.face.emotion)==null?void 0:g.enabled){let A=await(un==null?void 0:un.predict(f)),x=await A.data();te(A);for(let b=0;b<x.length;b++)x[b]>(((y=t.face.emotion)==null?void 0:y.minConfidence)||0)&&m.push({score:Math.min(.99,Math.trunc(100*x[b])/100),emotion:k0e[b]});m.sort((b,w)=>w.score-b.score)}te(f),p0[n]=m,L6=s,a(m)})):null}var Dp=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],I0e=Dp.length,_p=Dp.reduce((e,t,n)=>(e[t]=n,e),{}),S0e=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]],i2e=S0e.map(([e,t])=>[_p[e],_p[t]]),W6=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]];function V6(e){let t=e.reduce(({maxX:n,maxY:s,minX:r,minY:a},{position:{x:o,y:i}})=>({maxX:Math.max(n,o),maxY:Math.max(s,i),minX:Math.min(r,o),minY:Math.min(a,i)}),{maxX:Number.NEGATIVE_INFINITY,maxY:Number.NEGATIVE_INFINITY,minX:Number.POSITIVE_INFINITY,minY:Number.POSITIVE_INFINITY});return[t.minX,t.minY,t.maxX-t.minX,t.maxY-t.minY]}function U6(e,[t,n],[s,r]){let a=t/s,o=n/r,i=(c,u)=>({id:u,score:c.score,boxRaw:[c.box[0]/r,c.box[1]/s,c.box[2]/r,c.box[3]/s],box:[Math.trunc(c.box[0]*o),Math.trunc(c.box[1]*a),Math.trunc(c.box[2]*o),Math.trunc(c.box[3]*a)],keypoints:c.keypoints.map(({score:d,part:p,position:h})=>({score:d,part:p,position:[Math.trunc(h.x*o),Math.trunc(h.y*a)],positionRaw:[h.x/s,h.y/s]}))});return e.map((c,u)=>i(c,u))}var ib=class{constructor(t,n){ve(this,"priorityQueue");ve(this,"numberOfElements");ve(this,"getElementValue");this.priorityQueue=new Array(t),this.numberOfElements=-1,this.getElementValue=n}enqueue(t){this.priorityQueue[++this.numberOfElements]=t,this.swim(this.numberOfElements)}dequeue(){let t=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,t}empty(){return this.numberOfElements===-1}size(){return this.numberOfElements+1}all(){return this.priorityQueue.slice(0,this.numberOfElements+1)}max(){return this.priorityQueue[0]}swim(t){for(;t>0&&this.less(Math.floor(t/2),t);)this.exchange(t,Math.floor(t/2)),t=Math.floor(t/2)}sink(t){for(;2*t<=this.numberOfElements;){let n=2*t;if(n<this.numberOfElements&&this.less(n,n+1)&&n++,!this.less(t,n))break;this.exchange(t,n),t=n}}getValueAt(t){return this.getElementValue(this.priorityQueue[t])}less(t,n){return this.getValueAt(t)<this.getValueAt(n)}exchange(t,n){let s=this.priorityQueue[t];this.priorityQueue[t]=this.priorityQueue[n],this.priorityQueue[n]=s}};function lb(e,t,n,s){return{y:s.get(e,t,n),x:s.get(e,t,n+I0e)}}function ub(e,t,n){let{heatmapY:s,heatmapX:r,id:a}=e,{y:o,x:i}=lb(s,r,a,n);return{x:e.heatmapX*t+i,y:e.heatmapY*t+o}}function cb(e,t,n){return e<t?t:e>n?n:e}function G6(e,t,n,s){let r=n-e,a=s-t;return r*r+a*a}function db(e,t){return{x:e.x+t.x,y:e.y+t.y}}var Ns,C0e=["MobilenetV1/offset_2/BiasAdd","MobilenetV1/heatmap_2/BiasAdd","MobilenetV1/displacement_fwd_2/BiasAdd","MobilenetV1/displacement_bwd_2/BiasAdd"],h0=1,bc=16,T0e=50**2;function H6(e,t,n,s,r,a,o=2){let i=y=>({y:a.get(y.y,y.x,e),x:a.get(y.y,y.x,a.shape[2]/2+e)}),l=(y,A,x)=>({y:cb(Math.round(y.y/bc),0,A-1),x:cb(Math.round(y.x/bc),0,x-1)}),[c,u]=s.shape,d=l(t.position,c,u),p=i(d),f=db(t.position,p);for(let y=0;y<o;y++){let A=l(f,c,u),x=lb(A.y,A.x,n,r);f=db({x:A.x*bc,y:A.y*bc},{x:x.x,y:x.y})}let m=l(f,c,u),g=s.get(m.y,m.x,n);return{position:f,part:Dp[n],score:g}}function N0e(e,t,n,s,r){let a=W6.map(([p,h])=>[_p[p],_p[h]]),o=a.map(([,p])=>p),i=a.map(([p])=>p),l=t.shape[2],c=o.length,u=new Array(l),d=ub(e.part,bc,n);u[e.part.id]={score:e.score,part:Dp[e.part.id],position:d};for(let p=c-1;p>=0;--p){let h=o[p],f=i[p];u[h]&&!u[f]&&(u[f]=H6(p,u[h],f,t,n,r))}for(let p=0;p<c;++p){let h=i[p],f=o[p];u[h]&&!u[f]&&(u[f]=H6(p,u[h],f,t,n,s))}return u}function E0e(e,t,n,s,r){let[a,o]=r.shape,i=!0,l=Math.max(n-h0,0),c=Math.min(n+h0+1,a);for(let u=l;u<c;++u){let d=Math.max(s-h0,0),p=Math.min(s+h0+1,o);for(let h=d;h<p;++h)if(r.get(u,h,e)>t){i=!1;break}if(!i)break}return i}function R0e(e,t){let[n,s,r]=t.shape,a=new ib(n*s*r,({score:o})=>o);for(let o=0;o<n;++o)for(let i=0;i<s;++i)for(let l=0;l<r;++l){let c=t.get(o,i,l);c<e||E0e(l,c,o,i,t)&&a.enqueue({score:c,part:{heatmapY:o,heatmapX:i,id:l}})}return a}function j6(e,{x:t,y:n},s){return e.some(({keypoints:r})=>{var o;let a=(o=r[s])==null?void 0:o.position;return a?G6(n,t,a.y,a.x)<=T0e:!1})}function $0e(e,t){return t.reduce((s,{position:r,score:a},o)=>(j6(e,r,o)||(s+=a),s),0)/t.length}function D0e(e,t,n,s,r,a){let o=[],i=R0e(a,t);for(;o.length<r&&!i.empty();){let l=i.dequeue(),c=ub(l.part,bc,e);if(j6(o,c,l.part.id))continue;let u=N0e(l,t,e,n,s);u=u.filter(h=>h.score>a);let d=$0e(o,u),p=V6(u);d>a&&o.push({keypoints:u,box:p,score:Math.round(100*d)/100})}return o}async function pb(e,t){let n=j(()=>{if(!Ns.inputs[0].shape)return[];let o=$e.resizeBilinear(e,[Ns.inputs[0].shape[2],Ns.inputs[0].shape[1]]),i=xe(fe(pe(o,"float32"),127.5),1),c=Ns.execute(i,C0e).map(u=>dt(u,[0]));return c[1]=c[1].sigmoid(),c}),s=await Promise.all(n.map(o=>o.buffer()));for(let o of n)te(o);let r=await D0e(s[0],s[1],s[2],s[3],t.body.maxDetected,t.body.minConfidence);return Ns.inputs[0].shape?U6(r,[e.shape[1],e.shape[2]],[Ns.inputs[0].shape[2],Ns.inputs[0].shape[1]]):[]}async function q6(e){return!Ns||ie.initial?(Ns=await ut(ct(e.modelBasePath,e.body.modelPath||"")),!Ns||!Ns.modelUrl?ae("load model failed:",e.body.modelPath):e.debug&&ae("load model:",Ns.modelUrl)):e.debug&&ae("cached model:",Ns.modelUrl),Ns}function f0(e){return[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])]}function Pp(e){return[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2]}function X6(e,t,n){let s=t.shape[1],r=t.shape[2],a=[[e.startPoint[1]/s,e.startPoint[0]/r,e.endPoint[1]/s,e.endPoint[0]/r]];return $e.cropAndResize(t,a,[0],n)}function K6(e,t){let n=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],s=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]],r=e.palmLandmarks.map(a=>[a[0]*t[0],a[1]*t[1]]);return{startPoint:n,endPoint:s,palmLandmarks:r,confidence:e.confidence}}function m0(e,t=1.5){let n=Pp(e),s=f0(e),r=[t*s[0]/2,t*s[1]/2],a=[n[0]-r[0],n[1]-r[1]],o=[n[0]+r[0],n[1]+r[1]];return{startPoint:a,endPoint:o,palmLandmarks:e.palmLandmarks}}function g0(e){let t=Pp(e),n=f0(e),r=Math.max(...n)/2,a=[t[0]-r,t[1]-r],o=[t[0]+r,t[1]+r];return{startPoint:a,endPoint:o,palmLandmarks:e.palmLandmarks}}var Z6=[{x:.015625,y:.015625},{x:.015625,y:.015625},{x:.046875,y:.015625},{x:.046875,y:.015625},{x:.078125,y:.015625},{x:.078125,y:.015625},{x:.109375,y:.015625},{x:.109375,y:.015625},{x:.140625,y:.015625},{x:.140625,y:.015625},{x:.171875,y:.015625},{x:.171875,y:.015625},{x:.203125,y:.015625},{x:.203125,y:.015625},{x:.234375,y:.015625},{x:.234375,y:.015625},{x:.265625,y:.015625},{x:.265625,y:.015625},{x:.296875,y:.015625},{x:.296875,y:.015625},{x:.328125,y:.015625},{x:.328125,y:.015625},{x:.359375,y:.015625},{x:.359375,y:.015625},{x:.390625,y:.015625},{x:.390625,y:.015625},{x:.421875,y:.015625},{x:.421875,y:.015625},{x:.453125,y:.015625},{x:.453125,y:.015625},{x:.484375,y:.015625},{x:.484375,y:.015625},{x:.515625,y:.015625},{x:.515625,y:.015625},{x:.546875,y:.015625},{x:.546875,y:.015625},{x:.578125,y:.015625},{x:.578125,y:.015625},{x:.609375,y:.015625},{x:.609375,y:.015625},{x:.640625,y:.015625},{x:.640625,y:.015625},{x:.671875,y:.015625},{x:.671875,y:.015625},{x:.703125,y:.015625},{x:.703125,y:.015625},{x:.734375,y:.015625},{x:.734375,y:.015625},{x:.765625,y:.015625},{x:.765625,y:.015625},{x:.796875,y:.015625},{x:.796875,y:.015625},{x:.828125,y:.015625},{x:.828125,y:.015625},{x:.859375,y:.015625},{x:.859375,y:.015625},{x:.890625,y:.015625},{x:.890625,y:.015625},{x:.921875,y:.015625},{x:.921875,y:.015625},{x:.953125,y:.015625},{x:.953125,y:.015625},{x:.984375,y:.015625},{x:.984375,y:.015625},{x:.015625,y:.046875},{x:.015625,y:.046875},{x:.046875,y:.046875},{x:.046875,y:.046875},{x:.078125,y:.046875},{x:.078125,y:.046875},{x:.109375,y:.046875},{x:.109375,y:.046875},{x:.140625,y:.046875},{x:.140625,y:.046875},{x:.171875,y:.046875},{x:.171875,y:.046875},{x:.203125,y:.046875},{x:.203125,y:.046875},{x:.234375,y:.046875},{x:.234375,y:.046875},{x:.265625,y:.046875},{x:.265625,y:.046875},{x:.296875,y:.046875},{x:.296875,y:.046875},{x:.328125,y:.046875},{x:.328125,y:.046875},{x:.359375,y:.046875},{x:.359375,y:.046875},{x:.390625,y:.046875},{x:.390625,y:.046875},{x:.421875,y:.046875},{x:.421875,y:.046875},{x:.453125,y:.046875},{x:.453125,y:.046875},{x:.484375,y:.046875},{x:.484375,y:.046875},{x:.515625,y:.046875},{x:.515625,y:.046875},{x:.546875,y:.046875},{x:.546875,y:.046875},{x:.578125,y:.046875},{x:.578125,y:.046875},{x:.609375,y:.046875},{x:.609375,y:.046875},{x:.640625,y:.046875},{x:.640625,y:.046875},{x:.671875,y:.046875},{x:.671875,y:.046875},{x:.703125,y:.046875},{x:.703125,y:.046875},{x:.734375,y:.046875},{x:.734375,y:.046875},{x:.765625,y:.046875},{x:.765625,y:.046875},{x:.796875,y:.046875},{x:.796875,y:.046875},{x:.828125,y:.046875},{x:.828125,y:.046875},{x:.859375,y:.046875},{x:.859375,y:.046875},{x:.890625,y:.046875},{x:.890625,y:.046875},{x:.921875,y:.046875},{x:.921875,y:.046875},{x:.953125,y:.046875},{x:.953125,y:.046875},{x:.984375,y:.046875},{x:.984375,y:.046875},{x:.015625,y:.078125},{x:.015625,y:.078125},{x:.046875,y:.078125},{x:.046875,y:.078125},{x:.078125,y:.078125},{x:.078125,y:.078125},{x:.109375,y:.078125},{x:.109375,y:.078125},{x:.140625,y:.078125},{x:.140625,y:.078125},{x:.171875,y:.078125},{x:.171875,y:.078125},{x:.203125,y:.078125},{x:.203125,y:.078125},{x:.234375,y:.078125},{x:.234375,y:.078125},{x:.265625,y:.078125},{x:.265625,y:.078125},{x:.296875,y:.078125},{x:.296875,y:.078125},{x:.328125,y:.078125},{x:.328125,y:.078125},{x:.359375,y:.078125},{x:.359375,y:.078125},{x:.390625,y:.078125},{x:.390625,y:.078125},{x:.421875,y:.078125},{x:.421875,y:.078125},{x:.453125,y:.078125},{x:.453125,y:.078125},{x:.484375,y:.078125},{x:.484375,y:.078125},{x:.515625,y:.078125},{x:.515625,y:.078125},{x:.546875,y:.078125},{x:.546875,y:.078125},{x:.578125,y:.078125},{x:.578125,y:.078125},{x:.609375,y:.078125},{x:.609375,y:.078125},{x:.640625,y:.078125},{x:.640625,y:.078125},{x:.671875,y:.078125},{x:.671875,y:.078125},{x:.703125,y:.078125},{x:.703125,y:.078125},{x:.734375,y:.078125},{x:.734375,y:.078125},{x:.765625,y:.078125},{x:.765625,y:.078125},{x:.796875,y:.078125},{x:.796875,y:.078125},{x:.828125,y:.078125},{x:.828125,y:.078125},{x:.859375,y:.078125},{x:.859375,y:.078125},{x:.890625,y:.078125},{x:.890625,y:.078125},{x:.921875,y:.078125},{x:.921875,y:.078125},{x:.953125,y:.078125},{x:.953125,y:.078125},{x:.984375,y:.078125},{x:.984375,y:.078125},{x:.015625,y:.109375},{x:.015625,y:.109375},{x:.046875,y:.109375},{x:.046875,y:.109375},{x:.078125,y:.109375},{x:.078125,y:.109375},{x:.109375,y:.109375},{x:.109375,y:.109375},{x:.140625,y:.109375},{x:.140625,y:.109375},{x:.171875,y:.109375},{x:.171875,y:.109375},{x:.203125,y:.109375},{x:.203125,y:.109375},{x:.234375,y:.109375},{x:.234375,y:.109375},{x:.265625,y:.109375},{x:.265625,y:.109375},{x:.296875,y:.109375},{x:.296875,y:.109375},{x:.328125,y:.109375},{x:.328125,y:.109375},{x:.359375,y:.109375},{x:.359375,y:.109375},{x:.390625,y:.109375},{x:.390625,y:.109375},{x:.421875,y:.109375},{x:.421875,y:.109375},{x:.453125,y:.109375},{x:.453125,y:.109375},{x:.484375,y:.109375},{x:.484375,y:.109375},{x:.515625,y:.109375},{x:.515625,y:.109375},{x:.546875,y:.109375},{x:.546875,y:.109375},{x:.578125,y:.109375},{x:.578125,y:.109375},{x:.609375,y:.109375},{x:.609375,y:.109375},{x:.640625,y:.109375},{x:.640625,y:.109375},{x:.671875,y:.109375},{x:.671875,y:.109375},{x:.703125,y:.109375},{x:.703125,y:.109375},{x:.734375,y:.109375},{x:.734375,y:.109375},{x:.765625,y:.109375},{x:.765625,y:.109375},{x:.796875,y:.109375},{x:.796875,y:.109375},{x:.828125,y:.109375},{x:.828125,y:.109375},{x:.859375,y:.109375},{x:.859375,y:.109375},{x:.890625,y:.109375},{x:.890625,y:.109375},{x:.921875,y:.109375},{x:.921875,y:.109375},{x:.953125,y:.109375},{x:.953125,y:.109375},{x:.984375,y:.109375},{x:.984375,y:.109375},{x:.015625,y:.140625},{x:.015625,y:.140625},{x:.046875,y:.140625},{x:.046875,y:.140625},{x:.078125,y:.140625},{x:.078125,y:.140625},{x:.109375,y:.140625},{x:.109375,y:.140625},{x:.140625,y:.140625},{x:.140625,y:.140625},{x:.171875,y:.140625},{x:.171875,y:.140625},{x:.203125,y:.140625},{x:.203125,y:.140625},{x:.234375,y:.140625},{x:.234375,y:.140625},{x:.265625,y:.140625},{x:.265625,y:.140625},{x:.296875,y:.140625},{x:.296875,y:.140625},{x:.328125,y:.140625},{x:.328125,y:.140625},{x:.359375,y:.140625},{x:.359375,y:.140625},{x:.390625,y:.140625},{x:.390625,y:.140625},{x:.421875,y:.140625},{x:.421875,y:.140625},{x:.453125,y:.140625},{x:.453125,y:.140625},{x:.484375,y:.140625},{x:.484375,y:.140625},{x:.515625,y:.140625},{x:.515625,y:.140625},{x:.546875,y:.140625},{x:.546875,y:.140625},{x:.578125,y:.140625},{x:.578125,y:.140625},{x:.609375,y:.140625},{x:.609375,y:.140625},{x:.640625,y:.140625},{x:.640625,y:.140625},{x:.671875,y:.140625},{x:.671875,y:.140625},{x:.703125,y:.140625},{x:.703125,y:.140625},{x:.734375,y:.140625},{x:.734375,y:.140625},{x:.765625,y:.140625},{x:.765625,y:.140625},{x:.796875,y:.140625},{x:.796875,y:.140625},{x:.828125,y:.140625},{x:.828125,y:.140625},{x:.859375,y:.140625},{x:.859375,y:.140625},{x:.890625,y:.140625},{x:.890625,y:.140625},{x:.921875,y:.140625},{x:.921875,y:.140625},{x:.953125,y:.140625},{x:.953125,y:.140625},{x:.984375,y:.140625},{x:.984375,y:.140625},{x:.015625,y:.171875},{x:.015625,y:.171875},{x:.046875,y:.171875},{x:.046875,y:.171875},{x:.078125,y:.171875},{x:.078125,y:.171875},{x:.109375,y:.171875},{x:.109375,y:.171875},{x:.140625,y:.171875},{x:.140625,y:.171875},{x:.171875,y:.171875},{x:.171875,y:.171875},{x:.203125,y:.171875},{x:.203125,y:.171875},{x:.234375,y:.171875},{x:.234375,y:.171875},{x:.265625,y:.171875},{x:.265625,y:.171875},{x:.296875,y:.171875},{x:.296875,y:.171875},{x:.328125,y:.171875},{x:.328125,y:.171875},{x:.359375,y:.171875},{x:.359375,y:.171875},{x:.390625,y:.171875},{x:.390625,y:.171875},{x:.421875,y:.171875},{x:.421875,y:.171875},{x:.453125,y:.171875},{x:.453125,y:.171875},{x:.484375,y:.171875},{x:.484375,y:.171875},{x:.515625,y:.171875},{x:.515625,y:.171875},{x:.546875,y:.171875},{x:.546875,y:.171875},{x:.578125,y:.171875},{x:.578125,y:.171875},{x:.609375,y:.171875},{x:.609375,y:.171875},{x:.640625,y:.171875},{x:.640625,y:.171875},{x:.671875,y:.171875},{x:.671875,y:.171875},{x:.703125,y:.171875},{x:.703125,y:.171875},{x:.734375,y:.171875},{x:.734375,y:.171875},{x:.765625,y:.171875},{x:.765625,y:.171875},{x:.796875,y:.171875},{x:.796875,y:.171875},{x:.828125,y:.171875},{x:.828125,y:.171875},{x:.859375,y:.171875},{x:.859375,y:.171875},{x:.890625,y:.171875},{x:.890625,y:.171875},{x:.921875,y:.171875},{x:.921875,y:.171875},{x:.953125,y:.171875},{x:.953125,y:.171875},{x:.984375,y:.171875},{x:.984375,y:.171875},{x:.015625,y:.203125},{x:.015625,y:.203125},{x:.046875,y:.203125},{x:.046875,y:.203125},{x:.078125,y:.203125},{x:.078125,y:.203125},{x:.109375,y:.203125},{x:.109375,y:.203125},{x:.140625,y:.203125},{x:.140625,y:.203125},{x:.171875,y:.203125},{x:.171875,y:.203125},{x:.203125,y:.203125},{x:.203125,y:.203125},{x:.234375,y:.203125},{x:.234375,y:.203125},{x:.265625,y:.203125},{x:.265625,y:.203125},{x:.296875,y:.203125},{x:.296875,y:.203125},{x:.328125,y:.203125},{x:.328125,y:.203125},{x:.359375,y:.203125},{x:.359375,y:.203125},{x:.390625,y:.203125},{x:.390625,y:.203125},{x:.421875,y:.203125},{x:.421875,y:.203125},{x:.453125,y:.203125},{x:.453125,y:.203125},{x:.484375,y:.203125},{x:.484375,y:.203125},{x:.515625,y:.203125},{x:.515625,y:.203125},{x:.546875,y:.203125},{x:.546875,y:.203125},{x:.578125,y:.203125},{x:.578125,y:.203125},{x:.609375,y:.203125},{x:.609375,y:.203125},{x:.640625,y:.203125},{x:.640625,y:.203125},{x:.671875,y:.203125},{x:.671875,y:.203125},{x:.703125,y:.203125},{x:.703125,y:.203125},{x:.734375,y:.203125},{x:.734375,y:.203125},{x:.765625,y:.203125},{x:.765625,y:.203125},{x:.796875,y:.203125},{x:.796875,y:.203125},{x:.828125,y:.203125},{x:.828125,y:.203125},{x:.859375,y:.203125},{x:.859375,y:.203125},{x:.890625,y:.203125},{x:.890625,y:.203125},{x:.921875,y:.203125},{x:.921875,y:.203125},{x:.953125,y:.203125},{x:.953125,y:.203125},{x:.984375,y:.203125},{x:.984375,y:.203125},{x:.015625,y:.234375},{x:.015625,y:.234375},{x:.046875,y:.234375},{x:.046875,y:.234375},{x:.078125,y:.234375},{x:.078125,y:.234375},{x:.109375,y:.234375},{x:.109375,y:.234375},{x:.140625,y:.234375},{x:.140625,y:.234375},{x:.171875,y:.234375},{x:.171875,y:.234375},{x:.203125,y:.234375},{x:.203125,y:.234375},{x:.234375,y:.234375},{x:.234375,y:.234375},{x:.265625,y:.234375},{x:.265625,y:.234375},{x:.296875,y:.234375},{x:.296875,y:.234375},{x:.328125,y:.234375},{x:.328125,y:.234375},{x:.359375,y:.234375},{x:.359375,y:.234375},{x:.390625,y:.234375},{x:.390625,y:.234375},{x:.421875,y:.234375},{x:.421875,y:.234375},{x:.453125,y:.234375},{x:.453125,y:.234375},{x:.484375,y:.234375},{x:.484375,y:.234375},{x:.515625,y:.234375},{x:.515625,y:.234375},{x:.546875,y:.234375},{x:.546875,y:.234375},{x:.578125,y:.234375},{x:.578125,y:.234375},{x:.609375,y:.234375},{x:.609375,y:.234375},{x:.640625,y:.234375},{x:.640625,y:.234375},{x:.671875,y:.234375},{x:.671875,y:.234375},{x:.703125,y:.234375},{x:.703125,y:.234375},{x:.734375,y:.234375},{x:.734375,y:.234375},{x:.765625,y:.234375},{x:.765625,y:.234375},{x:.796875,y:.234375},{x:.796875,y:.234375},{x:.828125,y:.234375},{x:.828125,y:.234375},{x:.859375,y:.234375},{x:.859375,y:.234375},{x:.890625,y:.234375},{x:.890625,y:.234375},{x:.921875,y:.234375},{x:.921875,y:.234375},{x:.953125,y:.234375},{x:.953125,y:.234375},{x:.984375,y:.234375},{x:.984375,y:.234375},{x:.015625,y:.265625},{x:.015625,y:.265625},{x:.046875,y:.265625},{x:.046875,y:.265625},{x:.078125,y:.265625},{x:.078125,y:.265625},{x:.109375,y:.265625},{x:.109375,y:.265625},{x:.140625,y:.265625},{x:.140625,y:.265625},{x:.171875,y:.265625},{x:.171875,y:.265625},{x:.203125,y:.265625},{x:.203125,y:.265625},{x:.234375,y:.265625},{x:.234375,y:.265625},{x:.265625,y:.265625},{x:.265625,y:.265625},{x:.296875,y:.265625},{x:.296875,y:.265625},{x:.328125,y:.265625},{x:.328125,y:.265625},{x:.359375,y:.265625},{x:.359375,y:.265625},{x:.390625,y:.265625},{x:.390625,y:.265625},{x:.421875,y:.265625},{x:.421875,y:.265625},{x:.453125,y:.265625},{x:.453125,y:.265625},{x:.484375,y:.265625},{x:.484375,y:.265625},{x:.515625,y:.265625},{x:.515625,y:.265625},{x:.546875,y:.265625},{x:.546875,y:.265625},{x:.578125,y:.265625},{x:.578125,y:.265625},{x:.609375,y:.265625},{x:.609375,y:.265625},{x:.640625,y:.265625},{x:.640625,y:.265625},{x:.671875,y:.265625},{x:.671875,y:.265625},{x:.703125,y:.265625},{x:.703125,y:.265625},{x:.734375,y:.265625},{x:.734375,y:.265625},{x:.765625,y:.265625},{x:.765625,y:.265625},{x:.796875,y:.265625},{x:.796875,y:.265625},{x:.828125,y:.265625},{x:.828125,y:.265625},{x:.859375,y:.265625},{x:.859375,y:.265625},{x:.890625,y:.265625},{x:.890625,y:.265625},{x:.921875,y:.265625},{x:.921875,y:.265625},{x:.953125,y:.265625},{x:.953125,y:.265625},{x:.984375,y:.265625},{x:.984375,y:.265625},{x:.015625,y:.296875},{x:.015625,y:.296875},{x:.046875,y:.296875},{x:.046875,y:.296875},{x:.078125,y:.296875},{x:.078125,y:.296875},{x:.109375,y:.296875},{x:.109375,y:.296875},{x:.140625,y:.296875},{x:.140625,y:.296875},{x:.171875,y:.296875},{x:.171875,y:.296875},{x:.203125,y:.296875},{x:.203125,y:.296875},{x:.234375,y:.296875},{x:.234375,y:.296875},{x:.265625,y:.296875},{x:.265625,y:.296875},{x:.296875,y:.296875},{x:.296875,y:.296875},{x:.328125,y:.296875},{x:.328125,y:.296875},{x:.359375,y:.296875},{x:.359375,y:.296875},{x:.390625,y:.296875},{x:.390625,y:.296875},{x:.421875,y:.296875},{x:.421875,y:.296875},{x:.453125,y:.296875},{x:.453125,y:.296875},{x:.484375,y:.296875},{x:.484375,y:.296875},{x:.515625,y:.296875},{x:.515625,y:.296875},{x:.546875,y:.296875},{x:.546875,y:.296875},{x:.578125,y:.296875},{x:.578125,y:.296875},{x:.609375,y:.296875},{x:.609375,y:.296875},{x:.640625,y:.296875},{x:.640625,y:.296875},{x:.671875,y:.296875},{x:.671875,y:.296875},{x:.703125,y:.296875},{x:.703125,y:.296875},{x:.734375,y:.296875},{x:.734375,y:.296875},{x:.765625,y:.296875},{x:.765625,y:.296875},{x:.796875,y:.296875},{x:.796875,y:.296875},{x:.828125,y:.296875},{x:.828125,y:.296875},{x:.859375,y:.296875},{x:.859375,y:.296875},{x:.890625,y:.296875},{x:.890625,y:.296875},{x:.921875,y:.296875},{x:.921875,y:.296875},{x:.953125,y:.296875},{x:.953125,y:.296875},{x:.984375,y:.296875},{x:.984375,y:.296875},{x:.015625,y:.328125},{x:.015625,y:.328125},{x:.046875,y:.328125},{x:.046875,y:.328125},{x:.078125,y:.328125},{x:.078125,y:.328125},{x:.109375,y:.328125},{x:.109375,y:.328125},{x:.140625,y:.328125},{x:.140625,y:.328125},{x:.171875,y:.328125},{x:.171875,y:.328125},{x:.203125,y:.328125},{x:.203125,y:.328125},{x:.234375,y:.328125},{x:.234375,y:.328125},{x:.265625,y:.328125},{x:.265625,y:.328125},{x:.296875,y:.328125},{x:.296875,y:.328125},{x:.328125,y:.328125},{x:.328125,y:.328125},{x:.359375,y:.328125},{x:.359375,y:.328125},{x:.390625,y:.328125},{x:.390625,y:.328125},{x:.421875,y:.328125},{x:.421875,y:.328125},{x:.453125,y:.328125},{x:.453125,y:.328125},{x:.484375,y:.328125},{x:.484375,y:.328125},{x:.515625,y:.328125},{x:.515625,y:.328125},{x:.546875,y:.328125},{x:.546875,y:.328125},{x:.578125,y:.328125},{x:.578125,y:.328125},{x:.609375,y:.328125},{x:.609375,y:.328125},{x:.640625,y:.328125},{x:.640625,y:.328125},{x:.671875,y:.328125},{x:.671875,y:.328125},{x:.703125,y:.328125},{x:.703125,y:.328125},{x:.734375,y:.328125},{x:.734375,y:.328125},{x:.765625,y:.328125},{x:.765625,y:.328125},{x:.796875,y:.328125},{x:.796875,y:.328125},{x:.828125,y:.328125},{x:.828125,y:.328125},{x:.859375,y:.328125},{x:.859375,y:.328125},{x:.890625,y:.328125},{x:.890625,y:.328125},{x:.921875,y:.328125},{x:.921875,y:.328125},{x:.953125,y:.328125},{x:.953125,y:.328125},{x:.984375,y:.328125},{x:.984375,y:.328125},{x:.015625,y:.359375},{x:.015625,y:.359375},{x:.046875,y:.359375},{x:.046875,y:.359375},{x:.078125,y:.359375},{x:.078125,y:.359375},{x:.109375,y:.359375},{x:.109375,y:.359375},{x:.140625,y:.359375},{x:.140625,y:.359375},{x:.171875,y:.359375},{x:.171875,y:.359375},{x:.203125,y:.359375},{x:.203125,y:.359375},{x:.234375,y:.359375},{x:.234375,y:.359375},{x:.265625,y:.359375},{x:.265625,y:.359375},{x:.296875,y:.359375},{x:.296875,y:.359375},{x:.328125,y:.359375},{x:.328125,y:.359375},{x:.359375,y:.359375},{x:.359375,y:.359375},{x:.390625,y:.359375},{x:.390625,y:.359375},{x:.421875,y:.359375},{x:.421875,y:.359375},{x:.453125,y:.359375},{x:.453125,y:.359375},{x:.484375,y:.359375},{x:.484375,y:.359375},{x:.515625,y:.359375},{x:.515625,y:.359375},{x:.546875,y:.359375},{x:.546875,y:.359375},{x:.578125,y:.359375},{x:.578125,y:.359375},{x:.609375,y:.359375},{x:.609375,y:.359375},{x:.640625,y:.359375},{x:.640625,y:.359375},{x:.671875,y:.359375},{x:.671875,y:.359375},{x:.703125,y:.359375},{x:.703125,y:.359375},{x:.734375,y:.359375},{x:.734375,y:.359375},{x:.765625,y:.359375},{x:.765625,y:.359375},{x:.796875,y:.359375},{x:.796875,y:.359375},{x:.828125,y:.359375},{x:.828125,y:.359375},{x:.859375,y:.359375},{x:.859375,y:.359375},{x:.890625,y:.359375},{x:.890625,y:.359375},{x:.921875,y:.359375},{x:.921875,y:.359375},{x:.953125,y:.359375},{x:.953125,y:.359375},{x:.984375,y:.359375},{x:.984375,y:.359375},{x:.015625,y:.390625},{x:.015625,y:.390625},{x:.046875,y:.390625},{x:.046875,y:.390625},{x:.078125,y:.390625},{x:.078125,y:.390625},{x:.109375,y:.390625},{x:.109375,y:.390625},{x:.140625,y:.390625},{x:.140625,y:.390625},{x:.171875,y:.390625},{x:.171875,y:.390625},{x:.203125,y:.390625},{x:.203125,y:.390625},{x:.234375,y:.390625},{x:.234375,y:.390625},{x:.265625,y:.390625},{x:.265625,y:.390625},{x:.296875,y:.390625},{x:.296875,y:.390625},{x:.328125,y:.390625},{x:.328125,y:.390625},{x:.359375,y:.390625},{x:.359375,y:.390625},{x:.390625,y:.390625},{x:.390625,y:.390625},{x:.421875,y:.390625},{x:.421875,y:.390625},{x:.453125,y:.390625},{x:.453125,y:.390625},{x:.484375,y:.390625},{x:.484375,y:.390625},{x:.515625,y:.390625},{x:.515625,y:.390625},{x:.546875,y:.390625},{x:.546875,y:.390625},{x:.578125,y:.390625},{x:.578125,y:.390625},{x:.609375,y:.390625},{x:.609375,y:.390625},{x:.640625,y:.390625},{x:.640625,y:.390625},{x:.671875,y:.390625},{x:.671875,y:.390625},{x:.703125,y:.390625},{x:.703125,y:.390625},{x:.734375,y:.390625},{x:.734375,y:.390625},{x:.765625,y:.390625},{x:.765625,y:.390625},{x:.796875,y:.390625},{x:.796875,y:.390625},{x:.828125,y:.390625},{x:.828125,y:.390625},{x:.859375,y:.390625},{x:.859375,y:.390625},{x:.890625,y:.390625},{x:.890625,y:.390625},{x:.921875,y:.390625},{x:.921875,y:.390625},{x:.953125,y:.390625},{x:.953125,y:.390625},{x:.984375,y:.390625},{x:.984375,y:.390625},{x:.015625,y:.421875},{x:.015625,y:.421875},{x:.046875,y:.421875},{x:.046875,y:.421875},{x:.078125,y:.421875},{x:.078125,y:.421875},{x:.109375,y:.421875},{x:.109375,y:.421875},{x:.140625,y:.421875},{x:.140625,y:.421875},{x:.171875,y:.421875},{x:.171875,y:.421875},{x:.203125,y:.421875},{x:.203125,y:.421875},{x:.234375,y:.421875},{x:.234375,y:.421875},{x:.265625,y:.421875},{x:.265625,y:.421875},{x:.296875,y:.421875},{x:.296875,y:.421875},{x:.328125,y:.421875},{x:.328125,y:.421875},{x:.359375,y:.421875},{x:.359375,y:.421875},{x:.390625,y:.421875},{x:.390625,y:.421875},{x:.421875,y:.421875},{x:.421875,y:.421875},{x:.453125,y:.421875},{x:.453125,y:.421875},{x:.484375,y:.421875},{x:.484375,y:.421875},{x:.515625,y:.421875},{x:.515625,y:.421875},{x:.546875,y:.421875},{x:.546875,y:.421875},{x:.578125,y:.421875},{x:.578125,y:.421875},{x:.609375,y:.421875},{x:.609375,y:.421875},{x:.640625,y:.421875},{x:.640625,y:.421875},{x:.671875,y:.421875},{x:.671875,y:.421875},{x:.703125,y:.421875},{x:.703125,y:.421875},{x:.734375,y:.421875},{x:.734375,y:.421875},{x:.765625,y:.421875},{x:.765625,y:.421875},{x:.796875,y:.421875},{x:.796875,y:.421875},{x:.828125,y:.421875},{x:.828125,y:.421875},{x:.859375,y:.421875},{x:.859375,y:.421875},{x:.890625,y:.421875},{x:.890625,y:.421875},{x:.921875,y:.421875},{x:.921875,y:.421875},{x:.953125,y:.421875},{x:.953125,y:.421875},{x:.984375,y:.421875},{x:.984375,y:.421875},{x:.015625,y:.453125},{x:.015625,y:.453125},{x:.046875,y:.453125},{x:.046875,y:.453125},{x:.078125,y:.453125},{x:.078125,y:.453125},{x:.109375,y:.453125},{x:.109375,y:.453125},{x:.140625,y:.453125},{x:.140625,y:.453125},{x:.171875,y:.453125},{x:.171875,y:.453125},{x:.203125,y:.453125},{x:.203125,y:.453125},{x:.234375,y:.453125},{x:.234375,y:.453125},{x:.265625,y:.453125},{x:.265625,y:.453125},{x:.296875,y:.453125},{x:.296875,y:.453125},{x:.328125,y:.453125},{x:.328125,y:.453125},{x:.359375,y:.453125},{x:.359375,y:.453125},{x:.390625,y:.453125},{x:.390625,y:.453125},{x:.421875,y:.453125},{x:.421875,y:.453125},{x:.453125,y:.453125},{x:.453125,y:.453125},{x:.484375,y:.453125},{x:.484375,y:.453125},{x:.515625,y:.453125},{x:.515625,y:.453125},{x:.546875,y:.453125},{x:.546875,y:.453125},{x:.578125,y:.453125},{x:.578125,y:.453125},{x:.609375,y:.453125},{x:.609375,y:.453125},{x:.640625,y:.453125},{x:.640625,y:.453125},{x:.671875,y:.453125},{x:.671875,y:.453125},{x:.703125,y:.453125},{x:.703125,y:.453125},{x:.734375,y:.453125},{x:.734375,y:.453125},{x:.765625,y:.453125},{x:.765625,y:.453125},{x:.796875,y:.453125},{x:.796875,y:.453125},{x:.828125,y:.453125},{x:.828125,y:.453125},{x:.859375,y:.453125},{x:.859375,y:.453125},{x:.890625,y:.453125},{x:.890625,y:.453125},{x:.921875,y:.453125},{x:.921875,y:.453125},{x:.953125,y:.453125},{x:.953125,y:.453125},{x:.984375,y:.453125},{x:.984375,y:.453125},{x:.015625,y:.484375},{x:.015625,y:.484375},{x:.046875,y:.484375},{x:.046875,y:.484375},{x:.078125,y:.484375},{x:.078125,y:.484375},{x:.109375,y:.484375},{x:.109375,y:.484375},{x:.140625,y:.484375},{x:.140625,y:.484375},{x:.171875,y:.484375},{x:.171875,y:.484375},{x:.203125,y:.484375},{x:.203125,y:.484375},{x:.234375,y:.484375},{x:.234375,y:.484375},{x:.265625,y:.484375},{x:.265625,y:.484375},{x:.296875,y:.484375},{x:.296875,y:.484375},{x:.328125,y:.484375},{x:.328125,y:.484375},{x:.359375,y:.484375},{x:.359375,y:.484375},{x:.390625,y:.484375},{x:.390625,y:.484375},{x:.421875,y:.484375},{x:.421875,y:.484375},{x:.453125,y:.484375},{x:.453125,y:.484375},{x:.484375,y:.484375},{x:.484375,y:.484375},{x:.515625,y:.484375},{x:.515625,y:.484375},{x:.546875,y:.484375},{x:.546875,y:.484375},{x:.578125,y:.484375},{x:.578125,y:.484375},{x:.609375,y:.484375},{x:.609375,y:.484375},{x:.640625,y:.484375},{x:.640625,y:.484375},{x:.671875,y:.484375},{x:.671875,y:.484375},{x:.703125,y:.484375},{x:.703125,y:.484375},{x:.734375,y:.484375},{x:.734375,y:.484375},{x:.765625,y:.484375},{x:.765625,y:.484375},{x:.796875,y:.484375},{x:.796875,y:.484375},{x:.828125,y:.484375},{x:.828125,y:.484375},{x:.859375,y:.484375},{x:.859375,y:.484375},{x:.890625,y:.484375},{x:.890625,y:.484375},{x:.921875,y:.484375},{x:.921875,y:.484375},{x:.953125,y:.484375},{x:.953125,y:.484375},{x:.984375,y:.484375},{x:.984375,y:.484375},{x:.015625,y:.515625},{x:.015625,y:.515625},{x:.046875,y:.515625},{x:.046875,y:.515625},{x:.078125,y:.515625},{x:.078125,y:.515625},{x:.109375,y:.515625},{x:.109375,y:.515625},{x:.140625,y:.515625},{x:.140625,y:.515625},{x:.171875,y:.515625},{x:.171875,y:.515625},{x:.203125,y:.515625},{x:.203125,y:.515625},{x:.234375,y:.515625},{x:.234375,y:.515625},{x:.265625,y:.515625},{x:.265625,y:.515625},{x:.296875,y:.515625},{x:.296875,y:.515625},{x:.328125,y:.515625},{x:.328125,y:.515625},{x:.359375,y:.515625},{x:.359375,y:.515625},{x:.390625,y:.515625},{x:.390625,y:.515625},{x:.421875,y:.515625},{x:.421875,y:.515625},{x:.453125,y:.515625},{x:.453125,y:.515625},{x:.484375,y:.515625},{x:.484375,y:.515625},{x:.515625,y:.515625},{x:.515625,y:.515625},{x:.546875,y:.515625},{x:.546875,y:.515625},{x:.578125,y:.515625},{x:.578125,y:.515625},{x:.609375,y:.515625},{x:.609375,y:.515625},{x:.640625,y:.515625},{x:.640625,y:.515625},{x:.671875,y:.515625},{x:.671875,y:.515625},{x:.703125,y:.515625},{x:.703125,y:.515625},{x:.734375,y:.515625},{x:.734375,y:.515625},{x:.765625,y:.515625},{x:.765625,y:.515625},{x:.796875,y:.515625},{x:.796875,y:.515625},{x:.828125,y:.515625},{x:.828125,y:.515625},{x:.859375,y:.515625},{x:.859375,y:.515625},{x:.890625,y:.515625},{x:.890625,y:.515625},{x:.921875,y:.515625},{x:.921875,y:.515625},{x:.953125,y:.515625},{x:.953125,y:.515625},{x:.984375,y:.515625},{x:.984375,y:.515625},{x:.015625,y:.546875},{x:.015625,y:.546875},{x:.046875,y:.546875},{x:.046875,y:.546875},{x:.078125,y:.546875},{x:.078125,y:.546875},{x:.109375,y:.546875},{x:.109375,y:.546875},{x:.140625,y:.546875},{x:.140625,y:.546875},{x:.171875,y:.546875},{x:.171875,y:.546875},{x:.203125,y:.546875},{x:.203125,y:.546875},{x:.234375,y:.546875},{x:.234375,y:.546875},{x:.265625,y:.546875},{x:.265625,y:.546875},{x:.296875,y:.546875},{x:.296875,y:.546875},{x:.328125,y:.546875},{x:.328125,y:.546875},{x:.359375,y:.546875},{x:.359375,y:.546875},{x:.390625,y:.546875},{x:.390625,y:.546875},{x:.421875,y:.546875},{x:.421875,y:.546875},{x:.453125,y:.546875},{x:.453125,y:.546875},{x:.484375,y:.546875},{x:.484375,y:.546875},{x:.515625,y:.546875},{x:.515625,y:.546875},{x:.546875,y:.546875},{x:.546875,y:.546875},{x:.578125,y:.546875},{x:.578125,y:.546875},{x:.609375,y:.546875},{x:.609375,y:.546875},{x:.640625,y:.546875},{x:.640625,y:.546875},{x:.671875,y:.546875},{x:.671875,y:.546875},{x:.703125,y:.546875},{x:.703125,y:.546875},{x:.734375,y:.546875},{x:.734375,y:.546875},{x:.765625,y:.546875},{x:.765625,y:.546875},{x:.796875,y:.546875},{x:.796875,y:.546875},{x:.828125,y:.546875},{x:.828125,y:.546875},{x:.859375,y:.546875},{x:.859375,y:.546875},{x:.890625,y:.546875},{x:.890625,y:.546875},{x:.921875,y:.546875},{x:.921875,y:.546875},{x:.953125,y:.546875},{x:.953125,y:.546875},{x:.984375,y:.546875},{x:.984375,y:.546875},{x:.015625,y:.578125},{x:.015625,y:.578125},{x:.046875,y:.578125},{x:.046875,y:.578125},{x:.078125,y:.578125},{x:.078125,y:.578125},{x:.109375,y:.578125},{x:.109375,y:.578125},{x:.140625,y:.578125},{x:.140625,y:.578125},{x:.171875,y:.578125},{x:.171875,y:.578125},{x:.203125,y:.578125},{x:.203125,y:.578125},{x:.234375,y:.578125},{x:.234375,y:.578125},{x:.265625,y:.578125},{x:.265625,y:.578125},{x:.296875,y:.578125},{x:.296875,y:.578125},{x:.328125,y:.578125},{x:.328125,y:.578125},{x:.359375,y:.578125},{x:.359375,y:.578125},{x:.390625,y:.578125},{x:.390625,y:.578125},{x:.421875,y:.578125},{x:.421875,y:.578125},{x:.453125,y:.578125},{x:.453125,y:.578125},{x:.484375,y:.578125},{x:.484375,y:.578125},{x:.515625,y:.578125},{x:.515625,y:.578125},{x:.546875,y:.578125},{x:.546875,y:.578125},{x:.578125,y:.578125},{x:.578125,y:.578125},{x:.609375,y:.578125},{x:.609375,y:.578125},{x:.640625,y:.578125},{x:.640625,y:.578125},{x:.671875,y:.578125},{x:.671875,y:.578125},{x:.703125,y:.578125},{x:.703125,y:.578125},{x:.734375,y:.578125},{x:.734375,y:.578125},{x:.765625,y:.578125},{x:.765625,y:.578125},{x:.796875,y:.578125},{x:.796875,y:.578125},{x:.828125,y:.578125},{x:.828125,y:.578125},{x:.859375,y:.578125},{x:.859375,y:.578125},{x:.890625,y:.578125},{x:.890625,y:.578125},{x:.921875,y:.578125},{x:.921875,y:.578125},{x:.953125,y:.578125},{x:.953125,y:.578125},{x:.984375,y:.578125},{x:.984375,y:.578125},{x:.015625,y:.609375},{x:.015625,y:.609375},{x:.046875,y:.609375},{x:.046875,y:.609375},{x:.078125,y:.609375},{x:.078125,y:.609375},{x:.109375,y:.609375},{x:.109375,y:.609375},{x:.140625,y:.609375},{x:.140625,y:.609375},{x:.171875,y:.609375},{x:.171875,y:.609375},{x:.203125,y:.609375},{x:.203125,y:.609375},{x:.234375,y:.609375},{x:.234375,y:.609375},{x:.265625,y:.609375},{x:.265625,y:.609375},{x:.296875,y:.609375},{x:.296875,y:.609375},{x:.328125,y:.609375},{x:.328125,y:.609375},{x:.359375,y:.609375},{x:.359375,y:.609375},{x:.390625,y:.609375},{x:.390625,y:.609375},{x:.421875,y:.609375},{x:.421875,y:.609375},{x:.453125,y:.609375},{x:.453125,y:.609375},{x:.484375,y:.609375},{x:.484375,y:.609375},{x:.515625,y:.609375},{x:.515625,y:.609375},{x:.546875,y:.609375},{x:.546875,y:.609375},{x:.578125,y:.609375},{x:.578125,y:.609375},{x:.609375,y:.609375},{x:.609375,y:.609375},{x:.640625,y:.609375},{x:.640625,y:.609375},{x:.671875,y:.609375},{x:.671875,y:.609375},{x:.703125,y:.609375},{x:.703125,y:.609375},{x:.734375,y:.609375},{x:.734375,y:.609375},{x:.765625,y:.609375},{x:.765625,y:.609375},{x:.796875,y:.609375},{x:.796875,y:.609375},{x:.828125,y:.609375},{x:.828125,y:.609375},{x:.859375,y:.609375},{x:.859375,y:.609375},{x:.890625,y:.609375},{x:.890625,y:.609375},{x:.921875,y:.609375},{x:.921875,y:.609375},{x:.953125,y:.609375},{x:.953125,y:.609375},{x:.984375,y:.609375},{x:.984375,y:.609375},{x:.015625,y:.640625},{x:.015625,y:.640625},{x:.046875,y:.640625},{x:.046875,y:.640625},{x:.078125,y:.640625},{x:.078125,y:.640625},{x:.109375,y:.640625},{x:.109375,y:.640625},{x:.140625,y:.640625},{x:.140625,y:.640625},{x:.171875,y:.640625},{x:.171875,y:.640625},{x:.203125,y:.640625},{x:.203125,y:.640625},{x:.234375,y:.640625},{x:.234375,y:.640625},{x:.265625,y:.640625},{x:.265625,y:.640625},{x:.296875,y:.640625},{x:.296875,y:.640625},{x:.328125,y:.640625},{x:.328125,y:.640625},{x:.359375,y:.640625},{x:.359375,y:.640625},{x:.390625,y:.640625},{x:.390625,y:.640625},{x:.421875,y:.640625},{x:.421875,y:.640625},{x:.453125,y:.640625},{x:.453125,y:.640625},{x:.484375,y:.640625},{x:.484375,y:.640625},{x:.515625,y:.640625},{x:.515625,y:.640625},{x:.546875,y:.640625},{x:.546875,y:.640625},{x:.578125,y:.640625},{x:.578125,y:.640625},{x:.609375,y:.640625},{x:.609375,y:.640625},{x:.640625,y:.640625},{x:.640625,y:.640625},{x:.671875,y:.640625},{x:.671875,y:.640625},{x:.703125,y:.640625},{x:.703125,y:.640625},{x:.734375,y:.640625},{x:.734375,y:.640625},{x:.765625,y:.640625},{x:.765625,y:.640625},{x:.796875,y:.640625},{x:.796875,y:.640625},{x:.828125,y:.640625},{x:.828125,y:.640625},{x:.859375,y:.640625},{x:.859375,y:.640625},{x:.890625,y:.640625},{x:.890625,y:.640625},{x:.921875,y:.640625},{x:.921875,y:.640625},{x:.953125,y:.640625},{x:.953125,y:.640625},{x:.984375,y:.640625},{x:.984375,y:.640625},{x:.015625,y:.671875},{x:.015625,y:.671875},{x:.046875,y:.671875},{x:.046875,y:.671875},{x:.078125,y:.671875},{x:.078125,y:.671875},{x:.109375,y:.671875},{x:.109375,y:.671875},{x:.140625,y:.671875},{x:.140625,y:.671875},{x:.171875,y:.671875},{x:.171875,y:.671875},{x:.203125,y:.671875},{x:.203125,y:.671875},{x:.234375,y:.671875},{x:.234375,y:.671875},{x:.265625,y:.671875},{x:.265625,y:.671875},{x:.296875,y:.671875},{x:.296875,y:.671875},{x:.328125,y:.671875},{x:.328125,y:.671875},{x:.359375,y:.671875},{x:.359375,y:.671875},{x:.390625,y:.671875},{x:.390625,y:.671875},{x:.421875,y:.671875},{x:.421875,y:.671875},{x:.453125,y:.671875},{x:.453125,y:.671875},{x:.484375,y:.671875},{x:.484375,y:.671875},{x:.515625,y:.671875},{x:.515625,y:.671875},{x:.546875,y:.671875},{x:.546875,y:.671875},{x:.578125,y:.671875},{x:.578125,y:.671875},{x:.609375,y:.671875},{x:.609375,y:.671875},{x:.640625,y:.671875},{x:.640625,y:.671875},{x:.671875,y:.671875},{x:.671875,y:.671875},{x:.703125,y:.671875},{x:.703125,y:.671875},{x:.734375,y:.671875},{x:.734375,y:.671875},{x:.765625,y:.671875},{x:.765625,y:.671875},{x:.796875,y:.671875},{x:.796875,y:.671875},{x:.828125,y:.671875},{x:.828125,y:.671875},{x:.859375,y:.671875},{x:.859375,y:.671875},{x:.890625,y:.671875},{x:.890625,y:.671875},{x:.921875,y:.671875},{x:.921875,y:.671875},{x:.953125,y:.671875},{x:.953125,y:.671875},{x:.984375,y:.671875},{x:.984375,y:.671875},{x:.015625,y:.703125},{x:.015625,y:.703125},{x:.046875,y:.703125},{x:.046875,y:.703125},{x:.078125,y:.703125},{x:.078125,y:.703125},{x:.109375,y:.703125},{x:.109375,y:.703125},{x:.140625,y:.703125},{x:.140625,y:.703125},{x:.171875,y:.703125},{x:.171875,y:.703125},{x:.203125,y:.703125},{x:.203125,y:.703125},{x:.234375,y:.703125},{x:.234375,y:.703125},{x:.265625,y:.703125},{x:.265625,y:.703125},{x:.296875,y:.703125},{x:.296875,y:.703125},{x:.328125,y:.703125},{x:.328125,y:.703125},{x:.359375,y:.703125},{x:.359375,y:.703125},{x:.390625,y:.703125},{x:.390625,y:.703125},{x:.421875,y:.703125},{x:.421875,y:.703125},{x:.453125,y:.703125},{x:.453125,y:.703125},{x:.484375,y:.703125},{x:.484375,y:.703125},{x:.515625,y:.703125},{x:.515625,y:.703125},{x:.546875,y:.703125},{x:.546875,y:.703125},{x:.578125,y:.703125},{x:.578125,y:.703125},{x:.609375,y:.703125},{x:.609375,y:.703125},{x:.640625,y:.703125},{x:.640625,y:.703125},{x:.671875,y:.703125},{x:.671875,y:.703125},{x:.703125,y:.703125},{x:.703125,y:.703125},{x:.734375,y:.703125},{x:.734375,y:.703125},{x:.765625,y:.703125},{x:.765625,y:.703125},{x:.796875,y:.703125},{x:.796875,y:.703125},{x:.828125,y:.703125},{x:.828125,y:.703125},{x:.859375,y:.703125},{x:.859375,y:.703125},{x:.890625,y:.703125},{x:.890625,y:.703125},{x:.921875,y:.703125},{x:.921875,y:.703125},{x:.953125,y:.703125},{x:.953125,y:.703125},{x:.984375,y:.703125},{x:.984375,y:.703125},{x:.015625,y:.734375},{x:.015625,y:.734375},{x:.046875,y:.734375},{x:.046875,y:.734375},{x:.078125,y:.734375},{x:.078125,y:.734375},{x:.109375,y:.734375},{x:.109375,y:.734375},{x:.140625,y:.734375},{x:.140625,y:.734375},{x:.171875,y:.734375},{x:.171875,y:.734375},{x:.203125,y:.734375},{x:.203125,y:.734375},{x:.234375,y:.734375},{x:.234375,y:.734375},{x:.265625,y:.734375},{x:.265625,y:.734375},{x:.296875,y:.734375},{x:.296875,y:.734375},{x:.328125,y:.734375},{x:.328125,y:.734375},{x:.359375,y:.734375},{x:.359375,y:.734375},{x:.390625,y:.734375},{x:.390625,y:.734375},{x:.421875,y:.734375},{x:.421875,y:.734375},{x:.453125,y:.734375},{x:.453125,y:.734375},{x:.484375,y:.734375},{x:.484375,y:.734375},{x:.515625,y:.734375},{x:.515625,y:.734375},{x:.546875,y:.734375},{x:.546875,y:.734375},{x:.578125,y:.734375},{x:.578125,y:.734375},{x:.609375,y:.734375},{x:.609375,y:.734375},{x:.640625,y:.734375},{x:.640625,y:.734375},{x:.671875,y:.734375},{x:.671875,y:.734375},{x:.703125,y:.734375},{x:.703125,y:.734375},{x:.734375,y:.734375},{x:.734375,y:.734375},{x:.765625,y:.734375},{x:.765625,y:.734375},{x:.796875,y:.734375},{x:.796875,y:.734375},{x:.828125,y:.734375},{x:.828125,y:.734375},{x:.859375,y:.734375},{x:.859375,y:.734375},{x:.890625,y:.734375},{x:.890625,y:.734375},{x:.921875,y:.734375},{x:.921875,y:.734375},{x:.953125,y:.734375},{x:.953125,y:.734375},{x:.984375,y:.734375},{x:.984375,y:.734375},{x:.015625,y:.765625},{x:.015625,y:.765625},{x:.046875,y:.765625},{x:.046875,y:.765625},{x:.078125,y:.765625},{x:.078125,y:.765625},{x:.109375,y:.765625},{x:.109375,y:.765625},{x:.140625,y:.765625},{x:.140625,y:.765625},{x:.171875,y:.765625},{x:.171875,y:.765625},{x:.203125,y:.765625},{x:.203125,y:.765625},{x:.234375,y:.765625},{x:.234375,y:.765625},{x:.265625,y:.765625},{x:.265625,y:.765625},{x:.296875,y:.765625},{x:.296875,y:.765625},{x:.328125,y:.765625},{x:.328125,y:.765625},{x:.359375,y:.765625},{x:.359375,y:.765625},{x:.390625,y:.765625},{x:.390625,y:.765625},{x:.421875,y:.765625},{x:.421875,y:.765625},{x:.453125,y:.765625},{x:.453125,y:.765625},{x:.484375,y:.765625},{x:.484375,y:.765625},{x:.515625,y:.765625},{x:.515625,y:.765625},{x:.546875,y:.765625},{x:.546875,y:.765625},{x:.578125,y:.765625},{x:.578125,y:.765625},{x:.609375,y:.765625},{x:.609375,y:.765625},{x:.640625,y:.765625},{x:.640625,y:.765625},{x:.671875,y:.765625},{x:.671875,y:.765625},{x:.703125,y:.765625},{x:.703125,y:.765625},{x:.734375,y:.765625},{x:.734375,y:.765625},{x:.765625,y:.765625},{x:.765625,y:.765625},{x:.796875,y:.765625},{x:.796875,y:.765625},{x:.828125,y:.765625},{x:.828125,y:.765625},{x:.859375,y:.765625},{x:.859375,y:.765625},{x:.890625,y:.765625},{x:.890625,y:.765625},{x:.921875,y:.765625},{x:.921875,y:.765625},{x:.953125,y:.765625},{x:.953125,y:.765625},{x:.984375,y:.765625},{x:.984375,y:.765625},{x:.015625,y:.796875},{x:.015625,y:.796875},{x:.046875,y:.796875},{x:.046875,y:.796875},{x:.078125,y:.796875},{x:.078125,y:.796875},{x:.109375,y:.796875},{x:.109375,y:.796875},{x:.140625,y:.796875},{x:.140625,y:.796875},{x:.171875,y:.796875},{x:.171875,y:.796875},{x:.203125,y:.796875},{x:.203125,y:.796875},{x:.234375,y:.796875},{x:.234375,y:.796875},{x:.265625,y:.796875},{x:.265625,y:.796875},{x:.296875,y:.796875},{x:.296875,y:.796875},{x:.328125,y:.796875},{x:.328125,y:.796875},{x:.359375,y:.796875},{x:.359375,y:.796875},{x:.390625,y:.796875},{x:.390625,y:.796875},{x:.421875,y:.796875},{x:.421875,y:.796875},{x:.453125,y:.796875},{x:.453125,y:.796875},{x:.484375,y:.796875},{x:.484375,y:.796875},{x:.515625,y:.796875},{x:.515625,y:.796875},{x:.546875,y:.796875},{x:.546875,y:.796875},{x:.578125,y:.796875},{x:.578125,y:.796875},{x:.609375,y:.796875},{x:.609375,y:.796875},{x:.640625,y:.796875},{x:.640625,y:.796875},{x:.671875,y:.796875},{x:.671875,y:.796875},{x:.703125,y:.796875},{x:.703125,y:.796875},{x:.734375,y:.796875},{x:.734375,y:.796875},{x:.765625,y:.796875},{x:.765625,y:.796875},{x:.796875,y:.796875},{x:.796875,y:.796875},{x:.828125,y:.796875},{x:.828125,y:.796875},{x:.859375,y:.796875},{x:.859375,y:.796875},{x:.890625,y:.796875},{x:.890625,y:.796875},{x:.921875,y:.796875},{x:.921875,y:.796875},{x:.953125,y:.796875},{x:.953125,y:.796875},{x:.984375,y:.796875},{x:.984375,y:.796875},{x:.015625,y:.828125},{x:.015625,y:.828125},{x:.046875,y:.828125},{x:.046875,y:.828125},{x:.078125,y:.828125},{x:.078125,y:.828125},{x:.109375,y:.828125},{x:.109375,y:.828125},{x:.140625,y:.828125},{x:.140625,y:.828125},{x:.171875,y:.828125},{x:.171875,y:.828125},{x:.203125,y:.828125},{x:.203125,y:.828125},{x:.234375,y:.828125},{x:.234375,y:.828125},{x:.265625,y:.828125},{x:.265625,y:.828125},{x:.296875,y:.828125},{x:.296875,y:.828125},{x:.328125,y:.828125},{x:.328125,y:.828125},{x:.359375,y:.828125},{x:.359375,y:.828125},{x:.390625,y:.828125},{x:.390625,y:.828125},{x:.421875,y:.828125},{x:.421875,y:.828125},{x:.453125,y:.828125},{x:.453125,y:.828125},{x:.484375,y:.828125},{x:.484375,y:.828125},{x:.515625,y:.828125},{x:.515625,y:.828125},{x:.546875,y:.828125},{x:.546875,y:.828125},{x:.578125,y:.828125},{x:.578125,y:.828125},{x:.609375,y:.828125},{x:.609375,y:.828125},{x:.640625,y:.828125},{x:.640625,y:.828125},{x:.671875,y:.828125},{x:.671875,y:.828125},{x:.703125,y:.828125},{x:.703125,y:.828125},{x:.734375,y:.828125},{x:.734375,y:.828125},{x:.765625,y:.828125},{x:.765625,y:.828125},{x:.796875,y:.828125},{x:.796875,y:.828125},{x:.828125,y:.828125},{x:.828125,y:.828125},{x:.859375,y:.828125},{x:.859375,y:.828125},{x:.890625,y:.828125},{x:.890625,y:.828125},{x:.921875,y:.828125},{x:.921875,y:.828125},{x:.953125,y:.828125},{x:.953125,y:.828125},{x:.984375,y:.828125},{x:.984375,y:.828125},{x:.015625,y:.859375},{x:.015625,y:.859375},{x:.046875,y:.859375},{x:.046875,y:.859375},{x:.078125,y:.859375},{x:.078125,y:.859375},{x:.109375,y:.859375},{x:.109375,y:.859375},{x:.140625,y:.859375},{x:.140625,y:.859375},{x:.171875,y:.859375},{x:.171875,y:.859375},{x:.203125,y:.859375},{x:.203125,y:.859375},{x:.234375,y:.859375},{x:.234375,y:.859375},{x:.265625,y:.859375},{x:.265625,y:.859375},{x:.296875,y:.859375},{x:.296875,y:.859375},{x:.328125,y:.859375},{x:.328125,y:.859375},{x:.359375,y:.859375},{x:.359375,y:.859375},{x:.390625,y:.859375},{x:.390625,y:.859375},{x:.421875,y:.859375},{x:.421875,y:.859375},{x:.453125,y:.859375},{x:.453125,y:.859375},{x:.484375,y:.859375},{x:.484375,y:.859375},{x:.515625,y:.859375},{x:.515625,y:.859375},{x:.546875,y:.859375},{x:.546875,y:.859375},{x:.578125,y:.859375},{x:.578125,y:.859375},{x:.609375,y:.859375},{x:.609375,y:.859375},{x:.640625,y:.859375},{x:.640625,y:.859375},{x:.671875,y:.859375},{x:.671875,y:.859375},{x:.703125,y:.859375},{x:.703125,y:.859375},{x:.734375,y:.859375},{x:.734375,y:.859375},{x:.765625,y:.859375},{x:.765625,y:.859375},{x:.796875,y:.859375},{x:.796875,y:.859375},{x:.828125,y:.859375},{x:.828125,y:.859375},{x:.859375,y:.859375},{x:.859375,y:.859375},{x:.890625,y:.859375},{x:.890625,y:.859375},{x:.921875,y:.859375},{x:.921875,y:.859375},{x:.953125,y:.859375},{x:.953125,y:.859375},{x:.984375,y:.859375},{x:.984375,y:.859375},{x:.015625,y:.890625},{x:.015625,y:.890625},{x:.046875,y:.890625},{x:.046875,y:.890625},{x:.078125,y:.890625},{x:.078125,y:.890625},{x:.109375,y:.890625},{x:.109375,y:.890625},{x:.140625,y:.890625},{x:.140625,y:.890625},{x:.171875,y:.890625},{x:.171875,y:.890625},{x:.203125,y:.890625},{x:.203125,y:.890625},{x:.234375,y:.890625},{x:.234375,y:.890625},{x:.265625,y:.890625},{x:.265625,y:.890625},{x:.296875,y:.890625},{x:.296875,y:.890625},{x:.328125,y:.890625},{x:.328125,y:.890625},{x:.359375,y:.890625},{x:.359375,y:.890625},{x:.390625,y:.890625},{x:.390625,y:.890625},{x:.421875,y:.890625},{x:.421875,y:.890625},{x:.453125,y:.890625},{x:.453125,y:.890625},{x:.484375,y:.890625},{x:.484375,y:.890625},{x:.515625,y:.890625},{x:.515625,y:.890625},{x:.546875,y:.890625},{x:.546875,y:.890625},{x:.578125,y:.890625},{x:.578125,y:.890625},{x:.609375,y:.890625},{x:.609375,y:.890625},{x:.640625,y:.890625},{x:.640625,y:.890625},{x:.671875,y:.890625},{x:.671875,y:.890625},{x:.703125,y:.890625},{x:.703125,y:.890625},{x:.734375,y:.890625},{x:.734375,y:.890625},{x:.765625,y:.890625},{x:.765625,y:.890625},{x:.796875,y:.890625},{x:.796875,y:.890625},{x:.828125,y:.890625},{x:.828125,y:.890625},{x:.859375,y:.890625},{x:.859375,y:.890625},{x:.890625,y:.890625},{x:.890625,y:.890625},{x:.921875,y:.890625},{x:.921875,y:.890625},{x:.953125,y:.890625},{x:.953125,y:.890625},{x:.984375,y:.890625},{x:.984375,y:.890625},{x:.015625,y:.921875},{x:.015625,y:.921875},{x:.046875,y:.921875},{x:.046875,y:.921875},{x:.078125,y:.921875},{x:.078125,y:.921875},{x:.109375,y:.921875},{x:.109375,y:.921875},{x:.140625,y:.921875},{x:.140625,y:.921875},{x:.171875,y:.921875},{x:.171875,y:.921875},{x:.203125,y:.921875},{x:.203125,y:.921875},{x:.234375,y:.921875},{x:.234375,y:.921875},{x:.265625,y:.921875},{x:.265625,y:.921875},{x:.296875,y:.921875},{x:.296875,y:.921875},{x:.328125,y:.921875},{x:.328125,y:.921875},{x:.359375,y:.921875},{x:.359375,y:.921875},{x:.390625,y:.921875},{x:.390625,y:.921875},{x:.421875,y:.921875},{x:.421875,y:.921875},{x:.453125,y:.921875},{x:.453125,y:.921875},{x:.484375,y:.921875},{x:.484375,y:.921875},{x:.515625,y:.921875},{x:.515625,y:.921875},{x:.546875,y:.921875},{x:.546875,y:.921875},{x:.578125,y:.921875},{x:.578125,y:.921875},{x:.609375,y:.921875},{x:.609375,y:.921875},{x:.640625,y:.921875},{x:.640625,y:.921875},{x:.671875,y:.921875},{x:.671875,y:.921875},{x:.703125,y:.921875},{x:.703125,y:.921875},{x:.734375,y:.921875},{x:.734375,y:.921875},{x:.765625,y:.921875},{x:.765625,y:.921875},{x:.796875,y:.921875},{x:.796875,y:.921875},{x:.828125,y:.921875},{x:.828125,y:.921875},{x:.859375,y:.921875},{x:.859375,y:.921875},{x:.890625,y:.921875},{x:.890625,y:.921875},{x:.921875,y:.921875},{x:.921875,y:.921875},{x:.953125,y:.921875},{x:.953125,y:.921875},{x:.984375,y:.921875},{x:.984375,y:.921875},{x:.015625,y:.953125},{x:.015625,y:.953125},{x:.046875,y:.953125},{x:.046875,y:.953125},{x:.078125,y:.953125},{x:.078125,y:.953125},{x:.109375,y:.953125},{x:.109375,y:.953125},{x:.140625,y:.953125},{x:.140625,y:.953125},{x:.171875,y:.953125},{x:.171875,y:.953125},{x:.203125,y:.953125},{x:.203125,y:.953125},{x:.234375,y:.953125},{x:.234375,y:.953125},{x:.265625,y:.953125},{x:.265625,y:.953125},{x:.296875,y:.953125},{x:.296875,y:.953125},{x:.328125,y:.953125},{x:.328125,y:.953125},{x:.359375,y:.953125},{x:.359375,y:.953125},{x:.390625,y:.953125},{x:.390625,y:.953125},{x:.421875,y:.953125},{x:.421875,y:.953125},{x:.453125,y:.953125},{x:.453125,y:.953125},{x:.484375,y:.953125},{x:.484375,y:.953125},{x:.515625,y:.953125},{x:.515625,y:.953125},{x:.546875,y:.953125},{x:.546875,y:.953125},{x:.578125,y:.953125},{x:.578125,y:.953125},{x:.609375,y:.953125},{x:.609375,y:.953125},{x:.640625,y:.953125},{x:.640625,y:.953125},{x:.671875,y:.953125},{x:.671875,y:.953125},{x:.703125,y:.953125},{x:.703125,y:.953125},{x:.734375,y:.953125},{x:.734375,y:.953125},{x:.765625,y:.953125},{x:.765625,y:.953125},{x:.796875,y:.953125},{x:.796875,y:.953125},{x:.828125,y:.953125},{x:.828125,y:.953125},{x:.859375,y:.953125},{x:.859375,y:.953125},{x:.890625,y:.953125},{x:.890625,y:.953125},{x:.921875,y:.953125},{x:.921875,y:.953125},{x:.953125,y:.953125},{x:.953125,y:.953125},{x:.984375,y:.953125},{x:.984375,y:.953125},{x:.015625,y:.984375},{x:.015625,y:.984375},{x:.046875,y:.984375},{x:.046875,y:.984375},{x:.078125,y:.984375},{x:.078125,y:.984375},{x:.109375,y:.984375},{x:.109375,y:.984375},{x:.140625,y:.984375},{x:.140625,y:.984375},{x:.171875,y:.984375},{x:.171875,y:.984375},{x:.203125,y:.984375},{x:.203125,y:.984375},{x:.234375,y:.984375},{x:.234375,y:.984375},{x:.265625,y:.984375},{x:.265625,y:.984375},{x:.296875,y:.984375},{x:.296875,y:.984375},{x:.328125,y:.984375},{x:.328125,y:.984375},{x:.359375,y:.984375},{x:.359375,y:.984375},{x:.390625,y:.984375},{x:.390625,y:.984375},{x:.421875,y:.984375},{x:.421875,y:.984375},{x:.453125,y:.984375},{x:.453125,y:.984375},{x:.484375,y:.984375},{x:.484375,y:.984375},{x:.515625,y:.984375},{x:.515625,y:.984375},{x:.546875,y:.984375},{x:.546875,y:.984375},{x:.578125,y:.984375},{x:.578125,y:.984375},{x:.609375,y:.984375},{x:.609375,y:.984375},{x:.640625,y:.984375},{x:.640625,y:.984375},{x:.671875,y:.984375},{x:.671875,y:.984375},{x:.703125,y:.984375},{x:.703125,y:.984375},{x:.734375,y:.984375},{x:.734375,y:.984375},{x:.765625,y:.984375},{x:.765625,y:.984375},{x:.796875,y:.984375},{x:.796875,y:.984375},{x:.828125,y:.984375},{x:.828125,y:.984375},{x:.859375,y:.984375},{x:.859375,y:.984375},{x:.890625,y:.984375},{x:.890625,y:.984375},{x:.921875,y:.984375},{x:.921875,y:.984375},{x:.953125,y:.984375},{x:.953125,y:.984375},{x:.984375,y:.984375},{x:.984375,y:.984375},{x:.03125,y:.03125},{x:.03125,y:.03125},{x:.09375,y:.03125},{x:.09375,y:.03125},{x:.15625,y:.03125},{x:.15625,y:.03125},{x:.21875,y:.03125},{x:.21875,y:.03125},{x:.28125,y:.03125},{x:.28125,y:.03125},{x:.34375,y:.03125},{x:.34375,y:.03125},{x:.40625,y:.03125},{x:.40625,y:.03125},{x:.46875,y:.03125},{x:.46875,y:.03125},{x:.53125,y:.03125},{x:.53125,y:.03125},{x:.59375,y:.03125},{x:.59375,y:.03125},{x:.65625,y:.03125},{x:.65625,y:.03125},{x:.71875,y:.03125},{x:.71875,y:.03125},{x:.78125,y:.03125},{x:.78125,y:.03125},{x:.84375,y:.03125},{x:.84375,y:.03125},{x:.90625,y:.03125},{x:.90625,y:.03125},{x:.96875,y:.03125},{x:.96875,y:.03125},{x:.03125,y:.09375},{x:.03125,y:.09375},{x:.09375,y:.09375},{x:.09375,y:.09375},{x:.15625,y:.09375},{x:.15625,y:.09375},{x:.21875,y:.09375},{x:.21875,y:.09375},{x:.28125,y:.09375},{x:.28125,y:.09375},{x:.34375,y:.09375},{x:.34375,y:.09375},{x:.40625,y:.09375},{x:.40625,y:.09375},{x:.46875,y:.09375},{x:.46875,y:.09375},{x:.53125,y:.09375},{x:.53125,y:.09375},{x:.59375,y:.09375},{x:.59375,y:.09375},{x:.65625,y:.09375},{x:.65625,y:.09375},{x:.71875,y:.09375},{x:.71875,y:.09375},{x:.78125,y:.09375},{x:.78125,y:.09375},{x:.84375,y:.09375},{x:.84375,y:.09375},{x:.90625,y:.09375},{x:.90625,y:.09375},{x:.96875,y:.09375},{x:.96875,y:.09375},{x:.03125,y:.15625},{x:.03125,y:.15625},{x:.09375,y:.15625},{x:.09375,y:.15625},{x:.15625,y:.15625},{x:.15625,y:.15625},{x:.21875,y:.15625},{x:.21875,y:.15625},{x:.28125,y:.15625},{x:.28125,y:.15625},{x:.34375,y:.15625},{x:.34375,y:.15625},{x:.40625,y:.15625},{x:.40625,y:.15625},{x:.46875,y:.15625},{x:.46875,y:.15625},{x:.53125,y:.15625},{x:.53125,y:.15625},{x:.59375,y:.15625},{x:.59375,y:.15625},{x:.65625,y:.15625},{x:.65625,y:.15625},{x:.71875,y:.15625},{x:.71875,y:.15625},{x:.78125,y:.15625},{x:.78125,y:.15625},{x:.84375,y:.15625},{x:.84375,y:.15625},{x:.90625,y:.15625},{x:.90625,y:.15625},{x:.96875,y:.15625},{x:.96875,y:.15625},{x:.03125,y:.21875},{x:.03125,y:.21875},{x:.09375,y:.21875},{x:.09375,y:.21875},{x:.15625,y:.21875},{x:.15625,y:.21875},{x:.21875,y:.21875},{x:.21875,y:.21875},{x:.28125,y:.21875},{x:.28125,y:.21875},{x:.34375,y:.21875},{x:.34375,y:.21875},{x:.40625,y:.21875},{x:.40625,y:.21875},{x:.46875,y:.21875},{x:.46875,y:.21875},{x:.53125,y:.21875},{x:.53125,y:.21875},{x:.59375,y:.21875},{x:.59375,y:.21875},{x:.65625,y:.21875},{x:.65625,y:.21875},{x:.71875,y:.21875},{x:.71875,y:.21875},{x:.78125,y:.21875},{x:.78125,y:.21875},{x:.84375,y:.21875},{x:.84375,y:.21875},{x:.90625,y:.21875},{x:.90625,y:.21875},{x:.96875,y:.21875},{x:.96875,y:.21875},{x:.03125,y:.28125},{x:.03125,y:.28125},{x:.09375,y:.28125},{x:.09375,y:.28125},{x:.15625,y:.28125},{x:.15625,y:.28125},{x:.21875,y:.28125},{x:.21875,y:.28125},{x:.28125,y:.28125},{x:.28125,y:.28125},{x:.34375,y:.28125},{x:.34375,y:.28125},{x:.40625,y:.28125},{x:.40625,y:.28125},{x:.46875,y:.28125},{x:.46875,y:.28125},{x:.53125,y:.28125},{x:.53125,y:.28125},{x:.59375,y:.28125},{x:.59375,y:.28125},{x:.65625,y:.28125},{x:.65625,y:.28125},{x:.71875,y:.28125},{x:.71875,y:.28125},{x:.78125,y:.28125},{x:.78125,y:.28125},{x:.84375,y:.28125},{x:.84375,y:.28125},{x:.90625,y:.28125},{x:.90625,y:.28125},{x:.96875,y:.28125},{x:.96875,y:.28125},{x:.03125,y:.34375},{x:.03125,y:.34375},{x:.09375,y:.34375},{x:.09375,y:.34375},{x:.15625,y:.34375},{x:.15625,y:.34375},{x:.21875,y:.34375},{x:.21875,y:.34375},{x:.28125,y:.34375},{x:.28125,y:.34375},{x:.34375,y:.34375},{x:.34375,y:.34375},{x:.40625,y:.34375},{x:.40625,y:.34375},{x:.46875,y:.34375},{x:.46875,y:.34375},{x:.53125,y:.34375},{x:.53125,y:.34375},{x:.59375,y:.34375},{x:.59375,y:.34375},{x:.65625,y:.34375},{x:.65625,y:.34375},{x:.71875,y:.34375},{x:.71875,y:.34375},{x:.78125,y:.34375},{x:.78125,y:.34375},{x:.84375,y:.34375},{x:.84375,y:.34375},{x:.90625,y:.34375},{x:.90625,y:.34375},{x:.96875,y:.34375},{x:.96875,y:.34375},{x:.03125,y:.40625},{x:.03125,y:.40625},{x:.09375,y:.40625},{x:.09375,y:.40625},{x:.15625,y:.40625},{x:.15625,y:.40625},{x:.21875,y:.40625},{x:.21875,y:.40625},{x:.28125,y:.40625},{x:.28125,y:.40625},{x:.34375,y:.40625},{x:.34375,y:.40625},{x:.40625,y:.40625},{x:.40625,y:.40625},{x:.46875,y:.40625},{x:.46875,y:.40625},{x:.53125,y:.40625},{x:.53125,y:.40625},{x:.59375,y:.40625},{x:.59375,y:.40625},{x:.65625,y:.40625},{x:.65625,y:.40625},{x:.71875,y:.40625},{x:.71875,y:.40625},{x:.78125,y:.40625},{x:.78125,y:.40625},{x:.84375,y:.40625},{x:.84375,y:.40625},{x:.90625,y:.40625},{x:.90625,y:.40625},{x:.96875,y:.40625},{x:.96875,y:.40625},{x:.03125,y:.46875},{x:.03125,y:.46875},{x:.09375,y:.46875},{x:.09375,y:.46875},{x:.15625,y:.46875},{x:.15625,y:.46875},{x:.21875,y:.46875},{x:.21875,y:.46875},{x:.28125,y:.46875},{x:.28125,y:.46875},{x:.34375,y:.46875},{x:.34375,y:.46875},{x:.40625,y:.46875},{x:.40625,y:.46875},{x:.46875,y:.46875},{x:.46875,y:.46875},{x:.53125,y:.46875},{x:.53125,y:.46875},{x:.59375,y:.46875},{x:.59375,y:.46875},{x:.65625,y:.46875},{x:.65625,y:.46875},{x:.71875,y:.46875},{x:.71875,y:.46875},{x:.78125,y:.46875},{x:.78125,y:.46875},{x:.84375,y:.46875},{x:.84375,y:.46875},{x:.90625,y:.46875},{x:.90625,y:.46875},{x:.96875,y:.46875},{x:.96875,y:.46875},{x:.03125,y:.53125},{x:.03125,y:.53125},{x:.09375,y:.53125},{x:.09375,y:.53125},{x:.15625,y:.53125},{x:.15625,y:.53125},{x:.21875,y:.53125},{x:.21875,y:.53125},{x:.28125,y:.53125},{x:.28125,y:.53125},{x:.34375,y:.53125},{x:.34375,y:.53125},{x:.40625,y:.53125},{x:.40625,y:.53125},{x:.46875,y:.53125},{x:.46875,y:.53125},{x:.53125,y:.53125},{x:.53125,y:.53125},{x:.59375,y:.53125},{x:.59375,y:.53125},{x:.65625,y:.53125},{x:.65625,y:.53125},{x:.71875,y:.53125},{x:.71875,y:.53125},{x:.78125,y:.53125},{x:.78125,y:.53125},{x:.84375,y:.53125},{x:.84375,y:.53125},{x:.90625,y:.53125},{x:.90625,y:.53125},{x:.96875,y:.53125},{x:.96875,y:.53125},{x:.03125,y:.59375},{x:.03125,y:.59375},{x:.09375,y:.59375},{x:.09375,y:.59375},{x:.15625,y:.59375},{x:.15625,y:.59375},{x:.21875,y:.59375},{x:.21875,y:.59375},{x:.28125,y:.59375},{x:.28125,y:.59375},{x:.34375,y:.59375},{x:.34375,y:.59375},{x:.40625,y:.59375},{x:.40625,y:.59375},{x:.46875,y:.59375},{x:.46875,y:.59375},{x:.53125,y:.59375},{x:.53125,y:.59375},{x:.59375,y:.59375},{x:.59375,y:.59375},{x:.65625,y:.59375},{x:.65625,y:.59375},{x:.71875,y:.59375},{x:.71875,y:.59375},{x:.78125,y:.59375},{x:.78125,y:.59375},{x:.84375,y:.59375},{x:.84375,y:.59375},{x:.90625,y:.59375},{x:.90625,y:.59375},{x:.96875,y:.59375},{x:.96875,y:.59375},{x:.03125,y:.65625},{x:.03125,y:.65625},{x:.09375,y:.65625},{x:.09375,y:.65625},{x:.15625,y:.65625},{x:.15625,y:.65625},{x:.21875,y:.65625},{x:.21875,y:.65625},{x:.28125,y:.65625},{x:.28125,y:.65625},{x:.34375,y:.65625},{x:.34375,y:.65625},{x:.40625,y:.65625},{x:.40625,y:.65625},{x:.46875,y:.65625},{x:.46875,y:.65625},{x:.53125,y:.65625},{x:.53125,y:.65625},{x:.59375,y:.65625},{x:.59375,y:.65625},{x:.65625,y:.65625},{x:.65625,y:.65625},{x:.71875,y:.65625},{x:.71875,y:.65625},{x:.78125,y:.65625},{x:.78125,y:.65625},{x:.84375,y:.65625},{x:.84375,y:.65625},{x:.90625,y:.65625},{x:.90625,y:.65625},{x:.96875,y:.65625},{x:.96875,y:.65625},{x:.03125,y:.71875},{x:.03125,y:.71875},{x:.09375,y:.71875},{x:.09375,y:.71875},{x:.15625,y:.71875},{x:.15625,y:.71875},{x:.21875,y:.71875},{x:.21875,y:.71875},{x:.28125,y:.71875},{x:.28125,y:.71875},{x:.34375,y:.71875},{x:.34375,y:.71875},{x:.40625,y:.71875},{x:.40625,y:.71875},{x:.46875,y:.71875},{x:.46875,y:.71875},{x:.53125,y:.71875},{x:.53125,y:.71875},{x:.59375,y:.71875},{x:.59375,y:.71875},{x:.65625,y:.71875},{x:.65625,y:.71875},{x:.71875,y:.71875},{x:.71875,y:.71875},{x:.78125,y:.71875},{x:.78125,y:.71875},{x:.84375,y:.71875},{x:.84375,y:.71875},{x:.90625,y:.71875},{x:.90625,y:.71875},{x:.96875,y:.71875},{x:.96875,y:.71875},{x:.03125,y:.78125},{x:.03125,y:.78125},{x:.09375,y:.78125},{x:.09375,y:.78125},{x:.15625,y:.78125},{x:.15625,y:.78125},{x:.21875,y:.78125},{x:.21875,y:.78125},{x:.28125,y:.78125},{x:.28125,y:.78125},{x:.34375,y:.78125},{x:.34375,y:.78125},{x:.40625,y:.78125},{x:.40625,y:.78125},{x:.46875,y:.78125},{x:.46875,y:.78125},{x:.53125,y:.78125},{x:.53125,y:.78125},{x:.59375,y:.78125},{x:.59375,y:.78125},{x:.65625,y:.78125},{x:.65625,y:.78125},{x:.71875,y:.78125},{x:.71875,y:.78125},{x:.78125,y:.78125},{x:.78125,y:.78125},{x:.84375,y:.78125},{x:.84375,y:.78125},{x:.90625,y:.78125},{x:.90625,y:.78125},{x:.96875,y:.78125},{x:.96875,y:.78125},{x:.03125,y:.84375},{x:.03125,y:.84375},{x:.09375,y:.84375},{x:.09375,y:.84375},{x:.15625,y:.84375},{x:.15625,y:.84375},{x:.21875,y:.84375},{x:.21875,y:.84375},{x:.28125,y:.84375},{x:.28125,y:.84375},{x:.34375,y:.84375},{x:.34375,y:.84375},{x:.40625,y:.84375},{x:.40625,y:.84375},{x:.46875,y:.84375},{x:.46875,y:.84375},{x:.53125,y:.84375},{x:.53125,y:.84375},{x:.59375,y:.84375},{x:.59375,y:.84375},{x:.65625,y:.84375},{x:.65625,y:.84375},{x:.71875,y:.84375},{x:.71875,y:.84375},{x:.78125,y:.84375},{x:.78125,y:.84375},{x:.84375,y:.84375},{x:.84375,y:.84375},{x:.90625,y:.84375},{x:.90625,y:.84375},{x:.96875,y:.84375},{x:.96875,y:.84375},{x:.03125,y:.90625},{x:.03125,y:.90625},{x:.09375,y:.90625},{x:.09375,y:.90625},{x:.15625,y:.90625},{x:.15625,y:.90625},{x:.21875,y:.90625},{x:.21875,y:.90625},{x:.28125,y:.90625},{x:.28125,y:.90625},{x:.34375,y:.90625},{x:.34375,y:.90625},{x:.40625,y:.90625},{x:.40625,y:.90625},{x:.46875,y:.90625},{x:.46875,y:.90625},{x:.53125,y:.90625},{x:.53125,y:.90625},{x:.59375,y:.90625},{x:.59375,y:.90625},{x:.65625,y:.90625},{x:.65625,y:.90625},{x:.71875,y:.90625},{x:.71875,y:.90625},{x:.78125,y:.90625},{x:.78125,y:.90625},{x:.84375,y:.90625},{x:.84375,y:.90625},{x:.90625,y:.90625},{x:.90625,y:.90625},{x:.96875,y:.90625},{x:.96875,y:.90625},{x:.03125,y:.96875},{x:.03125,y:.96875},{x:.09375,y:.96875},{x:.09375,y:.96875},{x:.15625,y:.96875},{x:.15625,y:.96875},{x:.21875,y:.96875},{x:.21875,y:.96875},{x:.28125,y:.96875},{x:.28125,y:.96875},{x:.34375,y:.96875},{x:.34375,y:.96875},{x:.40625,y:.96875},{x:.40625,y:.96875},{x:.46875,y:.96875},{x:.46875,y:.96875},{x:.53125,y:.96875},{x:.53125,y:.96875},{x:.59375,y:.96875},{x:.59375,y:.96875},{x:.65625,y:.96875},{x:.65625,y:.96875},{x:.71875,y:.96875},{x:.71875,y:.96875},{x:.78125,y:.96875},{x:.78125,y:.96875},{x:.84375,y:.96875},{x:.84375,y:.96875},{x:.90625,y:.96875},{x:.90625,y:.96875},{x:.96875,y:.96875},{x:.96875,y:.96875},{x:.0625,y:.0625},{x:.0625,y:.0625},{x:.0625,y:.0625},{x:.0625,y:.0625},{x:.0625,y:.0625},{x:.0625,y:.0625},{x:.1875,y:.0625},{x:.1875,y:.0625},{x:.1875,y:.0625},{x:.1875,y:.0625},{x:.1875,y:.0625},{x:.1875,y:.0625},{x:.3125,y:.0625},{x:.3125,y:.0625},{x:.3125,y:.0625},{x:.3125,y:.0625},{x:.3125,y:.0625},{x:.3125,y:.0625},{x:.4375,y:.0625},{x:.4375,y:.0625},{x:.4375,y:.0625},{x:.4375,y:.0625},{x:.4375,y:.0625},{x:.4375,y:.0625},{x:.5625,y:.0625},{x:.5625,y:.0625},{x:.5625,y:.0625},{x:.5625,y:.0625},{x:.5625,y:.0625},{x:.5625,y:.0625},{x:.6875,y:.0625},{x:.6875,y:.0625},{x:.6875,y:.0625},{x:.6875,y:.0625},{x:.6875,y:.0625},{x:.6875,y:.0625},{x:.8125,y:.0625},{x:.8125,y:.0625},{x:.8125,y:.0625},{x:.8125,y:.0625},{x:.8125,y:.0625},{x:.8125,y:.0625},{x:.9375,y:.0625},{x:.9375,y:.0625},{x:.9375,y:.0625},{x:.9375,y:.0625},{x:.9375,y:.0625},{x:.9375,y:.0625},{x:.0625,y:.1875},{x:.0625,y:.1875},{x:.0625,y:.1875},{x:.0625,y:.1875},{x:.0625,y:.1875},{x:.0625,y:.1875},{x:.1875,y:.1875},{x:.1875,y:.1875},{x:.1875,y:.1875},{x:.1875,y:.1875},{x:.1875,y:.1875},{x:.1875,y:.1875},{x:.3125,y:.1875},{x:.3125,y:.1875},{x:.3125,y:.1875},{x:.3125,y:.1875},{x:.3125,y:.1875},{x:.3125,y:.1875},{x:.4375,y:.1875},{x:.4375,y:.1875},{x:.4375,y:.1875},{x:.4375,y:.1875},{x:.4375,y:.1875},{x:.4375,y:.1875},{x:.5625,y:.1875},{x:.5625,y:.1875},{x:.5625,y:.1875},{x:.5625,y:.1875},{x:.5625,y:.1875},{x:.5625,y:.1875},{x:.6875,y:.1875},{x:.6875,y:.1875},{x:.6875,y:.1875},{x:.6875,y:.1875},{x:.6875,y:.1875},{x:.6875,y:.1875},{x:.8125,y:.1875},{x:.8125,y:.1875},{x:.8125,y:.1875},{x:.8125,y:.1875},{x:.8125,y:.1875},{x:.8125,y:.1875},{x:.9375,y:.1875},{x:.9375,y:.1875},{x:.9375,y:.1875},{x:.9375,y:.1875},{x:.9375,y:.1875},{x:.9375,y:.1875},{x:.0625,y:.3125},{x:.0625,y:.3125},{x:.0625,y:.3125},{x:.0625,y:.3125},{x:.0625,y:.3125},{x:.0625,y:.3125},{x:.1875,y:.3125},{x:.1875,y:.3125},{x:.1875,y:.3125},{x:.1875,y:.3125},{x:.1875,y:.3125},{x:.1875,y:.3125},{x:.3125,y:.3125},{x:.3125,y:.3125},{x:.3125,y:.3125},{x:.3125,y:.3125},{x:.3125,y:.3125},{x:.3125,y:.3125},{x:.4375,y:.3125},{x:.4375,y:.3125},{x:.4375,y:.3125},{x:.4375,y:.3125},{x:.4375,y:.3125},{x:.4375,y:.3125},{x:.5625,y:.3125},{x:.5625,y:.3125},{x:.5625,y:.3125},{x:.5625,y:.3125},{x:.5625,y:.3125},{x:.5625,y:.3125},{x:.6875,y:.3125},{x:.6875,y:.3125},{x:.6875,y:.3125},{x:.6875,y:.3125},{x:.6875,y:.3125},{x:.6875,y:.3125},{x:.8125,y:.3125},{x:.8125,y:.3125},{x:.8125,y:.3125},{x:.8125,y:.3125},{x:.8125,y:.3125},{x:.8125,y:.3125},{x:.9375,y:.3125},{x:.9375,y:.3125},{x:.9375,y:.3125},{x:.9375,y:.3125},{x:.9375,y:.3125},{x:.9375,y:.3125},{x:.0625,y:.4375},{x:.0625,y:.4375},{x:.0625,y:.4375},{x:.0625,y:.4375},{x:.0625,y:.4375},{x:.0625,y:.4375},{x:.1875,y:.4375},{x:.1875,y:.4375},{x:.1875,y:.4375},{x:.1875,y:.4375},{x:.1875,y:.4375},{x:.1875,y:.4375},{x:.3125,y:.4375},{x:.3125,y:.4375},{x:.3125,y:.4375},{x:.3125,y:.4375},{x:.3125,y:.4375},{x:.3125,y:.4375},{x:.4375,y:.4375},{x:.4375,y:.4375},{x:.4375,y:.4375},{x:.4375,y:.4375},{x:.4375,y:.4375},{x:.4375,y:.4375},{x:.5625,y:.4375},{x:.5625,y:.4375},{x:.5625,y:.4375},{x:.5625,y:.4375},{x:.5625,y:.4375},{x:.5625,y:.4375},{x:.6875,y:.4375},{x:.6875,y:.4375},{x:.6875,y:.4375},{x:.6875,y:.4375},{x:.6875,y:.4375},{x:.6875,y:.4375},{x:.8125,y:.4375},{x:.8125,y:.4375},{x:.8125,y:.4375},{x:.8125,y:.4375},{x:.8125,y:.4375},{x:.8125,y:.4375},{x:.9375,y:.4375},{x:.9375,y:.4375},{x:.9375,y:.4375},{x:.9375,y:.4375},{x:.9375,y:.4375},{x:.9375,y:.4375},{x:.0625,y:.5625},{x:.0625,y:.5625},{x:.0625,y:.5625},{x:.0625,y:.5625},{x:.0625,y:.5625},{x:.0625,y:.5625},{x:.1875,y:.5625},{x:.1875,y:.5625},{x:.1875,y:.5625},{x:.1875,y:.5625},{x:.1875,y:.5625},{x:.1875,y:.5625},{x:.3125,y:.5625},{x:.3125,y:.5625},{x:.3125,y:.5625},{x:.3125,y:.5625},{x:.3125,y:.5625},{x:.3125,y:.5625},{x:.4375,y:.5625},{x:.4375,y:.5625},{x:.4375,y:.5625},{x:.4375,y:.5625},{x:.4375,y:.5625},{x:.4375,y:.5625},{x:.5625,y:.5625},{x:.5625,y:.5625},{x:.5625,y:.5625},{x:.5625,y:.5625},{x:.5625,y:.5625},{x:.5625,y:.5625},{x:.6875,y:.5625},{x:.6875,y:.5625},{x:.6875,y:.5625},{x:.6875,y:.5625},{x:.6875,y:.5625},{x:.6875,y:.5625},{x:.8125,y:.5625},{x:.8125,y:.5625},{x:.8125,y:.5625},{x:.8125,y:.5625},{x:.8125,y:.5625},{x:.8125,y:.5625},{x:.9375,y:.5625},{x:.9375,y:.5625},{x:.9375,y:.5625},{x:.9375,y:.5625},{x:.9375,y:.5625},{x:.9375,y:.5625},{x:.0625,y:.6875},{x:.0625,y:.6875},{x:.0625,y:.6875},{x:.0625,y:.6875},{x:.0625,y:.6875},{x:.0625,y:.6875},{x:.1875,y:.6875},{x:.1875,y:.6875},{x:.1875,y:.6875},{x:.1875,y:.6875},{x:.1875,y:.6875},{x:.1875,y:.6875},{x:.3125,y:.6875},{x:.3125,y:.6875},{x:.3125,y:.6875},{x:.3125,y:.6875},{x:.3125,y:.6875},{x:.3125,y:.6875},{x:.4375,y:.6875},{x:.4375,y:.6875},{x:.4375,y:.6875},{x:.4375,y:.6875},{x:.4375,y:.6875},{x:.4375,y:.6875},{x:.5625,y:.6875},{x:.5625,y:.6875},{x:.5625,y:.6875},{x:.5625,y:.6875},{x:.5625,y:.6875},{x:.5625,y:.6875},{x:.6875,y:.6875},{x:.6875,y:.6875},{x:.6875,y:.6875},{x:.6875,y:.6875},{x:.6875,y:.6875},{x:.6875,y:.6875},{x:.8125,y:.6875},{x:.8125,y:.6875},{x:.8125,y:.6875},{x:.8125,y:.6875},{x:.8125,y:.6875},{x:.8125,y:.6875},{x:.9375,y:.6875},{x:.9375,y:.6875},{x:.9375,y:.6875},{x:.9375,y:.6875},{x:.9375,y:.6875},{x:.9375,y:.6875},{x:.0625,y:.8125},{x:.0625,y:.8125},{x:.0625,y:.8125},{x:.0625,y:.8125},{x:.0625,y:.8125},{x:.0625,y:.8125},{x:.1875,y:.8125},{x:.1875,y:.8125},{x:.1875,y:.8125},{x:.1875,y:.8125},{x:.1875,y:.8125},{x:.1875,y:.8125},{x:.3125,y:.8125},{x:.3125,y:.8125},{x:.3125,y:.8125},{x:.3125,y:.8125},{x:.3125,y:.8125},{x:.3125,y:.8125},{x:.4375,y:.8125},{x:.4375,y:.8125},{x:.4375,y:.8125},{x:.4375,y:.8125},{x:.4375,y:.8125},{x:.4375,y:.8125},{x:.5625,y:.8125},{x:.5625,y:.8125},{x:.5625,y:.8125},{x:.5625,y:.8125},{x:.5625,y:.8125},{x:.5625,y:.8125},{x:.6875,y:.8125},{x:.6875,y:.8125},{x:.6875,y:.8125},{x:.6875,y:.8125},{x:.6875,y:.8125},{x:.6875,y:.8125},{x:.8125,y:.8125},{x:.8125,y:.8125},{x:.8125,y:.8125},{x:.8125,y:.8125},{x:.8125,y:.8125},{x:.8125,y:.8125},{x:.9375,y:.8125},{x:.9375,y:.8125},{x:.9375,y:.8125},{x:.9375,y:.8125},{x:.9375,y:.8125},{x:.9375,y:.8125},{x:.0625,y:.9375},{x:.0625,y:.9375},{x:.0625,y:.9375},{x:.0625,y:.9375},{x:.0625,y:.9375},{x:.0625,y:.9375},{x:.1875,y:.9375},{x:.1875,y:.9375},{x:.1875,y:.9375},{x:.1875,y:.9375},{x:.1875,y:.9375},{x:.1875,y:.9375},{x:.3125,y:.9375},{x:.3125,y:.9375},{x:.3125,y:.9375},{x:.3125,y:.9375},{x:.3125,y:.9375},{x:.3125,y:.9375},{x:.4375,y:.9375},{x:.4375,y:.9375},{x:.4375,y:.9375},{x:.4375,y:.9375},{x:.4375,y:.9375},{x:.4375,y:.9375},{x:.5625,y:.9375},{x:.5625,y:.9375},{x:.5625,y:.9375},{x:.5625,y:.9375},{x:.5625,y:.9375},{x:.5625,y:.9375},{x:.6875,y:.9375},{x:.6875,y:.9375},{x:.6875,y:.9375},{x:.6875,y:.9375},{x:.6875,y:.9375},{x:.6875,y:.9375},{x:.8125,y:.9375},{x:.8125,y:.9375},{x:.8125,y:.9375},{x:.8125,y:.9375},{x:.8125,y:.9375},{x:.8125,y:.9375},{x:.9375,y:.9375},{x:.9375,y:.9375},{x:.9375,y:.9375},{x:.9375,y:.9375},{x:.9375,y:.9375},{x:.9375,y:.9375}];var hb=class{constructor(t){ve(this,"model");ve(this,"anchors");ve(this,"anchorsTensor");ve(this,"inputSize");ve(this,"inputSizeTensor");ve(this,"doubleInputSizeTensor");this.model=t,this.anchors=Z6.map(n=>[n.x,n.y]),this.anchorsTensor=dr(this.anchors),this.inputSize=this.model&&this.model.inputs&&this.model.inputs[0].shape?this.model.inputs[0].shape[2]:0,this.inputSizeTensor=Zt([this.inputSize,this.inputSize]),this.doubleInputSizeTensor=Zt([this.inputSize*2,this.inputSize*2])}normalizeBoxes(t){return j(()=>{let n=_e(t,[0,0],[-1,2]),s=_e(t,[0,2],[-1,2]),r=ue(fe(n,this.inputSizeTensor),this.anchorsTensor),a=fe(s,this.doubleInputSizeTensor),o=L(xe(r,a),this.inputSizeTensor),i=L(ue(r,a),this.inputSizeTensor);return Ru([o,i],1)})}normalizeLandmarks(t,n){return j(()=>{let s=ue(fe(G(t,[-1,7,2]),this.inputSizeTensor),this.anchors[n]);return L(s,this.inputSizeTensor)})}async getBoxes(t,n){let s={};s.batched=this.model.predict(t),s.predictions=dt(s.batched),s.scores=j(()=>dt(ns(_e(s.predictions,[0,0],[-1,1]))));let r=await s.scores.data();s.boxes=_e(s.predictions,[0,1],[-1,4]),s.norm=this.normalizeBoxes(s.boxes),s.nms=await $e.nonMaxSuppressionAsync(s.norm,s.scores,3*n.hand.maxDetected,n.hand.iouThreshold,n.hand.minConfidence);let a=await s.nms.array(),o=[];for(let i of a){let l=_e(s.norm,[i,0],[1,-1]),c=j(()=>G(this.normalizeLandmarks(_e(s.predictions,[i,5],[1,14]),i),[-1,2]));o.push({box:l,palmLandmarks:c,confidence:r[i]})}for(let i of Object.keys(s))te(s[i]);return o}async estimateHandBounds(t,n){let s=t.shape[1],r=t.shape[2],a=j(()=>xe(fe($e.resizeBilinear(t,[this.inputSize,this.inputSize]),127.5),1)),o=await this.getBoxes(a,n);te(a);let i=[];if(!o||o.length===0)return i;for(let l of o){let c=await l.box.data(),u=c.slice(0,2),d=c.slice(2,4),p=await l.palmLandmarks.array();te(l.box),te(l.palmLandmarks),i.push(K6({startPoint:u,endPoint:d,palmLandmarks:p,confidence:l.confidence},[r/this.inputSize,s/this.inputSize]))}return i}};function _0e(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function Y6(e,t){let n=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]);return _0e(n)}var J6=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]];function Vo(e,t){let n=0;for(let s=0;s<e.length;s++)n+=e[s]*t[s];return n}function P0e(e,t){let n=[];for(let s=0;s<e.length;s++)n.push(e[s][t]);return n}function Q6(e,t){let n=[],s=e.length;for(let r=0;r<s;r++){n.push([]);for(let a=0;a<s;a++)n[r].push(Vo(e[r],P0e(t,a)))}return n}function fb(e,t){let n=Math.cos(e),s=Math.sin(e),r=[[n,-s,0],[s,n,0],[0,0,1]],a=J6(t[0],t[1]),o=Q6(a,r),i=J6(-t[0],-t[1]);return Q6(o,i)}function e8(e){let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],n=[e[0][2],e[1][2]],s=[-Vo(t[0],n),-Vo(t[1],n)];return[t[0].concat(s[0]),t[1].concat(s[1]),[0,0,1]]}function mb(e,t){return[Vo(e,t[0]),Vo(e,t[1])]}var F0e=5,t8=1.65,n8=[0,5,9,13,17,1,2],O0e=0,M0e=2,gb=class{constructor(t,n){ve(this,"handDetector");ve(this,"handPoseModel");ve(this,"inputSize");ve(this,"storedBoxes");ve(this,"skipped");ve(this,"detectedHands");this.handDetector=t,this.handPoseModel=n,this.inputSize=this.handPoseModel&&this.handPoseModel.inputs[0].shape?this.handPoseModel.inputs[0].shape[2]:0,this.storedBoxes=[],this.skipped=0,this.detectedHands=0}calculateLandmarksBoundingBox(t){let n=t.map(o=>o[0]),s=t.map(o=>o[1]),r=[Math.min(...n),Math.min(...s)],a=[Math.max(...n),Math.max(...s)];return{startPoint:r,endPoint:a}}getBoxForPalmLandmarks(t,n){let s=t.map(a=>mb([...a,1],n)),r=this.calculateLandmarksBoundingBox(s);return m0(g0(r),F0e)}getBoxForHandLandmarks(t){let n=this.calculateLandmarksBoundingBox(t),s=m0(g0(n),t8);s.palmLandmarks=[];for(let r=0;r<n8.length;r++)s.palmLandmarks.push(t[n8[r]].slice(0,2));return s}transformRawCoords(t,n,s,r){let a=f0(n),o=[a[0]/this.inputSize,a[1]/this.inputSize,(a[0]+a[1])/this.inputSize/2],i=t.map(h=>[o[0]*(h[0]-this.inputSize/2),o[1]*(h[1]-this.inputSize/2),o[2]*h[2]]),l=fb(s,[0,0]),c=i.map(h=>[...mb(h,l),h[2]]),u=e8(r),d=[...Pp(n),1],p=[Vo(d,u[0]),Vo(d,u[1])];return c.map(h=>[Math.trunc(h[0]+p[0]),Math.trunc(h[1]+p[1]),Math.trunc(h[2])])}async estimateHands(t,n){let s=!1,r;(this.skipped===0||this.skipped>n.hand.skipFrames||!n.hand.landmarks||!n.skipFrame)&&(r=await this.handDetector.estimateHandBounds(t,n),this.skipped=0),n.skipFrame&&this.skipped++,r&&r.length>0&&(r.length!==this.detectedHands&&this.detectedHands!==n.hand.maxDetected||!n.hand.landmarks)&&(this.detectedHands=0,this.storedBoxes=[...r],this.storedBoxes.length>0&&(s=!0));let a=[];for(let o=0;o<this.storedBoxes.length;o++){let i=this.storedBoxes[o];if(!!i)if(n.hand.landmarks){let l=n.hand.rotation?Y6(i.palmLandmarks[O0e],i.palmLandmarks[M0e]):0,c=Pp(i),u=[c[0]/t.shape[2],c[1]/t.shape[1]],d=n.hand.rotation&&ie.kernels.includes("rotatewithoffset")?$e.rotateWithOffset(t,l,0,u):t.clone(),p=fb(-l,c),h=s?this.getBoxForPalmLandmarks(i.palmLandmarks,p):i,f=X6(h,d,[this.inputSize,this.inputSize]),m=fe(f,255);te(f),te(d);let[g,y]=await this.handPoseModel.predict(m);te(m);let A=(await g.data())[0];if(te(g),A>=n.hand.minConfidence/4){let x=G(y,[-1,3]),b=await x.array();te(y),te(x);let w=this.transformRawCoords(b,h,l,p),k=this.getBoxForHandLandmarks(w);this.storedBoxes[o]={...k,confidence:A};let S={landmarks:w,confidence:A,boxConfidence:i.confidence,fingerConfidence:A,box:{topLeft:k.startPoint,bottomRight:k.endPoint}};a.push(S)}else this.storedBoxes[o]=null;te(y)}else{let l=m0(g0(i),t8),c={confidence:i.confidence,boxConfidence:i.confidence,fingerConfidence:0,box:{topLeft:l.startPoint,bottomRight:l.endPoint},landmarks:[]};a.push(c)}}return this.storedBoxes=this.storedBoxes.filter(o=>o!==null),this.detectedHands=a.length,a.length>n.hand.maxDetected&&(a.length=n.hand.maxDetected),a}};var Je={thumb:0,index:1,middle:2,ring:3,pinky:4,all:[0,1,2,3,4],nameMapping:{0:"thumb",1:"index",2:"middle",3:"ring",4:"pinky"},pointsMapping:{0:[[0,1],[1,2],[2,3],[3,4]],1:[[0,5],[5,6],[6,7],[7,8]],2:[[0,9],[9,10],[10,11],[11,12]],3:[[0,13],[13,14],[14,15],[15,16]],4:[[0,17],[17,18],[18,19],[19,20]]},getName:e=>Je.nameMapping[e],getPoints:e=>Je.pointsMapping[e]},cs={none:0,half:1,full:2,nameMapping:{0:"none",1:"half",2:"full"},getName:e=>cs.nameMapping[e]},Ze={verticalUp:0,verticalDown:1,horizontalLeft:2,horizontalRight:3,diagonalUpRight:4,diagonalUpLeft:5,diagonalDownRight:6,diagonalDownLeft:7,nameMapping:{0:"verticalUp",1:"verticalDown",2:"horizontalLeft",3:"horizontalRight",4:"diagonalUpRight",5:"diagonalUpLeft",6:"diagonalDownRight",7:"diagonalDownLeft"},getName:e=>Ze.nameMapping[e]},y0=class{constructor(t){ve(this,"name");ve(this,"curls");ve(this,"directions");ve(this,"weights");ve(this,"weightsRelative");this.name=t,this.curls={},this.directions={},this.weights=[1,1,1,1,1],this.weightsRelative=[1,1,1,1,1]}addCurl(t,n,s){typeof this.curls[t]=="undefined"&&(this.curls[t]=[]),this.curls[t].push([n,s])}addDirection(t,n,s){this.directions[t]||(this.directions[t]=[]),this.directions[t].push([n,s])}setWeight(t,n){this.weights[t]=n;let s=this.weights.reduce((r,a)=>r+a,0);this.weightsRelative=this.weights.map(r=>r*5/s)}matchAgainst(t,n){let s=0;for(let r in t){let a=t[r],o=this.curls[r];if(typeof o=="undefined"){s+=this.weightsRelative[r];continue}for(let[i,l]of o)if(a===i){s+=l*this.weightsRelative[r];break}}for(let r in n){let a=n[r],o=this.directions[r];if(typeof o=="undefined"){s+=this.weightsRelative[r];continue}for(let[i,l]of o)if(a===i){s+=l*this.weightsRelative[r];break}}return s/10}};var Uo=new y0("thumbs up");Uo.addCurl(Je.thumb,cs.none,1);Uo.addDirection(Je.thumb,Ze.verticalUp,1);Uo.addDirection(Je.thumb,Ze.diagonalUpLeft,.25);Uo.addDirection(Je.thumb,Ze.diagonalUpRight,.25);for(let e of[Je.index,Je.middle,Je.ring,Je.pinky])Uo.addCurl(e,cs.full,1),Uo.addDirection(e,Ze.horizontalLeft,1),Uo.addDirection(e,Ze.horizontalRight,1);var Qt=new y0("victory");Qt.addCurl(Je.thumb,cs.half,.5);Qt.addCurl(Je.thumb,cs.none,.5);Qt.addDirection(Je.thumb,Ze.verticalUp,1);Qt.addDirection(Je.thumb,Ze.diagonalUpLeft,1);Qt.addCurl(Je.index,cs.none,1);Qt.addDirection(Je.index,Ze.verticalUp,.75);Qt.addDirection(Je.index,Ze.diagonalUpLeft,1);Qt.addCurl(Je.middle,cs.none,1);Qt.addDirection(Je.middle,Ze.verticalUp,1);Qt.addDirection(Je.middle,Ze.diagonalUpLeft,.75);Qt.addCurl(Je.ring,cs.full,1);Qt.addDirection(Je.ring,Ze.verticalUp,.2);Qt.addDirection(Je.ring,Ze.diagonalUpLeft,1);Qt.addDirection(Je.ring,Ze.horizontalLeft,.2);Qt.addCurl(Je.pinky,cs.full,1);Qt.addDirection(Je.pinky,Ze.verticalUp,.2);Qt.addDirection(Je.pinky,Ze.diagonalUpLeft,1);Qt.addDirection(Je.pinky,Ze.horizontalLeft,.2);Qt.setWeight(Je.index,2);Qt.setWeight(Je.middle,2);var s8=[Uo,Qt];var z0e=.7,Nl={HALF_CURL_START_LIMIT:60,NO_CURL_START_LIMIT:130,DISTANCE_VOTE_POWER:1.1,SINGLE_ANGLE_VOTE_POWER:.9,TOTAL_ANGLE_VOTE_POWER:1.6};function r8(e,t,n,s){let r=(t-s)/(e-n),a=Math.atan(r)*180/Math.PI;return a<=0?a=-a:a>0&&(a=180-a),a}function a8(e,t){if(!e||!t)return[0,0];let n=r8(e[0],e[1],t[0],t[1]);if(e.length===2)return n;let s=r8(e[1],e[2],t[1],t[2]);return[n,s]}function o8(e,t=1){let n=0,s=0,r=0;return e>=75&&e<=105?n=1*t:e>=25&&e<=155?s=1*t:r=1*t,[n,s,r]}function L0e(e,t,n){let s=e[0]-t[0],r=e[0]-n[0],a=t[0]-n[0],o=e[1]-t[1],i=e[1]-n[1],l=t[1]-n[1],c=e[2]-t[2],u=e[2]-n[2],d=t[2]-n[2],p=Math.sqrt(s*s+o*o+c*c),h=Math.sqrt(r*r+i*i+u*u),f=Math.sqrt(a*a+l*l+d*d),m=(f*f+p*p-h*h)/(2*f*p);m>1?m=1:m<-1&&(m=-1);let g=Math.acos(m);g=57.2958*g%180;let y;return g>Nl.NO_CURL_START_LIMIT?y=cs.none:g>Nl.HALF_CURL_START_LIMIT?y=cs.half:y=cs.full,y}function i8(e,t,n,s){let r;return s===Math.abs(e)?e>0?r=Ze.horizontalLeft:r=Ze.horizontalRight:s===Math.abs(t)?t>0?r=Ze.horizontalLeft:r=Ze.horizontalRight:n>0?r=Ze.horizontalLeft:r=Ze.horizontalRight,r}function l8(e,t,n,s){let r;return s===Math.abs(e)?e<0?r=Ze.verticalDown:r=Ze.verticalUp:s===Math.abs(t)?t<0?r=Ze.verticalDown:r=Ze.verticalUp:n<0?r=Ze.verticalDown:r=Ze.verticalUp,r}function B0e(e,t,n,s,r,a,o,i){let l,c=l8(e,t,n,s),u=i8(r,a,o,i);return c===Ze.verticalUp?u===Ze.horizontalLeft?l=Ze.diagonalUpLeft:l=Ze.diagonalUpRight:u===Ze.horizontalLeft?l=Ze.diagonalDownLeft:l=Ze.diagonalDownRight,l}function W0e(e,t,n,s){let r=e[0]-t[0],a=e[0]-n[0],o=t[0]-n[0],i=e[1]-t[1],l=e[1]-n[1],c=t[1]-n[1],u=Math.max(Math.abs(r),Math.abs(a),Math.abs(o)),d=Math.max(Math.abs(i),Math.abs(l),Math.abs(c)),p=0,h=0,f=0,m=d/(u+1e-5);m>1.5?p+=Nl.DISTANCE_VOTE_POWER:m>.66?h+=Nl.DISTANCE_VOTE_POWER:f+=Nl.DISTANCE_VOTE_POWER;let g=Math.sqrt(r*r+i*i),y=Math.sqrt(a*a+l*l),A=Math.sqrt(o*o+c*c),x=Math.max(g,y,A),b=e[0],w=e[1],k=n[0],S=n[1];x===g?(k=n[0],S=n[1]):x===A&&(b=t[0],w=t[1]);let F=a8([b,w],[k,S]),R=o8(F,Nl.TOTAL_ANGLE_VOTE_POWER);p+=R[0],h+=R[1],f+=R[2];for(let T of s){let O=o8(T,Nl.SINGLE_ANGLE_VOTE_POWER);p+=O[0],h+=O[1],f+=O[2]}let D;return p===Math.max(p,h,f)?D=l8(l,i,c,d):f===Math.max(h,f)?D=i8(a,r,o,u):D=B0e(l,i,c,d,a,r,o,u),D}function u8(e){let t=[],n=[],s=[],r=[];if(!e)return{curls:s,directions:r};for(let a of Je.all){let o=Je.getPoints(a),i=[],l=[];for(let c of o){let u=e[c[0]],d=e[c[1]],p=a8(u,d),h=p[0],f=p[1];i.push(h),l.push(f)}t.push(i),n.push(l)}for(let a of Je.all){let o=a===Je.thumb?1:0,i=Je.getPoints(a),l=e[i[o][0]],c=e[i[o+1][1]],u=e[i[3][1]],d=L0e(l,c,u),p=W0e(l,c,u,t[a].slice(o));s[a]=d,r[a]=p}return{curls:s,directions:r}}function A0(e){if(!e||e.length===0)return null;let t=u8(e),n={};for(let s of Je.all)n[Je.getName(s)]={curl:cs.getName(t.curls[s]),direction:Ze.getName(t.directions[s])};return n}function c8(e){let t=[];if(!e||e.length===0)return t;let n=u8(e);for(let s of s8){let r=s.matchAgainst(n.curls,n.directions);r>=z0e&&t.push({name:s.name,confidence:r})}return t}var d8={thumb:[1,2,3,4],index:[5,6,7,8],middle:[9,10,11,12],ring:[13,14,15,16],pinky:[17,18,19,20],palm:[0]},ca,da,p8;async function yb(e,t){let n=await p8.estimateHands(e,t);if(!n)return[];let s=[];for(let r=0;r<n.length;r++){let a={};if(n[r].landmarks)for(let u of Object.keys(d8))a[u]=d8[u].map(d=>n[r].landmarks[d]);let o=n[r].landmarks,i=[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,0,0],l=[0,0,0,0];if(o&&o.length>0){for(let u of o)u[0]<i[0]&&(i[0]=u[0]),u[1]<i[1]&&(i[1]=u[1]),u[0]>i[2]&&(i[2]=u[0]),u[1]>i[3]&&(i[3]=u[1]);i[2]-=i[0],i[3]-=i[1],l=[i[0]/(e.shape[2]||0),i[1]/(e.shape[1]||0),i[2]/(e.shape[2]||0),i[3]/(e.shape[1]||0)]}else i=n[r].box?[Math.trunc(Math.max(0,n[r].box.topLeft[0])),Math.trunc(Math.max(0,n[r].box.topLeft[1])),Math.trunc(Math.min(e.shape[2]||0,n[r].box.bottomRight[0])-Math.max(0,n[r].box.topLeft[0])),Math.trunc(Math.min(e.shape[1]||0,n[r].box.bottomRight[1])-Math.max(0,n[r].box.topLeft[1]))]:[0,0,0,0],l=[n[r].box.topLeft[0]/(e.shape[2]||0),n[r].box.topLeft[1]/(e.shape[1]||0),(n[r].box.bottomRight[0]-n[r].box.topLeft[0])/(e.shape[2]||0),(n[r].box.bottomRight[1]-n[r].box.topLeft[1])/(e.shape[1]||0)];let c=A0(o);s.push({id:r,score:Math.round(100*n[r].confidence)/100,boxScore:Math.round(100*n[r].boxConfidence)/100,fingerScore:Math.round(100*n[r].fingerConfidence)/100,label:"hand",box:i,boxRaw:l,keypoints:o,annotations:a,landmarks:c})}return s}async function Ab(e){var n,s,r,a,o,i;ie.initial&&(ca=null,da=null),!ca||!da?([ca,da]=await Promise.all([e.hand.enabled?ut(ct(e.modelBasePath,((n=e.hand.detector)==null?void 0:n.modelPath)||""),{fromTFHub:(((s=e.hand.detector)==null?void 0:s.modelPath)||"").includes("tfhub.dev")}):null,e.hand.landmarks?ut(ct(e.modelBasePath,((r=e.hand.skeleton)==null?void 0:r.modelPath)||""),{fromTFHub:(((a=e.hand.skeleton)==null?void 0:a.modelPath)||"").includes("tfhub.dev")}):null]),e.hand.enabled&&(!ca||!ca.modelUrl?ae("load model failed:",((o=e.hand.detector)==null?void 0:o.modelPath)||""):e.debug&&ae("load model:",ca.modelUrl),!da||!da.modelUrl?ae("load model failed:",((i=e.hand.skeleton)==null?void 0:i.modelPath)||""):e.debug&&ae("load model:",da.modelUrl))):(e.debug&&ae("cached model:",ca.modelUrl),e.debug&&ae("cached model:",da.modelUrl));let t=new hb(ca);return p8=new gb(t,da),[ca,da]}function xb(e,t=[1,1]){let n=[e.map(i=>i[0]),e.map(i=>i[1])],s=[Math.min(...n[0]),Math.min(...n[1])],r=[Math.max(...n[0]),Math.max(...n[1])],a=[s[0],s[1],r[0]-s[0],r[1]-s[1]],o=[a[0]/t[0],a[1]/t[1],a[2]/t[0],a[3]/t[1]];return{box:a,boxRaw:o}}function h8(e,t=[1,1]){let n=[e.map(c=>c[0]),e.map(c=>c[1])],s=[Math.min(...n[0]),Math.min(...n[1])],r=[Math.max(...n[0]),Math.max(...n[1])],a=[(s[0]+r[0])/2,(s[1]+r[1])/2],o=Math.max(a[0]-s[0],a[1]-s[1],-a[0]+r[0],-a[1]+r[1]),i=[Math.trunc(a[0]-o),Math.trunc(a[1]-o),Math.trunc(2*o),Math.trunc(2*o)],l=[i[0]/t[0],i[1]/t[1],i[2]/t[0],i[3]/t[1]];return{box:i,boxRaw:l}}function vc(e,t){let n=[e[2]*t,e[3]*t];return[e[0]-(n[0]-e[2])/2,e[1]-(n[1]-e[3])/2,n[0],n[1]]}function Fp(e){return[Math.max(0,e[1]),Math.max(0,e[0]),Math.min(1,e[3]+e[1]),Math.min(1,e[2]+e[0])]}var Rt=[null,null],V0e=["StatefulPartitionedCall/Postprocessor/Slice","StatefulPartitionedCall/Postprocessor/ExpandDims_1"],Go=[[0,0],[0,0]],U0e=["hand","fist","pinch","point","face","tip","pinchtip"],f8=4,m8=1.6,G0e=512,H0e=1.4,x0=0,Ho=[0,0],ds={boxes:[],hands:[]},g8={thumb:[1,2,3,4],index:[5,6,7,8],middle:[9,10,11,12],ring:[13,14,15,16],pinky:[17,18,19,20],palm:[0]};async function y8(e){var t;if(ie.initial&&(Rt[0]=null),Rt[0])e.debug&&ae("cached model:",Rt[0].modelUrl);else{wc(["tensorlistreserve","enter","tensorlistfromtensor","merge","loopcond","switch","exit","tensorliststack","nextiteration","tensorlistsetitem","tensorlistgetitem","reciprocal","shape","split","where"],e),Rt[0]=await ut(ct(e.modelBasePath,((t=e.hand.detector)==null?void 0:t.modelPath)||""));let n=Object.values(Rt[0].modelSignature.inputs);Go[0][0]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[1].size):0,Go[0][1]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[2].size):0,!Rt[0]||!Rt[0].modelUrl?ae("load model failed:",e.object.modelPath):e.debug&&ae("load model:",Rt[0].modelUrl)}return Rt[0]}async function A8(e){var t;if(ie.initial&&(Rt[1]=null),Rt[1])e.debug&&ae("cached model:",Rt[1].modelUrl);else{Rt[1]=await ut(ct(e.modelBasePath,((t=e.hand.skeleton)==null?void 0:t.modelPath)||""));let n=Object.values(Rt[1].modelSignature.inputs);Go[1][0]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[1].size):0,Go[1][1]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[2].size):0,!Rt[1]||!Rt[1].modelUrl?ae("load model failed:",e.object.modelPath):e.debug&&ae("load model:",Rt[1].modelUrl)}return Rt[1]}async function j0e(e,t){let n=[];if(!e||!Rt[0])return n;let s={},r=(e.shape[2]||1)/(e.shape[1]||1),a=Math.min(Math.round((e.shape[1]||0)/8)*8,G0e),o=Math.round(a*r/8)*8;s.resize=$e.resizeBilinear(e,[a,o]),s.cast=pe(s.resize,"int32"),[s.rawScores,s.rawBoxes]=await Rt[0].executeAsync(s.cast,V0e),s.boxes=dt(s.rawBoxes,[0,2]),s.scores=dt(s.rawScores,[0]);let i=Wn(s.scores,1);te(i[f8]),i.splice(f8,1),s.filtered=Tn(i,1),te(i),s.max=Bn(s.filtered,1),s.argmax=Fs(s.filtered,1);let l=0;s.nms=await $e.nonMaxSuppressionAsync(s.boxes,s.max,t.hand.maxDetected,t.hand.iouThreshold,t.hand.minConfidence);let c=await s.nms.data(),u=await s.max.data(),d=await s.argmax.data();for(let p of Array.from(c)){let h=_e(s.boxes,p,1),f=await h.data();te(h);let m=[f[1],f[0],f[3]-f[1],f[2]-f[0]],g=vc(m,H0e),y=Fp(g),A=[Math.trunc(m[0]*Ho[0]),Math.trunc(m[1]*Ho[1]),Math.trunc(m[2]*Ho[0]),Math.trunc(m[3]*Ho[1])],x=u[p],b=U0e[d[p]],w={id:l++,score:x,box:A,boxRaw:g,boxCrop:y,label:b};n.push(w)}return Object.keys(s).forEach(p=>te(s[p])),n.sort((p,h)=>h.score-p.score),n.length>(t.hand.maxDetected||1)&&(n.length=t.hand.maxDetected||1),n}async function x8(e,t,n){let s={id:t.id,score:Math.round(100*t.score)/100,boxScore:Math.round(100*t.score)/100,fingerScore:0,box:t.box,boxRaw:t.boxRaw,label:t.label,keypoints:[],landmarks:{},annotations:{}};if(e&&Rt[1]&&n.hand.landmarks&&t.score>(n.hand.minConfidence||0)){let r={};r.crop=$e.cropAndResize(e,[t.boxCrop],[0],[Go[1][0],Go[1][1]],"bilinear"),r.cast=pe(r.crop,"float32"),r.div=fe(r.cast,255),[r.score,r.keypoints]=Rt[1].execute(r.div);let a=(await r.score.data())[0],o=(100-Math.trunc(100/(1+Math.exp(a))))/100;if(o>=(n.hand.minConfidence||0)){s.fingerScore=o,r.reshaped=G(r.keypoints,[-1,3]);let c=(await r.reshaped.array()).map(u=>[u[0]/Go[1][1],u[1]/Go[1][0],u[2]||0]).map(u=>[u[0]*t.boxRaw[2],u[1]*t.boxRaw[3],u[2]||0]);s.keypoints=c.map(u=>[Ho[0]*(u[0]+t.boxRaw[0]),Ho[1]*(u[1]+t.boxRaw[1]),u[2]||0]),s.landmarks=A0(s.keypoints);for(let u of Object.keys(g8))s.annotations[u]=g8[u].map(d=>s.landmarks&&s.keypoints[d]?s.keypoints[d]:null)}Object.keys(r).forEach(i=>te(r[i]))}return s}async function bb(e,t){var n,s;return!Rt[0]||!Rt[1]||!((n=Rt[0])==null?void 0:n.inputs[0].shape)||!((s=Rt[1])==null?void 0:s.inputs[0].shape)?[]:(Ho=[e.shape[2]||0,e.shape[1]||0],x0++,t.skipFrame&&x0<=(t.hand.skipFrames||0)?ds.hands:new Promise(async r=>{t.skipFrame&&x0<5*(t.hand.skipFrames||0)&&ds.hands.length>0?ds.hands=await Promise.all(ds.boxes.map(o=>x8(e,o,t))):(ds.boxes=await j0e(e,t),ds.hands=await Promise.all(ds.boxes.map(o=>x8(e,o,t))),x0=0);let a=[...ds.boxes];if(ds.boxes.length=0,t.cacheSensitivity>0)for(let o=0;o<ds.hands.length;o++){let i=h8(ds.hands[o].keypoints,Ho);if(i.box[2]/(e.shape[2]||1)>.05&&i.box[3]/(e.shape[1]||1)>.05&&ds.hands[o].fingerScore&&ds.hands[o].fingerScore>(t.hand.minConfidence||0)){let l=vc(i.box,m8),c=vc(i.boxRaw,m8),u=Fp(c);ds.boxes.push({...a[o],box:l,boxRaw:c,boxCrop:u})}}r(ds.hands)}))}var kb={};Mc(kb,{connected:()=>wb,kpt:()=>vb});var vb=["nose","leftEyeInside","leftEye","leftEyeOutside","rightEyeInside","rightEye","rightEyeOutside","leftEar","rightEar","leftMouth","rightMouth","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftPalm","rightPalm","leftIndex","rightIndex","leftPinky","rightPinky","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle","leftHeel","rightHeel","leftFoot","rightFoot","bodyCenter","bodyTop","leftThumb","leftHand","rightThumb","rightHand"],wb={leftLeg:["leftHip","leftKnee","leftAnkle","leftHeel","leftFoot"],rightLeg:["rightHip","rightKnee","rightAnkle","rightHeel","rightFoot"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist","leftPalm"],rightArm:["rightShoulder","rightElbow","rightWrist","rightPalm"],leftHand:[],rightHand:[],head:[]};var b8={initial:!0},cn=[null,null],jo=[[0,0],[0,0]],Ib=Number.MAX_SAFE_INTEGER,Sb,Cb=null,qo=[[0,0],[0,0],[0,0],[0,0]];async function v8(e){var t,n;if(b8.initial&&(cn[0]=null),!cn[0]&&((t=e.body.detector)==null?void 0:t.modelPath)){cn[0]=await ut(ct(e.modelBasePath,((n=e.body.detector)==null?void 0:n.modelPath)||""));let s=Object.values(cn[0].modelSignature.inputs);jo[0][0]=Array.isArray(s)?parseInt(s[0].tensorShape.dim[1].size):0,jo[0][1]=Array.isArray(s)?parseInt(s[0].tensorShape.dim[2].size):0,!cn[0]||!cn[0].modelUrl?ae("load model failed:",e.object.modelPath):e.debug&&ae("load model:",cn[0].modelUrl)}else e.debug&&cn[0]&&ae("cached model:",cn[0].modelUrl);return cn[0]}async function w8(e){var t;if(b8.initial&&(cn[1]=null),cn[1])e.debug&&ae("cached model:",cn[1].modelUrl);else{cn[1]=await ut(ct(e.modelBasePath,e.body.modelPath||""));let n=Object.values(cn[1].modelSignature.inputs);jo[1][0]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[1].size):0,jo[1][1]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[2].size):0,((t=e.body.modelPath)==null?void 0:t.includes("lite"))?Sb=["ld_3d","output_segmentation","output_heatmap","world_3d","output_poseflag"]:Sb=["Identity","Identity_2","Identity_3","Identity_4","Identity_1"],!cn[1]||!cn[1].modelUrl?ae("load model failed:",e.object.modelPath):e.debug&&ae("load model:",cn[1].modelUrl)}return cn[1]}function q0e(e,t){let n=e.map(o=>o.position[0]),s=e.map(o=>o.position[1]),r=[Math.min(...n),Math.min(...s),Math.max(...n)-Math.min(...n),Math.max(...s)-Math.min(...s)],a=[r[0]/t[0],r[1]/t[1],r[2]/t[0],r[3]/t[1]];return{keypointsBox:r,keypointsBoxRaw:a}}async function X0e(e){let t={};if(!e.shape||!e.shape[1]||!e.shape[2])return e;qo=[[0,0],[e.shape[2]>e.shape[1]?Math.trunc((e.shape[2]-e.shape[1])/2):0,e.shape[2]>e.shape[1]?Math.trunc((e.shape[2]-e.shape[1])/2):0],[e.shape[1]>e.shape[2]?Math.trunc((e.shape[1]-e.shape[2])/2):0,e.shape[1]>e.shape[2]?Math.trunc((e.shape[1]-e.shape[2])/2):0],[0,0]],t.pad=ur(e,qo),t.resize=$e.resizeBilinear(t.pad,[jo[1][0],jo[1][1]]);let n=fe(t.resize,255);return Object.keys(t).forEach(s=>te(t[s])),n}function K0e(e,t){for(let n of e)n.position=[n.position[0]*(t[0]+qo[2][0]+qo[2][1])/t[0]-qo[2][0],n.position[1]*(t[1]+qo[1][0]+qo[1][1])/t[1]-qo[1][0],n.position[2]],n.positionRaw=[n.position[0]/t[0],n.position[1]/t[1],n.position[2]];return e}async function Z0e(e,t,n){var d;let s={};s.input=await X0e(e),[s.ld,s.segmentation,s.heatmap,s.world,s.poseflag]=await((d=cn[1])==null?void 0:d.execute(s.input,Sb));let r=await s.ld.data(),a=[],o=5;for(let p=0;p<r.length/o;p++){let h=(100-Math.trunc(100/(1+Math.exp(r[o*p+3]))))/100,f=[r[o*p+0]/jo[1][0],r[o*p+1]/jo[1][1],r[o*p+2]+0],m=[Math.trunc(n[0]*f[0]),Math.trunc(n[1]*f[1]),f[2]];a.push({part:vb[p],positionRaw:f,position:m,score:h})}let i=Math.round(100*a.reduce((p,h)=>p+=h.score,0)/a.length)/100;if(i<(t.body.minConfidence||0))return null;let l=K0e(a,n),c=q0e(l,[n[0],n[1]]);Object.keys(s).forEach(p=>te(s[p]));let u={};for(let[p,h]of Object.entries(wb)){let f=[];for(let m=0;m<h.length-1;m++){let g=l.find(A=>A.part===h[m]),y=l.find(A=>A.part===h[m+1]);g&&y&&g.score>(t.body.minConfidence||0)&&y.score>(t.body.minConfidence||0)&&f.push([g.position,y.position])}u[p]=f}return{id:0,score:i,box:c.keypointsBox,boxRaw:c.keypointsBoxRaw,keypoints:l,annotations:u}}async function Tb(e,t){let n=[e.shape[2]||0,e.shape[1]||0];return Ib<(t.body.skipFrames||0)&&t.skipFrame?Ib++:(Cb=await Z0e(e,t,n),Ib=0),Cb?[Cb]:[]}var Rb={};Mc(Rb,{connected:()=>Eb,kpt:()=>Nb});var Nb=["head","neck","rightShoulder","rightElbow","rightWrist","chest","leftShoulder","leftElbow","leftWrist","bodyCenter","rightHip","rightKnee","rightAnkle","leftHip","leftKnee","leftAnkle"],Eb={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var dn,Zn={id:0,keypoints:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,annotations:{}},$b=Number.MAX_SAFE_INTEGER;async function Db(e){return ie.initial&&(dn=null),dn?e.debug&&ae("cached model:",dn.modelUrl):(dn=await ut(ct(e.modelBasePath,e.body.modelPath||"")),!dn||!dn.modelUrl?ae("load model failed:",e.body.modelPath):e.debug&&ae("load model:",dn.modelUrl)),dn}function Y0e(e,t){let[n,s]=e.shape;return j(()=>{let r=(i,l)=>xe(i,L(fe(i,Ee(l,"int32")),Ee(l,"int32"))),a=G(e,[s*n]),o=Bn(a,0).dataSync()[0];if(o>t){let i=Fs(a,0),l=r(i,n).dataSync()[0],c=fe(i,Ee(n,"int32")).dataSync()[0];return[l,c,o]}return[0,0,o]})}async function _b(e,t){var n;return $b<(((n=t.body)==null?void 0:n.skipFrames)||0)&&t.skipFrame&&Object.keys(Zn.keypoints).length>0?($b++,[Zn]):($b=0,new Promise(async s=>{var u;let r=j(()=>{if(!(dn==null?void 0:dn.inputs[0].shape))return null;let d=$e.resizeBilinear(e,[dn.inputs[0].shape[2],dn.inputs[0].shape[1]],!1);return L(d,2).sub(1)}),a;if(t.body.enabled&&(a=await(dn==null?void 0:dn.predict(r))),te(r),a){Zn.keypoints.length=0;let d=a.squeeze();te(a);let p=d.unstack(2);te(d);for(let h=0;h<p.length;h++){let[f,m,g]=Y0e(p[h],t.body.minConfidence);g>(((u=t.body)==null?void 0:u.minConfidence)||0)&&Zn.keypoints.push({score:Math.round(100*g)/100,part:Nb[h],positionRaw:[f/dn.inputs[0].shape[2],m/dn.inputs[0].shape[1]],position:[Math.round(e.shape[2]*f/dn.inputs[0].shape[2]),Math.round(e.shape[1]*m/dn.inputs[0].shape[1])]})}p.forEach(h=>te(h))}Zn.score=Zn.keypoints.reduce((d,p)=>p.score>d?p.score:d,0);let o=Zn.keypoints.map(d=>d.position[0]),i=Zn.keypoints.map(d=>d.position[1]);Zn.box=[Math.min(...o),Math.min(...i),Math.max(...o)-Math.min(...o),Math.max(...i)-Math.min(...i)];let l=Zn.keypoints.map(d=>d.positionRaw[0]),c=Zn.keypoints.map(d=>d.positionRaw[1]);Zn.boxRaw=[Math.min(...l),Math.min(...c),Math.max(...l)-Math.min(...l),Math.max(...c)-Math.min(...c)];for(let[d,p]of Object.entries(Eb)){let h=[];for(let f=0;f<p.length-1;f++){let m=Zn.keypoints.find(y=>y.part===p[f]),g=Zn.keypoints.find(y=>y.part===p[f+1]);m&&g&&m.score>(t.body.minConfidence||0)&&g.score>(t.body.minConfidence||0)&&h.push([m.position,g.position])}Zn.annotations[d]=h}s([Zn])}))}var Fb={};Mc(Fb,{connected:()=>b0,kpt:()=>Op,pairs:()=>Pb});var Op=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],Pb=[["leftEye","rightEye"],["leftEar","rightEar"],["leftShoulder","rightShoulder"],["leftElbow","rightElbow"],["leftWrist","rightWrist"],["leftHip","rightHip"],["leftKnee","rightKnee"],["leftAnkle","rightAnkle"]],b0={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var pn,El=0,J0e=1.5,Dn={boxes:[],bodies:[]},Ob=Number.MAX_SAFE_INTEGER,ps=[];async function k8(e){return ie.initial&&(pn=null),pn?e.debug&&ae("cached model:",pn.modelUrl):(wc(["size"],e),pn=await ut(ct(e.modelBasePath,e.body.modelPath||"")),!pn||!pn.modelUrl?ae("load model failed:",e.body.modelPath):e.debug&&ae("load model:",pn.modelUrl)),El=pn.inputs[0].shape?pn.inputs[0].shape[2]:0,El===-1&&(El=256),pn}function I8(){for(let e of Pb){let t=ps.find(s=>s.part===e[0]),n=ps.find(s=>s.part===e[1]);if(t&&n&&t.position[0]>n.position[0]){let s=t;t=n,n=s}}}async function S8(e,t,n,s){let r=e[0][0];ps.length=0;let a=0;for(let c=0;c<r.length;c++)if(a=r[c][2],a>t.body.minConfidence){let u=[(s[3]-s[1])*r[c][1]+s[1],(s[2]-s[0])*r[c][0]+s[0]];ps.push({score:Math.round(100*a)/100,part:Op[c],positionRaw:u,position:[Math.round((n.shape[2]||0)*u[0]),Math.round((n.shape[1]||0)*u[1])]})}I8(),a=ps.reduce((c,u)=>u.score>c?u.score:c,0);let o=[],i=xb(ps.map(c=>c.position),[n.shape[2],n.shape[1]]),l={};for(let[c,u]of Object.entries(b0)){let d=[];for(let p=0;p<u.length-1;p++){let h=ps.find(m=>m.part===u[p]),f=ps.find(m=>m.part===u[p+1]);h&&f&&h.score>(t.body.minConfidence||0)&&f.score>(t.body.minConfidence||0)&&d.push([h.position,f.position])}l[c]=d}return o.push({id:0,score:a,box:i.box,boxRaw:i.boxRaw,keypoints:ps,annotations:l}),o}async function C8(e,t,n,s){let r=[];for(let a=0;a<e[0].length;a++){let o=e[0][a],i=Math.round(100*o[51+4])/100;if(i>t.body.minConfidence){ps.length=0;for(let u=0;u<17;u++){let d=o[3*u+2];if(d>t.body.minConfidence){let p=[(s[3]-s[1])*o[3*u+1]+s[1],(s[2]-s[0])*o[3*u+0]+s[0]];ps.push({part:Op[u],score:Math.round(100*d)/100,positionRaw:p,position:[Math.round((n.shape[2]||0)*p[0]),Math.round((n.shape[1]||0)*p[1])]})}}I8();let l=xb(ps.map(u=>u.position),[n.shape[2],n.shape[1]]),c={};for(let[u,d]of Object.entries(b0)){let p=[];for(let h=0;h<d.length-1;h++){let f=ps.find(g=>g.part===d[h]),m=ps.find(g=>g.part===d[h+1]);f&&m&&f.score>(t.body.minConfidence||0)&&m.score>(t.body.minConfidence||0)&&p.push([f.position,m.position])}c[u]=p}r.push({id:a,score:i,box:l.box,boxRaw:l.boxRaw,keypoints:[...ps],annotations:c})}}return r.sort((a,o)=>o.score-a.score),r.length>t.body.maxDetected&&(r.length=t.body.maxDetected),r}async function Mb(e,t){return!pn||!(pn==null?void 0:pn.inputs[0].shape)?[]:(t.skipFrame||(Dn.boxes.length=0),Ob++,t.skipFrame&&Ob<=(t.body.skipFrames||0)?Dn.bodies:new Promise(async n=>{let s={};if(Ob=0,Dn.bodies=[],Dn.boxes.length>=(t.body.maxDetected||0))for(let r=0;r<Dn.boxes.length;r++){s.crop=$e.cropAndResize(e,[Dn.boxes[r]],[0],[El,El],"bilinear"),s.cast=pe(s.crop,"int32"),s.res=await(pn==null?void 0:pn.predict(s.cast));let a=await s.res.array(),o=s.res.shape[2]===17?await S8(a,t,e,Dn.boxes[r]):await C8(a,t,e,Dn.boxes[r]);Dn.bodies=Dn.bodies.concat(o),Object.keys(s).forEach(i=>te(s[i]))}if(Dn.bodies.length!==t.body.maxDetected){s.resized=$e.resizeBilinear(e,[El,El],!1),s.cast=pe(s.resized,"int32"),s.res=await(pn==null?void 0:pn.predict(s.cast));let r=await s.res.array();Dn.bodies=s.res.shape[2]===17?await S8(r,t,e,[0,0,1,1]):await C8(r,t,e,[0,0,1,1]),Object.keys(s).forEach(a=>te(s[a]))}Dn.boxes.length=0;for(let r=0;r<Dn.bodies.length;r++)if(Dn.bodies[r].keypoints.length>Op.length/2){let a=vc(Dn.bodies[r].boxRaw,J0e),o=Fp(a);Dn.boxes.push(o)}n(Dn.bodies)}))}var kc=[{class:1,label:"person"},{class:2,label:"bicycle"},{class:3,label:"car"},{class:4,label:"motorcycle"},{class:5,label:"airplane"},{class:6,label:"bus"},{class:7,label:"train"},{class:8,label:"truck"},{class:9,label:"boat"},{class:10,label:"traffic light"},{class:11,label:"fire hydrant"},{class:12,label:"stop sign"},{class:13,label:"parking meter"},{class:14,label:"bench"},{class:15,label:"bird"},{class:16,label:"cat"},{class:17,label:"dog"},{class:18,label:"horse"},{class:19,label:"sheep"},{class:20,label:"cow"},{class:21,label:"elephant"},{class:22,label:"bear"},{class:23,label:"zebra"},{class:24,label:"giraffe"},{class:25,label:"backpack"},{class:26,label:"umbrella"},{class:27,label:"handbag"},{class:28,label:"tie"},{class:29,label:"suitcase"},{class:30,label:"frisbee"},{class:31,label:"skis"},{class:32,label:"snowboard"},{class:33,label:"sports ball"},{class:34,label:"kite"},{class:35,label:"baseball bat"},{class:36,label:"baseball glove"},{class:37,label:"skateboard"},{class:38,label:"surfboard"},{class:39,label:"tennis racket"},{class:40,label:"bottle"},{class:41,label:"wine glass"},{class:42,label:"cup"},{class:43,label:"fork"},{class:44,label:"knife"},{class:45,label:"spoon"},{class:46,label:"bowl"},{class:47,label:"banana"},{class:48,label:"apple"},{class:49,label:"sandwich"},{class:50,label:"orange"},{class:51,label:"broccoli"},{class:52,label:"carrot"},{class:53,label:"hot dog"},{class:54,label:"pizza"},{class:55,label:"donut"},{class:56,label:"cake"},{class:57,label:"chair"},{class:58,label:"couch"},{class:59,label:"potted plant"},{class:60,label:"bed"},{class:61,label:"dining table"},{class:62,label:"toilet"},{class:63,label:"tv"},{class:64,label:"laptop"},{class:65,label:"mouse"},{class:66,label:"remote"},{class:67,label:"keyboard"},{class:68,label:"cell phone"},{class:69,label:"microwave"},{class:70,label:"oven"},{class:71,label:"toaster"},{class:72,label:"sink"},{class:73,label:"refrigerator"},{class:74,label:"book"},{class:75,label:"clock"},{class:76,label:"vase"},{class:77,label:"scissors"},{class:78,label:"teddy bear"},{class:79,label:"hair drier"},{class:80,label:"toothbrush"}];var Es,v0=[],zb=Number.MAX_SAFE_INTEGER,w0=2.5;async function T8(e){if(!Es||ie.initial){Es=await ut(ct(e.modelBasePath,e.object.modelPath||""));let t=Object.values(Es.modelSignature.inputs);if(Es.inputSize=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):null,!Es.inputSize)throw new Error(`cannot determine model inputSize: ${e.object.modelPath}`);!Es||!Es.modelUrl?ae("load model failed:",e.object.modelPath):e.debug&&ae("load model:",Es.modelUrl)}else e.debug&&ae("cached model:",Es.modelUrl);return Es}async function Q0e(e,t,n,s){let r=0,a=[];for(let c of[1,2,4])j(async()=>{var g,y;let u=c*13,d=(g=e.find(A=>A.shape[1]===u**2&&A.shape[2]===kc.length))==null?void 0:g.squeeze(),p=(y=e.find(A=>A.shape[1]===u**2&&A.shape[2]<kc.length))==null?void 0:y.squeeze(),f=await p.reshape([-1,4,p.shape[1]/4]).argMax(2).array(),m=await d.array();for(let A=0;A<d.shape[0];A++)for(let x=0;x<d.shape[1];x++){let b=m[A][x];if(b>s.object.minConfidence&&x!==61){let w=(.5+Math.trunc(A%u))/u,k=(.5+Math.trunc(A/u))/u,S=f[A].map(B=>B*(u/c/t)),[N,$]=[w-w0/c*S[0],k-w0/c*S[1]],[F,R]=[w+w0/c*S[2]-N,k+w0/c*S[3]-$],D=[N,$,F,R];D=D.map(B=>Math.max(0,Math.min(B,1)));let T=[D[0]*n[0],D[1]*n[1],D[2]*n[0],D[3]*n[1]],O={id:r++,score:Math.round(100*b)/100,class:x+1,label:kc[x].label,box:T.map(B=>Math.trunc(B)),boxRaw:D};a.push(O)}}});e.forEach(c=>te(c));let o=a.map(c=>[c.boxRaw[1],c.boxRaw[0],c.boxRaw[3],c.boxRaw[2]]),i=a.map(c=>c.score),l=[];if(o&&o.length>0){let c=await $e.nonMaxSuppressionAsync(o,i,s.object.maxDetected,s.object.iouThreshold,s.object.minConfidence);l=await c.data(),te(c)}return a=a.filter((c,u)=>l.includes(u)).sort((c,u)=>u.score-c.score),a}async function Lb(e,t){return zb<(t.object.skipFrames||0)&&t.skipFrame&&v0.length>0?(zb++,v0):(zb=0,!ie.kernels.includes("mod")||!ie.kernels.includes("sparsetodense")?v0:new Promise(async n=>{let s=[e.shape[2],e.shape[1]],r=$e.resizeBilinear(e,[Es.inputSize,Es.inputSize],!1),a=fe(r,255),o=a.transpose([0,3,1,2]);te(a),te(r);let i;t.object.enabled&&(i=await Es.predict(o)),te(o);let l=await Q0e(i,Es.inputSize,s,t);v0=l,n(l)}))}var rr,Rl=0,k0=[],Bb=Number.MAX_SAFE_INTEGER;async function N8(e){if(ie.initial&&(rr=null),rr)e.debug&&ae("cached model:",rr.modelUrl);else{wc(["floormod"],e),rr=await ut(ct(e.modelBasePath,e.object.modelPath||""));let t=Object.values(rr.modelSignature.inputs);Rl=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0,!rr||!rr.modelUrl?ae("load model failed:",e.object.modelPath):e.debug&&ae("load model:",rr.modelUrl)}return rr}async function ege(e,t,n){if(!e)return[];let s=[],r=await e.array(),a=dt(e);te(e);let o=xn(a,6,1);te(a);let i=Tn([o[1],o[0],o[3],o[2]],1),l=dt(i);te(i);let c=dt(o[4]),u=dt(o[5]);o.forEach(f=>te(f));let d=await $e.nonMaxSuppressionAsync(l,c,n.object.maxDetected,n.object.iouThreshold,n.object.minConfidence);te(l),te(c),te(u);let p=await d.data();te(d);let h=0;for(let f of p){let m=Math.trunc(100*r[0][f][4])/100,g=r[0][f][5],y=kc[g].label,[A,x]=[r[0][f][0]/Rl,r[0][f][1]/Rl],b=[A,x,r[0][f][2]/Rl-A,r[0][f][3]/Rl-x],w=[Math.trunc(b[0]*t[0]),Math.trunc(b[1]*t[1]),Math.trunc(b[2]*t[0]),Math.trunc(b[3]*t[1])];s.push({id:h++,score:m,class:g,label:y,box:w,boxRaw:b})}return s}async function Wb(e,t){return Bb<(t.object.skipFrames||0)&&t.skipFrame&&k0.length>0?(Bb++,k0):(Bb=0,!ie.kernels.includes("mod")||!ie.kernels.includes("sparsetodense")?k0:new Promise(async n=>{let s=[e.shape[2],e.shape[1]],r=$e.resizeBilinear(e,[Rl,Rl]),a=t.object.enabled?rr==null?void 0:rr.execute(r,["tower_0/detections"]):null;te(r);let o=await ege(a,s,t);k0=o,n(o)}))}var Gs,Vb=!1;async function Ub(e){return!Gs||ie.initial?(Gs=await ut(ct(e.modelBasePath,e.segmentation.modelPath||"")),!Gs||!Gs.modelUrl?ae("load model failed:",e.segmentation.modelPath):e.debug&&ae("load model:",Gs.modelUrl)):e.debug&&ae("cached model:",Gs.modelUrl),Gs}async function E8(e,t,n){var m,g;if(Vb)return{data:[],canvas:null,alpha:null};Vb=!0,Gs||await Ub(n);let s=yc(e,n),r=((m=s.canvas)==null?void 0:m.width)||0,a=((g=s.canvas)==null?void 0:g.height)||0;if(!s.tensor)return{data:[],canvas:null,alpha:null};let o={};o.resize=$e.resizeBilinear(s.tensor,[Gs.inputs[0].shape?Gs.inputs[0].shape[1]:0,Gs.inputs[0].shape?Gs.inputs[0].shape[2]:0],!1),te(s.tensor),o.norm=fe(o.resize,255),o.res=Gs.predict(o.norm),o.squeeze=dt(o.res,0),o.squeeze.shape[2]===2?(o.softmax=nl(o.squeeze),[o.bg,o.fg]=Wn(o.softmax,2),o.expand=jt(o.fg,2),o.pad=jt(o.expand,0),o.crop=$e.cropAndResize(o.pad,[[0,0,.5,.5]],[0],[r,a]),o.data=dt(o.crop,0)):o.data=$e.resizeBilinear(o.squeeze,[a,r]);let i=Array.from(await o.data.data());if(ie.node&&!ie.Canvas&&typeof ImageData=="undefined")return n.debug&&ae("canvas support missing"),Object.keys(o).forEach(y=>te(o[y])),{data:i,canvas:null,alpha:null};let l=Ts(r,a);await Xs.toPixels(o.data,l);let c=l.getContext("2d");n.segmentation.blur&&n.segmentation.blur>0&&(c.filter=`blur(${n.segmentation.blur}px)`);let u=c.getImageData(0,0,r,a),d=Ts(r,a),p=d.getContext("2d");s.canvas&&p.drawImage(s.canvas,0,0),p.globalCompositeOperation="darken",n.segmentation.blur&&n.segmentation.blur>0&&(p.filter=`blur(${n.segmentation.blur}px)`),p.drawImage(l,0,0),p.globalCompositeOperation="source-over",p.filter="none";let h=p.getImageData(0,0,r,a);for(let y=0;y<r*a;y++)h.data[4*y+3]=u.data[4*y+0];p.putImageData(h,0,0);let f=null;if(t&&d){f=Ts(r,a);let y=yc(t,n);te(y.tensor);let A=f.getContext("2d");A.drawImage(y.canvas,0,0,f.width,f.height),A.drawImage(d,0,0)}return Object.keys(o).forEach(y=>te(o[y])),Vb=!1,{data:i,canvas:f||d,alpha:l}}var Xo;var R1e=Number.MAX_SAFE_INTEGER;async function R8(e){return ie.initial&&(Xo=null),Xo?e.debug&&ae("cached model:",Xo.modelUrl):(Xo=await ut(ct(e.modelBasePath,e.face.agegenderrace.modelPath)),!Xo||!Xo.modelUrl?ae("load model failed:",e.face.agegenderrace.modelPath):e.debug&&ae("load model:",Xo.modelUrl)),Xo}var Mp=class{constructor(){ve(this,"age",null);ve(this,"agegenderrace",null);ve(this,"blazeposedetect",null);ve(this,"blazepose",null);ve(this,"centernet",null);ve(this,"efficientpose",null);ve(this,"embedding",null);ve(this,"emotion",null);ve(this,"facedetect",null);ve(this,"faceiris",null);ve(this,"facemesh",null);ve(this,"faceres",null);ve(this,"gender",null);ve(this,"handpose",null);ve(this,"handskeleton",null);ve(this,"handtrack",null);ve(this,"movenet",null);ve(this,"nanodet",null);ve(this,"posenet",null);ve(this,"segmentation",null)}};function Gb(e){for(let t of Object.keys(e.models))e.models[t]=null}async function $8(e){var t,n,s,r,a,o,i,l,c,u,d,p,h,f,m,g,y,A,x,b,w,k,S,N,$,F,R,D,T,O;ie.initial&&Gb(e),e.config.hand.enabled&&(!e.models.handpose&&((n=(t=e.config.hand.detector)==null?void 0:t.modelPath)==null?void 0:n.includes("handdetect"))&&([e.models.handpose,e.models.handskeleton]=await Ab(e.config)),!e.models.handskeleton&&e.config.hand.landmarks&&((r=(s=e.config.hand.detector)==null?void 0:s.modelPath)==null?void 0:r.includes("handdetect"))&&([e.models.handpose,e.models.handskeleton]=await Ab(e.config))),e.config.face.enabled&&!e.models.facedetect&&(e.models.facedetect=S6(e.config)),e.config.face.enabled&&((a=e.config.face.mesh)==null?void 0:a.enabled)&&!e.models.facemesh&&(e.models.facemesh=P6(e.config)),e.config.face.enabled&&((o=e.config.face.iris)==null?void 0:o.enabled)&&!e.models.faceiris&&(e.models.faceiris=T6(e.config)),e.config.hand.enabled&&!e.models.handtrack&&((l=(i=e.config.hand.detector)==null?void 0:i.modelPath)==null?void 0:l.includes("handtrack"))&&(e.models.handtrack=y8(e.config)),e.config.hand.enabled&&e.config.hand.landmarks&&!e.models.handskeleton&&((u=(c=e.config.hand.detector)==null?void 0:c.modelPath)==null?void 0:u.includes("handtrack"))&&(e.models.handskeleton=A8(e.config)),e.config.body.enabled&&!e.models.posenet&&((p=(d=e.config.body)==null?void 0:d.modelPath)==null?void 0:p.includes("posenet"))&&(e.models.posenet=q6(e.config)),e.config.body.enabled&&!e.models.efficientpose&&((f=(h=e.config.body)==null?void 0:h.modelPath)==null?void 0:f.includes("efficientpose"))&&(e.models.efficientpose=Db(e.config)),e.config.body.enabled&&!e.models.blazepose&&((g=(m=e.config.body)==null?void 0:m.modelPath)==null?void 0:g.includes("blazepose"))&&(e.models.blazepose=w8(e.config)),e.config.body.enabled&&!e.models.blazeposedetect&&((y=e.config.body.detector)==null?void 0:y.modelPath)&&((x=(A=e.config.body)==null?void 0:A.modelPath)==null?void 0:x.includes("blazepose"))&&(e.models.blazeposedetect=v8(e.config)),e.config.body.enabled&&!e.models.efficientpose&&((w=(b=e.config.body)==null?void 0:b.modelPath)==null?void 0:w.includes("efficientpose"))&&(e.models.efficientpose=Db(e.config)),e.config.body.enabled&&!e.models.movenet&&((S=(k=e.config.body)==null?void 0:k.modelPath)==null?void 0:S.includes("movenet"))&&(e.models.movenet=k8(e.config)),e.config.object.enabled&&!e.models.nanodet&&(($=(N=e.config.object)==null?void 0:N.modelPath)==null?void 0:$.includes("nanodet"))&&(e.models.nanodet=T8(e.config)),e.config.object.enabled&&!e.models.centernet&&((R=(F=e.config.object)==null?void 0:F.modelPath)==null?void 0:R.includes("centernet"))&&(e.models.centernet=N8(e.config)),e.config.face.enabled&&((D=e.config.face.emotion)==null?void 0:D.enabled)&&!e.models.emotion&&(e.models.emotion=B6(e.config)),e.config.face.enabled&&((T=e.config.face.description)==null?void 0:T.enabled)&&!e.models.faceres&&(e.models.faceres=z6(e.config)),e.config.segmentation.enabled&&!e.models.segmentation&&(e.models.segmentation=Ub(e.config)),e.config.face.enabled&&((O=e.config.face.agegenderrace)==null?void 0:O.enabled)&&!e.models.agegenderrace&&(e.models.agegenderrace=R8(e.config));for await(let B of Object.keys(e.models))e.models[B]&&typeof e.models[B]!="undefined"&&(e.models[B]=await e.models[B])}async function D8(e){let t=["const","placeholder","noop","pad","squeeze","add","sub","mul","div"];for(let n of Object.keys(e.models))if(e.models[n]){let s=[];Array.isArray(e.models[n])?s=e.models[n].filter(r=>r!==null).map(r=>r&&r.executor?r:r.model):s=[e.models[n]];for(let r of s){if(!r){e.config.debug&&ae("model marked as loaded but not defined:",n);continue}let a=[],o=r==null?void 0:r.executor;if(o&&o.graph.nodes)for(let l of Object.values(o.graph.nodes)){let c=l.op.toLowerCase();a.includes(c)||a.push(c)}else!o&&e.config.debug&&ae("model signature not determined:",n);let i=[];for(let l of a)!t.includes(l)&&!e.env.kernels.includes(l)&&!e.env.kernels.includes(l.replace("_",""))&&!e.env.kernels.includes(l.replace("native",""))&&!e.env.kernels.includes(l.replace("v2",""))&&i.push(l);i.length>0&&e.config.debug&&ae("model validation:",n,i)}}}var Wt={name:"humangl",priority:999,canvas:null,gl:null,extensions:[],webGLattr:{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!1,desynchronized:!0}};function tge(){let e=Wt.gl;!e||(Wt.extensions=e.getSupportedExtensions())}async function _8(e){var t;if(e.config.backend==="humangl"&&(Wt.name in ts().registry&&(!Wt.gl||!Wt.gl.getParameter(Wt.gl.VERSION))&&(ae("error: humangl backend invalid context"),Gb(e)),!W2(Wt.name))){try{Wt.canvas=await Ts(100,100)}catch(s){ae("error: cannot create canvas:",s);return}try{Wt.gl=(t=Wt.canvas)==null?void 0:t.getContext("webgl2",Wt.webGLattr),Wt.canvas&&(Wt.canvas.addEventListener("webglcontextlost",async s=>{throw ae("error: humangl:",s.type),ae("possible browser memory leak using webgl or conflict with multiple backend registrations"),e.emit("error"),new Error("browser webgl error")}),Wt.canvas.addEventListener("webglcontextrestored",s=>{ae("error: humangl context restored:",s)}),Wt.canvas.addEventListener("webglcontextcreationerror",s=>{ae("error: humangl context create:",s)}))}catch(s){ae("error: cannot get WebGL context:",s);return}try{Em(2,Wt.gl)}catch(s){ae("error: cannot set WebGL context:",s);return}try{let s=new zm(Wt.gl);Xi(Wt.name,()=>new ic(s),Wt.priority)}catch(s){ae("error: cannot register WebGL backend:",s);return}try{Zr("webgl").forEach(r=>{let a={...r,backendName:Wt.name};Yr(a)})}catch(s){ae("error: cannot update WebGL backend registration:",s);return}let n=Tr().getGPGPUContext?Tr().getGPGPUContext().gl:null;if(n)ae(`humangl webgl version:${n.getParameter(n.VERSION)} renderer:${n.getParameter(n.RENDERER)}`);else{ae("error: no current gl context:",n,Wt.gl);return}try{gs.set("WEBGL_VERSION",2)}catch(s){ae("error: cannot set WebGL backend flags:",s);return}tge(),ae("backend registered:",Wt.name)}}async function I0(e,t=!1){if(e.state="backend",t||ie.initial||e.config.backend&&e.config.backend.length>0&&lr()!==e.config.backend){let n=ot();if(e.config.backend&&e.config.backend.length>0){if(typeof window=="undefined"&&typeof WorkerGlobalScope!="undefined"&&e.config.debug&&e.config.debug&&ae("running inside web worker"),ie.browser&&e.config.backend==="tensorflow"&&(e.config.debug&&ae("override: backend set to tensorflow while running in browser"),e.config.backend="humangl"),ie.node&&(e.config.backend==="webgl"||e.config.backend==="humangl")&&(e.config.debug&&ae(`override: backend set to ${e.config.backend} while running in nodejs`),e.config.backend="tensorflow"),ie.browser&&e.config.backend==="webgpu")if(typeof navigator=="undefined"||typeof navigator.gpu=="undefined")ae("override: backend set to webgpu but browser does not support webgpu"),e.config.backend="humangl";else{let r=await navigator.gpu.requestAdapter();e.config.debug&&ae("enumerated webgpu adapter:",r)}e.config.backend==="humangl"&&await _8(e);let s=Object.keys(ts().registryFactory);if(e.config.debug&&ae("available backends:",s),s.includes(e.config.backend)||(ae(`error: backend ${e.config.backend} not found in registry`),e.config.backend=ie.node?"tensorflow":"webgl",e.config.debug&&ae(`override: setting backend ${e.config.backend}`)),e.config.debug&&ae("setting backend:",e.config.backend),e.config.backend==="wasm"){if(e.config.debug&&ae("wasm path:",e.config.wasmPath),typeof(Sl==null?void 0:Sl.setWasmPaths)!="undefined")await wC(e.config.wasmPath);else throw new Error("wasm backend is not loaded");let r=await Z().getAsync("WASM_HAS_SIMD_SUPPORT"),a=await Z().getAsync("WASM_HAS_MULTITHREAD_SUPPORT");e.config.debug&&ae(`wasm execution: ${r?"SIMD":"no SIMD"} ${a?"multithreaded":"singlethreaded"}`),e.config.debug&&!r&&ae("warning: wasm simd support is not enabled")}try{await R3(e.config.backend),await ef()}catch(r){return ae("error: cannot set backend:",e.config.backend,r),!1}}if(lr()==="humangl"&&(gs.set("CHECK_COMPUTATION_FOR_ERRORS",!1),gs.set("WEBGL_CPU_FORWARD",!0),gs.set("WEBGL_PACK_DEPTHWISECONV",!1),gs.set("WEBGL_USE_SHAPES_UNIFORMS",!0),gs.set("CPU_HANDOFF_SIZE_THRESHOLD",256),typeof e.config.deallocate!="undefined"&&e.config.deallocate&&(ae("changing webgl: WEBGL_DELETE_TEXTURE_THRESHOLD:",!0),gs.set("WEBGL_DELETE_TEXTURE_THRESHOLD",0)),Tr().getGPGPUContext)){let s=await Tr().getGPGPUContext().gl;e.config.debug&&ae(`gl version:${s.getParameter(s.VERSION)} renderer:${s.getParameter(s.RENDERER)}`)}lr()==="webgpu"&&(gs.set("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD",512),gs.set("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE",0),gs.set("WEBGPU_CPU_FORWARD",!0)),E3(),await ef(),e.performance.backend=Math.trunc(ot()-n),e.config.backend=lr(),a0(),e.env=ie}return!0}function wc(e,t){for(let n of e){let s={kernelName:n,backendName:t.backend,kernelFunc:()=>{t.debug&&ae("kernelFunc",n,t.backend)}};Yr(s)}ie.kernels=Zr(lr()).map(n=>n.kernelName.toLowerCase())}var pa={color:"rgba(173, 216, 230, 0.6)",labelColor:"rgba(173, 216, 230, 1)",shadowColor:"black",font:'small-caps 14px "Segoe UI"',lineHeight:18,lineWidth:4,pointSize:2,roundRect:8,drawPoints:!1,drawLabels:!0,drawBoxes:!0,drawPolygons:!0,drawGaze:!0,fillPolygons:!1,useDepth:!0,useCurves:!1,bufferedOutput:!0},$l=e=>{if(e&&e.getContext)return e.getContext("2d");throw new Error("invalid canvas")},Ic=e=>Math.round(e*180/Math.PI);function Hb(e,t,n,s=0,r){e.fillStyle=r.useDepth&&s?`rgba(${127.5+2*s}, ${127.5-2*s}, 255, 0.3)`:r.color,e.beginPath(),e.arc(t,n,r.pointSize,0,2*Math.PI),e.fill()}function zp(e,t,n,s,r,a){if(e.beginPath(),a.useCurves){let o=(t+t+s)/2,i=(n+n+r)/2;e.ellipse(o,i,s/2,r/2,0,0,2*Math.PI)}else e.lineWidth=a.lineWidth,e.moveTo(t+a.roundRect,n),e.lineTo(t+s-a.roundRect,n),e.quadraticCurveTo(t+s,n,t+s,n+a.roundRect),e.lineTo(t+s,n+r-a.roundRect),e.quadraticCurveTo(t+s,n+r,t+s-a.roundRect,n+r),e.lineTo(t+a.roundRect,n+r),e.quadraticCurveTo(t,n+r,t,n+r-a.roundRect),e.lineTo(t,n+a.roundRect),e.quadraticCurveTo(t,n,t+a.roundRect,n),e.closePath();e.stroke()}function P8(e,t=[],n){if(!(t===void 0||t.length===0)){e.beginPath(),e.moveTo(t[0][0],t[0][1]);for(let s of t){let r=s[2]||0;e.strokeStyle=n.useDepth&&r?`rgba(${127.5+2*r}, ${127.5-2*r}, 255, 0.3)`:n.color,e.fillStyle=n.useDepth&&r?`rgba(${127.5+2*r}, ${127.5-2*r}, 255, 0.3)`:n.color,e.lineTo(s[0],Math.round(s[1]))}e.stroke(),n.fillPolygons&&(e.closePath(),e.fill())}}function nge(e,t=[],n){if(!(t===void 0||t.length===0)){if(!n.useCurves||t.length<=2){P8(e,t,n);return}e.moveTo(t[0][0],t[0][1]);for(let s=0;s<t.length-2;s++){let r=(t[s][0]+t[s+1][0])/2,a=(t[s][1]+t[s+1][1])/2;e.quadraticCurveTo(t[s][0],t[s][1],r,a)}e.quadraticCurveTo(t[t.length-2][0],t[t.length-2][1],t[t.length-1][0],t[t.length-1][1]),e.stroke(),n.fillPolygons&&(e.closePath(),e.fill())}}function F8(e,t,n,s=5){let r,a,o;e.beginPath(),e.moveTo(t[0],t[1]),e.lineTo(n[0],n[1]),r=Math.atan2(n[1]-t[1],n[0]-t[0]),a=s*Math.cos(r)+n[0],o=s*Math.sin(r)+n[1],e.moveTo(a,o),r+=1/3*(2*Math.PI),a=s*Math.cos(r)+n[0],o=s*Math.sin(r)+n[1],e.lineTo(a,o),r+=1/3*(2*Math.PI),a=s*Math.cos(r)+n[0],o=s*Math.sin(r)+n[1],e.lineTo(a,o),e.closePath(),e.stroke(),e.fill()}async function jb(e,t,n){let s=fn(pa,n);if(!t||!e)return;let r=$l(e);r.font=s.font,r.fillStyle=s.color;let a=1;for(let o=0;o<t.length;o++){let i=[],l=[];if([i,l]=Object.entries(t[o]),l.length>1&&l[1].length>0){let c=i[1]>0?`#${i[1]}`:"",u=`${i[0]} ${c}: ${l[1]}`;s.shadowColor&&s.shadowColor!==""&&(r.fillStyle=s.shadowColor,r.fillText(u,8,2+a*s.lineHeight)),r.fillStyle=s.labelColor,r.fillText(u,6,0+a*s.lineHeight),a+=1}}}async function qb(e,t,n){var a,o,i,l,c;let s=fn(pa,n);if(!t||!e)return;let r=$l(e);for(let u of t){r.font=s.font,r.strokeStyle=s.color,r.fillStyle=s.color,s.drawBoxes&&zp(r,u.box[0],u.box[1],u.box[2],u.box[3],s);let d=[];if(d.push(`face: ${Math.trunc(100*u.score)}%`),u.genderScore&&d.push(`${u.gender||""} ${Math.trunc(100*u.genderScore)}%`),u.age&&d.push(`age: ${u.age||""}`),u.iris&&d.push(`distance: ${u.iris}`),u.emotion&&u.emotion.length>0){let p=u.emotion.map(h=>`${Math.trunc(100*h.score)}% ${h.emotion}`);p.length>3&&(p.length=3),d.push(p.join(" "))}u.rotation&&u.rotation.angle&&u.rotation.gaze&&(u.rotation.angle.roll&&d.push(`roll: ${Ic(u.rotation.angle.roll)}\xB0 yaw:${Ic(u.rotation.angle.yaw)}\xB0 pitch:${Ic(u.rotation.angle.pitch)}\xB0`),u.rotation.gaze.bearing&&d.push(`gaze: ${Ic(u.rotation.gaze.bearing)}\xB0`)),d.length===0&&d.push("face"),r.fillStyle=s.color;for(let p=d.length-1;p>=0;p--){let h=Math.max(u.box[0],0),f=p*s.lineHeight+u.box[1];s.shadowColor&&s.shadowColor!==""&&(r.fillStyle=s.shadowColor,r.fillText(d[p],h+5,f+16)),r.fillStyle=s.labelColor,r.fillText(d[p],h+4,f+15)}if(r.lineWidth=1,u.mesh&&u.mesh.length>0){if(s.drawPoints)for(let p of u.mesh)Hb(r,p[0],p[1],p[2],s);if(s.drawPolygons){if(r.lineWidth=1,u.mesh.length>450)for(let p=0;p<Cl.length/3;p++){let h=[Cl[p*3+0],Cl[p*3+1],Cl[p*3+2]].map(f=>u.mesh[f]);P8(r,h,s)}if(u.annotations&&u.annotations.leftEyeIris&&u.annotations.leftEyeIris[0]){r.strokeStyle=s.useDepth?"rgba(255, 200, 255, 0.3)":s.color,r.beginPath();let p=Math.abs(u.annotations.leftEyeIris[3][0]-u.annotations.leftEyeIris[1][0])/2,h=Math.abs(u.annotations.leftEyeIris[4][1]-u.annotations.leftEyeIris[2][1])/2;r.ellipse(u.annotations.leftEyeIris[0][0],u.annotations.leftEyeIris[0][1],p,h,0,0,2*Math.PI),r.stroke(),s.fillPolygons&&(r.fillStyle=s.useDepth?"rgba(255, 255, 200, 0.3)":s.color,r.fill())}if(u.annotations&&u.annotations.rightEyeIris&&u.annotations.rightEyeIris[0]){r.strokeStyle=s.useDepth?"rgba(255, 200, 255, 0.3)":s.color,r.beginPath();let p=Math.abs(u.annotations.rightEyeIris[3][0]-u.annotations.rightEyeIris[1][0])/2,h=Math.abs(u.annotations.rightEyeIris[4][1]-u.annotations.rightEyeIris[2][1])/2;r.ellipse(u.annotations.rightEyeIris[0][0],u.annotations.rightEyeIris[0][1],p,h,0,0,2*Math.PI),r.stroke(),s.fillPolygons&&(r.fillStyle=s.useDepth?"rgba(255, 255, 200, 0.3)":s.color,r.fill())}if(s.drawGaze&&((a=u.rotation)==null?void 0:a.angle)){r.strokeStyle="pink";let p=u.box[0]+u.box[2]/2-u.box[3]*Ic(u.rotation.angle.yaw)/90,h=u.box[1]+u.box[3]/2+u.box[2]*Ic(u.rotation.angle.pitch)/90,f=new Path2D(`
|
|
M ${u.box[0]+u.box[2]/2} ${u.box[1]}
|
|
C
|
|
${p} ${u.box[1]},
|
|
${p} ${u.box[1]+u.box[3]},
|
|
${u.box[0]+u.box[2]/2} ${u.box[1]+u.box[3]}
|
|
`),m=new Path2D(`
|
|
M ${u.box[0]} ${u.box[1]+u.box[3]/2}
|
|
C
|
|
${u.box[0]} ${h},
|
|
${u.box[0]+u.box[2]} ${h},
|
|
${u.box[0]+u.box[2]} ${u.box[1]+u.box[3]/2}
|
|
`);r.stroke(m),r.stroke(f)}if(s.drawGaze&&((i=(o=u.rotation)==null?void 0:o.gaze)==null?void 0:i.strength)&&((c=(l=u.rotation)==null?void 0:l.gaze)==null?void 0:c.bearing)&&u.annotations.leftEyeIris&&u.annotations.rightEyeIris&&u.annotations.leftEyeIris[0]&&u.annotations.rightEyeIris[0]){r.strokeStyle="pink",r.fillStyle="pink";let p=[u.annotations.leftEyeIris[0][0]+Math.sin(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[3],u.annotations.leftEyeIris[0][1]+Math.cos(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[2]];F8(r,[u.annotations.leftEyeIris[0][0],u.annotations.leftEyeIris[0][1]],[p[0],p[1]],4);let h=[u.annotations.rightEyeIris[0][0]+Math.sin(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[3],u.annotations.rightEyeIris[0][1]+Math.cos(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[2]];F8(r,[u.annotations.rightEyeIris[0][0],u.annotations.rightEyeIris[0][1]],[h[0],h[1]],4)}}}}}async function Xb(e,t,n){var a;let s=fn(pa,n);if(!t||!e)return;let r=$l(e);r.lineJoin="round";for(let o=0;o<t.length;o++){if(r.strokeStyle=s.color,r.fillStyle=s.color,r.lineWidth=s.lineWidth,r.font=s.font,s.drawBoxes&&t[o].box&&((a=t[o].box)==null?void 0:a.length)===4&&(zp(r,t[o].box[0],t[o].box[1],t[o].box[2],t[o].box[3],s),s.drawLabels&&(s.shadowColor&&s.shadowColor!==""&&(r.fillStyle=s.shadowColor,r.fillText(`body ${100*t[o].score}%`,t[o].box[0]+3,1+t[o].box[1]+s.lineHeight,t[o].box[2])),r.fillStyle=s.labelColor,r.fillText(`body ${100*t[o].score}%`,t[o].box[0]+2,0+t[o].box[1]+s.lineHeight,t[o].box[2]))),s.drawPoints&&t[o].keypoints)for(let i=0;i<t[o].keypoints.length;i++)r.fillStyle=s.useDepth&&t[o].keypoints[i].position[2]?`rgba(${127.5+2*(t[o].keypoints[i].position[2]||0)}, ${127.5-2*(t[o].keypoints[i].position[2]||0)}, 255, 0.5)`:s.color,Hb(r,t[o].keypoints[i].position[0],t[o].keypoints[i].position[1],0,s);if(s.drawLabels&&t[o].keypoints){r.font=s.font;for(let i of t[o].keypoints)r.fillStyle=s.useDepth&&i.position[2]?`rgba(${127.5+2*i.position[2]}, ${127.5-2*i.position[2]}, 255, 0.5)`:s.color,r.fillText(`${i.part} ${Math.trunc(100*i.score)}%`,i.position[0]+4,i.position[1]+4)}if(s.drawPolygons&&t[o].keypoints&&t[o].annotations)for(let i of Object.values(t[o].annotations))for(let l of i)nge(r,l,s)}}async function Kb(e,t,n){let s=fn(pa,n);if(!t||!e)return;let r=$l(e);r.lineJoin="round",r.font=s.font;for(let a of t){if(s.drawBoxes&&(r.strokeStyle=s.color,r.fillStyle=s.color,zp(r,a.box[0],a.box[1],a.box[2],a.box[3],s),s.drawLabels&&(s.shadowColor&&s.shadowColor!==""&&(r.fillStyle=s.shadowColor,r.fillText(`hand:${Math.trunc(100*a.score)}%`,a.box[0]+3,1+a.box[1]+s.lineHeight,a.box[2])),r.fillStyle=s.labelColor,r.fillText(`hand:${Math.trunc(100*a.score)}%`,a.box[0]+2,0+a.box[1]+s.lineHeight,a.box[2])),r.stroke()),s.drawPoints&&a.keypoints&&a.keypoints.length>0)for(let o of a.keypoints)r.fillStyle=s.useDepth?`rgba(${127.5+2*(o[2]||0)}, ${127.5-2*(o[2]||0)}, 255, 0.5)`:s.color,Hb(r,o[0],o[1],0,s);if(s.drawLabels&&a.annotations){let o=(i,l)=>{!i||i.length===0||!i[0]||(r.fillStyle=s.useDepth?`rgba(${127.5+2*i[i.length-1][2]}, ${127.5-2*i[i.length-1][2]}, 255, 0.5)`:s.color,r.fillText(l,i[i.length-1][0]+4,i[i.length-1][1]+4))};r.font=s.font,o(a.annotations.index,"index"),o(a.annotations.middle,"middle"),o(a.annotations.ring,"ring"),o(a.annotations.pinky,"pinky"),o(a.annotations.thumb,"thumb"),o(a.annotations.palm,"palm")}if(s.drawPolygons&&a.annotations){let o=i=>{if(!(!i||i.length===0||!i[0]))for(let l=0;l<i.length;l++)r.beginPath(),r.strokeStyle=s.useDepth?`rgba(${127.5+2*i[l][2]}, ${127.5-2*i[l][2]}, 255, 0.5)`:s.color,r.moveTo(i[l>0?l-1:0][0],i[l>0?l-1:0][1]),r.lineTo(i[l][0],i[l][1]),r.stroke()};r.lineWidth=s.lineWidth,o(a.annotations.index),o(a.annotations.middle),o(a.annotations.ring),o(a.annotations.pinky),o(a.annotations.thumb)}}}async function Zb(e,t,n){let s=fn(pa,n);if(!t||!e)return;let r=$l(e);r.lineJoin="round",r.font=s.font;for(let a of t)if(s.drawBoxes){if(r.strokeStyle=s.color,r.fillStyle=s.color,zp(r,a.box[0],a.box[1],a.box[2],a.box[3],s),s.drawLabels){let o=`${a.label} ${Math.round(100*a.score)}%`;s.shadowColor&&s.shadowColor!==""&&(r.fillStyle=s.shadowColor,r.fillText(o,a.box[0]+3,1+a.box[1]+s.lineHeight,a.box[2])),r.fillStyle=s.labelColor,r.fillText(o,a.box[0]+2,0+a.box[1]+s.lineHeight,a.box[2])}r.stroke()}}async function O8(e,t,n){let s=fn(pa,n);if(!t||!e)return;let r=$l(e);r.lineJoin="round",r.font=s.font;for(let a=0;a<t.length;a++)if(s.drawBoxes){if(r.strokeStyle=s.color,r.fillStyle=s.color,zp(r,t[a].box[0],t[a].box[1],t[a].box[2],t[a].box[3],s),s.drawLabels){let o=`person #${a}`;s.shadowColor&&s.shadowColor!==""&&(r.fillStyle=s.shadowColor,r.fillText(o,t[a].box[0]+3,1+t[a].box[1]+s.lineHeight,t[a].box[2])),r.fillStyle=s.labelColor,r.fillText(o,t[a].box[0]+2,0+t[a].box[1]+s.lineHeight,t[a].box[2])}r.stroke()}}async function M8(e,t){if(!e||!t)return;$l(t).drawImage(e,0,0)}async function z8(e,t,n){if(!t||!t.performance||!t||!e)return null;let s=ot(),r=fn(pa,n),a=Promise.all([qb(e,t.face,r),Xb(e,t.body,r),Kb(e,t.hand,r),Zb(e,t.object,r),jb(e,t.gesture,r)]);return t.performance.draw=Math.trunc(ot()-s),a}var sge=e=>{let t=(d,p)=>Math.atan2(d[1]-p[1],d[0]-p[0]);if(!e.annotations.rightEyeIris||!e.annotations.leftEyeIris)return{bearing:0,strength:0};let n=[0,-.1],s=1,r=e.mesh[33][2]>e.mesh[263][2],a=r?e.mesh[473]:e.mesh[468],o=r?[(e.mesh[133][0]+e.mesh[33][0])/2,(e.mesh[133][1]+e.mesh[33][1])/2]:[(e.mesh[263][0]+e.mesh[362][0])/2,(e.mesh[263][1]+e.mesh[362][1])/2],i=r?[e.mesh[133][0]-e.mesh[33][0],e.mesh[23][1]-e.mesh[27][1]]:[e.mesh[263][0]-e.mesh[362][0],e.mesh[253][1]-e.mesh[257][1]],l=[(o[0]-a[0])/i[0]-n[0],s*(a[1]-o[1])/i[1]-n[1]],c=Math.sqrt(l[0]**2+l[1]**2);return c=Math.min(c,e.boxRaw[2]/2,e.boxRaw[3]/2),{bearing:(t([0,0],l)+Math.PI/2)%Math.PI,strength:c}},L8=(e,t)=>{let n=g=>{let y=Math.sqrt(g[0]*g[0]+g[1]*g[1]+g[2]*g[2]);return g[0]/=y,g[1]/=y,g[2]/=y,g},s=(g,y)=>{let A=g[0]-y[0],x=g[1]-y[1],b=g[2]-y[2];return[A,x,b]},r=(g,y)=>{let A=g[1]*y[2]-g[2]*y[1],x=g[2]*y[0]-g[0]*y[2],b=g[0]*y[1]-g[1]*y[0];return[A,x,b]},a=g=>{let[y,A,x,b,w,k,S,N,$]=g,F,R,D;return b<1?b>-1?(D=Math.asin(b),R=Math.atan2(-S,y),F=Math.atan2(-k,w)):(D=-Math.PI/2,R=-Math.atan2(N,$),F=0):(D=Math.PI/2,R=Math.atan2(N,$),F=0),isNaN(F)&&(F=0),isNaN(R)&&(R=0),isNaN(D)&&(D=0),{pitch:2*-F,yaw:2*-R,roll:2*-D}},o=g=>{let y=(x,b,w,k)=>Math.atan2(k-b,w-x);return{pitch:y(g[10][1],g[10][2],g[152][1],g[152][2]),yaw:y(g[33][0],g[33][2],g[263][0],g[263][2]),roll:y(g[33][0],g[33][1],g[263][0],g[263][1])}},i=e.meshRaw;if(!i||i.length<300)return{angle:{pitch:0,yaw:0,roll:0},matrix:[1,0,0,0,1,0,0,0,1],gaze:{bearing:0,strength:0}};let l=Math.max(e.boxRaw[2]*t[0],e.boxRaw[3]*t[1])/1.5,c=[i[10],i[152],i[234],i[454]].map(g=>[g[0]*t[0]/l,g[1]*t[1]/l,g[2]]),u=n(s(c[1],c[0])),d=n(s(c[3],c[2])),p=n(r(d,u));d=r(u,p);let h=[d[0],d[1],d[2],u[0],u[1],u[2],p[0],p[1],p[2]],f=a(h),m=i.length===478?sge(e):{bearing:0,strength:0};return{angle:f,matrix:h,gaze:m}};var Yb=async(e,t)=>{var d,p,h,f;let n,s,r,a,o,i,l,c=[];e.state="run:face",n=ot();let u=await _6(t,e.config);if(e.performance.face=Math.trunc(ot()-n),!t.shape||t.shape.length!==4)return[];if(!u)return[];for(let m=0;m<u.length;m++){if(e.analyze("Get Face"),!u[m].tensor||u[m].tensor.isDisposedInternal){ae("Face object is disposed:",u[m].tensor);continue}let g=L8(u[m],[t.shape[2],t.shape[1]]);e.analyze("Start Emotion:"),e.config.async?o=e.config.face.emotion.enabled?ob(u[m].tensor||nn([]),e.config,m,u.length):{}:(e.state="run:emotion",n=ot(),o=e.config.face.emotion.enabled?await ob(u[m].tensor||nn([]),e.config,m,u.length):{},e.performance.emotion=Math.trunc(ot()-n)),e.analyze("End Emotion:"),e.analyze("Start Description:"),e.config.async?l=e.config.face.description.enabled?sb(u[m].tensor||nn([]),e.config,m,u.length):[]:(e.state="run:description",n=ot(),l=e.config.face.description.enabled?await sb(u[m].tensor||nn([]),e.config,m,u.length):[],e.performance.embedding=Math.trunc(ot()-n)),e.analyze("End Description:"),e.config.async&&([s,a,o,i,l,r]=await Promise.all([s,a,o,i,l,r])),e.analyze("Finish Face:"),!e.config.face.iris.enabled&&((p=(d=u[m])==null?void 0:d.annotations)==null?void 0:p.leftEyeIris)&&((f=(h=u[m])==null?void 0:h.annotations)==null?void 0:f.rightEyeIris)&&(delete u[m].annotations.leftEyeIris,delete u[m].annotations.rightEyeIris);let y=u[m].annotations&&u[m].annotations.leftEyeIris&&u[m].annotations.leftEyeIris[0]&&u[m].annotations.rightEyeIris&&u[m].annotations.rightEyeIris[0]&&u[m].annotations.leftEyeIris.length>0&&u[m].annotations.rightEyeIris.length>0&&u[m].annotations.leftEyeIris[0]!==null&&u[m].annotations.rightEyeIris[0]!==null?Math.max(Math.abs(u[m].annotations.leftEyeIris[3][0]-u[m].annotations.leftEyeIris[1][0]),Math.abs(u[m].annotations.rightEyeIris[4][1]-u[m].annotations.rightEyeIris[2][1]))/t.shape[2]:0,A=e.config.face.detector.return?dt(u[m].tensor):null;te(u[m].tensor),u[m].tensor&&delete u[m].tensor,c.push({...u[m],id:m,age:l.age,gender:l.gender,genderScore:l.genderScore,embedding:l.descriptor,emotion:o,iris:y!==0?Math.trunc(500/y/11.7)/100:0,rotation:g,tensor:A}),e.analyze("End Face")}return e.analyze("End FaceMesh:"),e.config.async&&(e.performance.face&&delete e.performance.face,e.performance.age&&delete e.performance.age,e.performance.gender&&delete e.performance.gender,e.performance.emotion&&delete e.performance.emotion),c};var B8=e=>{if(!e)return[];let t=[];for(let n=0;n<e.length;n++){let s=e[n].keypoints.find(l=>l.part==="leftWrist"),r=e[n].keypoints.find(l=>l.part==="rightWrist"),a=e[n].keypoints.find(l=>l.part==="nose");a&&s&&r&&s.position[1]<a.position[1]&&r.position[1]<a.position[1]?t.push({body:n,gesture:"i give up"}):a&&s&&s.position[1]<a.position[1]?t.push({body:n,gesture:"raise left hand"}):a&&r&&r.position[1]<a.position[1]&&t.push({body:n,gesture:"raise right hand"});let o=e[n].keypoints.find(l=>l.part==="leftShoulder"),i=e[n].keypoints.find(l=>l.part==="rightShoulder");o&&i&&t.push({body:n,gesture:`leaning ${o.position[1]>i.position[1]?"left":"right"}`})}return t},W8=e=>{if(!e)return[];let t=[];for(let n=0;n<e.length;n++)if(e[n].mesh&&e[n].mesh.length>450){let s=e[n].mesh[33][2]-e[n].mesh[263][2];Math.abs(s)<10?t.push({face:n,gesture:"facing center"}):t.push({face:n,gesture:`facing ${s<0?"left":"right"}`}),Math.abs(e[n].mesh[374][1]-e[n].mesh[386][1])/Math.abs(e[n].mesh[443][1]-e[n].mesh[450][1])<.2&&t.push({face:n,gesture:"blink left eye"}),Math.abs(e[n].mesh[145][1]-e[n].mesh[159][1])/Math.abs(e[n].mesh[223][1]-e[n].mesh[230][1])<.2&&t.push({face:n,gesture:"blink right eye"});let o=Math.min(100,500*Math.abs(e[n].mesh[13][1]-e[n].mesh[14][1])/Math.abs(e[n].mesh[10][1]-e[n].mesh[152][1]));o>10&&t.push({face:n,gesture:`mouth ${Math.trunc(o)}% open`});let i=e[n].mesh[152][2];Math.abs(i)>10&&t.push({face:n,gesture:`head ${i<0?"up":"down"}`})}return t},V8=e=>{if(!e)return[];let t=[];for(let n=0;n<e.length;n++){if(!e[n].annotations||!e[n].annotations.leftEyeIris||!e[n].annotations.leftEyeIris[0]||!e[n].annotations.rightEyeIris||!e[n].annotations.rightEyeIris[0])continue;let s=e[n].annotations.leftEyeIris[3][0]-e[n].annotations.leftEyeIris[1][0],r=e[n].annotations.leftEyeIris[4][1]-e[n].annotations.leftEyeIris[2][1],a=Math.abs(s*r),o=e[n].annotations.rightEyeIris[3][0]-e[n].annotations.rightEyeIris[1][0],i=e[n].annotations.rightEyeIris[4][1]-e[n].annotations.rightEyeIris[2][1],l=Math.abs(o*i),c=!1;Math.abs(a-l)/Math.max(a,l)<.25&&(c=!0,t.push({iris:n,gesture:"facing center"}));let d=Math.abs(e[n].mesh[33][0]-e[n].annotations.rightEyeIris[0][0])/e[n].box[2],p=Math.abs(e[n].mesh[263][0]-e[n].annotations.leftEyeIris[0][0])/e[n].box[2];(p>.06||d>.06)&&(c=!1),p>.06&&t.push({iris:n,gesture:"looking right"}),d>.06&&t.push({iris:n,gesture:"looking left"});let h=Math.abs(e[n].mesh[145][1]-e[n].annotations.rightEyeIris[0][1])/e[n].box[3],f=Math.abs(e[n].mesh[374][1]-e[n].annotations.leftEyeIris[0][1])/e[n].box[3];(f<.01||h<.01||f>.022||h>.022)&&(c=!1),(f<.01||h<.01)&&t.push({iris:n,gesture:"looking down"}),(f>.022||h>.022)&&t.push({iris:n,gesture:"looking up"}),c&&t.push({iris:n,gesture:"looking center"})}return t},U8=e=>{if(!e)return[];let t=[];for(let n=0;n<e.length;n++){let s=[];if(e[n].annotations)for(let[r,a]of Object.entries(e[n].annotations))r!=="palmBase"&&Array.isArray(a)&&a[0]&&s.push({name:r.toLowerCase(),position:a[0]});if(s&&s.length>0){let r=s.reduce((o,i)=>o.position[2]<i.position[2]?o:i);t.push({hand:n,gesture:`${r.name} forward`});let a=s.reduce((o,i)=>o.position[1]<i.position[1]?o:i);t.push({hand:n,gesture:`${a.name} up`})}if(e[n].keypoints){let r=c8(e[n].keypoints);for(let a of r)t.push({hand:n,gesture:a.name})}}return t};var Pe={face:[],body:[],hand:[],gesture:[],object:[],persons:[],performance:{},timestamp:0};function G8(e,t){var o,i,l,c,u,d,p,h,f,m,g,y,A,x,b,w,k,S,N,$,F,R,D,T,O,B,H;let n=performance.now();if(!e)return{face:[],body:[],hand:[],gesture:[],object:[],persons:[],performance:{},timestamp:0};let s=Date.now()-e.timestamp,r=s<1e3?8-Math.log(s+1):1;if(Pe.canvas=e.canvas,!Pe.body||e.body.length!==Pe.body.length)Pe.body=JSON.parse(JSON.stringify(e.body));else for(let z=0;z<e.body.length;z++){let X=e.body[z].box.map((K,oe)=>((r-1)*Pe.body[z].box[oe]+K)/r),ee=e.body[z].boxRaw.map((K,oe)=>((r-1)*Pe.body[z].boxRaw[oe]+K)/r),J=e.body[z].keypoints.map((K,oe)=>({score:K.score,part:K.part,position:[Pe.body[z].keypoints[oe]?((r-1)*Pe.body[z].keypoints[oe].position[0]+K.position[0])/r:K.position[0],Pe.body[z].keypoints[oe]?((r-1)*Pe.body[z].keypoints[oe].position[1]+K.position[1])/r:K.position[1]],positionRaw:[Pe.body[z].keypoints[oe]?((r-1)*Pe.body[z].keypoints[oe].positionRaw[0]+K.positionRaw[0])/r:K.position[0],Pe.body[z].keypoints[oe]?((r-1)*Pe.body[z].keypoints[oe].positionRaw[1]+K.positionRaw[1])/r:K.position[1]]})),Q={},ne={connected:{}};((i=(o=t.body)==null?void 0:o.modelPath)==null?void 0:i.includes("efficientpose"))?ne=Rb:((c=(l=t.body)==null?void 0:l.modelPath)==null?void 0:c.includes("blazepose"))?ne=kb:((d=(u=t.body)==null?void 0:u.modelPath)==null?void 0:d.includes("movenet"))&&(ne=Fb);for(let[K,oe]of Object.entries(ne.connected)){let ce=[];for(let he=0;he<oe.length-1;he++){let Ae=J.find(Ce=>Ce.part===oe[he]),Se=J.find(Ce=>Ce.part===oe[he+1]);Ae&&Se&&Ae.score>(t.body.minConfidence||0)&&Se.score>(t.body.minConfidence||0)&&ce.push([Ae.position,Se.position])}Q[K]=ce}Pe.body[z]={...e.body[z],box:X,boxRaw:ee,keypoints:J,annotations:Q}}if(!Pe.hand||e.hand.length!==Pe.hand.length)Pe.hand=JSON.parse(JSON.stringify(e.hand));else for(let z=0;z<e.hand.length;z++){let X=e.hand[z].box.map((ne,K)=>((r-1)*Pe.hand[z].box[K]+ne)/r),ee=e.hand[z].boxRaw.map((ne,K)=>((r-1)*Pe.hand[z].boxRaw[K]+ne)/r);Pe.hand[z].keypoints.length!==e.hand[z].keypoints.length&&(Pe.hand[z].keypoints=e.hand[z].keypoints);let J=e.hand[z].keypoints&&e.hand[z].keypoints.length>0?e.hand[z].keypoints.map((ne,K)=>ne.map((oe,ce)=>((r-1)*(Pe.hand[z].keypoints[K][ce]||1)+(oe||0))/r)):[],Q={};if(Object.keys(Pe.hand[z].annotations).length!==Object.keys(e.hand[z].annotations).length)Pe.hand[z].annotations=e.hand[z].annotations,Q=Pe.hand[z].annotations;else if(e.hand[z].annotations)for(let ne of Object.keys(e.hand[z].annotations))Q[ne]=e.hand[z].annotations[ne]&&e.hand[z].annotations[ne][0]?e.hand[z].annotations[ne].map((K,oe)=>K.map((ce,he)=>((r-1)*Pe.hand[z].annotations[ne][oe][he]+ce)/r)):null;Pe.hand[z]={...e.hand[z],box:X,boxRaw:ee,keypoints:J,annotations:Q}}if(!Pe.face||e.face.length!==Pe.face.length)Pe.face=JSON.parse(JSON.stringify(e.face));else for(let z=0;z<e.face.length;z++){let X=e.face[z].box.map((Q,ne)=>((r-1)*Pe.face[z].box[ne]+Q)/r),ee=e.face[z].boxRaw.map((Q,ne)=>((r-1)*Pe.face[z].boxRaw[ne]+Q)/r),J={matrix:[0,0,0,0,0,0,0,0,0],angle:{roll:0,yaw:0,pitch:0},gaze:{bearing:0,strength:0}};J.matrix=(p=e.face[z].rotation)==null?void 0:p.matrix,J.angle={roll:((r-1)*(((f=(h=Pe.face[z].rotation)==null?void 0:h.angle)==null?void 0:f.roll)||0)+(((g=(m=e.face[z].rotation)==null?void 0:m.angle)==null?void 0:g.roll)||0))/r,yaw:((r-1)*(((A=(y=Pe.face[z].rotation)==null?void 0:y.angle)==null?void 0:A.yaw)||0)+(((b=(x=e.face[z].rotation)==null?void 0:x.angle)==null?void 0:b.yaw)||0))/r,pitch:((r-1)*(((k=(w=Pe.face[z].rotation)==null?void 0:w.angle)==null?void 0:k.pitch)||0)+(((N=(S=e.face[z].rotation)==null?void 0:S.angle)==null?void 0:N.pitch)||0))/r},J.gaze={bearing:((r-1)*(((F=($=Pe.face[z].rotation)==null?void 0:$.gaze)==null?void 0:F.bearing)||0)+(((D=(R=e.face[z].rotation)==null?void 0:R.gaze)==null?void 0:D.bearing)||0))/r,strength:((r-1)*(((O=(T=Pe.face[z].rotation)==null?void 0:T.gaze)==null?void 0:O.strength)||0)+(((H=(B=e.face[z].rotation)==null?void 0:B.gaze)==null?void 0:H.strength)||0))/r},Pe.face[z]={...e.face[z],rotation:J,box:X,boxRaw:ee}}if(!Pe.object||e.object.length!==Pe.object.length)Pe.object=JSON.parse(JSON.stringify(e.object));else for(let z=0;z<e.object.length;z++){let X=e.object[z].box.map((J,Q)=>((r-1)*Pe.object[z].box[Q]+J)/r),ee=e.object[z].boxRaw.map((J,Q)=>((r-1)*Pe.object[z].boxRaw[Q]+J)/r);Pe.object[z]={...e.object[z],box:X,boxRaw:ee}}if(e.persons){let z=e.persons;if(!Pe.persons||z.length!==Pe.persons.length)Pe.persons=JSON.parse(JSON.stringify(z));else for(let X=0;X<z.length;X++)Pe.persons[X].box=z[X].box.map((ee,J)=>((r-1)*Pe.persons[X].box[J]+ee)/r)}e.gesture&&(Pe.gesture=e.gesture);let a=performance.now();return e.performance&&(Pe.performance={...e.performance,interpolate:Math.round(a-n)}),Pe}function S0(e,t,n={order:2}){let s=0;for(let r=0;r<e.length;r++){let a=n.order===2?e[r]-t[r]:Math.abs(e[r]-t[r]);s+=n.order===2?a*a:a**n.order}return s}function H8(e,t,n={order:2}){let s=S0(e,t,n),r=n.order===2?Math.sqrt(s):s**(1/n.order);return Math.max(0,100-r)/100}function j8(e,t,n={order:2,threshold:0}){if(!Array.isArray(e)||!Array.isArray(t)||e.length<64||t.length===0||e.length!==t[0].length)return{index:-1,distance:Number.POSITIVE_INFINITY,similarity:0};let s=Number.MAX_SAFE_INTEGER,r=-1;for(let a=0;a<t.length;a++){let o=S0(e,t[a],{order:n.order});if(o<s&&(s=o,r=a),s<n.threshold)break}return s=n.order===2?Math.sqrt(s):s**(1/n.order),{index:r,distance:s,similarity:Math.max(0,100-s)/100}}function q8(e,t,n,s,r){var i,l,c,u,d,p,h,f,m,g,y,A,x,b,w,k;let a=0,o=[];for(let S of e){let N={id:a++,face:S,body:null,hands:{left:null,right:null},gestures:[],box:[0,0,0,0]};for(let O of t)S.box[0]>O.box[0]&&S.box[0]<O.box[0]+O.box[2]&&S.box[1]+S.box[3]>O.box[1]&&S.box[1]+S.box[3]<O.box[1]+O.box[3]&&(N.body=O);if(N.body)for(let O of n)O.box[0]+O.box[2]>N.body.box[0]&&O.box[0]+O.box[2]<N.body.box[0]+N.body.box[2]&&O.box[1]+O.box[3]>N.body.box[1]&&O.box[1]+O.box[3]<N.body.box[1]+N.body.box[3]&&N.hands&&(N.hands.left=O),O.box[0]<N.body.box[0]+N.body.box[2]&&O.box[0]>N.body.box[0]&&O.box[1]+O.box[3]>N.body.box[1]&&O.box[1]+O.box[3]<N.body.box[1]+N.body.box[3]&&N.hands&&(N.hands.right=O);for(let O of s)O.face!==void 0&&O.face===S.id?(i=N.gestures)==null||i.push(O):O.iris!==void 0&&O.iris===S.id?(l=N.gestures)==null||l.push(O):O.body!==void 0&&O.body===((c=N.body)==null?void 0:c.id)?(u=N.gestures)==null||u.push(O):O.hand!==void 0&&O.hand===((p=(d=N.hands)==null?void 0:d.left)==null?void 0:p.id)?(h=N.gestures)==null||h.push(O):O.hand!==void 0&&O.hand===((m=(f=N.hands)==null?void 0:f.right)==null?void 0:m.id)&&((g=N.gestures)==null||g.push(O));let $=[],F=[],R=O=>{O&&O.length===4&&($.push(O[0],O[0]+O[2]),F.push(O[1],O[1]+O[3]))};R((y=N.face)==null?void 0:y.box),R((A=N.body)==null?void 0:A.box),R((b=(x=N.hands)==null?void 0:x.left)==null?void 0:b.box),R((k=(w=N.hands)==null?void 0:w.right)==null?void 0:k.box);let D=Math.min(...$),T=Math.min(...F);N.box=[D,T,Math.max(...$)-D,Math.max(...F)-T],r&&r[1]&&r[2]&&(N.boxRaw=[N.box[0]/r[2],N.box[1]/r[1],N.box[2]/r[2],N.box[3]/r[1]]),o.push(N)}return o}var C0=`
|
|
/9j/4AAQSkZJRgABAQEAYABgAAD/4QBoRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUA
|
|
AAABAAAARgEoAAMAAAABAAIAAAExAAIAAAARAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQu
|
|
bmV0IDQuMi4xMwAA/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoUDg8MEBcUGBgXFBYWGh0lHxob
|
|
IxwWFiAsICMmJykqKRkfLTAtKDAlKCko/9sAQwEHBwcKCAoTCgoTKBoWGigoKCgoKCgoKCgoKCgo
|
|
KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo/8AAEQgBAAEAAwEhAAIRAQMRAf/E
|
|
AB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAE
|
|
EQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZH
|
|
SElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1
|
|
tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEB
|
|
AQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXET
|
|
IjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFla
|
|
Y2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXG
|
|
x8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAwDAQACEQMRAD8A+qaKACigApGOKAML
|
|
Xp8xlF5A7V4X8RtYs7PzfNImnx8sa8Kp9z3q2tEgp6angWs62ZZ5CTGoJ6DArGNz5p+UrID6EUrF
|
|
PUlW1EuN0XNW7PQ2L5j3JnoKXN0KijqNP0eYoqXBdgPuuo+ZPeupisWn2Jd4+0r924XgsQOCff3/
|
|
AJ1FzRKxDqGii6m3siiQ8F1XGfXI6YNWLfRbiRQMkcZI9fpTDluT2/h6Qy8gDPbtmtG38JeY480Z
|
|
5zSLUTZg8M28YwYxjAArXtdPt402qgHbpSaLWhma3o0Uqk7Nx9DWLaaVblgPs6qRyds2M/gRSQp9
|
|
zZOni2iWS2hlQ+kjYz9OMGrdjq89vIPPVhj+8M/lQyDq9P1WOYBlMZz1AOD+VdDaTiReOKulK0jO
|
|
tHmi0WDTlr0TyxRVhT8tJjIX+9SUxHXUV553BRQAVBcPhSBTSuxPY86+IGti0s5I7dsORy9fM3i6
|
|
8e8mfDO5P90ZrWWiJicNPpZZtxV/xrW0jQt4DOv6Vk2dEEdTY6BHuB25rpbPSo0QARjP0qTRI17W
|
|
wA/hFaMWmoQMgflQXYsDS142rU9tpqqenfNA7GgtihxkdKuRW6qMY/GkDZY8sY4Ap4hXbyB+VArk
|
|
EtuH4wPyrk/EGkOm+a3jw3suRQLc5i38SX9hJ9nnY+XnBUdPyNdFY6pa3KkkAE9l6f8AfJ/pSJT6
|
|
GhDmI+Zb4ZRycdv6ium0nUhKFydrelTsNnS2829RnrVgV6NKXNG55lWPLIM81Op+WrZkRMfmNNzT
|
|
A7GivPO4KKAEY4XNYWt3vkwPg4OK0giJdjw/xrqhm87Zs8tc7pX5A+leSajf6aHYJ50kn4AZpTep
|
|
rBWRm2Vobm4BXfyehPFdnpmnBFUY5rI2SN63tlToK0YI+KZpFF+3QdavwoKTLtoW0Toaswpk5pCb
|
|
LCxipAhoIuP2dKevHXoaYDylRyxhlwRQI4nxVoCXWZI1GfpXGtbSWjYPGP73+NIGupt6TqMsLruZ
|
|
ih4xnP5V09mQ+JLd8gn0xSYJnVaVdkook69K34zuUGunDS3Rx4qOzHVIp4rrOMY3NJQI7GivPO8K
|
|
KAILt9kZrz3xlebYiu8KCCWb0XvW0NFch6ysfO3jLVjfXLIn+pQkKorl7WxNxIPl71g2dUUdpo+l
|
|
pBGvHPet23iC8ihFosrxirkHQUFo0IF4FXI1O726CpKLacCrMJoJLYHAPpTwucHpSRJJ5e4AZI9x
|
|
UqpxzVpCuOC8cUpQUMRnXttuB4rjNdsYyeVwfXpmpGmcvcQyafMCFJjPY10eg34BUg4DcZP8jUO4
|
|
HaRq3lLNF+IHet7R7jz7c56rwa2wz9+xhiVeFy/T1PFegeaNPWigDsc0ZrzzvDNIaAM7VpNqdegr
|
|
xL4l6kywyRhseZ19lrdfAZL4jxYg3Fw20d63tJsdrDI5rm3Z3R0R0Mce1eKnQYAplIkWrMJ45oZS
|
|
NO3PHbNXIyfpSGWowSOasxLUiZdjFSqtNEMkUemKlAGKsRJjAppFAiORMjmsTVrNZEO4cfSoZSOD
|
|
1eJ7WXBUzQZ+7nkfSo7e2Ei+ZaMzxntjBX2NSU1Y6/wxqojiEFzkA8KTXYaUoWRyv3W5rSjpNHPX
|
|
+BmpSg8V6J5gUUAdhRXnneFFAGHrTfu5PpXzj8S70/aZtxzztXFbv4DKHxHI+H4GZiz9zxXXW8G3
|
|
GBXMjvLRXAx0oPGPSmMVeOnWrMTYpFI0bcg1fh54xmgovRcD3qxETSIZcRvzp+/BpEkqsBUqsM9K
|
|
q4Em4Gkxk0yRGXrVW6i8yFhkg+tJjRxGsWrxllkUMh9eK5uMz6bcebbnfG33kPcVkay2OntPKuo0
|
|
nhXI67c8qa7Lw3c+adjcEDGK1paSRhVV4s6A0or0jyRRQ1AHX0V553hRQBz+vNtt5z3xXzX8Qbdm
|
|
uic5YnOMdK3l8JnTXvlbwpYl+WySOgrp5YfLOOB9O1c62O7qQkc+9RsKChFPWp4DluOlSykaNruH
|
|
ArUgHShFNF2NT1qxGO3NBmyxGcE1N2560CFzjrUysO9JAPDDjFOVuKoQuSRTWouBkazbCa3cd8cV
|
|
wF7IISQccHBzUSWpV9C3o1x5b5GAjdQD1rs9DjC3kckbEhqKfxIzn8LOupRXqnkPccBSkUAzraK8
|
|
87wooA5rxMSI3HqK8B8bQl9Q8sffY5b/AAraXwkUviNrw9pH2W1ViMMRTdRjw4HpWNtDti9TPc4P
|
|
FQs2M5qdyyMHLcfjV63HTAoBGtap0wK0YxigpsuRDtVhVYd6GQydVwwIqdRnqKCR23I5pCMUW6gD
|
|
YNKuetAEise9KTxQBWuFyhrznxNZkXjFeN3I+tTIZg2OqmzmxNF0PO3vXp/g2+hukVl4zyPanTXv
|
|
JmVR+60dpThXpnlPceopWFAbnV0V553hSGgRynjC5FujOey14Ssp1HxNmTnc+a3kvcIpv37HoEYQ
|
|
QmMdVHSsnVbYJF5jVk0dsNzlruVIsl2wKxbjWrVHILjg1CRbZJb+ILHPzyhfStODWLQgFJFYd+el
|
|
UJM27HUIXxhga1Y5lLVLKLkMnoauxnPPrSEx7ShF+Y/n2qrc6xBbhizDAqkK1zJuvG9nbg8ZA681
|
|
ly/Ei052RO3uKAsZlx8QGd8xxvt9Aa1NH8dK7AXMcip64zigdkdrZX8F7EJLdwwNXMkrz1qRMRly
|
|
CK4TxmpidWI49felPYSOMmi80NIoOV6qRzXYeA5SskYPfirpfEjGr8LPWVHyD6U4CvQPL3ZItOYc
|
|
UDOoNFeed4Uhpks4H4iE/Z5MeleMeGULeLgjds10S+BGdL+Jc9OSBU2Huc5Nc74yvUtrcDBrJnZF
|
|
63PJdXvLy/lKWw46bvQVz82jXhkLO5Y+9ZlsYthcRnbIjY9R3q3awTRkEM3WmJI6C0ea3dGRsr1x
|
|
XY6TqW9FLHnjrUs0izpLK5DDjofSta3ckH09KRUkZuuTvFGdvPauE1Y3U6Mqbssf/rUxHPTaJPK2
|
|
ZmJPbBqzY6DCZh5xJC9s9aBJHU6dpemJjfEmfetJtI0+VPkUr/unFOxdiextHs33W07YHQHk11mk
|
|
Xb3KbZ1xIvcd6LEyWho4Nct41sTPYb16ipexCPPZN+wYGCvH1rrPAEJmvkPoc1VL4kZVvgZ6yFwK
|
|
cBXoHkkqinFaVyzo80GuE7WJRQSziPiGdthK5HQV4x4J/wBI8WPIewNdEvgRNL42emO/yj1UHNef
|
|
eNpRczbC+I17DvWT2OqJxc0sMK4TCisy41q0hfEkqj8aixdwTXNOlwvmqD9anS9tXH7uVG+hosO4
|
|
/wC0oOhrR0+6G4YNIEzsNEuCxAPNdjZruA4xxUmjINSjURksOlcbqFykbnjFA1sYGoassaknCqO5
|
|
rl7rxhGm7yBnBxuJq0rkSlYpw+NLlsfd5P8AerVsvHEqSBHwPVgcgVpyMyVXU3rXxcHYETAk+hru
|
|
/DWti6ZSTyOKzZqndHaxvvUGq2rQ+dYyqR24qWI8dvbr7LqDxyDAzXpvw6FvIxePGSM06Xxoyr/A
|
|
zviKFHNegeX1J41zUhXioGbuaSuM6wpCaBHG/EcA6HN/exxXjXw2jL67cv8A3Qa6H8CFR+NnoWpO
|
|
I4XI44rxLxrqjQzSEsQM1gdSPM9U1uR1YbmWIdXHf2rmpIb67YS28UrRlsLI3c/jW0VZGUpO5pW1
|
|
jfLNOjahawzwReYI5cjzMkDavHJ5/SrVv9uhtPtVxCPLBwzxnlT9KGghLU3tKvvPjHzbl7EGuisJ
|
|
GRxWLOg7nRXJEbDjmvSNK+aFSfSoZr0KutRkphc4NcRrdkVjL9aVio7Hk3iqS8ubhrWzUlsZY9kG
|
|
cZNc5D4aee5MclzJIFTzHAO0MfatqSOWu7bFS1srDUZEis0vIZoUxPvfcC+4/dx2xjr712XiTwXb
|
|
WmlQ6hol3cRhoFd4rlg3zY5wR0GelavQwjq7GD4etdVvSnk2wAB+9v8A8mvcfA2kXiRo0/UdcDis
|
|
ZnTTulqeoWqbUAJqWUb42X1FZlnjfjSwlGrr5S/eNdD4RkvLAAQ4yRyaUZcruVKl7TQ9I0G+mnzH
|
|
ckFwM8VuIK7ac3KF2eXiKapz5UWYxipNtMyNejNch0jSar3cjR27uoyQCRVRWom9DxTx54gu5fMi
|
|
lbKdMVjfCZPNlv5v9rFbVHpYqjGzbOn8SzFI9o715L4u0r7arYzk+lYdTqSujy7U/C0u4vHk+WwO
|
|
xuh9q3J9dgvbdVukMV1EwbDDgn04rZMwlHoZ+orZ6hfQ3RWVnQYCgZAq+8U0ln5NtBsV2yxYcfgK
|
|
JtW0CnB31LlroVwJ1nQLGDjeP7w+lb0dsFxjrWB0tHS6NuWPJ6A16ToUm63T3Gallr4S7cxiTjrX
|
|
PaxaF7dlVeSMUhxZ5jd+H7qCa4eF3DSE5x3zXN3Wk6jbyeaiFWUY6ZyPStYS5SalPmVipFbX0E4c
|
|
W0alvmPHJrag0rVvEE6LdljGpG2NRtQD+tW5XMI0uU9M8NeFo9PiQhecDIIrtrOMIoG3H4VlJm9t
|
|
C6CB06VPGM1IHLeItGS6uw+ORT7e3jsbQvj7gzUNam0JaWE+HN7NqOqX80n3FO1RXo8YzXdS+BHk
|
|
4z+KyzGPapcU2YIv7qQtiuaxvcaWqG4O6FwfSrS1JbPnrxoxkv7qIfejcitj4V2f2exumI+8+aKn
|
|
xHTT+G5d8Txlm4rjLxMsQwzWT3OiK0Mm6sEkVsAcjFc1d+FEmlGwEDPQVopaEuOpr6f4ZWNAu3tW
|
|
vHpAj5ZQcUFIWaDjGMVUMQ3cVDBmvbhY7QAV2nh+T/R1yeKhlrY31+b61FcQK6nIoJMi401WblRi
|
|
qr6PCw5UYq9y+YgOgWzNkRrx3xWjp+nx2v3FQcelAbmko9anQ4GBUNisPHWr1qMrQhS2K11HvmYV
|
|
hamcxSRZ5xRIqluS/DKAQQXZxyXrvo2FdlL4EeZjH+/ZbjNSZpswLNBrE1Gt7VE4ODVIlnh/j61F
|
|
j4lmeTGyUbq6LwdEqWbeX0YbhSqfEddP4Bddj4JIrhL5d8h7VjI6oLQqKNzelWre3yc4/ClFjaL6
|
|
wqBxxUUxwCKu5BmXRA6c+9ZjP83FSBoQuPs4BrsNBlUW659KmRrDY6G1lyQtW3Hy0lqQ1qVJnAbm
|
|
oy3b9KYJCqRj3o4zRctIlhjLHmpSuOBRbQOpLGpPFaES7UqkZzKN1KsEc87/AHUUmvPLTVGv72aQ
|
|
k7WJwKmRrQ3ud74Ltilgz4++2a6iNDXdS0gjyMU71my7GpqTbxSbMki3SViajTTHqkSeR/GeyZmg
|
|
nQHkEE1S+F+oPPavBL96I4/Cia1udVF+4dVrkW+Fq8+v4tjMDWUkdVJ6WM0cNV+F+MVmjUcZgqnP
|
|
1qpNNnkcVRLiZtxIS1UzzIF7mghlxUZpVQdq6nTVdAoAOKzkbQWhvwM6gMM1twOJYx3NOJE11Kt1
|
|
H1/pVVlwBkk+9NocXoOQ45FPj+fkUJFF2NSB700v/hTEty5ZpkjvVyUgcCq6GM9zC14/8Se6GcZQ
|
|
1574Xs5WkI2HBPHFQ1dm1KSSZ7Rotn9l0+KPHIHNacae1dy0Vjxaj5ptlhVp+2s2CJ9ppCKzuWNx
|
|
zSFc1SYrHNeNdIGpaYw25ZeRXmvheyk0jVpEdcLJ0q3ZxNKTa0O3vQHg/DNcHrsJDmsmjspnNzNt
|
|
fFIJ24GazOhC+azDmgZIOOKBsp3J2qSaZodubq58yQ4QAnmhGT3NO18pb7BORmu205LfYpyKVkWp
|
|
Oxr5gKYWoIZWgfGfloFq1qTPLubnGO1RPtxg4P0oBAkY/hBz6VNDDkZ6AU0W2WSdqkdKr9ZOaGSj
|
|
VtcLHmnOcgmmYvcz7mBLy3MbdD1q9ouiRK6bUAVeelOC1InPlidSsWMDFOCEdq3uefykqrinYqGy
|
|
rFvApMVka2DAowKAsMkRXQqwyDXn/iWyitNQ3qPl6itIvRoF8RXinW4tQ6HI6GuW8SIVBPalc6qe
|
|
5x9x97r3qruwTjrWZ0ksZ9TUmcDNAmZ9/wAoao63rR0+w22MLPtAzt6mghmfofiB76LdJBJBIp5D
|
|
d/oa7bSdWLIPnpDi9TM8TeKdas51XTbIyxd3J/pXS+E/EFxqNoFu7do5OmD60maHWrnZyDRkn/69
|
|
MlEyOR0xntVoNx+FUgYjPxg4FLCuWDZyKQr2RoRnP0qO+nEFpJITgAUzLqZnhu6+0rknOTXpOmwJ
|
|
Fbrt5yMmnHYyr6Oxb2ijaKLnPYMClwKQWK3n0hn+lachHOJ9pNNN0apQFzsY10a4v4hXQh0xpieQ
|
|
MA1XLZNjhK80cT8OdV+3Wl3A7ZZJCw+hrR1qLcjZ/CsbnfHRnFXseHJArOYYbrUs1uPhYbuatqFP
|
|
ByfSkMq3UIINYkto+87Tx6GkSxfsDbflGD7CtTw/pk4nzITtPIFMFudsukh4Rxz71paTpKwP5jcn
|
|
0qTRy0NORMDgVCqewoJTJgAoxjntTiTu7fWmFxAcnn1q3EPl+X8KZMi4gKqB1Peob/Tv7Us5bfeU
|
|
yOoq4R5nYxqT5I8xieH9J1DTbvyJELRg8ODwa9Ms5mSFV9BWiptbnNVrKdmif7Q1KLg96XIZc5Is
|
|
pNL5pqeUrmMtZs0jzV08phchaY00zH1p2ZNxjS1g+LdJOt6U9ssmxjyGp2urDjLlaZzng/wUPDqz
|
|
TSTmWeTrjpVjVk3Rvjr2rnqQ5dDvo1XUd2cTqSNk9OKxXGCeKxZ1DAxHTr2q5C/y8GokUhsz54qu
|
|
uCxzSQjQ0+FZblR2ro4bZYiMVQ0dBb7Qi5x0qzuG5QOh71LYErDufpSeWrHnimIXbjkUjLkH1Hem
|
|
gGxryc+tXI19KYmWegq9YLiLJ7mtqS945cS7QsWehqxA9dEjz4krPSxyZqbFFhGxUm6smjRM55Lk
|
|
HvSvNxXTY57kLT+9MNwKdhXGm5FIbkU7Bca1wMEVhaiuQcVhXWiZ14R6tHGanGBI2OtYkqEHjgVy
|
|
s9ErEeo6UBsHipKEZs5qpPdRxcbhx70NCSuybTNWihc5brW9Fq6vjMnFSdEIdDRi8RRKygZbHFbu
|
|
m6nb3RA3gMegNJhOm0jbXGOoxTuCc1Rz3FyoGKawz9KaAVcZqeMgCmIkB4FaUTbYwB6V00Fuzixb
|
|
0SFMuDU8Mlbs4UPeXHeiOXkUrDuXYnyKk3cVk0ap6HMxxketSMhrcwRC0dMMZFMQ3yzSeVQAeUaz
|
|
9Vj8uPd271nVV4m+GdpnHX67pCeKyLtBtNcR6xlk9RVeWTb3qRnO6trgttyIfm71z7ai8j7/AJmN
|
|
DNqUVa5Yi1AnjynHuBV+11YJhWWXcP8AZNSzqgmaEerSsf3NtIQP4mGKtRavdRgMIpVI9KjU0a7n
|
|
R6T43uYQI7qN2Tpkqciu503VVuQGAYZHQjFVc4alPlZrpKGAznpTwxOc9+lWjIlUACnM4XApiLNk
|
|
nmvnsK0NvpXZRVonmYqV52GsmanhXitTmFkSiJTSAvwrxUxXIrJ7miOfjf1pzNWxkRlqYWpgJupu
|
|
6gQbuahvIxPA6eo4pNXVioS5WmefakGhndH4INZs5DJXA10PaTurmLO21uKpSZqGMoXGnRzBiyjd
|
|
9Kx5rcQS428fSkjanLoaOliHGZFB56VswW+mtPufcBsGOAfmxz+tFkd8HpoaUx09FAtFY8DO71qb
|
|
Sms/Nb7RbecG6AEjFLS5c78t+p0djpVs9wsyQiJAdyr1rW+zqjErzSe559Sbk9S3C+MA1bjbgE1S
|
|
MSXzMVG0vNUI2tPKrAuCMnrVzNd0PhR49W/O2xrHmp4TxVMzQshpIzzQBehqesnuaI5VGzT2bitz
|
|
FEbNTC1ADS1JupgG6l3UAc14s04yR/aYRll+8BXCtLncDXFWjys9TCz5oW7GddH5qqNzWDOgQnC8
|
|
VSuo1kHzAGkPYopEY2+RWxV23Vzj5G/Kg3jWaNazhZuqNXS6TaKhB2c0jR1nJWOlhOxRxU4YkCgx
|
|
Y0OQatQyDbyaaFYe8uF4NY3iC9ltbVGj43NTIL3h7WzMihjzXVQXYYDdW9Cf2WcOJpfaRZ3g9KsQ
|
|
mupnCLIabGeaAL0LcVY3cVmzRHIxtUhetzEjZqjLUAIWpN1ArhupwagAfDKQ3Q1594v0c2bm6tx+
|
|
5Y8j+6ayrR5onThp8s7dzkZjuqAAmuBnqC7c0iwgtzSA0rWzjfGRW3ZadDu4AoNYo2rfS4v7orSh
|
|
05UA2r0pDbsTm29KRottBNyJ0wpJ9KhD7f6U0ikNWffIFBz60zVUW52ow4UcUN6EPcx44WsbgOmd
|
|
ua7TT5Bd24KHnFKnLlZFSN4koluLdueRWvp14swweG9DXoxldHlTjYtzGoo25qzEvwtUxas2jRPQ
|
|
5CNqkLVsYoYzUzdQA3dSFqBBmnqaBhuqhriCXTpVIzxUz+Fl03aSPI9QTypW2/dz0qKNw3SvOPZR
|
|
Mqin8VLKRcs3O4Cuk0w/MDjt1NBtHY6O2IIHY1pxgFaETIRwMkjtVSUEk4570MlFW5bap6dKzWm8
|
|
1tqH8aY+hp2FvGoGayNevVt7/ap4xzUvYjqTLtvLPcvJxSaVcyWsxTnFZlnT2t15xHmCtOBYwQy4
|
|
B9q7cPO+jPPxFO2qLEj5HWo42+aus4HpoX4W4FTF+KlotbHII9SFuK0MUNZqiLUDE3UbqBBupwag
|
|
Bc1DefPbyD/ZND2KjujyPWlKzuPesRZjHJXms9lMuw3StjnmphKDSLTJ7OfE3JrpbO4GQc9qlnRA
|
|
3LO82k5NbFvdADkjBoCSHyXIIIzgVQvdRigT7wzjgUzO1jHknlvG7qnp61etYFQDIpCZoqVijzXn
|
|
3iC8EmsOuaCGb/heR/s0ijkVv6fbxy3QMg5xmsnuX0Ldzut3+UYTPWk+2GJSe+M1pFtamcldalmx
|
|
1eO4XaThhWnC+TXqR2PHqL3maUJ4qRjxSEjj42qXdxVmaGs1MJoATfSbqBAG5p6mgAzTJTmNvpQU
|
|
tzzHXY83D/U1zF5FhjgV5r3Pa6FMsV5HWnLe7RhqBRdmTwagN2d2K2rPU1C5LAnPrUs6Iysbdrq6
|
|
f3gK0BrUKj/WClY05iM6xLOcQAj3NT29uznfKSzHuadzNu7NSBFjHNSm5VO9IRnajqoWMhTzXFtA
|
|
bvUfMduSeg702Qz0rS7FbTToQFwzjJqaGTFyfK5PQViyzUuFmuIdgGABya5u/vTaN5cnUHFUmLoZ
|
|
zyskwlgJweSK6zQdUEwVJeGr0aUrxPLxEfe0OrhPAqVjxWhznGRtUwatDK4jNxURbmkAm6jNABup
|
|
6tQAFqhupNtu59qUnZFwV5JHnWsHdIx96w5lz15rzT2uhRmt85xWbcxMnUGmZlB0bdxmrNvFIcfM
|
|
350mWjbs7YkDJY/jW5ZWW4jikWkdNp9mqYJFaJdEHHakUULu/VB1rLn1Ld/FgetMGYd/qWSQmSa0
|
|
/AemS32pfa7piLeLkg9z6UmQtz0W7uQ2cZx0A9BVzR7cAea6j2rPqX0L99KRat5A6Dk1wOoKZ52a
|
|
YfMORTYRLujiGWEq6/NWza2yKQVHNdOHerRy4laJo6TTnbbtb8KuM3Fdh5z3OJjbmpt3FaMxAtUZ
|
|
agBN1GaQBzTwaAAms3VbjERUGsa07RsdeFpuUuY4jUjljWTKK4j02RE4IpJYFk6imQkVl0xWarsO
|
|
mAEcUi0bNnZBR0rWtoguMCkUi21wI161mXuocEKaYXMS4u+pY/hVCSWSY4HT0pEmlouiSahdpEBl
|
|
mOceleiwWcNjClvHgJH97Hc1EmVFFi3Czy7mwIl/WtJbjP7uLgd/apQ2VNVvtsBhiPzdK5S4nAuR
|
|
nqOCaTGi9pcytPlU+XpmumtWII44rah8ZjiNIXRuWeNvvViQ/LXpJWPJbu7nCRvVkNxVsxBmqJmo
|
|
EPiXca0YLMuOlJsuKuPlsSi5IrNuG8s4HWs5VEkbwoOTKsk+FJY4rC1K53k1xTk5O7PSpwVNWRzt
|
|
4cms+WpKICtSLTETQj5q0YeBSGiys23pUguGxQMq3E59ayrm4x3yaAKiRtO2WPHcmhruKFxFajzZ
|
|
ScA44qRHoXhuMaLpxaUg6hcDLMf4F9KlhuDeXGASIl+8azZslYma68y48m1+7nFW5rtbRNhb5z1p
|
|
iMKbUg0zuW4A4rPgb7VdKXOMmpA7HRbMS7nUYiUda0lkQOBngVrS+JGdbWLRt2bAx5BqeQ/LXpnj
|
|
PQ4GJ+ashuK0MhWaoWcA0AaOmASMK7jRNPWYBmHyiuepO2x10qfcv6vYxCzYqoGK4HVYVTJrmb5l
|
|
c6oaM5TUJ8EgGsG4kLNUHT0M64OaqMMikSRsuKbnFMRLG3zVehOaGNE445NNlnVFpDMu6uie9Vo1
|
|
8z5mOAOST2pDK91cNN+5tsrH3PrW54a06KxT7fdrlh/q1Pc+tJ6IUdZGvHPLezMcnBOWbsPap5r3
|
|
ylFtbdT1xUWNWzU0/Zbwlgfmx8zGsHWtRHmMqE59aAMyNifvHPc1f0gtPdqkY5JosJHeNci2tktY
|
|
euPnNY+oXWZEVJNrZ9aun8SIq/CzodHuriIokhDIR1ronbKZr0o6o8ipoz//2Q==`,T0=`
|
|
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAsICAoIBwsKCQoNDAsNERwSEQ8PESIZGhQcKSQrKigk
|
|
JyctMkA3LTA9MCcnOEw5PUNFSElIKzZPVU5GVEBHSEX/2wBDAQwNDREPESESEiFFLicuRUVFRUVF
|
|
RUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUX/wAARCASwBLADASIA
|
|
AhEBAxEB/8QAGwABAAIDAQEAAAAAAAAAAAAAAAEDAgQFBgf/xABDEAEAAgECBAMECQIDBgUFAQAA
|
|
AQIDBBEFEiExE0FRBiJhcRQjMkJSgZGhsWLBJDNyFSVTY3OSNEPR4fAHFjWCokT/xAAYAQEAAwEA
|
|
AAAAAAAAAAAAAAAAAQIDBP/EACARAQEBAQADAQEBAQEBAAAAAAABAhEDITFBEjJRIhP/2gAMAwEA
|
|
AhEDEQA/APqYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAKNTq8OkxzfNkisQC8eb1XtRNbzXT4q7eU2nu0MntRq/D8StMccvW29ZmdvgjsTyvZjxOLj
|
|
+s8WLxn8TFPXs6Oj9oct7c14rkxz22nrB2I49KOdTjelmszfmpMeUxv/AA28OqwZ4icWWtt/SUi4
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmdo3nsPNe0Pt
|
|
Fh09Z0+DNWL7+9O/7A3eJcZppsV5raI27esvH6jX5ddM25p79Ilo59VbUZOe2Tm/PeGvfPfT2iKR
|
|
PLv1+DO678XmW/a97U6TtOyzTbTF538/T9WjTNecm9a7126tqk3rSYxY5ta1plRZqZNXGjyZcPXl
|
|
mZmsx+qjBrsuO16xM7eXRt04JrdTltk5OWJnfaWf0a2lty5MdZnfzSn+WOHiOutFpjHa9e8bQ2fp
|
|
+alYy462pk7zXbuxjPesbRS0f6ZZV1ET1tErzXFLHo+A+1ddZf6NrI8PJHa1vN6iJi0bxMTHwfOa
|
|
zhzd61v1846utwniM6DUdb3nBaNrVmd9vjC/ZVePYirBqMWppz4rxaPgtEAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAItaK1m09ojcHnvarjM8P0vh49+a/eY8ng9D
|
|
h1fGM1rxjtGPfvbzdbjuTJxHX48cTPNltM/KsS9Dw7S49Jp6UpHaGe2vjz1y9J7LYK13vHWe7bj2
|
|
ex1tvM80ekuxW3RnW3Vm6P5jRx8H0+OYmMcb+bapo8GKPdpC6bQwtdHU8JpWkdJ/JweL6e23iU67
|
|
d4dubSqyVi9Zi0bwIs68XGp36TtEq7ZJmZmevzdbifCKWtbJinkt6eTgZPFw32t+sRurbWVzxs1y
|
|
Rv6T8V1NZNPtfq0seTm+Kevr+SZuxXjvaPiV8N4viycto9HseG6+uu08W6Rkj7UPmFck1tE1nlmP
|
|
Ld3eA8V8HVVi1pjq6Ma/pnqce/ERMTETHaUrKgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAADW19+TQ5p/p2bLS4v04Zmt5VjeQeJ4bjnLqsupv+Ka1+ERLv4reTmcNxcuC
|
|
vy3l0qdI2hlr66sT02ot0ZV7qqrInruzrVZLGSZ37JjqgYTG0K5lbaFVhDT1Ub456RPweY4hixWi
|
|
eSdpjvD1eWejz3FNHWYtkpvFo9EIseb3tS3SerOms22rfpPqZKzvvHSYUz70TExG6Gdbs2rljeJ/
|
|
Mx5L0vEzPaelnOi98c9J2bFNTFpit47+a+PVUvx9T9nOIfT+GV5p3yY/ds67wvsXqpxau+G09Lx+
|
|
r3TqrEAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADV4ljnLw3U0jvO
|
|
O0fs2lWqyUw6XLkyfYrWZkHldBEV09eveG3Fq1mI3jd4vPrOIaid8G9MP3Y38k6fNrt/rMk9Ou8s
|
|
tfXXn49rGWInuy8SO/k5Gl1E3rG/fzbOe94wTy99mbRvTrMOOvNfJWsesywniukrG/jU6fF43WYN
|
|
TmtEeJtEQ06aSmK2+bNtEd+qfSO17unF9Hmvy1y13XWyVmN4tExLxVK8PmNq5NrT58zawam+m/yc
|
|
0Xj8NpRYSvQZ7xEOdqI3rPozxayNRXe0ct/ON03jmrKB5nV4q1yTO20Obmv4c+cx8HoeI6WZpNoj
|
|
q83niYmYscU0r8aJ6T1n49zeJ+Meqm1drb9J+Kd5p136StGVem9l9TbHxLDFp7W7+sS+q1nesT6w
|
|
+PcAzVjiGHftzQ+v4f8AJpv6On8jH9ZgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAABp8VrW/C9TW0ztOO3b5Nxp8VmI4bn37TWYB8f1HFtTfUfR9FWJmsdZ9I7MtJxDX5s
|
|
d8ta1y0xzteaR2277rcuhycP12SceLxMeWNpjttHwlu8I0mfQ1y+D7k5YmJmY36T36Ka43z/AF1t
|
|
cI1ds+qxVj7/AEej19PCw9HJ4NoK4OIU5Y35YmZdzVTGebVZabx5jJS+Tmns81rNLm1Wrzc9rVw4
|
|
Yibbem72mXTTS0w0M3BvEta1bWrM95ie5EanY87wXgNOL6XPfxraXLhra/W28bR/dzYzarBqJxRe
|
|
bzE7Rt5vWU9n8mPHOGmS0Ypnea1naJb+k9ncNLR7u2y/WcxXO4TOoyUrN6zD0FaW5Y3hu49FiwUi
|
|
KxCvLMR0hlW0jn6ukWw3iXjOJzbDlneOj3GaN6zDzfFOH+LE7SRGo83XNSZ2lbG2/WfdlvaT2cy6
|
|
rNFInlrv1mfJ37cK4PwTTxOoidRm2+/2/KFuyMp47XB4LivXiunrH2b2iH2qn2K/J8x4fGDNxTSZ
|
|
9Nh8OviRvTyfT6xtWI+DeXs9MNZubypASqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAOZx6/LoOWPvWiHTcf2hiZ0e8fc2mf1E5+vP/AEeuSd7RC2uKtI6QjHfeINTfwtPf
|
|
Jvty9WPfbt/lucP03gxfJf7d/wBoReYpm97zaNeLb4Ims9Nt94auDjem1Wo5PFi1onylS+1o7l8V
|
|
bxvtupjDMdNkYtXS1+Stt+m63xImEJ4xjHER2ZxMUjeUTO3VRmydBbjLJqPi08mbeVOXJPq1sl5Q
|
|
Vbkz9+rRy35rxHqzmZlVEe/Ez5LRlW5iyfR6zffaIjq1OSNZps2a21rZInafSPJhxGMl9LStLRWM
|
|
lorM/A4dkrWbYfLZC2W/7K6eubX6b4RzT+W76K8b7G6X62cu3Sten59nsm3j+OXz3/0ANGIAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0OIYfpOHPijvNNo+fdvtXJO18k/
|
|
/OwPFYbz2ls3jx8VqW6xMdWPEdP9D4lkx/dt79flLLHbkxTPwY6nt2512ORTRzE2x4/dpE7cvkme
|
|
E4IrW3hRMxO8THRtU1FKWtvtvK2upx22rzRCtXkqzh2jtF7ZbT122b01ndnpuWuP3Z3+Ky20qDVv
|
|
fauzVy3mejZzNK8dVjqi87KLRLYtXruqvXzkQp7Qoid88R6rcl+WGlW0/Sa22mfhCZOq2x082ix6
|
|
jkm822pO8VrPdr4dNObVeDo8XW3uzMbzK+mvxT7szE27cvnu9j7PcNjSaXx8mOIzZevbrEeic5tN
|
|
+SZnpt8J4fHD9HXHO3PPW0x/DeBtJxx29vaAJQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAKNRim9Z5e89Nl4DzXtVh5babURHrSf7f3ec1+qnDorWrvvt5Pccb0n0zhmWk
|
|
Rvevv1+cPE2rGTFNZU26PFfxwa5dVkjelI2772nZnX6bbrEUq3o0d678u8wmuDL2ittvVjXdneeK
|
|
cGv4jpJ6U56+kS7+j118+GLXpakzHaWlp9NNY3tv+bbiYiNoQy1y30uyZJlrWmZnuym6q1iIJnop
|
|
yW2Te8bdWnnypQqzZOadokiIpSZntWN5lrxki19vNRxrUeBwnNNd+fJEY6/OejXLn3Xe/wDp9wyn
|
|
E8uo4lqqxblv7lJ26T6vpD5X7G8QycKzeBMbzMRM1/FH/wA/h9QwZ6ajDXLitvWzRgsAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAeL45w+dDrZvWv1OWd4+E+j2jX
|
|
12jx67TWw5Y6T2nzifU+rZ1y9eHwzDYxxEy18+DJodXfT5o96vafWPVbjyxDn1OOzHudbM0rt2UW
|
|
iI69mVtRXZq5tREb9VUoy2iIlRbJ0UX1VZ6btTLrI7V6yk62M2oisT1c7JmtkttVMUyZp6x0beDS
|
|
RWOvdKijDimvWd3G9pNRMfRcNfvZOb9Hpb0itJeP47k/3hgjaZnbaP1XxWW3T0movbNS0W645nbf
|
|
0nrMPpXs3xamoxdJiLbe/X1n8Uf3fKsOTw4jbaXo+EarJhtGTHMxeJ6xH7Sti9Zaj6x3HM4NxXFx
|
|
DS1mtoi8dJrv2l011QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AGjxLhODieOIye7kr9m8d4eM4to9RwjPXFa0ZIvG9bR0fQXmPbDFvTTZPOJmEWS/V8bs9R43NxLL
|
|
G8eFbePg1bajU5/s0l1ceKLx1hbjwRE9mOpx0y2uRTSZsm3PMw2aaKtIjo6kYo9EXpET0hVLXxYK
|
|
xC6MZvyx1lFs0RHfaPiCnU12pLyHGNDbUajBekWma2npWN3p8+opa20e9LSyZLxExTlpM+vdOdcZ
|
|
a9tPS8MyUvFrzWlI6727u1pYxYrbVmb7x+TQx6au3Nqcl7/0rcmW9axGnwZJj1novmxnZXV0fFp4
|
|
ZxLBPgTGK8xzXr5fOH0bFlpmxVyY7Rato3iYfNuG2x56Wrqa8s2jz+7Lu8O12bS6jkwzN6THNNI6
|
|
tvrN68Y4rxlx1vHa0bskAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAA4XtTTm0OKfTJ/aXdcL2pyRGjwU362yb7fkJz9eTxxyZJjyltRXzUZK7TFtl9Lbwy06YzrHwa+
|
|
fJFd/wCVt8m0bQ0eS2qzcm+1K/an+zNZFL5M1pjFXeI72ky48eGnPkvNp27+TPU6nHpMfLXaIjpE
|
|
erk5dRMxOfN1mPeisfshW1ne1a1577Y6x5R3U0zze31FOWI6ze0byU098kRlzbxM9qrMlPDpyRMR
|
|
Md5Vt/Ihp5898mWZm1pjftE91uCt7fCI7dWeHDEW3t723l6rslqxWZnasR+SYhFbzhnfxJ2jyeq9
|
|
lcGXWZcmW0zWKxHLaI7794eJx5fpfEKabT8t8l5isddo3l9S4VjrwrRUwzSJt3tav3pdOL6Y6dXD
|
|
j8HFWm+/KsU4NRXPvtWazHquWVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAa+fXYNP9u8b+kdZBsDkZOO135cWOZn4y5Wu4xqctbe9y19Kp4njt6vi+PDm8DFMWybbzPlV
|
|
5PiGtz67UxbNbeKTtWIjaIXYpnwuaftT5tXJT3vmi1pMsrU5qIrG1V1a+5DCa7b9GFbRr5J6Wnbt
|
|
Cu+Wmk0m8956z8ZWZNorbfzcbX5rZslazPux3hUt41NTntktObJ13+zX1bek01r4/HzVm0bxPXy/
|
|
+bNfDgjVa2uOY92kdfg6ufJOKvLXtttVVSqbcta2vM7zXtHpLQy5ZtMd+vWd+7Zy3mdJHXra3f0c
|
|
vUarw7zFY5rT2hH1Lavnrgx81p3U49Pk4nE5L35MO/StfNRXR5tXnrS8W67WvfyiPSPi7uLHFK1p
|
|
jrtSsbR5Lc4RzsXBaYreP4l45esRD2HD9fnw6evvWvO3Tfr0aGk0U55ra0TFInv6uzgrXFXlx0i0
|
|
77RPlC83Yj+JW7oddqr6vHzTTw9/f6dod+L1t9m0T8pcbFSmPHER3892W0zPuz+jSbVvidkcqmfP
|
|
Sel7bekrI4n4dZnPWIrHeYnZee2Wpy8dEaml4npNZblw5qzb8M9JbYgAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAABEzFYmZnaI7yCXL1XGa0jJXT0571nbee27DiXEprp8nhbxG20W8
|
|
5cbD0ikfnKO+urTPvjoZdXqctdsmTaPSvRpWmsdZ6yztfaGplvv3lWW1tyRlz1x0vkn7Vo5atTNe
|
|
Y0+1o79V2KsZsvX7Ne5mwxnyTNvsx2iGneM/rCdRSuOsTasTt5kRFtpjqmOH4t4nk7estiMNa97R
|
|
Hwhna0iuKTEdmGWa4672nZtRele1N59Zlq6vLOSsYorEc07qcW65euzRvtXvPZy52naZ7ujr6fXV
|
|
rWdukREK8+njHgmZmPc67bq6ivVWhxxgxZLztNrT1mZ/SP4VZs0zaOvfp84WUtNsXLvtv3699+rU
|
|
z7+Jtt5qURqMnPpctaR1rMSw4ZoK57eNk6xHaJRh97Ltt7lo5Z+L1HAPZvVauZ2nFTSzMTzeJEz8
|
|
to6xPfvsZntPZ9rXxabmxzefdrv0j1dXh/BcmstW1qxTHHasR3+b0GPhGl+kWmd64dNEVjf73T7X
|
|
y8vy+Ddx6O3iRakxTH5RXrMw1/lX+3Itw2MFIraN48qRHdZi0cUjmmPen9noox1iO0fNzdXEYrTt
|
|
stcmd9aX0bJ+HePmiKTitO8TMLZ1cVjrMfqpz6ys4pjfrPRWZ9rXXptUit6zO+23VyaRHEc05L1/
|
|
w9J9ys/en1ljqdVbwYw452tlnl3jyjzbmmiMeKtYjpEbLeTXPUU8ee/+qjJpsV5rbkrFqzE1tEbT
|
|
DpYNbW21Mnu29fKWna0KbqTdjXXjld0cvQ63ltGHNPSfs2n+HUbS9c2s2UASqAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAOVxPWe99HpP8ArmP4b+r1EabT3yT3iOkesvMVtN7za07zad5l
|
|
XV5GmM9vVfEstvDx0jtaVVMlq+UJ18b5cMRvPeSuK87bUt+i2Z3PtG7zXpjkzXt6R+TXyTMzvM7t
|
|
ydHqZ+zhv1+Cv/ZuqvPTHMfOYaTMil1a1K2vHSLTELq2v+KWzThGo84rH5rq8JzedqR+ZeI7WnOS
|
|
34pYTafWXR/2Pln/AMyrKOCWnvmiPyR6O1y9585lhWJvl557Q6eo4T4dYiMvW3b3UanhldHpJtGX
|
|
e09unmjsT7eb1l4trI2t0hsZfrdNO0bzy+nzU20/+NmkzO9esz+TZxWis9dttvPv+Tn21jjaW8zn
|
|
26bTG3mp1M/Wzv3t0jyWXiKZJmsTERaZhXXDbNl8WaztWenxZLstPp5pau8frDtVrNMM5cfTfpMf
|
|
3aunxxbes9d/R09Dp8ebJi09ptFr3jtt2WyrW9wy1Jx132mK+Xq9PotT0iIU19ntLtExa3T47T+q
|
|
6nBaYvsZstZ+cT/LeMnUi0TXffo1s2m8Ws2/OIMWk5Jib5L328rS2t94Sh5TV4ppklpW6PT6rh+P
|
|
NbebTHyas8E081mZy5P2W6OFhjxNTE/hr/LoRO0Kvo9dPqctKzMxEx1la5t3tdnjnMs4noievcrO
|
|
yZjeFF1OSnNV0OG62cn1GWffj7Mz5w05joovzY7xes7TE7w0xrjPeex6Ua+j1UarBFu1o6Wj0lsN
|
|
3JfQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACrU5o0+nvlt92P3BxuM6nxNRGCs+7Tv8
|
|
2hToxm1r3m9utrTvMsonqyt7XTmcja0u3O6FMfi5t/u0/lzdJM81p9O3zdvHTwsUR5+bfPqOfX1h
|
|
dqV+3O7bs1+T31oqmI3TEM4rvCdkDGIIhlFd2daboS0NXG2bD6bufxXU1vlmu/u4us/N0+L1tTSx
|
|
kr9qk7w89j1FNZMV3jxLzvaJ8mer+LSOZqK2xZotbvljfr/89U453rXt9lse081xZtNjx7TGKu0t
|
|
DHlrevSevaN5Y6+tJ8c7VRNMt63n3ub+6/R54rERMztDYy4a5omclYmfxKcenrjtHLvtPrCnVmdb
|
|
eFe3JXmjy6eS/DrMuLVYsta9Mdt++6qLxO+0dEc8UmInr18iUfReHcXrqccb9Z27Q61Lb13eJ9nc
|
|
1Z35rTvE9avY4bTkpG8xEfB05vYxqybc07R281naGMREdoT5JQqy9mply7Q3bV3iXG1eXw7TWSka
|
|
c258t7+tpT5/BjT7MfHqndz12Z+M4lMMKyziUJJiN1WSu9fku23RaOgKNJqbaTU1t9yelo+D0cTE
|
|
xEx1iXmM1Nt3W4PqvFweDaffx9vjDbGvxz+TP66QDRiAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAOJxzU73rp6z296zsZMkYsdr2naKxvLyObNOfNfJbvad1dXkaeOdpvsc2yuZVzfbfqybutwu
|
|
s5s8R92J3dvJb3tnO4HSMegtmt3nfZvYp8SZl0z45NfSK7onH1bNcfRFqnUKJr0Y7dVtq7prjEsK
|
|
0XVpEM6028mW20IHK41aPo3J6zs4ODhdcvPnvExFevNXpMOrxi/PlrTee7PLX6Pwa09uaNlKtHg9
|
|
dM3z5d7ReOu02nu0JzZMfblrv5R5uvrcdImZ26T1mYhxs1Os7RH93PZ7axuafNfLitvbaYU3yZYt
|
|
PXs9NwHhui1HBa5LVicsb81onrEuVqNNSuS8Y67dZ6xPZa59Il9uX41vEitImZme3q2Kxbxora0T
|
|
Md/ROSa4Ztkj7c9OafL5LuGYubmyX3iu/TfbdSfVnpvZLT/XZK233+Mbbva1xRXyiPk8pwbH4N6T
|
|
adq5a71n0tD1WDL4tPe6Xr0tDpz8YVnJHWEXYxbqlBedoef4tW0XraO09HdyztSZcbUz43C+ee9b
|
|
SVMaeOfqq7+jGckQ1Yz7+7v2RN/WXPXZPjci2+2yyJaVMuy+uSJlA2d+pNoVRbeDcSxyTE+TDDlt
|
|
pdRXLTynrHrDOyiyZeVFnY9TjvXJjres71tG8MnJ4Nqt4tp7T1jrV1nRL1x2cvABKAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAHJ49qfD09cNZ97JPX5PPw2uI6j6Vrsl/ux7tfk1mWr7dOM8iLdm
|
|
vfebREefRsWldw7SxqNbWbR7lPesrn3Vteo7dYjDpMGCvfbeXQ0uLlxRLRxROfUc34p6fCHYrXlr
|
|
EejqrjY8uzCYW7MZjdVKqK9VlaxCYrsnYExBMRMJRPZA8/xPHtmpP9W2xx76vhWOInvt/C7ike7N
|
|
vwzE9kcapGfhlevTaFbFo8RqJ5vy8/RoW09ek0msxHfp3dzNoLzp4zUmZpMbT8HJyYJi20X2n0lh
|
|
ZY1li/RaidBF4w2mK3jrHaFGp1lN+tptPp5IjBkid5mIp16TKu0abBPv33vPlM7z+iPdFNcWXU5I
|
|
tkrNce/b1W5db1nTaf3ax9q0fxDW1ebNk2phty1mOu09VOm8W19orEz23j1TwfSeERFuEYMddptW
|
|
d43dvBn21eKJ75KbW+cf/JcTgMxXTb3nbljz+TpcPmc2uyZO1KRtVtGVdi0bx07qJnllsRO6rNTe
|
|
N4XVamsy8mnvPwc3R2jPwe8TPbdlxXNOPSZfhWWpwO85OFzv57qrODkzeHntSe8Sn6Rv0a3EZ218
|
|
8nXekfr1a0ZLVnqx19dWb6demXybOO7lYMvNMdW9S/VVLo0us7tPHdtUtEwJiZU3jq2Jhham8CVG
|
|
PNODNTJXvWd3qcWSubFXJWd4tG8PK3pPd1OB6veLaa89Y61/u2xfxh5c/rsgNHOAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAANLimq+i6O0xPv392rdeZ4rq/pOqnlnelOkIt5F8Z7Wj27I2I6sb25YY
|
|
V1ImY3dbQ08LRc23vZp2j5OJG+XJWle9p2h6HHtbJXFT7OOIpX+7TxT31j5rycdTh+Dpz+XaG/sw
|
|
w18PHWseULN2trBE9UcrJKBhFU7JAQi0dEomegNDUYovM7x3jb5tO1ZvpbaTLtzRExWfWPJ08kbT
|
|
Ex5NXWYYyV5omYtHWJieyeDzuizfRs19Jn6TM7Ru1uMcJxZqTkw+5f4ebqa7SV1MR4tdrx2vEfy1
|
|
axqsNOTLjnLXytVXi3Xj8+nmsxTLM16d5npPyUzpekTtSK+U7vS6vQ/SYmK1vWPS1HOn2dvvvvE/
|
|
tDO5XlcO+LbfHSd/W3o6/BdDOXPTnj3Kz38rS6Wm4FNrRyRzTH3p6RH/AKvR8L4dXSzE3jmtHn5I
|
|
mbfqLV+m4dbLSsZInHjr3iI6zLpYaxS01rHuxHRHiT9mv6s67Vj1aqL6326MrWiYa+/Q54BxPaGe
|
|
XRZpj8MquB4+Xg8zPnB7SX30to379GxpK1xcHiKz5IS8xr8PLPixH2bftLTy05o6dHYyVjLhy0t1
|
|
izjZa3pMVv3iO/qz1G2L+NbSajbNyW7xLsY8kTDz+fJXFqKZN4iZnafi6WHL0iYlStI7OO+7axW2
|
|
crFl7dW9jvE9ULN+J3ZbdFGOy+AYWpEqN7afNXLj+1Wd23KrJVMvCzseh0+auow1yU7WhY4fCdV4
|
|
OadPefcvPuz6S7jol649Tl4AJVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAV581NPhtkvO0R+4NPi2
|
|
r8DB4dJ9+/7Q83Po2NTqLanNbLfvPaPSFDHV66sZ5ET0hRknyW2lTtMyouz0c8usx2n7s7vScKwx
|
|
zc1vu/y85p+maJh6Th+SOWeveXR4/wDLm8v+nX5mUWa9bbrInolmu5jdTNkxYFk2Isr3TuCzeGMz
|
|
+THdEyDDJO9Ja823rt2XWnya946pGvktDXta0ztWu/ybvLE9dkcoOf4GbJPWK1j49VmLh9JtE33v
|
|
Mevb9G7WsW8l1ccREISophiJ2jpDYpijbaOjOuOJ8ujOdqxsgVcsUjaETYvbaFFrgu5lVsm0yUtu
|
|
ryg43H5m+GIj1XcJzePoL4pnrWGtxmfchr8JvfHS1622if3QljzTTLes+qrNjrkiYtCzPMxnm095
|
|
YZJ6boS5teB49Tqscza97VtvWvlv8V/FOF34RrIxTM2xXjelp/eHoeA6XnzReY3ivX/0dfivDcfE
|
|
9HbDbaLx1pb0lOs+jO7K8Lis3cN+0NKcd9PmthzV5clJ2mF9J9GHHVL108dm1SznYr/Ft0tuhLb8
|
|
mNohFbMhLWy0mJ3rPXvDvcO1karBG8/WV6Wj+7kWrvDDBlvpdRGSnbzj1hpjX4z8mOx6UYYstc2O
|
|
uSk71tG7Ns5AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACZ2jeXneJ62dVl5KT9VTt8Z9W9xbWclPo+O
|
|
fft9qfSHEU1pv48ftYST23ZTDC/p0YtlVuvVjMbM5+LCZjYGWGdrTPxiHY4ffaf3cjTxz1v6xMS6
|
|
Olty2iXVj/Dk8n+ndrkhnGRo1v8AFdW3RCrZ5uiYsqrboncSu508yjmZRYQt50TfowYTbYGVrKrT
|
|
uTZjvukQnYhMIGVY2ZxPVWyrHVCWzXpVXkt3TE7Va+W4K7X3jv1auTNy3jdba0RZpamfroQN7Hk3
|
|
6wr1GTaN2OOJiu6Mu98NvgDi8Wy74d/yZ8PiPAiO2zU4nb6qIn1bugjfFE/ASp1ke9u15mbbRDZ1
|
|
Mb823kx0Ontn1OOkedoJCvT8I03gaKsz9q/WW+isRWsVjtHRKyrhe0XCfpWL6Vgr9fjjrEfeh5fF
|
|
feH0V5Dj3DPoOo+k4a/U5J6xH3ZZ7z3228evytOk7NvFbo0cdols47bSybt7HbddHVqUs2aW3Qnq
|
|
xVeu8LILR3SlZw3V/R8nhXn6u0/pLuPMXjeHT4Zruf6jLPvR9mZ8/g1xrvpz+TH7HUAaMAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAABRq9VXSYJyW79qx6yvmdo3l5viGs+maqYrO+OnSvx+KLeLZz2te1rZL2v
|
|
ed7WneZYWnZl5K72YV1xEyxmeqJljzIEWlVkszvbZp5soN3h2SJz3pP3odCnuWmPRxuERfJrZmtZ
|
|
mtY96fR28kbX3dXj/wAuTyf6bmK+9YX1s0cNtm3Sd4LFY2K23W1s16StiUJW7bp22RW3RluBuruz
|
|
mWEgrmCGWyNkoExKE1QlPmsqRDKeyBjaejWy2W3ttDUyz1QKslvehVqKTNosyyTvELabXptIJpaP
|
|
B39Ia2mz+JGpr51jdZefDx2hzuHZObNq58poJaGtjxJ2+LoaKP8ADRPo5+T3skx5OhpOmC0fBNQ0
|
|
5yTbn+bt8A0u9raiY6RHLVwY62mI6zMvaaHBGn0mPHt1iN5+aYVsACBXqMFNTgviyxvW0bSsAeE1
|
|
mkvw7V2w5Ote9besJx2er4rw2nEdNNekZa9aW9JeQjnxZLYskTW9Z2mJY7zz26fHrrdpbZsY7NGt
|
|
mxjvso1b9NmUwpx33XRO4K7VUTE1nmrvEx1bVo2VWiJE/XY4frY1WPlt0y17x6/FuPM0m+HJGTHO
|
|
1qu9pNVXVYt46Xj7VfRtnXXL5MfzexsALsgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHM4jxOMFJphmJv529Dq
|
|
ZLfjDjPEIx450+K3v2+1MeUOHSOWFc3nJkmZnf4yujpVlqunOeFpV2nctLCZUXRM7MJtsWlRkv3Q
|
|
ky5NmpWt9RnrixVm17TtEQnJabXisRMzPSIew9n+CRoccajURvqLx5/chfOest642OGcIpoOG2w7
|
|
ROW9d72+LQvXevyejcPUU5M+SvpLeOataraw2a0dLbLqTtK1G3Es4lVWWUSoldFtmcXUbpidgXzK
|
|
GEW3TuCUSncnsDFMMLSms9EC6J6FpVzbZE5ALy0809ZbFr9GtfrEoFMzuuwz0Ueey3HbaBLDXe7i
|
|
tMOfwWnP9I+NZbuttvhs1uBRtXPb4SDm3iIvf57N7Dbl0VrS5+XrltEd+Z1Jx7cNms9N4TURRw3T
|
|
+PrcO3WszEvZOD7P6aYiMlvu16S7y1QAIAABxOPcLnUY/pWCv1tI96I+9DtgmXl68Biy7/NtUu3+
|
|
O8HnFa2s0tfd75KR5fFyMWTdhrPHVnX9R0cd21S3Rzsdm1iuqs256wrmGcT0RYSx5d047X02SMmO
|
|
esd49YRE9WcdSXhZ2O1p89NRji9J+cei1xMc3wXi+KZj1j1dTTaqmor06WjvWW+ddcu8XK8BZmAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAMMmWmKu952UZ9XFZmuP3revlDTtzWnmvO8q3XGmfHb9ZanV3yxtWeWn7y4es
|
|
vPNtDqZJ6Ts5mppvdl/XXRMyfGvSNlu/RVvtOzLfoipLT1VTKbSpvfogRkvtDVyZOhkyvQcA4Dzz
|
|
XV6yvTvTHMfvK+c9U3rkW+zvA/D21urr789cdZ8vi9KDb45rejl8Rry6iJ/FV1HP4vXbBTJEfYt1
|
|
+UpiHM295bXsqrO9l8QkZ0lZEqqLeyBZHZLGvZkhIndADKJ3TMoqWQMZ6pjsxll2jsCLSrmU2lFY
|
|
36gieyu0LJk3jbsga0wdqzK20QpyztQGprL/AFMrOE05NLkt6qdVWZxNrSe5o9vWBLiUjnzXn0vL
|
|
q555dHt8HOwV928/1z/LpzXxbYccRvzTB+jucOwxh0dI22mY3ltIrHLWIjyjZKyoAAAAACJiJjaY
|
|
3iXleM8InR5J1GniZw2n3oj7s/8Ao9Wi9a3rNbRE1mNpifNFnVs65XhcWTdt47bnFuF24dm8TFEz
|
|
p7T0/pn0a+HJux1OOrOux08d1ndqY7tillVkzExLOk7yd4YxGwluViJhE45raL0na0dtlWO0+bZr
|
|
1TKi+2zptZGTamT3b/tLacvJjiY3XaTWdYxZZ6/dtPm1zrv1z78fPcbwC7EAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABhkyV
|
|
xUm152iAZWtFazNp2iGhm1Vss8uP3aevnKrNntqLdelI7VRHRnrX/HRjx/tZREVjZXeybW6KbWZt
|
|
pCZ6S08tN7Nmbb7zCrJtyoS5145bSx5mWafelr3tsKmS/o08uXyhlly7RPV2+AcBnPNdZrK+53pS
|
|
fP4ytnPVda4y4BwHxOXV6uvu96Unz+MvVxG0bQRG0bR2G0nHLb2gCUDX12LxtFmpHeazt82wT1gH
|
|
mMN4tWs+rcr2aEV8DU5sM/cvO3yb+O0csLUTSdrLphRE8tlkZI7Atr2ZMazDJVKTYSCawi7Ksq7z
|
|
1QERvLK3ZGPrKbyCrbdnMcsbeaa18/RhvvM7oGEwTG0JmYYTIML22a2e28xELM19oURPNO4lOem+
|
|
n3ZY5+prVnMc2GYU4/L4A0a15cNf6rz/AC6fC6+NxCPOuOu/5tHJTbHj+F5/l1+BYumXJMd9o3/d
|
|
MRXYASgAAAAAAABhlxUz4rY8lYtS0bTEvH8R4ffhmo6bzhtPu29Pg9mq1Gnx6rDbFmrzVsizq2df
|
|
zXkMWTeIbNL7tbXaHLwzUctvexWn3bmPL8WFnHVL326VZ91MfFVjvvVlz79kLrcf2m7j7bNHH3bl
|
|
J2SirLQoy4t1++7G0dBC/RanxI8PJPv18/WG241+alovSdrV6w6mDNGfFF4/OPSW2b1zeTPL1aAs
|
|
zAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAVZ9RXBTe3WZ7R6iZOpzZq4ac1p+UermZMl89+a/byj0Ra9815ted59PQ32hlrXXRjH
|
|
DpCLX6ML5NlNsm/ZRqstfdXzbsZt06sLZNvNB1Za8RDWyZdo7q8udq5Mu/mIMt4md2lmy7JzZuWJ
|
|
dHgfBL8RvGo1MTXTxPSPx/8AstJ1XWpIs4BwSdbeNVqq/URPu0n73/s9hEREbRG0QUpWlYrWIisR
|
|
tER5JbSccur2gCUAAAAPM8Sry8Uyz67fwuxbzVPGsE49XGbvF42V4M0TEL33ERnktsxpk3sumK2j
|
|
admFdPFZ33VS2Mdui2J3UU6LYlFSsN2O5NkCyJ6K7T1TEsbAsxdpReerKkTFGMxvYEz0rsqtbbpC
|
|
b2VT1QEzuwtbaGUxspuJU3neWdKoiu8rq12gCI92YatLcublnzbEz1aOptyZqTuDHLfxN6R0+t5X
|
|
qdJhjBp6UiPLeXl9NSMnEKxHa1+bb8nrlvxUAAAAAAAAAAABTqtNj1eC2LLXeto/R43VabJw/VTh
|
|
ydY+7b1h7ho8V4dXiGlmvbJXrS3xRZ1fGv5rzeHN02bEW3cys3xZJx5ImtqztMS3MeTeGFjqlb2O
|
|
8btql3NpbZtYsnSBLeiWfdTjtutid+ghherHS5p0+f3vsX6T8Fkw181d4lMvEWdnHaGnw/UeNh5L
|
|
T7+PpPxbjdyWcvAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAo1Oprgr63ntAmTqdRqK4K9etp7Q5d7Wy2m953lNrWyWm953mVd77R0
|
|
Za1104xxlN9lV8qnJl2a9s3xUXX2ybsJyRDWtl3YWydEC+2VRkzeW6q+T4tbJm+KRdfK1cmWZnlr
|
|
vNp7RC/R6HU8SycmCk7ed57Q9ZwvgOn4fEXtHi5/O9o7fJaZ6z1uRyOEezVstq6jiEbV71xevzer
|
|
rWtKxWsRFY6REeSRrJxz22gCUAAAAAANbX6aNVpL0npMRvWfSXlKamsRMVvXm+EvZXjmpaPWHzfL
|
|
oNRjzXicfWJ8phfPxFejx72x7xMzK+sXiNoiXlq+Pi6fWV/VfTNqfLJl/WTg9Pji8R70LqvMV1Gq
|
|
j/zcv6yz+lanzzZP1lWpelTET6S81Gp1P/Gyf90s412rjtnyfqql6asREdWM9+jz9eJ6yP8Az7uh
|
|
odZqMt458tpB1JvEViI3/RhzRt13/R1MNaziiZiJn5K9ZNceKZiIiQcu/WekT+iYrWI3lzdTrs+8
|
|
8uW0fJzcur1Np/zsn6g79phVaIeetqNR/wAXJ/3SwnUaj/i5P+6UD0ldonum161h5mNRqP8Ai5P1
|
|
lNtRqJjacuT9Qd22WN5aGeZyZd/KHJy59RHbLf8AVq31Gp/4uT9ZEvS8Lr/vSs2npzRtL1z53wK+
|
|
oza/HW2XJNd99pmX0Rb8VAAAAAAAAAAAAAAcHj/C5yV+l4I9+v24jzj1cLFk8nu5jeNpeW41wmdL
|
|
knU6ev1Vp96sfdn/ANFdTrXG+eq1q5F2LLtbZoY8m8d11bbSydErsYsm+zZrO/zcnBm226uhiyRK
|
|
EtrvCrJDOJTeu8A1MWX6Lqq5N/dnpb5O5ExMbx2cPNTeJb/DM/iYPDtPvY+nzhri/jDy5/W6AuwA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAa2p1UYo5adbz+xbxMlvqJ1OqjDHLXree0ejmzNrWm953tPmTPWbWneZ7yoy5YhjrXXTjH8s75N
|
|
mtkyxt0VZM2/m175N1V03yTKubMLXVXybeYLLX2VXy7eam+b0bOg4VquJW+rry4/O9uyZOq3UjVm
|
|
9r25axMzPaIdvhns1kzbZddM0p5Y47z8/R2+HcF03Doi1a8+Xzvbv+TotJnjDXkt+K8ODHp8cY8N
|
|
IpSO0RCwF2YAAAAAAAAACvUZYw6fJkntWN3k8dfHz2vLucdz8mkjFE9bz1+UOZosX1UzPm0nqI/W
|
|
MYo9FlcPNklfFGeH/NshLGun+Cz6PtHZtVZWlRLS+jxPkRpIn7rdoupHTdA5s6SI+7H6Mfo+32Y2
|
|
+To3neSIiZ7A0IjPXpXLePlMotGW3272t85datKzHZjbTVnsDj+FG/2Y/RlGP4R+jo20u7H6N1Ql
|
|
o+H8I/REY957R+jpfReiK6eOYHLtj2tttH6KrY/6Y/R2c+kjeJiFVtLG24hxpw7/AHY/RRkw9O37
|
|
O99Hrt1YX0tfOBLjcGp4XF8c+u8fs9c4dcVcGemSI61nd3IneN1orQAAAAAAAAAAAAABFqxes1tE
|
|
TE9JiUgPKcX4RbRXnNgiZwWnrH4XPi28PdXpW9JraImsxtMS8pxXhF9DecuGJtgmf+1TWW2N/la1
|
|
L7N7T5e3Vy6W3hsYcvLbqzbO9jvvCzvDR0+XeO7crO6FmGSvRThy/RtVXJ92elvk2rRvDUzU7pl4
|
|
izsd2J3jeBpcNz+Lg5LT7+Pp+Xk3W7js5eAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADs0NTrN96Yp6edkW8Wzm6+LNTq4pvTHO9vOfRoWtt
|
|
1mes95YWvs1s2fZldddOczLPLn2ju0MmebT3YZc2/mpm3qqllN1drsbZIhr3yzvtHf4AsvlYYseb
|
|
V5Yx4KTe0+UQ6nDvZ3UazbJqd8OKeu33peq0eh0+hxcmnxxWPOfOfm0mP+steT/ji8N9mKY9suum
|
|
L37+HHaPm9DSlaVitKxWsdohI0Y22gAgAAAAAAAAAABXnyRhw3yT92Nwef4xm8bVzET0rPJH5d12
|
|
CvLhho3rN9RWs9Z23n5y6O21YhrVYbdGOCfrrLPJRpv863zVS6FS09SvZj3lVZZRdPSqmnSWdrIE
|
|
ebOkK4ldTsgW1WKqd1oMZhEVZyRAImOjGI6rJ7IiATNd46qL02bHkiaxaoNGY2n4ImPgtyV2n0Vo
|
|
Gvlx7x2beiyTk08RPevSVUxux00+Fn2n7N+n5rRFb4AAAAAAAAAAAAAAACLVres1tETWekxKQHlu
|
|
L8InR2nPp43wz3j8P/s5dLveWrFqzW0bxPeJeV4xwmdFec+CJnDM9Y/CrY1xv8qvTZ+WYdbDk5oh
|
|
5zHk283U0eo3jaZZ2N5XYjrCnLSJhOK+8d1kxvCqzSwZvousrb7k9LfJ3nB1OLeJdLhufx9LEWn3
|
|
6e7LXN9Ofy5/W4AuxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAETaKxMzO0Qi9646Ta07RDmZ9VbPbaOlI7Qi3i+c3TPUaqcu9adKfy0722ZXvFa9
|
|
XO1OrjrESxt66ZJmcjPUanlidmhkzTZVfLN5VWvsC2b7R3U3yqrZZtO1esz2h2+F+zWTUcuXXTNM
|
|
feKR3n5+iZLVbqRzNJo9TxHLyaekz62ntD1fDOA6fQbZL7Zc/wCKY6R8odLBgxabFGPDSKUjyiFj
|
|
SZkYa3aALKAAAAAAAAAAAAAADQ4pl2pTFH3p3n5Q33E12Tn1eSfKscsLZ+orS00eJqbW+Lfnu1tF
|
|
XaJnZsz3WpCfsyp00fWSvmPdVYOmSUDd8kR3InoQosy7JmUX7MdwZ17ro7KKT1XRPRAsrO0rYndr
|
|
79V1ZBaQiJ6JgCSIJASwrO07MpV2nqBlrv1a1o2bf2qtfLXaQUTO0sb05o3jv3ZXhjS20xEphW5h
|
|
yeJjjf7UdJWNKLziyRePsz0lux1SgAQAAAAAAAAAAAAAADG9K5KTS8Rato2mJZAPIcU4ZbQZuekT
|
|
OC3afT4NXFkmlntc2GmoxWx5K71tG0vHa/RX0GpmlutJ61t6wrY2xr8dXS5uesN+tt4ef0eaa223
|
|
2dnHk3juyreM81OaFGiy/RtZET9jJ7s/2bdutd2jqKeic3iNTsd8a2h1H0jTVtP2o6W+bZbOO+gA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABje9cdJt
|
|
adohGTLXFTmvO0fy52bJfU23t0pHaqLeL5xdK9Rnvqb+cUjtCi94xxvK3JetKuHrdZvaa1ljb10y
|
|
cnIs1Wt3naJc++TmVWvMz1YWybfMGdsm3eWek0mo4jm8PT0mfW3lDf4V7P5tdMZdRviwfvZ6/TaX
|
|
DpMMYsFIpWPTzXmf+steT8jn8L4Dp+HxF77Zc/4pjpHydYGjC3oAAAAAAAAAAAAAAAAADG9opS1p
|
|
7RG7zszN6WtPe0zLua+3Joss/wBOzhzG2OsL5+IrY09dsSyYRijbHEMvOChb7KjF0yS2LQ169Mso
|
|
S24noyrPVXWejNVKbTuw3T3REdQWU6LYlVvsyiUDPfqupPRr79VuOQX1lZEqoZxIMksd0gT2VT0l
|
|
bPZVbuCaW8i8bwr32WxbcGnkjaZa9p2ndv5qbw5+aNugLItF6TEtvTX5sMb969HMpfazc0d9stqe
|
|
vVZDdAQAAAAAAAAAAAAAAAADV1+iprtPOO/2u9bektoB4TJTJpNRbHkja1Z6uto8viVht+0HDvpG
|
|
H6Tjj6zHHvbecONw7Ltfkmeqmo6Ma69DXbbZTkr1mGWO3RneOaGbZRoM30fVzSelMnT83aef1FZ7
|
|
x3h1tBqfpGnjmn369LNc3sc3kzy9bQCzIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAa+q1dNNXr7157VhGp1Xh70x+9f9ocy283m1p5rz3mVbrjXHjt91lz
|
|
5c9+fJ1nyjyhdM8lZlOOIiqrUXikd+kMreunnI5XEdX4dZiZcG+XmtNl/F83PeeWWHDOGanieSKY
|
|
q+5H2rz2hMzWd1Iqx1yajJXHhrNrW6REeb1nCPZumn2z62Ivl7xTyr/6uhwzhGn4Zj2xxzZJ+1kn
|
|
vLoNJnjHW7TbbsAszAAAAAAAAAAAAAAAAAAAAaPFrbaSK/itEOXt0rDf4xb/ACa/GZacRvaF58Q2
|
|
IjasQnzPIhCU92tMbZGzHmotG10C6nZkwpPRmipIllEbMIZIE7solgmJBnCyk9VMM6z1BtVllEqK
|
|
z0WRILYlluriWcSDJVbusV27gwInaSWM9ECyZ3hqamnSWxFmOSOaqRx725bNnSZNs9J+OynVY+WZ
|
|
YYr7TE+nVaIr0Ais81Yn1hKAAAAAAAAAAAAAAAAAABExvG09peU4nov9n66L0j6q/WPg9Y1OJaON
|
|
ZpL0+9HWs/EWzeVz9PbmrEtnyc3h9reHy26TWdnSr2YX6657ijLXpLX0+onSamL/AHJ6W+Tbv2aW
|
|
ekTv16JzeI1Ox6KJiYiY7Slz+E6jxdN4dp3vj6fl5Og2clnKACAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACZ2jeQRMxEbzO0Q08uqtkma4ulfO3r8lefUePMxWf
|
|
cjy9WvlzVxV6T1Z61/x0Y8f7Wc7Ur1lqVy+LqOWJ2hp6rXddon5rOF1tfmz5OkT0qzb8dWbxjp1c
|
|
biuuilJ5Z6r+IcQrixzEy8zl1E6rNt1tMztFY81sztU1eRucN4ffi2p5esRM72n0h7rS6XFo8FcO
|
|
CkVpX082nwXh3+z9FWLxHi36328vg6TZyW9ABAAAAAAAAAAAAAAAAAAAAAADj8Unm1tK/hqppHvw
|
|
y1k8/EMk+m0GOPeafiFpCZYwolnXspvHvLa9mF46gmnZmwozRUiUCBKYYsoBLOFbKAX0llEqqyzi
|
|
QXRLOJVRLOOwLIljZMEgrlhKyYYTAK5nZPN0RZjugUanHzVlz6xtLq361c+9eXItPpXX0dubTU+E
|
|
bL2lw2++O1fSW6m/VYAISAAAAAAAAAAAAAAAAAp1GbwcfTreelYEydcuMcRrM/L9nnlsV6wqpi2r
|
|
tv133mfWVkRyRtEdGFva7MzkYZNoamWN4bV4mYa9qztKIujhVppxGI8r1mJegeZpknBqKZY+7L0t
|
|
LRekWrO8TG8Ns/HJ5ZypAWZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAADS12fp4VJ6z9qVuq1HgUiI+3bpDl589cOKZmevqprXPTbx477rDJlrhr1nq4+s182tMRP
|
|
RqaziXiZJrWekNG17ZbxWJ336M5LXRbI3dLTJrs07RMY6fan1dHLrowY+X7MVjt6N3R6Kul0EbWm
|
|
s7bz8Z+LnabQX43r7Y53php/mXj+Dnv0f1JO1x/8ZxbUzj02O15mfLtD13AvZqnDds+pmMmo26el
|
|
XX0Wh0/D8EYtNjilY7+s/NstpOOTW7QBKgAAAAAAAAAAAAAAAAAAAAAADG88tLW9I3BwJtz6nNf1
|
|
vK/DHVqYJ3pzT5y3MPZeojOWMQylEKpTVjZnDCwkqzYQyRRICATCITAJZQxhMAshnEq4ZQC2srKq
|
|
qrIBZCWNZZgwswmFloVyCu0dFcx1WyrtCBhv5NTPHXds2U5o3hIz4ffbPt+KHUcTSW5c9Jme0u2v
|
|
VYAKpAAAAAAAAAAAAAAAAYZctcVOa35R6tLrltN795/YvknNqrfhpPLH92V5isd9mWq6fHjk6rn0
|
|
ZxG8KK5Jm/wbVZiYZtqrmkqL023bkxvCiY3lJHNyRG81mHS4Rn5sNsNp64+3yaWaNrzOzHBl+i6q
|
|
mT7s9J+S+ay8mex6EIneN47SNXKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAImYiJme0JafEs3h6fkidrZOn5eaLeJk7eOdm1Hi2vmtPTry/CHmOJcUvmvOPF1n09Pm
|
|
6HF9ZGm01qxO3R5vSY7XwzmzTy47zzTEd7en5Mfvt2/PURWdo3tvPrPlKymbktFqTtMTvHzbOLDG
|
|
f63JXbFX7FdnoODcDprZpq9TjiMMTvSn4vj8l5fxnrk91saPSa7i2hpOfbTVt5x1m0fLydzR6PDo
|
|
dPGHBXasd585n1lsRERG0dIF5OOe6tAEqgAAAAAAAAAAAAAAAAAAAAAAADX11+TRZrf0y2Gjxe22
|
|
gtH4piP3TPpXKwxtjhuYo9xq442iIblI2pC1RET2ILd9kxCqRjZmwlCSEohIJAQAAJZISDKGUd2M
|
|
MoBnVbVVCyAWVWeSuqyOwIlXZZKue4MJV2WWYT2QKbKL9YlfdRdIo35b7/Hd3KTzUrPrDh27uxpb
|
|
c2mpPwX/ABX9XAKpAAAAAAAAAAAAAACekTIp1eTwtJmv+GkyJn1oafeazbfpMzLR4jq/o8b823zX
|
|
6XNF8ERCvTcNpxLV5LauvPhx9Irv3lhztdtv8TtaWLicXrt03jzjzb2k1nid56ty3s/w+a7Uwzjn
|
|
1raejlarhmbhl/FpbxMO/fzj5p/ixSeXOvTtRfeI280ZI26tfDm3pWe63LaZx7qtGvniJ6tPLvOK
|
|
fOa9WzbJvTbza02jl3n5SSljscK1MajSxWZ96nSW88xw/VfQ9XMT9nfa3yemid43jtLeXsce88qQ
|
|
EqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADia3UTm1l4j7OP3Y/u
|
|
7Vp2rM+kPJW1PhYcmS0+9MzKm/jbwz31weMzbV8UppazPL9q0/BF4rk1GLDSNqxPWPhCnHmnNrtT
|
|
qPKteWPm6U6OdHaZvO+SaRNvhv12Ub/q3FhtrNVj0uKOt56z6R5y9zix1w4qY6RtWsREOJ7L6OKa
|
|
S2rvX6zNM7T6Vh3mmZyOfya7eACzIAAAAAAAAAAAAAAAAAAAAAAAAAAczjVvqMVfW/8AZ03I41bf
|
|
Lp6/OVs/UVrY47NyOzUxd4bUJpEbb3Z7IiOrKIVSjZhMLJYyhKIgmGUQSDESIEbJEgQmCITEAmGU
|
|
IiGUAyhZVhDOoM4Wx2VQtqBKuyyWEgqlhKyyuyBVaGtkbNmvk7A15l1eH2300R6TMORPSXT4ZO+O
|
|
8fFefEX63gEAAAAAAAAAAAAAAAq1WPxdLlp+Kkx+y1Fvsz8gjhaDauGK8sx07y3OE3m1tT6RaP4c
|
|
vU6yMNKUx73zT0ilY3l2eF6a+m0kRl/zbzz3+Ez5M8z26fJruW6wzYq5sV8d43raNpZjRzPPaTmx
|
|
5b6bJ9rHO3zb2WJ8GWPEscY9bgzxH2t62n19GWW0eHOzHU5XbjXZ1x8WTnz2iZ7S2M1IjH2+LX0V
|
|
KTqs8zO9ot0j8nUthi1J3UaOFMTfLFo6xMbS9BwHWTqdHOO8+/hnln5eTjYMFo1WTH5VnePzXcIm
|
|
2k4zlpPSmXy/hfF5eMfJns69OA2cgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAADG/2LfJ874rW845mubliY7bPoto5qzHrDz0+yePNF41OotaJ7RWNtpV1OtfHqZ715fhu
|
|
j8adNpcVfeyzE2/vLuanhOu1nEctIxTTFa/+ZPbZ3eHcF0vDbTfFE2yzG03t32+DokynXl9+leDB
|
|
TTYKYccbUpWIhYCzEAAAAAAAAAAAAAAAAAAAAAAAAAAAAcXjE/4zDH9M/wAu04XF5/3jj/0f3Wz9
|
|
RUYmzDWxS2I7FSyjuzY1ZKpRKEygEwiWUIkGIk2QJNhKQhMIhkCYZQxhlAMoZwwZwgWQshVCyATL
|
|
CWc9ldpBhZXLOVdpQK7NfJPRdaWvknoDVvPvOnwuel4+TlXn3nS4VPvXj4QtEV0wAAAAAAAAAAAA
|
|
AAAAAVV02CmTxK4qRf8AFFeq0AAAanEsfPpZmO9Ji0NDLfkwdOsulrumiyzHlVzJrz4Ovoy26vB8
|
|
cTBa9NffLtMY77Rv8Yegx5ImkKdJoY1HC81Y+3OSbVn0mGGkmbY45u6tnrrTOu2xGO0RxCd+nNVj
|
|
qKxTV1vH2pjaGtnyzXXYdo96ZmGXEMk15b7/AGZiVerWPTYckZcNbx5wzc7hGbnxXxzPWk7x8pdF
|
|
0S9jh1OXgAlUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAcPjEf4/FP9H93ccXjMf4vDP9Mx+62fqKrx+S+GvibEFSsqyYwlVK
|
|
ZYsmIMoRKYJQIPIEiQ2ATCUQygCGUIhMAyhnDCGUIFkLIV1ZxIMpVWWSrsCuyqyyyq09ECq8tfJK
|
|
66jJ2Bp5J6upwn7dv9Lk5J951uE/av8AJaIrqAAAAAAAAAAAAAAAAAAAAAAq1Mc2myxPnWf4cmtu
|
|
XT9fR0tffk0WSe28bfq5Wbamm3326MtunwfK6PCv/AxPraZ/dz9PO97/AOqf5dHhdZrw7Dv3mOb9
|
|
XOxRFM+avpe38mvkPHf/AFWlrKba7Tzt99ZxKkfR7euyNXMTrtPHfa0z+zPiM/UR8Zj+Wbdu8HpN
|
|
M2bfzrV13M4dO2pyR61dNvj44/J/oAWZgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADj8bj63BPzdhyeNx0wz8ZWz9RWri7Nmv
|
|
VrYu0NmqaRZHZlDGGSiwxZSgCEkCBCQSCQBMJRCYgEsoYx3Z17AlMIhlCBnDOGEM4AlhZZKq4KrK
|
|
7LLKrIFN2vdfZReAaObu6/CO9vk5OePR1uEd7fJeIrqAIAAAAAAAAAAAAAAAAAAAAGtxCk5NFliI
|
|
3mI32+XVyNTyZOHTee946PQKPoeDffw4777eW/yVs60xv+ZxOnr4Okx1t05KRv8Ao41Z5q3yed5m
|
|
XY1szXRZ5jvFJ/hxItP0aOSN9q7yrtr4f2tHFM5+KT16Yq/vK/iGSbXw4vO14UcPx5MGfNbPG18m
|
|
1oj4THRsTw7VanPXVYpi3gzMcnrvCnG11JOupwuN8+a3pEQ6jT4divjxWnJExa09pbjbM5HHu90A
|
|
JUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAHM41H1GOf6nTc/jEf4Ws+lls/UX45uGekNujTwdm5RNIthKIZKLDFlsiQIShIC
|
|
EgCUJ7AmGTGO7IDzZQhMSDJMMYZQgZwzhhDOATuqssmVdgVWVWWyqtCBTeVF19lF+wNLNG7q8I+9
|
|
8nLyupwnt+S8RXUAQAAAAAAAAAAAAAAAAAAAAAAItWL1mto3iY2lyrcLyUxzix2ia2nvPeK+jrCL
|
|
OrTVnxpanhuPPemSs8l6RtE7dJj0ldpNP9GwRSZ3neZmV4cR/Vs4AJQAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANHi1d9H
|
|
M+kt5ra+vPoskfDdOfqK4mn7Q3aNHBPZu0W0RdDOGFWcKLCJZeTGQQlCQSgASBsCYZQxhlAJTAmA
|
|
TsmAgGcM4YQyjsgRLC3VnaVcgwsrt3Z2V2QK7tbJ1bN5a9waeWO7p8Knt8nNyebpcK8vkvlFdQBA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAK9RXmwZI+ErEWjesx6wQeZwejeo0cccuW8
|
|
elpblJaaRGxVnCuss4ZrMvJEgCAASISCQIBlCYYpieoM0wx8k7gzIRueYM4Z79FcSy3QEsLJmWFp
|
|
BjaVVpZWlXMoGNmvkXXlr3kGtknu6XCf7OXkl1OEdl8orqgIAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAHmskcmtzV/rls0U62OXiWX4zErcc9GmkRfWVkSqqziWayxCPIANwBIhIJSxS
|
|
CRG6dwZwlhEs4BluMdzfqgZxLLdXuy3AmVdpZTKuZBjaVVpWWV2QlhZRdfZRcGpl7urwfrzfJy8r
|
|
rcH61vPyWitdMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHA4nHLxKZ9awnH2ZcY
|
|
jbW459aq8fZpfiI2IZwrqzhmsz3Ebm4JN0AMhCQSIASndiAziWUSriWcAyRujc80DM3RCfIETLCW
|
|
UsZEsJYSslXZAwlTddPZTkBp5e7r8Gj6rJPxhx8k9Xa4PG2C8/FaK10QAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAcfjcbZMFvnDWx9m5x2PqcNvS+zSxT7sNPxH62YZQwqzhRZO6UCB
|
|
KUAJTux3SDIRuAncQAmJZRLBMSgZ7iIAZRKd2DICUSlAljLCYWMLIFVukNfI2bNbIDTyT7zu8Ijb
|
|
Sz/qcG/2nf4T/wCE/wD2WnxWt4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHL9oL
|
|
+Hw2cm28VvEuPptfgyVj6yIn0no7/FtJfW8NzYMe3PaPd39d3iMug1WktNc2C9dvPbeP1aZ9xF+v
|
|
T471tHu2iflK2HkqWmvaZj5Surqc9Ps5bx+alTHqYHm68S1Vf/NmfnC2vGNTXvyT84Ql6A3cSvHM
|
|
sfaxVn5Ssrxyv3sM/lKB1xza8bwT3pePyWV4tpZ+/MfOEjfGrXiGlt2zV/PotrqcN/s5aT/+wLRj
|
|
FontMSlAlKEgndO6IAZQljDIEgeQljLCzOVdkCu/SGrkbF56NPNeKxMzMRHxENe0+89DwuNtHHzl
|
|
5PJr8NcnLW3Pbf7r1nCZm2gpae8zMrz4i/W6AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAETETG0xukB4HVaeMHEtRi26RedvkyjBSfX9W77QYvC4xz7dMlYlrU7M929dWJLFc6aPK0q
|
|
7YLxPS0S22FlP6q38Zac0yR92s/KVc3tHfFf8tpbcsLRvB/dR/8ALLVnU0r9uL1+dZI1mnmdvGpv
|
|
6TOy6ym+Oto2tWJ+cJ/tW+KLK5KW+zes/KU7tG+h01p64qx8Y6NXNo6Y+uPJlp8rLf0rfG7MXtHa
|
|
0x8pZxqs9e2a8f8A7Oj7HaTHn0+f6RWM23LETfr6vRW4PoL99NT8ui7F4+vEdXXtnt+fVbXjGsr/
|
|
AOZE/OsPS29nuH27YrV+VpeV9pdPXhOtw49NG9Mld55+vXcTPd42I47qo7xSfyWV9oM8d8VJ/VxM
|
|
d8l46xWF9cV7en6o/qLfxp2I9ob+eCv/AHMo9op89P8A/wBORGmyT5R+qfo2X8P7n9Q/jTsx7RR5
|
|
6ef+4/8AuHftg/8A6cWcOSO9J/WEbWr3pY7Efzp2Lcfv5YK/9zWy8d1E/ZpSv5Oba1/+Hb9lc+LP
|
|
bFt87I7E/wAabWbiurvEx4nL/pjZzc2bJkn372t85ZXx55/BX85lucC0vPxnTxlnnjm32mOiZqUu
|
|
LJ2p4TwnVavNWaYbRTfre0bQ99pcH0bT0xb78vmtiIiNojaErMwAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAHnfarF7umzRHaZrLjYrdIen9ocPi8JyTt1xzF4eUw23rCm3R4r6bMy
|
|
wt6kdTaWLdjswmNoZontsCm0K5XWjopnuDC0dGpqG5bs08/daKV672MjbSaif6oh6Z5f2LtvptRX
|
|
0tEvUN3Jfo8f7cYve0eX4zV7B5z20xc/C8eSPuZIRficfXlcPaG7ino08HWIbePpLF2NuiyOyrHK
|
|
3fZFSwuovHVfaVF4QK5YWTM9UT0EKry6Ps1Tn4zjn8NZn9nOtLseydObiWW34cf918fWfk+PYANn
|
|
KAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAq1WKM+ly4p+/WYeBxTNd6zG0xO0
|
|
vobw3FcP0bi2em20Tbmj5Srr418V9sa2Z7qKyzi07MXUylhaU7yjqhLCeiq3ddaFNxFYW7NLNG8t
|
|
zya+WO6Va9J7FW66mvwidnrXiPY3Ny8RyUn71Jj9Ht3RPjk19HK9pMHj8D1ER3rHN+jqqtTjjNps
|
|
uOe16zAifXzfTz7kNyndpYazS9qT0mszDdoxrsi6m8LazMq6zDOsq1ZEyrt1WWlXaUCqyq0rbKbi
|
|
Fdp6PReyFd8uqv8ACsfy83aXrPZHHto89/xX2/SP/dpj6y8vx6EBq5gAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAB5n2q03LfDqqx39y39npmlxbS/TOG5se29tuavzgWzeV4mtui2
|
|
O3RRSY2hdVhqO2MvI36iu9lUsrSrvDHn6spnmSiq5jooyV6tq1VV69RC32byTh43h8otMx+r6I+Z
|
|
aK/g8TwX7bXh9Mid4iW+fjl8n1ICWb57xLBOm4zqse20Tbmj8+qKdnS9q8PhcTw5tumSm0/OHMxz
|
|
0Za+uzx3sX1t0Zxurr1ZxvspWiZYWZbsbT0QK7KLrZVZJFaqt5vbezNOTg9J/FaZeJns93wCvLwb
|
|
T/GJn92uGHldIBowAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADuAPA67F9H4l
|
|
qMW20VvO3yRWW97T4fC4rXJHSMtI/WGhVlue3b473K2KzMML4+62tujG9pnozXaOSOVFMnVbmq1t
|
|
trJRW5E7wwvUxTvCyY6CHOt7moxz6Wh9PxTzYaT61h8x1MbZK/OH0zTf+Fxf6I/htj45vL9WgLMn
|
|
mvbPFvocGWO9L7fq85p5maw9d7VYvE4JkmPu2if3eW0+PasdFNOnxfF1Y2hlykRsmY+LJ0MZjZXa
|
|
eq2eyi8oQTO0KLdZWzPRjWu6VaqtHR73g0bcI0sf0Q8Nkq93wqNuFaWP+XDTDDytwBowAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAef9q8HNpcGaI60vtPyl56k9Iew49j8ThGe
|
|
PwxFv0l4zH2U26fDfTYiyJljvsjf4sm6vJ1hrXjq2MkqLdZEVbgbMx0auGdmzNt6iHN1Ub5af6of
|
|
TdPG2nxx6Vj+HzaaTm1+nx/iyVj930ysbViPRrj45vL9SAuyc7j1efguqj+jd4/T33rD3HEcPj8O
|
|
1GP8WOY/Z4TTT7sKadHhbcsZnaCJ3TPZk6VdrKbTutmP0U2nqgrGOsr8deiuI2X09EqKM1dt3uuG
|
|
f/jdN/06/wAPE546S9rwud+Gaaf+XH8NMMPK2wGjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAABrcRp4nDtRWPPHP8PCYusPoWSvNjtX1iYfPuWaXtX8MzCuvjfw32siu8ptXoxi
|
|
0wy5t4YulReqmazu2skbquURWFInddM7VYRGyL291KFnCcfj8e0le/Lbmn8n0N4b2Ur4nHLWmPsY
|
|
5e5a5+OXyXugBZmiY3iY9Xz7NjnTa3Ph/BeYj5PoTxftFg8Hjk2iOmWkW/Psrr418V5WrWd2faFc
|
|
V2jdnEMXWxntupmN7NiYU27iWML6dVMVnddjgVqMsdHr+CW5uE6f4Rt+7yuSsTDv+zWXn0WTHP3L
|
|
/tK+GHl+O0A1c4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8Dn93W56/wDM
|
|
t/L3z59qp24jn+OS38lnpr4r7ZxHQ2TEstt3PXUrt27K57rr1VT0BjKnJPRbMqMs7QlV2fYvHvrd
|
|
VknyrEfu9m8f7FZI8fVU85iJewbT45NfQBKo817W4eulzxHaZrL0rje09ItwqbfhtBVs3leai8RD
|
|
KLw1sduesL606dWFdsZT1jdhNeq6K9DlhCVUU6s4jZnt1YzAhnM71dH2bycmszY/K1d/0c6OzY4R
|
|
fwuK4p8rTstn6z8k7HrwGzkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHz3
|
|
Vxvr80/8y38voTwGpj/F5/8AqT/JfjTx/WVeyY6FPspc9dZPVXaOq2WEwIUTVRmjo2rNfLHRI3vZ
|
|
DJycXtX8dZh7t879nsnhcbwz23tt+r6I2nxyb+gCVBzuPY/E4PqI9K7ui19fTxNBnp60n+Aj5/pJ
|
|
3jZu1aOnnltMNussdfXbm+l3ZM9URHREdZVXTuT1Nk7boQiOkJw28PU47/htEp5eivJPLMTCZ9Vv
|
|
x7mJ3iJ9UqNHk8XR4b+tIXuhxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD
|
|
weqjbWZ4/wCZP8vePCaz/wDIaiP+Zb+UX408f0r9lOxWOifJhXWjfyYWllPRXYQxnrCrJHRd3YZI
|
|
6A1NJecHEsN/S0T+76bE7xE+r5dk93LW3pL6ZpMni6PDf8VIn9m2fjm8s9rgFmQxvHNS0esbMiew
|
|
PnHLyai9fS0w2aNfUTtrs3+uf5bGPqy068fF227KtSsdFlKqNGMV6myyY6sbdIQI8tlOWOi6Jhhk
|
|
j3RD0vA8nicMx9etZmHRcT2Zyb6XNT8N9/2dt0T449T2AJVAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAHhdfG3E9TH9cvdPEcXjk4zqI/q3L8aeP6xr2TsxpLOekMK6mFo6qpXSrm
|
|
OqBixvHSVmzC4OfqK7S9/wAByeLwbTW9K7fo8Fqo6Paeyl+fglI/Da0NcMPK7QC7AAB8313TiOf/
|
|
AKk/y2MHWrX4jG3E9R/1Lfyv0/aFNOrHxuU7LI7MMayGTVlHWUXhNe6Z6wIUsb9d1m20q7dkDpez
|
|
N9tRqKT5xEvRvKez9+Xis1/FSYerb5+OTyf6AFlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAB43j9eXjN/jWJ/Z7J5L2mry8Upb8VIF8f6aGOey2eynHvOy7bowrrYSxZSwQJ2YXZ
|
|
92N4BoanrEvVexmTm4blr+HJ/aHltRHSXofYm/1Wrp5RaJaYY+X49WA0c4AD51xONuKan/qW/lbp
|
|
+0MOLRtxbU/9SU4J7KadWPjep2WQrr2WRPRk1TvsndXMpiRCb9FNu0rbTuqvKBscCjfi9PhWZeue
|
|
V9n434rafTHL1TfPxy+T/QAszAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHmv
|
|
avHtfTZfnV6VxPajHzcNrf8ABeJFs/XnMcr4no18c+6vr2YadkY2YM57sEDLyY37Mo7MMnYGlqO0
|
|
vQ+xNfqNVb1tEfs87qZ2rL0/sVX/AHdnt65P7Q0wx8vx6UBo5wAHz/jUbcX1PT78qtO2vaCnJxjP
|
|
8Zif2amnnspp04+OjWejKJ6MKdmcMmyJn4m5ZHzEVPMwtJv0VZLbQDqezcb8RzT6Y/7vUPM+ytZt
|
|
n1OTyiIh6Ztn45N/6AFlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABocbxeLw
|
|
nUR5xXm/Rvq8+OMuDJjntaswEeBxT0bNZ6NatZpNqz3rO0rqsdO3PxlaWEMpY+aqWXkryT0ZT2V3
|
|
7A0dVPuy9f7G124NM/iyT/Z4zWT7sw957MYfB4Fp4/FE2/WWmGHldcBowAAeM9qKcvFeb8VIly9P
|
|
0nq7ntbTbVYL+tJj93CwT76unR4/jo0nozhhTsy3Y1sWljM9Ce7HyQIm3RRlttVbaWrnt0Sh6n2U
|
|
x8vD8mSfv3/h3XN4Bi8Lg2nj8Uc36y6TeOPXugCUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAPD8RxeBxXUU26Tbmj8+quro+02Lw+I4ssdslNvzhzazvDPbq8d7GW7Dfqz2VzG
|
|
0s2qd+iu/Zn5Ksk9BVztX1mI8930zh2LwOHabH+HHWP2fNYp4+vwYvxXiP3fUqxtWIjyjZtj45/L
|
|
faQFmQADzftfj3w6fJ6WmHmsP23rvaqnNwqLfhvEvIYZ+sV038bo0noy36MK9oZQxrdMyrlnMbMZ
|
|
QKrS1M07zEestq/RRjr4utwY/wAV4j91p9V18fQdJj8LR4ccfdpEfsuREbREJbuMAAAAAAAAAAAA
|
|
BAJAAAAEAJEAJQAJQAJEAJQAJQAJEACUJAQlAJEAJQAJQJAAAEAJEAJBAAAJAABAJEJAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwvanDzaPFmjvjv8A
|
|
tLztJ3h7HjGHx+FainnFeaPnHV4vFbeIU038VbHeGF+kso7Mb9mTdhKnLK3dRm7SIrHhGPxeP6Sv
|
|
9cT/AHfSnz72Zx+J7Q45/BWZ/Z9BbZ+OXyfQBZQABzeP4/E4NqI9Ii36S8Ng/wAx9C4jTxOH6ivr
|
|
jn+Hz3B/mQi/GvjdCnWNlsdI2V07LIlg6USrt2ZzZXMoFV+zPhGLxeOaavpbm/RVltEN72Yx+Jxm
|
|
b7dKUmf7L5+s9/HtRA2cqRACRACRACRACUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAACQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQCQQCRACRACRCQBCQBCQB
|
|
ACRACRACRACRACL1i9LVntMbPATTwdRkxT3pea/u+gPE8Xx+DxrPHlaYt+qNfGvjvtXXsi0dOrKk
|
|
dEXjZg6VMtbP2bMtXUdpEV0/Y2nNxbNf8OP+727xvsXH+N1U/wBEfy9k3nxyb+gCVQAGOWvNivX1
|
|
rMPnGGOXNNfOJ2fSZ6w+dZKeHxDPX8N7R+6L8a+L63KdoZ7q6zvEMpnowdKJ6ywmWUyqvIKM0vQ+
|
|
x+D6rU55+9aKx+TzWa36vbezmDwODYenW+95/Nphj5L6dQBo5wAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAEiAAAEoA
|
|
AAAAAAAAAAAAAEAkEAkRuAkQbgkQAkQAkQAkQAl5T2nx8nEMOT8dNv0l6pwfarHvpcGWPu32/WCr
|
|
YvK4mOem6b9mGKd4Z3idmFdka0y1c892zfpMtLPaNpEV6D2Kj/Eauf6YeweQ9ieuTVz8K/3evbT4
|
|
5NfQBKoAA8FxCvJxrUx/XMvevD8Zry8fz/Haf2RfjTx/6RSOnRMyypHu9kXjowrqVSrvPRnZVl6V
|
|
kK0775MsUjvadn0nT4ow6bFijtSsVfPuFYvpPGtNTy54mfy6vorXDm8l9pEC7JIgBIgBIgBIgBIg
|
|
BIgBIhIAgBIhIAgBIgBIIBIAAhIAhIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJAAAAAAAAAAAAAAA
|
|
AAAAAAAAABAJQkAEAAAAAAAAAAjc3BIjdG4Mkbo5kcwMjdhzHMDPc3V8xzAs3N1fMjmBZubq+Y5g
|
|
Wbm6vmOYFm5ur5jmBZubq+Y5gWbm6vmOYFm5ur5jmBZubq+Y5gWbm6vmTzAz3N2HMnmBlu5ftFTx
|
|
OEZJ/DMW/d0t2rxKni8N1FPWkiZ9eS08e7Cy8dGGn6UhZaJljXZGnmc3UT3dPP2cnUT78xCIV6j2
|
|
H/8A9c/6f7vXPI+w8bU1U+vL/d63du5NfUiDcVSIAS8b7RV5eOb/AIqRL2TyXtNX/e2KfXH/AHlF
|
|
+NPH/pr4+2xcxx0hFpY11K7R16KM32ZWz3UaidqSgrc9kcPicWyZJjfw6T+727y3sXh2xarN+K0V
|
|
h6lvPjj3e0ASqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJQAAAAAkQAkQAkAAAAAAAAAAAAAAA
|
|
EgAAAAAAAAAAAAAAAAAAAAAgAAABKDcAN0bgkY8xzAyRux5kcwM9zdXNkTcFm6OZXzMeYFvMibKu
|
|
ZHMC2bo51U2RuC2bom6rc3BZzom6sBZzI52ADPnOdggFnMc6skFnMc6rc3BbznOp3RzAv50c6nml
|
|
HMC/nOf4qOY5wX85zqOc5wbHOc7X5znBsc6edr85zg2ec52vzpi4NjmY5bROG+/bllVzsNTk5dLl
|
|
n0pP8BHmMHWNmzt0aum8obm08vVjfrtnxztR0mXHzTvaZdjVRMTLkZo6yiFen9iZ2pqY/wBP93rN
|
|
3kPY+/LfPX1rE/u9XzN3HfqzdO6vmTuIZ7m7Hc3Bnu8t7TR/vHBP9E/y9Pu837SV31umn+if5Rfi
|
|
/j/01MMb1hjkrtKzBG0bMsmOZY11tOYamr6Und0LUc7XT7u3rJPqL8er9lcPhcFpbzyWm39v7O00
|
|
+FYvA4Zpsc94xxu227jv1IAgAAAAAAAAABKAAAASgASgBIgBIgBIgBIhIAAAAAAAAAAAAAAAAAAC
|
|
UACUJAAAAAAAAAAAABIAAAAAAAAAAAAAAAAAAAAg3AEbomQZbo3YzLGbAz3RNlc3YzcFs2YzdVN2
|
|
M2Bdzom6nmNwW86JurTAMuY3REJ2BB1ZRVMVBhsbSsiqeUFXLucq3lTygp5TlXcpygp5TlXcpygp
|
|
5TlXcqOUFXKjlXcrGYBXysdlswiYBVMdUTCyY6sZBWxlnMMZgGLGZZSwkDdHMiWO4MuY5mEyjcFn
|
|
N1OdVzHMC3nTzqeY5gX85zqOZPMC+Lqdbk20eb/RKOZr8QybaK/XvtH7iZ9aGlp2luzT3fg19NHS
|
|
OjbmPcYX67XH1XSZ9XIzRvMuzrK7zLkZYmYnciunb9lZ5dTk+OP+71cXeP8AZnJ/ip2nf3J/l6iL
|
|
/Fu5L9bMWZczXi6YuIbEWTzKIuyiwLt3nuO25uI4a/hx7/rLuczg8TicvFLbfdpEK6+NPH/phhjo
|
|
stLGkctUWnoxrrU3j1cnWTzZq1jzl1clo5Zcu8c+txR63iP3Tn6pv4+g4o5cVI9IiGe7CJ2iE7t3
|
|
GyN2O6dwSINwSISAlAAlACRAAlAAlACRACRCQAAAAAAAAAASgASISAAAAAAAAAAAAACQAAAAAAAA
|
|
AAAAAASAAAAAAAAAAAAAAAAIAAAQCAJljuljsCJlhMs9mOwMJYys5TkBVsjZdyHICrZPKt5E8oK4
|
|
qmKrOVOwMIqyirPY2Bjyp2ZbAI2NmSARsbMgEbI2ZAMdjZICNkbMkSCNmOzJEgx2YyzljMAwlhKy
|
|
WEwCuWErJhhMArlhLOWEgxljMpljIImWMyTKJA3N0IBO5vux3NwZbnMx3NwZczT4jf3MdPW27a3a
|
|
fJOq1XNP2KdIRfi+J2trSYfcjeF+Wm1OicVeWIiN9kai8xjY12ORqultnI1Ecsujq79XP1FovWYI
|
|
rTgeq+j8QrWZ+3Mx+r2UXeC0WG2Ti2kiN5mL807eUREvbzbaejefHJv62Iv8WUXa0WTFhVtRdlF2
|
|
rz9WUXBtc7jR9dqc2T1ttHyhvZMvJitb0jdq6XHNcNenWVN3028U99WRj6Kb02be3Tq18/SN2Lpc
|
|
3UdN9nOmZrqKX/DaJ/d0svvTLRzV3jomK6+Pd1vvWJj0ZczT0mXxNJht60hfFnQ4qu3N1cWTEgs3
|
|
Tur5k7gz3N2O5uDM3Y7m4MtxBuCQASIASIASAAAAAAACRCQAAAAAAAAEoSAAAAAAAAAAAlAAlCQA
|
|
AAAAAAAAAAASAAAAAAAAAAAAIASgAAAEJAQJQCNkbMgGOyOVnsAw5TlZ7GwMOVPKy2NgY7GzIBGx
|
|
skA2AAAAAAAAAAQkBAEghEskAxYzDPZGwK5hjMLJhjMAqmGEwumrCagomFcw2JqqtUFEsLLrV82F
|
|
o7gqljKyYYTGwMZRKUSCAQAboJnaN5Bjkneu0d5W4ccViIiOzHFWbTzNumP1Zarr8eeRMbxDW1Mx
|
|
NO67NbkhzNVnmInqzaOZrL93JyZeV0M1++7S02jvxDWxhxx033tPpC8Z6rrezWjmZyazJG2/u03h
|
|
2vFibTHoqvamiwVwY+nLGzV0+SZ1Mx8G0/45tOhzJ5lXMc3UVXRdlF1HP+iYsDPLPPy49/tz1+Te
|
|
pSIr0ho6ak5Ms5J8o2q6NImOrHV7XX488ypzTtHXo0s9t6zG7c1G1qz6ubeZiZ3UatXJG3yauSO7
|
|
cvMTEx5tPLb3prPRMVr0HB8vicNxf0+7+kt+LOJwTJyY/Bnz3tH93X36N58cWvq6LSyiyndMSlC7
|
|
mZcymLJiwLosmJVRLKLAtiU7q4lMSCzc3YxJuDMRuAlKAEgAAAlAkAAAAAABKAEgAAAAAJAAAAAA
|
|
AAAAAAAEgAAAAAAAAAAAAAkAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAhIAAACAAAASgAAAAAAEAAAA
|
|
hGzJAImGMwzQDDZjNVuyNgUTVhNGxysZqDVmiu1G5NN2M4waM0+DCaN2cbGcQNGaMZq3JxMJxA1J
|
|
qx2bU4kU09slorWNwa20z02RXHbJbl26QvtFovbHWkxEdJt5y2MOHlr2U1W3jx+1hiw8vSO63lmI
|
|
XRTaEWmtY6snRHO1VpmJ+DjavpSZl2s8b7y4HFcnh0n0gha5ebJN55KRM2mdoiPN6fh+kpwXh0Wy
|
|
RHj5Otp/s5Ps1p62y31+em9aTMYt/OfVfxTiPjZ52naI7fBrI5t66xz5+a1rW7yx0eSL6iZjtEOX
|
|
qNbSletom3lENjh2fbHzbbWt3iVozruc+5ztWubf4M4ybpQ2Oboyrva0Vjza8WdDR4OkXt3n9ldX
|
|
kaePP9VtYqctYhdvt5oivTeCZ2YOxXk6ubqMfV0b9mrljfqlFcq88k7z2U5axeItDa1OPessuC8P
|
|
ya7XRWYnwqdbT/ZMilvIu4dpslNdixXja8Y5tt85djZdbDWnGOesRtXFtuw6T27No5Kx2OrKYQlC
|
|
ExKJgBnEpiyvdlEgsizKLKollFgWxLKJVRLKJBbEp3VxLKJBnuMWQJEbpBIAAAJAAAABIAAAAAAA
|
|
lAJAAAAAAAAAAAAAASAAAAAAAAAAAAAJAAAABAJABAlAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAA
|
|
AAABAJQAAAAgAABAAI2EoBGyJhkgGPKxmqxAKpownHC+YRMdN5BrTj67R3bOn01o7p01Iv71u89o
|
|
b9a7LfBTfS1vWI2jf12VfQPSW8KX2mas+NC2iv6xMNfJpMnLtEbuuxtMRCtzF55NR5rPps1N/ctP
|
|
y6uHreE6nXZ4pak48X3rT06fB7fNeI33cbX6mI32R/MWu7XF116aDSRhxbRERs8f499bkyZeeKae
|
|
kzE2mdon81/tfxDLGOunwbzlzbx08oaHBvZHJlx48mrvaa94pu04y617576rNGLRRM0397JEd/lu
|
|
9Dw/S3x4qxffo6mm4NjwUiKY4iI9Ib1dHFY6QIaNabbrYrLfrpJtaK1rMzPZb/s+05IpP59OyLeJ
|
|
k7eNfRaOc1ue32I7fGXYpi5Y77M8OGMeOKxHSFsU3Y29deZMzirl6dlVvhLatCjJHeYQv1rXnps1
|
|
8k9/VsW6qLVmZIi1rzitlvFKRvaZ2h6TSaenC9FFY+3brM+sqeG8Prp4+kZ+lvuxPkr1mqm95nfp
|
|
DXM459676a2q1dsV7XietvNno78+CJn1cjX6mOeIm0bR33dfRU5NJjidt9t5afjG/V6JZ7I2QMNh
|
|
nyo2BhsMuVG3wAhMSbbQRAMolnE+iuGUSCyJZRKuGUSCyJZK4llEgyZMYTuCUsYSCQASISAAAlCQ
|
|
AAAAAAEoASCASAAAAAAAAAAAAlACRACQAAAAAAAAAEgCEoASCAAAAAAAAAAAAAAAAAAAAAAABAAA
|
|
AAAAAAAISAIAAAAAAQAAACASgAAAQJAQAAhIDHZhln3do7z0WS18mWsajHjmes7pg3dNi5aRMNqO
|
|
yvDHTpPRaigHZhN4hHRlaVN59JY3zRENLUavaO+yq0iNVlitJ6vNcR1MVi0zO0era1/Ea0rPvbz5
|
|
PM5MWp45qvo2GZrhmfrsnpHpHzTCseEcM/2vrr8Q1Eb4qzy44nziPN63HpYiIiI7LNHoqabBTFii
|
|
IpSNohuVxrKtWMEejPwY9G1FFmHB4mWJn7MdfnIM9JpIx15to5pbUaas/a6rqViI7MxPxqX0UT1r
|
|
O3wVzpbR2hviP5i03Y5s6a879FNtHljydhExCv8AMTPJXBnRZbz0iG5ptFjwe/l96zctMVamTJtE
|
|
yTMibu1VrdTzRMR0j0ed4lr64MVpm0RERvMz5NvX62uOJ69XhOKX1HH9bHDtFvNYnfJeOy0Z2ojX
|
|
6jjnEq6fRUmccTvN/J9H0eKcOnx45neaxEbubwHgOHg+milI3vP2resu3Wu0JQmITsmISDHZHKz2
|
|
JgFc1RMLJhGwK9iIZ7MZgEdgmAEwyiWCdwWRLKJVxKYsC2JTuriWUSDNlEsIlMAySx3SCRCQSIAS
|
|
AAACRACQAAAAAAASIASAAAAAAAAAAAAAAACRACRACQASIAAAAAAAAAAAAAAAAAAAAAAAAQCUAAAA
|
|
AAAAAAIAAAAAAAAQAAAAAACBICBICAAEJAQJQCJcLjuS2ny6fPG/LWdpd1o8T0X07SXx/e7wCdJx
|
|
Wa0jmneHQpxPDMdZmJfNtZm49weZrh0/j4o7VtSZ2+Uw0/8A7o49k92vBLc/ntFohFW9PqGXimOI
|
|
6Tu1L8T3eCx6r2t1O3JwvHjifO99v7t/Bwf2l1PXU6rS6eJ8qUm8x+so5TsekzcSjbvs4mt4rzW5
|
|
K2mbT0itesy2cHsvbvqtbmyz5xERWP2jd1tJwrTaONsOKtZ8585+cnDrzmn4Rq+IZObUROHD32n7
|
|
Vv8A0ej0uhxaXFGPFSK1j0bkY4jyZRVZVXFGUVWbGwKsk8mObekNrSW3pWf1a2aYjHbm7bNnQ1id
|
|
PW0TvuDdhJEbQABMsLW2R0ZTMQrvfbz2YWzVhpanUxEd0dWkW5c8R5uXxDX1w4pnfr5Q19XxKuOJ
|
|
2neXltVqtVxbV/RdJ715+1bypANfiOu1HENV9C0MTfNeesx2rD1PAeBYuE6aKx72W3W9/WVnBuB4
|
|
eF4dqRzZbdb5J72l160WVK02ZxCYhOwI23TsnY2BGxsnYBjsiYZsZBjMMZZSgGEolMsQDdG6NwZ7
|
|
piVe6YkFsSziVMWZRILolMSriWUSCyJTuwhMSDMRCQSI3SAlACRCQAAEoAEoASAAAAAAAAACUACR
|
|
ACQAAAAAAAAAAAAASAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAABAAAAAAAAAAAAACBKAAAAAAAQ
|
|
JQAAAhICEbJAYTWJ7wx8KvpC0BV4ceieWGewDHlNmWwCNjZICNhIDmcZredBecdpiY69FXCOLW+i
|
|
UiZidukulmxxlx2paN4mNng+K4+I8Hy2yaTfl37TXetoCPfRxfp1qi3F48ofKMvtvxak8s6LDv61
|
|
rZji9rPaLUf5PC+bfttS0q8q3p9W/wBrRMdpUZuKdN99nzvFqPbTVz7nD8OKs+do2/mW3h4D7Xaq
|
|
ZnPrtNpqz35aRaYOHY9Zk4pNt9rR+rl6zi+OnS+WN57Rv1lXp/YrNaYtruL6zNPnGO3hxP6O5w/2
|
|
f0HDuun09Yv55Le9afznqcOvO4tBreMTHu30unnva0bWt8on+70nDuE4OHYYx4Kbesz3tPrMuhGO
|
|
IjpDOKrK9YVpsyiGUQnYGOyUgI2SlAIEmwMWMs9kTAMJYzDOYRMArmGErZhhMArlHmzmGMwDE3Ts
|
|
bAbs4swj5pgFkSziVcM4BZEsolXDKAZwyhjCYBkACQhIAAAAAAAJAAAAAAAAAAAAAAAAAAAShIAA
|
|
AAAAAAJAAAAAAAAAAAAAABAJEAAAAAAAAAAAAAAAIEoBKAAAAAAAAAAAAAAABAlAAAAAAAIAAAAA
|
|
BAkBAkBAkBAlACEgMZjdjbFW8bWrEx8YWANb6Fp+bfwab+vLDKMFK9qxH5L0bAr8OPRPKz2AY7J2
|
|
SbAjYZAI2E7AIEgIEgIEgMdkSy2NgY7MdlmyNoBXsxmFuyNgVTVjNV3KjlBRNTlXTVHKCrlIqt5T
|
|
lBhEMohlFerLlBjEMohMVTEARDKCITsAk2AEgAAAkAAAAAAAAAAAAAAAAAAAAAAAASAAAAAAAAD/
|
|
2Q==`;async function rge(e){let t=(r,a="application/octet-stream")=>fetch(`data:${a};base64,${r}`).then(o=>o.blob()),n,s;switch(e.config.warmup){case"face":n=await t(C0);break;case"body":case"full":n=await t(T0);break;default:n=null}if(n){let r=await createImageBitmap(n);s=await e.detect(r,e.config),r.close()}return s}async function age(e){return new Promise(t=>{let n;switch(e.config.warmup){case"face":n="data:image/jpeg;base64,"+C0;break;case"full":case"body":n="data:image/jpeg;base64,"+T0;break;default:n=null}let s;typeof Image!="undefined"?s=new Image:ie.Image&&(s=new ie.Image),s.onload=async()=>{let r=Ts(s.naturalWidth,s.naturalHeight);if(!r)ae("Warmup: Canvas not found"),t({});else{let a=r.getContext("2d");a&&a.drawImage(s,0,0);let o=await e.image(r),i=await e.detect(o.tensor,e.config);t(i)}},n?s.src=n:t(null)})}async function oge(e){let t=r=>Buffer.from(r,"base64"),n;if(e.config.warmup==="face"&&(n=t(C0)),(e.config.warmup==="body"||e.config.warmup==="full")&&(n=t(T0)),!n)return null;let s;if(typeof void 0!="undefined"){let r=(void 0).decodeJpeg(n),a=r.expandDims(0);e.tf.dispose(r),s=await e.detect(a,e.config),e.tf.dispose(a)}else e.config.debug&&ae("Warmup tfjs-node not loaded");return s}async function X8(e,t){let n=ot();if(e.state="warmup",t&&(e.config=fn(e.config,t)),!e.config.warmup||e.config.warmup==="none")return{error:"null"};let s;return new Promise(async r=>{typeof createImageBitmap=="function"?s=await rge(e):typeof Image!="undefined"||ie.Canvas!==void 0?s=await age(e):s=await oge(e);let a=ot();e.config.debug&&ae("Warmup",e.config.warmup,Math.round(a-n),"ms"),e.emit("warmup"),r(s)})}var Sc,Lp,Bp,N0,Z8=class{constructor(t){ve(this,"version");ve(this,"config");ve(this,"result");ve(this,"state");ve(this,"process");ve(this,"tf");ve(this,"env");ve(this,"draw");ve(this,"models");ve(this,"events");ve(this,"faceTriangulation");ve(this,"faceUVMap");ve(this,"performance");Lc(this,Sc,void 0);Lc(this,Lp,void 0);Lc(this,Bp,void 0);ve(this,"gl");ve(this,"analyze",(...t)=>{if(!zc(this,Lp))return;let n=this.tf.engine().state.numTensors,s=zc(this,Sc);Bc(this,Sc,n);let r=n-s;r!==0&&ae(...t,r)});Lc(this,N0,t=>{if(!zc(this,Bp))return null;if(!t)return"input is not defined";if(this.env.node&&!(t instanceof Ke))return"input must be a tensor";try{this.tf.getBackend()}catch(n){return"backend not loaded"}return null});ve(this,"similarity",H8);ve(this,"distance",S0);ve(this,"match",j8);ve(this,"emit",t=>{var n;this.events&&this.events.dispatchEvent&&((n=this.events)==null||n.dispatchEvent(new Event(t)))});a0(),this.env=ie,xa.wasmPath=`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${Jh}/dist/`,xa.modelBasePath=this.env.browser?"../models/":"file://models/",xa.backend=this.env.browser?"humangl":"tensorflow",this.version=Lx,Object.defineProperty(this,"version",{value:Lx}),this.config=JSON.parse(JSON.stringify(xa)),Object.seal(this.config),t&&(this.config=fn(this.config,t)),this.tf=Sl,this.state="idle",Bc(this,Sc,0),Bc(this,Lp,!1),Bc(this,Bp,!1),this.performance={backend:0,load:0,image:0,frames:0,cached:0,changed:0,total:0,draw:0},this.events=typeof EventTarget!="undefined"?new EventTarget:void 0,this.models=new Mp,this.draw={options:pa,canvas:(n,s)=>M8(n,s),face:(n,s,r)=>qb(n,s,r),body:(n,s,r)=>Xb(n,s,r),hand:(n,s,r)=>Kb(n,s,r),gesture:(n,s,r)=>jb(n,s,r),object:(n,s,r)=>Zb(n,s,r),person:(n,s,r)=>O8(n,s,r),all:(n,s,r)=>z8(n,s,r)},this.result={face:[],body:[],hand:[],gesture:[],object:[],performance:{},timestamp:0,persons:[]},this.process={tensor:null,canvas:null},this.faceTriangulation=F6,this.faceUVMap=O6,this.gl=Wt,this.emit("create")}reset(){let t=this.config.backend;this.config=JSON.parse(JSON.stringify(xa)),this.config.backend=t}validate(t){return n2(xa,t||this.config)}image(t,n=!0){return yc(t,this.config,n)}async segmentation(t,n){return E8(t,n,this.config)}enhance(t){return nb(t)}async init(){await I0(this,!0),await this.tf.ready(),f6(this.env)}async load(t){this.state="load";let n=ot(),s=Object.values(this.models).filter(o=>o).length;t&&(this.config=fn(this.config,t)),ie.initial&&(this.config.debug&&ae(`version: ${this.version}`),this.config.debug&&ae(`tfjs version: ${this.tf.version_core}`),await I0(this)||ae("error: backend check failed"),await ef(),this.env.browser&&(this.config.debug&&ae("configuration:",this.config),this.config.debug&&ae("tf flags:",this.tf.ENV.flags))),await $8(this),ie.initial&&this.config.debug&&ae("tf engine state:",this.tf.engine().state.numBytes,"bytes",this.tf.engine().state.numTensors,"tensors"),ie.initial=!1,Object.values(this.models).filter(o=>o).length!==s&&(await D8(this),this.emit("load"));let a=Math.trunc(ot()-n);a>(this.performance.load||0)&&(this.performance.load=a)}next(t=this.result){return G8(t,this.config)}async warmup(t){return X8(this,t)}async detect(t,n){return this.state="detect",new Promise(async s=>{var y,A,x,b,w,k,S,N,$,F,R,D,T,O,B,H,z,X,ee,J,Q,ne;this.state="config";let r,a;this.config=fn(this.config,n),this.state="check";let o=zc(this,N0).call(this,t);o&&(ae(o,t),s({error:o}));let i=ot();await I0(this),await this.load(),r=ot(),this.state="image";let l=yc(t,this.config);if(this.process=l,this.performance.image=Math.trunc(ot()-r),this.analyze("Get Image:"),!l.tensor){this.config.debug&&ae("could not convert input to tensor"),s({error:"could not convert input to tensor"});return}this.emit("image"),r=ot(),this.config.skipFrame=await m6(this.config,l.tensor),this.performance.frames||(this.performance.frames=0),this.performance.cached||(this.performance.cached=0),this.performance.frames++,this.config.skipFrame&&this.performance.cached++,this.performance.changed=Math.trunc(ot()-r),this.analyze("Check Changed:");let c=[],u=[],d=[],p=[];this.state="detect:face",this.config.async?(c=this.config.face.enabled?Yb(this,l.tensor):[],this.performance.face&&delete this.performance.face):(r=ot(),c=this.config.face.enabled?await Yb(this,l.tensor):[],a=Math.trunc(ot()-r),a>0&&(this.performance.face=a)),this.config.async&&(this.config.body.maxDetected===-1||this.config.hand.maxDetected===-1)&&(c=await c),this.analyze("Start Body:"),this.state="detect:body";let h=this.config.body.maxDetected===-1?fn(this.config,{body:{maxDetected:this.config.face.enabled?1*c.length:1}}):this.config;this.config.async?(((y=this.config.body.modelPath)==null?void 0:y.includes("posenet"))?u=this.config.body.enabled?pb(l.tensor,h):[]:((A=this.config.body.modelPath)==null?void 0:A.includes("blazepose"))?u=this.config.body.enabled?Tb(l.tensor,h):[]:((x=this.config.body.modelPath)==null?void 0:x.includes("efficientpose"))?u=this.config.body.enabled?_b(l.tensor,h):[]:((b=this.config.body.modelPath)==null?void 0:b.includes("movenet"))&&(u=this.config.body.enabled?Mb(l.tensor,h):[]),this.performance.body&&delete this.performance.body):(r=ot(),((w=this.config.body.modelPath)==null?void 0:w.includes("posenet"))?u=this.config.body.enabled?await pb(l.tensor,h):[]:((k=this.config.body.modelPath)==null?void 0:k.includes("blazepose"))?u=this.config.body.enabled?await Tb(l.tensor,h):[]:((S=this.config.body.modelPath)==null?void 0:S.includes("efficientpose"))?u=this.config.body.enabled?await _b(l.tensor,h):[]:((N=this.config.body.modelPath)==null?void 0:N.includes("movenet"))&&(u=this.config.body.enabled?await Mb(l.tensor,h):[]),a=Math.trunc(ot()-r),a>0&&(this.performance.body=a)),this.analyze("End Body:"),this.analyze("Start Hand:"),this.state="detect:hand";let f=this.config.hand.maxDetected===-1?fn(this.config,{hand:{maxDetected:this.config.face.enabled?2*c.length:1}}):this.config;this.config.async?(((F=($=this.config.hand.detector)==null?void 0:$.modelPath)==null?void 0:F.includes("handdetect"))?d=this.config.hand.enabled?yb(l.tensor,f):[]:((D=(R=this.config.hand.detector)==null?void 0:R.modelPath)==null?void 0:D.includes("handtrack"))&&(d=this.config.hand.enabled?bb(l.tensor,f):[]),this.performance.hand&&delete this.performance.hand):(r=ot(),((O=(T=this.config.hand.detector)==null?void 0:T.modelPath)==null?void 0:O.includes("handdetect"))?d=this.config.hand.enabled?await yb(l.tensor,f):[]:((H=(B=this.config.hand.detector)==null?void 0:B.modelPath)==null?void 0:H.includes("handtrack"))&&(d=this.config.hand.enabled?await bb(l.tensor,f):[]),a=Math.trunc(ot()-r),a>0&&(this.performance.hand=a)),this.analyze("End Hand:"),this.analyze("Start Object:"),this.state="detect:object",this.config.async?(((z=this.config.object.modelPath)==null?void 0:z.includes("nanodet"))?p=this.config.object.enabled?Lb(l.tensor,this.config):[]:((X=this.config.object.modelPath)==null?void 0:X.includes("centernet"))&&(p=this.config.object.enabled?Wb(l.tensor,this.config):[]),this.performance.object&&delete this.performance.object):(r=ot(),((ee=this.config.object.modelPath)==null?void 0:ee.includes("nanodet"))?p=this.config.object.enabled?await Lb(l.tensor,this.config):[]:((J=this.config.object.modelPath)==null?void 0:J.includes("centernet"))&&(p=this.config.object.enabled?await Wb(l.tensor,this.config):[]),a=Math.trunc(ot()-r),a>0&&(this.performance.object=a)),this.analyze("End Object:"),this.state="detect:await",this.config.async&&([c,u,d,p]=await Promise.all([c,u,d,p])),this.state="detect:gesture";let m=[];this.config.gesture.enabled&&(r=ot(),m=[...W8(c),...B8(u),...U8(d),...V8(c)],this.config.async?this.performance.gesture&&delete this.performance.gesture:this.performance.gesture=Math.trunc(ot()-r)),this.performance.total=Math.trunc(ot()-i);let g=((ne=(Q=this.process)==null?void 0:Q.tensor)==null?void 0:ne.shape)||[];this.result={face:c,body:u,hand:d,gesture:m,object:p,performance:this.performance,canvas:this.process.canvas,timestamp:Date.now(),get persons(){return q8(c,u,d,m,g)}},te(l.tensor),this.emit("detect"),this.state="idle",s(this.result)})}};Sc=new WeakMap,Lp=new WeakMap,Bp=new WeakMap,N0=new WeakMap;return ige;})();
|
|
/**
|
|
* @license
|
|
* Copyright 2017 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2018 Google LLC
|
|
*
|
|
* Use of this source code is governed by an MIT-style
|
|
* license that can be found in the LICENSE file or at
|
|
* https://opensource.org/licenses/MIT.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC
|
|
*
|
|
* Use of this source code is governed by an MIT-style
|
|
* license that can be found in the LICENSE file or at
|
|
* https://opensource.org/licenses/MIT.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2020 Google Inc. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2020 Google LLC
|
|
*
|
|
* Use of this source code is governed by an MIT-style
|
|
* license that can be found in the LICENSE file or at
|
|
* https://opensource.org/licenses/MIT.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use backend file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the License);
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an AS IS BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* https://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the License);
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an AS IS BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/** @license See the LICENSE file. */
|