mirror of https://github.com/vladmandic/human
8020 lines
1.6 MiB
8020 lines
1.6 MiB
"use strict";/*
|
|
Human
|
|
homepage: <https://github.com/vladmandic/human>
|
|
author: <https://github.com/vladmandic>'
|
|
*/
|
|
|
|
var Human=(()=>{var Qc=Object.defineProperty;var iR=Object.getOwnPropertyDescriptor;var oR=Object.getOwnPropertyNames;var lR=Object.prototype.hasOwnProperty;var uR=(e,t,r)=>t in e?Qc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var ws=(e,t)=>{for(var r in t)Qc(e,r,{get:t[r],enumerable:!0})},dR=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of oR(t))!lR.call(e,a)&&a!==r&&Qc(e,a,{get:()=>t[a],enumerable:!(n=iR(t,a))||n.enumerable});return e};var pR=e=>dR(Qc({},"__esModule",{value:!0}),e);var fe=(e,t,r)=>(uR(e,typeof t!="symbol"?t+"":t,r),r),jb=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var wp=(e,t,r)=>(jb(e,t,"read from private field"),r?r.call(e):t.get(e)),kp=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},Ip=(e,t,r,n)=>(jb(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var gAe={};ws(gAe,{Human:()=>kb,default:()=>kb,defaults:()=>ks,draw:()=>gb,env:()=>he,match:()=>wb,models:()=>T1});function se(...e){let t=new Date,r=`${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(r,"Human:",...e)}function Hb(e,t){let r=e.endsWith("/")?"":"/",a=t.startsWith(".")||t.startsWith("/")||t.startsWith("http:")||t.startsWith("https:")||t.startsWith("file:")?`${t}`:`${e}${r}${t}`;if(!a.toLocaleLowerCase().includes(".json"))throw new Error(`modelpath error: expecting json file: ${a}`);return a}var oe=()=>typeof performance!="undefined"?performance.now():parseInt((Number(process.hrtime.bigint())/1e3/1e3).toString());function hg(e,t,r="config",n=[]){for(let a of Object.keys(t))if(typeof t[a]=="object")hg(e[a],t[a],a,n);else{let s=e&&typeof e[a]!="undefined";s||n.push({reason:"unknown property",where:`${r}.${a} = ${t[a]}`});let i=e&&typeof e[a]==typeof t[a];s&&!i&&n.push({reason:"property type mismatch",where:`${r}.${a} = ${t[a]}`,expected:typeof e[a]})}return t.debug&&r==="config"&&n.length>0&&se("invalid configuration",n),n}function Gt(...e){let t=r=>r&&typeof r=="object";return e.reduce((r,n)=>(Object.keys(n||{}).forEach(a=>{let s=r[a],i=n[a];Array.isArray(s)&&Array.isArray(i)?r[a]=s.concat(...i):t(s)&&t(i)?r[a]=Gt(s,i):r[a]=i}),r),{})}var ks={backend:"",modelBasePath:"",cacheModels:!0,wasmPath:"",wasmPlatformFetch:!1,debug:!0,async:!0,warmup:"full",cacheSensitivity:.7,skipAllowed:!1,deallocate:!1,filter:{enabled:!0,equalization:!1,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:99,skipTime:2500,minConfidence:.2,iouThreshold:.1,mask:!1,return:!1},mesh:{enabled:!0,modelPath:"facemesh.json",keepInvalid:!1},attention:{enabled:!1,modelPath:"facemesh-attention.json"},iris:{enabled:!0,modelPath:"iris.json"},emotion:{enabled:!0,minConfidence:.1,skipFrames:99,skipTime:1500,modelPath:"emotion.json"},description:{enabled:!0,modelPath:"faceres.json",skipFrames:99,skipTime:3e3,minConfidence:.1},antispoof:{enabled:!1,skipFrames:99,skipTime:4e3,modelPath:"antispoof.json"},liveness:{enabled:!1,skipFrames:99,skipTime:4e3,modelPath:"liveness.json"}},body:{enabled:!0,modelPath:"movenet-lightning.json",maxDetected:-1,minConfidence:.3,skipFrames:1,skipTime:200},hand:{enabled:!0,rotation:!0,skipFrames:99,skipTime:1e3,minConfidence:.5,iouThreshold:.2,maxDetected:-1,landmarks:!0,detector:{modelPath:"handtrack.json"},skeleton:{modelPath:"handlandmark-full.json"}},object:{enabled:!1,modelPath:"mb3-centernet.json",minConfidence:.2,iouThreshold:.4,maxDetected:10,skipFrames:99,skipTime:2e3},segmentation:{enabled:!1,modelPath:"selfie.json",blur:8}};var Ue={};ws(Ue,{Abs:()=>Go,Acos:()=>Hu,Acosh:()=>qu,AdadeltaOptimizer:()=>nm,AdagradOptimizer:()=>am,AdamOptimizer:()=>sm,AdamaxOptimizer:()=>im,Add:()=>Qa,AddN:()=>Zs,All:()=>Xu,Any:()=>Ku,ArgMax:()=>Ys,ArgMin:()=>Zu,Asin:()=>Yu,Asinh:()=>Ju,Atan:()=>Qu,Atan2:()=>td,Atanh:()=>ed,AvgPool:()=>Js,AvgPool3D:()=>ah,AvgPool3DGrad:()=>df,AvgPoolGrad:()=>uf,BackendWasm:()=>EC,BatchMatMul:()=>Qs,BatchToSpaceND:()=>jo,Bincount:()=>pf,BroadcastArgs:()=>hf,BroadcastTo:()=>K7,Callback:()=>E8,CallbackList:()=>Ew,Cast:()=>ei,Ceil:()=>ti,ClipByValue:()=>es,Complex:()=>sh,ComplexAbs:()=>ih,Concat:()=>Ho,Conv2D:()=>ri,Conv2DBackpropFilter:()=>cf,Conv2DBackpropInput:()=>ni,Conv3D:()=>oh,Conv3DBackpropFilterV2:()=>ff,Conv3DBackpropInputV2:()=>mf,Cos:()=>ai,Cosh:()=>si,CropAndResize:()=>Xo,Cumprod:()=>qo,Cumsum:()=>ii,CustomCallback:()=>$w,DataStorage:()=>nh,DenseBincount:()=>gf,DepthToSpace:()=>Ko,DepthwiseConv2dNative:()=>oi,DepthwiseConv2dNativeBackpropFilter:()=>yf,DepthwiseConv2dNativeBackpropInput:()=>Af,Diag:()=>xf,Dilation2D:()=>lh,Dilation2DBackpropFilter:()=>N0,Dilation2DBackpropInput:()=>T0,ENV:()=>ba,EarlyStopping:()=>R8,Einsum:()=>uh,Elu:()=>ui,EluGrad:()=>bf,Environment:()=>q7,Equal:()=>Zo,Erf:()=>rd,Exp:()=>di,ExpandDims:()=>Yo,Expm1:()=>Jo,FFT:()=>vf,Fill:()=>nd,FlipLeftRight:()=>Qo,Floor:()=>pi,FloorDiv:()=>hi,FromPixels:()=>jp,FusedBatchNorm:()=>ci,FusedConv2D:()=>Os,FusedDepthwiseConv2D:()=>zs,GPGPUContext:()=>Tu,GatherNd:()=>tl,GatherV2:()=>el,GraphModel:()=>Uh,Greater:()=>rl,GreaterEqual:()=>fi,History:()=>Rw,IFFT:()=>wf,Identity:()=>mi,Imag:()=>dh,InputSpec:()=>Zt,IsFinite:()=>ad,IsInf:()=>sd,IsNan:()=>id,KernelBackend:()=>Gu,LRN:()=>ph,LRNGrad:()=>If,LayerVariable:()=>bw,LayersModel:()=>Za,LeakyRelu:()=>gi,Less:()=>nl,LessEqual:()=>al,LinSpace:()=>kf,Log:()=>yi,Log1p:()=>od,LogSoftmax:()=>Y7,LogicalAnd:()=>sl,LogicalNot:()=>il,LogicalOr:()=>ld,LogicalXor:()=>Z7,LowerBound:()=>r$,MathBackendCPU:()=>pA,MathBackendWebGL:()=>qh,Max:()=>Ai,MaxPool:()=>bi,MaxPool3D:()=>hh,MaxPool3DGrad:()=>Cf,MaxPoolGrad:()=>Sf,MaxPoolWithArgmax:()=>Tf,Maximum:()=>xi,Mean:()=>vi,Min:()=>wi,Minimum:()=>ki,MirrorPad:()=>Ii,Mod:()=>ud,MomentumOptimizer:()=>om,Multinomial:()=>Nf,Multiply:()=>Si,Neg:()=>ol,NonMaxSuppressionV3:()=>ul,NonMaxSuppressionV4:()=>dd,NonMaxSuppressionV5:()=>dl,NotEqual:()=>ll,OP_SCOPE_SUFFIX:()=>h6,OneHot:()=>hl,OnesLike:()=>pl,Optimizer:()=>as,OptimizerConstructors:()=>Ss,Pack:()=>cl,PadV2:()=>Ci,Pool:()=>n$,Pow:()=>Ti,Prelu:()=>Ni,Prod:()=>Ei,RMSPropOptimizer:()=>lm,RNN:()=>ss,Range:()=>pd,Rank:()=>r6,Real:()=>ch,RealDiv:()=>li,Reciprocal:()=>hd,Reduction:()=>aw,Relu:()=>Ri,Relu6:()=>Mi,Reshape:()=>fl,ResizeBilinear:()=>$i,ResizeBilinearGrad:()=>Rf,ResizeNearestNeighbor:()=>cd,ResizeNearestNeighborGrad:()=>Ef,Reverse:()=>ml,RotateWithOffset:()=>El,Round:()=>gl,Rsqrt:()=>Fi,SGDOptimizer:()=>Fh,ScatterNd:()=>yl,SearchSorted:()=>$f,Select:()=>Al,Selu:()=>fd,Sequential:()=>wm,Sigmoid:()=>Pi,Sign:()=>md,Sin:()=>_i,Sinh:()=>bl,Slice:()=>xl,Softmax:()=>Di,Softplus:()=>gd,SpaceToBatchND:()=>vl,SparseFillEmptyRows:()=>fh,SparseReshape:()=>yd,SparseSegmentMean:()=>mh,SparseSegmentSum:()=>gh,SparseToDense:()=>yh,SplitV:()=>wl,Sqrt:()=>Oi,Square:()=>Ad,SquaredDifference:()=>Li,Step:()=>Vi,StridedSlice:()=>kl,StringNGrams:()=>Ah,StringSplit:()=>Mf,StringToHashBucketFast:()=>Ff,Sub:()=>Bi,Sum:()=>zi,SymbolicTensor:()=>pa,Tan:()=>Il,Tanh:()=>Wi,Tensor:()=>nt,TensorBuffer:()=>ir,Tile:()=>ts,TopK:()=>Sl,Transform:()=>Cl,Transpose:()=>$a,Unique:()=>_f,Unpack:()=>Tl,UnsortedSegmentSum:()=>xh,UpperBound:()=>a$,Variable:()=>Xp,ZerosLike:()=>Nl,_FusedMatMul:()=>Ps,abs:()=>ar,acos:()=>q6,acosh:()=>X6,add:()=>le,addN:()=>Of,all:()=>Yy,any:()=>_0,argMax:()=>$n,argMin:()=>K6,asin:()=>Z6,asinh:()=>Y6,atan:()=>J6,atan2:()=>Q6,atanh:()=>ev,avgPool:()=>zf,avgPool3d:()=>Qy,backend:()=>Dn,backend_util:()=>C,basicLSTMCell:()=>KF,batchNorm:()=>Mu,batchNorm2d:()=>av,batchNorm3d:()=>sv,batchNorm4d:()=>iv,batchToSpaceND:()=>Df,bincount:()=>e3,booleanMaskAsync:()=>lz,broadcastArgs:()=>ov,broadcastTo:()=>Bp,broadcast_util:()=>$l,browser:()=>Ln,buffer:()=>De,callbacks:()=>Lj,cast:()=>me,ceil:()=>lv,clipByValue:()=>fn,clone:()=>Vr,complex:()=>Ya,concat:()=>St,concat1d:()=>uv,concat2d:()=>bd,concat3d:()=>dv,concat4d:()=>pv,constraints:()=>Sw,conv1d:()=>t3,conv2d:()=>Ls,conv2dTranspose:()=>n3,conv3d:()=>a3,conv3dTranspose:()=>cv,copyRegisteredKernels:()=>l$,cos:()=>Lf,cosh:()=>s3,cosineWindow:()=>E3,cumprod:()=>O0,cumsum:()=>i3,customGrad:()=>Pa,data:()=>tk,denseBincount:()=>fv,deprecationWarn:()=>Wy,depthToSpace:()=>mv,depthwiseConv2d:()=>Nh,deregisterOp:()=>Vj,device_util:()=>kh,diag:()=>C_,dilation2d:()=>gv,disableDeprecationWarnings:()=>OM,dispose:()=>ee,disposeVariables:()=>zM,div:()=>pe,divNoNan:()=>yv,dot:()=>F_,dropout:()=>Kv,einsum:()=>Av,elu:()=>Eh,enableDebugMode:()=>PM,enableProdMode:()=>By,enclosingPowerOfTwo:()=>Zv,engine:()=>Xt,env:()=>Z,equal:()=>Mn,erf:()=>xv,euclideanNorm:()=>Iv,exp:()=>Fn,expandDims:()=>Kt,expm1:()=>Sv,eye:()=>u3,fft:()=>Zf,fill:()=>vd,findBackend:()=>Uy,findBackendFactory:()=>WM,floor:()=>Rh,floorDiv:()=>Ch,forceHalfFloat:()=>wI,fused:()=>Vs,gather:()=>Fu,gatherND:()=>Xv,gather_util:()=>Gy,getBackend:()=>Hr,getGradient:()=>Ng,getKernel:()=>E0,getKernelsForBackend:()=>Fa,getThreadsCount:()=>p3e,gpgpu_util:()=>Q9,grad:()=>cP,grads:()=>fP,greater:()=>gn,greaterEqual:()=>Ml,ifft:()=>Yp,imag:()=>Sh,image:()=>Ie,inTopKAsync:()=>Az,initializers:()=>Cw,input:()=>jw,io:()=>Cr,irfft:()=>S3,isFinite:()=>nP,isInf:()=>sP,isNaN:()=>Cv,keep:()=>mr,kernel_impls:()=>Kn,layers:()=>Tw,leakyRelu:()=>Wf,less:()=>d3,lessEqual:()=>Fl,linalg:()=>sw,linspace:()=>Tv,loadGraphModel:()=>jH,loadGraphModelSync:()=>HH,loadLayersModel:()=>ZU,localResponseNormalization:()=>Nv,log:()=>_n,log1p:()=>Vf,logSigmoid:()=>xP,logSoftmax:()=>p3,logSumExp:()=>Rv,logicalAnd:()=>ga,logicalNot:()=>Gf,logicalOr:()=>h3,logicalXor:()=>TP,losses:()=>rL,lowerBound:()=>$v,matMul:()=>Ye,math:()=>N6,max:()=>yr,maxPool:()=>jf,maxPool3d:()=>f3,maxPoolWithArgmax:()=>Mv,maximum:()=>rs,mean:()=>Vt,memory:()=>F0,meshgrid:()=>_P,metrics:()=>C8,min:()=>Bs,minimum:()=>$h,mirrorPad:()=>Fv,mod:()=>kd,model:()=>XU,models:()=>T8,moments:()=>Hf,movingAverage:()=>dz,mul:()=>L,multiRNNCell:()=>BP,multinomial:()=>_v,neg:()=>Mt,nextFrame:()=>M3,norm:()=>Bf,notEqual:()=>_u,oneHot:()=>Zp,ones:()=>cn,onesLike:()=>Pn,op:()=>W,outerProduct:()=>jP,pad:()=>Xn,pad1d:()=>XP,pad2d:()=>ZP,pad3d:()=>JP,pad4d:()=>eO,pool:()=>sO,pow:()=>Ws,prelu:()=>Xf,print:()=>w6,prod:()=>m3,profile:()=>DM,rand:()=>uO,randomGamma:()=>cO,randomNormal:()=>Pv,randomUniform:()=>Id,range:()=>Pu,ready:()=>xd,real:()=>Ru,reciprocal:()=>Ov,registerBackend:()=>Rl,registerCallbackConstructor:()=>YU,registerGradient:()=>J7,registerKernel:()=>qn,registerOp:()=>Wj,regularizers:()=>N8,relu:()=>Da,relu6:()=>A3,removeBackend:()=>BM,reshape:()=>U,reverse:()=>On,reverse1d:()=>vO,reverse2d:()=>kO,reverse3d:()=>SO,reverse4d:()=>TO,rfft:()=>Yf,round:()=>x3,rsqrt:()=>b3,scalar:()=>Se,scatterND:()=>qv,scatter_util:()=>jy,searchSorted:()=>c3,selu:()=>v3,separableConv2d:()=>zv,sequential:()=>KU,serialization:()=>ue,setBackend:()=>Vy,setPlatform:()=>VM,setThreadsCount:()=>d3e,setWasmPath:()=>u3e,setWasmPaths:()=>HA,setWebGLContext:()=>Fm,setdiff1dAsync:()=>Dv,shared:()=>$m,sigmoid:()=>Tr,sign:()=>Lv,signal:()=>tL,sin:()=>w3,sinh:()=>k3,slice:()=>_e,slice1d:()=>Kf,slice2d:()=>I3,slice3d:()=>_l,slice4d:()=>Po,slice_util:()=>Dt,softmax:()=>Sd,softplus:()=>wd,spaceToBatchND:()=>qf,sparse:()=>$p,sparseToDense:()=>N3,spectral:()=>eL,split:()=>Yt,sqrt:()=>Er,square:()=>bt,squaredDifference:()=>C3,squeeze:()=>et,stack:()=>ur,step:()=>Mh,stridedSlice:()=>Bv,string:()=>f0,sub:()=>ce,sum:()=>ke,sumOutType:()=>wh,tan:()=>Wv,tanh:()=>$u,tensor:()=>ft,tensor1d:()=>Nt,tensor2d:()=>ca,tensor3d:()=>R6,tensor4d:()=>JO,tensor5d:()=>QO,tensor6d:()=>ez,tensor_util:()=>ha,test_util:()=>G6,tidy:()=>X,tile:()=>jn,time:()=>LM,topk:()=>Vv,train:()=>Ao,transpose:()=>tt,truncatedNormal:()=>Jf,unique:()=>Wg,unregisterGradient:()=>o$,unregisterKernel:()=>i$,unsortedSegmentSum:()=>Uv,unstack:()=>an,upcastType:()=>Nr,upperBound:()=>Gv,util:()=>v,valueAndGrad:()=>mP,valueAndGrads:()=>gP,variable:()=>jv,variableGrads:()=>Ev,version:()=>nc,version_converter:()=>XH,version_core:()=>Zy,version_cpu:()=>_X,version_layers:()=>t5,version_wasm:()=>h3e,version_webgl:()=>dre,webgl:()=>pre,webgl_util:()=>k9,webgpu:()=>IS,where:()=>Ur,whereAsync:()=>T3,zeros:()=>Ot,zerosLike:()=>at});var hR=Object.create,af=Object.defineProperty,cR=Object.getOwnPropertyDescriptor,P7=Object.getOwnPropertyNames,fR=Object.getPrototypeOf,mR=Object.prototype.hasOwnProperty,gR=e=>af(e,"__esModule",{value:!0}),dr=(e,t)=>function(){return t||(0,e[P7(e)[0]])((t={exports:{}}).exports,t),t.exports},Be=(e,t)=>{for(var r in t)af(e,r,{get:t[r],enumerable:!0})},yR=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of P7(t))!mR.call(e,a)&&(r||a!=="default")&&af(e,a,{get:()=>t[a],enumerable:!(n=cR(t,a))||n.enumerable});return e},Vo=(e,t)=>yR(gR(af(e!=null?hR(fR(e)):{},"default",!t&&e&&e.__esModule?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e),AR=dr({"src/node_modules/long/src/long.js"(e,t){t.exports=n;var r=null;try{r=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(S){}function n(S,z,O){this.low=S|0,this.high=z|0,this.unsigned=!!O}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0});function a(S){return(S&&S.__isLong__)===!0}n.isLong=a;var s={},i={};function o(S,z){var O,j,K;return z?(S>>>=0,(K=0<=S&&S<256)&&(j=i[S],j)?j:(O=u(S,(S|0)<0?-1:0,!0),K&&(i[S]=O),O)):(S|=0,(K=-128<=S&&S<128)&&(j=s[S],j)?j:(O=u(S,S<0?-1:0,!1),K&&(s[S]=O),O))}n.fromInt=o;function l(S,z){if(isNaN(S))return z?b:x;if(z){if(S<0)return b;if(S>=g)return R}else{if(S<=-y)return F;if(S+1>=y)return E}return S<0?l(-S,z).neg():u(S%f|0,S/f|0,z)}n.fromNumber=l;function u(S,z,O){return new n(S,z,O)}n.fromBits=u;var d=Math.pow;function h(S,z,O){if(S.length===0)throw Error("empty string");if(S==="NaN"||S==="Infinity"||S==="+Infinity"||S==="-Infinity")return x;if(typeof z=="number"?(O=z,z=!1):z=!!z,O=O||10,O<2||36<O)throw RangeError("radix");var j;if((j=S.indexOf("-"))>0)throw Error("interior hyphen");if(j===0)return h(S.substring(1),z,O).neg();for(var K=l(d(O,8)),D=x,Y=0;Y<S.length;Y+=8){var V=Math.min(8,S.length-Y),re=parseInt(S.substring(Y,Y+V),O);if(V<8){var Q=l(d(O,V));D=D.mul(Q).add(l(re))}else D=D.mul(K),D=D.add(l(re))}return D.unsigned=z,D}n.fromString=h;function p(S,z){return typeof S=="number"?l(S,z):typeof S=="string"?h(S,z):u(S.low,S.high,typeof z=="boolean"?z:S.unsigned)}n.fromValue=p;var c=1<<16,m=1<<24,f=c*c,g=f*f,y=g/2,A=o(m),x=o(0);n.ZERO=x;var b=o(0,!0);n.UZERO=b;var w=o(1);n.ONE=w;var I=o(1,!0);n.UONE=I;var T=o(-1);n.NEG_ONE=T;var E=u(-1,2147483647,!1);n.MAX_VALUE=E;var R=u(-1,-1,!0);n.MAX_UNSIGNED_VALUE=R;var F=u(0,-2147483648,!1);n.MIN_VALUE=F;var $=n.prototype;$.toInt=function(){return this.unsigned?this.low>>>0:this.low},$.toNumber=function(){return this.unsigned?(this.high>>>0)*f+(this.low>>>0):this.high*f+(this.low>>>0)},$.toString=function(S){if(S=S||10,S<2||36<S)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(F)){var z=l(S),O=this.div(z),j=O.mul(z).sub(this);return O.toString(S)+j.toInt().toString(S)}else return"-"+this.neg().toString(S);for(var K=l(d(S,6),this.unsigned),D=this,Y="";;){var V=D.div(K),re=D.sub(V.mul(K)).toInt()>>>0,Q=re.toString(S);if(D=V,D.isZero())return Q+Y;for(;Q.length<6;)Q="0"+Q;Y=""+Q+Y}},$.getHighBits=function(){return this.high},$.getHighBitsUnsigned=function(){return this.high>>>0},$.getLowBits=function(){return this.low},$.getLowBitsUnsigned=function(){return this.low>>>0},$.getNumBitsAbs=function(){if(this.isNegative())return this.eq(F)?64:this.neg().getNumBitsAbs();for(var S=this.high!=0?this.high:this.low,z=31;z>0&&(S&1<<z)==0;z--);return this.high!=0?z+33:z+1},$.isZero=function(){return this.high===0&&this.low===0},$.eqz=$.isZero,$.isNegative=function(){return!this.unsigned&&this.high<0},$.isPositive=function(){return this.unsigned||this.high>=0},$.isOdd=function(){return(this.low&1)===1},$.isEven=function(){return(this.low&1)===0},$.equals=function(S){return a(S)||(S=p(S)),this.unsigned!==S.unsigned&&this.high>>>31===1&&S.high>>>31===1?!1:this.high===S.high&&this.low===S.low},$.eq=$.equals,$.notEquals=function(S){return!this.eq(S)},$.neq=$.notEquals,$.ne=$.notEquals,$.lessThan=function(S){return this.comp(S)<0},$.lt=$.lessThan,$.lessThanOrEqual=function(S){return this.comp(S)<=0},$.lte=$.lessThanOrEqual,$.le=$.lessThanOrEqual,$.greaterThan=function(S){return this.comp(S)>0},$.gt=$.greaterThan,$.greaterThanOrEqual=function(S){return this.comp(S)>=0},$.gte=$.greaterThanOrEqual,$.ge=$.greaterThanOrEqual,$.compare=function(S){if(a(S)||(S=p(S)),this.eq(S))return 0;var z=this.isNegative(),O=S.isNegative();return z&&!O?-1:!z&&O?1:this.unsigned?S.high>>>0>this.high>>>0||S.high===this.high&&S.low>>>0>this.low>>>0?-1:1:this.sub(S).isNegative()?-1:1},$.comp=$.compare,$.negate=function(){return!this.unsigned&&this.eq(F)?F:this.not().add(w)},$.neg=$.negate,$.add=function(S){a(S)||(S=p(S));var z=this.high>>>16,O=this.high&65535,j=this.low>>>16,K=this.low&65535,D=S.high>>>16,Y=S.high&65535,V=S.low>>>16,re=S.low&65535,Q=0,ie=0,J=0,ae=0;return ae+=K+re,J+=ae>>>16,ae&=65535,J+=j+V,ie+=J>>>16,J&=65535,ie+=O+Y,Q+=ie>>>16,ie&=65535,Q+=z+D,Q&=65535,u(J<<16|ae,Q<<16|ie,this.unsigned)},$.subtract=function(S){return a(S)||(S=p(S)),this.add(S.neg())},$.sub=$.subtract,$.multiply=function(S){if(this.isZero())return x;if(a(S)||(S=p(S)),r){var z=r.mul(this.low,this.high,S.low,S.high);return u(z,r.get_high(),this.unsigned)}if(S.isZero())return x;if(this.eq(F))return S.isOdd()?F:x;if(S.eq(F))return this.isOdd()?F:x;if(this.isNegative())return S.isNegative()?this.neg().mul(S.neg()):this.neg().mul(S).neg();if(S.isNegative())return this.mul(S.neg()).neg();if(this.lt(A)&&S.lt(A))return l(this.toNumber()*S.toNumber(),this.unsigned);var O=this.high>>>16,j=this.high&65535,K=this.low>>>16,D=this.low&65535,Y=S.high>>>16,V=S.high&65535,re=S.low>>>16,Q=S.low&65535,ie=0,J=0,ae=0,de=0;return de+=D*Q,ae+=de>>>16,de&=65535,ae+=K*Q,J+=ae>>>16,ae&=65535,ae+=D*re,J+=ae>>>16,ae&=65535,J+=j*Q,ie+=J>>>16,J&=65535,J+=K*re,ie+=J>>>16,J&=65535,J+=D*V,ie+=J>>>16,J&=65535,ie+=O*Q+j*re+K*V+D*Y,ie&=65535,u(ae<<16|de,ie<<16|J,this.unsigned)},$.mul=$.multiply,$.divide=function(S){if(a(S)||(S=p(S)),S.isZero())throw Error("division by zero");if(r){if(!this.unsigned&&this.high===-2147483648&&S.low===-1&&S.high===-1)return this;var z=(this.unsigned?r.div_u:r.div_s)(this.low,this.high,S.low,S.high);return u(z,r.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?b:x;var O,j,K;if(this.unsigned){if(S.unsigned||(S=S.toUnsigned()),S.gt(this))return b;if(S.gt(this.shru(1)))return I;K=b}else{if(this.eq(F)){if(S.eq(w)||S.eq(T))return F;if(S.eq(F))return w;var D=this.shr(1);return O=D.div(S).shl(1),O.eq(x)?S.isNegative()?w:T:(j=this.sub(S.mul(O)),K=O.add(j.div(S)),K)}else if(S.eq(F))return this.unsigned?b:x;if(this.isNegative())return S.isNegative()?this.neg().div(S.neg()):this.neg().div(S).neg();if(S.isNegative())return this.div(S.neg()).neg();K=x}for(j=this;j.gte(S);){O=Math.max(1,Math.floor(j.toNumber()/S.toNumber()));for(var Y=Math.ceil(Math.log(O)/Math.LN2),V=Y<=48?1:d(2,Y-48),re=l(O),Q=re.mul(S);Q.isNegative()||Q.gt(j);)O-=V,re=l(O,this.unsigned),Q=re.mul(S);re.isZero()&&(re=w),K=K.add(re),j=j.sub(Q)}return K},$.div=$.divide,$.modulo=function(S){if(a(S)||(S=p(S)),r){var z=(this.unsigned?r.rem_u:r.rem_s)(this.low,this.high,S.low,S.high);return u(z,r.get_high(),this.unsigned)}return this.sub(this.div(S).mul(S))},$.mod=$.modulo,$.rem=$.modulo,$.not=function(){return u(~this.low,~this.high,this.unsigned)},$.and=function(S){return a(S)||(S=p(S)),u(this.low&S.low,this.high&S.high,this.unsigned)},$.or=function(S){return a(S)||(S=p(S)),u(this.low|S.low,this.high|S.high,this.unsigned)},$.xor=function(S){return a(S)||(S=p(S)),u(this.low^S.low,this.high^S.high,this.unsigned)},$.shiftLeft=function(S){return a(S)&&(S=S.toInt()),(S&=63)===0?this:S<32?u(this.low<<S,this.high<<S|this.low>>>32-S,this.unsigned):u(0,this.low<<S-32,this.unsigned)},$.shl=$.shiftLeft,$.shiftRight=function(S){return a(S)&&(S=S.toInt()),(S&=63)===0?this:S<32?u(this.low>>>S|this.high<<32-S,this.high>>S,this.unsigned):u(this.high>>S-32,this.high>=0?0:-1,this.unsigned)},$.shr=$.shiftRight,$.shiftRightUnsigned=function(S){if(a(S)&&(S=S.toInt()),S&=63,S===0)return this;var z=this.high;if(S<32){var O=this.low;return u(O>>>S|z<<32-S,z>>>S,this.unsigned)}else return S===32?u(z,0,this.unsigned):u(z>>>S-32,0,this.unsigned)},$.shru=$.shiftRightUnsigned,$.shr_u=$.shiftRightUnsigned,$.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},$.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},$.toBytes=function(S){return S?this.toBytesLE():this.toBytesBE()},$.toBytesLE=function(){var S=this.high,z=this.low;return[z&255,z>>>8&255,z>>>16&255,z>>>24,S&255,S>>>8&255,S>>>16&255,S>>>24]},$.toBytesBE=function(){var S=this.high,z=this.low;return[S>>>24,S>>>16&255,S>>>8&255,S&255,z>>>24,z>>>16&255,z>>>8&255,z&255]},n.fromBytes=function(S,z,O){return O?n.fromBytesLE(S,z):n.fromBytesBE(S,z)},n.fromBytesLE=function(S,z){return new n(S[0]|S[1]<<8|S[2]<<16|S[3]<<24,S[4]|S[5]<<8|S[6]<<16|S[7]<<24,z)},n.fromBytesBE=function(S,z){return new n(S[4]<<24|S[5]<<16|S[6]<<8|S[7],S[0]<<24|S[1]<<16|S[2]<<8|S[3],z)}}}),xR=dr({"(disabled):src/node_modules/node-fetch/browser.js"(){}}),bR=dr({"(disabled):util"(){}}),vR=dr({"src/node_modules/seedrandom/lib/alea.js"(e,t){(function(r,n,a){function s(u){var d=this,h=l();d.next=function(){var p=2091639*d.s0+d.c*23283064365386963e-26;return d.s0=d.s1,d.s1=d.s2,d.s2=p-(d.c=p|0)},d.c=1,d.s0=h(" "),d.s1=h(" "),d.s2=h(" "),d.s0-=h(u),d.s0<0&&(d.s0+=1),d.s1-=h(u),d.s1<0&&(d.s1+=1),d.s2-=h(u),d.s2<0&&(d.s2+=1),h=null}function i(u,d){return d.c=u.c,d.s0=u.s0,d.s1=u.s1,d.s2=u.s2,d}function o(u,d){var h=new s(u),p=d&&d.state,c=h.next;return c.int32=function(){return h.next()*4294967296|0},c.double=function(){return c()+(c()*2097152|0)*11102230246251565e-32},c.quick=c,p&&(typeof p=="object"&&i(p,h),c.state=function(){return i(h,{})}),c}function l(){var u=4022871197,d=function(h){h=String(h);for(var p=0;p<h.length;p++){u+=h.charCodeAt(p);var c=.02519603282416938*u;u=c>>>0,c-=u,c*=u,u=c>>>0,c-=u,u+=c*4294967296}return(u>>>0)*23283064365386963e-26};return d}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.alea=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),wR=dr({"src/node_modules/seedrandom/lib/xor128.js"(e,t){(function(r,n,a){function s(l){var u=this,d="";u.x=0,u.y=0,u.z=0,u.w=0,u.next=function(){var p=u.x^u.x<<11;return u.x=u.y,u.y=u.z,u.z=u.w,u.w^=u.w>>>19^p^p>>>8},l===(l|0)?u.x=l:d+=l;for(var h=0;h<d.length+64;h++)u.x^=d.charCodeAt(h)|0,u.next()}function i(l,u){return u.x=l.x,u.y=l.y,u.z=l.z,u.w=l.w,u}function o(l,u){var d=new s(l),h=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,h&&(typeof h=="object"&&i(h,d),p.state=function(){return i(d,{})}),p}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.xor128=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),kR=dr({"src/node_modules/seedrandom/lib/xorwow.js"(e,t){(function(r,n,a){function s(l){var u=this,d="";u.next=function(){var p=u.x^u.x>>>2;return u.x=u.y,u.y=u.z,u.z=u.w,u.w=u.v,(u.d=u.d+362437|0)+(u.v=u.v^u.v<<4^(p^p<<1))|0},u.x=0,u.y=0,u.z=0,u.w=0,u.v=0,l===(l|0)?u.x=l:d+=l;for(var h=0;h<d.length+64;h++)u.x^=d.charCodeAt(h)|0,h==d.length&&(u.d=u.x<<10^u.x>>>4),u.next()}function i(l,u){return u.x=l.x,u.y=l.y,u.z=l.z,u.w=l.w,u.v=l.v,u.d=l.d,u}function o(l,u){var d=new s(l),h=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,h&&(typeof h=="object"&&i(h,d),p.state=function(){return i(d,{})}),p}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.xorwow=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),IR=dr({"src/node_modules/seedrandom/lib/xorshift7.js"(e,t){(function(r,n,a){function s(l){var u=this;u.next=function(){var h=u.x,p=u.i,c,m,f;return c=h[p],c^=c>>>7,m=c^c<<24,c=h[p+1&7],m^=c^c>>>10,c=h[p+3&7],m^=c^c>>>3,c=h[p+4&7],m^=c^c<<7,c=h[p+7&7],c=c^c<<13,m^=c^c<<9,h[p]=m,u.i=p+1&7,m};function d(h,p){var c,m,f=[];if(p===(p|0))m=f[0]=p;else for(p=""+p,c=0;c<p.length;++c)f[c&7]=f[c&7]<<15^p.charCodeAt(c)+f[c+1&7]<<13;for(;f.length<8;)f.push(0);for(c=0;c<8&&f[c]===0;++c);for(c==8?m=f[7]=-1:m=f[c],h.x=f,h.i=0,c=256;c>0;--c)h.next()}d(u,l)}function i(l,u){return u.x=l.x.slice(),u.i=l.i,u}function o(l,u){l==null&&(l=+new Date);var d=new s(l),h=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,h&&(h.x&&i(h,d),p.state=function(){return i(d,{})}),p}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.xorshift7=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),SR=dr({"src/node_modules/seedrandom/lib/xor4096.js"(e,t){(function(r,n,a){function s(l){var u=this;u.next=function(){var h=u.w,p=u.X,c=u.i,m,f;return u.w=h=h+1640531527|0,f=p[c+34&127],m=p[c=c+1&127],f^=f<<13,m^=m<<17,f^=f>>>15,m^=m>>>12,f=p[c]=f^m,u.i=c,f+(h^h>>>16)|0};function d(h,p){var c,m,f,g,y,A=[],x=128;for(p===(p|0)?(m=p,p=null):(p=p+"\0",m=0,x=Math.max(x,p.length)),f=0,g=-32;g<x;++g)p&&(m^=p.charCodeAt((g+32)%p.length)),g===0&&(y=m),m^=m<<10,m^=m>>>15,m^=m<<4,m^=m>>>13,g>=0&&(y=y+1640531527|0,c=A[g&127]^=m+y,f=c==0?f+1:0);for(f>=128&&(A[(p&&p.length||0)&127]=-1),f=127,g=4*128;g>0;--g)m=A[f+34&127],c=A[f=f+1&127],m^=m<<13,c^=c<<17,m^=m>>>15,c^=c>>>12,A[f]=m^c;h.w=y,h.X=A,h.i=f}d(u,l)}function i(l,u){return u.i=l.i,u.w=l.w,u.X=l.X.slice(),u}function o(l,u){l==null&&(l=+new Date);var d=new s(l),h=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,h&&(h.X&&i(h,d),p.state=function(){return i(d,{})}),p}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.xor4096=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),CR=dr({"src/node_modules/seedrandom/lib/tychei.js"(e,t){(function(r,n,a){function s(l){var u=this,d="";u.next=function(){var p=u.b,c=u.c,m=u.d,f=u.a;return p=p<<25^p>>>7^c,c=c-m|0,m=m<<24^m>>>8^f,f=f-p|0,u.b=p=p<<20^p>>>12^c,u.c=c=c-m|0,u.d=m<<16^c>>>16^f,u.a=f-p|0},u.a=0,u.b=0,u.c=-1640531527,u.d=1367130551,l===Math.floor(l)?(u.a=l/4294967296|0,u.b=l|0):d+=l;for(var h=0;h<d.length+20;h++)u.b^=d.charCodeAt(h)|0,u.next()}function i(l,u){return u.a=l.a,u.b=l.b,u.c=l.c,u.d=l.d,u}function o(l,u){var d=new s(l),h=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,h&&(typeof h=="object"&&i(h,d),p.state=function(){return i(d,{})}),p}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.tychei=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),TR=dr({"(disabled):crypto"(){}}),NR=dr({"src/node_modules/seedrandom/seedrandom.js"(e,t){(function(r,n,a){var s=256,i=6,o=52,l="random",u=a.pow(s,i),d=a.pow(2,o),h=d*2,p=s-1,c;function m(w,I,T){var E=[];I=I==!0?{entropy:!0}:I||{};var R=A(y(I.entropy?[w,b(n)]:w==null?x():w,3),E),F=new f(E),$=function(){for(var S=F.g(i),z=u,O=0;S<d;)S=(S+O)*s,z*=s,O=F.g(1);for(;S>=h;)S/=2,z/=2,O>>>=1;return(S+O)/z};return $.int32=function(){return F.g(4)|0},$.quick=function(){return F.g(4)/4294967296},$.double=$,A(b(F.S),n),(I.pass||T||function(S,z,O,j){return j&&(j.S&&g(j,F),S.state=function(){return g(F,{})}),O?(a[l]=S,z):S})($,R,"global"in I?I.global:this==a,I.state)}function f(w){var I,T=w.length,E=this,R=0,F=E.i=E.j=0,$=E.S=[];for(T||(w=[T++]);R<s;)$[R]=R++;for(R=0;R<s;R++)$[R]=$[F=p&F+w[R%T]+(I=$[R])],$[F]=I;(E.g=function(S){for(var z,O=0,j=E.i,K=E.j,D=E.S;S--;)z=D[j=p&j+1],O=O*s+D[p&(D[j]=D[K=p&K+z])+(D[K]=z)];return E.i=j,E.j=K,O})(s)}function g(w,I){return I.i=w.i,I.j=w.j,I.S=w.S.slice(),I}function y(w,I){var T=[],E=typeof w,R;if(I&&E=="object")for(R in w)try{T.push(y(w[R],I-1))}catch(F){}return T.length?T:E=="string"?w:w+"\0"}function A(w,I){for(var T=w+"",E,R=0;R<T.length;)I[p&R]=p&(E^=I[p&R]*19)+T.charCodeAt(R++);return b(I)}function x(){try{var w;return c&&(w=c.randomBytes)?w=w(s):(w=new Uint8Array(s),(r.crypto||r.msCrypto).getRandomValues(w)),b(w)}catch(E){var I=r.navigator,T=I&&I.plugins;return[+new Date,r,T,r.screen,b(n)]}}function b(w){return String.fromCharCode.apply(0,w)}if(A(a.random(),n),typeof t=="object"&&t.exports){t.exports=m;try{c=TR()}catch(w){}}else typeof define=="function"&&define.amd?define(function(){return m}):a["seed"+l]=m})(typeof self!="undefined"?self:e,[],Math)}}),sf=dr({"src/node_modules/seedrandom/index.js"(e,t){var r=vR(),n=wR(),a=kR(),s=IR(),i=SR(),o=CR(),l=NR();l.alea=r,l.xor128=n,l.xorwow=a,l.xorshift7=s,l.xor4096=i,l.tychei=o,t.exports=l}}),O7=dr({"(disabled):src/node_modules/string_decoder/index.js"(){}}),Ty=dr({"(disabled):fs"(){}}),I0=dr({"(disabled):path"(){}}),ER=dr({"(disabled):worker_threads"(){}}),RR=dr({"(disabled):perf_hooks"(){}}),$R=dr({"(disabled):os"(){}}),MR=dr({"src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm-threaded-simd.js"(e,t){var r=(()=>{var n=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(n=n||__filename),function(a){a=a||{};function s(){return Fe.buffer!=Or&&ra(Fe.buffer),Ac}function i(){return Fe.buffer!=Or&&ra(Fe.buffer),xc}function o(){return Fe.buffer!=Or&&ra(Fe.buffer),pp}function l(){return Fe.buffer!=Or&&ra(Fe.buffer),bc}function u(){return Fe.buffer!=Or&&ra(Fe.buffer),vc}function d(){return Fe.buffer!=Or&&ra(Fe.buffer),wc}function h(){return Fe.buffer!=Or&&ra(Fe.buffer),kc}var p=typeof a!="undefined"?a:{},c,m;p.ready=new Promise(function(N,_){c=N,m=_});var f;typeof process!="undefined"&&process.listeners&&(f={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var g=Object.assign({},p),y=[],A="./this.program",x=(N,_)=>{throw _},b=typeof window=="object",w=typeof importScripts=="function",I=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",T=p.ENVIRONMENT_IS_PTHREAD||!1,E="";function R(N){return p.locateFile?p.locateFile(N,E):E+N}var F,$,S,z;function O(N){N instanceof bp||Q("exiting due to exception: "+N)}var j,K,D;if(I){w?E=I0().dirname(E)+"/":E=__dirname+"/",D=()=>{K||(j=Ty(),K=I0())},F=function(_,G){return D(),_=K.normalize(_),j.readFileSync(_,G?void 0:"utf8")},S=_=>{var G=F(_,!0);return G.buffer||(G=new Uint8Array(G)),G},$=(_,G,te)=>{D(),_=K.normalize(_),j.readFile(_,function(ge,xe){ge?te(ge):G(xe.buffer)})},process.argv.length>1&&(A=process.argv[1].replace(/\\/g,"/")),y=process.argv.slice(2),process.on("uncaughtException",function(_){if(!(_ instanceof bp))throw _}),process.on("unhandledRejection",function(_){throw _}),x=(_,G)=>{if(uo())throw process.exitCode=_,G;O(G),process.exit(_)},p.inspect=function(){return"[Emscripten Module object]"};let N;try{N=ER()}catch(_){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),_}global.Worker=N.Worker}else(b||w)&&(w?E=self.location.href:typeof document!="undefined"&&document.currentScript&&(E=document.currentScript.src),typeof n!="undefined"&&n&&(E=n),E.indexOf("blob:")!==0?E=E.substr(0,E.replace(/[?#].*/,"").lastIndexOf("/")+1):E="",I||(F=N=>{var _=new XMLHttpRequest;return _.open("GET",N,!1),_.send(null),_.responseText},w&&(S=N=>{var _=new XMLHttpRequest;return _.open("GET",N,!1),_.responseType="arraybuffer",_.send(null),new Uint8Array(_.response)}),$=(N,_,G)=>{var te=new XMLHttpRequest;te.open("GET",N,!0),te.responseType="arraybuffer",te.onload=()=>{if(te.status==200||te.status==0&&te.response){_(te.response);return}G()},te.onerror=G,te.send(null)}),z=N=>document.title=N);I&&typeof performance=="undefined"&&(global.performance=RR().performance);var Y=console.log.bind(console),V=console.warn.bind(console);I&&(D(),Y=N=>j.writeSync(1,N+`
|
|
`),V=N=>j.writeSync(2,N+`
|
|
`));var re=p.print||Y,Q=p.printErr||V;Object.assign(p,g),g=null,p.arguments&&(y=p.arguments),p.thisProgram&&(A=p.thisProgram),p.quit&&(x=p.quit);var ie=4;function J(N){J.shown||(J.shown={}),J.shown[N]||(J.shown[N]=1,Q(N))}function ae(N,_){if(typeof WebAssembly.Function=="function"){for(var G={i:"i32",j:"i64",f:"f32",d:"f64"},te={parameters:[],results:_[0]=="v"?[]:[G[_[0]]]},ge=1;ge<_.length;++ge)te.parameters.push(G[_[ge]]);return new WebAssembly.Function(te,N)}var xe=[1,0,1,96],Te=_.slice(0,1),Pe=_.slice(1),Pt={i:127,j:126,f:125,d:124};xe.push(Pe.length);for(var ge=0;ge<Pe.length;++ge)xe.push(Pt[Pe[ge]]);Te=="v"?xe.push(0):xe=xe.concat([1,Pt[Te]]),xe[1]=xe.length-2;var ia=new Uint8Array([0,97,115,109,1,0,0,0].concat(xe,[2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0])),oa=new WebAssembly.Module(ia),Jc=new WebAssembly.Instance(oa,{e:{f:N}}),vp=Jc.exports.f;return vp}var de=[],be;function ve(){if(de.length)return de.pop();try{Sn.grow(1)}catch(N){throw N instanceof RangeError?"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.":N}return Sn.length-1}function Ee(N,_){for(var G=N;G<N+_;G++){var te=su(G);te&&be.set(te,G)}}var $e=0,ze=N=>{$e=N},We=Atomics.load,Ke=Atomics.store,ot=Atomics.compareExchange,pt;p.wasmBinary&&(pt=p.wasmBinary);var ht=p.noExitRuntime||!0;typeof WebAssembly!="object"&&ru("no native wasm support detected");var Fe,wt,xt=!1,Pr;function hr(N,_){N||ru(_)}function Qr(N){var _=p["_"+N];return _}function rr(N,_,G,te,ge){var xe={string:function(Cn){var hu=0;if(Cn!=null&&Cn!==0){var Gb=(Cn.length<<2)+1;hu=pu(Gb),oo(Cn,hu,Gb)}return hu},array:function(Cn){var hu=pu(Cn.length);return Ga(Cn,hu),hu}};function Te(Cn){return _==="string"?In(Cn):_==="boolean"?Boolean(Cn):Cn}var Pe=Qr(N),Pt=[],ia=0;if(te)for(var oa=0;oa<te.length;oa++){var Jc=xe[G[oa]];Jc?(ia===0&&(ia=dg()),Pt[oa]=Jc(te[oa])):Pt[oa]=te[oa]}var vp=Pe.apply(null,Pt);function sR(Cn){return ia!==0&&Xc(ia),Te(Cn)}return vp=sR(vp),vp}function cr(N,_,G,te){G=G||[];var ge=G.every(function(Te){return Te==="number"}),xe=_!=="string";return xe&&ge&&!te?Qr(N):function(){return rr(N,_,G,arguments,te)}}var ta=1;function en(N){var _=new TextDecoder(N);this.decode=G=>(G.buffer instanceof SharedArrayBuffer&&(G=new Uint8Array(G)),_.decode.call(_,G))}var nr=typeof TextDecoder!="undefined"?new en("utf8"):void 0;function kn(N,_,G){for(var te=_+G,ge=_;N[ge]&&!(ge>=te);)++ge;if(ge-_>16&&N.subarray&&nr)return nr.decode(N.subarray(_,ge));for(var xe="";_<ge;){var Te=N[_++];if(!(Te&128)){xe+=String.fromCharCode(Te);continue}var Pe=N[_++]&63;if((Te&224)==192){xe+=String.fromCharCode((Te&31)<<6|Pe);continue}var Pt=N[_++]&63;if((Te&240)==224?Te=(Te&15)<<12|Pe<<6|Pt:Te=(Te&7)<<18|Pe<<12|Pt<<6|N[_++]&63,Te<65536)xe+=String.fromCharCode(Te);else{var ia=Te-65536;xe+=String.fromCharCode(55296|ia>>10,56320|ia&1023)}}return xe}function In(N,_){return N?kn(i(),N,_):""}function ys(N,_,G,te){if(!(te>0))return 0;for(var ge=G,xe=G+te-1,Te=0;Te<N.length;++Te){var Pe=N.charCodeAt(Te);if(Pe>=55296&&Pe<=57343){var Pt=N.charCodeAt(++Te);Pe=65536+((Pe&1023)<<10)|Pt&1023}if(Pe<=127){if(G>=xe)break;_[G++]=Pe}else if(Pe<=2047){if(G+1>=xe)break;_[G++]=192|Pe>>6,_[G++]=128|Pe&63}else if(Pe<=65535){if(G+2>=xe)break;_[G++]=224|Pe>>12,_[G++]=128|Pe>>6&63,_[G++]=128|Pe&63}else{if(G+3>=xe)break;_[G++]=240|Pe>>18,_[G++]=128|Pe>>12&63,_[G++]=128|Pe>>6&63,_[G++]=128|Pe&63}}return _[G]=0,G-ge}function oo(N,_,G){return ys(N,i(),_,G)}function yc(N){for(var _=0,G=0;G<N.length;++G){var te=N.charCodeAt(G);te>=55296&&te<=57343&&(te=65536+((te&1023)<<10)|N.charCodeAt(++G)&1023),te<=127?++_:te<=2047?_+=2:te<=65535?_+=3:_+=4}return _}var As=typeof TextDecoder!="undefined"?new en("utf-16le"):void 0;function Ga(N,_){s().set(N,_)}function dp(N,_,G){for(var te=0;te<N.length;++te)s()[_++>>0]=N.charCodeAt(te);G||(s()[_>>0]=0)}function eu(N,_){return N%_>0&&(N+=_-N%_),N}var Or,Ac,xc,pp,bc,vc,Ib,wc,kc;T&&(Or=p.buffer);function ra(N){Or=N,p.HEAP8=Ac=new Int8Array(N),p.HEAP16=pp=new Int16Array(N),p.HEAP32=vc=new Int32Array(N),p.HEAPU8=xc=new Uint8Array(N),p.HEAPU16=bc=new Uint16Array(N),p.HEAPU32=Ib=new Uint32Array(N),p.HEAPF32=wc=new Float32Array(N),p.HEAPF64=kc=new Float64Array(N)}var Ic=p.INITIAL_MEMORY||16777216;if(T)Fe=p.wasmMemory,Or=p.buffer;else if(p.wasmMemory)Fe=p.wasmMemory;else if(Fe=new WebAssembly.Memory({initial:Ic/65536,maximum:32768,shared:!0}),!(Fe.buffer instanceof SharedArrayBuffer))throw Q("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"),I&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");Fe&&(Or=Fe.buffer),Ic=Or.byteLength,ra(Or);var Sn,tu=[],xs=[],M1=[],Sc=[],lo=!1,F1=!1,Cc=0;function uo(){return ht||Cc>0}function zr(){if(p.preRun)for(typeof p.preRun=="function"&&(p.preRun=[p.preRun]);p.preRun.length;)Sb(p.preRun.shift());$c(tu)}function hp(){lo=!0,!T&&$c(xs)}function _1(){T||(Oe.terminateAllThreads(),F1=!0)}function P1(){if(!T){if(p.postRun)for(typeof p.postRun=="function"&&(p.postRun=[p.postRun]);p.postRun.length;)cp(p.postRun.shift());$c(Sc)}}function Sb(N){tu.unshift(N)}function Cb(N){xs.unshift(N)}function cp(N){Sc.unshift(N)}var bs=0,Tc=null,na=null;function fp(N){bs++,p.monitorRunDependencies&&p.monitorRunDependencies(bs)}function Tb(N){if(bs--,p.monitorRunDependencies&&p.monitorRunDependencies(bs),bs==0&&(Tc!==null&&(clearInterval(Tc),Tc=null),na)){var _=na;na=null,_()}}p.preloadedImages={},p.preloadedAudios={};function ru(N){T?postMessage({cmd:"onAbort",arg:N}):p.onAbort&&p.onAbort(N),N="Aborted("+N+")",Q(N),xt=!0,Pr=1,N+=". Build with -s ASSERTIONS=1 for more info.";var _=new WebAssembly.RuntimeError(N);throw m(_),_}var O1="data:application/octet-stream;base64,";function Nc(N){return N.startsWith(O1)}function Ec(N){return N.startsWith("file://")}var Dr;Dr="tfjs-backend-wasm-threaded-simd.wasm",Nc(Dr)||(Dr=R(Dr));function Rc(N){try{if(N==Dr&&pt)return new Uint8Array(pt);if(S)return S(N);throw"both async and sync fetching of the wasm failed"}catch(_){ru(_)}}function nu(){if(!pt&&(b||w)){if(typeof fetch=="function"&&!Ec(Dr))return fetch(Dr,{credentials:"same-origin"}).then(function(N){if(!N.ok)throw"failed to load wasm binary file at '"+Dr+"'";return N.arrayBuffer()}).catch(function(){return Rc(Dr)});if($)return new Promise(function(N,_){$(Dr,function(G){N(new Uint8Array(G))},_)})}return Promise.resolve().then(function(){return Rc(Dr)})}function z1(){var N={env:Uc,wasi_snapshot_preview1:Uc};function _(Te,Pe){var Pt=Te.exports;if(p.asm=Pt,G1(p.asm.emscripten_tls_init),Sn=p.asm.__indirect_function_table,Cb(p.asm.__wasm_call_ctors),wt=Pe,!T){var ia=Oe.unusedWorkers.length;Oe.unusedWorkers.forEach(function(oa){Oe.loadWasmModuleToWorker(oa,function(){--ia||Tb("wasm-instantiate")})})}}T||fp("wasm-instantiate");function G(Te){_(Te.instance,Te.module)}function te(Te){return nu().then(function(Pe){return WebAssembly.instantiate(Pe,N)}).then(function(Pe){return Pe}).then(Te,function(Pe){Q("failed to asynchronously prepare wasm: "+Pe),ru(Pe)})}function ge(){return!pt&&typeof WebAssembly.instantiateStreaming=="function"&&!Nc(Dr)&&!Ec(Dr)&&typeof fetch=="function"?fetch(Dr,{credentials:"same-origin"}).then(function(Te){var Pe=WebAssembly.instantiateStreaming(Te,N);return Pe.then(G,function(Pt){return Q("wasm streaming compile failed: "+Pt),Q("falling back to ArrayBuffer instantiation"),te(G)})}):te(G)}if(p.instantiateWasm)try{var xe=p.instantiateWasm(N,_);return xe}catch(Te){return Q("Module.instantiateWasm callback failed with error: "+Te),!1}return ge().catch(m),{}}var Nb,Eb,D1={};function $c(N){for(;N.length>0;){var _=N.shift();if(typeof _=="function"){_(p);continue}var G=_.func;typeof G=="number"?_.arg===void 0?su(G)():su(G)(_.arg):G(_.arg===void 0?null:_.arg)}}function au(N){var _=dg(),G=N();return Xc(_),G}function cE(N){return N}function Rb(N){var _=/\b_Z[\w\d_]+/g;return N.replace(_,function(G){var te=G;return G===te?G:te+" ["+G+"]"})}function L1(N){u()[N>>2]=0;var _=Oe.pthreads[N];delete Oe.pthreads[N],_.worker.terminate(),ug(N),Oe.runningWorkers.splice(Oe.runningWorkers.indexOf(_.worker),1),_.worker.pthread=void 0}function B1(N){var _=Oe.pthreads[N];_.worker.postMessage({cmd:"cancel"})}function Mc(N){var _=Oe.pthreads[N];if(_){u()[N>>2]=0;var G=_.worker;Oe.returnWorkerToPool(G)}}function Fc(N){rR(N)}function W1(N){if(N instanceof bp||N=="unwind")return Pr;x(1,N)}var Oe={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],init:function(){T?Oe.initWorker():Oe.initMainThread()},initMainThread:function(){for(var N=8,_=0;_<N;++_)Oe.allocateUnusedWorker()},initWorker:function(){ht=!1},pthreads:{},setExitStatus:function(N){Pr=N},terminateAllThreads:function(){for(var N in Oe.pthreads){var _=Oe.pthreads[N];_&&_.worker&&Oe.returnWorkerToPool(_.worker)}for(var G=0;G<Oe.unusedWorkers.length;++G){var te=Oe.unusedWorkers[G];te.terminate()}Oe.unusedWorkers=[]},returnWorkerToPool:function(N){Oe.runWithoutMainThreadQueuedCalls(function(){delete Oe.pthreads[N.pthread.threadInfoStruct],Oe.unusedWorkers.push(N),Oe.runningWorkers.splice(Oe.runningWorkers.indexOf(N),1),ug(N.pthread.threadInfoStruct),N.pthread=void 0})},runWithoutMainThreadQueuedCalls:function(N){u()[Ub>>2]=0;try{N()}finally{u()[Ub>>2]=1}},receiveObjectTransfer:function(N){},threadInit:function(){for(var N in Oe.tlsInitFunctions)Oe.tlsInitFunctions[N]()},loadWasmModuleToWorker:function(N,_){N.onmessage=G=>{var te=G.data,ge=te.cmd;if(N.pthread&&(Oe.currentProxiedOperationCallerThread=N.pthread.threadInfoStruct),te.targetThread&&te.targetThread!=qc()){var xe=Oe.pthreads[te.targetThread];xe?xe.worker.postMessage(te,te.transferList):Q('Internal error! Worker sent a message "'+ge+'" to target pthread '+te.targetThread+", but that thread no longer exists!"),Oe.currentProxiedOperationCallerThread=void 0;return}ge==="processQueuedMainThreadWork"?Db():ge==="spawnThread"?Pc(te):ge==="cleanupThread"?Mc(te.thread):ge==="killThread"?L1(te.thread):ge==="cancelThread"?B1(te.thread):ge==="loaded"?(N.loaded=!0,_&&_(N),N.runPthread&&(N.runPthread(),delete N.runPthread)):ge==="print"?re("Thread "+te.threadId+": "+te.text):ge==="printErr"?Q("Thread "+te.threadId+": "+te.text):ge==="alert"?alert("Thread "+te.threadId+": "+te.text):te.target==="setimmediate"?N.postMessage(te):ge==="onAbort"?p.onAbort&&p.onAbort(te.arg):Q("worker sent an unknown command "+ge),Oe.currentProxiedOperationCallerThread=void 0},N.onerror=G=>{var te="worker sent an error!";throw Q(te+" "+G.filename+":"+G.lineno+": "+G.message),G},I&&(N.on("message",function(G){N.onmessage({data:G})}),N.on("error",function(G){N.onerror(G)}),N.on("detachedExit",function(){})),N.postMessage({cmd:"load",urlOrBlob:p.mainScriptUrlOrBlob||n,wasmMemory:Fe,wasmModule:wt})},allocateUnusedWorker:function(){var N=R("tfjs-backend-wasm-threaded-simd.worker.js");Oe.unusedWorkers.push(new Worker(N))},getNewWorker:function(){return Oe.unusedWorkers.length==0&&(Oe.allocateUnusedWorker(),Oe.loadWasmModuleToWorker(Oe.unusedWorkers[0])),Oe.unusedWorkers.pop()}};function V1(){var N=qc(),_=u()[N+44>>2],G=u()[N+48>>2],te=_-G;Vb(_,te),Xc(_)}p.establishStackSpace=V1;function _c(N){if(T)return co(1,0,N);try{Fc(N)}catch(_){W1(_)}}var po=[];function su(N){var _=po[N];return _||(N>=po.length&&(po.length=N+1),po[N]=_=Sn.get(N)),_}function U1(N,_){return su(N)(_)}p.invokeEntryPoint=U1;function $b(){var N=new Error;if(!N.stack){try{throw new Error}catch(_){N=_}if(!N.stack)return"(no stack trace available)"}return N.stack.toString()}function G1(N,_,G){Oe.tlsInitFunctions.push(N)}function Mb(N,_){Sn.set(N,_),po[N]=_}var ho;I?ho=()=>{var N=process.hrtime();return N[0]*1e3+N[1]/1e6}:T?ho=()=>performance.now()-p.__performance_now_clock_drift:ho=()=>performance.now();var j1=!0;function H1(N){return u()[zb()>>2]=N,N}function q1(N,_){var G;if(N===0)G=Date.now();else if((N===1||N===4)&&j1)G=ho();else return H1(28),-1;return u()[_>>2]=G/1e3|0,u()[_+4>>2]=G%1e3*1e3*1e3|0,0}function X1(N,_){return q1(N,_)}function K1(N){Lb(N,!w,1,!b),Oe.threadInit()}function Z1(N){T?postMessage({cmd:"cleanupThread",thread:N}):Mc(N)}function Pc(N){var _=Oe.getNewWorker();if(!_)return 6;Oe.runningWorkers.push(_);var G=Oe.pthreads[N.pthread_ptr]={worker:_,threadInfoStruct:N.pthread_ptr};_.pthread=G;var te={cmd:"run",start_routine:N.startRoutine,arg:N.arg,threadInfoStruct:N.pthread_ptr};return _.runPthread=()=>{te.time=performance.now(),_.postMessage(te,N.transferList)},_.loaded&&(_.runPthread(),delete _.runPthread),0}function Y1(N,_,G,te){if(typeof SharedArrayBuffer=="undefined")return Q("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var ge=[],xe=0;if(T&&(ge.length===0||xe))return Bb(687865856,N,_,G,te);if(xe)return xe;var Te={startRoutine:G,pthread_ptr:N,arg:te,transferList:ge};return T?(Te.cmd="spawnThread",postMessage(Te,ge),0):Pc(Te)}function J1(){return 2097152}function Q1(N,_){if(N==_)postMessage({cmd:"processQueuedMainThreadWork"});else if(T)postMessage({targetThread:N,cmd:"processThreadQueue"});else{var G=Oe.pthreads[N],te=G&&G.worker;if(!te)return;te.postMessage({cmd:"processThreadQueue"})}return 1}function e2(){ru("")}function t2(){I||w||J("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function Oc(){return 2147483648}function r2(N,_,G){i().copyWithin(N,_,_+G)}function n2(){return I?$R().cpus().length:navigator.hardwareConcurrency}function co(N,_){var G=arguments.length-2,te=arguments;return au(function(){for(var ge=G,xe=pu(ge*8),Te=xe>>3,Pe=0;Pe<G;Pe++){var Pt=te[2+Pe];h()[Te+Pe]=Pt}return Wb(N,ge,xe,_)})}var mp=[];function a2(N,_,G){mp.length=_;for(var te=G>>3,ge=0;ge<_;ge++)mp[ge]=h()[te+ge];var xe=N<0,Te=xe?D1[-N-1]:k2[N];return Te.apply(null,mp)}function s2(N){try{return Fe.grow(N-Or.byteLength+65535>>>16),ra(Fe.buffer),1}catch(_){}}function i2(N){var _=i().length;if(N=N>>>0,N<=_)return!1;var G=Oc();if(N>G)return!1;for(var te=1;te<=4;te*=2){var ge=_*(1+.2/te);ge=Math.min(ge,N+100663296);var xe=Math.min(G,eu(Math.max(N,ge),65536)),Te=s2(xe);if(Te)return!0}return!1}var Xe={inEventHandler:0,removeAllEventListeners:function(){for(var N=Xe.eventHandlers.length-1;N>=0;--N)Xe._removeHandler(N);Xe.eventHandlers=[],Xe.deferredCalls=[]},registerRemoveEventListeners:function(){Xe.removeEventListenersRegistered||(M1.push(Xe.removeAllEventListeners),Xe.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(N,_,G){function te(Te,Pe){if(Te.length!=Pe.length)return!1;for(var Pt in Te)if(Te[Pt]!=Pe[Pt])return!1;return!0}for(var ge in Xe.deferredCalls){var xe=Xe.deferredCalls[ge];if(xe.targetFunction==N&&te(xe.argsList,G))return}Xe.deferredCalls.push({targetFunction:N,precedence:_,argsList:G}),Xe.deferredCalls.sort(function(Te,Pe){return Te.precedence<Pe.precedence})},removeDeferredCalls:function(N){for(var _=0;_<Xe.deferredCalls.length;++_)Xe.deferredCalls[_].targetFunction==N&&(Xe.deferredCalls.splice(_,1),--_)},canPerformEventHandlerRequests:function(){return Xe.inEventHandler&&Xe.currentEventHandler.allowsDeferredCalls},runDeferredCalls:function(){if(Xe.canPerformEventHandlerRequests())for(var N=0;N<Xe.deferredCalls.length;++N){var _=Xe.deferredCalls[N];Xe.deferredCalls.splice(N,1),--N,_.targetFunction.apply(null,_.argsList)}},eventHandlers:[],removeAllHandlersOnTarget:function(N,_){for(var G=0;G<Xe.eventHandlers.length;++G)Xe.eventHandlers[G].target==N&&(!_||_==Xe.eventHandlers[G].eventTypeString)&&Xe._removeHandler(G--)},_removeHandler:function(N){var _=Xe.eventHandlers[N];_.target.removeEventListener(_.eventTypeString,_.eventListenerFunc,_.useCapture),Xe.eventHandlers.splice(N,1)},registerOrRemoveHandler:function(N){var _=function(te){++Xe.inEventHandler,Xe.currentEventHandler=N,Xe.runDeferredCalls(),N.handlerFunc(te),Xe.runDeferredCalls(),--Xe.inEventHandler};if(N.callbackfunc)N.eventListenerFunc=_,N.target.addEventListener(N.eventTypeString,_,N.useCapture),Xe.eventHandlers.push(N),Xe.registerRemoveEventListeners();else for(var G=0;G<Xe.eventHandlers.length;++G)Xe.eventHandlers[G].target==N.target&&Xe.eventHandlers[G].eventTypeString==N.eventTypeString&&Xe._removeHandler(G--)},queueEventHandlerOnThread_iiii:function(N,_,G,te,ge){au(function(){var xe=pu(12);u()[xe>>2]=G,u()[xe+4>>2]=te,u()[xe+8>>2]=ge,lg(N,637534208,_,te,xe)})},getTargetThreadForEventCallback:function(N){switch(N){case 1:return 0;case 2:return Oe.currentProxiedOperationCallerThread;default:return N}},getNodeNameForTarget:function(N){return N?N==window?"#window":N==screen?"#screen":N&&N.nodeName?N.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function o2(N){var _=yc(N)+1,G=og(_);return oo(N,G,_),G}function l2(N,_,G,te){au(function(){var ge=pu(12),xe=0;_&&(xe=o2(_)),u()[ge>>2]=xe,u()[ge+4>>2]=G,u()[ge+8>>2]=te,lg(N,657457152,0,xe,ge)})}function u2(N,_,G,te){_=_?In(_):"",l2(N,_,G,te)}function d2(N){return N>2?In(N):N}var p2=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function h2(N){N=d2(N);var _=p2[N]||(typeof document!="undefined"?document.querySelector(N):void 0);return _}function gp(N){return h2(N)}function zc(N,_,G){var te=gp(N);if(!te)return-4;if(te.canvasSharedPtr&&(u()[te.canvasSharedPtr>>2]=_,u()[te.canvasSharedPtr+4>>2]=G),te.offscreenCanvas||!te.controlTransferredOffscreen){te.offscreenCanvas&&(te=te.offscreenCanvas);var ge=!1;if(te.GLctxObject&&te.GLctxObject.GLctx){var xe=te.GLctxObject.GLctx.getParameter(2978);ge=xe[0]===0&&xe[1]===0&&xe[2]===te.width&&xe[3]===te.height}te.width=_,te.height=G,ge&&te.GLctxObject.GLctx.viewport(0,0,_,G)}else if(te.canvasSharedPtr){var Te=u()[te.canvasSharedPtr+8>>2];return u2(Te,N,_,G),1}else return-4;return 0}function Dc(N,_,G){return T?co(2,1,N,_,G):zc(N,_,G)}function c2(N,_,G){var te=gp(N);return te?zc(N,_,G):Dc(N,_,G)}function f2(){throw"unwind"}function m2(N){var _=N.getExtension("ANGLE_instanced_arrays");if(_)return N.vertexAttribDivisor=function(G,te){_.vertexAttribDivisorANGLE(G,te)},N.drawArraysInstanced=function(G,te,ge,xe){_.drawArraysInstancedANGLE(G,te,ge,xe)},N.drawElementsInstanced=function(G,te,ge,xe,Te){_.drawElementsInstancedANGLE(G,te,ge,xe,Te)},1}function g2(N){var _=N.getExtension("OES_vertex_array_object");if(_)return N.createVertexArray=function(){return _.createVertexArrayOES()},N.deleteVertexArray=function(G){_.deleteVertexArrayOES(G)},N.bindVertexArray=function(G){_.bindVertexArrayOES(G)},N.isVertexArray=function(G){return _.isVertexArrayOES(G)},1}function y2(N){var _=N.getExtension("WEBGL_draw_buffers");if(_)return N.drawBuffers=function(G,te){_.drawBuffersWEBGL(G,te)},1}function A2(N){return!!(N.multiDrawWebgl=N.getExtension("WEBGL_multi_draw"))}var _t={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},queries:[],stringCache:{},unpackAlignment:4,recordError:function(N){_t.lastError||(_t.lastError=N)},getNewId:function(N){for(var _=_t.counter++,G=N.length;G<_;G++)N[G]=null;return _},getSource:function(N,_,G,te){for(var ge="",xe=0;xe<_;++xe){var Te=te?u()[te+xe*4>>2]:-1;ge+=In(u()[G+xe*4>>2],Te<0?void 0:Te)}return ge},createContext:function(N,_){N.getContextSafariWebGL2Fixed||(N.getContextSafariWebGL2Fixed=N.getContext,N.getContext=function(ge,xe){var Te=N.getContextSafariWebGL2Fixed(ge,xe);return ge=="webgl"==Te instanceof WebGLRenderingContext?Te:null});var G=N.getContext("webgl",_);if(!G)return 0;var te=_t.registerContext(G,_);return te},registerContext:function(N,_){var G=og(8);u()[G+4>>2]=qc();var te={handle:G,attributes:_,version:_.majorVersion,GLctx:N};return N.canvas&&(N.canvas.GLctxObject=te),_t.contexts[G]=te,(typeof _.enableExtensionsByDefault=="undefined"||_.enableExtensionsByDefault)&&_t.initExtensions(te),G},makeContextCurrent:function(N){return _t.currentContext=_t.contexts[N],p.ctx=Vc=_t.currentContext&&_t.currentContext.GLctx,!(N&&!Vc)},getContext:function(N){return _t.contexts[N]},deleteContext:function(N){_t.currentContext===_t.contexts[N]&&(_t.currentContext=null),typeof Xe=="object"&&Xe.removeAllHandlersOnTarget(_t.contexts[N].GLctx.canvas),_t.contexts[N]&&_t.contexts[N].GLctx.canvas&&(_t.contexts[N].GLctx.canvas.GLctxObject=void 0),Ob(_t.contexts[N].handle),_t.contexts[N]=null},initExtensions:function(N){if(N||(N=_t.currentContext),!N.initExtensionsDone){N.initExtensionsDone=!0;var _=N.GLctx;m2(_),g2(_),y2(_),_.disjointTimerQueryExt=_.getExtension("EXT_disjoint_timer_query"),A2(_);var G=_.getSupportedExtensions()||[];G.forEach(function(te){!te.includes("lose_context")&&!te.includes("debug")&&_.getExtension(te)})}}},x2=["default","low-power","high-performance"];function b2(N,_){var G=_>>2,te=u()[G+6],ge={alpha:!!u()[G+0],depth:!!u()[G+1],stencil:!!u()[G+2],antialias:!!u()[G+3],premultipliedAlpha:!!u()[G+4],preserveDrawingBuffer:!!u()[G+5],powerPreference:x2[te],failIfMajorPerformanceCaveat:!!u()[G+7],majorVersion:u()[G+8],minorVersion:u()[G+9],enableExtensionsByDefault:u()[G+10],explicitSwapControl:u()[G+11],proxyContextToMainThread:u()[G+12],renderViaOffscreenBackBuffer:u()[G+13]},xe=gp(N);if(!xe||ge.explicitSwapControl)return 0;var Te=_t.createContext(xe,ge);return Te}function v2(N,_){return b2(N,_)}var iu={mappings:{},buffers:[null,[],[]],printChar:function(N,_){var G=iu.buffers[N];_===0||_===10?((N===1?re:Q)(kn(G,0)),G.length=0):G.push(_)},varargs:void 0,get:function(){iu.varargs+=4;var N=u()[iu.varargs-4>>2];return N},getStr:function(N){var _=In(N);return _},get64:function(N,_){return N}};function Lc(N){return T?co(3,1,N):0}function Bc(N,_,G,te,ge){if(T)return co(4,1,N,_,G,te,ge)}function Wc(N,_,G,te){if(T)return co(5,1,N,_,G,te);for(var ge=0,xe=0;xe<G;xe++){var Te=u()[_>>2],Pe=u()[_+4>>2];_+=8;for(var Pt=0;Pt<Pe;Pt++)iu.printChar(N,i()[Te+Pt]);ge+=Pe}return u()[te>>2]=ge,0}function w2(N){ze(N)}Oe.init();var Vc,k2=[null,_c,Dc,Lc,Bc,Wc],Fb=!1,Uc={__clock_gettime:X1,__emscripten_init_main_thread_js:K1,__emscripten_thread_cleanup:Z1,__pthread_create_js:Y1,_emscripten_default_pthread_stack_size:J1,_emscripten_notify_thread_queue:Q1,abort:e2,emscripten_check_blocking_allowed:t2,emscripten_get_heap_max:Oc,emscripten_get_now:ho,emscripten_memcpy_big:r2,emscripten_num_logical_cores:n2,emscripten_receive_on_main_thread_js:a2,emscripten_resize_heap:i2,emscripten_set_canvas_element_size:c2,emscripten_unwind_to_js_event_loop:f2,emscripten_webgl_create_context:v2,exit:Fc,fd_close:Lc,fd_seek:Bc,fd_write:Wc,memory:Fe||p.wasmMemory,setTempRet0:w2},_b=z1(),I2=p.___wasm_call_ctors=function(){return(I2=p.___wasm_call_ctors=p.asm.__wasm_call_ctors).apply(null,arguments)},S2=p._init=function(){return(S2=p._init=p.asm.init).apply(null,arguments)},C2=p._init_with_threads_count=function(){return(C2=p._init_with_threads_count=p.asm.init_with_threads_count).apply(null,arguments)},T2=p._get_threads_count=function(){return(T2=p._get_threads_count=p.asm.get_threads_count).apply(null,arguments)},N2=p._register_tensor=function(){return(N2=p._register_tensor=p.asm.register_tensor).apply(null,arguments)},E2=p._dispose_data=function(){return(E2=p._dispose_data=p.asm.dispose_data).apply(null,arguments)},R2=p._dispose=function(){return(R2=p._dispose=p.asm.dispose).apply(null,arguments)},$2=p._Abs=function(){return($2=p._Abs=p.asm.Abs).apply(null,arguments)},M2=p._Add=function(){return(M2=p._Add=p.asm.Add).apply(null,arguments)},F2=p._AddN=function(){return(F2=p._AddN=p.asm.AddN).apply(null,arguments)},_2=p._All=function(){return(_2=p._All=p.asm.All).apply(null,arguments)},P2=p._Any=function(){return(P2=p._Any=p.asm.Any).apply(null,arguments)},O2=p._ArgMax=function(){return(O2=p._ArgMax=p.asm.ArgMax).apply(null,arguments)},z2=p._AvgPool=function(){return(z2=p._AvgPool=p.asm.AvgPool).apply(null,arguments)},D2=p._BatchMatMul=function(){return(D2=p._BatchMatMul=p.asm.BatchMatMul).apply(null,arguments)},L2=p._Ceil=function(){return(L2=p._Ceil=p.asm.Ceil).apply(null,arguments)},B2=p._ClipByValue=function(){return(B2=p._ClipByValue=p.asm.ClipByValue).apply(null,arguments)},W2=p._Conv2D=function(){return(W2=p._Conv2D=p.asm.Conv2D).apply(null,arguments)},V2=p._Conv2DBackpropInput=function(){return(V2=p._Conv2DBackpropInput=p.asm.Conv2DBackpropInput).apply(null,arguments)},U2=p._Cos=function(){return(U2=p._Cos=p.asm.Cos).apply(null,arguments)},G2=p._Cosh=function(){return(G2=p._Cosh=p.asm.Cosh).apply(null,arguments)},j2=p._CropAndResize=function(){return(j2=p._CropAndResize=p.asm.CropAndResize).apply(null,arguments)},H2=p._Cumprod=function(){return(H2=p._Cumprod=p.asm.Cumprod).apply(null,arguments)},q2=p._Cumsum=function(){return(q2=p._Cumsum=p.asm.Cumsum).apply(null,arguments)},X2=p._DepthToSpace=function(){return(X2=p._DepthToSpace=p.asm.DepthToSpace).apply(null,arguments)},K2=p._DepthwiseConv2dNative=function(){return(K2=p._DepthwiseConv2dNative=p.asm.DepthwiseConv2dNative).apply(null,arguments)},Z2=p._Elu=function(){return(Z2=p._Elu=p.asm.Elu).apply(null,arguments)},Y2=p._Equal=function(){return(Y2=p._Equal=p.asm.Equal).apply(null,arguments)},J2=p._Exp=function(){return(J2=p._Exp=p.asm.Exp).apply(null,arguments)},Q2=p._FlipLeftRight=function(){return(Q2=p._FlipLeftRight=p.asm.FlipLeftRight).apply(null,arguments)},eg=p._Floor=function(){return(eg=p._Floor=p.asm.Floor).apply(null,arguments)},tg=p._FloorDiv=function(){return(tg=p._FloorDiv=p.asm.FloorDiv).apply(null,arguments)},rg=p._FusedBatchNorm=function(){return(rg=p._FusedBatchNorm=p.asm.FusedBatchNorm).apply(null,arguments)},Gc=p._FusedConv2D=function(){return(Gc=p._FusedConv2D=p.asm.FusedConv2D).apply(null,arguments)},jc=p._FusedDepthwiseConv2D=function(){return(jc=p._FusedDepthwiseConv2D=p.asm.FusedDepthwiseConv2D).apply(null,arguments)},yp=p._Gather=function(){return(yp=p._Gather=p.asm.Gather).apply(null,arguments)},ng=p._GatherNd=function(){return(ng=p._GatherNd=p.asm.GatherNd).apply(null,arguments)},ag=p._Greater=function(){return(ag=p._Greater=p.asm.Greater).apply(null,arguments)},ou=p._GreaterEqual=function(){return(ou=p._GreaterEqual=p.asm.GreaterEqual).apply(null,arguments)},Ap=p._LeakyRelu=function(){return(Ap=p._LeakyRelu=p.asm.LeakyRelu).apply(null,arguments)},xp=p._Less=function(){return(xp=p._Less=p.asm.Less).apply(null,arguments)},Pb=p._LessEqual=function(){return(Pb=p._LessEqual=p.asm.LessEqual).apply(null,arguments)},lu=p._Log=function(){return(lu=p._Log=p.asm.Log).apply(null,arguments)},uu=p._LogicalAnd=function(){return(uu=p._LogicalAnd=p.asm.LogicalAnd).apply(null,arguments)},sg=p._LogicalNot=function(){return(sg=p._LogicalNot=p.asm.LogicalNot).apply(null,arguments)},H=p._LogicalOr=function(){return(H=p._LogicalOr=p.asm.LogicalOr).apply(null,arguments)},ne=p._LogicalXor=function(){return(ne=p._LogicalXor=p.asm.LogicalXor).apply(null,arguments)},ye=p._Max=function(){return(ye=p._Max=p.asm.Max).apply(null,arguments)},Re=p._MaxPool=function(){return(Re=p._MaxPool=p.asm.MaxPool).apply(null,arguments)},lt=p._Maximum=function(){return(lt=p._Maximum=p.asm.Maximum).apply(null,arguments)},ct=p._Mean=function(){return(ct=p._Mean=p.asm.Mean).apply(null,arguments)},Ze=p._Min=function(){return(Ze=p._Min=p.asm.Min).apply(null,arguments)},He=p._Minimum=function(){return(He=p._Minimum=p.asm.Minimum).apply(null,arguments)},qt=p._MirrorPad=function(){return(qt=p._MirrorPad=p.asm.MirrorPad).apply(null,arguments)},aa=p._Multiply=function(){return(aa=p._Multiply=p.asm.Multiply).apply(null,arguments)},sa=p._Neg=function(){return(sa=p._Neg=p.asm.Neg).apply(null,arguments)},du=p._NonMaxSuppressionV3=function(){return(du=p._NonMaxSuppressionV3=p.asm.NonMaxSuppressionV3).apply(null,arguments)},fo=p._NonMaxSuppressionV4=function(){return(fo=p._NonMaxSuppressionV4=p.asm.NonMaxSuppressionV4).apply(null,arguments)},ig=p._NonMaxSuppressionV5=function(){return(ig=p._NonMaxSuppressionV5=p.asm.NonMaxSuppressionV5).apply(null,arguments)},tn=p._NotEqual=function(){return(tn=p._NotEqual=p.asm.NotEqual).apply(null,arguments)},vs=p._OneHot=function(){return(vs=p._OneHot=p.asm.OneHot).apply(null,arguments)},Hc=p._PadV2=function(){return(Hc=p._PadV2=p.asm.PadV2).apply(null,arguments)},fE=p._Pow=function(){return(fE=p._Pow=p.asm.Pow).apply(null,arguments)},mE=p._Prelu=function(){return(mE=p._Prelu=p.asm.Prelu).apply(null,arguments)},gE=p._Prod=function(){return(gE=p._Prod=p.asm.Prod).apply(null,arguments)},yE=p._RealDiv=function(){return(yE=p._RealDiv=p.asm.RealDiv).apply(null,arguments)},AE=p._Relu=function(){return(AE=p._Relu=p.asm.Relu).apply(null,arguments)},xE=p._Relu6=function(){return(xE=p._Relu6=p.asm.Relu6).apply(null,arguments)},bE=p._ResizeBilinear=function(){return(bE=p._ResizeBilinear=p.asm.ResizeBilinear).apply(null,arguments)},vE=p._Reverse=function(){return(vE=p._Reverse=p.asm.Reverse).apply(null,arguments)},wE=p._RotateWithOffset=function(){return(wE=p._RotateWithOffset=p.asm.RotateWithOffset).apply(null,arguments)},kE=p._Round=function(){return(kE=p._Round=p.asm.Round).apply(null,arguments)},IE=p._Rsqrt=function(){return(IE=p._Rsqrt=p.asm.Rsqrt).apply(null,arguments)},SE=p._ScatterNd=function(){return(SE=p._ScatterNd=p.asm.ScatterNd).apply(null,arguments)},CE=p._SelectV2=function(){return(CE=p._SelectV2=p.asm.SelectV2).apply(null,arguments)},TE=p._Sigmoid=function(){return(TE=p._Sigmoid=p.asm.Sigmoid).apply(null,arguments)},NE=p._Sin=function(){return(NE=p._Sin=p.asm.Sin).apply(null,arguments)},EE=p._Softmax=function(){return(EE=p._Softmax=p.asm.Softmax).apply(null,arguments)},RE=p._SparseFillEmptyRows=function(){return(RE=p._SparseFillEmptyRows=p.asm.SparseFillEmptyRows).apply(null,arguments)},$E=p._SparseReshape=function(){return($E=p._SparseReshape=p.asm.SparseReshape).apply(null,arguments)},ME=p._SparseSegmentReduction=function(){return(ME=p._SparseSegmentReduction=p.asm.SparseSegmentReduction).apply(null,arguments)},FE=p._Sqrt=function(){return(FE=p._Sqrt=p.asm.Sqrt).apply(null,arguments)},_E=p._Square=function(){return(_E=p._Square=p.asm.Square).apply(null,arguments)},PE=p._SquaredDifference=function(){return(PE=p._SquaredDifference=p.asm.SquaredDifference).apply(null,arguments)},OE=p._Step=function(){return(OE=p._Step=p.asm.Step).apply(null,arguments)},zE=p._StridedSlice=function(){return(zE=p._StridedSlice=p.asm.StridedSlice).apply(null,arguments)},DE=p._Sub=function(){return(DE=p._Sub=p.asm.Sub).apply(null,arguments)},LE=p._Sum=function(){return(LE=p._Sum=p.asm.Sum).apply(null,arguments)},BE=p._Tan=function(){return(BE=p._Tan=p.asm.Tan).apply(null,arguments)},WE=p._Tanh=function(){return(WE=p._Tanh=p.asm.Tanh).apply(null,arguments)},VE=p._Tile=function(){return(VE=p._Tile=p.asm.Tile).apply(null,arguments)},UE=p._TopK=function(){return(UE=p._TopK=p.asm.TopK).apply(null,arguments)},GE=p._Transform=function(){return(GE=p._Transform=p.asm.Transform).apply(null,arguments)},jE=p._Transpose=function(){return(jE=p._Transpose=p.asm.Transpose).apply(null,arguments)},HE=p.__FusedMatMul=function(){return(HE=p.__FusedMatMul=p.asm._FusedMatMul).apply(null,arguments)},og=p._malloc=function(){return(og=p._malloc=p.asm.malloc).apply(null,arguments)},Ob=p._free=function(){return(Ob=p._free=p.asm.free).apply(null,arguments)},qE=p._emscripten_tls_init=function(){return(qE=p._emscripten_tls_init=p.asm.emscripten_tls_init).apply(null,arguments)},zb=p.___errno_location=function(){return(zb=p.___errno_location=p.asm.__errno_location).apply(null,arguments)},qc=p._pthread_self=function(){return(qc=p._pthread_self=p.asm.pthread_self).apply(null,arguments)},Db=p._emscripten_main_thread_process_queued_calls=function(){return(Db=p._emscripten_main_thread_process_queued_calls=p.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},XE=p.__emscripten_thread_crashed=function(){return(XE=p.__emscripten_thread_crashed=p.asm._emscripten_thread_crashed).apply(null,arguments)},Lb=p.__emscripten_thread_init=function(){return(Lb=p.__emscripten_thread_init=p.asm._emscripten_thread_init).apply(null,arguments)},KE=p._emscripten_current_thread_process_queued_calls=function(){return(KE=p._emscripten_current_thread_process_queued_calls=p.asm.emscripten_current_thread_process_queued_calls).apply(null,arguments)},ZE=p._emscripten_main_browser_thread_id=function(){return(ZE=p._emscripten_main_browser_thread_id=p.asm.emscripten_main_browser_thread_id).apply(null,arguments)},YE=p._emscripten_sync_run_in_main_thread_2=function(){return(YE=p._emscripten_sync_run_in_main_thread_2=p.asm.emscripten_sync_run_in_main_thread_2).apply(null,arguments)},Bb=p._emscripten_sync_run_in_main_thread_4=function(){return(Bb=p._emscripten_sync_run_in_main_thread_4=p.asm.emscripten_sync_run_in_main_thread_4).apply(null,arguments)},Wb=p._emscripten_run_in_main_runtime_thread_js=function(){return(Wb=p._emscripten_run_in_main_runtime_thread_js=p.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)},lg=p._emscripten_dispatch_to_thread_=function(){return(lg=p._emscripten_dispatch_to_thread_=p.asm.emscripten_dispatch_to_thread_).apply(null,arguments)},ug=p.__emscripten_thread_free_data=function(){return(ug=p.__emscripten_thread_free_data=p.asm._emscripten_thread_free_data).apply(null,arguments)},JE=p.__emscripten_thread_exit=function(){return(JE=p.__emscripten_thread_exit=p.asm._emscripten_thread_exit).apply(null,arguments)},QE=p._memalign=function(){return(QE=p._memalign=p.asm.memalign).apply(null,arguments)},Vb=p._emscripten_stack_set_limits=function(){return(Vb=p._emscripten_stack_set_limits=p.asm.emscripten_stack_set_limits).apply(null,arguments)},dg=p.stackSave=function(){return(dg=p.stackSave=p.asm.stackSave).apply(null,arguments)},Xc=p.stackRestore=function(){return(Xc=p.stackRestore=p.asm.stackRestore).apply(null,arguments)},pu=p.stackAlloc=function(){return(pu=p.stackAlloc=p.asm.stackAlloc).apply(null,arguments)},eR=p.dynCall_iijjiiii=function(){return(eR=p.dynCall_iijjiiii=p.asm.dynCall_iijjiiii).apply(null,arguments)},tR=p.dynCall_jiji=function(){return(tR=p.dynCall_jiji=p.asm.dynCall_jiji).apply(null,arguments)},Ub=p.__emscripten_allow_main_runtime_queued_calls=21664;p.cwrap=cr,p.keepRuntimeAlive=uo,p.PThread=Oe,p.PThread=Oe,p.wasmMemory=Fe,p.ExitStatus=bp;var Kc;function bp(N){this.name="ExitStatus",this.message="Program terminated with exit("+N+")",this.status=N}na=function N(){Kc||pg(),Kc||(na=N)};function pg(N){if(N=N||y,bs>0)return;if(T){c(p),hp(),postMessage({cmd:"loaded"});return}if(zr(),bs>0)return;function _(){Kc||(Kc=!0,p.calledRun=!0,!xt&&(hp(),c(p),p.onRuntimeInitialized&&p.onRuntimeInitialized(),P1()))}p.setStatus?(p.setStatus("Running..."),setTimeout(function(){setTimeout(function(){p.setStatus("")},1),_()},1)):_()}p.run=pg;function rR(N,_){if(Pr=N,!_&&T)throw _c(N),"unwind";uo()||_1(),nR(N)}function nR(N){Pr=N,uo()||(Oe.terminateAllThreads(),p.onExit&&p.onExit(N),xt=!0),x(N,new bp(N))}if(p.preInit)for(typeof p.preInit=="function"&&(p.preInit=[p.preInit]);p.preInit.length>0;)p.preInit.pop()();pg();var Zc;f&&(Zc={uncaughtException:process.listeners("uncaughtException").filter(function(N){return!f.uncaughtException.indexOf(N)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(N){return!f.unhandledRejection.indexOf(N)>-1})});var Yc;if(typeof WasmBackendModule!="undefined")Yc=WasmBackendModule;else if(typeof a!="undefined")Yc=a;else throw new Error("Could not find wasm module in post.js");if(Zc){var aR=Yc._dispose;Yc._dispose=function(){aR(),Zc.uncaughtException.forEach(function(N){process.removeListener("uncaughtException",N)}),Zc.unhandledRejection.forEach(function(N){process.removeListener("unhandledRejection",N)})}}return a.ready}})();typeof e=="object"&&typeof t=="object"?t.exports=r:typeof define=="function"&&define.amd?define([],function(){return r}):typeof e=="object"&&(e.WasmBackendModuleThreadedSimd=r)}}),FR=dr({"src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js"(e,t){var r=(()=>{var n=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(n=n||__filename),function(a){a=a||{};var s=typeof a!="undefined"?a:{},i,o;s.ready=new Promise(function(H,ne){i=H,o=ne});var l;typeof process!="undefined"&&process.listeners&&(l={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var u=Object.assign({},s),d=[],h="./this.program",p=(H,ne)=>{throw ne},c=typeof window=="object",m=typeof importScripts=="function",f=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="";function y(H){return s.locateFile?s.locateFile(H,g):g+H}var A,x,b,w;function I(H){H instanceof Ap||$("exiting due to exception: "+H)}var T,E,R;f?(m?g=I0().dirname(g)+"/":g=__dirname+"/",R=()=>{E||(T=Ty(),E=I0())},A=function(H,ne){return R(),H=E.normalize(H),T.readFileSync(H,ne?void 0:"utf8")},b=H=>{var ne=A(H,!0);return ne.buffer||(ne=new Uint8Array(ne)),ne},x=(H,ne,ye)=>{R(),H=E.normalize(H),T.readFile(H,function(Re,lt){Re?ye(Re):ne(lt.buffer)})},process.argv.length>1&&(h=process.argv[1].replace(/\\/g,"/")),d=process.argv.slice(2),process.on("uncaughtException",function(H){if(!(H instanceof Ap))throw H}),process.on("unhandledRejection",function(H){throw H}),p=(H,ne)=>{if(pp())throw process.exitCode=H,ne;I(ne),process.exit(H)},s.inspect=function(){return"[Emscripten Module object]"}):(c||m)&&(m?g=self.location.href:typeof document!="undefined"&&document.currentScript&&(g=document.currentScript.src),n&&(g=n),g.indexOf("blob:")!==0?g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1):g="",A=H=>{var ne=new XMLHttpRequest;return ne.open("GET",H,!1),ne.send(null),ne.responseText},m&&(b=H=>{var ne=new XMLHttpRequest;return ne.open("GET",H,!1),ne.responseType="arraybuffer",ne.send(null),new Uint8Array(ne.response)}),x=(H,ne,ye)=>{var Re=new XMLHttpRequest;Re.open("GET",H,!0),Re.responseType="arraybuffer",Re.onload=()=>{if(Re.status==200||Re.status==0&&Re.response){ne(Re.response);return}ye()},Re.onerror=ye,Re.send(null)},w=H=>document.title=H);var F=s.print||console.log.bind(console),$=s.printErr||console.warn.bind(console);Object.assign(s,u),u=null,s.arguments&&(d=s.arguments),s.thisProgram&&(h=s.thisProgram),s.quit&&(p=s.quit);var S=4;function z(H){z.shown||(z.shown={}),z.shown[H]||(z.shown[H]=1,$(H))}function O(H,ne){if(typeof WebAssembly.Function=="function"){for(var ye={i:"i32",j:"i64",f:"f32",d:"f64"},Re={parameters:[],results:ne[0]=="v"?[]:[ye[ne[0]]]},lt=1;lt<ne.length;++lt)Re.parameters.push(ye[ne[lt]]);return new WebAssembly.Function(Re,H)}var ct=[1,0,1,96],Ze=ne.slice(0,1),He=ne.slice(1),qt={i:127,j:126,f:125,d:124};ct.push(He.length);for(var lt=0;lt<He.length;++lt)ct.push(qt[He[lt]]);Ze=="v"?ct.push(0):ct=ct.concat([1,qt[Ze]]),ct[1]=ct.length-2;var aa=new Uint8Array([0,97,115,109,1,0,0,0].concat(ct,[2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0])),sa=new WebAssembly.Module(aa),du=new WebAssembly.Instance(sa,{e:{f:H}}),fo=du.exports.f;return fo}var j=[],K;function D(){if(j.length)return j.pop();try{As.grow(1)}catch(H){throw H instanceof RangeError?"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.":H}return As.length-1}function Y(H,ne){for(var ye=H;ye<H+ne;ye++){var Re=fp(ye);Re&&K.set(Re,ye)}}var V=0,re=H=>{V=H},Q;s.wasmBinary&&(Q=s.wasmBinary);var ie=s.noExitRuntime||!0;typeof WebAssembly!="object"&&lo("no native wasm support detected");var J,ae=!1,de;function be(H,ne){H||lo(ne)}function ve(H){var ne=s["_"+H];return ne}function Ee(H,ne,ye,Re,lt){var ct={string:function(tn){var vs=0;if(tn!=null&&tn!==0){var Hc=(tn.length<<2)+1;vs=yp(Hc),ht(tn,vs,Hc)}return vs},array:function(tn){var vs=yp(tn.length);return xt(tn,vs),vs}};function Ze(tn){return ne==="string"?ot(tn):ne==="boolean"?Boolean(tn):tn}var He=ve(H),qt=[],aa=0;if(Re)for(var sa=0;sa<Re.length;sa++){var du=ct[ye[sa]];du?(aa===0&&(aa=Gc()),qt[sa]=du(Re[sa])):qt[sa]=Re[sa]}var fo=He.apply(null,qt);function ig(tn){return aa!==0&&jc(aa),Ze(tn)}return fo=ig(fo),fo}function $e(H,ne,ye,Re){ye=ye||[];var lt=ye.every(function(Ze){return Ze==="number"}),ct=ne!=="string";return ct&<&&!Re?ve(H):function(){return Ee(H,ne,ye,arguments,Re)}}var ze=1,We=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function Ke(H,ne,ye){for(var Re=ne+ye,lt=ne;H[lt]&&!(lt>=Re);)++lt;if(lt-ne>16&&H.subarray&&We)return We.decode(H.subarray(ne,lt));for(var ct="";ne<lt;){var Ze=H[ne++];if(!(Ze&128)){ct+=String.fromCharCode(Ze);continue}var He=H[ne++]&63;if((Ze&224)==192){ct+=String.fromCharCode((Ze&31)<<6|He);continue}var qt=H[ne++]&63;if((Ze&240)==224?Ze=(Ze&15)<<12|He<<6|qt:Ze=(Ze&7)<<18|He<<12|qt<<6|H[ne++]&63,Ze<65536)ct+=String.fromCharCode(Ze);else{var aa=Ze-65536;ct+=String.fromCharCode(55296|aa>>10,56320|aa&1023)}}return ct}function ot(H,ne){return H?Ke(cr,H,ne):""}function pt(H,ne,ye,Re){if(!(Re>0))return 0;for(var lt=ye,ct=ye+Re-1,Ze=0;Ze<H.length;++Ze){var He=H.charCodeAt(Ze);if(He>=55296&&He<=57343){var qt=H.charCodeAt(++Ze);He=65536+((He&1023)<<10)|qt&1023}if(He<=127){if(ye>=ct)break;ne[ye++]=He}else if(He<=2047){if(ye+1>=ct)break;ne[ye++]=192|He>>6,ne[ye++]=128|He&63}else if(He<=65535){if(ye+2>=ct)break;ne[ye++]=224|He>>12,ne[ye++]=128|He>>6&63,ne[ye++]=128|He&63}else{if(ye+3>=ct)break;ne[ye++]=240|He>>18,ne[ye++]=128|He>>12&63,ne[ye++]=128|He>>6&63,ne[ye++]=128|He&63}}return ne[ye]=0,ye-lt}function ht(H,ne,ye){return pt(H,cr,ne,ye)}function Fe(H){for(var ne=0,ye=0;ye<H.length;++ye){var Re=H.charCodeAt(ye);Re>=55296&&Re<=57343&&(Re=65536+((Re&1023)<<10)|H.charCodeAt(++ye)&1023),Re<=127?++ne:Re<=2047?ne+=2:Re<=65535?ne+=3:ne+=4}return ne}var wt=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):void 0;function xt(H,ne){rr.set(H,ne)}function Pr(H,ne,ye){for(var Re=0;Re<H.length;++Re)rr[ne++>>0]=H.charCodeAt(Re);ye||(rr[ne>>0]=0)}function hr(H,ne){return H%ne>0&&(H+=ne-H%ne),H}var Qr,rr,cr,ta,en,nr,kn,In,ys;function oo(H){Qr=H,s.HEAP8=rr=new Int8Array(H),s.HEAP16=ta=new Int16Array(H),s.HEAP32=nr=new Int32Array(H),s.HEAPU8=cr=new Uint8Array(H),s.HEAPU16=en=new Uint16Array(H),s.HEAPU32=kn=new Uint32Array(H),s.HEAPF32=In=new Float32Array(H),s.HEAPF64=ys=new Float64Array(H)}var yc=s.INITIAL_MEMORY||16777216,As,Ga=[],dp=[],eu=[],Or=!1,Ac=!1,xc=0;function pp(){return ie||xc>0}function bc(){if(s.preRun)for(typeof s.preRun=="function"&&(s.preRun=[s.preRun]);s.preRun.length;)kc(s.preRun.shift());cp(Ga)}function vc(){Or=!0,cp(dp)}function Ib(){Ac=!0}function wc(){if(s.postRun)for(typeof s.postRun=="function"&&(s.postRun=[s.postRun]);s.postRun.length;)Ic(s.postRun.shift());cp(eu)}function kc(H){Ga.unshift(H)}function ra(H){dp.unshift(H)}function Ic(H){eu.unshift(H)}var Sn=0,tu=null,xs=null;function M1(H){Sn++,s.monitorRunDependencies&&s.monitorRunDependencies(Sn)}function Sc(H){if(Sn--,s.monitorRunDependencies&&s.monitorRunDependencies(Sn),Sn==0&&(tu!==null&&(clearInterval(tu),tu=null),xs)){var ne=xs;xs=null,ne()}}s.preloadedImages={},s.preloadedAudios={};function lo(H){s.onAbort&&s.onAbort(H),H="Aborted("+H+")",$(H),ae=!0,de=1,H+=". Build with -s ASSERTIONS=1 for more info.";var ne=new WebAssembly.RuntimeError(H);throw o(ne),ne}var F1="data:application/octet-stream;base64,";function Cc(H){return H.startsWith(F1)}function uo(H){return H.startsWith("file://")}var zr;zr="tfjs-backend-wasm.wasm",Cc(zr)||(zr=y(zr));function hp(H){try{if(H==zr&&Q)return new Uint8Array(Q);if(b)return b(H);throw"both async and sync fetching of the wasm failed"}catch(ne){lo(ne)}}function _1(){if(!Q&&(c||m)){if(typeof fetch=="function"&&!uo(zr))return fetch(zr,{credentials:"same-origin"}).then(function(H){if(!H.ok)throw"failed to load wasm binary file at '"+zr+"'";return H.arrayBuffer()}).catch(function(){return hp(zr)});if(x)return new Promise(function(H,ne){x(zr,function(ye){H(new Uint8Array(ye))},ne)})}return Promise.resolve().then(function(){return hp(zr)})}function P1(){var H={env:au,wasi_snapshot_preview1:au};function ne(Ze,He){var qt=Ze.exports;s.asm=qt,J=s.asm.memory,oo(J.buffer),As=s.asm.__indirect_function_table,ra(s.asm.__wasm_call_ctors),Sc("wasm-instantiate")}M1("wasm-instantiate");function ye(Ze){ne(Ze.instance)}function Re(Ze){return _1().then(function(He){return WebAssembly.instantiate(He,H)}).then(function(He){return He}).then(Ze,function(He){$("failed to asynchronously prepare wasm: "+He),lo(He)})}function lt(){return!Q&&typeof WebAssembly.instantiateStreaming=="function"&&!Cc(zr)&&!uo(zr)&&typeof fetch=="function"?fetch(zr,{credentials:"same-origin"}).then(function(Ze){var He=WebAssembly.instantiateStreaming(Ze,H);return He.then(ye,function(qt){return $("wasm streaming compile failed: "+qt),$("falling back to ArrayBuffer instantiation"),Re(ye)})}):Re(ye)}if(s.instantiateWasm)try{var ct=s.instantiateWasm(H,ne);return ct}catch(Ze){return $("Module.instantiateWasm callback failed with error: "+Ze),!1}return lt().catch(o),{}}var Sb,Cb;function cp(H){for(;H.length>0;){var ne=H.shift();if(typeof ne=="function"){ne(s);continue}var ye=ne.func;typeof ye=="number"?ne.arg===void 0?fp(ye)():fp(ye)(ne.arg):ye(ne.arg===void 0?null:ne.arg)}}function bs(H){return H}function Tc(H){var ne=/\b_Z[\w\d_]+/g;return H.replace(ne,function(ye){var Re=ye;return ye===Re?ye:Re+" ["+ye+"]"})}var na=[];function fp(H){var ne=na[H];return ne||(H>=na.length&&(na.length=H+1),na[H]=ne=As.get(H)),ne}function Tb(){var H=new Error;if(!H.stack){try{throw new Error}catch(ne){H=ne}if(!H.stack)return"(no stack trace available)"}return H.stack.toString()}function ru(H,ne){As.set(H,ne),na[H]=ne}function O1(){lo("")}function Nc(H,ne,ye){cr.copyWithin(H,ne,ne+ye)}function Ec(){return 2147483648}function Dr(H){try{return J.grow(H-Qr.byteLength+65535>>>16),oo(J.buffer),1}catch(ne){}}function Rc(H){var ne=cr.length;H=H>>>0;var ye=Ec();if(H>ye)return!1;for(var Re=1;Re<=4;Re*=2){var lt=ne*(1+.2/Re);lt=Math.min(lt,H+100663296);var ct=Math.min(ye,hr(Math.max(H,lt),65536)),Ze=Dr(ct);if(Ze)return!0}return!1}var nu={mappings:{},buffers:[null,[],[]],printChar:function(H,ne){var ye=nu.buffers[H];ne===0||ne===10?((H===1?F:$)(Ke(ye,0)),ye.length=0):ye.push(ne)},varargs:void 0,get:function(){nu.varargs+=4;var H=nr[nu.varargs-4>>2];return H},getStr:function(H){var ne=ot(H);return ne},get64:function(H,ne){return H}};function z1(H){return 0}function Nb(H,ne,ye,Re,lt){}function Eb(H,ne,ye,Re){for(var lt=0,ct=0;ct<ye;ct++){var Ze=nr[ne>>2],He=nr[ne+4>>2];ne+=8;for(var qt=0;qt<He;qt++)nu.printChar(H,cr[Ze+qt]);lt+=He}return nr[Re>>2]=lt,0}function D1(H){re(H)}var $c=!1,au={abort:O1,emscripten_memcpy_big:Nc,emscripten_resize_heap:Rc,fd_close:z1,fd_seek:Nb,fd_write:Eb,setTempRet0:D1},cE=P1(),Rb=s.___wasm_call_ctors=function(){return(Rb=s.___wasm_call_ctors=s.asm.__wasm_call_ctors).apply(null,arguments)},L1=s._init=function(){return(L1=s._init=s.asm.init).apply(null,arguments)},B1=s._init_with_threads_count=function(){return(B1=s._init_with_threads_count=s.asm.init_with_threads_count).apply(null,arguments)},Mc=s._get_threads_count=function(){return(Mc=s._get_threads_count=s.asm.get_threads_count).apply(null,arguments)},Fc=s._register_tensor=function(){return(Fc=s._register_tensor=s.asm.register_tensor).apply(null,arguments)},W1=s._dispose_data=function(){return(W1=s._dispose_data=s.asm.dispose_data).apply(null,arguments)},Oe=s._dispose=function(){return(Oe=s._dispose=s.asm.dispose).apply(null,arguments)},V1=s._Abs=function(){return(V1=s._Abs=s.asm.Abs).apply(null,arguments)},_c=s._Add=function(){return(_c=s._Add=s.asm.Add).apply(null,arguments)},po=s._AddN=function(){return(po=s._AddN=s.asm.AddN).apply(null,arguments)},su=s._All=function(){return(su=s._All=s.asm.All).apply(null,arguments)},U1=s._Any=function(){return(U1=s._Any=s.asm.Any).apply(null,arguments)},$b=s._ArgMax=function(){return($b=s._ArgMax=s.asm.ArgMax).apply(null,arguments)},G1=s._AvgPool=function(){return(G1=s._AvgPool=s.asm.AvgPool).apply(null,arguments)},Mb=s._BatchMatMul=function(){return(Mb=s._BatchMatMul=s.asm.BatchMatMul).apply(null,arguments)},ho=s._Ceil=function(){return(ho=s._Ceil=s.asm.Ceil).apply(null,arguments)},j1=s._ClipByValue=function(){return(j1=s._ClipByValue=s.asm.ClipByValue).apply(null,arguments)},H1=s._Conv2D=function(){return(H1=s._Conv2D=s.asm.Conv2D).apply(null,arguments)},q1=s._Conv2DBackpropInput=function(){return(q1=s._Conv2DBackpropInput=s.asm.Conv2DBackpropInput).apply(null,arguments)},X1=s._Cos=function(){return(X1=s._Cos=s.asm.Cos).apply(null,arguments)},K1=s._Cosh=function(){return(K1=s._Cosh=s.asm.Cosh).apply(null,arguments)},Z1=s._CropAndResize=function(){return(Z1=s._CropAndResize=s.asm.CropAndResize).apply(null,arguments)},Pc=s._Cumprod=function(){return(Pc=s._Cumprod=s.asm.Cumprod).apply(null,arguments)},Y1=s._Cumsum=function(){return(Y1=s._Cumsum=s.asm.Cumsum).apply(null,arguments)},J1=s._DepthToSpace=function(){return(J1=s._DepthToSpace=s.asm.DepthToSpace).apply(null,arguments)},Q1=s._DepthwiseConv2dNative=function(){return(Q1=s._DepthwiseConv2dNative=s.asm.DepthwiseConv2dNative).apply(null,arguments)},e2=s._Elu=function(){return(e2=s._Elu=s.asm.Elu).apply(null,arguments)},t2=s._Equal=function(){return(t2=s._Equal=s.asm.Equal).apply(null,arguments)},Oc=s._Exp=function(){return(Oc=s._Exp=s.asm.Exp).apply(null,arguments)},r2=s._FlipLeftRight=function(){return(r2=s._FlipLeftRight=s.asm.FlipLeftRight).apply(null,arguments)},n2=s._Floor=function(){return(n2=s._Floor=s.asm.Floor).apply(null,arguments)},co=s._FloorDiv=function(){return(co=s._FloorDiv=s.asm.FloorDiv).apply(null,arguments)},mp=s._FusedBatchNorm=function(){return(mp=s._FusedBatchNorm=s.asm.FusedBatchNorm).apply(null,arguments)},a2=s._FusedConv2D=function(){return(a2=s._FusedConv2D=s.asm.FusedConv2D).apply(null,arguments)},s2=s._FusedDepthwiseConv2D=function(){return(s2=s._FusedDepthwiseConv2D=s.asm.FusedDepthwiseConv2D).apply(null,arguments)},i2=s._Gather=function(){return(i2=s._Gather=s.asm.Gather).apply(null,arguments)},Xe=s._GatherNd=function(){return(Xe=s._GatherNd=s.asm.GatherNd).apply(null,arguments)},o2=s._Greater=function(){return(o2=s._Greater=s.asm.Greater).apply(null,arguments)},l2=s._GreaterEqual=function(){return(l2=s._GreaterEqual=s.asm.GreaterEqual).apply(null,arguments)},u2=s._LeakyRelu=function(){return(u2=s._LeakyRelu=s.asm.LeakyRelu).apply(null,arguments)},d2=s._Less=function(){return(d2=s._Less=s.asm.Less).apply(null,arguments)},p2=s._LessEqual=function(){return(p2=s._LessEqual=s.asm.LessEqual).apply(null,arguments)},h2=s._Log=function(){return(h2=s._Log=s.asm.Log).apply(null,arguments)},gp=s._LogicalAnd=function(){return(gp=s._LogicalAnd=s.asm.LogicalAnd).apply(null,arguments)},zc=s._LogicalNot=function(){return(zc=s._LogicalNot=s.asm.LogicalNot).apply(null,arguments)},Dc=s._LogicalOr=function(){return(Dc=s._LogicalOr=s.asm.LogicalOr).apply(null,arguments)},c2=s._LogicalXor=function(){return(c2=s._LogicalXor=s.asm.LogicalXor).apply(null,arguments)},f2=s._Max=function(){return(f2=s._Max=s.asm.Max).apply(null,arguments)},m2=s._MaxPool=function(){return(m2=s._MaxPool=s.asm.MaxPool).apply(null,arguments)},g2=s._Maximum=function(){return(g2=s._Maximum=s.asm.Maximum).apply(null,arguments)},y2=s._Mean=function(){return(y2=s._Mean=s.asm.Mean).apply(null,arguments)},A2=s._Min=function(){return(A2=s._Min=s.asm.Min).apply(null,arguments)},_t=s._Minimum=function(){return(_t=s._Minimum=s.asm.Minimum).apply(null,arguments)},x2=s._MirrorPad=function(){return(x2=s._MirrorPad=s.asm.MirrorPad).apply(null,arguments)},b2=s._Multiply=function(){return(b2=s._Multiply=s.asm.Multiply).apply(null,arguments)},v2=s._Neg=function(){return(v2=s._Neg=s.asm.Neg).apply(null,arguments)},iu=s._NonMaxSuppressionV3=function(){return(iu=s._NonMaxSuppressionV3=s.asm.NonMaxSuppressionV3).apply(null,arguments)},Lc=s._NonMaxSuppressionV4=function(){return(Lc=s._NonMaxSuppressionV4=s.asm.NonMaxSuppressionV4).apply(null,arguments)},Bc=s._NonMaxSuppressionV5=function(){return(Bc=s._NonMaxSuppressionV5=s.asm.NonMaxSuppressionV5).apply(null,arguments)},Wc=s._NotEqual=function(){return(Wc=s._NotEqual=s.asm.NotEqual).apply(null,arguments)},w2=s._OneHot=function(){return(w2=s._OneHot=s.asm.OneHot).apply(null,arguments)},Vc=s._PadV2=function(){return(Vc=s._PadV2=s.asm.PadV2).apply(null,arguments)},k2=s._Pow=function(){return(k2=s._Pow=s.asm.Pow).apply(null,arguments)},Fb=s._Prelu=function(){return(Fb=s._Prelu=s.asm.Prelu).apply(null,arguments)},Uc=s._Prod=function(){return(Uc=s._Prod=s.asm.Prod).apply(null,arguments)},_b=s._RealDiv=function(){return(_b=s._RealDiv=s.asm.RealDiv).apply(null,arguments)},I2=s._Relu=function(){return(I2=s._Relu=s.asm.Relu).apply(null,arguments)},S2=s._Relu6=function(){return(S2=s._Relu6=s.asm.Relu6).apply(null,arguments)},C2=s._ResizeBilinear=function(){return(C2=s._ResizeBilinear=s.asm.ResizeBilinear).apply(null,arguments)},T2=s._Reverse=function(){return(T2=s._Reverse=s.asm.Reverse).apply(null,arguments)},N2=s._RotateWithOffset=function(){return(N2=s._RotateWithOffset=s.asm.RotateWithOffset).apply(null,arguments)},E2=s._Round=function(){return(E2=s._Round=s.asm.Round).apply(null,arguments)},R2=s._Rsqrt=function(){return(R2=s._Rsqrt=s.asm.Rsqrt).apply(null,arguments)},$2=s._ScatterNd=function(){return($2=s._ScatterNd=s.asm.ScatterNd).apply(null,arguments)},M2=s._SelectV2=function(){return(M2=s._SelectV2=s.asm.SelectV2).apply(null,arguments)},F2=s._Sigmoid=function(){return(F2=s._Sigmoid=s.asm.Sigmoid).apply(null,arguments)},_2=s._Sin=function(){return(_2=s._Sin=s.asm.Sin).apply(null,arguments)},P2=s._Softmax=function(){return(P2=s._Softmax=s.asm.Softmax).apply(null,arguments)},O2=s._SparseFillEmptyRows=function(){return(O2=s._SparseFillEmptyRows=s.asm.SparseFillEmptyRows).apply(null,arguments)},z2=s._SparseReshape=function(){return(z2=s._SparseReshape=s.asm.SparseReshape).apply(null,arguments)},D2=s._SparseSegmentReduction=function(){return(D2=s._SparseSegmentReduction=s.asm.SparseSegmentReduction).apply(null,arguments)},L2=s._Sqrt=function(){return(L2=s._Sqrt=s.asm.Sqrt).apply(null,arguments)},B2=s._Square=function(){return(B2=s._Square=s.asm.Square).apply(null,arguments)},W2=s._SquaredDifference=function(){return(W2=s._SquaredDifference=s.asm.SquaredDifference).apply(null,arguments)},V2=s._Step=function(){return(V2=s._Step=s.asm.Step).apply(null,arguments)},U2=s._StridedSlice=function(){return(U2=s._StridedSlice=s.asm.StridedSlice).apply(null,arguments)},G2=s._Sub=function(){return(G2=s._Sub=s.asm.Sub).apply(null,arguments)},j2=s._Sum=function(){return(j2=s._Sum=s.asm.Sum).apply(null,arguments)},H2=s._Tan=function(){return(H2=s._Tan=s.asm.Tan).apply(null,arguments)},q2=s._Tanh=function(){return(q2=s._Tanh=s.asm.Tanh).apply(null,arguments)},X2=s._Tile=function(){return(X2=s._Tile=s.asm.Tile).apply(null,arguments)},K2=s._TopK=function(){return(K2=s._TopK=s.asm.TopK).apply(null,arguments)},Z2=s._Transform=function(){return(Z2=s._Transform=s.asm.Transform).apply(null,arguments)},Y2=s._Transpose=function(){return(Y2=s._Transpose=s.asm.Transpose).apply(null,arguments)},J2=s.__FusedMatMul=function(){return(J2=s.__FusedMatMul=s.asm._FusedMatMul).apply(null,arguments)},Q2=s._malloc=function(){return(Q2=s._malloc=s.asm.malloc).apply(null,arguments)},eg=s._free=function(){return(eg=s._free=s.asm.free).apply(null,arguments)},tg=s.___errno_location=function(){return(tg=s.___errno_location=s.asm.__errno_location).apply(null,arguments)},rg=s._emscripten_main_thread_process_queued_calls=function(){return(rg=s._emscripten_main_thread_process_queued_calls=s.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},Gc=s.stackSave=function(){return(Gc=s.stackSave=s.asm.stackSave).apply(null,arguments)},jc=s.stackRestore=function(){return(jc=s.stackRestore=s.asm.stackRestore).apply(null,arguments)},yp=s.stackAlloc=function(){return(yp=s.stackAlloc=s.asm.stackAlloc).apply(null,arguments)},ng=s.dynCall_iijjiiii=function(){return(ng=s.dynCall_iijjiiii=s.asm.dynCall_iijjiiii).apply(null,arguments)},ag=s.dynCall_jiji=function(){return(ag=s.dynCall_jiji=s.asm.dynCall_jiji).apply(null,arguments)};s.cwrap=$e;var ou;function Ap(H){this.name="ExitStatus",this.message="Program terminated with exit("+H+")",this.status=H}xs=function H(){ou||xp(),ou||(xs=H)};function xp(H){if(H=H||d,Sn>0||(bc(),Sn>0))return;function ne(){ou||(ou=!0,s.calledRun=!0,!ae&&(vc(),i(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),wc()))}s.setStatus?(s.setStatus("Running..."),setTimeout(function(){setTimeout(function(){s.setStatus("")},1),ne()},1)):ne()}s.run=xp;function Pb(H){de=H,pp()||(s.onExit&&s.onExit(H),ae=!0),p(H,new Ap(H))}if(s.preInit)for(typeof s.preInit=="function"&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();xp();var lu;l&&(lu={uncaughtException:process.listeners("uncaughtException").filter(function(H){return!l.uncaughtException.indexOf(H)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(H){return!l.unhandledRejection.indexOf(H)>-1})});var uu;if(typeof a!="undefined")uu=a;else if(typeof WasmBackendModuleThreadedSimd!="undefined")uu=WasmBackendModuleThreadedSimd;else throw new Error("Could not find wasm module in post.js");if(lu){var sg=uu._dispose;uu._dispose=function(){sg(),lu.uncaughtException.forEach(function(H){process.removeListener("uncaughtException",H)}),lu.unhandledRejection.forEach(function(H){process.removeListener("unhandledRejection",H)})}}return a.ready}})();typeof e=="object"&&typeof t=="object"?t.exports=r:typeof define=="function"&&define.amd?define([],function(){return r}):typeof e=="object"&&(e.WasmBackendModule=r)}}),_R=1e-7,PR=1e-4,nh=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}},Gu=class{refCount(e){return Tn("refCount")}incRef(e){return Tn("incRef")}timerAvailable(){return!0}time(e){return Tn("time")}read(e){return Tn("read")}readSync(e){return Tn("readSync")}readToGPU(e,t){return Tn("readToGPU")}numDataIds(){return Tn("numDataIds")}disposeData(e,t){return Tn("disposeData")}write(e,t,r){return Tn("write")}move(e,t,r,n,a){return Tn("move")}memory(){return Tn("memory")}floatPrecision(){return Tn("floatPrecision")}epsilon(){return this.floatPrecision()===32?_R:PR}dispose(){return Tn("dispose")}};function Tn(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 z7(e){let t=e.length,r=0;for(;t>0;)r=Math.random()*t|0,t--,S0(e,t,r)}function OR(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 r=e.length,n=0;for(;r>0;)n=Math.random()*r|0,r--,S0(e,r,n),S0(t,r,n)}function Gp(e,t,r){return Math.max(e,Math.min(t,r))}function zR(e){return e%2===0?e:e+1}function S0(e,t,r){let n=e[t];e[t]=e[r],e[r]=n}function DR(e){let t=0;for(let r=0;r<e.length;r++)t+=e[r];return t}function LR(e,t){let r=Math.random();return t*r+(1-r)*e}function BR(e,t){let r=0;for(let n=0;n<e.length;n++){let a=Number(e[n])-Number(t[n]);r+=a*a}return r}function P(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function jr(e,t,r=""){P(Ks(e,t),()=>r+` Shapes ${e} and ${t} must match`)}function Uo(e){P(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function $o(e,t=[],r=!1){if(t==null&&(t=[]),Array.isArray(e)||Sr(e)&&!r)for(let n=0;n<e.length;++n)$o(e[n],t,r);else t.push(e);return t}function It(e){if(e.length===0)return 1;let t=e[0];for(let r=1;r<e.length;r++)t*=e[r];return t}function WR(e){return e.length===0}function Ks(e,t){if(e===t)return!0;if(e==null||t==null||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function Nu(e){return e%1===0}function VR(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 UR(e){let t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function GR(e){let t=new Uint32Array(e);for(let r=0;r<e;++r)t[r]=r;return z7(t),t}function Lp(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function jR(e,t=n=>0,r){return new Promise((n,a)=>{let s=0,i=()=>{if(e()){n();return}s++;let o=t(s);if(r!=null&&s>=r){a();return}setTimeout(i,o)};i()})}function HR(e,t){let r=1,n=-1;for(let s=0;s<e.length;++s)if(e[s]>=0)r*=e[s];else if(e[s]===-1){if(n!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${n} and dim ${s}`);n=s}else if(e[s]<0)throw Error(`Shapes can not be < 0. Found ${e[s]} at dim ${s}`);if(n===-1){if(t>0&&t!==r)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(r===0)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%r!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${r}`);let a=e.slice();return a[n]=t/r,a}function Hn(e,t){let r=t.length;return e=e==null?t.map((n,a)=>a):[].concat(e),P(e.every(n=>n>=-r&&n<r),()=>`All values in axis param must be in range [-${r}, ${r}) but got axis ${e}`),P(e.every(n=>Nu(n)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(n=>n<0?r+n:n)}function D7(e,t){let r=[],n=[],a=t!=null&&Array.isArray(t)&&t.length===0,s=t==null||a?null:Hn(t,e).sort(),i=0;for(let o=0;o<e.length;++o){if(s!=null){if(s[i]===o&&e[o]!==1)throw new Error(`Can't squeeze axis ${o} since its dim '${e[o]}' is not 1`);(s[i]==null||s[i]>o)&&e[o]===1&&(r.push(e[o]),n.push(o)),s[i]<=o&&i++}e[o]!==1&&(r.push(e[o]),n.push(o))}return{newShape:r,keptDims:n}}function L7(e,t){let r=null;if(e==null||e==="float32")r=new Float32Array(t);else if(e==="int32")r=new Int32Array(t);else if(e==="bool")r=new Uint8Array(t);else throw new Error(`Unknown data type ${e}`);return r}function B7(e,t){let r=null;if(e==null||e==="float32")r=new Float32Array(t);else if(e==="int32")r=new Int32Array(t);else if(e==="bool")r=new Uint8Array(t);else if(e==="string")r=new Array(t);else throw new Error(`Unknown data type ${e}`);return r}function W7(e,t){for(let r=0;r<e.length;r++){let n=e[r];if(isNaN(n)||!isFinite(n))throw Error(`A tensor of type ${t} being uploaded contains ${n}.`)}}function V7(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function qR(e,t){return!(t==="complex64"||t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64"||t==="bool"&&e==="bool")}function Sr(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}function Tg(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 U7(e){if(e==null)return 0;let t=0;return e.forEach(r=>t+=r.length),t}function Ns(e){return typeof e=="string"||e instanceof String}function G7(e){return typeof e=="boolean"}function j7(e){return typeof e=="number"}function of(e){return Array.isArray(e)?of(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":j7(e)?"float32":Ns(e)?"string":G7(e)?"bool":"float32"}function _s(e){return!!(e&&e.constructor&&e.call&&e.apply)}function C0(e,t){for(let r=t;r<e;++r)if(e%r===0)return r;return e}function ju(e){let t=e.length;if(t<2)return[];let r=new Array(t-1);r[t-2]=e[t-1];for(let n=t-3;n>=0;--n)r[n]=r[n+1]*e[n+1];return r}function H7(e,t,r,n=!1){let a=new Array;if(t.length===1){let s=t[0]*(n?2:1);for(let i=0;i<s;i++)a[i]=r[e+i]}else{let s=t[0],i=t.slice(1),o=i.reduce((l,u)=>l*u)*(n?2:1);for(let l=0;l<s;l++)a[l]=H7(e+l*o,i,r,n)}return a}function ku(e,t,r=!1){if(e.length===0)return t[0];let n=e.reduce((a,s)=>a*s)*(r?2:1);if(n===0)return[];if(n!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${r?" for a complex tensor":""}.`);return H7(0,e,t,r)}function Ny(e,t){let r=lf(e,t);for(let n=0;n<r.length;n++)r[n]=1;return r}function lf(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 XR(e,t){let r=e.reduce((n,a)=>n*a,1);if(t==null||t==="float32")return ku(e,new Float32Array(r));if(t==="int32")return ku(e,new Int32Array(r));if(t==="bool")return ku(e,new Uint8Array(r));throw new Error(`Unknown data type ${t}`)}function Ey(e){e.forEach(t=>{P(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function KR(e,t,r){if(t===0)return 0;if(t===1)return e[0];let n=e[e.length-1];for(let a=0;a<e.length-1;++a)n+=r[a]*e[a];return n}function ZR(e,t,r){if(t===0)return[];if(t===1)return[e];let n=new Array(t);for(let a=0;a<n.length-1;++a)n[a]=Math.floor(e/r[a]),e-=n[a]*r[a];return n[n.length-1]=e,n}function Ry(e){return e&&e.then&&typeof e.then=="function"}var qb="tfjsflags",q7=class{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=YR,this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&(Z().getBool("IS_TEST")||Z().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,r){if(this.flagRegistry[e]={evaluationFn:t,setHook:r},this.urlFlags[e]!=null){let n=this.urlFlags[e];Z().getBool("IS_TEST")||Z().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${n}.`),this.set(e,n)}}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(Ry(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);qb in e&&e[qb].split(",").forEach(t=>{let[r,n]=t.split(":");this.urlFlags[r]=QR(r,n)})}};function YR(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(r,...n)=>(JR(t,n[0],n[1]),n.join("="))),t}function JR(e,t,r){e[decodeURIComponent(t)]=decodeURIComponent(r||"")}function QR(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 ba}var ba=null;function e$(e){ba=e}var cg;function X7(){if(cg==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");cg=e}return cg}function t$(){let e=X7();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function $y(e,t){let r=t$();if(r.has(e))return r.get(e);{let n=t();return r.set(e,n),r.get(e)}}var Go="Abs",Hu="Acos",qu="Acosh",Qa="Add",Zs="AddN",Xu="All",Ku="Any",Ys="ArgMax",Zu="ArgMin",Yu="Asin",Ju="Asinh",Qu="Atan",ed="Atanh",td="Atan2",Js="AvgPool",uf="AvgPoolGrad",ah="AvgPool3D",df="AvgPool3DGrad",Qs="BatchMatMul",jo="BatchToSpaceND",pf="Bincount",K7="BroadcastTo",hf="BroadcastArgs",ei="Cast",ti="Ceil",es="ClipByValue",sh="Complex",ih="ComplexAbs",Ho="Concat",ri="Conv2D",cf="Conv2DBackpropFilter",ni="Conv2DBackpropInput",oh="Conv3D",ff="Conv3DBackpropFilterV2",mf="Conv3DBackpropInputV2",ai="Cos",si="Cosh",qo="Cumprod",ii="Cumsum",Xo="CropAndResize",gf="DenseBincount",Ko="DepthToSpace",oi="DepthwiseConv2dNative",yf="DepthwiseConv2dNativeBackpropFilter",Af="DepthwiseConv2dNativeBackpropInput",xf="Diag",lh="Dilation2D",T0="Dilation2DBackpropInput",N0="Dilation2DBackpropFilter",li="RealDiv",uh="Einsum",ui="Elu",bf="EluGrad",rd="Erf",Zo="Equal",di="Exp",Yo="ExpandDims",Jo="Expm1",vf="FFT",nd="Fill",Qo="FlipLeftRight",pi="Floor",hi="FloorDiv",ci="FusedBatchNorm",el="GatherV2",tl="GatherNd",rl="Greater",fi="GreaterEqual",mi="Identity",wf="IFFT",dh="Imag",ad="IsFinite",sd="IsInf",id="IsNan",gi="LeakyRelu",nl="Less",al="LessEqual",kf="LinSpace",yi="Log",od="Log1p",sl="LogicalAnd",il="LogicalNot",ld="LogicalOr",Z7="LogicalXor",Y7="LogSoftmax",r$="LowerBound",ph="LRN",If="LRNGrad",Ai="Max",xi="Maximum",bi="MaxPool",Sf="MaxPoolGrad",hh="MaxPool3D",Cf="MaxPool3DGrad",Tf="MaxPoolWithArgmax",vi="Mean",wi="Min",ki="Minimum",Ii="MirrorPad",ud="Mod",Nf="Multinomial",Si="Multiply",ol="Neg",ll="NotEqual",ul="NonMaxSuppressionV3",dd="NonMaxSuppressionV4",dl="NonMaxSuppressionV5",pl="OnesLike",hl="OneHot",cl="Pack",Ci="PadV2",n$="Pool",Ti="Pow",Ni="Prelu",Ei="Prod",pd="Range",ch="Real",hd="Reciprocal",Ri="Relu",fl="Reshape",cd="ResizeNearestNeighbor",Ef="ResizeNearestNeighborGrad",$i="ResizeBilinear",Rf="ResizeBilinearGrad",Mi="Relu6",ml="Reverse",gl="Round",Fi="Rsqrt",yl="ScatterNd",$f="SearchSorted",Al="Select",fd="Selu",xl="Slice",_i="Sin",bl="Sinh",md="Sign",Pi="Sigmoid",gd="Softplus",Oi="Sqrt",zi="Sum",vl="SpaceToBatchND",wl="SplitV",Di="Softmax",fh="SparseFillEmptyRows",yd="SparseReshape",mh="SparseSegmentMean",gh="SparseSegmentSum",yh="SparseToDense",Li="SquaredDifference",Ad="Square",kl="StridedSlice",Ah="StringNGrams",Mf="StringSplit",Ff="StringToHashBucketFast",Bi="Sub",Il="Tan",Wi="Tanh",ts="Tile",Sl="TopK",Cl="Transform",$a="Transpose",_f="Unique",Tl="Unpack",xh="UnsortedSegmentSum",a$="UpperBound",Nl="ZerosLike",Vi="Step",jp="FromPixels",El="RotateWithOffset",Ps="_FusedMatMul",Os="FusedConv2D",zs="FusedDepthwiseConv2D";function Ts(...e){Z().getBool("IS_TEST")||Z().getBool("PROD")||console.warn(...e)}function s$(...e){Z().getBool("IS_TEST")||Z().getBool("PROD")||console.log(...e)}var Eu=$y("kernelRegistry",()=>new Map),Hp=$y("gradRegistry",()=>new Map);function E0(e,t){let r=My(e,t);return Eu.get(r)}function Ng(e){return Hp.get(e)}function Fa(e){let t=Eu.entries(),r=[];for(;;){let{done:n,value:a}=t.next();if(n)break;let[s,i]=a,[o]=s.split("_");o===e&&r.push(i)}return r}function qn(e){let{kernelName:t,backendName:r}=e,n=My(t,r);Eu.has(n)&&Ts(`The kernel '${t}' for backend '${r}' is already registered`),Eu.set(n,e)}function J7(e){let{kernelName:t}=e;Hp.has(t)&&Z().getBool("DEBUG")&&Ts(`Overriding the gradient for '${t}'`),Hp.set(t,e)}function i$(e,t){let r=My(e,t);if(!Eu.has(r))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);Eu.delete(r)}function o$(e){if(!Hp.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Hp.delete(e)}function l$(e,t){Fa(e).forEach(r=>{let n=Object.assign({},r,{backendName:t});qn(n)})}function My(e,t){return`${t}_${e}`}var v={};Be(v,{arraysEqual:()=>Ks,assert:()=>P,assertNonNegativeIntegerDimensions:()=>Ey,assertNonNull:()=>Uo,assertShapesMatch:()=>jr,bytesFromStringArray:()=>U7,bytesPerElement:()=>Tg,checkConversionForErrors:()=>W7,clamp:()=>Gp,computeStrides:()=>ju,createScalarValue:()=>f$,createShuffledIndices:()=>GR,decodeString:()=>R0,distSquared:()=>BR,encodeString:()=>vh,fetch:()=>g$,fingerPrint64:()=>c$,flatten:()=>$o,getArrayFromDType:()=>B7,getTypedArrayFromDType:()=>L7,hasEncodingLoss:()=>qR,hexToLong:()=>bh,indexToLoc:()=>ZR,inferDtype:()=>of,inferFromImplicitShape:()=>HR,isBoolean:()=>G7,isFunction:()=>_s,isInt:()=>Nu,isNumber:()=>j7,isPromise:()=>Ry,isScalarShape:()=>WR,isString:()=>Ns,isTypedArray:()=>Sr,isValidDtype:()=>V7,locToIndex:()=>KR,makeOnesTypedArray:()=>Ny,makeZerosNestedTypedArray:()=>XR,makeZerosTypedArray:()=>lf,nearestDivisor:()=>C0,nearestLargerEven:()=>zR,now:()=>qp,parseAxisParam:()=>Hn,randUniform:()=>LR,repeatedTry:()=>jR,rightPad:()=>Lp,shuffle:()=>z7,shuffleCombo:()=>OR,sizeFromShape:()=>It,sizeToSquarishShape:()=>UR,squeezeShape:()=>D7,sum:()=>DR,swap:()=>S0,tanh:()=>VR,toNestedArray:()=>ku,toTypedArray:()=>Pf});var Xb=Vo(AR()),bo=Xb.default||Xb;function bh(e){return bo.fromString(e,!0,16)}var Q7=bh("c3a5c85c97cb3127"),yo=bh("b492b66fbe98f273"),Lr=bh("9ae16a3b2f90404f");function Eg(e){return e.xor(e.shru(47))}function e6(e,t,r){let n=e.slice(t,t+r);return bo.fromBytes(Array.from(n),!0,!0)}function kt(e,t){return e6(e,t,8)}function Kb(e,t){return e6(e,t,4)}function fr(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function Rs(e,t,r=bh("9ddfea08eb382d69")){let n=e.xor(t).mul(r);n=n.xor(n.shru(47));let a=t.xor(n).mul(r);return a=a.xor(a.shru(47)),a=a.mul(r),a}function u$(e,t,r,n,a,s){a=a.add(e),s=fr(s.add(a).add(n),21);let i=a;return a=a.add(t),a=a.add(r),s=s.add(fr(a,44)),[a.add(n),s.add(i)]}function e0(e,t,r,n){return u$(kt(e,t),kt(e,t+8),kt(e,t+16),kt(e,t+24),r,n)}function d$(e,t=e.length){if(t>=8){let r=Lr.add(t*2),n=kt(e,0).add(Lr),a=kt(e,t-8),s=fr(a,37).mul(r).add(n),i=fr(n,25).add(a).mul(r);return Rs(s,i,r)}if(t>=4){let r=Lr.add(t*2),n=Kb(e,0);return Rs(n.shl(3).add(t),Kb(e,t-4),r)}if(t>0){let r=e[0],n=e[t>>1],a=e[t-1],s=r+(n<<8),i=t+(a<<2);return Eg(Lr.mul(s).xor(Q7.mul(i))).mul(Lr)}return Lr}function p$(e,t=e.length){let r=Lr.add(t*2),n=kt(e,0).mul(yo),a=kt(e,8),s=kt(e,t-8).mul(r),i=kt(e,t-16).mul(Lr);return Rs(fr(n.add(a),43).add(fr(s,30)).add(i),n.add(fr(a.add(Lr),18)).add(s),r)}function h$(e,t=e.length){let r=Lr.add(t*2),n=kt(e,0).mul(Lr),a=kt(e,8),s=kt(e,t-8).mul(r),i=kt(e,t-16).mul(Lr),o=fr(n.add(a),43).add(fr(s,30)).add(i),l=Rs(o,n.add(fr(a.add(Lr),18)).add(s),r),u=kt(e,16).mul(r),d=kt(e,24),h=o.add(kt(e,t-32)).mul(r),p=l.add(kt(e,t-24)).mul(r);return Rs(fr(u.add(d),43).add(fr(h,30)).add(p),u.add(fr(d.add(n),18)).add(h),r)}function c$(e,t=e.length){let r=bo.fromNumber(81,!0);if(t<=32)return t<=16?d$(e,t):p$(e,t);if(t<=64)return h$(e,t);let n=r,a=r.mul(yo).add(113),s=Eg(a.mul(Lr).add(113)).mul(Lr),i=[bo.UZERO,bo.UZERO],o=[bo.UZERO,bo.UZERO];n=n.mul(Lr).add(kt(e,0));let l=0,u=(t-1>>6)*64,d=u+(t-1&63)-63;do n=fr(n.add(a).add(i[0]).add(kt(e,l+8)),37).mul(yo),a=fr(a.add(i[1]).add(kt(e,l+48)),42).mul(yo),n=n.xor(o[1]),a=a.add(i[0]).add(kt(e,l+40)),s=fr(s.add(o[0]),33).mul(yo),i=e0(e,l,i[1].mul(yo),n.add(o[0])),o=e0(e,l+32,s.add(o[1]),a.add(kt(e,l+16))),[s,n]=[n,s],l+=64;while(l!==u);let h=yo.add(s.and(255).shl(1));return l=d,o[0]=o[0].add(t-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),n=fr(n.add(a).add(i[0]).add(kt(e,l+8)),37).mul(h),a=fr(a.add(i[1]).add(kt(e,l+48)),42).mul(h),n=n.xor(o[1].mul(9)),a=a.add(i[0].mul(9).add(kt(e,l+40))),s=fr(s.add(o[0]),33).mul(h),i=e0(e,l,i[1].mul(h),n.add(o[0])),o=e0(e,l+32,s.add(o[1]),a.add(kt(e,l+16))),[s,n]=[n,s],Rs(Rs(i[0],o[0],h).add(Eg(a).mul(Q7)).add(s),Rs(i[1],o[1],h).add(n),h)}function f$(e,t){return t==="string"?vh(e):Pf([e],t)}function m$(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Pf(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=$o(e)),Z().getBool("DEBUG")&&W7(e,t),m$(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 r=new Uint8Array(e.length);for(let n=0;n<r.length;++n)Math.round(e[n])!==0&&(r[n]=1);return r}else throw new Error(`Unknown data type ${t}`)}function qp(){return Z().platform.now()}function g$(e,t){return Z().platform.fetch(e,t)}function vh(e,t="utf-8"){return t=t||"utf-8",Z().platform.encode(e,t)}function R0(e,t="utf-8"){return t=t||"utf-8",Z().platform.decode(e,t)}var y$=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new x$)}profileKernel(e,t,r){let n,a=()=>{n=r()},s,i=qp();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(a);else{a();for(let o of n)o.dataSync();s=Promise.resolve({kernelMs:qp()-i})}if(Z().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let o=0;o<n.length;o++){let l=n[o];l.data().then(u=>{A$(u,l.dtype,e)})}return{kernelName:e,outputs:n,inputs:t,timeMs:s.then(o=>o.kernelMs),extraInfo:s.then(o=>o.getExtraProfileInfo!=null?o.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:r,timeMs:n,inputs:a,extraInfo:s}=e;r.forEach(i=>{Promise.all([i.data(),n,s]).then(o=>{this.logger.logKernelProfile(t,i,o[0],o[1],a,o[2])})})}};function A$(e,t,r){if(t!=="float32")return!1;for(let n=0;n<e.length;n++){let a=e[n];if(isNaN(a)||!isFinite(a))return console.warn(`Found ${a} in the result of '${r}'`),!0}return!1}var x$=class{logKernelProfile(e,t,r,n,a,s){let i=typeof n=="number"?Lp(`${n}ms`,9):n.error,o=Lp(e,25),l=t.rank,u=t.size,d=Lp(t.shape.toString(),14),h="";for(let p in a){let c=a[p];if(c!=null){let m=c.shape||t.shape,f=m.length;h+=`${p}: ${f}D ${f>0?m:""} `}}console.log(`%c${o} %c${i} %c${l}D ${d} %c${u} %c${h} %c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function b$(e,t,r){let n={},a={};for(let l=0;l<t.length;l++)n[t[l].id]=!0;for(let l=0;l<e.length;l++){let u=e[l],d=u.inputs;for(let h in d){let p=d[h],c=!1;for(let m=0;m<t.length;m++)if(n[p.id]){u.outputs.forEach(f=>n[f.id]=!0),c=!0,a[u.id]=!0;break}if(c)break}}let s={};s[r.id]=!0;let i={};for(let l=e.length-1;l>=0;l--){let u=e[l],d=u.inputs;for(let h=0;h<u.outputs.length;h++)if(s[u.outputs[h].id]){for(let p in d)s[d[p].id]=!0,i[u.id]=!0;break}}let o=[];for(let l=0;l<e.length;l++){let u=e[l];if(a[u.id]&&i[u.id]){let d={};for(let p in u.inputs){let c=u.inputs[p];n[c.id]&&(d[p]=c)}let h=Object.assign({},u);h.inputs=d,h.outputs=u.outputs,o.push(h)}}return o}function v$(e,t,r,n){for(let a=t.length-1;a>=0;a--){let s=t[a],i=[];if(s.outputs.forEach(l=>{let u=e[l.id];u!=null?i.push(u):i.push(null)}),s.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);let o=s.gradient(i);for(let l in s.inputs){if(!(l in o))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(o)}.`);let u=r(()=>o[l]());if(u.dtype!=="float32")throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);let d=s.inputs[l];if(!Ks(u.shape,d.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${d.shape}'`);if(e[d.id]==null)e[d.id]=u;else{let h=e[d.id];e[d.id]=n(h,u),h.dispose()}}}}var Zb=20,Sp=3,fg=7;function w$(e,t,r,n){let a=ju(t),s=k$(e,t,r,a),i=t.length,o=h0(e,t,r,a,s),l=["Tensor"];return n&&(l.push(` dtype: ${r}`),l.push(` rank: ${i}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(o.map(u=>" "+u).join(`
|
|
`)),l.join(`
|
|
`)}function k$(e,t,r,n){let a=It(t),s=n[n.length-1],i=new Array(s).fill(0),o=t.length,l=r==="complex64"?Rp(e):e;if(o>1)for(let u=0;u<a/s;u++){let d=u*s;for(let h=0;h<s;h++)i[h]=Math.max(i[h],Ep(l[d+h],0,r).length)}return i}function Ep(e,t,r){let n;return Array.isArray(e)?n=`${parseFloat(e[0].toFixed(fg))} + ${parseFloat(e[1].toFixed(fg))}j`:Ns(e)?n=`'${e}'`:r==="bool"?n=t6(e):n=parseFloat(e.toFixed(fg)).toString(),Lp(n,t)}function t6(e){return e===0?"false":"true"}function h0(e,t,r,n,a,s=!0){let i=r==="complex64"?2:1,o=t[0],l=t.length;if(l===0){if(r==="complex64"){let f=Rp(e);return[Ep(f[0],0,r)]}return r==="bool"?[t6(e[0])]:[e[0].toString()]}if(l===1){if(o>Zb){let g=Sp*i,y=Array.from(e.slice(0,g)),A=Array.from(e.slice((o-Sp)*i,o*i));return r==="complex64"&&(y=Rp(y),A=Rp(A)),["["+y.map((x,b)=>Ep(x,a[b],r)).join(", ")+", ..., "+A.map((x,b)=>Ep(x,a[o-Sp+b],r)).join(", ")+"]"]}let f=r==="complex64"?Rp(e):Array.from(e);return["["+f.map((g,y)=>Ep(g,a[y],r)).join(", ")+"]"]}let u=t.slice(1),d=n.slice(1),h=n[0]*i,p=[];if(o>Zb){for(let f=0;f<Sp;f++){let g=f*h,y=g+h;p.push(...h0(e.slice(g,y),u,r,d,a,!1))}p.push("...");for(let f=o-Sp;f<o;f++){let g=f*h,y=g+h;p.push(...h0(e.slice(g,y),u,r,d,a,f===o-1))}}else for(let f=0;f<o;f++){let g=f*h,y=g+h;p.push(...h0(e.slice(g,y),u,r,d,a,f===o-1))}let c=l===2?",":"";p[0]="["+p[0]+c;for(let f=1;f<p.length-1;f++)p[f]=" "+p[f]+c;let m=`,
|
|
`;for(let f=2;f<l;f++)m+=`
|
|
`;return p[p.length-1]=" "+p[p.length-1]+"]"+(s?"":m),p}function Rp(e){let t=[];for(let r=0;r<e.length;r+=2)t.push([e[r],e[r+1]]);return t}var ir=class{constructor(e,t,r){if(this.dtype=t,this.shape=e.slice(),this.size=It(e),r!=null){let n=r.length;P(n===this.size,()=>`Length of values '${n}' 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=r||B7(t,this.size),this.strides=ju(e)}set(e,...t){t.length===0&&(t=[0]),P(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let r=this.locToIndex(t);this.values[r]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let n of e){if(n<0||n>=this.shape[t]){let a=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(a)}t++}let r=e[e.length-1];for(let n=0;n<e.length-1;++n)r+=this.strides[n]*e[n];return this.values[r]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let r=0;r<e.length-1;++r)t+=this.strides[r]*e[r];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let r=0;r<t.length-1;++r)t[r]=Math.floor(e/this.strides[r]),e-=t[r]*this.strides[r];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return la().makeTensor(this.values,this.shape,this.dtype)}},la=null,xu=null,I$=null;function S$(e){la=e}function C$(e){xu=e}function T$(e){I$=e}var nt=class{constructor(e,t,r,n){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=It(e),this.strides=ju(e),this.dataId=r,this.id=n,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return xu.buffer(this.shape,this.dtype,e)}bufferSync(){return xu.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return ku(this.shape,e,this.dtype==="complex64")}arraySync(){return ku(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=la().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(r=>R0(r))}catch(r){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),la().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();let e=la().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>R0(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 la().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(la().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return xu.print(this,e)}clone(){return this.throwIfDisposed(),xu.clone(this)}toString(e=!1){let t=this.dataSync();return w$(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),xu.cast(this,e)}variable(e=!0,t,r){return this.throwIfDisposed(),la().makeVariable(this,e,t,r)}};Object.defineProperty(nt,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function N$(){return $y("Tensor",()=>nt)}N$();var Xp=class extends nt{constructor(e,t,r,n){super(e.shape,e.dtype,e.dataId,n),this.trainable=t,this.name=r}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(!Ks(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);la().disposeTensor(this),this.dataId=e.dataId,la().incRef(this,null)}dispose(){la().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(Xp,Symbol.hasInstance,{value:e=>e instanceof nt&&e.assign!=null&&e.assign instanceof Function});var ha={};Be(ha,{assertTypesMatch:()=>o6,getTensorsInContainer:()=>Fy,isTensorInList:()=>R$,makeTypesMatch:()=>Lt});var r6=(e=>(e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6",e))(r6||{}),n6=(e=>(e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64",e))(n6||{}),a6=(e=>(e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64",e))(a6||{}),s6=(e=>(e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64",e))(s6||{}),i6=(e=>(e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64",e))(i6||{}),E$={float32:s6,int32:n6,bool:a6,complex64:i6};function Nr(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return E$[e][t]}function wh(e){return Nr(e,"int32")}function Lt(e,t){if(e.dtype===t.dtype)return[e,t];let r=Nr(e.dtype,t.dtype);return[e.cast(r),t.cast(r)]}function o6(e,t){P(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function R$(e,t){return t.some(r=>r.id===e.id)}function Fy(e){let t=[];return l6(e,t,new Set),t}function l6(e,t,r){if(e==null)return;if(e instanceof nt){t.push(e);return}if(!$$(e))return;let n=e;for(let a in n){let s=n[a];r.has(s)||(r.add(s),l6(s,t,r))}}function $$(e){return Array.isArray(e)||typeof e=="object"}function mg(e){return e.kernelName!=null}var Yb=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()}},Rg=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Yb}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 r=e[t];if(await this.initializeBackend(r).success){await this.setBackend(r);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,r=1){return e in this.registryFactory?(Ts(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:r},!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:r}=this.initializeBackend(e);if(!(r?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new y$(this.backendInstance),!0}setupRegisteredKernels(){Fa(this.backendName).forEach(e=>{e.setupFunc!=null&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Fa(e).forEach(t=>{t.disposeFunc!=null&&t.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 r=t.factory();if(r&&!(r instanceof Gu)&&typeof r.then=="function"){let n=++this.pendingBackendInitId,a=r.then(s=>n<this.pendingBackendInitId?!1:(this.registry[e]=s,this.pendingBackendInit=null,!0)).catch(s=>(n<this.pendingBackendInitId||(this.pendingBackendInit=null,Ts(`Initialization of backend ${e} failed`),Ts(s.stack||s.message)),!1));return this.pendingBackendInit=a,{success:a,asyncInit:!0}}else return this.registry[e]=r,{success:!0,asyncInit:!1}}catch(r){return Ts(`Initialization of backend ${e} failed`),Ts(r.stack||r.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 r=e[t],{success:n,asyncInit:a}=this.initializeBackend(r);if(a||n)return{name:r,asyncInit:a}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){let r=this.state.tensorInfo.get(t),n=r.backend,a=this.readSync(t),s=n.refCount(t);n.disposeData(t,!0),r.backend=e,e.move(t,a,r.shape,r.dtype,s),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let r=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");r=e}let n;return this.scopedRun(()=>this.startScope(r),()=>this.endScope(n),()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n))}scopedRun(e,t,r){e();try{let n=r();return t(),n}catch(n){throw t(),n}}nextTensorId(){return Rg.nextTensorId++}nextVariableId(){return Rg.nextVariableId++}clone(e){let t=B.runKernel(mi,{x:e}),r={x:e},n=s=>({x:()=>{let i="float32",o={x:s},l={dtype:i};return B.runKernel(ei,o,l)}}),a=[];return this.addTapeNode(this.state.activeScope.name,r,[t],n,a,{}),t}runKernel(e,t,r){if(this.backendName==null&&this.backend,E0(e,this.backendName)==null)throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:r})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,r){let n=this.backend.numDataIds(),a=0;r.forEach(o=>{a+=o.dtype==="complex64"?3:1});let s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=n-t-a-s;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,r=[],n=this.isTapeOn(),a=this.state.numBytes,s=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let i;this.backendName==null&&this.backend;let o,l=mg(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(mg(e)){let{kernelName:c,inputs:m,attrs:f}=e;this.backendName==null&&this.backend;let g=E0(c,this.backendName);P(g!=null,()=>`Cannot find registered kernel '${c}' for backend '${this.backendName}'`),i=()=>{let y=this.backend.numDataIds();o=g.kernelFunc({inputs:m,attrs:f,backend:this.backend});let A=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(c,y,A);let x=A.map(b=>b.rank!=null?b:this.makeTensorFromTensorInfo(b));if(n){let b=this.getTensorsForGradient(c,m,x);r=this.saveTensorsForBackwardMode(b)}return x}}else{let{forwardFunc:c}=e,m=f=>{!n||(r=f.map(g=>this.keep(this.clone(g))))};i=()=>{let f=this.backend.numDataIds();o=this.tidy(()=>c(this.backend,m));let g=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,f,g),g}}let{inputs:u,attrs:d}=e,h=mg(e)?null:e.backwardsFunc,p;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=i():(p=this.profiler.profileKernel(l,u,()=>i()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs)}),n&&this.addTapeNode(l,u,t,h,r,d),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map(c=>u[c]!=null?u[c].shape:null),outputShapes:t.map(c=>c.shape),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(t=>this.keep(this.clone(t)))}getTensorsForGradient(e,t,r){let n=Ng(e);if(n!=null){let a=n.inputsToSave||[],s=n.outputsToSave||[],i;n.saveAllInputs?(P(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),i=Object.keys(t).map(l=>t[l])):i=a.map(l=>t[l]);let o=r.filter((l,u)=>s[u]);return i.concat(o)}return[]}makeTensor(e,t,r,n){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");r=r||"float32",n=n||this.backend;let a=e;r==="string"&&Ns(e[0])&&(a=e.map(o=>vh(o)));let s=n.write(a,t,r),i=new nt(t,r,s,this.nextTensorId());if(this.trackTensor(i,n),r==="string"){let o=this.state.tensorInfo.get(s),l=U7(a);this.state.numBytes+=l-o.bytes,o.bytes=l}return i}makeTensorFromDataId(e,t,r,n){r=r||"float32";let a={dataId:e,shape:t,dtype:r};return this.makeTensorFromTensorInfo(a,n)}makeTensorFromTensorInfo(e,t){let{dataId:r,shape:n,dtype:a}=e,s=new nt(n,a,r,this.nextTensorId());return this.trackTensor(s,t),s}makeVariable(e,t=!0,r,n){r=r||this.nextVariableId().toString(),n!=null&&n!==e.dtype&&(e=e.cast(n));let a=new Xp(e,t,r,this.nextTensorId());if(this.state.registeredVariables[a.name]!=null)throw new Error(`Variable with name ${a.name} was already registered`);return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let r=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(r=e.size*Tg(e.dtype)),this.state.numBytes+=r,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:r})),e instanceof Xp||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 r=e.size*Tg(e.dtype);this.state.numBytes-=r}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,r=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(n=>n.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-r;for(let n of this.state.activeProfile.kernels)n.kernelTimeMs=await n.kernelTimeMs,n.extraInfo=await n.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,r,n,a,s){let i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:r,saved:a},o=Ng(e);o!=null&&(n=o.gradFunc),n!=null&&(i.gradient=l=>(l=l.map((u,d)=>{if(u==null){let h=r[d],p=lf(h.size,h.dtype);return this.makeTensor(p,h.shape,h.dtype)}return u}),n(l.length>1?l:l[0],a,s))),this.state.activeTape.push(i)}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=Fy(e),r=new Set(t.map(a=>a.id));for(let a=0;a<this.state.activeScope.track.length;a++){let s=this.state.activeScope.track[a];!s.kept&&!r.has(s.id)&&s.dispose()}let n=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(a=>{!a.kept&&a.scopeId===n.id&&this.track(a)})}gradients(e,t,r,n=!1){if(P(t.length>0,()=>"gradients() received an empty list of xs."),r!=null&&r.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${r.dtype}'`);let a=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));P(a instanceof nt,()=>"The result y returned by f() must be a tensor.");let s=b$(this.state.activeTape,t,a);if(!n&&s.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 i={};i[a.id]=r==null?M$(a.shape):r,v$(i,s,l=>this.tidy(l),F$);let o=t.map(l=>i[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let u of l.saved)u.dispose()}),this.state.activeTape=null),{value:a,grads:o}})}customGrad(e){return P(_s(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{P(t.every(i=>i instanceof nt),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let r,n={};t.forEach((i,o)=>{n[o]=i});let a=(i,o)=>(r=e(...t,o),P(r.value instanceof nt,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),P(_s(r.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),r.value),s=(i,o)=>{let l=r.gradFunc(i,o),u=Array.isArray(l)?l:[l];P(u.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(...)."),P(u.every(h=>h instanceof nt),()=>"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 d={};return u.forEach((h,p)=>{d[p]=()=>h}),d};return this.runKernelFunc({forwardFunc:a,backwardsFunc:s,inputs:n})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){let t=qp(),r=await this.backend.time(e);return r.wallMs=qp()-t,r}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 Yb;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}},_y=Rg;_y.nextTensorId=0;_y.nextVariableId=0;function M$(e){let t=Ny(It(e),"float32");return B.makeTensor(t,e,"float32")}function u6(){let e=X7();if(e._tfengine==null){let t=new q7(e);e._tfengine=new _y(t)}return e$(e._tfengine.ENV),S$(()=>e._tfengine),e._tfengine}var B=u6();function F$(e,t){let r={a:e,b:t};return B.runKernel(Qa,r)}var kh={};Be(kh,{isBrowser:()=>d6,isMobile:()=>O$,mockIsMobile:()=>P$});function _$(){return typeof navigator!="undefined"&&navigator!=null}var $g;function P$(e){$g=e}function O$(e){if($g!==void 0)return $g;if(e||_$()){if(e||(e=navigator),e.product==="ReactNative")return!0;let t=e.userAgent||e.vendor||(typeof window!="undefined"?window.opera:"");if(!t){let r=e;return r.userAgentData&&r.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 d6(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Rn=Z();Rn.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.")});Rn.registerFlag("IS_BROWSER",()=>d6());Rn.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Rn.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Rn.registerFlag("PROD",()=>!1);Rn.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Rn.getBool("DEBUG"));Rn.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Rn.registerFlag("IS_TEST",()=>!1);Rn.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);Rn.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);Rn.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);Rn.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY",()=>!1);function _a(e,t){let r=e;if(Sr(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let n=[];for(;Array.isArray(r)||Sr(r)&&t!=="string";)n.push(r.length),r=r[0];return Array.isArray(e)&&Z().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&p6(e,n,[]),n}function p6(e,t,r){if(r=r||[],!Array.isArray(e)&&!Sr(e)){P(t.length===0,()=>`Element arr[${r.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}P(t.length>0,()=>`Element arr[${r.join("][")}] should be a primitive, but is an array of ${e.length} elements`),P(e.length===t[0],()=>`Element arr[${r.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let n=t.slice(1);for(let a=0;a<e.length;++a)p6(e[a],n,r.concat(a))}function Jb(e,t,r,n){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 '${r}' passed to '${n}' must be ${e} tensor, but got ${t} tensor`)}}function M(e,t,r,n="numeric"){if(e instanceof nt)return Jb(n,e.dtype,t,r),e;let a=of(e);if(a!=="string"&&["bool","int32","float32"].indexOf(n)>=0&&(a=n),Jb(n,a,t,r),e==null||!Sr(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){let o=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${r}' must be a Tensor or TensorLike, but got '${o}'`)}let s=_a(e,a);!Sr(e)&&!Array.isArray(e)&&(e=[e]);let i=a!=="string"?Pf(e,a):$o(e,[],!0);return B.makeTensor(i,s,a)}function Kp(e,t,r,n="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${r} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((a,s)=>M(a,`${t}[${s}]`,r,n))}var h6="__op";function W(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 r=t[0],n=e[r];r.endsWith("_")&&(r=r.substring(0,r.length-1)),r=r+h6;let a=(...s)=>{B.startScope(r);try{let i=n(...s);return Ry(i)&&console.error("Cannot return a Promise inside of tidy."),B.endScope(i),i}catch(i){throw B.endScope(null),i}};return Object.defineProperty(a,"name",{value:r,configurable:!0}),a}function z$(e,t){let r=M(e,"real","complex"),n=M(t,"imag","complex");jr(r.shape,n.shape,`real and imag shapes, ${r.shape} and ${n.shape}, must match in call to tf.complex().`);let a={real:r,imag:n};return B.runKernel(sh,a)}var Ya=W({complex_:z$});function Ui(e,t,r,n){if(n==null&&(n=of(e)),n==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Sr(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){Ey(t);let a=It(t),s=It(r);P(a===s,()=>`Based on the provided shape, [${t}], the tensor should have ${a} values but has ${s}`);for(let i=0;i<r.length;++i){let o=r[i],l=i===r.length-1?o!==It(t.slice(i)):!0;P(r[i]===t[i]||!l,()=>`Error creating a new Tensor. Inferred shape (${r}) does not match the provided shape (${t}). `)}}return!Sr(e)&&!Array.isArray(e)&&(e=[e]),t=t||r,e=n!=="string"?Pf(e,n):$o(e,[],!0),B.makeTensor(e,t,n)}function ft(e,t,r){let n=_a(e,r);return Ui(e,t,n,r)}var Mg={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},$0=4;async function D$(e,t){let r=[],n=[],a=Array.isArray(e)?e.map(i=>i.name):Object.keys(e);for(let i=0;i<a.length;++i){let o=a[i],l=Array.isArray(e)?e[i].tensor:e[o];if(l.dtype!=="float32"&&l.dtype!=="int32"&&l.dtype!=="bool"&&l.dtype!=="string"&&l.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${o}': ${l.dtype}`);let u={name:o,shape:l.shape,dtype:l.dtype};if(l.dtype==="string"){let d=new Promise(async h=>{let p=await l.bytes(),c=p.reduce((g,y)=>g+y.length,0)+$0*p.length,m=new Uint8Array(c),f=0;for(let g=0;g<p.length;g++){let y=p[g],A=new Uint8Array(new Uint32Array([y.length]).buffer);m.set(A,f),f+=$0,m.set(y,f),f+=y.length}h(m)});n.push(d)}else n.push(l.data());t!=null&&(u.group=t),r.push(u)}let s=await Promise.all(n);return{data:L$(s),specs:r}}function c6(e,t){let r={},n,a=0;for(let s of t){let i=s.name,o=s.dtype,l=s.shape,u=It(l),d;if("quantization"in s){let h=s.quantization;if(h.dtype==="uint8"||h.dtype==="uint16"){if(!("min"in h&&"scale"in h))throw new Error(`Weight ${s.name} with quantization ${h.dtype} doesn't have corresponding metadata min and scale.`)}else if(h.dtype==="float16"){if(o!=="float32")throw new Error(`Weight ${s.name} is quantized with ${h.dtype} which only supports weights of type float32 not ${o}.`)}else throw new Error(`Weight ${s.name} has unknown quantization dtype ${h.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let p=Mg[h.dtype],c=e.slice(a,a+u*p),m=h.dtype==="uint8"?new Uint8Array(c):new Uint16Array(c);if(o==="float32")if(h.dtype==="uint8"||h.dtype==="uint16"){d=new Float32Array(m.length);for(let f=0;f<m.length;f++){let g=m[f];d[f]=g*h.scale+h.min}}else if(h.dtype==="float16")n===void 0&&(n=j$()),d=n(m);else throw new Error(`Unsupported quantization type ${h.dtype} for weight type float32.`);else if(o==="int32"){if(h.dtype!=="uint8"&&h.dtype!=="uint16")throw new Error(`Unsupported quantization type ${h.dtype} for weight type int32.`);d=new Int32Array(m.length);for(let f=0;f<m.length;f++){let g=m[f];d[f]=Math.round(g*h.scale+h.min)}}else throw new Error(`Unsupported dtype in weight '${i}': ${o}`);a+=u*p}else if(o==="string"){let h=It(s.shape);d=[];for(let p=0;p<h;p++){let c=new Uint32Array(e.slice(a,a+$0))[0];a+=$0;let m=new Uint8Array(e.slice(a,a+c));d.push(m),a+=c}}else{let h=Mg[o],p=e.slice(a,a+u*h);if(o==="float32")d=new Float32Array(p);else if(o==="int32")d=new Int32Array(p);else if(o==="bool")d=new Uint8Array(p);else if(o==="complex64"){d=new Float32Array(p);let c=new Float32Array(d.length/2),m=new Float32Array(d.length/2);for(let y=0;y<c.length;y++)c[y]=d[y*2],m[y]=d[y*2+1];let f=ft(c,l,"float32"),g=ft(m,l,"float32");r[i]=Ya(f,g),f.dispose(),g.dispose()}else throw new Error(`Unsupported dtype in weight '${i}': ${o}`);a+=u*h}o!=="complex64"&&(r[i]=ft(d,l,o))}return r}function L$(e){if(e===null)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0,r=[];e.forEach(s=>{if(t+=s.byteLength,r.push(s.byteLength===s.buffer.byteLength?s:new s.constructor(s)),!(s instanceof Float32Array||s instanceof Int32Array||s instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${s.constructor.name}`)});let n=new Uint8Array(t),a=0;return r.forEach(s=>{n.set(new Uint8Array(s.buffer),a),a+=s.byteLength}),n.buffer}var Py=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function Qb(e){return Py?Buffer.byteLength(e):new Blob([e]).size}function B$(e){if(Py)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),r="";for(let n=0,a=t.length;n<a;n++)r+=String.fromCharCode(t[n]);return btoa(r)}function W$(e){if(Py){let n=Buffer.from(e,"base64");return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;++n)r.set([t.charCodeAt(n)],n);return r.buffer}function Oy(e){if(e.length===1)return e[0];let t=0;e.forEach(a=>{t+=a.byteLength});let r=new Uint8Array(t),n=0;return e.forEach(a=>{r.set(new Uint8Array(a),n),n+=a.byteLength}),r.buffer}function e4(e){let t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);let r=e.split(t);return r[r.length-1]}function f6(e,t){let r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return e.signature!=null&&(r.signature=e.signature),e.userDefinedMetadata!=null&&(r.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(r.modelInitializer=e.modelInitializer),e.trainingConfig!=null&&(r.trainingConfig=e.trainingConfig),r}async function zy(e,t){let r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(e.trainingConfig!=null&&(r.trainingConfig=e.trainingConfig),e.weightsManifest!=null){let[n,a]=await t(e.weightsManifest);r.weightSpecs=n,r.weightData=a}return e.signature!=null&&(r.signature=e.signature),e.userDefinedMetadata!=null&&(r.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(r.modelInitializer=e.modelInitializer),r}function Ih(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:Qb(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:Qb(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function V$(){let e=r=>{let n=r<<13,a=0;for(;(n&8388608)===0;)a-=8388608,n<<=1;return n&=-8388609,a+=947912704,n|a},t=new Uint32Array(2048);t[0]=0;for(let r=1;r<1024;r++)t[r]=e(r);for(let r=1024;r<2048;r++)t[r]=939524096+(r-1024<<13);return t}function U$(){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 G$(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function j$(){let e=V$(),t=U$(),r=G$();return n=>{let a=new ArrayBuffer(4*n.length),s=new Uint32Array(a);for(let i=0;i<n.length;i++){let o=n[i],l=e[r[o>>10]+(o&1023)]+t[o>>10];s[i]=l}return new Float32Array(a)}}var Wt=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Wt.instance==null&&(Wt.instance=new Wt),Wt.instance}static registerSaveRouter(e){Wt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Wt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Wt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Wt.getHandlers(e,"load",t)}static getHandlers(e,t,r){let n=[];return(t==="load"?Wt.getInstance().loadRouters:Wt.getInstance().saveRouters).forEach(a=>{let s=a(e,r);s!==null&&n.push(s)}),n}},H$=e=>Wt.registerSaveRouter(e),q$=e=>Wt.registerLoadRouter(e),X$=e=>Wt.getSaveHandlers(e),K$=(e,t)=>Wt.getLoadHandlers(e,t),Fg="tensorflowjs",_g=1,Io="models_store",Es="model_info_store";function m6(){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 Pg(e){let t=e.result;t.createObjectStore(Io,{keyPath:"modelPath"}),t.createObjectStore(Es,{keyPath:"modelPath"})}var Mo=class{constructor(e){if(this.indexedDB=m6(),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((r,n)=>{let a=this.indexedDB.open(Fg,_g);a.onupgradeneeded=()=>Pg(a),a.onsuccess=()=>{let s=a.result;if(t==null){let i=s.transaction(Io,"readonly"),o=i.objectStore(Io).get(this.modelPath);o.onsuccess=()=>{if(o.result==null)return s.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));r(o.result.modelArtifacts)},o.onerror=l=>(s.close(),n(o.error)),i.oncomplete=()=>s.close()}else{let i=Ih(t),o=s.transaction(Es,"readwrite"),l=o.objectStore(Es),u=l.put({modelPath:this.modelPath,modelArtifactsInfo:i}),d;u.onsuccess=()=>{d=s.transaction(Io,"readwrite");let h=d.objectStore(Io).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i});h.onsuccess=()=>r({modelArtifactsInfo:i}),h.onerror=p=>{l=o.objectStore(Es);let c=l.delete(this.modelPath);c.onsuccess=()=>(s.close(),n(h.error)),c.onerror=m=>(s.close(),n(h.error))}},u.onerror=h=>(s.close(),n(u.error)),o.oncomplete=()=>{d==null?s.close():d.oncomplete=()=>s.close()}}},a.onerror=s=>n(a.error)})}};Mo.URL_SCHEME="indexeddb://";var g6=e=>Z().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Mo.URL_SCHEME)?Z$(e.slice(Mo.URL_SCHEME.length)):null;Wt.registerSaveRouter(g6);Wt.registerLoadRouter(g6);function Z$(e){return new Mo(e)}function Y$(e){return e.startsWith(Mo.URL_SCHEME)?e.slice(Mo.URL_SCHEME.length):e}var J$=class{constructor(){this.indexedDB=m6()}async listModels(){return new Promise((e,t)=>{let r=this.indexedDB.open(Fg,_g);r.onupgradeneeded=()=>Pg(r),r.onsuccess=()=>{let n=r.result,a=n.transaction(Es,"readonly"),s=a.objectStore(Es).getAll();s.onsuccess=()=>{let i={};for(let o of s.result)i[o.modelPath]=o.modelArtifactsInfo;e(i)},s.onerror=i=>(n.close(),t(s.error)),a.oncomplete=()=>n.close()},r.onerror=n=>t(r.error)})}async removeModel(e){return e=Y$(e),new Promise((t,r)=>{let n=this.indexedDB.open(Fg,_g);n.onupgradeneeded=()=>Pg(n),n.onsuccess=()=>{let a=n.result,s=a.transaction(Es,"readwrite"),i=s.objectStore(Es),o=i.get(e),l;o.onsuccess=()=>{if(o.result==null)return a.close(),r(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let u=i.delete(e),d=()=>{l=a.transaction(Io,"readwrite");let h=l.objectStore(Io).delete(e);h.onsuccess=()=>t(o.result.modelArtifactsInfo),h.onerror=p=>r(o.error)};u.onsuccess=d,u.onerror=h=>(d(),a.close(),r(o.error))}},o.onerror=u=>(a.close(),r(o.error)),s.oncomplete=()=>{l==null?a.close():l.oncomplete=()=>a.close()}},n.onerror=a=>r(n.error)})}},Xa="/",bu="tensorflowjs_models",y6="info",Q$="model_topology",eM="weight_specs",tM="weight_data",rM="model_metadata";function A6(e){return{info:[bu,e,y6].join(Xa),topology:[bu,e,Q$].join(Xa),weightSpecs:[bu,e,eM].join(Xa),weightData:[bu,e,tM].join(Xa),modelMetadata:[bu,e,rM].join(Xa)}}function x6(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function nM(e){let t=e.split(Xa);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Xa)}function aM(e){return e.startsWith(Fo.URL_SCHEME)?e.slice(Fo.URL_SCHEME.length):e}var Fo=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=A6(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),r=JSON.stringify(e.weightSpecs),n=Ih(e);try{this.LS.setItem(this.keys.info,JSON.stringify(n)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,r),this.LS.setItem(this.keys.weightData,B$(e.weightData));let a={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(a)),{modelArtifactsInfo:n}}catch(a){throw x6(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=${n.modelTopologyBytes}, weightSpecsBytes=${n.weightSpecsBytes}, weightDataBytes=${n.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={},r=JSON.parse(this.LS.getItem(this.keys.topology));if(r==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=r;let n=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(n==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=n;let a=this.LS.getItem(this.keys.modelMetadata);if(a!=null){let i=JSON.parse(a);t.format=i.format,t.generatedBy=i.generatedBy,t.convertedBy=i.convertedBy,i.signature!=null&&(t.signature=i.signature),i.userDefinedMetadata!=null&&(t.userDefinedMetadata=i.userDefinedMetadata),i.modelInitializer!=null&&(t.modelInitializer=i.modelInitializer),i.trainingConfig!=null&&(t.trainingConfig=i.trainingConfig)}let s=this.LS.getItem(this.keys.weightData);if(s==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=W$(s),t}};Fo.URL_SCHEME="localstorage://";var b6=e=>Z().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Fo.URL_SCHEME)?sM(e.slice(Fo.URL_SCHEME.length)):null;Wt.registerSaveRouter(b6);Wt.registerLoadRouter(b6);function sM(e){return new Fo(e)}var iM=class{constructor(){P(Z().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),P(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=bu+Xa,r=Xa+y6;for(let n=0;n<this.LS.length;++n){let a=this.LS.key(n);if(a.startsWith(t)&&a.endsWith(r)){let s=nM(a);e[s]=JSON.parse(this.LS.getItem(a))}}return e}async removeModel(e){e=aM(e);let t=A6(e);if(this.LS.getItem(t.info)==null)throw new Error(`Cannot find model at path '${e}'`);let r=JSON.parse(this.LS.getItem(t.info));return x6(t),r}},Iu="://",Nn=class{constructor(){this.managers={}}static getInstance(){return Nn.instance==null&&(Nn.instance=new Nn),Nn.instance}static registerManager(e,t){P(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Iu)&&(e=e.slice(0,e.indexOf(Iu))),P(e.length>0,()=>"scheme must not be an empty string.");let r=Nn.getInstance();P(r.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),r.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 c0(e){if(e.indexOf(Iu)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Nn.getSchemes().join(",")}`);return{scheme:e.split(Iu)[0],path:e.split(Iu)[1]}}async function v6(e,t,r=!1){P(e!==t,()=>`Old path and new path are the same: '${e}'`);let n=Wt.getLoadHandlers(e);P(n.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),P(n.length<2,()=>`Copying failed because more than one (${n.length}) load handlers for source URL ${e}.`);let a=n[0],s=Wt.getSaveHandlers(t);P(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),P(s.length<2,()=>`Copying failed because more than one (${n.length}) save handlers for destination URL ${t}.`);let i=s[0],o=c0(e).scheme,l=c0(e).path,u=o===c0(e).scheme,d=await a.load();r&&u&&await Nn.getManager(o).removeModel(l);let h=await i.save(d);return r&&!u&&await Nn.getManager(o).removeModel(l),h.modelArtifactsInfo}async function oM(){let e=Nn.getSchemes(),t={};for(let r of e){let n=await Nn.getManager(r).listModels();for(let a in n){let s=r+Iu+a;t[s]=n[a]}}return t}async function lM(e){let t=c0(e);return Nn.getManager(t.scheme).removeModel(t.path)}async function uM(e,t){return v6(e,t,!1)}async function dM(e,t){return v6(e,t,!0)}var pM=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 pM);try{Nn.registerManager(Fo.URL_SCHEME,new iM)}catch(e){}try{Nn.registerManager(Mo.URL_SCHEME,new J$)}catch(e){}}var hM={importFetch:()=>xR()},gg,cM=class{constructor(){this.util=bR(),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return Z().global.fetch!=null?Z().global.fetch(e,t):(gg==null&&(gg=hM.importFetch()),gg(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().get("IS_BROWSER")&&Z().setPlatform("node",new cM);function De(e,t="float32",r){return t=t||"float32",Ey(e),new ir(e,t,r)}function fM(e,t){let r=M(e,"x","cast");if(!V7(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&r.dtype!=="string"||t!=="string"&&r.dtype==="string")throw new Error("Only strings can be casted to strings");let n={x:r},a={dtype:t};return B.runKernel(ei,n,a)}var me=W({cast_:fM});function mM(e){let t={x:M(e,"x","clone","string_or_numeric")};return B.runKernel(mi,t)}var Vr=W({clone_:mM});function w6(e,t=!1){console.log(e.toString(t))}u6();var gM={buffer:De,cast:me,clone:Vr,print:w6};C$(gM);var Cr={};Be(Cr,{browserFiles:()=>kM,browserHTTPRequest:()=>NM,concatenateArrayBuffers:()=>Oy,copyModel:()=>uM,decodeWeights:()=>c6,encodeWeights:()=>D$,fromMemory:()=>RM,fromMemorySync:()=>T6,getLoadHandlers:()=>K$,getModelArtifactsForJSON:()=>zy,getModelArtifactsInfoForJSON:()=>Ih,getSaveHandlers:()=>X$,http:()=>Ly,isHTTPScheme:()=>zg,listModels:()=>oM,loadWeights:()=>IM,moveModel:()=>dM,registerLoadRouter:()=>q$,registerSaveRouter:()=>H$,removeModel:()=>lM,weightsLoaderFactory:()=>I6,withSaveHandler:()=>$M,withSaveHandlerSync:()=>MM});var yM="model",AM=".json",xM=".weights.bin";function t4(e){return new Promise(t=>setTimeout(t)).then(e)}var Og=class{constructor(e){if(!Z().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Og.URL_SCHEME)&&(e=e.slice(Og.URL_SCHEME.length)),(e==null||e.length===0)&&(e=yM),this.modelJsonFileName=e+AM,this.weightDataFileName=e+xM}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 r=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],n=f6(e,r),a=window.URL.createObjectURL(new Blob([JSON.stringify(n)],{type:"application/json"})),s=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(s.download=this.modelJsonFileName,s.href=a,await t4(()=>s.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let i=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;i.download=this.weightDataFileName,i.href=t,await t4(()=>i.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Ih(e)}}}},M0=Og;M0.URL_SCHEME="downloads://";var bM=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 r=new FileReader;r.onload=n=>{let a=JSON.parse(n.target.result),s=a.modelTopology;if(s==null){t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));return}if(a.weightsManifest==null){t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));return}if(this.weightsFiles.length===0){e({modelTopology:s});return}let i=zy(a,o=>this.loadWeights(o));e(i)},r.onerror=n=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),r.readAsText(this.jsonFile)})}loadWeights(e){let t=[],r=[];for(let s of e)t.push(...s.weights),r.push(...s.paths);let n=this.checkManifestAndWeightFiles(e),a=r.map(s=>this.loadWeightsFile(s,n[s]));return Promise.all(a).then(s=>[t,Oy(s)])}loadWeightsFile(e,t){return new Promise((r,n)=>{let a=new FileReader;a.onload=s=>{let i=s.target.result;r(i)},a.onerror=s=>n(`Failed to weights data from file of path '${e}'.`),a.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){let t=[],r=this.weightsFiles.map(a=>e4(a.name)),n={};for(let a of e)a.paths.forEach(s=>{let i=e4(s);if(t.indexOf(i)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${i}'`);if(t.push(i),r.indexOf(i)===-1)throw new Error(`Weight file with basename '${i}' is not provided.`);n[s]=this.weightsFiles[r.indexOf(i)]});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 n}},vM=e=>Z().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(M0.URL_SCHEME)?wM(e.slice(M0.URL_SCHEME.length)):null;Wt.registerSaveRouter(vM);function wM(e="model"){return new M0(e)}function kM(e){return new bM(e)}function r4(e,t,r,n){i(e),r=r==null?0:r,n=n==null?1:n,o(r,n);let a=0,s=l=>(l.then(u=>{let d=r+ ++a/e.length*(n-r);return t(d),u}),l);function i(l){P(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function o(l,u){P(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),P(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),P(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(e.map(s))}async function k6(e,t){t==null&&(t={});let r=t.fetchFunc==null?Z().platform.fetch:t.fetchFunc,n=e.map(u=>r(u,t.requestInit,{isBinary:!0})),a=0,s=.5,i=(t.onProgress==null?await Promise.all(n):await r4(n,t.onProgress,a,s)).map(u=>u.arrayBuffer()),o=.5,l=1;return t.onProgress==null?await Promise.all(i):await r4(i,t.onProgress,o,l)}async function IM(e,t="",r,n){return I6(a=>k6(a,{requestInit:n}))(e,t,r)}function I6(e){return async(t,r="",n)=>{let a=t.map(()=>!1),s={},i=n!=null?n.map(()=>!1):[],o=[];if(t.forEach((c,m)=>{let f=0;c.weights.forEach(g=>{let y="quantization"in g?g.quantization.dtype:g.dtype,A=Mg[y]*It(g.shape),x=()=>{a[m]=!0,s[m]==null&&(s[m]=[]),s[m].push({manifestEntry:g,groupOffset:f,sizeBytes:A})};n!=null?n.forEach((b,w)=>{b===g.name&&(x(),i[w]=!0)}):x(),o.push(g.name),f+=A})}),!i.every(c=>c)){let c=n.filter((m,f)=>!i[f]);throw new Error(`Could not find weights in manifest with names: ${c.join(", ")}.
|
|
Manifest JSON has weights with names: ${o.join(", ")}.`)}let l=a.reduce((c,m,f)=>(m&&c.push(f),c),[]),u=[];l.forEach(c=>{t[c].paths.forEach(m=>{let f=r+(r.endsWith("/")?"":"/")+m;u.push(f)})});let d=await e(u),h={},p=0;return l.forEach(c=>{let m=t[c].paths.length,f=0;for(let x=0;x<m;x++)f+=d[p+x].byteLength;let g=new ArrayBuffer(f),y=new Uint8Array(g),A=0;for(let x=0;x<m;x++){let b=new Uint8Array(d[p+x]);y.set(b,A),A+=b.byteLength}s[c].forEach(x=>{let b=g.slice(x.groupOffset,x.groupOffset+x.sizeBytes),w=c6(b,[x.manifestEntry]);for(let I in w)h[I]=w[I]}),p+=m}),h}}var SM="application/octet-stream",CM="application/json",Dy=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?(P(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,P(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&P(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 r=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],n=f6(e,r);t.body.append("model.json",new Blob([JSON.stringify(n)],{type:CM}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:SM}),"model.weights.bin");let a=await this.fetch(this.path,t);if(a.ok)return{modelArtifactsInfo:Ih(e),responses:[a]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${a.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(a){let s=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?s+=" 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.":s+=" Please make sure the server is serving valid JSON for this request.",new Error(s)}let r=t.modelTopology,n=t.weightsManifest;if(r==null&&n==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return zy(t,a=>this.loadWeights(a))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[r,n]=TM(t),a=this.weightPathPrefix||r,s=[];for(let u of e)s.push(...u.weights);let i=[],o=[];for(let u of e)for(let d of u.paths)this.weightUrlConverter!=null?o.push(this.weightUrlConverter(d)):i.push(a+d+n);this.weightUrlConverter&&i.push(...await Promise.all(o));let l=await k6(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[s,Oy(l)]}};Dy.URL_SCHEME_REGEX=/^https?:\/\//;function TM(e){let t=e.lastIndexOf("/"),r=e.lastIndexOf("?"),n=e.substring(0,t),a=r>t?e.substring(r):"";return[n+"/",a]}function zg(e){return e.match(Dy.URL_SCHEME_REGEX)!=null}var S6=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let r=!0;if(Array.isArray(e)?r=e.every(n=>zg(n)):r=zg(e),r)return Ly(e,t)}return null};Wt.registerSaveRouter(S6);Wt.registerLoadRouter(S6);function Ly(e,t){return new Dy(e,t)}function NM(e,t){return Ly(e,t)}var yg=class{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}},C6=class{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}},EM=class{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}};function RM(e,t,r,n){let a=arguments;return new EM(T6(...a))}function T6(e,t,r,n){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new yg(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 yg({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 yg({modelTopology:e,weightSpecs:t,weightData:r,trainingConfig:n}))}function $M(e){return new C6(e)}function MM(e){return new C6(e)}var N6={};Be(N6,{confusionMatrix:()=>XM});function FM(e,t,r=!1,n=!1){let a=M(e,"a","matMul"),s=M(t,"b","matMul");[a,s]=Lt(a,s);let i={a,b:s},o={transposeA:r,transposeB:n};return B.runKernel(Qs,i,o)}var Ye=W({matMul_:FM});function _M(e,t,r=1,n=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let a={indices:M(e,"indices","oneHot","int32")},s={depth:t,onValue:r,offValue:n};return B.runKernel(hl,a,s)}var Zp=W({oneHot_:_M});function By(){Z().set("PROD",!0)}function PM(){Z().set("DEBUG",!0)}function OM(){Z().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Wy(e){Z().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}T$(Wy);function zM(){B.disposeVariables()}function Xt(){return B}function F0(){return B.memory()}function DM(e){return B.profile(e)}function X(e,t){return B.tidy(e,t)}function ee(e){Fy(e).forEach(t=>t.dispose())}function mr(e){return B.keep(e)}function LM(e){return B.time(e)}function Vy(e){return B.setBackend(e)}function xd(){return B.ready()}function Hr(){return B.backendName}function BM(e){B.removeBackend(e)}function Uy(e){return B.findBackend(e)}function WM(e){return B.findBackendFactory(e)}function Rl(e,t,r=1){return B.registerBackend(e,t,r)}function Dn(){return B.backend}function VM(e,t){Z().setPlatform(e,t)}function UM(e){let t={input:M(e,"input","imag")};return B.runKernel(dh,t)}var Sh=W({imag_:UM});function GM(e){let t={x:M(e,"x","neg")};return B.runKernel(ol,t)}var Mt=W({neg_:GM});function jM(e){let t={input:M(e,"input","real")};return B.runKernel(ch,t)}var Ru=W({real_:jM});function HM(e,t,r){let n=M(e,"x","transpose");if(t==null&&(t=n.shape.map((i,o)=>o).reverse()),P(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(i=>{P(i>=0&&i<n.rank,()=>`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();let a={x:n},s={perm:t};return n.dtype==="complex64"?X(()=>{let i=Ru(n),o=Sh(n);return i=B.runKernel($a,{x:i},s),o=B.runKernel($a,{x:o},s),r&&(o=Mt(o)),Ya(i,o)}):B.runKernel($a,a,s)}var tt=W({transpose_:HM});function qM(e,t,r){let n=M(e,"labels","confusionMatrix"),a=M(t,"predictions","confusionMatrix");P(r==null||r>0&&Number.isInteger(r),()=>`If provided, numClasses must be a positive integer, but got ${r}`),P(n.rank===1,()=>`Expected the rank of labels to be 1, but got ${n.rank}`),P(a.rank===1,()=>`Expected the rank of predictions to be 1, but got ${a.rank}`),P(n.shape[0]===a.shape[0],()=>`Mismatch in the number of examples: ${n.shape[0]} vs. ${a.shape[0]}. Labels and predictions should have the same number of elements.`),P(r>0&&Number.isInteger(r),()=>`numClasses is required to be a positive integer, but got ${r}`);let s=Zp(me(n,"int32"),r),i=Zp(me(a,"int32"),r),o=tt(s),l=Ye(o,i);return me(l,"int32")}var XM=W({confusionMatrix_:qM}),$l={};Be($l,{assertAndGetBroadcastShape:()=>At,getBroadcastDims:()=>E6,getReductionAxes:()=>Jt});function E6(e,t){let r=e.length,n=[];for(let a=0;a<r;a++){let s=r-1-a,i=e[s]||1;(t[t.length-1-a]||1)>1&&i===1&&n.unshift(s)}return n}function Jt(e,t){let r=[];for(let n=0;n<t.length;n++){let a=e[e.length-n-1],s=t.length-n-1,i=t[s];(a==null||a===1&&i>1)&&r.unshift(s)}return r}function At(e,t){let r=[],n=Math.max(e.length,t.length);for(let a=0;a<n;a++){let s=e[e.length-a-1];s==null&&(s=1);let i=t[t.length-a-1];if(i==null&&(i=1),s===1)r.unshift(i);else if(i===1)r.unshift(s);else if(s!==i){let o=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(o)}else r.unshift(s)}return r}var Ln={};Be(Ln,{fromPixels:()=>tF,fromPixelsAsync:()=>QM,toPixels:()=>eF});function R6(e,t,r){if(Uo(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let n=_a(e,r);if(n.length!==3&&n.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Ui(e,t,n,r)}var mo;function $6(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 r=!1,n=!1,a=!1,s=!1,i=!1,o=!1;if(e.data instanceof Uint8Array)r=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)n=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)a=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)s=!0;else if(e.getContext!=null)i=!0;else if(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)o=!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(a&&a&&e.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.");if(E0(jp,B.backendName)!=null){let p={pixels:e},c={numChannels:t};return B.runKernel(jp,p,c)}let[l,u]=a?[e.videoWidth,e.videoHeight]:[e.width,e.height],d;if(i)d=e.getContext("2d").getImageData(0,0,l,u).data;else if(n||r)d=e.data;else if(s||a||o){if(mo==null)if(typeof document=="undefined")if(typeof OffscreenCanvas!="undefined"&&typeof OffscreenCanvasRenderingContext2D!="undefined")mo=new OffscreenCanvas(1,1).getContext("2d");else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");else{let p=Z().getBool("CANVAS2D_WILL_READ_FREQUENTLY");mo=document.createElement("canvas").getContext("2d",{willReadFrequently:p})}mo.canvas.width=l,mo.canvas.height=u,mo.drawImage(e,0,0,l,u),d=mo.getImageData(0,0,l,u).data}let h;if(t===4)h=new Int32Array(d);else{let p=l*u;h=new Int32Array(p*t);for(let c=0;c<p;c++)for(let m=0;m<t;++m)h[c*t+m]=d[c*4+m]}return R6(h,[u,l,t],"int32")}function KM(e){return e!=null&&e.data instanceof Uint8Array}function ZM(){return typeof window!="undefined"&&typeof ImageBitmap!="undefined"&&window.hasOwnProperty("createImageBitmap")}function YM(e){return e!=null&&e.width!==0&&e.height!==0}function JM(e){return ZM()&&!(e instanceof ImageBitmap)&&YM(e)&&!KM(e)}async function QM(e,t=3){let r=null;if(Z().getBool("WRAP_TO_IMAGEBITMAP")&&JM(e)){let n;try{n=await createImageBitmap(e,{premultiplyAlpha:"none"})}catch(a){n=null}n!=null&&n.width===e.width&&n.height===e.height?r=n:r=e}else r=e;return $6(r,t)}async function eF(e,t){let r=M(e,"img","toPixels");if(!(e instanceof nt)){let u=r;r=me(u,"int32"),u.dispose()}if(r.rank!==2&&r.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${r.rank}.`);let[n,a]=r.shape.slice(0,2),s=r.rank===2?1:r.shape[2];if(s>4||s===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${s}`);if(r.dtype!=="float32"&&r.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${r.dtype}. Please use float32 or int32 tensors.`);let i=await r.data(),o=r.dtype==="float32"?255:1,l=new Uint8ClampedArray(a*n*4);for(let u=0;u<n*a;++u){let d=[0,0,0,255];for(let p=0;p<s;p++){let c=i[u*s+p];if(r.dtype==="float32"){if(c<0||c>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${c}.`)}else if(r.dtype==="int32"&&(c<0||c>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${c}.`);s===1?(d[0]=c*o,d[1]=c*o,d[2]=c*o):d[p]=c*o}let h=u*4;l[h+0]=Math.round(d[0]),l[h+1]=Math.round(d[1]),l[h+2]=Math.round(d[2]),l[h+3]=Math.round(d[3])}if(t!=null){t.width=a,t.height=n;let u=t.getContext("2d"),d=new ImageData(l,a,n);u.putImageData(d,0,0)}return r!==e&&r.dispose(),l}var tF=W({fromPixels_:$6}),Gy={};Be(Gy,{prepareAndValidate:()=>M6});function M6(e,t){let r=e.shape.length,n=t.shape.length;if(r<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${r}.`);if(n<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${n}.`);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[n-1]>r)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[n-1]} vs. ${r}`);if(It(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let a=t.shape,s=a[a.length-1],i=1;for(let h=0;h<a.length-1;++h)i*=a[h];let o=e.shape,l=a.slice();l.pop();let u=1;for(let h=s;h<r;++h)u*=o[h],l.push(o[h]);let d=[...ju(e.shape).map(h=>h/u),1].slice(0,s);return[l,i,u,d]}var jy={};Be(jy,{calculateShapes:()=>F6,validateInput:()=>qy,validateUpdateShape:()=>Hy});function Hy(e,t,r){let n=t.rank>1?t.shape[t.rank-1]:1,a=t.rank>1?t.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${r.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${n}, and batchDim: ${a}.`;if(r.rank<a)throw new Error(s+` update.rank < ${a}. `);if(e.length<n+(r.rank-a))throw new Error(s+` Output shape length < ${n+(r.rank-a)}`);if(r.rank!==a+e.length-n)throw new Error(s+` update.rank != ${a+e.length-n}`);for(let i=0;i<a;++i)if(r.shape[i]!==t.shape[i])throw new Error(s+` updates.shape[${i}] (${r.shape[i]}) != indices.shape[${i}] (${t.shape[i]}).`);for(let i=0;i<r.rank-a;++i)if(r.shape[i+a]!==e[i+n])throw new Error(s+` updates.shape[${i+a}] (${r.shape[i+a]}) != shape[${i+a}] (${e[i+a]})`)}function qy(e,t,r){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(r.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${r}`);if(r.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}`)}Hy(r,t,e)}function F6(e,t,r){let n=t.shape.length,a=n>1?t.shape[n-1]:1,s=r.length,i=1;for(let h=a;h<s;++h)i*=r[h];let o=a<1?1:a,l=It(t.shape)/o,u=[...ju(r.slice(0,a)),1],d=It(r);return{sliceRank:a,numUpdates:l,sliceSize:i,strides:u,outputSize:d}}var Dt={};Be(Dt,{assertParamsValid:()=>nF,computeFlatOffset:()=>lF,computeOutShape:()=>sF,getNormalizedAxes:()=>iF,isSliceContinous:()=>oF,maskToAxes:()=>aF,parseSliceParams:()=>V6,sliceInfo:()=>uF,startForAxis:()=>B6,startIndicesWithElidedDims:()=>z6,stopForAxis:()=>W6,stopIndicesWithElidedDims:()=>D6,stridesForAxis:()=>L6,stridesWithElidedDims:()=>_6});var Dg=-2,rF=-1;function nF(e,t,r){let n=e.shape.length;P(n===t.length,()=>`Error in slice${n}D: Length of begin ${t} must match the rank of the array (${n}).`),P(n===r.length,()=>`Error in slice${n}D: Length of size ${r} must match the rank of the array (${n}).`);for(let a=0;a<n;++a)P(t[a]+r[a]<=e.shape[a],()=>`Error in slice${n}D: begin[${a}] + size[${a}] (${t[a]+r[a]}) would overflow input.shape[${a}] (${e.shape[a]})`)}function aF(e){let t=[],r=0;for(;e>0;)e&1&&t.push(r),e/=2,r++;return t}function sF(e,t,r){let n=[];for(let a=0;a<e.length;a++)n[a]=Math.ceil((t[a]-e[a])/r[a]);return n}function _6(e,t,r,n){let a=[...e];for(let s=a.length;s<n.length;s++)a.push(1);for(let s=0;s<r;s++)s===0?a[t]=1:(a.splice(t,0,1),a.pop());return a}function P6(e,t,r){return r<=e?r:r-(t-1)}function O6(e,t){let r=[];for(let n=0;n<e;n++)r.push(t+n);return r}function iF(e,t,r,n,a,s,i,o,l){let u=e.length,d=new Array(u),h=new Array(u),p=new Array(u);if(t.length&&r>0){let c=t[0],m=r+1;d=z6(i,c,m,n,e),h=D6(o,c,m,a,e),p=_6(s,c,m,e)}else for(let c=0;c<u;c++)d[c]=B6(i,n,s,e,c,l),h[c]=W6(o,a,s,e,c,l),p[c]=L6(s,c,l);return{begin:d,end:h,strides:p}}function z6(e,t,r,n,a){let s=[...a],i=O6(r,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=0;else{let l=P6(t,r,o),u=n[l];e&1<<l&&(u=0),s[o]=u}return s}function D6(e,t,r,n,a){let s=[...a],i=O6(r,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=Number.MAX_SAFE_INTEGER;else{let l=P6(t,r,o),u=n[l];e&1<<l&&(u=Number.MAX_SAFE_INTEGER),s[o]=u}for(let o=0;o<s.length;o++){let l=a[o];s[o]<0&&(s[o]+=l),s[o]=Gp(0,s[o],a[o])}return s}function L6(e,t,r){let n=e[t];return(r&1<<t||n==null)&&(n=1),n}function B6(e,t,r,n,a,s){let i=t[a],o=r[a]||1;(e&1<<a||s&1<<a||i==null)&&(o>0?i=Number.MIN_SAFE_INTEGER:i=Number.MAX_SAFE_INTEGER);let l=n[a];return i<0&&(i+=l),i=Gp(0,i,l-1),i}function W6(e,t,r,n,a,s){let i=t[a],o=r[a]||1;(e&1<<a||s&1<<a||i==null)&&(o>0?i=Number.MAX_SAFE_INTEGER:i=Number.MIN_SAFE_INTEGER);let l=n[a];return i<0&&(i+=l),o>0?i=Gp(0,i,l):i=Gp(-1,i,l-1),i}function oF(e,t,r){let n=r.length;for(let a=0;a<r.length;a++)if(r[a]>1){n=a;break}for(let a=n+1;a<r.length;a++)if(t[a]>0||r[a]!==e[a])return!1;return!0}function lF(e,t){let r=e.length>0?e[e.length-1]:1;for(let n=0;n<e.length-1;n++)r+=e[n]*t[n];return r}function V6(e,t,r){let n,a=e.shape.length;typeof t=="number"?n=[t,...new Array(a-1).fill(0)]:t.length<a?n=t.concat(new Array(a-t.length).fill(0)):n=t.slice(),n.forEach(i=>{P(i!==-1,()=>"slice() does not support negative begin indexing.")});let s;return r==null?s=new Array(a).fill(-1):typeof r=="number"?s=[r,...new Array(a-1).fill(-1)]:r.length<a?s=r.concat(new Array(a-r.length).fill(-1)):s=r,s=s.map((i,o)=>i>=0?i:(P(i===-1,()=>`Negative size values should be exactly -1 but got ${i} for the slice() size at index ${o}.`),e.shape[o]-n[o])),[n,s]}function uF(e,t,r,n,a,s,i,o,l){let u;if(n==null?(u=new Array(t.length),u.fill(1)):u=n,i!=null&&(i&i-1)!==0)throw new Error("Multiple ellipses in slice is not allowed.");let d=!1,h={dims:u.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:r.slice(),strides:u.slice(),beginMask:a,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};for(let A=0;A<h.dims;A++)d&&(1<<A&o)!==0&&h.numAddAxisAfterEllipsis++,1<<A&i&&(d=!0);d||(h.ellipsisMask|=1<<h.dims,h.dims++);let p={dims:e.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};dF(h,p);let c=!0,m=!0,f=!0,g=[],y=[];for(let A=0;A<e.length;++A){if(p.strides[A]===0)throw Error(`strides[${A}] must be non-zero`);let x=!!(p.shrinkAxisMask&1<<A),b=e[A];if(b===-1){g.push(x?1:-1);continue}let w=[p.beginMask&1<<A,p.endMask&1<<A],I=[p.strides[A]>0?0:-1,p.strides[A]>0?b:b-1];if(x&&p.strides[A]<=0)throw Error("only stride 1 allowed on non-range indexing.");f=f&&p.strides[A]===1;let T=!!(p.beginMask&1<<A&&p.endMask&1<<A);if(p.beginValid&&p.endValid){if(x){let $=p.begin[A]<0?b+p.begin[A]:p.begin[A];if(p.begin[A]=$,p.end[A]=p.begin[A]+1,$<0||$>=b)throw Error(`slice index ${p.begin[A]} of dimension ${A} out of bounds.`)}else p.begin[A]=n4(p.begin[A],0,p.strides[A],b,w,I),p.end[A]=n4(p.end[A],1,p.strides[A],b,w,I);let F=p.strides[A]===1&&p.begin[A]===0&&p.end[A]===b;c=c&&F,m=m&&(A===0&&p.strides[A]===1||F)}else c=c&&p.strides[A]===1&&T,m=m&&(A===0&&p.strides[A]===1||T);let E,R=!1;if(p.beginValid&&p.endValid?(E=p.end[A]-p.begin[A],R=!0):x?(E=1,R=!0):T&&b>=0&&(p.strides[A]<0?E=-b:E=b,R=!0),R){let F;E===0||E<0!=p.strides[A]<0?F=0:F=Math.trunc(E/p.strides[A])+(E%p.strides[A]!==0?1:0),g.push(F)}else g.push(-1)}for(let A=0;A<p.finalShapeGatherIndices.length;++A){let x=p.finalShapeGatherIndices[A];x>=0?y.push(g[x]):x===Dg&&y.push(1)}return{finalShapeSparse:y.filter((A,x)=>p.finalShapeGatherIndices[x]!==Dg),finalShape:y,isIdentity:c,sliceDim0:m,isSimpleSlice:f,begin:p.begin,end:p.end,strides:p.strides}}function dF(e,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let r=0;t.beginValid=e.begin!=null,t.endValid=e.end!=null,t.begin=new Array(t.dims),t.end=new Array(t.dims),t.strides=new Array(t.dims),t.finalShapeGatherIndices=[],t.finalShapeGatherIndicesSparse=[],t.inputShapeGatherIndicesSparse=new Array(t.dims);for(let n=0;n<e.dims;n++)if(1<<n&e.ellipsisMask){let a=Math.min(t.dims-(e.dims-n)+1+e.numAddAxisAfterEllipsis,t.dims);for(;r<a;r++)t.begin[r]=0,t.end[r]=0,t.strides[r]=1,t.beginMask|=1<<r,t.endMask|=1<<r,t.finalShapeGatherIndices.push(r),t.finalShapeGatherIndicesSparse.push(-1),t.inputShapeGatherIndicesSparse[r]=n}else if(1<<n&e.newAxisMask)t.finalShapeGatherIndices.push(Dg),t.finalShapeGatherIndicesSparse.push(-1);else{if(r===t.begin.length)throw Error(`Index out of range using input dim ${r}; input has only ${t.dims} dims, ${t.begin.length}.`);e.begin!=null&&(t.begin[r]=e.begin[n]),e.end!=null&&(t.end[r]=e.end[n]),t.strides[r]=e.strides[n],e.beginMask&1<<n&&(t.beginMask|=1<<r),e.endMask&1<<n&&(t.endMask|=1<<r),e.shrinkAxisMask&1<<n?(t.finalShapeGatherIndices.push(rF),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<r):(t.finalShapeGatherIndices.push(r),t.finalShapeGatherIndicesSparse.push(n)),t.inputShapeGatherIndicesSparse[r]=n,r++}}function n4(e,t,r,n,a,s){if(a[t])return r>0?s[t]:s[t+1&1];{let i=e<0?n+e:e;return i<s[0]?s[0]:i>s[1]?s[1]:i}}var ue={};Be(ue,{Serializable:()=>U6,SerializationMap:()=>vo,registerClass:()=>Gi});var U6=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},vo=class{constructor(){this.classNameMap={}}static getMap(){return vo.instance==null&&(vo.instance=new vo),vo.instance}static register(e){vo.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function Gi(e){P(e.className!=null,()=>"Class being registered does not have the static className property defined."),P(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),P(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),vo.register(e)}var G6={};Be(G6,{TEST_EPSILON_FLOAT16:()=>j6,encodeStrings:()=>H6,expectArrayBuffersEqual:()=>yF,expectArraysClose:()=>hF,expectArraysEqual:()=>fF,expectNumbersClose:()=>mF,expectPromiseToFail:()=>cF,expectValuesInRange:()=>gF,testEpsilon:()=>Xy});var pF=.001,j6=.1;function hF(e,t,r){return r==null&&(r=Xy()),Lg(e,t,(n,a)=>Ky(n,a,r))}function Xy(){return B.backend.floatPrecision()===32?pF:j6}function Lg(e,t,r){let n=!0;if((Sr(e)||Sr(t))&&(n=!1),Sr(e)&&Sr(t)&&(n=!0),n){let i=e.constructor.name,o=t.constructor.name;if(i!==o)throw new Error(`Arrays are of different type. Actual: ${i}. Expected: ${o}`)}if(Array.isArray(e)&&Array.isArray(t)){let i=_a(e),o=_a(t);if(!Ks(i,o))throw new Error(`Arrays have different shapes. Actual: [${i}]. Expected: [${o}]`)}let a=Sr(e)?e:$o(e),s=Sr(t)?t:$o(t);if(a.length!==s.length)throw new Error(`Arrays have different lengths actual: ${a.length} vs expected: ${s.length}.
|
|
Actual: ${a}.
|
|
Expected: ${s}.`);for(let i=0;i<s.length;++i){let o=a[i],l=s[i];if(!r(o,l))throw new Error(`Arrays differ: actual[${i}] = ${o}, expected[${i}] = ${l}.
|
|
Actual: ${a}.
|
|
Expected: ${s}.`)}}function cF(e,t){e().then(()=>t.fail(),()=>t())}function fF(e,t){let r=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Ns(e)||Ns(e[0])||Ns(t)||Ns(t[0])?Lg(e,r,(n,a)=>n==a):Lg(e,t,(n,a)=>Ky(n,a,0))}function mF(e,t,r){if(r==null&&(r=Xy()),!Ky(e,t,r))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function Ky(e,t,r){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>r)}function gF(e,t,r){for(let n=0;n<e.length;n++)if(e[n]<t||e[n]>r)throw new Error(`Value out of range:${e[n]} low: ${t}, high: ${r}`)}function yF(e,t){let r=new Float32Array(e),n=new Float32Array(t);if(r.length!==n.length)throw new Error(`Expected ArrayBuffer to be of length ${n.length}, but it was ${r.length}`);for(let a=0;a<n.length;a++)if(r[a]!==n[a])throw new Error(`Expected ArrayBuffer value at ${a} to be ${n[a]} but got ${r[a]} instead`)}function H6(e){for(let t=0;t<e.length;t++){let r=e[t];Array.isArray(r)?H6(r):e[t]=vh(r)}return e}var Zy="0.0.0";function AF(e,t){let r=M(e,"a","add"),n=M(t,"b","add");[r,n]=Lt(r,n);let a={a:r,b:n};return B.runKernel(Qa,a)}var le=W({add_:AF});function xF(e,t){let r=M(e,"a","floorDiv"),n=M(t,"b","floorDiv");[r,n]=Lt(r,n);let a={a:r,b:n};return B.runKernel(hi,a)}var Ch=W({floorDiv_:xF});function bF(e,t){let r=M(e,"a","div"),n=M(t,"b","div");if([r,n]=Lt(r,n),r.dtype==="int32"&&n.dtype==="int32")return Ch(r,n);let a={a:r,b:n},s={};return B.runKernel(li,a,s)}var pe=W({div_:bF});function vF(e,t){let r=M(e,"a","mul"),n=M(t,"b","mul");[r,n]=Lt(r,n);let a={a:r,b:n};return B.runKernel(Si,a)}var L=W({mul_:vF});function wF(e){let t=M(e,"x","abs");if(t.dtype==="complex64"){let r={x:t};return B.runKernel(ih,r)}else{let r={x:t};return B.runKernel(Go,r)}}var ar=W({abs_:wF});function kF(e){let t={x:M(e,"x","acos")};return B.runKernel(Hu,t)}var q6=W({acos_:kF});function IF(e){let t={x:M(e,"x","acosh")};return B.runKernel(qu,t)}var X6=W({acosh_:IF});function SF(e){P(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),P(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((a,s)=>M(a,`tensors${s}`,"addN")),r=t[0];t.forEach(a=>{if(a.dtype!==r.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(a=>{if(!Ks(a.shape,r.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let n=t;return B.runKernel(Zs,n)}var Of=W({addN_:SF});function CF(e,t=null,r=!1){let n={x:M(e,"x","all","bool")},a={axis:t,keepDims:r};return B.runKernel(Xu,n,a)}var Yy=W({all_:CF});function TF(e,t=null,r=!1){let n={x:M(e,"x","any","bool")},a={axis:t,keepDims:r};return B.runKernel(Ku,n,a)}var _0=W({any_:TF});function NF(e,t=0){let r={x:M(e,"x","argMax")},n={axis:t};return B.runKernel(Ys,r,n)}var $n=W({argMax_:NF});function EF(e,t=0){let r={x:M(e,"x","argMin")},n={axis:t};return B.runKernel(Zu,r,n)}var K6=W({argMin_:EF});function RF(e){let t={x:M(e,"x","asin")};return B.runKernel(Yu,t)}var Z6=W({asin_:RF});function $F(e){let t={x:M(e,"x","asinh")};return B.runKernel(Ju,t)}var Y6=W({asinh_:$F});function MF(e){let t={x:M(e,"x","atan")};return B.runKernel(Qu,t)}var J6=W({atan_:MF});function FF(e,t){let r=M(e,"a","atan2"),n=M(t,"b","atan2");[r,n]=Lt(r,n);let a={a:r,b:n};return B.runKernel(td,a)}var Q6=W({atan2_:FF});function _F(e){let t={x:M(e,"x","atanh")};return B.runKernel(ed,t)}var ev=W({atanh_:_F});function PF(e,t,r,n,a="NHWC",s){let i=e[3],o=[...t,i],l=nv(a);return Th(e,o,r,s,n,null,null,l)}function tv(e,t,r,n,a,s,i="channelsLast"){let[o,l]=P0(t),u;if(i==="channelsLast")u=[o,l,e[3],e[3]];else if(i==="channelsFirst")u=[o,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return Th(e,u,r,n,a,s,!1,i)}function OF(e,t,r,n,a,s,i="NDHWC"){let[o,l,u]=Bg(t),d,h;if(i==="NDHWC")h="channelsLast",d=[o,l,u,e[4],e[4]];else if(i==="NCDHW")h="channelsFirst",d=[o,l,u,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return rv(e,d,r,n,a,!1,h,s)}function Th(e,t,r,n,a,s,i=!1,o="channelsLast"){let[l,u,d,h]=[-1,-1,-1,-1];if(o==="channelsLast")[l,u,d,h]=e;else if(o==="channelsFirst")[l,h,u,d]=e;else throw new Error(`Unknown dataFormat ${o}`);let[p,c,,m]=t,[f,g]=P0(r),[y,A]=P0(n),x=Su(p,y),b=Su(c,A),{padInfo:w,outHeight:I,outWidth:T}=LF(a,u,d,f,g,x,b,s,o),E=i?m*h:m,R;return o==="channelsFirst"?R=[l,E,I,T]:o==="channelsLast"&&(R=[l,I,T,E]),{batchSize:l,dataFormat:o,inHeight:u,inWidth:d,inChannels:h,outHeight:I,outWidth:T,outChannels:E,padInfo:w,strideHeight:f,strideWidth:g,filterHeight:p,filterWidth:c,effectiveFilterHeight:x,effectiveFilterWidth:b,dilationHeight:y,dilationWidth:A,inShape:e,outShape:R,filterShape:t}}function rv(e,t,r,n,a,s=!1,i="channelsLast",o){let[l,u,d,h,p]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[l,u,d,h,p]=e;else if(i==="channelsFirst")[l,p,u,d,h]=e;else throw new Error(`Unknown dataFormat ${i}`);let[c,m,f,,g]=t,[y,A,x]=Bg(r),[b,w,I]=Bg(n),T=Su(c,b),E=Su(m,w),R=Su(f,I),{padInfo:F,outDepth:$,outHeight:S,outWidth:z}=BF(a,u,d,h,y,A,x,T,E,R,o),O=s?g*p:g,j;return i==="channelsFirst"?j=[l,O,$,S,z]:i==="channelsLast"&&(j=[l,$,S,z,O]),{batchSize:l,dataFormat:i,inDepth:u,inHeight:d,inWidth:h,inChannels:p,outDepth:$,outHeight:S,outWidth:z,outChannels:O,padInfo:F,strideDepth:y,strideHeight:A,strideWidth:x,filterDepth:c,filterHeight:m,filterWidth:f,effectiveFilterDepth:T,effectiveFilterHeight:E,effectiveFilterWidth:R,dilationDepth:b,dilationHeight:w,dilationWidth:I,inShape:e,outShape:j,filterShape:t}}function zF(e,t,r,n,a){n==null&&(n=Jy(e,t,r));let s=e[0],i=e[1],o=To((s-t+2*n)/r+1,a),l=To((i-t+2*n)/r+1,a);return[o,l]}function DF(e,t,r,n,a,s){a==null&&(a=Jy(e,t,n));let i=e[0],o=e[1],l=e[2],u=To((i-t+2*a)/n+1,s),d=To((o-t+2*a)/n+1,s),h=To((l-t+2*a)/n+1,s);return[u,d,h,r]}function Jy(e,t,r,n=1){let a=Su(t,n);return Math.floor((e[0]*(r-1)-r+a)/2)}function P0(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function Bg(e){return typeof e=="number"?[e,e,e]:e}function Su(e,t){return t<=1?e:e+(e-1)*(t-1)}function LF(e,t,r,n,a,s,i,o,l){let u,d,h;if(typeof e=="number"){u={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let p=zF([t,r],s,n,e,o);d=p[0],h=p[1]}else if(e==="same"){d=Math.ceil(t/n),h=Math.ceil(r/a);let p=Math.max(0,(d-1)*n+s-t),c=Math.max(0,(h-1)*a+i-r),m=Math.floor(p/2),f=p-m,g=Math.floor(c/2),y=c-g;u={top:m,bottom:f,left:g,right:y,type:"SAME"}}else if(e==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},d=Math.ceil((t-s+1)/n),h=Math.ceil((r-i+1)/a);else if(typeof e=="object"){let p=l==="channelsLast"?e[1][0]:e[2][0],c=l==="channelsLast"?e[1][1]:e[2][1],m=l==="channelsLast"?e[2][0]:e[3][0],f=l==="channelsLast"?e[2][1]:e[3][1];u={top:p,bottom:c,left:m,right:f,type:p===0&&c===0&&m===0&&f===0?"VALID":"EXPLICIT"},d=To((t-s+p+c)/n+1,o),h=To((r-i+m+f)/a+1,o)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outHeight:d,outWidth:h}}function BF(e,t,r,n,a,s,i,o,l,u,d){let h,p,c,m;if(typeof e=="number"){h={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let f=DF([t,r,n,1],o,1,a,e,d);p=f[0],c=f[1],m=f[2]}else if(e==="same"){p=Math.ceil(t/a),c=Math.ceil(r/s),m=Math.ceil(n/i);let f=(p-1)*a+o-t,g=(c-1)*s+l-r,y=(m-1)*i+u-n,A=Math.floor(f/2),x=f-A,b=Math.floor(g/2),w=g-b,I=Math.floor(y/2),T=y-I;h={top:b,bottom:w,left:I,right:T,front:A,back:x,type:"SAME"}}else if(e==="valid")h={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-o+1)/a),c=Math.ceil((r-l+1)/s),m=Math.ceil((n-u+1)/i);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:h,outDepth:p,outHeight:c,outWidth:m}}function To(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 Ds(e){let[t,r,n]=P0(e);return t===1&&r===1&&n===1}function za(e,t){return Ds(e)||Ds(t)}function nv(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function qr(e,t,r){if(r!=null){if(typeof t=="string")throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${r} but got pad ${t}.`);if(typeof t=="number")P(Nu(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${r} but got pad ${t}.`);else if(typeof t=="object")t.forEach(n=>{n.forEach(a=>{P(Nu(a),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${r} but got pad ${a}.`)})});else throw Error(`Error in ${e}: Unknown padding parameter: ${t}`)}}function WF(e,t){let r={x:M(e,"x","reshape","string_or_numeric")},n={shape:t};return B.runKernel(fl,r,n)}var U=W({reshape_:WF});function VF(e,t,r,n,a){let s=M(e,"x","avgPool","float32"),i=1;P(za(r,i),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'`);let o=s,l=!1;s.rank===3&&(l=!0,o=U(s,[1,s.shape[0],s.shape[1],s.shape[2]])),P(o.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${o.rank}.`),qr("avgPool",n,a);let u={x:o},d={filterSize:t,strides:r,pad:n,dimRoundingMode:a},h=B.runKernel(Js,u,d);return h=me(h,s.dtype),l?U(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var zf=W({avgPool_:VF});function UF(e,t,r,n,a,s="NDHWC"){let i=M(e,"x","avgPool3d","float32"),o=i,l=!1;i.rank===4&&(l=!0,o=U(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),P(o.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`),P(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),qr("avgPool3d",n,a);let u={x:o},d={filterSize:t,strides:r,pad:n,dimRoundingMode:a,dataFormat:s},h=B.runKernel(ah,u,d);return h=me(h,o.dtype),l?U(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var Qy=W({avgPool3d_:UF});function GF(e,t=0){P(e.length>=1,()=>"Pass at least one tensor to concat");let r=Kp(e,"tensors","concat","string_or_numeric");if(r[0].dtype==="complex64"&&r.forEach(s=>{if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
|
|
with dtype ${s.dtype}. `)}),r.length===1)return Vr(r[0]);let n=r,a={axis:t};return B.runKernel(Ho,n,a)}var St=W({concat_:GF});function jF(e){let t={x:M(e,"x","sigmoid","float32")};return B.runKernel(Pi,t)}var Tr=W({sigmoid_:jF});function HF(e,t,r){let n=M(e,"x","slice","string_or_numeric");if(n.rank===0)throw new Error("Slicing scalar is not possible");let a={x:n},s={begin:t,size:r};return B.runKernel(xl,a,s)}var _e=W({slice_:HF});function qF(e){let t={x:M(e,"x","tanh","float32")};return B.runKernel(Wi,t)}var $u=W({tanh_:qF});function XF(e,t,r,n,a,s){let i=M(e,"forgetBias","basicLSTMCell"),o=M(t,"lstmKernel","basicLSTMCell"),l=M(r,"lstmBias","basicLSTMCell"),u=M(n,"data","basicLSTMCell"),d=M(a,"c","basicLSTMCell"),h=M(s,"h","basicLSTMCell"),p=St([u,h],1),c=Ye(p,o),m=le(c,l),f=m.shape[0],g=m.shape[1]/4,y=[f,g],A=_e(m,[0,0],y),x=_e(m,[0,g],y),b=_e(m,[0,g*2],y),w=_e(m,[0,g*3],y),I=le(L(Tr(A),$u(x)),L(d,Tr(le(i,b)))),T=L($u(I),Tr(w));return[I,T]}var KF=W({basicLSTMCell_:XF});function ZF(e,t,r){let n=M(e,"x","batchToSpaceND"),a=t.reduce((o,l)=>o*l);P(n.rank>=1+t.length,()=>`input rank is ${n.rank} but should be > than blockShape.length ${t.length}`),P(r.length===t.length,()=>`crops.length is ${r.length} but should be equal to blockShape.length ${t.length}`),P(n.shape[0]%a===0,()=>`input tensor batch is ${n.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${a}`);let s={x:n},i={blockShape:t,crops:r};return B.runKernel(jo,s,i)}var Df=W({batchToSpaceND_:ZF});function YF(e){let t;return e.rank===0||e.rank===1?t=U(e,[1,1,1,e.size]):e.rank===2?t=U(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function JF(e,t,r,n,a,s){s==null&&(s=.001);let i=M(e,"x","batchNorm"),o=M(t,"mean","batchNorm"),l=M(r,"variance","batchNorm"),u;a!=null&&(u=M(a,"scale","batchNorm"));let d;n!=null&&(d=M(n,"offset","batchNorm")),P(o.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),P(d==null||o.rank===d.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),P(u==null||o.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let h={x:YF(i),scale:u,offset:d,mean:o,variance:l},p={varianceEpsilon:s},c=B.runKernel(ci,h,p);return U(c,i.shape)}var Mu=W({batchNorm_:JF});function QF(e,t,r,n,a,s){let i=M(e,"x","batchNorm"),o=M(t,"mean","batchNorm"),l=M(r,"variance","batchNorm"),u;a!=null&&(u=M(a,"scale","batchNorm"));let d;return n!=null&&(d=M(n,"offset","batchNorm")),P(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),P(o.rank===2||o.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`),P(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),d!=null&&P(d.rank===2||d.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${d.rank}.`),Mu(i,o,l,d,u,s)}var av=W({batchNorm2d_:QF});function e_(e,t,r,n,a,s){let i=M(e,"x","batchNorm"),o=M(t,"mean","batchNorm"),l=M(r,"variance","batchNorm"),u;a!=null&&(u=M(a,"scale","batchNorm"));let d;return n!=null&&(d=M(n,"offset","batchNorm")),P(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),P(o.rank===3||o.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`),P(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),d!=null&&P(d.rank===3||d.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${d.rank}.`),Mu(i,o,l,d,u,s)}var sv=W({batchNorm3d_:e_});function t_(e,t,r,n,a,s){let i=M(e,"x","batchNorm"),o=M(t,"mean","batchNorm"),l=M(r,"variance","batchNorm"),u;a!=null&&(u=M(a,"scale","batchNorm"));let d;return n!=null&&(d=M(n,"offset","batchNorm")),P(i.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`),P(o.rank===4||o.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`),P(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),d!=null&&P(d.rank===4||d.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${d.rank}.`),Mu(i,o,l,d,u,s)}var iv=W({batchNorm4d_:t_});function r_(e,t,r){let n=M(e,"x","bincount"),a=M(t,"weights","bincount");P(n.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${n.dtype}`),P(r>=0,()=>`size must be non-negative, but got ${r}.`),P(a.size===n.size||a.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${n.shape}, weights shape: ${a.shape}.`);let s={x:n,weights:a},i={size:r};return B.runKernel(pf,s,i)}var e3=W({bincount_:r_});function n_(e,t){let r=M(e,"s0","broadcastArgs","int32"),n=M(t,"s1","broadcastArgs","int32");if(r.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${r.rank}`);if(n.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${n.rank}`);let a={s0:r,s1:n};return B.runKernel(hf,a)}var ov=W({broadcastArgs_:n_});function a_(e,t){let r=M(e,"broadcastTo","x"),n=r.shape;if(t.some(l=>!(l>0)||l%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.length<r.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${r.rank}.`);if(t.length>r.rank){let l=r.shape.slice();for(;l.length<t.length;)l.unshift(1);r=U(r,l)}let a=r.shape,s=Array.from(t);for(let l=t.length-1;l>=0;l--)if(a[l]===t[l])s[l]=1;else if(r.shape[l]!==1)throw new Error(`broadcastTo(): [${n}] cannot be broadcast to [${t}].`);if(s.map((l,u)=>l>1?u:-1).filter(l=>l>=0).length===0)return Vr(r);let i={x:r},o={reps:s};return B.runKernel(ts,i,o)}var Bp=W({broadcastTo_:a_});function s_(e){let t={x:M(e,"x","ceil","float32")};return B.runKernel(ti,t)}var lv=W({ceil_:s_});function i_(e,t,r){let n=M(e,"x","clipByValue");P(t<=r,()=>`Error in clip: min (${t}) must be less than or equal to max (${r}).`);let a={x:n},s={clipValueMin:t,clipValueMax:r};return B.runKernel(es,a,s)}var fn=W({clipByValue_:i_});function o_(e){return St(e,0)}var uv=W({concat1d_:o_});function l_(e,t){return St(e,t)}var bd=W({concat2d_:l_});function u_(e,t){return St(e,t)}var dv=W({concat3d_:u_});function d_(e,t){return St(e,t)}var pv=W({concat4d_:d_});function p_(e,t,r,n,a="NHWC",s=[1,1],i){let o=M(e,"x","conv2d","float32"),l=M(t,"filter","conv2d","float32"),u=o,d=!1;o.rank===3&&(d=!0,u=U(o,[1,o.shape[0],o.shape[1],o.shape[2]])),P(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),P(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),qr("conv2d",n,i);let h=a==="NHWC"?u.shape[3]:u.shape[1];P(h===l.shape[2],()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${l.shape[2]}.`),P(za(r,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${r} and dilations '${s}'`);let p={x:u,filter:l},c={strides:r,pad:n,dataFormat:a,dilations:s,dimRoundingMode:i},m=B.runKernel(ri,p,c);return d?U(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Ls=W({conv2d_:p_});function h_(e,t,r,n,a="NWC",s=1,i){let o=M(e,"x","conv1d"),l=M(t,"filter","conv1d"),u=o,d=!1;o.rank===2&&(d=!0,u=U(o,[1,o.shape[0],o.shape[1]])),P(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),P(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),qr("conv1d",n,i),P(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),P(za(r,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${r} and dilation '${s}'`),P(a==="NWC",()=>`Error in conv1d: got dataFormat of ${a} but only NWC is currently supported.`);let h=U(l,[1,l.shape[0],l.shape[1],l.shape[2]]),p=U(u,[u.shape[0],1,u.shape[1],u.shape[2]]),c=Ls(p,h,[1,r],n,"NHWC",[1,s],i);return d?U(c,[c.shape[2],c.shape[3]]):U(c,[c.shape[0],c.shape[2],c.shape[3]])}var t3=W({conv1d_:h_});function c_(e,t,r,n,a,s="NHWC",i){P(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let o=e,l=t,u=!1;t.rank===3&&(u=!0,l=U(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),P(o.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`),P(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),P(r.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${r.rank}`);let d=s==="NHWC"?o[3]:o[1],h=s==="NHWC"?l.shape[3]:l.shape[1];P(d===r.shape[2],()=>`Error in conv2dDerInput: depth of input (${d}) must match input depth for filter ${r.shape[2]}.`),P(h===r.shape[3],()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${r.shape[3]}.`),qr("conv2dDerInput",a,i);let p={dy:l,filter:r},c={strides:n,pad:a,dataFormat:s,dimRoundingMode:i,inputShape:o},m=B.runKernel(ni,p,c);return u?U(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var r3=W({conv2DBackpropInput_:c_});function f_(e,t,r,n,a,s){let i=M(e,"x","conv2dTranspose"),o=M(t,"filter","conv2dTranspose");return r3(r,i,o,n,a,"NHWC",s)}var n3=W({conv2dTranspose_:f_});function m_(e,t,r,n,a="NDHWC",s=[1,1,1]){let i=M(e,"x","conv3d"),o=M(t,"filter","conv3d"),l=i,u=!1;i.rank===4&&(u=!0,l=U(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),P(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),P(o.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`),P(l.shape[4]===o.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`),P(za(r,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${r} and dilations '${s}'`),P(a==="NDHWC",()=>`Error in conv3d: got dataFormat of ${a} but only NDHWC is currently supported.`);let d={x:l,filter:o},h={strides:r,pad:n,dataFormat:a,dilations:s},p=B.runKernel(oh,d,h);return u?U(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var a3=W({conv3d_:m_});function g_(e,t,r,n,a){P(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let s=e,i=t,o=!1;t.rank===4&&(o=!0,i=U(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),s=[1,e[0],e[1],e[2],e[3]]);let l=s[4],u=i.shape[4];P(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),P(i.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),P(r.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${r.rank}`),P(l===r.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${r.shape[3]}.`),P(u===r.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${r.shape[4]}.`);let d={dy:i,filter:r},h={pad:a,strides:n,inputShape:s},p=B.runKernel(mf,d,h);return o?U(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var hv=W({conv3DBackpropInput_:g_});function y_(e,t,r,n,a){let s=M(e,"x","conv3dTranspose"),i=M(t,"filter","conv3dTranspose");return hv(r,s,i,n,a)}var cv=W({conv3dTranspose_:y_});function A_(e){let t={x:M(e,"x","cos","float32")};return B.runKernel(ai,t)}var Lf=W({cos_:A_});function x_(e){let t={x:M(e,"x","cosh","float32")};return B.runKernel(si,t)}var s3=W({cosh_:x_});function b_(e,t=0,r=!1,n=!1){let a={x:M(e,"x","cumprod")},s={axis:t,exclusive:r,reverse:n};return B.runKernel(qo,a,s)}var O0=W({cumprod_:b_});function v_(e,t=0,r=!1,n=!1){let a={x:M(e,"x","cumsum")},s={axis:t,exclusive:r,reverse:n};return B.runKernel(ii,a,s)}var i3=W({cumsum_:v_});function w_(e,t,r,n=!1){let a=M(e,"x","denseBincount"),s=M(t,"weights","denseBincount");P(a.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${a.dtype}`),P(a.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${a.rank}.`),P(r>=0,()=>`size must be non-negative, but got ${r}.`),P(s.size===a.size||s.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${a.shape}, weights shape: ${s.shape}.`);let i={x:a,weights:s},o={size:r,binaryOutput:n};return B.runKernel(gf,i,o)}var fv=W({denseBincount_:w_});function k_(e,t,r="NHWC"){let n=M(e,"x","depthToSpace","float32"),a=r==="NHWC"?n.shape[1]:n.shape[2],s=r==="NHWC"?n.shape[2]:n.shape[3],i=r==="NHWC"?n.shape[3]:n.shape[1];P(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),P(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${a} and ${t} for depthToSpace with input shape
|
|
${n.shape}`),P(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${s} and ${t} for depthToSpace with input shape
|
|
${n.shape}`),P(i%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${n.shape}`);let o={x:n},l={blockSize:t,dataFormat:r};return B.runKernel(Ko,o,l)}var mv=W({depthToSpace_:k_});function I_(e,t,r,n,a="NHWC",s=[1,1],i){let o=M(e,"x","depthwiseConv2d","float32"),l=M(t,"filter","depthwiseConv2d","float32"),u=o,d=!1;o.rank===3&&(d=!0,u=U(o,[1,o.shape[0],o.shape[1],o.shape[2]])),P(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),P(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),P(u.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),qr("depthwiseConv2d",n,i);let h={x:u,filter:l},p={strides:r,pad:n,dataFormat:a,dilations:s,dimRoundingMode:i},c=B.runKernel(oi,h,p);return d?U(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var Nh=W({depthwiseConv2d_:I_});function S_(e){let t={x:M(e,"x","diag")};return B.runKernel(xf,t)}var C_=W({diag_:S_});function T_(e,t,r,n,a=[1,1],s="NHWC"){let i=M(e,"x","dilation2d"),o=M(t,"filter","dilation2d");P(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),P(o.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`),P(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=i,u=!1;i.rank===3&&(l=U(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=!0);let d={x:l,filter:o},h={strides:r,pad:n,dilations:a},p=B.runKernel(lh,d,h);return u?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var gv=W({dilation2d_:T_});function N_(e,t){let r=M(e,"a","equal","string_or_numeric"),n=M(t,"b","equal","string_or_numeric");[r,n]=Lt(r,n),At(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(Zo,a)}var Mn=W({equal_:N_});function E_(e,t,r){let n=M(t,"a","where"),a=M(r,"b","where"),s=M(e,"condition","where","bool"),i=At(At(s.shape,n.shape),a.shape),o=Bp(s,i),l=Bp(n,i),u=Bp(a,i),d={condition:o,t:l,e:u};return B.runKernel(Al,d)}var Ur=W({where_:E_});function R_(e){let t={x:M(e,"x","zerosLike")};return B.runKernel(Nl,t)}var at=W({zerosLike_:R_});function $_(e,t){let r=M(e,"a","div"),n=M(t,"b","div");[r,n]=Lt(r,n);let a=pe(r,n),s=at(a),i=Mn(n,s);return Ur(i,s,a)}var yv=W({divNoNan_:$_});function M_(e,t){let r=M(e,"t1","dot"),n=M(t,"t2","dot");P((r.rank===1||r.rank===2)&&(n.rank===1||n.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${r.rank} and ${n.rank}.`);let a=r.rank===1?r.size:r.shape[1],s=n.rank===1?n.size:n.shape[0];if(P(a===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${a} and ${s}.`),r.rank===1&&n.rank===1){let i=U(r,[1,-1]),o=U(n,[-1,1]),l=Ye(i,o);return U(l,[])}else if(r.rank===1&&n.rank===2){let i=U(r,[1,-1]),o=U(n,[n.shape[0],n.shape[1]]),l=Ye(i,o);return U(l,[l.size])}else if(r.rank===2&&n.rank===1){let i=U(n,[-1,1]),o=Ye(r,i);return U(o,[o.size])}else{let i=U(n,[n.shape[0],n.shape[1]]);return Ye(r,i)}}var F_=W({dot_:M_});function __(e,...t){let r=t.map((a,s)=>M(a,`tensors${s}`,"einsum")),n={equation:e};return B.runKernel(uh,r,n)}var Av=W({einsum_:__});function P_(e){let t={x:M(e,"x","elu","float32")};return B.runKernel(ui,t)}var Eh=W({elu_:P_});function O_(e){let t=M(e,"x","erf");P(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=me(t,"float32"));let r={x:t};return B.runKernel(rd,r)}var xv=W({erf_:O_});function o3(e,t){for(let r=0;r<e.length;++r)if(e[e.length-r-1]!==t-1-r)return!1;return!0}function bv(e,t,r){let n=e.length+t.length,a=[],s=0,i=0;for(let o=0;o<n;o++)r.indexOf(o)===-1?a.push(e[s++]):a.push(t[i++]);return a}function vv(e,t){let r=[],n=e.length;for(let s=0;s<n;s++)t.indexOf(s)===-1&&r.push(e[s]);let a=t.map(s=>e[s]);return[r,a]}function _o(e,t){let r=t.map(n=>1);return bv(e,r,t)}function z_(e,t,r){P(o3(t,r),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${r} input.`)}function wv(e,t){if(o3(e,t))return null;let r=[];for(let n=0;n<t;++n)e.indexOf(n)===-1&&r.push(n);return e.forEach(n=>r.push(n)),r}function l3(e){return e.map((t,r)=>[r,t]).sort((t,r)=>t[1]-r[1]).map(t=>t[0])}function D_(e,t){let r=[];for(let n=t-e;n<t;++n)r.push(n);return r}function L_(e,t=null,r=!1){let n={x:M(e,"x","max")},a={reductionIndices:t,keepDims:r};return B.runKernel(Ai,n,a)}var yr=W({max_:L_});function B_(e,t=null,r=!1){let n={x:M(e,"x","min")},a={axis:t,keepDims:r};return B.runKernel(wi,n,a)}var Bs=W({min_:B_});function W_(e,t){let r=M(e,"base","pow"),n=M(t,"exp","pow");[r,n]=Lt(r,n);let a={a:r,b:n};return B.runKernel(Ti,a)}var Ws=W({pow_:W_});function Se(e,t){if((Sr(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"&&Sr(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Ui(e,[],[],t)}function V_(e){let t={x:M(e,"x","sqrt","float32")};return B.runKernel(Oi,t)}var Er=W({sqrt_:V_});function U_(e){let t=M(e,"x","square"),r={};return B.runKernel("Square",{x:t},r)}var bt=W({square_:U_});function G_(e,t=null,r=!1){let n=M(e,"x","sum");n.dtype==="bool"&&(n=me(n,"int32"));let a={x:n},s={axis:t,keepDims:r};return B.runKernel(zi,a,s)}var ke=W({sum_:G_});function j_(e,t="euclidean",r=null,n=!1){e=M(e,"x","norm");let a=kv(e,t,r),s=a.shape;if(n){let i=Hn(r,e.shape);s=_o(a.shape,i)}return U(a,s)}function kv(e,t,r=null){if(e.rank===0)return ar(e);if(e.rank!==1&&r===null)return kv(U(e,[-1]),t,r);if(e.rank===1||typeof r=="number"||Array.isArray(r)&&r.length===1){if(t===1)return ke(ar(e),r);if(t===1/0)return yr(ar(e),r);if(t===-1/0)return Bs(ar(e),r);if(t==="euclidean"||t===2)return Er(ke(Ws(ar(e),Se(2,"int32")),r));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(r)&&r.length===2){if(t===1)return yr(ke(ar(e),r[0]),r[1]-1);if(t===1/0)return yr(ke(ar(e),r[1]),r[0]);if(t===-1/0)return Bs(ke(ar(e),r[1]),r[0]);if(t==="fro"||t==="euclidean")return Er(ke(bt(e),r));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${r}`)}var Bf=W({norm_:j_});function H_(e,t=null,r=!1){return Bf(e,"euclidean",t,r)}var Iv=W({euclideanNorm_:H_});function q_(e){let t={x:M(e,"x","exp")};return B.runKernel(di,t)}var Fn=W({exp_:q_});function X_(e,t=0){let r=M(e,"x","expandDims","string_or_numeric");P(t<=r.rank,()=>"Axis must be <= rank of the tensor");let n={input:r},a={dim:t};return B.runKernel(Yo,n,a)}var Kt=W({expandDims_:X_});function K_(e){let t={x:M(e,"x","expm1")};return B.runKernel(Jo,t)}var Sv=W({expm1_:K_});function Z_(e,t){let r=M(e,"x","tile","string_or_numeric");P(r.rank===t.length,()=>`Error in transpose: rank of input ${r.rank} must match length of reps ${t}.`);let n={x:r},a={reps:t};return B.runKernel(ts,n,a)}var jn=W({tile_:Z_});function Y_(e,t,r,n="float32"){t==null&&(t=e);let a=De([e,t],n),s=e<=t?e:t;for(let o=0;o<s;++o)a.set(1,o,o);let i=U(a.toTensor(),[e,t]);if(r==null)return i;if(r.length===1)return jn(Kt(i,0),[r[0],1,1]);if(r.length===2)return jn(Kt(Kt(i,0),0),[r[0],r[1],1,1]);if(r.length===3)return jn(Kt(Kt(Kt(i,0),0),0),[r[0],r[1],r[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${r.length}D.`)}var u3=W({eye_:Y_});function vd(e,t,r){let n={shape:e,value:t,dtype:r};return B.runKernel(nd,{},n)}function J_(e){let t={x:M(e,"x","floor","float32")};return B.runKernel(pi,t)}var Rh=W({floor_:J_});function Q_(e,t,r=0,n=0){let a=M(e,"x","gather"),s=M(t,"indices","gather","int32"),i={x:a,indices:s},o={axis:r,batchDims:n};return B.runKernel(el,i,o)}var Fu=W({gather_:Q_});function eP(e,t){let r=M(e,"a","greater","string_or_numeric"),n=M(t,"b","greater","string_or_numeric");[r,n]=Lt(r,n),At(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(rl,a)}var gn=W({greater_:eP});function tP(e,t){let r=M(e,"a","greaterEqual","string_or_numeric"),n=M(t,"b","greaterEqual","string_or_numeric");[r,n]=Lt(r,n),At(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(fi,a)}var Ml=W({greaterEqual_:tP});function rP(e){let t={x:M(e,"x","isFinite")};return B.runKernel(ad,t)}var nP=W({isFinite_:rP});function aP(e){let t={x:M(e,"x","isInf")};return B.runKernel(sd,t)}var sP=W({isInf_:aP});function iP(e){let t={x:M(e,"x","isNaN")};return B.runKernel(id,t)}var Cv=W({isNaN_:iP});function oP(e,t=.2){let r={x:M(e,"x","leakyRelu")},n={alpha:t};return B.runKernel(gi,r,n)}var Wf=W({leakyRelu_:oP});function lP(e,t){let r=M(e,"a","less","string_or_numeric"),n=M(t,"b","less","string_or_numeric");[r,n]=Lt(r,n),At(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(nl,a)}var d3=W({less_:lP});function uP(e,t){let r=M(e,"a","lessEqual","string_or_numeric"),n=M(t,"b","lessEqual","string_or_numeric");[r,n]=Lt(r,n),At(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(al,a)}var Fl=W({lessEqual_:uP});function Tv(e,t,r){if(r<=0)throw new Error("The number of values should be positive.");let n={start:e,stop:t,num:r};return B.runKernel(kf,{},n)}function dP(e,t=5,r=1,n=1,a=.5){let s=M(e,"x","localResponseNormalization");P(s.rank===4||s.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
rank ${s.rank}.`),P(Nu(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=s,o=!1;s.rank===3&&(o=!0,i=U(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:i},u={depthRadius:t,bias:r,alpha:n,beta:a},d=B.runKernel(ph,l,u);return o?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Nv=W({localResponseNormalization_:dP});function pP(e){let t={x:M(e,"x","log","float32")};return B.runKernel(yi,t)}var _n=W({log_:pP});function hP(e){let t={x:M(e,"x","log1p")};return B.runKernel(od,t)}var Vf=W({log1p_:hP});function cP(e){return P(_s(e),()=>"The f passed in grad(f) must be a function"),(t,r)=>{let n=M(t,"x","tf.grad","string_or_numeric"),a=r!=null?M(r,"dy","tf.grad"):null;return B.tidy(()=>{let{value:s,grads:i}=B.gradients(()=>e(n),[n],a);return a!=null&&jr(s.shape,a.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Uf(i),i[0]})}}function fP(e){return P(_s(e),()=>"The f passed in grads(f) must be a function"),(t,r)=>{P(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let n=Kp(t,"args","tf.grads","string_or_numeric"),a=r!=null?M(r,"dy","tf.grads"):null;return B.tidy(()=>{let{value:s,grads:i}=B.gradients(()=>e(...n),n,a);return a!=null&&jr(s.shape,a.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Uf(i),i})}}function mP(e){return P(_s(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,r)=>{P(t instanceof nt,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),P(r==null||r instanceof nt,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:n,value:a}=B.gradients(()=>e(t),[t],r);return Uf(n),{grad:n[0],value:a}}}function gP(e){return P(_s(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,r)=>{P(Array.isArray(t)&&t.every(a=>a instanceof nt),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),P(r==null||r instanceof nt,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let n=B.gradients(()=>e(...t),t,r);return r!=null&&jr(n.value.shape,r.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Uf(n.grads),n}}function Ev(e,t){P(_s(e),()=>"The f passed in variableGrads(f) must be a function"),P(t==null||Array.isArray(t)&&t.every(u=>u instanceof Xp),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let r=t!=null;if(!r){t=[];for(let u in B.registeredVariables)t.push(B.registeredVariables[u])}let n=r?t.filter(u=>!u.trainable):null,a=t.length;t=t.filter(u=>u.trainable),P(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${a} variables is trainable.`);let s=!0,{value:i,grads:o}=B.gradients(e,t,null,s);P(o.some(u=>u!=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()."),P(i.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`);let l={};return t.forEach((u,d)=>{o[d]!=null&&(l[u.name]=o[d])}),n!=null&&n.forEach(u=>l[u.name]=null),{value:i,grads:l}}function Pa(e){return B.customGrad(e)}function Uf(e){if(e.filter(t=>t==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 yP(e){let t={x:M(e,"x","softplus")};return B.runKernel(gd,t)}var wd=W({softplus_:yP});function AP(e){let t=M(e,"x","logSigmoid");return Pa(r=>({value:Mt(wd(Mt(r))),gradFunc:n=>L(n,Tr(Mt(r)))}))(t)}var xP=W({logSigmoid_:AP});function bP(e,t){let r=M(e,"a","sub"),n=M(t,"b","sub");[r,n]=Lt(r,n);let a={a:r,b:n};return B.runKernel(Bi,a)}var ce=W({sub_:bP});function vP(e,t=-1){let r=M(e,"logits","logSoftmax");if(t===-1&&(t=r.rank-1),t!==r.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${r.rank} and axis was ${t}`);return Pa((n,a)=>{let s=yr(n,t,!0),i=ce(n,s),o=ce(me(i,"float32"),_n(ke(Fn(i),t,!0)));return a([o]),{value:o,gradFunc:(l,u)=>{let[d]=u,h=!0,p=Fn(d);return ce(l,L(ke(l,t,h),p))}}})(r)}var p3=W({logSoftmax_:vP});function wP(e,t=null,r=!1){let n=M(e,"x","logSumExp"),a=Hn(t,n.shape),s=yr(n,a,!0),i=ce(n,s),o=Fn(i),l=ke(o,a),u=_n(l),d=le(U(s,u.shape),u);if(r){let h=_o(d.shape,a);return U(d,h)}return d}var Rv=W({logSumExp_:wP});function kP(e,t){let r=M(e,"a","logicalAnd","bool"),n=M(t,"b","logicalAnd","bool");At(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(sl,a)}var ga=W({logicalAnd_:kP});function IP(e){let t={x:M(e,"x","logicalNot","bool")};return B.runKernel(il,t)}var Gf=W({logicalNot_:IP});function SP(e,t){let r=M(e,"a","logicalOr","bool"),n=M(t,"b","logicalOr","bool");At(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(ld,a)}var h3=W({logicalOr_:SP});function CP(e,t){let r=M(e,"a","logicalXor","bool"),n=M(t,"b","logicalXor","bool");return At(r.shape,n.shape),ga(h3(e,t),Gf(ga(e,t)))}var TP=W({logicalXor_:CP}),t0=2147483648;function NP(e,t,r="left"){let n=M(e,"sortedSequence","searchSorted"),a=M(t,"values","searchSorted"),s=n.shape[n.shape.length-1],i=a.shape[a.shape.length-1],o=U(n,[-1,s]),l=U(a,[-1,i]);if(o.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(o.shape[0]!==l.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(It(l.shape)>=t0)throw new Error(`values tensor size must less than ${t0}`);if(o.shape[1]>=t0)throw new Error(`trailing dim_size must less than ${t0} for int32 output type, was ${o.shape[1]}`);let u={sortedSequence:o,values:l},d={side:r};return B.runKernel($f,u,d)}var c3=W({searchSorted_:NP});function $v(e,t){return c3(e,t,"left")}function EP(e,t,r,n,a){let s=M(e,"x","maxPool"),i=1,o=s,l=!1;s.rank===3&&(l=!0,o=U(s,[1,s.shape[0],s.shape[1],s.shape[2]])),P(o.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`),P(za(r,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'`),qr("maxPool",n,a);let u={x:o},d={filterSize:t,strides:r,pad:n,dimRoundingMode:a},h=B.runKernel(bi,u,d);return l?U(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var jf=W({maxPool_:EP});function RP(e,t=[1,1,1],r,n,a,s="NDHWC"){let i=M(e,"x","maxPool3d"),o=i,l=!1;i.rank===4&&(l=!0,o=U(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),P(o.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`),P(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),qr("maxPool3d",n,a);let u={x:o},d={filterSize:t,strides:r,pad:n,dimRoundingMode:a,dataFormat:s},h=B.runKernel(hh,u,d);return l?U(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var f3=W({maxPool3d_:RP});function $P(e,t,r,n,a=!1){let s={x:M(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:r,pad:n,includeBatchInIndex:a},o=B.runKernel(Tf,s,i);return{result:o[0],indexes:o[1]}}var Mv=W({maxPoolWithArgmax_:$P});function MP(e,t){let r=M(e,"a","maximum"),n=M(t,"b","maximum");[r,n]=Lt(r,n),r.dtype==="bool"&&(r=me(r,"int32"),n=me(n,"int32")),At(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(xi,a)}var rs=W({maximum_:MP});function FP(e,t=null,r=!1){let n={x:M(e,"x","mean")},a={axis:t,keepDims:r};return B.runKernel(vi,n,a)}var Vt=W({mean_:FP});function Ot(e,t="float32"){if(t==="complex64"){let n=Ot(e,"float32"),a=Ot(e,"float32");return Ya(n,a)}let r=lf(It(e),t);return B.makeTensor(r,e,t)}function cn(e,t="float32"){if(t==="complex64"){let n=cn(e,"float32"),a=Ot(e,"float32");return Ya(n,a)}let r=Ny(It(e),t);return B.makeTensor(r,e,t)}function _P(e,t,{indexing:r="xy"}={}){if(r!=="xy"&&r!=="ij")throw new TypeError(`${r} is not a valid third argument to meshgrid`);if(e===void 0)return[];let n=M(e,"x","meshgrid",e instanceof nt?e.dtype:"float32");if(t===void 0)return[n];let a=M(t,"y","meshgrid",t instanceof nt?t.dtype:"float32"),s=It(n.shape),i=It(a.shape);return r==="xy"?(n=U(n,[1,-1]),a=U(a,[-1,1]),[Ye(cn([i,1],n.dtype),n),Ye(a,cn([1,s],a.dtype))]):(n=U(n,[-1,1]),a=U(a,[1,-1]),[Ye(n,cn([1,i],n.dtype)),Ye(cn([s,1],a.dtype),a)])}function PP(e,t){let r=M(e,"a","minimum"),n=M(t,"b","minimum");[r,n]=Lt(r,n),r.dtype==="bool"&&(r=me(r,"int32"),n=me(n,"int32")),At(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(ki,a)}var $h=W({minimum_:PP});function OP(e,t,r){P(r==="reflect"||r==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${r}.`);let n=M(e,"x","mirrorPad");if(n.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");P(t.length===n.rank,()=>`Padding doesn't match input. Must be ${n.rank}. Got ${t.length}.`);let a=r==="reflect"?1:0;for(let o=0;o<n.rank;o++)P(t[o].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),P(t[o][0]>=0&&t[o][0]<=n.shape[o]-a&&t[o][1]>=0&&t[o][1]<=n.shape[o]-a,()=>`Padding in dimension ${o} cannot be greater than or equal to ${n.shape[o]-a} or less than 0 for input of shape ${n.shape}`);let s={paddings:t,mode:r},i={x:n};return B.runKernel(Ii,i,s)}var Fv=W({mirrorPad_:OP});function zP(e,t){let r=M(e,"a","mod"),n=M(t,"b","mod");[r,n]=Lt(r,n);let a={a:r,b:n};return B.runKernel(ud,a)}var kd=W({mod_:zP});function DP(e,t=null,r=!1){e=M(e,"x","moments");let n=Hn(t,e.shape),a=Vt(e,n,r),s=a.shape;r||(s=_o(a.shape,n));let i=bt(ce(me(e,"float32"),U(a,s))),o=Vt(i,n,r);return{mean:a,variance:o}}var Hf=W({moments_:DP});function LP(e,t,r,n){let a=M(t,"data","multiRNNCell"),s=Kp(r,"c","multiRNNCell"),i=Kp(n,"h","multiRNNCell"),o=a,l=[];for(let h=0;h<e.length;h++){let p=e[h](o,s[h],i[h]);l.push(p[0]),l.push(p[1]),o=p[1]}let u=[],d=[];for(let h=0;h<l.length;h+=2)u.push(l[h]),d.push(l[h+1]);return[u,d]}var BP=W({multiRNNCell_:LP});function WP(e,t,r,n=!1){let a=M(e,"logits","multinomial"),s=a.size,i=a.rank;if(s<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${s}.`);if(i>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);r=r||Math.random();let o={logits:i===1?U(a,[1,-1]):a},l={numSamples:t,seed:r,normalized:n},u=B.runKernel(Nf,o,l);return i===1?U(u,[u.size]):u}var _v=W({multinomial_:WP});function VP(e,t){let r=M(e,"a","notEqual","string_or_numeric"),n=M(t,"b","notEqual","string_or_numeric");[r,n]=Lt(r,n),At(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(ll,a)}var _u=W({notEqual_:VP});function UP(e){let t={x:M(e,"x","onesLike")};return B.runKernel(pl,t)}var Pn=W({onesLike_:UP});function GP(e,t){let r=M(e,"v1","outerProduct"),n=M(t,"v2","outerProduct");P(r.rank===1&&n.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${r.rank} and ${n.rank}.`);let a=U(r,[-1,1]),s=U(n,[1,-1]);return Ye(a,s)}var jP=W({outerProduct_:GP});function HP(e,t,r=0){let n=M(e,"x","pad");if(n.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let a={paddings:t,constantValue:r},s={x:n};return B.runKernel(Ci,s,a)}var Xn=W({pad_:HP});function qP(e,t,r=0){return P(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),Xn(e,[t],r)}var XP=W({pad1d_:qP});function KP(e,t,r=0){return P(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Xn(e,t,r)}var ZP=W({pad2d_:KP});function YP(e,t,r=0){return P(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."),Xn(e,t,r)}var JP=W({pad3d_:YP});function QP(e,t,r=0){return P(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."),Xn(e,t,r)}var eO=W({pad4d_:QP});function tO(e,t,r){let n=M(e,"x","spaceToBatchND");P(n.rank>=1+t.length,()=>`input rank ${n.rank} should be > than [blockShape] ${t.length}`),P(r.length===t.length,()=>`paddings.shape[0] ${r.length} must be equal to [blockShape] ${t.length}`),P(n.shape.reduce((i,o,l)=>l>0&&l<=t.length?i&&(o+r[l-1][0]+r[l-1][1])%t[l-1]===0:i,!0),()=>`input spatial dimensions ${n.shape.slice(1)} with paddings ${r.toString()} must be divisible by blockShapes ${t.toString()}`);let a={x:n},s={blockShape:t,paddings:r};return B.runKernel(vl,a,s)}var qf=W({spaceToBatchND_:tO});function rO(e,t,r,n,a,s,i){a==null&&(a=[1,1]),s==null&&(s=1),n===0&&(n="valid");let o=M(e,"x","maxPool"),l=o,u=!1;o.rank===3&&(u=!0,l=U(o,[1,o.shape[0],o.shape[1],o.shape[2]])),P(za(s,a),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${a}'`);let d=tv(l.shape,t,s,a,n),h=[d.dilationHeight,d.dilationWidth],p;n==="same"?p=aO([d.filterHeight,d.filterWidth],h):p=[[0,0],[0,0]];let c=h[0]===1&&h[1]===1,[m,f]=nO([d.inHeight,d.inWidth],h,p),g=c?n:"valid",y=c?l:qf(l,h,m),A=(r==="avg"?()=>zf(y,t,s,g,i):()=>jf(y,t,s,g,i))(),x=c?A:Df(A,h,f);return u?U(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function nO(e,t,r){let n=r.map(d=>d[0]),a=r.map(d=>d[1]),s=e.concat(n,a),i=t.map((d,h)=>(d-s[h]%d)%d),o=a.map((d,h)=>d+i[h]),l=t.map((d,h)=>[n[h],o[h]]),u=t.map((d,h)=>[0,i[h]]);return[l,u]}function aO(e,t){let r=e.map((s,i)=>s+(s-1)*(t[i]-1)).map(s=>s-1),n=r.map(s=>Math.floor(s/2)),a=r.map((s,i)=>s-n[i]);return r.map((s,i)=>[n[i],a[i]])}var sO=W({pool_:rO});function iO(e,t){let r=M(e,"x","prelu"),n=M(t,"alpha","prelu"),a={x:r,alpha:n};return B.runKernel(Ni,a)}var Xf=W({prelu_:iO});function oO(e,t=null,r=!1){let n=M(e,"x","prod");n.dtype==="bool"&&(n=me(n,"int32"));let a={x:n},s={axis:t,keepDims:r};return B.runKernel(Ei,a,s)}var m3=W({prod_:oO});function lO(e,t,r){let n=It(e),a=null;if(r==null||r==="float32")a=new Float32Array(n);else if(r==="int32")a=new Int32Array(n);else if(r==="bool")a=new Uint8Array(n);else throw new Error(`Unknown data type ${r}`);for(let s=0;s<n;s++)a[s]=t();return B.makeTensor(a,e,r)}var uO=W({rand_:lO}),g3=Vo(sf()),y3=class{constructor(e,t,r,n,a){this.mean=e,this.stdDev=t,this.dtype=r,this.nextVal=NaN,this.truncated=n,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);let s=a||Math.random();this.random=g3.alea(s.toString())}nextValue(){if(!isNaN(this.nextVal)){let n=this.nextVal;return this.nextVal=NaN,n}let e,t,r=!1;for(;!r;){let n,a,s;do n=2*this.random()-1,a=2*this.random()-1,s=n*n+a*a;while(s>=1||s===0);let i=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*n*i,t=this.mean+this.stdDev*a*i,(!this.truncated||this.isValidTruncated(e))&&(r=!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}},dO=class{constructor(e,t,r,n){this.alpha=e,this.beta=1/t,this.dtype=r;let a=n||Math.random();this.randu=g3.alea(a.toString()),this.randn=new y3(0,1,r,!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,r,n,a,s;for(;;){do n=this.randn.nextValue(),s=1+this.c*n;while(s<=0);if(s*=s*s,e=n*n,t=1-.331*e*e,r=.5*e+this.d*(1-s+Math.log(s)),a=this.randu(),a<t||Math.log(a)<r)break}return s=1/this.beta*this.d*s,this.alpha<1&&(s*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(s)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}},pO=class{constructor(e=0,t=1,r,n){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=r,n==null&&(n=Math.random()),typeof n=="number"&&(n=n.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=g3.alea(n)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function hO(e,t,r=1,n="float32",a){if(r==null&&(r=1),n==null&&(n="float32"),n!=="float32"&&n!=="int32")throw new Error(`Unsupported data type ${n}`);let s=new dO(t,r,n,a),i=De(e,n);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var cO=W({randomGamma_:hO});function fO(e,t=0,r=1,n,a){if(n!=null&&n==="bool")throw new Error(`Unsupported data type ${n}`);let s=new y3(t,r,n,!1,a),i=De(e,n);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var Pv=W({randomNormal_:fO});function mO(e,t=0,r=1,n="float32",a){let s=De(e,n),i=new pO(t,r,null,a);for(let o=0;o<s.values.length;o++)s.values[o]=i.nextValue();return s.toTensor()}var Id=W({randomUniform_:mO});function Pu(e,t,r=1,n="float32"){if(r===0)throw new Error("Cannot have a step of zero");let a={start:e,stop:t,step:r,dtype:n};return B.runKernel(pd,{},a)}function gO(e){let t={x:M(e,"x","reciprocal")};return B.runKernel(hd,t)}var Ov=W({reciprocal_:gO});function yO(e){let t={x:M(e,"x","relu")};return B.runKernel(Ri,t)}var Da=W({relu_:yO});function AO(e){let t={x:M(e,"x","relu6")};return B.runKernel(Mi,t)}var A3=W({relu6_:AO});function xO(e,t){let r={x:M(e,"x","reverse")},n={dims:t};return B.runKernel(ml,r,n)}var On=W({reverse_:xO});function bO(e){let t=M(e,"x","reverse");return P(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),On(t,0)}var vO=W({reverse1d_:bO});function wO(e,t){let r=M(e,"x","reverse");return P(r.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${r.rank}.`),On(r,t)}var kO=W({reverse2d_:wO});function IO(e,t){let r=M(e,"x","reverse");return P(r.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${r.rank}.`),On(r,t)}var SO=W({reverse3d_:IO});function CO(e,t){let r=M(e,"x","reverse");return P(r.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${r.rank}.`),On(r,t)}var TO=W({reverse4d_:CO});function NO(e){let t={x:M(e,"x","round")};return B.runKernel(gl,t)}var x3=W({round_:NO});function EO(e){let t={x:M(e,"x","rsqrt","float32")};return B.runKernel(Fi,t)}var b3=W({rsqrt_:EO});function RO(e){let t={x:M(e,"x","selu")};return B.runKernel(fd,t)}var v3=W({selu_:RO});function $O(e,t,r,n,a,s=[1,1],i="NHWC"){let o=M(e,"x","separableConv2d"),l=M(t,"depthwiseFilter","separableConv2d"),u=M(r,"pointwiseFilter","separableConv2d"),d=o,h=!1;if(o.rank===3&&(h=!0,d=U(o,[1,o.shape[0],o.shape[1],o.shape[2]])),i==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");P(d.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${d.rank}.`),P(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),P(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),P(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),P(u.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);let p=l.shape[2],c=l.shape[3];P(u.shape[2]===p*c,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*c}, but got ${u.shape[2]}.`);let m=Nh(d,l,n,a,i,s),f=Ls(m,u,1,"valid",i);return h?U(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var zv=W({separableConv2d_:$O});async function MO(e,t){let r=M(e,"x","setdiff1d"),n=M(t,"y","setdiff1d");P(r.dtype===n.dtype,()=>`x and y should have the same dtype, but got x (${r.dtype}) and y (${n.dtype}).`),P(r.rank===1,()=>`x should be 1D tensor, but got x (${r.shape}).`),P(n.rank===1,()=>`y should be 1D tensor, but got y (${n.shape}).`);let a=await r.data(),s=await n.data(),i=new Set(s),o=0;for(let d=0;d<a.length;d++)i.has(a[d])||o++;let l=new ir([o],r.dtype),u=new ir([o],"int32");for(let d=0,h=0;d<a.length;d++)i.has(a[d])||(l.values[h]=a[d],u.values[h]=d,h++);return[l.toTensor(),u.toTensor()]}var Dv=MO;function FO(e){let t={x:M(e,"x","sign")};return B.runKernel(md,t)}var Lv=W({sign_:FO});function _O(e){let t={x:M(e,"x","sin","float32")};return B.runKernel(_i,t)}var w3=W({sin_:_O});function PO(e){let t={x:M(e,"x","sinh")};return B.runKernel(bl,t)}var k3=W({sinh_:PO});function OO(e,t,r){let n=M(e,"x","slice1d");return P(n.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${n.rank} tensor`),_e(n,[t],[r])}var Kf=W({slice1d_:OO});function zO(e,t,r){let n=M(e,"x","slice2d");return P(n.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${n.rank} tensor`),_e(n,t,r)}var I3=W({slice2d_:zO});function DO(e,t,r){let n=M(e,"x","slice3d");return P(n.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${n.rank} tensor`),_e(n,t,r)}var _l=W({slice3d_:DO});function LO(e,t,r){let n=M(e,"x","slice4d");return P(n.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${n.rank} tensor`),_e(n,t,r)}var Po=W({slice4d_:LO});function BO(e,t=-1){let r=M(e,"logits","softmax","float32");if(t===-1&&(t=r.rank-1),t!==r.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${r.rank} and dim was ${t}`);let n={logits:r},a={dim:t};return B.runKernel(Di,n,a)}var Sd=W({softmax_:BO});function WO(e){P(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return B.runKernel(vf,t)}var Zf=W({fft_:WO});function VO(e){P(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return B.runKernel(wf,t)}var Yp=W({ifft_:VO});function UO(e){let t=e.shape[e.shape.length-1],r=e.size/t,n;if(t<=2){let a=U(e,[r,t]);n=Yp(a)}else{let a=[r,2*(t-1)],s=U(Ru(e),[r,t]),i=U(Sh(e),[r,t]),o=On(_e(s,[0,1],[r,t-2]),1),l=L(On(_e(i,[0,1],[r,t-2]),1),Se(-1)),u=St([s,o],1),d=St([i,l],1),h=U(Ya(u,d),[a[0],a[1]]);n=Yp(h)}if(n=Ru(n),e.rank===3&&e.shape[0]!==0){let a=n,s=e.shape[0];n=U(n,[s,n.shape[0]/s,n.shape[1]]),a.dispose()}return n}var S3=W({irfft_:UO});function GO(e,t,r=0){let n={x:M(e,"x","split")},a={numOrSizeSplits:t,axis:r};return B.runKernel(wl,n,a)}var Yt=W({split_:GO});function jO(e,t){P(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let r=e.shape[e.shape.length-1],n=e.size/r,a;if(t!=null&&t<r){let m=e.shape.map(g=>0),f=e.shape.map(g=>g);f[e.shape.length-1]=t,a=_e(e,m,f),r=t}else if(t!=null&&t>r){let m=e.shape.map(f=>f);m[e.shape.length-1]=t-r,a=St([e,Ot(m)],e.shape.length-1),r=t}else a=e;let s=at(a),i=U(Ya(a,s),[n,r]),o=Zf(i),l=Math.floor(r/2)+1,u=Ru(o),d=Sh(o),h=Yt(u,[l,r-l],u.shape.length-1),p=Yt(d,[l,r-l],d.shape.length-1),c=a.shape.slice();return c[a.shape.length-1]=l,U(Ya(h[0],p[0]),c)}var Yf=W({rfft_:jO});function HO(e,t){let r=M(e,"a","squaredDifference"),n=M(t,"b","squaredDifference");[r,n]=Lt(r,n),At(r.shape,n.shape);let a={a:r,b:n},s={};return B.runKernel(Li,a,s)}var C3=W({squaredDifference_:HO});function qO(e,t){let r=M(e,"x","squeeze");return U(r,D7(r.shape,t).newShape)}var et=W({squeeze_:qO});function XO(e,t=0){let r=Kp(e,"tensors","stack","string_or_numeric");P(r.length>=1,()=>"Pass at least one tensor to tf.stack"),r.length>0&&P(t<=r[0].rank,()=>"Axis must be <= rank of the tensor");let n=r,a={axis:t};return B.runKernel(cl,n,a)}var ur=W({stack_:XO});function KO(e,t=0){let r={x:M(e,"x","step")},n={alpha:t};return B.runKernel(Vi,r,n)}var Mh=W({step_:KO});function ZO(e,t,r,n,a=0,s=0,i=0,o=0,l=0){let u={x:M(e,"x","stridedSlice","string_or_numeric")},d={begin:t,end:r,strides:n,beginMask:a,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return B.runKernel(kl,u,d)}var Bv=W({stridedSlice_:ZO});function YO(e){let t={x:M(e,"x","tan","float32")};return B.runKernel(Il,t)}var Wv=W({tan_:YO});function Nt(e,t){Uo(e);let r=_a(e,t);if(r.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Ui(e,null,r,t)}function ca(e,t,r){if(Uo(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let n=_a(e,r);if(n.length!==2&&n.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Ui(e,t,n,r)}function JO(e,t,r){if(Uo(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let n=_a(e,r);if(n.length!==4&&n.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Ui(e,t,n,r)}function QO(e,t,r){if(Uo(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let n=_a(e,r);if(n.length!==5&&n.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Ui(e,t,n,r)}function ez(e,t,r){if(Uo(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let n=_a(e,r);if(n.length!==6&&n.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||n,Ui(e,t,n,r)}function tz(e,t=1,r=!0){let n=M(e,"x","topk");if(n.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let a=n.shape[n.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>a)throw new Error(`'k' passed to topk() must be <= the last dimension (${a}) but got ${t}`);let s={x:n},i={k:t,sorted:r},[o,l]=B.runKernel(Sl,s,i);return{values:o,indices:l}}var Vv=W({topk_:tz});function rz(e,t=0,r=1,n,a){if(n!=null&&n==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new y3(t,r,n,!0,a),i=De(e,n);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var Jf=W({truncatedNormal_:rz});function nz(e,t=0){let r=M(e,"x","unique","string_or_numeric");P(r.rank>0,()=>"The input tensor must be at least 1D");let n={x:r},a={axis:t},[s,i]=B.runKernel(_f,n,a);return{values:s,indices:i}}var Wg=W({unique_:nz});function az(e,t,r){let n=M(e,"x","unsortedSegmentSum"),a=M(t,"segmentIds","unsortedSegmentSum","int32");P(Nu(r),()=>"numSegments must be of dtype int");let s={x:n,segmentIds:a},i={numSegments:r};return B.runKernel(xh,s,i)}var Uv=W({unsortedSegmentSum_:az});function sz(e,t=0){let r=M(e,"x","unstack","string_or_numeric");P(t>=-r.shape.length&&t<r.shape.length,()=>`Axis = ${t} is not in [-${r.shape.length}, ${r.shape.length})`);let n={value:r},a={axis:t};return B.runKernel(Tl,n,a)}var an=W({unstack_:sz});function Gv(e,t){return c3(e,t,"right")}function jv(e,t=!0,r,n){return B.makeVariable(e,t,r,n)}function Hv(e,t){let r=[];for(let s=0;s<t.length;s++)t[s]&&r.push(s);let n=De(e,"int32"),a=De([r.length,e.length],"int32");for(let s=0;s<r.length;s++){let i=n.indexToLoc(r[s]),o=s*e.length;a.values.set(i,o)}return a.toTensor()}async function iz(e){let t=M(e,"condition","whereAsync","bool"),r=await t.data(),n=Hv(t.shape,r);return e!==t&&t.dispose(),n}var T3=iz;async function oz(e,t,r){let n=M(e,"tensor","boolMask"),a=M(t,"mask","boolMask","bool"),s=r==null?0:r,i=a.rank,o=n.shape;P(i>0,()=>"mask cannot be scalar"),jr(o.slice(s,s+i),a.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let f=s;f<s+i;f++)l*=o[f];let u=o.slice(0,s).concat([l],o.slice(s+i)),d=U(n,u),h=U(a,[-1]),p=await T3(h),c=et(p,[1]),m=Fu(d,c,s);return e!==n&&n.dispose(),t!==a&&a.dispose(),c.dispose(),d.dispose(),h.dispose(),p.dispose(),m}var lz=oz;function uz(e,t,r,n,a=!0){let s=M(e,"v","movingAverage"),i=M(t,"x","movingAverage"),o=M(r,"decay","movingAverage");o6(s,i),P(Ks(s.shape,i.shape),()=>"Shape mismatch in v and x");let l=Se(1),u=ce(l,o),d=L(ce(i,s),u);if(a){P(n!=null,()=>"When using zeroDebias: true, step is required.");let h=M(n,"step","movingAverage");d=pe(d,ce(l,Ws(o,h)))}return le(s,d)}var dz=W({movingAverage_:uz});function pz(e,t,r){let n=M(e,"indices","scatterND","int32"),a=M(t,"updates","scatterND");qy(a,n,r);let s={indices:n,updates:a},i={shape:r};return B.runKernel(yl,s,i)}var qv=W({scatterND_:pz});function hz(e,t,r,n){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 a=e.rank>0?e.shape[0]:1,s=e.rank>1?e.shape[1]:1;if(r.length!==s)throw new Error(`outputShape has incorrect number of elements:, ${r.length}, should be: ${s}.`);let i=t.size;if(!(t.rank===0||t.rank===1&&i===a))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${a}]`);if(t.dtype!==n.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function cz(e,t,r,n=0){let a=M(e,"sparseIndices","sparseToDense","int32"),s=M(t,"sparseValues","sparseToDense","string_or_numeric"),i=M(n,"defaultValue","sparseToDense",s.dtype);hz(a,s,r,i);let o={sparseIndices:a,sparseValues:s,defaultValue:i},l={outputShape:r};return B.runKernel(yh,o,l)}var N3=W({sparseToDense_:cz});function fz(e,t){let r=M(t,"indices","gatherND","int32"),n={params:M(e,"x","gatherND","string_or_numeric"),indices:r};return B.runKernel(tl,n)}var Xv=W({gatherND_:fz});function mz(e,t){if(t==null)return e.shape.slice();if(Ks(e.shape,t))return t;if(e.shape.length===t.length){let r=[];for(let n=0;n<e.shape.length;n++)t[n]==null&&e.shape[n]!=null?r.push(e.shape[n]):r.push(t[n]);return r}return t}function gz(e,t,r,n){let a=M(e,"x","dropout");if(P(a.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${a.dtype} tensor instead.`),P(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof nt?a.clone():a;let s=mz(a,r),i=1-t,o=pe(Rh(le(Id(s,0,1,"float32",n),i)),i);return L(a,o)}var Kv=W({dropout_:gz});function Zv(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function E3(e,t,r){let n=1-e%2,a=new Float32Array(e);for(let s=0;s<e;++s){let i=2*Math.PI*s/(e+n-1);a[s]=t-r*Math.cos(i)}return Nt(a,"float32")}async function yz(e,t,r=1){let n=M(e,"predictions","inTopK"),a=M(t,"targets","inTopK");P(n.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${n.rank}`),P(n.rank-1===a.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${n.rank} and targets rank ${a.rank}`),jr(n.shape.slice(0,n.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let s=n.shape[n.shape.length-1];P(r>0&&r<=s,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${r}`);let i=await n.data(),o=await a.data(),[l,u]=[i.length/s,s],d=L7("bool",l);for(let h=0;h<l;h++){let p=h*u,c=i.subarray(p,p+u),m=[];for(let f=0;f<c.length;f++)m.push({value:c[f],index:f});m.sort((f,g)=>g.value-f.value),d[h]=0;for(let f=0;f<r;f++)if(m[f].index===o[h]){d[h]=1;break}}return e!==n&&n.dispose(),t!==a&&a.dispose(),ft(d,a.shape,"bool")}var Az=yz,Vs={};Be(Vs,{conv2d:()=>vz,depthwiseConv2d:()=>Sz,matMul:()=>Tz});function xz(e,t,r,n,a,s="NHWC",i){let o=e;e.rank===3&&(o=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=U(t,[1,t.shape[0],t.shape[1],t.shape[2]])),P(o.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`),P(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),P(r.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${r}.`);let u=s==="NHWC"?o.shape[3]:o.shape[1],d=s==="NHWC"?l.shape[3]:l.shape[1];P(u===r[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${r[2]}.`),P(d===r[3],()=>`Error in conv2dDerFilter: depth of dy (${d}) must match output depth for filter (${r[3]}).`),qr("conv2dDerFilter",a,i);let h={x:o,dy:l},p={strides:n,pad:a,dataFormat:s,dimRoundingMode:i,filterShape:r};return B.runKernel(cf,h,p)}var R3=W({conv2DBackpropFilter_:xz});function Qf(e,t,r){if(r==null||r==="linear")return e;if(r==="relu")return L(e,Mh(t));throw new Error(`Cannot compute gradient for fused activation ${r}.`)}function em(e,t){let r=t,n=Jt(e.shape,t.shape);return n.length>0&&(r=ke(r,n)),U(r,e.shape)}function tm(e,t,r,n){if(t==="linear")return e;if(t==="relu")return Da(e);if(t==="elu")return Eh(e);if(t==="relu6")return A3(e);if(t==="prelu")return Xf(e,r);if(t==="leakyrelu")return Wf(e,n);if(t==="sigmoid")return Tr(e);throw new Error(`Unknown fused activation ${t}.`)}var rm=(e,t)=>!(e>0)||t==="linear";function bz({x:e,filter:t,strides:r,pad:n,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:d}){if(l=l||"linear",rm(B.state.gradientDepth,l)===!1){P(a==="NHWC",()=>`Error in fused conv2d: got dataFormat of ${a} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);let I=Ls(e,t,r,n,a,s,i);return o!=null&&(I=le(I,o)),tm(I,l,u,d)}let h=M(e,"x","conv2d","float32"),p=M(t,"filter","conv2d","float32"),c=h,m=!1;h.rank===3&&(m=!0,c=U(h,[1,h.shape[0],h.shape[1],h.shape[2]])),P(c.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${c.rank}.`),P(p.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`),qr("fused conv2d",n,i);let f=a==="NHWC"?c.shape[3]:c.shape[1];P(p.shape[2]===f,()=>`Error in conv2d: depth of input (${f}) must match input depth for filter ${p.shape[2]}.`),P(za(r,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${r} and dilations '${s}'`);let g=Th(c.shape,p.shape,r,s,n,i),y;o!=null&&(y=M(o,"bias","fused conv2d"),[y]=Lt(y,h),a==="NHWC"?At(g.outShape,y.shape):(P(y.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${y.shape.length}.`),P(y.shape.length===0||y.shape[0]===g.outChannels||y.shape[0]===1,()=>`Error in fused conv2d: bias shape (${y.shape}) is not compatible with the number of output channels (${g.outChannels})`)));let A;if(u!=null){let I=u.shape;if(P(I.length<=1||I.length===3,()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${I.length}.`),I.length===1)P(I[0]===1||I[0]===g.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${I}) is not compatible with the number of output channels (${g.outChannels}).`);else if(I.length===3)try{At(I,g.outShape)}catch(T){let E=`Error in fused conv2d: PReLU activation weights (${I}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(E)}A=M(u,"prelu weights","fused conv2d")}let x=(I,T)=>{P(a==="NHWC",()=>`Error in gradient of fused conv2D: got dataFormat of ${a} but only NHWC is currently supported.`);let[E,R,F,$]=T,S=Qf(I,F,l);P(Ds(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let z=r3(R.shape,S,E,r,n),O=R3(R,S,E.shape,r,n),j=[z,O];if($!=null){let K=em($,S);j.push(K)}return j},b={x:c,filter:p,bias:y,preluActivationWeights:A},w={strides:r,pad:n,dataFormat:a,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:d};return o==null?Pa((I,T,E)=>{let R=B.runKernel(Os,b,w);return E([T,I,R]),m&&(R=U(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:x}})(c,p):Pa((I,T,E,R)=>{let F=B.runKernel(Os,b,w);return R([T,I,F,E]),m&&(F=U(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:x}})(c,p,y)}var vz=W({fusedConv2d_:bz});function wz(e,t,r,n,a,s=[1,1],i){let o=e;e.rank===3&&(o=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=U(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={x:o,dy:l},d={strides:n,pad:a,dimRoundingMode:i,dilations:s,filterShape:r};return B.runKernel(yf,u,d)}var Yv=W({depthwiseConv2dNativeBackpropFilter_:wz});function kz(e,t,r,n,a,s=[1,1],i){let o=t,l=!1;t.rank===3&&(l=!0,o=U(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={dy:o,filter:r},d={strides:n,pad:a,dimRoundingMode:i,dilations:s,inputShape:e},h=B.runKernel(Af,u,d);return l?U(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var Jv=W({depthwiseConv2dNativeBackpropInput_:kz});function Iz({x:e,filter:t,strides:r,pad:n,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:d}){if(rm(B.state.gradientDepth,l)===!1){let w=Nh(e,t,r,n,a,s,i);return o!=null&&(w=le(w,o)),tm(w,l,u,d)}let h=M(e,"x","depthwiseConv2d","float32"),p=M(t,"filter","depthwiseConv2d","float32"),c=h,m=!1;h.rank===3&&(m=!0,c=U(h,[1,h.shape[0],h.shape[1],h.shape[2]])),P(c.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),P(p.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`),P(c.shape[3]===p.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),s==null&&(s=[1,1]),P(za(r,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${s}'`),qr("fused depthwiseConv2d",n,i);let f=Th(c.shape,p.shape,r,s,n,i,!0),g;o!=null&&(g=M(o,"bias","fused conv2d"),[g]=Lt(g,h),At(f.outShape,g.shape));let y;u!=null&&(y=M(u,"prelu weights","fused depthwiseConv2d"));let A=(w,I)=>{P(Ds(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[T,E,R,F]=I,$=Qf(w,R,l),S=Jv(E.shape,$,T,r,n,s,i),z=Yv(E,$,T.shape,r,n,s,i);if(F!=null){let O=em(g,$);return[S,z,O]}return[S,z]},x={x:c,filter:p,bias:g,preluActivationWeights:y},b={strides:r,pad:n,dataFormat:a,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:d};return o==null?Pa((w,I,T)=>{let E=B.runKernel(zs,x,b);return T([I,w,E]),m&&(E=U(E,[E.shape[1],E.shape[2],E.shape[3]])),{value:E,gradFunc:A}})(c,p):Pa((w,I,T,E)=>{let R=B.runKernel(zs,x,b);return E([I,w,R,T]),m&&(R=U(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:A}})(c,p,g)}var Sz=W({fusedDepthwiseConv2d_:Iz});function Cz({a:e,b:t,transposeA:r=!1,transposeB:n=!1,bias:a,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:o=.2}){if(rm(B.state.gradientDepth,s)===!1){let F=Ye(e,t,r,n);return a!=null&&(F=le(F,a)),tm(F,s,i,o)}let l=M(e,"a","fused matMul"),u=M(t,"b","fused matMul");[l,u]=Lt(l,u);let d=r?l.shape[l.rank-2]:l.shape[l.rank-1],h=n?u.shape[u.rank-1]:u.shape[u.rank-2],p=r?l.shape[l.rank-1]:l.shape[l.rank-2],c=n?u.shape[u.rank-2]:u.shape[u.rank-1],m=l.shape.slice(0,-2),f=u.shape.slice(0,-2),g=It(m),y=It(f);P(d===h,()=>`Error in fused matMul: inner shapes (${d}) and (${h}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${r} and transposeB=${n} must match.`);let A=At(l.shape.slice(0,-2),u.shape.slice(0,-2)).concat([p,c]),x=r?U(l,[g,d,p]):U(l,[g,p,d]),b=n?U(u,[y,c,h]):U(u,[y,h,c]),w;a!=null&&(w=M(a,"bias","fused matMul"),[w]=Lt(w,l),At(A,w.shape));let I;i!=null&&(I=M(i,"prelu weights","fused matMul"));let T=(F,$)=>{let[S,z,O,j]=$,K=Qf(U(F,O.shape),O,s),D,Y;if(!r&&!n?(D=Ye(K,z,!1,!0),Y=Ye(S,K,!0,!1)):!r&&n?(D=Ye(K,z,!1,!1),Y=Ye(K,S,!0,!1)):r&&!n?(D=Ye(z,K,!1,!0),Y=Ye(S,K,!1,!1)):(D=Ye(z,K,!0,!0),Y=Ye(K,S,!0,!0)),a!=null){let V=em(j,K);return[D,Y,V]}else return[D,Y]},E={a:x,b,bias:w,preluActivationWeights:I},R={transposeA:r,transposeB:n,activation:s,leakyreluAlpha:o};return a==null?Pa((F,$,S)=>{let z=B.runKernel(Ps,E,R);return S([F,$,z]),{value:U(z,A),gradFunc:T}})(x,b):Pa((F,$,S,z)=>{let O=B.runKernel(Ps,E,R);return z([F,$,O,S]),{value:U(O,A),gradFunc:T}})(x,b,w)}var Tz=W({fusedMatMul_:Cz});function Nz(e){return E3(e,.54,.46)}var Ez=W({hammingWindow_:Nz});function Rz(e){return E3(e,.5,.5)}var Qv=W({hannWindow_:Rz});function $z(e,t,r,n=!1,a=0){let s=0,i=[];for(;s+t<=e.size;)i.push(_e(e,s,t)),s+=r;if(n)for(;s<e.size;){let o=s+t-e.size,l=St([_e(e,s,t-o),vd([o],a)]);i.push(l),s+=r}return i.length===0?ca([],[0,t]):U(St(i),[i.length,t])}var ew=W({frame_:$z});function Mz(e,t,r,n,a=Qv){n==null&&(n=Zv(t));let s=ew(e,t,r),i=L(s,a(t));return Yf(i,n)}var Fz=W({stft_:Mz});function _z(e,t,r,n,a="bilinear",s=0){let i=M(e,"image","cropAndResize"),o=M(t,"boxes","cropAndResize","float32"),l=M(r,"boxInd","cropAndResize","int32"),u=o.shape[0];P(i.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),P(o.rank===2&&o.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${o.shape}.`),P(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${o.shape}.`),P(n.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${n.length}.`),P(n[0]>=1&&n[1]>=1,()=>`cropSize must be atleast [1,1], but was ${n}`),P(a==="bilinear"||a==="nearest",()=>`method must be bilinear or nearest, but was ${a}`);let d={image:i,boxes:o,boxInd:l},h={method:a,extrapolationValue:s,cropSize:n};return B.runKernel(Xo,d,h)}var Pz=W({cropAndResize_:_z});function Oz(e){let t=M(e,"image","flipLeftRight","float32");P(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let r={image:t};return B.runKernel(Qo,r,{})}var zz=W({flipLeftRight_:Oz});function Dz(e){let t=M(e,"image","grayscaleToRGB"),r=t.rank-1,n=t.shape[r];P(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),P(n===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${n}.`);let a=new Array(t.rank);return a.fill(1,0,r),a[r]=3,jn(t,a)}var Lz=W({grayscaleToRGB_:Dz});function Bz(e,t,r=0,n=.5){let a=M(e,"image","rotateWithOffset","float32");P(a.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${a.rank}.`);let s={image:a},i={radians:t,fillValue:r,center:n};return B.runKernel(El,s,i)}var Wz=W({rotateWithOffset_:Bz});function Cd(e,t,r,n,a,s){n==null&&(n=.5),a==null&&(a=Number.NEGATIVE_INFINITY),s==null&&(s=0);let i=e.shape[0];return r=Math.min(r,i),P(0<=n&&n<=1,()=>`iouThreshold must be in [0, 1], but was '${n}'`),P(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),P(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),P(t.rank===1,()=>"scores must be a 1D tensor"),P(t.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`),P(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:r,iouThreshold:n,scoreThreshold:a,softNmsSigma:s}}function Vz(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY){let s=M(e,"boxes","nonMaxSuppression","float32"),i=M(t,"scores","nonMaxSuppression","float32"),o=Cd(s,i,r,n,a);r=o.maxOutputSize,n=o.iouThreshold,a=o.scoreThreshold;let l={maxOutputSize:r,iouThreshold:n,scoreThreshold:a};return B.runKernel(ul,{boxes:s,scores:i},l)}var Uz=W({nonMaxSuppression_:Vz});function Gz(e,t,r){let n=jz(e,t,r),a=n<0?-(n+1):n;e.splice(a,0,t)}function jz(e,t,r){return qz(e,t,r||Hz)}function Hz(e,t){return e>t?1:e<t?-1:0}function qz(e,t,r){let n=0,a=e.length,s=0,i=!1;for(;n<a;){s=n+(a-n>>>1);let o=r(t,e[s]);o>0?n=s+1:(a=s,i=!o)}return i?n:-n-1}function tw(e,t,r,n,a){return $3(e,t,r,n,a,0)}function rw(e,t,r,n,a,s){return $3(e,t,r,n,a,0,!1,s,!0)}function nw(e,t,r,n,a,s){return $3(e,t,r,n,a,s,!0)}function $3(e,t,r,n,a,s,i=!1,o=!1,l=!1){let u=[];for(let g=0;g<t.length;g++)t[g]>a&&u.push({score:t[g],boxIndex:g,suppressBeginIndex:0});u.sort(a4);let d=s>0?-.5/s:0,h=[],p=[];for(;h.length<r&&u.length>0;){let g=u.pop(),{score:y,boxIndex:A,suppressBeginIndex:x}=g;if(y<a)break;let b=!1;for(let w=h.length-1;w>=x;--w){let I=Xz(e,A,h[w]);if(I>=n){b=!0;break}if(g.score=g.score*Kz(n,d,I),g.score<=a)break}g.suppressBeginIndex=h.length,b||(g.score===y?(h.push(A),p.push(g.score)):g.score>a&&Gz(u,g,a4))}let c=h.length,m=r-c;o&&m>0&&(h.push(...new Array(m).fill(0)),p.push(...new Array(m).fill(0)));let f={selectedIndices:h};return i&&(f.selectedScores=p),l&&(f.validOutputs=c),f}function Xz(e,t,r){let n=e.subarray(t*4,t*4+4),a=e.subarray(r*4,r*4+4),s=Math.min(n[0],n[2]),i=Math.min(n[1],n[3]),o=Math.max(n[0],n[2]),l=Math.max(n[1],n[3]),u=Math.min(a[0],a[2]),d=Math.min(a[1],a[3]),h=Math.max(a[0],a[2]),p=Math.max(a[1],a[3]),c=(o-s)*(l-i),m=(h-u)*(p-d);if(c<=0||m<=0)return 0;let f=Math.max(s,u),g=Math.max(i,d),y=Math.min(o,h),A=Math.min(l,p),x=Math.max(y-f,0)*Math.max(A-g,0);return x/(c+m-x)}function Kz(e,t,r){let n=Math.exp(t*r*r);return r<=e?n:0}function a4(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function Zz(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY){let s=M(e,"boxes","nonMaxSuppressionAsync"),i=M(t,"scores","nonMaxSuppressionAsync"),o=Cd(s,i,r,n,a);r=o.maxOutputSize,n=o.iouThreshold,a=o.scoreThreshold;let l=await Promise.all([s.data(),i.data()]),u=l[0],d=l[1],{selectedIndices:h}=tw(u,d,r,n,a);return s!==e&&s.dispose(),i!==t&&i.dispose(),Nt(h,"int32")}var Yz=Zz;function Jz(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY,s=0){let i=M(e,"boxes","nonMaxSuppression"),o=M(t,"scores","nonMaxSuppression"),l=Cd(i,o,r,n,a,s);r=l.maxOutputSize,n=l.iouThreshold,a=l.scoreThreshold,s=l.softNmsSigma;let u={boxes:i,scores:o},d={maxOutputSize:r,iouThreshold:n,scoreThreshold:a,softNmsSigma:s},h=B.runKernel(dl,u,d);return{selectedIndices:h[0],selectedScores:h[1]}}var Qz=W({nonMaxSuppressionWithScore_:Jz});async function eD(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY,s=0){let i=M(e,"boxes","nonMaxSuppressionAsync"),o=M(t,"scores","nonMaxSuppressionAsync"),l=Cd(i,o,r,n,a,s);r=l.maxOutputSize,n=l.iouThreshold,a=l.scoreThreshold,s=l.softNmsSigma;let u=await Promise.all([i.data(),o.data()]),d=u[0],h=u[1],{selectedIndices:p,selectedScores:c}=nw(d,h,r,n,a,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:Nt(p,"int32"),selectedScores:Nt(c)}}var tD=eD;function rD(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY,s=!1){let i=M(e,"boxes","nonMaxSuppression"),o=M(t,"scores","nonMaxSuppression"),l=Cd(i,o,r,n,a,null),u=l.maxOutputSize,d=l.iouThreshold,h=l.scoreThreshold,p={boxes:i,scores:o},c={maxOutputSize:u,iouThreshold:d,scoreThreshold:h,padToMaxOutputSize:s},m=B.runKernel(dd,p,c);return{selectedIndices:m[0],validOutputs:m[1]}}var nD=W({nonMaxSuppressionPadded_:rD});async function aD(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY,s=!1){let i=M(e,"boxes","nonMaxSuppressionAsync"),o=M(t,"scores","nonMaxSuppressionAsync"),l=Cd(i,o,r,n,a,null),u=l.maxOutputSize,d=l.iouThreshold,h=l.scoreThreshold,[p,c]=await Promise.all([i.data(),o.data()]),{selectedIndices:m,validOutputs:f}=rw(p,c,u,d,h,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:Nt(m,"int32"),validOutputs:Se(f,"int32")}}var sD=aD;function iD(e,t,r=!1,n=!1){let a=M(e,"images","resizeBilinear");P(a.rank===3||a.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${a.rank}.`),P(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),P(n===!1||r===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=a,i=!1;a.rank===3&&(i=!0,s=U(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let[]=t,o={images:s},l={alignCorners:r,halfPixelCenters:n,size:t},u=B.runKernel($i,o,l);return i?U(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var oD=W({resizeBilinear_:iD});function lD(e,t,r=!1,n=!1){let a=M(e,"images","resizeNearestNeighbor");P(a.rank===3||a.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${a.rank}.`),P(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),P(a.dtype==="float32"||a.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),P(n===!1||r===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=a,i=!1;a.rank===3&&(i=!0,s=U(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let[]=t,o={images:s},l={alignCorners:r,halfPixelCenters:n,size:t},u=B.runKernel(cd,o,l);return i?U(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var uD=W({resizeNearestNeighbor_:lD});function dD(e,t="binary",r=!1,n=.5){let a=M(e,"image","threshold"),s=.2989,i=.587,o=.114,l=a.shape[0]*a.shape[1],u=L(Nt([n]),255),d,h,p,c;if(P(a.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${a.rank}.`),P(a.shape[2]===3||a.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${a.shape[2]}.`),P(a.dtype==="int32"||a.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${a.dtype}.`),P(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),a.shape[2]===3){[d,h,p]=Yt(a,[1,1,1],-1);let f=L(d,s),g=L(h,i),y=L(p,o);c=le(le(f,g),y)}else c=e;if(t==="otsu"){let f=e3(me(x3(c),"int32"),ft([]),256);u=pD(f,l)}let m=r?Fl(c,u):gn(c,u);return me(L(m,255),"int32")}function pD(e,t){let r=Nt([-1]),n=Nt([0]),a=Nt([0]),s,i,o,l,u,d;for(let h=0;h<e.size-1;h++){s=_e(e,0,h+1),i=_e(e,h+1),u=pe(ke(s),t),d=pe(ke(i),t);let p=ke(L(s,Pu(0,s.size)));o=pe(p,ke(s));let c=vd(i.shape,s.size),m=le(Pu(0,i.size),c),f=L(i,m);l=pe(ke(f),ke(i));let g=ce(o,l),y=ce(o,l),A=L(u,d);a=L(L(A,g),y);let x=gn(a,n);n=Ur(x,a,n),r=Ur(x,Nt([h]),r)}return r}var hD=W({threshold_:dD});function cD(e,t,r="nearest",n="constant",a=0,s){let i=M(e,"image","transform","float32"),o=M(t,"transforms","transform","float32");P(i.rank===4,()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`),P(o.rank===2&&(o.shape[0]===i.shape[0]||o.shape[0]===1)&&o.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),P(s==null||s.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`);let l={image:i,transforms:o},u={interpolation:r,fillMode:n,fillValue:a,outputShape:s};return B.runKernel(Cl,l,u)}var fD=W({transform_:cD});function mD(e,t,r){P(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),P(r%1===0,()=>`bandPart(): numUpper must be an integer, got ${r}.`);let n=M(e,"a","bandPart");P(n.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${n.rank}.`);let a=n.shape,[s,i]=n.shape.slice(-2);if(!(t<=s))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`);if(!(r<=i))throw new Error(`bandPart(): numUpper (${r}) must not be greater than the number of columns (${i}).`);t<0&&(t=s),r<0&&(r=i);let o=U(Pu(0,s,1,"int32"),[-1,1]),l=Pu(0,i,1,"int32"),u=ce(o,l),d=ga(Fl(u,Se(+t,"int32")),Ml(u,Se(-r,"int32"))),h=Ot([s,i],n.dtype);return U(ur(an(U(n,[-1,s,i])).map(p=>Ur(d,p,h))),a)}var gD=W({bandPart_:mD});function yD(e){let t;if(Array.isArray(e)){t=!1,P(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let a=e[0].shape[0];for(let s=1;s<e.length;++s)P(e[s].shape[0]===a,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[s].shape[0]} vs. ${a})`)}else t=!0,e=Yt(e,e.shape[0],0).map(a=>et(a,[0]));P(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let r=[],n=e;for(let a=0;a<e.length;++a)r.push(B.tidy(()=>{let s=n[a];if(a>0)for(let i=0;i<a;++i){let o=L(ke(L(r[i],s)),r[i]);s=ce(s,o)}return pe(s,Bf(s,"euclidean"))}));return t?ur(r,0):r}var AD=W({gramSchmidt_:yD});function xD(e,t=!1){if(P(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return s4(e,t);{let r=e.shape.slice(0,e.shape.length-2).reduce((l,u)=>l*u),n=an(U(e,[r,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),a=[],s=[];n.forEach(l=>{let[u,d]=s4(l,t);a.push(u),s.push(d)});let i=U(ur(a,0),e.shape),o=U(ur(s,0),e.shape);return[i,o]}}function s4(e,t=!1){return B.tidy(()=>{P(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let r=e.shape[0],n=e.shape[1],a=u3(r),s=Vr(e),i=ca([[1]],[1,1]),o=Vr(i),l=r>=n?n:r;for(let u=0;u<l;++u){let d=s,h=o,p=a;[o,s,a]=B.tidy(()=>{let c=_e(s,[u,u],[r-u,1]),m=Bf(c),f=_e(s,[u,u],[1,1]),g=Ur(gn(f,0),ca([[-1]]),ca([[1]])),y=ce(f,L(g,m)),A=pe(c,y);A.shape[0]===1?o=Vr(i):o=St([i,_e(A,[1,0],[A.shape[0]-1,A.shape[1]])],0);let x=Mt(pe(Ye(g,y),m)),b=_e(s,[u,0],[r-u,n]),w=L(x,o),I=tt(o);if(u===0)s=ce(b,Ye(w,Ye(I,b)));else{let R=ce(b,Ye(w,Ye(I,b)));s=St([_e(s,[0,0],[u,n]),R],0)}let T=tt(w),E=_e(a,[0,u],[r,a.shape[1]-u]);if(u===0)a=ce(E,Ye(Ye(E,o),T));else{let R=ce(E,Ye(Ye(E,o),T));a=St([_e(a,[0,0],[r,u]),R],1)}return[o,s,a]}),ee([d,h,p])}return!t&&r>n&&(a=_e(a,[0,0],[r,n]),s=_e(s,[0,0],[n,n])),[a,s]})}var bD=W({qr_:xD}),aw=(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",e))(aw||{});function vD(e,t,r=3){let n=M(e,"losses","computeWeightedLoss"),a=null;t!=null&&(a=M(t,"weights","computeWeightedLoss"));let s=a==null?n:L(n,a);if(r===0)return s;if(r===2)return ke(s);if(r===1){if(a==null)return Vt(s);{let i=n.size/a.size,o=pe(ke(s),ke(a));return i>1?pe(o,Se(i)):o}}if(r===3){if(a==null)return pe(ke(s),Se(n.size));{let i=L(a,cn(n.shape)),o=me(ke(_u(i,Se(0))),"float32");return pe(ke(s),o)}}throw Error(`Unknown reduction: ${r}`)}var ns=W({computeWeightedLoss_:vD});function wD(e,t,r,n=3){let a=M(e,"labels","absoluteDifference"),s=M(t,"predictions","absoluteDifference"),i=null;r!=null&&(i=M(r,"weights","absoluteDifference")),jr(a.shape,s.shape,"Error in absoluteDifference: ");let o=ar(ce(a,s));return ns(o,i,n)}var kD=W({absoluteDifference_:wD});function ID(e,t,r,n,a=3){let s=M(e,"labels","cosineDistance"),i=M(t,"predictions","cosineDistance"),o=null;n!=null&&(o=M(n,"weights","cosineDistance")),jr(s.shape,i.shape,"Error in cosineDistance: ");let l=Se(1),u=ce(l,ke(L(s,i),r,!0));return ns(u,o,a)}var SD=W({cosineDistance_:ID});function CD(e,t,r,n=3){let a=M(e,"labels","hingeLoss"),s=M(t,"predictions","hingeLoss"),i=null;r!=null&&(i=M(r,"weights","hingeLoss")),jr(a.shape,s.shape,"Error in hingeLoss: ");let o=Se(1);a=ce(L(Se(2),a),o);let l=Da(ce(o,L(a,s)));return ns(l,i,n)}var TD=W({hingeLoss_:CD});function ND(e,t,r,n=1,a=3){let s=M(e,"labels","huberLoss"),i=M(t,"predictions","huberLoss"),o=null;r!=null&&(o=M(r,"weights","huberLoss")),jr(s.shape,i.shape,"Error in huberLoss: ");let l=Se(n),u=ar(ce(i,s)),d=$h(u,l),h=ce(u,d),p=le(L(Se(.5),bt(d)),L(l,h));return ns(p,o,a)}var ED=W({huberLoss_:ND});function RD(e,t,r,n=1e-7,a=3){let s=M(e,"labels","logLoss"),i=M(t,"predictions","logLoss"),o=null;r!=null&&(o=M(r,"weights","logLoss")),jr(s.shape,i.shape,"Error in logLoss: ");let l=Se(1),u=Se(n),d=Mt(L(s,_n(le(i,u)))),h=L(ce(l,s),_n(le(ce(l,i),u))),p=ce(d,h);return ns(p,o,a)}var $D=W({logLoss_:RD});function MD(e,t,r,n=3){let a=M(e,"labels","meanSquaredError"),s=M(t,"predictions","meanSquaredError"),i=null;r!=null&&(i=M(r,"weights","meanSquaredError")),jr(a.shape,s.shape,"Error in meanSquaredError: ");let o=C3(a,s);return ns(o,i,n)}var FD=W({meanSquaredError_:MD});function _D(e,t){let r=M(e,"labels","sigmoidCrossEntropyWithLogits"),n=M(t,"logits","sigmoidCrossEntropyWithLogits");jr(r.shape,n.shape,"Error in sigmoidCrossEntropyWithLogits: ");let a=Da(n),s=L(n,r),i=Vf(Fn(Mt(ar(n))));return le(ce(a,s),i)}function PD(e,t,r,n=0,a=3){let s=M(e,"multiClassLabels","sigmoidCrossEntropy"),i=M(t,"logits","sigmoidCrossEntropy"),o=null;if(r!=null&&(o=M(r,"weights","sigmoidCrossEntropy")),jr(s.shape,i.shape,"Error in sigmoidCrossEntropy: "),n>0){let u=Se(n),d=Se(1),h=Se(.5);s=le(L(s,ce(d,u)),L(h,u))}let l=_D(s,i);return ns(l,o,a)}var OD=W({sigmoidCrossEntropy_:PD});function zD(e,t,r=-1){if(r===-1&&(r=t.rank-1),r!==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 ${r}`);return Pa((n,a,s)=>{let i=Rv(a,[r],!0),o=ce(me(a,"float32"),i);s([n,o]);let l=Mt(L(o,n));return{value:ke(l,[r]),gradFunc:(u,d)=>{let[h,p]=d,c=_o(u.shape,[r]);return[L(U(u,c),ce(me(h,"float32"),Fn(p))),L(U(u,c),ce(Fn(p),me(h,"float32")))]}}})(e,t)}function DD(e,t,r,n=0,a=3){let s=M(e,"onehotLabels","softmaxCrossEntropy"),i=M(t,"logits","softmaxCrossEntropy"),o=null;if(r!=null&&(o=M(r,"weights","softmaxCrossEntropy")),jr(s.shape,i.shape,"Error in softmaxCrossEntropy: "),n>0){let u=Se(n),d=Se(1),h=Se(s.shape[1]);s=le(L(s,ce(d,u)),pe(u,h))}let l=zD(s,i);return ns(l,o,a)}var LD=W({softmaxCrossEntropy_:DD});function BD(e,t,r,n){let a=M(e,"indices","sparseFillEmptyRows","int32"),s=M(t,"values","sparseFillEmptyRows"),i=M(r,"denseShape","sparseFillEmptyRows","int32"),o=M(n,"defaultValue","sparseFillEmptyRows",s.dtype);if(a.rank!==2)throw new Error(`Indices should be Tensor2D but received shape
|
|
${a.shape}`);if(s.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);if(i.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(o.rank!==0)throw new Error(`Default value should be a scalar but received shape ${o.shape}`);let l={indices:a,values:s,denseShape:i,defaultValue:o},u=B.runKernel(fh,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var WD=W({sparseFillEmptyRows_:BD});function VD(e,t,r){let n=M(e,"inputIndices","sparseReshape","int32"),a=M(t,"inputShape","sparseReshape","int32"),s=M(r,"newShape","sparseReshape","int32");if(n.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
|
|
${n.shape}`);if(a.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${a.shape}`);if(s.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);let i={inputIndices:n,inputShape:a,newShape:s},o=B.runKernel(yd,i);return{outputIndices:o[0],outputShape:o[1]}}var UD=W({sparseReshape_:VD});function GD(e,t,r){let n=M(e,"data","sparseSegmentMean"),a=M(t,"indices","sparseSegmentMean","int32"),s=M(r,"segmentIds","sparseSegmentMean","int32");if(n.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${a.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${s.shape}`);let i={data:n,indices:a,segmentIds:s};return B.runKernel(mh,i)}var jD=W({sparseSegmentMean_:GD});function HD(e,t,r){let n=M(e,"data","sparseSegmentSum"),a=M(t,"indices","sparseSegmentSum","int32"),s=M(r,"segmentIds","sparseSegmentSum","int32");if(n.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${a.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${s.shape}`);let i={data:n,indices:a,segmentIds:s};return B.runKernel(gh,i)}var qD=W({sparseSegmentSum_:HD});function XD(e,t,r,n,a,s,i,o){let l=M(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 u=M(t,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let d={separator:r,nGramWidths:n,leftPad:a,rightPad:s,padWidth:i,preserveShortSequences:o},h={data:l,dataSplits:u},p=B.runKernel(Ah,h,d);return{nGrams:p[0],nGramsSplits:p[1]}}var KD=W({stringNGrams_:XD});function ZD(e,t,r=!0){let n=M(e,"input","stringSplit","string"),a=M(t,"delimiter","stringSplit","string");if(n.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${n.shape}`);if(a.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${a.shape}`);let s={skipEmpty:r},i={input:n,delimiter:a},o=B.runKernel(Mf,i,s);return{indices:o[0],values:o[1],shape:o[2]}}var YD=W({stringSplit_:ZD});function JD(e,t){let r=M(e,"input","stringToHashBucketFast","string"),n={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let a={input:r};return B.runKernel(Ff,a,n)}var QD=W({stringToHashBucketFast_:JD}),eL={fft:Zf,ifft:Yp,rfft:Yf,irfft:S3},tL={hammingWindow:Ez,hannWindow:Qv,frame:ew,stft:Fz},Ie={flipLeftRight:zz,grayscaleToRGB:Lz,resizeNearestNeighbor:uD,resizeBilinear:oD,rotateWithOffset:Wz,cropAndResize:Pz,nonMaxSuppression:Uz,nonMaxSuppressionAsync:Yz,nonMaxSuppressionWithScore:Qz,nonMaxSuppressionWithScoreAsync:tD,nonMaxSuppressionPadded:nD,nonMaxSuppressionPaddedAsync:sD,threshold:hD,transform:fD},sw={bandPart:gD,gramSchmidt:AD,qr:bD},rL={absoluteDifference:kD,computeWeightedLoss:ns,cosineDistance:SD,hingeLoss:TD,huberLoss:ED,logLoss:$D,meanSquaredError:FD,sigmoidCrossEntropy:OD,softmaxCrossEntropy:LD},$p={sparseFillEmptyRows:WD,sparseReshape:UD,sparseSegmentMean:jD,sparseSegmentSum:qD},f0={stringNGrams:KD,stringSplit:YD,stringToHashBucketFast:QD},as=class extends U6{minimize(e,t=!1,r){let{value:n,grads:a}=this.computeGradients(e,r);if(r!=null){let s=r.map(i=>({name:i.name,tensor:a[i.name]}));this.applyGradients(s)}else this.applyGradients(a);return ee(a),t?n:(n.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return Ev(e,t)}dispose(){this.iterations_!=null&&ee(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Se(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(as,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var nm=class extends as{constructor(e,t,r=null){super(),this.learningRate=e,this.rho=t,this.epsilon=r,this.accumulatedGrads=[],this.accumulatedUpdates=[],r==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,r)=>{let n=B.registeredVariables[t],a=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${t}/accum_grad`,variable:X(()=>at(n).variable(a))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName:`${t}/accum_var`,variable:X(()=>at(n).variable(a))});let s=Array.isArray(e)?e[r].tensor:e[t];if(s==null)return;let i=this.accumulatedGrads[r].variable,o=this.accumulatedUpdates[r].variable;X(()=>{let l=le(L(i,this.rho),L(bt(s),1-this.rho)),u=L(pe(Er(le(o,this.epsilon)),Er(le(i,this.epsilon))),s),d=le(L(o,this.rho),L(bt(u),1-this.rho));i.assign(l),o.assign(d);let h=le(L(u,-this.learningRate),n);n.assign(h)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(ee(this.accumulatedGrads.map(e=>e.variable)),ee(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,r=!1;this.accumulatedGrads=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(r)})),this.accumulatedUpdates=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(r)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}};nm.className="Adadelta";Gi(nm);var am=class extends as{constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,r)=>{let n=B.registeredVariables[t];this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${t}/accumulator`,variable:X(()=>vd(n.shape,this.initialAccumulatorValue).variable(!1))});let a=Array.isArray(e)?e[r].tensor:e[t];if(a==null)return;let s=this.accumulatedGrads[r].variable;X(()=>{let i=le(s,bt(a));s.assign(i);let o=le(L(pe(a,Er(le(i,B.backend.epsilon()))),-this.learningRate),n);n.assign(o)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&ee(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(r=>({originalName:r.name,variable:r.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}};am.className="Adagrad";Gi(am);var sm=class extends as{constructor(e,t,r,n=null){super(),this.learningRate=e,this.beta1=t,this.beta2=r,this.epsilon=n,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],X(()=>{this.accBeta1=Se(t).variable(),this.accBeta2=Se(r).variable()}),n==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(r=>r.name):Object.keys(e);X(()=>{let r=ce(1,this.accBeta1),n=ce(1,this.accBeta2);t.forEach((a,s)=>{let i=B.registeredVariables[a],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${a}/m`,variable:X(()=>at(i).variable(o))}),this.accumulatedSecondMoment[s]==null&&(this.accumulatedSecondMoment[s]={originalName:`${a}/v`,variable:X(()=>at(i).variable(o))});let l=Array.isArray(e)?e[s].tensor:e[a];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,d=this.accumulatedSecondMoment[s].variable,h=le(L(u,this.beta1),L(l,1-this.beta1)),p=le(L(d,this.beta2),L(bt(l),1-this.beta2)),c=pe(h,r),m=pe(p,n);u.assign(h),d.assign(p);let f=le(L(pe(c,le(Er(m),this.epsilon)),-this.learningRate),i);i.assign(f)}),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&&ee(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&ee(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),X(()=>{this.accBeta1.assign(Ws(this.beta1,this.iterations_+1)),this.accBeta2.assign(Ws(this.beta2,this.iterations_+1))});let t=e.length/2,r=!1;this.accumulatedFirstMoment=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(r)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(r)}))}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)}};sm.className="Adam";Gi(sm);var im=class extends as{constructor(e,t,r,n=null,a=0){super(),this.learningRate=e,this.beta1=t,this.beta2=r,this.epsilon=n,this.decay=a,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],X(()=>{this.iteration=Se(0).variable(),this.accBeta1=Se(t).variable()}),n==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(r=>r.name):Object.keys(e);X(()=>{let r=ce(1,this.accBeta1),n=pe(-this.learningRate,le(L(this.iteration,this.decay),1));t.forEach((a,s)=>{let i=B.registeredVariables[a],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${a}/m`,variable:at(i).variable(o)}),this.accumulatedWeightedInfNorm[s]==null&&(this.accumulatedWeightedInfNorm[s]={originalName:`${a}/v`,variable:at(i).variable(o)});let l=Array.isArray(e)?e[s].tensor:e[a];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,d=this.accumulatedWeightedInfNorm[s].variable,h=le(L(u,this.beta1),L(l,1-this.beta1)),p=L(d,this.beta2),c=ar(l),m=rs(p,c);u.assign(h),d.assign(m);let f=le(L(pe(n,r),pe(h,le(m,this.epsilon))),i);i.assign(f)}),this.iteration.assign(le(this.iteration,1)),this.accBeta1.assign(L(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&ee(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&ee(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)}};im.className="Adamax";Gi(im);var Fh=class extends as{constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,r)=>{let n=Array.isArray(e)?e[r].tensor:e[t];if(n==null)return;let a=B.registeredVariables[t];X(()=>{let s=le(L(this.c,n),a);a.assign(s)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=mr(Se(-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)}};Fh.className="SGD";Gi(Fh);var om=class extends Fh{constructor(e,t,r=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=r,this.accumulations=[],this.m=Se(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,r)=>{let n=B.registeredVariables[t];this.accumulations[r]==null&&(this.accumulations[r]={originalName:`${t}/momentum`,variable:X(()=>at(n).variable(!1))});let a=this.accumulations[r].variable,s=Array.isArray(e)?e[r].tensor:e[t];s!=null&&X(()=>{let i,o=le(L(this.m,a),s);this.useNesterov?i=le(L(this.c,le(s,L(o,this.m))),n):i=le(L(this.c,o),n),a.assign(o),n.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&ee(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(r=>({originalName:r.name,variable:r.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)}};om.className="Momentum";Gi(om);var lm=class extends as{constructor(e,t=.9,r=0,n=null,a=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=r,this.epsilon=n,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=a,n==null&&(this.epsilon=B.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,r)=>{let n=B.registeredVariables[t],a=!1;this.accumulatedMeanSquares[r]==null&&(this.accumulatedMeanSquares[r]={originalName:`${t}/rms`,variable:X(()=>at(n).variable(a))}),this.accumulatedMoments[r]==null&&(this.accumulatedMoments[r]={originalName:`${t}/momentum`,variable:X(()=>at(n).variable(a))}),this.accumulatedMeanGrads[r]==null&&this.centered&&(this.accumulatedMeanGrads[r]={originalName:`${t}/mg`,variable:X(()=>at(n).variable(a))});let s=Array.isArray(e)?e[r].tensor:e[t];if(s==null)return;let i=this.accumulatedMeanSquares[r].variable,o=this.accumulatedMoments[r].variable;X(()=>{let l=le(L(i,this.decay),L(bt(s),1-this.decay));if(this.centered){let u=this.accumulatedMeanGrads[r].variable,d=le(L(u,this.decay),L(s,1-this.decay)),h=pe(L(s,this.learningRate),Er(ce(l,le(bt(d),this.epsilon)))),p=le(L(o,this.momentum),h);i.assign(l),u.assign(d),o.assign(p);let c=ce(n,p);n.assign(c)}else{let u=le(L(i,this.decay),L(bt(s),1-this.decay)),d=le(L(o,this.momentum),pe(L(s,this.learningRate),Er(le(u,this.epsilon))));i.assign(u),o.assign(d);let h=ce(n,d);n.assign(h)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&ee(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&ee(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&ee(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,r=!1;this.accumulatedMeanSquares=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(r)})),this.accumulatedMoments=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(r)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(n=>({originalName:n.name,variable:n.tensor.variable(r)})))}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)}};lm.className="RMSProp";Gi(lm);var Ss=class{static sgd(e){return new Fh(e)}static momentum(e,t,r=!1){return new om(e,t,r)}static rmsprop(e,t=.9,r=0,n=null,a=!1){return new lm(e,t,r,n,a)}static adam(e=.001,t=.9,r=.999,n=null){return new sm(e,t,r,n)}static adadelta(e=.001,t=.95,r=null){return new nm(e,t,r)}static adamax(e=.002,t=.9,r=.999,n=null,a=0){return new im(e,t,r,n,a)}static adagrad(e,t=.1){return new am(e,t)}},Ao={sgd:Ss.sgd,momentum:Ss.momentum,adadelta:Ss.adadelta,adagrad:Ss.adagrad,rmsprop:Ss.rmsprop,adamax:Ss.adamax,adam:Ss.adam},nL=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function M3(){return new Promise(e=>nL(()=>e()))}var C={};Be(C,{ERF_A1:()=>fL,ERF_A2:()=>mL,ERF_A3:()=>gL,ERF_A4:()=>yL,ERF_A5:()=>AL,ERF_P:()=>cL,PARALLELIZE_THRESHOLD:()=>F3,SELU_SCALE:()=>ow,SELU_SCALEALPHA:()=>iw,applyActivation:()=>tm,assertAndGetBroadcastShape:()=>At,assertAxesAreInnerMostDims:()=>z_,assertParamsConsistent:()=>aL,assignToTypedArray:()=>IL,axesAreInnerMostDims:()=>o3,calculateShapes:()=>F6,checkEinsumDimSizes:()=>RL,checkPadOnDimRoundingMode:()=>qr,combineLocations:()=>bv,complexWithEvenIndex:()=>vL,complexWithOddIndex:()=>wL,computeConv2DInfo:()=>Th,computeConv3DInfo:()=>rv,computeDefaultPad:()=>Jy,computeDilation2DInfo:()=>PF,computeOptimalWindowSize:()=>iL,computeOutAndReduceShapes:()=>vv,computeOutShape:()=>sL,computePool2DInfo:()=>tv,computePool3DInfo:()=>OF,convertConv2DDataFormat:()=>nv,decodeEinsumEquation:()=>NL,eitherStridesOrDilationsAreOne:()=>za,expandShapeToKeepDim:()=>_o,exponent:()=>CL,exponents:()=>SL,fromStringArrayToUint8:()=>YL,fromUint8ToStringArray:()=>ZL,getAxesPermutation:()=>wv,getBroadcastDims:()=>E6,getComplexWithIndex:()=>kL,getEinsumComputePath:()=>$L,getEinsumPermutation:()=>EL,getFusedBiasGradient:()=>em,getFusedDyActivation:()=>Qf,getImageCenter:()=>oL,getInnerMostAxes:()=>D_,getPermuted:()=>uL,getReductionAxes:()=>Jt,getReshaped:()=>lL,getReshapedPermuted:()=>dL,getSliceBeginCoords:()=>pL,getSliceSize:()=>hL,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>PL,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>OL,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>zL,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>BL,getSparseReshapeInputOutputMismatchErrorMessage:()=>VL,getSparseReshapeInputOutputMultipleErrorMessage:()=>WL,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>DL,getSparseReshapeNegativeOutputDimErrorMessage:()=>LL,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>HL,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>UL,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>GL,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>jL,getUndoAxesPermutation:()=>l3,isIdentityPermutation:()=>ML,log:()=>s$,mergeRealAndImagArrays:()=>xL,prepareAndValidate:()=>M6,prepareSplitSize:()=>_L,segment_util:()=>lw,shouldFuse:()=>rm,slice_util:()=>Dt,splitRealAndImagArrays:()=>bL,tupleValuesAreOne:()=>Ds,upcastType:()=>Nr,validateInput:()=>qy,validateUpdateShape:()=>Hy,warn:()=>Ts});function aL(e,t){let r=e[0].length;e.forEach((a,s)=>{P(a.length===r,()=>`Error in concat${r}D: rank of tensors[${s}] must be the same as the rank of the rest (${r})`)}),P(t>=0&&t<r,()=>`Error in concat${r}D: axis must be between 0 and ${r-1}.`);let n=e[0];e.forEach((a,s)=>{for(let i=0;i<r;i++)P(i===t||a[i]===n[i],()=>`Error in concat${r}D: Shape of tensors[${s}] (${a}) does not match the shape of the rest (${n}) along the non-concatenated axis ${s}.`)})}function sL(e,t){let r=e[0].slice();for(let n=1;n<e.length;n++)r[t]+=e[n][t];return r}var F3=30;function iL(e){return e<=F3?e:C0(e,Math.floor(Math.sqrt(e)))}function oL(e,t,r){let n=r*(typeof e=="number"?e:e[0]),a=t*(typeof e=="number"?e:e[1]);return[n,a]}function lL(e,t,r,n=!0){let a=[];if(n)a=a.concat(t.slice(0)),a.push(e[0]/r),a=a.concat(e.slice(1));else{a=a.concat(e[0]);let s=t.length;for(let i=0;i<s;++i)a=a.concat([e[i+1]/t[i],t[i]]);a=a.concat(e.slice(s+1))}return a}function uL(e,t,r=!0){let n=[];if(r){n.push(t);for(let a=t+1;a<e;++a)a<=2*t?(n.push(a),n.push(a-(t+1))):n.push(a)}else{let a=[],s=[];for(let i=1;i<e;++i)i>=t*2+1||i%2===1?s.push(i):a.push(i);n.push(...a),n.push(0),n.push(...s)}return n}function dL(e,t,r,n=!0){let a=[];n?a.push(e[0]/r):a.push(e[0]*r);for(let s=1;s<e.length;++s)s<=t.length?n?a.push(t[s-1]*e[s]):a.push(e[s]/t[s-1]):a.push(e[s]);return a}function pL(e,t){let r=[0];for(let n=0;n<t;++n)r.push(e[n][0]);return r}function hL(e,t,r){let n=e.slice(0,1);for(let a=0;a<r;++a)n.push(e[a+1]-t[a][0]-t[a][1]);return n}var iw=1.7580993408473768,ow=1.0507009873554805,cL=.3275911,fL=.254829592,mL=-.284496736,gL=1.421413741,yL=-1.453152027,AL=1.061405429;function xL(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 r=new Float32Array(e.length*2);for(let n=0;n<r.length;n+=2)r[n]=e[n/2],r[n+1]=t[n/2];return r}function bL(e){let t=new Float32Array(e.length/2),r=new Float32Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=e[n],r[n/2]=e[n+1];return{real:t,imag:r}}function vL(e){let t=Math.ceil(e.length/4),r=new Float32Array(t),n=new Float32Array(t);for(let a=0;a<e.length;a+=4)r[Math.floor(a/4)]=e[a],n[Math.floor(a/4)]=e[a+1];return{real:r,imag:n}}function wL(e){let t=Math.floor(e.length/4),r=new Float32Array(t),n=new Float32Array(t);for(let a=2;a<e.length;a+=4)r[Math.floor(a/4)]=e[a],n[Math.floor(a/4)]=e[a+1];return{real:r,imag:n}}function kL(e,t){let r=e[t*2],n=e[t*2+1];return{real:r,imag:n}}function IL(e,t,r,n){e[n*2]=t,e[n*2+1]=r}function SL(e,t){let r=new Float32Array(e/2),n=new Float32Array(e/2);for(let a=0;a<Math.ceil(e/2);a++){let s=(t?2:-2)*Math.PI*(a/e);r[a]=Math.cos(s),n[a]=Math.sin(s)}return{real:r,imag:n}}function CL(e,t,r){let n=(r?2:-2)*Math.PI*(e/t),a=Math.cos(n),s=Math.sin(n);return{real:a,imag:s}}var Ag="->",TL=/->/g,i4=",",o4="...";function NL(e,t){e=e.replace(/\s/g,"");let r=(e.length-e.replace(TL,"").length)/Ag.length;if(r<1)throw new Error("Equations without an arrow are not supported.");if(r>1)throw new Error(`Equation must contain exactly one arrow ("${Ag}").`);let[n,a]=e.split(Ag);P(n.indexOf(o4)===-1,()=>`The ellipsis notation ("${o4}") is not supported yet.`);let s=n.split(i4),i=s.length;if(t!==i)throw new Error(`Expected ${i} input tensors, received ${t}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let o=[];for(let p=0;p<a.length;++p){let c=a[p];if(!s.some(m=>m.indexOf(c)!==-1))throw new Error(`Output subscripts contain the label ${c} not present in the input subscripts.`);o.indexOf(c)===-1&&o.push(c)}for(let p=0;p<n.length;++p){let c=n[p];o.indexOf(c)===-1&&c!==i4&&o.push(c)}let l=new Array(s.length);for(let p=0;p<i;++p){if(new Set(s[p].split("")).size!==s[p].length)throw new Error(`Found duplicate axes in input component ${s[p]}. Support for duplicate axes in input is not implemented yet.`);l[p]=[];for(let c=0;c<s[p].length;++c)l[p].push(o.indexOf(s[p][c]))}let u=o.length,d=a.length,h=[];for(let p=d;p<u;++p)h.push(p);return{allDims:o,summedDims:h,idDims:l}}function EL(e,t){let r=new Array(e);r.fill(-1);for(let a=0;a<t.length;++a)r[t[a]]=a;let n=[];for(let a=0;a<e;++a)r[a]===-1&&n.push(a);return r=r.filter(a=>a!==-1),{permutationIndices:r,expandDims:n}}function RL(e,t,r){let n=new Array(e);for(let a=0;a<r.length;++a){let s=r[a].shape;for(let i=0;i<t[a].length;++i)n[t[a][i]]===void 0?n[t[a][i]]=s[i]:P(n[t[a][i]]===s[i],()=>`Expected dimension ${n[t[a][i]]} at axis ${i} of input shaped ${JSON.stringify(s)}, but got dimension ${s[i]}`)}}function $L(e,t){let r=e,n=[],a=0;e.length===0&&r.push(-1),a=e.length+1;for(let i=0;i<a;++i)n.push([]);let s=[];for(let i=0;i<r.length;++i){let o=r[i],l=FL(t,o);for(let u of l)s.indexOf(u)===-1&&(n[i].push(u),s.push(u))}return{path:r,steps:n}}function ML(e){return e.every((t,r)=>t===r)}function FL(e,t){let r=[];for(let n=0;n<e.length;++n)(e[n].length===0||e[n].indexOf(t)!==-1||t===-1)&&r.push(n);return r}function _L(e,t,r=0){let n=[];if(typeof t=="number")P(e.shape[r]%t===0,()=>"Number of splits must evenly divide the axis."),n=new Array(t).fill(e.shape[r]/t);else{let a=t.reduce((i,o)=>(o===-1&&(i+=1),i),0);P(a<=1,()=>"There should be only one negative value in split array.");let s=t.indexOf(-1);if(s!==-1){let i=t.reduce((o,l)=>l>0?o+l:o);t[s]=e.shape[r]-i}P(e.shape[r]===t.reduce((i,o)=>i+o),()=>"The sum of sizes must match the size of the axis dimension."),n=t}return n}function PL(e){return`Received SparseTensor with denseShape[0] = 0 but
|
|
indices.shape[0] = ${e}`}function OL(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function zL(e,t,r){return`indices(${e}, 0) is invalid: ${t} >= ${r}`}function DL(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function LL(e,t){return`size ${e} must be non-negative, not ${t}`}function BL(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function WL(e,t){let r=It(e),n=It(t);return`Input to reshape is a SparseTensor with ${r}
|
|
dense values, but the requested shape requires a multiple of ${n}. inputShape=${e} outputShape= ${t}`}function VL(e,t){let r=It(e),n=It(t);return`Input to reshape is a tensor with ${r} dense values, but the requested shape has ${n}. inputShape=${e} outputShape=${t}`}function UL(){return"segment ids must be >= 0"}function GL(){return"segment ids are not increasing"}function jL(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function HL(e,t,r){return`Bad: indices[${e}] == ${t} out of range [0, ${r})`}var lw={};Be(lw,{collectGatherOpShapeInfo:()=>KL,computeOutShape:()=>XL,segOpComputeOptimalWindowSize:()=>qL});function qL(e,t){let r=!1,n;for(e<=F3?(n=e,r=!0):n=C0(e,Math.floor(Math.sqrt(e)));!r;)n>t||n===e?r=!0:n=C0(e,n+1);return n}function XL(e,t,r){let n=[],a=e.length;for(let s=0;s<a;s++)s!==t?n.push(e[s]):n.push(r);return n}function KL(e,t,r,n){let a=t.shape.length,s=e.shape.length;if(n!==0&&(n<-a||n>a))throw new Error(`Expect batchDims in the range of [-${a}, ${a}], but got ${n}`);if(n<0&&(n+=a),n>s)throw new Error(`batchDims (${n}) must be less than rank(x) (
|
|
${s}).`);if(r<n)throw new Error(`batchDims (${n}) must be less than or equal to axis (${r}).`);for(let h=0;h<n;++h)if(e.shape[h]!==t.shape[h])throw new Error(`x.shape[${h}]: ${e.shape[h]} should be equal to indices.shape[${h}]: ${t.shape[h]}.`);let i=e.shape[r],o=[],l=1,u=1,d=1;for(let h=0;h<n;++h)o.push(e.shape[h]),l*=e.shape[h];for(let h=n;h<r;h++)o.push(e.shape[h]),u*=e.shape[h];for(let h=n;h<a;h++)o.push(t.shape[h]);for(let h=r+1;h<s;h++)o.push(e.shape[h]),d*=e.shape[h];return{batchSize:l,sliceSize:d,outerSize:u,dimSize:i,outputShape:o}}function ZL(e){try{return e.map(t=>R0(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function YL(e){return e.map(t=>vh(t))}var Kn={};Be(Kn,{nonMaxSuppressionV3Impl:()=>tw,nonMaxSuppressionV4Impl:()=>rw,nonMaxSuppressionV5Impl:()=>nw,whereImpl:()=>Hv});var ja=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,ja.prototype)}},da=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,da.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)}},uw=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,uw.prototype)}},dw=class{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){let r=this.cache.keys().next().value;this.cache.delete(r)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;t<this.maxEntries-e;t++){let r=this.cache.keys().next().value;this.cache.delete(r)}this.maxEntries=e}};function Oo(e,t){if(Array.isArray(e)){let r=[];for(let n=0;n<t;n++)r=r.concat(e);return r}else{let r=new Array(t);return r.fill(e),r}}function Na(e,t){if(!e)throw new uw(t)}function l4(e,t){let r=0;for(let n of e)n===t&&r++;return r}function rn(e){return e.length===1?e[0]:e}function Tt(e){return Array.isArray(e)?e:[e]}function Ha(e){let t=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return t[0]!=="_"?t:"private"+t}function wo(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,r)=>r.toUpperCase())}var Un={};function _3(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function Vg(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>Vg(t));else{let t=Object.keys(e);for(let r of t){let n=e[r];n!=null&&typeof n=="object"&&(!Array.isArray(n)&&n.type==="ndarray"&&typeof n.value=="number"?e[r]=n.value:Vg(n))}}}function _h(e,t={},r={},n="object",a=!1){if(typeof e=="string"){let s=e,i;if(s in r)i=r[s];else if(s in Un)i=Un[s];else if(i=t[s],i==null)throw new q(`Unknown ${n}: ${e}. This may be due to one of the following reasons:
|
|
1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${n} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return i}else{let s=e;if(s.className==null||s.config==null)throw new q(`${n}: Improper config format: ${JSON.stringify(s)}.
|
|
'className' and 'config' must set.`);let i=s.className,o,l;if(i in r?[o,l]=r[i]:i in Un?[o,l]=Un.className:i in t&&([o,l]=t[i]),o==null)throw new q(`Unknown ${n}: ${i}. This may be due to one of the following reasons:
|
|
1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${n} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){let u={};for(let c of Object.keys(Un))u[c]=Un[c];for(let c of Object.keys(r))u[c]=r[c];let d=s.config;d.customObjects=u;let h={...Un};for(let c of Object.keys(r))Un[c]=r[c];Vg(s.config);let p=l(o,s.config,r,a);return Un={...h},p}else{let u={...Un};for(let h of Object.keys(r))Un[h]=r[h];let d=new o(s.config);return Un={...u},d}}}function JL(e,t){return e<t?-1:e>t?1:0}function r0(e,t){return-1*JL(e,t)}function $s(e){if(e==null)return e;let t=[];for(let r of e)t.indexOf(r)===-1&&t.push(r);return t}function QL(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 Pl(e,t,r){if(r!=null&&e.indexOf(r)<0)throw new q(`${r} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function P3(e,t,r=0,n=1/0){return Na(r>=0),Na(n>=r),Array.isArray(e)&&e.length>=r&&e.length<=n&&e.every(a=>typeof a===t)}function gr(e,t){Array.isArray(e)?(v.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((r,n)=>gr(r,`element ${n+1} of ${t}`))):v.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${pw(e)}.`)}function pw(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>pw(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function eB(e,t,r){let n=r!=null?r():v.now(),a;return(...s)=>{let i=r!=null?r():v.now();return i-n<t||(n=i,a=e(...s)),a}}function hw(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}var tB=0;function cw(){return tB++}var n0={};function um(e=""){return e in n0||(n0[e]=0),n0[e]+=1,e+n0[e].toString()}var rB=["channelsFirst","channelsLast"],nB=["nearest","bilinear"],aB=["valid","same","causal"],sB=["max","avg"],iB=["sum","mul","concat","ave"],cu=new Map;function jt(e){Pl(rB,"DataFormat",e)}function oB(e){Pl(nB,"InterpolationFormat",e)}function Bn(e){Pl(aB,"PaddingMode",e)}function fw(e){Pl(sB,"PoolMode",e)}var Wp=[],u4="/";function No(e,t){Wp.push(e);try{let r=t();return Wp.pop(),r}catch(r){throw Wp.pop(),r}}function lB(){return Wp.length===0?"":Wp.join(u4)+u4}function mw(e){if(!yw(e))throw new Error("Not a valid tensor name: '"+e+"'");return lB()+e}function gw(e){if(!yw(e))throw new Error("Not a valid tensor name: '"+e+"'");cu.has(e)||cu.set(e,0);let t=cu.get(e);if(cu.set(e,cu.get(e)+1),t>0){let r=`${e}_${t}`;return cu.set(r,1),r}else return e}var uB=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function yw(e){return!!e.match(uB)}function dB(e){return e===parseInt(e.toString(),10)}function Ms(e,t,r){t==null&&(t=0),r==null&&(r=e.length);let n=1;for(let a=t;a<r;++a)n*=e[a];return n}function Ou(e){if(e.length===0)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let r=0;r<e.length;r++){let n=e[r];n<t&&(t=n)}return t}function Us(e){if(e.length===0)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let r=0;r<e.length;r++){let n=e[r];n>t&&(t=n)}return t}function ya(e,t){if(t<e)throw new q(`end (${t}) < begin (${e}) is forbidden.`);let r=[];for(let n=e;n<t;++n)r.push(n);return r}var xg;function sr(){return xg==null&&(xg=Dn().epsilon()),xg}function Aa(){return"channelsLast"}function dm(e,t){return me(e,t)}function Ph(e,t=-1){let r=e.shape.slice();return t<0&&(t=r.length+t+1),r.splice(t,0,1),U(e,r)}function pB(e,t){return X(()=>{if(e.shape.length!==2)throw new q(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let r=Ph(e,1);return Ug(r,[1,t,1])})}function hB(e){let t=[Ms(e.shape)];return U(e,t)}function cB(e){if(e.rank<=1)throw new q(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);let t=[e.shape[0],Ms(e.shape,1)];return U(e,t)}function Eo(e,t,r){return X(()=>{switch(e.rank){case 1:return Kf(e,t,r);case 2:return I3(e,[t,0],[r,e.shape[1]]);case 3:return _l(e,[t,0,0],[r,e.shape[1],e.shape[2]]);case 4:return Po(e,[t,0,0,0],[r,e.shape[1],e.shape[2],e.shape[3]]);case 5:return _e(e,[t,0,0,0,0],[r,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return _e(e,[t,0,0,0,0,0],[r,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 bg(e,t,r){return X(()=>{switch(e.rank){case 1:return Kf(e,t,r);case 2:return I3(e,[0,t],[e.shape[0],r]);case 3:return _l(e,[0,0,t],[e.shape[0],e.shape[1],r]);case 4:return Po(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],r]);default:throw new q(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function a0(e,t,r,n){return X(()=>{switch(e.rank){case 1:return Kf(e,t,r);case 2:switch(n){case 1:return Eo(e,t,r);case 2:return bg(e,t,r);default:throw new q(`The axis is not within the rank of the tensor ${n}`)}case 3:switch(n){case 1:return Eo(e,t,r);case 2:return _l(e,[0,t,0],[e.shape[0],r,e.shape[2]]);case 3:return bg(e,t,r);default:throw new q(`The axis is not within the rank of the tensor ${n}`)}case 4:switch(n){case 1:return Eo(e,t,r);case 2:return Po(e,[0,t,0,0],[e.shape[0],r,e.shape[2],e.shape[3]]);case 3:return Po(e,[0,0,t,0],[e.shape[0],e.shape[1],r,e.shape[3]]);case 4:return bg(e,t,r);default:throw new q(`The axis is not within the rank of the tensor ${n}`)}default:throw new q(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function O3(e,t=-1){let r;return t<0&&(r=e[0].rank,r!==0?t=r:t=0),t===e[0].rank&&(t=-1),St(e,t)}function d4(e,t){switch(e.rank){case 1:return uv([e,t]);case 2:return bd([e,t],0);case 3:return dv([e,t],0);case 4:return pv([e,t],0);default:throw new q(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Ug(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 jn(e,t)}function pm(e,t=0,r=1,n,a){return Pv(e,t,r,n,a)}function Ma(e,t,r,n){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 a=e.shape.slice(-1)[0],s=t.shape.slice(-2)[0];if(a!==s)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)return Vs.matMul({a:e,b:t,transposeA:!1,transposeB:!1,bias:n?Gg(e.rank,n,Aa()):null,activation:r});{let a=e.shape.slice(),s=a.pop();e=U(e,[-1,s]);let i=t.shape.slice(),o=i.pop(),l=i.pop(),u=[...i,o],d=Array.from({length:t.rank},(m,f)=>f===0?t.rank-2:f<=t.rank-2?f-1:f);t=U(tt(t,d),[l,-1]);let h=[...a,...u],p=!1,c=!1;return U(Vs.matMul({a:e,b:t,transposeA:p,transposeB:c,bias:n?Gg(e.rank,n,Aa()):null,activation:r}),h)}}function Aw(e,t,r){return X(()=>(Array.isArray(t)?t=Nt(t,"int32"):t=me(t,"int32"),Fu(e,t,r)))}function Oh(e){return L(e,e)}function Gg(e,t,r){let n=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(r==="channelsFirst")return n.length===1?U(t,[1,n[0],1,1,1]):U(t,[1,n[3],n[0],n[1],n[2]]);if(r==="channelsLast")return n.length===1?U(t,[1,1,1,1,n[0]]):U(t,[1].concat(n))}else if(e===4){if(r==="channelsFirst")return n.length===1?U(t,[1,n[0],1,1]):U(t,[1,n[2],n[0],n[1]]);if(r==="channelsLast")return n.length===1?U(t,[1,1,1,n[0]]):U(t,[1].concat(n))}else if(e===3){if(r==="channelsFirst")return n.length===1?U(t,[1,n[0],1]):U(t,[1,n[1],n[0]]);if(r==="channelsLast")return n.length===1?U(t,[1,1,n[0]]):U(t,[1].concat(n))}else if(e<3)return t;throw new q(`Unsupported input rank by biasAdd: ${t.rank}`)}function va(e,t,r){return X(()=>(r==null&&(r=Aa()),jt(r),le(e,Gg(e.rank,t,r))))}function fB(e,t=1){if(t!==1)throw new Ve(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Eh(e)}function mB(e){return X(()=>pe(e,le(ar(e),1)))}function xw(e,t,r,n){return X(()=>Kv(e,t,r,n))}function gB(e){return X(()=>{let t=le(.5,L(.2,e));return fn(t,0,1)})}function zh(e,t,r=!1){return r?e():t()}var yB=["fanIn","fanOut","fanAvg"],AB=["normal","uniform","truncatedNormal"];function xB(e){Pl(yB,"FanMode",e)}function bB(e){Pl(AB,"Distribution",e)}var Zn=class extends ue.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},z3=class extends Zn{apply(e,t){return Ot(e,t)}};z3.className="Zeros";ue.registerClass(z3);var hm=class extends Zn{apply(e,t){return cn(e,t)}};hm.className="Ones";ue.registerClass(hm);var D3=class extends Zn{constructor(e){if(super(),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 X(()=>L(Se(this.value),cn(e,t)))}getConfig(){return{value:this.value}}};D3.className="Constant";ue.registerClass(D3);var L3=class extends Zn{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 Id(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};L3.className="RandomUniform";ue.registerClass(L3);var B3=class extends Zn{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 pm(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};B3.className="RandomNormal";ue.registerClass(B3);var W3=class extends Zn{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 Jf(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};W3.className="TruncatedNormal";ue.registerClass(W3);var V3=class extends Zn{constructor(e){super(),this.gain=e.gain!=null?e.gain:1}apply(e,t){return X(()=>{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,u3(e[0]))})}getConfig(){return{gain:this.gain}}};V3.className="Identity";ue.registerClass(V3);function vB(e,t="channelsLast"){let r,n;if(jt(t),e.length===2)r=e[0],n=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let a=Ms(e,2);r=e[1]*a,n=e[0]*a}else if(t==="channelsLast"){let a=Ms(e,0,e.length-2);r=e[e.length-2]*a,n=e[e.length-1]*a}}else{let a=Ms(e);r=Math.sqrt(a),n=Math.sqrt(a)}return[r,n]}var sn=class extends Zn{constructor(e){if(super(),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,xB(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,bB(this.distribution),this.seed=e.seed}apply(e,t){let r=vB(e),n=r[0],a=r[1],s=this.scale;if(this.mode==="fanIn"?s/=Math.max(1,n):this.mode==="fanOut"?s/=Math.max(1,a):s/=Math.max(1,(n+a)/2),this.distribution==="normal"){let i=Math.sqrt(s);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Ve(`${this.getClassName()} does not support dType ${t}.`);return Jf(e,0,i,t,this.seed)}else{let i=Math.sqrt(3*s);return Id(e,-i,i,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};sn.className="VarianceScaling";ue.registerClass(sn);var cm=class extends sn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return sn.className}};cm.className="GlorotUniform";ue.registerClass(cm);var fm=class extends sn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return sn.className}};fm.className="GlorotNormal";ue.registerClass(fm);var mm=class extends sn{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return sn.className}};mm.className="HeNormal";ue.registerClass(mm);var gm=class extends sn{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return sn.className}};gm.className="HeUniform";ue.registerClass(gm);var ym=class extends sn{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return sn.className}};ym.className="LeCunNormal";ue.registerClass(ym);var Am=class extends sn{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return sn.className}};Am.className="LeCunNormal";ue.registerClass(Am);var U3=class extends Zn{constructor(e){if(super(),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 X(()=>{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 r=e[0]>e[1]?[e[1],e[0]]:e,n=pm(r,0,1,"float32"),a=sw.gramSchmidt(n);return e[0]>e[1]&&(a=tt(a)),L(this.gain,a)})}getConfig(){return{gain:this.gain,seed:this.seed}}};U3.className="Orthogonal";ue.registerClass(U3);var p4={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 h4(e,t={}){return _h(e,ue.SerializationMap.getMap().classNameMap,t,"initializer")}function zt(e){return _3(e)}function $t(e){if(typeof e=="string"){let t=e in p4?p4[e]:e;if(t==="GlorotNormal")return new fm;if(t==="GlorotUniform")return new cm;if(t==="HeNormal")return new mm;if(t==="HeUniform")return new gm;if(t==="LeCunNormal")return new ym;if(t==="LeCunUniform")return new Am;{let r={};return r.className=t,r.config={},h4(r)}}else return e instanceof Zn?e:h4(e)}function jg(e){return Array.isArray(e)&&Array.isArray(e[0])}function z0(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function je(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 mt(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 D0(e){let t=0;for(let r of e)r.shape.length===0?t+=1:t+=r.shape.reduce((n,a)=>n*a);return t}var c4="Variable",bw=class{constructor(e,t="float32",r=c4,n=!0,a=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=cw(),r=r==null?c4:r,this.originalName=mw(r),this.name=gw(this.originalName),this.trainable_=n,this.constraint=a,this.val=jv(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),wB(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 wB(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function Hg(e){return e.map(t=>t.read())}function G3(e){e.forEach(t=>{t[0].write(t[1])})}var Zt=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||{}}},pa=class{constructor(e,t,r,n,a,s,i){this.dtype=e,this.shape=t,this.sourceLayer=r,this.inputs=n,this.callArgs=a,this.outputTensorIndex=i,this.id=cw(),s!=null&&(this.originalName=mw(s),this.name=gw(this.originalName)),this.rank=t.length}},kB=0,xm=class{constructor(e,t){this.callArgs=t,this.id=kB++,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 r of e.inboundLayers)r!=null&&r.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}}},IB=0,st=class extends ue.Serializable{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=IB++,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 r=this.getClassName();t=Ha(r)+"_"+um(r)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let r;if(e.batchInputShape!=null)r=e.batchInputShape;else if(e.inputShape!=null){let a=null;e.batchSize!=null&&(a=e.batchSize),r=[a].concat(e.inputShape)}this.batchInputShape=r;let n=e.dtype;n==null&&(n=e.inputDType),n==null&&(n="float32"),this.dtype=n}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 da(`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 rn(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return rn(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new ja(`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 ja(`Layer ${this.name} is not connected, no input to return.`);return rn(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new ja(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new ja(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return rn(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=Tt(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=Tt(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 r=0;r<e.length;r++){let n=e[r],a=t[r];if(a==null)continue;let s=n.rank;if(a.ndim!=null&&s!==a.ndim)throw new q(`Input ${r} is incompatible with layer ${this.name}: expected ndim=${a.ndim}, found ndim=${s}`);if(a.maxNDim!=null&&s>a.maxNDim)throw new q(`Input ${r} is incompatible with layer ${this.name}: expected max_ndim=${a.maxNDim}, found ndim=${s}`);if(a.minNDim!=null&&s<a.minNDim)throw new q(`Input ${r} is incompatible with layer ${this.name}: expected min_ndim=${a.minNDim}, found ndim=${s}.`);if(a.dtype!=null&&n.dtype!==a.dtype)throw new q(`Input ${r} is incompatible with layer ${this.name} : expected dtype=${a.dtype}, found dtype=${n.dtype}.`);if(a.axes){let i=n.shape;for(let o in a.axes){let l=Number(o),u=a.axes[o],d=l>=0?i[l]:i[i.length+l];if(u!=null&&[u,null].indexOf(d)===-1)throw new q(`Input ${r} is incompatible with layer ${this.name}: expected axis ${l} of input shape to have value ${u} but got shape ${i}.`)}}if(a.shape!=null)for(let i=0;i<a.shape.length;++i){let o=a.shape[i],l=n.shape[i];if(o!=null&&l!=null&&o!==l)throw new q(`Input ${r} is incompatible with layer ${this.name}: expected shape=${a.shape}, found shape=${n.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 r=Tt(e),n=!0;for(let s of r)if(!(s instanceof pa)){n=!1;break}let a=!0;for(let s of r)if(s instanceof pa){a=!1;break}if(n===a)throw new q("Arguments to apply() must be all SymbolicTensors or all Tensors");return No(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);let s=[];for(let i of Tt(e))s.push(i.shape);this.build(rn(s)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&a&&(this._refCount=1)}if(this.assertInputCompatibility(e),a){let s=this.call(e,t),i=Tt(s),o=[];for(let l of i)r.indexOf(l)!==-1&&(l=l.clone()),o.push(l);if(s=rn(o),this.activityRegularizer!=null)throw new Ve("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}else{let s=SB(e),i=this.computeOutputShape(s),o,l=CB(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?s[0]:s),i!=null&&i.length>0&&Array.isArray(i[0])?o=i.map((u,d)=>new pa(l,u,this,Tt(e),t,this.name,d)):o=new pa(l,i,this,Tt(e),t,this.name),this.addInboundNode(e,o,null,null,s,i,t),this._refCount++,this.activityRegularizer!=null)throw new Ve("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return o}})}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((r,n)=>{r!=null&&e[n]!=null&&e[n]!==r&&(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 ja(`The layer ${this.name} has never been called and thus has no defined output shape.`);let e=[];for(let t of this.inboundNodes){let r=JSON.stringify(t.outputShapes);e.indexOf(r)===-1&&e.push(r)}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 ja(`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 da(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return D0(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Hg(e?this.trainableWeights:this.weights)}setWeights(e){X(()=>{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 r=[],n=Hg(t);for(let a=0;a<n.length;++a){let s=n[a],i=t[a],o=e[a];if(!v.arraysEqual(s.shape,o.shape))throw new q(`Layer weight shape ${s.shape} not compatible with provided weight shape ${o.shape}`);r.push([i,o])}G3(r)})}addWeight(e,t,r,n,a,s,i,o){if(this._addedWeightNames.indexOf(e)!==-1)throw new q(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),r==null&&(r="float32"),this.fastWeightInitDuringBuild&&(n=o!=null?o():$t("zeros"));let l=n.apply(t,r),u=new bw(l,r,e,s,i);return l.dispose(),a!=null&&this.addLoss(()=>a.apply(u.read())),s==null&&(s=!0),s?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=Tt(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(r=>{if(r!=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,r,n,a,s,i=null){let o=Tt(e);t=Tt(t),r=Tt(r),n=Tt(n),a=z0(a),s=z0(s);let l=[],u=[],d=[];for(let h of o)l.push(h.sourceLayer),u.push(h.nodeIndex),d.push(h.tensorIndex);new xm({outboundLayer:this,inboundLayers:l,nodeIndices:u,tensorIndices:d,inputTensors:o,outputTensors:t,inputMasks:r,outputMasks:n,inputShapes:a,outputShapes:s},i);for(let h=0;h<t.length;h++)t[h].sourceLayer=this,t[h].nodeIndex=this.inboundNodes.length-1,t[h].tensorIndex=h}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 SB(e){e=Tt(e);let t=[];for(let r of e)t.push(r.shape);return rn(t)}function CB(e){return"float32"}function vw(e,t,r){if((t==null||r!=null&&r>0)&&(t=e.sourceLayer,r=e.nodeIndex),t.inboundNodes.length===0)return[e];{let n=t.inboundNodes[r];if(n.inboundLayers.length===0)return n.inputTensors;{let a=[];for(let s=0;s<n.inboundLayers.length;s++){let i=n.inputTensors[s],o=n.inboundLayers[s],l=n.nodeIndices[s],u=vw(i,o,l);for(let d of u)a.indexOf(d)===-1&&a.push(d)}return a}}}var Td=class extends st{constructor(e){if(super({dtype:e.dtype,name:e.name!=null?e.name:um("input").toString()}),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 r=e.dtype||"float32";this.batchInputShape=t,this.dtype=r,this.inputSpec=[{shape:t}];let n=new pa(this.dtype,this.batchInputShape,this,[],{},this.name);n.nodeIndex=0,n.tensorIndex=0,new xm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[n],outputTensors:[n],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}}};Td.className="InputLayer";ue.registerClass(Td);function ww(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 r=e.dtype;return r==null&&(r="float32"),new Td({batchInputShape:t,name:e.name,dtype:r,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}function TB(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return me(t,e.dtype)}catch(r){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 So=class{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof So)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,r){if(this.id2Value[e.id]==null)this.id2Value[e.id]=TB(e,t),this.name2Id[e.name]=e.id,r!=null&&(this.id2Mask[e.id]=r);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 pa){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 pa){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&&ee(this.id2Mask)}},L0=new dw,B0=new dw;function NB(e){L0!=null&&L0.setMaxEntries(e),B0!=null&&B0.setMaxEntries(e)}function Mp(e,t,r,n){let a=r==null?!1:r.training,s=Array.isArray(e),i=s?e:[e],o=i.map(m=>m.name),l=[],u=t.names();for(let m of o)u.indexOf(m)!==-1?l.push(t.getValue(m)):l.push(null);n!=null&&(n.maxNumTensors=-1/0,n.minNumTensors=1/0);let d=o.join(",")+"|"+t.names().sort().join(","),h=L0.get(d),p;if(h==null){let m=EB(i,t);h=m.sorted,p=m.recipientCounts,L0.put(d,h),B0.put(d,p)}p={},a||Object.assign(p,B0.get(d));let c=new So(t);for(let m=0;m<h.length;++m){if(n!=null){let R=F0().numTensors;R>n.maxNumTensors&&(n.maxNumTensors=R),R<n.minNumTensors&&(n.minNumTensors=R)}let f=h[m],g=f.sourceLayer;if(g instanceof Td)continue;let y=[],A=[],x=[],b=!1;for(let R of f.inputs){let F=c.getValue(R),$=c.getMask(R);y.push(F),A.push($),$!=null&&(b=!0),a||(p[R.name]--,p[R.name]===0&&!t.hasKey(R)&&o.indexOf(R.name)===-1&&!F.isDisposed&&R.sourceLayer.stateful!==!0&&x.push(F))}b&&(r=r||{},r.mask=A[0]);let w=Tt(g.apply(y,r)),I=null;g.supportsMasking&&(I=g.computeMask(y,A));let T=$B(f),E=Array.isArray(T)?T:[T];for(let R=0;R<E.length;++R){c.hasKey(E[R])||c.add(E[R],w[R],Array.isArray(I)?I[0]:I);let F=o.indexOf(E[R].name);F!==-1&&(l[F]=w[R])}a||ee(x)}return c.disposeMasks(),s?l:l[0]}function EB(e,t){v.assert(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let r=[],n={};if(e.length===1){let a=f4(e[0],t);r=a.sorted,n=a.recipientMap}else{let a=new Set;for(let s of e){let{sorted:i,recipientMap:o}=f4(s,t);for(let l of i)a.has(l.name)||(r.push(l),a.add(l.name));for(let l in o)n[l]==null&&(n[l]=new Set),o[l].forEach(u=>n[l].add(u))}}return{sorted:r,recipientCounts:RB(n)}}function RB(e){let t={};for(let r in e)t[r]=e[r].size;return t}function f4(e,t){let r=new Set,n=[],a={};for(let o of t.names())r.add(o);let s=[],i=[];for(s.push(e);s.length>0;){let o=s[s.length-1];if(r.has(o.name)){s.pop();continue}let l=i[i.length-1]===s.length-1;if(o.inputs.length===0||l)s.pop(),n.push(o),r.add(o.name),l&&i.pop();else{i.push(s.length-1);for(let u of o.inputs)a[u.name]==null&&(a[u.name]=new Set),a[u.name].add(o.name),!r.has(u.name)&&s.push(u)}}return{sorted:n,recipientMap:a}}function $B(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let r=null;for(let n=0;n<e.sourceLayer.inboundNodes.length;++n)for(let a of e.sourceLayer.inboundNodes[n].outputTensors)if(a.id===e.id){r=n;break}t=e.sourceLayer.getOutputAt(r)}return t}var MB=Z();MB.registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES",()=>100,NB);var kw={kernelName:Go,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,Mh(me(r,"float32"),-1))}}},FB={kernelName:Hu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>{let n=bt(me(r,"float32")),a=Er(ce(Se(1),n));return Mt(pe(e,a))}}}},_B={kernelName:qu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>{let n=Er(ce(bt(me(r,"float32")),1));return pe(e,n)}}}},PB={kernelName:Qa,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=At(r.shape,n.shape);return{a:()=>{let s=e,i=Jt(r.shape,a);return i.length>0&&(s=ke(s,i)),U(s,r.shape)},b:()=>{let s=e,i=Jt(n.shape,a);return i.length>0&&(s=ke(s,i)),U(s,n.shape)}}}},OB={kernelName:Zs,saveAllInputs:!0,gradFunc:(e,t)=>{let r={};return t.forEach((n,a)=>{r[a]=()=>e.clone()}),r}},zB={kernelName:Ys,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>at(r)}}},DB={kernelName:Zu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>at(r)}}},LB={kernelName:Yu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,Er(ce(Se(1),bt(me(r,"float32")))))}}},BB={kernelName:Ju,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>{let n=Er(le(Se(1),bt(me(r,"float32"))));return pe(e,n)}}}},WB={kernelName:td,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=At(r.shape,n.shape);return{a:()=>{let s=le(bt(r),bt(n)),i=L(e,pe(n,s)),o=Jt(r.shape,a);return o.length>0&&(i=ke(i,o)),U(i,r.shape)},b:()=>{let s=le(bt(r),bt(n)),i=Mt(L(e,pe(r,s))),o=Jt(n.shape,a);return o.length>0&&(i=ke(i,o)),U(i,n.shape)}}}},VB={kernelName:Qu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,le(bt(me(r,"float32")),1))}}},UB={kernelName:ed,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,ce(Se(1),bt(me(r,"float32"))))}}};function GB(e,t,r,n,a,s){let i=M(e,"dy","avgPool3dGrad"),o=M(t,"input","avgPool3dGrad"),l=i,u=o,d=!1;o.rank===4&&(d=!0,l=U(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),u=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),P(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),P(u.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),qr("avgPool3dGrad",a,s);let h={dy:l,input:u},p={filterSize:r,strides:n,pad:a,dimRoundingMode:s},c=B.runKernel(df,h,p);return d?U(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var jB=W({avgPool3dGrad_:GB}),HB={kernelName:ah,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{filterSize:a,strides:s,pad:i,dimRoundingMode:o}=r;return{x:()=>jB(e,n,a,s,i,o)}}};function qB(e,t,r,n,a){let s=M(e,"dy","avgPoolGrad"),i=M(t,"input","avgPoolGrad");P(i.rank===s.rank,()=>`Rank of input (${i.rank}) does not match rank of dy (${s.rank})`);let o=i,l=s,u=!1;i.rank===3&&(u=!0,o=U(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=U(s,[1,s.shape[0],s.shape[1],s.shape[2]])),P(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),P(o.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`);let d={dy:l,input:o},h={filterSize:r,strides:n,pad:a},p=B.runKernel(uf,d,h);return u?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var XB=W({avgPoolGrad_:qB}),KB={kernelName:Js,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{filterSize:a,strides:s,pad:i}=r;return{x:()=>XB(e,n,a,s,i)}}},ZB={kernelName:Qs,inputsToSave:["a","b"],gradFunc:(e,t,r)=>{let[n,a]=t,{transposeA:s,transposeB:i}=r;return!s&&!i?{a:()=>Ye(e,a,!1,!0),b:()=>Ye(n,e,!0,!1)}:!s&&i?{a:()=>Ye(e,a,!1,!1),b:()=>Ye(e,n,!0,!1)}:s&&!i?{a:()=>Ye(a,e,!1,!0),b:()=>Ye(n,e,!1,!1)}:{a:()=>Ye(a,e,!0,!0),b:()=>Ye(e,n,!0,!0)}}},YB={kernelName:jo,gradFunc:(e,t,r)=>{let{blockShape:n,crops:a}=r;return{x:()=>qf(e,n,a)}}},JB={kernelName:K7,gradFunc:(e,t,r)=>{let n=r,a=n.inputShape,s=n.shape,i=Array.from(s);for(let l=a.length-1;l>=0;l--)if(a[l]===s[l])i[l]=1;else if(a[l]!==1)throw new Error(`broadcastTo(): [${a}] cannot be broadcast to [${s}].`);let o=[];for(let l=0;l<i.length;l++)i[l]>1&&o.push(l);return{x:()=>ke(e,o,!0)}}},QB={kernelName:ei,gradFunc:e=>({x:()=>e.clone()})},eW={kernelName:ti,gradFunc:e=>({x:()=>at(e)})},tW={kernelName:es,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{clipValueMin:a,clipValueMax:s}=r;return{x:()=>Ur(ga(Ml(n,a),Fl(n,s)),e,at(e))}}},rW={kernelName:ih,inputsToSave:["x"],gradFunc:kw.gradFunc},nW={kernelName:Ho,saveAllInputs:!0,gradFunc:(e,t,r)=>{let n=t.map(o=>o.shape),{axis:a}=r,s=Hn(a,t[0].shape)[0],i=n.map(o=>o[s]);return Yt(e,i,s).map(o=>()=>o)}},aW={kernelName:ri,inputsToSave:["x","filter"],gradFunc:(e,t,r)=>{let[n,a]=t,{dilations:s,strides:i,pad:o,dataFormat:l}=r;return P(Ds(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>r3(n.shape,e,a,i,o,l),filter:()=>R3(n,e,a.shape,i,o,l)}}},sW={kernelName:ni,inputsToSave:["dy","filter"],gradFunc:(e,t,r)=>{let[n,a]=t,{strides:s,pad:i,dataFormat:o,dimRoundingMode:l}=r;return{dy:()=>Ls(e,a,s,i,o,1,l),filter:()=>R3(e,n,a.shape,s,i,o,l)}}};function iW(e,t,r,n,a){let s=e;e.rank===4&&(s=U(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;i.rank===4&&(i=U(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),P(s.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`),P(i.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`),P(r.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${r}.`),P(s.shape[4]===r[3],()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${r[3]}.`),P(i.shape[4]===r[4],()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${r[4]}).`);let o={x:s,dy:i},l={strides:n,pad:a,filterShape:r};return B.runKernel(ff,o,l)}var oW=W({conv3DBackpropFilter_:iW}),lW={kernelName:oh,inputsToSave:["x","filter"],gradFunc:(e,t,r)=>{let{dilations:n,strides:a,pad:s}=r;P(Ds(n),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${n}'`);let[i,o]=t;return{x:()=>hv(i.shape,e,o,a,s),filter:()=>oW(i,e,o.shape,a,s)}}},uW={kernelName:ai,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(Mt(w3(me(r,"float32"))),e)}}},dW={kernelName:si,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(k3(me(r,"float32")),e)}}},pW={kernelName:ii,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{axis:a,exclusive:s,reverse:i}=r;return{x:()=>{let o=wv([a],n.rank),l=i3(e,a,s,!i);return o!=null&&(l=tt(l,o)),l}}}},hW={kernelName:oi,inputsToSave:["x","filter"],gradFunc:(e,t,r)=>{let{dilations:n,strides:a,pad:s,dimRoundingMode:i}=r,o=n==null?[1,1]:n;P(Ds(o),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);let[l,u]=t;return P(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),P(u.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`),P(l.shape[3]===u.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),P(za(a,o),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${o}'.`),qr("depthwiseConv2d",s,i),{x:()=>Jv(l.shape,e,u,a,s,o,i),filter:()=>Yv(l,e,u.shape,a,s,o,i)}}},cW={kernelName:lh,inputsToSave:["x","filter"],gradFunc:(e,t,r)=>{let[n,a]=t,s={x:n,filter:a,dy:e},i={x:n,filter:a,dy:e};return{x:()=>B.runKernel(T0,s,r),filter:()=>B.runKernel(N0,i,r)}}},fW={kernelName:ui,outputsToSave:[!0],gradFunc:(e,t)=>{let[r]=t,n={dy:e,y:r};return{x:()=>B.runKernel(bf,n)}}},mW={kernelName:rd,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t,n=L(Fn(Mt(bt(r))),2/Math.sqrt(Math.PI));return{x:()=>L(e,n)}}},gW={kernelName:di,outputsToSave:[!0],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,r)}}},yW={kernelName:Yo,inputsToSave:["input"],gradFunc:(e,t)=>{let[r]=t;return{input:()=>U(e,r.shape)}}},AW={kernelName:Jo,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,Fn(r))}}},xW={kernelName:pi,gradFunc:e=>({x:()=>at(e)})},bW={kernelName:hi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=At(r.shape,n.shape);return{a:()=>{let s=pe(e,me(n,"float32")),i=Jt(r.shape,a);return i.length>0?U(ke(s,i),r.shape):s},b:()=>{let s=L(e,me(r,"float32")),i=Jt(n.shape,a);i.length>0&&(s=U(ke(s,i),n.shape));let o=bt(n);return Mt(pe(s,me(o,"float32")))}}}},vW={kernelName:ci,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,r)=>{let{varianceEpsilon:n}=r,[a,s,i,o]=t,l=o==null?Se(1):o,u=Jt(s.shape,a.shape),d=[];if(s.rank===1){for(let f=0;f<a.shape.length-1;++f)d.push(a.shape[f]);d.push(1)}let h=ce(a,s),p=L(e,l),c=b3(le(i,Se(n))),m=L(L(L(c,c),c),Se(-.5));return{x:()=>s.rank===1?U(L(L(e,jn(U(c,[1,1,1,s.shape[0]]),d)),l),a.shape):U(L(L(e,c),l),a.shape),mean:()=>{let f=L(L(c,Se(-1)),p);return s.rank===1&&(f=ke(f,u)),U(f,s.shape)},variance:()=>{let f=L(L(m,h),p);return s.rank===1&&(f=ke(f,u)),U(f,s.shape)},scale:()=>{let f=L(h,c),g=L(e,f);return s.rank===1&&(g=ke(g,u)),U(g,s.shape)},offset:()=>{let f=e;return s.rank===1&&(f=ke(f,u)),U(f,s.shape)}}}},wW={kernelName:el,inputsToSave:["x","indices"],gradFunc:(e,t,r)=>{let[n,a]=t,{axis:s}=r,i=Hn(s,n.shape)[0];return{x:()=>{let o=n.shape,l=a.size,u=o.slice(0,i),d=u.length,h=o.slice(s,o.length).slice(1),p=h.length,c=m4(0,d),m=m4(d+1,d+1+p),f=g4([u,[l],h]),g=U(e,f),y=U(a,[l]),A=g4([[d],c,m]),x=tt(g,A),b=Uv(x,y,n.shape[i]),w=l3(A);return b=tt(b,w),b},indices:()=>a}}};function m4(e,t){let r=[];for(let n=e;n<t;++n)r.push(n);return r}function g4(e){let t=[];for(let r=0;r<e.length;++r)for(let n=0;n<e[r].length;++n)t.push(e[r][n]);return t}var kW={kernelName:fi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t;return{a:()=>at(r),b:()=>at(n)}}},IW={kernelName:mi,gradFunc:e=>({x:()=>me(e,"float32")})},SW={kernelName:ad,gradFunc:e=>({x:()=>at(e)})},CW={kernelName:sd,gradFunc:e=>({x:()=>at(e)})},TW={kernelName:id,gradFunc:e=>({x:()=>at(e)})},NW={kernelName:gi,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{alpha:a}=r,s=gn(n,0);return{x:()=>Ur(s,e,L(e,a))}}},EW={kernelName:od,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,le(r,1))}}},RW={kernelName:yi,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,me(r,"float32"))}}},$W={kernelName:Y7,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,r)=>{let[n]=t,{axis:a}=r;return{logits:()=>{let s=Fn(n);return ce(e,L(ke(e,a,!0),s))}}}};function MW(e,t,r,n=5,a=1,s=1,i=.5){let o={x:e,y:t,dy:r},l={depthRadius:n,bias:a,alpha:s,beta:i};return B.runKernel(If,o,l)}var FW=W({localResponseNormalizationBackprop_:MW}),_W={kernelName:ph,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let[n,a]=t,{depthRadius:s,bias:i,alpha:o,beta:l}=r;return{x:()=>FW(n,a,e,s,i,o,l)}}};function Iw(e,t,r,n){return t.rank<r.rank&&(t=U(t,_o(t.shape,n))),e.rank<r.rank&&(e=U(e,_o(e.shape,n))),{x:()=>L(e,me(Mn(r,t),e.dtype))}}var y4={kernelName:Ai,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let n=r,{reductionIndices:a}=n,s=t[0],i=t[1],o=Hn(a,s.shape),l=Iw(e,i,s,o);return{x:()=>l.x()}}},PW={kernelName:xi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t;return{a:()=>L(e,me(Ml(r,n),"float32")),b:()=>L(e,me(d3(r,n),"float32"))}}};function OW(e,t,r,n,a,s,i){let o=M(e,"dy","maxPool3dGrad"),l=M(t,"input","maxPool3dGrad"),u=M(r,"output","maxPool3dGrad"),d=o,h=l,p=u,c=!1;l.rank===4&&(c=!0,d=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),h=U(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),p=U(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),P(d.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${d.rank}.`),P(h.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${h.rank}.`),P(p.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${p.rank}.`),qr("maxPool3dGrad",s,i);let m={dy:d,input:h,output:p},f={filterSize:n,strides:a,pad:s,dimRoundingMode:i},g=B.runKernel(Cf,m,f);return c?U(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var zW=W({maxPool3dGrad_:OW}),DW={kernelName:hh,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let[n,a]=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=r;return{x:()=>zW(e,n,a,s,i,o,l)}}};function LW(e,t,r,n,a,s,i){let o=M(e,"dy","maxPoolGrad"),l=M(t,"input","maxPoolGrad"),u=M(r,"output","maxPoolGrad");P(l.rank===o.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`),P(o.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`),P(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),qr("maxPoolGrad",s,i);let d={dy:o,input:l,output:u},h={filterSize:n,strides:a,pad:s,dimRoundingMode:i};return B.runKernel(Sf,d,h)}var BW=W({maxPoolGrad_:LW}),WW={kernelName:bi,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let[n,a]=t,{filterSize:s,strides:i,pad:o}=r;return{x:()=>BW(e,n,a,s,i,o)}}},VW={kernelName:vi,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{axis:a}=r,s=Hn(a,n.shape),i=vv(n.shape,s)[1],o=It(i);return{x:()=>{let l=n.shape.slice();s.forEach(d=>{l[d]=1});let u=U(e,l);return pe(L(u,cn(n.shape,"float32")),o)}}}},UW={kernelName:wi,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let n=r,{axis:a}=n,[s,i]=t,o=Hn(a,s.shape),l=Iw(e,i,s,o);return{x:()=>l.x()}}},GW={kernelName:ki,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t;return{a:()=>L(e,me(Fl(r,n),"float32")),b:()=>L(e,me(gn(r,n),"float32"))}}},jW={kernelName:Ii,inputsToSave:["x"],gradFunc:(e,t,r)=>{let n=t[0],{paddings:a}=r,s=a.map(i=>i[0]);return{x:()=>_e(e,s,n.shape)}}},HW={kernelName:ud,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=At(r.shape,n.shape);return{a:()=>{let s=Jt(r.shape,a);return s.length>0?U(ke(e,s),r.shape):e},b:()=>{let s=L(e,Mt(Rh(pe(r,n)))),i=Jt(n.shape,a);return i.length>0?U(ke(s,i),n.shape):s}}}},qW={kernelName:Si,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=At(r.shape,n.shape);return{a:()=>{let s=L(e,me(n,"float32")),i=Jt(r.shape,a);return i.length>0?U(ke(s,i),r.shape):s},b:()=>{let s=L(e,me(r,"float32")),i=Jt(n.shape,a);return i.length>0?U(ke(s,i),n.shape):s}}}},XW={kernelName:ol,gradFunc:e=>({x:()=>Mt(e)})},KW={kernelName:hl,inputsToSave:["indices"],gradFunc:(e,t)=>{let r=t[0];return{indices:()=>Ot(r.shape,"float32")}}},ZW={kernelName:pl,gradFunc:e=>({x:()=>at(e)})},YW={kernelName:cl,saveAllInputs:!0,gradFunc:(e,t,r)=>{let{axis:n}=r;return an(e,n).map(a=>()=>a)}},A4={kernelName:Ci,inputsToSave:["x"],gradFunc:(e,t,r)=>{let n=t[0],{paddings:a}=r,s=a.map(i=>i[0]);return{x:()=>_e(e,s,n.shape)}}},JW={kernelName:Ti,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[r,n,a]=t,s=r,i=n,o=At(s.shape,i.shape);return{a:()=>{let l=me(i,"float32"),u=L(e,L(l,Ws(s,ce(l,Se(1))))),d=Jt(s.shape,o);return d.length>0&&(u=ke(u,d)),U(u,s.shape)},b:()=>{let l=gn(s,0),u=Ur(l,_n(s),at(s)),d=L(e,L(a,u)),h=Jt(i.shape,o);return h.length>0&&(d=ke(d,h)),U(d,i.shape)}}}},QW={kernelName:Ni,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[r,n]=t,a=gn(r,0);return{x:()=>Ur(a,e,L(e,n)),alpha:()=>{let s=Ur(a,at(e),L(e,r)),i=Jt(n.shape,e.shape);return i.length>0&&(s=ke(s,i)),U(s,n.shape)}}}};function eV(e,t,r){let n=e.shape.slice();n[r]=1;let a=U(t,n),s=O0(e,r,!0,!1),i=O0(e,r,!0,!0),o=L(s,i);return L(a,o)}function tV(e,t,r){let n=e.shape.length,a=n-r.length,s=C.getAxesPermutation(r,n),i=e;s!=null&&(i=tt(e,s));let o=i.shape.slice(),l=o.splice(n-r.length,r.length).reduce((h,p)=>h*p,1);o.push(l);let u=i.reshape(o),d=eV(u,t,a);if(d=d.reshape(i.shape),s!=null){let h=C.getUndoAxesPermutation(s);d=tt(d,h)}return d}var rV={kernelName:Ei,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{axis:a}=r,s=[];return a==null?s=n.shape.map((i,o)=>o):typeof a=="number"?s=[a]:s=a,{x:()=>tV(n,e,s)}}},nV={kernelName:li,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=At(r.shape,n.shape);return{a:()=>{let s=pe(e,me(n,"float32")),i=Jt(r.shape,a);return i.length>0?U(ke(s,i),r.shape):s},b:()=>{let s=L(e,me(r,"float32")),i=Jt(n.shape,a);i.length>0&&(s=U(ke(s,i),n.shape));let o=bt(n);return Mt(pe(s,me(o,"float32")))}}}},aV={kernelName:hd,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,Mt(bt(r)))}}},sV={kernelName:Mi,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t,n=L(Fl(r,6),Mh(r));return{x:()=>L(e,me(n,"float32"))}}},iV={kernelName:Ri,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,me(Mh(r),"float32"))}}},oV={kernelName:fl,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>U(e,r.shape)}}},lV={kernelName:$i,inputsToSave:["images"],gradFunc:(e,t,r)=>{let[n]=t,a={dy:e,images:n};return{images:()=>B.runKernel(Rf,a,r)}}},uV={kernelName:cd,inputsToSave:["images"],gradFunc:(e,t,r)=>{let[n]=t,a={dy:e,images:n};return{images:()=>B.runKernel(Ef,a,r)}}},dV={kernelName:ml,gradFunc:(e,t,r)=>{let{dims:n}=r,a=Hn(n,e.shape);return{x:()=>On(e,a)}}},pV={kernelName:gl,gradFunc:e=>({x:()=>at(e)})},hV={kernelName:Fi,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>Mt(pe(e,L(Ws(r,1.5),2)))}}},cV={kernelName:Al,inputsToSave:["condition"],gradFunc:(e,t)=>{let[r]=t;return{condition:()=>me(at(r),"float32"),t:()=>L(e,me(r,e.dtype)),e:()=>L(e,me(Gf(r),e.dtype))}}},fV={kernelName:fd,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>{let n=gn(r,Se(0)),a=Se(iw),s=Se(ow),i=L(e,s),o=L(L(e,a),Fn(me(r,"float32")));return Ur(n,i,o)}}}},mV={kernelName:Pi,outputsToSave:[!0],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,L(r,ce(Se(1),r)))}}},gV={kernelName:md,gradFunc:e=>({x:()=>at(e)})},yV={kernelName:_i,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(Lf(me(r,"float32")),e)}}},AV={kernelName:bl,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(s3(me(r,"float32")),e)}}},xV={kernelName:xl,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{begin:a,size:s}=r,i=n.shape,[o,l]=V6(n,a,s),u=[];for(let d=0;d<e.rank;d++)u.push([o[d],i[d]-o[d]-l[d]]);return{x:()=>Xn(e,u)}}},bV={kernelName:Di,outputsToSave:[!0],gradFunc:(e,t,r)=>{let[n]=t,{dim:a}=r,s=!0,i=L(e,n);return{logits:()=>ce(i,L(ke(i,[a],s),n))}}},vV={kernelName:gd,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,Tr(r))}}},x4={kernelName:vl,gradFunc:(e,t,r)=>{let{blockShape:n,paddings:a}=r;return{x:()=>Df(e,n,a)}}},b4={kernelName:wl,gradFunc:(e,t,r)=>{let{axis:n}=r;return{x:()=>St(e,n)}}},wV={kernelName:Oi,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,L(Er(me(r,"float32")),2))}}},kV={kernelName:Ad,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,L(me(r,"float32"),2))}}},IV={kernelName:Li,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=Se(2);return{a:()=>L(e,L(a,ce(r,n))),b:()=>L(e,L(a,ce(n,r)))}}},SV={kernelName:Vi,gradFunc:e=>({x:()=>at(e)})},CV={kernelName:Bi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=At(r.shape,n.shape);return{a:()=>{let s=e,i=Jt(r.shape,a);return i.length>0&&(s=ke(s,i)),U(s,r.shape)},b:()=>{let s=e,i=Jt(n.shape,a);return i.length>0&&(s=ke(s,i)),U(Mt(s),n.shape)}}}},TV={kernelName:zi,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,a=n.shape.slice(),{axis:s}=r;Hn(s,n.shape).forEach(l=>{a[l]=1});let i=U(e,a),o=L(i,cn(n.shape,"float32"));return{x:()=>o}}},NV={kernelName:Il,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,bt(Lf(r)))}}},EV={kernelName:Wi,outputsToSave:[!0],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(ce(Se(1),bt(r)),e)}}},RV={kernelName:ts,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{reps:a}=r;return{x:()=>{let s=at(n);if(n.rank===1)for(let i=0;i<a[0];++i)s=le(s,_e(e,[i*n.shape[0]],[n.shape[0]]));else if(n.rank===2)for(let i=0;i<a[0];++i)for(let o=0;o<a[1];++o)s=le(s,_e(e,[i*n.shape[0],o*n.shape[1]],[n.shape[0],n.shape[1]]));else if(n.rank===3)for(let i=0;i<a[0];++i)for(let o=0;o<a[1];++o)for(let l=0;l<a[2];++l)s=le(s,_e(e,[i*n.shape[0],o*n.shape[1],l*n.shape[2]],[n.shape[0],n.shape[1],n.shape[2]]));else if(n.rank===4)for(let i=0;i<a[0];++i)for(let o=0;o<a[1];++o)for(let l=0;l<a[2];++l)for(let u=0;u<a[3];++u)s=le(s,_e(e,[i*n.shape[0],o*n.shape[1],l*n.shape[2],u*n.shape[3]],[n.shape[0],n.shape[1],n.shape[2],n.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${n.rank} tensors yet.`);return s}}}},$V={kernelName:$a,gradFunc:(e,t,r)=>{let n=r,{perm:a}=n,s=l3(a);return{x:()=>tt(e,s)}}},MV={kernelName:Tl,gradFunc:(e,t,r)=>{let n=r,{axis:a}=n;return{value:()=>ur(e,a)}}},FV={kernelName:xh,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>_V(e,r)}}};function _V(e,t){let r=rs(t,at(t)),n=Fu(e,r),a=Ml(t,Se(0,"int32")),s=n.rank-a.rank;for(let o=0;o<s;++o)a=Kt(a,o+1);a=ga(a,cn(n.shape,"bool"));let i=at(n);return Ur(a,n,i)}var PV={kernelName:Nl,gradFunc:e=>({x:()=>at(e)})},OV=[kw,FB,_B,PB,OB,zB,DB,LB,BB,WB,VB,UB,HB,KB,ZB,YB,JB,QB,eW,tW,rW,nW,sW,aW,lW,uW,dW,pW,hW,cW,nV,fW,mW,gW,yW,AW,bW,xW,vW,wW,kW,IW,SW,CW,TW,NW,EW,RW,$W,_W,y4,y4,PW,DW,WW,VW,UW,GW,jW,HW,qW,XW,KW,ZW,YW,A4,A4,JW,QW,rV,aV,sV,iV,oV,lV,uV,dV,pV,hV,cV,fV,mV,gV,yV,AV,xV,bV,vV,x4,x4,b4,b4,wV,IV,kV,SV,CV,TV,NV,EV,RV,$V,MV,FV,PV];for(let e of OV)J7(e);var Sw={};Be(Sw,{maxNorm:()=>zV,minMaxNorm:()=>BV,nonNeg:()=>LV,unitNorm:()=>DV});function j3(e,t){return X(()=>Er(ke(L(e,e),t,!0)))}var Dh=class extends ue.Serializable{getConfig(){return{}}},H3=class extends Dh{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 X(()=>{let t=j3(e,this.axis),r=fn(t,0,this.maxValue);return L(e,pe(r,le(sr(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};H3.className="MaxNorm";ue.registerClass(H3);var q3=class extends Dh{constructor(e){super(),this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return X(()=>pe(e,le(sr(),j3(e,this.axis))))}getConfig(){return{axis:this.axis}}};q3.className="UnitNorm";ue.registerClass(q3);var X3=class extends Dh{apply(e){return Da(e)}};X3.className="NonNeg";ue.registerClass(X3);var K3=class extends Dh{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 X(()=>{let t=j3(e,this.axis),r=le(L(this.rate,fn(t,this.minValue,this.maxValue)),L(1-this.rate,t));return L(e,pe(r,le(sr(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};K3.className="MinMaxNorm";ue.registerClass(K3);var v4={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function or(e){return _3(e)}function w4(e,t={}){return _h(e,ue.SerializationMap.getMap().classNameMap,t,"constraint")}function lr(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in v4?v4[e]:e,config:{}};return w4(t)}else return e instanceof Dh?e:w4(e)}function zV(e){return new H3(e)}function DV(e){return new q3(e)}function LV(){return new X3}function BV(e){return new K3(e)}var Cw={};Be(Cw,{constant:()=>UV,glorotNormal:()=>ZV,glorotUniform:()=>KV,heNormal:()=>YV,heUniform:()=>JV,identity:()=>qV,leCunNormal:()=>QV,leCunUniform:()=>eU,ones:()=>VV,orthogonal:()=>tU,randomNormal:()=>jV,randomUniform:()=>GV,truncatedNormal:()=>HV,varianceScaling:()=>XV,zeros:()=>WV});function WV(){return new z3}function VV(){return new hm}function UV(e){return new D3(e)}function GV(e){return new L3(e)}function jV(e){return new B3(e)}function HV(e){return new W3(e)}function qV(e){return new V3(e)}function XV(e){return new sn(e)}function KV(e){return new cm(e)}function ZV(e){return new fm(e)}function YV(e){return new mm(e)}function JV(e){return new gm(e)}function QV(e){return new ym(e)}function eU(e){return new Am(e)}function tU(e){return new U3(e)}var Tw={};Be(Tw,{Layer:()=>st,RNN:()=>ss,RNNCell:()=>Wh,activation:()=>CG,add:()=>PG,alphaDropout:()=>Aj,average:()=>OG,averagePooling1d:()=>aA,averagePooling2d:()=>sA,averagePooling3d:()=>iA,avgPool1d:()=>jG,avgPool2d:()=>qG,avgPool3d:()=>KG,avgPooling1d:()=>HG,avgPooling2d:()=>XG,avgPooling3d:()=>ZG,batchNormalization:()=>VG,bidirectional:()=>dj,concatenate:()=>zG,conv1d:()=>yG,conv2d:()=>AG,conv2dTranspose:()=>xG,conv3d:()=>bG,conv3dTranspose:()=>vG,convLstm2d:()=>ij,convLstm2dCell:()=>oj,cropping2D:()=>kG,dense:()=>TG,depthwiseConv2d:()=>SG,dot:()=>WG,dropout:()=>NG,elu:()=>pG,embedding:()=>_G,flatten:()=>RG,gaussianDropout:()=>yj,gaussianNoise:()=>gj,globalAveragePooling1d:()=>YG,globalAveragePooling2d:()=>JG,globalMaxPool1d:()=>hj,globalMaxPool2d:()=>cj,globalMaxPooling1d:()=>w8,globalMaxPooling2d:()=>k8,gru:()=>ej,gruCell:()=>tj,input:()=>jw,inputLayer:()=>dG,layerNormalization:()=>UG,leakyReLU:()=>cG,lstm:()=>rj,lstmCell:()=>nj,masking:()=>xj,maxPool1d:()=>fj,maxPool2d:()=>mj,maxPooling1d:()=>I8,maxPooling2d:()=>S8,maxPooling3d:()=>QG,maximum:()=>DG,minimum:()=>LG,multiply:()=>BG,permute:()=>FG,prelu:()=>fG,reLU:()=>hG,repeatVector:()=>$G,reshape:()=>MG,rnn:()=>lj,separableConv2d:()=>wG,simpleRNN:()=>aj,simpleRNNCell:()=>sj,softmax:()=>mG,spatialDropout1d:()=>EG,stackedRNNCells:()=>uj,thresholdedReLU:()=>gG,timeDistributed:()=>pj,upSampling2d:()=>IG,zeroPadding2d:()=>GG});async function Cs(e){if(e==null)return;let t=[],r=[],n=[];for(let a in e){let s=e[a];if(typeof s!="number"){let i=s;t.push(i.data()),r.push(a),n.push(i)}}if(t.length>0){let a=await Promise.all(t);for(let s=0;s<a.length;++s)e[r[s]]=a[s][0];ee(n)}}function Nw(e){if(e!=null)for(let t in e){let r=e[t];typeof r!="number"&&r.dispose()}}var rU=125,zu=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){}},Ew=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 r of this.callbacks)await r.onEpochBegin(e,t)}async onEpochEnd(e,t){t==null&&(t={});for(let r of this.callbacks)await r.onEpochEnd(e,t)}async onBatchBegin(e,t){t==null&&(t={});for(let r of this.callbacks)await r.onBatchBegin(e,t)}async onBatchEnd(e,t){t==null&&(t={});for(let r of this.callbacks)await r.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)}},nU=class extends zu{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){t==null&&(t={});let r=t.size==null?0:t.size;this.seen+=r;for(let n in t){let a=t[n];if(typeof a=="number")this.totals.hasOwnProperty(n)||(this.totals[n]=0),this.totals[n]=this.totals[n]+a*r;else{let s;n in this.totals?s=this.totals[n]:this.totals[n]=0;let i=X(()=>le(this.totals[n],L(a,r)));this.totals[n]=i,s!=null&&s.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(let r of this.params.metrics)this.totals[r]!=null&&(typeof this.totals[r]=="number"?t[r]=this.totals[r]/this.seen:X(()=>{let n=L(pe(1,this.seen),this.totals[r]);t[r]=n,this.totals[r].dispose(),mr(t[r])}))}},Rw=class extends zu{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(let r in t)this.history[r]==null&&(this.history[r]=[]),this.history[r].push(t[r])}async syncData(){let e=[],t=[],r=[];for(let a in this.history){let s=this.history[a];for(let i=0;i<s.length;++i)if(typeof s[i]!="number"){let o=s[i];e.push(o.data()),t.push(a),r.push(i)}}let n=await Promise.all(e);for(let a=0;a<n.length;++a)this.history[t[a]][r[a]].dispose(),this.history[t[a]][r[a]]=n[a][0]}},$w=class extends zu{constructor(e,t){if(super(),this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||M3,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=rU),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=eB(this.maybeWait.bind(this),this.yieldEvery,this.nowFunc)),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,r){let n=[];this.yield!=null&&(await Cs(r),n.push(this.yield(e,t,r))),n.push(this.nextFrameFunc()),await Promise.all(n)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await Cs(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){let r=[];this.epochEnd!=null&&(await Cs(t),r.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&r.push(this.nextFrameFunc()),await Promise.all(r)}async onBatchBegin(e,t){this.batchBegin!=null&&(await Cs(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){let r=[];this.batchEnd!=null&&(await Cs(t),r.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?r.push(this.nextFrameFunc()):v.isNumber(this.yieldEvery)&&r.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(r)}async onTrainBegin(e){this.trainBegin!=null&&(await Cs(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await Cs(e),await this.trainEnd(e))}};function Mw(e,t){return e==null&&(e={}),e instanceof zu?[e]:Array.isArray(e)&&e[0]instanceof zu?e:Tt(e).map(r=>new $w(r,t))}var Ca=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}`),Ca.checkForDuplicate(t),Ca.constructors[e]==null&&(Ca.constructors[e]=[]),Ca.constructors[e].push(t)}static checkForDuplicate(e){for(let t in Ca.constructors)Ca.constructors[+t].forEach(r=>{if(r===e)throw new q("Duplicate callback constructor.")})}static clear(){Ca.constructors={}}static createCallbacks(e){let t=[];for(let r in Ca.constructors){let n=+r;e>=n&&t.push(...Ca.constructors[n])}return t.map(r=>new r)}},Z3=Ca;Z3.constructors={};function Fw(e,t,r,n,a,s,i,o,l){let u=new Rw,d=[new nU,...Z3.createCallbacks(t)];e!=null&&d.push(...e),d.push(u);let h=new Ew(d);return h.setParams({epochs:r,initialEpoch:n,samples:a,steps:s,batchSize:i,verbose:t,doValidation:o,metrics:l}),{callbackList:h,history:u}}function fa(e,t={},r=!1){return _h(e,ue.SerializationMap.getMap().classNameMap,t,"layer",r)}function W0(e,t){return X(()=>{e.dtype!=="float32"&&(e=me(e,"float32"));let r=ke(Oh(e),t,!0),n=vd(r.shape,sr()),a=Er(rs(r,n));return pe(e,a)})}function Ol(e,t){return X(()=>Vt(Oh(ce(t,e)),-1))}function bm(e,t){return X(()=>Vt(ar(ce(t,e)),-1))}function Nd(e,t){return X(()=>{let r=ce(e,t),n=fn(ar(e),sr(),Number.MAX_VALUE),a=ar(pe(r,n));return L(100,Vt(a,-1))})}function aU(e,t){return X(()=>{let r=fn(t,sr(),Number.MAX_VALUE),n=_n(le(1,r)),a=fn(e,sr(),Number.MAX_VALUE),s=_n(le(1,a));return Vt(Oh(ce(n,s)),-1)})}function sU(e,t){return X(()=>{let r=rs(0,ce(1,L(e,t)));return Vt(Oh(r),-1)})}function iU(e,t){return X(()=>{let r=rs(0,ce(1,L(e,t)));return Vt(r,-1)})}function oU(e,t){return X(()=>{let r=ke(L(e,t),-1),n=yr(L(ce(1,e),t),-1);return rs(0,le(1,ce(n,r)))})}function lU(e,t){return X(()=>{let r=Math.log(2),n=ce(t,e),a=ce(le(n,wd(L(-2,n))),r);return Vt(a,-1)})}function Jp(e,t,r=!1){return X(()=>{if(r)t=Sd(t);else{let n=ke(t,t.shape.length-1,!0);t=pe(t,n)}return t=fn(t,sr(),1-sr()),Mt(ke(L(me(e,"float32"),_n(t)),t.shape.length-1))})}function V0(e,t,r=!1){return X(()=>{let n=me(Rh(hB(e)),"int32");t=fn(t,sr(),1-sr());let a=t.shape,s=U(Zp(n,a[a.length-1]),a);return Jp(s,t,r)})}function uU(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 X(()=>{let r=Da(t),n=Mt(ar(t));return le(ce(r,L(t,e)),Vf(Fn(n)))})}function vm(e,t){return X(()=>{let r;return r=fn(t,sr(),1-sr()),r=_n(pe(r,ce(1,r))),Vt(uU(e,r),-1)})}function dU(e,t){return X(()=>{let r=fn(e,sr(),1),n=fn(t,sr(),1);return ke(L(e,_n(pe(r,n))),-1)})}function pU(e,t){return X(()=>{let r=_n(le(sr(),t));return Vt(ce(t,L(e,r)),-1)})}function Y3(e,t){return X(()=>{let r=W0(e,-1),n=W0(t,-1),a=L(r,n);return Mt(ke(a,-1))})}var U0={meanSquaredError:Ol,meanAbsoluteError:bm,meanAbsolutePercentageError:Nd,meanSquaredLogarithmicError:aU,squaredHinge:sU,hinge:iU,categoricalHinge:oU,logcosh:lU,categoricalCrossentropy:Jp,sparseCategoricalCrossentropy:V0,binaryCrossentropy:vm,kullbackLeiblerDivergence:dU,poisson:pU,cosineProximity:Y3};function vg(e){if(typeof e=="string"){if(e in U0)return U0[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 J3(e,t){return X(()=>{let r=L(.5,Pn(t)),n=dm(gn(t,r),e.dtype);return Vt(Mn(e,n),-1)})}function Q3(e,t){return X(()=>dm(Mn($n(e,-1),$n(t,-1)),"float32"))}function _w(e,t){return X(()=>me(ke(ga(Mn(e,1),Mn(t,1))),"float32"))}function hU(e,t){return X(()=>me(ke(ga(Mn(e,1),Mn(t,0))),"float32"))}function cU(e,t){return X(()=>me(ke(ga(Mn(e,0),Mn(t,1))),"float32"))}function Pw(e,t){return X(()=>{let r=_w(e,t),n=cU(e,t),a=le(r,n);return me(Ur(gn(a,0),pe(r,a),0),"float32")})}function fU(e,t){return X(()=>{let r=_w(e,t),n=hU(e,t),a=le(r,n);return me(Ur(gn(a,0),pe(r,a),0),"float32")})}function Ow(e,t){return vm(e,t)}function zw(e,t){return e.rank===t.rank&&(e=et(e,[e.rank-1])),t=$n(t,-1),t.dtype!==e.dtype&&(t=me(t,e.dtype)),me(Mn(e,t),"float32")}var mU=Ol,gU=Ol,yU=bm,AU=bm,xU=Nd,bU=Nd,e5=Jp,vU=Y3,Dw=V0,G0={binaryAccuracy:J3,categoricalAccuracy:Q3,precision:Pw,categoricalCrossentropy:e5,sparseCategoricalCrossentropy:Dw,mse:mU,MSE:gU,mae:yU,MAE:AU,mape:xU,MAPE:bU,cosine:vU};function wU(e){if(typeof e=="string"&&e in G0)return G0[e];if(typeof e!="string"&&e!=null)return e;throw new q(`Unknown metric ${e}`)}function s0(e){if(Na(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let r of Object.keys(U0))if(U0[r]===e){t=r;break}if(t!==void 0)return t;for(let r of Object.keys(G0))if(G0[r]===e){t=r;break}return t!==void 0?t:e.name}}function kU(e){let t={Adagrad:()=>Ao.adagrad(.01),Adadelta:()=>Ao.adadelta(1,.95,sr()),Adam:()=>Ao.adam(.001,.9,.999,sr()),Adamax:()=>Ao.adamax(.002,.9,.999,sr(),0),RMSProp:()=>Ao.rmsprop(.001,.9,0,sr()),SGD:()=>Ao.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 k4=1*1024*1024;function I4(e,t,r=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!qg(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(r){let n=JSON.stringify(e);n.length>k4&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${n.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${k4}.`)}}function qg(e){if(e===null)return!0;if(typeof e=="object")if(Object.getPrototypeOf(e)===Object.prototype){let t=Object.keys(e);for(let r of t)if(typeof r!="string"||!qg(e[r]))return!1;return!0}else if(Array.isArray(e)){for(let t of e)if(!qg(t))return!1;return!0}else return!1;else{let t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function IU(e,t,r,n=console.log){let a=CU(e),s=["Layer (type)","Input Shape","Output shape","Param #"];a?(t=t||90,r=r||[.32,.61,.89,1]):(t=t||115,r=r||[.24,.48,.7,.8,1]),r[r.length-1]<=1&&(r=r.map(d=>Math.floor(t*d)));let i;if(!a){s.push("Receives inputs"),i=[];for(let d in e.nodesByDepth)i.push(...e.nodesByDepth[d])}n("_".repeat(t)),j0(s,r,n),n("=".repeat(t));let o=e.layers;for(let d=0;d<o.length;++d)a?TU(o[d],r,n):NU(o[d],r,i,n),n((d===o.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();let l=SU(e),u=D0(e.nonTrainableWeights);n(`Total params: ${l+u}`),n(`Trainable params: ${l}`),n(`Non-trainable params: ${u}`),n("_".repeat(t))}function SU(e){let t;return e.collectedTrainableWeights!=null?t=D0(e.collectedTrainableWeights):t=D0(e.trainableWeights),t}function CU(e){let t=!0,r=[],n=[];for(let a in e.nodesByDepth)r.push(e.nodesByDepth[a]);for(let a of r){if(a.length>1||a.length===1&&a[0].inboundLayers.length>1){t=!1;break}n.push(...a)}if(t)for(let a of e.layers){let s=!1;for(let i of a.inboundNodes)if(n.indexOf(i)!==-1)if(s){t=!1;break}else s=!0;if(!t)break}return t}function j0(e,t,r=console.log){let n="";for(let a=0;a<e.length;++a)a>0&&(n=n.slice(0,n.length-1)+" "),n+=e[a],n=n.slice(0,t[a]),n+=" ".repeat(t[a]-n.length);r(n)}function TU(e,t,r){let n,a;try{a=e.inboundNodes.map(l=>JSON.stringify(l.inputShapes)).join(",")}catch(l){a="multiple"}try{n=JSON.stringify(e.outputShape)}catch(l){n="multiple"}let s=e.name,i=e.getClassName(),o=[`${s} (${i})`,a,n,e.countParams().toString()];j0(o,t,r)}function NU(e,t,r,n){let a,s;try{s=e.inboundNodes.map(h=>JSON.stringify(h.inputShapes)).join(",")}catch(h){s="multiple"}try{a=JSON.stringify(e.outputShape)}catch(h){a="multiple"}let i=[];for(let h of e.inboundNodes)if(!(r!=null&&r.length>0&&r.indexOf(h)===-1))for(let p=0;p<h.inboundLayers.length;++p){let c=h.inboundLayers[p].name,m=h.nodeIndices[p],f=h.tensorIndices[p];i.push(`${c}[${m}][${f}]`)}let o=e.name,l=e.getClassName(),u=i.length===0?"":i[0],d=[`${o} (${l})`,s,a,e.countParams().toString(),u];j0(d,t,n);for(let h=1;h<i.length;++h)j0(["","","","",i[h]],t,n)}function Lw(e,t,r){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof r=="string"}function Qp(e,t){if(e===null)return null;if(typeof e=="string")return wo(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let r=[],n=e.length;for(let a=0;a<n;++a){let s=e[a];Lw(t,a,s)?r.push(s):r.push(Qp(s,t))}return r}else{let r={};for(let n of Object.keys(e)){let a=e[n];if(n==="name"&&typeof a=="string")r[n]=a;else{let s=wo(n);r[s]=Qp(a,s)}}return r}}function Xg(e,t){if(e==null)return null;if(typeof e=="string")return Ha(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let r=[],n=e.length;for(let a=0;a<n;++a){let s=e[a];Lw(t,a,s)?r.push(s):r.push(Xg(s,t))}return r}else{let r={};for(let n of Object.keys(e)){let a=e[n],s=Ha(n);(n==="name"||n==="className")&&typeof a=="string"?r[s]=a:r[s]=Xg(a,n)}return r}}var t5="0.0.0",Ta=class extends st{constructor(e){if(super({}),this.containerNodes=new Set,this.name=e.name,this.name==null){let y=this.getClassName().toLowerCase();this.name=um(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],$s(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)}`);$s(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;Na(x===0,"input layer has >1 nodes"),Na(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 Td))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={},r={},n={},a={},s={},i=[],o=(y,A,x,b,w,I)=>{(b==null||w==null||I==null)&&(b=y.sourceLayer,w=y.nodeIndex,I=y.tensorIndex);let T=b.inboundNodes[w];if(x.indexOf(T)!==-1)throw new da(`The tensor ${y.name} at layer "${b.name}" is part of a cycle.`);if(A.indexOf(T)!==-1)return;this.containerNodes.add(Ta.nodeKey(b,w)),b.id in s||(s[b.id]=Object.keys(s).length),x.indexOf(T)===-1&&x.push(T);let E=T.inboundLayers.length;for(let R=0;R<E;R++){let F=T.inputTensors[R],$=T.inboundLayers[R],S=T.nodeIndices[R],z=T.tensorIndices[R];o(F,A,x,$,S,z)}for(A.push(T);x.indexOf(T)>=0;)x.splice(x.indexOf(T),1);i.push(T)},l=[],u=[];for(let y of this.outputs)o(y,l,u);let d=i.slice().reverse();for(let y of d){r[y.id]=y,y.id in t||(t[y.id]=0);let A=t[y.id],x=n[y.outboundLayer.id]==null?0:n[y.outboundLayer.id];A=Math.max(A,x),n[y.outboundLayer.id]=A,a[y.outboundLayer.id]=y.outboundLayer,t[y.id]=A;for(let b=0;b<y.inboundLayers.length;b++){let w=y.inboundLayers[b],I=y.nodeIndices[b],T=w.inboundNodes[I],E=t[T.id]==null?0:t[T.id];t[T.id]=Math.max(A+1,E),r[T.id]=T}}let h={};for(let y in t){let A=t[y];A in h||(h[A]=[]),h[A].push(r[y])}let p={};for(let y in n){let A=n[y];A in p||(p[A]=[]),p[A].push(a[y])}let c=Object.keys(p).map(y=>parseInt(y,10)).sort(r0);this.layers=[];for(let y of c){let A=p[y];A.sort((x,b)=>{let w=s[x.id],I=s[b.id];return w<I?-1:w>I?1:0});for(let x of A)x instanceof Ta&&this.internalContainerRefs.push(x),this.layers.push(x)}this.layersByDepth=p,c=Object.keys(h).map(y=>parseInt(y,10)).sort(r0);let m=this.inputs.slice(),f=[];for(let y of c)for(let A of h[y]){let x=A.outboundLayer;if(x!=null){for(let b of A.inputTensors)if(m.indexOf(b)===-1)throw new da(`Graph disconnected: cannot obtain value for tensor ${b} at layer "${x.name}". The following previous layers were accessed without issue: ${f}`);for(let b of A.outputTensors)m.push(b);f.push(x.name)}}this.nodesByDepth=h;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 da(`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 xm({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(r=>r.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 r of this.layers)t.push(...r.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){let r={},n=0;for(let s of this.layers)for(let i of s.weights){if(r[i.originalName]!=null)throw new q(`Duplicate weight name: ${i.originalName}`);r[i.originalName]=i,n++}let a=[];for(let s in e){let i=s;if(r[s]==null){let o=s.split("/");i=o.slice(0,-2).concat([o[o.length-1]]).join("/")}if(r[i]!=null)a.push([r[i],e[s]]);else if(t)throw new q(`Provided weight data has no target variable: ${s}`);delete r[i]}if(t){let s=[];for(let i in r)s.push(i);if(s.length>0)throw new q(`${s.length} of ${n} weights are not set: ${s}`)}G3(a)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${t5}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let r=Xg(this.updatedConfig());return t?JSON.stringify(r):r}call(e,t){return X(()=>{e=Tt(e);let r=new So;for(let n=0;n<this.inputs.length;++n)r.add(this.inputs[n],e[n]);return Mp(this.outputs,r,t)})}computeMask(e,t){return X(()=>{e=Tt(e);let r;return t==null?r=Oo(null,e.length):r=Tt(t),this.runInternalGraph(e,r)[1]})}computeOutputShape(e){let t=z0(e);if(t.length!==this.inputLayers.length)throw new q(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let r={};for(let i=0;i<t.length;i++){let o=this.inputLayers[i],l=t[i],u=o.name+"_0_0";r[u]=l}let n=Object.keys(this.nodesByDepth).map(i=>parseInt(i,10)).sort(r0);if(n.length>1)for(let i of n){let o=this.nodesByDepth[i];for(let l of o){let u=l.outboundLayer;if(this.inputLayers.map(m=>m.id).indexOf(u.id)!==-1)continue;let d=[];for(let m=0;m<l.inboundLayers.length;m++){let f=l.inboundLayers[m],g=l.nodeIndices[m],y=l.tensorIndices[m],A=`${f.name}_${g}_${y}`,x=r[A];d.push(x)}let h=u.computeOutputShape(rn(d)),p=z0(h),c=u.inboundNodes.indexOf(l);for(let m=0;m<p.length;m++){let f=`${u.name}_${c}_${m}`;r[f]=p[m]}}}let a=[],s=[];for(let i=0;i<this.outputLayers.length;i++){let o=this.outputLayers[i],l=this.outputLayersNodeIndices[i],u=this.outputLayersTensorIndices[i],d=`${o.name}_${l}_${u}`;s.push(d)}for(let i=0;i<s.length;i++){let o=s[i];Na(o in r),a.push(r[o])}return rn(a)}runInternalGraph(e,t){t==null&&(t=Oo(null,e.length));let r={};for(let o=0;o<this.inputs.length;++o){let l=this.inputs[o],u=e[o],d=t[o];r[l.id]=[u,d]}let n=Object.keys(this.nodesByDepth).map(o=>parseInt(o,10)).sort(r0);for(let o of n){let l=this.nodesByDepth[o];for(let u of l){let d=u.outboundLayer,h=u.inputTensors,p=u.outputTensors,c=new Array;for(let m of h)m.id in r&&c.push(r[m.id]);if(c.length===h.length){let m={},f,g,y,A;if(u.callArgs!=null&&(m=u.callArgs),c.length===1){let[x,b]=c[0];m.mask==null&&(m.mask=b),y=Tt(d.call(x,m)),A=Tt(d.computeMask(x,b)),f=[x],g=[b]}else f=c.map(x=>x[0]),g=c.map(x=>x[1]),m.mask==null&&(m.mask=g),y=Tt(d.call(f,m)),A=Tt(d.computeMask(f,g));if(d.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],I=A[x];r[b.id]=[w,I]}}}}let a=[],s=[],i=[];for(let o of this.outputs){Na(o.id in r,`Could not compute output ${o.name} : ${o.id}`);let[l,u]=r[o.id];i.push(l.shape),a.push(l),s.push(u)}return[a,s,i]}buildNodeConversionMap(e){let t={},r;for(let n of this.layers){r=n instanceof Ta?1:0;for(let a=0;a<n.inboundNodes.length;a++){let s=Ta.nodeKey(n,a);this.containerNodes.has(s)&&(t[s]=r,r+=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 r of this.layers)if(r.name===e)return r;throw new q(`No such layer: ${e}`)}calculateLosses(){return X(()=>{let e=[];for(let t of this.layers)for(let r=0;r<t.inboundNodes.length;++r){let n=Ta.nodeKey(t,r);this.containerNodes.has(n)&&e.push(...t.calculateLosses())}return e})}getConfig(){let e={name:this.name},t=this.buildNodeConversionMap(this.layers),r=[];for(let s of this.layers){let i=s.getClassName(),o=s.getConfig(),l=[];for(let d=0;d<s.inboundNodes.length;d++){let h=s.inboundNodes[d],p=Ta.nodeKey(s,d),c={};if(this.containerNodes.has(p)){if(h.callArgs)try{JSON.stringify(h.callArgs),c=h.callArgs}catch(m){console.warn(`Layer ${s.name} was passed non-serializable keyword arguments: ${h.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),c={}}if(h.inboundLayers.length>0){let m=[];for(let f=0;f<h.inboundLayers.length;f++){let g=h.inboundLayers[f],y=h.nodeIndices[f],A=h.tensorIndices[f],x=Ta.nodeKey(g,y),b=t[x];b==null&&(b=0),m.push([g.name,b,A,c])}l.push(m)}}}let u={};u.name=s.name,u.className=i,u.config=o,u.inboundNodes=l,r.push(u)}e.layers=r;let n=[];for(let s=0;s<this.inputLayers.length;s++){let i=this.inputLayers[s],o=this.inputLayersNodeIndices[s],l=Ta.nodeKey(i,o);if(!this.containerNodes.has(l))continue;let u=t[l];u==null&&(u=0);let d=this.inputLayersTensorIndices[s];n.push([i.name,u,d])}e.inputLayers=n;let a=[];for(let s=0;s<this.outputLayers.length;s++){let i=this.outputLayers[s],o=this.outputLayersNodeIndices[s],l=Ta.nodeKey(i,o);if(!this.containerNodes.has(l))continue;let u=t[l];u==null&&(u=0);let d=this.outputLayersTensorIndices[s];a.push([i.name,u,d])}return e.outputLayers=a,e}static fromConfig(e,t,r={},n=!1){let a={},s={};function i(f,g){f.name in s?s[f.name].push(g):s[f.name]=[g]}function o(f,g){let y=[],A;for(let x of g){let b=x[0],w=x[1],I=x[2];if(A=x[3]==null?{}:x[3],!(b in a)){i(f,g);return}let T=a[b];if(T.inboundNodes.length<=w){i(f,g);return}let E=T.inboundNodes[w];y.push(E.outputTensors[I])}y.length>0&&f.apply(rn(y),A)}function l(f){let g=f.name,y=fa(f,t.customObjects!=null?t.customObjects:{});y.setFastWeightInitDuringBuild(n),a[g]=y,f.inboundNodes.forEach(A=>{if(!(A instanceof Array))throw new q(`Corrupted configuration, expected array for nodeData: ${A}`);i(y,A)})}let u=t.name,d=t.layers;for(let f of d)l(f);for(;!QL(s);)for(let f of d){let g=a[f.name];if(g.name in s){let y=s[g.name];delete s[g.name];for(let A of y)o(g,A)}}let h=[],p=[],c=t.inputLayers;for(let f of c){let g=f[0],y=f[1],A=f[2];Na(g in a);let x=a[g].inboundNodes[y].outputTensors;h.push(x[A])}let m=t.outputLayers;for(let f of m){let g=f[0],y=f[1],A=f[2];Na(g in a);let x=a[g].inboundNodes[y].outputTensors;p.push(x[A])}return new e({inputs:h,outputs:p,name:u})}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(){X(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}};function EU(e,t,r){let n=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(a=>null);if(n===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!==n)throw new Error(`Provided ${r} is an array of ${e.length} element(s), but the model has ${n} 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 a=[];return t.forEach(s=>{s in e?a.push(e[s]):a.push(null)}),a}else throw new Error(`The model has multiple (${n}) outputs, so ${r} must be either an array with ${n} elements or an object with ${t} keys. Provided ${r} not understood: ${JSON.stringify(e)}`)}function Bw(e,t){return EU(e,t,"classWeight")}async function Ww(e,t,r,n){if(t!=null||n!=null)throw new Error("Support sampleWeight is not implemented yet");if(r!=null){let a=X(()=>{if(e.shape.length===1)return Vr(e);if(e.shape.length===2){if(e.shape[1]>1)return $n(e,1);if(e.shape[1]===1)return U(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.`)}),s=Array.from(await a.data());ee(a);let i=[];return s.forEach(o=>{if(r[o]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${o} exists in the data but not in classWeight`);i.push(r[o])}),Nt(i,"float32")}else return null}function RU(e,t){return L(e,t)}var $U=32;function Vw(e,t){let r,n,a=t;r=a.xs,n=a.ys,v.assert(r!=null&&n!=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 s=S4("input",e.inputNames,r),i=S4("output",e.outputNames,n),o=s[0].shape[0];v.assert(s.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${s.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`),v.assert(i.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${i.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let l=0;l<s.length;l++)v.assert(s[l].shape[0]===o,()=>`Batch size mismatch: input ${e.inputNames[l]} has ${s[l].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`);for(let l=0;l<i.length;l++)v.assert(i[l].shape[0]===o,()=>`Batch size mismatch: output ${e.outputNames[l]} has ${i[l].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`);return{xs:s,ys:i}}function S4(e,t,r){if(r instanceof nt)return[r];if(Array.isArray(r))return v.assert(r.length===t.length,()=>`Received an array of ${r.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),r;{let n=[];for(let a of t){if(r[a]==null)throw new q(`The feature data generated by the dataset lacks the required ${e} key '${a}'.`);n.push(r[a])}return n}}function MU(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 FU(e,t,r){let n=r.batchesPerEpoch!=null;if(v.assert(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),v.assert(r!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),v.assert(r.epochs!=null&&r.epochs>0&&Number.isInteger(r.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${r.epochs}`),v.assert(!n||r.batchesPerEpoch>0&&Number.isInteger(r.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${r.batchesPerEpoch}`),v.assert(r.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 a=r.validationData!=null,s,i;if(a)if(C4(r.validationData))v.assert(r.validationBatches==null||r.validationBatches>0&&Number.isInteger(r.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${r.validationBatches}`);else{let g=MU(r.validationData);s=g.xs,i=g.ys}let o=e.makeTrainFunction(),l=e.getDedupedMetricsNames(),u;a?u=l.slice().concat(l.map(g=>"val_"+g)):u=l.slice();let d=Mw(r.callbacks,r.yieldEvery),h=r.verbose==null?1:r.verbose,{callbackList:p,history:c}=Fw(d,h,r.epochs,null,null,_U(t,r),null,a,u);p.setModel(e),e.history=c,await p.onTrainBegin(),e.stopTraining_=!1;let m=r.initialEpoch==null?0:r.initialEpoch,f=await t.iterator();for(;m<r.epochs;){let g={};await p.onEpochBegin(m);let y=0,A=0;for(n||(f=await t.iterator());!n||y<r.batchesPerEpoch;){let x=await f.next();if(n&&x.done){console.warn(`You provided \`batchesPerEpoch\` as ${r.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, ${r.batchesPerEpoch*r.epochs} batches). You may need to use the repeat() function when building your dataset.`);break}if(x.value!=null){let{xs:b,ys:w}=Vw(e,x.value),I={};I.batch=A,I.size=b[0].shape[0],await p.onBatchBegin(A,I);let T=[];if(r.classWeight!=null){let F=Bw(r.classWeight,e.outputNames);for(let $=0;$<F.length;++$)T.push(await Ww(w[$],null,F[$]))}let E=b.concat(w).concat(T),R=o(E);ee(E);for(let F=0;F<l.length;++F){let $=l[F],S=R[F];I[$]=S,mr(S)}await p.onBatchEnd(A,I),Nw(I),A++,y++}if(n?y>=r.batchesPerEpoch:x.done){if(a){let b;C4(r.validationData)?b=Tt(await e.evaluateDataset(r.validationData,{batches:r.validationBatches})):b=Tt(e.evaluate(s,i,{batchSize:r.validationBatchSize==null?$U:r.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(m,g),m++,e.stopTraining_)break}return await p.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function _U(e,t){let r=null;return t.batchesPerEpoch!=null?r=t.batchesPerEpoch:Number.isFinite(e.size)&&(r=e.size),r}function C4(e){return typeof e.iterator=="function"}function PU(e){return typeof e.next=="function"}async function OU(e,t,r){r=r||{};let n=r.batches!=null,a=e.testFunction,s=[];if(r.verbose>0)throw new Ve("Verbose mode is not implemented yet.");v.assert(!n||r.batches>0&&Number.isInteger(r.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(r.batches)}`);let i=PU(t)?t:await t.iterator(),o=0,l=0;for(;!n||l<r.batches;){let u=await i.next();if(s=X(()=>{if(u.value){let{xs:d,ys:h}=Vw(e,u.value),p=d.concat(h),c=X(()=>a(p));if(ee(p),l===0)for(let f=0;f<c.length;++f)s.push(Se(0));let m=p[0].shape[0];for(let f=0;f<c.length;++f){let g=c[f],y=s[f];s[f]=X(()=>le(s[f],L(m,g))),l>0&&ee(y)}ee(c),o+=m,++l}return s}),u.done){n&&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, ${r.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let u=0;u<s.length;++u){let d=s[u];s[u]=pe(s[u],o),ee(d)}return rn(s)}function Kg(e){v.assert(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function Fp(e,t,r){return e==null?[null]:Array.isArray(e)?e.map(n=>Eo(n,t,r-t)):Eo(e,t,r-t)}function r5(e,t){return X(()=>e==null?null:Array.isArray(e)?e.map(r=>r5(r,t)):Aw(e,t.dtype==="int32"?t:me(t,"int32")))}function Zg(e,t){let r=[],n=0,a=null;for(;n<e;)a=n+t,a>=e&&(a=e),r.push([n,a]),n=a;return r}async function zU(e,t,r,n,a,s,i,o,l,u,d,h,p,c,m){a==null&&(a=32),s==null&&(s=1),d==null&&(d=!0),p==null&&(p=0);let f=!1;if(l!=null&&u!=null&&(f=!0),m!=null&&(f=!0,c==null))throw new q("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let g=e.checkNumSamples(r,a,c,"steps_per_epoch"),y;g!=null&&(y=ya(0,g)),i==null&&(i=1);let{callbackList:A,history:x}=Fw(o,i,s,p,g,c,a,f,h);A.setModel(e),e.history=x,await A.onTrainBegin(),e.stopTraining_=!1;for(let b=p;b<s;++b){await A.onEpochBegin(b);let w={};if(c!=null)throw new Ve("stepsPerEpoch mode is not implemented yet.");{if(d==="batch")throw new Ve("batch shuffling is not implemneted yet");d&&v.shuffle(y);let I=Nt(y),T=Zg(g,a);for(let E=0;E<T.length;++E){let R={};if(await A.onBatchBegin(E,R),X(()=>{let F=T[E][0],$=T[E][1],S=Eo(I,F,$-F);R.batch=E,R.size=$-F;let z=r5(r,S),O=t(z);for(let j=0;j<n.length;++j){let K=n[j],D=O[j];R[K]=D,mr(D)}if(E===T.length-1&&f){let j=e.testLoop(l,u,a);for(let K=0;K<n.length;++K){let D=n[K],Y=j[K];mr(Y),w["val_"+D]=Y}}}),await A.onBatchEnd(E,R),Nw(R),e.stopTraining_)break}I.dispose()}if(await A.onEpochEnd(b,w),e.stopTraining_)break}return await A.onTrainEnd(),await e.history.syncData(),e.history}async function DU(e,t,r,n={}){if(e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;let a,s,i,o,l,u,d,h,p;try{let c=n.batchSize==null?32:n.batchSize;Kg(c);let m=!1,f=await e.standardizeUserData(t,r,n.sampleWeight,n.classWeight,m,c);a=f[0],s=f[1],p=f[2];let g=!1,y;if(n.validationData!=null&&n.validationData.length>0){if(g=!0,n.validationData.length===2)l=n.validationData[0],u=n.validationData[1];else throw n.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; ${n.validationData} is invalid.`);let E=!0,R=await e.standardizeUserData(l,u,null,null,E,c);d=R[0],h=R[1],y=d.concat(h)}else if(n.validationSplit!=null&&n.validationSplit>0&&n.validationSplit<1){g=!0;let E=Math.floor(a[0].shape[0]*(1-n.validationSplit)),R=a[0].shape[0];d=Fp(a,E,R),i=a,a=Fp(a,0,E),h=Fp(s,E,R),o=s,s=Fp(s,0,E),y=d.concat(h)}else n.validationSteps!=null&&(g=!0);let A=a.concat(s).concat(p);e.checkTrainableWeightsConsistency();let x=e.makeTrainFunction(),b=e.getDedupedMetricsNames(),w,I;g?(e.makeTestFunction(),w=e.testFunction,I=b.slice().concat(b.map(E=>"val_"+E))):(w=null,y=[],I=b.slice());let T=Mw(n.callbacks,n.yieldEvery);return await zU(e,x,A,b,c,n.epochs,n.verbose,T,w,y,n.shuffle,I,n.initialEpoch,null,null)}finally{e.isTraining=!1,ua(a,t),ua(s,r),ua(i,t),ua(o,r),ua(d,l),ua(h,u),p!=null&&ee(p)}}function Uw(e){let t=[];e instanceof nt&&(e=[e]);for(let r=0;r<e.length;++r){let n=e[r];if(n.rank===1)t.push(Ph(n,1));else{if(n.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(n)}}return t}function ua(e,t){if(e==null)return;let r=[];if(t instanceof nt)r.push(t.id);else if(Array.isArray(t))t.forEach(a=>r.push(a.id));else if(t!=null)for(let a in t){let s=t[a];r.push(s.id)}let n=[];if(e instanceof nt)r.indexOf(e.id)===-1&&n.push(e);else if(Array.isArray(e))e.forEach(a=>{r.indexOf(a.id)===-1&&n.push(a)});else if(e!=null)for(let a in e){let s=e[a];r.indexOf(s.id)===-1&&n.push(s)}n.forEach(a=>{a.isDisposed||a.dispose()})}function LU(e){return e instanceof nt}function Yg(e){return Array.isArray(e)}function T4(e){return!LU(e)&&!Yg(e)}function N4(e,t,r,n=!0,a=""){if(t==null||t.length===0){if(e!=null){let i=!1;if(Yg(e)&&e.length>0)i=!0;else if(T4(e)){for(let o in e)if(e.hasOwnProperty(o)){i=!0;break}}else i=!0;if(i)throw new q(`Error when checking model ${a} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(i=>null);let s;if(T4(e)){e=e,s=[];for(let i of t){if(e[i]==null)throw new q(`No data provided for "${i}". Need data for each key in: ${t}`);s.push(e[i])}}else if(Yg(e)){if(e=e,e.length!==t.length)throw new q(`Error when checking model ${a}: 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}`);s=e}else{if(e=e,t.length>1)throw new q(`The model ${a} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=Uw(s),r!=null)for(let i=0;i<t.length;++i){if(r[i]==null)continue;let o=s[i];if(o.shape.length!==r[i].length)throw new q(`Error when checking ${a}: expected ${t[i]} to have ${r[i].length} dimension(s). but got array with shape ${o.shape}`);for(let l=0;l<r[i].length;++l){if(l===0&&!n)continue;let u=o.shape[l],d=r[i][l];if(d!=null&&d>=0&&u!==d)throw new q(`${a} expected a batch of elements where each example has shape [${r[i].slice(1,r[i].length)}] (i.e.,tensor shape [*,${r[i].slice(1,r[i].length)}]) but the ${a} received an input with ${o.shape[0]} examples, each with shape [${o.shape.slice(1,o.shape.length)}] (tensor shape [${o.shape}])`)}}return s}function BU(e,t,r){let n=$s(e.map(s=>s.shape[0]));n.sort();let a=$s(t.map(s=>s.shape[0]));if(a.sort(),n.length>1)throw new q(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(s=>s.shape))}`);if(a.length>1)throw new q(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(s=>s.shape))}`);if(n.length>0&&a.length>0&&!v.arraysEqual(n,a))throw new q(`Input Tensors should have the same number of samples as target Tensors. Found ${n[0]} input sample(s) and ${a[0]} target sample(s).`)}function WU(e,t,r){let n=[Ol,vm,Jp];for(let a=0;a<e.length;++a){let s=e[a],i=t[a],o=r[a];if(i!=null){if(i===Jp&&s.shape[s.shape.length-1]===1)throw new q(`You are passing a target array of shape ${s.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(n.indexOf(i)!==-1){let l=s.shape.slice(1),u=o.slice(1);for(let d=0;d<l.length;++d){let h=l[d],p=u[d];if(p!=null&&h!==p)throw new q(`A target Tensor with shape ${s.shape} was passed for an output of shape ${o}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}function E4(e,t,r,n=!0,a=""){let s;if(Array.isArray(e)){if(e.length!==t.length)throw new q(`Error when checking model ${a}: 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).`);s=e}else{if(t.length>1)throw new q(`The model expects ${t.length} ${a} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);s=[e]}if(r!=null)for(let i=0;i<t.length;++i){if(r[i]==null)continue;let o=s[i];if(o.shape.length!==r[i].length)throw new q(`Error when checking ${a}: expected ${t[i]} to have ${r[i].length} dimension(s), but got array with shape ${JSON.stringify(o.shape)}`);for(let l=0;l<r[i].length;++l){if(l===0&&!n)continue;let u=o.shape[l],d=r[i][l];if(d!=null&&d!==u)throw new q(`Error when checking ${a}: expected ${t[i]} to have shape ${JSON.stringify(r[i])} but got array with shape ${JSON.stringify(o.shape)}.`)}}}function VU(e,t){if(e==null||Array.isArray(e)&&e.length===0)return t.map(n=>[]);let r;if(typeof e=="string"||typeof e=="function")r=[e];else if(Array.isArray(e)||typeof e=="object")r=e;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);if(Array.isArray(r))return t.map(n=>r);{let n=[];for(let a of t){let s=r.hasOwnProperty(a)?r[a]:[];Array.isArray(s)||(s=[s]),n.push(s)}return n}}var UU="layers-model",Za=class extends Ta{constructor(e){super(e),this.isTraining=!1}summary(e,t,r=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).");IU(this,e,t,r)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=kU(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof as))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 s in e.loss)if(this.outputNames.indexOf(s)===-1)throw new q(`Unknown entry in loss dictionary: "${s}". Only expected the following keys: ${this.outputNames}`);for(let s of this.outputNames)e.loss[s]==null&&console.warn(`Output "${s}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${s} during training`),t.push(vg(e.loss[s]))}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(s=>vg(s))}else{let s=vg(e.loss);this.outputs.forEach(i=>{t.push(s)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let s=0;s<this.outputs.length;++s){let i=this.internalOutputShapes[s],o=this.outputNames[s];this.feedOutputNames.push(o),this.feedOutputShapes.push(i),this.feedLossFns.push(this.lossFunctions[s])}let r=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],No("loss",()=>{for(let s=0;s<this.outputs.length;++s){if(r.indexOf(s)!==-1)continue;let i=this.lossFunctions[s];this.outputs.length>1&&(this.metricsTensors.push([i,s]),this.metricsNames.push(this.outputNames[s]+"_loss"))}});let n=VU(e.metrics,this.outputNames),a=(s,i,o)=>{this.outputNames.length>1&&(i=this.outputNames[s]+"_"+i),this.metricsNames.push(i),this.metricsTensors.push([o,s])};No("metric",()=>{for(let s=0;s<this.outputs.length;++s){if(r.indexOf(s)!==-1)continue;let i=n[s];(o=>{let l="",u,d,h;for(let p of o){if(typeof p=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(p)!==-1){let m=this.internalOutputShapes[s];m[m.length-1]===1||this.lossFunctions[s]===vm?["accuracy","acc"].indexOf(p)!==-1?d=J3:["crossentropy","ce"].indexOf(p)!==-1&&(d=Ow):this.lossFunctions[s]===V0?["accuracy","acc"].indexOf(p)!==-1?d=zw:["crossentropy","ce"].indexOf(p)!==-1&&(d=Dw):["accuracy","acc"].indexOf(p)!==-1?d=Q3:["crossentropy","ce"].indexOf(p)!==-1&&(d=e5);let f;["accuracy","acc"].indexOf(p)!==-1?f="acc":["crossentropy","ce"].indexOf(p)!==-1&&(f="ce"),h=d,u=l+f}else h=wU(p),u=l+s0(p);let c;No(u,()=>{c=h}),a(s,u,c)}})(i)}}),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,r={}){let n=r.batchSize==null?32:r.batchSize;Kg(n);let a=!0,s=this.standardizeUserDataXY(e,t,a,n);try{let i=s[0].concat(s[1]);this.makeTestFunction();let o=this.testFunction,l=this.testLoop(o,i,n,r.verbose,r.steps);return rn(l)}finally{ua(s[0],e),ua(s[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),OU(this,e,t)}checkNumSamples(e,t,r,n="steps"){let a;if(r!=null){if(a=null,t!=null)throw new q(`If ${n} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?a=e[0].shape[0]:a=e.shape[0];else throw new q(`Either the input data should have a defined shape, or ${n} shoud be specified.`);return a}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new q("`outputs` is an empty Array, which is not allowed.");let r=Array.isArray(t),n=r?t:[t],a=this.retrieveSymbolicTensors(n),s=new So;if(e instanceof nt&&(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 o=0;o<this.inputs.length;++o)s.add(this.inputs[o],e[o])}else for(let o of this.inputs){let l=e[o.name];if(l==null)throw new q(`No value is provided for the model's input ${o.name}`);s.add(o,l)}let i=Mp(a,s);return r?i:i[0]}retrieveSymbolicTensors(e){let t=Oo(null,e.length),r=e.length;for(let n of this.layers){let a=Array.isArray(n.output)?n.output:[n.output],s=a.map(i=>i.name);for(let i=0;i<e.length;++i){let o=s.indexOf(e[i]);if(o!==-1&&(t[i]=a[o],r--),r===0)break}if(r===0)break}if(r>0){let n=[];throw t.forEach((a,s)=>{a==null&&n.push(e[s])}),new q(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,r=!1){return X(()=>{let n=this.checkNumSamples(e);if(r)throw new Ve("Verbose predictLoop() is not implemented yet.");let a=Zg(n,t),s=this.outputs.map(i=>[]);for(let i=0;i<a.length;++i)X(()=>{let o=a[i][0],l=a[i][1],u=Fp(e,o,l),d=[];if(Array.isArray(u))for(let p=0;p<u.length;++p)d.push({key:this.inputs[p],value:u[p]});else d.push({key:this.inputs[0],value:u});let h=new So(d);return Mp(this.outputs,h)}).forEach((o,l)=>s[l].push(o));return rn(s.map(i=>St(i,0)))})}predict(e,t={}){let r=Uw(e);E4(r,this.inputNames,this.feedInputShapes,!1);try{let n=t.batchSize==null?32:t.batchSize;return Kg(n),this.predictLoop(r,n)}finally{ua(r,e)}}predictOnBatch(e){E4(e,this.inputNames,this.feedInputShapes,!0);let t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,r=!0,n){if(this.optimizer_==null)throw new da("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let a=[];for(let s=0;s<this.feedOutputShapes.length;++s){let i=this.feedOutputShapes[s];this.feedLossFns[s]===V0?a.push(i.slice(0,i.length-1).concat([1])):a.push(i)}if(e=N4(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=N4(t,this.feedOutputNames,a,!1,"target"),BU(e,t,null),WU(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&n!=null&&n>0&&e[0].shape[0]%n!==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 ${n}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,r,n,a=!0,s){let[i,o]=this.standardizeUserDataXY(e,t,a,s);if(r!=null)throw new Error("sample weight is not supported yet.");let l=null;if(n!=null){let u=Bw(n,this.outputNames);l=[];for(let d=0;d<u.length;++d)l.push(await Ww(o[d],null,u[d]))}return[i,o,l]}testLoop(e,t,r,n=0,a){return X(()=>{let s=this.checkNumSamples(t,r,a,"steps"),i=[];if(n>0)throw new Ve("Verbose mode is not implemented yet.");if(a!=null)throw new Ve("steps mode in testLoop() is not implemented yet");{let o=Zg(s,r),l=Nt(ya(0,s));for(let u=0;u<o.length;++u){let d=o[u][0],h=o[u][1],p=Eo(l,d,h-d),c=r5(t,p),m=e(c);if(u===0)for(let f=0;f<m.length;++f)i.push(Se(0));for(let f=0;f<m.length;++f){let g=m[f];i[f]=le(i[f],L(h-d,g))}}for(let u=0;u<i.length;++u)i[u]=pe(i[u],s)}return i})}getDedupedMetricsNames(){let e=this.metricsNames,t=[];for(let r=0;r<e.length;++r){let n=e[r],a=n;l4(e,n)>1&&(a+=`_${l4(e.slice(0,r),n)}`),t.push(a)}return t}makeTrainFunction(){return e=>{let t=[],r=e.slice(0,this.inputs.length),n=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),s=[],i=()=>{let u=[];for(let c=0;c<this.inputs.length;++c)u.push({key:this.inputs[c],value:r[c]});let d=new So(u),h=Mp(this.outputs,d,{training:!0}),p;for(let c=0;c<this.lossFunctions.length;++c){let m=this.lossFunctions[c],f=m(n[c],h[c]);a[c]!=null&&(f=RU(f,a[c]));let g=Vt(f);t.push(g),c===0?p=f:p=le(p,f)}for(let c=0;c<this.metricsTensors.length;++c){let m;if(this.outputs.length>1&&c<this.outputs.length)m=t[c];else{let f=this.metricsTensors[c][0],g=this.metricsTensors[c][1];m=Vt(f(n[g],h[g]))}mr(m),s.push(m)}return p=Vt(p),this.calculateLosses().forEach(c=>{p=le(p,c)}),p},o=this.collectedTrainableWeights.map(u=>u.read()),l=!0;return[this.optimizer_.minimize(i,l,o)].concat(s)}}makeTestFunction(){this.testFunction=e=>X(()=>{let t=[],r,n=e.slice(0,this.inputs.length),a=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=[];for(let l=0;l<this.inputs.length;++l)s.push({key:this.inputs[l],value:n[l]});let i=new So(s),o=Mp(this.outputs,i);for(let l=0;l<this.lossFunctions.length;++l){let u=this.lossFunctions[l],d=Vt(u(a[l],o[l]));l===0?r=d:r=le(r,d),t.push(r)}for(let l=0;l<this.metricsTensors.length;++l){let u=this.metricsTensors[l][0],d=this.metricsTensors[l][1],h=Vt(u(a[d],o[d]));t.push(h)}return t})}async fit(e,t,r={}){return DU(this,e,t,r)}async fitDataset(e,t){return FU(this,e,t)}async trainOnBatch(e,t){let r=await this.standardizeUserData(e,t),n=r[0],a=r[1],s=this.makeTrainFunction()(n.concat(a)),i=[];for(let o of s){let l=await o.data();i.push(l[0])}return ee(s),ua(r[0],e),ua(r[1],t),rn(i)}getNamedWeights(e){let t=[],r=e!=null&&e.trainableOnly,n=r?this.trainableWeights:this.weights,a=this.getWeights(r);for(let s=0;s<n.length;++s)r&&!n[s].trainable||t.push({name:n[s].originalName,tensor:a[s]});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=F0().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-F0().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=Ha(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=>Ha(t))}else{let t=Object.keys(this.loss);e={};let r=this.loss;for(let n of t)if(typeof r[n]=="string")e[n]=Ha(r[n]);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[Ha(s0(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>Ha(s0(e)));{let e={};for(let t in this.metrics)e[t]=Ha(s0(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=Qp(e.optimizer_config),r=fa(t),n;if(typeof e.loss=="string")n=wo(e.loss);else if(Array.isArray(e.loss))n=e.loss.map(s=>wo(s));else if(e.loss!=null){n={};for(let s in e.loss)n[s]=wo(e.loss[s])}let a;if(Array.isArray(e.metrics))a=e.metrics.map(s=>wo(s));else if(e.metrics!=null){a={};for(let s in e.metrics)a[s]=wo(e.metrics[s])}this.compile({loss:n,metrics:a,optimizer:r})}async save(e,t){if(typeof e=="string"){let i=Cr.getSaveHandlers(e);if(i.length===0)throw new q(`Cannot find any save handlers for URL '${e}'`);if(i.length>1)throw new q(`Found more than one (${i.length}) save handlers for URL '${e}'`);e=i[0]}if(e.save==null)throw new q("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let r=await Cr.encodeWeights(this.getNamedWeights(t)),n=!1,a=null,s={modelTopology:this.toJSON(a,n),format:UU,generatedBy:`TensorFlow.js tfjs-layers v${t5}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){s.trainingConfig=this.getTrainingConfig();let i="optimizer",{data:o,specs:l}=await Cr.encodeWeights(await this.optimizer.getWeights(),i);r.specs.push(...l),r.data=Cr.concatenateArrayBuffers([r.data,o])}return this.userDefinedMetadata!=null&&(I4(this.userDefinedMetadata,this.name,!0),s.userDefinedMetadata=this.userDefinedMetadata),s.weightData=r.data,s.weightSpecs=r.specs,e.save(s)}setUserDefinedMetadata(e){I4(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};Za.className="Model";ue.registerClass(Za);var Gw=class extends Za{};Gw.className="Functional";ue.registerClass(Gw);async function GU(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let r=e.modelTopology;r.model_config!=null&&(r=r.model_config);let n=Qp(r),a=fa(n,t);if(e.weightsManifest!=null){let s=await Cr.loadWeights(e.weightsManifest,e.pathPrefix,a.weights.map(o=>o.originalName)),i={};for(let o of a.weights)i[o.originalName]=s[o.originalName];a.loadWeights(i),ee(s)}return a}async function jU(e,t){if(t==null&&(t={}),typeof e=="string"){let r=Cr.getLoadHandlers(e,t);if(r.length===0)r.push(Cr.browserHTTPRequest(e,t));else if(r.length>1)throw new q(`Found more than one (${r.length}) load handlers for URL '${e}'`);e=r[0]}return HU(e,void 0,t)}async function HU(e,t,r){if(r==null&&(r={}),e.load==null)throw new q("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let n=await e.load(),a=n.modelTopology;a.model_config!=null&&(a=a.model_config);let s=r.strict==null?!0:r.strict,i=n.weightData!=null&&n.weightSpecs!=null&&s,o=fa(Qp(a),t,i),l=n.trainingConfig;if(l!=null&&o.loadTrainingConfig(l),n.userDefinedMetadata!=null&&o.setUserDefinedMetadata(n.userDefinedMetadata),n.weightData!=null){if(n.weightSpecs==null)throw new q("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:u,optimizerWeights:d}=qU(n.weightData,n.weightSpecs);o.loadWeights(u,s),o.optimizer!=null&&d.length>0&&await o.optimizer.setWeights(d),ee(u),ee(d.map(h=>h.tensor))}return o}function qU(e,t){let r=Cr.decodeWeights(e,t),n={},a=[];return t.forEach(s=>{s.group==="optimizer"?a.push({name:s.name,tensor:r[s.name]}):n[s.name]=r[s.name]}),{modelWeights:n,optimizerWeights:a}}var Jg=class extends Za{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:um("sequential_"),e.layers!=null)for(let t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(t=>t<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 Jg||e instanceof Za,r;if(t){if(r=e,r.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(r.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 n=ww({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(n)}if(t)this.outputs=r.outputs,this.inputs=r.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=vw(this.outputs[0])}this.inboundNodes=[],new xm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Oo(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(n=>n.shape),outputShapes:this.outputs[0].shape})}else{let n=e.apply(this.outputs[0]);if(Array.isArray(n))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=[n],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(mt(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 Za({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,r=console.log){this.built||this.build(),super.summary(e,t,r)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,r={}){if(!this.built)throw new da("The model needs to be compiled before being used.");return this.model.evaluate(e,t,r)}async evaluateDataset(e,t){if(!this.built)throw new da("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,r={}){if(!this.built)throw new da("The model needs to be compiled before being used.");return this.model.fit(e,t,r)}async fitDataset(e,t){if(!this.built)throw new da("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,r={},n=!1){let a,s={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new q("Legacy serialization format not supported yet.");a=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."),a=t.layers,delete t.layers,s=t;let i=new e(s);if(!(i instanceof Jg))throw new Ve(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(let o of a){let l=fa(o,void 0,n);n&&l.setFastWeightInitDuringBuild(!0),i.add(l)}return i}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 r={};r.className=t.getClassName(),r.config=t.getConfig(),e.push(r)}return{name:this.name,layers:e}}},wm=Jg;wm.className="Sequential";ue.registerClass(wm);function XU(e){return new Za(e)}function KU(e){return new wm(e)}function ZU(e,t){return t==null&&(t={}),jU(e,t)}function jw(e){return ww(e)}function YU(e,t){Z3.registerCallbackConstructor(e,t)}var ln=class extends ue.Serializable{getConfig(){return{}}},Hw=class extends ln{apply(e,t=1){return fB(e,t)}};Hw.className="elu";ue.registerClass(Hw);var qw=class extends ln{apply(e){return v3(e)}};qw.className="selu";ue.registerClass(qw);var Xw=class extends ln{apply(e){return Da(e)}};Xw.className="relu";ue.registerClass(Xw);var Kw=class extends ln{apply(e){return X(()=>$h(6,Da(e)))}};Kw.className="relu6";ue.registerClass(Kw);var Zw=class extends ln{apply(e){return e}};Zw.className="linear";ue.registerClass(Zw);var Yw=class extends ln{apply(e){return Tr(e)}};Yw.className="sigmoid";ue.registerClass(Yw);var Jw=class extends ln{apply(e){return gB(e)}};Jw.className="hardSigmoid";ue.registerClass(Jw);var Qw=class extends ln{apply(e){return wd(e)}};Qw.className="softplus";ue.registerClass(Qw);var e8=class extends ln{apply(e){return mB(e)}};e8.className="softsign";ue.registerClass(e8);var t8=class extends ln{apply(e){return $u(e)}};t8.className="tanh";ue.registerClass(t8);var n5=class extends ln{apply(e,t=-1){return Sd(e,t)}};n5.className="softmax";ue.registerClass(n5);var r8=class extends ln{apply(e,t=-1){return p3(e,t)}};r8.className="logSoftmax";ue.registerClass(r8);var n8=class extends ln{apply(e,t=1){return X(()=>L(Tr(L(e,t)),e))}};n8.className="swish";ue.registerClass(n8);var a8=class extends ln{apply(e){return X(()=>L(e,$u(wd(e))))}};a8.className="mish";ue.registerClass(a8);function Gs(e){return e.getClassName()}function wg(e,t={}){return _h(e,ue.SerializationMap.getMap().classNameMap,t,"activation")}function js(e){if(e==null){let t={};return t.className="linear",t.config={},wg(t)}if(typeof e=="string"){let t={};return t.className=e,t.config={},wg(t)}else return e instanceof ln?e:wg(e)}function a5(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 s8=class extends ue.Serializable{},Lh=class extends s8{constructor(e){super(),a5(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 X(()=>{let t=Ot([1]);return this.hasL1&&(t=le(t,ke(L(this.l1,ar(e))))),this.hasL2&&(t=le(t,ke(L(this.l2,Oh(e))))),U(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};Lh.className="L1L2";ue.registerClass(Lh);function JU(e){return a5(e),new Lh({l1:e!=null?e.l1:null,l2:0})}function QU(e){return a5(e),new Lh({l2:e!=null?e.l2:null,l1:0})}var R4={l1l2:"L1L2"};function vt(e){return _3(e)}function $4(e,t={}){return _h(e,ue.SerializationMap.getMap().classNameMap,t,"regularizer")}function Ft(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in R4?R4[e]:e,config:{}};return $4(t)}else return e instanceof s8?e:$4(e)}var s5=class extends st{constructor(e){super(e==null?{}:e),this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=je(e);let r=Da(e);return this.maxValue!=null&&(r=fn(r,0,this.maxValue)),r}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};s5.className="ReLU";ue.registerClass(s5);var i5=class extends st{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 r=je(e);return Wf(r,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};i5.className="LeakyReLU";ue.registerClass(i5);var o5=class extends st{constructor(e){if(super(e==null?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=$t(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Ft(e.alphaRegularizer),this.alphaConstraint=lr(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=mt(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let n of this.sharedAxes)t[n-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let r={};if(this.sharedAxes!=null)for(let n=1;n<e.length;++n)r[n]=e[n];this.inputSpec=[new Zt({ndim:e.length,axes:r})],this.built=!0}call(e,t){return e=je(e),Xf(e,this.alpha.read())}getConfig(){let e={alphaInitializer:zt(this.alphaInitializer),alphaRegularizer:vt(this.alphaRegularizer),alphaConstraint:or(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}};o5.className="PReLU";ue.registerClass(o5);var l5=class extends st{constructor(e){if(super(e==null?{}:e),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 r=je(e);return Eh(r)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};l5.className="ELU";ue.registerClass(l5);var u5=class extends st{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 r=je(e);return L(r,me(gn(r,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){let e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}};u5.className="ThresholdedReLU";ue.registerClass(u5);var d5=class extends st{constructor(e){super(e==null?{}:e),this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new n5().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){let r=je(e);return this.softmax(r,this.axis)}computeOutputShape(e){return e}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};d5.className="Softmax";ue.registerClass(d5);function Cu(e,t,r){if(typeof e=="number")return Oo(e,t);if(e.length!==t)throw new q(`The ${r} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let n=0;n<t;++n){let a=e[n];if(!dB(a))throw new q(`The ${r} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${a}`)}return e}function ma(e,t,r,n,a=1){if(e==null)return e;let s=t+(t-1)*(a-1),i;return r==="same"?i=e:i=e-s+1,Math.floor((i+n-1)/n)}function Ea(e,t,r,n){if(e==null)return null;if(n==="valid")e=e*t+Us([r-t,0]);else if(n==="same")e=e*t;else throw new q(`Unsupport padding mode: ${n}.`);return e}function p5(e,t){return X(()=>(jt(t),t==="channelsFirst"?tt(e,[0,2,3,1]):e))}function i8(e,t){return X(()=>(jt(t),t==="channelsFirst"?tt(e,[0,2,3,4,1]):e))}function eG(e,t,r,n=1,a="valid",s,i=1){return X(()=>{if(s==null&&(s=Aa()),jt(s),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(r!=null&&r.shape.length!==1)throw new q(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(s==="channelsFirst"&&(e=tt(e,[0,2,1])),a==="causal")throw new Ve("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=t3(e,t,n,a==="same"?"same":"valid","NWC",i);return r!=null&&(o=va(o,r)),o})}function M4(e,t,r,n=[1,1],a="valid",s,i,o=null){return X(()=>{if(s==null&&(s=Aa()),jt(s),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=p5(e,s);if(a==="causal")throw new Ve("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=Vs.conv2d({x:l,filter:t,strides:n,pad:a==="same"?"same":"valid",dilations:i,dataFormat:"NHWC",bias:r,activation:o}),s==="channelsFirst"&&(l=tt(l,[0,3,1,2])),l})}function tG(e,t,r,n=[1,1,1],a="valid",s,i){return X(()=>{if(s==null&&(s=Aa()),jt(s),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 o=i8(e,s);if(a==="causal")throw new Ve("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=a3(o,t,n,a==="same"?"same":"valid","NDHWC",i),r!=null&&(o=va(o,r)),s==="channelsFirst"&&(o=tt(o,[0,4,1,2,3])),o})}var h5=class extends st{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",h5.verifyArgs(t),this.rank=e,gr(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=Cu(t.kernelSize,e,"kernelSize"),this.strides=Cu(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,Bn(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,jt(this.dataFormat),this.activation=js(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=$t(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=lr(t.biasConstraint),this.biasRegularizer=Ft(t.biasRegularizer),this.activityRegularizer=Ft(t.activityRegularizer),this.dilationRate=Cu(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(Na("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!P3(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:Gs(this.activation),useBias:this.useBias,biasInitializer:zt(this.biasInitializer),biasRegularizer:vt(this.biasRegularizer),activityRegularizer:vt(this.activityRegularizer),biasConstraint:or(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},Bh=class extends h5{constructor(e,t){super(e,t),this.kernel=null,Bh.verifyArgs(t),this.filters=t.filters,gr(this.filters,"filters"),this.kernelInitializer=$t(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=lr(t.kernelConstraint),this.kernelRegularizer=Ft(t.kernelRegularizer)}build(e){e=mt(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 r=e[t],n=this.kernelSize.concat([r,this.filters]);this.kernel=this.addWeight("kernel",n,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]:r}}],this.built=!0}call(e,t){return X(()=>{e=je(e);let r,n=this.bias==null?null:this.bias.read(),a=hw(this.activation.getClassName());if(a!=null&&this.rank===2)r=M4(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,a);else{if(this.rank===1)r=eG(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)r=M4(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)r=tG(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Ve("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(r=this.activation.apply(r))}return r})}computeOutputShape(e){e=mt(e);let t=[],r=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let a=0;a<r.length;++a){let s=ma(r[a],this.kernelSize[a],this.padding,this.strides[a],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[a]);t.push(s)}let n=[e[0]];return this.dataFormat==="channelsLast"?(n=n.concat(t),n.push(this.filters)):(n.push(this.filters),n=n.concat(t)),n}getConfig(){let e={filters:this.filters,kernelInitializer:zt(this.kernelInitializer),kernelRegularizer:vt(this.kernelRegularizer),kernelConstraint:or(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)}`)}},o8=class extends Bh{constructor(e){super(2,e),o8.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!P3(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)}.`)}},km=o8;km.className="Conv2D";ue.registerClass(km);var l8=class extends Bh{constructor(e){super(3,e),l8.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)}.`)}},Im=l8;Im.className="Conv3D";ue.registerClass(Im);var c5=class extends km{constructor(e){if(super(e),this.inputSpec=[new Zt({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=mt(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 r=e[t],n=this.kernelSize.concat([this.filters,r]);this.kernel=this.addWeight("kernel",n,"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 Zt({ndim:4,axes:{[t]:r}})],this.built=!0}call(e,t){return X(()=>{let r=je(e);if(r.shape.length!==4)throw new q(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${r.shape.length}`);let n=r.shape,a=n[0],s,i;this.dataFormat==="channelsFirst"?(s=2,i=3):(s=1,i=2);let o=n[s],l=n[i],u=this.kernelSize[0],d=this.kernelSize[1],h=this.strides[0],p=this.strides[1],c=Ea(o,h,u,this.padding),m=Ea(l,p,d,this.padding),f=[a,c,m,this.filters];this.dataFormat!=="channelsLast"&&(r=tt(r,[0,2,3,1]));let g=n3(r,this.kernel.read(),f,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=tt(g,[0,3,1,2])),this.bias!=null&&(g=va(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=mt(e);let t=e.slice(),r,n,a;this.dataFormat==="channelsFirst"?(r=1,n=2,a=3):(r=3,n=1,a=2);let s=this.kernelSize[0],i=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return t[r]=this.filters,t[n]=Ea(t[n],o,s,this.padding),t[a]=Ea(t[a],l,i,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};c5.className="Conv2DTranspose";ue.registerClass(c5);var f5=class extends Im{constructor(e){if(super(e),this.inputSpec=[new Zt({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=mt(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 r=e[t],n=this.kernelSize.concat([this.filters,r]);this.kernel=this.addWeight("kernel",n,"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 Zt({ndim:5,axes:{[t]:r}})],this.built=!0}call(e,t){return X(()=>{let r=je(e);if(r.shape.length!==5)throw new q(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${r.shape.length}`);let n=r.shape,a=n[0],s,i,o;this.dataFormat==="channelsFirst"?(o=2,s=3,i=4):(o=1,s=2,i=3);let l=n[o],u=n[s],d=n[i],h=this.kernelSize[0],p=this.kernelSize[1],c=this.kernelSize[2],m=this.strides[0],f=this.strides[1],g=this.strides[2],y=Ea(l,m,h,this.padding),A=Ea(u,f,p,this.padding),x=Ea(d,g,c,this.padding),b=[a,y,A,x,this.filters];this.dataFormat!=="channelsLast"&&(r=tt(r,[0,2,3,4,1]));let w=cv(r,this.kernel.read(),b,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(w=tt(w,[0,4,1,2,3])),this.bias!==null&&(w=va(w,this.bias.read(),this.dataFormat)),this.activation!==null&&(w=this.activation.apply(w)),w})}computeOutputShape(e){e=mt(e);let t=e.slice(),r,n,a,s;this.dataFormat==="channelsFirst"?(r=1,n=2,a=3,s=4):(r=4,n=1,a=2,s=3);let i=this.kernelSize[0],o=this.kernelSize[1],l=this.kernelSize[2],u=this.strides[0],d=this.strides[1],h=this.strides[2];return t[r]=this.filters,t[n]=Ea(t[n],u,i,this.padding),t[a]=Ea(t[a],d,o,this.padding),t[s]=Ea(t[s],h,l,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};f5.className="Conv3DTranspose";ue.registerClass(f5);var u8=class extends Bh{constructor(e,t){if(super(e,t),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=$t(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Ft(t.depthwiseRegularizer),this.depthwiseConstraint=lr(t.depthwiseConstraint),this.pointwiseInitializer=$t(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Ft(t.pointwiseRegularizer),this.pointwiseConstraint=lr(t.pointwiseConstraint)}build(e){if(e=mt(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 r=e[t],n=this.kernelSize.concat([r,this.depthMultiplier]),a=[];for(let i=0;i<this.rank;++i)a.push(1);a.push(r*this.depthMultiplier,this.filters);let s=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",n,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,s,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",a,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,s,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,s,this.biasConstraint):this.bias=null,this.inputSpec=[new Zt({ndim:this.rank+2,axes:{[t]:r}})],this.built=!0}call(e,t){return X(()=>{e=je(e);let r;if(this.rank===1)throw new Ve("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=tt(e,[0,2,3,1])),r=zv(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(r=va(r,this.bias.read(),this.dataFormat)),this.activation!=null&&(r=this.activation.apply(r)),this.dataFormat==="channelsFirst"&&(r=tt(r,[0,3,1,2])),r})}getConfig(){let e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=zt(this.depthwiseInitializer),e.pointwiseInitializer=zt(this.pointwiseInitializer),e.depthwiseRegularizer=vt(this.depthwiseRegularizer),e.pointwiseRegularizer=vt(this.pointwiseRegularizer),e.depthwiseConstraint=or(this.depthwiseConstraint),e.pointwiseConstraint=or(this.pointwiseConstraint),e}};u8.className="SeparableConv";var m5=class extends u8{constructor(e){super(2,e)}};m5.className="SeparableConv2D";ue.registerClass(m5);var d8=class extends Bh{constructor(e){super(1,e),d8.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"&&!P3(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)}.`)}},g5=d8;g5.className="Conv1D";ue.registerClass(g5);var y5=class extends st{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 X(()=>{if(e=je(e),this.dataFormat==="channelsLast"){let r=a0(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return a0(r,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let r=a0(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return a0(r,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}};y5.className="Cropping2D";ue.registerClass(y5);var A5=class extends st{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,jt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,oB(this.interpolation)}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){let t=e[2]==null?null:this.size[0]*e[2],r=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,r]}else{let t=e[1]==null?null:this.size[0]*e[1],r=e[2]==null?null:this.size[1]*e[2];return[e[0],t,r,e[3]]}}call(e,t){return X(()=>{let r=je(e),n=r.shape;if(this.dataFormat==="channelsFirst"){r=tt(r,[0,2,3,1]);let a=this.size[0]*n[2],s=this.size[1]*n[3],i=this.interpolation==="nearest"?Ie.resizeNearestNeighbor(r,[a,s]):Ie.resizeBilinear(r,[a,s]);return tt(i,[0,3,1,2])}else{let a=this.size[0]*n[1],s=this.size[1]*n[2];return this.interpolation==="nearest"?Ie.resizeNearestNeighbor(r,[a,s]):Ie.resizeBilinear(r,[a,s])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}};A5.className="UpSampling2D";ue.registerClass(A5);function rG(e,t,r=[1,1],n="valid",a,s){return X(()=>{a==null&&(a=Aa()),jt(a);let i=p5(e,a);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 i=Nh(i,t,r,n==="same"?"same":"valid","NHWC",s),a==="channelsFirst"&&(i=tt(i,[0,3,1,2])),i})}var x5=class extends h5{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=$t(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=lr(e.depthwiseConstraint),this.depthwiseRegularizer=Ft(e.depthwiseRegularizer)}build(e){if(e=mt(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 r=e[t],n=[this.kernelSize[0],this.kernelSize[1],r,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",n,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[r*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return X(()=>{e=je(e);let r=rG(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(r=va(r,this.bias.read(),this.dataFormat)),this.activation!=null&&(r=this.activation.apply(r)),r})}computeOutputShape(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2],n=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,a=ma(t,this.kernelSize[0],this.padding,this.strides[0]),s=ma(r,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],n,a,s]:[e[0],a,s,n]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=zt(this.depthwiseInitializer),e.depthwiseRegularizer=vt(this.depthwiseRegularizer),e.depthwiseConstraint=or(this.depthwiseRegularizer),e}};x5.className="DepthwiseConv2D";ue.registerClass(x5);function p8(e,t,r,n){if(Array.isArray(e)){if(t!=null||r!=null)throw new q("When inputs is an array, neither initialState or constants should be provided");n!=null&&(r=e.slice(e.length-n,e.length),e=e.slice(0,e.length-n)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function a(s){return s==null||Array.isArray(s)?s:[s]}return t=a(t),r=a(r),{inputs:e,initialState:t,constants:r}}function h8(e,t,r,n=!1,a,s,i=!1,o=!1){return X(()=>{let l=t.shape.length;if(l<3)throw new q(`Input should be at least 3D, but is ${l}D.`);let u=[1,0].concat(ya(2,l));if(t=tt(t,u),s!=null)throw new Ve("The rnn() functoin of the deeplearn.js backend does not support constants yet.");i&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),a!=null&&(a=me(me(a,"bool"),"float32"),a.rank===l-1&&(a=Kt(a,-1)),a=tt(a,u)),n&&(t=On(t,0),a!=null&&(a=On(a,0)));let d=[],h,p=r,c=t.shape[0],m=an(t),f;a!=null&&(f=an(a));for(let y=0;y<c;++y){let A=m[y],x=X(()=>e(A,p));if(a==null)h=x[0],p=x[1];else{let b=X(()=>{let w=f[y],I=ce(Pn(w),w),T=le(L(x[0],w),L(p[0],I)),E=p.map((R,F)=>le(L(x[1][F],w),L(R,I)));return{output:T,newStates:E}});h=b.output,p=b.newStates}o&&d.push(h)}let g;return o&&(g=ur(d,1)),[h,g,p]})}var c8=class extends st{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 Tm({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 Zt({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 ya(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){jg(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);let r=t[0],n;if(this.returnSequences?n=[e[0],e[1],r]:n=[e[0],r],this.returnState){let a=[];for(let s of t)a.push([e[0],s]);return[n].concat(a)}else return n}computeMask(e,t){return X(()=>{Array.isArray(t)&&(t=t[0]);let r=this.returnSequences?t:null;if(this.returnState){let n=this.states.map(a=>null);return[r].concat(n)}else return r})}get states(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let r=0;r<e;++r)t.push(null);return t}else return this.states_}set states(e){this.states_=e}build(e){if(this.numConstants!=null)throw new Ve("Constants support is not implemented in RNN yet.");jg(e)&&(e=e[0]),e=e;let t=this.stateful?e[0]:null,r=e.slice(2);this.inputSpec[0]=new Zt({shape:[t,null,...r]});let n=[e[0]].concat(e.slice(2));this.cell.build(n);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(s=>s.shape[s.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(s=>new Zt({shape:[null,s]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){X(()=>{if(!this.stateful)throw new ja("Cannot call resetStates() on an RNN Layer that is not stateful.");let r=this.inputSpec[0].shape[0];if(r==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(n=>Ot([r,n])):this.states_=[Ot([r,this.cell.stateSize])];else if(e==null)ee(this.states_),this.keptStates!=null&&(ee(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(n=>Ot([r,n])):this.states_[0]=Ot([r,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()):ee(this.states_);for(let n=0;n<this.states_.length;++n){let a=e[n],s=Array.isArray(this.cell.stateSize)?this.cell.stateSize[n]:this.cell.stateSize,i=[r,s];if(!v.arraysEqual(a.shape,i))throw new q(`State ${n} is incompatible with layer ${this.name}: expected shape=${i}, received shape=${a.shape}`);this.states_[n]=a}}this.states_=this.states_.map(n=>mr(n.clone()))})}apply(e,t){let r=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});let a=p8(e,r,n,this.numConstants);e=a.inputs,r=a.initialState,n=a.constants;let s=[],i=[];if(r!=null){t.initialState=r,s=s.concat(r),this.stateSpec=[];for(let o of r)this.stateSpec.push(new Zt({shape:o.shape}));i=i.concat(this.stateSpec)}if(n!=null&&(t.constants=n,s=s.concat(n),this.numConstants=n.length),s[0]instanceof pa){let o=[e].concat(s),l=this.inputSpec.concat(i),u=this.inputSpec;this.inputSpec=l;let d=super.apply(o,t);return this.inputSpec=u,d}else return super.apply(e,t)}call(e,t){return X(()=>{let r=t==null?null:t.mask,n=t==null?null:t.training,a=t==null?null:t.initialState;e=je(e),a==null&&(this.stateful?a=this.states_:a=this.getInitialState(e));let s=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(a.length!==s)throw new q(`RNN Layer has ${s} state(s) but was passed ${a.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");let i={training:n},o=h8((p,c)=>{let m=this.cell.call([p].concat(c),i);return[m[0],m.slice(1)]},e,a,this.goBackwards,r,null,this.unroll,this.returnSequences),l=o[0],u=o[1],d=o[2];this.stateful&&this.resetStates(d,n);let h=this.returnSequences?u:l;return this.returnState?[h].concat(d):h})}getInitialState(e){return X(()=>{let t=Ot(e.shape);return t=ke(t,[1,2]),t=Ph(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(r=>r>1?Ug(t,[1,r]):t):this.cell.stateSize>1?[Ug(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 r=this.cell.getConfig();return this.getClassName()===c8.className&&(t.cell={className:this.cell.getClassName(),config:r}),{...r,...e,...t}}static fromConfig(e,t,r={}){let n=t.cell,a=fa(n,r);return new e(Object.assign(t,{cell:a}))}},ss=c8;ss.className="RNN";ue.registerClass(ss);var Wh=class extends st{},Sm=class extends Wh{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,gr(this.units,"units"),this.activation=js(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=$t(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=$t(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=$t(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Ft(e.kernelRegularizer),this.recurrentRegularizer=Ft(e.recurrentRegularizer),this.biasRegularizer=Ft(e.biasRegularizer),this.kernelConstraint=lr(e.kernelConstraint),this.recurrentConstraint=lr(e.recurrentConstraint),this.biasConstraint=lr(e.biasConstraint),this.dropout=Ou([1,Us([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Ou([1,Us([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=mt(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 X(()=>{if(e=e,e.length!==2)throw new q(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let r=e[1];e=e[0];let n=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Hs({ones:()=>Pn(e),rate:this.dropout,training:n,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Hs({ones:()=>Pn(r),rate:this.recurrentDropout,training:n,dropoutFunc:this.dropoutFunc}));let a,s=this.dropoutMask,i=this.recurrentDropoutMask;s!=null?a=Ma(L(e,s),this.kernel.read()):a=Ma(e,this.kernel.read()),this.bias!=null&&(a=va(a,this.bias.read())),i!=null&&(r=L(r,i));let o=le(a,Ma(r,this.recurrentKernel.read()));return this.activation!=null&&(o=this.activation.apply(o)),[o,o]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Gs(this.activation),useBias:this.useBias,kernelInitializer:zt(this.kernelInitializer),recurrentInitializer:zt(this.recurrentInitializer),biasInitializer:zt(this.biasInitializer),kernelRegularizer:vt(this.kernelRegularizer),recurrentRegularizer:vt(this.recurrentRegularizer),biasRegularizer:vt(this.biasRegularizer),activityRegularizer:vt(this.activityRegularizer),kernelConstraint:or(this.kernelConstraint),recurrentConstraint:or(this.recurrentConstraint),biasConstraint:or(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return{...e,...t}}};Sm.className="SimpleRNNCell";ue.registerClass(Sm);var b5=class extends ss{constructor(e){e.cell=new Sm(e),super(e)}call(e,t){return X(()=>{this.cell.dropoutMask!=null&&(ee(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(ee(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let r=t==null?null:t.mask,n=t==null?null:t.training,a=t==null?null:t.initialState;return super.call(e,{mask:r,training:n,initialState:a})})}static fromConfig(e,t){return new e(t)}};b5.className="SimpleRNN";ue.registerClass(b5);var Cm=class extends Wh{constructor(e){if(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",e.resetAfter)throw new q("GRUCell does not support reset_after parameter set to true.");this.units=e.units,gr(this.units,"units"),this.activation=js(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=js(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=$t(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=$t(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=$t(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Ft(e.kernelRegularizer),this.recurrentRegularizer=Ft(e.recurrentRegularizer),this.biasRegularizer=Ft(e.biasRegularizer),this.kernelConstraint=lr(e.kernelConstraint),this.recurrentConstraint=lr(e.recurrentConstraint),this.biasConstraint=lr(e.biasConstraint),this.dropout=Ou([1,Us([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Ou([1,Us([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=mt(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 X(()=>{if(e=e,e.length!==2)throw new q(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let r=t.training==null?!1:t.training,n=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Hs({ones:()=>Pn(e),rate:this.dropout,training:r,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Hs({ones:()=>Pn(n),rate:this.recurrentDropout,training:r,count:3,dropoutFunc:this.dropoutFunc}));let a=this.dropoutMask,s=this.recurrentDropoutMask,i,o,l;0<this.dropout&&this.dropout<1&&(e=L(e,a[0]));let u=Ma(e,this.kernel.read());this.useBias&&(u=va(u,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(n=L(n,s[0]));let d=this.recurrentKernel.read(),[h,p]=Yt(d,[2*this.units,this.units],d.rank-1),c=Ma(n,h),[m,f,g]=Yt(u,3,u.rank-1),[y,A]=Yt(c,2,c.rank-1);i=this.recurrentActivation.apply(le(m,y)),o=this.recurrentActivation.apply(le(f,A));let x=Ma(L(o,n),p);l=this.activation.apply(le(g,x));let b=le(L(i,n),L(le(1,Mt(i)),l));return[b,b]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Gs(this.activation),recurrentActivation:Gs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:zt(this.kernelInitializer),recurrentInitializer:zt(this.recurrentInitializer),biasInitializer:zt(this.biasInitializer),kernelRegularizer:vt(this.kernelRegularizer),recurrentRegularizer:vt(this.recurrentRegularizer),biasRegularizer:vt(this.biasRegularizer),activityRegularizer:vt(this.activityRegularizer),kernelConstraint:or(this.kernelConstraint),recurrentConstraint:or(this.recurrentConstraint),biasConstraint:or(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return{...e,...t}}};Cm.className="GRUCell";ue.registerClass(Cm);var v5=class extends ss{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 Cm(e),super(e)}call(e,t){return X(()=>{this.cell.dropoutMask!=null&&(ee(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(ee(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let r=t==null?null:t.mask,n=t==null?null:t.training,a=t==null?null:t.initialState;return super.call(e,{mask:r,training:n,initialState:a})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};v5.className="GRU";ue.registerClass(v5);var Vh=class extends Wh{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,gr(this.units,"units"),this.activation=js(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=js(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=$t(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=$t(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=$t(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=lr(e.kernelConstraint),this.recurrentConstraint=lr(e.recurrentConstraint),this.biasConstraint=lr(e.biasConstraint),this.dropout=Ou([1,Us([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Ou([1,Us([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;e=mt(e);let r=e[e.length-1];this.kernel=this.addWeight("kernel",[r,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 n;if(this.useBias){if(this.unitForgetBias){let a=this.biasInitializer,s=this.units;n=new(t=class extends Zn{apply(i,o){let l=a.apply([s]),u=new hm().apply([s]),d=a.apply([s*2]);return d4(d4(l,u),d)}},t.className="CustomInit",t)}else n=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,n,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return X(()=>{let r=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 n=e[1],a=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Hs({ones:()=>Pn(e),rate:this.dropout,training:r,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Hs({ones:()=>Pn(n),rate:this.recurrentDropout,training:r,count:4,dropoutFunc:this.dropoutFunc}));let s=this.dropoutMask,i=this.recurrentDropoutMask,o,l,u,d;0<this.dropout&&this.dropout<1&&(e=L(e,s[0]));let h=Ma(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(n=L(n,i[0])),h=le(h,Ma(n,this.recurrentKernel.read())),this.useBias&&(h=va(h,this.bias.read()));let[p,c,m,f]=Yt(h,4,h.rank-1);o=this.recurrentActivation.apply(p),l=this.recurrentActivation.apply(c),u=le(L(l,a),L(o,this.activation.apply(m))),d=this.recurrentActivation.apply(f);let g=L(d,this.activation.apply(u));return[g,g,u]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Gs(this.activation),recurrentActivation:Gs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:zt(this.kernelInitializer),recurrentInitializer:zt(this.recurrentInitializer),biasInitializer:zt(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:vt(this.kernelRegularizer),recurrentRegularizer:vt(this.recurrentRegularizer),biasRegularizer:vt(this.biasRegularizer),activityRegularizer:vt(this.activityRegularizer),kernelConstraint:or(this.kernelConstraint),recurrentConstraint:or(this.recurrentConstraint),biasConstraint:or(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return{...e,...t}}};Vh.className="LSTMCell";ue.registerClass(Vh);var w5=class extends ss{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 Vh(e),super(e)}call(e,t){return X(()=>{this.cell.dropoutMask!=null&&(ee(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(ee(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let r=t==null?null:t.mask,n=t==null?null:t.training,a=t==null?null:t.initialState;return super.call(e,{mask:r,training:n,initialState:a})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};w5.className="LSTM";ue.registerClass(w5);var Tm=class extends Wh{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 X(()=>{e=e;let r=e.slice(1),n=[];for(let i of this.cells.slice().reverse())Array.isArray(i.stateSize)?n.push(r.splice(0,i.stateSize.length)):n.push(r.splice(0,1));n.reverse();let a=[],s;for(let i=0;i<this.cells.length;++i){let o=this.cells[i];r=n[i],i===0?s=[e[0]].concat(r):s=[s[0]].concat(r),s=o.call(s,t),a.push(s.slice(1))}r=[];for(let i of a.slice().reverse())r.push(...i);return[s[0]].concat(r)})}build(e){jg(e)&&(e=e[0]),e=e;let t;this.cells.forEach((r,n)=>{No(`RNNCell_${n}`,()=>{r.build(e),Array.isArray(r.stateSize)?t=r.stateSize[0]:t=r.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){let e=super.getConfig(),t=n=>({className:n.getClassName(),config:n.getConfig()}),r={cells:this.cells.map(t)};return{...e,...r}}static fromConfig(e,t,r={}){let n=[];for(let a of t.cells)n.push(fa(a,r));return new e({cells:n})}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 r of this.cells)t.push(...r.trainableWeights);return t.concat(e)}return e}getWeights(){let e=[];for(let t of this.cells)e.push(...t.weights);return Hg(e)}setWeights(e){let t=[];for(let r of this.cells){let n=r.weights.length,a=e.splice(n);for(let s=0;s<r.weights.length;++s)t.push([r.weights[s],a[s]])}G3(t)}};Tm.className="StackedRNNCells";ue.registerClass(Tm);function Hs(e){let{ones:t,rate:r,training:n=!1,count:a=1,dropoutFunc:s}=e,i=()=>s!=null?s(t(),r):xw(t(),r),o=()=>zh(i,t,n);return!a||a<=1?mr(o().clone()):Array(a).fill(void 0).map(o).map(l=>mr(l.clone()))}var f8=class extends ss{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 Zt({ndim:5})]}call(e,t){return X(()=>{if(this.cell.dropoutMask!=null&&(ee(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(ee(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new q("ConvRNN2D cell does not support constants");let r=t==null?null:t.mask,n=t==null?null:t.training,a=t==null?null:t.initialState;return super.call(e,{mask:r,training:n,initialState:a})})}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 X(()=>{let{stateSize:t}=this.cell,r=e.shape,n=this.computeSingleOutputShape(r),a=[n[0],...n.slice(2)],s=Ot(a);return Array.isArray(t)?Array(t.length).fill(s):[s]})}resetStates(e,t=!1){X(()=>{if(!this.stateful)throw new ja("Cannot call resetStates() on an RNN Layer that is not stateful.");let r=this.inputSpec[0].shape,n=this.computeSingleOutputShape(r),a=[n[0],...n.slice(2)];if(r[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(()=>Ot(a)):this.states_=[Ot(a)];else if(e==null)ee(this.states_),this.keptStates!=null&&(ee(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Ot(a)):this.states_[0]=Ot(a);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()):ee(this.states_);for(let s=0;s<this.states_.length;++s){let i=e[s],o=a;if(!v.arraysEqual(i.shape,o))throw new q(`State ${s} is incompatible with layer ${this.name}: expected shape=${o}, received shape=${i.shape}`);this.states_[s]=i}}this.states_=this.states_.map(s=>mr(s.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:r,kernelSize:n,padding:a,strides:s,dilationRate:i}=this.cell,o=t==="channelsFirst",l=e[o?3:2],u=e[o?4:3],d=ma(l,n[0],a,s[0],i[0]),h=ma(u,n[1],a,s[1],i[1]);return[...e.slice(0,2),...o?[r,d,h]:[d,h,r]]}};f8.className="ConvRNN2D";var Nm=class extends Vh{constructor(e){let{filters:t,kernelSize:r,strides:n,padding:a,dataFormat:s,dilationRate:i}=e;super({...e,units:t}),this.filters=t,gr(this.filters,"filters"),this.kernelSize=Cu(r,2,"kernelSize"),this.kernelSize.forEach(o=>gr(o,"kernelSize")),this.strides=Cu(n||1,2,"strides"),this.strides.forEach(o=>gr(o,"strides")),this.padding=a||"valid",Bn(this.padding),this.dataFormat=s||"channelsLast",jt(this.dataFormat),this.dilationRate=Cu(i||1,2,"dilationRate"),this.dilationRate.forEach(o=>gr(o,"dilationRate"))}build(e){var t;e=mt(e);let r=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[r]==null)throw new q(`The channel dimension of the input should be defined. Found ${e[r]}`);let n=e[r],a=4,s=this.kernelSize.concat([n,this.filters*a]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let i=this.kernelSize.concat([this.filters,this.filters*a]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",i,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let o;if(this.unitForgetBias){let l=this.biasInitializer,u=this.filters;o=new(t=class extends Zn{apply(d,h){let p=l.apply([u]),c=cn([u]),m=l.apply([u*2]);return O3([p,c,m])}},t.className="CustomInit",t)}else o=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*a],null,o,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return X(()=>{if(e.length!==3)throw new q(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let r=t.training||!1,n=e[0],a=e[1],s=e[2],i=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Hs({ones:()=>Pn(n),rate:this.dropout,training:r,count:i,dropoutFunc:this.dropoutFunc}));let o=this.dropoutMask,l=(V,re,Q)=>!re||!re[Q]?V:L(re[Q],V),u=l(n,o,0),d=l(n,o,1),h=l(n,o,2),p=l(n,o,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Hs({ones:()=>Pn(a),rate:this.recurrentDropout,training:r,count:i,dropoutFunc:this.dropoutFunc}));let c=this.recurrentDropoutMask,m=l(a,c,0),f=l(a,c,1),g=l(a,c,2),y=l(a,c,3),A=3,[x,b,w,I]=Yt(this.kernel.read(),i,A),[T,E,R,F]=this.useBias?Yt(this.bias.read(),i):[null,null,null,null];u=this.inputConv(u,x,T,this.padding),d=this.inputConv(d,b,E,this.padding),h=this.inputConv(h,w,R,this.padding),p=this.inputConv(p,I,F,this.padding);let[$,S,z,O]=Yt(this.recurrentKernel.read(),i,A);m=this.recurrentConv(m,$),f=this.recurrentConv(f,S),g=this.recurrentConv(g,z),y=this.recurrentConv(y,O);let j=this.recurrentActivation.apply(le(u,m)),K=this.recurrentActivation.apply(le(d,f)),D=le(L(K,s),L(j,this.activation.apply(le(h,g)))),Y=L(this.recurrentActivation.apply(le(p,y)),this.activation.apply(D));return[Y,Y,D]})}getConfig(){let{units:e,...t}=super.getConfig(),r={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return{...t,...r}}inputConv(e,t,r,n){let a=Ls(e,t,this.strides,n||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return r?va(a,r,this.dataFormat):a}recurrentConv(e,t){return Ls(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};Nm.className="ConvLSTM2DCell";ue.registerClass(Nm);var k5=class extends f8{constructor(e){let t=new Nm(e);super({...e,cell:t})}static fromConfig(e,t){return new e(t)}};k5.className="ConvLSTM2D";ue.registerClass(k5);var Em=class extends st{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,r=[];for(let n=0;n<this.noiseShape.length;++n)r.push(this.noiseShape[n]==null?t[n]:this.noiseShape[n]);return r}call(e,t){return X(()=>{this.invokeCallHook(e,t);let r=je(e);if(0<this.rate&&this.rate<1){let n=t.training==null?!1:t.training,a=this.getNoiseShape(r);return zh(()=>xw(r,this.rate,a,this.seed),()=>r,n)}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()}};Em.className="Dropout";ue.registerClass(Em);var I5=class extends Em{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};I5.className="SpatialDropout1D";ue.registerClass(I5);var S5=class extends st{constructor(e){if(super(e),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,gr(this.units,"units"),this.activation=js(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=$t(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=$t(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=lr(e.kernelConstraint),this.biasConstraint=lr(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=mt(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=mt(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return X(()=>{this.invokeCallHook(e,t);let r=je(e),n=hw(this.activation.getClassName()),a;return n!=null?a=Ma(r,this.kernel.read(),n,this.bias?this.bias.read():null):(a=Ma(r,this.kernel.read()),this.bias!=null&&(a=va(a,this.bias.read())),this.activation!=null&&(a=this.activation.apply(a))),a})}getConfig(){let e={units:this.units,activation:Gs(this.activation),useBias:this.useBias,kernelInitializer:zt(this.kernelInitializer),biasInitializer:zt(this.biasInitializer),kernelRegularizer:vt(this.kernelRegularizer),biasRegularizer:vt(this.biasRegularizer),activityRegularizer:vt(this.activityRegularizer),kernelConstraint:or(this.kernelConstraint),biasConstraint:or(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};S5.className="Dense";ue.registerClass(S5);var C5=class extends st{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=mt(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],Ms(e,1)]}call(e,t){return X(()=>{this.invokeCallHook(e,t);let r=je(e);if(this.dataFormat==="channelsFirst"&&r.rank>1){let n=[0];for(let a=2;a<r.rank;++a)n.push(a);n.push(1),r=tt(r,n)}return cB(r)})}getConfig(){let e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);let t=super.getConfig();return Object.assign(e,t),e}};C5.className="Flatten";ue.registerClass(C5);var T5=class extends st{constructor(e){super(e),this.supportsMasking=!0,this.activation=js(e.activation)}call(e,t){return X(()=>{this.invokeCallHook(e,t);let r=je(e);return this.activation.apply(r)})}getConfig(){let e={activation:Gs(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};T5.className="Activation";ue.registerClass(T5);var N5=class extends st{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 X(()=>(e=je(e),pB(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};N5.className="RepeatVector";ue.registerClass(N5);var E5=class extends st{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 r="Total size of new array must be unchanged.",n=t.slice(),a=1,s=null;for(let o=0;o<n.length;++o){let l=n[o];if(this.isUnknown(l))if(s===null)s=o;else throw new q("Can only specifiy one unknown dimension.");else a*=l}let i=Ms(e);if(s!==null){if(a===0||i%a!==0)throw new q(r);n[s]=i/a}else if(i!==a)throw new q(r);return n}computeOutputShape(e){let t=!1;for(let r=0;r<e.length;++r)if(this.isUnknown(e[r])){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 X(()=>{this.invokeCallHook(e,t);let r=je(e),n=r.shape,a=n.slice(0,1).concat(this.fixUnknownDimension(n.slice(1),this.targetShape));return U(r,a)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};E5.className="Reshape";ue.registerClass(E5);var R5=class extends st{constructor(e){if(super(e),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=ya(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 Zt({ndim:this.dims.length+1})]}computeOutputShape(e){e=mt(e);let t=e.slice();return this.dims.forEach((r,n)=>{t[n+1]=e[r]}),t}call(e,t){return tt(je(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};R5.className="Permute";ue.registerClass(R5);var $5=class extends st{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 r=je(e),n=-1;return _0(_u(r,this.maskValue),n)}call(e,t){return X(()=>{this.invokeCallHook(e,t);let r=je(e),n=-1,a=!0,s=_0(_u(r,this.maskValue),n,a);return L(r,me(s,r.dtype))})}};$5.className="Masking";ue.registerClass($5);var M5=class extends st{constructor(e){if(super(e),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(Tt(e.inputLength))}this.inputDim=e.inputDim,gr(this.inputDim,"inputDim"),this.outputDim=e.outputDim,gr(this.outputDim,"outputDim"),this.embeddingsInitializer=$t(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Ft(e.embeddingsRegularizer),this.activityRegularizer=Ft(e.activityRegularizer),this.embeddingsConstraint=lr(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 X(()=>this.maskZero?(e=je(e),_u(e,at(e))):null)}computeOutputShape(e){if(e=mt(e),this.inputLength==null)return[...e,this.outputDim];let t=Tt(this.inputLength);if(t.length!==e.length-1)throw new q(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let r=0;for(let n=0;n<t.length;++n){let a=t[n],s=e[n+1];if(a!=null&&s!=null&&a!==s)throw new q(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);a==null&&(t[r]=s),r++}}return[e[0],...t,this.outputDim]}call(e,t){return X(()=>{this.invokeCallHook(e,t);let r=je(e);r.dtype!=="int32"&&(r=dm(r,"int32"));let n=Aw(this.embeddings.read(),U(r,[r.size]));return U(n,mt(this.computeOutputShape(r.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:zt(this.embeddingsInitializer),embeddingsRegularizer:vt(this.embeddingsRegularizer),activityRegularizer:vt(this.activityRegularizer),embeddingsConstraint:or(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};M5.className="Embedding";ue.registerClass(M5);var zl=class extends st{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 r=e.slice(0,e.length-t.length);for(let n=0;n<t.length;++n){let a=e[e.length-t.length+n],s=t[n];if(a==null||s==null||a<0||s<0)r.push(null);else if(a===1)r.push(s);else if(s===1)r.push(a);else{if(a!==s)throw new q("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));r.push(a)}}return r}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[mt(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 a of e)a!=null&&a[0]!==null&&t.push(a[0]);if(t=$s(t),t.length>1)throw new q(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let r=e[0]==null?null:e[0].slice(1);for(let a=1;a<e.length;++a){let s=e[a]==null?null:e[a].slice(1);r=this.computeElementwiseOpOutputShape(r,s)}let n=e.map(a=>a.length);e.indexOf(null)===-1&&$s(n).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return X(()=>{if(e=e,this.reshapeRequired){let r=[],n=e.map(a=>a.rank);if(n.indexOf(null)===-1){let a=Us(n);for(let s of e){let i=s.rank;for(let o=0;o<a-i;++o)s=Ph(s,1);r.push(s)}return this.mergeFunction(r)}else{let a=!1;for(let o of e){let l=o.rank;if(l==null){let u=o.shape,d=u[0],h=u.slice(1).concat([d]),p=U(o,[d].concat(Ms(u.slice(1))));p=tt(p,[1,0]),p=U(p,h),r.push(p),a=!0}else if(l>1){let u=ya(1,l).concat([0]);r.push(tt(o,u)),a=!0}else r.push(o)}let s=this.mergeFunction(r),i=s.rank;if(a){if(i==null){let o=s.shape,l=o.length,u=o[l-1],d=[u].concat(o.slice(0,o.length-1));s=U(tt(U(s,[-1,u]),[1,0]),d)}else if(i>1){let o=[i-1].concat(ya(0,i-1));s=tt(s,o)}}return s}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let n=1;n<e.length;++n){let a=e[n]==null?null:e[n].slice(1);t=this.computeElementwiseOpOutputShape(t,a)}let r=[];for(let n of e)n!=null&&n[0]!==null&&r.push(n[0]);return r=$s(r),r.length===1?t=r.concat(t):t=[null].concat(t),t}computeMask(e,t){return X(()=>{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(n=>n==null))return null;t=t.map(n=>n==null?n:Kt(n,0));let r=t[0];for(let n=1;n<t.length-1;++n)r=ga(r,t[n]);return r})}},F5=class extends zl{constructor(e){super(e)}mergeFunction(e){return X(()=>{let t=e[0].clone();for(let r=1;r<e.length;++r)t=le(t,e[r]);return t})}};F5.className="Add";ue.registerClass(F5);var _5=class extends zl{constructor(e){super(e)}mergeFunction(e){return X(()=>{let t=e[0].clone();for(let r=1;r<e.length;++r)t=L(t,e[r]);return t})}};_5.className="Multiply";ue.registerClass(_5);var P5=class extends zl{constructor(e){super(e)}mergeFunction(e){return X(()=>{let t=e[0].clone();for(let r=1;r<e.length;++r)t=le(t,e[r]);return L(1/e.length,t)})}};P5.className="Average";ue.registerClass(P5);var O5=class extends zl{constructor(e){super(e)}mergeFunction(e){return X(()=>{let t=e[0];for(let r=1;r<e.length;++r)t=rs(t,e[r]);return t})}};O5.className="Maximum";ue.registerClass(O5);var z5=class extends zl{constructor(e){super(e)}mergeFunction(e){return X(()=>{let t=e[0];for(let r=1;r<e.length;++r)t=$h(t,e[r]);return t})}};z5.className="Minimum";ue.registerClass(z5);var D5=class extends zl{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 n of e)if(n!=null){t=!1;break}if(t)return;let r=[];for(let n=0;n<e.length;++n){let a=e[n].slice();a.splice(this.axis,1);let s=!1;for(let i of r)if(v.arraysEqual(i,a)){s=!0;break}s||r.push(a)}if(r.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 X(()=>O3(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,r=t[0].slice(),n=this.axis<0?r.length+this.axis:this.axis;for(let a of t.slice(1)){if(r[n]==null||a[n]==null){r[n]=null;break}r[n]+=a[n]}return r}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 X(()=>{let r=!0;if(t.forEach(s=>{if(s!=null){r=!1;return}}),r)return null;let n=[];for(let s=0;s<e.length;++s)t[s]==null?n.push(me(Pn(e[s]),"bool")):t[s].rank<e[s].rank?n.push(Kt(t[s],-1)):n.push(t[s]);let a=St(n,this.axis);return Yy(a,-1,!1)})}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};D5.className="Concatenate";ue.registerClass(D5);function Cp(e,t){for(;e<0;)e+=t;return e}function nG(e,t,r){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 r=="number"&&(r=[r,r]),e.dtype==="complex64"||t.dtype==="complex64")throw new Ve("batchDot is not implemented for complex64-type Tensors yet.");let n=e.shape.length,a=t.shape.length;r==null&&(r=[n-1,a-2]);let s=r;return X(()=>{let i;if(n>a){i=n-a;let l=[];for(let u=0;u<i;++u)l.push(1);t=U(t,t.shape.concat(l))}else if(a>n){i=a-n;let l=[];for(let u=0;u<i;++u)l.push(1);e=U(e,e.shape.concat(l))}else i=0;let o;if(e.shape.length===2&&t.shape.length===2)s[0]===s[1]?o=ke(L(e,t),s[0]):o=ke(L(tt(e,[1,0]),t),s[1]);else{let l=s[0]!==e.shape.length-1,u=s[1]===t.shape.length-1;o=Ye(e,t,l,u)}if(i>0){let l;n>a?l=n+a-3:l=n-1;let u=[];for(let d=l;d<l+i;++d)u.push(d);o=et(o,u)}return o.shape.length===1&&(o=Kt(o,1)),o})}var L5=class extends zl{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],r=e[1];if(t.length>3||r.length>3)throw new Ve("Dot layer does not support tensors of 4D or higher rank yet.");let n=this.interpretAxes(t,r);if(t[n[0]]!==r[n[1]])throw new q(`Dimension incompatibility: ${t[n[0]]} !== ${r[n[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],r=e[1],n;return Array.isArray(this.axes)?n=this.axes.map((a,s)=>Cp(a,e[s].shape.length)):n=[Cp(this.axes,t.shape.length),Cp(this.axes,r.shape.length)],this.normalize&&(t=W0(t,n[0]),r=W0(r,n[1])),nG(t,r,n)}interpretAxes(e,t){let r;return Array.isArray(this.axes)?r=this.axes:r=[Cp(this.axes,e.length),Cp(this.axes,t.length)],r}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(),r=e[1].slice();if(t.length>3||r.length>3)throw new Ve("Dot layer does not support tensors of 4D or higher rank yet.");let n=this.interpretAxes(t,r);t.splice(n[0],1),r.splice(n[1],1),r.splice(0,1);let a=t.concat(r);return a.length===1&&a.push(1),a}computeMask(e,t){return null}getConfig(){let e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}};L5.className="Dot";ue.registerClass(L5);var B5=class extends st{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 X(()=>{this.invokeCallHook(e,t);let r=je(e);return zh(()=>le(pm(r.shape,0,this.stddev),r),()=>r,t.training||!1)})}};B5.className="GaussianNoise";ue.registerClass(B5);var W5=class extends st{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 X(()=>{this.invokeCallHook(e,t);let r=je(e);return this.rate>0&&this.rate<1?zh(()=>{let n=Math.sqrt(this.rate/(1-this.rate));return L(r,pm(r.shape,1,n))},()=>r,t.training||!1):r})}};W5.className="GaussianDropout";ue.registerClass(W5);var V5=class extends st{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||je(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 X(()=>{if(this.rate<1&&this.rate>0){let r=this._getNoiseShape(e);return zh(()=>{let n=je(e),a=1.6732632423543772,s=1.0507009873554805,i=-a*s,o=Ml(Id(r),this.rate);o=dm(o,"float32");let l=((1-this.rate)*(1+this.rate*i**2))**-.5,u=-l*i*this.rate,d=le(L(n,o),L(le(o,-1),i));return le(L(d,l),u)},()=>je(e),t.training||!1)}return e})}};V5.className="AlphaDropout";ue.registerClass(V5);function eh(e,t,r,n,a,s=.001){let i;if(e.rank===2)i=av(e,t,r,n,a,s);else if(e.rank===3)i=sv(e,t,r,n,a,s);else if(e.rank===4)i=iv(e,t,r,n,a,s);else throw new Ve(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return i}function aG(e,t,r,n,a=.001){return X(()=>{let s=Hf(e,n),i=s.mean,o=s.variance;return[eh(e,i,o,r,t,a),i,o]})}function sG(e,t,r,n,a=.001){return X(()=>{let s=Hf(e,n),i=s.mean,o=s.variance,l=[];for(let c of ya(0,e.rank))n.indexOf(c)!==-1?l.push(1):l.push(e.shape[c]);let u=U(i,l),d=U(o,l),h=t==null?null:U(t,l),p=r==null?null:U(r,l);return[eh(e,u,d,p,h,a),i,o]})}function iG(e,t,r,n,a=.001){return v.arraysEqual(n.slice().sort(),ya(0,e.rank-1))?aG(e,t,r,n,a):sG(e,t,r,n,a)}var U5=class extends st{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=$t(e.betaInitializer||"zeros"),this.gammaInitializer=$t(e.gammaInitializer||"ones"),this.movingMeanInitializer=$t(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=$t(e.movingVarianceInitializer||"ones"),this.betaConstraint=lr(e.betaConstraint),this.gammaConstraint=lr(e.gammaConstraint),this.betaRegularizer=Ft(e.betaRegularizer),this.gammaRegularizer=Ft(e.gammaRegularizer)}build(e){e=mt(e);let t=this.axis>=0?this.axis:this.axis+e.length,r=e[t];if(r==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 Zt({ndim:e.length,axes:{[t]:r}})];let n=[r];this.scale&&(this.gamma=this.addWeight("gamma",n,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",n,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",n,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",n,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return X(()=>{let r=t.training==null?!1:t.training,n=je(e),a=n.shape,s=a.length,i=ya(0,s),o=this.axis>=0?this.axis:this.axis+s;i.splice(o,1);let l=Oo(1,s);l[o]=a[o];let u=i.slice();u.sort();let d=!v.arraysEqual(u,ya(0,s).slice(0,s-1)),h=()=>{if(d){let g=U(this.movingMean.read(),l),y=U(this.movingVariance.read(),l),A=this.center?U(this.beta.read(),l):null,x=this.scale?U(this.gamma.read(),l):null;return eh(n,g,y,A,x,this.epsilon)}else return eh(n,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!r)return h();let[p,c,m]=iG(n,this.gamma.read(),this.beta.read(),i,this.epsilon),f=(g,y,A)=>{X(()=>{let x=1-A,b=g.read(),w=L(ce(b,y),x);g.write(ce(b,w))})};return f(this.movingMean,c,this.momentum),f(this.movingVariance,m,this.momentum),p})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:zt(this.betaInitializer),gammaInitializer:zt(this.gammaInitializer),movingMeanInitializer:zt(this.movingMeanInitializer),movingVarianceInitializer:zt(this.movingVarianceInitializer),betaRegularizer:vt(this.betaRegularizer),gammaRegularizer:vt(this.gammaRegularizer),betaConstraint:or(this.betaConstraint),gammaConstraint:or(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};U5.className="BatchNormalization";ue.registerClass(U5);var G5=class extends st{constructor(e){if(e==null&&(e={}),super(e),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=$t(e.betaInitializer||"zeros"),this.gammaInitializer=$t(e.gammaInitializer||"ones"),this.betaRegularizer=Ft(e.betaRegularizer),this.gammaRegularizer=Ft(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=mt(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let a=0;a<this.axis.length;++a)this.axis[a]<0&&(this.axis[a]+=t);for(let a of this.axis)if(a<0||a>=t)throw new Error(`Invalid axis: ${a}`);if(this.axis.length!==$s(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);let r=this.axis.map(a=>e[a]),n=!0;this.scale?this.gamma=this.addWeight("gamma",r,"float32",this.gammaInitializer,this.gammaRegularizer,n):this.gamma=null,this.center?this.beta=this.addWeight("beta",r,"float32",this.betaInitializer,this.betaRegularizer,n):this.beta=null,this.built=!0}call(e,t){let r=je(e),n=r.shape,a=n.length;return X(()=>{let{mean:s,variance:i}=Hf(r,this.axis,!0),o=Oo(1,a);for(let c of this.axis)o[c]=n[c];let l=c=>c!=null&&c.shape.length!==a?U(c,o):c,u=this.scale?l(this.gamma.read()):null,d=this.center?l(this.beta.read()):null,h=[],p=[];for(let c=0;c<a;++c)this.axis.indexOf(c)!==-1?(h.push(n[c]),p.push(1)):(h.push(1),p.push(n[c]));return s=jn(s,h),i=jn(i,h),u!=null&&(u=jn(u,p)),d!=null&&(d=jn(d,p)),eh(r,s,i,d,u,this.epsilon)})}getConfig(){let e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:zt(this.betaInitializer),gammaInitializer:zt(this.gammaInitializer),betaRegularizer:vt(this.betaRegularizer),gammaRegularizer:vt(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}};G5.className="LayerNormalization";ue.registerClass(G5);function oG(e,t,r){return X(()=>{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(r==null&&(r=Aa()),r!=="channelsLast"&&r!=="channelsFirst")throw new q(`Unknown data format: ${r}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let n;return r==="channelsFirst"?n=[[0,0],[0,0],t[0],t[1]]:n=[[0,0],t[0],t[1],[0,0]],Xn(e,n)})}var j5=class extends st{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?Aa():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,r;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],r=[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.`);r=e.padding[1]}this.padding=[t,r]}this.inputSpec=[new Zt({ndim:4})]}computeOutputShape(e){e=mt(e);let t,r;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?r=e[3]+this.padding[1][0]+this.padding[1][1]:r=null,[e[0],e[1],t,r]):(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?r=e[2]+this.padding[1][0]+this.padding[1][1]:r=null,[e[0],t,r,e[3]])}call(e,t){return X(()=>oG(je(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};j5.className="ZeroPadding2D";ue.registerClass(j5);function Rm(e,t,r,n,a,s){return X(()=>{jt(a),fw(s),Bn(n),r==null&&(r=[1,1]),n==null&&(n="valid"),a==null&&(a=Aa()),s==null&&(s="max"),e=p5(e,a);let i,o=n==="same"?"same":"valid";return s==="max"?i=jf(e,t,r,o):i=zf(e,t,r,o),a==="channelsFirst"&&(i=tt(i,[0,3,1,2])),i})}function m8(e,t,r,n,a,s){return X(()=>{jt(a),fw(s),Bn(n),r==null&&(r=[1,1,1]),n==null&&(n="valid"),a==null&&(a=Aa()),s==null&&(s="max"),e=i8(e,a);let i,o=n==="same"?"same":"valid";return s==="max"?i=f3(e,t,r,o):i=Qy(e,t,r,o),a==="channelsFirst"&&(i=tt(i,[0,4,1,2,3])),i})}var g8=class extends st{constructor(e){if(e.poolSize==null&&(e.poolSize=2),super(e),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(gr(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)}`);gr(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,Bn(this.padding),this.inputSpec=[new Zt({ndim:3})]}computeOutputShape(e){e=mt(e);let t=ma(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return X(()=>{this.invokeCallHook(e,t),e=Ph(je(e),2);let r=this.poolingFunction(je(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return et(r,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},H5=class extends g8{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return jt(a),Bn(n),Rm(e,t,r,n,a,"max")}};H5.className="MaxPooling1D";ue.registerClass(H5);var q5=class extends g8{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return jt(a),Bn(n),Rm(e,t,r,n,a,"avg")}};q5.className="AveragePooling1D";ue.registerClass(q5);var y8=class extends st{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2]),super(e),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];gr(this.poolSize,"poolSize"),gr(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),Bn(this.padding),this.inputSpec=[new Zt({ndim:4})]}computeOutputShape(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=ma(t,this.poolSize[0],this.padding,this.strides[0]),r=ma(r,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,r]:[e[0],t,r,e[3]]}call(e,t){return X(()=>(this.invokeCallHook(e,t),this.poolingFunction(je(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}},X5=class extends y8{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return jt(a),Bn(n),Rm(e,t,r,n,a,"max")}};X5.className="MaxPooling2D";ue.registerClass(X5);var K5=class extends y8{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return jt(a),Bn(n),Rm(e,t,r,n,a,"avg")}};K5.className="AveragePooling2D";ue.registerClass(K5);var A8=class extends st{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2,2]),super(e),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];gr(this.poolSize,"poolSize"),gr(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),Bn(this.padding),this.inputSpec=[new Zt({ndim:5})]}computeOutputShape(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2],n=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=ma(t,this.poolSize[0],this.padding,this.strides[0]),r=ma(r,this.poolSize[1],this.padding,this.strides[1]),n=ma(n,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,r,n]:[e[0],t,r,n,e[4]]}call(e,t){return X(()=>(this.invokeCallHook(e,t),this.poolingFunction(je(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}},Z5=class extends A8{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return jt(a),Bn(n),m8(e,t,r,n,a,"max")}};Z5.className="MaxPooling3D";ue.registerClass(Z5);var Y5=class extends A8{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return jt(a),Bn(n),m8(e,t,r,n,a,"avg")}};Y5.className="AveragePooling3D";ue.registerClass(Y5);var x8=class extends st{constructor(e){super(e),this.inputSpec=[new Zt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Ve}},J5=class extends x8{constructor(e){super(e||{})}call(e,t){return X(()=>{let r=je(e);return Vt(r,1)})}};J5.className="GlobalAveragePooling1D";ue.registerClass(J5);var Q5=class extends x8{constructor(e){super(e||{})}call(e,t){return X(()=>{let r=je(e);return yr(r,1)})}};Q5.className="GlobalMaxPooling1D";ue.registerClass(Q5);var b8=class extends st{constructor(e){super(e),this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),this.inputSpec=[new Zt({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}},eA=class extends b8{call(e,t){return X(()=>{let r=je(e);return this.dataFormat==="channelsLast"?Vt(r,[1,2]):Vt(r,[2,3])})}};eA.className="GlobalAveragePooling2D";ue.registerClass(eA);var tA=class extends b8{call(e,t){return X(()=>{let r=je(e);return this.dataFormat==="channelsLast"?yr(r,[1,2]):yr(r,[2,3])})}};tA.className="GlobalMaxPooling2D";ue.registerClass(tA);var v8=class extends st{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,r={}){let n=t.layer,a=fa(n,r);delete t.layer;let s={layer:a};return Object.assign(s,t),new e(s)}},rA=class extends v8{constructor(e){super(e),this.supportsMasking=!0}build(e){if(e=mt(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=mt(e);let t=[e[0]].concat(e.slice(2)),r=this.layer.computeOutputShape(t),n=e[1];return[r[0],n].concat(r.slice(1))}call(e,t){return X(()=>(e=je(e),h8((r,n)=>[je(this.layer.call(r,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};rA.className="TimeDistributed";ue.registerClass(rA);function lG(e){Pl(iB,"BidirectionalMergeMode",e)}var uG="concat",nA=class extends v8{constructor(e){super(e);let t=e.layer.getConfig(),r={};r.className=e.layer.getClassName(),r.config=t,this.forwardLayer=fa(r),t.goBackwards=t.goBackwards!==!0;let n={};if(n.className=e.layer.getClassName(),n.config=t,this.backwardLayer=fa(n),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?uG:e.mergeMode,lG(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,r=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,r)),this.backwardLayer.setWeights(e.slice(r))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let r,n,a;return this.returnState&&(a=t.slice(1)),r=t[0],r=r,this.mergeMode==="concat"?(r[r.length-1]*=2,n=[r]):this.mergeMode==null?n=[r,r.slice()]:n=[r],this.returnState?this.mergeMode==null?n.concat(a).concat(a.slice()):[r].concat(a).concat(a.slice()):rn(n)}apply(e,t){let r=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});let a=p8(e,r,n,this.numConstants);if(e=a.inputs,r=a.initialState,n=a.constants,Array.isArray(e)&&(r=e.slice(1),e=e[0]),(r==null||r.length===0)&&n==null)return super.apply(e,t);let s=[],i=[];if(r!=null){let l=r.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=r,s.push(...r);let u=r.map(d=>new Zt({shape:d.shape}));this.forwardLayer.stateSpec=u.slice(0,l/2),this.backwardLayer.stateSpec=u.slice(l/2),i.push(...u)}if(n!=null)throw new Ve("Support for constants in Bidirectional layers is not implemented yet.");let o=s[0]instanceof pa;for(let l of s)if(l instanceof pa!==o)throw new q("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){let l=[e].concat(s),u=this.inputSpec.concat(i),d=this.inputSpec;this.inputSpec=u;let h=super.apply(l,t);return this.inputSpec=d,h}else return super.apply(e,t)}call(e,t){return X(()=>{let r=t.initialState,n,a;if(r==null)n=this.forwardLayer.call(e,t),a=this.backwardLayer.call(e,t);else{let o=r.slice(0,r.length/2),l=r.slice(r.length/2);n=this.forwardLayer.call(e,Object.assign(t,{initialState:o})),a=this.backwardLayer.call(e,Object.assign(t,{initialState:l}))}let s;this.returnState&&(Array.isArray(n)&&(s=n.slice(1).concat(a.slice(1))),n=n[0],a=a[0]),this.returnSequences&&(a=On(a,1));let i;return this.mergeMode==="concat"?i=O3([n,a]):this.mergeMode==="sum"?i=le(n,a):this.mergeMode==="ave"?i=L(.5,le(n,a)):this.mergeMode==="mul"?i=L(n,a):this.mergeMode==null&&(i=[n,a]),this.returnState?this.mergeMode==null?i.concat(s):[i].concat(s):i})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){No(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),No(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let r;if(this.returnSequences?this.mergeMode==null?r=[t,t]:r=t:this.mergeMode==null?r=[null,null]:r=null,this.returnState){let n=this.forwardLayer.states.map(a=>null);return Array.isArray(r)?r.concat(n).concat(n):[r].concat(n).concat(n)}else return r}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 r=fa(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 n=t;return n.layer=r,new e(n)}};nA.className="Bidirectional";ue.registerClass(nA);function dG(e){return new Td(e)}function pG(e){return new l5(e)}function hG(e){return new s5(e)}function cG(e){return new i5(e)}function fG(e){return new o5(e)}function mG(e){return new d5(e)}function gG(e){return new u5(e)}function yG(e){return new g5(e)}function AG(e){return new km(e)}function xG(e){return new c5(e)}function bG(e){return new Im(e)}function vG(e){return new f5(e)}function wG(e){return new m5(e)}function kG(e){return new y5(e)}function IG(e){return new A5(e)}function SG(e){return new x5(e)}function CG(e){return new T5(e)}function TG(e){return new S5(e)}function NG(e){return new Em(e)}function EG(e){return new I5(e)}function RG(e){return new C5(e)}function $G(e){return new N5(e)}function MG(e){return new E5(e)}function FG(e){return new R5(e)}function _G(e){return new M5(e)}function PG(e){return new F5(e)}function OG(e){return new P5(e)}function zG(e){return new D5(e)}function DG(e){return new O5(e)}function LG(e){return new z5(e)}function BG(e){return new _5(e)}function WG(e){return new L5(e)}function VG(e){return new U5(e)}function UG(e){return new G5(e)}function GG(e){return new j5(e)}function aA(e){return new q5(e)}function jG(e){return aA(e)}function HG(e){return aA(e)}function sA(e){return new K5(e)}function qG(e){return sA(e)}function XG(e){return sA(e)}function iA(e){return new Y5(e)}function KG(e){return iA(e)}function ZG(e){return iA(e)}function YG(e){return new J5(e)}function JG(e){return new eA(e)}function w8(e){return new Q5(e)}function k8(e){return new tA(e)}function I8(e){return new H5(e)}function S8(e){return new X5(e)}function QG(e){return new Z5(e)}function ej(e){return new v5(e)}function tj(e){return new Cm(e)}function rj(e){return new w5(e)}function nj(e){return new Vh(e)}function aj(e){return new b5(e)}function sj(e){return new Sm(e)}function ij(e){return new k5(e)}function oj(e){return new Nm(e)}function lj(e){return new ss(e)}function uj(e){return new Tm(e)}function dj(e){return new nA(e)}function pj(e){return new rA(e)}var hj=w8,cj=k8,fj=I8,mj=S8;function gj(e){return new B5(e)}function yj(e){return new W5(e)}function Aj(e){return new V5(e)}function xj(e){return new $5(e)}var C8={};Be(C8,{MAPE:()=>Rj,MSE:()=>Fj,binaryAccuracy:()=>bj,binaryCrossentropy:()=>vj,categoricalAccuracy:()=>kj,categoricalCrossentropy:()=>Ij,cosineProximity:()=>Tj,mape:()=>$j,meanAbsoluteError:()=>Nj,meanAbsolutePercentageError:()=>Ej,meanSquaredError:()=>Mj,mse:()=>_j,precision:()=>Sj,recall:()=>Cj,sparseCategoricalAccuracy:()=>wj});function bj(e,t){return J3(e,t)}function vj(e,t){return Ow(e,t)}function wj(e,t){return zw(e,t)}function kj(e,t){return Q3(e,t)}function Ij(e,t){return e5(e,t)}function Sj(e,t){return Pw(e,t)}function Cj(e,t){return fU(e,t)}function Tj(e,t){return Y3(e,t)}function Nj(e,t){return bm(e,t)}function Ej(e,t){return Nd(e,t)}function Rj(e,t){return Nd(e,t)}function $j(e,t){return Nd(e,t)}function Mj(e,t){return Ol(e,t)}function Fj(e,t){return Ol(e,t)}function _j(e,t){return Ol(e,t)}var T8={};Be(T8,{modelFromJSON:()=>GU});var N8={};Be(N8,{l1:()=>Oj,l1l2:()=>Pj,l2:()=>zj});function Pj(e){return new Lh(e)}function Oj(e){return JU(e)}function zj(e){return QU(e)}var E8=class extends zu{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof Za))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function i0(e,t){return e<t}function F4(e,t){return e>t}var R8=class extends E8{constructor(e){if(super(),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=i0:this.mode==="max"?this.monitorFunc=F4:this.monitor.indexOf("acc")!==-1?this.monitorFunc=F4:this.monitorFunc=i0,this.monitorFunc===i0&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===i0?1/0:-1/0}async onEpochEnd(e,t){await Cs(t);let r=this.getMonitorValue(t);r!=null&&(this.monitorFunc(r-this.minDelta,this.best)?(this.best=r,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 Dj(e){return new R8(e)}var Lj={earlyStopping:Dj},Bj=Z();Bj.registerFlag("KEEP_INTERMEDIATE_TENSORS",()=>!1,e=>{e&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")});var $8=(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_QINT16=15]="DT_QINT16",e[e.DT_QUINT16=16]="DT_QUINT16",e[e.DT_UINT16=17]="DT_UINT16",e[e.DT_COMPLEX128=18]="DT_COMPLEX128",e[e.DT_HALF=19]="DT_HALF",e[e.DT_RESOURCE=20]="DT_RESOURCE",e[e.DT_VARIANT=21]="DT_VARIANT",e[e.DT_UINT32=22]="DT_UINT32",e[e.DT_UINT64=23]="DT_UINT64",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",e[e.DT_QINT16_REF=115]="DT_QINT16_REF",e[e.DT_QUINT16_REF=116]="DT_QUINT16_REF",e[e.DT_UINT16_REF=117]="DT_UINT16_REF",e[e.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",e[e.DT_HALF_REF=119]="DT_HALF_REF",e[e.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",e[e.DT_VARIANT_REF=121]="DT_VARIANT_REF",e[e.DT_UINT32_REF=122]="DT_UINT32_REF",e[e.DT_UINT64_REF=123]="DT_UINT64_REF",e))($8||{}),_4;(e=>{let t;(r=>{r[r.LEGACY=0]="LEGACY",r[r.V1=1]="V1",r[r.V2=2]="V2"})(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(_4||(_4={}));var oA={};function Wj(e,t){let r={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};oA[e]=r}function M8(e){return oA[e]}function Vj(e){delete oA[e]}function k(e,t,r,n,a){let s=t.inputParams[e];if(s&&s.inputIndexStart!==void 0){let o=s.inputIndexStart,l=s.inputIndexEnd===0?void 0:s.inputIndexEnd===void 0?o+1:s.inputIndexEnd;if(s.type==="tensor")return Br(t.inputNames[s.inputIndexStart],r,n,a);if(s.type==="tensors")return t.inputNames.slice(o,l).map(h=>Br(h,r,n,a));let u=Br(t.inputNames.slice(o)[0],r,n,a),d=u.dataSync();return s.type==="number"?d[0]:v.toNestedArray(u.shape,d)}let i=t.attrParams[e];return i&&i.value}function Br(e,t,r,n){let[a,s]=pn(e);if(n!=null){let o=n.getHashTableHandleByName(a);if(o!=null)return o}let i=r.currentContextIds.find(o=>!!t[H0(a,o)]);return i!==void 0?t[H0(a,i)][s]:void 0}function Uj(e,t,r){return t[H0(e,r.currentContextId)]}function Ra(e,t){let[r,n,a]=pn(e);return[H0(r,t&&t.currentContextId),n,a]}function H0(e,t){return t?`${e}-${t}`:e}function pn(e){let t=e.split(":");if(t.length===1)return[e,0,void 0];let r=t[0],n=t.length===3?t[1]:void 0,a=Number(t[t.length-1]);return[r,a,n]}function m0(e,t,r){let n=k("pad",e,t,r);if(n==="explicit"){n=k("explicitPaddings",e,t,r);let a=[[0,0],[0,0],[0,0],[0,0]];for(let s=0;s<4;s++)a[s][0]=n[s*2],a[s][1]=n[s*2+1];return a}return n}function qa(e){return e.kept?e:Vr(e)}var F8={};Be(F8,{json:()=>Gj});var Gj=[{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}]}],_8={};Be(_8,{json:()=>jj});var jj=[{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}]}],P8={};Be(P8,{json:()=>Hj});var Hj=[{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:"TensorListConcatV2",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"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}],O8={};Be(O8,{json:()=>qj});var qj=[{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",defaultValue:.2}]},{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"}]}],z8={};Be(z8,{json:()=>Xj});var Xj=[{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"}]}],D8={};Be(D8,{json:()=>Kj});var Kj=[{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}]}],L8={};Be(L8,{json:()=>Zj});var Zj=[{tfOpName:"LowerBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{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:"UpperBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{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"}]}],B8={};Be(B8,{json:()=>Yj});var Yj=[{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"}]}],W8={};Be(W8,{json:()=>Jj});var Jj=[{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"}]}],V8={};Be(V8,{json:()=>Qj});var Qj=[{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"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}],U8={};Be(U8,{json:()=>eH});var eH=[{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}]}],G8={};Be(G8,{json:()=>tH});var tH=[{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:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2},{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"}]}],j8={};Be(j8,{json:()=>rH});var rH=[{tfOpName:"EuclideanNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",defaultValue:!1}]},{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}]}],H8={};Be(H8,{json:()=>nH});var nH=[{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:"Cumprod",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"}]},{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"}]}],q8={};Be(q8,{json:()=>aH});var aH=[{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}]}],X8={};Be(X8,{json:()=>sH});var sH=[{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"}]}],K8={};Be(K8,{json:()=>iH});var iH=[{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}]}],Z8={};Be(Z8,{json:()=>oH});var oH=[{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"}]}],Y8={};Be(Y8,{json:()=>lH});var lH=[{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:[]}],P4=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[F8,_8,P8,O8,z8,D8,L8,B8,W8,V8,U8,G8,j8,H8,q8,X8,K8,Z8,Y8],t=[].concat(...e.map(r=>r.json));this.opMappers=t.reduce((r,n)=>(r[n.tfOpName]=n,r),{})}transformGraph(e,t={}){let r=e.node,n=[],a=[],s=[],i=r.reduce((m,f)=>(m[f.name]=this.mapNode(f),f.op.startsWith("Placeholder")?n.push(m[f.name]):f.op==="Const"?a.push(m[f.name]):(f.input==null||f.input.length===0)&&s.push(m[f.name]),m),{}),o=[],l=[],u={},d={};t!=null&&(u=this.mapSignatureEntries(t.inputs),d=this.mapSignatureEntries(t.outputs));let h=Object.keys(i);h.forEach(m=>{let f=i[m];f.inputNames.forEach((g,y)=>{let[A,,x]=Ra(g),b=i[A];if(b.outputs!=null){let w=b.outputs.indexOf(x);if(w!==-1){let I=`${A}:${w}`;f.inputNames[y]=I}}f.inputs.push(b),b.children.push(f)})}),Object.keys(d).length===0?h.forEach(m=>{let f=i[m];f.children.length===0&&l.push(f)}):Object.keys(d).forEach(m=>{let[f]=Ra(m),g=i[f];g!=null&&(g.signatureKey=d[m],l.push(g))}),Object.keys(u).length>0?Object.keys(u).forEach(m=>{let[f]=Ra(m),g=i[f];g&&(g.signatureKey=u[m],o.push(g))}):o=n;let p={};e.library!=null&&e.library.function!=null&&(p=e.library.function.reduce((m,f)=>(m[f.signature.name]=this.mapFunction(f),m),{}));let c={nodes:i,inputs:o,outputs:l,weights:a,placeholders:n,signature:t,functions:p};return s.length>0&&(c.initNodes=s),c}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,r)=>(t[e[r].name]=r,t),{})}mapNode(e){let t=M8(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});let r={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(n=>n.startsWith("^")?n.slice(1):n),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return t.inputs!=null&&(r.inputParams=t.inputs.reduce((n,a)=>(n[a.name]={type:a.type,inputIndexStart:a.start,inputIndexEnd:a.end},n),{})),t.attrs!=null&&(r.attrParams=t.attrs.reduce((n,a)=>{let s=a.type,i;switch(a.type){case"string":i=Qg(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=Qg(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"string[]":i=iy(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=iy(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"number":i=ty(e.attr,a.tfName,a.defaultValue||0),i===void 0&&!!a.tfDeprecatedName&&(i=ty(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"number[]":i=sy(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=sy(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool":i=ey(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=ey(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool[]":i=ly(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=ly(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape":i=ay(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=ay(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape[]":i=oy(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=oy(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype":i=ry(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=ry(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype[]":i=ny(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=ny(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"func":i=O4(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=O4(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${a.type} for op: ${e.op}`)}return n[a.name]={value:i,type:s},n},{})),r}mapFunction(e){let t=e.nodeDef,r=[],n=[],a={};t!=null&&(a=t.reduce((u,d)=>(u[d.name]=this.mapNode(d),d.op==="Const"&&n.push(u[d.name]),u),{}));let s=[],i=[];e.signature.inputArg.forEach(u=>{let[d]=Ra(u.name),h={name:d,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:lA(u.type),type:"dtype"}},children:[]};h.signatureKey=u.name,s.push(h),a[d]=h}),Object.keys(a).forEach(u=>{let d=a[u];d.inputNames.forEach((h,p)=>{let[c,,m]=Ra(h),f=a[c];if(f.outputs!=null){let g=f.outputs.indexOf(m);if(g!==-1){let y=`${c}:${g}`;d.inputNames[p]=y}}d.inputs.push(f),f.children.push(d)})});let o=e.ret;e.signature.outputArg.forEach(u=>{let[d,h]=Ra(o[u.name]),p=a[d];p!=null&&(p.defaultOutput=h,i.push(p))});let l=this.mapArgsToSignature(e);return{nodes:a,inputs:s,outputs:i,weights:n,placeholders:r,signature:l}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,r)=>(t[r.name]=this.mapArgToTensorInfo(r),t),{}),outputs:e.signature.outputArg.reduce((t,r)=>(t[r.name]=this.mapArgToTensorInfo(r,e.ret),t),{})}}mapArgToTensorInfo(e,t){let r=e.name;return t!=null&&(r=t[r]),{name:r,dtype:e.type}}};function uH(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 J8(e,t){let r=Array.isArray(e)?String.fromCharCode.apply(null,e):uH(e);return t?r:r.toLowerCase()}function Qg(e,t,r,n=!1){let a=e[t];return a!=null?J8(a.s,n):r}function ey(e,t,r){let n=e[t];return n?n.b:r}function ty(e,t,r){let n=e[t]||{},a=n.i!=null?n.i:n.f!=null?n.f:r;return typeof a=="number"?a:parseInt(a,10)}function lA(e){switch(typeof e=="string"&&(e=$8[e]),e){case 1:case 19:return"float32";case 3:case 9:case 6:case 4:return"int32";case 10:return"bool";case 2:return"float32";case 7:return"string";default:return null}}function O4(e,t,r){let n=e[t];return n&&n.func?n.func.name:r}function ry(e,t,r){let n=e[t];return n&&n.type?lA(n.type):r}function ny(e,t,r){let n=e[t];return n&&n.list&&n.list.type?n.list.type.map(a=>lA(a)):r}function Q8(e){if(!e.unknownRank)return e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function ay(e,t,r){let n=e[t];return n&&n.shape?Q8(n.shape):r}function sy(e,t,r){let n=e[t];return n?((n.list.f&&n.list.f.length?n.list.f:n.list.i)||[]).map(a=>typeof a=="number"?a:parseInt(a,10)):r}function iy(e,t,r,n=!1){let a=e[t];return a&&a.list&&a.list.s?a.list.s.map(s=>J8(s,n)):r}function oy(e,t,r){let n=e[t];return n&&n.list&&n.list.shape?n.list.shape.map(a=>Q8(a)):r}function ly(e,t,r){let n=e[t];return n&&n.list&&n.list.b?n.list.b:r}var dH=class{constructor(e,t,r){this.node=e,this.tensorMap=t,this.context=r,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(n=>this.getInput(n)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((n,a)=>(n[a]=this.getAttr(a),n),{}))}getInput(e){return Br(e,this.tensorMap,this.context)}getAttr(e,t){let r=this.node.rawAttrs[e];if(r.tensor!=null)return Br(e,this.tensorMap,this.context);if(r.i!=null||r.f!=null)return ty(this.node.rawAttrs,e,t);if(r.s!=null)return Qg(this.node.rawAttrs,e,t);if(r.b!=null)return ey(this.node.rawAttrs,e,t);if(r.shape!=null)return ay(this.node.rawAttrs,e,t);if(r.type!=null)return ry(this.node.rawAttrs,e,t);if(r.list!=null){if(r.list.i!=null||r.list.f!=null)return sy(this.node.rawAttrs,e,t);if(r.list.s!=null)return iy(this.node.rawAttrs,e,t);if(r.list.shape!=null)return oy(this.node.rawAttrs,e,t);if(r.list.b!=null)return ly(this.node.rawAttrs,e,t);if(r.list.type!=null)return ny(this.node.rawAttrs,e,t)}return t}},pH=(e,t,r)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[le(k("a",e,t,r),k("b",e,t,r))];case"AddN":return[Of(k("tensors",e,t,r))];case"FloorMod":case"Mod":return[kd(k("a",e,t,r),k("b",e,t,r))];case"Mul":return[L(k("a",e,t,r),k("b",e,t,r))];case"RealDiv":case"Div":return[pe(k("a",e,t,r),k("b",e,t,r))];case"DivNoNan":return[yv(k("a",e,t,r),k("b",e,t,r))];case"FloorDiv":return[Ch(k("a",e,t,r),k("b",e,t,r))];case"Sub":return[ce(k("a",e,t,r),k("b",e,t,r))];case"Minimum":return[$h(k("a",e,t,r),k("b",e,t,r))];case"Maximum":return[rs(k("a",e,t,r),k("b",e,t,r))];case"Pow":return[Ws(k("a",e,t,r),k("b",e,t,r))];case"SquaredDifference":return[C3(k("a",e,t,r),k("b",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},hH=(e,t,r)=>{switch(e.op){case"Abs":case"ComplexAbs":return[ar(k("x",e,t,r))];case"Acos":return[q6(k("x",e,t,r))];case"Acosh":return[X6(k("x",e,t,r))];case"Asin":return[Z6(k("x",e,t,r))];case"Asinh":return[Y6(k("x",e,t,r))];case"Atan":return[J6(k("x",e,t,r))];case"Atan2":return[Q6(k("x",e,t,r),k("y",e,t,r))];case"Atanh":return[ev(k("x",e,t,r))];case"Ceil":return[lv(k("x",e,t,r))];case"Complex":return[Ya(k("real",e,t,r),k("imag",e,t,r))];case"Cos":return[Lf(k("x",e,t,r))];case"Cosh":return[s3(k("x",e,t,r))];case"Elu":return[Eh(k("x",e,t,r))];case"Erf":return[xv(k("x",e,t,r))];case"Exp":return[Fn(k("x",e,t,r))];case"Expm1":return[Sv(k("x",e,t,r))];case"Floor":return[Rh(k("x",e,t,r))];case"Log":return[_n(k("x",e,t,r))];case"Log1p":return[Vf(k("x",e,t,r))];case"Imag":return[Sh(k("x",e,t,r))];case"Neg":return[Mt(k("x",e,t,r))];case"Reciprocal":return[Ov(k("x",e,t,r))];case"Real":return[Ru(k("x",e,t,r))];case"Relu":return[Da(k("x",e,t,r))];case"Round":return[x3(k("x",e,t,r))];case"Selu":return[v3(k("x",e,t,r))];case"Sigmoid":return[Tr(k("x",e,t,r))];case"Sin":return[w3(k("x",e,t,r))];case"Sign":return[Lv(k("x",e,t,r))];case"Sinh":return[k3(k("x",e,t,r))];case"Softplus":return[wd(k("x",e,t,r))];case"Sqrt":return[Er(k("x",e,t,r))];case"Square":return[bt(k("x",e,t,r))];case"Tanh":return[$u(k("x",e,t,r))];case"Tan":return[Wv(k("x",e,t,r))];case"ClipByValue":return[fn(k("x",e,t,r),k("clipValueMin",e,t,r),k("clipValueMax",e,t,r))];case"Relu6":return[A3(k("x",e,t,r))];case"Rsqrt":return[b3(Br(e.inputNames[0],t,r))];case"Prod":return[m3(k("x",e,t,r),k("axes",e,t,r))];case"LeakyRelu":return[Wf(k("x",e,t,r),k("alpha",e,t,r))];case"Prelu":return[Xf(k("x",e,t,r),k("alpha",e,t,r))];case"IsNan":return[Cv(Br(e.inputNames[0],t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Gn(e,t,r=""){if(!(typeof e=="number"||typeof t=="number")){v.assert(e.length===t.length,()=>r+` Shapes ${e} and ${t} must match`);for(let n=0;n<e.length;n++){let a=e[n],s=t[n];v.assert(a<0||s<0||a===s,()=>r+` Shapes ${e} and ${t} must match`)}}}function z4(e){return!(typeof e=="number"||e.some(t=>t<0))}function Tp(e,t,r){let n=uy(e,r),a=!z4(n);if(a&&t.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${n}`);if(a&&t.forEach(s=>{n=uy(s.shape,n)}),!z4(n))throw new Error(`Non-fully-defined elementShape: ${n}`);return n}function uy(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 r=[];for(let n=0;n<e.length;++n){let a=e[n],s=t[n];if(a>=0&&s>=0&&a!==s)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);r[n]=a>=0?a:s}return r}var cH=class{constructor(e,t,r,n,a,s,i){this.name=e,this.dtype=t,this.maxSize=r,this.elementShape=n,this.identicalElementShapes=a,this.dynamicSize=s,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=Se(0),mr(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 r=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),Gn(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),r.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(r.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);r.tensor=t,mr(t),r.written=!0,this.tensors[e]=r}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((r,n)=>this.write(r,t[n]))}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 n=0;n<this.size();n++)e.push(n)}if(e.length===0)return ft([],[0].concat(this.elementShape));let r=this.readMany(e);return Gn(this.elementShape,r[0].shape,"TensorArray shape mismatch: "),ur(r,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 ft([],[0].concat(this.elementShape));let t=[];for(let n=0;n<this.size();n++)t.push(n);let r=this.readMany(t);return Gn(this.elementShape,r[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${r[0].shape})`),St(r,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 r=Math.max(...e);if(!this.dynamicSize&&r>=this.maxSize)throw new Error(`Max index must be < array size (${r} vs. ${this.maxSize})`);this.writeMany(e,an(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 r=0,n=e.map(o=>(r+=o,r));if(r!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
|
|
tensor.shape[0], but sum of lengths is
|
|
${r}, 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 a=r===0?0:t.size/r,s=[];X(()=>{t=U(t,[1,r,a]);for(let o=0;o<e.length;++o){let l=o===0?0:n[o-1],u=[0,l,0],d=[1,e[o],a];s[o]=U(_e(t,u,d),this.elementShape)}return s});let i=[];for(let o=0;o<e.length;o++)i[o]=o;this.writeMany(i,s)}},Du=class{constructor(e,t,r,n=-1){this.tensors=e,this.elementShape=t,this.elementDtype=r,e!=null&&e.forEach(a=>{if(r!==a.dtype)throw new Error(`Invalid data types; op elements ${r}, but list elements ${a.dtype}`);Gn(t,a.shape,"TensorList shape mismatch: "),mr(a)}),this.idTensor=Se(0),this.maxNumElements=n,mr(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Du([...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,r=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(r!==-1&&this.tensors.length!==r)throw new Error(`Operation expected a list with ${r} elements but got a list with ${this.tensors.length} elements.`);Gn(e,this.elementShape,"TensorList shape mismatch: ");let n=Tp(this.elementShape,this.tensors,e);return X(()=>{let a=this.tensors.map(s=>U(s,n));return ur(a,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 r=Tp(this.elementShape,this.tensors,e),n=this.tensors.pop();return Gn(n.shape,e,"TensorList shape mismatch: "),U(n,r)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Gn(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");mr(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}.`);let t=new Du([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let r=0;r<Math.min(this.tensors.length,e);++r)t.tensors[r]=this.tensors[r];return t}getItem(e,t,r){if(r!==this.elementDtype)throw new Error(`Invalid data types; op elements ${r}, 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.`);Gn(this.tensors[e].shape,t,"TensorList shape mismatch: ");let n=Tp(this.elementShape,this.tensors,t);return U(this.tensors[e],n)}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.`);Gn(this.elementShape,t.shape,"TensorList shape mismatch: "),mr(t),this.tensors[e]=t}gather(e,t,r){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);Gn(this.elementShape,r,"TensorList shape mismatch: "),e=e.slice(0,this.size());let n=Tp(this.elementShape,this.tensors,r);return e.length===0?ft([],[0].concat(n)):X(()=>{let a=e.map(s=>U(this.tensors[s],n));return ur(a,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Gn(this.elementShape,t,"TensorList shape mismatch: ");let r=Tp(this.elementShape,this.tensors,t);return this.size()===0?ft([],[0].concat(r)):X(()=>{let n=this.tensors.map(a=>U(a,r));return St(n,0)})}};function fH(e,t,r){let n=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!==r)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${r}`);let a=e.shape.slice(1);Gn(a,t,"TensorList shape mismatch: ");let s=an(e);return new Du(s,t,n)}function mH(e,t,r){return new Du([],e,t,r)}function gH(e,t,r,n){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);let a=Math.max(...t);if(n!=null&&n!==-1&&a>=n)throw new Error(`Max index must be < array size (${a} vs. ${n})`);let s=new Du([],r,e.dtype,n),i=an(e,0);return t.forEach((o,l)=>{s.setItem(o,i[l])}),s}function yH(e,t,r){let n=0,a=t.map(d=>(n+=d,n));if(n!==e.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: ${e.shape}`);let s=e.shape.slice(1),i=uy(s,r),o=n===0?0:e.size/n,l=X(()=>{let d=[];e=U(e,[1,n,o]);for(let h=0;h<t.length;++h){let p=h===0?0:a[h-1],c=[0,p,0],m=[1,t[h],o];d[h]=U(_e(e,c,m),i)}return e.dispose(),d}),u=new Du([],r,e.dtype,t.length);for(let d=0;d<l.length;d++)u.setItem(d,l[d]);return u}var AH=async(e,t,r)=>{switch(e.op){case"If":case"StatelessIf":{let n=k("thenBranch",e,t,r),a=k("elseBranch",e,t,r),s=k("cond",e,t,r),i=k("args",e,t,r);return(await s.data())[0]?r.functionMap[n].executeFunctionAsync(i,r.tensorArrayMap,r.tensorListMap):r.functionMap[a].executeFunctionAsync(i,r.tensorArrayMap,r.tensorListMap)}case"While":case"StatelessWhile":{let n=k("body",e,t,r),a=k("cond",e,t,r),s=k("args",e,t,r),i=await r.functionMap[a].executeFunctionAsync(s,r.tensorArrayMap,r.tensorListMap),o=s.map(d=>d.id),l=await i[0].data();i.forEach(d=>{!d.kept&&o.indexOf(d.id)===-1&&d.dispose()});let u=s;for(;l[0];){let d=u;u=await r.functionMap[n].executeFunctionAsync(u,r.tensorArrayMap,r.tensorListMap);let h=u.map(c=>c.id);d.forEach(c=>{!c.kept&&o.indexOf(c.id)===-1&&h.indexOf(c.id)===-1&&c.dispose()});let p=await r.functionMap[a].executeFunctionAsync(u,r.tensorArrayMap,r.tensorListMap);l=await p[0].data(),p.forEach(c=>{!c.kept&&o.indexOf(c.id)===-1&&h.indexOf(c.id)===-1&&c.dispose()})}return u}case"LoopCond":{let n=k("pred",e,t,r);return[qa(n)]}case"Switch":{let n=k("pred",e,t,r),a=k("data",e,t,r);return a.kept||(a=qa(a)),(await n.data())[0]?[void 0,a]:[a,void 0]}case"Merge":{let n=e.inputNames.find(a=>Br(a,t,r)!==void 0);if(n){let a=Br(n,t,r);return[qa(a)]}return}case"Enter":{let n=k("frameName",e,t,r),a=k("tensor",e,t,r);return r.enterFrame(n),[qa(a)]}case"Exit":{let n=k("tensor",e,t,r);return r.exitFrame(),[qa(n)]}case"NextIteration":{let n=k("tensor",e,t,r);return r.nextIteration(),[qa(n)]}case"TensorArrayV3":{let n=k("size",e,t,r),a=k("dtype",e,t,r),s=k("elementShape",e,t,r),i=k("dynamicSize",e,t,r),o=k("clearAfterRead",e,t,r),l=k("identicalElementShapes",e,t,r),u=k("name",e,t,r),d=new cH(u,a,n,s,l,i,o);return r.addTensorArray(d),[d.idTensor,Se(1)]}case"TensorArrayWriteV3":{let n=k("tensorArrayId",e,t,r),a=k("index",e,t,r),s=k("tensor",e,t,r),i=r.getTensorArray(n.id);return i.write(a,s),[i.idTensor]}case"TensorArrayReadV3":{let n=k("tensorArrayId",e,t,r),a=k("index",e,t,r);return[r.getTensorArray(n.id).read(a)]}case"TensorArrayGatherV3":{let n=k("tensorArrayId",e,t,r),a=k("indices",e,t,r),s=k("dtype",e,t,r);return[r.getTensorArray(n.id).gather(a,s)]}case"TensorArrayScatterV3":{let n=k("tensorArrayId",e,t,r),a=k("indices",e,t,r),s=k("tensor",e,t,r),i=r.getTensorArray(n.id);return i.scatter(a,s),[i.idTensor]}case"TensorArrayConcatV3":{let n=k("tensorArrayId",e,t,r),a=r.getTensorArray(n.id),s=k("dtype",e,t,r);return[a.concat(s)]}case"TensorArraySplitV3":{let n=k("tensorArrayId",e,t,r),a=k("tensor",e,t,r),s=k("lengths",e,t,r),i=r.getTensorArray(n.id);return i.split(s,a),[i.idTensor]}case"TensorArraySizeV3":{let n=k("tensorArrayId",e,t,r),a=r.getTensorArray(n.id);return[Se(a.size(),"int32")]}case"TensorArrayCloseV3":{let n=k("tensorArrayId",e,t,r),a=r.getTensorArray(n.id);return a.clearAndClose(),[a.idTensor]}case"TensorListSetItem":{let n=k("tensorListId",e,t,r),a=k("index",e,t,r),s=k("tensor",e,t,r),i=r.getTensorList(n.id);return i.setItem(a,s),[i.idTensor]}case"TensorListGetItem":{let n=k("tensorListId",e,t,r),a=k("index",e,t,r),s=k("elementShape",e,t,r),i=k("elementDType",e,t,r);return[r.getTensorList(n.id).getItem(a,s,i)]}case"TensorListScatterV2":case"TensorListScatter":{let n=k("indices",e,t,r),a=k("tensor",e,t,r),s=k("elementShape",e,t,r),i=k("numElements",e,t,r),o=gH(a,n,s,i);return r.addTensorList(o),[o.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let n=k("elementShape",e,t,r),a=k("elementDType",e,t,r),s;e.op==="TensorListReserve"?s="numElements":s="maxNumElements";let i=k(s,e,t,r),o=mH(n,a,i);return r.addTensorList(o),[o.idTensor]}case"TensorListGather":{let n=k("tensorListId",e,t,r),a=k("indices",e,t,r),s=k("elementShape",e,t,r),i=k("elementDType",e,t,r);return[r.getTensorList(n.id).gather(a,i,s)]}case"TensorListStack":{let n=k("tensorListId",e,t,r),a=k("elementShape",e,t,r),s=k("elementDType",e,t,r),i=k("numElements",e,t,r);return[r.getTensorList(n.id).stack(a,s,i)]}case"TensorListFromTensor":{let n=k("tensor",e,t,r),a=k("elementShape",e,t,r),s=k("elementDType",e,t,r),i=fH(n,a,s);return r.addTensorList(i),[i.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{let n=k("tensorListId",e,t,r),a=r.getTensorList(n.id),s=k("dtype",e,t,r),i=k("elementShape",e,t,r);return[a.concat(s,i)]}case"TensorListPushBack":{let n=k("tensorListId",e,t,r),a=k("tensor",e,t,r),s=r.getTensorList(n.id);return s.pushBack(a),[s.idTensor]}case"TensorListPopBack":{let n=k("tensorListId",e,t,r),a=k("elementShape",e,t,r),s=k("elementDType",e,t,r);return[r.getTensorList(n.id).popBack(a,s)]}case"TensorListSplit":{let n=k("tensor",e,t,r),a=k("elementShape",e,t,r),s=k("lengths",e,t,r),i=yH(n,s,a);return r.addTensorList(i),[i.idTensor]}case"TensorListLength":{let n=k("tensorListId",e,t,r),a=r.getTensorList(n.id);return[Se(a.size(),"int32")]}case"TensorListResize":{let n=k("tensorListId",e,t,r),a=k("size",e,t,r),s=r.getTensorList(n.id).resize(a);return r.addTensorList(s),[s.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function D4(e,t,r){let[n,a]=k("fusedOps",e,t,r),s=n==="biasadd",i=!s,o=a==="prelu",l=n==="fusedbatchnorm",u=k("numArgs",e,t,r);if(s){if(o&&u!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&s&&u!==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 d=k("strides",e,t,r),h=m0(e,t,r),p=k("dataFormat",e,t,r).toUpperCase(),c=k("dilations",e,t,r),[m,f]=k("args",e,t,r);i&&(f=m,m=void 0);let g=k("leakyreluAlpha",e,t,r);return{stride:d,pad:h,dataFormat:p,dilations:c,biasArg:m,preluArg:f,activationFunc:a,leakyreluAlpha:g}}var xH=(e,t,r)=>{switch(e.op){case"Conv1D":{let n=k("stride",e,t,r),a=k("pad",e,t,r),s=k("dataFormat",e,t,r).toUpperCase(),i=k("dilation",e,t,r);return[t3(k("x",e,t,r),k("filter",e,t,r),n,a,s,i)]}case"Conv2D":{let n=k("strides",e,t,r),a=m0(e,t,r),s=k("dataFormat",e,t,r).toUpperCase(),i=k("dilations",e,t,r);return[Ls(k("x",e,t,r),k("filter",e,t,r),[n[1],n[2]],a,s,[i[1],i[2]])]}case"_FusedConv2D":{let{stride:n,pad:a,dataFormat:s,dilations:i,biasArg:o,preluArg:l,activationFunc:u,leakyreluAlpha:d}=D4(e,t,r);return[Vs.conv2d({x:k("x",e,t,r),filter:k("filter",e,t,r),strides:[n[1],n[2]],pad:a,dataFormat:s,dilations:[i[1],i[2]],bias:o,activation:u,preluActivationWeights:l,leakyreluAlpha:d})]}case"FusedDepthwiseConv2dNative":{let{stride:n,pad:a,dataFormat:s,dilations:i,biasArg:o,preluArg:l,activationFunc:u,leakyreluAlpha:d}=D4(e,t,r);return[Vs.depthwiseConv2d({x:k("x",e,t,r),filter:k("filter",e,t,r),strides:[n[1],n[2]],pad:a,dataFormat:s,dilations:[i[1],i[2]],bias:o,activation:u,preluActivationWeights:l,leakyreluAlpha:d})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let n=k("outputShape",e,t,r),a=k("strides",e,t,r),s=m0(e,t,r);return[n3(k("x",e,t,r),k("filter",e,t,r),n,[a[1],a[2]],s)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let n=k("strides",e,t,r),a=m0(e,t,r),s=k("dilations",e,t,r),i=k("dataFormat",e,t,r).toUpperCase();return[Nh(k("input",e,t,r),k("filter",e,t,r),[n[1],n[2]],a,i,[s[1],s[2]])]}case"Conv3D":{let n=k("strides",e,t,r),a=k("pad",e,t,r),s=k("dataFormat",e,t,r).toUpperCase(),i=k("dilations",e,t,r);return[a3(k("x",e,t,r),k("filter",e,t,r),[n[1],n[2],n[3]],a,s,[i[1],i[2],i[3]])]}case"AvgPool":{let n=k("strides",e,t,r),a=k("pad",e,t,r),s=k("kernelSize",e,t,r);return[zf(k("x",e,t,r),[s[1],s[2]],[n[1],n[2]],a)]}case"MaxPool":{let n=k("strides",e,t,r),a=k("pad",e,t,r),s=k("kernelSize",e,t,r);return[jf(k("x",e,t,r),[s[1],s[2]],[n[1],n[2]],a)]}case"MaxPoolWithArgmax":{let n=k("strides",e,t,r),a=k("pad",e,t,r),s=k("kernelSize",e,t,r),i=k("includeBatchInIndex",e,t,r),{result:o,indexes:l}=Mv(k("x",e,t,r),[s[1],s[2]],[n[1],n[2]],a,i);return[o,l]}case"AvgPool3D":{let n=k("strides",e,t,r),a=k("pad",e,t,r),s=k("kernelSize",e,t,r);return[Qy(k("x",e,t,r),[s[1],s[2],s[3]],[n[1],n[2],n[3]],a)]}case"MaxPool3D":{let n=k("strides",e,t,r),a=k("pad",e,t,r),s=k("kernelSize",e,t,r);return[f3(k("x",e,t,r),[s[1],s[2],s[3]],[n[1],n[2],n[3]],a)]}case"Dilation2D":{let n=k("strides",e,t,r),a=k("pad",e,t,r),s=k("dilations",e,t,r),i=n[1],o=n[2],l=s[1],u=s[2];return[gv(k("x",e,t,r),k("filter",e,t,r),[i,o],a,[l,u],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},bH=(e,t,r)=>{switch(e.op){case"Fill":{let n=k("shape",e,t,r),a=k("dtype",e,t,r),s=k("value",e,t,r);return[vd(n,s,a)]}case"LinSpace":{let n=k("start",e,t,r),a=k("stop",e,t,r),s=k("num",e,t,r);return[Tv(n,a,s)]}case"Multinomial":{let n=k("logits",e,t,r),a=k("numSamples",e,t,r),s=k("seed",e,t,r);return[_v(n,a,s)]}case"OneHot":{let n=k("indices",e,t,r),a=k("depth",e,t,r),s=k("onValue",e,t,r),i=k("offValue",e,t,r);return[Zp(n,a,s,i)]}case"Ones":return[cn(k("shape",e,t,r),k("dtype",e,t,r))];case"OnesLike":return[Pn(k("x",e,t,r))];case"RandomUniform":return[Id(k("shape",e,t,r),k("minval",e,t,r),k("maxval",e,t,r),k("dtype",e,t,r))];case"Range":{let n=k("start",e,t,r),a=k("stop",e,t,r),s=k("step",e,t,r);return[Pu(n,a,s,k("dtype",e,t,r))]}case"TruncatedNormal":{let n=k("shape",e,t,r),a=k("mean",e,t,r),s=k("stdDev",e,t,r),i=k("seed",e,t,r);return[Jf(n,a,s,k("dtype",e,t,r),i)]}case"Zeros":return[Ot(k("shape",e,t,r),k("dtype",e,t,r))];case"ZerosLike":return[at(k("x",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function kg(e,t,r){let n=k("boxes",e,t,r),a=k("scores",e,t,r),s=k("maxOutputSize",e,t,r),i=k("iouThreshold",e,t,r),o=k("scoreThreshold",e,t,r),l=k("softNmsSigma",e,t,r);return{boxes:n,scores:a,maxOutputSize:s,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}}var vH=async(e,t,r)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:n,scores:a,maxOutputSize:s,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}=kg(e,t,r),u=await Ie.nonMaxSuppressionWithScoreAsync(n,a,s,i,o,l);return[u.selectedIndices,u.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:n,scores:a,maxOutputSize:s,iouThreshold:i,scoreThreshold:o}=kg(e,t,r),l=k("padToMaxOutputSize",e,t,r),u=await Ie.nonMaxSuppressionPaddedAsync(n,a,s,i,o,l);return[u.selectedIndices,u.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:n,scores:a,maxOutputSize:s,iouThreshold:i,scoreThreshold:o}=kg(e,t,r);return[await Ie.nonMaxSuppressionAsync(n,a,s,i,o)]}case"Where":{let n=me(k("condition",e,t,r),"bool"),a=[await T3(n)];return n.dispose(),a}case"ListDiff":return Dv(k("x",e,t,r),k("y",e,t,r));default:throw TypeError(`Node type ${e.op} is not implemented`)}},wH=(e,t,r)=>{switch(e.op){case"LowerBound":{let n=k("sortedSequence",e,t,r),a=k("values",e,t,r);return[$v(n,a)]}case"TopKV2":{let n=k("x",e,t,r),a=k("k",e,t,r),s=k("sorted",e,t,r),i=Vv(n,a,s);return[i.values,i.indices]}case"UpperBound":{let n=k("sortedSequence",e,t,r),a=k("values",e,t,r);return[Gv(n,a)]}case"Unique":{let n=k("x",e,t,r),a=Wg(n);return[a.values,a.indices]}case"UniqueV2":{let n=k("x",e,t,r),a=k("axis",e,t,r),s=Wg(n,a);return[s.values,s.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},kH=(e,t,r)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let n=k("default",e,t,r);return[Br(e.name,t,r)||n];case"Placeholder":return[Br(e.name,t,r)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let u=k("x",e,t,r);return[qa(u)]}case"IdentityN":return k("x",e,t,r).map(u=>qa(u));case"Snapshot":let a=k("x",e,t,r);return[qa(a)];case"Shape":return[Nt(k("x",e,t,r).shape,"int32")];case"ShapeN":return k("x",e,t,r).map(u=>Nt(u.shape));case"Size":return[Se(k("x",e,t,r).size,"int32")];case"Rank":return[Se(k("x",e,t,r).rank,"int32")];case"NoOp":return[Se(1)];case"Print":let s=k("x",e,t,r),i=k("data",e,t,r),o=k("message",e,t,r),l=k("summarize",e,t,r);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(o);for(let u=0;u<i.length;u++)console.log(Array.prototype.slice.call(i[u].dataSync()).slice(0,l));return[s];default:throw TypeError(`Node type ${e.op} is not implemented`)}},IH=class{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Se(0),this.tensorMap=new Map,mr(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 Se(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);let r=await e.data();return this.tensorMap.forEach(n=>n.dispose()),this.tensorMap.clear(),X(()=>{let n=an(t),a=r.length,s=n.length;v.assert(a===s,()=>`The number of elements doesn't match, keys has ${a} elements, the values has ${s} elements.`);for(let i=0;i<a;i++){let o=r[i],l=n[i];mr(l),this.tensorMap.set(o,l)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);let r=await e.data();return X(()=>{let n=[];for(let a=0;a<r.length;a++){let s=r[a],i=this.findWithDefault(s,t);n.push(i)}return ur(n)})}findWithDefault(e,t){let r=this.tensorMap.get(e);return r!=null?r: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}`)}},SH=async(e,t,r,n)=>{switch(e.op){case"HashTable":case"HashTableV2":{let a=k("keyDType",e,t,r),s=k("valueDType",e,t,r),i=new IH(a,s);return n.addHashTable(e.name,i),[i.handle]}case"LookupTableImport":case"LookupTableImportV2":{let a=k("tableHandle",e,t,r,n),s=k("keys",e,t,r),i=k("values",e,t,r);return[await n.getHashTableById(a.id).import(s,i)]}case"LookupTableFind":case"LookupTableFindV2":{let a=k("tableHandle",e,t,r,n),s=k("keys",e,t,r),i=k("defaultValue",e,t,r);return[await n.getHashTableById(a.id).find(s,i)]}case"LookupTableSize":case"LookupTableSizeV2":{let a=k("tableHandle",e,t,r,n);return[n.getHashTableById(a.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},CH=(e,t,r)=>{switch(e.op){case"ResizeBilinear":{let n=k("images",e,t,r),a=k("size",e,t,r),s=k("alignCorners",e,t,r),i=k("halfPixelCenters",e,t,r);return[Ie.resizeBilinear(n,[a[0],a[1]],s,i)]}case"ResizeNearestNeighbor":{let n=k("images",e,t,r),a=k("size",e,t,r),s=k("alignCorners",e,t,r),i=k("halfPixelCenters",e,t,r);return[Ie.resizeNearestNeighbor(n,[a[0],a[1]],s,i)]}case"CropAndResize":{let n=k("image",e,t,r),a=k("boxes",e,t,r),s=k("boxInd",e,t,r),i=k("cropSize",e,t,r),o=k("method",e,t,r),l=k("extrapolationValue",e,t,r);return[Ie.cropAndResize(n,a,s,i,o,l)]}case"ImageProjectiveTransformV3":{let n=k("images",e,t,r),a=k("transforms",e,t,r),s=k("outputShape",e,t,r),i=k("fillValue",e,t,r),o=k("interpolation",e,t,r),l=k("fillMode",e,t,r);return[Ie.transform(n,a,o.toLowerCase(),l.toLowerCase(),i,s)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},TH=(e,t,r)=>{switch(e.op){case"Equal":return[Mn(k("a",e,t,r),k("b",e,t,r))];case"NotEqual":return[_u(k("a",e,t,r),k("b",e,t,r))];case"Greater":return[gn(k("a",e,t,r),k("b",e,t,r))];case"GreaterEqual":return[Ml(k("a",e,t,r),k("b",e,t,r))];case"Less":return[d3(k("a",e,t,r),k("b",e,t,r))];case"LessEqual":return[Fl(k("a",e,t,r),k("b",e,t,r))];case"LogicalAnd":return[ga(k("a",e,t,r),k("b",e,t,r))];case"LogicalNot":return[Gf(k("a",e,t,r))];case"LogicalOr":return[h3(k("a",e,t,r),k("b",e,t,r))];case"Select":case"SelectV2":return[Ur(k("condition",e,t,r),k("a",e,t,r),k("b",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},NH=(e,t,r)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[Ye(k("a",e,t,r),k("b",e,t,r),k("transposeA",e,t,r),k("transposeB",e,t,r))];case"Einsum":return[Av(k("equation",e,t,r),...k("tensors",e,t,r))];case"Transpose":return[tt(k("x",e,t,r),k("perm",e,t,r))];case"_FusedMatMul":let[n,a]=k("fusedOps",e,t,r),s=n==="biasadd",i=a==="prelu",o=k("numArgs",e,t,r),l=k("leakyreluAlpha",e,t,r);if(s){if(i&&o!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&o!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[u,d]=k("args",e,t,r);return[Vs.matMul({a:k("a",e,t,r),b:k("b",e,t,r),transposeA:k("transposeA",e,t,r),transposeB:k("transposeB",e,t,r),bias:u,activation:a,preluActivationWeights:d,leakyreluAlpha:l})];default:throw TypeError(`Node type ${e.op} is not implemented`)}},EH=(e,t,r)=>{switch(e.op){case"EuclideanNorm":return[Iv(k("x",e,t,r),k("axis",e,t,r),k("keepDims",e,t,r))];case"FusedBatchNorm":case"FusedBatchNormV2":return[Mu(k("x",e,t,r),k("mean",e,t,r),k("variance",e,t,r),k("offset",e,t,r),k("scale",e,t,r),k("epsilon",e,t,r))];case"FusedBatchNormV3":return[Mu(k("x",e,t,r),k("mean",e,t,r),k("variance",e,t,r),k("offset",e,t,r),k("scale",e,t,r),k("epsilon",e,t,r))];case"LRN":return[Nv(k("x",e,t,r),k("radius",e,t,r),k("bias",e,t,r),k("alpha",e,t,r),k("beta",e,t,r))];case"Softmax":return[Sd(k("x",e,t,r))];case"LogSoftmax":return[p3(k("x",e,t,r))];case"SparseToDense":return[N3(k("sparseIndices",e,t,r),k("outputShape",e,t,r),k("sparseValues",e,t,r),k("defaultValue",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},RH=(e,t,r)=>{switch(e.op){case"Max":{let i=k("axis",e,t,r),o=k("keepDims",e,t,r);return[yr(k("x",e,t,r),i,o)]}case"Mean":{let i=k("axis",e,t,r),o=k("keepDims",e,t,r);return[Vt(k("x",e,t,r),i,o)]}case"Min":{let i=k("axis",e,t,r),o=k("keepDims",e,t,r);return[Bs(k("x",e,t,r),i,o)]}case"Sum":{let i=k("axis",e,t,r),o=k("keepDims",e,t,r);return[ke(k("x",e,t,r),i,o)]}case"All":{let i=k("axis",e,t,r),o=k("keepDims",e,t,r);return[Yy(k("x",e,t,r),i,o)]}case"Any":{let i=k("axis",e,t,r),o=k("keepDims",e,t,r);return[_0(k("x",e,t,r),i,o)]}case"ArgMax":{let i=k("axis",e,t,r);return[$n(k("x",e,t,r),i)]}case"ArgMin":{let i=k("axis",e,t,r);return[K6(k("x",e,t,r),i)]}case"Prod":{let i=k("axis",e,t,r),o=k("keepDims",e,t,r);return[m3(k("x",e,t,r),i,o)]}case"Cumprod":{let i=k("axis",e,t,r),o=k("exclusive",e,t,r),l=k("reverse",e,t,r);return[O0(k("x",e,t,r),i,o,l)]}case"Cumsum":{let i=k("axis",e,t,r),o=k("exclusive",e,t,r),l=k("reverse",e,t,r);return[i3(k("x",e,t,r),i,o,l)]}case"Bincount":let n=k("x",e,t,r),a=k("weights",e,t,r),s=k("size",e,t,r);return[e3(n,a,s)];case"DenseBincount":{let i=k("x",e,t,r),o=k("weights",e,t,r),l=k("size",e,t,r),u=k("binaryOutput",e,t,r);return[fv(i,o,l,u)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},$H=(e,t,r)=>{switch(e.op){case"ConcatV2":case"Concat":{let n=k("n",e,t,r),a=k("axis",e,t,r),s=k("tensors",e,t,r);return s=s.slice(0,n),[St(s,a)]}case"Gather":{let n=k("x",e,t,r),a=k("indices",e,t,r);return[Fu(n,me(a,"int32"),0)]}case"GatherV2":{let n=k("axis",e,t,r),a=k("batchDims",e,t,r),s=k("x",e,t,r),i=k("indices",e,t,r);return[Fu(s,me(i,"int32"),n,a)]}case"Reverse":{let n=k("dims",e,t,r),a=[];for(let i=0;i<n.length;i++)n[i]&&a.push(i);let s=k("x",e,t,r);return[On(s,a)]}case"ReverseV2":{let n=k("axis",e,t,r),a=k("x",e,t,r);return[On(a,n)]}case"Slice":{let n=k("begin",e,t,r),a=k("size",e,t,r);return[_e(k("x",e,t,r),n,a)]}case"StridedSlice":{let n=k("begin",e,t,r),a=k("end",e,t,r),s=k("strides",e,t,r),i=k("beginMask",e,t,r),o=k("endMask",e,t,r),l=k("ellipsisMask",e,t,r),u=k("newAxisMask",e,t,r),d=k("shrinkAxisMask",e,t,r),h=k("x",e,t,r);return[Bv(h,n,a,s,i,o,l,u,d)]}case"Pack":return X(()=>{let n=k("axis",e,t,r),a=k("tensors",e,t,r),s=a[0].shape,i=et(a[0]).shape,o=a.map(l=>{let u=v.arraysEqual(l.shape,s);if(!u&&!v.arraysEqual(et(l).shape,i))throw new Error("the input tensors shape does not match");return u?l:U(l,s)});return[ur(o,n)]});case"Unpack":{let n=k("axis",e,t,r),a=k("tensor",e,t,r);return an(a,n)}case"Tile":{let n=k("reps",e,t,r);return[jn(k("x",e,t,r),n)]}case"Split":case"SplitV":{let n=k("axis",e,t,r),a=k("numOrSizeSplits",e,t,r),s=k("x",e,t,r);return Yt(s,a,n)}case"ScatterNd":{let n=k("indices",e,t,r),a=k("values",e,t,r),s=k("shape",e,t,r);return[qv(n,a,s)]}case"GatherNd":{let n=k("x",e,t,r),a=k("indices",e,t,r);return[Xv(n,a)]}case"SparseToDense":{let n=k("sparseIndices",e,t,r),a=k("outputShape",e,t,r),s=k("sparseValues",e,t,r),i=k("defaultValue",e,t,r);return[N3(n,s,a,s.dtype===i.dtype?i:me(i,s.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},MH=(e,t,r)=>{switch(e.op){case"SparseFillEmptyRows":{let{outputIndices:n,outputValues:a,emptyRowIndicator:s,reverseIndexMap:i}=$p.sparseFillEmptyRows(k("indices",e,t,r),k("values",e,t,r),k("denseShape",e,t,r),k("defaultValue",e,t,r));return[n,a,s,i]}case"SparseReshape":{let{outputIndices:n,outputShape:a}=$p.sparseReshape(k("inputIndices",e,t,r),k("inputShape",e,t,r),k("newShape",e,t,r));return[n,a]}case"SparseSegmentMean":return[$p.sparseSegmentMean(k("data",e,t,r),k("indices",e,t,r),k("segmentIds",e,t,r))];case"SparseSegmentSum":return[$p.sparseSegmentSum(k("data",e,t,r),k("indices",e,t,r),k("segmentIds",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},FH=(e,t,r)=>{switch(e.op){case"FFT":return[Zf(k("x",e,t,r))];case"IFFT":return[Yp(k("x",e,t,r))];case"RFFT":return[Yf(k("x",e,t,r))];case"IRFFT":return[S3(k("x",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},_H=(e,t,r)=>{switch(e.op){case"StringNGrams":{let{nGrams:n,nGramsSplits:a}=f0.stringNGrams(k("data",e,t,r),k("dataSplits",e,t,r),k("separator",e,t,r),k("nGramWidths",e,t,r),k("leftPad",e,t,r),k("rightPad",e,t,r),k("padWidth",e,t,r),k("preserveShortSequences",e,t,r));return[n,a]}case"StringSplit":{let{indices:n,values:a,shape:s}=f0.stringSplit(k("input",e,t,r),k("delimiter",e,t,r),k("skipEmpty",e,t,r));return[n,a,s]}case"StringToHashBucketFast":return[f0.stringToHashBucketFast(k("input",e,t,r),k("numBuckets",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},PH=(e,t,r)=>{switch(e.op){case"Cast":return[me(k("x",e,t,r),k("dtype",e,t,r))];case"ExpandDims":{let n=k("axis",e,t,r);return[Kt(k("x",e,t,r),n)]}case"Squeeze":{let n=k("axis",e,t,r);return[et(k("x",e,t,r),n)]}case"Reshape":return[U(k("x",e,t,r),k("shape",e,t,r))];case"MirrorPad":return[Fv(k("x",e,t,r),k("padding",e,t,r),k("mode",e,t,r))];case"PadV2":case"Pad":return[Xn(k("x",e,t,r),k("padding",e,t,r),k("constantValue",e,t,r))];case"SpaceToBatchND":{let n=k("blockShape",e,t,r),a=k("paddings",e,t,r);return[qf(k("x",e,t,r),n,a)]}case"BatchToSpaceND":{let n=k("blockShape",e,t,r),a=k("crops",e,t,r);return[Df(k("x",e,t,r),n,a)]}case"DepthToSpace":{let n=k("blockSize",e,t,r),a=k("dataFormat",e,t,r).toUpperCase();return[mv(k("x",e,t,r),n,a)]}case"BroadcastTo":return[Bp(k("x",e,t,r),k("shape",e,t,r))];case"BroadcastArgs":return[ov(k("s0",e,t,r),k("s1",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function L4(e,t,r,n){let a=((s,i,o)=>{switch(s.category){case"arithmetic":return X(()=>pH(s,i,o));case"basic_math":return X(()=>hH(s,i,o));case"control":return AH(s,i,o);case"convolution":return X(()=>xH(s,i,o));case"creation":return X(()=>bH(s,i,o));case"dynamic":return vH(s,i,o);case"evaluation":return X(()=>wH(s,i,o));case"image":return X(()=>CH(s,i,o));case"graph":return X(()=>kH(s,i,o));case"logical":return X(()=>TH(s,i,o));case"matrices":return X(()=>NH(s,i,o));case"normalization":return X(()=>EH(s,i,o));case"reduction":return X(()=>RH(s,i,o));case"slice_join":return X(()=>$H(s,i,o));case"sparse":return X(()=>MH(s,i,o));case"spectral":return X(()=>FH(s,i,o));case"string":return X(()=>_H(s,i,o));case"transformation":return X(()=>PH(s,i,o));case"hash_table":return SH(s,i,o,n);case"custom":let l=M8(s.op);if(l&&l.customExecutor)return l.customExecutor(new dH(s,i,o));throw TypeError(`Custom op ${s.op} is not registered.`);default:throw TypeError(`Unknown op '${s.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,r);return v.isPromise(a)?a.then(s=>[].concat(s)):[].concat(a)}var B4=class{constructor(e={},t={},r={},n={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=r,this.functionMap=n,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 r=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(r))}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 W4(e,t,r,n){let a=new Set,s=[],i=null,o=null,l=new Set,u=Object.keys(e).map(p=>pn(p)[0]),d=[];n!=null&&(d=n.map(p=>pn(p.name)[0]));let h=[...t];for(;h.length>0;){let p=h.pop();if((ek(p)||BH(p)||WH(p))&&i==null&&(i=p,o=i.children.map(c=>c.name).filter(c=>a.has(c))),a.add(p.name),r[p.name]==null&&u.indexOf(p.name)===-1&&d.indexOf(p.name)===-1){if(p.inputs.length===0){s.push(p.name);continue}p.inputs.forEach(c=>{l.has(c.name)||(l.add(c.name),h.push(c))})}}return{inputs:e,outputs:t,usedNodes:a,missingInputs:s,dynamicNode:i,syncInputs:o}}function OH(e,t,r){let{usedNodes:n,inputs:a}=r,s=[],i=Object.keys(a).map(d=>pn(d)[0]).map(d=>e.nodes[d]),o=e.initNodes;i.forEach(d=>{n.has(d.name)&&s.push(d)}),e.weights.forEach(d=>{n.has(d.name)&&s.push(d)}),o!=null&&o.forEach(d=>{n.has(d.name)&&s.push(d)});let l=new Set,u=[];for(;s.length>0;){let d=s.pop();l.add(d.name),t[d.name]||u.push(d),d.children.forEach(h=>{!l.has(h.name)&&n.has(h.name)&&h.inputs.every(p=>l.has(p.name))&&s.push(h)})}return u}var zH=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],DH=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],LH=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function ek(e){return zH.indexOf(e.op)>=0}function BH(e){return DH.indexOf(e.op)>=0}function WH(e){return LH.indexOf(e.op)>=0}var dy=class{constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},this.intermediateTensors={},this.keepTensorForDebug=!1,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(r=>{this._functionExecutorMap[r]=new dy(e.functions[r],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(r=>e[r].map(n=>n.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 r=e.map(a=>a.name).sort(),n=t.map(a=>a.name).sort();return r.join(this.SEPERATOR)+"--"+n.join(this.SEPERATOR)}compile(e,t){let r=W4(e,t,this.weightMap,this._initNodes),{missingInputs:n,dynamicNode:a,syncInputs:s}=r;if(a!=null)throw new Error(`This execution contains the node '${a.name}', which has the dynamic op '${a.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${s}]`);if(n.length>0){let i=t.map(l=>l.name),o=Object.keys(e);throw new Error(`Cannot compute the outputs [${i}] from the provided inputs [${o}]. Missing the following inputs: [${n}]`)}return OH(this.graph,this.weightMap,r)}execute(e,t){e=this.mapInputs(e);let r=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);let n=r.map(d=>this.graph.nodes[pn(d)[0]]),a=t.map(d=>pn(d)[0]),s=a.map(d=>this.graph.nodes[d]);this.resetIntermediateTensors(),s.length===0&&(s=this._outputs);let i=this.getCompilationKey(n,s),o=this.compiledMap.get(i);o==null&&(o=this.compile(e,s),this.compiledMap.set(i,o));let l={},u={};return X(()=>{let d=new B4(this.weightMap,l,u,this.functionExecutorMap),h={...this.weightMap};Object.keys(e).forEach(m=>{let[f,g]=pn(m),y=[];y[g]=e[m],h[f]=y});let p=this.getFrozenTensorIds(h),c={};for(let m=0;m<o.length;m++){let f=o[m];if(!h[f.name]){let g=L4(f,h,d,this._resourceManager);if(v.isPromise(g))throw new Error(`The execution of the op '${f.op}' returned a promise. Please use model.executeAsync() instead.`);h[f.name]=g,this.checkTensorForDisposal(f.name,f,h,d,p,a,c)}}return this.parent==null&&d.dispose(p),t.map(m=>Br(m,h,d))})}getFrozenTensorIds(e){let t=[].concat.apply([],Object.keys(e).map(r=>e[r]).map(r=>r.map(n=>n.id)));return new Set(t)}checkTensorForDisposal(e,t,r,n,a,s,i){t.category==="control"||s.indexOf(e)!==-1||(r[e].forEach(o=>{o!=null&&(i[o.id]=(i[o.id]||0)+t.children.length)}),t.inputs.forEach(o=>{if(o.category!=="control"){let l=Uj(o.name,r,n);l!=null&&l.forEach(u=>{if(u&&!u.kept&&!a.has(u.id)){let d=i[u.id];if(d===1){if(!this.keepTensorForDebug)u.dispose();else{let[h,p]=Ra(t.name,n);this.intermediateTensors[h]?this.intermediateTensors[h][p]=u:(this.intermediateTensors[h]=[],this.intermediateTensors[h][p]=u)}delete i[u.id]}else d!=null&&i[u.id]--}})}}))}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){!this.intermediateTensors||(Object.keys(this.intermediateTensors).forEach(e=>this.intermediateTensors[e].forEach(t=>t.dispose())),this.disposeTensorsMap())}disposeTensorsMap(){!this.tensorsMap||Object.keys(this.tensorsMap).forEach(e=>{this.tensorsMap[e].forEach(t=>{t&&!t.kept&&!t.isDisposed&&!this.keepIds.has(t.id)&&t.dispose()})})}getIntermediateTensors(){return this.tensorsMap}resetIntermediateTensors(){for(let e in this.intermediateTensors)this.intermediateTensors[e].forEach(t=>t.dispose()),delete this.intermediateTensors[e]}async _executeAsync(e,t,r=!1,n={},a={}){r||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepTensorForDebug=Z().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(u){console.warn(u.message)}this.resetIntermediateTensors();let s=new B4(this.weightMap,n,a,this.functionExecutorMap);this.tensorsMap=await this.executeWithControlFlow(e,s,t,r);let i=t.map(u=>Br(u,this.tensorsMap,s)),o=i.map(u=>u.id),l=Object.keys(e).map(u=>e[u].id);return this.keepIds=new Set([...o,...l,...this.weightIds]),this.keepTensorForDebug||this.disposeTensorsMap(),this.parent==null&&s.dispose(this.keepIds),i}async executeFunctionAsync(e,t,r){let n=e.reduce((a,s,i)=>(a[this.inputs[i].name]=s,a),{});return this._executeAsync(n,this.outputNodes,!0,t,r)}async executeWithControlFlow(e,t,r,n){let a=Object.keys(e),s=a.map(A=>this.graph.nodes[pn(A)[0]]),i=r.map(A=>pn(A)[0]),o=i.map(A=>this.graph.nodes[A]);o.length===0&&(o=this._outputs);let{usedNodes:l,missingInputs:u,dynamicNode:d,syncInputs:h}=W4(e,o,this.weightMap,this._initNodes),p=[...s,...this.graph.weights,...this._initNodes||[]].map(A=>({node:A,contexts:t.currentContext})),c={...this.weightMap};Object.keys(e).forEach(A=>{let[x,b]=pn(A),w=[];w[b]=e[A],c[x]=w});let m={},f=this.getFrozenTensorIds(c),g={};for(;p.length>0;){let A=this.processStack(s,p,t,c,g,f,i,m,l);await Promise.all(A)}d==null&&!n&&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=o.filter(A=>!ek(A)&&!Br(A.name,c,t)).map(A=>A.name);if(y.length>0){let A="";throw d!=null&&(A=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${h}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${a}]. Consider providing the following inputs: [${u}]. ${A}`)}return c}processStack(e,t,r,n,a,s,i,o,l){let u=[];for(;t.length>0;){let d=t.pop();r.currentContext=d.contexts;let h="";if(d.node.op==="Enter"&&k("isConstant",d.node,n,r)&&([h]=Ra(d.node.name,r)),n[d.node.name]==null){let p=L4(d.node,n,r,this._resourceManager);h||([h]=Ra(d.node.name,r));let c=r.currentContext;v.isPromise(p)?u.push(p.then(m=>(n[h]=m,r.currentContext=c,this.checkTensorForDisposal(h,d.node,n,r,s,i,o),this.processChildNodes(d.node,t,r,n,a,l),m))):(n[h]=p,this.checkTensorForDisposal(h,d.node,n,r,s,i,o),this.processChildNodes(d.node,t,r,n,a,l))}else this.processChildNodes(d.node,t,r,n,a,l)}return u}processChildNodes(e,t,r,n,a,s){e.children.forEach(i=>{let[o]=Ra(i.name,r);a[o]||!s.has(i.name)||(i.op==="Merge"?i.inputNames.some(l=>!!Br(l,n,r))&&(a[o]=!0,t.push({contexts:r.currentContext,node:i})):i.inputNames.every(l=>!!Br(l,n,r))&&(a[o]=!0,t.push({contexts:r.currentContext,node:i})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{let r=e[t],[n]=pn(t),a=this.graph.nodes[n];if(a.attrParams.shape&&a.attrParams.shape.value){let s=a.attrParams.shape.value,i=s.length===r.shape.length&&r.shape.every((o,l)=>s[l]===-1||s[l]===o);v.assert(i,()=>`The shape of dict['${a.name}'] provided in model.execute(dict) must be [${s}], but was [${r.shape}]`)}a.attrParams.dtype&&a.attrParams.dtype.value&&v.assert(r.dtype===a.attrParams.dtype.value,()=>`The dtype of dict['${a.name}'] provided in model.execute(dict) must be ${a.attrParams.dtype.value}, but was ${r.dtype}`)})}mapInputs(e){let t={};for(let r in e)if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[r]!=null){let n=this._signature.inputs[r];t[n.name]=e[r]}else t[r]=e[r];return t}checkInputs(e){let t=Object.keys(e).filter(r=>{let[n]=pn(r);return this.graph.nodes[n]==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[r]=pn(t);if(!this.graph.nodes[r])throw new Error(`The output '${t}' is not found in the graph`)})}},VH=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]}},UH="?tfjs-format=file",GH="model.json",Uh=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new VH}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=Cr.browserHTTPRequest(e,this.loadOptions);else{let t=Cr.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(Cr.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]}}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=this.handler.load();return v.isPromise(e)?e.then(t=>this.loadSync(t)):this.loadSync(e)}loadSync(e){this.artifacts=e;let t=this.artifacts.modelTopology,r;this.artifacts.userDefinedMetadata!=null&&this.artifacts.userDefinedMetadata.signature!=null?r=this.artifacts.userDefinedMetadata.signature:r=this.artifacts.signature,this.signature=r,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;let n=Cr.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new dy(P4.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(n),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){let a=P4.Instance.transformGraph(e.modelInitializer);this.initializer=new dy(a),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 r=Cr.getSaveHandlers(e);if(r.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(r.length>1)throw new Error(`Found more than one (${r.length}) save handlers for URL '${e}'`);e=r[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 nt)&&!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,r,n)=>(t[r]=e[n],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 r=this.executor.execute(e,t);return r.length>1?r:r[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let r=await this.executor.executeAsync(e,t);return r.length>1?r:r[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,r)=>(t[r]=[e[r]],t),{})}dispose(){this.executor.dispose(),this.initializer&&this.initializer.dispose(),this.resourceManager.dispose()}};async function jH(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&&typeof e=="string"&&(e=qH(e));let r=new Uh(e,t);return await r.load(),r}function HH(e){if(e==null)throw new Error("modelUrl in loadGraphModelSync() cannot be null. Please provide a url or an IOHandler that loads the model");if(!e.load)throw new Error(`modelUrl IO Handler ${e} has no load function`);let t=new Uh(e);return t.load(),t}function qH(e){return e.endsWith("/")||(e=e+"/"),`${e}${GH}${UH}`}var XH="0.0.0",tk={};Be(tk,{CSVDataset:()=>ck,Dataset:()=>Ed,FileDataSource:()=>bk,TextLineDataset:()=>hk,URLDataSource:()=>vk,array:()=>yq,csv:()=>Nq,func:()=>Eq,generator:()=>Rq,microphone:()=>Mq,version_data:()=>Fq,webcam:()=>$q,zip:()=>Aq});var KH=Vo(sf()),ZH=Vo(sf());function YH(e,t){return q0(e,t)}function q0(e,t,r=new Map,n=new Set){if(e==null)return null;if(typeof Blob=="function"&&e instanceof Blob)return e.slice();if(n.has(e))throw new Error("Circular references are not supported.");if(r.has(e))return r.get(e);let a=t(e);if(a.recurse&&a.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(a.recurse)if(Lu(e)){let s=Array.isArray(e)?[]:{};n.add(e);for(let i in e){let o=e[i],l=q0(o,t,r,n);s[i]=l}return n.delete(e),e.__proto__&&(s.__proto__=e.__proto__),s}else throw new Error(`Can't recurse into non-iterable type: ${e}`);else return r.set(e,a.value),a.value}function JH(e,t=nk){return rk(e,t)}function rk(e,t,r=new Set){let n=e[0];if(r.has(n))throw new Error("Circular references are not supported.");let a=t(e);if(a.recurse&&a.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(a.recurse)if(Lu(n)){let s=Array.isArray(n)?[]:{};r.add(n);for(let i in n){let o=e.map(u=>u[i]),l=rk(o,t,r);s[i]=l}return r.delete(n),s}else throw new Error(`Can't recurse into non-iterable type: ${n}`);else return a.value}function nk(e){return e===null?null:Lu(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function ak(e,t){let r=new Map;q0(e,t,r);for(let n of Array.from(r.keys())){let a=r.get(n);if(v.isPromise(a)){let s=await a;r.set(n,s)}}return q0(e,t,r)}function Lu(e){let t=!1;if(Z().get("IS_BROWSER"))t=e instanceof TextDecoder;else{let{StringDecoder:r}=O7();t=e instanceof r}return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof nt)&&!(e instanceof Promise)&&!t)}function QH(e){return e==null||eq(e)||Array.isArray(e)||typeof e=="object"&&e instanceof nt||v.isTypedArray(e)}function eq(e){return e===null||typeof e!="object"&&typeof e!="function"}function tq(e){return YH(e,rq)}function rq(e){return e instanceof nt?{value:e.clone(),recurse:!1}:Lu(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}var sk=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),r=this.get(t);return this.set(t,this.pop()),r}},ik=class extends sk{constructor(){super(ik.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),r=this.length();for(let n=0;n<r;n++)t[n]=this.get(this.wrap(this.begin+n));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=r}},ok=ik;ok.INITIAL_CAPACITY=32;function lk(e){return new sq(e)}function uA(e){return new iq(e)}function nq(e,t){return new uk(e,t)}function aq(e,t=dk.FAIL){return new mq(e,t)}var xr=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=[],r=await e.next();for(;!r.done;)t.push(r.value),r=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(),r=e(t.value);for(;!t.done&&r;)t=await this.next(),r=e(t.value)}handleErrors(e){return new cq(this,e)}filter(e){return new pq(this,e)}map(e){return new hq(this,e)}mapAsync(e){return new V4(this,e)}serialMapAsync(e){return new V4(this,e).serial()}flatmap(e){return new fq(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 dq(this,e,t)}columnMajorBatch(e,t=!0,r=nk){return this.rowMajorBatch(e,t).map(n=>JH(n,r))}concatenate(e,t){return new uk(lk([this,e]),t)}take(e){return e<0||e==null?this:new uq(this,e)}skip(e){return e<0||e==null?this:new lq(this,e)}prefetch(e){return new pk(this,e)}shuffle(e,t){return new gq(this,e,t)}serial(){return new oq(this)}},sq=class extends xr{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:tq(e),done:!1}}},iq=class extends xr{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}}},oq=class extends xr{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()}},lq=class extends xr{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;ee(e.value)}return this.upstream.next()}},uq=class extends xr{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()}},dq=class extends xr{constructor(e,t,r=!0){super(),this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=r,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}}},pq=class extends xr{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;ee(e.value)}}},hq=class extends xr{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=ha.getTensorsInContainer(e.value),r=this.transform(e.value),n=ha.getTensorsInContainer(r);for(let a of t)ha.isTensorInList(a,n)||a.dispose();return{value:r,done:!1}}},cq=class extends xr{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}}}},V4=class extends xr{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=ha.getTensorsInContainer(e.value),r=await this.transform(e.value),n=ha.getTensorsInContainer(r);for(let a of t)ha.isTensorInList(a,n)||a.dispose();return{value:r,done:!1}}},dA=class extends xr{constructor(){super(),this.outputQueue=new ok,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}}},fq=class extends dA{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=ha.getTensorsInContainer(e.value),r=this.transform(e.value),n=ha.getTensorsInContainer(r);this.outputQueue.pushAll(r);for(let a of t)ha.isTensorInList(a,n)||a.dispose();return!0}},uk=class extends xr{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 r=await this.moreIterators.next();if(r.done)return{value:null,done:!0};this.iterator=r.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}},dk=(e=>(e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST",e))(dk||{}),mq=class extends xr{constructor(e,t=0){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,r=0;function n(s){return s instanceof xr?{value:s.next().then(i=>(t++,i.done&&r++,i.value)),recurse:!1}:{value:null,recurse:!0}}let a=await ak(this.iterators,n);if(t===r)return{value:null,done:!0};if(r>0)switch(this.mismatchMode){case 0:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case 1:return{value:null,done:!0};case 2:default:}return this.count++,{value:a,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},pk=class extends xr{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new sk(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()}},gq=class extends pk{constructor(e,t,r){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=ZH.alea(r||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}}},Ed=class{constructor(){this.size=null}batch(e,t=!0){let r=this;v.assert(e>0,()=>`batchSize needs to be positive, but it is
|
|
${e}`);let n;return this.size===1/0||this.size==null?n=this.size:t?n=Math.ceil(this.size/e):n=Math.floor(this.size/e),dn(async()=>(await r.iterator()).columnMajorBatch(e,t,xq),n)}concatenate(e){let t=this,r;return this.size===1/0||e.size===1/0?r=1/0:this.size!=null&&e.size!=null?r=this.size+e.size:r=null,dn(async()=>(await t.iterator()).concatenate(await e.iterator()),r)}filter(e){let t=this,r;return this.size===1/0?r=1/0:r=null,dn(async()=>(await t.iterator()).filter(n=>X(()=>e(n))),r)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return dn(async()=>(await t.iterator()).map(r=>X(()=>e(r))),this.size)}mapAsync(e){let t=this;return dn(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 dn(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){let t=this,r;return this.size!=null&&e>0?r=this.size*e:e===0?r=0:this.size!=null&&(e===void 0||e<0)?r=1/0:r=null,dn(async()=>{let n=uA(async()=>({value:await t.iterator(),done:!1}));return nq(n.take(e))},r)}skip(e){let t=this,r;return this.size!=null&&e>=0&&this.size>=e?r=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?r=0:r=null,dn(async()=>(await t.iterator()).skip(e),r)}shuffle(e,t,r=!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 n=this,a=KH.alea(t||v.now().toString());return dn(async()=>{let s=a.int32();return r&&(s+=a.int32()),(await n.iterator()).shuffle(e,s.toString())},this.size)}take(e){let t=this,r;return this.size!=null&&this.size>e?r=e:this.size!=null&&this.size<=e?r=this.size:r=null,dn(async()=>(await t.iterator()).take(e),r)}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()}};Ed.MAX_BUFFER_SIZE=1e4;function dn(e,t=null){return new class extends Ed{constructor(){super(...arguments),this.size=t}async iterator(){return e()}}}function yq(e){return dn(async()=>lk(e),e.length)}function Aq(e){if(!Lu(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let r=0;r<e.length;r++)t=t==null?e[r].size:Math.min(t,e[r].size);else if(e instanceof Object)for(let r in e)t=t==null?e[r].size:Math.min(t,e[r].size);return dn(async()=>{let r=await ak(e,n=>{if(n instanceof Ed)return{value:n.iterator(),recurse:!1};if(Lu(n))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return aq(r,1)},t)}function xq(e){if(e===null)return null;let t=e[0];return QH(t)?{value:bq(e),recurse:!1}:{value:null,recurse:!0}}function bq(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof nt?ur(e):ft(e)}var hk=class extends Ed{constructor(e){super(),this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split(`
|
|
`).map(e=>(e.endsWith("\r")&&(e=e.slice(0,-1)),e))}},o0='"',Np=Symbol("out"),U4=Symbol("field"),l0=Symbol("quote"),Ig=Symbol("quoteafterquote"),G4=Symbol("quoteinquote"),ck=class extends Ed{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 hk(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((n,a)=>(n[a]=n[a]+1||1,n),{}),r=Object.keys(t).filter(n=>t[n]>1);if(v.assert(r.length===0,()=>"Duplicate column names found: "+r.toString()),this.columnConfigs){for(let n of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(n)===-1)throw new Error('The key "'+n+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let e=await(await this.base.iterator()).next();if(e.done)throw new Error("No data was found for CSV parsing.");let t=e.value;return this.parseRow(t,!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),r={},n={};for(let a=0;a<this.fullColumnNames.length;a++){let s=this.fullColumnNames[a],i=this.columnConfigs?this.columnConfigs[s]:null;if(!(this.configuredColumnsOnly&&!i)){let o=t[a],l=null;if(o==="")if(i&&i.default!==void 0)l=i.default;else{if(i&&(i.required||i.isLabel))throw new Error(`Required column ${s} is empty in this line: ${e}`);l=void 0}else{let u=Number(o);if(isNaN(u))i&&i.dtype==="bool"?l=this.getBoolean(o):l=o;else if(!i||!i.dtype)l=u;else switch(i.dtype){case"float32":l=u;break;case"int32":l=Math.floor(u);break;case"bool":l=this.getBoolean(o);break;default:l=u}}i&&i.isLabel?n[s]=l:r[s]=l}}return Object.keys(n).length===0?r:{xs:r,ys:n}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let r=[],n=0,a=e.length,s=Np;for(let i=0;i<a;i++)switch(s){case Np:switch(e.charAt(i)){case o0:n=i+1,s=l0;break;case this.delimiter:if(n=i+1,this.delimiter===" "&&this.delimWhitespace)break;r.push(""),s=Np;break;default:s=U4,n=i;break}break;case U4:switch(e.charAt(i)){case this.delimiter:r.push(e.substring(n,i)),s=Np,n=i+1;break;default:}break;case l0:switch(e.charAt(i)){case o0:s=Ig;break;default:}break;case Ig:switch(e.charAt(i)){case this.delimiter:r.push(e.substring(n,i-1)),s=Np,n=i+1;break;case o0:s=l0;break;default:s=G4;break}break;case G4:switch(e.charAt(i)){case o0:s=l0;break;default:}break;default:}if(s===Ig?r.push(e.substring(n,a-1)):r.push(e.substring(n)),t&&r.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${r}`);return r}},fk=class extends xr{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_BROWSER"))throw new Error("microphone API is only supported in browser environment.");let t=new fk(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(r){throw new Error(`Error thrown while initializing video stream: ${r.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,r=await this.getAudioData();if(this.includeSpectrogram){let n=this.flattenQueue(r.freqDataQueue);e=this.getTensorFromAudioDataArray(n,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){let n=this.flattenQueue(r.timeDataQueue);t=this.getTensorFromAudioDataArray(n,[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=[],r=0;return new Promise(n=>{let a=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&n({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++r===this.numFrames&&(clearInterval(a),n({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,r=new Float32Array(e.length*t);return e.forEach((n,a)=>r.set(n,a*t)),r}getTensorFromAudioDataArray(e,t){let r=new Float32Array(v.sizeFromShape(t));return r.set(e,r.length-e.length),ft(r,t)}},mk=class extends xr{constructor(e,t){if(super(),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=Nt([0],"int32"),this.webcamConfig.centerCrop){let r=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,n=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,a=(1-r)/2,s=(1-n)/2,i=a+r,o=n+s;this.cropBox=ca([s,a,o,i],[1,4])}else this.cropBox=ca([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(!Z().get("IS_BROWSER"))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 r=new mk(e,t);return await r.start(),r}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=Ln.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 X(()=>{let t=Kt(me(e,"float32"),0),r;r=Ie.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let n=r.shape;return U(r,n.slice(1))})}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach(e=>e.stop());try{this.webcamVideoElement.srcObject=null}catch(e){console.log(e),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}},gk=class{},yk=class extends xr{split(e){return new vq(this,e)}},vq=class extends yk{constructor(e,t){super(),this.upstream=e,this.impl=new wq(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},wq=class extends dA{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 r of t.slice(0,-1))this.outputQueue.push(r);return this.carryover=t[t.length-1],!0}},kq=class extends xr{decodeUTF8(){return new Iq(this)}},Iq=class extends yk{constructor(e){super(),this.upstream=e,this.impl=new Sq(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},Sq=class extends dA{constructor(e){if(super(),this.upstream=e,Z().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=O7();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 r;return Z().get("IS_BROWSER")?r=this.decoder.decode(t,{stream:!0}):r=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(r),!0}},Ak=class extends kq{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((e,t)=>{let r=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)e(new Uint8Array(this.file.slice(this.offset,r)));else{let n=new FileReader;n.onload=s=>{let i=n.result;if(i instanceof ArrayBuffer&&(i=new Uint8Array(i)),!(i instanceof Uint8Array))return t(new TypeError("FileReader returned unknown type."));e(i)},n.onabort=s=>t(new Error("Aborted")),n.onerror=s=>t(new Error(s.type));let a=this.file.slice(this.offset,r);n.readAsArrayBuffer(a)}this.offset=r}),done:!1}}};async function Cq(e,t={},r){let n,a;typeof e=="string"?n=e:(n=e.url,a=Tq(e));let s=await(r||v.fetch)(n,a);if(s.ok){let i=new Uint8Array(await s.arrayBuffer());return new Ak(i,t)}else throw new Error(s.statusText)}var Tq=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 xk(e){return typeof e=="string"&&e.slice(0,7)==="file://"}var bk=class extends gk{constructor(e,t={}){super(),this.input=e,this.options=t}async iterator(){if(xk(this.input)&&Z().get("IS_NODE")){let e=Ty();this.input=e.readFileSync(this.input.slice(7))}return new Ak(this.input,this.options)}},vk=class extends gk{constructor(e,t={}){super(),this.url=e,this.fileOptions=t}async iterator(){return xk(this.url)?new bk(this.url,this.fileOptions).iterator():Cq(this.url,this.fileOptions)}};function Nq(e,t={}){return new ck(new vk(e),t)}function Eq(e){let t=uA(e);return dn(async()=>t)}function Rq(e){return dn(async()=>{let t=await e();return uA(()=>t.next())})}async function $q(e,t){return mk.create(e,t)}async function Mq(e){return fk.create(e)}var Fq="0.0.0";function Ce(e,t){Array.isArray(e)||(e=[e]),e.forEach(r=>{r!=null&&v.assert(r.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}var _q=Kn.whereImpl,wk=class extends Gu{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new nh(this,Xt())}nextDataId(){return wk.nextDataId++}write(e,t,r){this.firstUse&&(this.firstUse=!1,Z().get("IS_NODE")&&C.warn(`
|
|
============================
|
|
Hi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details.
|
|
============================`));let n={id:this.nextDataId()};return this.data.set(n,{values:e,dtype:r,refCount:1}),n}makeTensorInfo(e,t,r){let n;if(t==="string"&&r!=null&&r.length>0&&v.isString(r[0])){let a=r.map(s=>v.encodeString(s));n=this.write(a,e,t)}else n=this.write(r,e,t);return{dataId:n,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,r,n,a){this.data.set(e,{values:t,dtype:n,refCount:a})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:r}=this.data.get(e);if(t==="complex64"){let n=this.readSync(r.real.dataId),a=this.readSync(r.imag.dataId);return C.mergeRealAndImagArrays(n,a)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId);if(e.dtype==="string")try{let r=t.map(n=>v.decodeString(n));return De(e.shape,e.dtype,r)}catch(r){throw new Error("Failed to decode encoded string bytes into utf-8")}return De(e.shape,e.dtype,t)}makeOutput(e,t,r){return Xt().makeTensorFromTensorInfo(this.makeTensorInfo(t,r,e),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:r}=this.data.get(e);r!=null&&(this.disposeData(r.real.dataId,!0),this.disposeData(r.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){Ce([e],"where");let t=this.readSync(e.dataId);return _q(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}},pA=wk;pA.nextDataId=0;var $m={};Be($m,{addImpl:()=>Ik,bincountImpl:()=>cA,bincountReduceImpl:()=>Sk,ceilImpl:()=>Ck,concatImpl:()=>fA,equalImpl:()=>Tk,expImpl:()=>Ek,expm1Impl:()=>$k,floorImpl:()=>Mk,gatherNdImpl:()=>Fk,gatherV2Impl:()=>_k,greaterEqualImpl:()=>Ok,greaterImpl:()=>Pk,lessEqualImpl:()=>Dk,lessImpl:()=>zk,linSpaceImpl:()=>Lk,logImpl:()=>Bk,maxImpl:()=>Wk,maximumImpl:()=>Vk,minimumImpl:()=>Uk,multiplyImpl:()=>mA,negImpl:()=>Gk,notEqualImpl:()=>jk,prodImpl:()=>Hk,rangeImpl:()=>yA,rsqrtImpl:()=>qk,scatterImpl:()=>wu,sigmoidImpl:()=>wX,simpleAbsImpl:()=>kk,sliceImpl:()=>K0,sparseFillEmptyRowsImpl:()=>Kk,sparseReshapeImpl:()=>Zk,sparseSegmentReductionImpl:()=>AA,sqrtImpl:()=>SX,squaredDifferenceImpl:()=>Yk,stridedSliceImpl:()=>Jk,stringNGramsImpl:()=>Qk,stringSplitImpl:()=>e9,stringToHashBucketFastImpl:()=>t9,subImpl:()=>r9,tileImpl:()=>n9,topKImpl:()=>s9,transposeImpl:()=>gA,uniqueImpl:()=>i9});function kk(e){let t=new Float32Array(e.length);for(let r=0;r<e.length;++r)t[r]=Math.abs(e[r]);return t}var Pq=e=>{let{x:t}=e.inputs,r=e.backend;Ce(t,"abs");let n=new Float32Array(v.sizeFromShape(t.shape)),a=r.data.get(t.dataId).values;return n=kk(a),r.makeOutput(n,t.shape,t.dtype)},Oq={kernelName:Go,backendName:"cpu",kernelFunc:Pq};function Qt(e){return(t,r,n,a,s)=>{let i=C.assertAndGetBroadcastShape(t,r),o=i.length,l=v.computeStrides(i),u=v.sizeFromShape(i),d=v.getTypedArrayFromDType(s,u),h=t.length,p=r.length,c=v.computeStrides(t),m=v.computeStrides(r),f=C.getBroadcastDims(t,i),g=C.getBroadcastDims(r,i);if(f.length+g.length===0)for(let y=0;y<d.length;++y)d[y]=e(n[y%n.length],a[y%a.length]);else for(let y=0;y<d.length;++y){let A=v.indexToLoc(y,o,l),x=A.slice(-h);f.forEach(T=>x[T]=0);let b=v.locToIndex(x,h,c),w=A.slice(-p);g.forEach(T=>w[T]=0);let I=v.locToIndex(w,p,m);d[y]=e(n[b],a[I])}return[d,i]}}function hn(e){let{inputs:t,backend:r}=e,{real:n,imag:a}=t,s=r.data.get(n.dataId).values,i=r.data.get(a.dataId).values,o=r.makeTensorInfo(n.shape,"complex64"),l=r.data.get(o.dataId);return l.complexTensorInfos={real:r.makeTensorInfo(n.shape,"float32",s),imag:r.makeTensorInfo(a.shape,"float32",i)},o}var zq={kernelName:sh,backendName:"cpu",kernelFunc:hn};function X0(e,t,r="float32"){if(r==="complex64"){let a=X0(e,t,"float32"),s=X0(e,t,"float32");return hn({inputs:{real:a,imag:s},backend:e})}let n=v.makeZerosTypedArray(v.sizeFromShape(t),r);return e.makeTensorInfo(t,r,n)}function Oa(e){let{inputs:t,backend:r}=e,{x:n}=t;return r.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}var Dq={kernelName:mi,backendName:"cpu",kernelFunc:Oa};function zo(e){let{inputs:t,backend:r}=e,{input:n}=t,a=r.data.get(n.dataId).complexTensorInfos.real,s=r.data.get(a.dataId).values;return r.makeTensorInfo(a.shape,a.dtype,s)}var Lq={kernelName:ch,backendName:"cpu",kernelFunc:zo};function qs(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{dtype:s}=n;if(s==="complex64"){if(a.dtype==="complex64")return Oa({inputs:{x:a},backend:r});let i=X0(r,a.shape,a.dtype),o=qs({inputs:{x:a},backend:r,attrs:{dtype:"float32"}}),l=hn({inputs:{real:o,imag:i},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}if(a.dtype==="complex64"){let i=zo({inputs:{input:a},backend:r}),o=qs({inputs:{x:i},backend:r,attrs:{dtype:s}});return r.disposeIntermediateTensorInfo(i),o}if(!v.hasEncodingLoss(a.dtype,s)){let i=Oa({inputs:{x:a},backend:r});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32"){let i=r.data.get(a.dataId).values,o=Int32Array.from(i);return r.makeTensorInfo(a.shape,"int32",o)}if(s==="bool"){let i=r.data.get(a.dataId).values,o=v.toTypedArray([0],a.dtype),[l,u]=Qt((d,h)=>d!==h?1:0)(a.shape,[],i,o,"bool");return r.makeTensorInfo(u,"bool",l)}throw new Error(`Error in Cast: failed to cast ${a.dtype} to ${s}`)}var Bq={kernelName:ei,backendName:"cpu",kernelFunc:qs};function br(e,t,r,n){return r==null?({inputs:a,backend:s})=>{let{a:i,b:o}=a,l=s;Ce([i,o],e);let u=l.data.get(i.dataId).values,d=l.data.get(o.dataId).values,h=i.dtype==="string"?C.fromUint8ToStringArray(u):u,p=i.dtype==="string"?C.fromUint8ToStringArray(d):d,c=n||i.dtype,[m,f]=t(i.shape,o.shape,h,p,c);return l.makeTensorInfo(f,c,m)}:({inputs:a,backend:s})=>{let{a:i,b:o}=a,l=s;if(i.dtype==="complex64"||o.dtype==="complex64"){let u=qs({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),d=l.data.get(u.dataId),h=d.complexTensorInfos.real,p=d.complexTensorInfos.imag,c=l.data.get(h.dataId).values,m=l.data.get(p.dataId).values,f=qs({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(f.dataId),y=g.complexTensorInfos.real,A=g.complexTensorInfos.imag,x=l.data.get(y.dataId).values,b=l.data.get(A.dataId).values,[w,I,T]=r(i.shape,o.shape,c,m,x,b),E=l.makeTensorInfo(T,"float32",w),R=l.makeTensorInfo(T,"float32",I),F=hn({inputs:{real:E,imag:R},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(f),l.disposeIntermediateTensorInfo(E),l.disposeIntermediateTensorInfo(R),F}else{let u=l.data.get(i.dataId).values,d=l.data.get(o.dataId).values,h=n||i.dtype,[p,c]=t(i.shape,o.shape,u,d,h);return l.makeTensorInfo(c,h,p)}}}function hA(e){return(t,r,n,a,s,i)=>{let o=C.assertAndGetBroadcastShape(t,r),l=v.sizeFromShape(o),u=o.length,d=v.computeStrides(o),h=v.getTypedArrayFromDType("float32",l),p=v.getTypedArrayFromDType("float32",l),c=C.getBroadcastDims(t,o),m=C.getBroadcastDims(r,o),f=C.mergeRealAndImagArrays(n,a),g=C.mergeRealAndImagArrays(s,i),y=t.length,A=v.computeStrides(t),x=r.length,b=v.computeStrides(r);if(c.length+m.length===0)for(let w=0;w<h.length;w++){let I=w%f.length,T=w%g.length,E=e(f[I*2],f[I*2+1],g[T*2],g[T*2+1]);h[w]=E.real,p[w]=E.imag}else for(let w=0;w<h.length;w++){let I=v.indexToLoc(w,u,d),T=I.slice(-y);c.forEach(S=>T[S]=0);let E=v.locToIndex(T,y,A),R=I.slice(-x);m.forEach(S=>R[S]=0);let F=v.locToIndex(R,x,b),$=e(f[E*2],f[E*2+1],g[F*2],g[F*2+1]);h[w]=$.real,p[w]=$.imag}return[h,p,o]}}var Ik=Qt((e,t)=>e+t),Wq=hA((e,t,r,n)=>({real:e+r,imag:t+n})),Bu=br(Qa,Ik,Wq),Vq={kernelName:Qa,backendName:"cpu",kernelFunc:Bu};function cA(e,t,r,n,a){let s=v.sizeFromShape(n),i=v.makeZerosTypedArray(a,r);for(let o=0;o<e.length;o++){let l=e[o];if(l<0)throw new Error("Input x must be non-negative!");l>=a||(s>0?i[l]+=t[o]:i[l]+=1)}return i}function Sk(e,t,r,n=!1){let a=e.shape[0],s=e.shape[1],i=De([a,r],t.dtype);for(let o=0;o<a;o++)for(let l=0;l<s;l++){let u=e.get(o,l);if(u<0)throw new Error("Input x must be non-negative!");u>=r||(n?i.set(1,o,u):t.size>0?i.set(i.get(o,u)+t.get(o,l),o,u):i.set(i.get(o,u)+1,o,u))}return i}function ji(e){return(t,r,n)=>{let a=v.getTypedArrayFromDType(r,t.length);for(let s=0;s<t.length;++s)a[s]=e(t[s],n);return a}}function gt(e,t,r){return({inputs:n,attrs:a,backend:s})=>{let{x:i}=n;if(Ce(i,e),i.dtype==="string"||r==="string")throw new Error("unaryKernelFunc does not support string input/output");let o=s,l=o.data.get(i.dataId).values,u=v.sizeFromShape(i.shape),d=r||i.dtype,h=v.getArrayFromDType(d,u);for(let p=0;p<u;++p)h[p]=t(l[p],a);return o.makeTensorInfo(i.shape,d,h)}}function Rd(e,t,r){return({inputs:n,attrs:a,backend:s})=>{let{x:i}=n;if(Ce(i,e),i.dtype==="string"||r==="string")throw new Error("unaryKernelFunc does not support string input/output");let o=s,l=o.data.get(i.dataId).values,u=r||i.dtype,d=t(l,u,a);return o.makeTensorInfo(i.shape,u,d)}}var Ck=ji(e=>Math.ceil(e)),Uq=Rd(ti,Ck),Gq={kernelName:ti,backendName:"cpu",kernelFunc:Uq};function fA(e,t,r,n){let a=v.getArrayFromDType(r,v.sizeFromShape(t));if(n&&r!=="string"){let s=0;e.forEach(i=>{let o=v.sizeFromShape(i.shape);a.set(i.vals,s),s+=o})}else{let s=0;e.forEach(i=>{let o=r==="string"?C.fromUint8ToStringArray(i.vals):i.vals,l=0;for(let u=0;u<i.shape[0];++u){let d=u*t[1]+s;for(let h=0;h<i.shape[1];++h)a[d+h]=o[l++]}s+=i.shape[1]})}return a}var Tk=Qt((e,t)=>e===t?1:0),Nk=br(Zo,Tk,null,"bool"),jq={kernelName:Zo,backendName:"cpu",kernelFunc:Nk},Ek=ji(e=>Math.exp(e)),Rk=Rd(di,Ek,"float32"),Hq={kernelName:di,backendName:"cpu",kernelFunc:Rk},$k=ji(e=>Math.expm1(e)),qq=Rd(Jo,$k),Xq={kernelName:Jo,backendName:"cpu",kernelFunc:qq},Mk=ji(e=>Math.floor(e)),Kq=Rd(pi,Mk),Zq={kernelName:pi,backendName:"cpu",kernelFunc:Kq};function Fk(e,t,r,n,a,s,i,o,l){let u=De([n,s],r);for(let d=0;d<n;d++){let h=[],p=0;for(let c=0;c<a;c++){let m=e[d*a+c];p+=m*i[c],h.push(m)}if(p<0||p>=l/s)throw new Error(`Invalid indices: ${h} does not index into ${o}`);for(let c=0;c<s;c++)u.values[d*s+c]=t.get(...t.indexToLoc(p*s+c))}return u}function _k(e,t,r){let n=De(r,e.dtype);for(let a=0;a<n.size;++a){let s=n.indexToLoc(a).slice(),i=s[0],o=s[2],l=t.locToIndex([i,o]);s[2]=t.values[l];let u=e.locToIndex(s);0<=u&&u<e.values.length&&(n.values[a]=e.values[u])}return n}var Pk=Qt((e,t)=>e>t?1:0),Yq=br(rl,Pk,null,"bool"),Jq={kernelName:rl,backendName:"cpu",kernelFunc:Yq},Ok=Qt((e,t)=>e>=t?1:0),Qq=br(fi,Ok,null,"bool"),eX={kernelName:fi,backendName:"cpu",kernelFunc:Qq},zk=Qt((e,t)=>e<t?1:0),tX=br(nl,zk,null,"bool"),rX={kernelName:nl,backendName:"cpu",kernelFunc:tX},Dk=Qt((e,t)=>e<=t?1:0),nX=br(al,Dk,null,"bool"),aX={kernelName:al,backendName:"cpu",kernelFunc:nX};function Lk(e,t,r){let n=(t-e)/(r-1),a=v.makeZerosTypedArray(r,"float32");a[0]=e;for(let s=1;s<a.length;s++)a[s]=a[s-1]+n;return a}var Bk=ji(e=>Math.log(e)),sX=Rd(yi,Bk),iX={kernelName:yi,backendName:"cpu",kernelFunc:sX};function Wk(e,t,r,n){let a=v.getTypedArrayFromDType(n,v.sizeFromShape(r));for(let s=0;s<a.length;++s){let i=s*t,o=e[i];for(let l=0;l<t;++l){let u=e[i+l];(Number.isNaN(u)||u>o)&&(o=u)}a[s]=o}return a}var Vk=Qt((e,t)=>Math.max(e,t)),oX=br(xi,Vk),lX={kernelName:xi,backendName:"cpu",kernelFunc:oX},Uk=Qt((e,t)=>Math.min(e,t)),uX=br(ki,Uk),dX={kernelName:ki,backendName:"cpu",kernelFunc:uX},mA=Qt((e,t)=>e*t),pX=hA((e,t,r,n)=>({real:e*r-t*n,imag:e*n+t*r})),Mm=br(Si,mA,pX),hX={kernelName:Si,backendName:"cpu",kernelFunc:Mm};function Gk(e,t,r){let n=v.createScalarValue(-1,r);return mA([],t,n,e,r)}function cX(e){let{inputs:t,backend:r}=e,{x:n}=t;Ce(n,"neg");let a=r.data.get(n.dataId).values,[s,i]=Gk(a,n.shape,n.dtype);return r.makeTensorInfo(i,n.dtype,s)}var fX={kernelName:ol,backendName:"cpu",kernelFunc:cX},jk=Qt((e,t)=>e!==t?1:0),mX=br(ll,jk,null,"bool"),gX={kernelName:ll,backendName:"cpu",kernelFunc:mX};function gA(e,t,r,n,a){let s=t.length,i=v.sizeFromShape(t),o=v.computeStrides(t),l=v.computeStrides(a),u=v.getTypedArrayFromDType(r,v.sizeFromShape(a));for(let d=0;d<i;++d){let h=v.indexToLoc(d,s,o),p=new Array(h.length);for(let m=0;m<p.length;m++)p[m]=h[n[m]];let c=v.locToIndex(p,s,l);u[c]=e[d]}return u}function on(e){let{inputs:t,attrs:r,backend:n}=e,{x:a}=t,{perm:s}=r;Ce(a,"transpose");let i=a.shape.length,o=new Array(i);for(let d=0;d<o.length;d++)o[d]=a.shape[s[d]];let l=n.data.get(a.dataId).values,u=gA(l,a.shape,a.dtype,s,o);return{dataId:n.write(u,o,a.dtype),shape:o,dtype:a.dtype}}var yX={kernelName:$a,backendName:"cpu",kernelFunc:on};function Hk(e,t,r,n){let[a,s]=C.computeOutAndReduceShapes(e,n),i=Nr(t,"int32"),o=v.makeZerosTypedArray(v.sizeFromShape(a),i),l=v.sizeFromShape(s);for(let u=0;u<o.length;++u){let d=u*l,h=1;for(let p=0;p<l;++p)h*=r[d+p];o[u]=h}return{outVals:o,outShape:a,outDtype:i}}function AX(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;Ce(a,"prod");let o=a.shape.length,l=v.parseAxisParam(s,a.shape),u=C.getAxesPermutation(l,o),d=l,h=a,p=[];u!=null&&(h=on({inputs:{x:a},backend:r,attrs:{perm:u}}),p.push(h),d=C.getInnerMostAxes(d.length,o));let c=r.data.get(h.dataId).values,{outVals:m,outShape:f,outDtype:g}=Hk(h.shape,h.dtype,c,d),y=f;return i&&(y=C.expandShapeToKeepDim(f,l)),p.forEach(A=>r.disposeIntermediateTensorInfo(A)),r.makeTensorInfo(y,g,m)}var xX={kernelName:Ei,backendName:"cpu",kernelFunc:AX};function yA(e,t,r,n){let a=e===t,s=e<t&&r<0,i=t<e&&r>1;if(a||s||i)return v.makeZerosTypedArray(0,n);let o=Math.abs(Math.ceil((t-e)/r)),l=v.makeZerosTypedArray(o,n);t<e&&r===1&&(r=-1),l[0]=e;for(let u=1;u<l.length;u++)l[u]=l[u-1]+r;return l}var qk=ji(e=>1/Math.sqrt(e)),bX=Rd(Fi,qk),vX={kernelName:Fi,backendName:"cpu",kernelFunc:bX};function wu(e,t,r,n,a,s,i,o,l,u){let d=[n/a,a],h=e.values,p=t.values;if(n===0)return De(r,t.dtype);let c=De(d,t.dtype);typeof l=="string"||typeof l=="number"?c.values.fill(l):typeof l=="boolean"&&c.values.fill(+l);for(let m=0;m<s;m++){let f=[],g=0;for(let y=0;y<i;y++){let A=h[m*i+y];f.push(A),g+=A*o[y]}if(g<0||g>=n/a)throw new Error(`Invalid indices: ${f} does not index into ${r}`);for(let y=0;y<a;y++)u?c.values[g*a+y]+=p[m*a+y]:c.values[g*a+y]=t.rank===0?p[0]:p[m*a+y]}return c}var wX=ji(e=>1/(1+Math.exp(-e))),Xk=gt(Pi,e=>1/(1+Math.exp(-e))),kX={kernelName:Pi,backendName:"cpu",kernelFunc:Xk};function K0(e,t,r,n,a){let s=Dt.isSliceContinous(n,t,r),i=v.sizeFromShape(r),o=v.computeStrides(n);if(s){let h=Dt.computeFlatOffset(t,o);return a==="string"?e.slice(h,h+i):e.subarray(h,h+i)}let l=a==="string"?C.fromUint8ToStringArray(e):e,u=De(n,a,l),d=De(r,a);for(let h=0;h<d.size;++h){let p=d.indexToLoc(h),c=p.map((m,f)=>m+t[f]);d.set(u.get(...c),...p)}return a==="string"?C.fromStringArrayToUint8(d.values):d.values}function Do(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{begin:s,size:i}=n;Ce(a,"slice");let[o,l]=Dt.parseSliceParams(a,s,i);Dt.assertParamsValid(a,o,l);let u=r.data.get(a.dataId).values,d=K0(u,o,l,a.shape,a.dtype);return r.makeTensorInfo(l,a.dtype,d)}var IX={kernelName:xl,backendName:"cpu",kernelFunc:Do};function Kk(e,t,r,n,a,s,i){let o=t[0],l=s[0],u=new Array(l),d=new Array(o),h=t[1];if(l===0){if(o!==0)throw new Error(C.getSparseFillEmptyRowsIndicesDenseShapeMismatch(o));let g=v.getArrayFromDType(r,0),y=v.getArrayFromDType(a,0);return[g,[0,h],y,u,d]}let p=!0,c=0,m=new Array(l).fill(0);for(let g=0;g<o;++g){let y=e[g*h];if(y<0)throw new Error(C.getSparseFillEmptyRowsNegativeIndexErrorMessage(g,y));if(y>=l)throw new Error(C.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(g,y,l));++m[y],p=p&&y>=c,c=y}let f=!0;for(let g=0;g<l;++g){let y=m[g]===0;u[g]=y,f=f&&!y,m[g]=Math.max(m[g],1),g>0&&(m[g]+=m[g-1])}if(f&&p){let g=e,y=n;for(let A=0;A<o;++A)d[A]=A;return[g,[o,h],y,u,d]}else{let g=m[l-1],y=v.getArrayFromDType(r,g*h),A=v.getArrayFromDType(a,g),x=new Array(l).fill(0);for(let b=0;b<o;++b){let w=e[b*h],I=x[w],T=(w===0?0:m[w-1])+I;x[w]++;for(let E=0;E<h;++E)y[T*h+E]=e[b*h+E];A[T]=n[b],d[b]=T}for(let b=0;b<l;++b)if(x[b]===0){let w=b===0?0:m[b-1];y[w*h+0]=b;for(let I=1;I<h;++I)y[w*h+I]=0;A[w]=i}return[y,[g,h],A,u,d]}}function Zk(e,t,r,n,a){let s=v.sizeFromShape(n),i=t[0],o=a.length,l=[],u=1,d=-1;for(let f=0;f<o;++f){let g=a[f];if(g===-1){if(d!==-1)throw new Error(C.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(d,f));d=f,l.push(1)}else{if(g<0)throw new Error(C.getSparseReshapeNegativeOutputDimErrorMessage(f,g));u*=g,l.push(g)}}if(d!==-1){if(u<=0)throw new Error(C.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());let f=Math.trunc(s/u);if(u*f!==s)throw new Error(C.getSparseReshapeInputOutputMultipleErrorMessage(n,l));l[d]=f}if(v.sizeFromShape(l)!==s)throw new Error(C.getSparseReshapeInputOutputMismatchErrorMessage(n,l));let h=n.length,p=[];if(h>0){p[h-1]=1;for(let f=h-2;f>=0;--f)p[f]=p[f+1]*n[f+1]}let c=[];if(o>0){c[o-1]=1;for(let f=o-2;f>=0;--f)c[f]=c[f+1]*l[f+1]}let m=v.getArrayFromDType(r,i*o);for(let f=0;f<i;++f){let g=0;for(let y=0;y<h;++y)g+=e[f*h+y]*p[y];for(let y=0;y<o;++y)m[f*o+y]=Math.trunc(g/c[y]),g%=c[y]}return[m,[i,o],l]}function AA(e,t,r,n,a,s=!1,i=0){let o=n.length,l=[t[0],e.length/t[0]],u=l[1],d=o>0?a[o-1]+1:0;if(d<0)throw new Error(C.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let h=t.slice();h[0]=d;let p=h.reduce((A,x)=>A*x,1),c=v.getArrayFromDType(r,p);if(o===0)return d>0&&c.fill(i),[c,h];if(d<=0)throw new Error(C.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let m=0,f=1,g=0,y=a[m];for(;;){let A=0;if(f<o){if(A=a[f],y===A){++f;continue}if(y>=A)throw new Error(C.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage())}if(y<0||y>=d)throw new Error(C.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(y,d));y>g&&c.fill(i,g*u,y*u);for(let x=m;x<f;++x){let b=n[x];if(b<0||b>=l[0])throw new Error(C.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(x,n[x],l[0]));for(let w=0;w<u;w++)c[y*u+w]+=e[b*u+w]}if(s)for(let x=0;x<u;x++)c[y*u+x]/=f-m;if(m=f,++f,g=y+1,y=A,f>o)break}return g<d&&c.fill(i,g*u,d*u),[c,h]}var SX=ji(e=>Math.sqrt(e)),CX=gt(Oi,e=>Math.sqrt(e)),TX={kernelName:Oi,backendName:"cpu",kernelFunc:CX},Yk=Qt((e,t)=>{let r=e-t;return r*r}),NX=br(Li,Yk),EX={kernelName:Li,backendName:"cpu",kernelFunc:NX};function Jk(e,t,r,n){let a=De(e,t.dtype);for(let s=0;s<a.size;s++){let i=a.indexToLoc(s),o=new Array(i.length);for(let l=0;l<o.length;l++)o[l]=i[l]*r[l]+n[l];a.set(t.get(...o),...i)}return a}var RX=class{constructor(e,t,r,n,a,s){this.separator=v.encodeString(e),this.nGramWidths=t,this.leftPad=v.encodeString(r),this.rightPad=v.encodeString(n),this.padWidth=a,this.preserveShort=s}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){let r=this.getPadWidth(t);return Math.max(0,e+2*r-t+1)}createNGrams(e,t,r,n,a,s){for(let i=0;i<a;++i){let o=this.getPadWidth(s),l=Math.max(0,o-i),u=Math.max(0,o-(a-(i+1))),d=s-(l+u),h=t+(l>0?0:i-o),p=0;p+=l*this.leftPad.length;for(let g=0;g<d;++g)p+=e[h+g].length;p+=u*this.rightPad.length,p+=(l+u+d-1)*this.separator.length,r[n+i]=new Uint8Array(p);let c=r[n+i],m=0,f=g=>g.forEach(y=>c[m++]=y);for(let g=0;g<l;++g)f(this.leftPad),f(this.separator);for(let g=0;g<d-1;++g)f(e[h+g]),f(this.separator);if(d>0){f(e[h+d-1]);for(let g=0;g<u;++g)f(this.separator),f(this.rightPad)}else{for(let g=0;g<u-1;++g)f(this.rightPad),f(this.separator);f(this.rightPad)}}}compute(e,t){let r=e.length,n=t.length;if(n>0){let o=t[0];if(o!==0)throw new Error(`First split value must be 0, got ${o}`);for(let l=1;l<n;++l){let u=t[l]>=o;if(u=u&&t[l]<=r,!u)throw new Error(`Invalid split value ${t[l]}, must be in [${o}, ${r}]`);o=t[l]}if(o!==r)throw new Error(`Last split value must be data size. Expected ${r}, got ${o}`)}let a=n-1,s=v.getArrayFromDType("int32",n);if(r===0||n===0){let o=new Array(r);for(let l=0;l<=a;++l)s[l]=0;return[o,s]}s[0]=0;for(let o=1;o<=a;++o){let l=t[o]-t[o-1],u=0;this.nGramWidths.forEach(d=>{u+=this.getNumNGrams(l,d)}),this.preserveShort&&l>0&&u===0&&(u=1),s[o]=s[o-1]+u}let i=new Array(s[a]);for(let o=0;o<a;++o){let l=t[o],u=s[o];if(this.nGramWidths.forEach(d=>{let h=t[o+1]-t[o],p=this.getNumNGrams(h,d);this.createNGrams(e,l,i,u,p,d),u+=p}),this.preserveShort&&u===s[o]){let d=t[o+1]-t[o];if(d===0)continue;let h=d+2*this.padWidth,p=1;this.createNGrams(e,l,i,u,p,h)}}return[i,s]}};function Qk(e,t,r,n,a,s,i,o){return new RX(r,n,a,s,i,o).compute(e,t)}function $X(e,t,r,n){if(!e.length)return;if(t.length===0){for(let s=0;s<e.length;++s)n.push(e.subarray(s,s+1));return}if(t.length===1){let s=t[0],i=e.indexOf(s);for(;i!==-1;){let o=e.subarray(0,i);(!r||o.length!==0)&&n.push(o),e=e.subarray(i+1),i=e.indexOf(s)}(!r||e.length!==0)&&n.push(e);return}let a=0;for(let s=0;s<e.length+1;s++)if(s===e.length||t.indexOf(e[s])!==-1){let i=e.subarray(a,s);(!r||i.length!==0)&&n.push(i),a=s+1}}function e9(e,t,r){let n=e.length,a=[],s=0,i=0,o=new Array(n);for(let p=0;p<n;++p){let c=a.length;$X(e[p],t,r,a);let m=a.length-c;o[p]=m,s+=m,i=Math.max(i,m)}let l=v.getArrayFromDType("int32",s*2),u=new Array(s),d=[n,i],h=0;for(let p=0;p<n;++p)for(let c=0;c<o[p];++c)l[h*2]=p,l[h*2+1]=c,u[h]=a[h],++h;return[l,u,d]}function t9(e,t){let r=v.getArrayFromDType("int32",e.length);for(let n=0;n<e.length;++n)r[n]=v.fingerPrint64(e[n]).modulo(t).getLowBitsUnsigned();return r}var r9=Qt((e,t)=>e-t),MX=hA((e,t,r,n)=>({real:e-r,imag:t-n})),xA=br(Bi,r9,MX),FX={kernelName:Bi,backendName:"cpu",kernelFunc:xA};function n9(e,t){let r=new Array(e.rank);for(let a=0;a<r.length;a++)r[a]=e.shape[a]*t[a];let n=De(r,e.dtype);for(let a=0;a<n.values.length;++a){let s=n.indexToLoc(a),i=new Array(e.rank);for(let l=0;l<i.length;l++)i[l]=s[l]%e.shape[l];let o=e.locToIndex(i);n.values[a]=e.values[o]}return n}var _p=(e,t)=>{let r=t.value-e.value;return r===0?e.index-t.index:r};function a9(e,t,r=0,n=e.length-1){for(;n>r;){if(n-r>600){let o=n-r+1,l=t-r+1,u=Math.log(o),d=.5*Math.exp(2*u/3),h=.5*Math.sqrt(u*d*(o-d)/o)*Math.sign(l-o/2),p=Math.max(r,Math.floor(t-l*d/o+h)),c=Math.min(n,Math.floor(t+(o-l)*d/o+h));a9(e,t,p,c)}let a=e[t],s=r,i=n;for(v.swap(e,r,t),_p(e[n],a)>0&&v.swap(e,r,n);s<i;){for(v.swap(e,s,i),s++,i--;_p(e[s],a)<0;)s=s+1;for(;_p(e[i],a)>0;)i=i-1}_p(e[r],a)===0?v.swap(e,r,i):(i=i+1,v.swap(e,i,n)),i<=t&&(r=i+1),t<=i&&(n=i-1)}}function s9(e,t,r,n,a){let s=t[t.length-1],[i,o]=[e.length/s,s],l=v.getTypedArrayFromDType(r,i*n),u=v.getTypedArrayFromDType("int32",i*n);for(let h=0;h<i;h++){let p=h*o,c=e.subarray(p,p+o),m=new Array(c.length);c.forEach((A,x)=>m[x]={value:A,index:x}),n<m.length&&(a9(m,n),m=m.slice(0,n)),a&&m.sort(_p);let f=h*n,g=l.subarray(f,f+n),y=u.subarray(f,f+n);for(let A=0;A<n;A++)g[A]=m[A].value,y[A]=m[A].index}let d=t.slice();return d[d.length-1]=n,[De(d,r,l),De(d,"int32",u)]}function i9(e,t,r,n){let a=v.parseAxisParam(t,r)[0],s=[1,r[0],1];for(let m=0;m<a;m++)s[0]*=r[m];s[1]=r[a];for(let m=a+1;m<r.length;m++)s[2]*=r[m];let i={},o=new Int32Array(r[a]),l=new ir(s,n,e),u=[],d=s[0]===1&&s[2]===1;for(let m=0;m<r[a];m++){let f;if(d)f=e[m].toString();else{let g=[];for(let y=0;y<s[0];y++)for(let A=0;A<s[2];A++)g.push(l.get(y,m,A));f=g.join(",")}if(i[f]!==void 0)o[m]=i[f];else{let g=Object.keys(i).length;i[f]=g,o[m]=g,u.push(m)}}let h=s.slice();h[1]=Object.keys(i).length;let p=new ir(h,n);u.forEach((m,f)=>{for(let g=0;g<s[0];g++)for(let y=0;y<s[2];y++)p.set(l.get(g,m,y),g,f,y)});let c=r.slice();return c[a]=h[1],{outputValues:p.values,outputShape:c,indices:o}}var _X="0.0.0";Rl("cpu",()=>new pA,1);var o9=gt(ui,e=>e>=0?e:Math.exp(e)-1),PX={kernelName:ui,backendName:"cpu",kernelFunc:o9};function l9(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{alpha:s}=n;Ce([a],"leakyRelu");let i=v.sizeFromShape(a.shape),o=r.data.get(a.dataId).values,l=v.getTypedArrayFromDType("float32",i);for(let u=0;u<o.length;u++)l[u]=o[u]<0?s*o[u]:o[u];return r.makeTensorInfo(a.shape,"float32",l)}var OX={kernelName:gi,backendName:"cpu",kernelFunc:l9},zX=Qt((e,t)=>e<0?t*e:e);function u9(e){let{inputs:t,backend:r}=e,{x:n,alpha:a}=t;Ce([n,a],"prelu");let s=r.data.get(n.dataId).values,i=r.data.get(a.dataId).values,[o,l]=zX(n.shape,a.shape,s,i,"float32");return r.makeTensorInfo(l,"float32",o)}var DX={kernelName:Ni,backendName:"cpu",kernelFunc:u9},d9=gt(Ri,e=>Math.max(0,e)),LX={kernelName:Ri,backendName:"cpu",kernelFunc:d9},p9=gt(Mi,e=>Math.min(Math.max(0,e),6)),BX={kernelName:Mi,backendName:"cpu",kernelFunc:p9};function Z0(e,t,r,n,a){if(r==="linear")return Oa({inputs:{x:t},backend:e});if(r==="relu")return d9({inputs:{x:t},backend:e});if(r==="elu")return o9({inputs:{x:t},backend:e});if(r==="relu6")return p9({inputs:{x:t},backend:e});if(r==="prelu")return u9({inputs:{x:t,alpha:n},backend:e});if(r==="leakyrelu")return l9({inputs:{x:t},backend:e,attrs:{alpha:a}});if(r==="sigmoid")return Xk({inputs:{x:t},backend:e});throw new Error(`Activation ${r} has not been implemented for the CPU backend.`)}function Ct(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{shape:s}=n,i=v.sizeFromShape(a.shape),o=v.inferFromImplicitShape(s,i),l=v.sizeFromShape(o);v.assert(i===l,()=>`The new shape (${o}) has ${l} elements and the old shape (${a.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`),r.incRef(a.dataId);let u=r.data.get(a.dataId);if(u.complexTensorInfos!=null){let d=u.complexTensorInfos.real,h=u.complexTensorInfos.imag;d.shape=o,h.shape=o}return{dataId:a.dataId,shape:o,dtype:a.dtype}}var WX={kernelName:fl,backendName:"cpu",kernelFunc:Ct};function h9(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s}=t,{transposeA:i,transposeB:o}=n;Ce([a,s],"matMul");let l=a.shape.length,u=s.shape.length,d=i?a.shape[l-2]:a.shape[l-1],h=o?s.shape[u-1]:s.shape[u-2],p=i?a.shape[l-1]:a.shape[l-2],c=o?s.shape[u-2]:s.shape[u-1],m=a.shape.slice(0,-2),f=s.shape.slice(0,-2),g=v.sizeFromShape(m),y=v.sizeFromShape(f),A=$l.assertAndGetBroadcastShape(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([p,c]);v.assert(d===h,()=>`Error in matMul: inner shapes (${d}) and (${h}) of Tensors with shapes ${a.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let x=i?[g,d,p]:[g,p,d],b=o?[y,c,h]:[y,h,c],w=Ct({inputs:{x:a},backend:r,attrs:{shape:x}}),I=Ct({inputs:{x:s},backend:r,attrs:{shape:b}}),T=i?w.shape[1]:w.shape[2],E=i?w.shape[2]:w.shape[1],R=o?I.shape[1]:I.shape[2],F=Math.max(g,y),$=r.data.get(w.dataId).values,S=r.data.get(I.dataId).values,z=v.computeStrides(w.shape),O=v.computeStrides(I.shape),[j,K,D]=i?[z[0],1,z[1]]:[z[0],z[1],1],[Y,V,re]=o?[1,O[1],O[0]]:[O[1],1,O[0]],Q=E*R,ie=De([F,E,R],w.dtype),J=ie.values,ae=r.blockSize;for(let de=0;de<F;de++)for(let be=0;be<E;be+=ae)for(let ve=0;ve<R;ve+=ae)for(let Ee=0;Ee<T;Ee+=ae){let $e=Math.min(be+ae,E),ze=Math.min(ve+ae,R),We=Math.min(Ee+ae,T);for(let Ke=be;Ke<$e;Ke++)for(let ot=ve;ot<ze;ot++){let pt=0;for(let ht=Ee;ht<We;ht++){let Fe=Math.min(de,g-1)*j,wt=Math.min(de,y-1)*re,xt=$[Fe+Ke*K+ht*D],Pr=S[ht*Y+ot*V+wt];pt+=xt*Pr}J[de*Q+(Ke*R+ot)]+=pt}}return r.disposeIntermediateTensorInfo(w),r.disposeIntermediateTensorInfo(I),r.makeTensorInfo(A,ie.dtype,ie.values)}var VX={kernelName:Qs,backendName:"cpu",kernelFunc:h9};function UX(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:d,leakyreluAlpha:h}=n,p,c,m,f=[];p=h9({inputs:{a,b:s},attrs:{transposeA:l,transposeB:u},backend:r}),i&&(c=Bu({inputs:{a:p,b:i},backend:r}),f.push(p),p=c),d&&(m=Z0(r,p,d,o,h),f.push(p),p=m);for(let g of f)r.disposeIntermediateTensorInfo(g);return p}var GX={kernelName:Ps,backendName:"cpu",kernelFunc:UX},jX=gt(Hu,e=>Math.acos(e)),HX={kernelName:Hu,backendName:"cpu",kernelFunc:jX},qX=gt(qu,e=>Math.acosh(e)),XX={kernelName:qu,backendName:"cpu",kernelFunc:qX};function KX(e){let{inputs:t,backend:r}=e,n=t;Ce(t,"addN");let a=n.map(o=>r.data.get(o.dataId).values),s=De(n[0].shape,n[0].dtype),i=s.values;for(let o=0;o<n.length;o++){let l=a[o];for(let u=0;u<i.length;u++)i[u]+=l[u]}return r.makeTensorInfo(s.shape,s.dtype,s.values)}var ZX={kernelName:Zs,backendName:"cpu",kernelFunc:KX};function YX(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;Ce(a,"all");let o=v.parseAxisParam(s,a.shape),l=o,u=C.getAxesPermutation(l,a.shape.length),d=a;u!=null&&(d=on({inputs:{x:a},backend:r,attrs:{perm:u}}),l=C.getInnerMostAxes(l.length,a.shape.length)),C.assertAxesAreInnerMostDims("all",l,d.shape.length);let[h,p]=C.computeOutAndReduceShapes(d.shape,l),c=v.sizeFromShape(p),m=v.makeZerosTypedArray(v.sizeFromShape(h),d.dtype),f=r.data.get(d.dataId).values;for(let y=0;y<m.length;++y){let A=y*c,x=f[A];for(let b=0;b<c;++b){let w=f[A+b];x=x&&w}m[y]=x}u!=null&&r.disposeIntermediateTensorInfo(d);let g=r.makeTensorInfo(h,d.dtype,m);if(i){let y=C.expandShapeToKeepDim(h,o),A=Ct({inputs:{x:g},backend:r,attrs:{shape:y}});return r.disposeIntermediateTensorInfo(g),A}return g}var JX={kernelName:Xu,backendName:"cpu",kernelFunc:YX};function QX(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;Ce(a,"any");let o=v.parseAxisParam(s,a.shape),l=o,u=C.getAxesPermutation(l,a.shape.length),d=a;u!=null&&(d=on({inputs:{x:a},backend:r,attrs:{perm:u}}),l=C.getInnerMostAxes(l.length,a.shape.length)),C.assertAxesAreInnerMostDims("any",l,d.shape.length);let[h,p]=C.computeOutAndReduceShapes(d.shape,l),c=v.sizeFromShape(p),m=v.makeZerosTypedArray(v.sizeFromShape(h),d.dtype),f=r.data.get(d.dataId).values;for(let y=0;y<m.length;++y){let A=y*c,x=f[A];for(let b=0;b<c;++b){let w=f[A+b];x=x||w}m[y]=x}u!=null&&r.disposeIntermediateTensorInfo(d);let g=r.makeTensorInfo(h,d.dtype,m);if(i){let y=C.expandShapeToKeepDim(h,o),A=Ct({inputs:{x:g},backend:r,attrs:{shape:y}});return r.disposeIntermediateTensorInfo(g),A}return g}var eK={kernelName:Ku,backendName:"cpu",kernelFunc:QX};function tK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s}=n;Ce(a,"argMax");let i=v.parseAxisParam(s,a.shape),o=C.getAxesPermutation(i,a.shape.length),l=a,u=[];o!=null&&(l=on({inputs:{x:a},backend:r,attrs:{perm:o}}),u.push(l),i=C.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],C.assertAxesAreInnerMostDims("argMax",i,l.shape.length);let[d,h]=C.computeOutAndReduceShapes(l.shape,i),p=v.sizeFromShape(d),c=v.makeZerosTypedArray(p,"int32"),m=v.sizeFromShape(h),f=r.data.get(l.dataId).values;for(let g=0;g<c.length;++g){let y=g*m,A=f[y],x=0;for(let b=0;b<m;++b){let w=f[y+b];w>A&&(A=w,x=b)}c[g]=x}return u.forEach(g=>r.disposeIntermediateTensorInfo(g)),r.makeTensorInfo(d,"int32",c)}var rK={kernelName:Ys,backendName:"cpu",kernelFunc:tK};function nK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s}=n;Ce(a,"argMin");let i=v.parseAxisParam(s,a.shape),o=C.getAxesPermutation(i,a.shape.length),l=a,u=[];o!=null&&(l=on({inputs:{x:a},backend:r,attrs:{perm:o}}),u.push(l),i=C.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],C.assertAxesAreInnerMostDims("argMin",i,l.shape.length);let[d,h]=C.computeOutAndReduceShapes(l.shape,i),p=v.sizeFromShape(d),c=v.makeZerosTypedArray(p,"int32"),m=v.sizeFromShape(h),f=r.data.get(l.dataId).values;for(let g=0;g<c.length;++g){let y=g*m,A=f[y],x=0;for(let b=0;b<m;++b){let w=f[y+b];w<A&&(A=w,x=b)}c[g]=x}return u.forEach(g=>r.disposeIntermediateTensorInfo(g)),r.makeTensorInfo(d,"int32",c)}var aK={kernelName:Zu,backendName:"cpu",kernelFunc:nK},sK=gt(Yu,e=>Math.asin(e)),iK={kernelName:Yu,backendName:"cpu",kernelFunc:sK},oK=gt(Ju,e=>Math.asinh(e)),lK={kernelName:Ju,backendName:"cpu",kernelFunc:oK},uK=gt(Qu,e=>Math.atan(e)),dK={kernelName:Qu,backendName:"cpu",kernelFunc:uK},pK=Qt((e,t)=>Math.atan2(e,t)),hK=br(td,pK),cK={kernelName:td,backendName:"cpu",kernelFunc:hK},fK=gt(ed,e=>Math.atanh(e)),mK={kernelName:ed,backendName:"cpu",kernelFunc:fK};function bA(e,t,r,n,a,s){let i=a.strideHeight,o=a.strideWidth,l=a.dilationHeight,u=a.dilationWidth,d=a.effectiveFilterHeight,h=a.effectiveFilterWidth,p=a.padInfo.top,c=a.padInfo.left,m=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,f=De(a.outShape,r),g=f.values,y=a.outShape[1]*a.outShape[2]*a.outShape[3],A=a.outShape[2]*a.outShape[3],x=a.outShape[3];for(let b=0;b<a.batchSize;++b){let w=b*y,I=b*n[0];for(let T=0;T<a.inChannels;++T)for(let E=0;E<a.outHeight;++E){let R=E*i-p,F=Math.max(0,R),$=Math.min(a.inHeight,d+R),S=w+E*A;for(let z=0;z<a.outWidth;++z){let O=z*o-c,j=Math.max(0,O),K=Math.min(a.inWidth,h+O),D=m,Y=0,V=0;for(let Q=F;Q<$;Q+=l){let ie=I+Q*n[1];for(let J=j;J<K;J+=u){let ae=ie+J*n[2],de=e[ae+T];s==="max"&&de>D?D=de:s==="avg"&&(Y+=de,V++)}if(isNaN(D))break}let re=S+z*x+T;g[re]=s==="avg"?Y/V:D}}}return f}function c9(e,t,r,n,a=!1,s=!1){let i=De(n.outShape,"int32"),o=n.strideHeight,l=n.strideWidth,u=n.dilationHeight,d=n.dilationWidth,h=n.effectiveFilterHeight,p=n.effectiveFilterWidth,c=n.padInfo.top,m=n.padInfo.left,f=De(t,r,e);for(let g=0;g<n.batchSize;++g)for(let y=0;y<n.inChannels;++y)for(let A=0;A<n.outHeight;++A){let x=A*o-c,b=x;for(;b<0;)b+=u;let w=Math.min(n.inHeight,h+x);for(let I=0;I<n.outWidth;++I){let T=I*l-m,E=T;for(;E<0;)E+=d;let R=Math.min(n.inWidth,p+T),F=Number.NEGATIVE_INFINITY,$=-1;for(let S=b;S<w;S+=u){let z=S-x;for(let O=E;O<R;O+=d){let j=O-T,K=f.get(g,S,O,y);K>F&&(F=K,a?$=s?((g*n.inHeight+S)*n.inWidth+O)*n.inChannels+y:(S*n.inWidth+O)*n.inChannels+y:$=z*p+j)}}i.set($,g,A,I,y)}}return i}function f9(e,t,r,n,a,s){let i=a.strideDepth,o=a.strideHeight,l=a.strideWidth,u=a.dilationDepth,d=a.dilationHeight,h=a.dilationWidth,p=a.effectiveFilterDepth,c=a.effectiveFilterHeight,m=a.effectiveFilterWidth,f=a.padInfo.front,g=a.padInfo.top,y=a.padInfo.left,A=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=De(a.outShape,r),b=x.values,w=a.outShape[1]*a.outShape[2]*a.outShape[3]*a.outShape[4],I=a.outShape[2]*a.outShape[3]*a.outShape[4],T=a.outShape[3]*a.outShape[4],E=a.outShape[4];for(let R=0;R<a.batchSize;++R){let F=R*w,$=R*n[0];for(let S=0;S<a.inChannels;++S)for(let z=0;z<a.outDepth;++z){let O=z*i-f,j=O;for(;j<0;)j+=u;let K=Math.min(a.inDepth,p+O),D=F+z*I;for(let Y=0;Y<a.outHeight;++Y){let V=Y*o-g,re=V;for(;re<0;)re+=d;let Q=Math.min(a.inHeight,c+V),ie=D+Y*T;for(let J=0;J<a.outWidth;++J){let ae=J*l-y,de=ae;for(;de<0;)de+=h;let be=Math.min(a.inWidth,m+ae),ve=ie+J*E,Ee=A,$e=0,ze=0;for(let Ke=j;Ke<K;Ke+=u){let ot=$+Ke*n[1];for(let pt=re;pt<Q;pt+=d){let ht=ot+pt*n[2];for(let Fe=de;Fe<be;Fe+=h){let wt=ht+Fe*n[3],xt=e[wt+S];if(s==="max"&&xt>Ee?Ee=xt:s==="avg"&&($e+=xt,ze++),isNaN(Ee))break}if(isNaN(Ee))break}if(isNaN(Ee))break}let We=ve+S;b[We]=s==="avg"?$e/ze:Ee}}}}return x}function gK(e,t){let r=De(t.outShape,"int32"),n=t.strideDepth,a=t.strideHeight,s=t.strideWidth,i=t.dilationDepth,o=t.dilationHeight,l=t.dilationWidth,u=t.effectiveFilterDepth,d=t.effectiveFilterHeight,h=t.effectiveFilterWidth,p=t.padInfo.front,c=t.padInfo.top,m=t.padInfo.left;for(let f=0;f<t.batchSize;++f)for(let g=0;g<t.inChannels;++g)for(let y=0;y<t.outDepth;++y){let A=y*n-p,x=A;for(;x<0;)x+=i;let b=Math.min(t.inDepth,u+A);for(let w=0;w<t.outHeight;++w){let I=w*a-c,T=I;for(;T<0;)T+=o;let E=Math.min(t.inHeight,d+I);for(let R=0;R<t.outWidth;++R){let F=R*s-m,$=F;for(;$<0;)$+=l;let S=Math.min(t.inWidth,h+F),z=Number.NEGATIVE_INFINITY,O=-1;for(let j=x;j<b;j+=i){let K=j-A;for(let D=T;D<E;D+=o){let Y=D-I;for(let V=$;V<S;V+=l){let re=V-F,Q=e.get(f,j,D,V,g);Q>=z&&(z=Q,O=K*d*h+Y*d+re)}}}r.set(O,f,y,w,R,g)}}}return r}function yK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t;Ce(a,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1;v.assert(C.eitherStridesOrDilationsAreOne(i,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=C.computePool2DInfo(a.shape,s,i,u,o,l),h;if(d.filterWidth===1&&d.filterHeight===1&&v.arraysEqual(d.inShape,d.outShape))h=Oa({inputs:{x:a},backend:r});else{let p=r.data.get(a.dataId).values,c=v.computeStrides(a.shape),m=bA(p,a.shape,a.dtype,c,d,"avg");h=r.makeTensorInfo(d.outShape,a.dtype,m.values)}return h}var AK={kernelName:Js,backendName:"cpu",kernelFunc:yK};function xK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=n;Ce(a,"avgPool3d");let d=C.computePool3DInfo(a.shape,s,i,1,o,l,u),h=r.data.get(a.dataId).values,p=f9(h,a.shape,a.dtype,v.computeStrides(a.shape),d,"avg");return r.makeTensorInfo(p.shape,"float32",p.values)}var bK={kernelName:ah,backendName:"cpu",kernelFunc:xK};function vK(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=n;Ce([a,s],"avgPool3DGrad");let d=C.computePool3DInfo(s.shape,i,o,1,l,u),h=d.strideDepth,p=d.strideHeight,c=d.strideWidth,m=d.filterDepth,f=d.filterHeight,g=d.filterWidth,y=d.dilationDepth,A=d.dilationHeight,x=d.dilationWidth,b=d.effectiveFilterDepth,w=d.effectiveFilterHeight,I=d.effectiveFilterWidth,T=b-1-d.padInfo.front,E=I-1-d.padInfo.left,R=w-1-d.padInfo.top,F=De(s.shape,"float32"),$=1/(m*f*g),S=r.bufferSync(a);for(let z=0;z<d.batchSize;++z)for(let O=0;O<d.inChannels;++O)for(let j=0;j<d.inDepth;++j)for(let K=0;K<d.inHeight;++K)for(let D=0;D<d.inWidth;++D){let Y=j-T,V=K-R,re=D-E,Q=0;for(let ie=0;ie<b;ie+=y){let J=(Y+ie)/h;if(!(J<0||J>=d.outDepth||Math.floor(J)!==J))for(let ae=0;ae<w;ae+=A){let de=(V+ae)/p;if(!(de<0||de>=d.outHeight||Math.floor(de)!==de))for(let be=0;be<I;be+=x){let ve=(re+be)/c;ve<0||ve>=d.outWidth||Math.floor(ve)!==ve||(Q+=S.get(z,J,de,ve,O))}}}F.set(Q*$,z,j,K,D,O)}return r.makeTensorInfo(F.shape,F.dtype,F.values)}var wK={kernelName:df,backendName:"cpu",kernelFunc:vK};function kK(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,i=s;Ce([a,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:u}=n,d=C.computePool2DInfo(i.shape,o,l,1,u),h=d.strideHeight,p=d.strideWidth,c=d.filterHeight,m=d.filterWidth,f=d.dilationHeight,g=d.dilationWidth,y=d.effectiveFilterHeight,A=d.effectiveFilterWidth,x=A-1-d.padInfo.left,b=y-1-d.padInfo.top,w=De(i.shape,"float32"),I=1/(c*m),T=r.data.get(a.dataId).values,E=De(a.shape,"float32",T);for(let R=0;R<d.batchSize;++R)for(let F=0;F<d.inChannels;++F)for(let $=0;$<d.inHeight;++$)for(let S=0;S<d.inWidth;++S){let z=$-b,O=S-x,j=0;for(let K=0;K<y;K+=f){let D=(z+K)/h;if(!(D<0||D>=d.outHeight||Math.floor(D)!==D))for(let Y=0;Y<A;Y+=g){let V=(O+Y)/p;V<0||V>=d.outWidth||Math.floor(V)!==V||(j+=E.get(R,D,V,F))}}w.set(j*I,R,$,S,F)}return r.makeTensorInfo(w.shape,w.dtype,w.values)}var IK={kernelName:uf,backendName:"cpu",kernelFunc:kK};function SK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,scale:s,offset:i,mean:o,variance:l}=t;v.assert(o.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),v.assert(i==null||o.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),v.assert(s==null||o.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),Ce([a,o,l,s,i],"batchNorm");let{varianceEpsilon:u}=n;u==null&&(u=.001);let d=r.data.get(a.dataId).values,h=r.data.get(o.dataId).values,p=r.data.get(l.dataId).values,c=s?r.data.get(s.dataId).values:new Float32Array([1]),m=i?r.data.get(i.dataId).values:new Float32Array([0]),f=new Float32Array(d.length),g=m.length,y=c.length,A=p.length,x=h.length,b=0,w=0,I=0,T=0;for(let E=0;E<d.length;++E)f[E]=m[b++]+(d[E]-h[w++])*c[I++]/Math.sqrt(p[T++]+u),b>=g&&(b=0),w>=x&&(w=0),I>=y&&(I=0),T>=A&&(T=0);return r.makeTensorInfo(a.shape,a.dtype,f)}var CK={kernelName:ci,backendName:"cpu",kernelFunc:SK};function TK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,crops:i}=n;Ce([a],"batchToSpaceND");let o=s.reduce((y,A)=>y*A),l=C.getReshaped(a.shape,s,o),u=C.getPermuted(l.length,s.length),d=C.getReshapedPermuted(a.shape,s,o),h=C.getSliceBeginCoords(i,s.length),p=C.getSliceSize(d,i,s.length),c=Ct({inputs:{x:a},backend:r,attrs:{shape:l}}),m=on({inputs:{x:c},backend:r,attrs:{perm:u}}),f=Ct({inputs:{x:m},backend:r,attrs:{shape:d}}),g=Do({inputs:{x:f},backend:r,attrs:{begin:h,size:p}});return r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(f),g}var NK={kernelName:jo,backendName:"cpu",kernelFunc:TK};function EK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,weights:s}=t,{size:i}=n,o=r.data.get(a.dataId).values,l=r.data.get(s.dataId).values,u=cA(o,l,s.dtype,s.shape,i);return r.makeTensorInfo([i],s.dtype,u)}var RK={kernelName:pf,backendName:"cpu",kernelFunc:EK};function $K(e){let{inputs:t,backend:r}=e,{s0:n,s1:a}=t,s=r.data.get(n.dataId).values,i=r.data.get(a.dataId).values,o=C.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return r.makeTensorInfo([o.length],"int32",Int32Array.from(o))}var MK={kernelName:hf,backendName:"cpu",kernelFunc:$K},FK=gt(es,(e,t)=>{let r=t;return e>r.clipValueMax?r.clipValueMax:e<r.clipValueMin?r.clipValueMin:e}),_K={kernelName:es,backendName:"cpu",kernelFunc:FK},PK=e=>{let{x:t}=e.inputs,r=e.backend,n=new Float32Array(v.sizeFromShape(t.shape)),a=r.data.get(t.dataId),s=a.complexTensorInfos.real,i=a.complexTensorInfos.imag,o=r.data.get(s.dataId).values,l=r.data.get(i.dataId).values;for(let u=0;u<o.length;u++){let d=o[u],h=l[u];n[u]=Math.hypot(d,h)}return r.makeOutput(n,t.shape,"float32")},OK={kernelName:ih,backendName:"cpu",kernelFunc:PK};function Wu(e){let{inputs:t,backend:r}=e,{input:n}=t,a=r.data.get(n.dataId).complexTensorInfos.imag,s=r.data.get(a.dataId).values;return r.makeTensorInfo(a.shape,a.dtype,s)}var zK={kernelName:dh,backendName:"cpu",kernelFunc:Wu};function Vu(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n,s=v.parseAxisParam(a,t[0].shape)[0],i=C.computeOutShape(t.map(f=>f.shape),s);if(v.sizeFromShape(i)===0)return r.makeTensorInfo(i,t[0].dtype,[]);let o=t.filter(f=>v.sizeFromShape(f.shape)>0);if(o.length===1)return Oa({inputs:{x:o[0]},backend:r});let l=o.map(f=>f.shape);if(C.assertParamsConsistent(l,s),o[0].dtype==="complex64"){let f=o.map(b=>zo({inputs:{input:b},backend:r})),g=o.map(b=>Wu({inputs:{input:b},backend:r})),y=Vu({inputs:f,backend:r,attrs:{axis:s}}),A=Vu({inputs:g,backend:r,attrs:{axis:s}}),x=hn({inputs:{real:y,imag:A},backend:r});return f.forEach(b=>r.disposeIntermediateTensorInfo(b)),g.forEach(b=>r.disposeIntermediateTensorInfo(b)),r.disposeIntermediateTensorInfo(y),r.disposeIntermediateTensorInfo(A),x}let u=o.map(f=>{let g=v.sizeFromShape(f.shape.slice(s));return Ct({inputs:{x:f},backend:r,attrs:{shape:[-1,g]}})}),d=u.map(f=>({vals:r.data.get(f.dataId).values,shape:f.shape}));i=C.computeOutShape(u.map(f=>f.shape),1);let h=u[0].shape[0]===1,p=fA(d,i,t[0].dtype,h),c=C.computeOutShape(o.map(f=>f.shape),s),m=r.makeTensorInfo(c,t[0].dtype,p);return u.forEach(f=>r.disposeIntermediateTensorInfo(f)),m}var DK={kernelName:Ho,backendName:"cpu",kernelFunc:Vu};function m9(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:d}=n;Ce([a,s],"conv2d");let h=C.convertConv2DDataFormat(l),p=C.computeConv2DInfo(a.shape,s.shape,i,u,o,d,!1,h),c=p.filterHeight,m=p.filterWidth,f=p.dilationHeight,g=p.dilationWidth,y=p.padInfo.left,A=p.padInfo.top,x=p.dataFormat==="channelsLast",b=new ir(p.outShape,a.dtype),w=v.computeStrides(a.shape),I=v.computeStrides(s.shape),T=w[0],E=x?w[1]:w[2],R=x?w[2]:1,F=x?1:w[1],$=b.strides[0],S=x?b.strides[1]:b.strides[2],z=x?b.strides[2]:1,O=x?1:b.strides[1],j=r.data.get(a.dataId).values,K=r.data.get(s.dataId).values,D=b.values;for(let Y=0;Y<p.batchSize;++Y){let V=Y*T,re=Y*$;for(let Q=0;Q<p.outHeight;++Q){let ie=re+Q*S,J=Q*p.strideHeight-A;for(let ae=0;ae<c;++ae){let de=J+ae*f;if(de<0||de>=p.inHeight)continue;let be=ae*I[0],ve=V+de*E;for(let Ee=0;Ee<p.outWidth;++Ee){let $e=ie+Ee*z,ze=Ee*p.strideWidth-y;for(let We=0;We<m;++We){let Ke=ze+We*g;if(Ke<0||Ke>=p.inWidth)continue;let ot=be+We*I[1],pt=ve+Ke*R,ht=ot;for(let Fe=0;Fe<p.inChannels;++Fe){let wt=j[pt+Fe*F];for(let xt=0;xt<p.outChannels;++xt)D[$e+xt*O]+=wt*K[ht+xt];ht+=p.outChannels}}}}}}return r.makeTensorInfo(b.shape,b.dtype,D)}var LK={kernelName:ri,backendName:"cpu",kernelFunc:m9};function BK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:d}=n;Ce([a,s],"conv2dBackpropFilter");let h=C.convertConv2DDataFormat(l),p=C.computeConv2DInfo(a.shape,d,i,1,o,u,!1,h),{strideHeight:c,strideWidth:m,filterHeight:f,filterWidth:g}=p,y=p.dataFormat==="channelsLast",A=new ir(p.filterShape,"float32"),x=p.padInfo.left,b=p.padInfo.top,w=r.data.get(a.dataId).values,I=r.data.get(s.dataId).values,T=new ir(a.shape,a.dtype,w),E=new ir(s.shape,s.dtype,I);for(let R=0;R<f;++R){let F=Math.max(0,Math.ceil((b-R)/c)),$=Math.min(p.outHeight,(p.inHeight+b-R)/c);for(let S=0;S<g;++S){let z=Math.max(0,Math.ceil((x-S)/m)),O=Math.min(p.outWidth,(p.inWidth+x-S)/m);for(let j=0;j<p.inChannels;++j)for(let K=0;K<p.outChannels;++K){let D=0;for(let Y=0;Y<p.batchSize;++Y)for(let V=F;V<$;++V){let re=R+V*c-b;for(let Q=z;Q<O;++Q){let ie=S+Q*m-x;y?D+=T.get(Y,re,ie,j)*E.get(Y,V,Q,K):D+=T.get(Y,j,re,ie)*E.get(Y,K,V,Q)}}A.set(D,R,S,j,K)}}}return r.makeTensorInfo(A.shape,A.dtype,A.values)}var WK={kernelName:cf,backendName:"cpu",kernelFunc:BK};function VK(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:d}=n;Ce([a,s],"conv2dBackpropInput");let h=v.computeStrides(s.shape),p=v.computeStrides(a.shape),c=C.convertConv2DDataFormat(u),m=C.computeConv2DInfo(i,s.shape,o,1,l,d,!1,c),f=new ir(m.inShape,"float32"),g=f.values,y=r.data.get(a.dataId).values,A=r.data.get(s.dataId).values,[x,b,w]=h,{batchSize:I,filterHeight:T,filterWidth:E,inChannels:R,inHeight:F,inWidth:$,outChannels:S,outHeight:z,outWidth:O,strideHeight:j,strideWidth:K}=m;c=m.dataFormat;let D=T-1-m.padInfo.top,Y=E-1-m.padInfo.left,V=c==="channelsLast",re=f.strides[0],Q=V?f.strides[1]:f.strides[2],ie=V?f.strides[2]:1,J=V?1:f.strides[1],ae=p[0],de=V?p[1]:p[2],be=V?p[2]:1,ve=V?1:p[1];for(let Ee=0;Ee<I;++Ee)for(let $e=0;$e<R;++$e)for(let ze=0;ze<F;++ze){let We=ze-D,Ke=Math.max(0,Math.ceil(We/j)),ot=Math.min(z,(T+We)/j);for(let pt=0;pt<$;++pt){let ht=pt-Y,Fe=Math.max(0,Math.ceil(ht/K)),wt=Math.min(O,(E+ht)/K),xt=0;for(let hr=Ke;hr<ot;++hr){let Qr=hr*j-We;for(let rr=Fe;rr<wt;++rr){let cr=rr*K-ht,ta=ae*Ee+de*hr+be*rr,en=x*(T-1-Qr)+b*(E-1-cr)+w*$e;for(let nr=0;nr<S;++nr){let kn=y[ta+ve*nr],In=A[en+nr];xt+=kn*In}}}let Pr=re*Ee+Q*ze+ie*pt+J*$e;g[Pr]=xt}}return r.makeTensorInfo(f.shape,f.dtype,f.values)}var UK={kernelName:ni,backendName:"cpu",kernelFunc:VK};function GK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l}=n;Ce([a,s],"conv3d");let u=C.computeConv3DInfo(a.shape,s.shape,i,l,o),{filterDepth:d,filterHeight:h,filterWidth:p,dilationDepth:c,dilationHeight:m,dilationWidth:f,padInfo:g}=u,y=g.front,A=g.left,x=g.top,b=new ir(u.outShape,a.dtype),w=r.data.get(a.dataId).values,I=r.data.get(s.dataId).values,T=b.values,E=v.computeStrides(a.shape),R=v.computeStrides(s.shape);for(let F=0;F<u.batchSize;++F){let $=F*E[0],S=F*b.strides[0];for(let z=0;z<u.outDepth;++z){let O=S+z*b.strides[1],j=z*u.strideDepth-y;for(let K=0;K<d;++K){let D=j+K*c;if(D<0||D>=u.inDepth)continue;let Y=K*R[0],V=$+D*E[1];for(let re=0;re<u.outHeight;++re){let Q=O+re*b.strides[2],ie=re*u.strideHeight-x;for(let J=0;J<h;++J){let ae=ie+J*m;if(ae<0||ae>=u.inHeight)continue;let de=Y+J*R[1],be=V+ae*E[2];for(let ve=0;ve<u.outWidth;++ve){let Ee=Q+ve*u.outChannels,$e=ve*u.strideWidth-A;for(let ze=0;ze<p;++ze){let We=$e+ze*f;if(We<0||We>=u.inWidth)continue;let Ke=de+ze*R[2],ot=be+We*u.inChannels,pt=Ke;for(let ht=0;ht<u.inChannels;++ht){let Fe=w[ot+ht];for(let wt=0;wt<u.outChannels;++wt)T[Ee+wt]+=Fe*I[pt+wt];pt+=u.outChannels}}}}}}}}return r.makeTensorInfo(b.shape,b.dtype,b.values)}var jK={kernelName:oh,backendName:"cpu",kernelFunc:GK};function HK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,pad:o,filterShape:l}=n;Ce([a,s],"conv3dBackpropFilterV2");let u=v.computeStrides(a.shape),d=v.computeStrides(s.shape),h=C.computeConv3DInfo(a.shape,l,i,1,o),p=h.strideDepth,c=h.strideHeight,m=h.strideWidth,f=h.filterDepth,g=h.filterHeight,y=h.filterWidth,A=new ir(h.filterShape,"float32"),x=A.values,[b,w,I,T]=A.strides,E=r.data.get(s.dataId).values,[R,F,$,S]=d,z=r.data.get(a.dataId).values,[O,j,K,D]=u,Y=h.padInfo.front,V=h.padInfo.left,re=h.padInfo.top;for(let Q=0;Q<f;++Q){let ie=Math.max(0,Math.ceil((Y-Q)/p)),J=Math.min(h.outDepth,(h.inDepth+Y-Q)/p),ae=Q*b;for(let de=0;de<g;++de){let be=Math.max(0,Math.ceil((re-de)/c)),ve=Math.min(h.outHeight,(h.inHeight+re-de)/c),Ee=de*w+ae;for(let $e=0;$e<y;++$e){let ze=Math.max(0,Math.ceil((V-$e)/m)),We=Math.min(h.outWidth,(h.inWidth+V-$e)/m),Ke=$e*I+Ee;for(let ot=0;ot<h.inChannels;++ot){let pt=ot*T+Ke;for(let ht=0;ht<h.outChannels;++ht){let Fe=0;for(let wt=0;wt<h.batchSize;++wt){let xt=wt*O,Pr=wt*R;for(let hr=ie;hr<J;++hr){let Qr=(Q+hr*p-Y)*j+xt,rr=hr*F+Pr;for(let cr=be;cr<ve;++cr){let ta=(de+cr*c-re)*K+Qr,en=cr*$+rr;for(let nr=ze;nr<We;++nr){let kn=($e+nr*m-V)*D+ta,In=nr*S+en;Fe+=z[kn+ot]*E[In+ht]}}}}x[pt+ht]=Fe}}}}}return r.makeTensorInfo(A.shape,A.dtype,A.values)}var qK={kernelName:ff,backendName:"cpu",kernelFunc:HK};function XK(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{pad:i,strides:o,inputShape:l}=n;Ce([a],"conv3dBackpropInputV2");let u=v.computeStrides(a.shape),d=v.computeStrides(s.shape),h=C.computeConv3DInfo(l,s.shape,o,1,i),p=new ir(h.inShape,"float32"),c=p.values,[m,f,g,y]=p.strides,A=r.data.get(a.dataId).values,[x,b,w,I]=u,T=r.data.get(s.dataId).values,[E,R,F,$]=d,{batchSize:S,filterDepth:z,filterHeight:O,filterWidth:j,inChannels:K,inDepth:D,inHeight:Y,inWidth:V,outChannels:re,outDepth:Q,outHeight:ie,outWidth:J,strideDepth:ae,strideHeight:de,strideWidth:be}=h,ve=z-1-h.padInfo.front,Ee=O-1-h.padInfo.top,$e=j-1-h.padInfo.left;for(let ze=0;ze<S;++ze)for(let We=0;We<K;++We)for(let Ke=0;Ke<D;++Ke){let ot=Ke-ve,pt=Math.max(0,Math.ceil(ot/ae)),ht=Math.min(Q,(z+ot)/ae);for(let Fe=0;Fe<Y;++Fe){let wt=Fe-Ee,xt=Math.max(0,Math.ceil(wt/de)),Pr=Math.min(ie,(O+wt)/de);for(let hr=0;hr<V;++hr){let Qr=hr-$e,rr=Math.max(0,Math.ceil(Qr/be)),cr=Math.min(J,(j+Qr)/be),ta=0;for(let en=pt;en<ht;++en){let nr=en*ae-ot;for(let kn=xt;kn<Pr;++kn){let In=kn*de-wt;for(let ys=rr;ys<cr;++ys){let oo=ys*be-Qr,yc=x*ze+b*en+w*kn+I*ys,As=E*(z-1-nr)+R*(O-1-In)+F*(j-1-oo)+$*We;for(let Ga=0;Ga<re;++Ga){let dp=A[yc+Ga],eu=T[As+Ga];ta+=dp*eu}}}}c[m*ze+f*Ke+g*Fe+y*hr+We]=ta}}}return r.makeTensorInfo(p.shape,p.dtype,p.values)}var KK={kernelName:mf,backendName:"cpu",kernelFunc:XK},ZK=gt(ai,e=>Math.cos(e)),YK={kernelName:ai,backendName:"cpu",kernelFunc:ZK},JK=gt(si,e=>Math.cosh(e)),QK={kernelName:si,backendName:"cpu",kernelFunc:JK};function eZ(e){let{inputs:t,backend:r,attrs:n}=e,{image:a,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=n,[d,h,p,c]=a.shape,m=s.shape[0],[f,g]=o,y=De([m,f,g,c],"float32"),A=r.data.get(s.dataId).values,x=r.data.get(i.dataId).values,b=r.data.get(a.dataId).values,w=v.computeStrides(a.shape),I=v.computeStrides(y.shape);for(let T=0;T<m;T++){let E=T*4,R=A[E],F=A[E+1],$=A[E+2],S=A[E+3],z=x[T];if(z>=d)continue;let O=f>1?($-R)*(h-1)/(f-1):0,j=g>1?(S-F)*(p-1)/(g-1):0;for(let K=0;K<f;K++){let D=f>1?R*(h-1)+K*O:.5*(R+$)*(h-1);if(D<0||D>h-1){for(let Y=0;Y<g;Y++)for(let V=0;V<c;V++){let re=V+Y*I[2]+K*I[1]+T*I[0];y.values[re]=u}continue}if(l==="bilinear"){let Y=Math.floor(D),V=Math.ceil(D),re=D-Y;for(let Q=0;Q<g;Q++){let ie=g>1?F*(p-1)+Q*j:.5*(F+S)*(p-1);if(ie<0||ie>p-1){for(let be=0;be<c;be++){let ve=be+Q*I[2]+K*I[1]+T*I[0];y.values[ve]=u}continue}let J=Math.floor(ie),ae=Math.ceil(ie),de=ie-J;for(let be=0;be<c;be++){let ve=be+J*w[2]+Y*w[1]+z*w[0],Ee=b[ve];ve=be+ae*w[2]+Y*w[1]+z*w[0];let $e=b[ve];ve=be+J*w[2]+V*w[1]+z*w[0];let ze=b[ve];ve=be+ae*w[2]+V*w[1]+z*w[0];let We=b[ve],Ke=Ee+($e-Ee)*de,ot=ze+(We-ze)*de;ve=be+Q*I[2]+K*I[1]+T*I[0],y.values[ve]=Ke+(ot-Ke)*re}}}else for(let Y=0;Y<g;++Y){let V=g>1?F*(p-1)+Y*j:.5*(F+S)*(p-1);if(V<0||V>p-1){for(let ie=0;ie<c;ie++){let J=ie+Y*I[2]+K*I[1]+T*I[0];y.values[J]=u}continue}let re=Math.round(V),Q=Math.round(D);for(let ie=0;ie<c;ie++){let J=ie+re*w[2]+Q*w[1]+z*w[0],ae=ie+Y*I[2]+K*I[1]+T*I[0];y.values[ae]=b[J]}}}}return r.makeTensorInfo(y.shape,y.dtype,y.values)}var tZ={kernelName:Xo,backendName:"cpu",kernelFunc:eZ};function rZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n;Ce(a,"cumprod");let l=C.getAxesPermutation([s],a.shape.length),u=a;l!=null&&(u=on({inputs:{x:a},backend:r,attrs:{perm:l}}));let d=C.getInnerMostAxes(1,a.shape.length)[0];if(d!==u.shape.length-1)throw new Error(`backend.cumprod in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${d}`);let h=Nr(u.dtype,"int32"),p=v.makeOnesTypedArray(v.sizeFromShape(u.shape),h),c=r.data.get(u.dataId).values,m=u.shape[u.shape.length-1],f=o?(y,A)=>y+m-A-1:(y,A)=>y+A;for(let y=0;y<c.length;y+=m)for(let A=0;A<m;A++){let x=f(y,A);if(A===0)p[x]=i?1:c[x];else{let b=f(y,A-1);p[x]=i?c[b]*p[b]:c[x]*p[b]}}let g=r.makeTensorInfo(u.shape,h,p);if(l!=null){let y=C.getUndoAxesPermutation(l),A=on({inputs:{x:g},backend:r,attrs:{perm:y}});return r.disposeIntermediateTensorInfo(g),r.disposeIntermediateTensorInfo(u),A}return g}var nZ={kernelName:qo,backendName:"cpu",kernelFunc:rZ};function aZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n;Ce(a,"cumsum");let l=C.getAxesPermutation([s],a.shape.length),u=a;l!=null&&(u=on({inputs:{x:a},backend:r,attrs:{perm:l}}));let d=C.getInnerMostAxes(1,a.shape.length)[0];if(d!==u.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${d}`);let h=Nr(u.dtype,"int32"),p=v.makeZerosTypedArray(v.sizeFromShape(u.shape),h),c=r.data.get(u.dataId).values,m=u.shape[u.shape.length-1],f=o?(y,A)=>y+m-A-1:(y,A)=>y+A;for(let y=0;y<c.length;y+=m)for(let A=0;A<m;A++){let x=f(y,A);if(A===0)p[x]=i?0:c[x];else{let b=f(y,A-1);p[x]=i?c[b]+p[b]:c[x]+p[b]}}let g=r.makeTensorInfo(u.shape,h,p);if(l!=null){let y=C.getUndoAxesPermutation(l),A=on({inputs:{x:g},backend:r,attrs:{perm:y}});return r.disposeIntermediateTensorInfo(g),r.disposeIntermediateTensorInfo(u),A}return g}var sZ={kernelName:ii,backendName:"cpu",kernelFunc:aZ};function iZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,weights:s}=t,{size:i,binaryOutput:o}=n;if(a.shape.length===1){let l=r.data.get(a.dataId).values,u=r.data.get(s.dataId).values,d=cA(l,u,s.dtype,s.shape,i);return r.makeTensorInfo([i],s.dtype,d)}else if(a.shape.length===2){let l=r.bufferSync(a),u=r.bufferSync(s),d=Sk(l,u,i,o);return r.makeTensorInfo(d.shape,s.dtype,d.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${a.shape.length}.`)}var oZ={kernelName:gf,backendName:"cpu",kernelFunc:iZ};function lZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockSize:s,dataFormat:i}=n;v.assert(i==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`);let o=a.shape[0],l=a.shape[1],u=a.shape[2],d=a.shape[3],h=l*s,p=u*s,c=d/(s*s),m=r.data.get(a.dataId).values,f=new Float32Array(o*h*p*c),g=0;for(let y=0;y<o;++y)for(let A=0;A<h;++A){let x=Math.floor(A/s),b=A%s;for(let w=0;w<p;++w){let I=Math.floor(w/s),T=w%s,E=(b*s+T)*c;for(let R=0;R<c;++R){let F=R+E+d*(I+u*(x+l*y));f[g++]=m[F]}}}return r.makeTensorInfo([o,h,p,c],a.dtype,f)}var uZ={kernelName:Ko,backendName:"cpu",kernelFunc:lZ};function g9(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=n;Ce([a,s],"depthwiseConv2DNative");let d=v.computeStrides(a.shape),h=v.computeStrides(s.shape),p=l;p==null&&(p=[1,1]),v.assert(C.eitherStridesOrDilationsAreOne(i,p),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${p}'`);let c=C.computeConv2DInfo(a.shape,s.shape,i,p,o,u,!0),{filterHeight:m,filterWidth:f,dilationHeight:g,dilationWidth:y,padInfo:A}=c,x=A.left,b=A.top,w=c.outChannels/c.inChannels,I=new ir(c.outShape,a.dtype),T=r.data.get(a.dataId).values,E=r.data.get(s.dataId).values,R=I.values;for(let F=0;F<c.batchSize;++F){let $=F*d[0],S=F*I.strides[0];for(let z=0;z<c.outHeight;++z){let O=S+z*I.strides[1],j=z*c.strideHeight-b;for(let K=0;K<m;++K){let D=j+K*g;if(D<0||D>=c.inHeight)continue;let Y=K*h[0],V=$+D*d[1];for(let re=0;re<c.outWidth;++re){let Q=O+re*I.strides[2],ie=re*c.strideWidth-x;for(let J=0;J<f;++J){let ae=ie+J*y;if(ae<0||ae>=c.inWidth)continue;let de=Y+J*h[1],be=V+ae*c.inChannels,ve=Q,Ee=de;for(let $e=0;$e<c.inChannels;++$e){let ze=T[be+$e];for(let We=0;We<w;++We)R[ve+We]+=ze*E[Ee+We];ve+=w,Ee+=w}}}}}}return r.makeTensorInfo(I.shape,I.dtype,I.values)}var dZ={kernelName:oi,backendName:"cpu",kernelFunc:g9};function pZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:d}=n;Ce([a,s],"depthwiseConv2dNativeBackpropFilter");let h=C.computeConv2DInfo(a.shape,d,i,o,l,u,!0),{strideHeight:p,strideWidth:c,filterHeight:m,filterWidth:f}=h,g=new ir(h.filterShape,"float32"),y=h.padInfo.left,A=h.padInfo.top,x=h.outChannels/h.inChannels,b=r.data.get(a.dataId).values,w=new ir(a.shape,a.dtype,b),I=r.data.get(s.dataId).values,T=new ir(s.shape,s.dtype,I);for(let E=0;E<m;++E){let R=Math.max(0,Math.ceil((A-E)/p)),F=Math.min(h.outHeight,(h.inHeight+A-E)/p);for(let $=0;$<f;++$){let S=Math.max(0,Math.ceil((y-$)/c)),z=Math.min(h.outWidth,(h.inWidth+y-$)/c);for(let O=0;O<h.outChannels;++O){let j=Math.trunc(O/x),K=O%x,D=0;for(let Y=0;Y<h.batchSize;++Y)for(let V=R;V<F;++V){let re=E+V*p-A;for(let Q=S;Q<z;++Q){let ie=$+Q*c-y;D+=w.get(Y,re,ie,j)*T.get(Y,V,Q,O)}}g.set(D,E,$,j,K)}}}return r.makeTensorInfo(g.shape,g.dtype,g.values)}var hZ={kernelName:yf,backendName:"cpu",kernelFunc:pZ};function cZ(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:d}=n;Ce([a,s],"depthwiseConv2DNativeBackpropInput");let h=v.computeStrides(a.shape),p=v.computeStrides(s.shape),c=C.computeConv2DInfo(d,s.shape,i,o,l,u,!0),m=new ir(c.inShape,"float32"),f=m.values,[g,y,A]=m.strides,x=r.data.get(a.dataId).values,[b,w,I]=h,T=r.data.get(s.dataId).values,[E,R,F]=p,{batchSize:$,filterHeight:S,filterWidth:z,inChannels:O,inHeight:j,inWidth:K,outChannels:D,outHeight:Y,outWidth:V,strideHeight:re,strideWidth:Q}=c,ie=S-1-c.padInfo.top,J=z-1-c.padInfo.left,ae=D/O;for(let de=0;de<$;++de)for(let be=0;be<O;++be)for(let ve=0;ve<j;++ve){let Ee=ve-ie,$e=Math.max(0,Math.ceil(Ee/re)),ze=Math.min(Y,(S+Ee)/re);for(let We=0;We<K;++We){let Ke=We-J,ot=Math.max(0,Math.ceil(Ke/Q)),pt=Math.min(V,(z+Ke)/Q),ht=0;for(let Fe=$e;Fe<ze;++Fe){let wt=Fe*re-Ee;for(let xt=ot;xt<pt;++xt){let Pr=xt*Q-Ke,hr=b*de+w*Fe+I*xt,Qr=E*(S-1-wt)+R*(z-1-Pr)+F*be;for(let rr=0;rr<ae;++rr){let cr=be*ae+rr,ta=x[hr+cr],en=T[Qr+rr];ht+=ta*en}}}f[g*de+y*ve+A*We+be]=ht}}return r.makeTensorInfo(m.shape,m.dtype,m.values)}var fZ={kernelName:Af,backendName:"cpu",kernelFunc:cZ};function mZ(e){let{inputs:t,backend:r}=e,{x:n}=t,a=v.sizeFromShape(n.shape),s=r.data.get(n.dataId).values,i=De([a,a],n.dtype),o=i.values;for(let u=0;u<s.length;u++)o[u*a+u]=s[u];let l=[...n.shape,...n.shape];return r.makeTensorInfo(l,i.dtype,i.values)}var gZ={kernelName:xf,backendName:"cpu",kernelFunc:mZ},yZ={kernelName:lh,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:r})=>{let{x:n,filter:a}=e,{strides:s,pad:i,dilations:o}=r,l=t,u=l.data.get(n.dataId).values,d=n.shape.length,h=l.data.get(a.dataId).values,p=a.shape.length,{batchSize:c,inHeight:m,inWidth:f,inChannels:g,outHeight:y,outWidth:A,padInfo:x,strideHeight:b,strideWidth:w,filterHeight:I,filterWidth:T,dilationHeight:E,dilationWidth:R,outShape:F}=C.computeDilation2DInfo(n.shape,a.shape,s,i,"NHWC",o),$=v.sizeFromShape(F),S=F.length,z=v.getArrayFromDType(n.dtype,$);for(let O=0;O<c;++O)for(let j=0;j<y;++j){let K=j*b-x.top;for(let D=0;D<A;++D){let Y=D*w-x.left;for(let V=0;V<g;++V){let re=Number.MIN_SAFE_INTEGER;for(let ie=0;ie<I;++ie){let J=K+ie*E;if(J>=0&&J<m)for(let ae=0;ae<T;++ae){let de=Y+ae*R;if(de>=0&&de<f){let be=v.locToIndex([O,J,de,V],d,v.computeStrides(n.shape)),ve=v.locToIndex([ie,ae,V],p,v.computeStrides(a.shape)),Ee=u[be]+h[ve];Ee>re&&(re=Ee)}}}let Q=v.locToIndex([O,j,D,V],S,v.computeStrides(F));z[Q]=re}}}return{dataId:l.write(v.toTypedArray(z,n.dtype),F,n.dtype),shape:F,dtype:n.dtype}}},AZ={kernelName:N0,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:r})=>{let{x:n,filter:a,dy:s}=e,{strides:i,pad:o,dilations:l}=r,u=t,d=v.toNestedArray(n.shape,u.data.get(n.dataId).values),h=v.toNestedArray(a.shape,u.data.get(a.dataId).values),{batchSize:p,inHeight:c,inWidth:m,inChannels:f,outHeight:g,outWidth:y,padInfo:A,strideHeight:x,strideWidth:b,filterHeight:w,filterWidth:I,dilationHeight:T,dilationWidth:E,outShape:R}=C.computeDilation2DInfo(n.shape,a.shape,i,o,"NHWC",l);v.assert(s.rank===R.length,()=>`Error in ${N0}, dy must have the same rank as output ${R.length}, but got ${s.rank}`);let F=v.toNestedArray(R,u.data.get(s.dataId).values),$=v.makeZerosNestedTypedArray(a.shape,a.dtype);for(let S=0;S<p;++S)for(let z=0;z<g;++z){let O=z*x-A.top;for(let j=0;j<y;++j){let K=j*b-A.left;for(let D=0;D<f;++D){let Y=Number.MIN_SAFE_INTEGER,V=0,re=0;for(let Q=0;Q<w;++Q){let ie=O+Q*T;if(ie>=0&&ie<c)for(let J=0;J<I;++J){let ae=K+J*E;if(ae>=0&&ae<m){let de=d[S][ie][ae][D]+h[Q][J][D];de>Y&&(Y=de,V=Q,re=J)}}}$[V][re][D]+=F[S][z][j][D]}}}return{dataId:u.write(v.toTypedArray($,n.dtype),a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}},xZ={kernelName:T0,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:r})=>{let{x:n,filter:a,dy:s}=e,{strides:i,pad:o,dilations:l}=r,u=t,d=v.toNestedArray(n.shape,u.data.get(n.dataId).values),h=v.toNestedArray(a.shape,u.data.get(a.dataId).values),{batchSize:p,inHeight:c,inWidth:m,inChannels:f,outHeight:g,outWidth:y,padInfo:A,strideHeight:x,strideWidth:b,filterHeight:w,filterWidth:I,dilationHeight:T,dilationWidth:E,outShape:R}=C.computeDilation2DInfo(n.shape,a.shape,i,o,"NHWC",l);v.assert(s.rank===R.length,()=>`Error in ${T0}, dy must have the same rank as output ${R.length}, but got ${s.rank}`);let F=v.toNestedArray(R,u.data.get(s.dataId).values),$=v.makeZerosNestedTypedArray(n.shape,n.dtype);for(let S=0;S<p;++S)for(let z=0;z<g;++z){let O=z*x-A.top;for(let j=0;j<y;++j){let K=j*b-A.left;for(let D=0;D<f;++D){let Y=Number.MIN_SAFE_INTEGER,V=O<0?0:O,re=K<0?0:K;for(let Q=0;Q<w;++Q){let ie=O+Q*T;if(ie>=0&&ie<c)for(let J=0;J<I;++J){let ae=K+J*E;if(ae>=0&&ae<m){let de=d[S][ie][ae][D]+h[Q][J][D];de>Y&&(Y=de,V=ie,re=ae)}}}$[S][V][re][D]+=F[S][z][j][D]}}}return{dataId:u.write(v.toTypedArray($,n.dtype),n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};function Gh(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;Ce(a,"sum");let o;a.dtype==="bool"?o=qs({inputs:{x:a},backend:r,attrs:{dtype:"int32"}}):o=Oa({inputs:{x:a},backend:r});let l=o.shape.length,u=v.parseAxisParam(s,o.shape),d=C.getAxesPermutation(u,l),h=u,p=o;d!=null&&(p=on({inputs:{x:o},backend:r,attrs:{perm:d}}),h=C.getInnerMostAxes(h.length,l)),C.assertAxesAreInnerMostDims("sum",h,p.shape.length);let[c,m]=C.computeOutAndReduceShapes(p.shape,h),f=C.upcastType(p.dtype,"int32"),g=X0(r,c,f),y=v.sizeFromShape(m),A=r.data.get(g.dataId).values,x=r.data.get(p.dataId).values;for(let b=0;b<A.length;++b){let w=b*y,I=0;for(let T=0;T<y;++T)I+=x[w+T];A[b]=I}if(i){let b=C.expandShapeToKeepDim(g.shape,u),w=g;g=Ct({inputs:{x:g},backend:r,attrs:{shape:b}}),r.disposeIntermediateTensorInfo(w)}return r.disposeIntermediateTensorInfo(o),d!=null&&r.disposeIntermediateTensorInfo(p),g}var bZ={kernelName:zi,backendName:"cpu",kernelFunc:Gh};function vZ(e){let{inputs:t,backend:r,attrs:n}=e,{equation:a}=n,s=t,{allDims:i,summedDims:o,idDims:l}=C.decodeEinsumEquation(a,s.length);C.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:d}=C.getEinsumComputePath(o,l),h=d.length,p=null,c=i.length,m=[];for(let f=0;f<h;++f){for(let g of d[f]){let{permutationIndices:y,expandDims:A}=C.getEinsumPermutation(c,l[g]),x;C.isIdentityPermutation(y)?x=s[g]:(x=on({inputs:{x:s[g]},backend:r,attrs:{perm:y}}),m.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=Ct({inputs:{x},backend:r,attrs:{shape:b}}),m.push(x)),p===null?p=x:(p=Mm({inputs:{a:x,b:p},backend:r}),m.push(p))}f<h-1&&(u[f]>=0&&(p=Gh({inputs:{x:p},backend:r,attrs:{axis:u[f]-(i.length-c),keepDims:!1}}),m.push(p)),c--)}for(let f of m)f!==p&&r.disposeIntermediateTensorInfo(f);return p}var wZ={kernelName:uh,backendName:"cpu",kernelFunc:vZ};function kZ(e){let{inputs:t,backend:r}=e,{dy:n,y:a}=t;Ce([n,a],"eluGrad");let s=new Float32Array(v.sizeFromShape(a.shape)),i=r.data.get(a.dataId).values,o=r.data.get(n.dataId).values;for(let l=0;l<i.length;++l){let u=i[l];u>=1?s[l]=o[l]:s[l]=o[l]*(u+1)}return r.makeTensorInfo(a.shape,"float32",s)}var IZ={kernelName:bf,backendName:"cpu",kernelFunc:kZ},SZ=C.ERF_P,CZ=C.ERF_A1,TZ=C.ERF_A2,NZ=C.ERF_A3,EZ=C.ERF_A4,RZ=C.ERF_A5,$Z=gt(rd,e=>{let t=Math.sign(e),r=Math.abs(e),n=1/(1+SZ*r);return t*(1-((((RZ*n+EZ)*n+NZ)*n+TZ)*n+CZ)*n*Math.exp(-r*r))}),MZ={kernelName:rd,backendName:"cpu",kernelFunc:$Z};function Y0(e){let{inputs:t,backend:r,attrs:n}=e,{input:a}=t,{dim:s}=n,i=a.shape.length,o=a.shape.slice(),l=s;return s<0&&(v.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),o.splice(l,0,1),Ct({inputs:{x:a},backend:r,attrs:{shape:o}})}var FZ={kernelName:Yo,backendName:"cpu",kernelFunc:Y0},_Z=Qt((e,t)=>e/t),vA=br(li,_Z),py={kernelName:li,backendName:"cpu",kernelFunc:vA};function y9(e,t,r){let n=e.shape,a=n[0],s=n[1],i=r.data.get(e.dataId),o=i.complexTensorInfos.real,l=i.complexTensorInfos.imag,u=[a,s],d=v.sizeFromShape(u),h=v.getTypedArrayFromDType("float32",d),p=v.getTypedArrayFromDType("float32",d);for(let g=0;g<a;g++){let y=Do({inputs:{x:o},backend:r,attrs:{begin:[g,0],size:[1,s]}}),A=Do({inputs:{x:l},backend:r,attrs:{begin:[g,0],size:[1,s]}}),x=hn({inputs:{real:y,imag:A},backend:r}),{real:b,imag:w}=PZ(x,t,r),I=C.mergeRealAndImagArrays(b,w);for(let T=0;T<s;T++){let E=C.getComplexWithIndex(I,T);h[g*s+T]=E.real,p[g*s+T]=E.imag}r.disposeIntermediateTensorInfo(y),r.disposeIntermediateTensorInfo(A),r.disposeIntermediateTensorInfo(x)}let c=r.makeTensorInfo(u,"float32",h),m=r.makeTensorInfo(u,"float32",p),f=hn({inputs:{real:c,imag:m},backend:r});return r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(m),f}function PZ(e,t,r){let n=v.sizeFromShape(e.shape),a=r.data.get(e.dataId),s=r.data.get(a.complexTensorInfos.real.dataId).values,i=r.data.get(a.complexTensorInfos.imag.dataId).values;if(OZ(n)){let o=hy(s,i,n,t,r),l=[e.shape[0],e.shape[1]];if(t){let u=r.makeTensorInfo(l,"float32",o.real),d=r.makeTensorInfo(l,"float32",o.imag),h=r.makeTensorInfo([],"float32",v.createScalarValue(n,"float32")),p=Oa({inputs:{x:h},backend:r}),c=py.kernelFunc({inputs:{a:u,b:h},backend:r}),m=py.kernelFunc({inputs:{a:d,b:p},backend:r}),f=r.data.get(c.dataId).values,g=r.data.get(m.dataId).values;return r.disposeIntermediateTensorInfo(u),r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(m),{real:f,imag:g}}return o}else{let o=C.mergeRealAndImagArrays(s,i),l=zZ(o,n,t);return C.splitRealAndImagArrays(l)}}function OZ(e){return(e&e-1)===0}function hy(e,t,r,n,a){if(r===1)return{real:e,imag:t};let s=C.mergeRealAndImagArrays(e,t),i=r/2,o=C.complexWithEvenIndex(s),l=o.real,u=o.imag,d=[l.length],h=a.makeTensorInfo(d,"float32",l),p=a.makeTensorInfo(d,"float32",u),c=hn({inputs:{real:h,imag:p},backend:a}),m=C.complexWithOddIndex(s),f=m.real,g=m.imag,y=[f.length],A=a.makeTensorInfo(y,"float32",f),x=a.makeTensorInfo(y,"float32",g),b=hn({inputs:{real:A,imag:x},backend:a}),w=hy(l,u,i,n,a),I=w.real,T=w.imag,E=[I.length],R=a.makeTensorInfo(E,"float32",I),F=a.makeTensorInfo(E,"float32",T),$=hn({inputs:{real:R,imag:F},backend:a}),S=hy(f,g,i,n,a),z=S.real,O=S.imag,j=[z.length],K=a.makeTensorInfo(j,"float32",z),D=a.makeTensorInfo(j,"float32",O),Y=hn({inputs:{real:K,imag:D},backend:a}),V=C.exponents(r,n),re=[V.real.length],Q=a.makeTensorInfo(re,"float32",V.real),ie=a.makeTensorInfo(re,"float32",V.imag),J=hn({inputs:{real:Q,imag:ie},backend:a}),ae=Mm({inputs:{a:J,b:Y},backend:a}),de=Bu({inputs:{a:$,b:ae},backend:a}),be=xA({inputs:{a:$,b:ae},backend:a}),ve=zo({inputs:{input:de},backend:a}),Ee=zo({inputs:{input:be},backend:a}),$e=Wu({inputs:{input:de},backend:a}),ze=Wu({inputs:{input:be},backend:a}),We=Vu({inputs:[ve,Ee],backend:a,attrs:{axis:0}}),Ke=Vu({inputs:[$e,ze],backend:a,attrs:{axis:0}}),ot=a.data.get(We.dataId).values,pt=a.data.get(Ke.dataId).values;return a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(p),a.disposeIntermediateTensorInfo(c),a.disposeIntermediateTensorInfo(A),a.disposeIntermediateTensorInfo(x),a.disposeIntermediateTensorInfo(b),a.disposeIntermediateTensorInfo(R),a.disposeIntermediateTensorInfo(F),a.disposeIntermediateTensorInfo($),a.disposeIntermediateTensorInfo(K),a.disposeIntermediateTensorInfo(D),a.disposeIntermediateTensorInfo(Y),a.disposeIntermediateTensorInfo(Q),a.disposeIntermediateTensorInfo(ie),a.disposeIntermediateTensorInfo(J),a.disposeIntermediateTensorInfo(ae),a.disposeIntermediateTensorInfo(de),a.disposeIntermediateTensorInfo(be),a.disposeIntermediateTensorInfo(ve),a.disposeIntermediateTensorInfo($e),a.disposeIntermediateTensorInfo(Ee),a.disposeIntermediateTensorInfo(ze),a.disposeIntermediateTensorInfo(We),a.disposeIntermediateTensorInfo(Ke),{real:ot,imag:pt}}function zZ(e,t,r){let n=new Float32Array(t*2);for(let a=0;a<t;a++){let s=0,i=0;for(let o=0;o<t;o++){let l=C.exponent(a*o,t,r),u=C.getComplexWithIndex(e,o);s+=u.real*l.real-u.imag*l.imag,i+=u.real*l.imag+u.imag*l.real}r&&(s/=t,i/=t),C.assignToTypedArray(n,s,i,a)}return n}function DZ(e){let{inputs:t,backend:r}=e,{input:n}=t,a=v.sizeFromShape(n.shape),s=n.shape[n.shape.length-1],i=a/s,o=Ct({inputs:{x:n},backend:r,attrs:{shape:[i,s]}}),l=y9(o,!1,r),u=Ct({inputs:{x:l},backend:r,attrs:{shape:n.shape}});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(l),u}var LZ={kernelName:vf,backendName:"cpu",kernelFunc:DZ};function wA(e){let{backend:t,attrs:r}=e,{shape:n,value:a,dtype:s}=r,i=s||v.inferDtype(a),o=v.getArrayFromDType(i,v.sizeFromShape(n));return WZ(o,a,i),t.makeTensorInfo(n,i,o)}var BZ={kernelName:nd,backendName:"cpu",kernelFunc:wA};function WZ(e,t,r){e.fill(t)}var VZ={kernelName:Qo,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{image:n}=e,a=r,s=v.getTypedArrayFromDType(n.dtype,v.sizeFromShape(n.shape)),[i,o,l,u]=n.shape,d=a.data.get(n.dataId).values;for(let h=0;h<i;h++){let p=h*l*o*u;for(let c=0;c<o;c++){let m=c*(l*u);for(let f=0;f<l;f++){let g=f*u;for(let y=0;y<u;y++){let A=Math.round(l-f-1),x=p+m+g+y,b=d[x];if(A>=0&&A<l){let w=A*u,I=p+m+w+y;b=d[I]}s[x]=b}}}}return{dataId:a.write(s,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},UZ=Qt((e,t)=>Math.floor(e/t)),GZ=br(hi,UZ,null,"int32"),jZ={kernelName:hi,backendName:"cpu",kernelFunc:GZ};function HZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:d,dilations:h,dimRoundingMode:p,activation:c,leakyreluAlpha:m}=n,f=m9({inputs:{x:a,filter:s},backend:r,attrs:{strides:l,pad:u,dataFormat:d,dilations:h,dimRoundingMode:p}});if(i){let g=f;if(d==="NCHW"&&i.shape.length===1&&i.shape[0]!==1){let y=Ct({inputs:{x:i},backend:r,attrs:{shape:[i.shape[0],1,1]}});f=Bu({inputs:{a:f,b:y},backend:r}),r.disposeIntermediateTensorInfo(y)}else f=Bu({inputs:{a:f,b:i},backend:r});r.disposeIntermediateTensorInfo(g)}if(c){let g=f;if(d==="NCHW"&&c==="prelu"&&o.shape.length===1&&o.shape[0]!==1){let y=Ct({inputs:{x:o},backend:r,attrs:{shape:[o.shape[0],1,1]}});f=Z0(r,f,c,y,m),r.disposeIntermediateTensorInfo(y)}else f=Z0(r,f,c,o,m);r.disposeIntermediateTensorInfo(g)}return f}var qZ={kernelName:Os,backendName:"cpu",kernelFunc:HZ};function XZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:d,dilations:h,dimRoundingMode:p,activation:c,leakyreluAlpha:m}=n,f=g9({inputs:{x:a,filter:s},backend:r,attrs:{strides:l,pad:u,dataFormat:d,dilations:h,dimRoundingMode:p}});if(i){let g=f;f=Bu({inputs:{a:f,b:i},backend:r}),r.disposeIntermediateTensorInfo(g)}if(c){let g=f;f=Z0(r,f,c,o,m),r.disposeIntermediateTensorInfo(g)}return f}var KZ={kernelName:zs,backendName:"cpu",kernelFunc:XZ};function ZZ(e){let{inputs:t,backend:r}=e,{params:n,indices:a}=t,s=v.sizeFromShape(n.shape),i=a.shape,o=i[i.length-1],[l,u,d,h]=C.prepareAndValidate(n,a);if(u===0)return r.makeTensorInfo(l,n.dtype,[]);let p=r.data.get(a.dataId).values,c=r.bufferSync(n),m=Fk(p,c,n.dtype,u,o,d,h,n.shape,s);return r.makeTensorInfo(l,n.dtype,m.values)}var YZ={kernelName:tl,backendName:"cpu",kernelFunc:ZZ};function JZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,indices:s}=t,{axis:i,batchDims:o}=n;Ce([a,s],"gatherV2");let l=v.parseAxisParam(i,a.shape)[0],u=r.data.get(s.dataId).values,d=a.shape[l];for(let b=0;b<u.length;++b){let w=u[b];v.assert(w<=d-1&&w>=0,()=>`GatherV2: the index value ${w} is not in [0, ${d-1}]`)}let h=o;o==null&&(h=0);let p=v.sizeFromShape(s.shape),c=C.segment_util.collectGatherOpShapeInfo(a,s,l,h),m=Ct({inputs:{x:a},backend:r,attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]}}),f=Ct({inputs:{x:s},backend:r,attrs:{shape:[c.batchSize,p/c.batchSize]}}),g=[c.batchSize,c.outerSize,p/c.batchSize,c.sliceSize],y=r.bufferSync(f),A=r.bufferSync(m),x=_k(A,y,g);return r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(f),r.makeTensorInfo(c.outputShape,x.dtype,x.values)}var QZ={kernelName:el,backendName:"cpu",kernelFunc:JZ};function eY(e){let{inputs:t,backend:r}=e,{input:n}=t,a=v.sizeFromShape(n.shape),s=n.shape[n.shape.length-1],i=a/s,o=Ct({inputs:{x:n},backend:r,attrs:{shape:[i,s]}}),l=y9(o,!0,r),u=Ct({inputs:{x:l},backend:r,attrs:{shape:n.shape}});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(l),u}var tY={kernelName:wf,backendName:"cpu",kernelFunc:eY},rY=gt(ad,e=>Number.isFinite(e)?1:0,"bool"),nY={kernelName:ad,backendName:"cpu",kernelFunc:rY},aY=gt(sd,e=>Math.abs(e)===1/0?1:0,"bool"),sY={kernelName:sd,backendName:"cpu",kernelFunc:aY},iY=gt(id,e=>Number.isNaN(e)?1:0,"bool"),oY={kernelName:id,backendName:"cpu",kernelFunc:iY};function lY(e){let{backend:t,attrs:r}=e,{start:n,stop:a,num:s}=r,i=Lk(n,a,s);return t.makeTensorInfo([i.length],"float32",i)}var uY={kernelName:kf,backendName:"cpu",kernelFunc:lY},dY=gt(od,e=>Math.log1p(e)),pY={kernelName:od,backendName:"cpu",kernelFunc:dY},hY=Qt((e,t)=>e&&t),cY=br(sl,hY,null,"bool"),fY={kernelName:sl,backendName:"cpu",kernelFunc:cY},mY=gt(il,e=>e?0:1,"bool"),gY={kernelName:il,backendName:"cpu",kernelFunc:mY},yY=Qt((e,t)=>e||t),AY=br(ld,yY,null,"bool"),xY={kernelName:ld,backendName:"cpu",kernelFunc:AY};function bY(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n;Ce(a,"LRN");let u=a.shape[3],d=u-1,h=r.data.get(a.dataId).values,p=v.sizeFromShape(a.shape),c=new Float32Array(p);function m(f){let g=f%u,y=f-g+Math.max(0,g-s),A=f-g+Math.min(g+s,d),x=0;for(;y<=A;y++){let b=h[y];x+=b*b}return x}for(let f=0;f<p;f++){let g=m(f),y=h[f]*Math.pow(i+o*g,-l);c[f]=y}return r.makeTensorInfo(a.shape,a.dtype,c)}var vY={kernelName:ph,backendName:"cpu",kernelFunc:bY};function wY(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:d}=n;Ce(i,"LRNGrad");let h=v.sizeFromShape(i.shape),p=i.shape[3],c=r.data.get(i.dataId).values,m=r.data.get(a.dataId).values,f=r.data.get(s.dataId).values,g=new Float32Array(h),y=h;for(let A=0;A<y;A++){let x=A%p,b=A-x+Math.max(0,x-o),w=A-x+Math.min(p,x+o+1),I=0;for(let T=b;T<w;T++)I+=Math.pow(m[T],2);I=u*I+l;for(let T=b;T<w;T++){let E=-2*u*d*m[T]*f[A]/I;A===T&&(E+=Math.pow(I,-d)),E*=c[A],g[T]+=E}}return r.makeTensorInfo(i.shape,a.dtype,g)}var kY={kernelName:If,backendName:"cpu",kernelFunc:wY};function A9(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{reductionIndices:s,keepDims:i}=n,o=r,l=a.shape,u=l.length,d=v.parseAxisParam(s,l),h=d,p=C.getAxesPermutation(h,u),c=o.data.get(a.dataId).values;if(p!=null){let b=new Array(u);for(let w=0;w<b.length;w++)b[w]=l[p[w]];c=gA(c,l,a.dtype,p,b),h=C.getInnerMostAxes(h.length,u),l=b}Ce(a,"max"),C.assertAxesAreInnerMostDims("max",h,u);let[m,f]=C.computeOutAndReduceShapes(l,h),g=v.sizeFromShape(f),y=Wk(c,g,m,a.dtype),A=o.write(y,m,a.dtype),x=m;return i&&(x=C.expandShapeToKeepDim(m,d)),{dataId:A,shape:x,dtype:a.dtype}}var IY={kernelName:Ai,backendName:"cpu",kernelFunc:A9};function SY(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t;Ce(a,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1;v.assert(C.eitherStridesOrDilationsAreOne(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=C.computePool2DInfo(a.shape,s,i,u,o,l),h;if(d.filterWidth===1&&d.filterHeight===1&&v.arraysEqual(d.inShape,d.outShape))h=Oa({inputs:{x:a},backend:r});else{let p=r.data.get(a.dataId).values,c=v.computeStrides(a.shape),m=bA(p,a.shape,a.dtype,c,d,"max");h=r.makeTensorInfo(d.outShape,a.dtype,m.values)}return h}var CY={kernelName:bi,backendName:"cpu",kernelFunc:SY};function TY(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=n;Ce(a,"maxPool3d");let d=C.computePool3DInfo(a.shape,s,i,1,o,l,u),h=r.data.get(a.dataId).values,p=f9(h,a.shape,a.dtype,v.computeStrides(a.shape),d,"max");return r.makeTensorInfo(p.shape,"float32",p.values)}var NY={kernelName:hh,backendName:"cpu",kernelFunc:TY};function EY(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=n;Ce([a,s],"maxPool3DGrad");let d=C.computePool3DInfo(s.shape,i,o,1,l,u),h=r.bufferSync(s),p=gK(h,d),c=d.strideDepth,m=d.strideHeight,f=d.strideWidth,g=d.dilationDepth,y=d.dilationHeight,A=d.dilationWidth,x=d.effectiveFilterDepth,b=d.effectiveFilterHeight,w=d.effectiveFilterWidth,I=x-1-d.padInfo.front,T=w-1-d.padInfo.left,E=b-1-d.padInfo.top,R=De(s.shape,"float32"),F=r.bufferSync(a);for(let $=0;$<d.batchSize;++$)for(let S=0;S<d.inChannels;++S)for(let z=0;z<d.inDepth;++z)for(let O=0;O<d.inHeight;++O)for(let j=0;j<d.inWidth;++j){let K=z-I,D=O-E,Y=j-T,V=0;for(let re=0;re<x;re+=g){let Q=(K+re)/c;if(!(Q<0||Q>=d.outDepth||Math.floor(Q)!==Q))for(let ie=0;ie<b;ie+=y){let J=(D+ie)/m;if(!(J<0||J>=d.outHeight||Math.floor(J)!==J))for(let ae=0;ae<w;ae+=A){let de=(Y+ae)/f;if(de<0||de>=d.outWidth||Math.floor(de)!==de)continue;let be=x*b*w-1-p.get($,Q,J,de,S),ve=re*b*w+ie*w+ae,Ee=be===ve?1:0;Ee!==0&&(V+=F.get($,Q,J,de,S)*Ee)}}}R.set(V,$,z,O,j,S)}return r.makeTensorInfo(R.shape,R.dtype,R.values)}var RY={kernelName:Cf,backendName:"cpu",kernelFunc:EY};function $Y(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s,output:i}=t,o=s;Ce([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:d,dimRoundingMode:h}=n,p=C.computePool2DInfo(o.shape,l,u,1,d,h),c=r.data.get(o.dataId).values,m=De(p.outShape,o.dtype,c9(c,o.shape,o.dtype,p).values),f=p.strideHeight,g=p.strideWidth,y=p.dilationHeight,A=p.dilationWidth,x=p.effectiveFilterHeight,b=p.effectiveFilterWidth,w=b-1-p.padInfo.left,I=x-1-p.padInfo.top,T=De(o.shape,"float32"),E=r.data.get(a.dataId).values,R=De(a.shape,"float32",E);for(let F=0;F<p.batchSize;++F)for(let $=0;$<p.inChannels;++$)for(let S=0;S<p.inHeight;++S)for(let z=0;z<p.inWidth;++z){let O=S-I,j=z-w,K=0;for(let D=0;D<x;D+=y){let Y=(O+D)/f;if(!(Y<0||Y>=p.outHeight||Math.floor(Y)!==Y))for(let V=0;V<b;V+=A){let re=(j+V)/g;if(re<0||re>=p.outWidth||Math.floor(re)!==re)continue;let Q=x*b-1-m.get(F,Y,re,$),ie=D*b+V,J=Q===ie?1:0;J!==0&&(K+=R.get(F,Y,re,$)*J)}}T.set(K,F,S,z,$)}return r.makeTensorInfo(T.shape,T.dtype,T.values)}var MY={kernelName:Sf,backendName:"cpu",kernelFunc:$Y};function FY(e,t,r,n,a){let s=v.computeStrides(t),i=bA(e,t,r,s,a,"max"),o=c9(e,t,r,a,!0,n);return[i.values,o.values]}var _Y={kernelName:Tf,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:n}=e,{filterSize:a,strides:s,pad:i,includeBatchInIndex:o}=t,l=r;Ce(n,"MaxPoolWithArgmax");let u=l.data.get(n.dataId).values,d=C.computePool2DInfo(n.shape,a,s,[1,1],i),[h,p]=FY(u,n.shape,n.dtype,o,d),c=l.write(h,d.outShape,n.dtype),m=l.write(p,d.outShape,n.dtype);return[{dataId:c,shape:d.outShape,dtype:n.dtype},{dataId:m,shape:d.outShape,dtype:"int32"}]}};function PY(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n,o=v.parseAxisParam(s,a.shape),l=C.computeOutAndReduceShapes(a.shape,o)[1],u=v.sizeFromShape(l),d=[],h=r.makeTensorInfo([],"float32",new Float32Array([u]));d.push(h);let p=qs({inputs:{x:a},backend:r,attrs:{dtype:"float32"}});d.push(p);let c=vA({inputs:{a:p,b:h},backend:r});d.push(c);let m=Gh({inputs:{x:c},backend:r,attrs:{axis:s,keepDims:i}});return d.forEach(f=>r.disposeIntermediateTensorInfo(f)),m}var OY={kernelName:vi,backendName:"cpu",kernelFunc:PY};function zY(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;Ce(a,"min");let o=v.parseAxisParam(s,a.shape),l=o,u=C.getAxesPermutation(l,a.shape.length),d=a;u!=null&&(d=on({inputs:{x:a},backend:r,attrs:{perm:u}}),l=C.getInnerMostAxes(l.length,a.shape.length)),C.assertAxesAreInnerMostDims("min",l,d.shape.length);let[h,p]=C.computeOutAndReduceShapes(d.shape,l),c=v.sizeFromShape(p),m=v.makeZerosTypedArray(v.sizeFromShape(h),d.dtype),f=r.data.get(d.dataId).values;for(let y=0;y<m.length;++y){let A=y*c,x=f[A];for(let b=0;b<c;++b){let w=f[A+b];(Number.isNaN(w)||w<x)&&(x=w)}m[y]=x}u!=null&&r.disposeIntermediateTensorInfo(d);let g=r.makeTensorInfo(h,d.dtype,m);if(i){let y=C.expandShapeToKeepDim(h,o),A=Ct({inputs:{x:g},backend:r,attrs:{shape:y}});return r.disposeIntermediateTensorInfo(g),A}return g}var DY={kernelName:wi,backendName:"cpu",kernelFunc:zY};function LY(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{paddings:s,mode:i}=n;Ce(a,"mirrorPad");let o=s.map((A,x)=>A[0]+a.shape[x]+A[1]),l=s.map(A=>A[0]),u=s.map((A,x)=>A[0]+a.shape[x]),d=i==="reflect"?0:1,h=r.data.get(a.dataId).values,p=a.shape.length,c=v.computeStrides(a.shape),m=v.sizeFromShape(o),f=o.length,g=v.computeStrides(o),y=v.getTypedArrayFromDType(a.dtype,m);for(let A=0;A<m;A++){let x=v.indexToLoc(A,f,g);for(let w=0;w<f;w++)x[w]<l[w]?x[w]=l[w]*2-x[w]-d:x[w]>=u[w]&&(x[w]=(u[w]-1)*2-x[w]+d);x=x.map((w,I)=>w-l[I]);let b=v.locToIndex(x,p,c);y[A]=h[b]}return{dataId:r.write(y,o,a.dtype),shape:o,dtype:a.dtype}}var BY={kernelName:Ii,backendName:"cpu",kernelFunc:LY},WY=Qt((e,t)=>{let r=e%t;return e<0&&t<0||e>=0&&t>=0?r:(r+t)%t}),VY=br(ud,WY),UY={kernelName:ud,backendName:"cpu",kernelFunc:VY},GY=Vo(sf());function x9(e){let{inputs:t,backend:r,attrs:n}=e,{logits:a}=t,{dim:s}=n,i=a.shape.length,o=s;if(o===-1&&(o=i-1),o!==i-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${o}`);let l=v.parseAxisParam([o],a.shape),u=A9({inputs:{x:a},backend:r,attrs:{reductionIndices:l,keepDims:!1}}),d=C.expandShapeToKeepDim(u.shape,l),h=Ct({inputs:{x:u},backend:r,attrs:{shape:d}}),p=xA({inputs:{a,b:h},backend:r}),c=Rk({inputs:{x:p},backend:r}),m=Gh({inputs:{x:c},backend:r,attrs:{axis:l,keepDims:!1}}),f=Ct({inputs:{x:m},backend:r,attrs:{shape:d}}),g=vA({inputs:{a:c,b:f},backend:r});return r.disposeIntermediateTensorInfo(u),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(f),g}var jY={kernelName:Di,backendName:"cpu",kernelFunc:x9};function HY(e){let{inputs:t,backend:r,attrs:n}=e,{logits:a}=t,{numSamples:s,seed:i,normalized:o}=n;Ce(a,"multinomial");let l=o?a:x9({inputs:{logits:a},backend:r,attrs:{dim:-1}}),u=l.shape[0],d=l.shape[1],h=r.data.get(l.dataId).values,p=[u,s],c=v.makeZerosTypedArray(v.sizeFromShape(p),"int32");for(let m=0;m<u;++m){let f=m*d,g=new Float32Array(d-1);g[0]=h[f];for(let x=1;x<g.length;++x)g[x]=g[x-1]+h[f+x];let y=GY.alea(i.toString()),A=m*s;for(let x=0;x<s;++x){let b=y();c[A+x]=g.length;for(let w=0;w<g.length;w++)if(b<g[w]){c[A+x]=w;break}}}return o||r.disposeIntermediateTensorInfo(l),r.makeTensorInfo(p,"int32",c)}var qY={kernelName:Nf,backendName:"cpu",kernelFunc:HY},XY=Kn.nonMaxSuppressionV3Impl;function KY(e){let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=n;Ce(a,"NonMaxSuppression");let u=r.data.get(a.dataId).values,d=r.data.get(s.dataId).values,{selectedIndices:h}=XY(u,d,i,o,l);return r.makeTensorInfo([h.length],"int32",new Int32Array(h))}var ZY={kernelName:ul,backendName:"cpu",kernelFunc:KY},YY=Kn.nonMaxSuppressionV4Impl;function JY(e){let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=n;Ce(a,"NonMaxSuppressionPadded");let d=r.data.get(a.dataId).values,h=r.data.get(s.dataId).values,{selectedIndices:p,validOutputs:c}=YY(d,h,i,o,l,u);return[r.makeTensorInfo([p.length],"int32",new Int32Array(p)),r.makeTensorInfo([],"int32",new Int32Array([c]))]}var QY={kernelName:dd,backendName:"cpu",kernelFunc:JY},eJ=Kn.nonMaxSuppressionV5Impl;function tJ(e){let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=n;Ce(a,"NonMaxSuppressionWithScore");let d=r.data.get(a.dataId).values,h=r.data.get(s.dataId).values,p=i,c=o,m=l,f=u,{selectedIndices:g,selectedScores:y}=eJ(d,h,p,c,m,f);return[r.makeTensorInfo([g.length],"int32",new Int32Array(g)),r.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var rJ={kernelName:dl,backendName:"cpu",kernelFunc:tJ};function nJ(e){let{inputs:t,backend:r,attrs:n}=e,{indices:a}=t,{depth:s,onValue:i,offValue:o}=n;Ce(a,"oneHot");let l=v.sizeFromShape(a.shape),u=new Float32Array(l*s);u.fill(o);let d=r.data.get(a.dataId).values;for(let h=0;h<l;++h)d[h]>=0&&d[h]<s&&(u[h*s+d[h]]=i);return r.makeTensorInfo([...a.shape,s],"int32",u)}var aJ={kernelName:hl,backendName:"cpu",kernelFunc:nJ};function J0(e){let{inputs:t,backend:r}=e,{x:n}=t;if(n.dtype==="string")throw new Error("zerosLike is not supported for string tensors");if(n.dtype==="complex64"){let a=zo({inputs:{input:n},backend:r}),s=J0({inputs:{x:a},backend:r}),i=Wu({inputs:{input:n},backend:r}),o=J0({inputs:{x:i},backend:r}),l=hn({inputs:{real:s,imag:o},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}else return wA({backend:r,attrs:{shape:n.shape,value:0,dtype:n.dtype}})}var sJ={kernelName:Nl,backendName:"cpu",kernelFunc:J0};function b9(e){let{inputs:t,backend:r}=e,{x:n}=t;if(n.dtype==="string")throw new Error("onesLike is not supported for string tensors");if(n.dtype==="complex64"){let a=zo({inputs:{input:n},backend:r}),s=b9({inputs:{x:a},backend:r}),i=Wu({inputs:{input:n},backend:r}),o=J0({inputs:{x:i},backend:r}),l=hn({inputs:{real:s,imag:o},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}else return wA({backend:r,attrs:{shape:n.shape,value:1,dtype:n.dtype}})}var iJ={kernelName:pl,backendName:"cpu",kernelFunc:b9};function v9(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n;if(t.length===1)return Y0({inputs:{input:t[0]},backend:r,attrs:{dim:a}});let s=t[0].shape,i=t[0].dtype;t.forEach(d=>{v.assertShapesMatch(s,d.shape,"All tensors passed to stack must have matching shapes"),v.assert(i===d.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(d=>{let h=Y0({inputs:{input:d},backend:r,attrs:{dim:a}});return o.push(h),h}),u=Vu({inputs:l,backend:r,attrs:{axis:a}});return o.forEach(d=>r.disposeIntermediateTensorInfo(d)),u}var oJ={kernelName:cl,backendName:"cpu",kernelFunc:v9};function lJ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{paddings:s,constantValue:i}=n;Ce(a,"pad");let o=s.map((y,A)=>y[0]+a.shape[A]+y[1]),l=s.map(y=>y[0]),u=r.data.get(a.dataId).values,d=v.sizeFromShape(a.shape),h=a.shape.length,p=v.computeStrides(a.shape),c=v.sizeFromShape(o),m=o.length,f=v.computeStrides(o),g=v.getTypedArrayFromDType(a.dtype,c);i!==0&&g.fill(i);for(let y=0;y<d;y++){let A=v.indexToLoc(y,h,p).map((b,w)=>b+l[w]),x=v.locToIndex(A,m,f);g[x]=u[y]}return{dataId:r.write(g,o,a.dtype),shape:o,dtype:a.dtype}}var w9={kernelName:Ci,backendName:"cpu",kernelFunc:lJ},uJ=Qt((e,t)=>Math.pow(e,t)),dJ=br(Ti,uJ),pJ={kernelName:Ti,backendName:"cpu",kernelFunc:dJ};function hJ(e){let{backend:t,attrs:r}=e,{start:n,stop:a,dtype:s,step:i}=r,o=yA(n,a,i,s);return t.makeTensorInfo([o.length],s,o)}var cJ={kernelName:pd,backendName:"cpu",kernelFunc:hJ},fJ=gt(hd,e=>1/e),mJ={kernelName:hd,backendName:"cpu",kernelFunc:fJ};function gJ(e){let{inputs:t,backend:r,attrs:n}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n;Ce(a,"resizeBilinear");let l=v.computeStrides(a.shape),[u,d]=o,[h,p,c,m]=a.shape,f=r.data.get(a.dataId).values,g=new Float32Array(v.sizeFromShape([h,u,d,m])),y=[s&&u>1?p-1:p,s&&d>1?c-1:c],A=[s&&u>1?u-1:u,s&&d>1?d-1:d],x=0,b=y[0]/A[0],w=y[1]/A[1];for(let I=0;I<h;I++)for(let T=0;T<u;T++){let E;i?E=b*(T+.5)-.5:E=b*T;let R=Math.max(0,Math.floor(E)),F=E-R,$=Math.min(p-1,Math.ceil(E)),S=I*l[0]+R*l[1],z=I*l[0]+$*l[1];for(let O=0;O<d;O++){let j;i?j=w*(O+.5)-.5:j=w*O;let K=Math.max(0,Math.floor(j)),D=j-K,Y=Math.min(c-1,Math.ceil(j)),V=S+K*l[2],re=z+K*l[2],Q=S+Y*l[2],ie=z+Y*l[2];for(let J=0;J<m;J++){let ae=f[V+J],de=f[re+J],be=f[Q+J],ve=f[ie+J],Ee=ae+(be-ae)*D,$e=de+(ve-de)*D,ze=Ee+($e-Ee)*F;g[x++]=ze}}}return r.makeTensorInfo([h,u,d,m],"float32",g)}var yJ={kernelName:$i,backendName:"cpu",kernelFunc:gJ};function AJ(e){let{inputs:t,backend:r,attrs:n}=e,{images:a,dy:s}=t,{alignCorners:i}=n;Ce([s,a],"resizeBilinearGrad");let o=v.computeStrides(a.shape),[l,u,d,h]=a.shape,[,p,c]=s.shape,m=new Float32Array(l*u*d*h),f=[i&&p>1?u-1:u,i&&c>1?d-1:d],g=[i&&p>1?p-1:p,i&&c>1?c-1:c],y=f[0]/g[0],A=f[1]/g[1],x=r.data.get(s.dataId).values,b=0;for(let w=0;w<l;w++){let I=w*o[0];for(let T=0;T<p;T++){let E=T*y,R=Math.floor(E),F=Math.min(Math.ceil(E),u-1),$=I+R*o[1],S=I+F*o[1],z=E-R,O=1-z;for(let j=0;j<c;j++){let K=j*A,D=Math.floor(K),Y=Math.min(Math.ceil(K),d-1),V=K-D,re=1-V,Q=$+D*o[2],ie=$+Y*o[2],J=S+D*o[2],ae=S+Y*o[2],de=O*re,be=O*V,ve=z*re,Ee=z*V;for(let $e=0;$e<h;$e++){let ze=x[b++];m[Q+$e]+=ze*de,m[ie+$e]+=ze*be,m[J+$e]+=ze*ve,m[ae+$e]+=ze*Ee}}}}return r.makeTensorInfo([l,d,u,h],"float32",m)}var xJ={kernelName:Rf,backendName:"cpu",kernelFunc:AJ};function bJ(e){let{inputs:t,backend:r,attrs:n}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n;Ce(a,"resizeNearestNeighbor");let l=v.computeStrides(a.shape),[u,d]=o,[h,p,c,m]=a.shape,f=r.data.get(a.dataId).values,g=new Float32Array(h*u*d*m),y=[s&&u>1?p-1:p,s&&d>1?c-1:c],A=[s&&u>1?u-1:u,s&&d>1?d-1:d],x=y[0]/A[0],b=y[1]/A[1],w=0;for(let I=0;I<h;I++){let T=I*l[0];for(let E=0;E<u;E++){let R=i?x*(E+.5):x*E,F=Math.min(p-1,s?Math.round(R):Math.floor(R));i&&(F=Math.max(0,F));let $=T+F*l[1];for(let S=0;S<d;S++){let z=i?b*(S+.5):b*S,O=Math.min(c-1,s?Math.round(z):Math.floor(z));i&&(O=Math.max(0,O));let j=$+O*l[2];for(let K=0;K<m;K++){let D=f[j+K];g[w++]=D}}}}return r.makeTensorInfo([h,u,d,m],a.dtype,g)}var vJ={kernelName:cd,backendName:"cpu",kernelFunc:bJ};function wJ(e){let{inputs:t,backend:r,attrs:n}=e,{images:a,dy:s}=t,{alignCorners:i}=n;Ce([s,a],"resizeNearestNeighborGrad");let o=v.computeStrides(a.shape),l=v.computeStrides(s.shape),[u,d,h,p]=a.shape,[,c,m]=s.shape,f=new Float32Array(u*d*h*p),g=r.data.get(s.dataId).values,y=[i&&c>1?d-1:d,i&&m>1?h-1:h],A=[i&&c>1?c-1:c,i&&m>1?m-1:m],x=y[0]/A[0],b=y[1]/A[1],w=1/x,I=1/b,T=Math.ceil(w)*2+2,E=Math.ceil(I)*2+2;for(let R=0;R<u;R++){let F=R*o[0];for(let $=0;$<d;$++){let S=F+$*o[1],z=Math.floor($*w),O=Math.floor(z-T/2);for(let j=0;j<h;j++){let K=S+j*o[2],D=Math.floor(j*I),Y=Math.floor(D-E/2);for(let V=0;V<p;V++){let re=0;for(let Q=0;Q<T;Q++){let ie=Q+O;if(ie<0||ie>=c)continue;let J=F+ie*l[1],ae=ie*x,de=Math.min(d-1,i?Math.round(ae):Math.floor(ae));if($===de)for(let be=0;be<E;be++){let ve=be+Y;if(ve<0||ve>=m)continue;let Ee=J+ve*l[2],$e=ve*b,ze=Math.min(h-1,i?Math.round($e):Math.floor($e));j===ze&&(re+=g[Ee+V])}}f[K+V]=re}}}}return r.makeTensorInfo(a.shape,a.dtype,f)}var kJ={kernelName:Ef,backendName:"cpu",kernelFunc:wJ};function IJ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{dims:s}=n;Ce(a,"reverse");let i=a.shape.length,o=v.parseAxisParam(s,a.shape);if(i===0)return Oa({inputs:{x:a},backend:r});let l=new ir(a.shape,a.dtype),u=r.bufferSync(a);for(let d=0;d<l.size;d++){let h=l.indexToLoc(d),p=h.slice();o.forEach(c=>p[c]=a.shape[c]-1-p[c]),l.set(u.get(...p),...h)}return r.makeTensorInfo(l.shape,l.dtype,l.values)}var SJ={kernelName:ml,backendName:"cpu",kernelFunc:IJ},CJ={kernelName:El,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{image:n}=e,{radians:a,fillValue:s,center:i}=t,o=r,l=v.getTypedArrayFromDType(n.dtype,v.sizeFromShape(n.shape)),[u,d,h,p]=n.shape,[c,m]=C.getImageCenter(i,d,h),f=255,g=Math.sin(a),y=Math.cos(a),A=o.data.get(n.dataId).values;for(let x=0;x<u;x++){let b=x*h*d*p;for(let w=0;w<d;w++){let I=w*(h*p);for(let T=0;T<h;T++){let E=T*p;for(let R=0;R<p;R++){let F=[u,w,T,R],$=F[2],S=F[1],z=($-c)*y-(S-m)*g,O=($-c)*g+(S-m)*y;z=Math.round(z+c),O=Math.round(O+m);let j=s;if(typeof s!="number"&&(R===3?j=f:j=s[R]),z>=0&&z<h&&O>=0&&O<d){let D=O*(h*p),Y=z*p,V=b+D+Y+R;j=A[V]}let K=b+I+E+R;l[K]=j}}}}return{dataId:o.write(l,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},TJ=gt(gl,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}),NJ={kernelName:gl,backendName:"cpu",kernelFunc:TJ};function EJ(e){let{inputs:t,backend:r,attrs:n}=e,{indices:a,updates:s}=t,{shape:i}=n,{sliceRank:o,numUpdates:l,sliceSize:u,strides:d,outputSize:h}=C.calculateShapes(s,a,i),p=!0,c=r.bufferSync(a),m=r.bufferSync(s),f=wu(c,m,i,h,u,l,o,d,0,p);return r.makeTensorInfo(i,f.dtype,f.values)}var RJ={kernelName:yl,backendName:"cpu",kernelFunc:EJ};function $J(e,t){let r=0,n=e.length,a=0;for(;r<n;)a=Math.floor((r+n)/2),e[a]<t?r=a+1:n=a;return n}function MJ(e,t){let r=0,n=e.length,a=0;for(;r<n;)a=Math.floor((r+n)/2),e[a]<=t?r=a+1:n=a;return n}function FJ(e,t,r,n,a,s){let i=v.getArrayFromDType("int32",r*a);for(let o=0;o<r;++o){let l=e.slice(o*n,(o+1)*n),u=o*a;for(let d=0;d<a;++d)i[u+d]=s==="left"?$J(l,t[d+u]):MJ(l,t[d+u])}return i}function _J(e){let{inputs:t,backend:r,attrs:n}=e,{sortedSequence:a,values:s}=t,{side:i}=n,o=r.data.get(a.dataId).values,l=r.data.get(s.dataId).values,u=FJ(o,l,a.shape[0],a.shape[1],s.shape[1],i);return r.makeTensorInfo(s.shape,"int32",u)}var PJ={kernelName:$f,backendName:"cpu",kernelFunc:_J};function OJ(e){let{inputs:t,backend:r}=e,{condition:n,t:a,e:s}=t;Ce([n,a,s],"select");let i=n.shape.length,o=r.data.get(n.dataId).values,l=r.data.get(a.dataId).values,u=r.data.get(s.dataId).values,d=Nr(a.dtype,s.dtype),h=v.makeZerosTypedArray(v.sizeFromShape(a.shape),d),p=0,c=i===0||i>1||a.shape.length===1?1:v.sizeFromShape(a.shape.slice(1));for(let m=0;m<o.length;m++)for(let f=0;f<c;f++)o[m]===1?h[p++]=l[m]:h[p++]=u[m];return r.makeTensorInfo(a.shape,d,h)}var zJ={kernelName:Al,backendName:"cpu",kernelFunc:OJ},DJ=C.SELU_SCALEALPHA,LJ=C.SELU_SCALE,BJ=gt(fd,e=>e>=0?LJ*e:DJ*(Math.exp(e)-1)),WJ={kernelName:fd,backendName:"cpu",kernelFunc:BJ},VJ=gt(md,e=>e<0?-1:e>0?1:0),UJ={kernelName:md,backendName:"cpu",kernelFunc:VJ},GJ=gt(_i,e=>Math.sin(e)),jJ={kernelName:_i,backendName:"cpu",kernelFunc:GJ},HJ=gt(bl,e=>Math.sinh(e)),qJ={kernelName:bl,backendName:"cpu",kernelFunc:HJ},XJ=11920928955078125e-23,j4=Math.log(XJ)+2,KJ=gt(gd,e=>{let t=e>-j4,r=e<j4,n=Math.exp(e),a;return r?a=n:t?a=e:a=Math.log(1+n),a}),ZJ={kernelName:gd,backendName:"cpu",kernelFunc:KJ};function YJ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,paddings:i}=n;Ce([a],"spaceToBatchND");let o=v.sizeFromShape(s),l=[[0,0]];l.push(...i);for(let g=1+s.length;g<a.shape.length;++g)l.push([0,0]);let u=w9.kernelFunc({inputs:{x:a},backend:r,attrs:{paddings:l,constantValue:0}}),d=C.getReshaped(u.shape,s,o,!1),h=C.getPermuted(d.length,s.length,!1),p=C.getReshapedPermuted(u.shape,s,o,!1),c=Ct({inputs:{x:u},backend:r,attrs:{shape:d}}),m=on({inputs:{x:c},backend:r,attrs:{perm:h}}),f=Ct({inputs:{x:m},backend:r,attrs:{shape:p}});return r.disposeIntermediateTensorInfo(u),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(m),f}var JJ={kernelName:vl,backendName:"cpu",kernelFunc:YJ};function QJ(e){let{inputs:t,backend:r}=e,{indices:n,values:a,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
|
|
${s.shape}`);if(n.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
|
|
${n.shape}`);if(a.shape.length!==1)throw new Error(`Values must be a vector, saw:
|
|
${a.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${i.shape}`);let o=r.data.get(n.dataId).values,l=r.data.get(a.dataId).values,u=r.data.get(s.dataId).values,d=r.data.get(i.dataId).values[0],[h,p,c,m,f]=Kk(o,n.shape,n.dtype,l,a.dtype,u,d);return[r.makeTensorInfo(p,n.dtype,h),r.makeTensorInfo([p[0]],a.dtype,c),r.makeTensorInfo([m.length],"bool",new Uint8Array(m.map(g=>Number(g)))),r.makeTensorInfo([f.length],n.dtype,new Int32Array(f))]}var eQ={kernelName:fh,backendName:"cpu",kernelFunc:QJ};function tQ(e){let{inputs:t,backend:r}=e,{inputIndices:n,inputShape:a,newShape:s}=t;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
|
|
${n.shape}`);if(a.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
|
|
${a.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(r.data.get(a.dataId).values),o=r.data.get(n.dataId).values,l=Array.from(r.data.get(s.dataId).values),[u,d,h]=Zk(o,n.shape,n.dtype,i,l);return[r.makeTensorInfo(d,n.dtype,u),r.makeTensorInfo([h.length],s.dtype,new Int32Array(h))]}var rQ={kernelName:yd,backendName:"cpu",kernelFunc:tQ};function nQ(e){let{inputs:t,backend:r}=e,{data:n,indices:a,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${a.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);if(a.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=r.data.get(n.dataId).values,o=r.data.get(a.dataId).values,l=r.data.get(s.dataId).values,[u,d]=AA(i,n.shape,n.dtype,o,l,!0);return r.makeTensorInfo(d,n.dtype,u)}var aQ={kernelName:mh,backendName:"cpu",kernelFunc:nQ};function sQ(e){let{inputs:t,backend:r}=e,{data:n,indices:a,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${a.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);if(a.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=r.data.get(n.dataId).values,o=r.data.get(a.dataId).values,l=r.data.get(s.dataId).values,[u,d]=AA(i,n.shape,n.dtype,o,l);return r.makeTensorInfo(d,n.dtype,u)}var iQ={kernelName:gh,backendName:"cpu",kernelFunc:sQ};function oQ(e){let{inputs:t,backend:r,attrs:n}=e,{sparseIndices:a,sparseValues:s,defaultValue:i}=t,{outputShape:o}=n,{sliceRank:l,numUpdates:u,sliceSize:d,strides:h,outputSize:p}=C.calculateShapes(s,a,o),c=!1,m=r.bufferSync(a),f;switch(s.dtype){case"bool":{let g=r.bufferSync(s),y=Boolean(r.data.get(i.dataId).values[0]);f=wu(m,g,o,p,d,u,l,h,y,c);break}case"float32":{let g=r.bufferSync(s),y=r.data.get(i.dataId).values[0];f=wu(m,g,o,p,d,u,l,h,y,c);break}case"int32":{let g=r.bufferSync(s),y=r.data.get(i.dataId).values[0];f=wu(m,g,o,p,d,u,l,h,y,c);break}case"string":{let g=r.bufferSync(s),y=v.decodeString(r.data.get(i.dataId).values[0]);f=wu(m,g,o,p,d,u,l,h,y,c);break}default:throw new Error(`Unsupported type ${s.dtype}`)}return r.makeTensorInfo(o,f.dtype,f.values)}var lQ={kernelName:yh,backendName:"cpu",kernelFunc:oQ};function uQ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{numOrSizeSplits:s,axis:i}=n,o=v.parseAxisParam(i,a.shape)[0],l=C.prepareSplitSize(a,s,o),u=new Array(a.shape.length).fill(0),d=a.shape.slice();return l.map(h=>{let p=[...d];p[o]=h;let c=Do({inputs:{x:a},backend:r,attrs:{begin:u,size:p}});return u[o]+=h,c})}var dQ={kernelName:wl,backendName:"cpu",kernelFunc:uQ},pQ={kernelName:Ad,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:r}=e,n=t;Ce(r,"square");let a=n.data.get(r.dataId).values,s=new Float32Array(a.length);for(let i=0;i<a.length;++i){let o=a[i];s[i]=o*o}return{dataId:n.write(s,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},hQ=gt(Vi,(e,t)=>{let r=t;return isNaN(e)?NaN:e>0?1:r.alpha}),cQ={kernelName:Vi,backendName:"cpu",kernelFunc:hQ};function fQ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:d,newAxisMask:h,shrinkAxisMask:p}=n;Ce(a,"stridedSlice");let{finalShapeSparse:c,finalShape:m,isIdentity:f,sliceDim0:g,isSimpleSlice:y,begin:A,end:x,strides:b}=Dt.sliceInfo(a.shape,s,i,o,l,u,d,h,p),w;if(f)w=Ct({inputs:{x:a},backend:r,attrs:{shape:m}});else if(g||y){v.assert(a.shape.length>=1,()=>`Input must have rank at least 1, got: ${a.shape.length}`);let I=Dt.computeOutShape(A,x,b),T=Do({inputs:{x:a},backend:r,attrs:{begin:A,size:I}});w=Ct({inputs:{x:T},backend:r,attrs:{shape:m}}),r.disposeIntermediateTensorInfo(T)}else{let I=r.bufferSync(a),T=Jk(c,I,b,A);w=r.makeTensorInfo(m,T.dtype,T.values)}return w}var mQ={kernelName:kl,backendName:"cpu",kernelFunc:fQ};function gQ(e){let{inputs:t,backend:r,attrs:n}=e,{separator:a,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=n,{data:d,dataSplits:h}=t,p=r.data.get(d.dataId).values,c=r.data.get(h.dataId).values,[m,f]=Qk(p,c,a,s,i,o,l,u);return[r.makeTensorInfo([m.length],"string",m),r.makeTensorInfo(h.shape,"int32",f)]}var yQ={kernelName:Ah,backendName:"cpu",kernelFunc:gQ};function AQ(e){let{inputs:t,backend:r,attrs:n}=e,{skipEmpty:a}=n,{input:s,delimiter:i}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let o=r.data.get(s.dataId).values,l=r.data.get(i.dataId).values[0],[u,d,h]=e9(o,l,a),p=d.length;return[r.makeTensorInfo([p,2],"int32",u),r.makeTensorInfo([p],"string",d),r.makeTensorInfo([2],"int32",new Int32Array(h))]}var xQ={kernelName:Mf,backendName:"cpu",kernelFunc:AQ};function bQ(e){let{inputs:t,backend:r,attrs:n}=e,{numBuckets:a}=n,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(a<=0)throw new Error("Number of buckets must be at least 1");let i=r.data.get(s.dataId).values,o=t9(i,a);return r.makeTensorInfo(s.shape,"int32",o)}var vQ={kernelName:Ff,backendName:"cpu",kernelFunc:bQ},wQ=gt(Il,e=>Math.tan(e)),kQ={kernelName:Il,backendName:"cpu",kernelFunc:wQ},IQ=gt(Wi,e=>Math.tanh(e)),SQ={kernelName:Wi,backendName:"cpu",kernelFunc:IQ};function CQ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{reps:s}=n;Ce(a,"tile");let i=n9(r.bufferSync(a),s);return r.makeTensorInfo(i.shape,i.dtype,i.values)}var TQ={kernelName:ts,backendName:"cpu",kernelFunc:CQ};function NQ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{k:s,sorted:i}=n;Ce(a,"topk");let o=r.data.get(a.dataId).values,[l,u]=s9(o,a.shape,a.dtype,s,i);return[r.makeTensorInfo(l.shape,l.dtype,l.values),r.makeTensorInfo(u.shape,u.dtype,u.values)]}var EQ={kernelName:Sl,backendName:"cpu",kernelFunc:NQ};function RQ(e){let{inputs:t,attrs:r,backend:n}=e,{image:a,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=r,[d,h,p,c]=a.shape,[m,f]=u!=null?u:[h,p],g=[d,m,f,c],y=v.computeStrides(a.shape),A=y[0],x=y[1],b=y[2],w=v.getTypedArrayFromDType(a.dtype,v.sizeFromShape(g));w.fill(l);let I=n.data.get(a.dataId).values,T=n.data.get(s.dataId).values;for(let E=0;E<d;++E){let R=s.shape[0]===1?T:T.subarray(E*8,E*8+8);for(let F=0;F<m;++F)for(let $=0;$<f;++$)for(let S=0;S<c;++S){let z,O=R[6]*$+R[7]*F+1;if(O===0)continue;let j=(R[0]*$+R[1]*F+R[2])/O,K=(R[3]*$+R[4]*F+R[5])/O,D=H4(j,p,o),Y=H4(K,h,o);switch(i){case"nearest":z=OQ(I,h,p,A,x,b,E,Y,D,S,l);break;case"bilinear":z=zQ(I,h,p,A,x,b,E,Y,D,S,l);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${i}`)}let V=E*A+F*x+$*b+S;w[V]=z}return n.makeTensorInfo(g,a.dtype,w)}return{dataId:n.write(w,g,a.dtype),shape:a.shape,dtype:a.dtype}}var $Q={kernelName:Cl,backendName:"cpu",kernelFunc:RQ};function H4(e,t,r){switch(r){case"reflect":return MQ(e,t);case"wrap":return FQ(e,t);case"nearest":return PQ(e,t);case"constant":default:return _Q(e,t)}}function MQ(e,t){let r=e;if(r<0)if(t<=1)r=0;else{let n=2*t;r<n&&(r=n*Math.trunc(-r/n)+r),r=r<-t?r+n:-r-1}else if(r>t-1)if(t<=1)r=0;else{let n=2*t;r-=n*Math.trunc(r/n),r>=t&&(r=n-r-1)}return v.clamp(0,r,t-1)}function FQ(e,t){let r=e;if(r<0)if(t<=1)r=0;else{let n=t-1;r+=t*(Math.trunc(-r/n)+1)}else if(r>t-1)if(t<=1)r=0;else{let n=t-1;r-=t*Math.trunc(r/n)}return v.clamp(0,r,t-1)}function _Q(e,t){return e}function PQ(e,t){return v.clamp(0,e,t-1)}function Pp(e,t,r,n,a,s,i,o,l,u,d){let h=i*n+o*a+l*s+u;return 0<=o&&o<t&&0<=l&&l<r?e[h]:d}function OQ(e,t,r,n,a,s,i,o,l,u,d){let h=Math.round(o),p=Math.round(l);return Pp(e,t,r,n,a,s,i,h,p,u,d)}function zQ(e,t,r,n,a,s,i,o,l,u,d){let h=Math.floor(o),p=Math.floor(l),c=h+1,m=p+1,f=(m-l)*Pp(e,t,r,n,a,s,i,h,p,u,d)+(l-p)*Pp(e,t,r,n,a,s,i,h,m,u,d),g=(m-l)*Pp(e,t,r,n,a,s,i,c,p,u,d)+(l-p)*Pp(e,t,r,n,a,s,i,c,m,u,d);return(c-o)*f+(o-h)*g}function DQ(e){let{inputs:t,attrs:r,backend:n}=e,{axis:a}=r,{x:s}=t;Ce(s,"unique");let i=n.data.get(s.dataId).values,{outputValues:o,outputShape:l,indices:u}=i9(i,a,s.shape,s.dtype);return[n.makeTensorInfo(l,s.dtype,o),n.makeTensorInfo([u.length],"int32",u)]}var LQ={kernelName:_f,backendName:"cpu",kernelFunc:DQ};function BQ(e){let{inputs:t,backend:r,attrs:n}=e,{value:a}=t,{axis:s}=n;s<0&&(s+=a.shape.length);let i=a.shape.length,o=a.shape[s],l=new Array(i-1),u=0;for(let c=0;c<i;c++)c!==s&&(l[u++]=a.shape[c]);let d=new Array(i).fill(0),h=a.shape.slice();h[s]=1;let p=new Array(o);for(let c=0;c<p.length;c++){d[s]=c;let m=Do({inputs:{x:a},backend:r,attrs:{begin:d,size:h}});p[c]=Ct({inputs:{x:m},backend:r,attrs:{shape:l}}),r.disposeIntermediateTensorInfo(m)}return p}var WQ={kernelName:Tl,backendName:"cpu",kernelFunc:BQ};function VQ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,segmentIds:s}=t,{numSegments:i}=n;Ce(a,"unsortedSegmentSum");let o=a.shape.length,l=s.shape.length,u=[],d=[],h=o-l,p=s;for(let m=0;m<h;++m){let f=Y0({inputs:{input:p},backend:r,attrs:{dim:m+1}});p=f,d.push(f)}for(let m=0;m<i;++m){let f=v.createScalarValue(m,"int32"),g=r.makeTensorInfo([],"int32",f),y=Nk({inputs:{a:g,b:p},backend:r}),A=qs({inputs:{x:y},backend:r,attrs:{dtype:"float32"}}),x=Mm({inputs:{a:A,b:a},backend:r}),b=Gh({inputs:{x},backend:r,attrs:{axis:0,keepDims:!1}});u.push(b),d.push(g),d.push(y),d.push(A),d.push(x),d.push(b)}let c=v9({inputs:u,backend:r,attrs:{axis:0}});return d.forEach(m=>r.disposeIntermediateTensorInfo(m)),c}var UQ={kernelName:xh,backendName:"cpu",kernelFunc:VQ},GQ=[GX,Oq,HX,XX,Vq,ZX,JX,eK,rK,aK,iK,lK,dK,cK,mK,AK,bK,wK,IK,VX,CK,NK,RK,MK,Bq,Gq,_K,zq,OK,DK,LK,WK,UK,jK,qK,KK,YK,QK,tZ,nZ,sZ,oZ,uZ,dZ,hZ,fZ,gZ,yZ,AZ,xZ,wZ,PX,IZ,jq,MZ,Hq,FZ,Xq,LZ,BZ,VZ,Zq,jZ,qZ,KZ,YZ,QZ,Jq,eX,Dq,tY,zK,nY,sY,oY,OX,rX,aX,uY,iX,pY,fY,gY,xY,vY,kY,IY,lX,CY,NY,RY,MY,_Y,OY,DY,dX,BY,UY,qY,hX,fX,ZY,QY,rJ,gX,aJ,iJ,oJ,w9,pJ,DX,xX,cJ,Lq,py,mJ,LX,BX,WX,yJ,xJ,vJ,kJ,SJ,CJ,NJ,vX,RJ,PJ,zJ,WJ,kX,UJ,jJ,qJ,IX,jY,ZJ,JJ,eQ,rQ,aQ,iQ,lQ,dQ,TX,pQ,EX,cQ,mQ,yQ,xQ,vQ,FX,bZ,kQ,SQ,TQ,EQ,$Q,yX,LQ,WQ,UQ,sJ];for(let e of GQ)qn(e);var k9={};Be(k9,{assertNotComplex:()=>Md,bindCanvasToFramebuffer:()=>tee,bindColorTextureToFramebuffer:()=>y0,bindTextureToProgramUniformSampler:()=>D9,bindTextureUnit:()=>P9,bindVertexBufferToProgramAttribute:()=>cy,callAndCheck:()=>we,canBeRepresented:()=>I9,createFragmentShader:()=>T9,createFramebuffer:()=>_9,createProgram:()=>N9,createStaticIndexBuffer:()=>$9,createStaticVertexBuffer:()=>R9,createTexture:()=>M9,createVertexShader:()=>C9,getBatchDim:()=>Lo,getExtensionOrThrow:()=>Op,getFramebufferErrorMessage:()=>L9,getMaxTexturesInShader:()=>U9,getNumChannels:()=>QQ,getProgramUniformLocation:()=>z9,getProgramUniformLocationOrThrow:()=>O9,getRowsCols:()=>Bo,getShapeAs3D:()=>A0,getTextureShapeFromLogicalShape:()=>W9,getWebGLDisjointQueryTimerVersion:()=>G9,getWebGLErrorMessage:()=>S9,getWebGLMaxTextureSize:()=>V9,hasExtension:()=>En,isCapableOfRenderingToFloatTexture:()=>j9,isDownloadFloatTextureEnabled:()=>H9,isReshapeFree:()=>th,isWebGLFenceEnabled:()=>q9,isWebGLVersionEnabled:()=>my,linkProgram:()=>E9,logShaderSourceAndInfoLog:()=>IA,resetMaxTextureSize:()=>ree,resetMaxTexturesInShader:()=>nee,unbindColorTextureFromFramebuffer:()=>fy,unbindTextureUnit:()=>eee,validateFramebuffer:()=>zp,validateProgram:()=>g0,validateTextureSize:()=>F9});var ko={},Sg={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Fm(e,t){ko[e]=t}function xa(e,t){if(!(e in ko)||t!=null){let n=HQ(e,t);if(n!==null)ko[e]=n;else return console.log("Could not get context for WebGL version",e),null}let r=ko[e];return r==null||r.isContextLost()?(delete ko[e],xa(e)):(r.disable(r.DEPTH_TEST),r.disable(r.STENCIL_TEST),r.disable(r.BLEND),r.disable(r.DITHER),r.disable(r.POLYGON_OFFSET_FILL),r.disable(r.SAMPLE_COVERAGE),r.enable(r.SCISSOR_TEST),r.enable(r.CULL_FACE),r.cullFace(r.BACK),ko[e])}function jQ(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 HQ(e,t){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let r=t==null?jQ(e):t;return r.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete ko[e]},!1),e===1?r.getContext("webgl",Sg)||r.getContext("experimental-webgl",Sg):r.getContext("webgl2",Sg)}function jh(e,t){return[t,e]}function qQ(e,t){return e*t}function u0(e){let t=v.sizeFromShape(e),r=Math.ceil(t/4);return v.sizeToSquarishShape(r)}function $d(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function XQ(e,t){let[r,n]=$d(e,t);return r*n*4}function kA(e,t){let r=e,n,a,s,i,o,l,u,d,h,p;return Z().getNumber("WEBGL_VERSION")===2?(n=r.R32F,a=r.R16F,s=r.RGBA16F,i=r.RGBA32F,o=r.RED,u=4,d=1,h=r.HALF_FLOAT,p=r.FLOAT,l=r.RGBA8):(n=e.RGBA,a=e.RGBA,s=e.RGBA,i=r.RGBA,o=e.RGBA,u=4,d=4,h=t!=null?t.HALF_FLOAT_OES:null,p=e.FLOAT,l=e.RGBA),{internalFormatFloat:n,internalFormatHalfFloat:a,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:d,textureTypeHalfFloat:h,textureTypeFloat:p}}function we(e,t){let r=t();return Z().getBool("DEBUG")&&KQ(e),r}function KQ(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+S9(e,t))}var ZQ=596e-10,YQ=65504;function I9(e){return!!(Z().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||ZQ<Math.abs(e)&&Math.abs(e)<YQ)}function S9(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 Op(e,t){return is(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function C9(e,t){let r=is(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(we(e,()=>e.shaderSource(r,t)),we(e,()=>e.compileShader(r)),e.getShaderParameter(r,e.COMPILE_STATUS)===!1)throw console.log(e.getShaderInfoLog(r)),new Error("Failed to compile vertex shader.");return r}function T9(e,t){let r=is(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(we(e,()=>e.shaderSource(r,t)),we(e,()=>e.compileShader(r)),Z().get("ENGINE_COMPILE_ONLY"))return r;if(e.getShaderParameter(r,e.COMPILE_STATUS)===!1)throw IA(t,e.getShaderInfoLog(r)),new Error("Failed to compile fragment shader.");return r}var JQ=/ERROR: [0-9]+:([0-9]+):/g;function IA(e,t){let r=JQ.exec(t);if(r==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}let n=+r[1],a=e.split(`
|
|
`),s=a.length.toString().length+2,i=a.map((h,p)=>v.rightPad((p+1).toString(),s)+h),o=0;for(let h=0;h<i.length;h++)o=Math.max(i[h].length,o);let l=i.slice(0,n-1),u=i.slice(n-1,n),d=i.slice(n);console.log(l.join(`
|
|
`)),console.log(t.split(`
|
|
`)[0]),console.log(`%c ${v.rightPad(u[0],o)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(d.join(`
|
|
`))}function N9(e){return is(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function E9(e,t){if(we(e,()=>e.linkProgram(t)),!Z().get("ENGINE_COMPILE_ONLY")&&e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function g0(e,t){if(we(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function R9(e,t){let r=is(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return we(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),we(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),r}function $9(e,t){let r=is(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return we(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,r)),we(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),r}function QQ(){return Z().getNumber("WEBGL_VERSION")===2?1:4}function M9(e){return is(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function F9(e,t){let r=Z().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let n=`[${e}x${t}]`;throw new Error("Requested texture size "+n+" is invalid.")}if(e>r||t>r){let n=`[${e}x${t}]`,a=`[${r}x${r}]`;throw new Error("Requested texture size "+n+" greater than WebGL maximum on this browser / GPU "+a+".")}}function _9(e){return is(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function cy(e,t,r,n,a,s,i){let o=e.getAttribLocation(t,r);return o===-1?!1:(we(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),we(e,()=>e.vertexAttribPointer(o,a,e.FLOAT,!1,s,i)),we(e,()=>e.enableVertexAttribArray(o)),!0)}function P9(e,t,r){B9(e,r),we(e,()=>e.activeTexture(e.TEXTURE0+r)),we(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function eee(e,t){B9(e,t),we(e,()=>e.activeTexture(e.TEXTURE0+t)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function O9(e,t,r){return is(e,()=>e.getUniformLocation(t,r),'uniform "'+r+'" not present in program.')}function z9(e,t,r){return e.getUniformLocation(t,r)}function D9(e,t,r,n){we(e,()=>P9(e,t,n)),we(e,()=>e.uniform1i(r,n))}function tee(e){we(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),we(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),we(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function y0(e,t,r){we(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,r)),we(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function fy(e,t){we(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),we(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function zp(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+L9(e,t))}function L9(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 is(e,t,r){let n=we(e,()=>t());if(n==null)throw new Error(r);return n}function B9(e,t){let r=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,n=t+e.TEXTURE0;if(n<e.TEXTURE0||n>r){let a=`[gl.TEXTURE0, gl.TEXTURE${r}]`;throw new Error(`textureUnit must be in ${a}.`)}}function Lo(e,t=2){return v.sizeFromShape(e.slice(0,e.length-t))}function Bo(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 A0(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[Lo(e),...Bo(e)]),t}function W9(e,t=!1){let r=Z().getNumber("WEBGL_MAX_TEXTURE_SIZE");t&&(r=r*2,e=e.map((a,s)=>s>=e.length-2?v.nearestLargerEven(e[s]):e[s]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=v.squeezeShape(e).newShape);let n=v.sizeFromShape(e);if(e.length<=1&&n<=r)return[1,n];if(e.length===2&&e[0]<=r&&e[1]<=r)return e;if(e.length===3&&e[0]*e[1]<=r&&e[2]<=r)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=r&&e[1]*e[2]<=r)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=r&&e[3]<=r)return[e[0]*e[1]*e[2],e[3]];if(e.length===4&&e[0]<=r&&e[1]*e[2]*e[3]<=r)return[e[0],e[1]*e[2]*e[3]];if(t){let a=Lo(e),s=2,i=2;return e.length&&([s,i]=Bo(e)),n=a*(s/2)*(i/2),v.sizeToSquarishShape(n).map(o=>o*2)}return v.sizeToSquarishShape(n)}function d0(e){return e%2===0}function th(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 r=e.slice(-1)[0],n=t.slice(-1)[0];if(r===n||d0(r)&&d0(n)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&d0(e[0])&&d0(t[0])}var x0,b0;function V9(e){if(x0==null){let t=xa(e);x0=t.getParameter(t.MAX_TEXTURE_SIZE)}return x0}function ree(){x0=null}function nee(){b0=null}function U9(e){if(b0==null){let t=xa(e);b0=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,b0)}function G9(e){if(e===0)return 0;let t,r=xa(e);return En(r,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:En(r,"EXT_disjoint_timer_query")?t=1:t=0,t}function En(e,t){return e.getExtension(t)!=null}function my(e){try{if(xa(e)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function j9(e){if(e===0)return!1;let t=xa(e);if(e===1){if(!En(t,"OES_texture_float"))return!1}else if(!En(t,"EXT_color_buffer_float"))return!1;return gy(t)}function H9(e){if(e===0)return!1;let t=xa(e);if(e===1){if(!En(t,"OES_texture_float")||!En(t,"WEBGL_color_buffer_float"))return!1}else{if(En(t,"EXT_color_buffer_float"))return gy(t);let r="EXT_color_buffer_half_float";if(En(t,r)){let n=t.getExtension(r);return aee(t,n)}return!1}return gy(t)}function gy(e){let t=kA(e),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r);let n=1,a=1;e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,n,a,0,t.textureFormatFloat,t.textureTypeFloat,null);let s=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);let i=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(r),e.deleteFramebuffer(s),i}function aee(e,t){let r=kA(e,t),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);let a=1,s=1;e.texImage2D(e.TEXTURE_2D,0,r.internalFormatHalfFloat,a,s,0,r.textureFormatFloat,r.textureTypeHalfFloat,null);let i=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,i),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(i),o}function q9(e){return e!==2?!1:xa(e).fenceSync!=null}function Md(e,t){Array.isArray(e)||(e=[e]),e.forEach(r=>{r!=null&&v.assert(r.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}var Me=Z();Me.registerFlag("HAS_WEBGL",()=>Me.getNumber("WEBGL_VERSION")>0);Me.registerFlag("WEBGL_VERSION",()=>my(2)?2:my(1)?1:0);Me.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);Me.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Me.get("WEBGL_VERSION")===2);Me.registerFlag("WEBGL_CPU_FORWARD",()=>!0);Me.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);Me.registerFlag("WEBGL_PACK",()=>Me.getBool("HAS_WEBGL"));Me.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Me.getBool("WEBGL_PACK"));Me.registerFlag("WEBGL_PACK_CLIP",()=>Me.getBool("WEBGL_PACK"));Me.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>Me.getBool("WEBGL_PACK"));Me.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Me.getBool("WEBGL_PACK"));Me.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Me.getBool("WEBGL_PACK"));Me.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Me.getBool("WEBGL_PACK"));Me.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Me.getBool("WEBGL_PACK"));Me.registerFlag("WEBGL_PACK_REDUCE",()=>Me.getBool("WEBGL_PACK"));Me.registerFlag("WEBGL_LAZILY_UNPACK",()=>Me.getBool("WEBGL_PACK"));Me.registerFlag("WEBGL_CONV_IM2COL",()=>Me.getBool("WEBGL_PACK"));Me.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>V9(Me.getNumber("WEBGL_VERSION")));Me.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>U9(Me.getNumber("WEBGL_VERSION")));Me.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let e=Me.getNumber("WEBGL_VERSION");return e===0?0:G9(e)});Me.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Me.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!kh.isMobile());Me.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>j9(Me.getNumber("WEBGL_VERSION")));Me.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>Me.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Me.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));Me.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>H9(Me.getNumber("WEBGL_VERSION")));Me.registerFlag("WEBGL_FENCE_API_ENABLED",()=>q9(Me.getNumber("WEBGL_VERSION")));Me.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>Me.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);Me.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}.`)});Me.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>kh.isMobile()?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}.`)});Me.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);Me.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1);Me.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5);Me.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128);function Xr(){let e,t,r,n,a,s,i,o,l,u;return Z().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",r="out",n="in",a="texture",s="outputColor",i="out vec4 outputColor;",o=`
|
|
bool isnan_custom(float val) {
|
|
uint floatToUint = floatBitsToUint(val);
|
|
return (floatToUint & 0x7fffffffu) > 0x7f800000u;
|
|
}
|
|
|
|
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="",u=`
|
|
#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",r="varying",n="varying",a="texture2D",s="gl_FragColor",i="",o=`
|
|
#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));
|
|
}
|
|
`,u=`
|
|
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:r,varyingFs:n,texture2D:a,output:s,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:l,defineRound:u}}function Dl(e,t,r="index"){let n=v.computeStrides(t);return n.map((a,s)=>{let i=`int ${e[s]} = ${r} / ${a}`,o=s===n.length-1?`int ${e[s+1]} = ${r} - ${e[s]} * ${a}`:`index -= ${e[s]} * ${a}`;return`${i}; ${o};`}).join("")}function _m(e,t,r="index"){let n=v.computeStrides(t);return n.map((a,s)=>{let i=`int ${e[s]} = ${r} / outShapeStrides[${s}]`,o=s===n.length-1?`int ${e[s+1]} = ${r} - ${e[s]} * outShapeStrides[${s}]`:`index -= ${e[s]} * outShapeStrides[${s}]`;return`${i}; ${o};`}).join("")}function see(e,t){let r=e.length,n=e.map(s=>`${t}[${s}]`),a=new Array(r-1);a[r-2]=n[r-1];for(let s=r-3;s>=0;--s)a[s]=`(${a[s+1]} * ${n[s+1]})`;return a}function iee(e,t,r="index"){let n=e.map((s,i)=>i),a=see(n,t);return a.map((s,i)=>{let o=`int ${e[i]} = ${r} / ${a[i]}`,l=i===a.length-1?`int ${e[i+1]} = ${r} - ${e[i]} * ${a[i]}`:`index -= ${e[i]} * ${a[i]}`;return`${o}; ${l};`}).join("")}function SA(e){let t=v.computeStrides(e).map(r=>r.toString());return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
|
|
}
|
|
`}function CA(){return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
|
|
}
|
|
`}var X9=`
|
|
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:K9}=C;function oee(e,t,r){let n=[];if(e.forEach(p=>{let c=v.sizeFromShape(p.shapeInfo.logicalShape);if(p.shapeInfo.isUniform?n.push(`uniform float ${p.name}${c>1?`[${c}]`:""};`):(n.push(`uniform sampler2D ${p.name};`),n.push(`uniform int offset${p.name};`)),r.enableShapeUniforms){let{uniformShape:m}=TA(r.packedInputs,p.shapeInfo.logicalShape,p.shapeInfo.texShape);switch(m.length){case 1:n.push(`uniform int ${p.name}Shape;`);break;case 2:n.push(`uniform ivec2 ${p.name}Shape;`);break;case 3:n.push(`uniform ivec3 ${p.name}Shape;`);break;case 4:n.push(`uniform ivec4 ${p.name}Shape;`);break;default:break}n.push(`uniform ivec2 ${p.name}TexShape;`)}}),r.enableShapeUniforms){switch(t.logicalShape.length){case 1:n.push("uniform int outShape;");break;case 2:n.push("uniform ivec2 outShape;"),n.push("uniform int outShapeStrides;");break;case 3:n.push("uniform ivec3 outShape;"),n.push("uniform ivec2 outShapeStrides;");break;case 4:n.push("uniform ivec4 outShape;"),n.push("uniform ivec3 outShapeStrides;");break;default:break}n.push("uniform ivec2 outTexShape;")}r.customUniforms&&r.customUniforms.forEach(p=>{n.push(`uniform ${p.type} ${p.name}${p.arrayIndex?`[${p.arrayIndex}]`:""};`)});let a=n.join(`
|
|
`),s=e.map(p=>lee(p,t,r.packedInputs,r.enableShapeUniforms)).join(`
|
|
`),i=t.texShape,o=Xr(),l=pee(o),u,d,h=fee(o);return t.isPacked?(u=uee(t.logicalShape,i,r.enableShapeUniforms),d=cee(o)):(u=dee(t.logicalShape,i,r.enableShapeUniforms),d=hee(o)),r.packedInputs&&(h+=Aee),[h,l,d,a,u,s,r.userCode].join(`
|
|
`)}function Fd(e,t=!1){let r=e.shapeInfo.logicalShape;switch(r.length){case 0:return Ree(e,t);case 1:return Mee(e,t);case 2:return _ee(e,t);case 3:return Oee(e,t);case 4:return Dee(e,t);case 5:return Lee(e);case 6:return Bee(e);default:throw new Error(`${r.length}-D input sampling is not yet supported`)}}function Z9(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return Eee(e);case 1:return $ee(e,t);case 2:return Fee(e,t);case 3:return Pee(e,t);default:return zee(e,t)}}function lee(e,t,r=!1,n){let a="";r?a+=Z9(e,n):a+=Fd(e,n);let s=e.shapeInfo.logicalShape,i=t.logicalShape;return s.length<=i.length&&(r?a+=Wee(e,t):a+=Vee(e,t)),a}function uee(e,t,r){switch(e.length){case 0:return Y9();case 1:return xee(e,t,r);case 2:return Tee(e,t,r);case 3:return vee(e,t,r);default:return kee(e,t,r)}}function dee(e,t,r){switch(e.length){case 0:return Y9();case 1:return bee(e,t,r);case 2:return Nee(e,t,r);case 3:return wee(e,t,r);case 4:return Iee(e,t,r);case 5:return See(e,t);case 6:return Cee(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function pee(e){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return ${e.texture2D}(textureSampler, uv).r;
|
|
}
|
|
`}function hee(e){return`
|
|
void setOutput(float val) {
|
|
${e.output} = vec4(val, 0, 0, 0);
|
|
}
|
|
`}function cee(e){return`
|
|
void setOutput(vec4 val) {
|
|
${e.output} = val;
|
|
}
|
|
`}function fee(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);
|
|
}
|
|
|
|
${mee}
|
|
${gee}
|
|
${yee}
|
|
`}var mee=`
|
|
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);
|
|
}
|
|
`,gee=`
|
|
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);
|
|
}
|
|
`,yee=`
|
|
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);
|
|
}
|
|
`,Aee=`
|
|
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 Y9(){return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`}function xee(e,t,r){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return n[0]===1?r?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * ${n[1]}.0);
|
|
}
|
|
`:n[1]===1?r?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * ${n[0]}.0);
|
|
}
|
|
`:r?`
|
|
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(${n[0]}, ${n[1]}));
|
|
return 2 * (resTexRC.x * ${n[1]} + resTexRC.y);
|
|
}
|
|
`}function bee(e,t,r){return t[0]===1?r?`
|
|
int getOutputCoords() {
|
|
return int(resultUV.x * float(outTexShape[1]));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return int(resultUV.x * ${t[1]}.0);
|
|
}
|
|
`:t[1]===1?r?`
|
|
int getOutputCoords() {
|
|
return int(resultUV.y * float(outTexShape[0]));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return int(resultUV.y * ${t[0]}.0);
|
|
}
|
|
`:r?`
|
|
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 vee(e,t,r){if(r)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 n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[2]/2),s=a*Math.ceil(e[1]/2);return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${n[0]}, ${n[1]}));
|
|
int index = resTexRC.x * ${n[1]} + resTexRC.y;
|
|
|
|
int b = index / ${s};
|
|
index -= b * ${s};
|
|
|
|
int r = 2 * (index / ${a});
|
|
int c = imod(index, ${a}) * 2;
|
|
|
|
return ivec3(b, r, c);
|
|
}
|
|
`}function wee(e,t,r){if(r)return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
${_m(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`;let n=Dl(["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;
|
|
${n}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}function kee(e,t,r){if(r)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 n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[e.length-1]/2),s=a*Math.ceil(e[e.length-2]/2),i=s,o="",l="b, r, c";for(let u=2;u<e.length-1;u++)i*=e[e.length-u-1],o=`
|
|
int b${u} = index / ${i};
|
|
index -= b${u} * ${i};
|
|
`+o,l=`b${u}, `+l;return`
|
|
ivec${e.length} getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${n[0]}, ${n[1]}));
|
|
int index = resTexRC.x * ${n[1]} + resTexRC.y;
|
|
|
|
${o}
|
|
|
|
int b = index / ${s};
|
|
index -= b * ${s};
|
|
|
|
int r = 2 * (index / ${a});
|
|
int c = imod(index, ${a}) * 2;
|
|
|
|
return ivec${e.length}(${l});
|
|
}
|
|
`}function Iee(e,t,r){if(r)return`
|
|
ivec4 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
${_m(["r","c","d","d2"],e)}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`;let n=Dl(["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;
|
|
${n}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`}function See(e,t){let r=Dl(["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;
|
|
|
|
${r}
|
|
|
|
ivec5 outShape = ivec5(r, c, d, d2, d3);
|
|
return outShape;
|
|
}
|
|
`}function Cee(e,t){let r=Dl(["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;
|
|
|
|
${r}
|
|
|
|
ivec6 result = ivec6(r, c, d, d2, d3, d4);
|
|
return result;
|
|
}
|
|
`}function Tee(e,t,r){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(v.arraysEqual(e,t))return r?`
|
|
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(${n[0]}, ${n[1]}));
|
|
}
|
|
`;let a=Math.ceil(e[1]/2);return r?`
|
|
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(${n[0]}, ${n[1]}));
|
|
|
|
int index = resTexRC.x * ${n[1]} + resTexRC.y;
|
|
int r = 2 * (index / ${a});
|
|
int c = imod(index, ${a}) * 2;
|
|
|
|
return ivec2(r, c);
|
|
}
|
|
`}function Nee(e,t,r){return v.arraysEqual(e,t)?r?`
|
|
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?r?`
|
|
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?r?`
|
|
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);
|
|
}
|
|
`:r?`
|
|
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 Ll(e){return`offset${e}`}function Eee(e){let t=e.name,r="get"+t.charAt(0).toUpperCase()+t.slice(1),n=Xr();return`
|
|
vec4 ${r}() {
|
|
return ${n.texture2D}(${t}, halfCR);
|
|
}
|
|
`}function Ree(e,t){let r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1);if(e.shapeInfo.isUniform)return`float ${n}() {return ${r};}`;let[a,s]=e.shapeInfo.texShape;if(a===1&&s===1)return`
|
|
float ${n}() {
|
|
return sampleTexture(${r}, halfCR);
|
|
}
|
|
`;let i=Ll(r);if(t)return`
|
|
float ${n}() {
|
|
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], ${i});
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;let[o,l]=e.shapeInfo.texShape;return`
|
|
float ${n}() {
|
|
vec2 uv = uvFromFlat(${o}, ${l}, ${i});
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function $ee(e,t){let r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,s=Xr();if(t)return`
|
|
vec4 ${n}(int index) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom1D(
|
|
packedTexShape[0], packedTexShape[1], index);
|
|
return ${s.texture2D}(${r}, uv);
|
|
}
|
|
`;let i=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];return`
|
|
vec4 ${n}(int index) {
|
|
vec2 uv = packedUVfrom1D(
|
|
${i[0]}, ${i[1]}, index);
|
|
return ${s.texture2D}(${r}, uv);
|
|
}
|
|
`}function Mee(e,t){let r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1);if(e.shapeInfo.isUniform)return`
|
|
float ${n}(int index) {
|
|
${_d(e)}
|
|
}
|
|
`;let a=e.shapeInfo.texShape,s=a[0],i=a[1];if(i===1&&s===1)return`
|
|
float ${n}(int index) {
|
|
return sampleTexture(${r}, halfCR);
|
|
}
|
|
`;let o=Ll(r);return i===1?t?`
|
|
float ${n}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / float(${r}TexShape[0]));
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / ${s}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:s===1?t?`
|
|
float ${n}(int index) {
|
|
vec2 uv = vec2((float(index + ${o}) + 0.5) / float(${r}TexShape[1]), 0.5);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(int index) {
|
|
vec2 uv = vec2((float(index + ${o}) + 0.5) / ${i}.0, 0.5);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:t?`
|
|
float ${n}(int index) {
|
|
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index + ${o});
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(int index) {
|
|
vec2 uv = uvFromFlat(${s}, ${i}, index + ${o});
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function Fee(e,t){let r=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,i=s[0],o=s[1],l=Xr();if(s!=null&&v.arraysEqual(r,s))return t?`
|
|
vec4 ${a}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
|
|
|
|
return ${l.texture2D}(${n}, uv);
|
|
}
|
|
`:`
|
|
vec4 ${a}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}.0, ${i}.0);
|
|
|
|
return ${l.texture2D}(${n}, uv);
|
|
}
|
|
`;if(t)return`
|
|
vec4 ${a}(int row, int col) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
|
|
int valuesPerRow = int(ceil(float(${n}Shape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
|
|
return ${l.texture2D}(${n}, uv);
|
|
}
|
|
`;let u=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],d=Math.ceil(r[1]/2);return`
|
|
vec4 ${a}(int row, int col) {
|
|
vec2 uv = packedUVfrom2D(${d}, ${u[0]}, ${u[1]}, row, col);
|
|
return ${l.texture2D}(${n}, uv);
|
|
}
|
|
`}function _ee(e,t){let r=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape;if(s!=null&&v.arraysEqual(r,s)){if(t)return`
|
|
float ${a}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let p=s[0],c=s[1];return`
|
|
float ${a}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${c}.0, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}let{newShape:i,keptDims:o}=v.squeezeShape(r),l=i;if(l.length<r.length){let p=Pd(e,l),c=["row","col"];return`
|
|
${Fd(p,t)}
|
|
float ${a}(int row, int col) {
|
|
return ${a}(${Od(c,o)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(${r[1]}, 1)));
|
|
${_d(e)}
|
|
}
|
|
`;let u=s[0],d=s[1],h=Ll(n);return d===1?t?`
|
|
float ${a}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${h}), vec3(${n}Shape[1], 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / float(${n}TexShape[0]));
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${h}), vec3(${r[1]}, 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / ${u}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:u===1?t?`
|
|
float ${a}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${h}), vec3(${n}Shape[1], 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / float(${n}TexShape[1]), 0.5);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${h}), vec3(${r[1]}, 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / ${d}.0, 0.5);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:t?`
|
|
float ${a}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${n}Shape[1] + col + ${h};
|
|
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${r[1]} + col + ${h};
|
|
vec2 uv = uvFromFlat(${u}, ${d}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function Pee(e,t){let r=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];if(r[0]===1){let p=r.slice(1),c=[1,2],m=Pd(e,p),f=["b","row","col"];return`
|
|
${Z9(m,t)}
|
|
vec4 ${a}(int b, int row, int col) {
|
|
return ${a}(${Od(f,c)});
|
|
}
|
|
`}let o=Xr();if(t)return`
|
|
vec4 ${a}(int b, int row, int col) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
|
|
int valuesPerRow = int(ceil(float(${n}Shape[2]) / 2.0));
|
|
int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom3D(
|
|
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
|
|
return ${o.texture2D}(${n}, uv);
|
|
}
|
|
`;let l=i[0],u=i[1],d=Math.ceil(r[2]/2),h=d*Math.ceil(r[1]/2);return`
|
|
vec4 ${a}(int b, int row, int col) {
|
|
vec2 uv = packedUVfrom3D(
|
|
${l}, ${u}, ${h}, ${d}, b, row, col);
|
|
return ${o.texture2D}(${n}, uv);
|
|
}
|
|
`}function Oee(e,t){let r=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),s=r[1]*r[2],i=r[2],{newShape:o,keptDims:l}=v.squeezeShape(r),u=o;if(u.length<r.length){let f=Pd(e,u),g=["row","col","depth"];return`
|
|
${Fd(f,t)}
|
|
float ${a}(int row, int col, int depth) {
|
|
return ${a}(${Od(g,l)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int row, int col, int depth) {
|
|
int index = round(dot(vec3(row, col, depth),
|
|
vec3(${s}, ${i}, 1)));
|
|
${_d(e)}
|
|
}
|
|
`;let d=e.shapeInfo.texShape,h=d[0],p=d[1],c=e.shapeInfo.flatOffset;if(p===s&&c==null)return t?`
|
|
float ${a}(int row, int col, int depth) {
|
|
int stride1 = ${n}Shape[2];
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(stride1, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${n}TexShape[1], ${n}TexShape[0]);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int row, int col, int depth) {
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(${i}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${p}.0, ${h}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(p===i&&c==null)return t?`
|
|
float ${a}(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(${n}Shape[1], 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(${r[1]}, 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}.0, ${h}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let m=Ll(n);return t?`
|
|
float ${a}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int stride0 = ${n}Shape[1] * ${n}Shape[2];
|
|
int stride1 = ${n}Shape[2];
|
|
int index = row * ${s} + col * ${i} + depth + ${m};
|
|
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${s} + col * ${i} + depth + ${m};
|
|
vec2 uv = uvFromFlat(${h}, ${p}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function zee(e,t){let r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1),a=Xr();if(t)return`
|
|
vec4 ${n}(int b2, int b, int row, int col) {
|
|
int valuesPerRow = int(ceil(float(${r}Shape[3]) / 2.0));
|
|
int texelsInBatch = valuesPerRow * int(ceil(float(${r}Shape[2]) / 2.0));
|
|
int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
|
|
texelsInBatch *= ${r}Shape[1];
|
|
index = b2 * texelsInBatch + index;
|
|
ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}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 ${a.texture2D}(${r}, uv);
|
|
}
|
|
`;let s=e.shapeInfo.logicalShape,i=s.length,o=e.shapeInfo.texShape,l=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],u=l[0],d=l[1],h=Math.ceil(s[i-1]/2),p=h*Math.ceil(s[i-2]/2),c="int b, int row, int col",m=`b * ${p} + (row / 2) * ${h} + (col / 2)`;for(let f=2;f<i-1;f++)c=`int b${f}, `+c,p*=s[i-f-1],m=`b${f} * ${p} + `+m;return`
|
|
vec4 ${n}(${c}) {
|
|
int index = ${m};
|
|
int texR = index / ${d};
|
|
int texC = index - texR * ${d};
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${d}, ${u});
|
|
return ${a.texture2D}(${r}, uv);
|
|
}
|
|
`}function Dee(e,t){let r=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),s=r[3],i=r[2]*s,o=r[1]*i,{newShape:l,keptDims:u}=v.squeezeShape(r);if(l.length<r.length){let A=Pd(e,l),x=["row","col","depth","depth2"];return`
|
|
${Fd(A,t)}
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
return ${a}(${Od(x,u)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
int index = round(dot(vec4(row, col, depth, depth2),
|
|
vec4(${o}, ${i}, ${s}, 1)));
|
|
${_d(e)}
|
|
}
|
|
`;let d=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,p=h[0],c=h[1],m=`int stride2 = ${n}Shape[3];`,f=`int stride1 = ${n}Shape[2] * stride2;`,g=`int stride0 = ${n}Shape[1] * stride1;`;if(c===o&&d==null)return t?`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
${m}
|
|
${f}
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(stride1, stride2, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${n}TexShape[1], ${n}TexShape[0]);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(${i}, ${s}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${c}.0, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(c===s&&d==null)return t?`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(${n}Shape[1] * ${n}Shape[2], ${n}Shape[2], 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${n}TexShape[1], ${n}TexShape[0]);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(${r[1]*r[2]}, ${r[2]}, 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${c}.0, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let y=Ll(n);return t?`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
${m}
|
|
${f}
|
|
${g}
|
|
int index = row * stride0 + col * stride1 +
|
|
depth * stride2 + depth2;
|
|
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${y});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${o} + col * ${i} +
|
|
depth * ${s} + depth2;
|
|
vec2 uv = uvFromFlat(${p}, ${c}, index + ${y});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function Lee(e){let t=e.shapeInfo.logicalShape,r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1),a=t[4],s=t[3]*a,i=t[2]*s,o=t[1]*i,{newShape:l,keptDims:u}=v.squeezeShape(t);if(l.length<t.length){let f=Pd(e,l),g=["row","col","depth","depth2","depth3"];return`
|
|
${Fd(f)}
|
|
float ${n}(int row, int col, int depth, int depth2, int depth3) {
|
|
return ${n}(${Od(g,u)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${n}(int row, int col, int depth, int depth2, int depth3) {
|
|
float index = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${o}, ${i}, ${s}, ${a})) +
|
|
depth3;
|
|
${_d(e)}
|
|
}
|
|
`;let d=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,p=h[0],c=h[1];if(c===o&&d==null)return`
|
|
float ${n}(int row, int col, int depth, int depth2, int depth3) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${i}, ${s}, ${a}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${c}.0, ${p}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;if(c===a&&d==null)return`
|
|
float ${n}(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(${c}.0, ${p}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;let m=Ll(r);return`
|
|
float ${n}(int row, int col, int depth, int depth2, int depth3) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${o} + col * ${i} + depth * ${s} +
|
|
depth2 * ${a} + depth3 + ${m};
|
|
vec2 uv = uvFromFlat(${p}, ${c}, index);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function Bee(e){let t=e.shapeInfo.logicalShape,r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1),{newShape:a,keptDims:s}=v.squeezeShape(t);if(a.length<t.length){let g=Pd(e,a),y=["row","col","depth","depth2","depth3","depth4"];return`
|
|
${Fd(g)}
|
|
float ${n}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return ${n}(${Od(y,s)});
|
|
}
|
|
`}let i=t[5],o=t[4]*i,l=t[3]*o,u=t[2]*l,d=t[1]*u;if(e.shapeInfo.isUniform)return`
|
|
float ${n}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int index = round(dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${d}, ${u}, ${l}, ${o})) +
|
|
dot(
|
|
vec2(depth3, depth4),
|
|
vec2(${i}, 1)));
|
|
${_d(e)}
|
|
}
|
|
`;let h=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,c=p[0],m=p[1];if(m===d&&h==null)return`
|
|
float ${n}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${u}, ${l}, ${o}, ${i})) +
|
|
float(depth4);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${m}.0, ${c}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;if(m===i&&h==null)return`
|
|
float ${n}(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(${m}.0, ${c}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;let f=Ll(r);return`
|
|
float ${n}(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 * ${d} + col * ${u} + depth * ${l} +
|
|
depth2 * ${o} + depth3 * ${i} + depth4 + ${f};
|
|
vec2 uv = uvFromFlat(${c}, ${m}, index);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function _d(e){let t=e.name,r=v.sizeFromShape(e.shapeInfo.logicalShape);return r<2?`return ${t};`:`
|
|
for (int i = 0; i < ${r}; i++) {
|
|
if (i == index) {
|
|
return ${t}[i];
|
|
}
|
|
}
|
|
`}function Wee(e,t){let r=e.name,n=r.charAt(0).toUpperCase()+r.slice(1),a="get"+n+"AtOutCoords",s=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o=K9(e.shapeInfo.logicalShape,t.logicalShape),l=yt(i),u=i-s,d,h=["x","y","z","w","u","v"];s===0?d="":i<2&&o.length>=1?d="coords = 0;":d=o.map(g=>`coords.${h[g+u]} = 0;`).join(`
|
|
`);let p="";i<2&&s>0?p="coords":p=e.shapeInfo.logicalShape.map((g,y)=>`coords.${h[y+u]}`).join(", ");let c="return outputValue;",m=v.sizeFromShape(e.shapeInfo.logicalShape)===1,f=v.sizeFromShape(t.logicalShape)===1;if(s===1&&!m&&!f)c=`
|
|
return vec4(outputValue.xy, outputValue.xy);
|
|
`;else if(m&&!f)i===1?c=`
|
|
return vec4(outputValue.x, outputValue.x, 0., 0.);
|
|
`:c=`
|
|
return vec4(outputValue.x);
|
|
`;else if(o.length){let g=s-2,y=s-1;o.indexOf(g)>-1&&o.indexOf(y)>-1?c="return vec4(outputValue.x);":o.indexOf(g)>-1?c="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(y)>-1&&(c="return vec4(outputValue.xx, outputValue.zz);")}return`
|
|
vec4 ${a}() {
|
|
${l} coords = getOutputCoords();
|
|
${d}
|
|
vec4 outputValue = get${n}(${p});
|
|
${c}
|
|
}
|
|
`}function Vee(e,t){let r=e.name,n=r.charAt(0).toUpperCase()+r.slice(1),a="get"+n+"AtOutCoords",s=t.texShape,i=e.shapeInfo.texShape,o=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&o===l&&e.shapeInfo.flatOffset==null&&v.arraysEqual(i,s))return`
|
|
float ${a}() {
|
|
return sampleTexture(${r}, resultUV);
|
|
}
|
|
`;let u=yt(l),d=K9(e.shapeInfo.logicalShape,t.logicalShape),h=l-o,p,c=["x","y","z","w","u","v"];o===0?p="":l<2&&d.length>=1?p="coords = 0;":p=d.map(f=>`coords.${c[f+h]} = 0;`).join(`
|
|
`);let m="";return l<2&&o>0?m="coords":m=e.shapeInfo.logicalShape.map((f,g)=>`coords.${c[g+h]}`).join(", "),`
|
|
float ${a}() {
|
|
${u} coords = getOutputCoords();
|
|
${p}
|
|
return get${n}(${m});
|
|
}
|
|
`}function yt(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 TA(e,t,r){let{newShape:n,keptDims:a}=v.squeezeShape(t),s=t.length,i=e&&s===3&&t[0]===1,o=i?t.slice(1):n,l=!e&&s>1&&!v.arraysEqual(t,r)&&n.length<s||i;return{useSqueezeShape:l,uniformShape:l?o:t,keptDims:a}}function Pd(e,t){let r=JSON.parse(JSON.stringify(e));return r.shapeInfo.logicalShape=t,r}function Od(e,t){return t.map(r=>e[r]).join(", ")}function Uee(e,t,r,n){let a=r.map((d,h)=>{let p={logicalShape:d.shape,texShape:d.isUniform?null:d.texData.texShape,isUniform:d.isUniform,isPacked:d.isUniform?!1:d.texData.isPacked,flatOffset:null};return d.texData!=null&&d.texData.slice!=null&&d.texData.slice.flatOffset>0&&(p.flatOffset=d.texData.slice.flatOffset),{name:t.variableNames[h],shapeInfo:p}}),s=a.map(d=>d.shapeInfo),i={logicalShape:n.shape,texShape:n.texData.texShape,isUniform:!1,isPacked:n.texData.isPacked,flatOffset:null},o=oee(a,i,t),l=T9(e.gl,o),u=e.createProgram(l);return Z().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:s,outShapeInfo:i,uniformLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,inShapesLocations:null,inTexShapesLocations:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:{program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:s,outShapeInfo:i,...J9(e,t,u)}}function J9(e,t,r){let n={},a={},s={},i=[],o,l,u,d=null,h=null;h=e.getUniformLocation(r,"NAN",!1),Z().getNumber("WEBGL_VERSION")===1&&(d=e.getUniformLocation(r,"INFINITY",!1));let p=!1;for(let c=0;c<t.variableNames.length;c++){let m=t.variableNames[c];n[m]=e.getUniformLocation(r,m,p),n[`offset${m}`]=e.getUniformLocation(r,`offset${m}`,p),t.enableShapeUniforms&&(a[`${m}Shape`]=e.getUniformLocation(r,`${m}Shape`,p),s[`${m}TexShape`]=e.getUniformLocation(r,`${m}TexShape`,p))}return t.enableShapeUniforms&&(o=e.getUniformLocation(r,"outShape",p),u=e.getUniformLocation(r,"outShapeStrides",p),l=e.getUniformLocation(r,"outTexShape",p)),t.customUniforms&&t.customUniforms.forEach((c,m)=>{i[m]=e.getUniformLocation(r,c.name,p)}),{uniformLocations:n,customUniformLocations:i,infLoc:d,nanLoc:h,inShapesLocations:a,inTexShapesLocations:s,outShapeLocation:o,outShapeStridesLocation:u,outTexShapeLocation:l}}function q4(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((r,n)=>{let a=r.logicalShape,s=t[n],i=s.shape;if(!v.arraysEqual(a,i))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${a} and ${i} must match`);if(r.isUniform&&s.isUniform)return;let o=r.texShape,l=s.isUniform?null:s.texData.texShape;if(!v.arraysEqual(o,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${o} and ${l} must match`)})}function Gee(e,t,r,n,a){t.program.enableShapeUniforms||(q4(t.inShapeInfos,r),q4([t.outShapeInfo],[n]));let s=n.texData.texture,i=n.texData.texShape;n.texData.isPacked?e.setOutputPackedMatrixTexture(s.texture,i[0],i[1]):e.setOutputMatrixTexture(s.texture,i[0],i[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),r.forEach((l,u)=>{let d=t.program.variableNames[u],h=t.uniformLocations[d],p=t.uniformLocations[`offset${d}`],c=t.inShapesLocations[`${d}Shape`],m=t.inTexShapesLocations[`${d}TexShape`];if(c){let{uniformShape:f}=TA(t.program.packedInputs,l.shape,l.texData.texShape);switch(f.length){case 1:e.gl.uniform1iv(c,new Int32Array(f));break;case 2:e.gl.uniform2iv(c,new Int32Array(f));break;case 3:e.gl.uniform3iv(c,new Int32Array(f));break;case 4:e.gl.uniform4iv(c,new Int32Array(f));break;default:break}}if(m&&e.gl.uniform2i(m,l.texData.texShape[0],l.texData.texShape[1]),h!=null){if(l.isUniform){if(v.sizeFromShape(l.shape)<2)e.gl.uniform1f(h,l.uniformValues[0]);else{let f=l.uniformValues;f instanceof Float32Array||(f=new Float32Array(f)),e.gl.uniform1fv(h,f)}return}l.texData.slice!=null&&p!=null&&e.gl.uniform1i(p,l.texData.slice.flatOffset),e.setInputMatrixTexture(l.texData.texture.texture,h,u)}});let o=t.outShapeLocation;if(o)switch(n.shape.length){case 1:e.gl.uniform1iv(o,new Int32Array(n.shape));break;case 2:e.gl.uniform2iv(o,new Int32Array(n.shape));break;case 3:e.gl.uniform3iv(o,new Int32Array(n.shape));break;case 4:e.gl.uniform4iv(o,new Int32Array(n.shape));break;default:break}if(t.outShapeStridesLocation){let l=v.computeStrides(n.shape);switch(n.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,n.texData.texShape[0],n.texData.texShape[1]),t.program.customUniforms&&a&&t.program.customUniforms.forEach((l,u)=>{let d=t.customUniformLocations[u],h=a[u];if(l.type==="float")e.gl.uniform1fv(d,h);else if(l.type==="vec2")e.gl.uniform2fv(d,h);else if(l.type==="vec3")e.gl.uniform3fv(d,h);else if(l.type==="vec4")e.gl.uniform4fv(d,h);else if(l.type==="int")e.gl.uniform1iv(d,h);else if(l.type==="ivec2")e.gl.uniform2iv(d,h);else if(l.type==="ivec3")e.gl.uniform3iv(d,h);else if(l.type==="ivec4")e.gl.uniform4iv(d,h);else throw Error(`uniform type ${l.type} is not supported yet.`)}),e.executeProgram()}function jee(e,t,r){let n="";t.concat(r).forEach(i=>{let o=i.texData!=null&&i.texData.slice!=null&&i.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!i.isUniform){let l=i.texData.texShape,{useSqueezeShape:u,uniformShape:d,keptDims:h}=TA(e.packedInputs,i.shape,l),p="",c="",m="";if(d.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(d.length===2&&!e.packedInputs)c=`${d[0]>1}_${d[1]>1}`;else if(d.length>2&&!e.packedInputs){let w=v.computeStrides(d);m=`${w[0]===l[1]}_${w[w.length-1]===l[1]}`}let f=i.shape.length,g=d.length===2&&v.arraysEqual(i.shape,l),y=v.sizeFromShape(i.shape)===1,A=C.getBroadcastDims(i.shape,r.shape),x=!e.packedInputs&&f===r.shape.length&&v.arraysEqual(l,r.texData.texShape),b=e.packedInputs||d.length>2?"":`${l[0]>1}_${l[1]>1}`;n+=`${f}_${x}_${u?h:""}_${d.length}_${y}_${A}_${g}_${p}_${c}_${m}_${b}_${o}`}else{let l=i.isUniform?"uniform":i.texData.texShape;n+=`${i.shape}_${l}_${o}`}});let a=e.userCode,s=e.constructor.name;return s+="_"+n+"_"+a+`${Z().getNumber("WEBGL_VERSION")}`,s}function un(e){return Z().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}var Hee=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Xr();this.outputShape=e,this.enableShapeUniforms=un(this.outputShape.length),this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms?_m(["r","c","d"],e):Dl(["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;
|
|
}
|
|
`}},qee=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Xr();this.outputShape=e,this.enableShapeUniforms=un(this.outputShape.length),this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms?_m(["r","c","d"],e):Dl(["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;
|
|
}
|
|
`}},Xee=class{constructor(e){this.variableNames=["A"],this.outTexUsage=3;let t=Xr();this.outputShape=e,this.userCode=`
|
|
${X9}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},Kee=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=3;let t=Xr();this.outputShape=e,this.userCode=`
|
|
${X9}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},Zee=class{constructor(e,t=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let r=Xr();this.outputShape=e,this.enableShapeUniforms=un(this.outputShape.length);let n="result";t&&(n="floor(result * 255. + 0.5)"),this.userCode=`
|
|
${this.enableShapeUniforms?CA():SA(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 = ${r.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];
|
|
}
|
|
|
|
${r.output} = vec4(${n}, 0., 0., 0.);
|
|
}
|
|
`}},Yee=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let r=Xr();this.outputShape=e,this.enableShapeUniforms=un(this.outputShape.length);let n="",a="result";t&&(a="floor(result * 255. + 0.5)");for(let s=0;s<=1;s++)for(let i=0;i<=1;i++){let o=s*2+i;n+=`
|
|
localCoords = coords;
|
|
if(localCoords[2] + ${i} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {
|
|
localCoords[2] += ${i};
|
|
if (localCoords[1] + ${s} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {
|
|
localCoords[1] += ${s};
|
|
|
|
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 = ${r.texture2D}(A, uv);
|
|
|
|
if (offset == 0) {
|
|
result[${o}] = values[0];
|
|
} else if (offset == 1) {
|
|
result[${o}] = values[1];
|
|
} else if (offset == 2) {
|
|
result[${o}] = values[2];
|
|
} else {
|
|
result[${o}] = values[3];
|
|
}
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
${this.enableShapeUniforms?CA():SA(e)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
int flatIndex, r, c, offset;
|
|
ivec3 localCoords;
|
|
vec2 uv;
|
|
vec4 values;
|
|
|
|
${n}
|
|
|
|
${r.output} = ${a};
|
|
}
|
|
`}},Q9={};Be(Q9,{bindVertexProgramAttributeStreams:()=>lI,createBufferFromOutputTexture:()=>pI,createFloat16MatrixTexture:()=>aI,createFloat16PackedMatrixTexture:()=>oI,createFloat32MatrixTexture:()=>nI,createIndexBuffer:()=>rI,createPackedMatrixTexture:()=>iI,createUnsignedBytesMatrixTexture:()=>sI,createVertexBuffer:()=>tI,createVertexShader:()=>eI,downloadByteEncodedFloatMatrixFromOutputTexture:()=>cI,downloadFloat32MatrixFromBuffer:()=>hI,downloadMatrixFromPackedOutputTexture:()=>mI,downloadPackedMatrixFromBuffer:()=>fI,getInternalFormatForFloat16MatrixTexture:()=>EA,getInternalFormatForFloat16PackedMatrixTexture:()=>MA,getInternalFormatForFloat32MatrixTexture:()=>NA,getInternalFormatForPackedMatrixTexture:()=>$A,getInternalFormatForUnsignedBytesMatrixTexture:()=>RA,uploadDenseMatrixToTexture:()=>uI,uploadPixelDataToTexture:()=>dI});function eI(e){let t=Xr(),r=`${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 C9(e,r)}function tI(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 R9(e,t)}function rI(e){let t=new Uint16Array([0,1,2,2,1,3]);return $9(e,t)}function Hh(e,t,r,n,a,s){F9(t,r);let i=M9(e),o=e.TEXTURE_2D;return we(e,()=>e.bindTexture(o,i)),we(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),we(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),we(e,()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST)),we(e,()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST)),Z().getNumber("WEBGL_VERSION")===1?we(e,()=>e.texImage2D(o,0,n,t,r,0,a,s,null)):we(e,()=>e.texStorage2D(o,1,n,t,r)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null)),{texture:i,texShape:[r,t]}}function NA(e){return e.internalFormatFloat}function nI(e,t,r,n){let[a,s]=jh(t,r);return Hh(e,a,s,NA(n),n.textureFormatFloat,e.FLOAT)}function EA(e){return e.internalFormatHalfFloat}function aI(e,t,r,n){let[a,s]=jh(t,r);return Hh(e,a,s,EA(n),n.textureFormatFloat,n.textureTypeHalfFloat)}function RA(e){return e.downloadTextureFormat}function sI(e,t,r,n){let[a,s]=jh(t,r);return Hh(e,a,s,RA(n),e.RGBA,e.UNSIGNED_BYTE)}function $A(e){return e.internalFormatPackedFloat}function iI(e,t,r,n){let[a,s]=$d(t,r);return Hh(e,a,s,$A(n),e.RGBA,e.FLOAT)}function MA(e){return e.internalFormatPackedHalfFloat}function oI(e,t,r,n){let[a,s]=$d(t,r);return Hh(e,a,s,MA(n),e.RGBA,n.textureTypeHalfFloat)}function lI(e,t,r){return we(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),cy(e,t,"clipSpacePos",r,3,20,0)&&cy(e,t,"uv",r,2,20,12)}function uI(e,t,r,n,a,s){we(e,()=>e.bindTexture(e.TEXTURE_2D,t));let i,o,l;a instanceof Uint8Array?(i=new Uint8Array(r*n*4),o=e.UNSIGNED_BYTE,l=e.RGBA):(i=new Float32Array(r*n*4),o=e.FLOAT,l=s.internalFormatPackedFloat),i.set(a),Z().getNumber("WEBGL_VERSION")===2?we(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RGBA,o,i)):we(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,r,n,0,e.RGBA,o,i)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function dI(e,t,r){we(e,()=>e.bindTexture(e.TEXTURE_2D,t)),r.data instanceof Uint8Array?Z().getNumber("WEBGL_VERSION")===2?we(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,r.width,r.height,e.RGBA,e.UNSIGNED_BYTE,r.data)):we(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,r.width,r.height,0,e.RGBA,e.UNSIGNED_BYTE,r.data)):Z().getNumber("WEBGL_VERSION")===2?we(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,r)):we(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function pI(e,t,r,n){let a=e.createBuffer();we(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,a));let s=4*4*t*r;return we(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ)),we(e,()=>e.readPixels(0,0,r,t,e.RGBA,e.FLOAT,0)),we(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),a}function hI(e,t,r){let n=e,a=new Float32Array(r);return n.bindBuffer(n.PIXEL_PACK_BUFFER,t),n.getBufferSubData(n.PIXEL_PACK_BUFFER,0,a),n.bindBuffer(n.PIXEL_PACK_BUFFER,null),a}function cI(e,t,r,n){let[a,s]=jh(t,r),i=4,o=new Uint8Array(qQ(t*r,i));return we(e,()=>e.readPixels(0,0,a,s,n.downloadTextureFormat,e.UNSIGNED_BYTE,o)),new Float32Array(o.buffer)}function fI(e,t,r,n,a,s,i,o){let l=e,u=new Float32Array(XQ(s,i));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}function mI(e,t,r){let n=new Float32Array(t*r*4);return we(e,()=>e.readPixels(0,0,r,t,e.RGBA,e.FLOAT,n)),n}var Tu=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,Fm(t,e)):this.gl=xa(t);let r="WEBGL_color_buffer_float",n="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),Z().getNumber("WEBGL_VERSION")===1){let a="OES_texture_float",s="OES_texture_half_float";if(this.textureFloatExtension=Op(this.gl,a),En(this.gl,s))this.textureHalfFloatExtension=Op(this.gl,s);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(r),En(this.gl,n))this.colorBufferHalfFloatExtension=Op(this.gl,n);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(r="EXT_color_buffer_float",En(this.gl,r))this.colorBufferFloatExtension=this.gl.getExtension(r);else if(En(this.gl,n))this.colorBufferHalfFloatExtension=this.gl.getExtension(n);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=tI(this.gl),this.indexBuffer=rI(this.gl),this.framebuffer=_9(this.gl),this.textureConfig=kA(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;we(e,()=>e.finish()),we(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),we(e,()=>e.deleteFramebuffer(this.framebuffer)),we(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),we(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),we(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),nI(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),aI(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),sI(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),dI(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,r,n){this.throwIfDisposed(),uI(this.gl,e,t,r,n,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),oI(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),iI(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(fy(this.gl,this.framebuffer),this.outputTexture=null),we(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,r){return this.downloadMatrixDriver(e,()=>cI(this.gl,t,r,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,r,n,a,s){return fI(this.gl,e,t,r,n,a,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return hI(this.gl,e,t)}createBufferFromTexture(e,t,r){this.bindTextureToFrameBuffer(e);let n=pI(this.gl,t,r,this.textureConfig);return this.unbindTextureToFrameBuffer(),n}createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,r;if(Z().getBool("WEBGL_FENCE_API_ENABLED")){let n=e,a=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),r=()=>{let s=n.clientWaitSync(a,0,0);return s===n.ALREADY_SIGNALED||s===n.CONDITION_SATISFIED},t=a}else Z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),r=()=>this.isQueryAvailable(t,Z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):r=()=>!0;return{query:t,isFencePassed:r}}downloadMatrixFromPackedTexture(e,t,r){return this.downloadMatrixDriver(e,()=>mI(this.gl,t,r))}createProgram(e){this.throwIfDisposed();let t=this.gl;this.vertexShader==null&&(this.vertexShader=eI(t));let r=N9(t);return we(t,()=>t.attachShader(r,this.vertexShader)),we(t,()=>t.attachShader(r,e)),E9(t,r),this.debug&&g0(t,r),this.vertexAttrsAreBound||(this.setProgram(r),this.vertexAttrsAreBound=lI(t,this.program,this.vertexBuffer)),r}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&we(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&g0(this.gl,this.program),we(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,r=!0){return this.throwIfDisposed(),r?O9(this.gl,e,t):z9(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),we(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,r){this.throwIfDisposed(),this.throwIfNoProgram(),D9(this.gl,e,t,r)}setOutputMatrixTexture(e,t,r){this.setOutputMatrixTextureDriver(e,r,t)}setOutputPackedMatrixTexture(e,t,r){this.throwIfDisposed();let[n,a]=$d(t,r);this.setOutputMatrixTextureDriver(e,n,a)}setOutputMatrixWriteRegion(e,t,r,n){this.setOutputMatrixWriteRegionDriver(r,e,n,t)}setOutputPackedMatrixWriteRegion(e,t,r,n){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&g0(this.gl,this.program),zp(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;this.debug&&this.debugValidate(),we(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),we(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Op(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 r=this.gl,n=this.getQueryTimerExtensionWebGL2(),a=r.createQuery();return r.beginQuery(n.TIME_ELAPSED_EXT,a),a}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,r=this.getQueryTimerExtensionWebGL2();t.endQuery(r.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 r=this.gl;return r.getQueryParameter(e,r.QUERY_RESULT)/1e6}else{let r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(e,r.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){let r=this.gl,n=this.getQueryTimerExtensionWebGL2(),a=r.getQueryParameter(e,r.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),a&&!this.disjoint}else{let r=this.getQueryTimerExtensionWebGL1(),n=r.getQueryObjectEXT(e,r.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=Jee(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){let{resolveFn:r}=this.itemsToPoll[t];r()}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(),y0(this.gl,e,this.framebuffer),this.debug&&zp(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(y0(this.gl,this.outputTexture,this.framebuffer),this.debug&&zp(this.gl)):fy(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);let r=t();return this.unbindTextureToFrameBuffer(),r}setOutputMatrixTextureDriver(e,t,r){this.throwIfDisposed();let n=this.gl;y0(n,e,this.framebuffer),this.debug&&zp(n),this.outputTexture=e,we(n,()=>n.viewport(0,0,t,r)),we(n,()=>n.scissor(0,0,t,r))}setOutputMatrixWriteRegionDriver(e,t,r,n){this.throwIfDisposed(),we(this.gl,()=>this.gl.scissor(e,t,r,n))}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 Jee(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}var{addImpl:Qee,bincountImpl:gI,bincountReduceImpl:ete,ceilImpl:tte,concatImpl:rte,equalImpl:nte,expImpl:ate,expm1Impl:ste,floorImpl:ite,gatherNdImpl:ote,gatherV2Impl:lte,greaterImpl:ute,greaterEqualImpl:dte,lessImpl:pte,lessEqualImpl:hte,linSpaceImpl:cte,logImpl:fte,maxImpl:mte,maximumImpl:gte,minimumImpl:yte,multiplyImpl:Ate,negImpl:xte,notEqualImpl:bte,prodImpl:vte,rangeImpl:wte,rsqrtImpl:kte,scatterImpl:Ite,sigmoidImpl:Ste,simpleAbsImpl:yI,sliceImpl:Cte,sparseFillEmptyRowsImpl:Tte,sparseReshapeImpl:Nte,sparseSegmentReductionImpl:AI,sqrtImpl:Ete,stridedSliceImpl:Rte,stringNGramsImpl:$te,stringSplitImpl:Mte,stringToHashBucketFastImpl:Fte,subImpl:_te,tileImpl:Pte,topKImpl:Ote,transposeImpl:FA,uniqueImpl:zte}=$m;function xI(e,t){return["x","y","z","w","u","v"].slice(0,t).map(r=>`${e}.${r}`)}function Wr(e,t){return t===1?[e]:xI(e,t)}function Dte(e,t){if(e===1)return"rc";let r="";for(let n=0;n<e;n++)r+=t[n],n<e-1&&(r+=",");return r}var Lte=class{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=un(this.outputShape.length),this.rank===0)this.userCode=`
|
|
void main() {
|
|
setOutput(vec4(getA(), 0., 0., 0.));
|
|
}
|
|
`;else{let t=Wr("rc",this.rank),r=yt(this.rank),n=this.getOutOfBoundsCondition(t),a=this.getSetup(t),s=this.getOutput(t);this.userCode=`
|
|
void main() {
|
|
${r} rc = getOutputCoords();
|
|
|
|
if(${n}) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
${a}
|
|
|
|
setOutput(vec4(${s}));
|
|
}
|
|
}
|
|
`}}getSourceCoordsArr(e){let t=[];for(let r=0;r<=1;r++)for(let n=0;n<=1;n++){let a=`${r===0?"r":"rp1"}, ${n===0?"c":"cp1"}`;for(let s=2;s<this.rank;s++)a=`${e[e.length-1-s]},`+a;t.push(a)}return t}getOutOfBoundsCondition(e){if(this.rank===1)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let r=this.rank-2;r<this.rank;r++)t+=`${e[r]} >= ${this.enableShapeUniforms?`outShape[${r}]`:this.outputShape[r]}`,r<this.rank-1&&(t+="||");return t}getSetup(e){if(this.rank===1)return"";let t=e.slice(-2),r=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],n=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`
|
|
int r = ${t[0]};
|
|
int c = ${t[1]};
|
|
int rp1 = r + 1;
|
|
int cp1 = c + 1;
|
|
|
|
bool cEdge = cp1 >= ${r};
|
|
bool rEdge = rp1 >= ${n};
|
|
`}getOutput(e){let t=this.getSourceCoordsArr(e);return this.rank===1?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${t[0]}),
|
|
cEdge ? 0. : getA(${t[1]}),
|
|
rEdge ? 0. : getA(${t[2]}),
|
|
rEdge || cEdge ? 0. : getA(${t[3]})`}},bI=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=un(this.outputShape.length);let r="";for(let n=0;n<4;n++){let a="thisRC = rc;";n%2===1&&(a+="thisRC.z += 1;"),n>1&&(a+="thisRC.y += 1;"),r+=`
|
|
${a}
|
|
${n>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[${n}] =
|
|
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
|
|
${n>0?"}":""}
|
|
`}this.userCode=`
|
|
${Bte(t,this.enableShapeUniforms)}
|
|
${this.enableShapeUniforms?CA():SA(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]};
|
|
|
|
${r}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function Bte(e,t){return`
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${t?iee(["r","c","d"],"inputShape"):Dl(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}var Wte=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,r){let n=K4(t,r),a=Z4(e,n,r);a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]);let s=X4(e,n,this.gpgpu.gl,this.gpgpu.textureConfig,r);if(this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();let o=this.freeTextures[a].shift();return this.usedTextures[a].push(o),o}let i;return n===3?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):n===4?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):n===1?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):n===0?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):n===2&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[a].push(i),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),i}releaseTexture(e,t,r,n){if(this.freeTextures==null)return;let a=K4(r,n),s=Z4(t,a,n);s in this.freeTextures||(this.freeTextures[s]=[]);let i=X4(t,a,this.gpgpu.gl,this.gpgpu.textureConfig,n),o=Z().get("WEBGL_DELETE_TEXTURE_THRESHOLD");o!==-1&&this._numBytesAllocated>o?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=i):(this.freeTextures[s].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;let l=this.usedTextures[s],u=l.indexOf(e);if(u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(u,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.texture)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function Vte(e,t){let r=e;if(t===r.R32F)return 4;if(t===r.R16F)return 2;if(t===r.RGBA32F||t===e.RGBA)return 16;if(t===r.RGBA16F)return 8;if(t===r.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}function X4(e,t,r,n,a){let s=Ute(t,n),i;if(a){let[l,u]=$d(e[0],e[1]);i=l*u}else{let[l,u]=jh(e[0],e[1]);i=l*u}let o=Vte(r,s);return i*o}function Ute(e,t){switch(e){case 3:return $A(t);case 4:return MA(t);case 1:return NA(t);case 0:return EA(t);case 2:return RA(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function Gte(e){return Z().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?3:1:e?4:0}function K4(e,t){if(e===1)return 3;if(e===0||e==null)return Gte(t);if(e===3||e===2)return 2;throw new Error(`Unknown logical texture type ${e}`)}function Z4(e,t,r){return`${e[0]}_${e[1]}_${t}_${r}`}var Ka=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=un(this.outputShape.length),this.userCode=`
|
|
float unaryOperation(float x) {
|
|
${t}
|
|
}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
float y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`}},Yn="if (isnan(x)) return x;",jte="return x;",Y4="return abs(x);",Hte="return (x >= 0.0) ? x : (exp(x) - 1.0);",qte=Yn+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,Xte=Yn+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,fu="return x;",Kte="return 1.0 / (1.0 + exp(-1.0 * x));",Zte="return x;",Yte=`
|
|
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;
|
|
`,Jte=`
|
|
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;
|
|
`,Qte=`
|
|
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;
|
|
`,ere="return 1.0 / (1.0 + exp(-1.0 * x));",Co=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=un(this.outputShape.length),this.userCode=`
|
|
vec4 unaryOperation(vec4 x) {
|
|
${t}
|
|
}
|
|
|
|
void main() {
|
|
vec4 x = getAAtOutCoords();
|
|
vec4 y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`}},tre=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=un(this.outputShape.length);let t=e.length,r=Wr("rc",t),n=yt(t),a=Dte(t,r),s=r.slice(-2),i=t<=1?"rc":`vec2(${s.join(",")})`;this.userCode=`
|
|
void main() {
|
|
${n} rc = getOutputCoords();
|
|
vec4 packedInput = getA(${a});
|
|
|
|
setOutput(getChannel(packedInput, ${i}));
|
|
}
|
|
`}},rre=Kn.whereImpl,nre=1e-7,are=1e-4,Cg={};function sre(e){return e in Cg||(Cg[e]={}),Cg[e]}var ire=Z().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),ore=600;function lre(){return Z().global.screen==null?1024:Z().global.screen.height*Z().global.screen.width*window.devicePixelRatio*ore/1024/1024}var vI=class extends Gu{constructor(e){if(super(),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");let t;if(e!=null){if(e instanceof Tu)t=e;else{let r=xa(Z().getNumber("WEBGL_VERSION"),e);t=new Tu(r)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{let r=xa(Z().getNumber("WEBGL_VERSION"));t=new Tu(r),this.binaryCache=sre(Z().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new Wte(this.gpgpu),this.numMBBeforeWarning=lre(),this.texData=new nh(this,Xt())}nextDataId(){return vI.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}write(e,t,r){if((Z().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||Z().getBool("DEBUG"))&&this.checkNumericalProblems(e),r==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let n={id:this.nextDataId()};return this.texData.set(n,{shape:t,dtype:r,values:e,usage:1,refCount:1}),n}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,r,n,a){if(Z().getBool("DEBUG")&&this.checkNumericalProblems(t),n==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:r,dtype:n,values:t,usage:1,refCount:a})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){let t=this.texData.get(e),{values:r,dtype:n,complexTensorInfos:a,slice:s,shape:i,isPacked:o}=t;if(s!=null){let h;o?h=new Co(i,fu):h=new Ka(i,fu);let p=this.runWebGLProgram(h,[{dataId:e,shape:i,dtype:n}],n),c=this.readSync(p.dataId);return this.disposeIntermediateTensorInfo(p),c}if(r!=null)return this.convertAndCacheOnCPU(e);if(n==="string")return r;let l=this.activeTimers!=null,u;l&&(u=v.now());let d;if(n==="complex64"){let h=this.readSync(a.real.dataId),p=this.readSync(a.imag.dataId);d=C.mergeRealAndImagArrays(h,p)}else d=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=v.now()-u),this.convertAndCacheOnCPU(e,d)}async read(e){if(this.pendingRead.has(e)){let c=this.pendingRead.get(e);return new Promise(m=>c.push(m))}let t=this.texData.get(e),{values:r,shape:n,slice:a,dtype:s,complexTensorInfos:i,isPacked:o}=t;if(a!=null){let c;o?c=new Co(n,fu):c=new Ka(n,fu);let m=this.runWebGLProgram(c,[{dataId:e,shape:n,dtype:s}],s),f=this.read(m.dataId);return this.disposeIntermediateTensorInfo(m),f}if(r!=null)return this.convertAndCacheOnCPU(e);if(Z().getBool("DEBUG")&&!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,u;if(s!=="complex64"&&Z().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);let c=this.texData.get(u.dataId);l=this.gpgpu.createBufferFromTexture(c.texture.texture,...u0(n))}this.pendingRead.set(e,[]),s!=="complex64"&&await this.gpgpu.createAndWaitForFence();let d;if(s==="complex64"){let c=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]),m=c[0],f=c[1];d=C.mergeRealAndImagArrays(m,f)}else if(l==null)d=this.getValuesFromTexture(e);else{let c=v.sizeFromShape(n);d=this.gpgpu.downloadFloat32MatrixFromBuffer(l,c)}if(u!=null&&this.disposeIntermediateTensorInfo(u),l!=null){let c=this.gpgpu.gl;we(c,()=>c.deleteBuffer(l))}let h=this.convertAndCacheOnCPU(e,d),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach(c=>c(h)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&Xt().removeDataId(e,this),this.pendingDeletes--),h}readToGPU(e,t={}){let r=this.texData.get(e),{values:n,shape:a,slice:s,dtype:i,isPacked:o,texture:l}=r;if(i==="complex64")throw new Error("Does not support reading texture for complex64 dtype.");if(s!=null){let p;o?p=new Co(a,fu):p=new Ka(a,fu);let c=this.runWebGLProgram(p,[{dataId:e,shape:a,dtype:i}],i),m=this.readToGPU(c,t);return this.disposeIntermediateTensorInfo(c),m}if(l==null)throw n!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");let u=this.decode(e,t.customTexShape),d=Xt().makeTensorFromTensorInfo(u),h=this.texData.get(u.dataId);return{tensorRef:d,...h.texture}}bufferSync(e){let t=this.readSync(e.dataId);if(e.dtype==="string")try{let r=t.map(n=>v.decodeString(n));return De(e.shape,e.dtype,r)}catch(r){throw new Error("Failed to decode encoded string bytes into utf-8")}return De(e.shape,e.dtype,t)}checkNumericalProblems(e){if(e!=null)for(let t=0;t<e.length;t++){let r=e[t];if(!I9(r))throw Z().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${r} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${r} cannot be represented on this device.`)}}getValuesFromTexture(e){let{shape:t,dtype:r,isPacked:n}=this.texData.get(e),a=v.sizeFromShape(t);if(Z().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let h=this.decode(e),p=this.texData.get(h.dataId),c=this.gpgpu.downloadMatrixFromPackedTexture(p.texture.texture,...u0(t)).subarray(0,a);return this.disposeIntermediateTensorInfo(h),c}let s=Z().getBool("WEBGL_PACK")&&n===!0,i=s?A0(t):t,o=s?new Kee(i):new Xee(i),l=this.runWebGLProgram(o,[{shape:i,dtype:r,dataId:e}],"float32"),u=this.texData.get(l.dataId),d=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(u.texture.texture,u.texShape[0],u.texShape[1]).subarray(0,a);return this.disposeIntermediateTensorInfo(l),d}timerAvailable(){return Z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(e){let t=this.activeTimers,r=[],n=!1;this.programTimersStack==null?(this.programTimersStack=r,n=!0):this.activeTimers.push(r),this.activeTimers=r,e();let a=v.flatten(this.activeTimers.map(o=>o.query)).filter(o=>o!=null),s=v.flatten(this.activeTimers.map(o=>o.name)).filter(o=>o!=null);this.activeTimers=t,n&&(this.programTimersStack=null);let i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(Z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let o=await Promise.all(a);i.kernelMs=v.sum(o),i.getExtraProfileInfo=()=>o.map((l,u)=>({name:s[u],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i})()}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:r}=this.texData.get(e);return r!=null&&(this.disposeData(r.real.dataId,t),this.disposeData(r.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){let{texture:t,dtype:r,texShape:n,usage:a,isPacked:s,slice:i}=this.texData.get(e),o=i&&i.origDataId||e,l=this.dataRefCount.get(o);l>1?this.dataRefCount.set(o,l-1):(this.dataRefCount.delete(o),t!=null&&(this.numBytesInGPU-=this.computeBytes(n,r),this.textureManager.releaseTexture(t,n,a,s)));let u=this.texData.get(e);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=ire){return Z().getBool("WEBGL_CPU_FORWARD")&&e.every(r=>this.texData.get(r.dataId).texture==null&&v.sizeFromShape(r.shape)<t)}getGPGPUContext(){return this.gpgpu}where(e){C.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let t=e.dataSync();return rre(e.shape,t)}packedUnaryOp(e,t,r){let n=new Co(e.shape,t),a=this.compileAndRun(n,[e],r);return Xt().makeTensorFromTensorInfo(a)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){let n=yI(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,n)}if(Z().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Y4,e.dtype);let t=new Ka(e.shape,Y4),r=this.compileAndRun(t,[e]);return Xt().makeTensorFromTensorInfo(r)}makeTensorInfo(e,t,r){let n;if(t==="string"&&r!=null&&r.length>0&&v.isString(r[0])){let a=r.map(s=>v.encodeString(s));n=this.write(a,e,t)}else n=this.write(r,e,t);return this.texData.get(n).usage=null,{dataId:n,shape:e,dtype:t}}makeOutput(e,t,r){return Xt().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,r),this)}unpackTensor(e){let t=new tre(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new Lte(e.shape),r=!0;return this.runWebGLProgram(t,[e],e.dtype,null,r)}packedReshape(e,t){let r=[Lo(e.shape),...Bo(e.shape)],n={dtype:e.dtype,shape:r,dataId:e.dataId},a=[Lo(t),...Bo(t)],s=new bI(a,r),i=!0,o=[r],l=this.runWebGLProgram(s,[n],e.dtype,o,i);return{dataId:l.dataId,shape:t,dtype:l.dtype}}decode(e,t){let r=this.texData.get(e),{isPacked:n,shape:a,dtype:s}=r;if(t!=null){let h=v.sizeFromShape(a),p=t[0]*t[1]*4;v.assert(h<=p,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.")}let i=A0(a),o;n?o=new qee(i):o=new Hee(i);let l=!0,u=[t!=null?t:u0(i)],d=this.runWebGLProgram(o,[{shape:i,dtype:s,dataId:e}],s,u,l,t);return{dtype:s,shape:a,dataId:d.dataId}}runWebGLProgram(e,t,r,n,a=!1,s){let i=this.makeTensorInfo(e.outputShape,r),o=this.texData.get(i.dataId);if(e.packedOutput&&(o.isPacked=!0),e.outPackingScheme===0){let g=s!=null?s:u0(e.outputShape);o.texShape=g.map(y=>y*2)}if(e.outTexUsage!=null&&(o.usage=e.outTexUsage),v.sizeFromShape(i.shape)===0)return o.values=v.getTypedArrayFromDType(i.dtype,0),i;let l=[],u=t.map(g=>{if(g.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let y=this.texData.get(g.dataId);if(y.texture==null){if(!e.packedInputs&&v.sizeFromShape(g.shape)<=Z().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:g.shape,texData:null,isUniform:!0,uniformValues:y.values};e.packedInputs&&(y.isPacked=!0,y.shape=g.shape)}if(this.uploadToGPU(g.dataId),!!y.isPacked!=!!e.packedInputs)g=y.isPacked?this.unpackTensor(g):this.packTensor(g),l.push(g),y=this.texData.get(g.dataId);else if(y.isPacked&&!th(y.shape,g.shape)){let A=g,x=g.shape;g.shape=y.shape,g=this.packedReshape(g,x),l.push(g),y=this.texData.get(g.dataId),A.shape=x}return{shape:g.shape,texData:y,isUniform:!1}});this.uploadToGPU(i.dataId);let d={shape:i.shape,texData:o,isUniform:!1},h=jee(e,u,d),p=this.getAndSaveBinary(h,()=>Uee(this.gpgpu,e,u,d)),c=this.activeTimers!=null,m;c&&(m=this.startTimer()),Z().get("ENGINE_COMPILE_ONLY")||Gee(this.gpgpu,p,u,d,n),l.forEach(g=>this.disposeIntermediateTensorInfo(g)),c&&(m=this.endTimer(m),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(m)}));let f=Z().get("WEBGL_FLUSH_THRESHOLD");if(f>0){let g=v.now();g-this.lastGlFlushTime>f&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=g)}if(!Z().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&a===!1){let g=this.unpackTensor(i);return this.disposeIntermediateTensorInfo(i),g}return i}compileAndRun(e,t,r,n,a=!1){return r=r||t[0].dtype,this.runWebGLProgram(e,t,r,n,a)}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(e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]}),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=X(()=>{if(!Z().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=Z().getBool("DEBUG");Z().set("DEBUG",!1);let t=this.abs(Se(1e-8)).dataSync()[0];if(Z().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?nre:are}uploadToGPU(e){let t=this.texData.get(e),{shape:r,dtype:n,values:a,texture:s,usage:i,isPacked:o}=t;if(s!=null)return;let l=this.activeTimers!=null,u;l&&(u=v.now());let d=t.texShape;if(d==null&&(d=W9(r,o),t.texShape=d),a!=null){let h=A0(r),p,c=d[1],m=d[0],f=a instanceof Uint8Array||a instanceof Uint8ClampedArray;(o||!f)&&([c,m]=$d(d[0],d[1])),o?p=new Yee(h,f):p=new Zee(h,f);let g=f?[m,c]:d,y=this.makeTensorInfo(g,n),A=this.texData.get(y.dataId);f?A.usage=2:A.usage=1,A.texShape=g,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(y.dataId),c,m,a);let x=[[m,c]],b=!0,w=this.runWebGLProgram(p,[y],n,x,b),I=this.texData.get(w.dataId);t.texShape=I.texShape,t.isPacked=I.isPacked,t.usage=I.usage,Z().get("ENGINE_COMPILE_ONLY")?this.disposeData(w.dataId):(t.texture=I.texture,t.values=null,this.texData.delete(w.dataId)),this.disposeIntermediateTensorInfo(y),l&&(this.uploadWaitMs+=v.now()-u)}else{let h=this.acquireTexture(d,i,n,o);t.texture=h}}convertAndCacheOnCPU(e,t){let r=this.texData.get(e),{dtype:n}=r;return this.releaseGPUData(e),t!=null&&(r.values=ure(t,n)),r.values}acquireTexture(e,t,r,n){if(this.numBytesInGPU+=this.computeBytes(e,r),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){let a=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${a} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,n)}computeBytes(e,t){return e[0]*e[1]*v.bytesPerElement(t)}checkCompileCompletion(){for(let[,e]of Object.entries(this.binaryCache))this.checkCompletion_(e)}async checkCompileCompletionAsync(){let e=[];if(this.gpgpu.parallelCompilationExtension){for(let[,t]of Object.entries(this.binaryCache))e.push(this.checkCompletionAsync_(t));return Promise.all(e)}else{for(let[,t]of Object.entries(this.binaryCache)){let r=new Promise(n=>{try{this.checkCompletion_(t),n(!0)}catch(a){throw a}});e.push(r)}return Promise.all(e)}}async checkCompletionAsync_(e){return this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(e):(await M3(),this.checkCompletionAsync_(e))}checkCompletion_(e){if(this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS)===!1)throw console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)),this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS)===!1?(IA(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)),new Error("Failed to compile fragment shader.")):new Error("Failed to link vertex and fragment shaders.");return!0}getUniformLocations(){for(let[,e]of Object.entries(this.binaryCache)){let{uniformLocations:t,customUniformLocations:r,infLoc:n,nanLoc:a,inShapesLocations:s,inTexShapesLocations:i,outShapeLocation:o,outShapeStridesLocation:l,outTexShapeLocation:u}=J9(this.gpgpu,e.program,e.webGLProgram);e.uniformLocations=t,e.customUniformLocations=r,e.infLoc=n,e.nanLoc=a,e.inShapesLocations=s,e.inTexShapesLocations=i,e.outShapeLocation=o,e.outShapeStridesLocation=l,e.outTexShapeLocation=u}}},qh=vI;qh.nextDataId=0;function ure(e,t){if(t==="float32"||t==="complex64")return e;if(t==="int32"||t==="bool"){let r=t==="int32"?new Int32Array(e.length):new Uint8Array(e.length);for(let n=0;n<r.length;++n)r[n]=Math.round(e[n]);return r}else throw new Error(`Unknown dtype ${t}`)}var dre="0.0.0";function wI(){Z().set("WEBGL_FORCE_F16_TEXTURES",!0)}kh.isBrowser()&&Rl("webgl",()=>new qh,2);var pre={forceHalfFloat:wI},kI=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,Uu=class{constructor(e,t,r){this.variableNames=["A","B"],this.outputShape=C.assertAndGetBroadcastShape(t,r),this.enableShapeUniforms=un(this.outputShape.length),this.userCode=`
|
|
float binaryOperation(float a, float b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float a = getAAtOutCoords();
|
|
float b = getBAtOutCoords();
|
|
setOutput(binaryOperation(a, b));
|
|
}
|
|
`}},Pm=`
|
|
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;
|
|
`,Xh=class{constructor(e,t,r,n=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=C.assertAndGetBroadcastShape(t,r);let a=this.outputShape.length;this.enableShapeUniforms=un(a);let s="";if(n)if(a===0||v.sizeFromShape(this.outputShape)===1)s=`
|
|
result.y = 0.;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else if(s=`
|
|
${yt(a)} coords = getOutputCoords();
|
|
`,a===1)this.enableShapeUniforms?s+=`
|
|
result.y = (coords + 1) >= outShape ? 0. : result.y;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`:s+=`
|
|
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else{let i=Wr("coords",a);this.enableShapeUniforms?s+=`
|
|
bool nextRowOutOfBounds =
|
|
(${i[a-2]} + 1) >= outShape[${a} - 2];
|
|
bool nextColOutOfBounds =
|
|
(${i[a-1]} + 1) >= outShape[${a} - 1];
|
|
result.y = nextColOutOfBounds ? 0. : result.y;
|
|
result.z = nextRowOutOfBounds ? 0. : result.z;
|
|
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
|
|
`:s+=`
|
|
bool nextRowOutOfBounds =
|
|
(${i[a-2]} + 1) >= ${this.outputShape[a-2]};
|
|
bool nextColOutOfBounds =
|
|
(${i[a-1]} + 1) >= ${this.outputShape[a-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);
|
|
${s}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function mn(e){let{inputs:t,backend:r}=e,{x:n}=t;return r.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}var hre={kernelName:mi,backendName:"webgl",kernelFunc:mn};function Hi(e){let{inputs:t,backend:r}=e,{real:n,imag:a}=t,s=r.makeTensorInfo(n.shape,"complex64"),i=r.texData.get(s.dataId),o=mn({inputs:{x:n},backend:r}),l=mn({inputs:{x:a},backend:r});return i.complexTensorInfos={real:o,imag:l},s}var cre={kernelName:sh,backendName:"webgl",kernelFunc:Hi},II="return (a < 0.) ? b * a : a;",SI=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function fre(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{alpha:s}=n,i=r.makeTensorInfo([],"float32",v.createScalarValue(s,"float32")),o=Z().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Xh(SI,a.shape,i.shape):new Uu(II,a.shape,i.shape),l=r.runWebGLProgram(o,[a,i],"float32");return r.disposeIntermediateTensorInfo(i),l}var mre={kernelName:gi,backendName:"webgl",kernelFunc:fre},CI="return (a < 0.) ? b * a : a;",TI=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function gre(e){let{inputs:t,backend:r}=e,{x:n,alpha:a}=t,s=Z().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Xh(TI,n.shape,a.shape):new Uu(CI,n.shape,a.shape);return r.runWebGLProgram(s,[n,a],"float32")}var yre={kernelName:Ni,backendName:"webgl",kernelFunc:gre},zd="if (isnan(x)) return x;",Are=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,xre=`
|
|
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:r,dtype:n}){return({inputs:a,backend:s})=>{let{x:i}=a,o=s,l=n||i.dtype;if(o.shouldExecuteOnCPU([i])&&r!=null){let h=o.texData.get(i.dataId),p=r(h.values,l);return o.makeTensorInfo(i.shape,l,p)}let u=Z().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,d;return u?d=new Co(i.shape,t):d=new Ka(i.shape,e),o.runWebGLProgram(d,[i],l)}}function wr({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:r=!1,supportsComplex:n=!1,cpuKernelImpl:a,dtype:s}){return({inputs:i,backend:o})=>{let{a:l,b:u}=i,d=o;if(n&&l.dtype==="complex64"){let m=d.texData.get(l.dataId),f=d.texData.get(u.dataId),[g,y]=[[m.complexTensorInfos.real,f.complexTensorInfos.real],[m.complexTensorInfos.imag,f.complexTensorInfos.imag]].map(x=>{let[b,w]=x,I={dataId:b.dataId,dtype:b.dtype,shape:l.shape},T={dataId:w.dataId,dtype:w.dtype,shape:u.shape},E=new Uu(e,l.shape,u.shape);return d.runWebGLProgram(E,[I,T],Nr(b.dtype,w.dtype))}),A=Hi({inputs:{real:g,imag:y},backend:d});return d.disposeIntermediateTensorInfo(g),d.disposeIntermediateTensorInfo(y),A}let h=s||Nr(l.dtype,u.dtype);if((l.dtype==="string"||u.dtype==="string"||d.shouldExecuteOnCPU([l,u]))&&a!=null){let m=d.texData.get(l.dataId).values,f=d.texData.get(u.dataId).values,g=l.dtype==="string"?C.fromUint8ToStringArray(m):m,y=l.dtype==="string"?C.fromUint8ToStringArray(f):f,[A,x]=a(l.shape,u.shape,g,y,h),b=d.makeTensorInfo(x,h),w=d.texData.get(b.dataId);return w.values=A,b}let p=Z().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,c;return p?c=new Xh(t,l.shape,u.shape,r):c=new Uu(e,l.shape,u.shape),d.runWebGLProgram(c,[l,u],h)}}function Om(e,t=!1){if(e==="linear")return t?Zte:jte;if(e==="relu")return t?Jte:qte;if(e==="elu")return t?Yte:Hte;if(e==="relu6")return t?Qte:Xte;if(e==="prelu")return t?TI:CI;if(e==="leakyrelu")return t?SI:II;if(e==="sigmoid")return t?ere:Kte;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var NI=class{constructor(e,t,r,n=!1,a=!1,s=!1,i=null,o=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r,this.enableShapeUniforms=un(this.outputShape.length);let u=n?e[1]:e[2],d=Math.ceil(u/2),h=n?"i * 2, rc.y":"rc.y, i * 2",p=a?"rc.z, i * 2":"i * 2, rc.z",c=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],m=a?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],f="",g="";i&&(o?f=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${i}
|
|
}`:l?f=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${i}
|
|
}`:f=`vec4 activation(vec4 x) {
|
|
${i}
|
|
}`,g="result = activation(result);");let y=s?"result += getBiasAtOutCoords();":"";s&&this.variableNames.push("bias"),o&&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=`
|
|
${f}
|
|
// Don't use uniform for sharedDimensionPacked for performance.
|
|
const float sharedDimension = ${d}.0;
|
|
|
|
vec4 dot2x2ARowBCol(ivec3 rc) {
|
|
vec4 result = vec4(0);
|
|
for (int i = 0; i < ${d}; i++) {
|
|
int batchA = ${A};
|
|
int batchB = ${x};
|
|
vec4 a = getMatrixA(batchA, ${h});
|
|
vec4 b = getMatrixB(batchB, ${p});
|
|
|
|
// These swizzled products need to be separately added.
|
|
// See: https://github.com/tensorflow/tfjs/issues/1735
|
|
result += (${c[0]} * ${m[0]});
|
|
result += (${c[1]} * ${m[1]});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
vec4 result = dot2x2ARowBCol(rc);
|
|
|
|
${y}
|
|
|
|
${g}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}},J4={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},Q4=class{constructor(e,t,r){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=C.assertAndGetBroadcastShape(t,r),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));
|
|
}
|
|
`}},e7="return a * b;";function _A(e){let{inputs:t,backend:r}=e,{a:n,b:a}=t,s=C.upcastType(n.dtype,a.dtype);if(n.dtype==="complex64"){let o=r.texData.get(n.dataId),l=r.texData.get(a.dataId),u=new Q4(J4.REAL,n.shape,a.shape),d=new Q4(J4.IMAG,n.shape,a.shape),h=[{dataId:o.complexTensorInfos.real.dataId,dtype:o.complexTensorInfos.real.dtype,shape:n.shape},{dataId:o.complexTensorInfos.imag.dataId,dtype:o.complexTensorInfos.imag.dtype,shape:n.shape},{dataId:l.complexTensorInfos.real.dataId,dtype:l.complexTensorInfos.real.dtype,shape:a.shape},{dataId:l.complexTensorInfos.imag.dataId,dtype:l.complexTensorInfos.imag.dtype,shape:a.shape}],p=r.runWebGLProgram(u,h,"float32"),c=r.runWebGLProgram(d,h,"float32"),m=Hi({inputs:{real:p,imag:c},backend:r});return r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(c),m}if(r.shouldExecuteOnCPU([n,a])){let o=r.texData.get(n.dataId),l=r.texData.get(a.dataId),[u,d]=Ate(n.shape,a.shape,o.values,l.values,s),h=r.makeTensorInfo(d,s),p=r.texData.get(h.dataId);return p.values=u,h}let i;return Z().getBool("WEBGL_PACK_BINARY_OPERATIONS")?i=new Xh(e7,n.shape,a.shape):i=new Uu(e7,n.shape,a.shape),r.runWebGLProgram(i,[n,a],s)}var bre={kernelName:Si,backendName:"webgl",kernelFunc:_A};function vre(e,t,r){let n=[Lo(e.shape),...Bo(e.shape)],a={dtype:e.dtype,shape:n,dataId:e.dataId},s=[Lo(t),...Bo(t)],i=new bI(s,n),o=!0,l=[n],u=r.runWebGLProgram(i,[a],e.dtype,l,o);return{dataId:u.dataId,shape:t,dtype:u.dtype}}function Ae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{shape:s}=n,i=r,o=v.sizeFromShape(a.shape),l=v.inferFromImplicitShape(s,o),u=v.sizeFromShape(l);v.assert(o===u,()=>`The new shape (${l}) has ${u} elements and the old shape (${a.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`);let d=i.texData.get(a.dataId);return d.isPacked&&!th(a.shape,l)&&!(d.texture!==null&&th(d.shape,l))?vre(a,l,i):(i.incRef(a.dataId),{dataId:a.dataId,shape:l,dtype:a.dtype})}var wre={kernelName:fl,backendName:"webgl",kernelFunc:Ae},t7=class{constructor(e,t){this.variableNames=["x"];let{windowSize:r,batchSize:n,inSize:a,outSize:s}=e;this.outputShape=[n,s];let i=Math.floor(r/4)*4,o=r%4,l="sumValue += dot(values, ones);";if(t!=null){let d=1/t;l=`sumValue += dot(values * ${v.isInt(d)?d.toPrecision(2):d}, ones);`}let u="";a%r>0&&(u=`
|
|
if (inIdx < 0 || inIdx >= ${a}) {
|
|
return 0.0;
|
|
}
|
|
`),this.userCode=`
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${u}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${r};
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < ${i}; 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 + ${i};
|
|
if (${o===1}) {
|
|
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
|
|
|
|
${l}
|
|
} else if (${o===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1), 0.0, 0.0);
|
|
|
|
${l}
|
|
} else if (${o===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2), 0.0);
|
|
|
|
${l}
|
|
}
|
|
setOutput(sumValue);
|
|
}
|
|
`}},kre=class{constructor(e,t){this.variableNames=["x"];let{windowSize:r,batchSize:n,inSize:a,outSize:s}=e;this.outputShape=[n,s];let i="0.0",o="";t==="prod"?i="1.0":t==="min"?(i="1.0 / 1e-20",o="min"):t==="max"&&(i="-1.0 / 1e-20",o="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 u=Math.floor(r/4)*4,d=r%4,h=`
|
|
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 = ${o}(values, minMaxValue);
|
|
if (${t==="min"} || ${t==="max"}) {
|
|
minMaxValue = ${o}(values, minMaxValue);
|
|
bvec4 isNaN = isnan(values);
|
|
if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
|
|
minMaxValue = vec4(NAN);
|
|
}
|
|
}
|
|
}
|
|
`,p="vec4";t==="all"?(i="1.0",h=`
|
|
bool reducedAllValue = all(values);
|
|
float floatedReducedAllValue = float(reducedAllValue);
|
|
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
|
|
`,p="bvec4"):t==="any"&&(i="0.0",h=`
|
|
bool reducedAnyValue = any(values);
|
|
float floatedReducedAnyValue = float(reducedAnyValue);
|
|
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
|
|
`,p="bvec4");let c="";a%r>0&&(c=`
|
|
if (inIdx < 0 || inIdx >= ${a}) {
|
|
return initializationValue;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = ${i};
|
|
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 * ${r};
|
|
|
|
vec4 minMaxValue = vec4(${i});
|
|
float prodValue = 1.0;
|
|
float sumValue = 0.0;
|
|
float allValue = 1.0;
|
|
float anyValue = 0.0;
|
|
|
|
for (int i = 0; i < ${u}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${h}
|
|
}
|
|
|
|
int inIdx = inOffset + ${u};
|
|
if (${d===1}) {
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${h}
|
|
} else if (${d===2}) {
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${h}
|
|
} else if (${d===3}) {
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
${h}
|
|
}
|
|
setOutput(${l});
|
|
}
|
|
`}};function Ire(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let r=t.length?t[t.length-1].outSize:e[1],n=C.computeOptimalWindowSize(r);t.push({inSize:r,windowSize:n,outSize:Math.ceil(r/n)})}return t}function Bl(e,t,r,n){let a=Ire(e.shape),s=e;for(let i=0;i<a.length;i++){let{inSize:o,windowSize:l,outSize:u}=a[i],d,h;r==="mean"?d=i===0?new t7({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},o):new t7({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u}):d=new kre({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},r),h=s,s=n.runWebGLProgram(d,[s],t),h.dataId!==e.dataId&&n.disposeIntermediateTensorInfo(h)}return s}var Sre=class{constructor(e,t){this.variableNames=["A"];let r=new Array(e.length);for(let s=0;s<r.length;s++)r[s]=e[t[s]];this.outputShape=r,this.rank=r.length;let n=yt(this.rank),a=Cre(t);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${a}));
|
|
}
|
|
`}};function Cre(e){let t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);let r=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],n=new Array(t);for(let a=0;a<e.length;a++)n[e[a]]=r[a];return n.join()}var Tre=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let r=new Array(e.length);for(let u=0;u<r.length;u++)r[u]=e[t[u]];if(this.outputShape=r,this.rank=r.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let n=yt(this.rank),a=xI("rc",this.rank),s=new Array(this.rank);for(let u=0;u<t.length;u++)s[t[u]]=a[u];let i=`vec2(${s.slice(-2).join()})`,o=`++${a[this.rank-1]} < ${r[this.rank-1]}`,l=`getChannel(getA(${s.join()}), ${i})`;this.userCode=`
|
|
void main() {
|
|
${n} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result[0] = ${l};
|
|
if(${o}) {
|
|
result[1] = ${l};
|
|
}
|
|
--${a[this.rank-1]};
|
|
if(++${a[this.rank-2]} < ${r[this.rank-2]}) {
|
|
result[2] = ${l};
|
|
if(${o}) {
|
|
result[3] = ${l};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function zm(e,t,r){let n=Z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Tre(e.shape,t):new Sre(e.shape,t);return r.runWebGLProgram(n,[e],e.dtype)}function Nre(e,t,r,n){let a=t,s=e.shape.length,i=v.parseAxisParam(a,e.shape),o=i,l=C.getAxesPermutation(o,s),u=l!=null,d=e;u&&(d=zm(e,l,n),o=C.getInnerMostAxes(o.length,s)),C.assertAxesAreInnerMostDims("sum",o,s);let[h,p]=C.computeOutAndReduceShapes(d.shape,o),c=h;r&&(c=C.expandShapeToKeepDim(h,i));let m=v.sizeFromShape(p),f=v.sizeFromShape(e.shape)/m,g=Ae({inputs:{x:d},attrs:{shape:[f,m]},backend:n}),y=wh(e.dtype),A=Bl(g,y,"sum",n),x=Ae({inputs:{x:A},attrs:{shape:c},backend:n});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(A),u&&n.disposeIntermediateTensorInfo(d),x}function Dm(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;return Nre(a,s,i,r)}var Ere={kernelName:zi,backendName:"webgl",kernelFunc:Dm};function Gr(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{perm:s}=n,i=r,o=a.shape.length,l=new Array(o);for(let d=0;d<l.length;d++)l[d]=a.shape[s[d]];let u;if(i.shouldExecuteOnCPU([a])){let d=i.texData.get(a.dataId).values,h=FA(d,a.shape,a.dtype,s,l);u=i.makeTensorInfo(l,a.dtype);let p=i.texData.get(u.dataId);p.values=h}else u=zm(a,s,i);return u}var Rre={kernelName:$a,backendName:"webgl",kernelFunc:Gr},EI=1e3;function Q0({a:e,b:t,transposeA:r,transposeB:n,backend:a,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){let u=e.shape.length,d=t.shape.length,h=r?e.shape[u-2]:e.shape[u-1],p=n?t.shape[d-1]:t.shape[d-2],c=r?e.shape[u-1]:e.shape[u-2],m=n?t.shape[d-2]:t.shape[d-1],f=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=v.sizeFromShape(f),A=v.sizeFromShape(g),x=$l.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([c,m]);v.assert(h===p,()=>`Error in matMul: inner shapes (${h}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${r} and transposeB=${n} must match.`);let b=r?[y,h,c]:[y,c,h],w=n?[A,m,p]:[A,p,m],I=Ae({inputs:{x:e},backend:a,attrs:{shape:b}}),T=Ae({inputs:{x:t},backend:a,attrs:{shape:w}}),E=[I,T],R=Math.max(y,A),F=r?I.shape[1]:I.shape[2],$=s!=null,S=i!=null,z=l==="leakyrelu",O=l!=null?Om(l,!0):null,j=$||S||z||O!=null,K;if((c===1||m===1)&&F>EI&&j===!1){let Y=I,V=T;r&&(Y=Gr({inputs:{x:I},backend:a,attrs:{perm:[0,2,1]}}),E.push(Y)),n&&(V=Gr({inputs:{x:T},backend:a,attrs:{perm:[0,2,1]}}),E.push(V));let re=m!==1,Q=m===1,ie=Y;re&&(ie=Ae({inputs:{x:Y},backend:a,attrs:{shape:[R,F,1]}}),E.push(ie));let J=m===1?2:1,ae=V;Q&&(ae=Ae({inputs:{x:V},backend:a,attrs:{shape:[R,1,F]}}),E.push(ae));let de=_A({inputs:{a:ie,b:ae},backend:a});K=Dm({inputs:{x:de},backend:a,attrs:{axis:J,keepDims:!0}}),E.push(de)}else{let Y=Nr(e.dtype,t.dtype),V=new NI(b,w,[R,c,m],r,n,$,O,S,z),re=[I,T];if(s!=null&&re.push(s),S&&re.push(i),z){let Q=a.makeTensorInfo([],"float32",v.createScalarValue(o,"float32"));re.push(Q),E.push(Q)}K=a.runWebGLProgram(V,re,Y)}let D=Ae({inputs:{x:K},backend:a,attrs:{shape:x}});E.push(K);for(let Y of E)a.disposeIntermediateTensorInfo(Y);return D}function $re(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:d,leakyreluAlpha:h}=n;return Q0({a,b:s,transposeA:l,transposeB:u,backend:r,bias:i,preluActivationWeights:o,leakyreluAlpha:h,activation:d})}var Mre={kernelName:Ps,backendName:"webgl",kernelFunc:$re},r7="return abs(x);";function Fre(e){let{inputs:t,backend:r}=e,{x:n}=t;if(r.shouldExecuteOnCPU([n])&&n.dtype!=="complex64"){let s=r.texData.get(n.dataId),i=yI(s.values);return r.makeTensorInfo(n.shape,n.dtype,i)}let a;return Z().getBool("WEBGL_PACK_UNARY_OPERATIONS")?a=new Co(n.shape,r7):a=new Ka(n.shape,r7),r.runWebGLProgram(a,[n],n.dtype)}var _re={kernelName:Go,backendName:"webgl",kernelFunc:Fre},Pre=Yn+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,Ore=it({opSnippet:Pre}),zre={kernelName:Hu,backendName:"webgl",kernelFunc:Ore},Dre=Yn+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,Lre=it({opSnippet:Dre}),Bre={kernelName:qu,backendName:"webgl",kernelFunc:Lre},n7="return a + b;",Wre=wr({opSnippet:n7,packedOpSnippet:n7,supportsComplex:!0,cpuKernelImpl:Qee}),Vre={kernelName:Qa,backendName:"webgl",kernelFunc:Wre},Ure=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((a,s)=>`T${s}`);let r=[];this.variableNames.forEach(a=>{r.push(`float v${a} = get${a}AtOutCoords();`)});let n=this.variableNames.map(a=>`v${a}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${r.join(`
|
|
`)}
|
|
|
|
float result = ${n};
|
|
setOutput(result);
|
|
}
|
|
`}},Gre=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((a,s)=>`T${s}`);let r=[];this.variableNames.forEach(a=>{r.push(`vec4 v${a} = get${a}AtOutCoords();`)});let n=this.variableNames.map(a=>`v${a}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${r.join(`
|
|
`)}
|
|
|
|
vec4 result = ${n};
|
|
setOutput(result);
|
|
}
|
|
`}};function v0(e){let{inputs:t,backend:r}=e,n=t;if(n.length===1)return mn({inputs:{x:n[0]},backend:r});if(n.length>Z().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let o=Math.floor(n.length/2),l=v0({inputs:n.slice(0,o),backend:r}),u=v0({inputs:n.slice(o),backend:r});return v0({inputs:[l,u],backend:r})}let a=n.map(o=>o.dtype).reduce((o,l)=>Nr(o,l)),s=n.map(o=>o.shape),i=Z().getBool("WEBGL_PACK")?new Gre(n[0].shape,s):new Ure(n[0].shape,s);return r.runWebGLProgram(i,n,a)}var jre={kernelName:Zs,backendName:"webgl",kernelFunc:v0};function Hre(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n,o=a.shape.length,l=v.parseAxisParam(s,a.shape),u=l,d=C.getAxesPermutation(u,o),h=a;d!=null&&(h=Gr({inputs:{x:a},backend:r,attrs:{perm:d}}),u=C.getInnerMostAxes(u.length,o)),C.assertAxesAreInnerMostDims("all",u,o);let[p,c]=C.computeOutAndReduceShapes(h.shape,u),m=v.sizeFromShape(c),f=Ae({inputs:{x:h},backend:r,attrs:{shape:[-1,m]}}),g=Bl(f,f.dtype,"all",r),y;if(i){let A=C.expandShapeToKeepDim(p,l);y=Ae({inputs:{x:g},backend:r,attrs:{shape:A}})}else y=Ae({inputs:{x:g},backend:r,attrs:{shape:p}});return r.disposeIntermediateTensorInfo(f),r.disposeIntermediateTensorInfo(g),d!=null&&r.disposeIntermediateTensorInfo(h),y}var qre={kernelName:Xu,backendName:"webgl",kernelFunc:Hre};function Xre(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n,o=a.shape.length,l=v.parseAxisParam(s,a.shape),u=l,d=C.getAxesPermutation(u,o),h=a;d!=null&&(h=Gr({inputs:{x:a},backend:r,attrs:{perm:d}}),u=C.getInnerMostAxes(u.length,o)),C.assertAxesAreInnerMostDims("any",u,o);let[p,c]=C.computeOutAndReduceShapes(h.shape,u),m=v.sizeFromShape(c),f=Ae({inputs:{x:h},backend:r,attrs:{shape:[-1,m]}}),g=Bl(f,f.dtype,"any",r),y;if(i){let A=C.expandShapeToKeepDim(p,l);y=Ae({inputs:{x:g},backend:r,attrs:{shape:A}})}else y=Ae({inputs:{x:g},backend:r,attrs:{shape:p}});return r.disposeIntermediateTensorInfo(f),r.disposeIntermediateTensorInfo(g),d!=null&&r.disposeIntermediateTensorInfo(h),y}var Kre={kernelName:Ku,backendName:"webgl",kernelFunc:Xre},Zre=class{constructor(e,t,r){this.variableNames=["A"];let{windowSize:n,batchSize:a,outSize:s}=e;r||this.variableNames.push("bestIndicesA"),this.outputShape=[a,s];let i=t==="max"?">":"<",o=r?"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 * ${n};
|
|
|
|
int bestIndex = inOffset;
|
|
float bestValue = getA(batch, bestIndex);
|
|
|
|
for (int i = 0; i < ${n}; i++) {
|
|
int inIdx = ${o};
|
|
float candidate = getA(batch, inIdx);
|
|
if (candidate ${i} bestValue) {
|
|
bestValue = candidate;
|
|
bestIndex = inIdx;
|
|
}
|
|
}
|
|
setOutput(float(bestIndex));
|
|
}
|
|
`}},Yre=class{constructor(e,t,r,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,v.assert(e.length>2,()=>`Packed arg${r.charAt(0).toUpperCase()+r.slice(1)} supports only inputs with rank above 2.`);let a=e[e.length-1],s=Math.ceil(a/t);this.outputShape=e.slice(0,-1),s>1&&this.outputShape.push(s),n||this.variableNames.push("bestIndicesA");let i=this.outputShape,o=i.length,l=yt(o),u=Wr("coords",o),d,h;if(s===1){h=o+1;let T=yt(h);d=`
|
|
${T} sourceLocR = ${T}(${u.join()}, 0);
|
|
++${u[o-1]};
|
|
${T} sourceLocG = ${T}(${u.join()}, 0);
|
|
++${u[o-2]};
|
|
${T} sourceLocA = ${T}(${u.join()}, 0);
|
|
--${u[o-1]};
|
|
${T} sourceLocB = ${T}(${u.join()}, 0);
|
|
--${u[o-2]};`}else h=o,d=`
|
|
${l} sourceLocR = coords;
|
|
++${u[o-1]};
|
|
${l} sourceLocG = coords;
|
|
++${u[o-2]};
|
|
${l} sourceLocA = coords;
|
|
--${u[o-1]};
|
|
${l} sourceLocB = coords;
|
|
--${u[o-2]};`;let p=["x","y","z","w","u","v"].slice(0,h),c="."+p[h-1],m=p.map(T=>"int "+T),f=Wr("sourceLocR",h-1).concat("inIdx.r"),g=Wr("sourceLocG",h-1).concat("inIdx.g"),y=Wr("sourceLocB",h-1).concat("inIdx.b"),A=Wr("sourceLocA",h-1).concat("inIdx.a"),x=r==="max"?"greaterThan":"lessThan",b=n?"":`
|
|
inIdx = round(vec4(getBestIndicesAChannel(${f.join()}),
|
|
getBestIndicesAChannel(${g.join()}),
|
|
getBestIndicesAChannel(${y.join()}),
|
|
getBestIndicesAChannel(${A.join()})));`,w=`vec4(
|
|
getAChannel(${f.join()}),
|
|
hasNextCol ? getAChannel(${g.join()}) : 0.,
|
|
hasNextRow ? getAChannel(${y.join()}) : 0.,
|
|
hasNextRow && hasNextCol ? getAChannel(${A.join()}) : 0.)`,I=n?"":`
|
|
float getBestIndicesAChannel(${m.join()}) {
|
|
return getChannel(getBestIndicesA(${p.join()}),
|
|
vec2(${p.slice(-2).join()}));
|
|
}`;this.userCode=`
|
|
float getAChannel(${m.join()}) {
|
|
return getChannel(getA(${p.join()}),
|
|
vec2(${p.slice(-2).join()}));
|
|
}
|
|
${I}
|
|
void main() {
|
|
${l} coords = getOutputCoords();
|
|
bool hasNextCol = ${u[o-1]} < ${i[o-1]-1};
|
|
bool hasNextRow = ${u[o-2]} < ${i[o-2]-1};
|
|
${d}
|
|
ivec4 srcIdx = ivec4(sourceLocR${c}, sourceLocG${c},
|
|
sourceLocB${c}, sourceLocA${c}) * ${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 RI(e,t,r,n=null){let a=t.shape[0],s=t.shape[1];n!=null&&(a=n.shape[0],s=n.shape[1]);let i=C.computeOptimalWindowSize(s),o={windowSize:i,inSize:s,batchSize:a,outSize:Math.ceil(s/i)},l=new Zre(o,r,n==null),u=[t];n!=null&&u.push(n);let d=e.runWebGLProgram(l,u,"int32");if(d.shape[1]===1)return d;let h=RI(e,t,r,d);return e.disposeIntermediateTensorInfo(d),h}function $I(e,t,r,n=null){let a=n!=null?n.shape:t.shape,s=a[a.length-1],i=C.computeOptimalWindowSize(s),o=new Yre(a,i,r,n==null),l=n==null?[t]:[t,n],u=e.runWebGLProgram(o,l,"int32");if(u.shape.length===t.shape.length){let d=$I(e,t,r,u);return e.disposeIntermediateTensorInfo(u),d}return u}function MI(e,t,r,n){let a=[r];if(C.assertAxesAreInnerMostDims("arg"+n.charAt(0).toUpperCase()+n.slice(1),a,t.shape.length),!Z().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let s=[],i=e.texData.get(t.dataId),o=i!==null&&i.isPacked,l=t;o&&(l=e.unpackTensor(t),s.push(l));let[u,d]=C.computeOutAndReduceShapes(l.shape,a),h=v.sizeFromShape(d),p=Ae({inputs:{x:l},backend:e,attrs:{shape:[-1,h]}});s.push(p);let c=RI(e,p,n);s.push(c);let m=Ae({inputs:{x:c},backend:e,attrs:{shape:u}});return s.forEach(f=>e.disposeIntermediateTensorInfo(f)),m}return $I(e,t,n)}function Jre(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s}=n,i=v.parseAxisParam(s,a.shape),o=C.getAxesPermutation(i,a.shape.length),l=a,u=[];o!=null&&(l=Gr({inputs:{x:a},backend:r,attrs:{perm:o}}),u.push(l),i=C.getInnerMostAxes(i.length,l.shape.length)),C.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let d=MI(r,l,i[0],"max");return u.forEach(h=>r.disposeIntermediateTensorInfo(h)),d}var Qre={kernelName:Ys,backendName:"webgl",kernelFunc:Jre};function ene(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s}=n,i=v.parseAxisParam(s,a.shape),o=C.getAxesPermutation(i,a.shape.length),l=a,u=[];o!=null&&(l=Gr({inputs:{x:a},backend:r,attrs:{perm:o}}),u.push(l),i=C.getInnerMostAxes(i.length,l.shape.length)),C.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let d=MI(r,l,i[0],"min");return u.forEach(h=>r.disposeIntermediateTensorInfo(h)),d}var tne={kernelName:Zu,backendName:"webgl",kernelFunc:ene},rne=Yn+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,nne=it({opSnippet:rne}),ane={kernelName:Yu,backendName:"webgl",kernelFunc:nne},sne=Yn+"return log(x + sqrt(x * x + 1.0));",ine=it({opSnippet:sne}),one={kernelName:Ju,backendName:"webgl",kernelFunc:ine},lne=Yn+`
|
|
return atan(x);
|
|
`,une=it({opSnippet:lne}),dne={kernelName:Qu,backendName:"webgl",kernelFunc:une},pne=Are+`
|
|
return atan(a, b);
|
|
`,hne=`
|
|
vec4 result = atan(a, b);
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+xre+`
|
|
return result;
|
|
`,cne=wr({opSnippet:pne,packedOpSnippet:hne}),fne={kernelName:td,backendName:"webgl",kernelFunc:cne},mne=Yn+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,gne=it({opSnippet:mne}),yne={kernelName:ed,backendName:"webgl",kernelFunc:gne},rh=class{constructor(e,t,r,n=!1,a=!1){if(this.variableNames=["x"],t==="avg"&&r)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideHeight,o=e.strideWidth,l=e.dilationHeight,u=e.dilationWidth,d=e.effectiveFilterHeight,h=e.effectiveFilterWidth,p=e.padInfo.top,c=e.padInfo.left;this.outputShape=e.outShape;let m=t==="avg",f=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,y="0.0";if(m||(y="-1.0 / 1e-20"),r){let T=">=";this.userCode=`
|
|
const ivec2 strides = ivec2(${i}, ${o});
|
|
const ivec2 pads = ivec2(${p}, ${c});
|
|
|
|
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 < ${d};
|
|
wR += ${l}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${h};
|
|
wC += ${u}) {
|
|
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 ${T} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${n?a?f:g:`wR * ${h} + 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(s/4)*4,w=s%4,I=`
|
|
if (${m}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${A}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec2 strides = ivec2(${i}, ${o});
|
|
const ivec2 pads = ivec2(${p}, ${c});
|
|
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 < ${d};
|
|
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 * ${u};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${u}, d),
|
|
getValue(batch, xR, xC + 2 * ${u}, d),
|
|
getValue(batch, xR, xC + 3 * ${u}, d)
|
|
);
|
|
|
|
${I}
|
|
}
|
|
|
|
int xC = xCCorner + ${b};
|
|
if (${w===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${I}
|
|
} else if (${w===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${u}, d),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${I}
|
|
} else if (${w===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${u}, d),
|
|
getValue(batch, xR, xC + 2 * ${u}, d),
|
|
initializationValue
|
|
);
|
|
|
|
${I}
|
|
}
|
|
}
|
|
setOutput(${x});
|
|
}
|
|
`}},PA=class{constructor(e,t,r,n=!1,a=!1){if(this.variableNames=["x"],t==="avg"&&r)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,l=e.strideWidth,u=e.dilationDepth,d=e.dilationHeight,h=e.dilationWidth,p=e.effectiveFilterDepth,c=e.effectiveFilterHeight,m=e.effectiveFilterWidth,f=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"),r){let R=">=";this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${i}, ${o}, ${l});
|
|
const ivec3 pads = ivec3(${f}, ${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 += ${u}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${c};
|
|
wR += ${d}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${m};
|
|
wC += ${h}) {
|
|
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 ${R} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${n?a?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${c} * ${m} +
|
|
wR * ${m} + 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 I=Math.floor(s/4)*4,T=s%4,E=`
|
|
if (${A}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${b}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${i}, ${o}, ${l});
|
|
const ivec3 pads = ivec3(${f}, ${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 += ${u}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${c};
|
|
wR += ${d}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${I}; wC += 4) {
|
|
int xC = xCCorner + wC * ${h};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${h}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${h}, ch),
|
|
getValue(batch, xD, xR, xC + 3 * ${h}, ch)
|
|
);
|
|
|
|
${E}
|
|
}
|
|
|
|
int xC = xCCorner + ${I};
|
|
if (${T===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${E}
|
|
} else if (${T===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${h}, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${E}
|
|
} else if (${T===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${h}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${h}, ch),
|
|
initializationValue
|
|
);
|
|
|
|
${E}
|
|
}
|
|
}
|
|
setOutput(${w});
|
|
}
|
|
}
|
|
`}};function Ane(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t;Md(a,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1;v.assert(C.eitherStridesOrDilationsAreOne(i,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=C.computePool2DInfo(a.shape,s,i,u,o,l);if(d.filterWidth===1&&d.filterHeight===1&&v.arraysEqual(d.inShape,d.outShape))return mn({inputs:{x:a},backend:r});let h=new rh(d,"avg",!1);return r.runWebGLProgram(h,[a],"float32")}var xne={kernelName:Js,backendName:"webgl",kernelFunc:Ane};function bne(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=n,d=[1,1,1],h=C.computePool3DInfo(a.shape,s,i,d,o,l,u),p=new PA(h,"avg",!1);return r.runWebGLProgram(p,[a],"float32")}var vne={kernelName:ah,backendName:"webgl",kernelFunc:bne},wne=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,r=e.filterWidth,n=e.strideHeight,a=e.strideWidth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=o-1-e.padInfo.top,d=l-1-e.padInfo.left,h=1/(t*r);this.userCode=`
|
|
const ivec2 pads = ivec2(${u}, ${d});
|
|
const float avgMultiplier = float(${h});
|
|
|
|
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 < ${o};
|
|
wR += ${s}) {
|
|
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 < ${l};
|
|
wC+= ${i}) {
|
|
float dyC = float(dyCCorner + wC) / ${a}.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);
|
|
}
|
|
`}},kne=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,r=e.filterHeight,n=e.filterWidth,a=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,d=e.effectiveFilterDepth,h=e.effectiveFilterHeight,p=e.effectiveFilterWidth,c=d-1-e.padInfo.front,m=h-1-e.padInfo.top,f=p-1-e.padInfo.left,g=1/(t*r*n);this.userCode=`
|
|
const ivec3 pads = ivec3(${c}, ${m}, ${f});
|
|
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 < ${d};
|
|
wD += ${o}) {
|
|
float dyD = float(dyDCorner + wD) / ${a}.0;
|
|
|
|
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyD = int(dyD);
|
|
|
|
for (int wR = 0; wR < ${h};
|
|
wR += ${l}) {
|
|
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 < ${p};
|
|
wC += ${u}) {
|
|
float dyC = float(dyCCorner + wC) / ${i}.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 Ine(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:d}=n,h=[1,1,1],p=C.computePool3DInfo(i.shape,o,l,h,u,d),c=new kne(p);return r.runWebGLProgram(c,[a],i.dtype)}var Sne={kernelName:df,backendName:"webgl",kernelFunc:Ine};function Cne(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,i=s;Md([a,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:u}=n,d=C.computePool2DInfo(i.shape,o,l,1,u),h=new wne(d);return r.runWebGLProgram(h,[a],i.dtype)}var Tne={kernelName:uf,backendName:"webgl",kernelFunc:Cne};function Nne(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s}=t,{transposeA:i,transposeB:o}=n;return Q0({a,b:s,transposeA:i,transposeB:o,backend:r})}var Ene={kernelName:Qs,backendName:"webgl",kernelFunc:Nne},Rne=class{constructor(e,t,r,n,a,s){this.outputShape=[],this.variableNames=["x","mean","variance"],C.assertAndGetBroadcastShape(e,t),C.assertAndGetBroadcastShape(e,r);let i="0.0";n!=null&&(C.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";a!=null&&(C.assertAndGetBroadcastShape(e,a),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
float x = getXAtOutCoords();
|
|
float mean = getMeanAtOutCoords();
|
|
float variance = getVarianceAtOutCoords();
|
|
float offset = ${i};
|
|
float scale = ${o};
|
|
float inv = scale * inversesqrt(variance + float(${s}));
|
|
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
|
|
}
|
|
`}},$ne=class{constructor(e,t,r,n,a,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],C.assertAndGetBroadcastShape(e,t),C.assertAndGetBroadcastShape(e,r);let i="vec4(0.0)";n!=null&&(C.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";a!=null&&(C.assertAndGetBroadcastShape(e,a),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
vec4 offset = ${i};
|
|
vec4 scale = ${o};
|
|
|
|
vec4 x = getXAtOutCoords();
|
|
vec4 mean = getMeanAtOutCoords();
|
|
vec4 variance = getVarianceAtOutCoords();
|
|
|
|
vec4 inv = scale * inversesqrt(variance + vec4(${s}));
|
|
|
|
setOutput((x - mean) * inv + offset);
|
|
}
|
|
`}},Mne=({inputs:e,backend:t,attrs:r})=>{let{x:n,mean:a,variance:s,offset:i,scale:o}=e;v.assert(a.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),v.assert(i==null||a.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),v.assert(o==null||a.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=r;l==null&&(l=.001);let u=[n,a,s],d=null;i!=null&&(d=i.shape,u.push(i));let h=null;o!=null&&(h=o.shape,u.push(o));let p=Z().getBool("WEBGL_PACK_NORMALIZATION")?new $ne(n.shape,a.shape,s.shape,d,h,l):new Rne(n.shape,a.shape,s.shape,d,h,l);return t.runWebGLProgram(p,u,u[0].dtype)},Fne={kernelName:ci,backendName:"webgl",kernelFunc:Mne},_ne=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=yt(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let r=Pne(this.rank),n,a=e.map((s,i)=>`sourceLoc.${yy[i]} = start[${i}] + coords.${yy[i]};`);n=`
|
|
${t} sourceLoc;
|
|
${t} coords = getOutputCoords();
|
|
${a.join(`
|
|
`)}
|
|
`,this.userCode=`
|
|
void main() {
|
|
${n}
|
|
setOutput(getSource(${r}));
|
|
}
|
|
`}},yy=["x","y","z","w","u","v"];function Pne(e){if(e===1)return"sourceLoc";if(e<=6)return yy.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var One=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=yt(this.rank),r=Wr("coords",this.rank),n=Wr("sourceLoc",this.rank),a=this.rank===1?"sourceLoc":`vec2(${n.slice(-2).join()})`,s=`getChannel(getSource(${n.join()}), ${a})`,i=`
|
|
result.x = ${s};
|
|
if (++${r[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${n[this.rank-1]};
|
|
result.y = ${s};
|
|
--${n[this.rank-1]};
|
|
}
|
|
`,o=this.rank===1?"":`
|
|
--${r[this.rank-1]};
|
|
if (++${r[this.rank-2]} < ${e[this.rank-2]}) {
|
|
++${n[this.rank-2]};
|
|
result.z = ${s};
|
|
if (++${r[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${n[this.rank-1]};
|
|
result.w = ${s};
|
|
}
|
|
}
|
|
`,l=this.rank<=4?`sourceLoc = coords +
|
|
${t}(${e.map((u,d)=>`start[${d}]`).join()});`:e.map((u,d)=>`${n[d]} = ${r[d]} + start[${d}];`).join(`
|
|
`);this.userCode=`
|
|
void main() {
|
|
${t} coords = getOutputCoords();
|
|
${t} sourceLoc;
|
|
${l}
|
|
vec4 result = vec4(0.);
|
|
${i}
|
|
${o}
|
|
setOutput(result);
|
|
}
|
|
`}};function zne(e,t,r,n){let a=n.texData.get(e.dataId),s=n.makeTensorInfo(r,e.dtype),i=n.texData.get(s.dataId);Object.assign(i,a),i.refCount=1,i.shape=r,i.dtype=e.dtype;let o=Dt.computeFlatOffset(t,v.computeStrides(e.shape));a.slice&&(o+=a.slice.flatOffset),i.slice={flatOffset:o,origDataId:a.slice&&a.slice.origDataId||e.dataId};let l=n.dataRefCount.get(i.slice.origDataId)||1;return n.dataRefCount.set(i.slice.origDataId,l+1),s}function Dd(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{begin:s,size:i}=n,[o,l]=Dt.parseSliceParams(a,s,i);if(Dt.assertParamsValid(a,o,l),v.sizeFromShape(l)===0)return r.makeTensorInfo(l,a.dtype,[]);if(r.shouldExecuteOnCPU([a])||a.dtype==="string"){let h=r.texData.get(a.dataId),p=Cte(h.values,o,l,a.shape,a.dtype);return r.makeTensorInfo(l,a.dtype,p)}let{isPacked:u}=r.texData.get(a.dataId),d=Dt.isSliceContinous(a.shape,o,l);if(u||!d){let h=Z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new One(l):new _ne(l),p=[o];return r.runWebGLProgram(h,[a],a.dtype,p)}return r.uploadToGPU(a.dataId),zne(a,o,l,r)}var Dne={kernelName:xl,backendName:"webgl",kernelFunc:Dd},Lne=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,crops:i}=n;v.assert(a.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((A,x)=>A*x),l=C.getReshaped(a.shape,s,o),u=C.getPermuted(l.length,s.length),d=C.getReshapedPermuted(a.shape,s,o),h=C.getSliceBeginCoords(i,s.length),p=C.getSliceSize(d,i,s.length),c=[],m=Ae({inputs:{x:a},backend:r,attrs:{shape:l}}),f=Gr({inputs:{x:m},backend:r,attrs:{perm:u}}),g=Ae({inputs:{x:f},backend:r,attrs:{shape:d}}),y=Dd({inputs:{x:g},backend:r,attrs:{begin:h,size:p}});return c.push(m),c.push(f),c.push(g),c.forEach(A=>r.disposeIntermediateTensorInfo(A)),y},Bne={kernelName:jo,backendName:"webgl",kernelFunc:Lne};function Wne(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,weights:s}=t,{size:i}=n,o=r.readSync(a.dataId),l=r.readSync(s.dataId),u=gI(o,l,s.dtype,s.shape,i);return r.makeTensorInfo([i],s.dtype,u)}var Vne={kernelName:pf,backendName:"webgl",kernelFunc:Wne};function Une(e){let{inputs:t,backend:r}=e,{s0:n,s1:a}=t,s=r.readSync(n.dataId),i=r.readSync(a.dataId),o=C.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return r.makeTensorInfo([o.length],"int32",Int32Array.from(o))}var Gne={kernelName:hf,backendName:"webgl",kernelFunc:Une},jne="return float(a != b);",FI=wr({opSnippet:jne,cpuKernelImpl:bte,dtype:"bool"}),Hne={kernelName:ll,backendName:"webgl",kernelFunc:FI};function Kh(e){let{inputs:t,backend:r}=e,{input:n}=t,a=r.texData.get(n.dataId);return mn({inputs:{x:a.complexTensorInfos.real},backend:r})}var qne={kernelName:ch,backendName:"webgl",kernelFunc:Kh},Xne="return float(int(x));";function Kne(e,t){let r=new Ka(e.shape,Xne),n=t.runWebGLProgram(r,[e],"int32");return{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}function Ay(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{dtype:s}=n;if(s==="complex64"){if(a.dtype==="complex64")return mn({inputs:{x:a},backend:r});let i=Ot(a.shape),o=Ay({inputs:{x:a},backend:r,attrs:{dtype:"float32"}}),l=Hi({inputs:{real:o,imag:i},backend:r});return i.dispose(),r.disposeIntermediateTensorInfo(o),l}if(a.dtype==="complex64"){let i=Kh({inputs:{input:a},backend:r}),o=Ay({inputs:{x:i},backend:r,attrs:{dtype:s}});return r.disposeIntermediateTensorInfo(i),o}if(!v.hasEncodingLoss(a.dtype,s)){let i=mn({inputs:{x:a},backend:r});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32")return Kne(a,r);if(s==="bool"){let i=r.makeTensorInfo([],"bool",v.getTypedArrayFromDType("bool",1)),o=FI({inputs:{a,b:i},backend:r});return r.disposeIntermediateTensorInfo(i),o}throw new Error(`Error in Cast: failed to cast ${a.dtype} to ${s}`)}var Zne={kernelName:ei,backendName:"webgl",kernelFunc:Ay},a7="return ceil(x);",Yne=it({opSnippet:a7,packedOpSnippet:a7,cpuKernelImpl:tte}),Jne={kernelName:ti,backendName:"webgl",kernelFunc:Yne},Qne=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));
|
|
}
|
|
`}},eae=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 tae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{clipValueMin:s,clipValueMax:i}=n,o;Z().getBool("WEBGL_PACK_CLIP")?o=new eae(a.shape):o=new Qne(a.shape);let l=[[s],[i]];return r.runWebGLProgram(o,[a],a.dtype,l)}var rae={kernelName:es,backendName:"webgl",kernelFunc:tae},nae=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 s7(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function aae(e){let{inputs:t,backend:r}=e,{x:n}=t,a=r.texData.get(n.dataId),s=new nae(n.shape),i=[s7(n,a.complexTensorInfos.real),s7(n,a.complexTensorInfos.imag)];return r.runWebGLProgram(s,i,i[0].dtype)}var sae={kernelName:ih,backendName:"webgl",kernelFunc:aae},iae=class{constructor(e){this.outputShape=[],this.outputShape=C.computeOutShape(e,1),this.variableNames=e.map((s,i)=>`T${i}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let s=1;s<t.length;s++)t[s]=t[s-1]+e[s][1];let r=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let s=1;s<t.length;s++){let i=t[s-1];r.push(`else if (yC < ${t[s]}) setOutput(getT${s}(yR, yC-${i}));`)}let n=t.length,a=t[t.length-1];r.push(`else setOutput(getT${n}(yR, yC-${a}));`),this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int yR = coords.x;
|
|
int yC = coords.y;
|
|
|
|
${r.join(`
|
|
`)}
|
|
}
|
|
`}},oae=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=C.computeOutShape(e,t);let r=this.outputShape,n=r.length,a=yt(n),s=Wr("coords",n),i=["x","y","z","w","u","v"].slice(0,n);this.variableNames=e.map((m,f)=>`T${f}`);let o=new Array(e.length-1);o[0]=e[0][t];for(let m=1;m<o.length;m++)o[m]=o[m-1]+e[m][t];let l=i[t],u=i.slice(-2),d=i.join(),h=`if (${l} < ${o[0]}) {
|
|
return getChannel(
|
|
getT0(${d}), vec2(${u.join()}));
|
|
}`;for(let m=1;m<o.length;m++){let f=o[m-1];h+=`
|
|
if (${l} < ${o[m]} && ${l} >= ${o[m-1]}) {
|
|
return getChannel(
|
|
getT${m}(${p0(i,l,f)}),
|
|
vec2(${p0(u,l,f)}));
|
|
}`}let p=o.length,c=o[o.length-1];h+=`
|
|
return getChannel(
|
|
getT${p}(${p0(i,l,c)}),
|
|
vec2(${p0(u,l,c)}));`,this.userCode=`
|
|
float getValue(${i.map(m=>"int "+m)}) {
|
|
${h}
|
|
}
|
|
|
|
void main() {
|
|
${a} coords = getOutputCoords();
|
|
vec4 result = vec4(getValue(${s}), 0., 0., 0.);
|
|
|
|
${s[n-1]} = ${s[n-1]} + 1;
|
|
if (${s[n-1]} < ${r[n-1]}) {
|
|
result.g = getValue(${s});
|
|
}
|
|
|
|
${s[n-2]} = ${s[n-2]} + 1;
|
|
if (${s[n-2]} < ${r[n-2]}) {
|
|
result.a = getValue(${s});
|
|
}
|
|
|
|
${s[n-1]} = ${s[n-1]} - 1;
|
|
if (${s[n-2]} < ${r[n-2]} &&
|
|
${s[n-1]} < ${r[n-1]}) {
|
|
result.b = getValue(${s});
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function p0(e,t,r){let n=e.indexOf(t);return e.map((a,s)=>s===n?`${a} - ${r}`:a).join()}function Lm(e){let{inputs:t,backend:r}=e,{input:n}=t,a=r.texData.get(n.dataId);return mn({inputs:{x:a.complexTensorInfos.imag},backend:r})}var lae={kernelName:dh,backendName:"webgl",kernelFunc:Lm};function vu(e,t,r){let n=e[0].dtype;if(n==="complex64"){let d=e.map(f=>Kh({inputs:{input:f},backend:r})),h=e.map(f=>Lm({inputs:{input:f},backend:r})),p=vu(d,t,r),c=vu(h,t,r),m=Hi({inputs:{real:p,imag:c},backend:r});return d.forEach(f=>r.disposeIntermediateTensorInfo(f)),h.forEach(f=>r.disposeIntermediateTensorInfo(f)),r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(c),m}let a=r.shouldExecuteOnCPU(e);if(n==="string"&&(a=!0),a){let d=e.map(y=>{let A=v.sizeFromShape(y.shape.slice(t));return Ae({inputs:{x:y},backend:r,attrs:{shape:[-1,A]}})}),h=d.map(y=>({vals:r.readSync(y.dataId),shape:y.shape})),p=C.computeOutShape(d.map(y=>y.shape),1),c=d[0].shape[0]===1,m=rte(h,p,n,c),f=C.computeOutShape(e.map(y=>y.shape),t),g=r.makeTensorInfo(f,n,m);return d.forEach(y=>r.disposeIntermediateTensorInfo(y)),g}if(e.length>Z().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let d=Math.floor(e.length/2),h=vu(e.slice(0,d),t,r),p=vu(e.slice(d),t,r),c=vu([h,p],t,r);return r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(p),c}if(Z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){let d=new oae(e.map(h=>h.shape),t);return r.runWebGLProgram(d,e,n)}let{tensors2D:s,outShape:i}=uae(e,t,r),o=new iae(s.map(d=>d.shape)),l=r.runWebGLProgram(o,s,n);s.forEach(d=>r.disposeIntermediateTensorInfo(d));let u=Ae({inputs:{x:l},attrs:{shape:i},backend:r});return r.disposeIntermediateTensorInfo(l),u}function uae(e,t,r){let n=C.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>Ae({inputs:{x:a},attrs:{shape:[-1,v.sizeFromShape(a.shape.slice(t))]},backend:r})),outShape:n}}function _I(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n,s=v.parseAxisParam(a,t[0].shape)[0],i=C.computeOutShape(t.map(u=>u.shape),s);if(v.sizeFromShape(i)===0)return r.makeTensorInfo(i,t[0].dtype,[]);let o=t.filter(u=>v.sizeFromShape(u.shape)>0);if(o.length===1)return mn({inputs:{x:o[0]},backend:r});let l=o.map(u=>u.shape);return C.assertParamsConsistent(l,s),vu(o,s,r)}var dae={kernelName:Ho,backendName:"webgl",kernelFunc:_I},PI=class{constructor(e,t=!1,r=null,n=!1,a=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let s=e.padInfo.top,i=e.padInfo.left,o=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,d=e.dilationWidth,h=e.filterHeight,p=e.filterWidth,c=Math.floor(e.inChannels/4)*4,m=e.inChannels%4,f=e.dataFormat==="channelsLast",g=f?1:2,y=f?2:3,A=f?3:1,x="",b="";r&&(n?x=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${r}
|
|
}`:a?x=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${r}
|
|
}`:x=`
|
|
float activation(float x) {
|
|
${r}
|
|
}
|
|
`,b="result = activation(result);");let w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${x}
|
|
|
|
const ivec2 strides = ivec2(${o}, ${l});
|
|
const ivec2 pads = ivec2(${s}, ${i});
|
|
|
|
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 < ${h}; wR++) {
|
|
int xR = xRCorner + wR * ${u};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${p}; wC++) {
|
|
int xC = xCCorner + wC * ${d};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${c}; 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 (${f}) {
|
|
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 (${m===1}) {
|
|
|
|
if (${f}) {
|
|
dotProd +=
|
|
getX(batch, xR, xC, ${c}) *
|
|
getW(wR, wC, ${c}, d2);
|
|
} else {
|
|
dotProd +=
|
|
getX(batch, ${c}, xR, xC) *
|
|
getW(wR, wC, ${c}, d2);
|
|
}
|
|
|
|
} else if (${m===2}) {
|
|
vec2 wValues = vec2(
|
|
getW(wR, wC, ${c}, d2),
|
|
getW(wR, wC, ${c} + 1, d2)
|
|
);
|
|
|
|
if (${f}) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xR, xC, ${c}),
|
|
getX(batch, xR, xC, ${c} + 1)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec2 xValues = vec2(
|
|
getX(batch, ${c}, xR, xC),
|
|
getX(batch, ${c} + 1, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
} else if (${m===3}) {
|
|
vec3 wValues = vec3(
|
|
getW(wR, wC, ${c}, d2),
|
|
getW(wR, wC, ${c} + 1, d2),
|
|
getW(wR, wC, ${c} + 2, d2)
|
|
);
|
|
|
|
if (${f}) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xR, xC, ${c}),
|
|
getX(batch, xR, xC, ${c} + 1),
|
|
getX(batch, xR, xC, ${c} + 2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec3 xValues = vec3(
|
|
getX(batch, ${c}, xR, xC),
|
|
getX(batch, ${c} + 1, xR, xC),
|
|
getX(batch, ${c} + 2, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
${w}
|
|
${b}
|
|
setOutput(result);
|
|
}
|
|
`}},pae=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,r=e.padInfo.top,n=e.padInfo.left,a=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,d=e.filterDepth,h=e.filterHeight,p=e.filterWidth,c=Math.floor(e.inChannels/4)*4,m=e.inChannels%4;this.userCode=`
|
|
const ivec3 strides = ivec3(${a}, ${s}, ${i});
|
|
const ivec3 pads = ivec3(${t}, ${r}, ${n});
|
|
|
|
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 < ${d}; wF++) {
|
|
int xF = xFCorner + wF * ${o};
|
|
|
|
if (xF < 0 || xF >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${h}; wR++) {
|
|
int xR = xRCorner + wR * ${l};
|
|
|
|
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 < ${c}; 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 (${m===1}) {
|
|
dotProd +=
|
|
getX(batch, xF, xR, xC, ${c}) *
|
|
getW(wF, wR, wC, ${c}, d2);
|
|
} else if (${m===2}) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xF, xR, xC, ${c}),
|
|
getX(batch, xF, xR, xC, ${c} + 1)
|
|
);
|
|
vec2 wValues = vec2(
|
|
getW(wF, wR, wC, ${c}, d2),
|
|
getW(wF, wR, wC, ${c} + 1, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else if (${m===3}) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xF, xR, xC, ${c}),
|
|
getX(batch, xF, xR, xC, ${c} + 1),
|
|
getX(batch, xF, xR, xC, ${c} + 2)
|
|
);
|
|
vec3 wValues = vec3(
|
|
getW(wF, wR, wC, ${c}, d2),
|
|
getW(wF, wR, wC, ${c} + 1, d2),
|
|
getW(wF, wR, wC, ${c} + 2, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},hae=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec4"},{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=un(this.outputShape.length);let{dataFormat:r}=t,n=Xr(),a=r==="channelsLast",s=a?1:2,i=a?2:3,o=this.enableShapeUniforms?"if(blockIndex < outShape[2] && pos < outShape[1]) {":`if(blockIndex < ${e[2]} && pos < ${e[1]}) {`,l="";for(let u=0;u<=1;u++)for(let d=0;d<=1;d++)l+=`
|
|
blockIndex = rc.z + ${d};
|
|
pos = rc.y + ${u};
|
|
|
|
${o}
|
|
offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
|
|
d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
|
|
|
|
if(d0 < inputShape[${s}] && 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[${i}] && d1 >= 0) {
|
|
|
|
ch = imod(pos, inChannels);
|
|
|
|
if (${a}) {
|
|
innerDims = vec2(d1, ch);
|
|
result[${u*2+d}] = getChannel(
|
|
getA(rc.x, d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[${u*2+d}] = getChannel(
|
|
getA(rc.x, ch, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
`;this.userCode=`
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0);
|
|
|
|
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
|
|
vec2 innerDims;
|
|
|
|
${l}
|
|
|
|
${n.output} = result;
|
|
}
|
|
`}};function ef(e,t){let r=e.length;return r>=3?t?[...e.slice(0,-3),e[r-3]*e[r-2],e[r-1]]:[...e.slice(0,-3),e[r-3],e[r-2]*e[r-1]]:!t&&r===1&&e[0]>1?[e[0],1]:null}function OI({x:e,filter:t,convInfo:r,backend:n,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=e.shape,u=n.texData.get(e.dataId),d=r.inChannels,h=l[0]*l[1]*l[2],p=r.outChannels,c=r.dataFormat==="channelsLast",m=!1,f=!1,g,y=[];if(s!=null){let A=ef(s.shape,c);A!=null&&(s=Ae({inputs:{x:s},backend:n,attrs:{shape:A}}),y.push(s))}if(a!=null){let A=ef(a.shape,c);A!=null&&(a=Ae({inputs:{x:a},backend:n,attrs:{shape:A}}),y.push(a))}if(!((h===1||p===1)&&d>EI)&&u.isPacked&&c&&u.texture!=null&&l[2]%2!==0&&v.arraysEqual(u.shape.slice(-3),l.slice(-3))){let A=l[0]*l[1]*(l[2]+1),x={dataId:e.dataId,shape:[1,A,r.inChannels],dtype:e.dtype},b=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,v.assert(th(u.shape,x.shape),()=>`packed reshape ${u.shape} to ${x.shape} isn't free`);let w=Ae({inputs:{x:t},backend:n,attrs:{shape:[1,r.inChannels,r.outChannels]}});y.push(w);let I=Q0({a:x,b:w,backend:n,transposeA:m,transposeB:f,bias:a,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),T=n.texData.get(I.dataId);v.assert(T.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=b,T.shape=r.outShape,g=mn({inputs:{x:I},backend:n}),g.shape=r.outShape,y.push(I)}else{let A=r.outHeight*r.outWidth,x=Ae({inputs:{x:e},backend:n,attrs:{shape:c?[r.batchSize,A,r.inChannels]:[r.batchSize,r.inChannels,A]}}),b=Ae({inputs:{x:t},backend:n,attrs:{shape:[1,r.inChannels,r.outChannels]}}),w=Q0({a:c?x:b,b:c?b:x,transposeA:!c,transposeB:f,backend:n,bias:a,activation:o,preluActivationWeights:s,leakyreluAlpha:i});g=Ae({inputs:{x:w},backend:n,attrs:{shape:r.outShape}}),y.push(x),y.push(b),y.push(w)}for(let A of y)n.disposeIntermediateTensorInfo(A);return g}function zI({x:e,filter:t,convInfo:r,backend:n,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let{filterWidth:l,filterHeight:u,inChannels:d,outWidth:h,outHeight:p,dataFormat:c}=r,m=c==="channelsLast",f=l*u*d,g=p*h,y=[r.batchSize,f,g],A=!0,x=!1,b=[];if(s!=null){let Y=ef(s.shape,m);Y!=null&&(s=Ae({inputs:{x:s},backend:n,attrs:{shape:Y}}),b.push(s))}if(a!=null){let Y=ef(a.shape,m);Y!=null&&(a=Ae({inputs:{x:a},backend:n,attrs:{shape:Y}}),b.push(a))}let w=Ae({inputs:{x:t},backend:n,attrs:{shape:[1,f,v.sizeFromShape(t.shape)/f]}});b.push(w);let I=new hae(y,r),T=[e.shape,[r.padInfo.top,r.padInfo.left],[r.strideHeight,r.strideWidth],[r.dilationHeight,r.dilationWidth],[r.inChannels],[r.filterWidth*r.inChannels],[r.outWidth]],E=n.runWebGLProgram(I,[e],"float32",T),R=Ae({inputs:{x:E},backend:n,attrs:{shape:y}});b.push(E),b.push(R);let F=a!=null,$=s!=null,S=o==="leakyrelu",z=o?Om(o,!0):null,O=new NI(m?R.shape:w.shape,m?w.shape:R.shape,m?[r.batchSize,g,r.outChannels]:[r.batchSize,r.outChannels,g],A,x,F,z,$,S),j=m?[R,w]:[w,R];if(a&&j.push(a),$&&j.push(s),S){let Y=n.makeTensorInfo([],"float32",v.createScalarValue(i,"float32"));j.push(Y),b.push(Y)}let K=n.runWebGLProgram(O,j,"float32"),D=Ae({inputs:{x:K},backend:n,attrs:{shape:r.outShape}});b.push(K);for(let Y of b)n.disposeIntermediateTensorInfo(Y);return D}function cae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:d}=n,h=C.convertConv2DDataFormat(l),p=C.computeConv2DInfo(a.shape,s.shape,i,u,o,d,!1,h),c;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"))c=OI({x:a,filter:s,convInfo:p,backend:r});else if(Z().getBool("WEBGL_CONV_IM2COL"))c=zI({x:a,filter:s,convInfo:p,backend:r});else{let f=new PI(p);c=r.runWebGLProgram(f,[a,s],"float32")}let m=Ae({inputs:{x:c},backend:r,attrs:{shape:p.outShape}});return r.disposeIntermediateTensorInfo(c),m}var fae={kernelName:ri,backendName:"webgl",kernelFunc:cae},mae=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,r=e.strideWidth,n=e.padInfo.top,a=e.padInfo.left,s=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} - ${n};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${r} - ${a};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
if (${s}) {
|
|
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);
|
|
}
|
|
`}},gae=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,r=e.filterWidth,n=e.strideHeight,a=e.strideWidth,s=e.dataFormat==="channelsLast",i=t-1-e.padInfo.top,o=r-1-e.padInfo.left,l=s?1:2,u=s?2:3,d=s?3:1;this.userCode=`
|
|
const ivec2 pads = ivec2(${i}, ${o});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[${d}];
|
|
|
|
ivec2 dyCorner = ivec2(coords[${l}], coords[${u}]) - 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) / ${n}.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 < ${r}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${a}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${r} - 1 - wC;
|
|
|
|
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
|
|
|
|
if (${s}) {
|
|
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);
|
|
}
|
|
`}},yae=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,r=e.strideHeight,n=e.strideWidth,a=e.padInfo.front,s=e.padInfo.top,i=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} - ${a};
|
|
|
|
if (xF < 0 || xF >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yR = 0; yR < ${e.outHeight}; yR++) {
|
|
int xR = wR + yR * ${r} - ${s};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${n} - ${i};
|
|
|
|
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);
|
|
}
|
|
`}},Aae=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,r=e.filterHeight,n=e.filterWidth,a=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.front,l=r-1-e.padInfo.top,u=n-1-e.padInfo.left;this.userCode=`
|
|
const ivec3 pads = ivec3(${o}, ${l}, ${u});
|
|
|
|
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) / ${a}.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 < ${r}; 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 = ${r} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${n}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${i}.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++) {
|
|
float xValue = getDy(batch, idyF, idyR, idyC, d2);
|
|
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function xae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:d}=n,h=C.convertConv2DDataFormat(l),p=C.computeConv2DInfo(a.shape,d,i,1,o,u,!1,h),c=new mae(p);return r.runWebGLProgram(c,[a,s],"float32")}var bae={kernelName:cf,backendName:"webgl",kernelFunc:xae};function vae(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:d}=n,h=C.convertConv2DDataFormat(u),p=C.computeConv2DInfo(i,s.shape,o,1,l,d,!1,h),c=new gae(p);return r.runWebGLProgram(c,[a,s],"float32")}var wae={kernelName:ni,backendName:"webgl",kernelFunc:vae};function kae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l}=n,u=C.computeConv3DInfo(a.shape,s.shape,i,l,o),d=new pae(u);return r.runWebGLProgram(d,[a,s],"float32")}var Iae={kernelName:oh,backendName:"webgl",kernelFunc:kae};function Sae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,pad:o,filterShape:l}=n,u=C.computeConv3DInfo(a.shape,l,i,1,o),d=new yae(u);return r.runWebGLProgram(d,[a,s],"float32")}var Cae={kernelName:ff,backendName:"webgl",kernelFunc:Sae};function Tae(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{pad:i,strides:o,inputShape:l}=n,u=C.computeConv3DInfo(l,s.shape,o,1,i),d=new Aae(u);return r.runWebGLProgram(d,[a,s],"float32")}var Nae={kernelName:mf,backendName:"webgl",kernelFunc:Tae},Eae=zd+`
|
|
return cos(x);
|
|
`,Rae=it({opSnippet:Eae}),$ae={kernelName:ai,backendName:"webgl",kernelFunc:Rae},Mae=`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,Fae=it({opSnippet:Mae}),_ae={kernelName:si,backendName:"webgl",kernelFunc:Fae},Pae=class{constructor(e,t,r,n,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[s,i,o,l]=e,[u]=t,[d,h]=r;this.outputShape=[u,d,h,l];let p=n==="bilinear"?1:0,[c,m]=[`${i-1}.0`,`${o-1}.0`],[f,g,y]=d>1?[`${(i-1)/(d-1)}`,"(y2-y1) * height_ratio",`y1*${c} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${c}`],[A,x,b]=h>1?[`${(o-1)/(h-1)}`,"(x2-x1) * width_ratio",`x1*${m} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${m}`];this.userCode=`
|
|
const float height_ratio = float(${f});
|
|
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 >= ${s}) {
|
|
return;
|
|
}
|
|
|
|
float height_scale = ${g};
|
|
float width_scale = ${x};
|
|
|
|
float in_y = ${y};
|
|
if( in_y < 0.0 || in_y > ${c} ) {
|
|
setOutput(float(${a}));
|
|
return;
|
|
}
|
|
float in_x = ${b};
|
|
if( in_x < 0.0 || in_x > ${m} ) {
|
|
setOutput(float(${a}));
|
|
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);
|
|
}
|
|
}
|
|
`}},Oae=e=>{let{inputs:t,backend:r,attrs:n}=e,{image:a,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=n,d=new Pae(a.shape,s.shape,o,l,u);return r.runWebGLProgram(d,[a,s,i],"float32")},zae={kernelName:Xo,backendName:"webgl",kernelFunc:Oae},i7=class{constructor(e,t,r,n){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];let a=this.outputShape.length,s=this.op==="*"?"1.0":"0.0",i=r?s:`getX(${o7(a,"coords",this.op)})`,o=this.outputShape[this.outputShape.length-1],l="",u="";r?(l=n?`end != ${o-1}`:"end != 0",u=n?"end + 1":"end - 1"):(l=n?`end + pow2 < ${o}`:"end >= pow2",u=n?"end + pow2":"end - pow2"),this.userCode=`
|
|
void main() {
|
|
${yt(a)} coords = getOutputCoords();
|
|
int end = ${l7(a,"coords",this.op)};
|
|
float val = ${i};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${l}) {
|
|
int idx = ${u};
|
|
${l7(a,"coords",this.op)} = idx;
|
|
val ${this.op}= getX(${o7(a,"coords",this.op)});
|
|
}
|
|
setOutput(val);
|
|
}
|
|
`}};function o7(e,t,r){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 new Error(`Cumulative ${r} for rank ${e} is not yet supported`)}function l7(e,t,r){if(e===1)return`${t}`;if(e===2)return`${t}.y`;if(e===3)return`${t}.z`;if(e===4)return`${t}.w`;throw new Error(`Cumulative ${r} for rank ${e} is not yet supported`)}function DI(e,t,r,n,a,s){let i=t.shape.length,o=C.getAxesPermutation([n],i),l=t;o!=null&&(l=Gr({inputs:{x:t},backend:r,attrs:{perm:o}}));let u=C.getInnerMostAxes(1,i)[0];if(u!==i-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${n}`);let d=l.shape[u],h=mn({inputs:{x:l},backend:r});for(let p=0;p<=Math.ceil(Math.log2(d))-1;p++){let c=new i7(e,l.shape,!1,s),m=[[p]],f=h;h=r.runWebGLProgram(c,[h],h.dtype,m),r.disposeIntermediateTensorInfo(f)}if(a){let p=new i7(e,l.shape,a,s),c=h;h=r.runWebGLProgram(p,[h],h.dtype),r.disposeIntermediateTensorInfo(c)}if(o!=null){let p=C.getUndoAxesPermutation(o),c=Gr({inputs:{x:h},backend:r,attrs:{perm:p}});return r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(l),c}return h}function Dae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n;return DI("*",a,r,s,i,o)}var Lae={kernelName:qo,backendName:"webgl",kernelFunc:Dae};function Bae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n;return DI("+",a,r,s,i,o)}var Wae={kernelName:ii,backendName:"webgl",kernelFunc:Bae};function Vae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,weights:s}=t,{size:i,binaryOutput:o}=n;if(a.shape.length===1){let l=r.readSync(a.dataId),u=r.readSync(s.dataId),d=gI(l,u,s.dtype,s.shape,i);return r.makeTensorInfo([i],s.dtype,d)}else if(a.shape.length===2){let l=r.bufferSync(a),u=r.bufferSync(s),d=ete(l,u,i,o);return r.makeTensorInfo(d.shape,s.dtype,d.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${a.shape.length}.`)}var Uae={kernelName:gf,backendName:"webgl",kernelFunc:Vae},Gae=class{constructor(e,t,r){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=r,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 jae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockSize:s,dataFormat:i}=n,o=a.shape[0],l=i==="NHWC"?a.shape[1]:a.shape[2],u=i==="NHWC"?a.shape[2]:a.shape[3],d=i==="NHWC"?a.shape[3]:a.shape[1],h=l*s,p=u*s,c=d/(s*s),m=i==="NHWC"?[o,h,p,c]:[o,c,h,p],f=new Gae(m,s,i);return r.runWebGLProgram(f,[a],a.dtype)}var Hae={kernelName:Ko,backendName:"webgl",kernelFunc:jae},LI=class{constructor(e,t=!1,r=null,n=!1,a=!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=un(this.outputShape.length);let s=e.filterHeight,i=e.filterWidth,o=e.outChannels/e.inChannels,l="",u="";r&&(n?l=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${r}
|
|
}`:a?l=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${r}
|
|
}`:l=`
|
|
float activation(float x) {
|
|
${r}
|
|
}
|
|
`,u="result = activation(result);");let d=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),a&&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 / ${o};
|
|
int q = d2 - d1 * ${o};
|
|
|
|
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 < ${s}; wR++) {
|
|
int xR = xRCorner + wR * dilations[0];
|
|
|
|
if (xR < 0 || xR >= inDims[0]) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${i}; 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;
|
|
${d}
|
|
${u}
|
|
setOutput(result);
|
|
}
|
|
`}},BI=class{constructor(e,t=!1,r=null,n=!1,a=!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=un(this.outputShape.length);let s=e.outChannels/e.inChannels,i=e.padInfo.left,o=e.strideWidth,l=e.dilationWidth,u=e.filterHeight,d=e.filterWidth,h=d,p=`
|
|
int xR; int xC; int xCOffset;
|
|
vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<d;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};`;p+=`
|
|
for (int r = 0; r < ${u}; r++) {
|
|
`;for(let g=0;g<d;g++)p+=`
|
|
xTexelC${g*2} = vec4(0.0);
|
|
xTexelC${g*2}Ready = 0;
|
|
xTexelC${g*2+1} = vec4(0.0);
|
|
xTexelC${g*2+1}Ready = 0;
|
|
xC${g} = vec4(0.0);`;p+=`
|
|
xR = xRCorner + r * dilations[0];
|
|
if (xR >=0 && xR < inDims[0]) {
|
|
`;for(let g=0;g<(h+1)/2;g++){let y=g*2;if(p+=`
|
|
xC = xCCorner + ${y*l};
|
|
`,o===1){if(y<d&&(i%2===1?(p+=`
|
|
xCOffset = xC + 1;
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = 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${y}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
`,l===1&&y>0?p+=`
|
|
xC${y} = vec4(xTexelC${y-2}.zw, xTexelC${y}.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${y} = vec4(previous.zw, xTexelC${y}.xy);
|
|
} else {
|
|
xC${y} = vec4(0.0, 0.0, xTexelC${y}.xy);
|
|
}
|
|
`):p+=`
|
|
if (xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${y}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
|
|
xC${y} = xTexelC${y};
|
|
`,y+1<d)){let A=i%2===0?v.nearestLargerEven(l):l;l%2===0&&i%2===1||l%2!==0&&i%2!==1?(p+=`
|
|
xCOffset = xC + imod(pads[1], 2) + ${A};
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
|
|
xTexelC${y+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${y+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y+1}Ready = 1;
|
|
}
|
|
`,l>1&&(p+=`
|
|
xCOffset -= 2;
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = getX(batch, xR, xCOffset, d1);
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
`),p+=`
|
|
xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.xy);
|
|
`):A===1?p+=`
|
|
xC${y+1} = xTexelC${y};
|
|
`:p+=`
|
|
xCOffset = xC + ${A};
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
|
|
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${y+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y+1}Ready = 1;
|
|
}
|
|
|
|
xC${y+1} = xTexelC${y+1};
|
|
`}}else y<d&&(i%2===1?(p+=`
|
|
xCOffset = xC + 1 - strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = 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${y}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
|
|
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${y+1}Ready == 0) {
|
|
xTexelC${y+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${y+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y+1}Ready = 1;
|
|
}
|
|
|
|
xC${y} = vec4(xTexelC${y}.zw, xTexelC${y+1}.zw);
|
|
`,y+1<d&&(p+=`
|
|
final = vec4(0.0);
|
|
xCOffset = xC + 1 + strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
final = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
xC${y+1} = vec4(xTexelC${y+1}.xy, final.xy);
|
|
`)):(p+=`
|
|
if(xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${y}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
|
|
xCOffset = xC + strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
|
|
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${y+1}.zw = vec2(0.);
|
|
}
|
|
xTexelC${y+1}Ready = 1;
|
|
}
|
|
|
|
xC${y} = vec4(
|
|
xTexelC${y}.xy, xTexelC${y+1}.xy);
|
|
`,y+1<d&&(p+=`
|
|
xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.zw);
|
|
`)));y<d&&(p+=`
|
|
wTexel = getW(r, ${y}, d1, q);
|
|
dotProd += xC${y} * vec4(wTexel.xz, wTexel.xz);
|
|
`,y+1<d&&(p+=`
|
|
wTexel = getW(r, ${y+1}, d1, q);
|
|
dotProd += xC${y+1} * vec4(wTexel.xz, wTexel.xz);
|
|
`))}p+=`
|
|
}
|
|
`,p+=`
|
|
}
|
|
`;let c="",m="";r&&(n?c=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${r}
|
|
}`:a?c=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${r}
|
|
}`:c=`vec4 activation(vec4 x) {
|
|
${r}
|
|
}`,m="result = activation(result);");let f=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${c}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int d2 = coords.w;
|
|
int d1 = d2 / ${s};
|
|
int q = d2 - d1 * ${s};
|
|
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);
|
|
${f}
|
|
${m}
|
|
setOutput(result);
|
|
}
|
|
`}};function qae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=n,d=l;d==null&&(d=[1,1]),v.assert(C.eitherStridesOrDilationsAreOne(i,d),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${d}'`);let h=C.computeConv2DInfo(a.shape,s.shape,i,d,o,u,!0),p;Z().getBool("WEBGL_PACK_DEPTHWISECONV")&&h.strideWidth<=2&&h.outChannels/h.inChannels===1?p=new BI(h):p=new LI(h);let c=[[h.padInfo.top,h.padInfo.left],[h.strideHeight,h.strideWidth],[h.dilationHeight,h.dilationWidth],[h.inHeight,h.inWidth]];return r.runWebGLProgram(p,[a,s],"float32",c)}var Xae={kernelName:oi,backendName:"webgl",kernelFunc:qae},Kae=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,r=e.strideWidth,n=e.padInfo.top,a=e.padInfo.left,s=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 * ${s} + 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} - ${n};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${r} - ${a};
|
|
|
|
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);
|
|
}
|
|
`}},Zae=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,r=e.filterWidth,n=e.strideHeight,a=e.strideWidth,s=t-1-e.padInfo.top,i=r-1-e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=`
|
|
const ivec2 pads = ivec2(${s}, ${i});
|
|
|
|
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) / ${n}.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 < ${r}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${a}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${r} - 1 - wC;
|
|
|
|
// TO DO: Vec4 over the channelMul
|
|
for (int dm = 0; dm < ${o}; dm++) {
|
|
int d2 = d1 * ${o} + dm;
|
|
float xValue = getDy(batch, idyR, idyC, d2);
|
|
float wValue = getW(wRPerm, wCPerm, d1, dm);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function Yae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:d}=n,h=C.computeConv2DInfo(a.shape,d,i,o,l,u,!0),p=new Kae(h);return r.runWebGLProgram(p,[a,s],"float32")}var Jae={kernelName:yf,backendName:"webgl",kernelFunc:Yae};function Qae(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:d}=n,h=C.computeConv2DInfo(d,s.shape,i,o,l,u,!0),p=new Zae(h);return r.runWebGLProgram(p,[a,s],"float32")}var ese={kernelName:Af,backendName:"webgl",kernelFunc:Qae},tse=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 rse(e){let{inputs:t,backend:r}=e,{x:n}=t,a=[...n.shape,...n.shape],s=v.sizeFromShape(n.shape),i=Ae({inputs:{x:n},backend:r,attrs:{shape:[s]}}),o=new tse(s),l=r.runWebGLProgram(o,[i],i.dtype),u=Ae({inputs:{x:l},backend:r,attrs:{shape:a}});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(l),u}var nse={kernelName:xf,backendName:"webgl",kernelFunc:rse},ase=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:r,padInfo:n,strideHeight:a,strideWidth:s,filterHeight:i,filterWidth:o,dilationHeight:l,dilationWidth:u}=e,{top:d,left:h}=n;this.userCode=`
|
|
const ivec2 strides = ivec2(${a}, ${s});
|
|
const ivec2 pads = ivec2(${d}, ${h});
|
|
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 < ${i}; h++) {
|
|
int hIn = hBeg + h * ${l};
|
|
|
|
if (hIn >= 0 && hIn < ${t}) {
|
|
for (int w = 0; w < ${o}; w++) {
|
|
int wIn = wBeg + w * ${u};
|
|
|
|
if (wIn >= 0 && wIn < ${r}) {
|
|
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 sse(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l}=n,u=C.computeDilation2DInfo(a.shape,s.shape,i,o,"NHWC",l),d,h=new ase(u);d=r.runWebGLProgram(h,[a,s],"float32");let p=Ae({inputs:{x:d},backend:r,attrs:{shape:u.outShape}});return r.disposeIntermediateTensorInfo(d),p}var ise={kernelName:lh,backendName:"webgl",kernelFunc:sse};function ose(e){let{inputs:t,backend:r,attrs:n}=e,{equation:a}=n,s=t,{allDims:i,summedDims:o,idDims:l}=C.decodeEinsumEquation(a,s.length);C.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:d}=C.getEinsumComputePath(o,l),h=d.length,p=null,c=i.length,m=[];for(let f=0;f<h;++f){for(let g of d[f]){let{permutationIndices:y,expandDims:A}=C.getEinsumPermutation(c,l[g]),x;C.isIdentityPermutation(y)?x=s[g]:(x=Gr({inputs:{x:s[g]},backend:r,attrs:{perm:y}}),m.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=Ae({inputs:{x},backend:r,attrs:{shape:b}}),m.push(x)),p===null?p=x:(p=_A({inputs:{a:x,b:p},backend:r}),m.push(p))}f<h-1&&(u[f]>=0&&(p=Dm({inputs:{x:p},backend:r,attrs:{axis:u[f]-(i.length-c),keepDims:!1}}),m.push(p)),c--)}for(let f of m)f!==p&&r.disposeIntermediateTensorInfo(f);return p}var lse={kernelName:uh,backendName:"webgl",kernelFunc:ose},use="return (x >= 0.0) ? x : (exp(x) - 1.0);",dse=`
|
|
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;
|
|
`,pse=it({opSnippet:use,packedOpSnippet:dse}),hse={kernelName:ui,backendName:"webgl",kernelFunc:pse},cse="return (b >= 1.0) ? a : a * (b + 1.0);",fse=`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,mse=e=>{let{inputs:t,backend:r}=e,{dy:n,y:a}=t,s=Z().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Xh(fse,n.shape,a.shape):new Uu(cse,n.shape,a.shape);return r.runWebGLProgram(s,[n,a],n.dtype)},gse={kernelName:bf,backendName:"webgl",kernelFunc:mse},yse=`
|
|
return vec4(equal(a, b));
|
|
`,Ase="return float(a == b);",xse=wr({opSnippet:Ase,packedOpSnippet:yse,dtype:"bool",cpuKernelImpl:nte}),bse={kernelName:Zo,backendName:"webgl",kernelFunc:xse},vse=`
|
|
// Error function is calculated approximately with elementary function.
|
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
float p = ${C.ERF_P};
|
|
float a1 = ${C.ERF_A1};
|
|
float a2 = ${C.ERF_A2};
|
|
float a3 = ${C.ERF_A3};
|
|
float a4 = ${C.ERF_A4};
|
|
float a5 = ${C.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));
|
|
`,wse=it({opSnippet:vse}),kse={kernelName:rd,backendName:"webgl",kernelFunc:wse},Ise=zd+`
|
|
return exp(x);
|
|
`,Sse=`
|
|
vec4 result = exp(x);
|
|
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;
|
|
`,WI=it({opSnippet:Ise,packedOpSnippet:Sse,cpuKernelImpl:ate,dtype:"float32"}),Cse={kernelName:di,backendName:"webgl",kernelFunc:WI};function xy(e){let{inputs:t,attrs:r,backend:n}=e,{dim:a}=r,{input:s}=t,i=s.shape.length,o=s.shape.slice(),l=a;return a<0&&(v.assert(-(i+1)<=a,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+a+1),o.splice(l,0,1),Ae({inputs:{x:s},backend:n,attrs:{shape:o}})}var Tse={kernelName:Yo,backendName:"webgl",kernelFunc:xy},u7="return exp(x) - 1.0;",Nse=it({opSnippet:u7,packedOpSnippet:u7,cpuKernelImpl:ste}),Ese={kernelName:Jo,backendName:"webgl",kernelFunc:Nse},d7=class{constructor(e,t,r){this.variableNames=["real","imag"];let n=t[1];this.outputShape=t;let a=r?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,s=r?`${n}.0`:"1.0",i;if(e==="real")i="return real * expR - imag * expI;";else if(e==="imag")i="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=`
|
|
const float exponentMultiplier = ${a};
|
|
|
|
float unaryOpComplex(float real, float expR, float imag, float expI) {
|
|
${i}
|
|
}
|
|
|
|
float mulMatDFT(int batch, int index) {
|
|
float indexRatio = float(index) / float(${n});
|
|
float exponentMultiplierTimesIndexRatio =
|
|
exponentMultiplier * indexRatio;
|
|
|
|
float result = 0.0;
|
|
|
|
for (int i = 0; i < ${n}; 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) / ${s};
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
setOutput(mulMatDFT(coords[0], coords[1]));
|
|
}
|
|
`}};function VI(e,t,r){let n=r.texData.get(e.dataId),a=v.sizeFromShape(e.shape),s=e.shape[e.shape.length-1],i=a/s,o=Ae({inputs:{x:e},backend:r,attrs:{shape:[i,s]}}),l=o.shape,u=new d7("real",l,t),d=new d7("imag",l,t),h=[{dataId:n.complexTensorInfos.real.dataId,dtype:n.complexTensorInfos.real.dtype,shape:l},{dataId:n.complexTensorInfos.imag.dataId,dtype:n.complexTensorInfos.imag.dtype,shape:l}],p=r.runWebGLProgram(u,h,"float32"),c=r.runWebGLProgram(d,h,"float32"),m=Hi({inputs:{real:p,imag:c},backend:r});r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(c);let f=Ae({inputs:{x:m},backend:r,attrs:{shape:e.shape}});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(m),f}function Rse(e){let{inputs:t,backend:r}=e,{input:n}=t;return VI(n,!1,r)}var $se={kernelName:vf,backendName:"webgl",kernelFunc:Rse},Mse=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 Zh(e){let{backend:t,attrs:r}=e,{shape:n,value:a}=r,{dtype:s}=r;if(s=s||v.inferDtype(a),s==="string"){let i=v.getArrayFromDType(s,v.sizeFromShape(n));return i.fill(a),t.makeTensorInfo(n,s,i)}else{let i=new Mse(n,a),o=[[a]];return t.runWebGLProgram(i,[],s,o)}}var Fse={kernelName:nd,backendName:"webgl",kernelFunc:Zh},_se=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);
|
|
}
|
|
`}},Pse={kernelName:Qo,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:r}=e,n=t,a=new _se(r.shape);return n.runWebGLProgram(a,[r],r.dtype)}},p7="return floor(x);",Ose=it({opSnippet:p7,packedOpSnippet:p7,cpuKernelImpl:ite}),zse={kernelName:pi,backendName:"webgl",kernelFunc:Ose},Dse=`
|
|
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;
|
|
}
|
|
`,Lse=`
|
|
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);
|
|
`,Bse=wr({opSnippet:Dse,packedOpSnippet:Lse,dtype:"int32"}),Wse={kernelName:hi,backendName:"webgl",kernelFunc:Bse},Vse=class{constructor(e){this.variableNames=["A"];let t=Xr(),[r,n]=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(${n}.0, ${r}.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));
|
|
}
|
|
`}},Use=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=Xr(),[r,n]=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(${n}.0, ${r}.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;
|
|
}
|
|
`}},Gse={kernelName:jp,backendName:"webgl",kernelFunc:jse},mu;function jse(e){let{inputs:t,backend:r,attrs:n}=e,{pixels:a}=t,{numChannels:s}=n,i=typeof HTMLVideoElement!="undefined"&&a instanceof HTMLVideoElement,o=typeof HTMLImageElement!="undefined"&&a instanceof HTMLImageElement,[l,u]=i?[a.videoWidth,a.videoHeight]:[a.width,a.height],d=[u,l],h=[u,l,s];(o||i)&&(mu==null&&(mu=document.createElement("canvas").getContext("2d")),mu.canvas.width=l,mu.canvas.height=u,mu.drawImage(a,0,0,l,u),a=mu.canvas);let p=r.makeTensorInfo(d,"int32");r.texData.get(p.dataId).usage=2,r.gpgpu.uploadPixelDataToTexture(r.getTexture(p.dataId),a);let c=Z().getBool("WEBGL_PACK")?new Use(h):new Vse(h),m=r.runWebGLProgram(c,[p],"int32");return r.disposeData(p.dataId),m}function Hse(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:d,dilations:h,dimRoundingMode:p,activation:c,leakyreluAlpha:m}=n,f=C.convertConv2DDataFormat(d),g=C.computeConv2DInfo(a.shape,s.shape,l,h,u,p,!1,f),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=OI({x:a,filter:s,convInfo:g,backend:r,bias:i,activation:c,preluActivationWeights:o,leakyreluAlpha:m});else if(Z().getBool("WEBGL_CONV_IM2COL"))y=zI({x:a,filter:s,convInfo:g,backend:r,bias:i,activation:c,preluActivationWeights:o,leakyreluAlpha:m});else{let b=i!=null,w=o!=null,I=c==="leakyrelu",T=c?Om(c,!1):null,E=new PI(g,b,T,w,I),R=[a,s],F=($,S)=>{if(S==="NCHW"&&$.shape.length===1&&$.shape[0]!==1){let z=Ae({inputs:{x:$},backend:r,attrs:{shape:[$.shape[0],1,1]}});return A.push(z),z}return $};if(b&&R.push(F(i,d)),w&&R.push(F(o,d)),I){let $=r.makeTensorInfo([],"float32",v.createScalarValue(m,"float32"));R.push($),A.push($)}y=r.runWebGLProgram(E,R,"float32")}let x=Ae({inputs:{x:y},backend:r,attrs:{shape:g.outShape}});return A.push(y),A.forEach(b=>r.disposeIntermediateTensorInfo(b)),x}var qse={kernelName:Os,backendName:"webgl",kernelFunc:Hse};function Xse(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:d,dimRoundingMode:h,activation:p,leakyreluAlpha:c}=n,m=[],f=d;f==null&&(f=[1,1]),v.assert(C.eitherStridesOrDilationsAreOne(l,f),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${f}'`);let g=C.computeConv2DInfo(a.shape,s.shape,l,f,u,h,!0),y=Z().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,A=p?Om(p,y):null,x=[a,s],b=i!=null,w=o!=null,I=p==="leakyrelu";if(b&&x.push(i),w&&x.push(o),I){let F=r.makeTensorInfo([],"float32",v.createScalarValue(c,"float32"));x.push(F),m.push(F)}let T;y?T=new BI(g,b,A,w,I):T=new LI(g,b,A,w,I);let E=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],R=r.runWebGLProgram(T,x,"float32",E);return m.forEach(F=>r.disposeIntermediateTensorInfo(F)),R}var Kse={kernelName:zs,backendName:"webgl",kernelFunc:Xse},Zse=class{constructor(e,t,r,n){this.sliceDim=e,this.strides=t,this.paramsShape=n,this.variableNames=["x","indices"],this.outputShape=r;let a=yt(t.length),s=yt(r.length),i=this.sliceDim>1?"strides[j]":"strides",o=yt(n.length),l=n.length>1?"paramsShape[j]":"paramsShape";this.userCode=`
|
|
${a} strides = ${a}(${this.strides});
|
|
${o} paramsShape = ${o}(${this.paramsShape});
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
int flattenIndex = 0;
|
|
bool out_of_bounds = false;
|
|
for (int j = 0; j < ${this.sliceDim}; j++) {
|
|
int index = round(getIndices(coords[0], j));
|
|
out_of_bounds = out_of_bounds || index < 0;
|
|
out_of_bounds = out_of_bounds || index >= ${l};
|
|
flattenIndex += index * ${i};
|
|
}
|
|
setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));
|
|
}
|
|
`}};function Yse(e){let{inputs:t,backend:r}=e,{params:n,indices:a}=t,s=a.shape,i=s[s.length-1],o=v.sizeFromShape(n.shape),[l,u,d,h]=C.prepareAndValidate(n,a),p=Ae({inputs:{x:a},backend:r,attrs:{shape:[u,i]}}),c=Ae({inputs:{x:n},backend:r,attrs:{shape:[v.sizeFromShape(n.shape)/d,d]}});if(r.shouldExecuteOnCPU([n,a])||n.dtype==="string"){let y=r.readSync(a.dataId),A=r.bufferSync(n),x=ote(y,A,n.dtype,u,i,d,h,n.shape,o);return r.makeTensorInfo(l,n.dtype,x.values)}let m=new Zse(i,h,[u,d],n.shape),f=r.runWebGLProgram(m,[c,p],c.dtype),g=Ae({inputs:{x:f},backend:r,attrs:{shape:l}});return r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),g}var Jse={kernelName:tl,backendName:"webgl",kernelFunc:Yse},Qse=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let r=yt(this.rank),n=eie(e,2);this.userCode=`
|
|
void main() {
|
|
${r} resRC = getOutputCoords();
|
|
int index = int(getIndices(resRC.x, resRC.z));
|
|
float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;
|
|
setOutput(inBounds * getA(${n}));
|
|
}
|
|
`}};function eie(e,t){let r=["resRC.x","resRC.y","resRC.z","resRC.w"],n=[];for(let a=0;a<e.length;a++)a===2?n.push("index"):n.push(`${r[a]}`);return n.join()}function UI(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,indices:s}=t,{axis:i,batchDims:o}=n,l=v.parseAxisParam(i,a.shape)[0];if(Z().get("DEBUG")){let A=r.readSync(s.dataId),x=a.shape[l];for(let b=0;b<A.length;++b){let w=A[b];v.assert(w<=x-1&&w>=0,()=>`GatherV2: the index value ${w} is not in [0, ${x-1}]`)}}let u=C.segment_util.collectGatherOpShapeInfo(a,s,l,o),d=v.sizeFromShape(s.shape),h=[],p=Ae({inputs:{x:a},backend:r,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),c=Ae({inputs:{x:s},backend:r,attrs:{shape:[u.batchSize,d/u.batchSize]}});h.push(p),h.push(c);let m=[u.batchSize,u.outerSize,d/u.batchSize,u.sliceSize];if(r.shouldExecuteOnCPU([a,s])||a.dtype==="string"){let A=r.bufferSync(c),x=r.bufferSync(p),b=lte(x,A,m);return h.forEach(w=>r.disposeIntermediateTensorInfo(w)),r.makeTensorInfo(u.outputShape,b.dtype,b.values)}let f=new Qse(p.shape,m),g=r.runWebGLProgram(f,[p,c],p.dtype);h.push(g);let y=Ae({inputs:{x:g},backend:r,attrs:{shape:u.outputShape}});return h.forEach(A=>r.disposeIntermediateTensorInfo(A)),y}var tie={kernelName:el,backendName:"webgl",kernelFunc:UI},rie="return float(a > b);",nie=`
|
|
return vec4(greaterThan(a, b));
|
|
`,aie=wr({opSnippet:rie,packedOpSnippet:nie,cpuKernelImpl:ute,dtype:"bool"}),sie={kernelName:rl,backendName:"webgl",kernelFunc:aie},iie="return float(a >= b);",oie=`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,lie=wr({opSnippet:iie,packedOpSnippet:oie,dtype:"bool",cpuKernelImpl:dte}),uie={kernelName:fi,backendName:"webgl",kernelFunc:lie};function die(e){let{inputs:t,backend:r}=e,{input:n}=t;return VI(n,!0,r)}var pie={kernelName:wf,backendName:"webgl",kernelFunc:die},hie="return float(!isnan(x) && !isinf(x));",cie=it({opSnippet:hie,dtype:"bool"}),fie={kernelName:ad,backendName:"webgl",kernelFunc:cie},mie="return float(isinf(x));",gie=it({opSnippet:mie,dtype:"bool"}),yie={kernelName:sd,backendName:"webgl",kernelFunc:gie},Aie="return float(isnan(x));",xie=it({opSnippet:Aie,dtype:"bool"}),bie={kernelName:id,backendName:"webgl",kernelFunc:xie},vie="return float(a < b);",wie=`
|
|
return vec4(lessThan(a, b));
|
|
`,kie=wr({opSnippet:vie,packedOpSnippet:wie,cpuKernelImpl:pte,dtype:"bool"}),Iie={kernelName:nl,backendName:"webgl",kernelFunc:kie},Sie="return float(a <= b);",Cie=`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,Tie=wr({opSnippet:Sie,packedOpSnippet:Cie,cpuKernelImpl:hte,dtype:"bool"}),Nie={kernelName:al,backendName:"webgl",kernelFunc:Tie};function Eie(e){let{backend:t,attrs:r}=e,{start:n,stop:a,num:s}=r,i=cte(n,a,s);return t.makeTensorInfo([i.length],"float32",i)}var Rie={kernelName:kf,backendName:"webgl",kernelFunc:Eie},$ie=zd+`
|
|
return x < 0.0 ? 0./0. : log(x);
|
|
`,Mie=`
|
|
vec4 result = log(x);
|
|
bvec4 isNaN = isnan(x);
|
|
result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);
|
|
result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);
|
|
result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);
|
|
result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);
|
|
return result;
|
|
`,Fie=it({opSnippet:$ie,packedOpSnippet:Mie,cpuKernelImpl:fte}),_ie={kernelName:yi,backendName:"webgl",kernelFunc:Fie},Pie=zd+`
|
|
return log(1.0 + x);
|
|
`,Oie=it({opSnippet:Pie}),zie={kernelName:od,backendName:"webgl",kernelFunc:Oie},Die="return float(a >= 1.0 && b >= 1.0);",Lie=`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,Bie=wr({opSnippet:Die,packedOpSnippet:Lie,dtype:"bool"}),Wie={kernelName:sl,backendName:"webgl",kernelFunc:Bie},Vie="return float(!(x >= 1.0));",Uie=it({opSnippet:Vie}),Gie={kernelName:il,backendName:"webgl",kernelFunc:Uie},jie="return float(a >= 1.0 || b >= 1.0);",Hie=`
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`,qie=wr({opSnippet:jie,packedOpSnippet:Hie,dtype:"bool"}),Xie={kernelName:ld,backendName:"webgl",kernelFunc:qie},Kie=class{constructor(e,t,r,n,a){this.variableNames=["x"],this.outputShape=[];let s=t,i=e[3]-1;this.outputShape=e;let o,l=`float(${r}) + float(${n}) * sum`;a===.5?o=`inversesqrt(${l})`:a===1?o=`1.0/(${l})`:o=`exp(log(${l}) * float(-${a}));`,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 = -${s}; j <= ${s}; j++) {
|
|
int idx = d + j;
|
|
if (idx >= 0 && idx <= ${i}) {
|
|
float z = getX(b, r, c, idx);
|
|
sum += z * z;
|
|
}
|
|
}
|
|
float val = x * ${o};
|
|
setOutput(val);
|
|
}
|
|
`}},Zie=class{constructor(e,t,r,n,a){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let s=t,i=e[3]-1;this.outputShape=e;let o,l=`float(${r}) + float(${n}) * sum`;a===.5?o=`inversesqrt(${l})`:a===1?o=`1.0/(${l})`:o=`exp(log(${l}) * float(-${a}));`,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 - ${s};
|
|
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 = - ${s}; j <= ${s}; j++) {
|
|
ivec2 idx = depth + j;
|
|
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
|
|
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${i}));
|
|
|
|
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 * ${o};
|
|
setOutput(result);
|
|
}
|
|
`}},Yie=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n,u=Z().getBool("WEBGL_PACK_NORMALIZATION")?new Zie(a.shape,s,i,o,l):new Kie(a.shape,s,i,o,l);return r.runWebGLProgram(u,[a],a.dtype)},Jie={kernelName:ph,backendName:"webgl",kernelFunc:Yie},Qie=class{constructor(e,t,r,n,a){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=r,this.alpha=n,this.beta=a,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(${n}) * norm + float(${r});
|
|
|
|
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(${n})
|
|
* float(${a})
|
|
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
|
|
/ norm;
|
|
if (k == d) {
|
|
dyi += pow(norm, -1.0 * ${a});
|
|
}
|
|
if (k == coords[3]) {
|
|
dyi *= getDy(b, r, c, d);
|
|
result += dyi;
|
|
}
|
|
}
|
|
else {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}},eoe=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:d}=n,h=new Qie(a.shape,o,l,u,d);return r.runWebGLProgram(h,[a,s,i],a.dtype)},toe={kernelName:If,backendName:"webgl",kernelFunc:eoe};function roe(e,t,r,n){let a=v.sizeFromShape(t),s=v.sizeFromShape(e.shape)/a,i=Ae({inputs:{x:e},attrs:{shape:[s,a]},backend:n}),o=Bl(i,e.dtype,"max",n),l=Ae({inputs:{x:o},attrs:{shape:r},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}function GI(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{reductionIndices:s,keepDims:i}=n,o=a.shape.length,l=v.parseAxisParam(s,a.shape),u=l,d=C.getAxesPermutation(u,o),h=d!=null,p=r.shouldExecuteOnCPU([a]),c=a;if(h){if(p){let A=r.texData.get(c.dataId).values,x=new Array(o);for(let I=0;I<x.length;I++)x[I]=a.shape[d[I]];let b=FA(A,a.shape,a.dtype,d,x);c=r.makeTensorInfo(x,a.dtype);let w=r.texData.get(c.dataId);w.values=b}else c=zm(a,d,r);u=C.getInnerMostAxes(u.length,o)}C.assertAxesAreInnerMostDims("max",u,o);let[m,f]=C.computeOutAndReduceShapes(c.shape,u),g=m;i&&(g=C.expandShapeToKeepDim(m,l));let y;if(p){let A=r.texData.get(c.dataId).values,x=mte(A,v.sizeFromShape(f),g,a.dtype);y=r.makeTensorInfo(g,a.dtype);let b=r.texData.get(y.dataId);b.values=x}else y=roe(c,f,g,r);return h&&r.disposeIntermediateTensorInfo(c),y}var noe={kernelName:Ai,backendName:"webgl",kernelFunc:GI},aoe=kI+`
|
|
return max(a, b);
|
|
`,soe=`
|
|
vec4 result = vec4(max(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Pm+`
|
|
return result;
|
|
`,ioe=wr({opSnippet:aoe,packedOpSnippet:soe,cpuKernelImpl:gte}),ooe={kernelName:xi,backendName:"webgl",kernelFunc:ioe};function loe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t;Md(a,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1;v.assert(C.eitherStridesOrDilationsAreOne(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=C.computePool2DInfo(a.shape,s,i,u,o,l);if(d.filterWidth===1&&d.filterHeight===1&&v.arraysEqual(d.inShape,d.outShape))return mn({inputs:{x:a},backend:r});let h=new rh(d,"max",!1);return r.runWebGLProgram(h,[a],a.dtype)}var uoe={kernelName:bi,backendName:"webgl",kernelFunc:loe};function doe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dataFormat:l,dimRoundingMode:u}=n,d=[1,1,1],h=C.computePool3DInfo(a.shape,s,i,d,o,u,l),p=new PA(h,"max",!1);return r.runWebGLProgram(p,[a],a.dtype)}var poe={kernelName:hh,backendName:"webgl",kernelFunc:doe},hoe=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,r=e.strideWidth,n=e.dilationHeight,a=e.effectiveFilterHeight,s=e.effectiveFilterWidth,i=a-1-e.padInfo.top,o=s-1-e.padInfo.left,l=a*s-1;this.userCode=`
|
|
const ivec2 pads = ivec2(${i}, ${o});
|
|
|
|
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 < ${a};
|
|
wR += ${n}) {
|
|
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 < ${s}; 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);
|
|
|
|
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 * ${s} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},coe=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,r=e.strideHeight,n=e.strideWidth,a=e.dilationDepth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterDepth,l=e.effectiveFilterHeight,u=e.effectiveFilterWidth,d=o-1-e.padInfo.front,h=l-1-e.padInfo.top,p=u-1-e.padInfo.left,c=o*l*u-1;this.userCode=`
|
|
const ivec3 pads = ivec3(${d}, ${h}, ${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 < ${o};
|
|
wD += ${a}) {
|
|
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 += ${s}) {
|
|
float dyR = float(dyRCorner + wR) / ${r}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${u};
|
|
wC += ${i}) {
|
|
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(batch, idyD, idyR, idyC, ch);
|
|
int maxPosValue = ${c} -
|
|
int(getMaxPos(batch, idyD, idyR, idyC, ch));
|
|
|
|
// Get the current value, check it against the value from the
|
|
// position matrix.
|
|
int curPosValue =
|
|
wD * ${l} * ${u} +
|
|
wR * ${u} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function foe(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:d}=n,h=[1,1,1],p=C.computePool3DInfo(i.shape,o,l,h,u,d),c=new PA(p,"max",!0),m=r.runWebGLProgram(c,[i],i.dtype),f=new coe(p),g=r.runWebGLProgram(f,[a,m],i.dtype);return r.disposeIntermediateTensorInfo(m),g}var moe={kernelName:Cf,backendName:"webgl",kernelFunc:foe};function goe(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s,output:i}=t,o=s;Md([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:d,dimRoundingMode:h}=n,p=C.computePool2DInfo(o.shape,l,u,1,d,h),c=!0,m=new rh(p,"max",c),f=r.runWebGLProgram(m,[o],o.dtype),g=new hoe(p),y=r.runWebGLProgram(g,[a,f],o.dtype);return r.disposeIntermediateTensorInfo(f),y}var yoe={kernelName:Sf,backendName:"webgl",kernelFunc:goe};function Aoe(e,t,r,n){let a=new rh(r,"max",!1),s=n.runWebGLProgram(a,[e],"float32");a=new rh(r,"max",!0,!0,t);let i=n.runWebGLProgram(a,[e],"float32");return[s,i]}var xoe={kernelName:Tf,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:n}=e,{filterSize:a,strides:s,pad:i,includeBatchInIndex:o}=t,l=r;v.assert(n.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${n.shape.length}.`);let u=[1,1];v.assert(C.eitherStridesOrDilationsAreOne(s,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);let d=C.computePool2DInfo(n.shape,a,s,u,i),[h,p]=Aoe(n,o,d,l);return[h,p]}};function boe(e,t,r,n){let a=v.sizeFromShape(t),s=v.sizeFromShape(e.shape)/a,i=Ae({inputs:{x:e},attrs:{shape:[s,a]},backend:n}),o=Bl(i,"float32","mean",n),l=Ae({inputs:{x:o},attrs:{shape:r},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}var voe={kernelName:vi,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:n}=e,{keepDims:a,axis:s}=t,i=r,o=n.shape.length,l=v.parseAxisParam(s,n.shape),u=l,d=C.getAxesPermutation(u,o),h=d!=null,p=i.shouldExecuteOnCPU([n]),c=[],m=n;if(h){if(p){let x=i.texData.get(m.dataId).values,b=new Array(o);for(let T=0;T<b.length;T++)b[T]=n.shape[d[T]];let w=FA(x,n.shape,n.dtype,d,b);m=i.makeTensorInfo(b,n.dtype);let I=i.texData.get(m.dataId);I.values=w}else m=zm(n,d,i);c.push(m),u=C.getInnerMostAxes(u.length,o)}C.assertAxesAreInnerMostDims("sum",u,o);let[f,g]=C.computeOutAndReduceShapes(m.shape,u),y=f;a&&(y=C.expandShapeToKeepDim(f,l));let A=boe(m,g,y,i);for(let x of c)i.disposeIntermediateTensorInfo(x);return A}};function woe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n,o=a.shape.length,l=v.parseAxisParam(s,a.shape),u=l,d=C.getAxesPermutation(u,o),h=a;d!=null&&(h=Gr({inputs:{x:a},backend:r,attrs:{perm:d}}),u=C.getInnerMostAxes(u.length,a.shape.length)),C.assertAxesAreInnerMostDims("min",u,o);let[p,c]=C.computeOutAndReduceShapes(h.shape,u),m=v.sizeFromShape(c),f=Ae({inputs:{x:h},backend:r,attrs:{shape:[-1,m]}}),g=Bl(f,f.dtype,"min",r),y;if(i){let A=C.expandShapeToKeepDim(p,l);y=Ae({inputs:{x:g},backend:r,attrs:{shape:A}})}else y=Ae({inputs:{x:g},backend:r,attrs:{shape:p}});return r.disposeIntermediateTensorInfo(f),r.disposeIntermediateTensorInfo(g),d!=null&&r.disposeIntermediateTensorInfo(h),y}var koe={kernelName:wi,backendName:"webgl",kernelFunc:woe},Ioe=kI+`
|
|
return min(a, b);
|
|
`,Soe=`
|
|
vec4 result = vec4(min(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Pm+`
|
|
return result;
|
|
`,Coe=wr({opSnippet:Ioe,packedOpSnippet:Soe,cpuKernelImpl:yte}),Toe={kernelName:ki,backendName:"webgl",kernelFunc:Coe},Noe=class{constructor(e,t,r){this.variableNames=["x"],this.outputShape=t.map((u,d)=>u[0]+e[d]+u[1]);let n=e.length,a=yt(n),s=t.map(u=>u[0]).join(","),i=t.map((u,d)=>u[0]+e[d]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n),l=r==="reflect"?0:1;if(n===1){this.userCode=`
|
|
int start = ${s};
|
|
int end = ${i};
|
|
|
|
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=`
|
|
${a} start = ${a}(${s});
|
|
${a} end = ${a}(${i});
|
|
|
|
void main() {
|
|
${a} outC = getOutputCoords();
|
|
for (int i = 0; i < ${n}; 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};
|
|
}
|
|
}
|
|
${a} coords = outC - start;
|
|
setOutput(getX(${o}));
|
|
}
|
|
`}},Eoe=class{constructor(e,t,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((c,m)=>c[0]+e[m]+c[1]);let n=e.length,a=yt(n),s=t.map(c=>c[0]).join(","),i=t.map((c,m)=>c[0]+e[m]).join(","),o=Wr("rc",n),l=Wr("source",n),u=`${o[n-1]} < ${this.outputShape[n-1]}`,d=n===1?"source":`vec2(${l.slice(-2).join()})`,h=r==="reflect"?0:1,p="";if(n===1){let c=`
|
|
${a} source = rc;
|
|
if (source < start) {
|
|
source = start * 2 - source - ${h};
|
|
} else if (source >= end) {
|
|
source = (end - 1) * 2 - source + ${h};
|
|
}
|
|
source -= start;
|
|
`;p=`
|
|
${a} rc = outputLoc;
|
|
${c}
|
|
result[0] = getChannel(getX(${l.join()}), ${d});
|
|
${o[n-1]} += 1;
|
|
if(${u}) {
|
|
${c}
|
|
result[1] = getChannel(getX(${l.join()}), ${d});
|
|
}
|
|
`}else{let c=`
|
|
${a} source = rc;
|
|
${a} lt = ${a}(lessThan(source, start));
|
|
${a} gte = ${a}(greaterThanEqual(source, end));
|
|
${a} orig = 1 - (lt + gte);
|
|
source = orig * source +
|
|
lt * (start * 2 - source - ${h}) +
|
|
gte * ((end - 1) * 2 - source + ${h});
|
|
source -= start;
|
|
`;p=`
|
|
${a} rc = outputLoc;
|
|
${c}
|
|
result[0] = getChannel(getX(${l.join()}), ${d});
|
|
${o[n-1]} += 1;
|
|
if(${u}) {
|
|
${c}
|
|
result[1] = getChannel(getX(${l.join()}), ${d});
|
|
}
|
|
rc = outputLoc;
|
|
${o[n-2]} += 1;
|
|
if(${o[n-2]} < ${this.outputShape[n-2]}) {
|
|
${c}
|
|
result[2] = getChannel(getX(${l.join()}), ${d});
|
|
${o[n-1]} += 1;
|
|
if(${u}) {
|
|
${c}
|
|
result[3] = getChannel(getX(${l.join()}), ${d});
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
const ${a} start = ${a}(${s});
|
|
const ${a} end = ${a}(${i});
|
|
|
|
void main() {
|
|
${a} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${p}
|
|
setOutput(result);
|
|
}
|
|
`}},Roe=({inputs:e,backend:t,attrs:r})=>{let{x:n}=e,{paddings:a,mode:s}=r,i=Z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Eoe(n.shape,a,s):new Noe(n.shape,a,s);return t.runWebGLProgram(i,[n],n.dtype)},$oe={kernelName:Ii,backendName:"webgl",kernelFunc:Roe},Moe=`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,Foe=`
|
|
vec4 result = mod(a, b);
|
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
|
`+Pm+`
|
|
return result;
|
|
`,_oe=wr({opSnippet:Moe,packedOpSnippet:Foe}),Poe={kernelName:ud,backendName:"webgl",kernelFunc:_oe},Ooe=class{constructor(e,t,r){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,r],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}));
|
|
}
|
|
`}},zoe=`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,Doe=`
|
|
// 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;
|
|
`,jI=wr({opSnippet:zoe,packedOpSnippet:Doe,checkOutOfBounds:!0}),Loe={kernelName:li,backendName:"webgl",kernelFunc:jI},h7="return a - b;",HI=wr({opSnippet:h7,packedOpSnippet:h7,supportsComplex:!0,cpuKernelImpl:_te}),Boe={kernelName:Bi,backendName:"webgl",kernelFunc:HI};function qI(e){let{inputs:t,backend:r,attrs:n}=e,{logits:a}=t,{dim:s}=n,i=v.parseAxisParam([s],a.shape),o=GI({inputs:{x:a},backend:r,attrs:{reductionIndices:i,keepDims:!1}}),l=C.expandShapeToKeepDim(o.shape,i),u=Ae({inputs:{x:o},backend:r,attrs:{shape:l}}),d=HI({inputs:{a,b:u},backend:r}),h=WI({inputs:{x:d},backend:r}),p=Dm({inputs:{x:h},backend:r,attrs:{axis:i,keepDims:!1}}),c=Ae({inputs:{x:p},backend:r,attrs:{shape:l}}),m=jI({inputs:{a:h,b:c},backend:r});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(u),r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(c),m}var Woe={kernelName:Di,backendName:"webgl",kernelFunc:qI};function Voe(e){let{inputs:t,backend:r,attrs:n}=e,{logits:a}=t,{numSamples:s,seed:i,normalized:o}=n,l=o?a:qI({inputs:{logits:a},backend:r,attrs:{dim:a.shape.length-1}}),u=l.shape[0],d=l.shape[1],h=new Ooe(u,d,s),p=[[i]],c=r.runWebGLProgram(h,[l],"int32",p);return o||r.disposeIntermediateTensorInfo(l),c}var Uoe={kernelName:Nf,backendName:"webgl",kernelFunc:Voe},Goe=Yn+`
|
|
return -x;
|
|
`,joe=`
|
|
vec4 result = -x;
|
|
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;
|
|
`;function Hoe(e){let{inputs:t,backend:r}=e,{x:n}=t;if(r.shouldExecuteOnCPU([n])){let s=r.texData.get(n.dataId),[i,o]=xte(s.values,n.shape,n.dtype);return r.makeTensorInfo(o,n.dtype,i)}let a;return Z().getBool("WEBGL_PACK_UNARY_OPERATIONS")?a=new Co(n.shape,joe):a=new Ka(n.shape,Goe),r.runWebGLProgram(a,[n],n.dtype)}var qoe={kernelName:ol,backendName:"webgl",kernelFunc:Hoe},Xoe=Kn.nonMaxSuppressionV3Impl;function Koe(e){C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=n,u=r.readSync(a.dataId),d=r.readSync(s.dataId),{selectedIndices:h}=Xoe(u,d,i,o,l);return r.makeTensorInfo([h.length],"int32",new Int32Array(h))}var Zoe={kernelName:ul,backendName:"webgl",kernelFunc:Koe},Yoe=Kn.nonMaxSuppressionV4Impl;function Joe(e){C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=n,d=r.readSync(a.dataId),h=r.readSync(s.dataId),{selectedIndices:p,validOutputs:c}=Yoe(d,h,i,o,l,u);return[r.makeTensorInfo([p.length],"int32",new Int32Array(p)),r.makeTensorInfo([],"int32",new Int32Array([c]))]}var Qoe={kernelName:dd,backendName:"webgl",kernelFunc:Joe},ele=Kn.nonMaxSuppressionV5Impl;function tle(e){C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=n,d=r.readSync(a.dataId),h=r.readSync(s.dataId),p=i,c=o,m=l,f=u,{selectedIndices:g,selectedScores:y}=ele(d,h,p,c,m,f);return[r.makeTensorInfo([g.length],"int32",new Int32Array(g)),r.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var rle={kernelName:dl,backendName:"webgl",kernelFunc:tle},nle=class{constructor(e,t,r,n){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int index = round(getIndices(coords.x));
|
|
setOutput(mix(float(${n}), float(${r}),
|
|
float(index == coords.y)));
|
|
}
|
|
`}},ale=e=>{let{inputs:t,backend:r,attrs:n}=e,{indices:a}=t,{depth:s,onValue:i,offValue:o}=n,l=v.sizeFromShape(a.shape),u=new nle(l,s,i,o),d=Ae({inputs:{x:a},backend:r,attrs:{shape:[l]}}),h=r.runWebGLProgram(u,[d],a.dtype);r.disposeIntermediateTensorInfo(d);let p=[...a.shape,s],c=Ae({inputs:{x:h},backend:r,attrs:{shape:p}});return r.disposeIntermediateTensorInfo(h),c},sle={kernelName:hl,backendName:"webgl",kernelFunc:ale};function tf(e){let{inputs:t,backend:r}=e,{x:n}=t;if(n.dtype==="complex64"){let a=Kh({inputs:{input:n},backend:r}),s=tf({inputs:{x:a},backend:r}),i=Lm({inputs:{input:n},backend:r}),o=tf({inputs:{x:i},backend:r}),l=Hi({inputs:{real:s,imag:o},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}else return Zh({attrs:{shape:n.shape,dtype:n.dtype,value:n.dtype==="string"?"":0},backend:r})}var ile={kernelName:Nl,backendName:"webgl",kernelFunc:tf};function XI(e){let{inputs:t,backend:r}=e,{x:n}=t;if(n.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(n.dtype==="complex64"){let a=Kh({inputs:{input:n},backend:r}),s=XI({inputs:{x:a},backend:r}),i=Lm({inputs:{input:n},backend:r}),o=tf({inputs:{x:i},backend:r}),l=Hi({inputs:{real:s,imag:o},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}else return Zh({attrs:{shape:n.shape,dtype:n.dtype,value:1},backend:r})}var ole={kernelName:pl,backendName:"webgl",kernelFunc:XI};function lle(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n;if(t.length===1)return xy({inputs:{input:t[0]},backend:r,attrs:{dim:a}});let s=t[0].shape,i=t[0].dtype;t.forEach(d=>{v.assertShapesMatch(s,d.shape,"All tensors passed to stack must have matching shapes"),v.assert(i===d.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(d=>{let h=xy({inputs:{input:d},backend:r,attrs:{dim:a}});return o.push(h),h}),u=_I({inputs:l,backend:r,attrs:{axis:a}});return o.forEach(d=>r.disposeIntermediateTensorInfo(d)),u}var ule={kernelName:cl,backendName:"webgl",kernelFunc:lle},dle=class{constructor(e,t,r){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((l,u)=>l[0]+e[u]+l[1]);let n=e.length,a=yt(n),s=t.map(l=>l[0]).join(","),i=t.map((l,u)=>l[0]+e[u]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n);if(n===1){this.userCode=`
|
|
int start = ${s};
|
|
int end = ${i};
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start || outC >= end) {
|
|
setOutput(value);
|
|
} else {
|
|
setOutput(getX(outC - start));
|
|
}
|
|
}
|
|
`;return}this.userCode=`
|
|
${a} start = ${a}(${s});
|
|
${a} end = ${a}(${i});
|
|
|
|
void main() {
|
|
${a} outC = getOutputCoords();
|
|
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
|
|
setOutput(value);
|
|
} else {
|
|
${a} coords = outC - start;
|
|
setOutput(getX(${o}));
|
|
}
|
|
}
|
|
`}},ple=class{constructor(e,t,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((m,f)=>m[0]+e[f]+m[1]);let n=e.length,a=yt(n),s=t.map(m=>m[0]).join(","),i=t.map((m,f)=>m[0]+e[f]).join(","),o=Wr("rc",n),l=Wr("source",n),u=`${o[n-1]} < ${this.outputShape[n-1]}`,d=n===1?"source":`vec2(${l.slice(-2).join()})`,h=[`${a} rc = outputLoc;`,`${o[n-1]} += 1;
|
|
if(${u}) {
|
|
`,n===1?"":`}
|
|
rc = outputLoc;
|
|
${o[n-2]} += 1;
|
|
if(${o[n-2]} < ${this.outputShape[n-2]}) {`,n===1?"":` ${o[n-1]} += 1;
|
|
if(${u}) {`],p=n===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",c="";for(let m=0,f=n===1?2:4;m<f;m++)c+=`
|
|
${h[m]}
|
|
if (${p}) {
|
|
result[${m}] = float(value);
|
|
} else {
|
|
${a} source = rc - start;
|
|
result[${m}] = getChannel(getX(${l.join()}), ${d});
|
|
}
|
|
`;c+=n===1?"} ":"}}",this.userCode=`
|
|
const ${a} start = ${a}(${s});
|
|
const ${a} end = ${a}(${i});
|
|
|
|
void main() {
|
|
${a} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${c}
|
|
setOutput(result);
|
|
}
|
|
`}},KI=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{paddings:s,constantValue:i}=n;if(v.sizeFromShape(a.shape)===0){let u=s.map((d,h)=>d[0]+a.shape[h]+d[1]);return Zh({backend:r,attrs:{shape:u,value:i,dtype:a.dtype}})}let o=Z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new ple(a.shape,s,i):new dle(a.shape,s,i),l=[[i]];return r.runWebGLProgram(o,[a],a.dtype,l)},hle={kernelName:Ci,backendName:"webgl",kernelFunc:KI},cle=`
|
|
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);
|
|
`,fle=`
|
|
// 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));
|
|
`+Pm+`
|
|
return result;
|
|
`,mle=wr({opSnippet:cle,packedOpSnippet:fle}),gle={kernelName:Ti,backendName:"webgl",kernelFunc:mle};function yle(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n,o=a.shape.length,l=[],u=v.parseAxisParam(s,a.shape),d=u,h=C.getAxesPermutation(d,o),p=a;h!=null&&(p=Gr({inputs:{x:a},backend:r,attrs:{perm:h}}),d=C.getInnerMostAxes(d.length,o),l.push(p)),C.assertAxesAreInnerMostDims("prod",d,o);let c;if(r.shouldExecuteOnCPU([p])){let m=r.texData.get(p.dataId).values,{outVals:f,outShape:g,outDtype:y}=vte(p.shape,p.dtype,m,d);c=r.makeTensorInfo(g,y,f)}else{let[m,f]=C.computeOutAndReduceShapes(p.shape,d),g=v.sizeFromShape(f),y=Ae({inputs:{x:p},backend:r,attrs:{shape:[-1,g]}}),A=wh(a.dtype),x=Bl(y,A,"prod",r);c=Ae({inputs:{x},backend:r,attrs:{shape:m}}),l.push(y),l.push(x)}if(i){l.push(c);let m=C.expandShapeToKeepDim(c.shape,u);c=Ae({inputs:{x:c},backend:r,attrs:{shape:m}})}return l.forEach(m=>r.disposeIntermediateTensorInfo(m)),c}var Ale={kernelName:Ei,backendName:"webgl",kernelFunc:yle},ZI=e=>{let{backend:t,attrs:r}=e,{start:n,stop:a,step:s,dtype:i}=r,o=wte(n,a,s,i);return t.makeTensorInfo([o.length],i,o)},xle={kernelName:pd,backendName:"webgl",kernelFunc:ZI},ble="return 1.0 / x;",vle=it({opSnippet:ble}),wle={kernelName:hd,backendName:"webgl",kernelFunc:vle},kle=Yn+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,Ile=`
|
|
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;
|
|
`,Sle=it({opSnippet:kle,packedOpSnippet:Ile}),Cle={kernelName:Ri,backendName:"webgl",kernelFunc:Sle},Tle=Yn+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,Nle=`
|
|
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;
|
|
`,Ele=it({opSnippet:Tle,packedOpSnippet:Nle}),Rle={kernelName:Mi,backendName:"webgl",kernelFunc:Ele},$le=class{constructor(e,t,r,n,a){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,r,l];let u=[n&&t>1?i-1:i,n&&r>1?o-1:o],d=[n&&t>1?t-1:t,n&&r>1?r-1:r],h;a?h="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":h="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${u[0]/d[0]},
|
|
${u[1]/d[1]});
|
|
const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
ivec2 yRC = coords.yz;
|
|
|
|
// Fractional source index.
|
|
vec2 sourceFracIndexRC = ${h};
|
|
|
|
// 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);
|
|
}
|
|
`}},Mle=class{constructor(e,t,r,n,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,r,l];let u=[n&&t>1?i-1:i,n&&r>1?o-1:o],d=[n&&t>1?t-1:t,n&&r>1?r-1:r],h;a?h="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":h="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${u[0]/d[0]},
|
|
${u[1]/d[1]},
|
|
${u[1]/d[1]});
|
|
const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,
|
|
${o}.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 = ${h};
|
|
|
|
// 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 < ${r-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 Fle(e){let{inputs:t,backend:r,attrs:n}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,d=Z().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Mle(a.shape,l,u,s,i):new $le(a.shape,l,u,s,i);return r.runWebGLProgram(d,[a],"float32")}var _le={kernelName:$i,backendName:"webgl",kernelFunc:Fle},Ple=class{constructor(e,t,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,n,a]=t,[,s,i]=e,o=[r&&s>1?n-1:n,r&&i>1?a-1:a],l=[r&&s>1?s-1:s,r&&i>1?i-1:i],u=o[0]/l[0],d=o[1]/l[1],h=1/u,p=1/d,c=Math.ceil(h)*2+2,m=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(${u});
|
|
const float widthScale = float(${d});
|
|
|
|
const float invHeightScale = float(${h});
|
|
const float invWidthScale = float(${p});
|
|
|
|
const int winHeight = int(${c});
|
|
const int winWidth = int(${m});
|
|
|
|
// 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 >= ${s}) {
|
|
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 >= ${i}) {
|
|
continue;
|
|
}
|
|
|
|
float dxR = float(dyR) * heightScale;
|
|
int topDxRIndex = int(floor(dxR));
|
|
int bottomDxRIndex = int(min(ceil(dxR), ${n-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), ${a-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 Ole(e){let{inputs:t,backend:r,attrs:n}=e,{images:a,dy:s}=t,{alignCorners:i}=n,o=new Ple(s.shape,a.shape,i);return r.runWebGLProgram(o,[s],s.dtype)}var zle={kernelName:Rf,backendName:"webgl",kernelFunc:Ole},Dle=class{constructor(e,t,r,n,a){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,r,l];let u=[n&&t>1?i-1:i,n&&r>1?o-1:o],d=[n&&t>1?t-1:t,n&&r>1?r-1:r],h=n?"0.5":"0.0",p;a?p="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${u[0]/d[0]},
|
|
${u[1]/d[1]});
|
|
const vec2 inputShapeRC = vec2(${i}.0, ${o}.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 + ${h})));
|
|
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}},Lle=class{constructor(e,t,r,n,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,r,l];let u=[n&&t>1?i-1:i,n&&r>1?o-1:o],d=[n&&t>1?t-1:t,n&&r>1?r-1:r],h=n?"0.5":"0.0",p;a?p="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${u[0]/d[0]},
|
|
${u[1]/d[1]},
|
|
${u[1]/d[1]});
|
|
const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,
|
|
${o}.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 + ${h})));
|
|
|
|
// Should we calculate next column and row elements in 2x2 packed cell.
|
|
bool hasNextCol = d < ${l-1};
|
|
bool hasNextRow = coords.z < ${r-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 Ble(e){let{inputs:t,backend:r,attrs:n}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,d=Z().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Lle(a.shape,l,u,s,i):new Dle(a.shape,l,u,s,i);return r.runWebGLProgram(d,[a],a.dtype)}var Wle={kernelName:cd,backendName:"webgl",kernelFunc:Ble},Vle=class{constructor(e,t,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,n,a]=t,[,s,i]=e,o=[r&&s>1?n-1:n,r&&i>1?a-1:a],l=[r&&s>1?s-1:s,r&&i>1?i-1:i],u=o[0]/l[0],d=o[1]/l[1],h=1/u,p=1/d,c=Math.ceil(h)*2+2,m=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(${u});
|
|
const float widthScale = float(${d});
|
|
|
|
const float invHeightScale = float(${h});
|
|
const float invWidthScale = float(${p});
|
|
|
|
const int winHeight = int(${c});
|
|
const int winWidth = int(${m});
|
|
|
|
// 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 >= ${s}) {
|
|
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 >= ${i}) {
|
|
continue;
|
|
}
|
|
|
|
float sourceFracRow =
|
|
float(${o[0]}) *
|
|
(float(dyR) / float(${l[0]}));
|
|
|
|
float sourceFracCol =
|
|
float(${o[1]}) *
|
|
(float(dyC) / float(${l[1]}));
|
|
|
|
int sourceNearestRow = int(min(
|
|
float(int(${n}) - 1),
|
|
${r} ? float(round(sourceFracRow)) :
|
|
float(floor(sourceFracRow))));
|
|
|
|
int sourceNearestCol = int(min(
|
|
float(int(${a}) - 1),
|
|
${r} ? float(round(sourceFracCol)) :
|
|
float(floor(sourceFracCol))));
|
|
|
|
if (r == sourceNearestRow && c == sourceNearestCol) {
|
|
accumulator += getDy(b, dyR, dyC, d);
|
|
}
|
|
}
|
|
}
|
|
// End loop over dy
|
|
|
|
setOutput(accumulator);
|
|
}
|
|
`}};function Ule(e){let{inputs:t,backend:r,attrs:n}=e,{images:a,dy:s}=t,{alignCorners:i}=n,o=new Vle(s.shape,a.shape,i);return r.runWebGLProgram(o,[s],s.dtype)}var Gle={kernelName:Ef,backendName:"webgl",kernelFunc:Ule},jle=class{constructor(e,t){this.variableNames=["x"];let r=e.length;if(r>4)throw new Error(`WebGL backend: Reverse of rank-${r} tensor is not yet supported`);if(this.outputShape=e,r===1){this.userCode=`
|
|
void main() {
|
|
int coord = getOutputCoords();
|
|
setOutput(getX(${e[0]} - coord - 1));
|
|
}
|
|
`;return}let n=i=>t.indexOf(i)!==-1&&e[i]!==1?`${e[i]} - coords[${i}] - 1`:`coords[${i}]`,a=e.map((i,o)=>n(o)).join(","),s=yt(r);this.userCode=`
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
setOutput(getX(${a}));
|
|
}
|
|
`}},Hle=class{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let r=e.length;if(r>4)throw new Error(`WebGL backend: Reverse of rank-${r} tensor is not yet supported`);this.outputShape=e;let n=Wr("rc",r),a=`${n[r-1]} + 1 < ${this.outputShape[r-1]}`,s=`${n[r-2]} + 1 < ${this.outputShape[r-2]}`,i=yt(r);r===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(${a}){
|
|
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
|
|
${e[0]} - (rc + 1) - 1);
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`:this.userCode=`
|
|
void main() {
|
|
${i} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result.r = ${o(n.slice())};
|
|
if(${a}){
|
|
result.g = ${l(n.slice())};
|
|
}
|
|
if(${s}) {
|
|
result.b = ${u(n.slice())};
|
|
if(${a}) {
|
|
result.a = ${d(n.slice())};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`;function o(c){return h(c)}function l(c){return c[r-1]="("+c[r-1]+" + 1)",h(c)}function u(c){return c[r-2]="("+c[r-2]+" + 1)",h(c)}function d(c){return c[r-1]="("+c[r-1]+" + 1)",c[r-2]="("+c[r-2]+" + 1)",h(c)}function h(c){let m=e.map((y,A)=>p(A,c)),f=m.join(","),g=m.slice(-2).join(",");return`getChannel(getX(${f}), vec2(${g}))`}function p(c,m){return t.indexOf(c)!==-1&&e[c]!==1?`${e[c]} - ${m[c]} - 1`:`${m[c]}`}}};function qle(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{dims:s}=n,i=a.shape.length,o=v.parseAxisParam(s,a.shape);if(i===0)return mn({inputs:{x:a},backend:r});let l=Z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Hle(a.shape,o):new jle(a.shape,o);return r.runWebGLProgram(l,[a],a.dtype)}var Xle={kernelName:ml,backendName:"webgl",kernelFunc:qle},Kle=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let r=e[1],n=e[2];this.outputShape=e;let a="";typeof t=="number"?a=`float outputValue = ${t.toFixed(2)};`:a=`
|
|
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]));
|
|
${a}
|
|
if(coordX >= 0 && coordX < ${n} && coordY >= 0 && coordY < ${r}) {
|
|
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}},Zle={kernelName:El,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{image:n}=e,{radians:a,fillValue:s,center:i}=t,o=r,l=new Kle(n.shape,s),[u,d]=C.getImageCenter(i,n.shape[1],n.shape[2]),h=[[u,d,Math.sin(a),Math.cos(a)]];return o.runWebGLProgram(l,[n],n.dtype,h)}},Yle=`
|
|
// 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;
|
|
}
|
|
}
|
|
`,Jle=it({opSnippet:Yle}),Qle={kernelName:gl,backendName:"webgl",kernelFunc:Jle},eue="return inversesqrt(x);",tue=it({opSnippet:eue,cpuKernelImpl:kte}),rue={kernelName:Fi,backendName:"webgl",kernelFunc:tue},YI=class{constructor(e,t,r,n,a,s,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;let o=yt(a.length),l=yt(s.length),u="";r===1?u="i":r===2&&(u="i, j");let d=`getIndices(${u})`,h="";n===1?h="i":n===2&&(h="i, coords[1]");let p=`getUpdates(${h})`,c=t>1?"strides[j]":"strides";this.userCode=`
|
|
${o} strides = ${o}(${a});
|
|
|
|
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(${d});
|
|
flattenedIndex += index * ${c};
|
|
}
|
|
if (flattenedIndex == coords[0]) {
|
|
sum += ${p};
|
|
found = true;
|
|
}
|
|
}
|
|
setOutput(mix(getDefaultValue(), sum, float(found)));
|
|
}
|
|
`}};function nue(e){let{inputs:t,backend:r,attrs:n}=e,{indices:a,updates:s}=t,{shape:i}=n,{sliceRank:o,numUpdates:l,sliceSize:u,strides:d,outputSize:h}=C.calculateShapes(s,a,i),p=[h/u,u];if(h===0)return r.makeTensorInfo(i,a.dtype);let c=Ae({inputs:{x:a},backend:r,attrs:{shape:[l,o]}}),m=Ae({inputs:{x:s},backend:r,attrs:{shape:[l,u]}}),f=r.makeTensorInfo([],"float32",new Float32Array([0])),g=new YI(l,o,c.shape.length,m.shape.length,d,p),y=r.runWebGLProgram(g,[m,c,f],m.dtype),A=Ae({inputs:{x:y},backend:r,attrs:{shape:i}});return r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(y),r.disposeIntermediateTensorInfo(f),A}var aue={kernelName:yl,backendName:"webgl",kernelFunc:nue},sue=class{constructor(e,t,r,n){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,r];let a="while (left < right) {",s=`for (int i = 0; i < ${Math.ceil(Math.log2(t+1))}; ++i) { if (left >= right) break;`,i=Z().getNumber("WEBGL_VERSION")===2?a:s,o=n==="left"?"<":"<=";this.userCode=`
|
|
int findBound(int batch, float value) {
|
|
int left = 0;
|
|
int right = numInputs;
|
|
int mid;
|
|
${i}
|
|
mid = (left + right) / 2;
|
|
if (getSortedSequence(batch, mid) ${o} value) {
|
|
left = mid + 1;
|
|
} else {
|
|
right = mid;
|
|
}
|
|
}
|
|
return right;
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int valueIndex = coords[1];
|
|
|
|
float value = getValues(batch, valueIndex);
|
|
|
|
setOutput(float(findBound(batch, value)));
|
|
}
|
|
`}};function iue(e){let{inputs:t,backend:r,attrs:n}=e,{sortedSequence:a,values:s}=t,{side:i}=n,o=new sue(a.shape[0],a.shape[1],s.shape[1],i),l=[[a.shape[1]]];return r.runWebGLProgram(o,[a,s],"int32",l)}var oue={kernelName:$f,backendName:"webgl",kernelFunc:iue},lue=class{constructor(e,t,r){this.variableNames=["c","a","b"],this.outputShape=t;let n,a;if(r>4)throw Error(`Where for rank ${r} is not yet supported`);if(r===1)a="resRC",n="resRC";else{let i=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],l=[];for(let u=0;u<t.length;u++)l.push(`${i[u]}`),u<e&&o.push(`${i[u]}`);n=o.join(),a=l.join()}let s=yt(r);this.userCode=`
|
|
void main() {
|
|
${s} resRC = getOutputCoords();
|
|
float cVal = getC(${n});
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(${a}));
|
|
} else {
|
|
setOutput(getB(${a}));
|
|
}
|
|
}
|
|
`}};function uue(e){let{inputs:t,backend:r}=e,{condition:n,t:a,e:s}=t,i=new lue(n.shape.length,a.shape,a.shape.length);return r.runWebGLProgram(i,[n,a,s],Nr(a.dtype,s.dtype))}var due={kernelName:Al,backendName:"webgl",kernelFunc:uue},pue=`
|
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
|
// see: https://arxiv.org/abs/1706.02515
|
|
float scaleAlpha = ${C.SELU_SCALEALPHA};
|
|
float scale = ${C.SELU_SCALE};
|
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
|
`,hue=it({opSnippet:pue}),cue={kernelName:fd,backendName:"webgl",kernelFunc:hue},fue=zd+`
|
|
return 1.0 / (1.0 + exp(-1.0 * x));
|
|
`,mue=`
|
|
vec4 result = 1.0 / (1.0 + exp(-1.0 * x));
|
|
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;
|
|
`,gue=it({opSnippet:fue,packedOpSnippet:mue,cpuKernelImpl:Ste}),yue={kernelName:Pi,backendName:"webgl",kernelFunc:gue},Aue=`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`,xue=it({opSnippet:Aue}),bue={kernelName:md,backendName:"webgl",kernelFunc:xue},vue=zd+`
|
|
return sin(x);
|
|
`,wue=it({opSnippet:vue}),kue={kernelName:_i,backendName:"webgl",kernelFunc:wue},Iue=`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,Sue=it({opSnippet:Iue}),Cue={kernelName:bl,backendName:"webgl",kernelFunc:Sue},Tue=`
|
|
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;
|
|
`,Nue=it({opSnippet:Tue}),Eue={kernelName:gd,backendName:"webgl",kernelFunc:Nue},Rue=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,paddings:i}=n;v.assert(a.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((y,A)=>y*A),l=[[0,0]];l.push(...i);for(let y=1+s.length;y<a.shape.length;++y)l.push([0,0]);let u=[],d=KI({inputs:{x:a},backend:r,attrs:{paddings:l,constantValue:0}}),h=C.getReshaped(d.shape,s,o,!1),p=C.getPermuted(h.length,s.length,!1),c=C.getReshapedPermuted(d.shape,s,o,!1),m=Ae({inputs:{x:d},backend:r,attrs:{shape:h}}),f=Gr({inputs:{x:m},backend:r,attrs:{perm:p}}),g=Ae({inputs:{x:f},backend:r,attrs:{shape:c}});return u.push(d),u.push(m),u.push(f),u.forEach(y=>r.disposeIntermediateTensorInfo(y)),g},$ue={kernelName:vl,backendName:"webgl",kernelFunc:Rue};function Mue(e){let{inputs:t,backend:r}=e,{indices:n,values:a,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
|
|
${s.shape}`);if(n.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
|
|
${n.shape}`);if(a.shape.length!==1)throw new Error(`Values must be a vector, saw:
|
|
${a.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${i.shape}`);let o=r.readSync(n.dataId),l=r.readSync(a.dataId),u=r.readSync(s.dataId),d=r.readSync(i.dataId)[0],[h,p,c,m,f]=Tte(o,n.shape,n.dtype,l,a.dtype,u,d);return[r.makeTensorInfo(p,n.dtype,h),r.makeTensorInfo([p[0]],a.dtype,c),r.makeTensorInfo([m.length],"bool",new Uint8Array(m.map(g=>Number(g)))),r.makeTensorInfo([f.length],n.dtype,new Int32Array(f))]}var Fue={kernelName:fh,backendName:"webgl",kernelFunc:Mue};function _ue(e){let{inputs:t,backend:r}=e,{inputIndices:n,inputShape:a,newShape:s}=t;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${n.shape}`);if(a.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${a.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(r.readSync(a.dataId)),o=r.readSync(n.dataId),l=Array.from(r.readSync(s.dataId)),[u,d,h]=Nte(o,n.shape,n.dtype,i,l);return[r.makeTensorInfo(d,n.dtype,u),r.makeTensorInfo([h.length],s.dtype,new Int32Array(h))]}var Pue={kernelName:yd,backendName:"webgl",kernelFunc:_ue};function Oue(e){let{inputs:t,backend:r}=e,{data:n,indices:a,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${a.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);let i=r.readSync(n.dataId),o=r.readSync(a.dataId),l=r.readSync(s.dataId),[u,d]=AI(i,n.shape,n.dtype,o,l,!0);return r.makeTensorInfo(d,n.dtype,u)}var zue={kernelName:mh,backendName:"webgl",kernelFunc:Oue};function Due(e){let{inputs:t,backend:r}=e,{data:n,indices:a,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${a.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);let i=r.readSync(n.dataId),o=r.readSync(a.dataId),l=r.readSync(s.dataId),[u,d]=AI(i,n.shape,n.dtype,o,l);return r.makeTensorInfo(d,n.dtype,u)}var Lue={kernelName:gh,backendName:"webgl",kernelFunc:Due};function Bue(e){let{inputs:t,backend:r,attrs:n}=e,{sparseIndices:a,sparseValues:s,defaultValue:i}=t,{outputShape:o}=n,{sliceRank:l,numUpdates:u,sliceSize:d,strides:h,outputSize:p}=C.calculateShapes(s,a,o),c=!1;if(s.dtype==="string"){let y=r.bufferSync(a),A=r.bufferSync(s),x=v.decodeString(r.readSync(i.dataId)[0]),b=Ite(y,A,o,p,d,u,l,h,x,c);return r.makeTensorInfo(o,b.dtype,b.values)}let m=new YI(u,l,a.shape.length,s.shape.length,h,[p,1],c),f=r.runWebGLProgram(m,[s,a,i],s.dtype),g=Ae({inputs:{x:f},backend:r,attrs:{shape:o}});return r.disposeIntermediateTensorInfo(f),g}var Wue={kernelName:yh,backendName:"webgl",kernelFunc:Bue};function Vue(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{numOrSizeSplits:s,axis:i}=n,o=v.parseAxisParam(i,a.shape)[0],l=C.prepareSplitSize(a,s,o),u=a.shape.length,d=new Array(u).fill(0),h=a.shape.slice();return l.map(p=>{let c=[...h];c[o]=p;let m=Dd({inputs:{x:a},backend:r,attrs:{begin:d,size:c}});return d[o]+=p,m})}var Uue={kernelName:wl,backendName:"webgl",kernelFunc:Vue},c7="return sqrt(x);",Gue=it({opSnippet:c7,packedOpSnippet:c7,cpuKernelImpl:Ete}),jue={kernelName:Oi,backendName:"webgl",kernelFunc:Gue},Hue="return x * x;",que=it({opSnippet:Hue}),Xue={kernelName:Ad,backendName:"webgl",kernelFunc:que},f7="return (a - b) * (a - b);",Kue=wr({opSnippet:f7,packedOpSnippet:f7}),Zue={kernelName:Li,backendName:"webgl",kernelFunc:Kue};function Yue({inputs:e,attrs:t,backend:r}){let{x:n}=e,a=Yn+`
|
|
return x > 0.0 ? 1.0 : float(${t.alpha});
|
|
`,s=new Ka(n.shape,a);return r.runWebGLProgram(s,[n],n.dtype)}var Jue={kernelName:Vi,backendName:"webgl",kernelFunc:Yue},Que=class{constructor(e,t,r){this.variableNames=["x"],this.outputShape=r;let n=r.length,a=yt(r.length),s=yt(r.length),i="";if(n===1)i="coords * strides + begin";else{let o=0;i=r.map((l,u)=>(o++,r.length===1?`coords * strides[${u}] + begin[${u}]`:`coords[${o-1}] * strides[${u}] + begin[${u}]`)).join(",")}this.userCode=`
|
|
${a} begin = ${a}(${e});
|
|
${a} strides = ${a}(${t});
|
|
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
setOutput(getX(${i}));
|
|
}
|
|
`}};function ede(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:d,newAxisMask:h,shrinkAxisMask:p}=n,{finalShapeSparse:c,finalShape:m,isIdentity:f,sliceDim0:g,isSimpleSlice:y,begin:A,end:x,strides:b}=Dt.sliceInfo(a.shape,s,i,o,l,u,d,h,p),w;if(f)w=Ae({inputs:{x:a},backend:r,attrs:{shape:m}});else if(g||y){v.assert(a.shape.length>=1,()=>`Input must have rank at least 1, got: ${a.shape.length}`);let T=Dt.computeOutShape(A,x,b),E=Dd({inputs:{x:a},backend:r,attrs:{begin:A,size:T}});w=Ae({inputs:{x:E},backend:r,attrs:{shape:m}}),r.disposeIntermediateTensorInfo(E)}else if(r.shouldExecuteOnCPU([a])){let T=r.readSync(a.dataId),E=De(a.shape,a.dtype,T),R=Rte(c,E,b,A);w=r.makeTensorInfo(m,a.dtype,R.values)}else{let T=new Que(A,b,c);w=r.runWebGLProgram(T,[a],a.dtype)}let I=Ae({inputs:{x:w},backend:r,attrs:{shape:m}});return r.disposeIntermediateTensorInfo(w),I}var tde={kernelName:kl,backendName:"webgl",kernelFunc:ede};function rde(e){let{inputs:t,backend:r,attrs:n}=e,{separator:a,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=n,{data:d,dataSplits:h}=t,p=r.readSync(d.dataId),c=r.readSync(h.dataId),[m,f]=$te(p,c,a,s,i,o,l,u);return[r.makeTensorInfo([m.length],"string",m),r.makeTensorInfo(h.shape,"int32",f)]}var nde={kernelName:Ah,backendName:"webgl",kernelFunc:rde};function ade(e){let{inputs:t,backend:r,attrs:n}=e,{skipEmpty:a}=n,{input:s,delimiter:i}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let o=r.readSync(s.dataId),l=r.readSync(i.dataId)[0],[u,d,h]=Mte(o,l,a),p=d.length;return[r.makeTensorInfo([p,2],"int32",u),r.makeTensorInfo([p],"string",d),r.makeTensorInfo([2],"int32",new Int32Array(h))]}var sde={kernelName:Mf,backendName:"webgl",kernelFunc:ade};function ide(e){let{inputs:t,backend:r,attrs:n}=e,{numBuckets:a}=n,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(a<=0)throw new Error("Number of buckets must be at least 1");let i=r.readSync(s.dataId),o=Fte(i,a);return r.makeTensorInfo(s.shape,"int32",o)}var ode={kernelName:Ff,backendName:"webgl",kernelFunc:ide},lde="return tan(x);",ude=it({opSnippet:lde}),dde={kernelName:Il,backendName:"webgl",kernelFunc:ude},pde=`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,hde=it({opSnippet:pde}),cde={kernelName:Wi,backendName:"webgl",kernelFunc:hde},fde=class{constructor(e,t){this.variableNames=["A"];let r=new Array(e.length);for(let s=0;s<r.length;s++)r[s]=e[s]*t[s];this.outputShape=r,this.rank=r.length;let n=yt(this.rank),a=mde(e);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${a}));
|
|
}
|
|
`}};function mde(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 r=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],n=[];for(let a=0;a<e.length;a++)n.push(`imod(${r[a]}, ${e[a]})`);return n.join()}function JI(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{reps:s}=n;if(a.dtype==="string"||a.shape.length>5){let o=r.readSync(a.dataId),l=a.dtype==="string"?o.map(h=>v.decodeString(h)):o,u=De(a.shape,a.dtype,l),d=Pte(u,s);return r.makeTensorInfo(d.shape,d.dtype,d.values)}let i=new fde(a.shape,s);return r.runWebGLProgram(i,[a],a.dtype)}var gde={kernelName:ts,backendName:"webgl",kernelFunc:JI},yde=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));
|
|
}
|
|
}
|
|
`}},Ade=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 go(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function m7(e){let t=1;for(;t<e;)t*=2;return t}function xde(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{k:s,sorted:i}=n,o=Z().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),l=Z().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),u=a.shape,d=u[u.length-1];if(r.shouldExecuteOnCPU([a])||d<o||s>l){let R=r.readSync(a.dataId),[F,$]=Ote(R,u,a.dtype,s,i);return[r.makeTensorInfo(F.shape,F.dtype,F.values),r.makeTensorInfo($.shape,$.dtype,$.values)]}if(s===0)return u[u.length-1]=0,[r.makeTensorInfo(u,a.dtype,[]),r.makeTensorInfo(u,"int32",[])];if(d===1)return[a,Zh({attrs:{shape:u,dtype:"int32",value:0},backend:r})];let h=r.texData.get(a.dataId),p=h!==null&&h.isPacked,c=p?r.unpackTensor(a):a,m=v.sizeFromShape(u)/d,f=Ae({inputs:{x:c},attrs:{shape:[m,d]},backend:r});p&&go(r,c);let g=m7(s),y=m7(d),A=null,x=()=>A===null?[f,f]:[f,A],b=(R,F,$)=>{let S=x(),z=new yde($),O=[[d],[A===null?1:0],[Number.NEGATIVE_INFINITY],[R],[F]],j=A;A=r.runWebGLProgram(z,S,"int32",O),go(r,j)};for(let R=1;R<g;R*=2){let F=R*2;for(let $=R;$>=1;$/=2)b(F,$,[m,y])}for(let R=y;R>g;R/=2){let F=x(),$=new Ade([m,R/2]),S=[[d],[A===null?1:0],[g]],z=A;A=r.runWebGLProgram($,F,"int32",S),go(r,z);let O=g/2,j=O*2;for(let K=O;K>=1;K/=2)b(j,K,A.shape)}let w=A;A=Dd({inputs:{x:A},backend:r,attrs:{begin:0,size:[m,s]}}),go(r,w);let I=UI({inputs:{x:f,indices:A},backend:r,attrs:{axis:1,batchDims:1}});go(r,f);let T=u.slice(0,-1);T.push(s),w=A,A=Ae({inputs:{x:A},attrs:{shape:T},backend:r}),go(r,w);let E=I;return I=Ae({inputs:{x:I},attrs:{shape:T},backend:r}),go(r,E),[I,A]}var bde={kernelName:Sl,backendName:"webgl",kernelFunc:xde},vde=class{constructor(e,t,r,n,a,s){this.variableNames=["Image","Transforms"],this.outputShape=s;let i=r==="nearest"?1:2,o;switch(n){case"constant":o=1;break;case"reflect":o=2;break;case"wrap":o=3;break;case"nearest":o=4;break;default:o=1;break}this.userCode=`
|
|
float mapCoord(float outCoord, float len) {
|
|
float inCoord = outCoord;
|
|
if(${o} == 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 (${o} == 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 (${o} == 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(${a});
|
|
}
|
|
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(${a});
|
|
} 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 (${i} == 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 wde(e){let{inputs:t,backend:r,attrs:n}=e,{image:a,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=n,[d,h,p,c]=a.shape,[m,f]=u!=null?u:[h,p],g=[d,m,f,c],y=new vde(h,p,i,o,l,g);return r.runWebGLProgram(y,[a,s],"float32")}var kde={kernelName:Cl,backendName:"webgl",kernelFunc:wde};function Ide(e){let{inputs:t,attrs:r,backend:n}=e,{axis:a}=r,{x:s}=t;Md(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let i=n.readSync(s.dataId),{outputValues:o,outputShape:l,indices:u}=zte(i,a,s.shape,s.dtype);return[n.makeTensorInfo(l,s.dtype,o),n.makeTensorInfo([u.length],"int32",u)]}var Sde={kernelName:_f,backendName:"webgl",kernelFunc:Ide};function Cde(e){let{inputs:t,backend:r,attrs:n}=e,{value:a}=t,{axis:s}=n;s<0&&(s+=a.shape.length);let i=a,o=i.shape.length,l=a.shape[s],u=new Array(o-1),d=0;for(let f=0;f<o;f++)f!==s&&(u[d++]=i.shape[f]);let h=[],p=new Array(o).fill(0),c=i.shape.slice();c[s]=1;let m=new Array(l);for(let f=0;f<m.length;f++){p[s]=f;let g=Dd({inputs:{x:i},backend:r,attrs:{begin:p,size:c}}),y=Ae({inputs:{x:g},backend:r,attrs:{shape:u}});m[f]=y,h.push(g)}return h.forEach(f=>r.disposeIntermediateTensorInfo(f)),m}var Tde={kernelName:Tl,backendName:"webgl",kernelFunc:Cde},Nde=class{constructor(e,t){this.variableNames=["x","segmentIds"];let r=e.windowSize,n=e.batchSize,a=e.inSize,s=e.numSegments,i=s*Math.ceil(a/r);this.outputShape=[n,i];let o="0.0",l="sumValue",u=Math.floor(r/4)*4,d=r%4,h=`
|
|
sumValue += dot(values, segFilter);
|
|
`,p="";a%r>0&&(p=`
|
|
if (inIdx < 0 || inIdx >= ${a}) {
|
|
return initializationValue;
|
|
}
|
|
`);let c="";a%r>0&&(c=`
|
|
if (inIdx < 0 || inIdx >= ${a}) {
|
|
return -1.0;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = ${o};
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${p}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
float getSegmentIdAtIndex(int inIdx) {
|
|
${c}
|
|
return getSegmentIds(inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = int(floor(float(outIdx) / float(
|
|
${s})) * float(${r}));
|
|
int currentSeg = int(mod(float(outIdx), float(${s})));
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < ${u}; 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
|
|
);
|
|
|
|
${h}
|
|
}
|
|
|
|
int inIdx = inOffset + ${u};
|
|
if (${d===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
|
|
);
|
|
|
|
${h}
|
|
} else if (${d===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
|
|
);
|
|
|
|
${h}
|
|
} else if (${d===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
|
|
);
|
|
|
|
${h}
|
|
}
|
|
setOutput(${l});
|
|
}
|
|
`}};function Ede(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,segmentIds:s}=t,{numSegments:i}=n,o=a.shape.length,l=[],u=0,d=C.getAxesPermutation([u],o),h=a;d!=null&&(h=Gr({inputs:{x:a},backend:r,attrs:{perm:d}}),l.push(h),u=C.getInnerMostAxes(1,o)[0]);let p=C.segment_util.computeOutShape(h.shape,u,i),c=v.sizeFromShape([h.shape[u]]),m=Ae({inputs:{x:h},backend:r,attrs:{shape:[-1,c]}});l.push(m);let f=wh(a.dtype),g=(b,w,I,T,E)=>{let R=b.shape[0],F=b.shape[1],$=C.segment_util.segOpComputeOptimalWindowSize(F,E),S={windowSize:$,inSize:F,batchSize:R,numSegments:E},z=new Nde(S,w),O=r.compileAndRun(z,[b,I],T);if(l.push(O),O.shape[1]===E)return O;let j=ZI({backend:r,attrs:{start:0,stop:E,step:1,dtype:"float32"}}),K=JI({inputs:{x:j},backend:r,attrs:{reps:[F/$]}});return l.push(j),l.push(K),g(O,w,K,T,E)},y=g(m,"unsortedSegmentSum",s,f,i),A=Ae({inputs:{x:y},backend:r,attrs:{shape:p}}),x=A;if(d!=null){l.push(A);let b=C.getUndoAxesPermutation(d);x=Gr({inputs:{x},backend:r,attrs:{perm:b}})}return l.forEach(b=>r.disposeIntermediateTensorInfo(b)),x}var Rde={kernelName:xh,backendName:"webgl",kernelFunc:Ede},$de=[Mre,_re,zre,Bre,Vre,jre,qre,Kre,Qre,tne,ane,one,dne,fne,yne,xne,vne,Sne,Tne,Ene,Fne,Bne,Vne,Gne,Zne,Jne,rae,cre,sae,dae,fae,bae,wae,Iae,Cae,Nae,$ae,_ae,zae,Lae,Wae,Uae,Hae,Xae,Jae,ese,nse,ise,lse,hse,gse,bse,kse,Cse,Tse,Ese,$se,Fse,Pse,zse,Wse,Gse,qse,Kse,Jse,tie,sie,uie,hre,pie,lae,fie,yie,bie,mre,Iie,Nie,Rie,_ie,zie,Wie,Gie,Xie,Jie,toe,noe,ooe,uoe,poe,moe,yoe,xoe,voe,koe,Toe,$oe,Poe,Uoe,bre,qoe,Zoe,Qoe,rle,Hne,sle,ole,ule,hle,gle,yre,Ale,xle,qne,Loe,wle,Cle,Rle,wre,_le,zle,Wle,Gle,Xle,Zle,Qle,rue,aue,oue,due,cue,yue,bue,kue,Cue,Dne,Woe,Eue,$ue,Fue,Pue,zue,Lue,Wue,Uue,jue,Xue,Zue,Jue,tde,nde,sde,ode,Boe,Ere,dde,cde,gde,bde,kde,Rre,Sde,Tde,Rde,ile];for(let e of $de)qn(e);var qi=Z();qi.registerFlag("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE",()=>15);qi.registerFlag("WEBGPU_CPU_FORWARD",()=>!0);qi.registerFlag("WEBGPU_MATMUL_WORK_PER_THREAD",()=>4);qi.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE",()=>!1);qi.registerFlag("WEBGPU_USE_LOW_POWER_GPU",()=>!1);qi.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e3);qi.registerFlag("WEBGPU_USE_PROFILE_TOOL",()=>!1);qi.registerFlag("WEBGPU_USE_IMPORT",()=>!1);var Mde="return a + b;",Fde="return areal * breal - aimag * bimag;",_de="return areal * bimag + aimag * breal;",Pde="return a / b;",Ode="return a * b;",zde="return (a - b) * (a - b);",Dde="return a - b;",Lde="return f32(a == b);",Bde="return vec4<f32>(a == b);",Wde="return f32(a > b);",Vde="return vec4<f32>(a > b);",Ude="return f32(a >= b);",Gde="return vec4<f32>(a >= b);",jde="return f32(a < b);",Hde="return vec4<f32>(a < b);",qde="return f32(a <= b);",Xde="return vec4<f32>(a <= b);",Kde="return f32(f32(a) >= 1.0 && f32(b) >= 1.0);",Zde=`return (vec4<f32>(a >= vec4<f32>(1.0)) *
|
|
vec4<f32>(b >= vec4<f32>(1.0)));`,Yde=`
|
|
if (isnan(a)) { return a; }
|
|
if (isnan(b)) { return b; }
|
|
`,QI=`
|
|
if (isNaN.r) {
|
|
resultTemp.r = uniforms.NAN;
|
|
}
|
|
if (isNaN.g) {
|
|
resultTemp.g = uniforms.NAN;
|
|
}
|
|
if (isNaN.b) {
|
|
resultTemp.b = uniforms.NAN;
|
|
}
|
|
if (isNaN.a) {
|
|
resultTemp.a = uniforms.NAN;
|
|
}
|
|
`,Jde=`
|
|
let s = sign(a) * sign(b);
|
|
let ia = i32(round(a));
|
|
let ib = i32(round(b));
|
|
return f32(idiv(ia, ib, s));
|
|
`,Qde=`
|
|
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);
|
|
`,epe="return f32(a != b);",tpe="return vec4<f32>(a != b);",rpe=`
|
|
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);
|
|
`,npe=`
|
|
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 = a < vec4<f32>(0.0) & floor(b) < b;
|
|
${QI}
|
|
return resultTemp;
|
|
`,ape="if (a < 0.0) { return b * a; } return a;",spe=`
|
|
let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
|
|
return (aLessThanZero * (b * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
|
|
`;function g7(e,t){let r=t?QI:Yde;return t?`
|
|
var resultTemp = vec4<f32>(${e}(a, b));
|
|
let isNaN = isnanVec4(a) | isnanVec4(b);
|
|
`+r+`
|
|
return resultTemp;
|
|
`:r+`
|
|
return ${e}(a, b);
|
|
`}function Yh(e,t){switch(e){case 0:return Ode;case 1:return Mde;case 2:return Dde;case 3:return Pde;case 4:return t?Bde:Lde;case 5:return t?Vde:Wde;case 6:return t?Gde:Ude;case 7:return t?Hde:jde;case 8:return t?Xde:qde;case 9:return t?Zde:Kde;case 10:return t?tpe:epe;case 11:return zde;case 12:return t?Qde:Jde;case 14:return t?spe:ape;case 15:return g7("max",t);case 16:return g7("min",t);case 13:return t?npe:rpe;case 17:return Fde;case 18:return _de;default:throw new Error(`BinaryType ${e} is not implemented!`)}}var ipe="return abs(a);",ope="return ceil(a);",lpe="return cos(a);",upe=`
|
|
let e2x = exp(-a);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,dpe="return exp(a) - 1.0;",ppe="if (a >= 0.0) { return a; } return (exp(a) - 1.0);",hpe=`
|
|
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;
|
|
`,cpe="return exp(a);",fpe="return floor(a);",mpe="return a;",gpe=`if (a < 0.0) { return 1.0/0.0; }
|
|
return log(a);`,ype="return f32(!(a >= 1.0));",Ape="return -a;",xpe="if (a < 0.0) { return uniforms.alpha * a; } return a;",bpe=`
|
|
let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
|
|
return (aLessThanZero * (uniforms.alpha * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
|
|
`,vpe="return select(a, 0.0, a < 0.0);",wpe="return clamp(a, 0.0, 6.0);",kpe="return clamp(a, vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<f32>(6.0, 6.0, 6.0, 6.0));",Ipe=`
|
|
return select(a, vec4<f32>(0.0), a < vec4<f32>(0.0));
|
|
`,Spe="return 1.0/sqrt(a);",Cpe="return 1.0 / (1.0 + exp(-1.0 * a));",Tpe="return sin(a);",Npe=`
|
|
let e2x = exp(a);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,Epe="return sqrt(a);",Rpe="return a * a;",$pe=`
|
|
let e2x = exp(-2.0 * abs(a));
|
|
return sign(a) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,Mpe="return f32(i32((a)));";function xo(e,t){switch(e){case 0:return ipe;case 2:return lpe;case 3:return upe;case 1:return ope;case 4:return t?hpe:ppe;case 5:return cpe;case 6:return dpe;case 7:return fpe;case 8:return mpe;case 9:return gpe;case 10:return ype;case 11:return Ape;case 14:return t?bpe:xpe;case 12:return t?Ipe:vpe;case 13:return t?kpe:wpe;case 15:return Spe;case 18:return Cpe;case 16:return Tpe;case 17:return Npe;case 19:return Epe;case 20:return Rpe;case 21:return $pe;case 22:return Mpe;default:throw new Error(`BinaryType ${e} is not implemented!`)}}function Wl(e,t=!1){if(e===null)return null;if(e==="linear")return xo(8);if(e==="relu")return xo(12,t);if(e==="elu")return xo(4,t);if(e==="relu6")return xo(13,t);if(e==="prelu")return Yh(14,t);if(e==="sigmoid")return xo(18,t);if(e==="leakyrelu")return xo(14,t);throw new Error(`Activation ${e} has not been implemented for the WebGPU backend.`)}var eS={};Be(eS,{ArrayBufferToTypedArray:()=>rS,GPUBytesPerElement:()=>w0,computeDispatch:()=>Le,computeWorkGroupSizeForConv2d:()=>OA,computeWorkGroupSizeForMatMul:()=>tS,computeWorkPerThreadForConv2d:()=>zA,flatDispatchLayout:()=>Je,isWebGPUSupported:()=>DA,tilesFitEvenlyIntoShape:()=>Fpe});var Ro=e=>{let t=1;for(let r=0;r<e.length;r++)t*=e[r];return t};function Fpe(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((r,n)=>r%e[n]===0)}function Le(e,t,r=[1,1,1],n=[1,1,1]){let[a,s,i]=[Math.ceil(Ro(e.x.map(o=>t[o]))/(r[0]*n[0])),e.y?Math.ceil(Ro(e.y.map(o=>t[o]))/(r[1]*n[1])):1,e.z?Math.ceil(Ro(e.z.map(o=>t[o]))/(r[2]*n[2])):1];return[a,s,i]}function OA(e,t,r=!1){if(r)return[8,8,1];let n=Ro(e.x.map(s=>t[s])),a=Ro(e.y.map(s=>t[s]));return n<=4?[4,16,1]:a<=4?[16,4,1]:[16,16,1]}function tS(e,t,r){return e===1?[32,1,1]:r===1?[1,32,1]:[8,8,1]}function zA(e,t,r=!1){if(r)return[4,4,1];let n=Ro(e.x.map(s=>t[s])),a=Ro(e.y.map(s=>t[s]));return n<=4?[1,2,1]:a<=4?[2,1,1]:[2,2,1]}function Je(e){return{x:e.map((t,r)=>r)}}function w0(e){if(e==="float32"||e==="int32"||e==="bool"||e==="string")return 4;if(e==="complex64")return 8;throw new Error(`Unknown dtype ${e}`)}function rS(e,t){if(t==="float32")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"||t==="string")return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}function DA(){return(typeof window!="undefined"||typeof WorkerGlobalScope!="undefined")&&!!navigator.gpu}var _pe=(e,t)=>e?`
|
|
mm_Asub[inputRow][inputCol] = mm_readA(
|
|
t * TileInner + inputRow,
|
|
globalRowStart / ${t} + inputCol, globalId);
|
|
`:`
|
|
mm_Asub[inputRow][inputCol] = mm_readA(
|
|
globalRow + innerRow,
|
|
t * TileInner / ${t} + inputCol, globalId);
|
|
`,Ppe=(e,t)=>e?`
|
|
let ACached0 = mm_Asub[k * InnerElementSize][localRow];
|
|
let ACached1 = mm_Asub[k * InnerElementSize + 1][localRow];
|
|
let ACached2 = mm_Asub[k * InnerElementSize + 2][localRow];
|
|
${t===3?"":"let ACached3 = mm_Asub[k * InnerElementSize + 3][localRow];"}
|
|
for (var i = 0; i < RowPerThread; i = i + 1) {
|
|
acc[i] = BCached[0] * ACached0[i] + acc[i];
|
|
acc[i] = BCached[1] * ACached1[i] + acc[i];
|
|
acc[i] = BCached[2] * ACached2[i] + acc[i];
|
|
${t===3?"":"acc[i] = BCached[3] * ACached3[i] + acc[i];"}
|
|
}`:`
|
|
for (var i = 0; i < RowPerThread; i = i + 1) {
|
|
let 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];
|
|
${t===3?"":"acc[i] = BCached[3] * ACached.w + acc[i];"}
|
|
}`;function nS(e,t,r,n,a=4,s=!1){let i=s?t:n,o=s?n:t,l=s?e[1]:a;return v.assert((s&&t===r||n%4===0||n%3===0)&&e[0]===4&&(a===3||a===4),()=>`tileInner ${n} must be divisible by 4|3. ColPerThread ${e[0]} must be 4.
|
|
innerElementSize ${a} must be 3|4.`),`
|
|
var<workgroup> mm_Asub : array<array<vec${l}<f32>, ${i/l}>, ${o}>;
|
|
var<workgroup> mm_Bsub : array<array<vec4<f32>, ${r/e[0]}>, ${n}>;
|
|
|
|
let RowPerThread = ${e[1]};
|
|
let ColPerThread = ${e[0]};
|
|
let InnerElementSize = ${a};
|
|
let TileInner = ${n};
|
|
|
|
@stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)
|
|
fn main(@builtin(local_invocation_id) LocalId : vec3<u32>,
|
|
@builtin(global_invocation_id) GlobalId : vec3<u32>,
|
|
@builtin(num_workgroups) NumWorkgroups: vec3<u32>,
|
|
@builtin(workgroup_id) workgroupId: vec3<u32>) {
|
|
localId = LocalId;
|
|
globalId = GlobalId;
|
|
numWorkgroups = NumWorkgroups;
|
|
|
|
let localRow = i32(localId.y);
|
|
let tileRow = ${t===1?"0":"localRow * RowPerThread"};
|
|
let tileCol = i32(localId.x);
|
|
|
|
let globalRow = ${t===1?"0":"i32(globalId.y) * RowPerThread"};
|
|
let globalCol = i32(globalId.x);
|
|
let globalRowStart = i32(workgroupId.y) * ${t};
|
|
|
|
let numTiles = (uniforms.dimInner - 1) / TileInner + 1;
|
|
|
|
var acc: array<vec4<f32>, RowPerThread>;
|
|
var BCached : array<vec4<f32>, 4>;
|
|
|
|
// Loop over shared dimension.
|
|
let RowPerThreadB = TileInner / i32(workGroupSizeY);
|
|
let tileRowB = localRow * 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;
|
|
${_pe(s,l)}
|
|
}
|
|
|
|
// 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 / InnerElementSize; k = k + 1) {
|
|
BCached[0] = mm_Bsub[k * InnerElementSize][tileCol];
|
|
BCached[1] = mm_Bsub[k * InnerElementSize + 1][tileCol];
|
|
BCached[2] = mm_Bsub[k * InnerElementSize + 2][tileCol];
|
|
${a===3?"":"BCached[3] = mm_Bsub[k * InnerElementSize + 3][tileCol];"}
|
|
|
|
${Ppe(s,a)}
|
|
}
|
|
|
|
workgroupBarrier();
|
|
}
|
|
|
|
for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) {
|
|
mm_write(globalRow + innerRow,
|
|
globalCol,
|
|
acc[innerRow], globalId);
|
|
}
|
|
}`}var Ope=class{constructor(e,t,r,n,a=!1,s=null,i=null,o=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workGroupSize=[8,8,1],this.isVec4=!0,this.outputShape=t,this.dispatchLayout={x:[2],y:[1],z:[0]},t[1]===1&&!a?this.elementsPerThread=[4,1,1]:this.elementsPerThread=[4,4,1],this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread);let l=s!=null,u=o!=null;l&&this.variableNames.push("bias"),u&&this.variableNames.push("preluActivationWeights"),this.tileAOuter=t[1]===1&&!a?1:this.workGroupSize[1]*this.elementsPerThread[1],this.tileBOuter=this.workGroupSize[0]*this.elementsPerThread[0],this.tileInner=this.tileBOuter,this.aShape=e,this.addBias=l,this.activation=i,this.hasPreluActivationWeights=u,this.batchAEqualOne=r,this.batchBEqualOne=n,this.transposeA=a;let d=a?e[1]:e[2];this.fitAOuter=t[1]%this.tileAOuter===0,this.fitBOuter=t[2]%this.tileBOuter===0,this.fitInner=d%this.tileInner===0,this.shaderKey=`matMulPackedVec4_${this.activation}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.elementsPerThread}_${this.batchAEqualOne}_${this.batchBEqualOne}_${this.transposeA}`}getUserCode(){let e=this.fitAOuter&&this.fitInner?"return A[batch * batchASize + row * uniforms.aShape[2] / 4 + col]":`if (coordsInBounds2D(vec2<i32>(row, col * 4), vec2<i32>(uniforms.aShape[1], uniforms.aShape[2]))) {
|
|
return A[batch * batchASize + row * uniforms.aShape[2] / 4 + col];
|
|
}
|
|
return vec4<f32>(0.0)`,t=this.fitInner&&this.fitBOuter?"return B[batch * batchBSize + row * uniforms.dimBOuter / 4 + col]":`if(coordsInBounds2D(vec2<i32>(row, col * 4), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return B[batch * batchBSize + row * uniforms.dimBOuter / 4 + col];
|
|
}
|
|
return vec4<f32>(0.0)`,r="",n="";if(this.activation){let s=Wl(this.activation,this.isVec4);this.hasPreluActivationWeights?r=`fn activation(a : vec4<f32>, outCoord : vec3<i32>) -> vec4<f32> {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${s}
|
|
}`:r=`
|
|
fn activation(a : vec4<f32>, outCoord : vec3<i32>) -> vec4<f32> {
|
|
${s}
|
|
}`,n="value = activation(value, outCoord);"}let a=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${r}
|
|
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> vec4<f32> {
|
|
${this.batchAEqualOne?`
|
|
let batchASize = 0;
|
|
let batch = 0;
|
|
`:`
|
|
let batchASize = uniforms.aShape[1] * uniforms.aShape[2] / 4;
|
|
let batch = i32(globalId.z);
|
|
`}
|
|
|
|
${e};
|
|
}
|
|
|
|
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> vec4<f32> {
|
|
${this.batchBEqualOne?`
|
|
let batchBSize = 0;
|
|
let batch = 0;
|
|
`:`
|
|
let batchBSize = uniforms.bShape[1] * uniforms.bShape[2] / 4;
|
|
let batch = i32(globalId.z);
|
|
`}
|
|
${t};
|
|
}
|
|
|
|
fn mm_write(row : i32, col : i32, valueIn : vec4<f32>, globalId : vec3<u32>) {
|
|
if (row < uniforms.dimAOuter && col * 4 < uniforms.dimBOuter)
|
|
{
|
|
var value = valueIn;
|
|
let batch = i32(globalId.z);
|
|
let outCoord = vec3<i32>(batch, row, col * 4);
|
|
${a}
|
|
${n}
|
|
setOutputAtCoords(outCoord[0], outCoord[1], outCoord[2], value);
|
|
}
|
|
}
|
|
${nS(this.elementsPerThread,this.tileAOuter,this.tileBOuter,this.tileInner,4,this.transposeA)}
|
|
`}};function zpe(e,t){if(Math.max(...e)>3)throw new Error("Cannot symbolically compute strides for rank > 4 tensor.");let r=e.length,n=e.map(s=>`${t}[${s}]`),a=new Array(r-1);a[r-2]=n[r-1];for(let s=r-3;s>=0;--s)a[s]=`(${a[s+1]} * ${n[s+1]})`;return a}var y7=(e,t,r,n,a,s=!1)=>{let i={dtype:a.dtype,shape:a.shape},o=Dpe(n,i,t,s),l=e.createShaderModule({code:o,label:t.constructor.name});return e.createComputePipeline({layout:r,compute:{module:l,entryPoint:"main"},label:t.constructor.name})};function Ar(e){if(e<=1)return"i32";if(e===2)return"vec2<i32>";if(e===3)return"vec3<i32>";if(e===4)return"vec4<i32>";if(e===5)return"vec5";if(e===6)return"vec6";throw Error(`GPU for rank ${e} is not yet supported`)}function Fs(e){if(e===0)return"x";if(e===1)return"y";if(e===2)return"z";if(e===3)return"w";if(e===4)return"u";if(e===5)return"v";throw Error(`Index ${e} is not yet supported`)}function rt(){return`
|
|
${Jh()}
|
|
let index = getGlobalIndex();
|
|
`}function Jh(){return`
|
|
${LA()}
|
|
fn main(@builtin(local_invocation_id) LocalId : vec3<u32>,
|
|
@builtin(global_invocation_id) GlobalId : vec3<u32>,
|
|
@builtin(num_workgroups) NumWorkgroups: vec3<u32>) {
|
|
localId = LocalId;
|
|
globalId = GlobalId;
|
|
numWorkgroups = NumWorkgroups;
|
|
`}function LA(){return`
|
|
@stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)
|
|
`}function Dpe(e,t,r,n=!1){let a=[];if(a.push(`
|
|
let workGroupSizeX = ${r.workGroupSize[0]}u;
|
|
let workGroupSizeY = ${r.workGroupSize[1]}u;
|
|
let workGroupSizeZ = ${r.workGroupSize[2]}u;
|
|
|
|
var<private> localId: vec3<u32>;
|
|
var<private> globalId: vec3<u32>;
|
|
var<private> numWorkgroups: vec3<u32>;
|
|
|
|
// Only used when the y/z dimension of workgroup size is 1.
|
|
fn getGlobalIndex() -> i32 {
|
|
${aS(r)?" 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 * numWorkgroups.x * numWorkgroups.y +
|
|
workGroupID.y * numWorkgroups.x + workGroupID.x) *
|
|
(workGroupSizeX * workGroupSizeY * workGroupSizeZ) +
|
|
localInvocationIndex);
|
|
`}
|
|
}
|
|
`),n===!0)return a.push(`
|
|
struct Uniform {
|
|
size : i32,
|
|
numChannels : i32,
|
|
outShapeStrides : vec2<i32>,
|
|
dispatchSize : vec3<u32>,
|
|
};
|
|
|
|
@group(0) @binding(0) var<storage, write> result: array<${k0(t.dtype,r.isVec4)}>;
|
|
@group(0) @binding(2) var<uniform> uniforms: Uniform;
|
|
`),[x7,a.join(`
|
|
`),b7(t.shape),r.getUserCode()].join(`
|
|
`);let s=!1,i=!1,o="struct Uniforms { NAN : f32, ";r.variableNames.forEach((m,f)=>{let g=Ar(e[f].shape.length);(g==="vec5"||g==="vec6")&&(i=!0),(s||i)&&(o+="@align(16) "),s=i,o+=`${m.charAt(0).toLowerCase()+m.slice(1)}Shape : ${g}, `});let l=Ar(t.shape.length);i=l==="vec5"||l==="vec6",(s||i)&&(o+="@align(16) "),s=i,o+=`outShape : ${l}, `;let u=t.shape.length-1,d=Ar(u);i=d==="vec5"||d==="vec6",(s||i)&&(o+="@align(16) "),s=i,o+=`
|
|
outShapeStrides: ${d}, `,r.size&&(s&&(o+="@align(16) "),s=!1,o+="size : i32, "),r.uniforms&&(s&&(o+="@align(16) "),o+=r.uniforms),o+="};",a.push(o),r.atomic?a.push(`
|
|
@group(0) @binding(0) var<storage, read_write> result: array<atomic<i32>>;
|
|
`):a.push(`
|
|
@group(0) @binding(0) var<storage, write> result: array<${k0(t.dtype,r.isVec4)}>;
|
|
`),r.variableNames.forEach((m,f)=>{a.push(`
|
|
@group(0) @binding(${1+f}) var<storage, read> ${m}: array<${r.variableTypes?r.variableTypes[f]:k0(e[f].dtype,r.isVec4)}>;
|
|
`)}),o!==""&&a.push(`
|
|
@group(0) @binding(${1+r.variableNames.length}) var<uniform> uniforms: Uniforms;
|
|
`);let[h,p]=Vpe(t.shape,r.dispatchLayout),c=[x7,a.join(`
|
|
`),b7(t.shape),h,Upe(t.shape.length)];if(r.atomic||c.push(Gpe(t.shape,t.dtype,r.isVec4)),p===t.shape.length){let m=e.map((f,g)=>Wpe(f,t.shape,r.variableTypes?r.variableTypes[g]==="vec4<f32>":r.isVec4,r.dispatchLayout.x.length===t.shape.length)).join(`
|
|
`);c.push(m)}return c.push(r.getUserCode()),c.join(`
|
|
`)}function A7(e,t,r=[],n="",a=""){let s=aS(e)?"flatDispatch":"";return e.shaderKey+"_"+(e.workGroupSize?e.workGroupSize.join(","):"")+t.map(i=>i.length).join(",")+r.join(",")+e.variableNames.join(",")+n+a+s}var x7=`
|
|
struct vec5 {x: i32, y: i32, z: i32, w: i32, u: i32};
|
|
struct vec6 {x: i32, y: i32, z: i32, w: i32, u: i32, v: i32};
|
|
|
|
// Checks whether coordinates lie within the bounds of the shape.
|
|
fn coordsInBounds2D(coord : vec2<i32>, shape : vec2<i32>) -> bool {
|
|
return all(coord >= vec2<i32>(0)) && all(coord < shape);
|
|
}
|
|
fn coordsInBounds3D(coord : vec3<i32>, shape : vec3<i32>) -> bool {
|
|
return all(coord >= vec3<i32>(0)) && all(coord < shape);
|
|
}
|
|
fn coordsInBounds4D(coord : vec4<i32>, shape : vec4<i32>) -> bool {
|
|
return all(coord >= vec4<i32>(0)) && all(coord < shape);
|
|
}
|
|
|
|
fn getIndexFromCoords1D(coord : i32, shape : i32) -> i32 {
|
|
return coord;
|
|
}
|
|
fn getIndexFromCoords2D(coords : vec2<i32>, shape : vec2<i32>) -> i32 {
|
|
return dot(coords, vec2<i32>(shape.y, 1));
|
|
}
|
|
fn getIndexFromCoords3D(coords : vec3<i32>, shape : vec3<i32>) -> i32 {
|
|
return dot(coords, vec3<i32>(shape.y * shape.z, shape.z, 1));
|
|
}
|
|
fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {
|
|
return dot(coords, vec4<i32>(
|
|
shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));
|
|
}
|
|
fn getIndexFromCoords5D(coords : vec5, shape : vec5) -> i32 {
|
|
let shapeStrides: vec5 = vec5(shape.y * shape.z * shape.w * shape.u, shape.z * shape.w * shape.u, shape.w * shape.u, shape.u, 1);
|
|
return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u;
|
|
}
|
|
fn getIndexFromCoords6D(coords : vec6, shape : vec6) -> i32 {
|
|
let shapeStrides: vec6 = vec6(shape.y * shape.z * shape.w * shape.u * shape.v, shape.z * shape.w * shape.u * shape.v, shape.w * shape.u * shape.v, shape.u * shape.v, shape.v, 1);
|
|
return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u + coords.v*shapeStrides.v;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
// NaN defination in IEEE 754-1985 is :
|
|
// - sign = either 0 or 1.
|
|
// - biased exponent = all 1 bits.
|
|
// - fraction = anything except all 0 bits (since all 0 bits represents infinity).
|
|
// https://en.wikipedia.org/wiki/IEEE_754-1985#Representation_of_non-numbers
|
|
fn isnan(val: f32) -> bool {
|
|
let floatToUint: u32 = bitcast<u32>(val);
|
|
return (floatToUint & 0x7fffffffu) > 0x7f800000u;
|
|
}
|
|
fn isnanVec4(val : vec4<f32>) -> vec4<bool> {
|
|
return vec4<bool>(isnan(val[0]), isnan(val[1]), isnan(val[2]), isnan(val[3]));
|
|
}
|
|
`;function b7(e){let t=e.length;if(t<=1)return"fn getCoordsFromIndex(index : i32) -> i32 { return index; }";let r=v.computeStrides(e),n=Ar(t),a=[];for(let i=0;i<t;i++)a.push(`d${i}`);if(r.length===1)return` fn getCoordsFromIndex(index : i32) -> vec2<i32> {
|
|
let d0 = index / uniforms.outShapeStrides; let d1 = index - d0 * uniforms.outShapeStrides;
|
|
return vec2<i32>(d0, d1);
|
|
}`;let s;return s="var index2 = index;"+r.map((i,o)=>{let l=`let ${a[o]} = index2 / uniforms.outShapeStrides.${Fs(o)}`,u=o===r.length-1?`let ${a[o+1]} = index2 - ${a[o]} * uniforms.outShapeStrides.${Fs(o)}`:`index2 = index2 - ${a[o]} * uniforms.outShapeStrides.${Fs(o)}`;return`${l}; ${u};`}).join(""),`
|
|
fn getCoordsFromIndex(index : i32) -> ${n} {
|
|
${s}
|
|
return ${n}(${a.join(",")});
|
|
}
|
|
`}function Lpe(e,t){let r=e.name,n=e.shape.length,a=Ar(n),s="get"+r.charAt(0).toUpperCase()+r.slice(1),i=["d0","d1","d2","d3","d4","d5"].slice(0,n),o=i.map(d=>`${d} : i32`).join(", ");if(n<1)return t?`
|
|
fn ${s}() -> vec4<f32> {
|
|
return vec4<f32>(${r}[0]);
|
|
}
|
|
`:`
|
|
fn ${s}() ->f32 {
|
|
return f32(${r}[0]);
|
|
}
|
|
`;let l=`uniforms.${r.charAt(0).toLowerCase()+r.slice(1)}Shape`,u=`${n}D`;return n===0&&(u="1D"),t?`
|
|
fn ${s}(${o}) -> vec4<f32> {
|
|
return vec4<f32>(${r}[getIndexFromCoords${u}(${a}(${i.join(",")}),
|
|
${l}) / 4]);
|
|
}
|
|
`:`
|
|
fn ${s}(${o}) -> f32 {
|
|
return f32(${r}[getIndexFromCoords${u}(${a}(${i.join(",")}),
|
|
${l})]);
|
|
}
|
|
`}function Bpe(e,t,r,n){let a=e.name,s=a.charAt(0).toUpperCase()+a.slice(1),i="get"+s+"ByOutput",o=e.shape.length,l=t.length,u=Ar(l);if(v.arraysEqual(e.shape,t)&&n)return r?`
|
|
fn ${i}Index(globalIndex : i32) -> vec4<f32> {
|
|
return vec4<f32>(${a}[globalIndex]);
|
|
}
|
|
|
|
fn ${i}Coords(coords : ${u}) -> vec4<f32> {
|
|
return vec4<f32>(${a}[${l>1?"getOutputIndexFromCoords(coords)":"coords"} / 4]);
|
|
}
|
|
`:`
|
|
fn ${i}Index(globalIndex : i32) -> f32 {
|
|
return f32(${a}[globalIndex]);
|
|
}
|
|
|
|
fn ${i}Coords(coords : ${u}) -> f32 {
|
|
return f32(${a}[${l>1?"getOutputIndexFromCoords(coords)":"coords"}]);
|
|
}
|
|
`;let d=C.getBroadcastDims(e.shape,t),h=l-o,p="";if(o===0)return r?`
|
|
fn ${i}Index(globalIndex : i32) -> vec4<f32> {
|
|
return get${s}();
|
|
}
|
|
|
|
fn ${i}Coords(coords : ${u}) -> vec4<f32> {
|
|
return get${s}();
|
|
}
|
|
`:`
|
|
fn ${i}Index(globalIndex : i32) -> f32{
|
|
return get${s}();
|
|
}
|
|
|
|
fn ${i}Coords(coords : ${u}) -> f32{
|
|
return get${s}();
|
|
}
|
|
`;l<2&&d.length>=1?p="coords = 0;":p=d.map(g=>`coords.${Fs(g+h)} = 0;`).join(`
|
|
`);let c="";if(l<2&&o>0)c="coords";else if(l>1){let g=Ar(o),y=e.shape.map((A,x)=>`coords.${Fs(x+h)}`).join(", ");c=`${g}(${y})`}else c="coords";let m=`uniforms.${a.charAt(0).toLowerCase()+a.slice(1)}Shape`,f=`${o}D`;return r?`
|
|
fn ${i}Index(globalIndex : i32) -> vec4<f32> {
|
|
var coords = getCoordsFromIndex(globalIndex);
|
|
${p}
|
|
return ${a}[getIndexFromCoords${f}(${c}, ${m}) / 4];
|
|
}
|
|
|
|
fn ${i}Coords(coordsIn : ${u}) -> vec4<f32> {
|
|
var coords = coordsIn;
|
|
${p}
|
|
return ${a}[getIndexFromCoords${f}(${c}, ${m}) / 4];
|
|
}
|
|
`:`
|
|
fn ${i}Index(globalIndex : i32) -> f32 {
|
|
var coords = getCoordsFromIndex(globalIndex);
|
|
${p}
|
|
return f32(${a}[getIndexFromCoords${f}(${c}, ${m})]);
|
|
}
|
|
|
|
fn ${i}Coords(coordsIn : ${u}) -> f32 {
|
|
var coords = coordsIn;
|
|
${p}
|
|
return f32(${a}[getIndexFromCoords${f}(${c}, ${m})]);
|
|
}
|
|
`}function Wpe(e,t,r,n){let a=Lpe(e,r);return e.shape.length<=t.length&&(a+=Bpe(e,t,r,n)),a}function Vpe(e,t){let{x:r,y:n=[],z:a=[]}=t,s=e.length;if(r.length===s)return[`fn getOutputCoords() -> ${Ar(s)}{
|
|
let globalIndex = getGlobalIndex();
|
|
return getCoordsFromIndex(globalIndex);
|
|
}
|
|
`,s];let i="",o=[r,n,a],l=0;for(let p=0;p<o.length;p++){let c=o[p];if(c.length!==0)if(l+=c.length,c.length===1)i+=`let d${c[0]} = i32(globalId[${p}]);`;else{let m=zpe(c,"uniforms.outShape");i+=`var index${p} = i32(globalId[${p}]);`;for(let f=0;f<m.length;f++)i+=`let d${c[f]} = index${p} / ${m[f]};`,f===m.length-1?i+=`let d${c[f+1]} = index${p} - d${c[f]} * ${m[f]};`:i+=`index${p} = index${p} - d${c[f]} * ${m[f]};`}}let u=[];for(let p=0;p<l;p++)u.push(`d${p}`);let d=Ar(l),h=`fn getOutputCoords() -> ${d} {
|
|
${i}
|
|
`;return u.length===0?h+=`return ${d}(0); }`:h+=`return ${d}(${u.join(",")}); }`,[h,l]}function Upe(e){let t="";switch(e){case 0:case 1:t+=`
|
|
fn getOutputIndexFromCoords(coords : i32) -> i32 {
|
|
return coords;
|
|
}
|
|
`;break;case 2:t+=`
|
|
fn getOutputIndexFromCoords(coords : vec2<i32>) -> i32 {
|
|
return dot(coords, vec2<i32>(uniforms.outShapeStrides, 1));
|
|
}
|
|
`;break;case 3:t+=`
|
|
fn getOutputIndexFromCoords(coords : vec3<i32>) -> i32 {
|
|
return dot(coords, vec3<i32>(uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, 1));
|
|
}
|
|
`;break;case 4:t+=`
|
|
fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
|
|
return dot(coords, vec4<i32>(
|
|
uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, uniforms.outShapeStrides.z, 1));
|
|
}
|
|
`;break;case 5:t+=`
|
|
fn getOutputIndexFromCoords(coords : vec5) -> i32 {
|
|
return coords.x * uniforms.outShapeStrides.x +
|
|
coords.y * uniforms.outShapeStrides.y +
|
|
coords.z * uniforms.outShapeStrides.z +
|
|
coords.w * uniforms.outShapeStrides.w +
|
|
coords.u;
|
|
}
|
|
`;break;case 6:t+=`
|
|
fn getOutputIndexFromCoords(coords : vec6) -> i32 {
|
|
return coords.x * uniforms.outShapeStrides.x +
|
|
coords.y * uniforms.outShapeStrides.y +
|
|
coords.z * uniforms.outShapeStrides.z +
|
|
coords.w * uniforms.outShapeStrides.w +
|
|
coords.u * uniforms.outShapeStrides.u +
|
|
coords.v;
|
|
}
|
|
`;break;default:v.assert(!1,()=>`Unsupported ${e}D shape`);break}return t}function aS(e){return e.dispatch[1]===1&&e.dispatch[2]===1}function k0(e,t){return e==="float32"?t?"vec4<f32>":"f32":e==="int32"||e==="bool"?t?"vec4<i32>":"i32":e}function Gpe(e,t,r){let n=e.length,a=k0(t,r),s;if(r?s=`fn setOutputAtIndex(flatIndex : i32, value : vec4<f32>) {
|
|
result[flatIndex] = ${a}(value);
|
|
}
|
|
fn setOutputAtIndexI32(flatIndex : i32, value : vec4<i32>) {
|
|
result[flatIndex] = ${a}(value);
|
|
}`:s=`fn setOutputAtIndex(flatIndex : i32, value : f32) {
|
|
result[flatIndex] = ${a}(value);
|
|
}
|
|
fn setOutputAtIndexI32(flatIndex : i32, value : i32) {
|
|
result[flatIndex] = ${a}(value);
|
|
}`,n>=2){let i=["d0","d1","d2","d3","d4","d5"].slice(0,n),o=Ar(n);r?s+=`
|
|
fn setOutputAtCoords(${i.map(l=>`${l} : i32`).join(", ")}, value : vec4<f32>) {
|
|
let flatIndex = getOutputIndexFromCoords(${o}(${i.join(", ")}));
|
|
setOutputAtIndex(flatIndex / 4, value);
|
|
}
|
|
fn setOutputAtCoordsI32(${i.map(l=>`${l} : i32`).join(", ")}, value : vec4<i32>) {
|
|
let flatIndex = getOutputIndexFromCoords(${o}(${i.join(", ")}));
|
|
setOutputAtIndexI32(flatIndex / 4, value);
|
|
}
|
|
`:s+=`
|
|
fn setOutputAtCoords(${i.map(l=>`${l} : i32`).join(", ")}, value : f32) {
|
|
let flatIndex = getOutputIndexFromCoords(${o}(${i.join(", ")}));
|
|
setOutputAtIndex(flatIndex, value);
|
|
}
|
|
fn setOutputAtCoordsI32(${i.map(l=>`${l} : i32`).join(", ")}, value : i32) {
|
|
let flatIndex = getOutputIndexFromCoords(${o}(${i.join(", ")}));
|
|
setOutputAtIndexI32(flatIndex, value);
|
|
}
|
|
`}return s}var jpe=e=>e?`
|
|
mm_Asub[inputRow][inputCol] = mm_readA(
|
|
t * TileInner + inputRow,
|
|
globalRowStart + inputCol, globalId);
|
|
`:`
|
|
mm_Asub[inputRow][inputCol] = mm_readA(
|
|
globalRowStart + inputRow,
|
|
t * TileInner + inputCol, globalId);
|
|
`,Hpe=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];";function BA(e,t,r=!1,n=32){let a=e[1]*t[1],s=e[0]*t[0],i=r?a:n,o=r?n:a;v.assert(o%t[1]===0&&i%t[0]===0&&n%t[1]===0,()=>`tileAHight ${o} must be divisible by workGroupSize[1]${t[1]}, tileAWidth ${i} must be divisible by workGroupSize[0]${t[0]}, tileInner ${n} must be divisible by workGroupSize[1]${t[1]}`);let l=o/t[1],u=i/t[0],d=n/t[1];return`
|
|
var<workgroup> mm_Asub : array<array<f32, ${i}>, ${o}>;
|
|
var<workgroup> mm_Bsub : array<array<f32, ${s}>, ${n}>;
|
|
let RowPerThread = ${e[1]};
|
|
let ColPerThread = ${e[0]};
|
|
let TileInner = ${n};
|
|
|
|
@stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)
|
|
fn main(@builtin(local_invocation_id) LocalId : vec3<u32>,
|
|
@builtin(global_invocation_id) GlobalId : vec3<u32>,
|
|
@builtin(num_workgroups) NumWorkgroups: vec3<u32>,
|
|
@builtin(workgroup_id) workgroupId: vec3<u32>) {
|
|
localId = LocalId;
|
|
globalId = GlobalId;
|
|
numWorkgroups = NumWorkgroups;
|
|
|
|
let tileRow = i32(localId.y) * RowPerThread;
|
|
let tileCol = i32(localId.x) * ColPerThread;
|
|
|
|
let globalRow = i32(globalId.y) * RowPerThread;
|
|
let globalCol = i32(globalId.x) * ColPerThread;
|
|
|
|
let globalRowStart = i32(workgroupId.y) * ${a};
|
|
|
|
let numTiles = (uniforms.dimInner - 1) / TileInner + 1;
|
|
|
|
var acc : array<array<f32, ColPerThread>, RowPerThread>;
|
|
|
|
// Without this initialization strange values show up in acc.
|
|
for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) {
|
|
for (var innerCol = 0; innerCol < ColPerThread; innerCol = innerCol + 1) {
|
|
acc[innerRow][innerCol] = 0.0;
|
|
}
|
|
}
|
|
|
|
let tileRowA = i32(localId.y) * ${l};
|
|
let tileColA = i32(localId.x) * ${u};
|
|
let tileRowB = i32(localId.y) * ${d};
|
|
// 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 < ${l}; innerRow = innerRow + 1) {
|
|
for (var innerCol = 0; innerCol < ${u}; innerCol = innerCol + 1) {
|
|
let inputRow = tileRowA + innerRow;
|
|
let inputCol = tileColA + innerCol;
|
|
${jpe(r)}
|
|
}
|
|
}
|
|
|
|
// Load one tile of B into local memory.
|
|
for (var innerRow = 0; innerRow < ${d}; innerRow = innerRow + 1) {
|
|
for (var innerCol = 0; innerCol < ColPerThread; innerCol = innerCol + 1) {
|
|
let inputRow = tileRowB + innerRow;
|
|
let inputCol = tileCol + innerCol;
|
|
mm_Bsub[inputRow][inputCol] = mm_readB(
|
|
t * ${n} + inputRow,
|
|
globalCol + innerCol, globalId);
|
|
}
|
|
}
|
|
|
|
workgroupBarrier();
|
|
|
|
// Compute acc values for a single thread.
|
|
var BCached : array<f32, ColPerThread>;
|
|
for (var k = 0; k < TileInner; k = k + 1) {
|
|
for (var inner = 0; inner < ColPerThread; inner = inner + 1) {
|
|
BCached[inner] = mm_Bsub[k][tileCol + inner];
|
|
}
|
|
|
|
for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) {
|
|
${Hpe(r)}
|
|
for (var innerCol = 0; innerCol < ColPerThread; innerCol = innerCol + 1) {
|
|
acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];
|
|
}
|
|
}
|
|
}
|
|
|
|
workgroupBarrier();
|
|
}
|
|
|
|
for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) {
|
|
for (var innerCol = 0; innerCol < ColPerThread; innerCol = innerCol + 1) {
|
|
mm_write(globalRow + innerRow,
|
|
globalCol + innerCol,
|
|
acc[innerRow][innerCol], globalId);
|
|
}
|
|
}
|
|
}
|
|
`}var qpe=e=>e?`
|
|
mm_readA(colA, globalRow, globalId),
|
|
mm_readA(colA + 1, globalRow, globalId),
|
|
mm_readA(colA + 2, globalRow, globalId),
|
|
mm_readA(colA + 3, globalRow, globalId)
|
|
`:`
|
|
mm_readA(globalRow, colA, globalId),
|
|
mm_readA(globalRow, colA + 1, globalId),
|
|
mm_readA(globalRow, colA + 2, globalId),
|
|
mm_readA(globalRow, colA + 3, globalId)
|
|
`;function Xpe(e,t=!1){return v.assert(e[1]===1&&e[2]===1,()=>`A linear work group size is required. But got ${e}.`),`
|
|
let TileSize = ${e[0]*4};
|
|
var<workgroup> mm_Asub : array<vec4<f32>, ${e[0]}>;
|
|
|
|
${Jh()}
|
|
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>(${qpe(t)});
|
|
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();
|
|
}
|
|
|
|
mm_write(globalRow, globalCol, acc, globalId);
|
|
}
|
|
`}var Kpe=class{constructor(e,t,r,n,a,s=!1,i=!1,o=null,l=null,u=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 d=s?e[1]:e[2];this.workGroupSize=tS(t[1],d,t[2]),(t[1]===1||t[2]===1)&&(r=1),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize,[r,r,1]),v.arraysEqual(this.dispatch,[1,1,1])&&(r=1,this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize,[r,r,1]));let h=o!=null,p=u!=null;h&&this.variableNames.push("bias"),p&&this.variableNames.push("preluActivationWeights"),this.workPerThread=r,this.transposeA=s,this.transposeB=i,this.addBias=h,this.activation=l,this.hasPreluActivationWeights=p,this.batchAEqualOne=n,this.batchBEqualOne=a,[this.fitAOuter,this.fitBOuter,this.fitInner]=this.getShapeFit(t[1],t[2],d),this.shaderKey=`matMulPacked_${this.workPerThread}_${s}_${i}_${this.activation}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.outputShape[1]>1}_${this.batchAEqualOne}_${this.batchBEqualOne}`}getShapeFit(e,t,r){let n=this.workGroupSize[1]*this.workPerThread,a=this.workGroupSize[0]*this.workPerThread;this.tileInner=32,this.outputShape[1]===1&&(this.tileInner=this.workGroupSize[0]*4);let s=e%n===0,i=t%a===0,o=r%this.tileInner===0;return[s,i,o]}getUserCode(){let e=this.fitAOuter&&this.fitInner?"return A[batch * batchASize + row * uniforms.aShape[2] + col];":`
|
|
if(row < uniforms.aShape[1] && col < uniforms.aShape[2]) {
|
|
return A[batch * batchASize + row * uniforms.aShape[2] + col];
|
|
}
|
|
return 0.0;
|
|
`,t;this.transposeB===!1?t="return B[batch * batchBSize + row * uniforms.dimBOuter + col];":t="return B[batch * batchBSize + col * uniforms.dimInner + row];";let r="",n="";if(this.activation){let s=Wl(this.activation,!1);this.hasPreluActivationWeights?r=`fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${s}
|
|
}`:r=`
|
|
fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
${s}
|
|
}
|
|
`,n="value = activation(value, outCoord);"}let a=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${r}
|
|
|
|
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
${this.batchAEqualOne?`
|
|
let batch = 0;
|
|
let batchASize = 0;
|
|
`:`
|
|
let batch = i32(globalId.z);
|
|
let batchASize = uniforms.aShape[1] * uniforms.aShape[2];
|
|
`}
|
|
${e}
|
|
}
|
|
|
|
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
${this.batchBEqualOne?`
|
|
let batch = 0;
|
|
let batchBSize = 0;
|
|
`:`
|
|
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>) {
|
|
${this.fitAOuter&&this.fitBOuter?"":"if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)"}
|
|
{
|
|
var value = valueIn;
|
|
let batch = i32(globalId.z);
|
|
let outCoord = vec3<i32>(batch, row, col);
|
|
${a}
|
|
${n}
|
|
setOutputAtCoords(batch, row, col, value);
|
|
}
|
|
}
|
|
${this.outputShape[1]>1?BA([this.workPerThread,this.workPerThread,1],this.workGroupSize,this.transposeA,this.tileInner):Xpe(this.workGroupSize,this.transposeA)}
|
|
`}};function Zpe(){return`
|
|
var<workgroup> sumValues : array<f32, workGroupSizeX>;
|
|
${Jh()}
|
|
let coords = getOutputCoords();
|
|
let batch = coords[0];
|
|
let row = coords[1];
|
|
let col = coords[2];
|
|
var sum = 0.0;
|
|
let Length = uniforms.dimInner;
|
|
for (var k = i32(localId.x); k < Length; k = k + i32(workGroupSizeX)) {
|
|
let dataA = mm_readA(batch, row, k);
|
|
let dataB = mm_readB(batch, k, col);
|
|
sum = sum + dataA * dataB;
|
|
}
|
|
sumValues[localId.x] = sum;
|
|
workgroupBarrier();
|
|
|
|
for(var currentSize = workGroupSizeX / 2u; currentSize > 1u;
|
|
currentSize = currentSize / 2u) {
|
|
if (localId.x < currentSize)
|
|
{
|
|
sumValues[localId.x] = sumValues[localId.x] + sumValues[localId.x + currentSize];
|
|
}
|
|
workgroupBarrier();
|
|
}
|
|
|
|
if (localId.x == 0u) {
|
|
sum = sumValues[0] + sumValues[1];
|
|
mm_write(batch, row, col, sum);
|
|
}
|
|
}
|
|
`}var Ype=class{constructor(e,t,r,n=!1,a=!1,s=null,i=null,o=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workGroupSize=[256,1,1],this.outputShape=e,this.dispatchLayout={x:[],y:[1,2],z:[0]},this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize);let l=s!=null,u=o!=null;l&&this.variableNames.push("bias"),u&&this.variableNames.push("preluActivationWeights"),this.transposeA=n,this.transposeB=a,this.addBias=l,this.activation=i,this.hasPreluActivationWeights=u,this.batchAEqualOne=t,this.batchBEqualOne=r,this.shaderKey=`matMulReduce_${this.activation}_${n}_${a}_${this.batchAEqualOne}_${this.batchBEqualOne}`}getUserCode(){let e;this.transposeA===!1?e="return f32(A[batch * batchASize + row * uniforms.dimInner + col]);":e="return f32(A[batch * batchASize + col * uniforms.dimAOuter + row]);";let t;this.transposeB===!1?t="return f32(B[batch * batchBSize + row * uniforms.dimBOuter + col]);":t="return f32(B[batch * batchBSize + col * uniforms.dimInner + row]);";let r="",n="";if(this.activation){let s=Wl(this.activation,!1);this.hasPreluActivationWeights?r=`fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${s}
|
|
}`:r=`
|
|
fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
${s}
|
|
}
|
|
`,n="value = activation(value, outCoord);"}let a=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${r}
|
|
|
|
fn mm_readA(batchIn: i32, row : i32, col : i32) -> f32 {
|
|
${this.batchAEqualOne?`
|
|
let batchASize = 0;
|
|
let batch = 0;
|
|
`:`
|
|
let batchASize = uniforms.aShape[1] * uniforms.aShape[2];
|
|
let batch = batchIn;
|
|
`}
|
|
${e}
|
|
}
|
|
|
|
fn mm_readB(batchIn: i32, row : i32, col : i32) -> f32 {
|
|
${this.batchBEqualOne?`
|
|
let batch = 0;
|
|
let batchBSize = 0;
|
|
`:`
|
|
let batch = batchIn;
|
|
let batchBSize = uniforms.bShape[1] * uniforms.bShape[2];
|
|
`}
|
|
${t}
|
|
}
|
|
|
|
fn mm_write(batch: i32, row : i32, col : i32, valueIn : f32) {
|
|
var value = valueIn;
|
|
let outCoord = vec3<i32>(batch, row, col);
|
|
${a}
|
|
${n}
|
|
setOutputAtCoords(batch, row, col, value);
|
|
}
|
|
${Zpe()}
|
|
`}};function Jpe(e){let t=e[1]/2,r=e[0],n=t>r?t:r;return`
|
|
var<workgroup> mm_Asub1 : array<array<f32, ${n}>, ${t}>;
|
|
var<workgroup> mm_Bsub1 : array<array<f32, ${r}>, ${n}>;
|
|
var<workgroup> mm_Asub2 : array<array<f32, ${n}>, ${t}>;
|
|
var<workgroup> mm_Bsub2 : array<array<f32, ${r}>, ${n}>;
|
|
|
|
// 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.
|
|
${Jh()}
|
|
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) / ${n} + 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 + ${n};
|
|
mm_Bsub1[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
|
|
globalRowB = globalRowB + ${n};
|
|
}
|
|
} 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 + ${n};
|
|
mm_Bsub1[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
|
|
globalRowB = globalRowB + ${n};
|
|
} else {
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < ${n}; 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 + ${n};
|
|
mm_Bsub2[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
|
|
globalRowB = globalRowB + ${n};
|
|
} else {
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < ${n}; 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 Qpe=class{constructor(e,t,r,n=null,a=null,s=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=r,this.dispatchLayout={x:[2],y:[1],z:[0]},this.dispatch=[Math.ceil(r[2]/this.workGroupSize[0]),Math.ceil(r[1]*2/this.workGroupSize[1]),r[0]];let i=n!=null;i&&this.variableNames.push("bias");let o=s!=null;o&&this.variableNames.push("preluActivationWeights"),this.addBias=i,this.activation=a,this.hasPreluActivationWeights=o,this.batchAEqualOne=e[0]===1,this.batchBEqualOne=t[0]===1,this.shaderKey=`matMulSmallOutputSize_${this.activation}_${this.batchAEqualOne}_${this.batchBEqualOne}`}getUserCode(){let e=`if (coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimAOuter, uniforms.dimInner))) {
|
|
return A[batch * batchASize + row * uniforms.dimInner + col];
|
|
}
|
|
return 0.0;`,t=`if (coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return B[batch * batchBSize + row * uniforms.dimBOuter + col];
|
|
}
|
|
return 0.0;`,r="",n="";if(this.activation){let s=Wl(this.activation,!1);this.hasPreluActivationWeights?r=`fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${s}
|
|
}`:r=`fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
${s}
|
|
}`,n="value = activation(value, outCoord);"}let a=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${r}
|
|
|
|
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
${this.batchAEqualOne?`
|
|
let batch = 0;
|
|
let batchASize = 0;
|
|
`:`
|
|
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 {
|
|
${this.batchBEqualOne?`
|
|
let batch = 0;
|
|
let batchBSize = 0;
|
|
`:`
|
|
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;
|
|
${a}
|
|
${n}
|
|
setOutputAtCoords(batch, row, col, value);
|
|
}
|
|
}
|
|
${Jpe(this.workGroupSize)}
|
|
`}};function qe(e){let{inputs:t,attrs:r}=e,{x:n}=t,{shape:a}=r,s=v.sizeFromShape(n.shape),i=v.inferFromImplicitShape(a,s),o=v.sizeFromShape(i);return v.assert(s===o,()=>`The new shape (${i}) has ${o} elements and the old shape (${n.shape}) has ${s} elements. The new shape and old shape must have the same number of elements.`),e.backend.incRef(n.dataId),{dataId:n.dataId,shape:i,dtype:n.dtype}}var ehe={kernelName:fl,backendName:"webgpu",kernelFunc:qe};function WA({a:e,b:t,transposeA:r,transposeB:n,backend:a,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){let u=e.shape.length,d=t.shape.length,h=r?e.shape[u-2]:e.shape[u-1],p=n?t.shape[d-1]:t.shape[d-2],c=r?e.shape[u-1]:e.shape[u-2],m=n?t.shape[d-2]:t.shape[d-1],f=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=v.sizeFromShape(f),A=v.sizeFromShape(g),x=$l.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([c,m]);v.assert(h===p,()=>`Error in matMul: inner shapes (${h}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${r} and transposeB=${n} must match.`);let b=r?[y,h,c]:[y,c,h],w=n?[A,m,p]:[A,p,m],I=qe({inputs:{x:e},backend:a,attrs:{shape:b}}),T=qe({inputs:{x:t},backend:a,attrs:{shape:w}}),E=[I,T],R=Math.max(y,A),F=y===1,$=A===1,S=(h%4===0&&!r||c%4===0&&r)&&m%4===0&&!n,z;c*m<=32?z=new Ype([R,c,m],F,$,r,n,s,l,i):!r&&!n&&(c<=16&&(m<=512||p>=2*m)||m<=16&&(c<=512||h>=2*c))?z=new Qpe(b,w,[R,c,m],s,l,i):S?z=new Ope(b,[R,c,m],F,$,r,s,l,i):z=new Kpe(b,[R,c,m],Z().get("WEBGPU_MATMUL_WORK_PER_THREAD"),F,$,r,n,s,l,i);let O=[I,T];s&&O.push(s),i&&O.push(i);let j=[{type:"int32",data:[c]},{type:"int32",data:[m]},{type:"int32",data:[h]}];l==="leakyrelu"&&(j.push({type:"float32",data:[o]}),z.uniforms+=" alpha : f32,");let K=a.runWebGPUProgram(z,O,e.dtype,j),D=qe({inputs:{x:K},backend:a,attrs:{shape:x}});E.push(K);for(let Y of E)a.disposeData(Y.dataId);return D}function the(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:d,leakyreluAlpha:h}=n;return WA({a,b:s,transposeA:l,transposeB:u,backend:r,bias:i,preluActivationWeights:o,leakyreluAlpha:h,activation:d})}var rhe={kernelName:Ps,backendName:"webgpu",kernelFunc:the},v7=class{constructor(e,t,r){this.variableNames=["AReal","AImag","BReal","BImag"],this.workGroupSize=[128,1,1],this.size=!0,this.outputShape=C.assertAndGetBroadcastShape(t,r),this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`binaryOpComplex_${e}`,this.op=e}getUserCode(){return`
|
|
fn binaryOpComplex(
|
|
areal : f32, aimag : f32, breal : f32, bimag : f32) -> f32 {
|
|
${Yh(this.op,!1)}
|
|
}
|
|
|
|
${rt()}
|
|
if(index < uniforms.size) {
|
|
let areal = getARealByOutputIndex(index);
|
|
let aimag = getAImagByOutputIndex(index);
|
|
let breal = getBRealByOutputIndex(index);
|
|
let bimag = getBImagByOutputIndex(index);
|
|
setOutputAtIndex(index, binaryOpComplex(areal, aimag, breal, bimag));
|
|
}
|
|
}
|
|
`}},nhe=class{constructor(e,t,r,n){this.variableNames=["A","B"],this.size=!0;let a=256;this.workGroupSize=[a,1,1],this.outputShape=C.assertAndGetBroadcastShape(t,r),this.dispatchLayout=Je(this.outputShape),this.lastDimensionSize=n?r[0]:t[0],this.lastDimensionSize<256?this.workPerThread=1:this.lastDimensionSize<512?this.workPerThread=2:this.workPerThread=4,this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.useSharedMemoryWithB=n,this.op=e,this.shaderKey=`binaryShared_${e}_${this.lastDimensionSize}_${this.useSharedMemoryWithB}`}getUserCode(){let e=this.lastDimensionSize>1?`coords[${this.outputShape.length-1}]`:"0",t=this.useSharedMemoryWithB?`let a = getAByOutputCoords(coords);
|
|
let b = sharedBuf[${e}];`:`let a = sharedBuf[${e}];
|
|
let b = getBByOutputCoords(coords);`;return`
|
|
fn binaryOperation(a : f32, b : f32) -> f32 {
|
|
${Yh(this.op,!1)}
|
|
}
|
|
var<workgroup> sharedBuf : array<f32, ${this.lastDimensionSize}>;
|
|
${rt()}
|
|
|
|
// 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"}[localIndex]);
|
|
}
|
|
workgroupBarrier();
|
|
|
|
for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
|
|
let flatIndex = index * ${this.workPerThread} + i;
|
|
if(flatIndex < uniforms.size) {
|
|
let coords = getCoordsFromIndex(flatIndex);
|
|
|
|
${t}
|
|
setOutputAtIndex(flatIndex, binaryOperation(a, b));
|
|
}
|
|
}
|
|
}
|
|
`}},ahe=class{constructor(e,t,r){this.variableNames=["A","B"],this.workPerThread=4,this.isVec4=!0,this.size=!0;let n=128;this.workGroupSize=[n,1,1],this.outputShape=C.assertAndGetBroadcastShape(t,r),this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.op=e,this.shaderKey=`binaryVec4_${e}`}getUserCode(){return`
|
|
fn binaryOperation(a : vec4<f32>, b : vec4<f32>) -> vec4<f32> {
|
|
${Yh(this.op,this.isVec4)}
|
|
}
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let a = getAByOutputIndex(index);
|
|
let b = getBByOutputIndex(index);
|
|
setOutputAtIndex(index, binaryOperation(a, b));
|
|
}
|
|
}
|
|
`}},sS=class{constructor(e,t,r){this.variableNames=["A","B"],this.size=!0;let n=128;this.workGroupSize=[n,1,1],this.outputShape=C.assertAndGetBroadcastShape(t,r),this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`binary_${e}`,this.op=e}getUserCode(){return`
|
|
fn binaryOperation(a : f32, b : f32) -> f32 {
|
|
${Yh(this.op,!1)}
|
|
}
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let a = getAByOutputIndex(index);
|
|
let b = getBByOutputIndex(index);
|
|
setOutputAtIndex(index, binaryOperation(a, b));
|
|
}
|
|
}
|
|
`}};function w7(e,t,r){if(v.arraysEqual(t,r)&&v.sizeFromShape(t)%4===0)return new ahe(e,t,r);let n=t.length===1&&r.length>1&&t[0]<1024,a=r.length===1&&t.length>1&&r[0]<1024;return n||a?new nhe(e,t,r,a):new sS(e,t,r)}function zn(e){let{inputs:t}=e,{x:r}=t;return e.backend.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}var she={kernelName:mi,backendName:"webgpu",kernelFunc:zn};function Ld(e){let{inputs:t,backend:r}=e,{real:n,imag:a}=t,s=r.makeTensorInfo(n.shape,"complex64"),i=r.tensorMap.get(s.dataId),o=zn({inputs:{x:n},backend:r}),l=zn({inputs:{x:a},backend:r});return i.complexTensorInfos={real:o,imag:l},s}var ihe={kernelName:sh,backendName:"webgpu",kernelFunc:Ld},Qh=class{constructor(e,t){this.variableNames=["A"],this.size=!0;let r=128;this.workGroupSize=[r,1,1],this.outputShape=e,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.op=t,this.shaderKey=`unary_${t}`}getUserCode(){return`
|
|
fn unaryOperation(a : f32) -> f32 {
|
|
${xo(this.op,!1)}
|
|
}
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let a = getAByOutputIndex(index);
|
|
setOutputAtIndex(index, unaryOperation(a));
|
|
}
|
|
}
|
|
`}};function kr({opType:e,cpuKernelImpl:t,dtype:r}){return({inputs:n,backend:a})=>{let{x:s}=n,i=a,o=r||s.dtype;if(i.shouldExecuteOnCPU([s])&&t!=null){let u=i.tensorMap.get(s.dataId),d=t(u.values,o);return i.makeTensorInfo(s.shape,o,d)}let l=new Qh(s.shape,e);return i.runWebGPUProgram(l,[s],o)}}function Kr({opSnippet:e,cpuKernelImpl:t,supportsComplex:r=!1,dtype:n}){return({inputs:a,backend:s})=>{let{a:i,b:o}=a,l=s;if(r&&i.dtype==="complex64"){let h=l.tensorMap.get(i.dataId),p=l.tensorMap.get(o.dataId),c,m;if(e!==0)[c,m]=[[h.complexTensorInfos.real,p.complexTensorInfos.real],[h.complexTensorInfos.imag,p.complexTensorInfos.imag]].map(g=>{let[y,A]=g,x={dataId:y.dataId,dtype:y.dtype,shape:i.shape},b={dataId:A.dataId,dtype:A.dtype,shape:o.shape},w=w7(e,i.shape,o.shape);return l.runWebGPUProgram(w,[x,b],Nr(y.dtype,A.dtype))});else{let g=new v7(17,i.shape,o.shape),y=new v7(18,i.shape,o.shape),A=[{dataId:h.complexTensorInfos.real.dataId,dtype:h.complexTensorInfos.real.dtype,shape:i.shape},{dataId:h.complexTensorInfos.imag.dataId,dtype:h.complexTensorInfos.imag.dtype,shape:i.shape},{dataId:p.complexTensorInfos.real.dataId,dtype:p.complexTensorInfos.real.dtype,shape:o.shape},{dataId:p.complexTensorInfos.imag.dataId,dtype:p.complexTensorInfos.imag.dtype,shape:o.shape}];c=l.runWebGPUProgram(g,A,"float32"),m=l.runWebGPUProgram(y,A,"float32")}let f=Ld({inputs:{real:c,imag:m},backend:l});return l.disposeData(c.dataId),l.disposeData(m.dataId),f}let u=n||Nr(i.dtype,o.dtype);if((i.dtype==="string"||o.dtype==="string"||l.shouldExecuteOnCPU([i,o]))&&t!=null){let h=l.tensorMap.get(i.dataId).values,p=l.tensorMap.get(o.dataId).values,c=i.dtype==="string"?C.fromUint8ToStringArray(h):h,m=i.dtype==="string"?C.fromUint8ToStringArray(p):p,[f,g]=t(i.shape,o.shape,c,m,u);return l.makeTensorInfo(g,u,f)}let d=w7(e,i.shape,o.shape);return l.runWebGPUProgram(d,[i,o],u)}}var{addImpl:ohe,ceilImpl:lhe,concatImpl:uhe,equalImpl:dhe,expImpl:phe,expm1Impl:hhe,floorImpl:che,gatherNdImpl:fhe,gatherV2Impl:mhe,greaterEqualImpl:ghe,greaterImpl:yhe,lessEqualImpl:Ahe,lessImpl:xhe,logImpl:bhe,maxImpl:vhe,maximumImpl:whe,minimumImpl:khe,multiplyImpl:Ihe,negImpl:She,notEqualImpl:Che,prodImpl:The,rangeImpl:Nhe,rsqrtImpl:Ehe,scatterImpl:Rhe,simpleAbsImpl:$he,sliceImpl:Mhe,stridedSliceImpl:Fhe,stringNGramsImpl:_he,subImpl:Phe,tileImpl:Ohe,topKImpl:zhe,transposeImpl:Dhe,uniqueImpl:bAe}=$m,Lhe=kr({opType:0,cpuKernelImpl:$he}),Bhe={kernelName:Go,backendName:"webgpu",kernelFunc:Lhe},Whe=Kr({opSnippet:1,cpuKernelImpl:ohe,supportsComplex:!0}),Vhe={kernelName:Qa,backendName:"webgpu",kernelFunc:Whe},Uhe=class{constructor(e){this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e[0],this.variableNames=e.map((t,r)=>`T${r}`),this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.shaderKey="addN"}getUserCode(){let e=[];this.variableNames.forEach(r=>{e.push(`let v${r} = get${r}ByOutputCoords(coords);`)});let t=this.variableNames.map(r=>`v${r}`).join(" + ");return`
|
|
${rt()}
|
|
for (var i = 0; i < ${this.workPerThread}; i = i + 1) {
|
|
let flatIndex = index * ${this.workPerThread} + i;
|
|
if (flatIndex < uniforms.size) {
|
|
let coords = getCoordsFromIndex(flatIndex);
|
|
${e.join(`
|
|
`)}
|
|
setOutputAtIndex(flatIndex, ${t});
|
|
}
|
|
}
|
|
}
|
|
`}};function Ghe(e){let{inputs:t,backend:r}=e,n=t;if(n.length===1)return zn({inputs:{x:n[0]},backend:r});let a=n.map(o=>o.dtype).reduce((o,l)=>Nr(o,l)),s=n.map(o=>o.shape),i=new Uhe(s);return r.runWebGPUProgram(i,n,a)}var jhe={kernelName:Zs,backendName:"webgpu",kernelFunc:Ghe},iS=class{constructor(e,t,r){this.workGroupSize=[64,1,1],this.variableNames=["x"],this.uniforms="infinityValue : f32,",this.size=!0;let n=[t];C.assertAxesAreInnerMostDims("arg"+r.charAt(0).toUpperCase()+r.slice(1),n,e.length),this.op=r==="min"?"<":">";let[a]=C.computeOutAndReduceShapes(e,n);this.outputShape=a.length===0?[1]:a,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,[1,1,1]),this.inputShape=e,this.shaderKey=`argMinMax${this.op}`}getUserCode(){let e=`
|
|
var<workgroup> xBestIndices : array<i32, ${this.workGroupSize[0]}>;
|
|
var<workgroup> xBestValues : array<f32, ${this.workGroupSize[0]}>;
|
|
`,t=()=>this.inputShape.length===1?"uniforms.xShape":`uniforms.xShape.${Fs(this.inputShape.length-1)}`,r=()=>{let n="";if(this.outputShape.length===1)this.inputShape.length!==1&&(n+="outputCoords,");else for(let a=0;a<this.outputShape.length;a++)n+=`outputCoords.${Fs(a)},`;return n};return`
|
|
fn DIV_CEIL(a : u32, b : u32) -> u32 {
|
|
return ((a - 1u) / b + 1u);
|
|
}
|
|
|
|
${e}
|
|
|
|
${rt()}
|
|
let outputIndex = index / i32(workGroupSizeX);
|
|
let reduceLength = ${t()};
|
|
|
|
var bestIndex = i32(localId.x);
|
|
var bestValue = uniforms.infinityValue;
|
|
let outputCoords = getCoordsFromIndex(outputIndex);
|
|
for (var k = i32(localId.x); k < reduceLength && outputIndex < uniforms.size;
|
|
k = k + i32(workGroupSizeX)) {
|
|
let candidate = getX(${r()} k);
|
|
if (!isnan(candidate) && candidate ${this.op} bestValue) {
|
|
bestValue = candidate;
|
|
bestIndex = k;
|
|
}
|
|
}
|
|
xBestValues[localId.x] = bestValue;
|
|
xBestIndices[localId.x] = bestIndex;
|
|
workgroupBarrier();
|
|
|
|
var reduceSize = min(u32(reduceLength), workGroupSizeX);
|
|
for (var currentSize = reduceSize / 2u; reduceSize > 1u;
|
|
currentSize = reduceSize / 2u) {
|
|
let interval = DIV_CEIL(reduceSize, 2u);
|
|
if (localId.x < currentSize) {
|
|
let candidate = xBestValues[localId.x + interval];
|
|
if (candidate ${this.op} bestValue) {
|
|
bestValue = candidate;
|
|
xBestValues[localId.x] = bestValue;
|
|
xBestIndices[localId.x] = xBestIndices[localId.x + interval];
|
|
}
|
|
}
|
|
reduceSize = interval;
|
|
workgroupBarrier();
|
|
}
|
|
|
|
if (localId.x == 0u && outputIndex < uniforms.size) {
|
|
setOutputAtIndexI32(outputIndex, xBestIndices[localId.x]);
|
|
}
|
|
}
|
|
`}},Hhe=class{constructor(e,t){this.variableNames=["A"],this.workGroupSize=[16,16,1];let r=new Array(e.length);for(let n=0;n<r.length;n++)r[n]=e[t[n]];this.outputShape=r,this.dispatchLayout={x:[0],y:[1]},this.dispatch=Le(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]}>;
|
|
${LA()}
|
|
fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
@builtin(workgroup_id) workgroupId : vec3<u32>) {
|
|
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[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) {
|
|
setOutputAtIndex((y * height + x), tile[localId.x]
|
|
[localId.y]);
|
|
}
|
|
}
|
|
`}},qhe=class{constructor(e,t){this.variableNames=["A"],this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0;let r=new Array(e.length);for(let n=0;n<r.length;n++)r[n]=e[t[n]];this.outputShape=r,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.newDim=t,this.shaderKey=`transpose_${t}`}getUserCode(){let e=Ar(this.outputShape.length),t=Xhe(this.newDim);return`
|
|
${rt()}
|
|
|
|
for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
|
|
let flatIndex = index * ${this.workPerThread} + i;
|
|
if(flatIndex < uniforms.size) {
|
|
let resRC = getCoordsFromIndex(flatIndex);
|
|
setOutputAtIndex(flatIndex, A[getIndexFromCoords${this.outputShape.length}D(
|
|
${e}(${t}), uniforms.aShape)]);
|
|
}
|
|
}
|
|
}
|
|
`}};function Xhe(e){let t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);let r=new Array(t);for(let n=0;n<e.length;n++)r[e[n]]=`resRC.${Fs(n)}`;return r.join()}function Ja(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{perm:s}=n,i=r,o=a.shape.length,l=new Array(o);for(let d=0;d<l.length;d++)l[d]=a.shape[s[d]];if(r.shouldExecuteOnCPU([a])){let d=i.tensorMap.get(a.dataId).values,h=Dhe(d,a.shape,a.dtype,s,l);return r.makeTensorInfo(l,a.dtype,h)}if(a.shape.length===2&&v.arraysEqual(s,[1,0])){let d=new Hhe(a.shape,s);return i.runWebGPUProgram(d,[a],a.dtype)}let u=new qhe(a.shape,s);return i.runWebGPUProgram(u,[a],a.dtype)}var Khe={kernelName:$a,backendName:"webgpu",kernelFunc:Ja};function Zhe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s}=n,i=v.parseAxisParam(s,a.shape),o=C.getAxesPermutation(i,a.shape.length),l=a,u=[];o!=null&&(l=Ja({inputs:{x:a},backend:r,attrs:{perm:o}}),u.push(l),i=C.getInnerMostAxes(i.length,l.shape.length)),C.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let d=new iS(l.shape,i[0],"max"),h=[{type:"float32",data:[Number.NEGATIVE_INFINITY]}],p=r.runWebGPUProgram(d,[l],"int32",h);return u.forEach(c=>r.disposeData(c.dataId)),p}var Yhe={kernelName:Ys,backendName:"webgpu",kernelFunc:Zhe};function Jhe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s}=n,i=v.parseAxisParam(s,a.shape),o=C.getAxesPermutation(i,a.shape.length),l=a,u=[];o!=null&&(l=Ja({inputs:{x:a},backend:r,attrs:{perm:o}}),u.push(l),i=C.getInnerMostAxes(i.length,l.shape.length)),C.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let d=new iS(l.shape,i[0],"min"),h=[{type:"float32",data:[Number.POSITIVE_INFINITY]}],p=r.runWebGPUProgram(d,[l],"int32",h);return u.forEach(c=>r.disposeData(c.dataId)),p}var Qhe={kernelName:Zu,backendName:"webgpu",kernelFunc:Jhe},oS=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.size=!0,this.outputShape=e.outShape,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(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"),`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
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}
|
|
}
|
|
}
|
|
|
|
setOutputAtIndex(index, ${t});
|
|
}
|
|
}
|
|
`}},lS=class{constructor(e){this.variableNames=["x"],this.uniforms="stride : vec2<i32>,",this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="poolWithFilterSizeEqualsOne"}getUserCode(){return`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let batch = coords[0];
|
|
let d = coords[3];
|
|
|
|
let xRCCorner = coords.yz * uniforms.stride;
|
|
let xRCorner = xRCCorner.x;
|
|
let xCCorner = xRCCorner.y;
|
|
|
|
let value = getX(batch, xRCorner, xCCorner, d);
|
|
setOutputAtIndex(index, value);
|
|
}
|
|
}
|
|
`}};function ece(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1,d=C.computePool2DInfo(a.shape,s,i,u,o,l);if(d.filterWidth===1&&d.filterHeight===1&&v.arraysEqual(d.inShape,d.outShape))return zn({inputs:{x:a},backend:r});let h,p=[{type:"int32",data:[d.strideHeight,d.strideWidth]}];return d.filterHeight===1&&d.filterWidth===1?h=new lS(d):(h=new oS(d,"avg"),p.push({type:"int32",data:[d.padInfo.top,d.padInfo.left]},{type:"int32",data:[d.dilationHeight,d.dilationWidth]},{type:"int32",data:[d.inHeight,d.inWidth]},{type:"int32",data:[d.effectiveFilterHeight,d.effectiveFilterWidth]})),r.runWebGPUProgram(h,[a],a.dtype,p)}var tce={kernelName:Js,backendName:"webgpu",kernelFunc:ece};function rce(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s}=t,{transposeA:i,transposeB:o}=n;return WA({a,b:s,transposeA:i,transposeB:o,backend:r})}var nce={kernelName:Qs,backendName:"webgpu",kernelFunc:rce},ace=class{constructor(e,t){this.variableNames=["source"],this.workPerThread=1,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.rank=t.length,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.start=e,this.uniforms=`start : ${Ar(e.length)}, `,this.shaderKey="slice"}getUserCode(){let e=Ar(this.rank),t=sce(this.rank),r;return this.start.length===1?r=this.outputShape.map((n,a)=>"sourceLoc = uniforms.start + coords;"):r=this.outputShape.map((n,a)=>`sourceLoc.${by[a]} = uniforms.start[${a}] + coords.${by[a]};`),`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
var sourceLoc : ${e};
|
|
let coords = getCoordsFromIndex(index);
|
|
${r.join(`
|
|
`)}
|
|
setOutputAtIndex(index, getSource(${t}));
|
|
}
|
|
}
|
|
`}},by=["x","y","z","w","u","v"];function sce(e){if(e===1)return"sourceLoc";if(e<=6)return by.slice(0,e).map(t=>`sourceLoc.${t}`).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}function Bd(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{begin:s,size:i}=n,[o,l]=Dt.parseSliceParams(a,s,i);if(Dt.assertParamsValid(a,o,l),r.shouldExecuteOnCPU([a])||a.dtype==="string"){let h=r.tensorMap.get(a.dataId),p=Mhe(h.values,o,l,a.shape,a.dtype);return r.makeTensorInfo(l,a.dtype,p)}if(v.sizeFromShape(l)===0)return r.makeTensorInfo(l,a.dtype,[]);let u=new ace(o,l),d=[{type:"int32",data:o}];return r.runWebGPUProgram(u,[a],a.dtype,d)}var ice={kernelName:xl,backendName:"webgpu",kernelFunc:Bd},oce=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,crops:i}=n;v.assert(a.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGPU backend not implemented yet");let o=s.reduce((A,x)=>A*x),l=C.getReshaped(a.shape,s,o),u=C.getPermuted(l.length,s.length),d=C.getReshapedPermuted(a.shape,s,o),h=C.getSliceBeginCoords(i,s.length),p=C.getSliceSize(d,i,s.length),c=[],m=qe({inputs:{x:a},backend:r,attrs:{shape:l}}),f=Ja({inputs:{x:m},backend:r,attrs:{perm:u}}),g=qe({inputs:{x:f},backend:r,attrs:{shape:d}}),y=Bd({inputs:{x:g},backend:r,attrs:{begin:h,size:p}});return c.push(m),c.push(f),c.push(g),c.forEach(A=>r.disposeData(A.dataId)),y},lce={kernelName:jo,backendName:"webgpu",kernelFunc:oce},uS=Kr({opSnippet:10,dtype:"bool",cpuKernelImpl:Che}),uce={kernelName:ll,backendName:"webgpu",kernelFunc:uS};function ec(e){let{inputs:t,backend:r}=e,{input:n}=t,a=r.tensorMap.get(n.dataId);return zn({inputs:{x:a.complexTensorInfos.real},backend:r})}var dce={kernelName:ch,backendName:"webgpu",kernelFunc:ec};function pce(e,t){let r=new Qh(e.shape,22),n=t.runWebGPUProgram(r,[e],"int32");return{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}function vy(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{dtype:s}=n;if(s==="complex64"){if(a.dtype==="complex64")return zn({inputs:{x:a},backend:r});let i=Ot(a.shape),o=vy({inputs:{x:a},backend:r,attrs:{dtype:"float32"}}),l=Ld({inputs:{real:o,imag:i},backend:r});return i.dispose(),r.disposeData(o.dataId),l}if(a.dtype==="complex64"){let i=ec({inputs:{input:a},backend:r}),o=vy({inputs:{x:i},backend:r,attrs:{dtype:s}});return r.disposeData(i.dataId),o}if(!v.hasEncodingLoss(a.dtype,s)){let i=zn({inputs:{x:a},backend:r});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32")return pce(a,r);if(s==="bool"){let i=r.makeTensorInfo([],"bool",v.getTypedArrayFromDType("bool",1)),o=uS({inputs:{a,b:i},backend:r});return r.disposeData(i.dataId),o}throw new Error(`Error in Cast: failed to cast ${a.dtype} to ${s}`)}var hce={kernelName:ei,backendName:"webgpu",kernelFunc:vy},cce=kr({opType:1,cpuKernelImpl:lhe}),fce={kernelName:ti,backendName:"webgpu",kernelFunc:cce},mce=class{constructor(e){this.variableNames=["A"],this.uniforms="minVal : f32, maxVal : f32,",this.workPerThread=4,this.workGroupSize=[64,1,1],this.isVec4=!0,this.size=!0,this.outputShape=e,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.shaderKey="clipVec4"}getUserCode(){return`
|
|
${rt()}
|
|
if(index < uniforms.size) {
|
|
let value = getAByOutputIndex(index);
|
|
var clampedValue : vec4<f32>;
|
|
for (var i = 0; i < 4; i = i + 1) {
|
|
if (isnan(value[i])) {
|
|
clampedValue[i] = value[i];
|
|
} else {
|
|
clampedValue[i] = clamp(value[i], uniforms.minVal, uniforms.maxVal);
|
|
}
|
|
}
|
|
|
|
setOutputAtIndex(index, clampedValue);
|
|
}
|
|
}
|
|
`}},gce=class{constructor(e){this.variableNames=["A"],this.uniforms="minVal : f32, maxVal : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="clip"}getUserCode(){return`
|
|
${rt()}
|
|
if(index < uniforms.size) {
|
|
let value = getAByOutputIndex(index);
|
|
if (isnan(value)) {
|
|
setOutputAtIndex(index, value);
|
|
return;
|
|
}
|
|
setOutputAtIndex(index, clamp(value, uniforms.minVal, uniforms.maxVal));
|
|
}
|
|
}
|
|
`}};function yce(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{clipValueMin:s,clipValueMax:i}=n,o,l=[{type:"float32",data:[s]},{type:"float32",data:[i]}];return v.sizeFromShape(a.shape)%4===0?o=new mce(a.shape):o=new gce(a.shape),r.runWebGPUProgram(o,[a],a.dtype,l)}var Ace={kernelName:es,backendName:"webgpu",kernelFunc:yce},xce=class{constructor(e){this.uniforms="",this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=C.computeOutShape(e,1),this.variableNames=e.map((t,r)=>`T${r}`),this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.offsetLength=e.length-1;for(let t=0;t<this.offsetLength;t++)this.uniforms+=`offset${t} : i32,`;this.shaderKey="concat"}getUserCode(){let e=[];if(this.offsetLength>0){e.push("if (yC < uniforms.offset0){ setOutputAtCoords(coords.x, coords.y, getT0(yR, yC)); }");for(let n=1;n<this.offsetLength;n++)e.push(`else if (yC < uniforms.offset${[n]}){ setOutputAtCoords(coords.x, coords.y, getT${n}(yR, yC - uniforms.offset${n-1})); }`);let t=this.offsetLength,r=this.offsetLength-1;e.push(`else { setOutputAtCoords(coords.x, coords.y, getT${t}(yR, yC - uniforms.offset${r})); }`)}else e.push("setOutputAtCoords(coords.x, coords.y, getT0(yR, yC));");return`
|
|
${rt()}
|
|
for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
|
|
let flatIndex = index * ${this.workPerThread} + i;
|
|
if(flatIndex < uniforms.size) {
|
|
let coords = getCoordsFromIndex(flatIndex);
|
|
let yR = coords.x;
|
|
let yC = coords.y;
|
|
|
|
${e.join(`
|
|
`)}
|
|
}
|
|
}
|
|
}
|
|
`}};function Bm(e){let{inputs:t,backend:r}=e,{input:n}=t,a=r.tensorMap.get(n.dataId);return zn({inputs:{x:a.complexTensorInfos.imag},backend:r})}var bce={kernelName:dh,backendName:"webgpu",kernelFunc:Bm};function wy(e,t,r){let n=e[0].dtype;if(n==="complex64"){let c=e.map(A=>ec({inputs:{input:A},backend:r})),m=e.map(A=>Bm({inputs:{input:A},backend:r})),f=wy(c,t,r),g=wy(m,t,r),y=Ld({inputs:{real:f,imag:g},backend:r});return c.forEach(A=>r.disposeData(A.dataId)),m.forEach(A=>r.disposeData(A.dataId)),r.disposeData(f.dataId),r.disposeData(g.dataId),y}let a=r.shouldExecuteOnCPU(e);if(n==="string"&&(a=!0),a){let c=e.map(b=>{let w=v.sizeFromShape(b.shape.slice(t));return qe({inputs:{x:b},backend:r,attrs:{shape:[-1,w]}})}),m=c.map(b=>({vals:r.readSync(b.dataId),shape:b.shape})),f=C.computeOutShape(c.map(b=>b.shape),1),g=c[0].shape[0]===1,y=uhe(m,f,n,g),A=C.computeOutShape(e.map(b=>b.shape),t),x=r.makeTensorInfo(A,n,y);return c.forEach(b=>r.disposeData(b.dataId)),x}let{tensors2D:s,outShape:i}=vce(e,t,r),o=s.map(c=>c.shape),l=new xce(o),u=[],d=new Array(o.length-1);if(d.length>0){d[0]=o[0][1],u.push({type:"int32",data:[d[0]]});for(let c=1;c<d.length;c++)d[c]=d[c-1]+o[c][1],u.push({type:"int32",data:[d[c]]})}let h=r.runWebGPUProgram(l,s,s[0].dtype,u);s.forEach(c=>r.disposeData(c.dataId));let p=qe({inputs:{x:h},backend:r,attrs:{shape:i}});return r.disposeData(h.dataId),p}function vce(e,t,r){let n=C.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>qe({inputs:{x:a},backend:r,attrs:{shape:[v.sizeFromShape(a.shape.slice(0,t)),v.sizeFromShape(a.shape.slice(t))]}})),outShape:n}}function dS(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n,s=v.parseAxisParam(a,t[0].shape)[0],i=C.computeOutShape(t.map(u=>u.shape),s);if(v.sizeFromShape(i)===0)return r.makeTensorInfo(i,t[0].dtype,[]);let o=t.filter(u=>v.sizeFromShape(u.shape)>0);if(o.length===1)return zn({inputs:{x:o[0]},backend:r});let l=o.map(u=>u.shape);return C.assertParamsConsistent(l,s),wy(o,s,r)}var wce={kernelName:Ho,backendName:"webgpu",kernelFunc:dS},gu=e=>{switch(e){case 1:return"f32";case 2:return"vec2<f32>";case 3:return"vec3<f32>";case 4:return"vec4<f32>";default:throw new Error(`innerElementSize ${e} is not supported.`)}};function kce(e,t,r,n,a=!1,s=null,i=!1,o=4,l=4,u=4){let d=F=>{switch(F){case 1:return"resData = x[xIndex];";case 3:return"resData = vec3<f32>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);";case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${F} is not supported.`)}},h=F=>{switch(F){case 1:return"return W[row * uniforms.wShape[3] + colIn];";case 4:return"return W[row * uniforms.wShape[3] / 4 + colIn];";default:throw new Error(`innerElementSize ${F} is not supported.`)}},p=e?`
|
|
let coord = vec4<i32>(batch, xRow, xCol, xCh);
|
|
`:`
|
|
let coord = vec4<i32>(batch, xCh, xRow, xCol);
|
|
`,c=e?`
|
|
let outCoord = vec4<i32>(
|
|
batch,
|
|
row / outWidth,
|
|
row % outWidth,
|
|
col);
|
|
`:`
|
|
let outCoord = vec4<i32>(
|
|
batch,
|
|
row,
|
|
col / outWidth,
|
|
col % outWidth);
|
|
`,m=e?"uniforms.xShape[1]":"uniforms.xShape[2]",f=e?"uniforms.xShape[2]":"uniforms.xShape[3]",g=e?"row":"col",y=e?"col":"row",A=`
|
|
let inChannels = uniforms.wShape[2];
|
|
let outWidth = ${e?"uniforms.outShape[2]":"uniforms.outShape[3]"};
|
|
let outRow = ${g} / outWidth;
|
|
let outCol = ${g} % outWidth;
|
|
|
|
let WRow = ${y} / (uniforms.filterDims[1] * inChannels);
|
|
let WCol = ${y} / inChannels % uniforms.filterDims[1];
|
|
let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];
|
|
let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];
|
|
let xCh = ${y} % inChannels;
|
|
var resData = ${gu(o)}(0.0);
|
|
// The bounds checking is always needed since we use it to pad zero for
|
|
// the 'same' padding type.
|
|
if (xRow >= 0 && xRow < ${m} && xCol >= 0 && xCol < ${f}) {
|
|
${p}
|
|
let xIndex = getIndexFromCoords4D(coord, uniforms.xShape);
|
|
${d(o)}
|
|
}
|
|
return resData;`,x=e?t&&n?`
|
|
let col = colIn * ${o};
|
|
${A}`:`
|
|
let col = colIn * ${o};
|
|
if (row < uniforms.dimAOuter && col < uniforms.dimInner) {
|
|
${A}
|
|
}
|
|
return ${gu(o)}(0.0);`:n&&r?`
|
|
let col = colIn * ${o};
|
|
${A}`:`
|
|
let col = colIn * ${o};
|
|
if (row < uniforms.dimInner && col < uniforms.dimBOuter) {
|
|
${A}
|
|
}
|
|
return ${gu(o)}(0.0);`,b=`${h(l)}`,w=gu(u),I=gu(e?o:l),T=gu(e?l:o),E="",R="";if(s){let F=Wl(s,u===4);i?E=`fn activation(a: ${w}, outCoord : vec4<i32>) -> ${w} {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${F}
|
|
}`:E=`
|
|
fn activation(a : ${w}, outCoord : vec4<i32>) -> ${w} {
|
|
${F}
|
|
}`,R="value = activation(value, outCoord);"}return`
|
|
${E}
|
|
fn mm_readA(row : i32, colIn : i32, globalId : vec3<u32>) -> ${I} {
|
|
var batch = i32(globalId.z);
|
|
${e?x:b}
|
|
}
|
|
|
|
fn mm_readB(row : i32, colIn : i32, globalId : vec3<u32>) -> ${T} {
|
|
var batch = i32(globalId.z);
|
|
${e?b:x}
|
|
}
|
|
|
|
fn mm_write(row : i32, colIn : i32, valueIn : ${w}, globalId : vec3<u32>) {
|
|
var col = colIn * ${u};
|
|
if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)
|
|
{
|
|
var batch = i32(globalId.z);
|
|
var value = valueIn;
|
|
let outWidth = ${e?"uniforms.outShape[2]":"uniforms.outShape[3]"};
|
|
${c}
|
|
${a?"value = value + getBiasByOutputCoords(outCoord);":""}
|
|
${R}
|
|
setOutputAtCoords(outCoord[0], outCoord[1], outCoord[2], outCoord[3], value);
|
|
}
|
|
}`}var Ice=class{constructor(e,t,r,n,a=!1,s=null,i=!1,o=!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,this.isChannelsLast=e.dataFormat==="channelsLast",this.isVec4=o,this.dispatchLayout=this.isChannelsLast?{x:[3],y:[1,2],z:[0]}:{x:[2,3],y:[1],z:[0]},this.workGroupSize=OA(this.dispatchLayout,this.outputShape,this.isVec4),this.elementsPerThread=zA(this.dispatchLayout,this.outputShape,this.isVec4),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread),this.innerElementSize=this.isVec4?e.inChannels%4===0?4:3:this.elementsPerThread[0],this.isVec4&&(this.variableTypes=this.innerElementSize===3?["f32","vec4<f32>"]:["vec4<f32>","vec4<f32>"]),a&&(this.variableNames.push("bias"),this.isVec4&&this.variableTypes.push("vec4<f32>")),i&&(this.variableNames.push("preluActivationWeights"),this.isVec4&&this.variableTypes.push("vec4<f32>")),this.addBias=a,this.activation=s,this.hasPreluActivationWeights=i,this.tileAOuter=this.workGroupSize[1]*this.elementsPerThread[1],this.tileBOuter=this.workGroupSize[0]*this.elementsPerThread[0],this.tileInner=Math.max(this.workGroupSize[0]*this.innerElementSize,this.workGroupSize[1]),this.fitAOuter=t%this.tileAOuter===0,this.fitBOuter=r%this.tileBOuter===0,this.fitInner=n%this.tileInner===0,this.shaderKey=`conv2DMM_${this.elementsPerThread}_${this.activation}}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.isVec4}_${this.innerElementSize}_${this.isChannelsLast}`}getUserCode(){let e=this.isVec4?nS(this.elementsPerThread,this.tileAOuter,this.tileBOuter,this.tileInner,this.innerElementSize,!this.isChannelsLast):BA(this.elementsPerThread,this.workGroupSize,!this.isChannelsLast,this.tileInner),t=this.isVec4?[this.isChannelsLast?this.innerElementSize:4,4,4]:[1,1,1];return`
|
|
${kce(this.isChannelsLast,this.fitAOuter,this.fitBOuter,this.fitInner,this.addBias,this.activation,this.hasPreluActivationWeights,t[0],t[1],t[2])}
|
|
${e}
|
|
`}};function k7(e,t){let r=e.length;return r>=3?t?[...e.slice(0,-3),e[r-3]*e[r-2],e[r-1]]:[...e.slice(0,-3),e[r-3],e[r-2]*e[r-1]]:!t&&r===1&&e[0]>1?[e[0],1]:null}function Sce({x:e,filter:t,convInfo:r,backend:n,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=r.dataFormat==="channelsLast",u=!l,d=!1,h=l&&r.filterHeight===r.inHeight&&r.filterWidth===r.inWidth&&r.padInfo.type==="VALID",p=[],c,m;if(h){let y=r.inHeight*r.inWidth*r.inChannels;c=qe({inputs:{x:e},backend:n,attrs:{shape:[1,r.batchSize,y]}}),m=qe({inputs:{x:t},backend:n,attrs:{shape:[1,y,r.outChannels]}})}else c=qe({inputs:{x:e},backend:n,attrs:{shape:l?[r.batchSize,r.inHeight*r.inWidth,r.inChannels]:[r.batchSize,r.inChannels,r.inHeight*r.inWidth]}}),m=qe({inputs:{x:t},backend:n,attrs:{shape:[1,r.inChannels,r.outChannels]}});if(p.push(c),p.push(m),s!=null){let y=k7(s.shape,l);y!=null&&(s=qe({inputs:{x:s},backend:n,attrs:{shape:y}}),p.push(s))}if(a!=null){let y=k7(a.shape,l);y!=null&&(a=qe({inputs:{x:a},backend:n,attrs:{shape:y}}),p.push(a))}let f=WA({a:l?c:m,b:l?m:c,transposeA:u,transposeB:d,backend:n,bias:a,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),g=qe({inputs:{x:f},backend:n,attrs:{shape:r.outShape}});p.push(f);for(let y of p)n.disposeData(y.dataId);return g}function pS({x:e,filter:t,convInfo:r,backend:n,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=a!=null,u=s!=null,d=r.dataFormat==="channelsLast";if(d&&r.filterHeight===r.inHeight&&r.filterWidth===r.inWidth&&r.padInfo.type==="VALID"||r.filterHeight===1&&r.filterWidth===1&&r.dilationHeight===1&&r.dilationWidth===1&&r.strideHeight===1&&r.strideWidth===1&&(r.padInfo.type==="SAME"||r.padInfo.type==="VALID"))return Sce({x:e,filter:t,convInfo:r,backend:n,bias:a,activation:o,preluActivationWeights:s,leakyreluAlpha:i});let h=((r.inChannels%4===0||r.inChannels%3===0)&&d||r.outWidth%4===0&&!d)&&r.outChannels%4===0,p=d?r.outHeight*r.outWidth:r.outChannels,c=d?r.outChannels:r.outHeight*r.outWidth,m=r.filterHeight*r.filterWidth*r.inChannels,f=[r.padInfo.top,r.padInfo.left],g=[{type:"int32",data:[r.filterHeight,r.filterWidth]},{type:"int32",data:[...f]},{type:"int32",data:[r.strideHeight,r.strideWidth]},{type:"int32",data:[r.dilationHeight,r.dilationWidth]},{type:"int32",data:[p]},{type:"int32",data:[c]},{type:"int32",data:[m]}],y=new Ice(r,p,c,m,l,o,u,h),A=[],x=[e,t];l&&(!d&&a.shape.length===1&&(a=qe({inputs:{x:a},backend:n,attrs:{shape:[a.shape[0],1,1]}}),A.push(a)),x.push(a)),u&&(!d&&s.shape.length===1&&(s=qe({inputs:{x:s},backend:n,attrs:{shape:[s.shape[0],1,1]}}),A.push(s)),x.push(s)),o==="leakyrelu"&&(g.push({type:"float32",data:[i]}),y.uniforms+=" alpha : f32,");let b=n.runWebGPUProgram(y,x,e.dtype,g);for(let w of A)n.disposeData(w.dataId);return b}function Cce(e){let{inputs:t,attrs:r,backend:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:d}=r,h=C.convertConv2DDataFormat(l),p=C.computeConv2DInfo(a.shape,s.shape,i,u,o,d,!1,h);return pS({x:a,filter:s,convInfo:p,backend:n})}var Tce={kernelName:ri,backendName:"webgpu",kernelFunc:Cce},Nce=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=OA(this.dispatchLayout,this.outputShape),this.elementsPerThread=zA(this.dispatchLayout,this.outputShape),this.dispatch=Le(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[getIndexFromCoords4D(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[getIndexFromCoords4D(coord, uniforms.wShape)];
|
|
}
|
|
return 0.0;
|
|
}
|
|
|
|
fn mm_write(row : i32, col : i32, valueInput : f32, globalId : vec3<u32>) {
|
|
if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)
|
|
{
|
|
var batch = i32(globalId.z);
|
|
var value = valueInput;
|
|
let outCoord = vec4<i32>(
|
|
batch,
|
|
row / uniforms.outShape[2],
|
|
row % uniforms.outShape[2],
|
|
col);
|
|
result[getIndexFromCoords4D(outCoord, uniforms.outShape)] = value;
|
|
}
|
|
}
|
|
|
|
${BA(this.elementsPerThread,this.workGroupSize)}
|
|
`}},Ece=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.size=!0,this.outputShape=e.inShape,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(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,r=this.isChannelsLast?3:1;return`
|
|
${rt()} {
|
|
if(index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let batch = coords[0];
|
|
let d1 = coords[${r}];
|
|
|
|
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;
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
setOutputAtIndex(index, dotProd);
|
|
}
|
|
}
|
|
`}};function Rce(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:d}=n,h=C.convertConv2DDataFormat(u),p=C.computeConv2DInfo(i,s.shape,o,1,l,d,!1,h),c=[{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]}],m;if(Z().getBool("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE"))m=new Ece(p);else{m=new Nce(p);let f=p.inShape[1]*p.inShape[2],g=p.inShape[3],y=p.filterHeight*p.filterWidth*p.outChannels;c.push({type:"uint32",data:[f]},{type:"uint32",data:[g]},{type:"uint32",data:[y]})}return r.runWebGPUProgram(m,[a,s],"float32",c)}var $ce={kernelName:ni,backendName:"webgpu",kernelFunc:Rce},Mce=kr({opType:2}),Fce={kernelName:ai,backendName:"webgpu",kernelFunc:Mce},_ce=kr({opType:3}),Pce={kernelName:si,backendName:"webgpu",kernelFunc:_ce},Oce=class{constructor(e,t,r,n){this.variableNames=["Image","Boxes","BoxInd"],this.uniforms="extrapolationValue : f32,",this.workGroupSize=[64,1,1],this.size=!0;let[a]=t;this.outputShape=[a,r[0],r[1],e],this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.methodId=n==="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)"],[r,n,a]=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}`],[s,i,o]=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`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let height_ratio = f32(${r});
|
|
let width_ratio = f32(${s});
|
|
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 = ${n};
|
|
let width_scale = ${i};
|
|
let in_y = ${a};
|
|
if( in_y < 0.0 || in_y > ${e} ) {
|
|
setOutputAtIndex(index, uniforms.extrapolationValue);
|
|
return;
|
|
}
|
|
let in_x = ${o};
|
|
if( in_x < 0.0 || in_x > ${t} ) {
|
|
setOutputAtIndex(index, 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;
|
|
setOutputAtIndex(index, 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);
|
|
setOutputAtIndex(index, newValue);
|
|
}
|
|
}
|
|
}
|
|
`}},zce=e=>{let{inputs:t,backend:r,attrs:n}=e,{image:a,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=n,d=new Oce(a.shape[3],s.shape,o,l),h=[{type:"float32",data:[u]}];return r.runWebGPUProgram(d,[a,s,i],"float32",h)},Dce={kernelName:Xo,backendName:"webgpu",kernelFunc:zce},I7=class{constructor(e,t,r,n){this.variableNames=["x"],this.uniforms="index : f32,",this.size=!0;let a=128;this.workGroupSize=[a,1,1],this.outputShape=t,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.exclusive=r,this.reverse=n,this.op=e,this.shaderKey=`cum_${this.op}_${this.exclusive}_${this.reverse}`}getUserCode(){let e=this.outputShape.length,t=this.op==="*"?"1.0":"0.0",r=this.exclusive?t:`getX(${S7(e,"coords",this.op)})`,n=this.outputShape[this.outputShape.length-1],a="",s="";return this.exclusive?(a=this.reverse?`end != ${n-1}`:"end != 0",s=this.reverse?"end + 1":"end - 1"):(a=this.reverse?`end + pow2 < ${n}`:"end >= pow2",s=this.reverse?"end + pow2":"end - pow2"),`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
var coords = getCoordsFromIndex(index);
|
|
|
|
let end = ${C7(e,"coords",this.op)};
|
|
var val = ${r};
|
|
let pow2 = i32(pow(2.0, uniforms.index));
|
|
if (${a}) {
|
|
let idx = ${s};
|
|
${C7(e,"coords",this.op)} = idx;
|
|
val ${this.op}= getX(${S7(e,"coords",this.op)});
|
|
}
|
|
setOutputAtIndex(index, val);
|
|
}
|
|
}
|
|
`}};function S7(e,t,r){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 ${r} for rank ${e} is not yet supported`)}function C7(e,t,r){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 ${r} for rank ${e} is not yet supported`)}function hS(e,t,r,n,a,s){let i=t.shape.length,o=C.getAxesPermutation([n],i),l=t;o!=null&&(l=Ja({inputs:{x:t},backend:r,attrs:{perm:o}}));let u=C.getInnerMostAxes(1,i)[0];if(u!==i-1)throw new Error(`WebGPU cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${n}`);let d=l.shape[u],h=zn({inputs:{x:l},backend:r});for(let p=0;p<=Math.ceil(Math.log2(d))-1;p++){let c=new I7(e,l.shape,!1,s),m=h,f=[{type:"float32",data:[p]}];h=r.runWebGPUProgram(c,[h],h.dtype,f),r.disposeData(m.dataId)}if(a){let p=new I7(e,l.shape,a,s),c=h,m=[{type:"float32",data:[0]}];h=r.runWebGPUProgram(p,[h],h.dtype,m),r.disposeData(c.dataId)}if(o!=null){let p=C.getUndoAxesPermutation(o),c=Ja({inputs:{x:h},backend:r,attrs:{perm:p}});return r.disposeData(h.dataId),r.disposeData(l.dataId),c}return h}function Lce(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n;return hS("*",a,r,s,i,o)}var Bce={kernelName:qo,backendName:"webgpu",kernelFunc:Lce};function Wce(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n;return hS("+",a,r,s,i,o)}var Vce={kernelName:ii,backendName:"webgpu",kernelFunc:Wce},Uce=class{constructor(e,t){this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.uniforms="blockSize : i32,",this.outputShape=e,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`depthToSpace_${t}`,this.dataFormat=t}getUserCode(){return`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(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()};
|
|
setOutputAtIndex(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 Gce(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockSize:s,dataFormat:i}=n,o=a.shape[0],l=i==="NHWC"?a.shape[1]:a.shape[2],u=i==="NHWC"?a.shape[2]:a.shape[3],d=i==="NHWC"?a.shape[3]:a.shape[1],h=l*s,p=u*s,c=d/(s*s),m=i==="NHWC"?[o,h,p,c]:[o,c,h,p],f=[{type:"int32",data:[s]}],g=new Uce(m,i);return r.runWebGPUProgram(g,[a],a.dtype,f)}var jce={kernelName:Ko,backendName:"webgpu",kernelFunc:Gce},cS=class{constructor(e,t=!1,r=null,n=!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=Le(this.dispatchLayout,this.outputShape,this.workGroupSize,[1,4,4]),v.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=r,this.hasPreluActivation=n,this.shaderKey=`depthwise3x3_${r}`}getUserCode(){let e="",t="";if(this.activation){let n=Wl(this.activation,this.isVec4);this.hasPreluActivation?e=`fn activation(a : vec4<f32>, outCoord : vec4<i32>) -> vec4<f32> {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${n}
|
|
}`:e=`
|
|
fn activation(a : vec4<f32>, outCoord : vec4<i32>) -> vec4<f32> {
|
|
${n}
|
|
}
|
|
`,t="dotProd[i] = activation(dotProd[i], coords);"}let r=this.addBias?"dotProd[i] = dotProd[i] + getBiasByOutputCoords(coords);":"";return`
|
|
${e}
|
|
|
|
${LA()}
|
|
fn main(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
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)) {
|
|
${r}
|
|
${t}
|
|
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], dotProd[i]);
|
|
}
|
|
}
|
|
}
|
|
`}},fS=class{constructor(e,t=!1,r=null,n=!1){this.variableNames=["x","W"],this.uniforms=`pad : vec2<i32>, stride : vec2<i32>, dilation : vec2<i32>,
|
|
inDims : vec2<i32>, filterHeight : i32, filterWidth : i32,
|
|
channelMul : i32,`,this.workGroupSize=[256,1,1],this.outputShape=e.outShape,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),v.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=r,this.hasPreluActivation=n,this.shaderKey=`depthwise_${this.activation}`}getUserCode(){let e="",t="";if(this.activation){let n=Wl(this.activation,!1);this.hasPreluActivation?e=`fn activation(a : f32, outCoord : vec4<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${n}
|
|
}`:e=`
|
|
fn activation(a : f32, outCoord : vec4<i32>) -> f32 {
|
|
${n}
|
|
}
|
|
`,t="dotProd = activation(dotProd, coords);"}let r=this.addBias?"dotProd = dotProd + getBiasByOutputCoords(coords);":"";return`
|
|
${e}
|
|
|
|
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)) {
|
|
setOutputAtCoords(batch, row, col, chan, value);
|
|
}
|
|
}
|
|
|
|
${Jh()}
|
|
let coords = getOutputCoords();
|
|
let batch = coords[0];
|
|
let xRCCorner = vec2<i32>(coords.yz) * uniforms.stride - uniforms.pad;
|
|
let d2 = coords[3];
|
|
let d1 = d2 / uniforms.channelMul;
|
|
let q = d2 - d1 * uniforms.channelMul;
|
|
|
|
let inputRowStart = xRCCorner.x;
|
|
let inputColStart = xRCCorner.y;
|
|
let inputRowEnd = inputRowStart + uniforms.filterHeight *
|
|
uniforms.dilation[0];
|
|
let inputColEnd = inputColStart + uniforms.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 < uniforms.filterHeight; wR = wR + 1) {
|
|
let xR = inputRowStart + wR * uniforms.dilation[0];
|
|
|
|
for (var wC = 0; wC < uniforms.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 < uniforms.filterHeight; wR = wR + 1) {
|
|
let xR = inputRowStart + wR * uniforms.dilation[0];
|
|
|
|
if (xR < 0 || xR >= uniforms.inDims[0]) {
|
|
continue;
|
|
}
|
|
|
|
for (var wC = 0; wC < uniforms.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;
|
|
}
|
|
}
|
|
}
|
|
|
|
${r}
|
|
${t}
|
|
writeResult(batch, coords[1], coords[2], d2, dotProd);
|
|
}
|
|
`}};function Hce(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=n,d=l;d==null&&(d=[1,1]);let h=C.computeConv2DInfo(a.shape,s.shape,i,d,o,u,!0),p=[{type:"int32",data:[h.padInfo.top,h.padInfo.left]},{type:"int32",data:[h.strideHeight,h.strideWidth]},{type:"int32",data:[h.dilationHeight,h.dilationWidth]},{type:"int32",data:[h.inHeight,h.inWidth]}],c;return h.batchSize===1&&h.inHeight===h.outHeight&&h.inWidth===h.outWidth&&h.strideHeight===1&&h.strideWidth===1&&h.filterHeight===h.filterWidth&&h.inChannels===h.outChannels&&h.dilationHeight===1&&h.dilationWidth===1&&h.filterHeight===3&&h.inChannels%4===0?c=new cS(h):(c=new fS(h),p.push({type:"int32",data:[h.filterHeight]},{type:"int32",data:[h.filterWidth]},{type:"int32",data:[h.outChannels/h.inChannels]})),r.runWebGPUProgram(c,[a,s],a.dtype,p)}var qce={kernelName:oi,backendName:"webgpu",kernelFunc:Hce},mS=Kr({opSnippet:0,cpuKernelImpl:Ihe,supportsComplex:!0}),Xce={kernelName:Si,backendName:"webgpu",kernelFunc:mS},Kce=class{constructor(e,t){this.workGroupSize=[64,1,1],this.variableNames=["x"],this.uniforms="reduceSize : i32,",this.size=!0,this.inputShape=[e.batchSize,e.inSize];let[r]=C.computeOutAndReduceShapes(this.inputShape,[1]);this.outputShape=r.length===0?[1]:r,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,[1,1,1]),this.reduceType=t,this.shaderKey=`reduce_${t}`}getUserCode(){let e="",t="0.0";this.reduceType==="min"||this.reduceType==="max"?(e=`
|
|
if (isnan(candidate)) {
|
|
bestValue = uniforms.NAN;
|
|
} else if (!isnan(bestValue) && candidate ${this.reduceType==="min"?"<":">"} bestValue)
|
|
{ bestValue = candidate; }`,t="f32(x[offset])"):this.reduceType==="sum"||this.reduceType==="mean"?e=" bestValue = bestValue + candidate; ":this.reduceType==="prod"&&(e=" bestValue = bestValue * candidate; ",t="1.0");let r=this.reduceType==="mean"?"setOutputAtIndex(outputIndex, bestValue / f32(uniforms.reduceSize));":"setOutputAtIndex(outputIndex, bestValue);";return`
|
|
fn DIV_CEIL(a : u32, b : u32) -> u32 {
|
|
return ((a - 1u) / b + 1u);
|
|
}
|
|
|
|
${`
|
|
var<workgroup> xBestValues : array<f32, ${this.workGroupSize[0]}>;
|
|
`}
|
|
fn getOffset(outputIndex : i32) -> i32 {
|
|
let outputCoords = getCoordsFromIndex(outputIndex);
|
|
let offset = ${this.outputShape.length===1?"outputCoords":"outputCoords[0]"} * uniforms.reduceSize;
|
|
return offset;
|
|
}
|
|
${rt()}
|
|
let outputIndex = index / i32(workGroupSizeX);
|
|
let offset = getOffset(outputIndex);
|
|
var bestValue = ${t};
|
|
let Length = uniforms.reduceSize;
|
|
let WorkPerThread = DIV_CEIL(u32(Length), workGroupSizeX);
|
|
for (var k = i32(localId.x); k < Length && outputIndex < uniforms.size;
|
|
k = k + i32(workGroupSizeX)) {
|
|
let candidate = f32(x[offset + k]);
|
|
${e}
|
|
}
|
|
xBestValues[localId.x] = bestValue;
|
|
workgroupBarrier();
|
|
|
|
var reduceSize = min(u32(Length), workGroupSizeX);
|
|
for (var currentSize = reduceSize / 2u; reduceSize > 1u;
|
|
currentSize = reduceSize / 2u) {
|
|
let interval = DIV_CEIL(reduceSize, 2u);
|
|
if (localId.x < currentSize) {
|
|
let candidate = xBestValues[localId.x + interval];
|
|
${e}
|
|
xBestValues[localId.x] = bestValue;
|
|
}
|
|
reduceSize = interval;
|
|
workgroupBarrier();
|
|
}
|
|
|
|
if (localId.x == 0u && outputIndex < uniforms.size) {
|
|
${r}
|
|
}
|
|
}
|
|
`}};function tc(e,t,r,n,a){let s=e.shape.length,i=[],o=v.parseAxisParam(t,e.shape),l=o,u=C.getAxesPermutation(l,s),d=e;u!=null&&(d=Ja({inputs:{x:e},attrs:{perm:u},backend:a}),l=C.getInnerMostAxes(l.length,s),i.push(d)),C.assertAxesAreInnerMostDims(n,l,s);let[h,p]=C.computeOutAndReduceShapes(d.shape,l),c=h;r&&(c=C.expandShapeToKeepDim(h,o));let m;if((n==="max"||n==="prod")&&a.shouldExecuteOnCPU([d])){let f=a.tensorMap.get(d.dataId).values;switch(n){case"max":let g=vhe(f,v.sizeFromShape(p),c,e.dtype);m=a.makeTensorInfo(c,e.dtype,g);break;case"prod":let{outVals:y,outShape:A,outDtype:x}=The(d.shape,d.dtype,f,l);m=a.makeTensorInfo(A,x,y);break;default:throw new Error(`${n} CPU implementation is not yet supported.`)}}else{let f=v.sizeFromShape(p),g=v.sizeFromShape(d.shape)/f,y={windowSize:f,inSize:f,batchSize:g,outSize:1},A=n==="mean"?"float32":wh(e.dtype),x=[{type:"int32",data:[f]}],b=new Kce(y,n),w=a.runWebGPUProgram(b,[d],A,x);i.push(w),m=qe({inputs:{x:w},attrs:{shape:c},backend:a})}return i.forEach(f=>a.disposeData(f.dataId)),m}function VA(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;return tc(a,s,i,"sum",r)}var Zce={kernelName:zi,backendName:"webgpu",kernelFunc:VA};function Yce(e){let{inputs:t,backend:r,attrs:n}=e,{equation:a}=n,s=t,{allDims:i,summedDims:o,idDims:l}=C.decodeEinsumEquation(a,s.length);C.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:d}=C.getEinsumComputePath(o,l),h=d.length,p=null,c=i.length,m=[];for(let f=0;f<h;++f){for(let g of d[f]){let{permutationIndices:y,expandDims:A}=C.getEinsumPermutation(c,l[g]),x;C.isIdentityPermutation(y)?x=s[g]:(x=Ja({inputs:{x:s[g]},backend:r,attrs:{perm:y}}),m.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=qe({inputs:{x},backend:r,attrs:{shape:b}}),m.push(x)),p===null?p=x:(p=mS({inputs:{a:x,b:p},backend:r}),m.push(p))}f<h-1&&(u[f]>=0&&(p=VA({inputs:{x:p},backend:r,attrs:{axis:u[f]-(i.length-c),keepDims:!1}}),m.push(p)),c--)}for(let f of m)f!==p&&r.disposeData(f.dataId);return p}var Jce={kernelName:uh,backendName:"webgpu",kernelFunc:Yce},Qce=kr({opType:4}),e0e={kernelName:ui,backendName:"webgpu",kernelFunc:Qce},t0e=Kr({opSnippet:4,dtype:"bool",cpuKernelImpl:dhe}),r0e={kernelName:Zo,backendName:"webgpu",kernelFunc:t0e},gS=kr({opType:5,cpuKernelImpl:phe,dtype:"float32"}),n0e={kernelName:di,backendName:"webgpu",kernelFunc:gS};function ky(e){let{inputs:t,attrs:r,backend:n}=e,{dim:a}=r,{input:s}=t,i=s.shape.length,o=s.shape.slice(),l=a;return a<0&&(v.assert(-(i+1)<=a,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+a+1),o.splice(l,0,1),qe({inputs:{x:s},backend:n,attrs:{shape:o}})}var a0e={kernelName:Yo,backendName:"webgpu",kernelFunc:ky},s0e=kr({opType:6,cpuKernelImpl:hhe}),i0e={kernelName:Jo,backendName:"webgpu",kernelFunc:s0e},o0e=class{constructor(e){this.variableNames=[],this.outputShape=[],this.uniforms="value : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="fill"}getUserCode(){return`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
setOutputAtIndex(index, uniforms.value);
|
|
}
|
|
}
|
|
`}};function Wd(e){let{backend:t,attrs:r}=e,{shape:n,value:a}=r,{dtype:s}=r;if(s=s||v.inferDtype(a),s==="string"){let i=v.getArrayFromDType(s,v.sizeFromShape(n));return i.fill(a),t.makeTensorInfo(n,s,i)}else{let i=new o0e(n),o=[{type:"float32",data:[a]}];return t.runWebGPUProgram(i,[],s,o)}}var l0e={kernelName:nd,backendName:"webgpu",kernelFunc:Wd},u0e=class{constructor(e){this.outputShape=[],this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="flipLeftRight"}getUserCode(){return`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let coordX = uniforms.xShape[2] - coords[2] - 1;
|
|
let outputValue = getX(coords[0], coords[1], coordX, coords[3]);
|
|
setOutputAtIndex(index, outputValue);
|
|
}
|
|
}
|
|
`}},d0e={kernelName:Qo,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{image:r}=e,n=t,a=new u0e(r.shape);return n.runWebGPUProgram(a,[r],r.dtype)}},p0e=kr({opType:7,cpuKernelImpl:che}),h0e={kernelName:pi,backendName:"webgpu",kernelFunc:p0e},c0e=Kr({opSnippet:12,dtype:"int32"}),f0e={kernelName:hi,backendName:"webgpu",kernelFunc:c0e},m0e=class{constructor(e,t=!1){this.outputShape=[0],this.variableNames=[],this.workGroupSize=[256,1,1],this.outputShape=e,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.useImport=t,this.shaderKey=`fromPixels_${this.useImport}`}getUserCode(){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>"};
|
|
|
|
${rt()}
|
|
let flatIndexBase = index * uniforms.numChannels;
|
|
for (var i = 0; i < uniforms.numChannels; i = i + 1) {
|
|
let flatIndex = flatIndexBase + i;
|
|
if (flatIndex < uniforms.size) {
|
|
let coords = getCoordsFromIndex(flatIndexBase);
|
|
let values = ${e};
|
|
result[flatIndex] = i32(floor(255.0 * values[i]));
|
|
}
|
|
}
|
|
}
|
|
`}},g0e={kernelName:jp,backendName:"webgpu",kernelFunc:y0e},yu;function y0e(e){let{inputs:t,backend:r,attrs:n}=e,{pixels:a}=t,{numChannels:s}=n;if(a==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let i=typeof HTMLVideoElement!="undefined"&&a instanceof HTMLVideoElement,o=typeof HTMLImageElement!="undefined"&&a instanceof HTMLImageElement,l=typeof HTMLCanvasElement!="undefined"&&a instanceof HTMLCanvasElement||typeof OffscreenCanvas!="undefined"&&a instanceof OffscreenCanvas,u=typeof ImageBitmap!="undefined"&&a instanceof ImageBitmap,[d,h]=i?[a.videoWidth,a.videoHeight]:[a.width,a.height],p=[h,d,s];if(Z().getBool("WEBGPU_USE_IMPORT")&&i)return T7({externalImage:a,backend:r,attrs:n,outShape:p,useImport:!0});if((i||o)&&(yu==null&&(yu=document.createElement("canvas").getContext("2d")),yu.canvas.width=d,yu.canvas.height=h,yu.drawImage(a,0,0,d,h),a=yu.canvas),u||l||i||o)return T7({externalImage:a,backend:r,attrs:n,outShape:p,useImport:!1});let c=a.data,m=c;if(s!=null&&s!==4){m=new Uint8Array(a.width*a.height*s);let y=c.length,A=0;for(let x=0;x<y;x++)x%4<s&&(m[A++]=c[x])}let f=r.makeTensorInfo(p,"int32"),g=r.tensorMap.get(f.dataId);return g.values=new Int32Array(m),r.maybeReleaseBuffer(f.dataId),r.uploadToGPU(f.dataId),f}function T7(e){let{externalImage:t,backend:r,attrs:n,outShape:a,useImport:s}=e,{numChannels:i}=n,o=v.sizeFromShape(a),l=v.computeStrides(a),u=new m0e(a,s),d=[{type:"uint32",data:[o]},{type:"uint32",data:[i]},{type:"uint32",data:[...l]},{type:"uint32",data:[...u.dispatch]}];return r.runFromPixelsProgram(u,a,d,s,t)}var A0e=class{constructor(e,t,r,n,a){this.uniforms="varianceEpsilon : f32,",this.workGroupSize=[128,1,1],this.size=!0,this.variableNames=["x","mean","variance"],C.assertAndGetBroadcastShape(e,t),C.assertAndGetBroadcastShape(e,r),this.outputShape=e,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),n!=null&&(C.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset")),a!=null&&(C.assertAndGetBroadcastShape(e,a),this.variableNames.push("scale")),this.offsetShape=n,this.scaleShape=a,this.shaderKey="batchNorm"}getUserCode(){let e="0.0";this.offsetShape!=null&&(e="getOffsetByOutputIndex(index)");let t="1.0";return this.scaleShape!=null&&(t="getScaleByOutputIndex(index)"),`
|
|
${rt()}
|
|
if (index < uniforms.size)
|
|
{
|
|
let xValue = getXByOutputIndex(index);
|
|
let meanValue = getMeanByOutputIndex(index);
|
|
let varianValue = getVarianceByOutputIndex(index);
|
|
let offsetValue = ${e};
|
|
let scaleValue = ${t};
|
|
let inv = scaleValue * inverseSqrt(varianValue + f32(uniforms.varianceEpsilon));
|
|
setOutputAtIndex(index,dot(vec3<f32>(xValue, -meanValue, offsetValue), vec3<f32>(inv, inv, 1.0)));
|
|
}
|
|
}
|
|
`}},x0e={kernelName:ci,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:n,scale:a,offset:s,mean:i,variance:o}=e,{varianceEpsilon:l}=t,u=r,d=[n,i,o],h=null;s!=null&&(h=s.shape,d.push(s));let p=null;a!=null&&(p=a.shape,d.push(a));let c=new A0e(n.shape,i.shape,o.shape,h,p),m=[{type:"float32",data:[l]}];return u.runWebGPUProgram(c,d,n.dtype,m)}};function b0e(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:d,dilations:h,dimRoundingMode:p,activation:c,leakyreluAlpha:m}=n,f=C.convertConv2DDataFormat(d),g=C.computeConv2DInfo(a.shape,s.shape,l,h,u,p,!1,f);return pS({x:a,filter:s,convInfo:g,backend:r,bias:i,preluActivationWeights:o,leakyreluAlpha:m,activation:c})}var v0e={kernelName:Os,backendName:"webgpu",kernelFunc:b0e};function w0e(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:d,dimRoundingMode:h,activation:p,leakyreluAlpha:c}=n,m=d;m==null&&(m=[1,1]),v.assert(C.eitherStridesOrDilationsAreOne(l,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`);let f=C.computeConv2DInfo(a.shape,s.shape,l,m,u,h,!0),g=[a,s],y=i!=null,A=o!=null;y&&g.push(i),A&&g.push(o);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]}],b;return 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.dilationHeight===1&&f.dilationWidth===1&&f.filterHeight===3&&f.inChannels%4===0?b=new cS(f,y,p,A):(b=new fS(f,y,p,A),x.push({type:"int32",data:[f.filterHeight]},{type:"int32",data:[f.filterWidth]},{type:"int32",data:[f.outChannels/f.inChannels]})),p==="leakyrelu"&&(x.push({type:"float32",data:[c]}),b.uniforms+=" alpha : f32,"),r.runWebGPUProgram(b,g,"float32",x)}var k0e={kernelName:zs,backendName:"webgpu",kernelFunc:w0e},I0e=class{constructor(e,t){this.variableNames=["A","indices"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`gathernd_${e}`,this.sliceDim=e,this.uniforms=`sliceDim : i32, strides : ${Ar(e)},`}getUserCode(){let e;return this.sliceDim>1?e="uniforms.strides[j]":e="uniforms.strides",`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(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;
|
|
}
|
|
|
|
setOutputAtIndex(index, getA(flattenIndex, coords[1]));
|
|
}
|
|
}
|
|
`}};function S0e(e){let{inputs:t,backend:r}=e,{params:n,indices:a}=t,s=a.shape,i=s[s.length-1],o=v.sizeFromShape(n.shape),[l,u,d,h]=C.prepareAndValidate(n,a),p=qe({inputs:{x:a},backend:r,attrs:{shape:[u,i]}}),c=qe({inputs:{x:n},backend:r,attrs:{shape:[v.sizeFromShape(n.shape)/d,d]}});if(r.shouldExecuteOnCPU([n,a])||n.dtype==="string"){let A=r.readSync(a.dataId),x=r.bufferSync(n),b=fhe(A,x,n.dtype,u,i,d,h,n.shape,o);return r.makeTensorInfo(l,n.dtype,b.values)}let m=new I0e(i,[u,d]),f=[{type:"int32",data:[i]},{type:"int32",data:h}],g=r.runWebGPUProgram(m,[c,p],c.dtype,f),y=qe({inputs:{x:g},backend:r,attrs:{shape:l}});return r.disposeData(p.dataId),r.disposeData(c.dataId),r.disposeData(g.dataId),y}var C0e={kernelName:tl,backendName:"webgpu",kernelFunc:S0e},T0e=class{constructor(e,t){this.variableNames=["A","indices"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e.slice(),this.aShape=e,this.outputShape=t,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="gather"}getUserCode(){let e=N0e(this.aShape);return`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let resRC = getCoordsFromIndex(index);
|
|
let indexZ = i32(getIndices(resRC.x, resRC.z));
|
|
let inBounds = select(0.0, 1.0, indexZ >= 0 && indexZ < uniforms.aShape[2]);
|
|
setOutputAtIndex(index, inBounds * getA(${e}));
|
|
}
|
|
}
|
|
`}};function N0e(e){let t=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[];for(let n=0;n<e.length;n++)n===2?r.push("indexZ"):r.push(`${t[n]}`);return r.join()}function yS(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,indices:s}=t,{axis:i,batchDims:o}=n,l=v.parseAxisParam(i,a.shape)[0],u=C.segment_util.collectGatherOpShapeInfo(a,s,l,o),d=v.sizeFromShape(s.shape),h=[],p=qe({inputs:{x:a},backend:r,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),c=qe({inputs:{x:s},backend:r,attrs:{shape:[u.batchSize,d/u.batchSize]}});h.push(p),h.push(c);let m=[u.batchSize,u.outerSize,d/u.batchSize,u.sliceSize];if(r.shouldExecuteOnCPU([a,s])){let A=r.tensorMap.get(c.dataId).values,x=De(c.shape,c.dtype,A),b=r.tensorMap.get(p.dataId).values,w=De(p.shape,p.dtype,b),I=mhe(w,x,m);return h.forEach(T=>r.disposeData(T.dataId)),r.makeTensorInfo(u.outputShape,I.dtype,I.values)}let f=new T0e(p.shape,m),g=r.runWebGPUProgram(f,[p,c],p.dtype);h.push(g);let y=qe({inputs:{x:g},backend:r,attrs:{shape:u.outputShape}});return h.forEach(A=>r.disposeData(A.dataId)),y}var E0e={kernelName:el,backendName:"webgpu",kernelFunc:yS},R0e=Kr({opSnippet:5,cpuKernelImpl:yhe,dtype:"bool"}),$0e={kernelName:rl,backendName:"webgpu",kernelFunc:R0e},M0e=Kr({opSnippet:6,dtype:"bool",cpuKernelImpl:ghe}),F0e={kernelName:fi,backendName:"webgpu",kernelFunc:M0e};function _0e(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{alpha:s}=n,i=[{type:"float32",data:[s]}],o=new Qh(a.shape,14);return o.uniforms="alpha : f32,",r.runWebGPUProgram(o,[a],"float32",i)}var P0e={kernelName:gi,backendName:"webgpu",kernelFunc:_0e},O0e=Kr({opSnippet:7,dtype:"bool",cpuKernelImpl:xhe}),z0e={kernelName:nl,backendName:"webgpu",kernelFunc:O0e},D0e=Kr({opSnippet:8,dtype:"bool",cpuKernelImpl:Ahe}),L0e={kernelName:al,backendName:"webgpu",kernelFunc:D0e},B0e=kr({opType:9,cpuKernelImpl:bhe}),W0e={kernelName:yi,backendName:"webgpu",kernelFunc:B0e},V0e=Kr({opSnippet:9,dtype:"bool"}),U0e={kernelName:sl,backendName:"webgpu",kernelFunc:V0e},G0e=kr({opType:10}),j0e={kernelName:il,backendName:"webgpu",kernelFunc:G0e};function AS(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{reductionIndices:s,keepDims:i}=n;return tc(a,s,i,"max",r)}var H0e={kernelName:Ai,backendName:"webgpu",kernelFunc:AS},q0e=Kr({opSnippet:15,cpuKernelImpl:whe}),X0e={kernelName:xi,backendName:"webgpu",kernelFunc:q0e};function K0e(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1,d=C.computePool2DInfo(a.shape,s,i,u,o,l),h,p=[];if(d.filterHeight===1&&d.filterWidth===1){if(v.arraysEqual(d.inShape,d.outShape))return zn({inputs:{x:a},backend:r});h=new lS(d),p.push({type:"int32",data:[d.strideHeight,d.strideWidth]})}else h=new oS(d,"max"),p.push({type:"int32",data:[d.strideHeight,d.strideWidth]},{type:"int32",data:[d.padInfo.top,d.padInfo.left]},{type:"int32",data:[d.dilationHeight,d.dilationWidth]},{type:"int32",data:[d.inHeight,d.inWidth]},{type:"int32",data:[d.effectiveFilterHeight,d.effectiveFilterWidth]});return r.runWebGPUProgram(h,[a],a.dtype,p)}var Z0e={kernelName:bi,backendName:"webgpu",kernelFunc:K0e};function Y0e(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{keepDims:s,axis:i}=n;return tc(a,i,s,"mean",r)}var J0e={kernelName:vi,backendName:"webgpu",kernelFunc:Y0e};function Q0e(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;return tc(a,s,i,"min",r)}var efe={kernelName:wi,backendName:"webgpu",kernelFunc:Q0e},tfe=Kr({opSnippet:16,cpuKernelImpl:khe}),rfe={kernelName:ki,backendName:"webgpu",kernelFunc:tfe},nfe=class{constructor(e,t,r){this.uniforms="",this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((n,a)=>n[0]+e[a]+n[1]),this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.xShape=e,t.map((n,a)=>{this.uniforms+=` pad${a} : vec2<i32>,`}),this.offset=r==="reflect"?0:1,this.shaderKey=`mirrorPad_${r}`}getUserCode(){let e=this.xShape.length,t=this.xShape.map((l,u)=>`uniforms.pad${u}[0]`).join(","),r=this.xShape.map((l,u)=>`uniforms.pad${u}[0] + uniforms.xShape${e>1?`[${u}]`:""}`).join(","),n=e===1?"start":"start[i]",a=e===1?"end":"end[i]",s=e===1?"outC":"outC[i]",i=Ar(e),o=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let start = ${i}(${t});
|
|
let end = ${i}(${r});
|
|
var outC = getCoordsFromIndex(index);
|
|
for (var i = 0; i < ${e}; i = i + 1) {
|
|
if (${s} < ${n}) {
|
|
${s} = ${n} * 2 - ${s} - ${this.offset};
|
|
} else if(${s} >= ${a}) {
|
|
${s} = (${a} - 1) * 2 - ${s} + ${this.offset};
|
|
}
|
|
}
|
|
let coords = outC - start;
|
|
setOutputAtIndex(index, getX(${o}));
|
|
}
|
|
}
|
|
`}},afe={kernelName:Ii,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:n}=e,{paddings:a,mode:s}=t,i=r,o=a.map(u=>({type:"int32",data:[u[0],u[1]]})),l=new nfe(n.shape,a,s);return i.runWebGPUProgram(l,[n],n.dtype,o)}};function sfe(e){let{inputs:t,backend:r}=e,{x:n}=t;if(r.shouldExecuteOnCPU([n])){let s=r.tensorMap.get(n.dataId),[i,o]=She(s.values,n.shape,n.dtype);return r.makeTensorInfo(o,n.dtype,i)}let a=new Qh(n.shape,11);return r.runWebGPUProgram(a,[n],n.dtype)}var ife={kernelName:ol,backendName:"webgpu",kernelFunc:sfe};function ofe(e){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=n,u=r.readSync(a.dataId),d=r.readSync(s.dataId),{selectedIndices:h}=Kn.nonMaxSuppressionV3Impl(u,d,i,o,l);return r.makeTensorInfo([h.length],"int32",new Int32Array(h))}var lfe={kernelName:ul,backendName:"webgpu",kernelFunc:ofe};function ufe(e){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=n,d=r.readSync(a.dataId),h=r.readSync(s.dataId),p=i,c=o,m=l,f=u,{selectedIndices:g,selectedScores:y}=Kn.nonMaxSuppressionV5Impl(d,h,p,c,m,f);return[r.makeTensorInfo([g.length],"int32",new Int32Array(g)),r.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var dfe={kernelName:dl,backendName:"webgpu",kernelFunc:ufe};function rf(e){let{inputs:t,backend:r}=e,{x:n}=t;if(n.dtype==="complex64"){let a=ec({inputs:{input:n},backend:r}),s=rf({inputs:{x:a},backend:r}),i=Bm({inputs:{input:n},backend:r}),o=rf({inputs:{x:i},backend:r}),l=Ld({inputs:{real:s,imag:o},backend:r});return r.disposeData(a.dataId),r.disposeData(s.dataId),r.disposeData(i.dataId),r.disposeData(o.dataId),l}else return Wd({attrs:{shape:n.shape,dtype:n.dtype,value:n.dtype==="string"?"":0},backend:r})}var pfe={kernelName:Nl,backendName:"webgpu",kernelFunc:rf};function xS(e){let{inputs:t,backend:r}=e,{x:n}=t;if(n.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(n.dtype==="complex64"){let a=ec({inputs:{input:n},backend:r}),s=xS({inputs:{x:a},backend:r}),i=Bm({inputs:{input:n},backend:r}),o=rf({inputs:{x:i},backend:r}),l=Ld({inputs:{real:s,imag:o},backend:r});return r.disposeData(a.dataId),r.disposeData(s.dataId),r.disposeData(i.dataId),r.disposeData(o.dataId),l}else return Wd({attrs:{shape:n.shape,dtype:n.dtype,value:1},backend:r})}var hfe={kernelName:pl,backendName:"webgpu",kernelFunc:xS};function cfe(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n;if(t.length===1)return ky({inputs:{input:t[0]},backend:r,attrs:{dim:a}});let s=t[0].shape,i=t[0].dtype;t.forEach(d=>{v.assertShapesMatch(s,d.shape,"All tensors passed to stack must have matching shapes"),v.assert(i===d.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(d=>{let h=ky({inputs:{input:d},backend:r,attrs:{dim:a}});return o.push(h),h}),u=dS({inputs:l,backend:r,attrs:{axis:a}});return o.forEach(d=>r.disposeData(d.dataId)),u}var ffe={kernelName:cl,backendName:"webgpu",kernelFunc:cfe},mfe=class{constructor(e,t){this.variableNames=["x"],this.uniforms="constantValue : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((r,n)=>r[0]+e[n]+r[1]),this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),t.map((r,n)=>{this.uniforms+=` pad${n} : vec2<i32>,`}),this.xShape=e,this.shaderKey="pad"}getUserCode(){let e=this.xShape.length,t=Ar(e),r=this.xShape.map((u,d)=>`uniforms.pad${d}[0]`).join(","),n=this.xShape.map((u,d)=>`uniforms.pad${d}[0] + uniforms.xShape${e>1?`[${d}]`:""}`).join(","),a=e>1?`${t}(${r})`:`${r}`,s=e>1?`${t}(${n})`:`${n}`,i=e>1?"any(outC < start)":"outC < start",o=e>1?"any(outC >= end)":"outC >= end",l=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let start = ${a};
|
|
let end = ${s};
|
|
let outC = getCoordsFromIndex(index);
|
|
|
|
if (${i} || ${o}) {
|
|
setOutputAtIndex(index, uniforms.constantValue);
|
|
} else {
|
|
let coords = outC - start;
|
|
setOutputAtIndex(index, getX(${l}));
|
|
}
|
|
}
|
|
}
|
|
`}},bS=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{paddings:s,constantValue:i}=n;if(s.every(u=>v.arraysEqual(u,[0,0])))return zn({inputs:{x:a},backend:r});if(v.sizeFromShape(a.shape)===0){let u=s.map((d,h)=>d[0]+a.shape[h]+d[1]);return Wd({backend:r,attrs:{shape:u,value:i,dtype:a.dtype}})}let o=[{type:"float32",data:[i]}];s.map(u=>o.push({type:"int32",data:[u[0],u[1]]}));let l=new mfe(a.shape,s);return r.runWebGPUProgram(l,[a],a.dtype,o)},gfe={kernelName:Ci,backendName:"webgpu",kernelFunc:bS},yfe=Kr({opSnippet:13}),Afe={kernelName:Ti,backendName:"webgpu",kernelFunc:yfe};function xfe(e){let{inputs:t,backend:r}=e,{x:n,alpha:a}=t,s=new sS(14,n.shape,a.shape);return r.runWebGPUProgram(s,[n,a],"float32")}var bfe={kernelName:Ni,backendName:"webgpu",kernelFunc:xfe};function vfe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;return tc(a,s,i,"prod",r)}var wfe={kernelName:Ei,backendName:"webgpu",kernelFunc:vfe},kfe=e=>{let{backend:t,attrs:r}=e,{start:n,stop:a,step:s,dtype:i}=r,o=Nhe(n,a,s,i);return t.makeTensorInfo([o.length],i,o)},Ife={kernelName:pd,backendName:"webgpu",kernelFunc:kfe},vS=Kr({opSnippet:3}),Sfe={kernelName:li,backendName:"webgpu",kernelFunc:vS},Cfe=kr({opType:12}),Tfe={kernelName:Ri,backendName:"webgpu",kernelFunc:Cfe},Nfe=kr({opType:13}),Efe={kernelName:Mi,backendName:"webgpu",kernelFunc:Nfe},Rfe=class{constructor(e,t,r){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2<f32>, halfPixelCenters : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,r,e[3]],this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="resizeBilinear"}getUserCode(){return`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let b = coords[0];
|
|
let d = coords[3];
|
|
let rc = coords.yz;
|
|
|
|
let effectiveInSize = vec2<f32>(
|
|
f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0],
|
|
f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]);
|
|
|
|
let effectiveOutSize = vec2<f32>(
|
|
f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0],
|
|
f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]);
|
|
|
|
let effectiveInputOverOutputRatioRC =
|
|
effectiveInSize / effectiveOutSize;
|
|
|
|
// Fractional source index
|
|
let sourceFracIndexRC =
|
|
(vec2<f32>(rc) + vec2<f32>(uniforms.halfPixelCenters)) *
|
|
effectiveInputOverOutputRatioRC - vec2<f32>(uniforms.halfPixelCenters);
|
|
|
|
// 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;
|
|
|
|
setOutputAtIndex(index, newValue);
|
|
}
|
|
}
|
|
`}};function $fe(e){let{inputs:t,backend:r,attrs:n}=e,{images:a}=t,{alignCorners:s,size:i,halfPixelCenters:o}=n,[l,u]=i,d=s&&l>1?1:0,h=s&&u>1?1:0,p=[{type:"float32",data:[d,h]},{type:"float32",data:[o?.5:0]}],c=new Rfe(a.shape,l,u);return r.runWebGPUProgram(c,[a],"float32",p)}var Mfe={kernelName:$i,backendName:"webgpu",kernelFunc:$fe},Ffe=class{constructor(e,t,r,n){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2<f32>, roundBase : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,r,e[3]],this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.halfPixelCenters=n,this.shaderKey=`resizeNearest_${n}`}getUserCode(){let e;return this.halfPixelCenters?e="max((vec2<f32>(rc) + vec2<f32>(0.5)) * effectiveInputOverOutputRatioRC, vec2<f32>(0.0))":e="vec2<f32>(rc) * effectiveInputOverOutputRatioRC",`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let b = coords[0];
|
|
let d = coords[3];
|
|
let rc = coords.yz;
|
|
|
|
let effectiveInSize = vec2<f32>(
|
|
f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0],
|
|
f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]);
|
|
|
|
let effectiveOutSize = vec2<f32>(
|
|
f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0],
|
|
f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]);
|
|
|
|
let effectiveInputOverOutputRatioRC =
|
|
effectiveInSize / effectiveOutSize;
|
|
|
|
// Fractional source index
|
|
let sourceFracIndexRC = ${e};
|
|
|
|
// 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 + uniforms.roundBase)));
|
|
let newValue = getX(b, sourceNearestRC.x, sourceNearestRC.y, d);
|
|
|
|
setOutputAtIndex(index, newValue);
|
|
}
|
|
}
|
|
`}};function _fe(e){let{inputs:t,backend:r,attrs:n}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,d=s&&l>1?1:0,h=s&&u>1?1:0,p=[{type:"float32",data:[d,h]},{type:"float32",data:[s?.5:0]}],c=new Ffe(a.shape,l,u,i);return r.runWebGPUProgram(c,[a],a.dtype,p)}var Pfe={kernelName:cd,backendName:"webgpu",kernelFunc:_fe},Ofe=class{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms=`centerX : f32, centerY : f32, sinRadians : f32,
|
|
cosRadians : f32,`,this.shaderKey="rotate",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`
|
|
${rt()}
|
|
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(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]);
|
|
}
|
|
setOutputAtIndex(index, outputValue);
|
|
}
|
|
}
|
|
`}},zfe={kernelName:El,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{image:n}=e,{radians:a,fillValue:s,center:i}=t,o=r,l=new Ofe(n.shape,s),[u,d]=C.getImageCenter(i,n.shape[1],n.shape[2]),h=[{type:"float32",data:[u]},{type:"float32",data:[d]},{type:"float32",data:[Math.sin(a)]},{type:"float32",data:[Math.cos(a)]}];return typeof s=="number"?h.push({type:"float32",data:[Number.parseFloat(s.toFixed(2))]}):h.push({type:"float32",data:s}),o.runWebGPUProgram(l,[n],n.dtype,h)}},Dfe=kr({opType:15,cpuKernelImpl:Ehe}),Lfe={kernelName:Fi,backendName:"webgpu",kernelFunc:Dfe},Bfe=class{constructor(e,t,r,n,a,s,i){this.variableNames=["updates","indices"],this.workGroupSize=[64,1,1],this.atomic=!0,this.outputShape=s,this.type=i,this.dispatchLayout=Je(e),this.dispatch=Le(this.dispatchLayout,e,this.workGroupSize),this.sliceDimGreaterThanOne=t>1,this.shaderKey=`scatter_${r}_${n}_${this.sliceDimGreaterThanOne}_${i}`;let o=Ar(a.length);this.uniforms=`sliceDim : i32, strides: ${o}, size: i32,`,this.updatesRank=n,this.indicesRank=r}getUserCode(){let e="";this.indicesRank===1?e="coords[0]":this.indicesRank===2&&(e="coords[0], j");let t=`getIndices(${e})`,r=this.sliceDimGreaterThanOne?"uniforms.strides[j]":"uniforms.strides",n="",a="",s="";this.updatesRank===1?(n="coords[0]",a="flattenedIndex",s=`
|
|
fn getUpdatesCoordsFromFlatIndex(index : i32) -> i32 {
|
|
return index;
|
|
}
|
|
`):this.updatesRank===2&&(n="coords[0], coords[1]",a="vec2<i32>(flattenedIndex, coords[1])",s=`
|
|
fn getUpdatesCoordsFromFlatIndex(index : i32) -> vec2<i32> {
|
|
let d0 = index / uniforms.updatesShape[1];
|
|
let d1 = index - d0 * uniforms.updatesShape[1];
|
|
return vec2<i32>(d0, d1);
|
|
}
|
|
`);let i=`getUpdates(${n})`,o=this.type==="int32"?"atomicAdd(&(result[flatIndex]), i32(updateValue));":`
|
|
var oldValue = atomicLoad(&(result[flatIndex]));
|
|
var exchanged = false;
|
|
for (; !exchanged;) {
|
|
let newValueF32 = bitcast<f32>(oldValue) + updateValue;
|
|
let newValue = bitcast<i32>(newValueF32);
|
|
let res = atomicCompareExchangeWeak(&(result[flatIndex]), oldValue, newValue);
|
|
oldValue = res.old_value;
|
|
exchanged = res.exchanged;
|
|
}
|
|
`;return`
|
|
${s}
|
|
|
|
${rt()}
|
|
|
|
if (index < uniforms.size) {
|
|
let coords = getUpdatesCoordsFromFlatIndex(index);
|
|
var flattenedIndex = 0;
|
|
for (var j = 0; j < uniforms.sliceDim; j = j + 1) {
|
|
let indexInside = i32(round(${t}));
|
|
flattenedIndex = flattenedIndex + indexInside * ${r};
|
|
}
|
|
let updateValue = ${i};
|
|
let flatIndex = getOutputIndexFromCoords(${a});
|
|
|
|
${o}
|
|
}
|
|
}`}};function Wfe(e){let{inputs:t,backend:r,attrs:n}=e,{indices:a,updates:s}=t,{shape:i}=n,{sliceRank:o,numUpdates:l,sliceSize:u,strides:d,outputSize:h}=C.calculateShapes(s,a,i),p=[h/u,u];if(h===0)return r.makeTensorInfo(i,a.dtype);let c=qe({inputs:{x:a},backend:r,attrs:{shape:[l,o]}}),m=qe({inputs:{x:s},backend:r,attrs:{shape:[l,u]}}),f=m.dtype,g=Wd({backend:r,attrs:{shape:p,value:0,dtype:f}}),y=v.sizeFromShape(m.shape),A=[{type:"int32",data:[o]},{type:"int32",data:d},{type:"int32",data:[y]}],x=new Bfe(m.shape,o,c.shape.length,m.shape.length,d,p,f),b=r.runWebGPUProgram(x,[m,c],f,A,g),w=qe({inputs:{x:b},backend:r,attrs:{shape:i}});return r.disposeData(c.dataId),r.disposeData(m.dataId),r.disposeData(b.dataId),w}var Vfe={kernelName:yl,backendName:"webgpu",kernelFunc:Wfe},Ufe=class{constructor(e,t,r){this.variableNames=["c","a","b"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.cRank=e,this.rank=r,this.shaderKey="select"}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 r=["resRC.x","resRC.y","resRC.z","resRC.w"],n=[],a=[];for(let s=0;s<this.outputShape.length;s++)a.push(`${r[s]}`),s<this.cRank&&n.push(`${r[s]}`);e=n.join(),t=a.join()}return`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let resRC = getCoordsFromIndex(index);
|
|
let cVal = getC(${e});
|
|
if (cVal >= 1.0) {
|
|
setOutputAtIndex(index, getA(${t}));
|
|
} else {
|
|
setOutputAtIndex(index, getB(${t}));
|
|
}
|
|
}
|
|
}
|
|
`}};function Gfe(e){let{inputs:t,backend:r}=e,{condition:n,t:a,e:s}=t,i=new Ufe(n.shape.length,a.shape,a.shape.length);return r.runWebGPUProgram(i,[n,a,s],Nr(a.dtype,s.dtype))}var jfe={kernelName:Al,backendName:"webgpu",kernelFunc:Gfe},Hfe=kr({opType:18}),qfe={kernelName:Pi,backendName:"webgpu",kernelFunc:Hfe},Xfe=kr({opType:16}),Kfe={kernelName:_i,backendName:"webgpu",kernelFunc:Xfe},Zfe=kr({opType:17}),Yfe={kernelName:bl,backendName:"webgpu",kernelFunc:Zfe},wS=Kr({opSnippet:2,cpuKernelImpl:Phe,supportsComplex:!0}),Jfe={kernelName:Bi,backendName:"webgpu",kernelFunc:wS};function Qfe(e){let{inputs:t,backend:r,attrs:n}=e,{logits:a}=t,{dim:s}=n,i=v.parseAxisParam([s],a.shape),o=AS({inputs:{x:a},backend:r,attrs:{reductionIndices:i,keepDims:!1}}),l=C.expandShapeToKeepDim(o.shape,i),u=qe({inputs:{x:o},backend:r,attrs:{shape:l}}),d=wS({inputs:{a,b:u},backend:r}),h=gS({inputs:{x:d},backend:r}),p=VA({inputs:{x:h},backend:r,attrs:{axis:i,keepDims:!1}}),c=qe({inputs:{x:p},backend:r,attrs:{shape:l}}),m=vS({inputs:{a:h,b:c},backend:r});return r.disposeData(o.dataId),r.disposeData(u.dataId),r.disposeData(d.dataId),r.disposeData(h.dataId),r.disposeData(p.dataId),r.disposeData(c.dataId),m}var eme={kernelName:Di,backendName:"webgpu",kernelFunc:Qfe},tme=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,paddings:i}=n;v.assert(a.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGPU backend not implemented yet");let o=s.reduce((y,A)=>y*A),l=[[0,0]];l.push(...i);for(let y=1+s.length;y<a.shape.length;++y)l.push([0,0]);let u=[],d=bS({inputs:{x:a},backend:r,attrs:{paddings:l,constantValue:0}}),h=C.getReshaped(d.shape,s,o,!1),p=C.getPermuted(h.length,s.length,!1),c=C.getReshapedPermuted(d.shape,s,o,!1),m=qe({inputs:{x:d},backend:r,attrs:{shape:h}}),f=Ja({inputs:{x:m},backend:r,attrs:{perm:p}}),g=qe({inputs:{x:f},backend:r,attrs:{shape:c}});return u.push(d),u.push(m),u.push(f),u.forEach(y=>r.disposeData(y.dataId)),g},rme={kernelName:vl,backendName:"webgpu",kernelFunc:tme},nme=class{constructor(e,t,r,n,a,s,i=!0){this.variableNames=["updates","indices","defaultValue"],this.workGroupSize=[64,1,1],this.workPerThread=4,this.size=!0,this.outputShape=s,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]);let o=t>1;this.shaderKey=`scatter_${r}_${n}_${o}`;let l=Ar(a.length);this.uniforms=`updateSize : i32, sliceDim : i32, strides: ${l},`;let u="";r===1?u="i":r===2&&(u="i, j"),this.indicesSnippet=`getIndices(${u})`;let d="";n===1?d="i":n===2&&(d="i, coords[1]"),this.updatesSnippet=`getUpdates(${d})`,this.strideString=o?"uniforms.strides[j]":"uniforms.strides"}getUserCode(){return`
|
|
${rt()}
|
|
|
|
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 = getCoordsFromIndex(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)
|
|
{
|
|
setOutputAtIndex(curIndex, mix(getDefaultValue(), sum[innerIndex], f32(found[innerIndex])));
|
|
}
|
|
}
|
|
}
|
|
}`}};function ame(e){let{inputs:t,backend:r,attrs:n}=e,{sparseIndices:a,sparseValues:s,defaultValue:i}=t,{outputShape:o}=n,{sliceRank:l,numUpdates:u,sliceSize:d,strides:h,outputSize:p}=C.calculateShapes(s,a,o),c=!1;if(s.dtype==="string"){let A=r.bufferSync(a),x=r.bufferSync(s),b=v.decodeString(r.readSync(i.dataId)[0]),w=Rhe(A,x,o,p,d,u,l,h,b,c);return r.makeTensorInfo(o,w.dtype,w.values)}let m=[{type:"int32",data:[u]},{type:"int32",data:[l]},{type:"int32",data:h}],f=new nme(u,l,a.shape.length,s.shape.length,h,[p,1],c),g=r.runWebGPUProgram(f,[s,a,i],s.dtype,m),y=qe({inputs:{x:g},backend:r,attrs:{shape:o}});return r.disposeData(g.dataId),y}var sme={kernelName:yh,backendName:"webgpu",kernelFunc:ame};function ime(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{numOrSizeSplits:s,axis:i}=n,o=v.parseAxisParam(i,a.shape)[0],l=C.prepareSplitSize(a,s,o),u=a.shape.length,d=new Array(u).fill(0),h=a.shape.slice();return l.map(p=>{let c=[...h];c[o]=p;let m=Bd({inputs:{x:a},backend:r,attrs:{begin:d,size:c}});return d[o]+=p,m})}var ome={kernelName:wl,backendName:"webgpu",kernelFunc:ime},lme=kr({opType:19}),ume={kernelName:Oi,backendName:"webgpu",kernelFunc:lme},dme={kernelName:Ad,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{x:r}=e,n=t,a=new Qh(r.shape,20);return n.runWebGPUProgram(a,[r],r.dtype)}},pme=Kr({opSnippet:11}),hme={kernelName:Li,backendName:"webgpu",kernelFunc:pme},cme=class{constructor(e){this.variableNames=["x"],this.workPerThread=1,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]);let t=Ar(this.outputShape.length);this.uniforms=`begin : ${t}, strides : ${t}, `,this.shaderKey="stridedSlice"}getUserCode(){let e=this.outputShape.length,t="";if(e===1)t="coords * uniforms.strides + uniforms.begin";else{let r=0;t=this.outputShape.map((n,a)=>(r++,this.outputShape.length===1?`coords * uniforms.strides[${a}] + uniforms.begin[${a}]`:`coords[${r-1}] * uniforms.strides[${a}] + uniforms.begin[${a}]`)).join(",")}return`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
setOutputAtIndex(index, getX(${t}));
|
|
}
|
|
}
|
|
`}};function fme(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:d,newAxisMask:h,shrinkAxisMask:p}=n,{finalShapeSparse:c,finalShape:m,isIdentity:f,sliceDim0:g,isSimpleSlice:y,begin:A,end:x,strides:b}=Dt.sliceInfo(a.shape,s,i,o,l,u,d,h,p),w;if(f)w=qe({inputs:{x:a},backend:r,attrs:{shape:m}});else if(g||y){v.assert(a.shape.length>=1,()=>`Input must have rank at least 1, got: ${a.shape.length}`);let I=Dt.computeOutShape(A,x,b),T=Bd({inputs:{x:a},backend:r,attrs:{begin:A,size:I}});w=qe({inputs:{x:T},backend:r,attrs:{shape:m}}),r.disposeData(T.dataId)}else if(r.shouldExecuteOnCPU([a])){let I=r.readSync(a.dataId),T=De(a.shape,a.dtype,I),E=Fhe(c,T,b,A);w=r.makeTensorInfo(m,a.dtype,E.values)}else{let I=new cme(c),T=[{type:"int32",data:A},{type:"int32",data:b}],E=r.runWebGPUProgram(I,[a],a.dtype,T);w=qe({inputs:{x:E},backend:r,attrs:{shape:m}}),r.disposeData(E.dataId)}return w}var mme={kernelName:kl,backendName:"webgpu",kernelFunc:fme};function gme(e){let{inputs:t,backend:r,attrs:n}=e,{separator:a,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=n,{data:d,dataSplits:h}=t,p=r.readSync(d.dataId),c=r.readSync(h.dataId),[m,f]=_he(p,c,a,s,i,o,l,u);return[r.makeTensorInfo([m.length],"string",m),r.makeTensorInfo(h.shape,"int32",f)]}var yme={kernelName:Ah,backendName:"webgpu",kernelFunc:gme},Ame=kr({opType:21}),xme={kernelName:Wi,backendName:"webgpu",kernelFunc:Ame},bme=class{constructor(e,t){this.variableNames=["A"],this.workGroupSize=[64,1,1],this.size=!0;let r=new Array(e.length);for(let n=0;n<r.length;n++)r[n]=e[n]*t[n];this.outputShape=r,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.rank=this.outputShape.length,this.shaderKey="tile"}getUserCode(){let e=vme(this.rank,"uniforms.");return`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let resRC = getCoordsFromIndex(index);
|
|
setOutputAtIndex(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 r=["resRC.x","resRC.y","resRC.z","resRC.w"],n=[];for(let a=0;a<e;a++)n.push(`(${r[a]} % ${t}aShape[${a}])`);return n.join()}function wme(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{reps:s}=n;if(r.shouldExecuteOnCPU([a])||a.dtype==="string"||a.shape.length>=5){let o=r.readSync(a.dataId),l=a.dtype==="string"?o.map(h=>v.decodeString(h)):o,u=De(a.shape,a.dtype,l),d=Ohe(u,s);return r.makeTensorInfo(d.shape,d.dtype,d.values)}let i=new bme(a.shape,s);return r.runWebGPUProgram(i,[a],a.dtype)}var kme={kernelName:ts,backendName:"webgpu",kernelFunc:wme},Ime=class{constructor(e){this.variableNames=["x","indices"],this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms=`inputSize : i32, firstPass : i32, negativeInf : f32,
|
|
dir : i32, inc : i32,`,this.shaderKey="swap"}getUserCode(){return`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let outC = getCoordsFromIndex(index);
|
|
let batch = outC[0];
|
|
let elemIdx = outC[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.
|
|
let isFirstInPair = elemIdx % (2 * uniforms.inc) < uniforms.inc;
|
|
var i = 0;
|
|
if (isFirstInPair) {
|
|
i = elemIdx;
|
|
} else {
|
|
i = elemIdx - uniforms.inc;
|
|
}
|
|
|
|
var i0 = 0;
|
|
if (uniforms.firstPass == 1) {
|
|
i0 = i;
|
|
} else {
|
|
i0 = i32(getIndices(batch, i));
|
|
}
|
|
|
|
var i1 = 0;
|
|
if (uniforms.firstPass == 1) {
|
|
i1 = i + uniforms.inc;
|
|
} else {
|
|
i1 = i32(getIndices(batch, i + uniforms.inc));
|
|
}
|
|
|
|
var x0 = f32(0.0);
|
|
var x1 = f32(0.0);
|
|
if (i0 < uniforms.inputSize) {
|
|
x0 = getX(batch, i0);
|
|
} else {
|
|
x0 = uniforms.negativeInf;
|
|
}
|
|
if (i1 < uniforms.inputSize) {
|
|
x1 = getX(batch, i1);
|
|
} else {
|
|
x1 = uniforms.negativeInf;
|
|
}
|
|
|
|
let reverse = elemIdx % (2 * uniforms.dir) >= uniforms.dir;
|
|
let isGreater = x0 > x1 || (x0 == x1 && i1 > i0);
|
|
if (reverse == isGreater) {
|
|
// Elements in opposite order of direction
|
|
let iTemp = i0;
|
|
i0 = i1;
|
|
i1 = iTemp;
|
|
}
|
|
if (isFirstInPair) {
|
|
setOutputAtIndex(index, f32(i0));
|
|
} else {
|
|
setOutputAtIndex(index, f32(i1));
|
|
}
|
|
}
|
|
}
|
|
`}},Sme=class{constructor(e){this.variableNames=["x","indices"],this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms="inputSize : i32, firstPass : i32, k : i32,",this.shaderKey="merge"}getUserCode(){return`
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let outC = getCoordsFromIndex(index);
|
|
let batch = outC[0];
|
|
let elemIdx = outC[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.
|
|
|
|
var i = 0;
|
|
if (elemIdx < uniforms.k) {
|
|
i = elemIdx;
|
|
} else {
|
|
i = elemIdx * 2 - elemIdx % uniforms.k;
|
|
}
|
|
var i0 = 0;
|
|
if (uniforms.firstPass == 1) {
|
|
i0 = i;
|
|
} else {
|
|
i0 = i32(getIndices(batch, i));
|
|
}
|
|
var i1 = 0;
|
|
if (uniforms.firstPass == 1) {
|
|
i1 = i + uniforms.k;
|
|
} else {
|
|
i1 = i32(getIndices(batch, i + uniforms.k));
|
|
}
|
|
|
|
let x0 = getX(batch, i0);
|
|
var x1 = f32(0.0);
|
|
if (i1 < uniforms.inputSize) {
|
|
x1 = getX(batch, i1);
|
|
} else {
|
|
x1 = x0;
|
|
}
|
|
|
|
if (x0 >= x1) {
|
|
setOutputAtIndex(index, f32(i0));
|
|
} else {
|
|
setOutputAtIndex(index, f32(i1));
|
|
}
|
|
}
|
|
}
|
|
`}};function Au(e,t){t!==null&&e.disposeData(t.dataId)}function N7(e){let t=1;for(;t<e;)t*=2;return t}function Cme(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{k:s,sorted:i}=n,o=a.shape,l=o[o.length-1];if(r.shouldExecuteOnCPU([a])){let b=r.readSync(a.dataId),[w,I]=zhe(b,o,a.dtype,s,i);return[r.makeTensorInfo(w.shape,w.dtype,w.values),r.makeTensorInfo(I.shape,I.dtype,I.values)]}if(s===0)return o[o.length-1]=0,[r.makeTensorInfo(o,a.dtype,[]),r.makeTensorInfo(o,"int32",[])];if(l===1)return[a,Wd({attrs:{shape:o,dtype:"int32",value:0},backend:r})];let u=v.sizeFromShape(o)/l,d=qe({inputs:{x:a},attrs:{shape:[u,l]},backend:r}),h=N7(s),p=N7(l),c=null,m=()=>c===null?[d,d]:[d,c],f=(b,w,I)=>{let T=m(),E=new Ime(I),R=[{type:"int32",data:[l]},{type:"int32",data:[c===null?1:0]},{type:"float32",data:[Number.NEGATIVE_INFINITY]},{type:"int32",data:[b]},{type:"int32",data:[w]}],F=c;c=r.runWebGPUProgram(E,T,"int32",R),Au(r,F)};for(let b=1;b<h;b*=2){let w=b*2;for(let I=b;I>=1;I/=2)f(w,I,[u,p])}for(let b=p;b>h;b/=2){let w=m(),I=new Sme([u,b/2]),T=[{type:"int32",data:[l]},{type:"int32",data:[c===null?1:0]},{type:"int32",data:[h]}],E=c;c=r.runWebGPUProgram(I,w,"int32",T),Au(r,E);let R=h/2,F=R*2;for(let $=R;$>=1;$/=2)f(F,$,c.shape)}let g=c;c=Bd({inputs:{x:c},backend:r,attrs:{begin:0,size:[u,s]}}),Au(r,g);let y=yS({inputs:{x:d,indices:c},backend:r,attrs:{axis:1,batchDims:1}});Au(r,d);let A=o.slice(0,-1);A.push(s),g=c,c=qe({inputs:{x:c},attrs:{shape:A},backend:r}),Au(r,g);let x=y;return y=qe({inputs:{x:y},attrs:{shape:A},backend:r}),Au(r,x),[y,c]}var Tme={kernelName:Sl,backendName:"webgpu",kernelFunc:Cme},Nme=class{constructor(e){this.variableNames=["Image","Transforms"],this.uniforms="interpolationModeId : i32, fillModeId : i32, fillValue : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Je(this.outputShape),this.dispatch=Le(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;
|
|
}
|
|
}
|
|
} else if (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);
|
|
} else if (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);
|
|
}
|
|
} else if (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);
|
|
} else if (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;
|
|
}
|
|
|
|
${rt()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
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;
|
|
}
|
|
}
|
|
setOutputAtIndex(index, outputValue);
|
|
}
|
|
}
|
|
`}};function Eme(e){let{inputs:t,backend:r,attrs:n}=e,{image:a,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=n,[d,h,p,c]=a.shape,[m,f]=u!=null?u:[h,p],g=[d,m,f,c],y=new Nme(g),A=i==="nearest"?1:2,x;switch(o){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 r.runWebGPUProgram(y,[a,s],"float32",b)}var Rme={kernelName:Cl,backendName:"webgpu",kernelFunc:Eme};function $me(e){let{inputs:t,backend:r,attrs:n}=e,{value:a}=t,{axis:s}=n;s<0&&(s+=a.shape.length);let i=a,o=i.shape.length,l=a.shape[s],u=new Array(o-1),d=0;for(let f=0;f<o;f++)f!==s&&(u[d++]=i.shape[f]);let h=[],p=new Array(o).fill(0),c=i.shape.slice();c[s]=1;let m=new Array(l);for(let f=0;f<m.length;f++){p[s]=f;let g=Bd({inputs:{x:i},backend:r,attrs:{begin:p,size:c}}),y=qe({inputs:{x:g},backend:r,attrs:{shape:u}});m[f]=y,h.push(g)}return h.forEach(f=>r.disposeData(f.dataId)),m}var Mme={kernelName:Tl,backendName:"webgpu",kernelFunc:$me},Fme=[rhe,Bhe,Vhe,jhe,Yhe,Qhe,tce,nce,lce,hce,fce,Ace,ihe,wce,Tce,$ce,Fce,Pce,Dce,Bce,Vce,jce,qce,Jce,e0e,r0e,n0e,a0e,i0e,l0e,d0e,g0e,h0e,f0e,x0e,v0e,k0e,C0e,E0e,$0e,F0e,she,bce,P0e,z0e,L0e,W0e,U0e,j0e,H0e,X0e,Z0e,J0e,efe,rfe,afe,Xce,ife,lfe,dfe,uce,hfe,ffe,gfe,Afe,bfe,wfe,Ife,dce,Sfe,Tfe,Efe,ehe,Mfe,Pfe,zfe,Lfe,Vfe,jfe,qfe,Kfe,Yfe,ice,mme,yme,eme,rme,sme,ome,ume,dme,hme,Jfe,Zce,xme,kme,Tme,Rme,Khe,Mme,pfe];for(let e of Fme)qn(e);var _me=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}acquireUploadBuffer(e,t){return this.acquireBuffer(e,t,!0)}acquireBuffer(e,t,r=!1){let n=E7(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 s=this.freeBuffers.get(n).shift();return this.usedBuffers.get(n).push(s),s}this.numBytesAllocated+=e;let a=this.device.createBuffer({mappedAtCreation:r,size:e,usage:t});return this.usedBuffers.get(n).push(a),a}releaseBuffer(e,t,r){if(this.freeBuffers.size===0)return;let n=E7(t,r);this.freeBuffers.has(n)||this.freeBuffers.set(n,[]),this.freeBuffers.get(n).push(e),this.numFreeBuffers++,this.numUsedBuffers--;let a=this.usedBuffers.get(n),s=a.indexOf(e);if(s<0)throw new Error("Cannot release a buffer that was never provided by this buffer manager");a.splice(s,1),this.numBytesUsed-=t}releaseUploadBuffer(e,t,r){e.mapAsync(GPUMapMode.WRITE).then(()=>{this.releaseBuffer(e,t,r)},n=>{})}getNumUsedBuffers(){return this.numUsedBuffers}getNumFreeBuffers(){return this.numFreeBuffers}dispose(){this.freeBuffers.forEach((e,t)=>{e.forEach(r=>{r.destroy()})}),this.usedBuffers.forEach((e,t)=>{e.forEach(r=>{r.destroy()})}),this.freeBuffers=new Map,this.usedBuffers=new Map,this.numUsedBuffers=0,this.numFreeBuffers=0,this.numBytesUsed=0,this.numBytesAllocated=0}};function E7(e,t){return`${e}_${t}`}var Pme=class{constructor(e){this.device=e,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures=new Map,this.usedTextures=new Map,this.numBytesUsed=0,this.numBytesAllocated=0}acquireTexture(e,t,r,n){let a=$7(r),s=e*t*a,i=R7(e,t,r,n);if(this.freeTextures.has(i)||this.freeTextures.set(i,[]),this.usedTextures.has(i)||this.usedTextures.set(i,[]),this.numBytesUsed+=s,this.numUsedTextures++,this.freeTextures.get(i).length>0){this.numFreeTextures--;let l=this.freeTextures.get(i).shift();return this.usedTextures.get(i).push(l),l}this.numBytesAllocated+=s;let o=this.device.createTexture({size:[e,t],format:r,usage:n});return this.usedTextures.get(i).push(o),o}releaseTexture(e,t,r,n,a){if(this.freeTextures.size===0)return;let s=R7(t,r,n,a);this.freeTextures.has(s)||this.freeTextures.set(s,[]),this.freeTextures.get(s).push(e),this.numFreeTextures++,this.numUsedTextures--;let i=this.usedTextures.get(s),o=i.indexOf(e);if(o<0)throw new Error("Cannot release a texture that was never provided by this texture manager");i.splice(o,1);let l=$7(n),u=t*r*l;this.numBytesUsed-=u}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){this.freeTextures.forEach((e,t)=>{e.forEach(r=>{r.destroy()})}),this.usedTextures.forEach((e,t)=>{e.forEach(r=>{r.destroy()})}),this.freeTextures=new Map,this.usedTextures=new Map,this.numUsedTextures=0,this.numFreeTextures=0,this.numBytesUsed=0,this.numBytesAllocated=0}};function R7(e,t,r,n){return`${e}_${t}_${r}_${n}`}function $7(e){if(e==="rgba8unorm")return 16;throw new Error(`${e} is not supported!`)}var Ome=Z().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD"),M7=(e,t)=>{let r=e.limits.maxComputeWorkgroupsPerDimension,n=t.dispatchLayout,a=t.dispatch;if(a.every(i=>i<=r))return a;v.assert(a[0]>r&&n.y===void 0&&n.z===void 0,()=>"Dispatch size exceeds WebGPU limits in Y or Z dimension.");let s=Math.ceil(Math.sqrt(a[0]));return s>r?(s=Math.ceil(Math.cbrt(a[0])),v.assert(s<=r,()=>"Total dispatch size exceeds WebGPU maximum."),[s,s,s]):[s,s,1]},kS=class extends Gu{constructor(e,t=!1){if(super(),this.commandQueueOwnedIds=new WeakSet,this.tensorDisposalQueue=[],this.uniformDisposalQueue=[],this.stagingDisposalQueue=[],this.textureDisposalQueue=[],this.disposed=!1,this.uploadWaitMs=0,this.downloadWaitMs=0,this.dispatchNumberInEncoder=0,this.fromPixelTextureLayout=null,this.fromPixelImportTextureLayout=null,!DA())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 _me(this.device),this.textureManager=new Pme(this.device),this.tensorMap=new nh(this,Xt()),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 kS.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.stagingDisposalQueue.forEach(e=>this.bufferManager.releaseUploadBuffer(e.buffer,e.byteSize,e.usage)),this.textureDisposalQueue.forEach(e=>this.textureManager.releaseTexture(e.texture,e.width,e.height,e.format,e.usage)),this.tensorDisposalQueue=[],this.uniformDisposalQueue=[],this.stagingDisposalQueue=[],this.textureDisposalQueue=[]}disposeData(e,t=!1){if(this.tensorMap.has(e)){let r=this.tensorMap.get(e);if(r.refCount--,!t&&r.refCount>0)return!1;if(this.commandQueueOwnedIds.has(e))return this.tensorDisposalQueue.push(e),!1;this.maybeReleaseBuffer(e);let{complexTensorInfos:n}=this.tensorMap.get(e);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.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}getTextureManager(){return this.textureManager}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,r){if(r==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let n={id:this.nextDataId()},a=v.sizeFromShape(t)*w0(r);return this.tensorMap.set(n,{dtype:r,shape:t,values:e,bufferInfo:{byteSize:a,usage:this.defaultGpuBufferUsage()},refCount:1}),n}move(e,t,r,n,a){if(n==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let s=v.sizeFromShape(r)*w0(n);this.tensorMap.set(e,{dtype:n,shape:r,values:t,bufferInfo:{byteSize:s,usage:this.defaultGpuBufferUsage()},refCount:a})}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}ensureCommandEncoderReady(){this.currentCommandEncoder||(this.currentCommandEncoder=this.device.createCommandEncoder())}ensureComputePassEnded(){this.currentComputePass&&(this.currentComputePass.end(),this.currentComputePass=null)}getComputePass(){return this.currentComputePass||(this.currentComputePass=this.currentCommandEncoder.beginComputePass()),this.currentComputePass}async getBufferData(e,t){let r=this.acquireBuffer(t,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(e,0,r,0,t),this.submitQueue(),await r.mapAsync(GPUMapMode.READ);let n=r.getMappedRange().slice(0);return r.unmap(),r!=null&&this.bufferManager.releaseBuffer(r,t,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 r=this.tensorMap.get(e);return this.maybeReleaseBuffer(e),r.values=t,r.values}readSync(e){let t=this.tensorMap.get(e),{values:r}=t;if(r==null)throw new Error("WebGPU readSync is only available for CPU-resident tensors.");return r}async read(e){if(!this.tensorMap.has(e))throw new Error(`Tensor ${e} was not registered!`);let t=this.tensorMap.get(e),{values:r}=t;if(r!=null)return this.convertAndCacheOnCPU(e,r);let n;if(t.dtype==="complex64"){let a=await Promise.all([this.read(t.complexTensorInfos.real.dataId),this.read(t.complexTensorInfos.imag.dataId)]),s=a[0],i=a[1];n=C.mergeRealAndImagArrays(s,i)}else{let a=t.values!=null?t.values:await this.getBufferData(t.bufferInfo.buffer,t.bufferInfo.byteSize);n=rS(a,t.dtype)}return this.convertAndCacheOnCPU(e,n),n}readToGPU(e){let t=this.tensorMap.get(e),{values:r,dtype:n,shape:a,bufferInfo:s}=t;if(n==="complex64")throw new Error("Does not support reading buffer for complex64 dtype.");if(s.buffer==null)throw r!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");let i=v.sizeFromShape(a)*w0(n),o=this.acquireBuffer(i);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(s.buffer,0,o,0,i),this.submitQueue();let l=this.makeTensorInfo(a,n),u=Xt().makeTensorFromTensorInfo(l),d=this.tensorMap.get(l.dataId);return d.bufferInfo.buffer=o,{tensorRef:u,buffer:o,bufSize:i}}bufferSync(e){let t=this.readSync(e.dataId);if(e.dtype==="string")try{let r=t.map(n=>v.decodeString(n));return De(e.shape,e.dtype,r)}catch(r){throw new Error("Failed to decode encoded string bytes into utf-8")}return De(e.shape,e.dtype,t)}async time(e){let t=this.activeTimers,r=[],n=!1;this.programTimersStack==null?(this.programTimersStack=r,n=!0):this.activeTimers.push(r),this.activeTimers=r,e();let a=v.flatten(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),s=v.flatten(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=t,n&&(this.programTimersStack=null);let i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},o=await Promise.all(a);return i.kernelMs=v.sum(o),i.getExtraProfileInfo=()=>o.map((l,u)=>({name:s[u],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", "),this.uploadWaitMs=0,this.downloadWaitMs=0,i}getAndSavePipeline(e,t){return e in this.pipelineCache||(this.pipelineCache[e]=t()),this.pipelineCache[e]}makeTensorInfo(e,t,r){let n;if(t==="string"&&r!=null&&r.length>0&&v.isString(r[0])){let a=r.map(s=>v.encodeString(s));n=this.write(a,e,t)}else n=this.write(r,e,t);return{dataId:n,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);if(t.bufferInfo.buffer==null&&(t.bufferInfo.buffer=this.acquireBuffer(t.bufferInfo.byteSize),t.values)){let r=this.bufferManager.acquireUploadBuffer(t.bufferInfo.byteSize,GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC),n=r.getMappedRange();t.dtype==="int32"||t.dtype==="bool"?new Int32Array(n).set(t.values):new Float32Array(n).set(t.values),r.unmap(),this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(r,0,t.bufferInfo.buffer,0,t.bufferInfo.byteSize);let a={byteSize:t.bufferInfo.byteSize,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC,buffer:r};this.stagingDisposalQueue.push(a)}}makeUniforms(e){let t=0,r=0,n=[];e.forEach(o=>{o.data.length===0&&(o.data=[1]);let l;switch(o.data.length){case 1:l=4;break;case 2:l=8;break;case 3:l=16;break;case 4:l=16;break;case 5:l=16;break;case 6:l=16;break;default:v.assert(!1,()=>`Unsupported ${o.data.length}D shape`)}(r===5||r===6)&&(l=16),t=Math.ceil(t/l)*l,r=o.data.length,n.push(t),t+=o.data.length*4});let a=new ArrayBuffer(t);e.forEach((o,l)=>{let u=n[l];o.type==="int32"?new Int32Array(a,u,o.data.length).set(o.data):o.type==="uint32"?new Uint32Array(a,u,o.data.length).set(o.data):new Float32Array(a,u,o.data.length).set(o.data)});let s=this.acquireBuffer(t,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.queue.writeBuffer(s,0,a,0,t);let i={byteSize:t,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM,buffer:s};return this.uniformDisposalQueue.push(i),{offset:0,size:t,buffer:s}}createLayout(e){let t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}});for(let a=0;a<e;a++)t.push({binding:a+1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}});t.push({binding:e+1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}});let r=this.device.createBindGroupLayout({entries:t}),n=this.device.createPipelineLayout({bindGroupLayouts:[r]});return{bindGroupLayout:r,pipelineLayout:n}}getCachedOrCreateLayout(e){return e in this.layoutCache||(this.layoutCache[e]=this.createLayout(e)),this.layoutCache[e]}makeBindGroup(e,t,r,n,a){let s=[n,...r];return a&&s.push(a),e.createBindGroup({layout:t,entries:s.map((i,o)=>({binding:o,resource:i}))})}runWebGPUProgram(e,t,r,n,a){if(!a){if(a=this.makeTensorInfo(e.outputShape,r),v.sizeFromShape(a.shape)===0){let I=this.tensorMap.get(a.dataId);return I.values=v.getTypedArrayFromDType(a.dtype,0),a}this.uploadToGPU(a.dataId)}e.dispatch=M7(this.device,e);let s=[{type:"float32",data:[NaN]}],i=t.concat(a).map(I=>I.shape),o="int32";i.map(I=>{s.push({type:o,data:I})});let l=v.computeStrides(a.shape);if(s.push({type:o,data:l}),e.size){let I=v.sizeFromShape(e.outputShape);s.push({type:o,data:[e.isVec4?I/4:I]})}n&&(s=[...s,...n]);let u=this.makeUniforms(s),d=t.map((I,T)=>{if(I.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(I.dataId),{dtype:this.tensorMap.get(I.dataId).dtype,shape:I.shape,name:e.variableNames[T]}}),h=d.map(I=>I.dtype).concat(a.dtype),p=d.map(I=>C.getBroadcastDims(I.shape,a.shape)),c=d.map(I=>v.arraysEqual(I.shape,a.shape)).join("_"),m=p.map(I=>I.join("_")).join(";"),f=A7(e,i,h,m,c),{bindGroupLayout:g,pipelineLayout:y}=this.getCachedOrCreateLayout(e.variableNames.length),A=this.getAndSavePipeline(f,()=>y7(this.device,e,y,d,a)),x=this.activeTimers!=null,b=this.makeBindGroup(this.device,g,t.map(I=>this.tensorToBinding(I)),this.tensorToBinding(a),u);this.ensureCommandEncoderReady();let w=this.getComputePass();return x&&this.supportTimeQuery&&w.writeTimestamp(this.querySet,0),w.setPipeline(A),w.setBindGroup(0,b),w.dispatchWorkgroups(e.dispatch[0],e.dispatch[1],e.dispatch[2]),x&&this.supportTimeQuery&&w.writeTimestamp(this.querySet,1),this.dispatchNumberInEncoder++,t.forEach(I=>{this.commandQueueOwnedIds.add(I.dataId)}),this.commandQueueOwnedIds.add(a.dataId),Z().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE")<=this.dispatchNumberInEncoder&&this.submitQueue(),x&&this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(this.querySet)}),a}getFromPixelTextureLayout(e){return e?(this.fromPixelImportTextureLayout===null&&(this.fromPixelImportTextureLayout=this.createFromPixelTextureLayout(!0)),this.fromPixelImportTextureLayout):(this.fromPixelTextureLayout===null&&(this.fromPixelTextureLayout=this.createFromPixelTextureLayout(!1)),this.fromPixelTextureLayout)}createFromPixelTextureLayout(e){let t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}),e?t.push({binding:1,visibility:GPUShaderStage.COMPUTE,externalTexture:{}}):t.push({binding:1,visibility:GPUShaderStage.COMPUTE,texture:{}}),t.push({binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{}});let r=this.device.createBindGroupLayout({entries:t}),n=this.device.createPipelineLayout({bindGroupLayouts:[r]});return{bindGroupLayout:r,pipelineLayout:n}}copyExternalImageToTexture(e,t){let r=GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,n="rgba8unorm",a=this.textureManager.acquireTexture(t[1],t[0],n,r),s=a.createView();this.queue.copyExternalImageToTexture({source:e},{texture:a},[t[1],t[0]]);let i={width:t[1],height:t[0],format:n,usage:r,texture:a};return this.textureDisposalQueue.push(i),s}runFromPixelsProgram(e,t,r,n,a){e.dispatch=M7(this.device,e);let s=this.makeTensorInfo(t,"int32");if(v.sizeFromShape(s.shape)===0){let f=this.tensorMap.get(s.dataId);return f.values=v.getTypedArrayFromDType(s.dtype,0),s}this.uploadToGPU(s.dataId);let i=A7(e,[s.shape]),o=this.getFromPixelTextureLayout(n),l=this.getAndSavePipeline(i,()=>y7(this.device,e,o.pipelineLayout,[],s,!0)),u;if(n){let f={source:a};u=this.device.importExternalTexture(f)}else u=this.copyExternalImageToTexture(a,s.shape);let d=this.tensorToBinding(s),h=this.makeUniforms(r),p=this.device.createBindGroup({layout:o.bindGroupLayout,entries:[{binding:0,resource:{buffer:d.buffer}},{binding:1,resource:u},{binding:2,resource:{buffer:h.buffer}}]});this.ensureCommandEncoderReady();let c=this.getComputePass(),m=this.activeTimers!=null;return m&&this.supportTimeQuery&&c.writeTimestamp(this.querySet,0),c.setPipeline(l),c.setBindGroup(0,p),c.dispatchWorkgroups(e.dispatch[0],e.dispatch[1],e.dispatch[2]),m&&this.supportTimeQuery&&c.writeTimestamp(this.querySet,1),this.commandQueueOwnedIds.add(s.dataId),this.dispatchNumberInEncoder++,Z().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE")<=this.dispatchNumberInEncoder&&this.submitQueue(),m&&this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(this.querySet)}),s}async getTimeFromQuerySet(e){let t=this.acquireBuffer(16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),r=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,r,0,16),this.submitQueue(),await r.mapAsync(GPUMapMode.READ);let n=new BigUint64Array(r.getMappedRange()),a=Number(n[1]-n[0]);return r.unmap(),this.bufferManager.releaseBuffer(r,16,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST),this.bufferManager.releaseBuffer(t,16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),a/1e6}shouldExecuteOnCPU(e,t=Ome){return Z().getBool("WEBGPU_CPU_FORWARD")&&e.every(r=>this.tensorMap.get(r.dataId).bufferInfo.buffer==null&&v.sizeFromShape(r.shape)<t)}numDataIds(){return this.tensorMap.numDataIds()-this.tensorDisposalQueue.length}dispose(){this.disposed||(this.bufferManager.dispose(),this.textureManager.dispose(),this.disposed=!0)}},UA=kS;UA.nextDataId=0;var IS={};Be(IS,{WebGPUBackend:()=>UA,webgpu_util:()=>eS});DA()&&Rl("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),r=t.limits,n={},a=t.features.has("timestamp-query");n.requiredLimits={maxComputeWorkgroupStorageSize:r.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.maxComputeWorkgroupsPerDimension},a?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 s=await t.requestDevice(n);return new UA(s,a)},3);var Ut=(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",e))(Ut||{}),Wm=(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",e))(Wm||{}),SS;function zme(e){SS=e.wasm.cwrap(Ps,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function Dme(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s,bias:i,preluActivationWeights:o}=t;if(a.dtype!=="float32"||s.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:u,activation:d,leakyreluAlpha:h}=n,p=r.dataIdMap.get(a.dataId).id,c=r.dataIdMap.get(s.dataId).id,m=0;if(i!=null){let E=r.dataIdMap.get(i.dataId);if(E.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${E.shape.length}.`);m=E.id}let f=o==null?0:r.dataIdMap.get(o.dataId).id,g=Wm[d];if(g==null)throw new Error(`${d} activation not yet supported for FusedConv2D in the wasm backend.`);let y=l?a.shape[2]:a.shape[1],A=u?s.shape[1]:s.shape[2],x=$l.assertAndGetBroadcastShape(a.shape.slice(0,-2),s.shape.slice(0,-2)),b=r.makeOutput([...x,y,A],a.dtype),w=r.dataIdMap.get(b.dataId).id,I=new Uint8Array(new Int32Array(a.shape).buffer),T=new Uint8Array(new Int32Array(s.shape).buffer);return SS(p,I,a.shape.length,c,T,s.shape.length,l,u,g,m,f,h||0,w),b}var Lme={kernelName:Ps,backendName:"wasm",setupFunc:zme,kernelFunc:Dme};function vr(e,t){let r;function n(s){r=s.wasm.cwrap(e,null,["number","number","number"])}function a(s){let{backend:i,inputs:{x:o}}=s,l=i.dataIdMap.get(o.dataId).id,u=i.makeOutput(o.shape,t||o.dtype),d=i.dataIdMap.get(u.dataId).id;return v.sizeFromShape(u.shape)===0||r(l,Ut[o.dtype],d),u}return{kernelName:e,backendName:"wasm",setupFunc:n,kernelFunc:a}}var Bme=vr(Go);function Ir(e,t,r){let n;function a(i){n=i.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function s(i){let{backend:o,inputs:l}=i,{a:u,b:d}=l,h=o.dataIdMap.get(u.dataId).id,p=o.dataIdMap.get(d.dataId).id,c=r!=null?r:u.dtype,m=C.assertAndGetBroadcastShape(u.shape,d.shape),f=o.makeOutput(m,c);if(v.sizeFromShape(m)===0)return f;let g=new Uint8Array(new Int32Array(u.shape).buffer),y=new Uint8Array(new Int32Array(d.shape).buffer),A=o.dataIdMap.get(f.dataId).id;return n(h,g,u.shape.length,p,y,d.shape.length,Ut[u.dtype],A),f}return{kernelName:e,backendName:"wasm",setupFunc:a,kernelFunc:s}}var Wme=!0,Vme=Ir(Qa,Wme),CS;function Ume(e){CS=e.wasm.cwrap(Zs,null,["array","number","number","number"])}function Gme(e){let{inputs:t,backend:r}=e,n=r.makeOutput(t[0].shape,t[0].dtype);if(v.sizeFromShape(n.shape)===0)return n;let a=t.map(o=>r.dataIdMap.get(o.dataId).id),s=new Uint8Array(new Int32Array(a).buffer),i=r.dataIdMap.get(n.dataId).id;return CS(s,a.length,Ut[n.dtype],i),n}var jme={kernelName:Zs,backendName:"wasm",setupFunc:Ume,kernelFunc:Gme};function Vm(e){let{inputs:{x:t},backend:r}=e,n=r.makeOutput(t.shape,t.dtype),a=r.typedArrayFromHeap(t);return r.typedArrayFromHeap(n).set(a),n}var Hme={kernelName:mi,backendName:"wasm",kernelFunc:Vm},TS;function qme(e){TS=e.wasm.cwrap($a,null,["number","array","number","number","number","array","number"])}function Xs(e){let{inputs:t,backend:r,attrs:n}=e,[a,s]=Kme(t.x.shape,n.perm),i=!0;for(let m=0;m<s.length;m++)s[m]!==m&&(i=!1);let o=Xme(t.x.shape,n.perm),l={dataId:t.x.dataId,shape:a,dtype:t.x.dtype};if(i){let m=Vm({inputs:t,backend:r});return m.shape=o,m}let u=r.makeOutput(o,l.dtype),d=r.dataIdMap.get(l.dataId).id,h=r.dataIdMap.get(u.dataId).id,p=new Uint8Array(new Int32Array(s).buffer),c=new Uint8Array(new Int32Array(l.shape).buffer);return TS(d,c,l.shape.length,Ut[l.dtype],h,p,s.length),u}function Xme(e,t){let r=new Array(e.length);for(let n=0;n<r.length;n++)r[n]=e[t[n]];return r}function Kme(e,t){let r=[],n=[];for(let a=0;a<e.length;++a)e[a]!==1&&r.push(e[a]),e[t[a]]!==1&&n.push(t[a]);for(let a=0;a<n.length;++a){let s=-1;for(let i=0;i<n.length;++i)n[i]>=a&&(s===-1||n[s]>n[i])&&(s=i);n[s]=a}return[r,n]}var Zme={kernelName:$a,backendName:"wasm",kernelFunc:Xs,setupFunc:qme};function Xi(e,t,r){let n=e.shape,a=e.shape.length,s=v.parseAxisParam(t,n),i=s,o=C.getAxesPermutation(i,a),l=null,u=!1;if(o!=null){let d=new Array(a);for(let p=0;p<d.length;p++)d[p]=n[o[p]];i=C.getInnerMostAxes(i.length,a),l=Xs({inputs:{x:e},attrs:{perm:o},backend:r});let h=r.dataIdMap.get(e.dataId).id;r.dataIdMap.get(l.dataId).id!==h&&(u=!0)}return{transposed:l,originalAxes:s,axes:i,inputWasTransposed:u}}var NS;function Yme(e){NS=e.wasm.cwrap(Xu,null,["number, number, number"])}function Jme(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:u,axes:d,originalAxes:h,inputWasTransposed:p}=Xi(i,a,t);if(p){let A=t.dataIdMap.get(u.dataId).id;l=u,o=A}let c=l.shape.length;C.assertAxesAreInnerMostDims("all",d,c);let[m,f]=C.computeOutAndReduceShapes(l.shape,d),g=v.sizeFromShape(f),y=t.makeOutput(m,i.dtype);if(v.sizeFromShape(l.shape)!==0){let A=t.dataIdMap.get(y.dataId).id;NS(o,g,A)}if(p&&t.disposeData(u.dataId),s){let A=C.expandShapeToKeepDim(y.shape,h);y.shape=A}return y}var Qme={kernelName:Xu,backendName:"wasm",setupFunc:Yme,kernelFunc:Jme},ES;function e1e(e){ES=e.wasm.cwrap(Ku,null,["number, number, number"])}function t1e(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:u,axes:d,originalAxes:h,inputWasTransposed:p}=Xi(i,a,t);if(p){let A=t.dataIdMap.get(u.dataId).id;l=u,o=A}let c=l.shape.length;C.assertAxesAreInnerMostDims("any",d,c);let[m,f]=C.computeOutAndReduceShapes(l.shape,d),g=v.sizeFromShape(f),y=t.makeOutput(m,i.dtype);if(v.sizeFromShape(l.shape)!==0){let A=t.dataIdMap.get(y.dataId).id;ES(o,g,A)}if(p&&t.disposeData(u.dataId),s){let A=C.expandShapeToKeepDim(y.shape,h);y.shape=A}return y}var r1e={kernelName:Ku,backendName:"wasm",setupFunc:e1e,kernelFunc:t1e},RS;function n1e(e){RS=e.wasm.cwrap(Ys,null,["number","number","number","number","number"])}function a1e(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a}=n,{x:s}=r,i=t.dataIdMap.get(s.dataId).id,o=i,l=s,{transposed:u,axes:d,inputWasTransposed:h}=Xi(s,a,t);if(h){let y=t.dataIdMap.get(u.dataId).id;y!==i&&(l=u,o=y)}let p=l.shape.slice(0,-1),c=t.makeOutput(p,"int32"),m=t.dataIdMap.get(c.dataId).id,f=v.sizeFromShape(c.shape),g=l.shape[d[0]];return RS(o,Ut[l.dtype],f,g,m),h&&t.disposeData(u.dataId),c}var s1e={kernelName:Ys,backendName:"wasm",kernelFunc:a1e,setupFunc:n1e},$S;function i1e(e){$S=e.wasm.cwrap(Js,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function o1e(e){let{inputs:t,attrs:r,backend:n}=e,a=t.x,s=n.dataIdMap.get(a.dataId).id,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=r,d=C.computePool2DInfo(a.shape,i,o,1,l,u),h=d.filterHeight,p=d.filterWidth,c=d.padInfo.top,m=d.padInfo.right,f=d.padInfo.bottom,g=d.padInfo.left,y=d.strideHeight,A=d.strideWidth,x=d.inChannels;if(d.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);if(d.dilationWidth!==1||d.dilationHeight!==1)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${d.dilationHeight}, ${d.dilationWidth}].`);let b=n.makeOutput(d.outShape,"float32"),w=n.dataIdMap.get(b.dataId).id;return $S(s,a.shape[0],a.shape[1],a.shape[2],h,p,c,m,f,g,y,A,x,w),b}var l1e={kernelName:Js,backendName:"wasm",setupFunc:i1e,kernelFunc:o1e};function nn(e){let{inputs:t,attrs:r}=e,{x:n}=t,{shape:a}=r,s=v.sizeFromShape(n.shape),i=v.inferFromImplicitShape(a,s);return v.assert(s===v.sizeFromShape(i),()=>`new shape: ${i}, old shape: ${n.shape}. New shape and old shape must have the same number of elements.`),e.backend.incRef(n.dataId),{dataId:n.dataId,shape:i,dtype:n.dtype}}var u1e={kernelName:fl,backendName:"wasm",kernelFunc:nn},MS;function d1e(e){MS=e.wasm.cwrap(Qs,null,["number","array","number","number","array","number","number","number","number"])}function p1e(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s}=t,{transposeA:i,transposeB:o}=n;if(a.dtype!=="float32"||s.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let l=a.shape.length,u=s.shape.length,d=i?a.shape[l-2]:a.shape[l-1],h=o?s.shape[u-1]:s.shape[u-2],p=i?a.shape[l-1]:a.shape[l-2],c=o?s.shape[u-2]:s.shape[u-1],m=a.shape.slice(0,-2),f=s.shape.slice(0,-2),g=v.sizeFromShape(m),y=v.sizeFromShape(f),A=$l.assertAndGetBroadcastShape(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([p,c]);v.assert(d===h,()=>`Error in matMul: inner shapes (${d}) and (${h}) of Tensors with shapes ${a.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let x=i?[g,d,p]:[g,p,d],b=o?[y,c,h]:[y,h,c],w=nn({inputs:{x:a},backend:r,attrs:{shape:x}}),I=nn({inputs:{x:s},backend:r,attrs:{shape:b}}),T=r.dataIdMap.get(w.dataId).id,E=r.dataIdMap.get(I.dataId).id,R=i?w.shape[2]:w.shape[1],F=o?I.shape[1]:I.shape[2],$=Math.max(g,y),S=r.makeOutput([$,R,F],w.dtype),z=r.dataIdMap.get(S.dataId).id,O=new Uint8Array(new Int32Array(w.shape).buffer),j=new Uint8Array(new Int32Array(I.shape).buffer);return MS(T,O,w.shape.length,E,j,I.shape.length,i,o,z),r.disposeData(w.dataId),r.disposeData(I.dataId),S.shape=A,S}var h1e={kernelName:Qs,backendName:"wasm",setupFunc:d1e,kernelFunc:p1e};function Wo(e){let{inputs:{x:t},attrs:{begin:r,size:n},backend:a}=e,[s,i]=Dt.parseSliceParams(t,r,n),o=Dt.isSliceContinous(t.shape,s,i),l=a.readSync(t.dataId),u=a.makeOutput(i,t.dtype),d=v.computeStrides(t.shape),h=a.dataIdMap.get(u.dataId);if(o){let m=Dt.computeFlatOffset(s,d);return t.dtype==="string"?h.stringBytes=l.slice(m,m+v.sizeFromShape(i)):a.typedArrayFromHeap(u).set(l.subarray(m,m+v.sizeFromShape(i))),u}if(t.dtype==="string"){let m=K0(l,s,i,t.shape,t.dtype);return h.stringBytes=m,u}let p=a.typedArrayFromHeap(u),c=t.shape.length;if(c===2)c1e(l,d[0],p,s,i);else if(c===3)f1e(l,d[0],d[1],p,s,i);else if(c===4)m1e(l,d[0],d[1],d[2],p,s,i);else{let m=K0(l,s,i,t.shape,t.dtype);p.set(m)}return u}function c1e(e,t,r,n,a){let s=0,i=n[0],o=n[1],l=i+a[0];for(let u=i;u<l;u++){let d=u*t+o;r.set(e.subarray(d,d+a[1]),s),s+=a[1]}}function f1e(e,t,r,n,a,s){let i=0,o=a[0],l=a[1],u=a[2],d=o+s[0],h=l+s[1];for(let p=o;p<d;p++)for(let c=l;c<h;c++){let m=p*t+c*r+u;n.set(e.subarray(m,m+s[2]),i),i+=s[2]}}function m1e(e,t,r,n,a,s,i){let o=0,l=s[0],u=s[1],d=s[2],h=l+i[0],p=u+i[1],c=d+i[2],m=s[3];for(let f=l;f<h;f++)for(let g=u;g<p;g++)for(let y=d;y<c;y++){let A=f*t+g*r+y*n+m;a.set(e.subarray(A,A+i[3]),o),o+=i[3]}}var g1e={kernelName:xl,backendName:"wasm",kernelFunc:Wo};function y1e(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,crops:i}=n,o=s.reduce((y,A)=>y*A),l=C.getReshaped(a.shape,s,o),u=C.getPermuted(l.length,s.length),d=C.getReshapedPermuted(a.shape,s,o),h=C.getSliceBeginCoords(i,s.length),p=C.getSliceSize(d,i,s.length),c=nn({inputs:{x:a},backend:r,attrs:{shape:l}}),m=Xs({inputs:{x:c},backend:r,attrs:{perm:u}}),f=nn({inputs:{x:m},backend:r,attrs:{shape:d}}),g=Wo({inputs:{x:f},backend:r,attrs:{begin:h,size:p}});return r.disposeData(c.dataId),r.disposeData(m.dataId),r.disposeData(c.dataId),g}var A1e={kernelName:jo,backendName:"wasm",kernelFunc:y1e};function rc(e){let{inputs:{x:t},attrs:{dtype:r},backend:n}=e,a=n.makeOutput(t.shape,r),s=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(a).set(s),a}var x1e={kernelName:ei,backendName:"wasm",kernelFunc:rc},b1e=vr(ti),FS;function v1e(e){FS=e.wasm.cwrap(es,null,["number","number","number","number"])}function w1e(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{clipValueMin:s,clipValueMax:i}=n,o=r.dataIdMap.get(a.dataId).id,l=r.makeOutput(a.shape,a.dtype),u=r.dataIdMap.get(l.dataId).id;return FS(o,s,i,u),l}var k1e={kernelName:es,backendName:"wasm",setupFunc:v1e,kernelFunc:w1e};function _S(e){let{inputs:t,backend:r}=e,n=v.parseAxisParam(e.attrs.axis,t[0].shape)[0],a=C.computeOutShape(t.map(c=>c.shape),n),s=t.filter(c=>v.sizeFromShape(c.shape)>0);if(s.length===1)return Vm({inputs:{x:s[0]},backend:r});let i=r.makeOutput(a,t[0].dtype);if(v.sizeFromShape(a)===0)return i;let o=s.map(c=>c.shape);if(C.assertParamsConsistent(o,n),s[0].dtype==="string"){let c=s.map(x=>{let b=v.sizeFromShape(x.shape.slice(n));return nn({inputs:{x},backend:r,attrs:{shape:[-1,b]}})}),m=c.map(x=>({vals:r.readSync(x.dataId),shape:x.shape}));a=C.computeOutShape(c.map(x=>x.shape),1);let f=c[0].shape[0]===1,g=fA(m,a,t[0].dtype,f),y=C.computeOutShape(s.map(x=>x.shape),n);i.shape=y;let A=r.dataIdMap.get(i.dataId);return A.stringBytes=C.fromStringArrayToUint8(g),c.forEach(x=>r.disposeData(x.dataId)),i}let l=v.sizeFromShape(s[0].shape.slice(0,n)),u=0,d=s.map(c=>{let m=v.sizeFromShape(c.shape.slice(n));return u+=m,m}),h=s.map(c=>r.typedArrayFromHeap(c)),p=r.typedArrayFromHeap(i);for(let c=0;c<l;c++){let m=c*u;for(let f=0;f<h.length;f++){let g=d[f],y=c*g,A=h[f].subarray(y,y+g);p.set(A,m),m+=g}}return i}var I1e={kernelName:Ho,backendName:"wasm",kernelFunc:_S},PS;function S1e(e){PS=e.wasm.cwrap(ri,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function C1e(e){let{inputs:t,attrs:r,backend:n}=e,{x:a,filter:s}=t,i=n.dataIdMap.get(a.dataId).id,o=n.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:d,dimRoundingMode:h,dataFormat:p}=r,c=C.convertConv2DDataFormat(p),m=C.computeConv2DInfo(a.shape,s.shape,l,u,d,h,!1,c),f=m.filterHeight,g=m.filterWidth,y=m.padInfo.top,A=m.padInfo.right,x=m.padInfo.bottom,b=m.padInfo.left,w=m.dilationHeight,I=m.dilationWidth,T=m.strideHeight,E=m.strideWidth,R=m.inChannels,F=m.outChannels,$=m.padInfo.type==="SAME"?1:0;if(m.dataFormat!=="channelsLast")throw new Error(`wasm backend Conv2D does not support dataFormat:'${m.dataFormat}'. Please use 'channelsLast'.`);let S=n.makeOutput(m.outShape,"float32"),z=n.dataIdMap.get(S.dataId).id;return PS(i,a.shape[0],a.shape[1],a.shape[2],o,f,g,y,A,x,b,$,w,I,T,E,R,F,z),S}var T1e={kernelName:ri,backendName:"wasm",setupFunc:S1e,kernelFunc:C1e},OS;function N1e(e){OS=e.wasm.cwrap(ni,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 E1e(e){let{backend:t,inputs:r,attrs:n}=e,{dy:a,filter:s}=r,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,inputShape:d}=n,h=1,p=C.convertConv2DDataFormat(l),c=C.computeConv2DInfo(d,s.shape,i,h,o,u,!1,p),{batchSize:m,filterHeight:f,filterWidth:g,inChannels:y,inHeight:A,inWidth:x,outChannels:b,outHeight:w,outWidth:I,strideHeight:T,strideWidth:E}=c,R=f-1-c.padInfo.top,F=g-1-c.padInfo.left,$=c.dataFormat==="channelsLast",S=v.computeStrides(c.inShape),z=v.computeStrides(a.shape),[O,j,K]=v.computeStrides(s.shape),D=S[0],Y=$?S[1]:S[2],V=$?S[2]:1,re=$?1:S[1],Q=z[0],ie=$?z[1]:z[2],J=$?z[2]:1,ae=$?1:z[1],de=t.makeOutput(c.inShape,"float32"),be=t.dataIdMap.get(de.dataId).id,ve=t.dataIdMap.get(a.dataId).id,Ee=t.dataIdMap.get(s.dataId).id;return OS(ve,Ee,m,f,g,A,x,y,w,I,b,T,E,R,F,O,j,K,D,Y,V,re,Q,ie,J,ae,be),de}var R1e={kernelName:ni,backendName:"wasm",setupFunc:N1e,kernelFunc:E1e},$1e=vr(ai),M1e=vr(si),zS=(e=>(e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest",e))(zS||{}),DS;function F1e(e){DS=e.wasm.cwrap(Xo,null,["number","number","number","number","array","number","number","number","number","number"])}function _1e(e){let{backend:t,inputs:r,attrs:n}=e,{method:a,extrapolationValue:s,cropSize:i}=n,{image:o,boxes:l,boxInd:u}=r,d=l.shape[0],[h,p]=i,c=[d,h,p,o.shape[3]],m=t.dataIdMap.get(o.dataId),f;o.dtype!=="float32"&&(f=rc({backend:t,inputs:{x:o},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(f.dataId));let g=m.id,y=t.dataIdMap.get(l.dataId).id,A=t.dataIdMap.get(u.dataId).id,x=t.makeOutput(c,"float32"),b=t.dataIdMap.get(x.dataId).id,w=new Uint8Array(new Int32Array(o.shape).buffer);return DS(g,y,A,d,w,h,p,zS[a],s,b),f!=null&&t.disposeData(f.dataId),x}var P1e={kernelName:Xo,backendName:"wasm",setupFunc:F1e,kernelFunc:_1e},LS;function O1e(e){LS=e.wasm.cwrap(qo,null,["number","number","number","number","number","number"])}function z1e(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n,l=a.shape.length;v.assert(a.dtype==="float32"||a.dtype==="int32",()=>`cumprod does not support ${a.dtype} tensors in the WASM backend`);let u=C.getAxesPermutation([s],l),d=a;u!==null&&(d=Xs({inputs:{x:a},attrs:{perm:u},backend:r}));let h=C.getInnerMostAxes(1,l)[0];C.assertAxesAreInnerMostDims("cumprod",[h],l);let p=r.makeOutput(d.shape,d.dtype),c=d.shape[h],m=r.dataIdMap.get(d.dataId).id,f=r.dataIdMap.get(p.dataId).id;LS(m,i?1:0,o?1:0,c,f,Ut[a.dtype]);let g=p;if(u!==null){let y=C.getUndoAxesPermutation(u);g=Xs({inputs:{x:p},attrs:{perm:y},backend:r}),r.disposeData(d.dataId),r.disposeData(p.dataId)}return g}var D1e={kernelName:qo,backendName:"wasm",setupFunc:O1e,kernelFunc:z1e},BS;function L1e(e){BS=e.wasm.cwrap(ii,null,["number","number","number","number","number","number"])}function B1e(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n,l=a.shape.length;v.assert(a.dtype==="float32"||a.dtype==="int32",()=>`cumsum does not support ${a.dtype} tensors in the WASM backend`);let u=C.getAxesPermutation([s],l),d=a;u!==null&&(d=Xs({inputs:{x:a},attrs:{perm:u},backend:r}));let h=C.getInnerMostAxes(1,l)[0];C.assertAxesAreInnerMostDims("cumsum",[h],l);let p=r.makeOutput(d.shape,d.dtype),c=d.shape[h],m=r.dataIdMap.get(d.dataId).id,f=r.dataIdMap.get(p.dataId).id;BS(m,i?1:0,o?1:0,c,f,Ut[a.dtype]);let g=p;if(u!==null){let y=C.getUndoAxesPermutation(u);g=Xs({inputs:{x:p},attrs:{perm:y},backend:r}),r.disposeData(d.dataId),r.disposeData(p.dataId)}return g}var W1e={kernelName:ii,backendName:"wasm",setupFunc:L1e,kernelFunc:B1e},WS;function V1e(e){WS=e.wasm.cwrap(Ko,null,["number","number","number","array","number","array","array","number","number"])}function U1e(e){let{backend:t,inputs:r,attrs:n}=e,{x:a}=r,{blockSize:s,dataFormat:i}=n,o=a.shape[0],l=i==="NHWC"?a.shape[1]:a.shape[2],u=i==="NHWC"?a.shape[2]:a.shape[3],d=i==="NHWC"?a.shape[3]:a.shape[1],h=l*s,p=u*s,c=d/(s*s),m=i==="NHWC"?[o,h,p,c]:[o,c,h,p],f=t.makeOutput(m,"float32"),g=t.dataIdMap.get(a.dataId).id,y=new Uint8Array(new Int32Array(v.computeStrides(a.shape)).buffer),A=new Uint8Array(new Int32Array(m).buffer),x=new Uint8Array(new Int32Array(v.computeStrides(m)).buffer),b=t.dataIdMap.get(f.dataId).id;return WS(g,s,i==="NHWC"?1:0,y,a.shape.length-1,A,x,m.length,b),f}var G1e={kernelName:Ko,backendName:"wasm",setupFunc:V1e,kernelFunc:U1e},VS;function j1e(e){VS=e.wasm.cwrap(oi,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function H1e(e){let{inputs:t,attrs:r,backend:n}=e,{x:a,filter:s}=t,i=n.dataIdMap.get(a.dataId).id,o=n.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:d,dimRoundingMode:h}=r,p=u==null?[1,1]:u,c=C.computeConv2DInfo(a.shape,s.shape,l,p,d,h,!0),m=c.filterHeight,f=c.filterWidth,g=c.padInfo.top,y=c.padInfo.right,A=c.padInfo.bottom,x=c.padInfo.left,b=c.dilationHeight,w=c.dilationWidth,I=c.strideHeight,T=c.strideWidth,E=c.inChannels,R=c.outChannels,F=c.padInfo.type==="SAME"?1:0;if(c.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);let $=n.makeOutput(c.outShape,"float32"),S=n.dataIdMap.get($.dataId).id;return VS(i,a.shape[0],a.shape[1],a.shape[2],o,m,f,g,y,A,x,F,b,w,I,T,E,R,S),$}var q1e={kernelName:oi,backendName:"wasm",setupFunc:j1e,kernelFunc:H1e},X1e=vr(ui),K1e=!1,Z1e=Ir(Zo,K1e,"bool"),Y1e=vr(di,"float32");function Iy(e){let{inputs:t,attrs:r,backend:n}=e,{input:a}=t,{dim:s}=r,i=a.shape.length,o=a.shape.slice(),l=s;return s<0&&(v.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),o.splice(l,0,1),nn({inputs:{x:a},backend:n,attrs:{shape:o}})}var J1e={kernelName:Yo,backendName:"wasm",kernelFunc:Iy};function US(e){let{attrs:{shape:t,value:r,dtype:n},backend:a}=e,s=a.makeOutput(t,n);return a.typedArrayFromHeap(s).fill(r),s}var Q1e={kernelName:nd,backendName:"wasm",kernelFunc:US},GS;function e2e(e){GS=e.wasm.cwrap(Qo,null,["number","number","number","number","number","number"])}function t2e(e){let{inputs:t,backend:r}=e,{image:n}=t,a=r.makeOutput(n.shape,n.dtype),s=r.dataIdMap.get(n.dataId).id,i=r.dataIdMap.get(a.dataId).id,[o,l,u,d]=n.shape;return GS(s,o,l,u,d,i),a}var r2e={kernelName:Qo,backendName:"wasm",kernelFunc:t2e,setupFunc:e2e},n2e=vr(pi),a2e=!1,s2e=Ir(hi,a2e),jS;function i2e(e){jS=e.wasm.cwrap(ci,null,["number","number","number","number","number","number","number"])}function o2e(e){let{backend:t,inputs:r,attrs:n}=e,{varianceEpsilon:a}=n,{x:s,mean:i,variance:o,offset:l,scale:u}=r,d=t.dataIdMap.get(s.dataId).id,h=t.dataIdMap.get(i.dataId).id,p=t.dataIdMap.get(o.dataId).id,c=l!=null?t.dataIdMap.get(l.dataId).id:0,m=u!=null?t.dataIdMap.get(u.dataId).id:0,f=t.makeOutput(s.shape,s.dtype);if(v.sizeFromShape(s.shape)===0)return f;let g=t.dataIdMap.get(f.dataId).id;return jS(d,h,p,c,m,a,g),f}var l2e={kernelName:ci,backendName:"wasm",setupFunc:i2e,kernelFunc:o2e},HS;function u2e(e){HS=e.wasm.cwrap(Os,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 d2e(e){let{inputs:t,attrs:r,backend:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:d,dataFormat:h,dimRoundingMode:p,activation:c,leakyreluAlpha:m}=r,f=C.computeConv2DInfo(a.shape,s.shape,l,d,u,p),g=Wm[c];if(g==null)throw new Error(`${c} activation not yet supported for FusedConv2D in the wasm backend.`);let y=n.dataIdMap.get(a.dataId).id,A=n.dataIdMap.get(s.dataId).id,x=f.outChannels,b=0;if(i!=null){let J=n.dataIdMap.get(i.dataId);if(J.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${J.shape.length}.`);if(J.shape[0]!==x)throw new Error(`FusedConv2D bias shape (${J.shape}) does not match the number of output channels (${x})`);b=J.id}let w=f.filterHeight,I=f.filterWidth,T=f.padInfo.top,E=f.padInfo.right,R=f.padInfo.bottom,F=f.padInfo.left,$=f.dilationHeight,S=f.dilationWidth,z=f.strideHeight,O=f.strideWidth,j=f.inChannels,K=f.padInfo.type==="SAME"?1:0,D=f.batchSize,Y=f.inHeight,V=f.inWidth;if(h!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${h}'. Please use 'NHWC'.`);let re=n.makeOutput(f.outShape,"float32"),Q=n.dataIdMap.get(re.dataId).id,ie=o==null?0:n.dataIdMap.get(o.dataId).id;return HS(y,D,Y,V,A,w,I,b,T,E,R,F,K,$,S,z,O,j,x,g,ie,m||0,Q),re}var p2e={kernelName:Os,backendName:"wasm",setupFunc:u2e,kernelFunc:d2e},qS;function h2e(e){qS=e.wasm.cwrap(zs,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 c2e(e){let{inputs:t,attrs:r,backend:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:d,dataFormat:h,dimRoundingMode:p,activation:c,leakyreluAlpha:m}=r,f=C.computeConv2DInfo(a.shape,s.shape,l,d,u,p,!0),g=Wm[c];if(g==null)throw new Error(`${c} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let y=n.dataIdMap.get(a.dataId).id,A=n.dataIdMap.get(s.dataId).id,x=f.outChannels,b=0;if(i!=null){let J=n.dataIdMap.get(i.dataId);if(J.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${J.shape.length}.`);if(J.shape[0]!==x)throw new Error(`FusedDepthwiseConv2D bias shape (${J.shape}) does not match the number of output channels (${x})`);b=J.id}let w=f.filterHeight,I=f.filterWidth,T=f.padInfo.top,E=f.padInfo.right,R=f.padInfo.bottom,F=f.padInfo.left,$=f.dilationHeight,S=f.dilationWidth,z=f.strideHeight,O=f.strideWidth,j=f.inChannels,K=f.padInfo.type==="SAME"?1:0,D=f.batchSize,Y=f.inHeight,V=f.inWidth;if(h!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${h}'. Please use 'NHWC'.`);let re=n.makeOutput(f.outShape,"float32"),Q=n.dataIdMap.get(re.dataId).id,ie=o==null?0:n.dataIdMap.get(o.dataId).id;return qS(y,D,Y,V,A,w,I,b,T,E,R,F,K,$,S,z,O,j,x,g,ie,m||0,Q),re}var f2e={kernelName:zs,backendName:"wasm",setupFunc:h2e,kernelFunc:c2e},XS;function m2e(e){XS=e.wasm.cwrap(tl,null,["number","number","number","number","number","number","array","number"])}function g2e(e){let{backend:t,inputs:r}=e,{params:n,indices:a}=r,[s,i,o,l]=Gy.prepareAndValidate(n,a),u=t.makeOutput(s,n.dtype);if(i===0)return u;let d=a.shape,h=d[d.length-1],p=t.dataIdMap.get(n.dataId).id,c=t.dataIdMap.get(a.dataId).id,m=new Uint8Array(new Int32Array(l).buffer),f=t.dataIdMap.get(u.dataId).id;return XS(p,Ut[n.dtype],c,i,h,o,m,f),u}var y2e={kernelName:tl,backendName:"wasm",setupFunc:m2e,kernelFunc:g2e},KS;function A2e(e){KS=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function x2e(e){let{backend:t,inputs:r,attrs:n}=e,{x:a,indices:s}=r,{axis:i,batchDims:o}=n,l=v.parseAxisParam(i,a.shape)[0],u=t.readSync(s.dataId),d=a.shape[l];for(let T=0;T<u.length;++T){let E=u[T];v.assert(E<=d-1&&E>=0,()=>`GatherV2: the index value ${E} is not in [0, ${d-1}]`)}let h=C.segment_util.collectGatherOpShapeInfo(a,s,l,o),p=nn({inputs:{x:a},attrs:{shape:[h.batchSize,h.outerSize,h.dimSize,h.sliceSize]},backend:t}),c=v.sizeFromShape(s.shape),m=nn({inputs:{x:s},attrs:{shape:[h.batchSize,c/h.batchSize]},backend:t}),f=[h.batchSize,h.outerSize,c/h.batchSize,h.sliceSize],g=t.makeOutput(f,a.dtype);if(v.sizeFromShape(a.shape)===0)return g;let y=p.shape.length-1,A=t.dataIdMap.get(p.dataId).id,x=t.dataIdMap.get(m.dataId).id,b=t.dataIdMap.get(g.dataId).id,w=new Uint8Array(new Int32Array(v.computeStrides(p.shape)).buffer),I=new Uint8Array(new Int32Array(v.computeStrides(f)).buffer);return KS(A,Ut[a.dtype],w,y,x,h.batchSize,I,b),t.disposeData(p.dataId),t.disposeData(m.dataId),g.shape=h.outputShape,g}var b2e={kernelName:el,backendName:"wasm",setupFunc:A2e,kernelFunc:x2e},v2e=!1,w2e=Ir(rl,v2e,"bool"),k2e=!1,I2e=Ir(fi,k2e,"bool"),ZS;function S2e(e){ZS=e.wasm.cwrap(gi,null,["number","number","number","number"])}function C2e(e){let{inputs:{x:t},attrs:{alpha:r},backend:n}=e,a=n.dataIdMap.get(t.dataId).id,s=n.makeOutput(t.shape,"float32");if(v.sizeFromShape(t.shape)!==0){let i=n.dataIdMap.get(s.dataId).id;ZS(a,Ut[t.dtype],r,i)}return s}var T2e={kernelName:gi,backendName:"wasm",setupFunc:S2e,kernelFunc:C2e},N2e=!1,E2e=Ir(nl,N2e,"bool"),R2e=!1,$2e=Ir(al,R2e,"bool"),M2e=vr(yi),F2e=!1,_2e=Ir(sl,F2e,"bool"),P2e=vr(il),O2e=!1,z2e=Ir(ld,O2e,"bool"),D2e=!1,L2e=Ir(Z7,D2e,"bool"),YS;function B2e(e){YS=e.wasm.cwrap(Ai,null,["number","number","number","number"])}function W2e(e){let{backend:t,inputs:r,attrs:n}=e,{reductionIndices:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:u,axes:d,originalAxes:h,inputWasTransposed:p}=Xi(i,a,t);if(p){let A=t.dataIdMap.get(u.dataId).id;l=u,o=A}let c=l.shape.length;C.assertAxesAreInnerMostDims("max",d,c);let[m,f]=C.computeOutAndReduceShapes(l.shape,d),g=v.sizeFromShape(f),y=t.makeOutput(m,i.dtype);if(v.sizeFromShape(l.shape)!==0){let A=t.dataIdMap.get(y.dataId).id;YS(o,Ut[i.dtype],g,A)}if(p&&t.disposeData(u.dataId),s){let A=C.expandShapeToKeepDim(y.shape,h);y.shape=A}return y}var V2e={kernelName:Ai,backendName:"wasm",setupFunc:B2e,kernelFunc:W2e},U2e=!1,G2e=Ir(xi,U2e),JS;function j2e(e){JS=e.wasm.cwrap(bi,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function H2e(e){let{inputs:t,attrs:r,backend:n}=e,a=t.x,s=n.dataIdMap.get(a.dataId).id;v.assert(a.dtype==="float32",()=>`Error in MaxPool: only float32 input is supported. Got ${a.dtype}.`);let{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=r,d=C.computePool2DInfo(a.shape,i,o,1,l,u),h=d.filterHeight,p=d.filterWidth,c=d.padInfo.top,m=d.padInfo.right,f=d.padInfo.bottom,g=d.padInfo.left,y=d.dilationHeight,A=d.dilationWidth,x=d.strideHeight,b=d.strideWidth,w=d.inChannels,I=d.outChannels;if(d.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);let T=n.makeOutput(d.outShape,"float32"),E=n.dataIdMap.get(T.dataId).id;return JS(s,a.shape[0],a.shape[1],a.shape[2],h,p,c,m,f,g,y,A,x,b,w,I,E),T}var q2e={kernelName:bi,backendName:"wasm",setupFunc:j2e,kernelFunc:H2e},QS;function X2e(e){QS=e.wasm.cwrap(vi,null,["number, number, number"])}function K2e(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:d,axes:h,originalAxes:p,inputWasTransposed:c}=Xi(i,a,t),m=h;if(c){let b=t.dataIdMap.get(d.dataId).id;b!==o&&(u=d,l=b,m=C.getInnerMostAxes(m.length,u.shape.length))}C.assertAxesAreInnerMostDims("mean",m,u.shape.length);let[f,g]=C.computeOutAndReduceShapes(u.shape,m),y=v.sizeFromShape(g),A=u;u.dtype!=="float32"&&(A=rc({backend:t,inputs:{x:u},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(A.dataId).id);let x=t.makeOutput(f,"float32");if(v.sizeFromShape(u.shape)!==0){let b=t.dataIdMap.get(x.dataId).id;QS(l,y,b)}if(c&&t.disposeData(d.dataId),s){let b=C.expandShapeToKeepDim(x.shape,p);x.shape=b}return u.dtype!=="float32"&&t.disposeData(A.dataId),x}var Z2e={kernelName:vi,backendName:"wasm",setupFunc:X2e,kernelFunc:K2e},eC;function Y2e(e){eC=e.wasm.cwrap(wi,null,["number","number","number","number"])}function J2e(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:d,axes:h,originalAxes:p,inputWasTransposed:c}=Xi(i,a,t);if(c){let x=t.dataIdMap.get(d.dataId).id;x!==o&&(u=d,l=x)}let m=u.shape.length;C.assertAxesAreInnerMostDims("min",h,m);let[f,g]=C.computeOutAndReduceShapes(u.shape,h),y=v.sizeFromShape(g),A=t.makeOutput(f,u.dtype);if(v.sizeFromShape(u.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;eC(l,Ut[i.dtype],y,x)}if(c&&t.disposeData(d.dataId),s){let x=C.expandShapeToKeepDim(A.shape,p);A.shape=x}return A}var Q2e={kernelName:wi,backendName:"wasm",setupFunc:Y2e,kernelFunc:J2e},ege=!1,tge=Ir(ki,ege),tC=(e=>(e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric",e))(tC||{}),rC;function rge(e){rC=e.wasm.cwrap(Ii,null,["number","array","number","number","array","array","number","number"])}function nge(e){let{inputs:{x:t},backend:r,attrs:{paddings:n,mode:a}}=e,s=n.map((m,f)=>m[0]+t.shape[f]+m[1]),i=r.dataIdMap.get(t.dataId).id,o=r.makeOutput(s,t.dtype),l=r.dataIdMap.get(o.dataId).id,u=new Uint8Array(new Int32Array(t.shape).buffer),d=n.map(m=>m[0]),h=n.map(m=>m[1]),p=new Uint8Array(new Int32Array(d).buffer),c=new Uint8Array(new Int32Array(h).buffer);return rC(i,u,t.shape.length,Ut[t.dtype],p,c,tC[a],l),o}var age={kernelName:Ii,backendName:"wasm",kernelFunc:nge,setupFunc:rge},sge=!0,ige=Ir(Si,sge),oge=vr(ol);function GA(e,t){let r=new Int32Array(e.wasm.HEAPU8.buffer,t,4),n=r[0],a=r[1],s=r[2],i=r[3];return e.wasm._free(t),{pSelectedIndices:n,selectedSize:a,pSelectedScores:s,pValidOutputs:i}}var nC;function lge(e){nC=e.wasm.cwrap(ul,"number",["number","number","number","number","number"])}function uge(e){let{backend:t,inputs:r,attrs:n}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:i}=n,{boxes:o,scores:l}=r,u=t.dataIdMap.get(o.dataId).id,d=t.dataIdMap.get(l.dataId).id,h=nC(u,d,s,a,i),{pSelectedIndices:p,selectedSize:c,pSelectedScores:m,pValidOutputs:f}=GA(t,h);return t.wasm._free(m),t.wasm._free(f),t.makeOutput([c],"int32",p)}var dge={kernelName:ul,backendName:"wasm",setupFunc:lge,kernelFunc:uge},aC;function pge(e){aC=e.wasm.cwrap(dd,"number",["number","number","number","number","number","bool"])}function hge(e){let{backend:t,inputs:r,attrs:n}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:i,padToMaxOutputSize:o}=n,{boxes:l,scores:u}=r,d=t.dataIdMap.get(l.dataId).id,h=t.dataIdMap.get(u.dataId).id,p=aC(d,h,s,a,i,o),{pSelectedIndices:c,selectedSize:m,pSelectedScores:f,pValidOutputs:g}=GA(t,p);t.wasm._free(f);let y=t.makeOutput([m],"int32",c),A=t.makeOutput([],"int32",g);return[y,A]}var cge={kernelName:dd,backendName:"wasm",setupFunc:pge,kernelFunc:hge},sC;function fge(e){sC=e.wasm.cwrap(dl,"number",["number","number","number","number","number","number"])}function mge(e){let{backend:t,inputs:r,attrs:n}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:i,softNmsSigma:o}=n,{boxes:l,scores:u}=r,d=t.dataIdMap.get(l.dataId).id,h=t.dataIdMap.get(u.dataId).id,p=sC(d,h,s,a,i,o),{pSelectedIndices:c,selectedSize:m,pSelectedScores:f,pValidOutputs:g}=GA(t,p);t.wasm._free(g);let y=t.makeOutput([m],"int32",c),A=t.makeOutput([m],"float32",f);return[y,A]}var gge={kernelName:dl,backendName:"wasm",setupFunc:fge,kernelFunc:mge},yge=!1,Age=Ir(ll,yge,"bool"),iC;function xge(e){iC=e.wasm.cwrap(hl,null,["number","number","number","number","number"])}function bge(e){let{inputs:t,backend:r,attrs:n}=e,{indices:a}=t,{depth:s,onValue:i,offValue:o}=n,l=r.makeOutput([...a.shape,s],"int32"),u=r.dataIdMap.get(l.dataId).id,d=r.dataIdMap.get(a.dataId).id;return iC(d,s,i,o,u),l}var vge={kernelName:hl,backendName:"wasm",setupFunc:xge,kernelFunc:bge};function wge(e){let{inputs:{x:t},backend:r}=e,n=r.makeOutput(t.shape,t.dtype);return r.typedArrayFromHeap(n).fill(1),n}var kge={kernelName:pl,backendName:"wasm",kernelFunc:wge};function Ige(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n;if(t.length===1)return Iy({inputs:{input:t[0]},backend:r,attrs:{dim:a}});let s=t[0].shape,i=t[0].dtype;t.forEach(d=>{v.assertShapesMatch(s,d.shape,"All tensors passed to stack must have matching shapes"),v.assert(i===d.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(d=>{let h=Iy({inputs:{input:d},backend:r,attrs:{dim:a}});return o.push(h),h}),u=_S({inputs:l,backend:r,attrs:{axis:a}});return o.forEach(d=>r.disposeData(d.dataId)),u}var Sge={kernelName:cl,backendName:"wasm",kernelFunc:Ige},oC;function Cge(e){oC=e.wasm.cwrap(Ci,null,["number","array","number","number","array","array","number","number"])}function Tge(e){let{inputs:{x:t},backend:r,attrs:{paddings:n,constantValue:a}}=e,s=n.map((m,f)=>m[0]+t.shape[f]+m[1]);if(v.sizeFromShape(t.shape)===0)return US({backend:r,attrs:{shape:s,value:a,dtype:t.dtype}});let i=r.dataIdMap.get(t.dataId).id,o=r.makeOutput(s,t.dtype),l=r.dataIdMap.get(o.dataId).id,u=new Uint8Array(new Int32Array(t.shape).buffer),d=n.map(m=>m[0]),h=n.map(m=>m[1]),p=new Uint8Array(new Int32Array(d).buffer),c=new Uint8Array(new Int32Array(h).buffer);return oC(i,u,t.shape.length,Ut[t.dtype],p,c,a,l),o}var lC={kernelName:Ci,backendName:"wasm",kernelFunc:Tge,setupFunc:Cge},Nge=!1,Ege=Ir(Ti,Nge),uC;function Rge(e){uC=e.wasm.cwrap(Ni,null,["number","number","number"])}function $ge(e){let{inputs:t,backend:r}=e,{x:n,alpha:a}=t,s=r.dataIdMap.get(n.dataId).id,i=r.dataIdMap.get(a.dataId).id,o=s,l=n,u=l;l.dtype!=="float32"&&(u=rc({backend:r,inputs:{x:n},attrs:{dtype:"float32"}}),o=r.dataIdMap.get(u.dataId).id);let d=r.makeOutput(n.shape,"float32"),h=r.dataIdMap.get(d.dataId).id;return uC(o,i,h),l.dtype!=="float32"&&r.disposeData(u.dataId),d}var Mge={kernelName:Ni,backendName:"wasm",setupFunc:Rge,kernelFunc:$ge},dC;function Fge(e){dC=e.wasm.cwrap(Ei,null,["number","number","number","number"])}function _ge(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:d,axes:h,originalAxes:p,inputWasTransposed:c}=Xi(i,a,t),m=h;if(c){let x=t.dataIdMap.get(d.dataId).id;x!==o&&(u=d,l=x,m=C.getInnerMostAxes(m.length,u.shape.length))}C.assertAxesAreInnerMostDims("prod",m,u.shape.length);let[f,g]=C.computeOutAndReduceShapes(u.shape,m),y=v.sizeFromShape(g),A=t.makeOutput(f,u.dtype);if(v.sizeFromShape(u.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;dC(l,y,Ut[A.dtype],x)}if(c&&t.disposeData(d.dataId),s){let x=C.expandShapeToKeepDim(A.shape,p);A.shape=x}return A}var Pge={kernelName:Ei,backendName:"wasm",setupFunc:Fge,kernelFunc:_ge},Oge=e=>{let{backend:t,attrs:r}=e,{start:n,stop:a,step:s,dtype:i}=r,o=yA(n,a,s,i),l=t.makeOutput([o.length],i);return t.typedArrayFromHeap(l).set(o),l},zge={kernelName:pd,backendName:"wasm",kernelFunc:Oge},Dge=!0,Lge=Ir(li,Dge),Bge=vr(Ri),Wge=vr(Mi),pC;function Vge(e){pC=e.wasm.cwrap($i,null,["number","number","number","number","number","number","number","number","number","number"])}function Uge(e){let{backend:t,inputs:r,attrs:n}=e,{images:a}=r,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,[d,h,p,c]=a.shape,m=[d,l,u,c],f=t.dataIdMap.get(a.dataId),g;f.dtype!=="float32"&&(g=rc({backend:t,inputs:{x:a},attrs:{dtype:"float32"}}),f=t.dataIdMap.get(g.dataId));let y=f.id,A=t.makeOutput(m,"float32");if(v.sizeFromShape(a.shape)===0)return A;let x=t.dataIdMap.get(A.dataId).id;return pC(y,d,h,p,c,l,u,s?1:0,i?1:0,x),g!=null&&t.disposeData(g.dataId),A}var Gge={kernelName:$i,backendName:"wasm",setupFunc:Vge,kernelFunc:Uge},hC;function jge(e){hC=e.wasm.cwrap(ml,null,["number","array","number","array","number","number"])}function Hge(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{dims:s}=n,i=v.parseAxisParam(s,a.shape);if(a.shape.length===0)return Vm({inputs:{x:a},backend:r});let o=r.makeOutput(a.shape,a.dtype),l=r.dataIdMap.get(a.dataId).id,u=r.dataIdMap.get(o.dataId).id,d=new Uint8Array(new Int32Array(i).buffer),h=new Uint8Array(new Int32Array(a.shape).buffer);hC(l,d,i.length,h,a.shape.length,u);let p=nn({inputs:{x:o},attrs:{shape:a.shape},backend:r});return r.disposeData(o.dataId),p}var qge={kernelName:ml,backendName:"wasm",kernelFunc:Hge,setupFunc:jge},cC;function Xge(e){cC=e.wasm.cwrap(El,null,["number","number","number","number","number","number","number","number","array","number","number"])}function Kge(e){let{inputs:t,backend:r,attrs:n}=e,{image:a}=t,{radians:s,fillValue:i,center:o}=n,l=r.makeOutput(a.shape,a.dtype),u=r.dataIdMap.get(a.dataId).id,d=r.dataIdMap.get(l.dataId).id,[h,p,c,m]=a.shape,[f,g]=C.getImageCenter(o,p,c),y=i===0,A=255,x=typeof i=="number"?[i,i,i,y?0:A]:[...i,A],b=new Uint8Array(new Int32Array(x).buffer);return cC(u,h,p,c,m,s,f,g,b,x.length,d),l}var Zge={kernelName:El,backendName:"wasm",kernelFunc:Kge,setupFunc:Xge},Yge=vr(gl),Jge=vr(Fi),fC;function Qge(e){fC=e.wasm.cwrap(yl,null,["number","number","number","number","number","number","array","number","number"])}function eye(e){let{backend:t,inputs:r,attrs:n}=e,{indices:a,updates:s}=r,{shape:i}=n,o=t.makeOutput(i,s.dtype);if(v.sizeFromShape(i)===0)return o;let{sliceRank:l,numUpdates:u,sliceSize:d,strides:h,outputSize:p}=jy.calculateShapes(s,a,i),c=t.dataIdMap.get(a.dataId).id,m=t.dataIdMap.get(s.dataId).id,f=new Uint8Array(new Int32Array(h).buffer),g=t.dataIdMap.get(o.dataId).id;return fC(c,m,Ut[s.dtype],l,u,d,f,p,g),o}var tye={kernelName:yl,backendName:"wasm",setupFunc:Qge,kernelFunc:eye},mC;function rye(e){mC=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function nye(e){let{inputs:t,backend:r}=e,{condition:n,t:a,e:s}=t,i=r.dataIdMap.get(n.dataId).id,o=r.dataIdMap.get(a.dataId).id,l=r.dataIdMap.get(s.dataId).id,u=r.makeOutput(a.shape,a.dtype),d=r.dataIdMap.get(u.dataId).id,h=n.shape.length,p=a.shape.length,c=h===0||h>1||p===1?1:v.sizeFromShape(a.shape.slice(1));return mC(i,o,l,c,d),u}var aye={kernelName:Al,backendName:"wasm",kernelFunc:nye,setupFunc:rye},gC;function sye(e){gC=e.wasm.cwrap(Pi,null,["number","number"])}function iye(e){let{backend:t,inputs:{x:r}}=e,n=t.dataIdMap.get(r.dataId).id,a=t.makeOutput(r.shape,r.dtype),s=t.dataIdMap.get(a.dataId).id;return v.sizeFromShape(a.shape)===0||gC(n,s),a}var oye={kernelName:"Sigmoid",backendName:"wasm",setupFunc:sye,kernelFunc:iye},lye=vr(_i),yC;function uye(e){yC=e.wasm.cwrap(Di,null,["number","number","number","number"])}function dye(e){let{backend:t,inputs:{logits:r},attrs:{dim:n}}=e,a=t.dataIdMap.get(r.dataId).id,s=t.makeOutput(r.shape,r.dtype),i=t.dataIdMap.get(s.dataId).id,o=r.shape[n],l=v.sizeFromShape(r.shape)/o;return v.sizeFromShape(s.shape)===0||yC(a,i,o,l),s}var pye={kernelName:Di,backendName:"wasm",setupFunc:uye,kernelFunc:dye};function hye(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,paddings:i}=n,o=v.sizeFromShape(s),l=[[0,0]];l.push(...i);for(let g=1+s.length;g<a.shape.length;++g)l.push([0,0]);let u=lC.kernelFunc({inputs:{x:a},backend:r,attrs:{paddings:l,constantValue:0}}),d=C.getReshaped(u.shape,s,o,!1),h=C.getPermuted(d.length,s.length,!1),p=C.getReshapedPermuted(u.shape,s,o,!1),c=nn({inputs:{x:u},backend:r,attrs:{shape:d}}),m=Xs({inputs:{x:c},backend:r,attrs:{perm:h}}),f=nn({inputs:{x:m},backend:r,attrs:{shape:p}});return r.disposeData(u.dataId),r.disposeData(c.dataId),r.disposeData(m.dataId),f}var cye={kernelName:vl,backendName:"wasm",kernelFunc:hye},AC;function fye(e){AC=e.wasm.cwrap("SparseFillEmptyRows","number",["number","number","number","number","number","number","number","number","number","number","number","number"])}function mye(e){let{backend:t,inputs:r}=e,{indices:n,values:a,denseShape:s,defaultValue:i}=r,o=n.shape[0],l=n.shape[1],u=t.readSync(s.dataId)[0],d=[o+u,l],h=t.dataIdMap.get(n.dataId).id,p=t.dataIdMap.get(a.dataId).id,c=t.dataIdMap.get(i.dataId).id,m=t.makeOutput(d,n.dtype),f=t.dataIdMap.get(m.dataId).id,g=t.makeOutput(d.slice(0,1),a.dtype),y=t.dataIdMap.get(g.dataId).id,A=t.makeOutput([u],"bool"),x=t.dataIdMap.get(A.dataId).id,b=t.makeOutput([o],n.dtype),w=t.dataIdMap.get(b.dataId).id,I=t.makeOutput([4],"int32"),T=t.dataIdMap.get(I.dataId).id,E=AC(h,p,Ut[a.dtype],o,u,l,c,f,y,x,w,T),R=t.readSync(I.dataId),F;switch(R[0]){case 1:{F=C.getSparseFillEmptyRowsIndicesDenseShapeMismatch(R[1]);break}case 2:{F=C.getSparseFillEmptyRowsNegativeIndexErrorMessage(R[1],R[2]);break}case 3:F=C.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(R[1],R[2],R[3]);break;default:F=""}if(t.disposeData(I.dataId),F)throw t.disposeData(m.dataId),t.disposeData(g.dataId),t.disposeData(A.dataId),t.disposeData(b.dataId),new Error(F);let $=m,S=g;return E!==d[0]&&($=Wo({inputs:{x:m},attrs:{begin:0,size:[E,l]},backend:t}),S=Wo({inputs:{x:g},attrs:{begin:0,size:E},backend:t}),t.disposeData(m.dataId),t.disposeData(g.dataId)),[$,S,A,b]}var gye={kernelName:fh,backendName:"wasm",setupFunc:fye,kernelFunc:mye},xC;function yye(e){xC=e.wasm.cwrap(yd,null,["number","number","number","number","number","number","number"])}function Aye(e){let{backend:t,inputs:r}=e,{inputIndices:n,inputShape:a,newShape:s}=r;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
|
|
${n.shape}`);if(a.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
|
|
${a.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=t.dataIdMap.get(n.dataId).id,o=t.dataIdMap.get(a.dataId).id,l=t.dataIdMap.get(s.dataId).id,u=n.shape[0],d=v.sizeFromShape(s.shape),h=t.makeOutput([u,d],n.dtype),p=t.dataIdMap.get(h.dataId).id,c=t.makeOutput([d],s.dtype),m=t.dataIdMap.get(c.dataId).id,f=t.makeOutput([3],"int32"),g=t.dataIdMap.get(f.dataId).id;xC(i,o,l,u,p,m,g);let y=t.readSync(f.dataId),A;switch(y[0]){case 0:{A=C.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(y[1],y[2]);break}case 1:{A=C.getSparseReshapeNegativeOutputDimErrorMessage(y[1],y[2]);break}case 2:A=C.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();break;case 3:{let x=Array.from(t.readSync(a.dataId)),b=Array.from(t.readSync(c.dataId));A=C.getSparseReshapeInputOutputMultipleErrorMessage(x,b);break}case 4:{let x=Array.from(t.readSync(a.dataId)),b=Array.from(t.readSync(c.dataId));A=C.getSparseReshapeInputOutputMismatchErrorMessage(x,b);break}default:A=""}if(t.disposeData(f.dataId),A)throw t.disposeData(h.dataId),t.disposeData(c.dataId),new Error(A);return[h,c]}var xye={kernelName:yd,backendName:"wasm",setupFunc:yye,kernelFunc:Aye},bC;function vC(e){bC=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function wC(e,t){let{backend:r,inputs:n}=e,{data:a,indices:s,segmentIds:i}=n,o=s.shape[0],l=r.readSync(i.dataId,o-1,o)[0],u=o>0?l+1:0;if(u<0)throw new Error(C.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let d=a.shape.slice();d[0]=u;let h=r.dataIdMap.get(a.dataId).id,p=r.dataIdMap.get(s.dataId).id,c=r.dataIdMap.get(i.dataId).id,m=r.makeOutput(d,a.dtype),f=r.dataIdMap.get(m.dataId).id,g=r.makeOutput([4],"int32"),y=r.dataIdMap.get(g.dataId).id;bC(h,Ut[a.dtype],a.shape[0],p,c,f,y,t,0);let A=r.readSync(g.dataId),x;switch(A[0]){case 0:{x=C.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break}case 1:{x=C.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break}case 2:x=C.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(A[1],A[2]);break;case 3:x=C.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(A[1],A[2],A[3]);break;default:x=""}if(r.disposeData(g.dataId),x)throw r.disposeData(m.dataId),new Error(x);return m}function bye(e){return wC(e,!0)}var vye={kernelName:mh,backendName:"wasm",setupFunc:vC,kernelFunc:bye};function wye(e){return wC(e,!1)}var kye={kernelName:gh,backendName:"wasm",setupFunc:vC,kernelFunc:wye};function Iye(e){let{inputs:t,attrs:r,backend:n}=e,{x:a}=t,{numOrSizeSplits:s,axis:i}=r,o=v.parseAxisParam(i,a.shape)[0],l=C.prepareSplitSize(a,s,o),u=new Array(a.shape.length).fill(0),d=a.shape.slice();return l.map(h=>{let p=[...d];p[o]=h;let c=Wo({inputs:{x:a},attrs:{begin:u,size:p},backend:n});return u[o]+=h,c})}var Sye={kernelName:wl,backendName:"wasm",kernelFunc:Iye},Cye=vr(Oi),Tye=vr(Ad),Nye=!0,Eye=Ir(Li,Nye),kC;function Rye(e){kC=e.wasm.cwrap(Vi,null,["number","number","number","number"])}function $ye(e){let{backend:t,inputs:r,attrs:n}=e,{alpha:a}=n,{x:s}=r,i=t.dataIdMap.get(s.dataId).id,o=t.makeOutput(s.shape,s.dtype),l=t.dataIdMap.get(o.dataId).id;return kC(i,a,Ut[s.dtype],l),o}var Mye={kernelName:Vi,backendName:"wasm",setupFunc:Rye,kernelFunc:$ye},IC;function Fye(e){IC=e.wasm.cwrap(kl,null,["number","array","number","array","array","array","array","array","number","number"])}function _ye(e){let{backend:t,inputs:r,attrs:n}=e,{x:a}=r,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:d,newAxisMask:h,shrinkAxisMask:p}=n,{finalShapeSparse:c,finalShape:m,isIdentity:f,sliceDim0:g,isSimpleSlice:y,begin:A,end:x,strides:b}=Dt.sliceInfo(a.shape,s,i,o,l,u,d,h,p),w;if(f)w=nn({inputs:{x:a},backend:t,attrs:{shape:m}});else if(g||y){v.assert(a.shape.length>=1,()=>`Input must have rank at least 1, got: ${a.shape.length}`);let I=Dt.computeOutShape(A,x,b),T=Wo({inputs:{x:a},backend:t,attrs:{begin:A,size:I}});w=nn({inputs:{x:T},backend:t,attrs:{shape:m}}),t.disposeData(T.dataId)}else{let I=t.makeOutput(c,"float32"),T=t.dataIdMap.get(a.dataId).id,E=new Uint8Array(new Int32Array(v.computeStrides(a.shape)).buffer),R=new Uint8Array(new Int32Array(A).buffer),F=new Uint8Array(new Int32Array(x).buffer),$=new Uint8Array(new Int32Array(b).buffer),S=new Uint8Array(new Int32Array(c).buffer),z=new Uint8Array(new Int32Array(v.computeStrides(c)).buffer),O=t.dataIdMap.get(I.dataId).id;IC(T,E,a.shape.length,R,F,$,S,z,c.length,O),w=nn({inputs:{x:I},backend:t,attrs:{shape:m}}),t.disposeData(I.dataId)}return w}var Pye={kernelName:kl,backendName:"wasm",setupFunc:Fye,kernelFunc:_ye},Oye=!0,zye=Ir(Bi,Oye),SC;function Dye(e){SC=e.wasm.cwrap(zi,null,["number","number","number","number"])}function Lye(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:d,axes:h,originalAxes:p,inputWasTransposed:c}=Xi(i,a,t),m=h;if(c){let x=t.dataIdMap.get(d.dataId).id;x!==o&&(u=d,l=x,m=C.getInnerMostAxes(m.length,u.shape.length))}C.assertAxesAreInnerMostDims("sum",m,u.shape.length);let[f,g]=C.computeOutAndReduceShapes(u.shape,m),y=v.sizeFromShape(g),A=t.makeOutput(f,u.dtype);if(v.sizeFromShape(u.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;SC(l,y,Ut[A.dtype],x)}if(c&&t.disposeData(d.dataId),s){let x=C.expandShapeToKeepDim(A.shape,p);A.shape=x}return A}var Bye={kernelName:zi,backendName:"wasm",setupFunc:Dye,kernelFunc:Lye},Wye=vr(Il),Vye=vr(Wi),CC;function Uye(e){CC=e.wasm.cwrap(ts,null,["number","array","number","array","number","number"])}function Gye(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,s=r.dataIdMap.get(a.dataId).id,{reps:i}=n,o=new Array(a.shape.length);for(let p=0;p<o.length;p++)o[p]=a.shape[p]*i[p];let l=new Uint8Array(new Int32Array(a.shape).buffer),u=new Uint8Array(new Int32Array(o).buffer),d=r.makeOutput(o,a.dtype),h=r.dataIdMap.get(d.dataId).id;return CC(s,l,a.shape.length,u,o.length,Ut[d.dtype],h),d}var jye={kernelName:ts,backendName:"wasm",setupFunc:Uye,kernelFunc:Gye},TC;function Hye(e){TC=e.wasm.cwrap(Sl,null,["number","array","number","number","number","bool","number","number"])}var qye=({inputs:e,backend:t,attrs:r})=>{let{x:n}=e,{k:a,sorted:s}=r,i=t.dataIdMap.get(n.dataId).id,o=new Uint8Array(new Int32Array(n.shape).buffer),l=n.shape.slice();l[l.length-1]=a;let u=t.makeOutput(l,n.dtype),d=t.dataIdMap.get(u.dataId).id,h=t.makeOutput(l,"int32"),p=t.dataIdMap.get(h.dataId).id;return TC(i,o,n.shape.length,Ut[n.dtype],a,s,d,p),[u,h]},Xye={kernelName:Sl,backendName:"wasm",setupFunc:Hye,kernelFunc:qye},NC;function Kye(e){NC=e.wasm.cwrap(Cl,null,["number","number","bool","number","number","number","number","number","number","array","number","number","number","number","number"])}function Zye(e){let{backend:t,inputs:r,attrs:n}=e,{image:a,transforms:s}=r,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=n,[d,h,p,c]=a.shape,[m,f]=u!=null?u:[h,p],g=[d,m,f,c],y=new Uint8Array(new Int32Array(v.computeStrides(a.shape)).buffer),A=t.makeOutput(g,a.dtype),x=t.dataIdMap.get(A.dataId).id,b=t.dataIdMap.get(a.dataId).id,w=t.dataIdMap.get(s.dataId).id,I=i==="nearest"?1:2,T;switch(o){case"constant":T=1;break;case"reflect":T=2;break;case"wrap":T=3;break;case"nearest":T=4;break;default:T=1;break}return NC(b,w,s.shape[0]>1,d,m,f,c,p,h,y,a.shape.length-1,I,T,l,x),A}var Yye={kernelName:Cl,backendName:"wasm",setupFunc:Kye,kernelFunc:Zye};function Jye(e){let{inputs:t,backend:r,attrs:n}=e,{value:a}=t,{axis:s}=n;s<0&&(s+=a.shape.length);let i=a.shape[s],o=a.shape.length,l=new Array(o-1),u=0;for(let c=0;c<o;c++)c!==s&&(l[u++]=a.shape[c]);let d=new Array(i),h=new Array(o).fill(0),p=a.shape.slice();p[s]=1;for(let c=0;c<d.length;c++)h[s]=c,d[c]=Wo({inputs:{x:a},attrs:{begin:h,size:p},backend:r});return d.map(({dataId:c,dtype:m})=>({dataId:c,dtype:m,shape:l}))}var Qye={kernelName:Tl,backendName:"wasm",kernelFunc:Jye};function e3e(e){let{inputs:{x:t},backend:r}=e,n=r.makeOutput(t.shape,t.dtype);return r.typedArrayFromHeap(n).fill(0),n}var t3e={kernelName:Nl,backendName:"wasm",kernelFunc:e3e},r3e=[Lme,Bme,Vme,jme,Qme,r1e,s1e,l1e,h1e,A1e,x1e,b1e,k1e,I1e,T1e,R1e,$1e,M1e,P1e,D1e,W1e,G1e,q1e,X1e,Z1e,Y1e,J1e,Q1e,r2e,n2e,s2e,l2e,p2e,f2e,y2e,b2e,w2e,I2e,Hme,T2e,E2e,$2e,M2e,_2e,P2e,z2e,L2e,V2e,G2e,q2e,Z2e,Q2e,tge,age,ige,oge,dge,cge,gge,Age,vge,kge,Sge,lC,Ege,Mge,Pge,zge,Lge,Bge,Wge,u1e,Gge,qge,Zge,Yge,Jge,tye,aye,oye,lye,g1e,pye,cye,gye,xye,vye,kye,Sye,Cye,Tye,Eye,Mye,Pye,zye,Bye,Wye,Vye,jye,Xye,Yye,Zme,Qye,t3e];for(let e of r3e)qn(e);var Sy=Z();Sy.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])));Sy.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(Sy.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 F7=Vo(MR()),n3e=`"use strict";var Module={};var ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads");var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",function(data){onmessage({data:data})});var fs=require("fs");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,"utf8"))},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+"
|
|
");return}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;self.alert=threadAlert;Module["instantiateWasm"]=((info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports});self.onmessage=(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})}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,1);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInit();try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(Module["keepRuntimeAlive"]()){Module["PThread"].setExitStatus(result)}else{Module["__emscripten_thread_exit"](result)}}catch(ex){if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["__emscripten_thread_exit"](ex.status)}}else{throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["__emscripten_thread_exit"](-1)}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else if(e.data.cmd==="processProxyingQueue"){if(Module["_pthread_self"]()){Module["_emscripten_proxy_execute_queue"](e.data.queue)}}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);if(Module["__emscripten_thread_crashed"]){Module["__emscripten_thread_crashed"]()}throw ex}});`,a3e=Vo(FR()),EC=class extends Gu{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(RC),Cy=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new nh(this,Xt())}write(e,t,r){let n={id:this.dataIdNextNumber++};return this.move(n,e,t,r,1),n}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=v.now();return e(),{kernelMs:v.now()-t}}move(e,t,r,n,a){let s=this.dataIdNextNumber++;if(n==="string"){let u=t;this.dataIdMap.set(e,{id:s,stringBytes:u,shape:r,dtype:n,memoryOffset:null,refCount:a});return}let i=v.sizeFromShape(r),o=i*v.bytesPerElement(n),l=this.wasm._malloc(o);this.dataIdMap.set(e,{id:s,memoryOffset:l,shape:r,dtype:n,refCount:a}),this.wasm.tfjs.registerTensor(s,i,l),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,o),l)}async read(e){return this.readSync(e)}readSync(e,t,r){let{memoryOffset:n,dtype:a,shape:s,stringBytes:i}=this.dataIdMap.get(e);if(a==="string")return(t==null||t===0)&&(r==null||r>=i.length)?i:i.slice(t,r);t=t||0,r=r||v.sizeFromShape(s);let o=v.bytesPerElement(a),l=this.wasm.HEAPU8.slice(n+t*o,n+r*o);return o3e(l.buffer,a)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){let r=this.dataIdMap.get(e);if(r.refCount--,!t&&r.refCount>0)return!1;this.wasm._free(r.memoryOffset),this.wasm.tfjs.disposeData(r.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,r){let n;if(r==null)n=this.write(null,e,t);else{let a=this.dataIdNextNumber++;n={id:a},this.dataIdMap.set(n,{id:a,memoryOffset:r,shape:e,dtype:t,refCount:1});let s=v.sizeFromShape(e);this.wasm.tfjs.registerTensor(a,s,r)}return{dataId:n,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:r}){let n=this.wasm.HEAPU8.buffer,{memoryOffset:a}=this.dataIdMap.get(r),s=v.sizeFromShape(e);switch(t){case"float32":return new Float32Array(n,a,s);case"int32":return new Int32Array(n,a,s);case"bool":return new Uint8Array(n,a,s);default:throw new Error(`Unknown dtype ${t}`)}}};function s3e(e){return(t,r)=>(v.fetch(e,{credentials:"same-origin"}).then(n=>{n.ok||t.env.a(`failed to load wasm binary file at '${e}'`),n.arrayBuffer().then(a=>{WebAssembly.instantiate(a,t).then(s=>{r(s.instance,s.module)})})}),{})}function _7(e,t,r){if(nf!=null)return nf;let n="tfjs-backend-wasm.wasm";return e&&t?n="tfjs-backend-wasm-threaded-simd.wasm":e&&(n="tfjs-backend-wasm-simd.wasm"),Vp!=null&&Vp[n]!=null?Vp[n]:r+n}async function i3e(){let[e,t]=await Promise.all([Z().getAsync("WASM_HAS_SIMD_SUPPORT"),Z().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((r,n)=>{let a={};a.locateFile=(o,l)=>{if(o.endsWith(".worker.js")){let u=n3e.replace(/\n/g,"\\n"),d=new Blob([u],{type:"application/javascript"});return URL.createObjectURL(d)}return o.endsWith(".wasm")?_7(e,t,Dp!=null?Dp:l):l+o},jA&&(a.instantiateWasm=s3e(_7(e,t,Dp!=null?Dp:"")));let s=!1;a.onAbort=()=>{s||Up||(Up=!0,n({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 i;t&&e&&nf==null?(a.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+F7.default.toString()],{type:"text/javascript"}),i=(0,F7.default)(a)):i=(0,a3e.default)(a),i.then(o=>{s=!0,Up=!1;let l=null;o.tfjs={init:o.cwrap("init",null,[]),initWithThreadsCount:o.cwrap("init_with_threads_count",null,["number"]),getThreadsCount:o.cwrap("get_threads_count","number",[]),registerTensor:o.cwrap("register_tensor",null,["number","number","number"]),disposeData:o.cwrap("dispose_data",l,["number"]),dispose:o.cwrap("dispose",l,[])},r({wasm:o})})})}function o3e(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 l3e=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],nf=null,Dp=null,Vp={},Up=!1,jA=!1;function u3e(e,t=!1){if(Wy("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),Up)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");nf=e,jA=t}function HA(e,t=!1){if(Up)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")Dp=e;else{Vp=e;let r=l3e.filter(n=>Vp[n]==null);if(r.length>0)throw new Error(`There were no entries found for the following binaries: ${r.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.`)}jA=t}var RC=-1,Cy=-1;function d3e(e){RC=e}function p3e(){if(Cy===-1)throw new Error("WASM backend not initialized.");return Cy}var h3e="0.0.0",c3e=2;Rl("wasm",async()=>{let{wasm:e}=await i3e();return new EC(e)},c3e);var Is="3.18.0-20220602",nc={tfjs:Is,"tfjs-core":Is,"tfjs-data":Is,"tfjs-layers":Is,"tfjs-converter":Is,"tfjs-backend-cpu":Is,"tfjs-backend-webgl":Is,"tfjs-backend-wasm":Is};var $C=`
|
|
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 MC=`
|
|
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];
|
|
}
|
|
`,FC=`
|
|
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;
|
|
}
|
|
`,_C=`
|
|
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);
|
|
}
|
|
`,PC=`
|
|
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;
|
|
}
|
|
`,OC=`
|
|
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 qA=(e,t,r)=>{let n=new RegExp("\\b"+t+" \\w+ (\\w+)","ig");e.replace(n,(a,s)=>(r[s]=0,a))},XA=class{constructor(t,r,n){fe(this,"uniform",{});fe(this,"attribute",{});fe(this,"gl");fe(this,"id");fe(this,"compile",(t,r)=>{let n=this.gl.createShader(r);return n?(this.gl.shaderSource(n,t),this.gl.compileShader(n),this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS)?n:(se(`filter: gl compile failed: ${this.gl.getShaderInfoLog(n)}`),null)):(se("filter: could not create shader"),null)});this.gl=t;let a=this.compile(r,this.gl.VERTEX_SHADER),s=this.compile(n,this.gl.FRAGMENT_SHADER);if(this.id=this.gl.createProgram(),!(!a||!s)){if(!this.id){se("filter: could not create webgl program");return}if(this.gl.attachShader(this.id,a),this.gl.attachShader(this.id,s),this.gl.linkProgram(this.id),!this.gl.getProgramParameter(this.id,this.gl.LINK_STATUS)){se(`filter: gl link failed: ${this.gl.getProgramInfoLog(this.id)}`);return}this.gl.useProgram(this.id),qA(r,"attribute",this.attribute);for(let i in this.attribute)this.attribute[i]=this.gl.getAttribLocation(this.id,i);qA(r,"uniform",this.uniform),qA(n,"uniform",this.uniform);for(let i in this.uniform)this.uniform[i]=this.gl.getUniformLocation(this.id,i)}}};function zC(){let e=0,t=null,r=!1,n=-1,a=[null,null],s=[],i=null,o=null,l=Zr(100,100),u={},d={INTERMEDIATE:1},h=l.getContext("webgl");if(!h){se("filter: cannot get webgl context");return}this.gl=h;function p(A,x){if(!(A===l.width&&x===l.height)){if(l.width=A,l.height=x,!i){let b=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=h.createBuffer(),h.bindBuffer(h.ARRAY_BUFFER,i),h.bufferData(h.ARRAY_BUFFER,b,h.STATIC_DRAW),h.pixelStorei(h.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0)}h.viewport(0,0,l.width,l.height),a=[null,null]}}function c(A,x){let b=h.createFramebuffer();h.bindFramebuffer(h.FRAMEBUFFER,b);let w=h.createRenderbuffer();h.bindRenderbuffer(h.RENDERBUFFER,w);let I=h.createTexture();return h.bindTexture(h.TEXTURE_2D,I),h.texImage2D(h.TEXTURE_2D,0,h.RGBA,A,x,0,h.RGBA,h.UNSIGNED_BYTE,null),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MAG_FILTER,h.LINEAR),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MIN_FILTER,h.LINEAR),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_2D,I,0),h.bindTexture(h.TEXTURE_2D,null),h.bindFramebuffer(h.FRAMEBUFFER,null),{fbo:b,texture:I}}function m(A){return a[A]=a[A]||c(l.width,l.height),a[A]}function f(A=0){if(!o)return;let x=null,b=null,w=!1;e===0?x=t:x=m(n).texture||null,e++,r&&!(A&d.INTERMEDIATE)?(b=null,w=e%2===0):(n=(n+1)%2,b=m(n).fbo||null),h.bindTexture(h.TEXTURE_2D,x),h.bindFramebuffer(h.FRAMEBUFFER,b),h.uniform1f(o.uniform.flipY,w?-1:1),h.drawArrays(h.TRIANGLES,0,6)}function g(A){if(u[A])return o=u[A],h.useProgram((o?o.id:null)||null),o;if(o=new XA(h,$C,A),!o)return se("filter: could not get webgl program"),null;let x=Float32Array.BYTES_PER_ELEMENT,b=4*x;return h.enableVertexAttribArray(o.attribute.pos),h.vertexAttribPointer(o.attribute.pos,2,h.FLOAT,!1,b,0*x),h.enableVertexAttribArray(o.attribute.uv),h.vertexAttribPointer(o.attribute.uv,2,h.FLOAT,!1,b,2*x),u[A]=o,o}let y={colorMatrix:A=>{let x=new Float32Array(A);x[4]/=255,x[9]/=255,x[14]/=255,x[19]/=255;let b=x[18]===1&&x[3]===0&&x[8]===0&&x[13]===0&&x[15]===0&&x[16]===0&&x[17]===0&&x[19]===0?FC:MC,w=g(b);!w||(h.uniform1fv(w.uniform.m,x),f())},brightness:A=>{let x=(A||0)+1;y.colorMatrix([x,0,0,0,0,0,x,0,0,0,0,0,x,0,0,0,0,0,1,0])},saturation:A=>{let x=(A||0)*2/3+1,b=(x-1)*-.5;y.colorMatrix([x,b,b,0,0,b,x,b,0,0,b,b,x,0,0,0,0,0,1,0])},desaturate:()=>{y.saturation(-1)},contrast:A=>{let x=(A||0)+1,b=-128*(x-1);y.colorMatrix([x,0,0,0,b,0,x,0,0,b,0,0,x,0,b,0,0,0,1,0])},negative:()=>{y.contrast(-2)},hue:A=>{A=(A||0)/180*Math.PI;let x=Math.cos(A),b=Math.sin(A),w=.213,I=.715,T=.072;y.colorMatrix([w+x*(1-w)+b*-w,I+x*-I+b*-I,T+x*-T+b*(1-T),0,0,w+x*-w+b*.143,I+x*(1-I)+b*.14,T+x*-T+b*-.283,0,0,w+x*-w+b*-(1-w),I+x*-I+b*I,T+x*(1-T)+b*T,0,0,0,0,0,1,0])},desaturateLuminance:()=>{y.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:()=>{y.colorMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0])},brownie:()=>{y.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:()=>{y.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:()=>{y.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:()=>{y.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:()=>{y.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:()=>{y.colorMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0])},convolution:A=>{let x=new Float32Array(A),b=1/l.width,w=1/l.height,I=g(OC);!I||(h.uniform1fv(I.uniform.m,x),h.uniform2f(I.uniform.px,b,w),f())},detectEdges:()=>{y.convolution.call(this,[0,1,0,1,-4,1,0,1,0])},sobelX:()=>{y.convolution.call(this,[-1,0,1,-2,0,2,-1,0,1])},sobelY:()=>{y.convolution.call(this,[-1,-2,-1,0,0,0,1,2,1])},sharpen:A=>{let x=A||1;y.convolution.call(this,[0,-1*x,0,-1*x,1+4*x,-1*x,0,-1*x,0])},emboss:A=>{let x=A||1;y.convolution.call(this,[-2*x,-1*x,0,-1*x,1,1*x,0,1*x,2*x])},blur:A=>{let x=A/7/l.width,b=A/7/l.height,w=g(PC);!w||(h.uniform2f(w.uniform.px,0,b),f(d.INTERMEDIATE),h.uniform2f(w.uniform.px,x,0),f())},pixelate:A=>{let x=A/l.width,b=A/l.height,w=g(_C);!w||(h.uniform2f(w.uniform.size,x,b),f())}};this.add=function(A){let x=Array.prototype.slice.call(arguments,1),b=y[A];s.push({func:b,args:x})},this.reset=function(){s=[]},this.get=function(){return s},this.apply=function(A){p(A.width,A.height),e=0,t||(t=h.createTexture()),h.bindTexture(h.TEXTURE_2D,t),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MIN_FILTER,h.NEAREST),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MAG_FILTER,h.NEAREST),h.texImage2D(h.TEXTURE_2D,0,h.RGBA,h.RGBA,h.UNSIGNED_BYTE,A);for(let x=0;x<s.length;x++){r=x===s.length-1;let b=s[x];b.func.apply(this,b.args||[])}return l},this.draw=function(A){return this.add("brightness",0),this.apply(A)}}async function Um(e){let t=e.shape.length===4?et(e):e,r=Yt(t,3,2),n=[Bs(r[0]),Bs(r[1]),Bs(r[2])],a=[yr(r[0]),yr(r[1]),yr(r[2])],s=await Promise.all(a.map(c=>c.data())),i=.99*Math.max(s[0][0],s[1][0],s[2][0]),o=[ce(r[0],n[0]),ce(r[1],n[1]),ce(r[2],n[2])],l=[ce(a[0],n[0]),ce(a[1],n[1]),ce(a[2],n[2])],u=[pe(i,l[0]),pe(i,l[1]),pe(i,l[2])],d=[L(o[0],u[0]),L(o[1],u[1]),L(o[2],u[2])],h=ur([d[0],d[1],d[2]],2),p=U(h,[1,t.shape[0],t.shape[1],3]);return ee([...r,...n,...a,...o,...l,...u,...d,h,t]),p}var Gm=3840,ut=null,er=null,Vd=null,Et,os={inputSum:0,cacheDiff:1,sumMethod:0,inputTensor:void 0};function Zr(e,t){let r;if(he.browser)if(he.worker){if(typeof OffscreenCanvas=="undefined")throw new Error("canvas error: attempted to run in web worker but OffscreenCanvas is not supported");r=new OffscreenCanvas(e,t)}else{if(typeof document=="undefined")throw new Error("canvas error: attempted to run in browser but DOM is not defined");r=document.createElement("canvas"),r.width=e,r.height=t}else typeof he.Canvas!="undefined"?r=new he.Canvas(e,t):typeof globalThis.Canvas!="undefined"&&(r=new globalThis.Canvas(e,t));return r}function jm(e,t){let r=t||Zr(e.width,e.height);return r.getContext("2d").drawImage(e,0,0),r}async function Ud(e,t,r=!0){if(!e)return t.debug&&se("input error: input is missing"),{tensor:null,canvas:null};if(!(e instanceof nt)&&!(typeof Image!="undefined"&&e instanceof Image)&&!(typeof he.Canvas!="undefined"&&e instanceof he.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 error: type is not recognized");if(e instanceof nt){let n=null;if(e.isDisposedInternal)throw new Error("input error: attempted to use tensor but it is disposed");if(!e.shape)throw new Error("input error: attempted to use tensor without a shape");if(e.shape.length===3){if(e.shape[2]===3)n=Kt(e,0);else if(e.shape[2]===4){let a=_l(e,[0,0,0],[-1,-1,3]);n=Kt(a,0),ee(a)}}else e.shape.length===4&&(e.shape[3]===3?n=Vr(e):e.shape[3]===4&&(n=Po(e,[0,0,0,0],[-1,-1,-1,3])));if(n==null||n.shape.length!==4||n.shape[0]!==1||n.shape[3]!==3)throw new Error(`input error: attempted to use tensor with unrecognized shape: ${e.shape}`);if(n.dtype==="int32"){let a=me(n,"float32");ee(n),n=a}return{tensor:n,canvas:t.filter.return?er:null}}else{if(typeof e.readyState!="undefined"&&e.readyState<=2)return t.debug&&se("input stream is not ready"),{tensor:null,canvas:ut};let n=e.naturalWidth||e.videoWidth||e.width||e.shape&&e.shape[1]>0,a=e.naturalHeight||e.videoHeight||e.height||e.shape&&e.shape[2]>0;if(!n||!a)return t.debug&&se("cannot determine input dimensions"),{tensor:null,canvas:ut};let s=n,i=a;if(s>Gm&&(s=Gm,i=Math.trunc(s*a/n)),i>Gm&&(i=Gm,s=Math.trunc(i*n/a)),(t.filter.width||0)>0?s=t.filter.width:(t.filter.height||0)>0&&(s=n*((t.filter.height||0)/a)),(t.filter.height||0)>0?i=t.filter.height:(t.filter.width||0)>0&&(i=a*((t.filter.width||0)/n)),!s||!i)throw new Error("input error: cannot determine dimension");(!ut||(ut==null?void 0:ut.width)!==s||(ut==null?void 0:ut.height)!==i)&&(ut=Zr(s,i));let o=ut.getContext("2d");if(typeof ImageData!="undefined"&&e instanceof ImageData?o.putImageData(e,0,0):t.filter.flip&&typeof o.translate!="undefined"?(o.translate(n,0),o.scale(-1,1),o.drawImage(e,0,0,n,a,0,0,ut==null?void 0:ut.width,ut==null?void 0:ut.height),o.setTransform(1,0,0,1,0,0)):o.drawImage(e,0,0,n,a,0,0,ut==null?void 0:ut.width,ut==null?void 0:ut.height),(!er||ut.width!==er.width||(ut==null?void 0:ut.height)!==(er==null?void 0:er.height))&&(er=Zr(ut.width,ut.height)),t.filter.enabled&&he.webgl.supported?(Et||(Et=he.browser?new zC:null),he.filter=!!Et,!Et||!Et.add?(t.debug&&se("input process error: cannot initialize filters"),he.webgl.supported=!1,t.filter.enabled=!1,jm(ut,er)):(Et.reset(),t.filter.brightness!==0&&Et.add("brightness",t.filter.brightness),t.filter.contrast!==0&&Et.add("contrast",t.filter.contrast),t.filter.sharpness!==0&&Et.add("sharpen",t.filter.sharpness),t.filter.blur!==0&&Et.add("blur",t.filter.blur),t.filter.saturation!==0&&Et.add("saturation",t.filter.saturation),t.filter.hue!==0&&Et.add("hue",t.filter.hue),t.filter.negative&&Et.add("negative"),t.filter.sepia&&Et.add("sepia"),t.filter.vintage&&Et.add("brownie"),t.filter.sepia&&Et.add("sepia"),t.filter.kodachrome&&Et.add("kodachrome"),t.filter.technicolor&&Et.add("technicolor"),t.filter.polaroid&&Et.add("polaroid"),t.filter.pixelate!==0&&Et.add("pixelate",t.filter.pixelate),Et.get()>0?er=Et.apply(ut):er=Et.draw(ut))):(jm(ut,er),Et&&(Et=null),he.filter=!!Et),!r)return{tensor:null,canvas:er};if(!er)throw new Error("canvas error: cannot create output");let l,u=3;if(typeof ImageData!="undefined"&&e instanceof ImageData||e.data&&e.width&&e.height)if(he.browser&&Ln)l=Ln?Ln.fromPixels(e):null;else{u=e.data.length/e.height/e.width;let p=new Uint8Array(e.data.buffer);l=ft(p,[e.height,e.width,u],"int32")}else if((!Vd||er.width!==Vd.width||er.height!==Vd.height)&&(Vd=Zr(er.width,er.height)),Ln&&he.browser)t.backend==="webgl"||t.backend==="humangl"||t.backend==="webgpu"?l=Ln.fromPixels(er):(Vd=jm(er),l=Ln.fromPixels(Vd));else{let m=jm(er).getContext("2d").getImageData(0,0,s,i);u=m.data.length/s/i;let f=new Uint8Array(m.data.buffer);l=ft(f,[s,i,u])}if(u===4){let p=_l(l,[0,0,0],[-1,-1,3]);ee(l),l=p}if(!l)throw new Error("input error: cannot create tensor");let d=me(l,"float32"),h=t.filter.equalization?await Um(d):Kt(d,0);return ee([l,d]),{tensor:h,canvas:t.filter.return?er:null}}}async function DC(e,t){let r=!1;if(e.cacheSensitivity===0||!t.shape||t.shape.length!==4||t.shape[1]>2048||t.shape[2]>2048)return r;if(!os.inputTensor)os.inputTensor=Vr(t);else if(os.inputTensor.shape[1]!==t.shape[1]||os.inputTensor.shape[2]!==t.shape[2])ee(os.inputTensor),os.inputTensor=Vr(t);else{let n={};n.diff=ce(t,os.inputTensor),n.squared=L(n.diff,n.diff),n.sum=ke(n.squared);let s=(await n.sum.data())[0]/(t.shape[1]||1)/(t.shape[2]||1)/255/3;ee([os.inputTensor,n.diff,n.squared,n.sum]),os.inputTensor=Vr(t),r=s<=(e.cacheSensitivity||0)}return r}async function LC(e,t,r){let n={};if(!t||!r||t.shape.length!==4||t.shape.length!==r.shape.length)return e.debug||se("invalid input tensor or tensor shapes do not match:",t.shape,r.shape),0;if(t.shape[0]!==1||r.shape[0]!==1||t.shape[3]!==3||r.shape[3]!==3)return e.debug||se("input tensors must be of shape [1, height, width, 3]:",t.shape,r.shape),0;n.input1=Vr(t),n.input2=t.shape[1]!==r.shape[1]||t.shape[2]!==r.shape[2]?Ie.resizeBilinear(r,[t.shape[1],t.shape[2]]):Vr(r),n.diff=ce(n.input1,n.input2),n.squared=L(n.diff,n.diff),n.sum=ke(n.squared);let s=(await n.sum.data())[0]/(t.shape[1]||1)/(t.shape[2]||1)/255/3;return ee([n.input1,n.input2,n.diff,n.squared,n.sum]),s}var KA=class{constructor(){fe(this,"browser");fe(this,"node");fe(this,"worker");fe(this,"platform","");fe(this,"agent","");fe(this,"backends",[]);fe(this,"initial");fe(this,"filter");fe(this,"tfjs");fe(this,"offscreen");fe(this,"perfadd",!1);fe(this,"wasm",{supported:void 0,backend:void 0,simd:void 0,multithread:void 0});fe(this,"webgl",{supported:void 0,backend:void 0,version:void 0,renderer:void 0});fe(this,"webgpu",{supported:void 0,backend:void 0,adapter:void 0});fe(this,"cpu",{model:void 0,flags:[]});fe(this,"kernels",[]);fe(this,"Canvas");fe(this,"Image");fe(this,"ImageData");if(this.browser=typeof navigator!="undefined",this.node=typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined",this.tfjs={version:nc["tfjs-core"]},this.offscreen=typeof OffscreenCanvas!="undefined",this.initial=!0,this.worker=this.browser&&this.offscreen?typeof WorkerGlobalScope!="undefined":void 0,typeof navigator!="undefined"){let t=navigator.userAgent.match(/\(([^()]+)\)/g);if(t&&t[0]){let r=t[0].match(/\(([^()]+)\)/g);this.platform=r&&r[0]?r[0].replace(/\(|\)/g,""):"",this.agent=navigator.userAgent.replace(t[0],""),this.platform[1]&&(this.agent=this.agent.replace(t[1],"")),this.agent=this.agent.replace(/ /g," ")}}else typeof process!="undefined"&&(this.platform=`${process.platform} ${process.arch}`,this.agent=`NodeJS ${process.version}`)}async updateBackend(){this.backends=Object.keys(Xt().registryFactory),this.wasm.supported=typeof WebAssembly!="undefined",this.wasm.backend=this.backends.includes("wasm"),this.wasm.supported&&this.wasm.backend&&Hr()==="wasm"&&(this.wasm.simd=await Z().getAsync("WASM_HAS_SIMD_SUPPORT"),this.wasm.multithread=await Z().getAsync("WASM_HAS_MULTITHREAD_SUPPORT"));let t=Zr(100,100),r=t?t.getContext("webgl2"):void 0;if(this.webgl.supported=typeof r!="undefined",this.webgl.backend=this.backends.includes("webgl"),this.webgl.supported&&this.webgl.backend&&(Hr()==="webgl"||Hr()==="humangl")){let n=Dn().gpgpu!=="undefined"?await Dn().getGPGPUContext().gl:null;n&&(this.webgl.version=n.getParameter(n.VERSION),this.webgl.renderer=n.getParameter(n.RENDERER))}this.webgpu.supported=this.browser&&typeof navigator.gpu!="undefined",this.webgpu.backend=this.backends.includes("webgpu");try{this.webgpu.supported&&(this.webgpu.adapter=(await navigator.gpu.requestAdapter()).name)}catch(n){this.webgpu.supported=!1}try{this.kernels=Fa(Hr()).map(n=>n.kernelName.toLowerCase())}catch(n){}}async updateCPU(){let t={model:"",flags:[]};this.node&&this.platform.startsWith("linux"),this.cpu?this.cpu=t:Object.defineProperty(this,"cpu",{value:t})}},he=new KA;var ls={cacheModels:!1,verbose:!0,debug:!1,modelBasePath:""},La={};async function y3e(e,t){return ls.debug&&se("load model fetch:",e,t),fetch(e,t)}function BC(e){ls.cacheModels=e.cacheModels,ls.verbose=e.debug,ls.modelBasePath=e.modelBasePath}async function Ge(e){var u,d,h;let t=Hb(ls.modelBasePath,e||"");t.toLowerCase().endsWith(".json")||(t+=".json");let r=t.split("/"),n=r[r.length-1].replace(".json",""),a="indexeddb://"+n;La[n]={name:n,manifest:0,weights:0,cached:!1};let s=await Cr.listModels();La[n].cached=ls.cacheModels&&Object.keys(s).includes(a);let i=typeof fetch=="undefined"?{}:{fetchFunc:(p,c)=>y3e(p,c)},o=new Uh(La[n].cached?a:t,i),l=!1;try{o.findIOHandler(),ls.debug&&se("model load handler:",o.handler);let p=await o.handler.load();La[n].manifest=((u=p==null?void 0:p.weightData)==null?void 0:u.byteLength)||0,o.loadSync(p),La[n].weights=((h=(d=o==null?void 0:o.artifacts)==null?void 0:d.weightData)==null?void 0:h.byteLength)||0,ls.verbose&&se("load model:",o.modelUrl,{bytes:La[n].weights}),l=!0}catch(p){se("error loading model:",t,p)}if(l&&ls.cacheModels&&!La[n].cached)try{let p=await o.save(a);se("model saved:",a,p)}catch(p){se("error saving model:",t,p)}return o}var ZA="2.8.1";var T1={};ws(T1,{Models:()=>cc,getModelStats:()=>ob,load:()=>lb,reset:()=>C1,validate:()=>ub});var Jn,YA=[],b3e=["white","black","asian","indian","other"],v3e=[15,23,28,35.5,45.5,55.5,65],WC=0,VC=0,JA=Number.MAX_SAFE_INTEGER;async function UC(e){return he.initial&&(Jn=null),Jn?e.debug&&se("cached model:",Jn.modelUrl):Jn=await Ge(e.face.gear),Jn}async function QA(e,t,r,n){var i,o;if(!Jn)return{age:0,gender:"unknown",genderScore:0,race:[]};let a=JA<(((i=t.face.gear)==null?void 0:i.skipFrames)||0),s=(((o=t.face.gear)==null?void 0:o.skipTime)||0)>oe()-VC;return t.skipAllowed&&s&&a&&WC===n&&YA[r]?(JA++,YA[r]):(JA=0,new Promise(async l=>{var y,A;if(!(Jn!=null&&Jn.inputs[0].shape))return;let u={},d=[[0,.1,.9,.9]];u.resize=Ie.cropAndResize(e,d,[0],[Jn.inputs[0].shape[2],Jn.inputs[0].shape[1]]);let h={age:0,gender:"unknown",genderScore:0,race:[]};(y=t.face.gear)!=null&&y.enabled&&([u.age,u.gender,u.race]=Jn.execute(u.resize,["age_output","gender_output","race_output"]));let p=await u.gender.data();h.gender=p[0]>p[1]?"male":"female",h.genderScore=Math.round(100*(p[0]>p[1]?p[0]:p[1]))/100;let c=await u.race.data();for(let x=0;x<c.length;x++)c[x]>(((A=t.face.gear)==null?void 0:A.minConfidence)||.2)&&h.race.push({score:Math.round(100*c[x])/100,race:b3e[x]});h.race.sort((x,b)=>b.score-x.score);let f=Array.from(await u.age.data()).map((x,b)=>[v3e[b],x]).sort((x,b)=>b[1]-x[1]),g=f[0][0];for(let x=1;x<f.length;x++)g+=f[x][1]*(f[x][0]-g);h.age=Math.round(10*g)/10,Object.keys(u).forEach(x=>ee(u[x])),YA[r]=h,WC=n,VC=oe(),l(h)}))}var Qe={tf255:255,tf1:1,tf2:2,tf05:.5,tf127:127.5,rgb:[.2989,.587,.114]};function jC(){Qe.tf255=Se(255,"float32"),Qe.tf1=Se(1,"float32"),Qe.tf2=Se(2,"float32"),Qe.tf05=Se(.5,"float32"),Qe.tf127=Se(127.5,"float32"),Qe.rgb=Nt([.2989,.587,.114],"float32")}var yn,Hm=[],HC=0,qC=0,ex=Number.MAX_SAFE_INTEGER;async function XC(e){return he.initial&&(yn=null),yn?e.debug&&se("cached model:",yn.modelUrl):yn=await Ge(e.face.ssrnet.modelPathAge),yn}async function tx(e,t,r,n){var i,o,l,u;if(!yn)return{age:0};let a=ex<(((i=t.face.ssrnet)==null?void 0:i.skipFrames)||0),s=(((o=t.face.ssrnet)==null?void 0:o.skipTime)||0)>oe()-qC;return t.skipAllowed&&a&&s&&HC===n&&((l=Hm[r])==null?void 0:l.age)&&((u=Hm[r])==null?void 0:u.age)>0?(ex++,Hm[r]):(ex=0,new Promise(async d=>{if(!(yn!=null&&yn.inputs)||!yn.inputs[0]||!yn.inputs[0].shape)return;let h={};h.resize=Ie.resizeBilinear(e,[yn.inputs[0].shape[2],yn.inputs[0].shape[1]],!1),h.enhance=L(h.resize,Qe.tf255);let p={age:0};if(t.face.ssrnet.enabled&&(h.age=yn.execute(h.enhance)),h.age){let c=await h.age.data();p.age=Math.trunc(10*c[0])/10}Object.keys(h).forEach(c=>ee(h[c])),Hm[r]=p,HC=n,qC=oe(),d(p)}))}var Qn,qm=[],ZC=0,YC=0,rx=Number.MAX_SAFE_INTEGER,nx=[.2989,.587,.114];async function JC(e){return he.initial&&(Qn=null),Qn?e.debug&&se("cached model:",Qn.modelUrl):Qn=await Ge(e.face.ssrnet.modelPathGender),Qn}async function ax(e,t,r,n){var i,o,l,u;if(!Qn)return{gender:"unknown",genderScore:0};let a=rx<(((i=t.face.ssrnet)==null?void 0:i.skipFrames)||0),s=(((o=t.face.ssrnet)==null?void 0:o.skipTime)||0)>oe()-YC;return t.skipAllowed&&a&&s&&ZC===n&&((l=qm[r])==null?void 0:l.gender)&&((u=qm[r])==null?void 0:u.genderScore)>0?(rx++,qm[r]):(rx=0,new Promise(async d=>{if(!(Qn!=null&&Qn.inputs[0].shape))return;let h={};h.resize=Ie.resizeBilinear(e,[Qn.inputs[0].shape[2],Qn.inputs[0].shape[1]],!1),h.enhance=X(()=>{let[m,f,g]=Yt(h.resize,3,3),y=L(m,nx[0]),A=L(f,nx[1]),x=L(g,nx[2]),b=Of([y,A,x]);return L(ce(b,Qe.tf05),2)});let p={gender:"unknown",genderScore:0};t.face.ssrnet.enabled&&(h.gender=Qn.execute(h.enhance));let c=await h.gender.data();p.gender=c[0]>c[1]?"female":"male",p.genderScore=c[0]>c[1]?Math.trunc(100*c[0])/100:Math.trunc(100*c[1])/100,Object.keys(h).forEach(m=>ee(h[m])),qm[r]=p,ZC=n,YC=oe(),d(p)}))}var Rr,Xm=[],sx=Number.MAX_SAFE_INTEGER,eT=0,tT=0;async function rT(e){var t;return he.initial&&(Rr=null),Rr?e.debug&&se("cached model:",Rr.modelUrl):Rr=await Ge((t=e.face.antispoof)==null?void 0:t.modelPath),Rr}async function ix(e,t,r,n){var i,o;if(!Rr)return 0;let a=(((i=t.face.antispoof)==null?void 0:i.skipTime)||0)>oe()-tT,s=sx<(((o=t.face.antispoof)==null?void 0:o.skipFrames)||0);return t.skipAllowed&&a&&s&&eT===n&&Xm[r]?(sx++,Xm[r]):(sx=0,new Promise(async l=>{let u=Ie.resizeBilinear(e,[Rr!=null&&Rr.inputs[0].shape?Rr.inputs[0].shape[2]:0,Rr!=null&&Rr.inputs[0].shape?Rr.inputs[0].shape[1]:0],!1),d=Rr==null?void 0:Rr.execute(u),h=(await d.data())[0];Xm[r]=Math.round(100*h)/100,eT=n,tT=oe(),ee([u,d]),l(Xm[r])}))}var ea={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:[185,40,39,37,0,267,269,270,409],lipsLowerOuter:[61,146,91,181,84,17,314,405,321,375,291],lipsUpperInner:[191,80,81,82,13,312,311,310,415],lipsLowerInner:[78,95,88,178,87,14,317,402,318,324,308],lipsLowerSemiOuter:[76,77,90,180,85,16,315,404,320,307,306],lipsUpperSemiOuter:[184,74,73,72,11,302,303,304,408],lipsLowerSemiInner:[62,96,89,179,86,15,316,403,319,325,292],lipsUpperSemiInner:[183,42,41,38,12,268,271,272,407],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]},ox={count:468,mouth:13,symmetryLine:[13,ea.midwayBetweenEyes[0]]},Vl={leftEye:0,rightEye:1,nose:2,mouth:3,leftEar:4,rightEar:5,symmetryLine:[3,2]},lx=[{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]},{key:"EyebrowUpper",indices:[63,64,65,66,67,68,69,70]},{key:"EyebrowLower",indices:[48,49,50,51,52,53]}],sc=[[.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]],Ul=[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 k3e=[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],I3e=[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],S3e=[33,133,362,263,1,78,308],Twe=k3e.map(e=>sc[e]),Nwe=I3e.map(e=>sc[e]),Ewe=S3e.map(e=>sc[e]);function Ki(e){let t=e.map(r=>r[0]);return t.push(e[e.length-1][1]),t}var C3e=[[61,146],[146,91],[91,181],[181,84],[84,17],[17,314],[314,405],[405,321],[321,375],[375,291],[61,185],[185,40],[40,39],[39,37],[37,0],[0,267],[267,269],[269,270],[270,409],[409,291],[78,95],[95,88],[88,178],[178,87],[87,14],[14,317],[317,402],[402,318],[318,324],[324,308],[78,191],[191,80],[80,81],[81,82],[82,13],[13,312],[312,311],[311,310],[310,415],[415,308]],T3e=[[263,249],[249,390],[390,373],[373,374],[374,380],[380,381],[381,382],[382,362],[263,466],[466,388],[388,387],[387,386],[386,385],[385,384],[384,398],[398,362]],N3e=[[276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]],E3e=[[474,475],[475,476],[476,477],[477,474]],R3e=[[33,7],[7,163],[163,144],[144,145],[145,153],[153,154],[154,155],[155,133],[33,246],[246,161],[161,160],[160,159],[159,158],[158,157],[157,173],[173,133]],$3e=[[46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]],M3e=[[469,470],[470,471],[471,472],[472,469]],F3e=[[10,338],[338,297],[297,332],[332,284],[284,251],[251,389],[389,356],[356,454],[454,323],[323,361],[361,288],[288,397],[397,365],[365,379],[379,378],[378,400],[400,377],[377,152],[152,148],[148,176],[176,149],[149,150],[150,136],[136,172],[172,58],[58,132],[132,93],[93,234],[234,127],[127,162],[162,21],[21,54],[54,103],[103,67],[67,109],[109,10]],Rwe={lips:Ki(C3e),leftEye:Ki(T3e),leftEyebrow:Ki(N3e),leftIris:Ki(E3e),rightEye:Ki(R3e),rightEyebrow:Ki($3e),rightIris:Ki(M3e),faceOval:Ki(F3e)};var Gd=e=>[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])],Km=e=>[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2,1],Zm=(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],Ym=(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],iT=(e,t)=>{let r=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],n=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]];return{startPoint:r,endPoint:n,landmarks:e.landmarks,confidence:e.confidence}},dx=(e,t,r)=>{let n=t.shape[1],a=t.shape[2],s=[e.startPoint[1]/n,e.startPoint[0]/a,e.endPoint[1]/n,e.endPoint[0]/a],i=Ie.cropAndResize(t,[s],[0],r),o=pe(i,Qe.tf255);return ee(i),o},Jm=(e,t)=>{let r=Km(e),n=Gd(e),a=[t*n[0]/2,t*n[1]/2];return{startPoint:[r[0]-a[0],r[1]-a[1]],endPoint:[r[0]+a[0],r[1]+a[1]],landmarks:e.landmarks,confidence:e.confidence}},Qm=e=>{let t=Km(e),r=Gd(e),n=Math.max(...r)/2;return{startPoint:[Math.round(t[0]-n),Math.round(t[1]-n)],endPoint:[Math.round(t[0]+n),Math.round(t[1]+n)],landmarks:e.landmarks,confidence:e.confidence}},oT=e=>{let t=e.map(n=>n[0]),r=e.map(n=>n[1]);return{startPoint:[Math.min(...t),Math.min(...r)],endPoint:[Math.max(...t),Math.max(...r)],landmarks:e}},px=[[1,0,0],[0,1,0],[0,0,1]],_3e=e=>e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI)),P3e=(e,t)=>_3e(Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]));var aT=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]],Gl=(e,t)=>{let r=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n];return r},O3e=(e,t)=>{let r=[];for(let n=0;n<e.length;n++)r.push(e[n][t]);return r},sT=(e,t)=>{let r=[],n=e.length;for(let a=0;a<n;a++){r.push([]);for(let s=0;s<n;s++)r[a].push(Gl(e[a],O3e(t,s)))}return r},lT=(e,t)=>{let r=Math.cos(e),n=Math.sin(e),a=[[r,-n,0],[n,r,0],[0,0,1]],s=aT(t[0],t[1]),i=sT(s,a),o=aT(-t[0],-t[1]);return sT(i,o)},z3e=e=>{let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],r=[e[0][2],e[1][2]],n=[-Gl(t[0],r),-Gl(t[1],r)];return[t[0].concat(n[0]),t[1].concat(n[1]),[0,0,1]]},D3e=(e,t)=>[Gl(e,t[0]),Gl(e,t[1])];function uT(e){let t=e===192?{strides:[4],anchors:[1]}:{strides:[e/16,e/8],anchors:[2,6]},r=[];for(let n=0;n<t.strides.length;n++){let a=t.strides[n],s=Math.floor((e+a-1)/a),i=Math.floor((e+a-1)/a),o=t.anchors[n];for(let l=0;l<s;l++){let u=a*(l+.5);for(let d=0;d<i;d++){let h=a*(d+.5);for(let p=0;p<o;p++)r.push([h,u])}}}return r}function dT(e,t,r,n,a){let s=Gd(t),i=e.map(c=>[s[0]/a*(c[0]-a/2),s[1]/a*(c[1]-a/2),c[2]||0]),o=r&&r!==0&&Math.abs(r)>.2,l=o?lT(r,[0,0]):px,u=o?i.map(c=>[...D3e(c,l),c[2]]):i,d=o?z3e(n):px,h=Km(t),p=[Gl(h,d[0]),Gl(h,d[1])];return u.map(c=>[Math.trunc(c[0]+p[0]),Math.trunc(c[1]+p[1]),Math.trunc(c[2]||0)])}function pT(e,t,r,n){let a=t.landmarks.length>=ox.count?ox.symmetryLine:Vl.symmetryLine,s=0,i=px,o;if(e&&he.kernels.includes("rotatewithoffset"))if(s=P3e(t.landmarks[a[0]],t.landmarks[a[1]]),s&&s!==0&&Math.abs(s)>.2){let u=Km(t),d=[u[0]/r.shape[2],u[1]/r.shape[1]],h=Ie.rotateWithOffset(r,s,0,d);i=lT(-s,u),o=dx(t,h,[n,n]),ee(h)}else o=dx(t,r,[n,n]);else o=dx(t,r,[n,n]);return[s,i,o]}var L3e=e=>{let t=e.map(n=>n[0]),r=e.map(n=>n[1]);return[Math.min(...t)+(Math.max(...t)-Math.min(...t))/2,Math.min(...r)+(Math.max(...r)-Math.min(...r))/2]},hT=(e,t)=>{let r=L3e(e),n=Gd(t);return{startPoint:[r[0]-n[0]/2,r[1]-n[1]/2],endPoint:[r[0]+n[0]/2,r[1]+n[1]/2]}};var cT=6,B3e=1.4,Ba,fT=null,Zi=0,ic=null,jd=()=>Zi;async function mT(e){var t;return he.initial&&(Ba=null),Ba?e.debug&&se("cached model:",Ba.modelUrl):Ba=await Ge((t=e.face.detector)==null?void 0:t.modelPath),Zi=Ba.inputs[0].shape?Ba.inputs[0].shape[2]:0,ic=Se(Zi,"int32"),fT=ca(uT(Zi)),Ba}function W3e(e){let t={};t.boxStarts=_e(e,[0,1],[-1,2]),t.centers=le(t.boxStarts,fT),t.boxSizes=_e(e,[0,3],[-1,2]),t.boxSizesNormalized=pe(t.boxSizes,ic),t.centersNormalized=pe(t.centers,ic),t.halfBoxSize=pe(t.boxSizesNormalized,Qe.tf2),t.starts=ce(t.centersNormalized,t.halfBoxSize),t.ends=le(t.centersNormalized,t.halfBoxSize),t.startNormalized=L(t.starts,ic),t.endNormalized=L(t.ends,ic);let r=bd([t.startNormalized,t.endNormalized],1);return Object.keys(t).forEach(n=>ee(t[n])),r}async function gT(e,t){var o,l,u,d;if(!e||e.isDisposedInternal||e.shape.length!==4||e.shape[1]<1||e.shape[2]<1)return[];let r={};r.resized=Ie.resizeBilinear(e,[Zi,Zi]),r.div=pe(r.resized,Qe.tf127),r.normalized=ce(r.div,Qe.tf05);let n=Ba==null?void 0:Ba.execute(r.normalized);if(Array.isArray(n)&&n.length>2){let h=n.sort((p,c)=>p.size-c.size);r.concat384=St([h[0],h[2]],2),r.concat512=St([h[1],h[3]],2),r.concat=St([r.concat512,r.concat384],1),r.batch=et(r.concat,0)}else Array.isArray(n)?r.batch=et(n[0]):r.batch=et(n);ee(n),r.boxes=W3e(r.batch),r.logits=_e(r.batch,[0,0],[-1,1]),r.sigmoid=Tr(r.logits),r.scores=et(r.sigmoid),r.nms=await Ie.nonMaxSuppressionAsync(r.boxes,r.scores,((o=t.face.detector)==null?void 0:o.maxDetected)||0,((l=t.face.detector)==null?void 0:l.iouThreshold)||0,((u=t.face.detector)==null?void 0:u.minConfidence)||0);let a=await r.nms.array(),s=[],i=await r.scores.data();for(let h=0;h<a.length;h++){let p=i[a[h]];if(p>(((d=t.face.detector)==null?void 0:d.minConfidence)||0)){let c={};c.bbox=_e(r.boxes,[a[h],0],[1,-1]),c.slice=_e(r.batch,[a[h],cT-1],[1,-1]),c.squeeze=et(c.slice),c.landmarks=U(c.squeeze,[cT,-1]);let m=await c.bbox.data(),f={startPoint:[m[0],m[1]],endPoint:[m[2],m[3]],landmarks:await c.landmarks.array(),confidence:p},g=iT(f,[(e.shape[2]||0)/Zi,(e.shape[1]||0)/Zi]),y=Jm(g,t.face.scale||B3e),A=Qm(y);s.push(A),Object.keys(c).forEach(x=>ee(c[x]))}}return Object.keys(r).forEach(h=>ee(r[h])),s}var e1={};ws(e1,{connected:()=>fx,kpt:()=>cx});var cx=["nose","leftEyeInside","leftEye","leftEyeOutside","rightEyeInside","rightEye","rightEyeOutside","leftEar","rightEar","leftMouth","rightMouth","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftPinky","rightPinky","leftIndex","rightIndex","leftThumb","rightThumb","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle","leftHeel","rightHeel","leftFoot","rightFoot","bodyCenter","bodyTop","leftPalm","leftHand","rightPalm","rightHand"],fx={shoulders:["leftShoulder","rightShoulder"],hips:["rightHip","leftHip"],mouth:["leftMouth","rightMouth"],leftLegUpper:["leftHip","leftKnee"],leftLegLower:["leftKnee","leftAnkle"],leftFoot:["leftAnkle","leftHeel","leftFoot"],leftTorso:["leftShoulder","leftHip"],leftArmUpper:["leftShoulder","leftElbow"],leftArmLower:["leftElbow","leftWrist"],leftHand:["leftWrist","leftPalm"],leftHandPinky:["leftPalm","leftPinky"],leftHandIndex:["leftPalm","leftIndex"],leftHandThumb:["leftPalm","leftThumb"],leftEyeOutline:["leftEyeInside","leftEyeOutside"],rightLegUpper:["rightHip","rightKnee"],rightLegLower:["rightKnee","rightAnkle"],rightFoot:["rightAnkle","rightHeel","rightFoot"],rightTorso:["rightShoulder","rightHip"],rightArmUpper:["rightShoulder","rightElbow"],rightArmLower:["rightElbow","rightWrist"],rightHand:["rightWrist","rightPalm"],rightHandPinky:["rightPalm","rightPinky"],rightHandIndex:["rightPalm","rightIndex"],rightHandThumb:["rightPalm","rightThumb"],rightEyeOutline:["rightEyeInside","rightEyeOutside"]};var AT=224,V3e,U3e=5,t1=[8,16,32,32,32];async function xT(){let e=[],t=0;for(;t<U3e;){let r=0,n=t;for(;n<t1.length&&t1[n]===t1[t];)r+=2,n++;let a=t1[t],s=Math.ceil(AT/a),i=Math.ceil(AT/a);for(let o=0;o<s;++o)for(let l=0;l<i;++l)for(let u=0;u<r;++u)e.push({x:(l+.5)/i,y:(o+.5)/s});t=n}V3e={x:Nt(e.map(r=>r.x)),y:Nt(e.map(r=>r.y))}}function us(e,t=[1,1]){let r=[e.map(o=>o[0]),e.map(o=>o[1])],n=[Math.min(...r[0]),Math.min(...r[1])],a=[Math.max(...r[0]),Math.max(...r[1])],s=[n[0],n[1],a[0]-n[0],a[1]-n[1]],i=[s[0]/t[0],s[1]/t[1],s[2]/t[0],s[3]/t[1]];return{box:s,boxRaw:i}}function bT(e,t=[1,1]){let r=[e.map(u=>u[0]),e.map(u=>u[1])],n=[Math.min(...r[0]),Math.min(...r[1])],a=[Math.max(...r[0]),Math.max(...r[1])],s=[(n[0]+a[0])/2,(n[1]+a[1])/2],i=Math.max(s[0]-n[0],s[1]-n[1],-s[0]+a[0],-s[1]+a[1]),o=[Math.trunc(s[0]-i),Math.trunc(s[1]-i),Math.trunc(2*i),Math.trunc(2*i)],l=[o[0]/t[0],o[1]/t[1],o[2]/t[0],o[3]/t[1]];return{box:o,boxRaw:l}}function r1(e,t){let r=[e[2]*t,e[3]*t];return[e[0]-(r[0]-e[2])/2,e[1]-(r[1]-e[3])/2,r[0],r[1]]}var kT={initial:!0},An={detector:null,landmarks:null},Hd={detector:[224,224],landmarks:[256,256]},mx=Number.MAX_SAFE_INTEGER,j3e={landmarks:["ld_3d","activation_segmentation","activation_heatmap","world_3d","output_poseflag"],detector:[]},a1=null,oc,Yi=[[0,0],[0,0],[0,0],[0,0]],vT=0,wT=e=>1-1/(1+Math.exp(e));async function IT(e){if(kT.initial&&(An.detector=null),!An.detector&&e.body.detector&&e.body.detector.modelPath){An.detector=await Ge(e.body.detector.modelPath);let t=Object.values(An.detector.modelSignature.inputs);Hd.detector[0]=Array.isArray(t)?parseInt(t[0].tensorShape.dim[1].size):0,Hd.detector[1]=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}else e.debug&&An.detector&&se("cached model:",An.detector.modelUrl);return await xT(),An.detector}async function ST(e){if(kT.initial&&(An.landmarks=null),An.landmarks)e.debug&&se("cached model:",An.landmarks.modelUrl);else{An.landmarks=await Ge(e.body.modelPath);let t=Object.values(An.landmarks.modelSignature.inputs);Hd.landmarks[0]=Array.isArray(t)?parseInt(t[0].tensorShape.dim[1].size):0,Hd.landmarks[1]=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}return An.landmarks}async function H3e(e,t){let r={};if(!e.shape||!e.shape[1]||!e.shape[2])return e;let n;if(oc&&(r.cropped=Ie.cropAndResize(e,[oc],[0],[e.shape[1],e.shape[2]])),e.shape[1]!==e.shape[2]){let a=[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],s=[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];Yi=[[0,0],a,s,[0,0]],r.pad=Xn(r.cropped||e,Yi),r.resize=Ie.resizeBilinear(r.pad,[t,t]),n=pe(r.resize,Qe.tf255)}else e.shape[1]!==t?(r.resize=Ie.resizeBilinear(r.cropped||e,[t,t]),n=pe(r.resize,Qe.tf255)):n=pe(r.cropped||e,Qe.tf255);return Object.keys(r).forEach(a=>ee(r[a])),n}function q3e(e,t){for(let r of e)r.position=[Math.trunc(r.position[0]*(t[0]+Yi[2][0]+Yi[2][1])/t[0]-Yi[2][0]),Math.trunc(r.position[1]*(t[1]+Yi[1][0]+Yi[1][1])/t[1]-Yi[1][0]),r.position[2]],r.positionRaw=[r.position[0]/t[0],r.position[1]/t[1],2*r.position[2]/(t[0]+t[1])];if(oc)for(let r of e)r.positionRaw=[r.positionRaw[0]+oc[1],r.positionRaw[1]+oc[0],r.positionRaw[2]],r.position=[Math.trunc(r.positionRaw[0]*t[0]),Math.trunc(r.positionRaw[1]*t[1]),r.positionRaw[2]];return e}async function X3e(e){let t=e.find(o=>o.part==="leftPalm"),r=e.find(o=>o.part==="leftWrist"),n=e.find(o=>o.part==="leftIndex");t.position[2]=((r.position[2]||0)+(n.position[2]||0))/2;let a=e.find(o=>o.part==="rightPalm"),s=e.find(o=>o.part==="rightWrist"),i=e.find(o=>o.part==="rightIndex");a.position[2]=((s.position[2]||0)+(i.position[2]||0))/2}async function K3e(e,t,r){var m;let n={};[n.ld,n.segmentation,n.heatmap,n.world,n.poseflag]=(m=An.landmarks)==null?void 0:m.execute(e,j3e.landmarks);let a=(await n.poseflag.data())[0],s=await n.ld.data(),i=await n.world.data();Object.keys(n).forEach(f=>ee(n[f]));let o=[],l=5;for(let f=0;f<s.length/l;f++){let g=wT(s[l*f+3]),y=wT(s[l*f+4]),A=Math.trunc(100*g*y*a)/100,x=[s[l*f+0]/Hd.landmarks[0],s[l*f+1]/Hd.landmarks[1],s[l*f+2]+0],b=[Math.trunc(r[0]*x[0]),Math.trunc(r[1]*x[1]),x[2]],w=[i[l*f+0],i[l*f+1],i[l*f+2]+0];o.push({part:cx[f],positionRaw:x,position:b,distance:w,score:A})}if(a<(t.body.minConfidence||0))return null;X3e(o);let u=q3e(o,r),d=u.map(f=>f.position),h=us(d,[r[0],r[1]]),p={};for(let[f,g]of Object.entries(fx)){let y=[];for(let A=0;A<g.length-1;A++){let x=u.find(w=>w.part===g[A]),b=u.find(w=>w.part===g[A+1]);x&&b&&y.push([x.position,b.position])}p[f]=y}return{id:0,score:Math.trunc(100*a)/100,box:h.box,boxRaw:h.boxRaw,keypoints:u,annotations:p}}async function gx(e,t){let r=[e.shape[2]||0,e.shape[1]||0],n=(t.body.skipTime||0)>oe()-vT,a=mx<(t.body.skipFrames||0);if(t.skipAllowed&&n&&a&&a1!==null)mx++;else{let s={};s.landmarks=await H3e(e,256),a1=await K3e(s.landmarks,t,r),Object.keys(s).forEach(i=>ee(s[i])),vT=oe(),mx=0}return a1?[a1]:[]}var qd=[{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 ds,jl=0,yx=[],TT=0,Ax=Number.MAX_SAFE_INTEGER;async function NT(e){if(he.initial&&(ds=null),ds)e.debug&&se("cached model:",ds.modelUrl);else{ds=await Ge(e.object.modelPath);let t=Object.values(ds.modelSignature.inputs);jl=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}return ds}async function Z3e(e,t,r){if(!e)return[];let n={},a=[],s=await e.array();n.squeeze=et(e);let i=Yt(n.squeeze,6,1);n.stack=ur([i[1],i[0],i[3],i[2]],1),n.boxes=et(n.stack),n.scores=et(i[4]),n.classes=et(i[5]),ee([e,...i]),n.nms=await Ie.nonMaxSuppressionAsync(n.boxes,n.scores,r.object.maxDetected,r.object.iouThreshold,r.object.minConfidence||0);let o=await n.nms.data(),l=0;for(let u of Array.from(o)){let d=Math.trunc(100*s[0][u][4])/100,h=s[0][u][5],p=qd[h].label,[c,m]=[s[0][u][0]/jl,s[0][u][1]/jl],f=[c,m,s[0][u][2]/jl-c,s[0][u][3]/jl-m],g=[Math.trunc(f[0]*t[0]),Math.trunc(f[1]*t[1]),Math.trunc(f[2]*t[0]),Math.trunc(f[3]*t[1])];a.push({id:l++,score:d,class:h,label:p,box:g,boxRaw:f})}return Object.keys(n).forEach(u=>ee(n[u])),a}async function xx(e,t){let r=(t.object.skipTime||0)>oe()-TT,n=Ax<(t.object.skipFrames||0);return t.skipAllowed&&r&&n&&yx.length>0?(Ax++,yx):(Ax=0,new Promise(async a=>{let s=[e.shape[2]||0,e.shape[1]||0],i=Ie.resizeBilinear(e,[jl,jl]),o=t.object.enabled?ds==null?void 0:ds.execute(i,["tower_0/detections"]):null;TT=oe(),ee(i);let l=await Z3e(o,s,t);yx=l,a(l)}))}var s1={};ws(s1,{connected:()=>vx,kpt:()=>bx});var bx=["head","neck","rightShoulder","rightElbow","rightWrist","chest","leftShoulder","leftElbow","leftWrist","bodyCenter","rightHip","rightKnee","rightAnkle","leftHip","leftKnee","leftAnkle"],vx={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var $r,RT=0,Yr={id:0,keypoints:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,annotations:{}},wx=Number.MAX_SAFE_INTEGER;async function $T(e){return he.initial&&($r=null),$r?e.debug&&se("cached model:",$r.modelUrl):$r=await Ge(e.body.modelPath),$r}async function Y3e(e,t){let[r,n]=e.shape,a=U(e,[n*r]),s=yr(a,0),i=(await s.data())[0];if(ee([a,s]),i>t){let o=$n(a,0),l=kd(o,r),u=(await l.data())[0],d=pe(o,Se(r,"int32")),h=(await d.data())[0];return ee([l,d]),[u,h,i]}return[0,0,i]}async function kx(e,t){let r=(t.body.skipTime||0)>oe()-RT,n=wx<(t.body.skipFrames||0);return t.skipAllowed&&r&&n&&Object.keys(Yr.keypoints).length>0?(wx++,[Yr]):(wx=0,new Promise(async a=>{var h;let s=X(()=>{if(!($r!=null&&$r.inputs[0].shape))return null;let p=Ie.resizeBilinear(e,[$r.inputs[0].shape[2],$r.inputs[0].shape[1]],!1),c=L(p,Qe.tf2);return ce(c,Qe.tf1)}),i;if(t.body.enabled&&(i=$r==null?void 0:$r.execute(s)),RT=oe(),ee(s),i){Yr.keypoints.length=0;let p=i.squeeze();ee(i);let c=p.unstack(2);ee(p);for(let m=0;m<c.length;m++){let[f,g,y]=await Y3e(c[m],t.body.minConfidence);y>(((h=t.body)==null?void 0:h.minConfidence)||0)&&Yr.keypoints.push({score:Math.round(100*y)/100,part:bx[m],positionRaw:[f/$r.inputs[0].shape[2],g/$r.inputs[0].shape[1]],position:[Math.round(e.shape[2]*f/$r.inputs[0].shape[2]),Math.round(e.shape[1]*g/$r.inputs[0].shape[1])]})}c.forEach(m=>ee(m))}Yr.score=Yr.keypoints.reduce((p,c)=>c.score>p?c.score:p,0);let o=Yr.keypoints.map(p=>p.position[0]),l=Yr.keypoints.map(p=>p.position[1]);Yr.box=[Math.min(...o),Math.min(...l),Math.max(...o)-Math.min(...o),Math.max(...l)-Math.min(...l)];let u=Yr.keypoints.map(p=>p.positionRaw[0]),d=Yr.keypoints.map(p=>p.positionRaw[1]);Yr.boxRaw=[Math.min(...u),Math.min(...d),Math.max(...u)-Math.min(...u),Math.max(...d)-Math.min(...d)];for(let[p,c]of Object.entries(vx)){let m=[];for(let f=0;f<c.length-1;f++){let g=Yr.keypoints.find(A=>A.part===c[f]),y=Yr.keypoints.find(A=>A.part===c[f+1]);g&&y&&g.score>(t.body.minConfidence||0)&&y.score>(t.body.minConfidence||0)&&m.push([g.position,y.position])}Yr.annotations[p]=m}a([Yr])}))}var J3e=["angry","disgust","fear","happy","sad","surprise","neutral"],Wn,i1=[],FT=0,_T=0,Ix=Number.MAX_SAFE_INTEGER;async function PT(e){var t;return he.initial&&(Wn=null),Wn?e.debug&&se("cached model:",Wn.modelUrl):Wn=await Ge((t=e.face.emotion)==null?void 0:t.modelPath),Wn}async function Sx(e,t,r,n){var i,o;if(!Wn)return[];let a=Ix<(((i=t.face.emotion)==null?void 0:i.skipFrames)||0),s=(((o=t.face.emotion)==null?void 0:o.skipTime)||0)>oe()-_T;return t.skipAllowed&&s&&a&&FT===n&&i1[r]&&i1[r].length>0?(Ix++,i1[r]):(Ix=0,new Promise(async l=>{var d,h;let u=[];if((d=t.face.emotion)!=null&&d.enabled){let p={},c=Wn!=null&&Wn.inputs[0].shape?Wn.inputs[0].shape[2]:0;p.resize=Ie.resizeBilinear(e,[c,c],!1),p.channels=L(p.resize,Qe.rgb),p.grayscale=ke(p.channels,3,!0),p.grayscaleSub=ce(p.grayscale,Qe.tf05),p.grayscaleMul=L(p.grayscaleSub,Qe.tf2),p.emotion=Wn==null?void 0:Wn.execute(p.grayscaleMul),_T=oe();let m=await p.emotion.data();for(let f=0;f<m.length;f++)m[f]>(((h=t.face.emotion)==null?void 0:h.minConfidence)||0)&&u.push({score:Math.min(.99,Math.trunc(100*m[f])/100),emotion:J3e[f]});u.sort((f,g)=>g.score-f.score),Object.keys(p).forEach(f=>ee(p[f]))}i1[r]=u,FT=n,l(u)}))}var xn,Cx=[],zT=0,DT=0,LT=Number.MAX_SAFE_INTEGER;async function BT(e){return he.initial&&(xn=null),xn?e.debug&&se("cached model:",xn.modelUrl):xn=await Ge(e.face.mobilefacenet.modelPath),xn}async function Tx(e,t,r,n){var i,o;if(!xn)return[];let a=LT<(((i=t.face.embedding)==null?void 0:i.skipFrames)||0),s=(((o=t.face.embedding)==null?void 0:o.skipTime)||0)>oe()-DT;return t.skipAllowed&&s&&a&&zT===n&&Cx[r]?(LT++,Cx[r]):new Promise(async l=>{var d;let u=[];if(((d=t.face.embedding)==null?void 0:d.enabled)&&(xn==null?void 0:xn.inputs[0].shape)){let h={};h.crop=Ie.resizeBilinear(e,[xn.inputs[0].shape[2],xn.inputs[0].shape[1]],!1),h.data=xn==null?void 0:xn.execute(h.crop);let p=await h.data.data();u=Array.from(p)}Cx[r]=u,zT=n,DT=oe(),l(u)})}var ps,Ji=0,Q3e=2.3,Nx=ea.leftEyeLower0,Ex=ea.rightEyeLower0,Xd={leftBounds:[Nx[0],Nx[Nx.length-1]],rightBounds:[Ex[0],Ex[Ex.length-1]]},Kd={upperCenter:3,lowerCenter:4,index:71,numCoordinates:76};async function jT(e){var t;return he.initial&&(ps=null),ps?e.debug&&se("cached model:",ps.modelUrl):ps=await Ge((t=e.face.iris)==null?void 0:t.modelPath),Ji=ps.inputs[0].shape?ps.inputs[0].shape[2]:0,Ji===-1&&(Ji=64),ps}function o1(e,t,r,n){for(let a=0;a<lx.length;a++){let{key:s,indices:i}=lx[a],o=ea[`${r}${s}`];if(!n||n.includes(s))for(let l=0;l<i.length;l++){let u=i[l];e[o[l]]=[t[u][0],t[u][1],(t[u][2]+e[o[l]][2])/2]}}}var e5e=e=>{let t=e[Xd.leftBounds[0]][2],r=e[Xd.rightBounds[0]][2];return t-r},VT=(e,t,r,n,a,s=!1)=>{let i=Qm(Jm(oT([e[r],e[n]]),Q3e)),o=Gd(i),l=Ie.cropAndResize(t,[[i.startPoint[1]/a,i.startPoint[0]/a,i.endPoint[1]/a,i.endPoint[0]/a]],[0],[Ji,Ji]);if(s&&he.kernels.includes("flipleftright")){let u=Ie.flipLeftRight(l);ee(l),l=u}return{box:i,boxSize:o,crop:l}},UT=(e,t,r,n=!1)=>{let a=[];for(let s=0;s<Kd.numCoordinates;s++){let i=e[s*3],o=e[s*3+1],l=e[s*3+2];a.push([(n?1-i/Ji:i/Ji)*r[0]+t.startPoint[0],o/Ji*r[1]+t.startPoint[1],l])}return{rawCoords:a,iris:a.slice(Kd.index)}},GT=(e,t,r)=>{let n=e[ea[`${r}EyeUpper0`][Kd.upperCenter]][2],a=e[ea[`${r}EyeLower0`][Kd.lowerCenter]][2],s=(n+a)/2;return t.map((i,o)=>{let l=s;return o===2?l=n:o===4&&(l=a),[i[0],i[1],l]})};async function HT(e,t,r,n){if(!ps)return r.debug&&se("face mesh iris detection requested, but model is not loaded"),e;let{box:a,boxSize:s,crop:i}=VT(e,t,Xd.leftBounds[0],Xd.leftBounds[1],n,!0),{box:o,boxSize:l,crop:u}=VT(e,t,Xd.rightBounds[0],Xd.rightBounds[1],n,!0),d=St([i,u]);ee(i),ee(u);let h=ps.execute(d);ee(d);let p=await h.data();ee(h);let c=p.slice(0,Kd.numCoordinates*3),{rawCoords:m,iris:f}=UT(c,a,s,!0),g=p.slice(Kd.numCoordinates*3),{rawCoords:y,iris:A}=UT(g,o,l,!1),x=e5e(e);Math.abs(x)<30?(o1(e,m,"left",null),o1(e,y,"right",null)):x<1?o1(e,m,"left",["EyeUpper0","EyeLower0"]):o1(e,y,"right",["EyeUpper0","EyeLower0"]);let b=GT(e,f,"left"),w=GT(e,A,"right");return e.concat(b).concat(w)}var t5e=[[61,146],[146,91],[91,181],[181,84],[84,17],[17,314],[314,405],[405,321],[321,375],[375,291],[61,185],[185,40],[40,39],[39,37],[37,0],[0,267],[267,269],[269,270],[270,409],[409,291],[78,95],[95,88],[88,178],[178,87],[87,14],[14,317],[317,402],[402,318],[318,324],[324,308],[78,191],[191,80],[80,81],[81,82],[82,13],[13,312],[312,311],[311,310],[310,415],[415,308]],r5e=[[263,249],[249,390],[390,373],[373,374],[374,380],[380,381],[381,382],[382,362],[263,466],[466,388],[388,387],[387,386],[386,385],[385,384],[384,398],[398,362]],n5e=[[276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]],a5e=[[474,475],[475,476],[476,477],[477,474]],s5e=[[33,7],[7,163],[163,144],[144,145],[145,153],[153,154],[154,155],[155,133],[33,246],[246,161],[161,160],[160,159],[159,158],[158,157],[157,173],[173,133]],i5e=[[46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]],o5e=[[469,470],[470,471],[471,472],[472,469]],l5e=[[10,338],[338,297],[297,332],[332,284],[284,251],[251,389],[389,356],[356,454],[454,323],[323,361],[361,288],[288,397],[397,365],[365,379],[379,378],[378,400],[400,377],[377,152],[152,148],[148,176],[176,149],[149,150],[150,136],[136,172],[172,58],[58,132],[132,93],[93,234],[234,127],[127,162],[162,21],[21,54],[54,103],[103,67],[67,109],[109,10]];function Qi(e){let t=e.map(r=>r[0]);return t.push(e[e.length-1][1]),t}var u5e={lips:Qi(t5e),leftEye:Qi(r5e),leftEyebrow:Qi(n5e),leftIris:Qi(a5e),rightEye:Qi(s5e),rightEyebrow:Qi(i5e),rightIris:Qi(o5e),faceOval:Qi(l5e)},d5e=Object.entries(u5e).map(([e,t])=>t.map(r=>[r,e])).flat(),s8e=new Map(d5e),lc=[61,146,91,181,84,17,314,405,321,375,291,185,40,39,37,0,267,269,270,409,78,95,88,178,87,14,317,402,318,324,308,191,80,81,82,13,312,311,310,415,76,77,90,180,85,16,315,404,320,307,306,184,74,73,72,11,302,303,304,408,62,96,89,179,86,15,316,403,319,325,292,183,42,41,38,12,268,271,272,407],Hl=[33,7,163,144,145,153,154,155,133,246,161,160,159,158,157,173,130,25,110,24,23,22,26,112,243,247,30,29,27,28,56,190,226,31,228,229,230,231,232,233,244,113,225,224,223,222,221,189,35,124,46,53,52,65,143,111,117,118,119,120,121,128,245,156,70,63,105,66,107,55,193],ql=[263,249,390,373,374,380,381,382,362,466,388,387,386,385,384,398,359,255,339,254,253,252,256,341,463,467,260,259,257,258,286,414,446,261,448,449,450,451,452,453,464,342,445,444,443,442,441,413,265,353,276,283,282,295,372,340,346,347,348,349,350,357,465,383,300,293,334,296,336,285,417];async function KT(e,t){let r={lips:await t.filter(s=>s.size===160)[0].data(),irisL:await t.filter(s=>s.size===10)[0].data(),eyeL:await t.filter(s=>s.size===142)[0].data(),irisR:await t.filter(s=>s.size===10)[1].data(),eyeR:await t.filter(s=>s.size===142)[1].data()},n=Hl.reduce((s,i)=>s+=e[i][2],0)/Hl.length;for(let s=0;s<r.irisL.length/2;s++)e.push([r.irisL[2*s+0],r.irisL[2*s+1],n]);let a=ql.reduce((s,i)=>s+=e[i][2],0)/ql.length;for(let s=0;s<r.irisR.length/2;s++)e.push([r.irisR[2*s+0],r.irisR[2*s+1],a]);for(let s=0;s<r.eyeL.length/2;s++)e[Hl[s]]=[r.eyeL[2*s+0],r.eyeL[2*s+1],e[Hl[s]][2]];for(let s=0;s<r.eyeR.length/2;s++)e[ql[s]]=[r.eyeR[2*s+0],r.eyeR[2*s+1],e[ql[s]][2]];for(let s=0;s<r.lips.length/2;s++)e[lc[s]]=[r.lips[2*s+0],r.lips[2*s+1],e[lc[s]][2]];return e}var Wa={boxes:[],skipped:Number.MAX_SAFE_INTEGER,timestamp:0},Mr=null,Xl=0;async function ZT(e,t){var o,l,u,d,h,p,c,m,f,g,y;let r=(((o=t.face.detector)==null?void 0:o.skipTime)||0)>oe()-Wa.timestamp,n=Wa.skipped<(((l=t.face.detector)==null?void 0:l.skipFrames)||0);!t.skipAllowed||!r||!n||Wa.boxes.length===0?(Wa.boxes=await gT(e,t),Wa.timestamp=oe(),Wa.skipped=0):Wa.skipped++;let a=[],s=[],i=0;for(let A=0;A<Wa.boxes.length;A++){let x=Wa.boxes[A],b=0,w,I={id:i++,mesh:[],meshRaw:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,boxScore:0,faceScore:0,annotations:{}};if([b,w,I.tensor]=pT((u=t.face.detector)==null?void 0:u.rotation,x,e,(d=t.face.mesh)!=null&&d.enabled?Xl:jd()),(h=t==null?void 0:t.filter)!=null&&h.equalization){let T=await Um(I.tensor);ee(I.tensor),I.tensor=T}if(I.boxScore=Math.round(100*x.confidence)/100,(p=t.face.mesh)!=null&&p.enabled)if(!Mr)t.debug&&se("face mesh detection requested, but model is not loaded");else{let T=Mr.execute(I.tensor),R=await T.find(F=>F.shape[F.shape.length-1]===1).data();if(I.faceScore=Math.round(100*R[0])/100,I.faceScore<(((c=t.face.detector)==null?void 0:c.minConfidence)||1)){if(x.confidence=I.faceScore,(m=t.face.mesh)!=null&&m.keepInvalid){I.box=Zm(x,e),I.boxRaw=Ym(x,e),I.score=I.boxScore,I.mesh=x.landmarks.map(F=>[(x.startPoint[0]+x.endPoint[0])/2+(x.endPoint[0]+x.startPoint[0])*F[0]/jd(),(x.startPoint[1]+x.endPoint[1])/2+(x.endPoint[1]+x.startPoint[1])*F[1]/jd()]),I.meshRaw=I.mesh.map(F=>[F[0]/(e.shape[2]||0),F[1]/(e.shape[1]||0),(F[2]||0)/Xl]);for(let F of Object.keys(Vl))I.annotations[F]=[I.mesh[Vl[F]]]}}else{let F=T.find(O=>O.shape[O.shape.length-1]===1404),$=U(F,[-1,3]),S=await $.array();ee($),(f=t.face.attention)!=null&&f.enabled?S=await KT(S,T):(g=t.face.iris)!=null&&g.enabled&&(S=await HT(S,I.tensor,t,Xl)),I.mesh=dT(S,x,b,w,Xl),I.meshRaw=I.mesh.map(O=>[O[0]/(e.shape[2]||0),O[1]/(e.shape[1]||0),(O[2]||0)/Xl]);for(let O of Object.keys(ea))I.annotations[O]=ea[O].map(j=>I.mesh[j]);I.score=I.faceScore;let z={...hT(I.mesh,x),confidence:x.confidence,landmarks:x.landmarks};I.box=Zm(z,e),I.boxRaw=Ym(z,e),s.push(z)}ee(T)}else{I.box=Zm(x,e),I.boxRaw=Ym(x,e),I.score=I.boxScore,I.mesh=x.landmarks.map(T=>[(x.startPoint[0]+x.endPoint[0])/2+(x.endPoint[0]+x.startPoint[0])*T[0]/jd(),(x.startPoint[1]+x.endPoint[1])/2+(x.endPoint[1]+x.startPoint[1])*T[1]/jd()]),I.meshRaw=I.mesh.map(T=>[T[0]/(e.shape[2]||0),T[1]/(e.shape[1]||0),(T[2]||0)/Xl]);for(let T of Object.keys(Vl))I.annotations[T]=[I.mesh[Vl[T]]]}I.score>(((y=t.face.detector)==null?void 0:y.minConfidence)||1)?a.push(I):ee(I.tensor)}return Wa.boxes=s,a}async function YT(e){var t,r,n,a,s,i;return he.initial&&(Mr=null),((r=(t=e==null?void 0:e.face)==null?void 0:t.attention)==null?void 0:r.enabled)&&(Mr==null?void 0:Mr.signature)&&Object.keys(((n=Mr==null?void 0:Mr.signature)==null?void 0:n.outputs)||{}).length<6&&(Mr=null),Mr?e.debug&&se("cached model:",Mr.modelUrl):(a=e.face.attention)!=null&&a.enabled?Mr=await Ge((s=e.face.attention)==null?void 0:s.modelPath):Mr=await Ge((i=e.face.mesh)==null?void 0:i.modelPath),Xl=Mr.inputs[0].shape?Mr.inputs[0].shape[2]:0,Mr}var JT=Ul,QT=sc;var bn,l1=[],eN=0,tN=0,$x=Number.MAX_SAFE_INTEGER;async function rN(e){var t;return he.initial&&(bn=null),bn?e.debug&&se("cached model:",bn.modelUrl):bn=await Ge((t=e.face.description)==null?void 0:t.modelPath),bn}function Mx(e){let t=e.image||e.tensor||e;if(!(bn!=null&&bn.inputs[0].shape))return t;let r=Ie.resizeBilinear(t,[bn.inputs[0].shape[2],bn.inputs[0].shape[1]],!1),n=L(r,Qe.tf255);return ee(r),n}async function Fx(e,t,r,n){var i,o,l,u;if(!bn)return{age:0,gender:"unknown",genderScore:0,descriptor:[]};let a=$x<(((i=t.face.description)==null?void 0:i.skipFrames)||0),s=(((o=t.face.description)==null?void 0:o.skipTime)||0)>oe()-eN;return t.skipAllowed&&a&&s&&tN===n&&((l=l1[r])==null?void 0:l.age)&&((u=l1[r])==null?void 0:u.age)>0?($x++,l1[r]):($x=0,new Promise(async d=>{var p,c;let h={age:0,gender:"unknown",genderScore:0,descriptor:[]};if((p=t.face.description)!=null&&p.enabled){let m=Mx(e),f=bn==null?void 0:bn.execute(m);eN=oe(),ee(m);let y=await(await f.find(R=>R.shape[1]===1)).data(),A=Math.trunc(200*Math.abs(y[0]-.5))/100;A>(((c=t.face.description)==null?void 0:c.minConfidence)||0)&&(h.gender=y[0]<=.5?"female":"male",h.genderScore=Math.min(.99,A));let x=$n(f.find(R=>R.shape[1]===100),1),b=(await x.data())[0];ee(x);let I=await f.find(R=>R.shape[1]===100).data();h.age=Math.round(I[b-1]>I[b+1]?10*b-100*I[b-1]:10*b+100*I[b+1])/10;let T=f.find(R=>R.shape[1]===1024),E=T?await T.data():[];h.descriptor=Array.from(E),f.forEach(R=>ee(R))}l1[r]=h,tN=n,d(h)}))}function u1(e){return[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])]}function uc(e){return[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2]}function sN(e,t,r){let n=t.shape[1],a=t.shape[2],s=[[e.startPoint[1]/n,e.startPoint[0]/a,e.endPoint[1]/n,e.endPoint[0]/a]];return Ie.cropAndResize(t,s,[0],r)}function iN(e,t){let r=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],n=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]],a=e.palmLandmarks.map(s=>[s[0]*t[0],s[1]*t[1]]);return{startPoint:r,endPoint:n,palmLandmarks:a,confidence:e.confidence}}function d1(e,t=1.5){let r=uc(e),n=u1(e),a=[t*n[0]/2,t*n[1]/2],s=[r[0]-a[0],r[1]-a[1]],i=[r[0]+a[0],r[1]+a[1]];return{startPoint:s,endPoint:i,palmLandmarks:e.palmLandmarks}}function p1(e){let t=uc(e),r=u1(e),a=Math.max(...r)/2,s=[t[0]-a,t[1]-a],i=[t[0]+a,t[1]+a];return{startPoint:s,endPoint:i,palmLandmarks:e.palmLandmarks}}function h5e(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function oN(e,t){let r=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]);return h5e(r)}var nN=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]];function eo(e,t){let r=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n];return r}function c5e(e,t){let r=[];for(let n=0;n<e.length;n++)r.push(e[n][t]);return r}function aN(e,t){let r=[],n=e.length;for(let a=0;a<n;a++){r.push([]);for(let s=0;s<n;s++)r[a].push(eo(e[a],c5e(t,s)))}return r}function Px(e,t){let r=Math.cos(e),n=Math.sin(e),a=[[r,-n,0],[n,r,0],[0,0,1]],s=nN(t[0],t[1]),i=aN(s,a),o=nN(-t[0],-t[1]);return aN(i,o)}function lN(e){let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],r=[e[0][2],e[1][2]],n=[-eo(t[0],r),-eo(t[1],r)];return[t[0].concat(n[0]),t[1].concat(n[1]),[0,0,1]]}function Ox(e,t){return[eo(e,t[0]),eo(e,t[1])]}var dN=[{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 h1=class{constructor(t){fe(this,"model");fe(this,"anchors");fe(this,"anchorsTensor");fe(this,"inputSize");fe(this,"inputSizeTensor");fe(this,"doubleInputSizeTensor");this.model=t,this.anchors=dN.map(r=>[r.x,r.y]),this.anchorsTensor=ca(this.anchors),this.inputSize=this.model&&this.model.inputs&&this.model.inputs[0].shape?this.model.inputs[0].shape[2]:0,this.inputSizeTensor=Nt([this.inputSize,this.inputSize]),this.doubleInputSizeTensor=Nt([this.inputSize*2,this.inputSize*2])}normalizeBoxes(t){let r={};r.boxOffsets=_e(t,[0,0],[-1,2]),r.boxSizes=_e(t,[0,2],[-1,2]),r.div=pe(r.boxOffsets,this.inputSizeTensor),r.boxCenterPoints=le(r.div,this.anchorsTensor),r.halfBoxSizes=pe(r.boxSizes,this.doubleInputSizeTensor),r.sub=ce(r.boxCenterPoints,r.halfBoxSizes),r.startPoints=L(r.sub,this.inputSizeTensor),r.add=le(r.boxCenterPoints,r.halfBoxSizes),r.endPoints=L(r.add,this.inputSizeTensor);let n=bd([r.startPoints,r.endPoints],1);return Object.keys(r).forEach(a=>ee(r[a])),n}normalizeLandmarks(t,r){let n={};n.reshape=U(t,[-1,7,2]),n.div=pe(n.reshape,this.inputSizeTensor),n.landmarks=le(n.div,this.anchors[r]);let a=L(n.landmarks,this.inputSizeTensor);return Object.keys(n).forEach(s=>ee(n[s])),a}async predict(t,r){let n={};n.resize=Ie.resizeBilinear(t,[this.inputSize,this.inputSize]),n.div=pe(n.resize,Qe.tf127),n.image=ce(n.div,Qe.tf1),n.batched=this.model.execute(n.image),n.predictions=et(n.batched),n.slice=_e(n.predictions,[0,0],[-1,1]),n.sigmoid=Tr(n.slice),n.scores=et(n.sigmoid);let a=await n.scores.data();n.boxes=_e(n.predictions,[0,1],[-1,4]),n.norm=this.normalizeBoxes(n.boxes),n.nms=await Ie.nonMaxSuppressionAsync(n.norm,n.scores,3*r.hand.maxDetected,r.hand.iouThreshold,r.hand.minConfidence);let s=await n.nms.array(),i=[];for(let o of s){let l={};l.box=_e(n.norm,[o,0],[1,-1]),l.slice=_e(n.predictions,[o,5],[1,14]),l.norm=this.normalizeLandmarks(l.slice,o),l.palmLandmarks=U(l.norm,[-1,2]);let u=await l.box.data(),d=u.slice(0,2),h=u.slice(2,4),p=await l.palmLandmarks.array(),c={startPoint:d,endPoint:h,palmLandmarks:p,confidence:a[o]},m=iN(c,[t.shape[2]/this.inputSize,t.shape[1]/this.inputSize]);i.push(m),Object.keys(l).forEach(f=>ee(l[f]))}return Object.keys(n).forEach(o=>ee(n[o])),i}};var g5e=5,pN=1.65,hN=[0,5,9,13,17,1,2],y5e=0,A5e=2,cN=0,c1=class{constructor(t,r){fe(this,"handDetector");fe(this,"handPoseModel");fe(this,"inputSize");fe(this,"storedBoxes");fe(this,"skipped");fe(this,"detectedHands");this.handDetector=t,this.handPoseModel=r,this.inputSize=this.handPoseModel&&this.handPoseModel.inputs[0].shape?this.handPoseModel.inputs[0].shape[2]:0,this.storedBoxes=[],this.skipped=Number.MAX_SAFE_INTEGER,this.detectedHands=0}calculateLandmarksBoundingBox(t){let r=t.map(i=>i[0]),n=t.map(i=>i[1]),a=[Math.min(...r),Math.min(...n)],s=[Math.max(...r),Math.max(...n)];return{startPoint:a,endPoint:s}}getBoxForPalmLandmarks(t,r){let n=t.map(s=>Ox([...s,1],r)),a=this.calculateLandmarksBoundingBox(n);return d1(p1(a),g5e)}getBoxForHandLandmarks(t){let r=this.calculateLandmarksBoundingBox(t),n=d1(p1(r),pN);n.palmLandmarks=[];for(let a=0;a<hN.length;a++)n.palmLandmarks.push(t[hN[a]].slice(0,2));return n}transformRawCoords(t,r,n,a){let s=u1(r),i=[s[0]/this.inputSize,s[1]/this.inputSize,(s[0]+s[1])/this.inputSize/2],o=t.map(c=>[i[0]*(c[0]-this.inputSize/2),i[1]*(c[1]-this.inputSize/2),i[2]*c[2]]),l=Px(n,[0,0]),u=o.map(c=>[...Ox(c,l),c[2]]),d=lN(a),h=[...uc(r),1],p=[eo(h,d[0]),eo(h,d[1])];return u.map(c=>[Math.trunc(c[0]+p[0]),Math.trunc(c[1]+p[1]),Math.trunc(c[2])])}async estimateHands(t,r){let n=!1,a,s=(r.hand.skipTime||0)>oe()-cN,i=this.skipped<(r.hand.skipFrames||0);r.skipAllowed&&s&&i&&(a=await this.handDetector.predict(t,r),this.skipped=0),r.skipAllowed&&this.skipped++,a&&a.length>0&&(a.length!==this.detectedHands&&this.detectedHands!==r.hand.maxDetected||!r.hand.landmarks)&&(this.detectedHands=0,this.storedBoxes=[...a],this.storedBoxes.length>0&&(n=!0));let o=[];for(let l=0;l<this.storedBoxes.length;l++){let u=this.storedBoxes[l];if(!!u)if(r.hand.landmarks){let d=r.hand.rotation?oN(u.palmLandmarks[y5e],u.palmLandmarks[A5e]):0,h=uc(u),p=[h[0]/t.shape[2],h[1]/t.shape[1]],c=r.hand.rotation&&he.kernels.includes("rotatewithoffset")?Ie.rotateWithOffset(t,d,0,p):t.clone(),m=Px(-d,h),f=n?this.getBoxForPalmLandmarks(u.palmLandmarks,m):u,g=sN(f,c,[this.inputSize,this.inputSize]),y=pe(g,Qe.tf255);ee(g),ee(c);let[A,x]=this.handPoseModel.execute(y);cN=oe(),ee(y);let b=(await A.data())[0];if(ee(A),b>=r.hand.minConfidence/4){let w=U(x,[-1,3]),I=await w.array();ee(x),ee(w);let T=this.transformRawCoords(I,f,d,m),E=this.getBoxForHandLandmarks(T);this.storedBoxes[l]={...E,confidence:b};let R={landmarks:T,confidence:b,boxConfidence:u.confidence,fingerConfidence:b,box:{topLeft:E.startPoint,bottomRight:E.endPoint}};o.push(R)}else this.storedBoxes[l]=null;ee(x)}else{let d=d1(p1(u),pN),h={confidence:u.confidence,boxConfidence:u.confidence,fingerConfidence:0,box:{topLeft:d.startPoint,bottomRight:d.endPoint},landmarks:[]};o.push(h)}}return this.storedBoxes=this.storedBoxes.filter(l=>l!==null),this.detectedHands=o.length,o.length>r.hand.maxDetected&&(o.length=r.hand.maxDetected),o}};var Jr={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=>Jr.nameMapping[e],getPoints:e=>Jr.pointsMapping[e]},ro={none:0,half:1,full:2,nameMapping:{0:"none",1:"half",2:"full"},getName:e=>ro.nameMapping[e]},Bt={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=>Bt.nameMapping[e]},to=class{constructor(t){fe(this,"name");fe(this,"curls");fe(this,"directions");fe(this,"weights");fe(this,"weightsRelative");this.name=t,this.curls={},this.directions={},this.weights=[1,1,1,1,1],this.weightsRelative=[1,1,1,1,1]}curl(t,r,n){typeof this.curls[t]=="undefined"&&(this.curls[t]=[]),this.curls[t].push([r,n])}direction(t,r,n){this.directions[t]||(this.directions[t]=[]),this.directions[t].push([r,n])}weight(t,r){this.weights[t]=r;let n=this.weights.reduce((a,s)=>a+s,0);this.weightsRelative=this.weights.map(a=>a*5/n)}matchAgainst(t,r){let n=0;for(let a in t){let s=t[a],i=this.curls[a];if(typeof i=="undefined"){n+=this.weightsRelative[a];continue}for(let[o,l]of i)if(s===o){n+=l*this.weightsRelative[a];break}}for(let a in r){let s=r[a],i=this.directions[a];if(typeof i=="undefined"){n+=this.weightsRelative[a];continue}for(let[o,l]of i)if(s===o){n+=l*this.weightsRelative[a];break}}return n/10}};var{thumb:wa,index:hs,middle:cs,ring:Kl,pinky:Zl}=Jr,{none:ka,half:b5e,full:Ia}=ro,{verticalUp:Zd,verticalDown:b8e,horizontalLeft:zx,horizontalRight:v5e,diagonalUpRight:w5e,diagonalUpLeft:Yd,diagonalDownRight:v8e,diagonalDownLeft:w8e}=Bt,no=new to("thumbs up");no.curl(wa,ka,1);no.direction(wa,Zd,1);no.direction(wa,Yd,.25);no.direction(wa,w5e,.25);for(let e of[Jr.index,Jr.middle,Jr.ring,Jr.pinky])no.curl(e,Ia,1),no.direction(e,zx,1),no.direction(e,v5e,1);var tr=new to("victory");tr.curl(wa,b5e,.5);tr.curl(wa,ka,.5);tr.direction(wa,Zd,1);tr.direction(wa,Yd,1);tr.curl(hs,ka,1);tr.direction(hs,Zd,.75);tr.direction(hs,Yd,1);tr.curl(cs,ka,1);tr.direction(cs,Zd,1);tr.direction(cs,Yd,.75);tr.curl(Kl,Ia,1);tr.direction(Kl,Zd,.2);tr.direction(Kl,Yd,1);tr.direction(Kl,zx,.2);tr.curl(Zl,Ia,1);tr.direction(Zl,Zd,.2);tr.direction(Zl,Yd,1);tr.direction(Zl,zx,.2);tr.weight(hs,2);tr.weight(cs,2);var ao=new to("point");ao.curl(wa,Ia,1);ao.curl(hs,ka,.5);ao.curl(cs,Ia,.5);ao.curl(Kl,Ia,.5);ao.curl(Zl,Ia,.5);ao.weight(hs,2);ao.weight(cs,2);var so=new to("middle finger");so.curl(wa,ka,1);so.curl(hs,Ia,.5);so.curl(cs,Ia,.5);so.curl(Kl,Ia,.5);so.curl(Zl,Ia,.5);so.weight(hs,2);so.weight(cs,2);var Jd=new to("open palm");Jd.curl(wa,ka,.75);Jd.curl(hs,ka,.75);Jd.curl(cs,ka,.75);Jd.curl(Kl,ka,.75);Jd.curl(Zl,ka,.75);var fN=[no,tr,ao,so,Jd];var k5e=.7,Yl={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 mN(e,t,r,n){let a=(t-n)/(e-r),s=Math.atan(a)*180/Math.PI;return s<=0?s=-s:s>0&&(s=180-s),s}function yN(e,t){if(!e||!t)return[0,0];let r=mN(e[0],e[1],t[0],t[1]);if(e.length===2)return r;let n=mN(e[1],e[2],t[1],t[2]);return[r,n]}function gN(e,t=1){let r=0,n=0,a=0;return e>=75&&e<=105?r=1*t:e>=25&&e<=155?n=1*t:a=1*t,[r,n,a]}function I5e(e,t,r){let n=e[0]-t[0],a=e[0]-r[0],s=t[0]-r[0],i=e[1]-t[1],o=e[1]-r[1],l=t[1]-r[1],u=e[2]-t[2],d=e[2]-r[2],h=t[2]-r[2],p=Math.sqrt(n*n+i*i+u*u),c=Math.sqrt(a*a+o*o+d*d),m=Math.sqrt(s*s+l*l+h*h),f=(m*m+p*p-c*c)/(2*m*p);f>1?f=1:f<-1&&(f=-1);let g=Math.acos(f);g=57.2958*g%180;let y;return g>Yl.NO_CURL_START_LIMIT?y=ro.none:g>Yl.HALF_CURL_START_LIMIT?y=ro.half:y=ro.full,y}function AN(e,t,r,n){let a;return n===Math.abs(e)?e>0?a=Bt.horizontalLeft:a=Bt.horizontalRight:n===Math.abs(t)?t>0?a=Bt.horizontalLeft:a=Bt.horizontalRight:r>0?a=Bt.horizontalLeft:a=Bt.horizontalRight,a}function xN(e,t,r,n){let a;return n===Math.abs(e)?e<0?a=Bt.verticalDown:a=Bt.verticalUp:n===Math.abs(t)?t<0?a=Bt.verticalDown:a=Bt.verticalUp:r<0?a=Bt.verticalDown:a=Bt.verticalUp,a}function S5e(e,t,r,n,a,s,i,o){let l,u=xN(e,t,r,n),d=AN(a,s,i,o);return u===Bt.verticalUp?d===Bt.horizontalLeft?l=Bt.diagonalUpLeft:l=Bt.diagonalUpRight:d===Bt.horizontalLeft?l=Bt.diagonalDownLeft:l=Bt.diagonalDownRight,l}function C5e(e,t,r,n){let a=e[0]-t[0],s=e[0]-r[0],i=t[0]-r[0],o=e[1]-t[1],l=e[1]-r[1],u=t[1]-r[1],d=Math.max(Math.abs(a),Math.abs(s),Math.abs(i)),h=Math.max(Math.abs(o),Math.abs(l),Math.abs(u)),p=0,c=0,m=0,f=h/(d+1e-5);f>1.5?p+=Yl.DISTANCE_VOTE_POWER:f>.66?c+=Yl.DISTANCE_VOTE_POWER:m+=Yl.DISTANCE_VOTE_POWER;let g=Math.sqrt(a*a+o*o),y=Math.sqrt(s*s+l*l),A=Math.sqrt(i*i+u*u),x=Math.max(g,y,A),b=e[0],w=e[1],I=r[0],T=r[1];x===g?(I=r[0],T=r[1]):x===A&&(b=t[0],w=t[1]);let F=yN([b,w],[I,T]),$=gN(F,Yl.TOTAL_ANGLE_VOTE_POWER);p+=$[0],c+=$[1],m+=$[2];for(let z of n){let O=gN(z,Yl.SINGLE_ANGLE_VOTE_POWER);p+=O[0],c+=O[1],m+=O[2]}let S;return p===Math.max(p,c,m)?S=xN(l,o,u,h):m===Math.max(c,m)?S=AN(s,a,i,d):S=S5e(l,o,u,h,s,a,i,d),S}function bN(e){let t=[],r=[],n=[],a=[];if(!e)return{curls:n,directions:a};for(let s of Jr.all){let i=Jr.getPoints(s),o=[],l=[];for(let u of i){let d=e[u[0]],h=e[u[1]],p=yN(d,h),c=p[0],m=p[1];o.push(c),l.push(m)}t.push(o),r.push(l)}for(let s of Jr.all){let i=s===Jr.thumb?1:0,o=Jr.getPoints(s),l=e[o[i][0]],u=e[o[i+1][1]],d=e[o[3][1]],h=I5e(l,u,d),p=C5e(l,u,d,t[s].slice(i));n[s]=h,a[s]=p}return{curls:n,directions:a}}function f1(e){if(!e||e.length===0)return null;let t=bN(e),r={};for(let n of Jr.all)r[Jr.getName(n)]={curl:ro.getName(t.curls[n]),direction:Bt.getName(t.directions[n])};return r}function vN(e){let t=[];if(!e||e.length===0)return t;let r=bN(e);for(let n of fN){let a=n.matchAgainst(r.curls,r.directions);a>=k5e&&t.push({name:n.name,confidence:a})}return t}var wN={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]},Qd,ep,kN;async function Lx(e,t){let r=await kN.estimateHands(e,t);if(!r)return[];let n=[];for(let a=0;a<r.length;a++){let s={};if(r[a].landmarks)for(let d of Object.keys(wN))s[d]=wN[d].map(h=>r[a].landmarks[h]);let i=r[a].landmarks,o=[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,0,0],l=[0,0,0,0];if(i&&i.length>0){for(let d of i)d[0]<o[0]&&(o[0]=d[0]),d[1]<o[1]&&(o[1]=d[1]),d[0]>o[2]&&(o[2]=d[0]),d[1]>o[3]&&(o[3]=d[1]);o[2]-=o[0],o[3]-=o[1],l=[o[0]/(e.shape[2]||0),o[1]/(e.shape[1]||0),o[2]/(e.shape[2]||0),o[3]/(e.shape[1]||0)]}else o=r[a].box?[Math.trunc(Math.max(0,r[a].box.topLeft[0])),Math.trunc(Math.max(0,r[a].box.topLeft[1])),Math.trunc(Math.min(e.shape[2]||0,r[a].box.bottomRight[0])-Math.max(0,r[a].box.topLeft[0])),Math.trunc(Math.min(e.shape[1]||0,r[a].box.bottomRight[1])-Math.max(0,r[a].box.topLeft[1]))]:[0,0,0,0],l=[r[a].box.topLeft[0]/(e.shape[2]||0),r[a].box.topLeft[1]/(e.shape[1]||0),(r[a].box.bottomRight[0]-r[a].box.topLeft[0])/(e.shape[2]||0),(r[a].box.bottomRight[1]-r[a].box.topLeft[1])/(e.shape[1]||0)];let u=f1(i);n.push({id:a,score:Math.round(100*r[a].confidence)/100,boxScore:Math.round(100*r[a].boxConfidence)/100,fingerScore:Math.round(100*r[a].fingerConfidence)/100,label:"hand",box:o,boxRaw:l,keypoints:i,annotations:s,landmarks:u})}return n}async function Bx(e){var r,n;he.initial&&(Qd=null,ep=null),!Qd||!ep?[Qd,ep]=await Promise.all([e.hand.enabled?Ge((r=e.hand.detector)==null?void 0:r.modelPath):null,e.hand.landmarks?Ge((n=e.hand.skeleton)==null?void 0:n.modelPath):null]):(e.debug&&se("cached model:",Qd.modelUrl),e.debug&&se("cached model:",ep.modelUrl));let t=new h1(Qd);return kN=new c1(t,ep),[Qd,ep]}var pr=[null,null],T5e=["StatefulPartitionedCall/Postprocessor/Slice","StatefulPartitionedCall/Postprocessor/ExpandDims_1"],io=[[0,0],[0,0]],N5e=["hand","fist","pinch","point","face","tip","pinchtip"],SN=4,CN=1.6,E5e=512,R5e=1.4,m1=Number.MAX_SAFE_INTEGER,Wx=0,fs=[0,0],Ht={boxes:[],hands:[]},TN={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],base:[0],palm:[0,17,13,9,5,1,0]};async function NN(e){var t;if(he.initial&&(pr[0]=null),pr[0])e.debug&&se("cached model:",pr[0].modelUrl);else{g1(["tensorlistreserve","enter","tensorlistfromtensor","merge","loopcond","switch","exit","tensorliststack","nextiteration","tensorlistsetitem","tensorlistgetitem","reciprocal","shape","split","where"],e),pr[0]=await Ge((t=e.hand.detector)==null?void 0:t.modelPath);let r=Object.values(pr[0].modelSignature.inputs);io[0][0]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[1].size):0,io[0][1]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[2].size):0}return pr[0]}async function EN(e){var t;if(he.initial&&(pr[1]=null),pr[1])e.debug&&se("cached model:",pr[1].modelUrl);else{pr[1]=await Ge((t=e.hand.skeleton)==null?void 0:t.modelPath);let r=Object.values(pr[1].modelSignature.inputs);io[1][0]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[1].size):0,io[1][1]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[2].size):0}return pr[1]}async function $5e(e,t){let r=[];if(!e||!pr[0])return r;let n={},a=(e.shape[2]||1)/(e.shape[1]||1),s=Math.min(Math.round((e.shape[1]||0)/8)*8,E5e),i=Math.round(s*a/8)*8;n.resize=Ie.resizeBilinear(e,[s,i]),n.cast=me(n.resize,"int32"),[n.rawScores,n.rawBoxes]=await pr[0].executeAsync(n.cast,T5e),n.boxes=et(n.rawBoxes,[0,2]),n.scores=et(n.rawScores,[0]);let o=an(n.scores,1);ee(o[SN]),o.splice(SN,1),n.filtered=ur(o,1),ee(o),n.max=yr(n.filtered,1),n.argmax=$n(n.filtered,1);let l=0;n.nms=await Ie.nonMaxSuppressionAsync(n.boxes,n.max,(t.hand.maxDetected||0)+1,t.hand.iouThreshold||0,t.hand.minConfidence||1);let u=await n.nms.data(),d=await n.max.data(),h=await n.argmax.data();for(let p of Array.from(u)){let c=_e(n.boxes,p,1),m=await c.data();ee(c);let f=[m[1],m[0],m[3]-m[1],m[2]-m[0]],g=r1(f,R5e),y=[Math.trunc(f[0]*fs[0]),Math.trunc(f[1]*fs[1]),Math.trunc(f[2]*fs[0]),Math.trunc(f[3]*fs[1])],A=d[p],x=N5e[h[p]],b={id:l++,score:A,box:y,boxRaw:g,label:x};r.push(b)}return Object.keys(n).forEach(p=>ee(n[p])),r.sort((p,c)=>c.score-p.score),r.length>(t.hand.maxDetected||1)&&(r.length=t.hand.maxDetected||1),r}async function Vx(e,t,r){let n={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&&pr[1]&&r.hand.landmarks&&t.score>(r.hand.minConfidence||0)){let a={},s=[t.boxRaw[1],t.boxRaw[0],t.boxRaw[3]+t.boxRaw[1],t.boxRaw[2]+t.boxRaw[0]];a.crop=Ie.cropAndResize(e,[s],[0],[io[1][0],io[1][1]],"bilinear"),a.div=pe(a.crop,Qe.tf255),[a.score,a.keypoints]=pr[1].execute(a.div,["Identity_1","Identity"]);let i=(await a.score.data())[0],o=(100-Math.trunc(100/(1+Math.exp(i))))/100;if(o>=(r.hand.minConfidence||0)){n.fingerScore=o,a.reshaped=U(a.keypoints,[-1,3]);let d=(await a.reshaped.array()).map(h=>[h[0]/io[1][1],h[1]/io[1][0],h[2]||0]).map(h=>[h[0]*t.boxRaw[2],h[1]*t.boxRaw[3],h[2]||0]);n.keypoints=d.map(h=>[fs[0]*(h[0]+t.boxRaw[0]),fs[1]*(h[1]+t.boxRaw[1]),h[2]||0]),n.landmarks=f1(n.keypoints);for(let h of Object.keys(TN))n.annotations[h]=TN[h].map(p=>n.landmarks&&n.keypoints[p]?n.keypoints[p]:null)}Object.keys(a).forEach(l=>ee(a[l]))}return n}async function Ux(e,t){var a,s;if(!pr[0]||!pr[1]||!((a=pr[0])!=null&&a.inputs[0].shape)||!((s=pr[1])!=null&&s.inputs[0].shape))return[];fs=[e.shape[2]||0,e.shape[1]||0],m1++;let r=(t.hand.skipTime||0)>oe()-Wx,n=m1<(t.hand.skipFrames||0);return t.skipAllowed&&r&&n?Ht.hands:new Promise(async i=>{let o=3*(t.hand.skipTime||0)>oe()-Wx,l=m1<3*(t.hand.skipFrames||0);t.skipAllowed&&Ht.hands.length===t.hand.maxDetected?Ht.hands=await Promise.all(Ht.boxes.map(d=>Vx(e,d,t))):t.skipAllowed&&o&&l&&Ht.hands.length>0?Ht.hands=await Promise.all(Ht.boxes.map(d=>Vx(e,d,t))):(Ht.boxes=await $5e(e,t),Wx=oe(),Ht.hands=await Promise.all(Ht.boxes.map(d=>Vx(e,d,t))),m1=0);let u=[...Ht.boxes];if(Ht.boxes.length=0,t.cacheSensitivity>0)for(let d=0;d<Ht.hands.length;d++){let h=bT(Ht.hands[d].keypoints,fs);if(h.box[2]/(e.shape[2]||1)>.05&&h.box[3]/(e.shape[1]||1)>.05&&Ht.hands[d].fingerScore&&Ht.hands[d].fingerScore>(t.hand.minConfidence||0)){let p=r1(h.box,CN),c=r1(h.boxRaw,CN);Ht.boxes.push({...u[d],box:p,boxRaw:c})}}for(let d=0;d<Ht.hands.length;d++){let h=us(Ht.hands[d].keypoints,fs);Ht.hands[d].box=h.box,Ht.hands[d].boxRaw=h.boxRaw}i(Ht.hands)})}var Fr,y1=[],Gx=Number.MAX_SAFE_INTEGER,$N=0,MN=0;async function FN(e){var t;return he.initial&&(Fr=null),Fr?e.debug&&se("cached model:",Fr.modelUrl):Fr=await Ge((t=e.face.liveness)==null?void 0:t.modelPath),Fr}async function jx(e,t,r,n){var i,o;if(!Fr)return 0;let a=(((i=t.face.liveness)==null?void 0:i.skipTime)||0)>oe()-MN,s=Gx<(((o=t.face.liveness)==null?void 0:o.skipFrames)||0);return t.skipAllowed&&a&&s&&$N===n&&y1[r]?(Gx++,y1[r]):(Gx=0,new Promise(async l=>{let u=Ie.resizeBilinear(e,[Fr!=null&&Fr.inputs[0].shape?Fr.inputs[0].shape[2]:0,Fr!=null&&Fr.inputs[0].shape?Fr.inputs[0].shape[1]:0],!1),d=Fr==null?void 0:Fr.execute(u),h=(await d.data())[0];y1[r]=Math.round(100*h)/100,$N=n,MN=oe(),ee([u,d]),l(y1[r])}))}var dc={};ws(dc,{connected:()=>x1,horizontal:()=>Hx,kpt:()=>A1,relative:()=>Xx,vertical:()=>qx});var A1=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],Hx=[["leftEye","rightEye"],["leftEar","rightEar"],["leftShoulder","rightShoulder"],["leftElbow","rightElbow"],["leftWrist","rightWrist"],["leftHip","rightHip"],["leftKnee","rightKnee"],["leftAnkle","rightAnkle"]],qx=[["leftKnee","leftShoulder"],["rightKnee","rightShoulder"],["leftAnkle","leftKnee"],["rightAnkle","rightKnee"]],Xx=[[["leftHip","rightHip"],["leftShoulder","rightShoulder"]],[["leftElbow","rightElbow"],["leftShoulder","rightShoulder"]]],x1={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=.005,vn={keypoints:[],padding:[[0,0],[0,0],[0,0],[0,0]]};function Kx(e){for(let t of Hx){let r=e.keypoints.findIndex(a=>a.part===t[0]),n=e.keypoints.findIndex(a=>a.part===t[1]);if(e.keypoints[r]&&e.keypoints[n]&&e.keypoints[r].position[0]<e.keypoints[n].position[0]){let a=e.keypoints[r];e.keypoints[r]=e.keypoints[n],e.keypoints[n]=a}}for(let t of qx){let r=e.keypoints.findIndex(a=>a&&a.part===t[0]),n=e.keypoints.findIndex(a=>a&&a.part===t[1]);e.keypoints[r]&&e.keypoints[n]&&e.keypoints[r].position[1]<e.keypoints[n].position[1]&&e.keypoints.splice(r,1)}for(let[t,r]of Xx){let n=e.keypoints.findIndex(u=>u&&u.part===t[0]),a=e.keypoints.findIndex(u=>u&&u.part===t[1]),s=e.keypoints.findIndex(u=>u&&u.part===r[0]),i=e.keypoints.findIndex(u=>u&&u.part===r[1]);if(!e.keypoints[s]||!e.keypoints[i])continue;let o=e.keypoints[n]?[Math.abs(e.keypoints[s].position[0]-e.keypoints[n].position[0]),Math.abs(e.keypoints[i].position[0]-e.keypoints[n].position[0])]:[0,0],l=e.keypoints[a]?[Math.abs(e.keypoints[i].position[0]-e.keypoints[a].position[0]),Math.abs(e.keypoints[s].position[0]-e.keypoints[a].position[0])]:[0,0];if(o[0]>o[1]||l[0]>l[1]){let u=e.keypoints[n];e.keypoints[n]=e.keypoints[a],e.keypoints[a]=u}}}function ON(e){for(let t=0;t<e.length;t++)if(e[t]&&vn.keypoints[t]){let r=[Math.abs(e[t].positionRaw[0]-vn.keypoints[t].positionRaw[0]),Math.abs(e[t].positionRaw[1]-vn.keypoints[t].positionRaw[1])];r[0]<PN&&r[1]<PN?e[t]=vn.keypoints[t]:vn.keypoints[t]=e[t]}else vn.keypoints[t]=e[t];return e}function zN(e,t){let r={};if(!e.shape||!e.shape[1]||!e.shape[2])return e;vn.padding=[[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]],r.pad=Xn(e,vn.padding),r.resize=Ie.resizeBilinear(r.pad,[t,t]);let n=me(r.resize,"int32");return Object.keys(r).forEach(a=>ee(r[a])),n}function DN(e,t){e.keypoints=e.keypoints.filter(n=>n&&n.position);for(let n of e.keypoints)n.position=[n.position[0]*(t[0]+vn.padding[2][0]+vn.padding[2][1])/t[0]-vn.padding[2][0],n.position[1]*(t[1]+vn.padding[1][0]+vn.padding[1][1])/t[1]-vn.padding[1][0]],n.positionRaw=[n.position[0]/t[0],n.position[1]/t[1]];let r=us(e.keypoints.map(n=>n.position),t);return e.box=r.box,e.boxRaw=r.boxRaw,e}var wn,b1=0,Zx=Number.MAX_SAFE_INTEGER,Jl={boxes:[],bodies:[],last:0};async function LN(e){return he.initial&&(wn=null),wn?e.debug&&se("cached model:",wn.modelUrl):(g1(["size"],e),wn=await Ge(e.body.modelPath)),b1=wn.inputs[0].shape?wn.inputs[0].shape[2]:0,b1<64&&(b1=256),wn}async function F5e(e,t,r){let n=e[0][0],a=[],s=0;for(let d=0;d<n.length;d++)if(s=n[d][2],s>t.body.minConfidence){let h=[n[d][1],n[d][0]];a.push({score:Math.round(100*s)/100,part:A1[d],positionRaw:h,position:[Math.round((r.shape[2]||0)*h[0]),Math.round((r.shape[1]||0)*h[1])]})}s=a.reduce((d,h)=>h.score>d?h.score:d,0);let i=[],o=us(a.map(d=>d.position),[r.shape[2],r.shape[1]]),l={};for(let[d,h]of Object.entries(x1)){let p=[];for(let c=0;c<h.length-1;c++){let m=a.find(g=>g.part===h[c]),f=a.find(g=>g.part===h[c+1]);m&&f&&m.score>(t.body.minConfidence||0)&&f.score>(t.body.minConfidence||0)&&p.push([m.position,f.position])}l[d]=p}let u={id:0,score:s,box:o.box,boxRaw:o.boxRaw,keypoints:a,annotations:l};return Kx(u),i.push(u),i}async function _5e(e,t,r){let n=[];for(let a=0;a<e[0].length;a++){let s=e[0][a],i=Math.round(100*s[51+4])/100;if(i>t.body.minConfidence){let o=[];for(let h=0;h<17;h++){let p=s[3*h+2];if(p>t.body.minConfidence){let c=[s[3*h+1],s[3*h+0]];o.push({part:A1[h],score:Math.round(100*p)/100,positionRaw:c,position:[Math.round((r.shape[2]||0)*c[0]),Math.round((r.shape[1]||0)*c[1])]})}}let l=us(o.map(h=>h.position),[r.shape[2],r.shape[1]]),u={};for(let[h,p]of Object.entries(x1)){let c=[];for(let m=0;m<p.length-1;m++){let f=o.find(y=>y.part===p[m]),g=o.find(y=>y.part===p[m+1]);f&&g&&f.score>(t.body.minConfidence||0)&&g.score>(t.body.minConfidence||0)&&c.push([f.position,g.position])}u[h]=c}let d={id:a,score:i,box:l.box,boxRaw:l.boxRaw,keypoints:[...o],annotations:u};Kx(d),n.push(d)}}return n.sort((a,s)=>s.score-a.score),n.length>t.body.maxDetected&&(n.length=t.body.maxDetected),n}async function Yx(e,t){if(!wn||!(wn!=null&&wn.inputs[0].shape))return[];t.skipAllowed||(Jl.boxes.length=0),Zx++;let r=(t.body.skipTime||0)>oe()-Jl.last,n=Zx<(t.body.skipFrames||0);return t.skipAllowed&&r&&n?Jl.bodies:new Promise(async a=>{let s={};Zx=0,s.input=zN(e,b1),s.res=wn==null?void 0:wn.execute(s.input),Jl.last=oe();let i=await s.res.array();Jl.bodies=s.res.shape[2]===17?await F5e(i,t,e):await _5e(i,t,e);for(let o of Jl.bodies)DN(o,[e.shape[2]||1,e.shape[1]||1]),ON(o.keypoints);Object.keys(s).forEach(o=>ee(s[o])),a(Jl.bodies)})}var tp,v1=[],WN=0,Jx=Number.MAX_SAFE_INTEGER,k1=0,w1=2.5;async function VN(e){if(!tp||he.initial){tp=await Ge(e.object.modelPath);let t=Object.values(tp.modelSignature.inputs);k1=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}else e.debug&&se("cached model:",tp.modelUrl);return tp}async function P5e(e,t,r){let n=0,a=[];for(let l of[1,2,4])X(async()=>{let u=l*13,d=et(e.find(f=>f.shape[1]===u**2&&(f.shape[2]||0)===qd.length)),h=et(e.find(f=>f.shape[1]===u**2&&(f.shape[2]||0)<qd.length)),c=await h.reshape([-1,4,h.shape[1]/4]).argMax(2).array(),m=await d.array();for(let f=0;f<d.shape[0];f++)for(let g=0;g<d.shape[1];g++){let y=m[f][g];if(y>(r.object.minConfidence||0)&&g!==61){let A=(.5+Math.trunc(f%u))/u,x=(.5+Math.trunc(f/u))/u,b=c[f].map(S=>S*(u/l/k1)),[w,I]=[A-w1/l*b[0],x-w1/l*b[1]],[T,E]=[A+w1/l*b[2]-w,x+w1/l*b[3]-I],R=[w,I,T,E];R=R.map(S=>Math.max(0,Math.min(S,1)));let F=[R[0]*t[0],R[1]*t[1],R[2]*t[0],R[3]*t[1]],$={id:n++,score:Math.round(100*y)/100,class:g+1,label:qd[g].label,box:F.map(S=>Math.trunc(S)),boxRaw:R};a.push($)}}});e.forEach(l=>ee(l));let s=a.map(l=>[l.boxRaw[1],l.boxRaw[0],l.boxRaw[3],l.boxRaw[2]]),i=a.map(l=>l.score),o=[];if(s&&s.length>0){let l=await Ie.nonMaxSuppressionAsync(s,i,r.object.maxDetected,r.object.iouThreshold,r.object.minConfidence);o=await l.data(),ee(l)}return a=a.filter((l,u)=>o.includes(u)).sort((l,u)=>u.score-l.score),a}async function Qx(e,t){let r=(t.object.skipTime||0)>oe()-WN,n=Jx<(t.object.skipFrames||0);return t.skipAllowed&&r&&n&&v1.length>0?(Jx++,v1):(Jx=0,!he.kernels.includes("mod")||!he.kernels.includes("sparsetodense")?v1:new Promise(async a=>{let s=[e.shape[2]||0,e.shape[1]||0],i=Ie.resizeBilinear(e,[k1,k1],!1),o=pe(i,Qe.tf255),l=o.transpose([0,3,1,2]);ee(o),ee(i);let u;t.object.enabled&&(u=tp.execute(l)),WN=oe(),ee(l);let d=await P5e(u,s,t);v1=d,a(d)}))}var hc=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],O5e=hc.length,pc=hc.reduce((e,t,r)=>(e[t]=r,e),{}),z5e=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]],H8e=z5e.map(([e,t])=>[pc[e],pc[t]]),GN=[["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 jN(e){let t=e.reduce(({maxX:r,maxY:n,minX:a,minY:s},{position:{x:i,y:o}})=>({maxX:Math.max(r,i),maxY:Math.max(n,o),minX:Math.min(a,i),minY:Math.min(s,o)}),{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 HN(e,[t,r],[n,a]){let s=t/n,i=r/a,o=(u,d)=>({id:d,score:u.score,boxRaw:[u.box[0]/a,u.box[1]/n,u.box[2]/a,u.box[3]/n],box:[Math.trunc(u.box[0]*i),Math.trunc(u.box[1]*s),Math.trunc(u.box[2]*i),Math.trunc(u.box[3]*s)],keypoints:u.keypoints.map(({score:h,part:p,position:c})=>({score:h,part:p,position:[Math.trunc(c.x*i),Math.trunc(c.y*s)],positionRaw:[c.x/n,c.y/n]})),annotations:{}});return e.map((u,d)=>o(u,d))}var I1=class{constructor(t,r){fe(this,"priorityQueue");fe(this,"numberOfElements");fe(this,"getElementValue");this.priorityQueue=new Array(t),this.numberOfElements=-1,this.getElementValue=r}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 r=2*t;if(r<this.numberOfElements&&this.less(r,r+1)&&r++,!this.less(t,r))break;this.exchange(t,r),t=r}}getValueAt(t){return this.getElementValue(this.priorityQueue[t])}less(t,r){return this.getValueAt(t)<this.getValueAt(r)}exchange(t,r){let n=this.priorityQueue[t];this.priorityQueue[t]=this.priorityQueue[r],this.priorityQueue[r]=n}};function eb(e,t,r,n){return{y:n.get(e,t,r),x:n.get(e,t,r+O5e)}}function tb(e,t,r){let{heatmapY:n,heatmapX:a,id:s}=e,{y:i,x:o}=eb(n,a,s,r);return{x:e.heatmapX*t+o,y:e.heatmapY*t+i}}function rb(e,t,r){return e<t?t:e>r?r:e}function qN(e,t,r,n){let a=r-e,s=n-t;return a*a+s*s}function nb(e,t){return{x:e.x+t.x,y:e.y+t.y}}var Sa,L5e=["MobilenetV1/offset_2/BiasAdd","MobilenetV1/heatmap_2/BiasAdd","MobilenetV1/displacement_fwd_2/BiasAdd","MobilenetV1/displacement_bwd_2/BiasAdd"],S1=1,rp=16,B5e=50**2;function XN(e,t,r,n,a,s,i=2){let o=y=>({y:s.get(y.y,y.x,e),x:s.get(y.y,y.x,s.shape[2]/2+e)}),l=(y,A,x)=>({y:rb(Math.round(y.y/rp),0,A-1),x:rb(Math.round(y.x/rp),0,x-1)}),[u,d]=n.shape,h=l(t.position,u,d),p=o(h),m=nb(t.position,p);for(let y=0;y<i;y++){let A=l(m,u,d),x=eb(A.y,A.x,r,a);m=nb({x:A.x*rp,y:A.y*rp},{x:x.x,y:x.y})}let f=l(m,u,d),g=n.get(f.y,f.x,r);return{position:m,part:hc[r],score:g}}function W5e(e,t,r,n,a){let s=GN.map(([p,c])=>[pc[p],pc[c]]),i=s.map(([,p])=>p),o=s.map(([p])=>p),l=t.shape[2],u=i.length,d=new Array(l),h=tb(e.part,rp,r);d[e.part.id]={score:e.score,part:hc[e.part.id],position:h};for(let p=u-1;p>=0;--p){let c=i[p],m=o[p];d[c]&&!d[m]&&(d[m]=XN(p,d[c],m,t,r,a))}for(let p=0;p<u;++p){let c=o[p],m=i[p];d[c]&&!d[m]&&(d[m]=XN(p,d[c],m,t,r,n))}return d}function V5e(e,t,r,n,a){let[s,i]=a.shape,o=!0,l=Math.max(r-S1,0),u=Math.min(r+S1+1,s);for(let d=l;d<u;++d){let h=Math.max(n-S1,0),p=Math.min(n+S1+1,i);for(let c=h;c<p;++c)if(a.get(d,c,e)>t){o=!1;break}if(!o)break}return o}function U5e(e,t){let[r,n,a]=t.shape,s=new I1(r*n*a,({score:i})=>i);for(let i=0;i<r;++i)for(let o=0;o<n;++o)for(let l=0;l<a;++l){let u=t.get(i,o,l);u<e||V5e(l,u,i,o,t)&&s.enqueue({score:u,part:{heatmapY:i,heatmapX:o,id:l}})}return s}function KN(e,{x:t,y:r},n){return e.some(({keypoints:a})=>{var i;let s=(i=a[n])==null?void 0:i.position;return s?qN(r,t,s.y,s.x)<=B5e:!1})}function G5e(e,t){return t.reduce((n,{position:a,score:s},i)=>(KN(e,a,i)||(n+=s),n),0)/t.length}function j5e(e,t,r,n,a,s){let i=[],o=U5e(s,t);for(;i.length<a&&!o.empty();){let l=o.dequeue(),u=tb(l.part,rp,e);if(KN(i,u,l.part.id))continue;let d=W5e(l,t,e,r,n);d=d.filter(c=>c.score>s);let h=G5e(i,d),p=jN(d);h>s&&i.push({keypoints:d,box:p,score:Math.round(100*h)/100})}return i}async function ab(e,t){let r=X(()=>{if(!Sa.inputs[0].shape)return[];let i=Ie.resizeBilinear(e,[Sa.inputs[0].shape[2],Sa.inputs[0].shape[1]]),o=ce(pe(me(i,"float32"),127.5),1),u=Sa.execute(o,L5e).map(d=>et(d,[0]));return u[1]=Tr(u[1]),u}),n=await Promise.all(r.map(i=>i.buffer()));for(let i of r)ee(i);let a=await j5e(n[0],n[1],n[2],n[3],t.body.maxDetected,t.body.minConfidence);return Sa.inputs[0].shape?HN(a,[e.shape[1],e.shape[2]],[Sa.inputs[0].shape[2],Sa.inputs[0].shape[1]]):[]}async function ZN(e){return!Sa||he.initial?Sa=await Ge(e.body.modelPath):e.debug&&se("cached model:",Sa.modelUrl),Sa}var Va,sb=!1;async function ib(e){return!Va||he.initial?Va=await Ge(e.segmentation.modelPath):e.debug&&se("cached model:",Va.modelUrl),Va}async function JN(e,t,r){var f,g;if(sb)return{data:[],canvas:null,alpha:null};sb=!0,Va||await ib(r);let n=await Ud(e,r),a=((f=n.tensor)==null?void 0:f.shape[2])||0,s=((g=n.tensor)==null?void 0:g.shape[1])||0;if(!n.tensor)return{data:[],canvas:null,alpha:null};let i={};i.resize=Ie.resizeBilinear(n.tensor,[Va.inputs[0].shape?Va.inputs[0].shape[1]:0,Va.inputs[0].shape?Va.inputs[0].shape[2]:0],!1),ee(n.tensor),i.norm=pe(i.resize,Qe.tf255),i.res=Va.execute(i.norm),i.squeeze=et(i.res,0),i.squeeze.shape[2]===2?(i.softmax=Sd(i.squeeze),[i.bg,i.fg]=an(i.softmax,2),i.expand=Kt(i.fg,2),i.pad=Kt(i.expand,0),i.crop=Ie.cropAndResize(i.pad,[[0,0,.5,.5]],[0],[a,s]),i.data=et(i.crop,0)):i.data=Ie.resizeBilinear(i.squeeze,[s,a]);let o=Array.from(await i.data.data());if(he.node&&!he.Canvas&&typeof ImageData=="undefined")return r.debug&&se("canvas support missing"),Object.keys(i).forEach(y=>ee(i[y])),{data:o,canvas:null,alpha:null};let l=Zr(a,s);Ln&&await Ln.toPixels(i.data,l);let u=l.getContext("2d");r.segmentation.blur&&r.segmentation.blur>0&&(u.filter=`blur(${r.segmentation.blur}px)`);let d=u.getImageData(0,0,a,s),h=Zr(a,s),p=h.getContext("2d");n.canvas&&p.drawImage(n.canvas,0,0),p.globalCompositeOperation="darken",r.segmentation.blur&&r.segmentation.blur>0&&(p.filter=`blur(${r.segmentation.blur}px)`),p.drawImage(l,0,0),p.globalCompositeOperation="source-over",p.filter="none";let c=p.getImageData(0,0,a,s);for(let y=0;y<a*s;y++)c.data[4*y+3]=d.data[4*y+0];p.putImageData(c,0,0);let m=null;if(t&&h){m=Zr(a,s);let y=await Ud(t,r);ee(y.tensor);let A=m.getContext("2d");A.drawImage(y.canvas,0,0,m.width,m.height),A.drawImage(h,0,0)}return Object.keys(i).forEach(y=>ee(i[y])),sb=!1,{data:o,canvas:h,alpha:l}}var cc=class{constructor(){fe(this,"ssrnetage",null);fe(this,"gear",null);fe(this,"blazeposedetect",null);fe(this,"blazepose",null);fe(this,"centernet",null);fe(this,"efficientpose",null);fe(this,"mobilefacenet",null);fe(this,"emotion",null);fe(this,"facedetect",null);fe(this,"faceiris",null);fe(this,"facemesh",null);fe(this,"faceres",null);fe(this,"ssrnetgender",null);fe(this,"handpose",null);fe(this,"handskeleton",null);fe(this,"handtrack",null);fe(this,"liveness",null);fe(this,"movenet",null);fe(this,"nanodet",null);fe(this,"posenet",null);fe(this,"segmentation",null);fe(this,"antispoof",null)}},ob=()=>{let e=0,t=0;for(let r of Object.values(La))e+=r.manifest,t+=r.weights;return{sizeManifest:e,sizeWeights:t,numModels:Object.values(La).length}};function C1(e){for(let t of Object.keys(e.models))e.models[t]=null}async function lb(e){var t,r,n,a,s,i,o,l,u,d,h,p,c,m,f,g,y,A,x,b,w,I,T,E,R,F,$,S,z,O,j;he.initial&&C1(e),e.config.hand.enabled&&(!e.models.handpose&&((r=(t=e.config.hand.detector)==null?void 0:t.modelPath)==null?void 0:r.includes("handdetect"))&&([e.models.handpose,e.models.handskeleton]=await Bx(e.config)),!e.models.handskeleton&&e.config.hand.landmarks&&((a=(n=e.config.hand.detector)==null?void 0:n.modelPath)==null?void 0:a.includes("handdetect"))&&([e.models.handpose,e.models.handskeleton]=await Bx(e.config))),e.config.body.enabled&&!e.models.blazepose&&((i=(s=e.config.body)==null?void 0:s.modelPath)==null?void 0:i.includes("blazepose"))&&(e.models.blazepose=ST(e.config)),e.config.body.enabled&&!e.models.blazeposedetect&&e.config.body.detector&&e.config.body.detector.modelPath&&(e.models.blazeposedetect=IT(e.config)),e.config.body.enabled&&!e.models.efficientpose&&((l=(o=e.config.body)==null?void 0:o.modelPath)==null?void 0:l.includes("efficientpose"))&&(e.models.efficientpose=$T(e.config)),e.config.body.enabled&&!e.models.movenet&&((d=(u=e.config.body)==null?void 0:u.modelPath)==null?void 0:d.includes("movenet"))&&(e.models.movenet=LN(e.config)),e.config.body.enabled&&!e.models.posenet&&((p=(h=e.config.body)==null?void 0:h.modelPath)==null?void 0:p.includes("posenet"))&&(e.models.posenet=ZN(e.config)),e.config.face.enabled&&!e.models.facedetect&&(e.models.facedetect=mT(e.config)),e.config.face.enabled&&((c=e.config.face.antispoof)==null?void 0:c.enabled)&&!e.models.antispoof&&(e.models.antispoof=rT(e.config)),e.config.face.enabled&&((m=e.config.face.liveness)==null?void 0:m.enabled)&&!e.models.liveness&&(e.models.liveness=FN(e.config)),e.config.face.enabled&&((f=e.config.face.description)==null?void 0:f.enabled)&&!e.models.faceres&&(e.models.faceres=rN(e.config)),e.config.face.enabled&&((g=e.config.face.emotion)==null?void 0:g.enabled)&&!e.models.emotion&&(e.models.emotion=PT(e.config)),e.config.face.enabled&&((y=e.config.face.iris)==null?void 0:y.enabled)&&!((A=e.config.face.attention)!=null&&A.enabled)&&!e.models.faceiris&&(e.models.faceiris=jT(e.config)),e.config.face.enabled&&((x=e.config.face.mesh)==null?void 0:x.enabled)&&!e.models.facemesh&&(e.models.facemesh=YT(e.config)),e.config.face.enabled&&((b=e.config.face.gear)==null?void 0:b.enabled)&&!e.models.gear&&(e.models.gear=UC(e.config)),e.config.face.enabled&&((w=e.config.face.ssrnet)==null?void 0:w.enabled)&&!e.models.ssrnetage&&(e.models.ssrnetage=XC(e.config)),e.config.face.enabled&&((I=e.config.face.ssrnet)==null?void 0:I.enabled)&&!e.models.ssrnetgender&&(e.models.ssrnetgender=JC(e.config)),e.config.face.enabled&&((T=e.config.face.mobilefacenet)==null?void 0:T.enabled)&&!e.models.mobilefacenet&&(e.models.mobilefacenet=BT(e.config)),e.config.hand.enabled&&!e.models.handtrack&&((R=(E=e.config.hand.detector)==null?void 0:E.modelPath)==null?void 0:R.includes("handtrack"))&&(e.models.handtrack=NN(e.config)),e.config.hand.enabled&&e.config.hand.landmarks&&!e.models.handskeleton&&(($=(F=e.config.hand.detector)==null?void 0:F.modelPath)==null?void 0:$.includes("handtrack"))&&(e.models.handskeleton=EN(e.config)),e.config.object.enabled&&!e.models.centernet&&((z=(S=e.config.object)==null?void 0:S.modelPath)==null?void 0:z.includes("centernet"))&&(e.models.centernet=NT(e.config)),e.config.object.enabled&&!e.models.nanodet&&((j=(O=e.config.object)==null?void 0:O.modelPath)==null?void 0:j.includes("nanodet"))&&(e.models.nanodet=VN(e.config)),e.config.segmentation.enabled&&!e.models.segmentation&&(e.models.segmentation=ib(e.config));for await(let K of Object.keys(e.models))e.models[K]&&typeof e.models[K]!="undefined"&&(e.models[K]=await e.models[K])}async function ub(e){let t=["const","placeholder","noop","pad","squeeze","add","sub","mul","div"];for(let r of Object.keys(e.models)){let n=e.models[r];if(!n)continue;let a=[],s=n==null?void 0:n.executor;if(s&&s.graph.nodes)for(let o of Object.values(s.graph.nodes)){let l=o.op.toLowerCase();a.includes(l)||a.push(l)}else!s&&e.config.debug&&se("model signature not determined:",r);let i=[];for(let o of a)!t.includes(o)&&!e.env.kernels.includes(o)&&!e.env.kernels.includes(o.replace("_",""))&&!e.env.kernels.includes(o.replace("native",""))&&!e.env.kernels.includes(o.replace("v2",""))&&i.push(o);e.config.debug&&i.length>0&&se("model validation failed:",r,i)}}var Rt={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 H5e(){let e=Rt.gl;!e||(Rt.extensions=e.getSupportedExtensions())}async function eE(e){var t;if(e.config.backend==="humangl"&&(Rt.name in Xt().registry&&(!Rt.gl||!Rt.gl.getParameter(Rt.gl.VERSION))&&(se("error: humangl backend invalid context"),C1(e)),!Uy(Rt.name))){try{Rt.canvas=await Zr(100,100)}catch(n){se("error: cannot create canvas:",n);return}try{if(Rt.gl=(t=Rt.canvas)==null?void 0:t.getContext("webgl2",Rt.webGLattr),!Rt.gl.getParameter(Rt.gl.VERSION).includes("2.0")){se("override: using fallback webgl backend as webgl 2.0 is not detected"),e.config.backend="webgl";return}Rt.canvas&&(Rt.canvas.addEventListener("webglcontextlost",async a=>{throw se("error: humangl:",a.type),se("possible browser memory leak using webgl or conflict with multiple backend registrations"),e.emit("error"),new Error("backend error: webgl context lost")}),Rt.canvas.addEventListener("webglcontextrestored",a=>{se("error: humangl context restored:",a)}),Rt.canvas.addEventListener("webglcontextcreationerror",a=>{se("error: humangl context create:",a)}))}catch(n){se("error: cannot get WebGL context:",n);return}try{Fm(2,Rt.gl)}catch(n){se("error: cannot set WebGL context:",n);return}try{let n=new Tu(Rt.gl);Rl(Rt.name,()=>new qh(n),Rt.priority)}catch(n){se("error: cannot register WebGL backend:",n);return}try{Fa("webgl").forEach(a=>{let s={...a,backendName:Rt.name};qn(s)})}catch(n){se("error: cannot update WebGL backend registration:",n);return}let r=Dn().getGPGPUContext?Dn().getGPGPUContext().gl:null;if(r)se(`humangl webgl version:${r.getParameter(r.VERSION)} renderer:${r.getParameter(r.RENDERER)}`);else{se("error: no current gl context:",r,Rt.gl);return}try{ba.set("WEBGL_VERSION",2)}catch(n){se("error: cannot set WebGL backend flags:",n);return}H5e(),se("backend registered:",Rt.name)}}function q5e(){if(!he.kernels.includes("mod")){let e={kernelName:"Mod",backendName:Hr(),kernelFunc:t=>X(()=>ce(t.inputs.a,L(pe(t.inputs.a,t.inputs.b),t.inputs.b)))};qn(e),he.kernels.push("mod")}if(!he.kernels.includes("floormod")){let e={kernelName:"FloorMod",backendName:Hr(),kernelFunc:t=>X(()=>Ch(t.inputs.a/t.inputs.b)*t.inputs.b+kd(t.inputs.a,t.inputs.b))};qn(e),he.kernels.push("floormod")}}async function N1(e,t=!1){if(e.state="backend",t||he.initial||e.config.backend&&e.config.backend.length>0&&Hr()!==e.config.backend){let r=oe();if(e.config.backend&&e.config.backend.length>0){if(typeof window=="undefined"&&typeof WorkerGlobalScope!="undefined"&&e.config.debug&&e.config.debug&&se("running inside web worker"),he.browser&&e.config.backend==="tensorflow"&&(e.config.debug&&se("override: backend set to tensorflow while running in browser"),e.config.backend="humangl"),he.node&&(e.config.backend==="webgl"||e.config.backend==="humangl")&&(e.config.debug&&se(`override: backend set to ${e.config.backend} while running in nodejs`),e.config.backend="tensorflow"),he.browser&&e.config.backend==="webgpu")if(typeof navigator=="undefined"||typeof navigator.gpu=="undefined")se("override: backend set to webgpu but browser does not support webgpu"),e.config.backend="humangl";else{let a=await navigator.gpu.requestAdapter();if(e.config.debug&&se("enumerated webgpu adapter:",a),!a)se("override: backend set to webgpu but browser reports no available gpu"),e.config.backend="humangl";else{let s="requestAdapterInfo"in a?await a.requestAdapterInfo():void 0;se("webgpu adapter info:",s)}}e.config.backend==="humangl"&&await eE(e);let n=Object.keys(Xt().registryFactory);if(e.config.debug&&se("available backends:",n),n.includes(e.config.backend)||(se(`error: backend ${e.config.backend} not found in registry`),e.config.backend=he.node?"tensorflow":"webgl",e.config.debug&&se(`override: setting backend ${e.config.backend}`)),e.config.debug&&se("setting backend:",e.config.backend),e.config.backend==="wasm"){try{Z().set("CANVAS2D_WILL_READ_FREQUENTLY",!0)}catch(i){}if(e.config.debug&&se("wasm path:",e.config.wasmPath),typeof(Ue==null?void 0:Ue.setWasmPaths)!="undefined")await HA(e.config.wasmPath,e.config.wasmPlatformFetch);else throw new Error("backend error: attempting to use wasm backend but wasm path is not set");let a=await Z().getAsync("WASM_HAS_SIMD_SUPPORT"),s=await Z().getAsync("WASM_HAS_MULTITHREAD_SUPPORT");e.config.debug&&se(`wasm execution: ${a?"SIMD":"no SIMD"} ${s?"multithreaded":"singlethreaded"}`),e.config.debug&&!a&&se("warning: wasm simd support is not enabled")}try{await Vy(e.config.backend),await xd(),jC()}catch(a){return se("error: cannot set backend:",e.config.backend,a),!1}}if(Hr()==="humangl"&&(ba.set("CHECK_COMPUTATION_FOR_ERRORS",!1),ba.set("WEBGL_CPU_FORWARD",!0),ba.set("WEBGL_USE_SHAPES_UNIFORMS",!0),ba.set("CPU_HANDOFF_SIZE_THRESHOLD",256),typeof e.config.deallocate!="undefined"&&e.config.deallocate&&(se("changing webgl: WEBGL_DELETE_TEXTURE_THRESHOLD:",!0),ba.set("WEBGL_DELETE_TEXTURE_THRESHOLD",0)),Dn().getGPGPUContext)){let n=await Dn().getGPGPUContext().gl;e.config.debug&&se(`gl version:${n.getParameter(n.VERSION)} renderer:${n.getParameter(n.RENDERER)}`)}Hr(),By(),await xd(),e.performance.initBackend=Math.trunc(oe()-r),e.config.backend=Hr(),await he.updateBackend(),q5e()}return!0}function g1(e,t){for(let r of e){let n={kernelName:r,backendName:t.backend,kernelFunc:()=>{t.debug&&se("kernelFunc",r,t.backend)}};qn(n)}he.kernels=Fa(Hr()).map(r=>r.kernelName.toLowerCase())}var gb={};ws(gb,{all:()=>mb,body:()=>ap,canvas:()=>fb,face:()=>np,gesture:()=>op,hand:()=>sp,object:()=>ip,options:()=>_r,person:()=>cb});var Vn=e=>{if(!e)se("draw error: invalid canvas");else if(!e.getContext)se("draw error: canvas context not defined");else{let t=e.getContext("2d");if(!t)se("draw error: cannot get canvas context");else return t}return null},Ql=e=>Math.round(e*180/Math.PI),ms=(e,t)=>{if(!t.useDepth||typeof e=="undefined")return t.color;let r=Uint8ClampedArray.from([127+2*e,127-2*e,255]);return`rgba(${r[0]}, ${r[1]}, ${r[2]}, ${t.alpha})`};function gs(e,t,r,n,a){e.fillStyle=ms(n,a),e.beginPath(),e.arc(t,r,a.pointSize,0,2*Math.PI),e.fill()}function Ua(e,t,r,n,a,s){if(e.beginPath(),e.lineWidth=s.lineWidth,s.useCurves){let i=(t+t+n)/2,o=(r+r+a)/2;e.ellipse(i,o,n/2,a/2,0,0,2*Math.PI)}else e.moveTo(t+s.roundRect,r),e.lineTo(t+n-s.roundRect,r),e.quadraticCurveTo(t+n,r,t+n,r+s.roundRect),e.lineTo(t+n,r+a-s.roundRect),e.quadraticCurveTo(t+n,r+a,t+n-s.roundRect,r+a),e.lineTo(t+s.roundRect,r+a),e.quadraticCurveTo(t,r+a,t,r+a-s.roundRect),e.lineTo(t,r+s.roundRect),e.quadraticCurveTo(t,r,t+s.roundRect,r),e.closePath();e.stroke()}function db(e,t,r){if(!(t.length<2)){e.beginPath(),e.moveTo(t[0][0],t[0][1]);for(let n of t)e.strokeStyle=ms(n[2],r),e.lineTo(Math.trunc(n[0]),Math.trunc(n[1]));e.stroke(),r.fillPolygons&&(e.closePath(),e.fill())}}function rE(e,t,r){if(!(t.length<2)){if(e.lineWidth=r.lineWidth,!r.useCurves||t.length<=2){db(e,t,r);return}e.moveTo(t[0][0],t[0][1]);for(let n=0;n<t.length-2;n++){let a=(t[n][0]+t[n+1][0])/2,s=(t[n][1]+t[n+1][1])/2;e.quadraticCurveTo(t[n][0],t[n][1],a,s)}e.quadraticCurveTo(t[t.length-2][0],t[t.length-2][1],t[t.length-1][0],t[t.length-1][1]),e.stroke(),r.fillPolygons&&(e.closePath(),e.fill())}}function pb(e,t,r,n=5){let a,s,i;e.beginPath(),e.moveTo(t[0],t[1]),e.lineTo(r[0],r[1]),a=Math.atan2(r[1]-t[1],r[0]-t[0]),s=n*Math.cos(a)+r[0],i=n*Math.sin(a)+r[1],e.moveTo(s,i),a+=1/3*(2*Math.PI),s=n*Math.cos(a)+r[0],i=n*Math.sin(a)+r[1],e.lineTo(s,i),a+=1/3*(2*Math.PI),s=n*Math.cos(a)+r[0],i=n*Math.sin(a)+r[1],e.lineTo(s,i),e.closePath(),e.stroke(),e.fill()}var _r={color:"rgba(173, 216, 230, 0.6)",labelColor:"rgba(173, 216, 230, 1)",shadowColor:"black",alpha:.5,font:'small-caps 16px "Segoe UI"',lineHeight:18,lineWidth:4,pointSize:2,roundRect:8,drawPoints:!1,drawLabels:!0,drawBoxes:!0,drawAttention:!0,drawGestures:!0,drawPolygons:!0,drawGaze:!0,fillPolygons:!1,useDepth:!0,useCurves:!1};var dt;function K5e(e,t){if(dt.drawLabels){let r=[];if(r.push(`face: ${Math.trunc(100*e.score)}%`),e.genderScore&&r.push(`${e.gender||""} ${Math.trunc(100*e.genderScore)}%`),e.age&&r.push(`age: ${e.age||""}`),e.iris&&r.push(`distance: ${e.iris}`),e.real&&r.push(`real: ${Math.trunc(100*e.real)}%`),e.live&&r.push(`live: ${Math.trunc(100*e.live)}%`),e.emotion&&e.emotion.length>0){let n=e.emotion.map(a=>`${Math.trunc(100*a.score)}% ${a.emotion}`);n.length>3&&(n.length=3),r.push(n.join(" "))}e.rotation&&e.rotation.angle&&e.rotation.gaze&&(e.rotation.angle.roll&&r.push(`roll: ${Ql(e.rotation.angle.roll)}\xB0 yaw:${Ql(e.rotation.angle.yaw)}\xB0 pitch:${Ql(e.rotation.angle.pitch)}\xB0`),e.rotation.gaze.bearing&&r.push(`gaze: ${Ql(e.rotation.gaze.bearing)}\xB0`)),r.length===0&&r.push("face"),t.fillStyle=dt.color;for(let n=r.length-1;n>=0;n--){let a=Math.max(e.box[0],0),s=n*dt.lineHeight+e.box[1];dt.shadowColor&&dt.shadowColor!==""&&(t.fillStyle=dt.shadowColor,t.fillText(r[n],a+5,s+16)),t.fillStyle=dt.labelColor,t.fillText(r[n],a+4,s+15)}}}function Z5e(e,t){if(e.annotations&&e.annotations.leftEyeIris&&e.annotations.leftEyeIris[0]){t.strokeStyle=dt.useDepth?"rgba(255, 200, 255, 0.3)":dt.color,t.beginPath();let r=Math.abs(e.annotations.leftEyeIris[3][0]-e.annotations.leftEyeIris[1][0])/2,n=Math.abs(e.annotations.leftEyeIris[4][1]-e.annotations.leftEyeIris[2][1])/2;t.ellipse(e.annotations.leftEyeIris[0][0],e.annotations.leftEyeIris[0][1],r,n,0,0,2*Math.PI),t.stroke(),dt.fillPolygons&&(t.fillStyle=dt.useDepth?"rgba(255, 255, 200, 0.3)":dt.color,t.fill())}if(e.annotations&&e.annotations.rightEyeIris&&e.annotations.rightEyeIris[0]){t.strokeStyle=dt.useDepth?"rgba(255, 200, 255, 0.3)":dt.color,t.beginPath();let r=Math.abs(e.annotations.rightEyeIris[3][0]-e.annotations.rightEyeIris[1][0])/2,n=Math.abs(e.annotations.rightEyeIris[4][1]-e.annotations.rightEyeIris[2][1])/2;t.ellipse(e.annotations.rightEyeIris[0][0],e.annotations.rightEyeIris[0][1],r,n,0,0,2*Math.PI),t.stroke(),dt.fillPolygons&&(t.fillStyle=dt.useDepth?"rgba(255, 255, 200, 0.3)":dt.color,t.fill())}}function Y5e(e,t){var r;if(dt.drawGaze&&((r=e.rotation)==null?void 0:r.angle)&&typeof Path2D!="undefined"){t.strokeStyle="pink";let n=e.box[0]+e.box[2]/2-e.box[3]*Ql(e.rotation.angle.yaw)/90,a=e.box[1]+e.box[3]/2+e.box[2]*Ql(e.rotation.angle.pitch)/90,s=new Path2D(`
|
|
M ${e.box[0]+e.box[2]/2} ${e.box[1]}
|
|
C
|
|
${n} ${e.box[1]},
|
|
${n} ${e.box[1]+e.box[3]},
|
|
${e.box[0]+e.box[2]/2} ${e.box[1]+e.box[3]}
|
|
`),i=new Path2D(`
|
|
M ${e.box[0]} ${e.box[1]+e.box[3]/2}
|
|
C
|
|
${e.box[0]} ${a},
|
|
${e.box[0]+e.box[2]} ${a},
|
|
${e.box[0]+e.box[2]} ${e.box[1]+e.box[3]/2}
|
|
`);t.stroke(i),t.stroke(s)}}function J5e(e,t){var r,n,a,s;if(dt.drawGaze&&((n=(r=e.rotation)==null?void 0:r.gaze)==null?void 0:n.strength)&&((s=(a=e.rotation)==null?void 0:a.gaze)==null?void 0:s.bearing)&&e.annotations.leftEyeIris&&e.annotations.rightEyeIris&&e.annotations.leftEyeIris[0]&&e.annotations.rightEyeIris[0]){t.strokeStyle="pink",t.fillStyle="pink";let i=[e.annotations.leftEyeIris[0][0]+Math.sin(e.rotation.gaze.bearing)*e.rotation.gaze.strength*e.box[3],e.annotations.leftEyeIris[0][1]+Math.cos(e.rotation.gaze.bearing)*e.rotation.gaze.strength*e.box[2]];pb(t,[e.annotations.leftEyeIris[0][0],e.annotations.leftEyeIris[0][1]],[i[0],i[1]],4);let o=[e.annotations.rightEyeIris[0][0]+Math.sin(e.rotation.gaze.bearing)*e.rotation.gaze.strength*e.box[3],e.annotations.rightEyeIris[0][1]+Math.cos(e.rotation.gaze.bearing)*e.rotation.gaze.strength*e.box[2]];pb(t,[e.annotations.rightEyeIris[0][0],e.annotations.rightEyeIris[0][1]],[o[0],o[1]],4)}}function Q5e(e,t){if(dt.drawPolygons&&e.mesh.length>=468){t.lineWidth=1;for(let r=0;r<Ul.length/3;r++){let n=[Ul[r*3+0],Ul[r*3+1],Ul[r*3+2]].map(a=>e.mesh[a]);db(t,n,dt)}Z5e(e,t)}}function eAe(e,t){if(dt.drawPoints&&e.mesh.length>=468)for(let r=0;r<e.mesh.length;r++)gs(t,e.mesh[r][0],e.mesh[r][1],e.mesh[r][2],dt),dt.drawAttention&&(lc.includes(r)&&gs(t,e.mesh[r][0],e.mesh[r][1],e.mesh[r][2]+127,dt),Hl.includes(r)&&gs(t,e.mesh[r][0],e.mesh[r][1],e.mesh[r][2]-127,dt),ql.includes(r)&&gs(t,e.mesh[r][0],e.mesh[r][1],e.mesh[r][2]-127,dt))}function tAe(e,t){dt.drawBoxes&&Ua(t,e.box[0],e.box[1],e.box[2],e.box[3],dt)}async function np(e,t,r){if(dt=Gt(_r,r),!t||!e)return;let n=Vn(e);if(!!n){n.font=dt.font,n.strokeStyle=dt.color,n.fillStyle=dt.color;for(let a of t)tAe(a,n),K5e(a,n),a.mesh&&a.mesh.length>0&&(eAe(a,n),Q5e(a,n),Y5e(a,n),J5e(a,n))}}async function ap(e,t,r){var s;let n=Gt(_r,r);if(!t||!e)return;let a=Vn(e);if(!!a){a.lineJoin="round";for(let i=0;i<t.length;i++){if(a.strokeStyle=n.color,a.fillStyle=n.color,a.lineWidth=n.lineWidth,a.font=n.font,n.drawBoxes&&t[i].box&&((s=t[i].box)==null?void 0:s.length)===4&&(Ua(a,t[i].box[0],t[i].box[1],t[i].box[2],t[i].box[3],n),n.drawLabels&&(n.shadowColor&&n.shadowColor!==""&&(a.fillStyle=n.shadowColor,a.fillText(`body ${100*t[i].score}%`,t[i].box[0]+3,1+t[i].box[1]+n.lineHeight,t[i].box[2])),a.fillStyle=n.labelColor,a.fillText(`body ${100*t[i].score}%`,t[i].box[0]+2,0+t[i].box[1]+n.lineHeight,t[i].box[2]))),n.drawPoints&&t[i].keypoints)for(let o=0;o<t[i].keypoints.length;o++)!t[i].keypoints[o].score||t[i].keypoints[o].score===0||(a.fillStyle=ms(t[i].keypoints[o].position[2],n),gs(a,t[i].keypoints[o].position[0],t[i].keypoints[o].position[1],0,n));if(n.drawLabels&&t[i].keypoints){a.font=n.font;for(let o of t[i].keypoints)!o.score||o.score===0||(a.fillStyle=ms(o.position[2],n),a.fillText(`${o.part} ${Math.trunc(100*o.score)}%`,o.position[0]+4,o.position[1]+4))}if(n.drawPolygons&&t[i].keypoints&&t[i].annotations)for(let o of Object.values(t[i].annotations))for(let l of o)rE(a,l,n)}}}async function sp(e,t,r){let n=Gt(_r,r);if(!t||!e)return;let a=Vn(e);if(!!a){a.lineJoin="round",a.font=n.font;for(let s of t){if(n.drawBoxes&&(a.strokeStyle=n.color,a.fillStyle=n.color,Ua(a,s.box[0],s.box[1],s.box[2],s.box[3],n),n.drawLabels&&(n.shadowColor&&n.shadowColor!==""&&(a.fillStyle=n.shadowColor,a.fillText(`hand:${Math.trunc(100*s.score)}%`,s.box[0]+3,1+s.box[1]+n.lineHeight,s.box[2])),a.fillStyle=n.labelColor,a.fillText(`hand:${Math.trunc(100*s.score)}%`,s.box[0]+2,0+s.box[1]+n.lineHeight,s.box[2])),a.stroke()),n.drawPoints&&s.keypoints&&s.keypoints.length>0)for(let i of s.keypoints)a.fillStyle=ms(i[2],n),gs(a,i[0],i[1],0,n);if(n.drawLabels&&s.annotations){let i=(o,l)=>{if(!o||o.length===0||!o[0])return;let u=o[o.length-1][2]||-256;a.fillStyle=ms(u,n),a.fillText(l,o[o.length-1][0]+4,o[o.length-1][1]+4)};a.font=n.font,i(s.annotations.index,"index"),i(s.annotations.middle,"middle"),i(s.annotations.ring,"ring"),i(s.annotations.pinky,"pinky"),i(s.annotations.thumb,"thumb"),i(s.annotations.palm,"palm")}if(n.drawPolygons&&s.annotations){let i=o=>{if(!(!o||o.length===0||!o[0]))for(let l=0;l<o.length;l++){a.beginPath();let u=o[l][2]||0;a.strokeStyle=ms(l*u,n),a.moveTo(o[l>0?l-1:0][0],o[l>0?l-1:0][1]),a.lineTo(o[l][0],o[l][1]),a.stroke()}};a.lineWidth=n.lineWidth,i(s.annotations.index),i(s.annotations.middle),i(s.annotations.ring),i(s.annotations.pinky),i(s.annotations.thumb)}}}}async function ip(e,t,r){let n=Gt(_r,r);if(!t||!e)return;let a=Vn(e);if(!!a){a.lineJoin="round",a.font=n.font;for(let s of t)if(n.drawBoxes){if(a.strokeStyle=n.color,a.fillStyle=n.color,Ua(a,s.box[0],s.box[1],s.box[2],s.box[3],n),n.drawLabels){let i=`${s.label} ${Math.round(100*s.score)}%`;n.shadowColor&&n.shadowColor!==""&&(a.fillStyle=n.shadowColor,a.fillText(i,s.box[0]+3,1+s.box[1]+n.lineHeight,s.box[2])),a.fillStyle=n.labelColor,a.fillText(i,s.box[0]+2,0+s.box[1]+n.lineHeight,s.box[2])}a.stroke()}}}async function op(e,t,r){let n=Gt(_r,r);if(!(!t||!e)&&n.drawGestures){let a=Vn(e);if(!a)return;a.font=n.font,a.fillStyle=n.color;let s=1;for(let i=0;i<t.length;i++){let o=[],l=[];if([o,l]=Object.entries(t[i]),l.length>1&&l[1].length>0){let u=o[1]>0?`#${o[1]}`:"",d=`${o[0]} ${u}: ${l[1]}`;n.shadowColor&&n.shadowColor!==""&&(a.fillStyle=n.shadowColor,a.fillText(d,8,2+s*n.lineHeight)),a.fillStyle=n.labelColor,a.fillText(d,6,0+s*n.lineHeight),s+=1}}}}var hb=0;async function cb(e,t,r){let n=Gt(_r,r);if(!t||!e)return;let a=Vn(e);if(!!a){a.lineJoin="round",a.font=n.font;for(let s=0;s<t.length;s++)if(n.drawBoxes){if(a.strokeStyle=n.color,a.fillStyle=n.color,Ua(a,t[s].box[0],t[s].box[1],t[s].box[2],t[s].box[3],n),n.drawLabels){let i=`person #${s}`;n.shadowColor&&n.shadowColor!==""&&(a.fillStyle=n.shadowColor,a.fillText(i,t[s].box[0]+3,1+t[s].box[1]+n.lineHeight,t[s].box[2])),a.fillStyle=n.labelColor,a.fillText(i,t[s].box[0]+2,0+t[s].box[1]+n.lineHeight,t[s].box[2])}a.stroke()}}}async function fb(e,t){if(!e||!t)return;let r=Vn(t);!r||r.drawImage(e,0,0)}async function mb(e,t,r){if(!t||!t.performance||!t||!e)return null;let n=oe(),a=Gt(_r,r),s=Promise.all([np(e,t.face,a),ap(e,t.body,a),sp(e,t.hand,a),ip(e,t.object,a),op(e,t.gesture,a)]);return hb=he.perfadd?hb+Math.round(oe()-n):Math.round(oe()-n),t.performance.draw=hb,s}var lp=.1,yb=.5;function rAe(e,t,r){let n=!1,a=r.length-1;for(let s=0;s<r.length;a=s++)r[s].y>t!=r[a].y>t&&e<(r[a].x-r[s].x)*(t-r[s].y)/(r[a].y-r[s].y)+r[s].x&&(n=!n);return n}async function nE(e){if(!e.tensor||!e.mesh||e.mesh.length<100)return e.tensor;let t=e.tensor.shape[2]||0,r=e.tensor.shape[1]||0,n=await e.tensor.buffer(),a=[];for(let i of ea.silhouette)a.push({x:(e.mesh[i][0]-e.box[0])/e.box[2],y:(e.mesh[i][1]-e.box[1])/e.box[3]});lp&&lp>0&&(a=a.map(i=>({x:i.x>.5?i.x+lp:i.x-lp,y:i.y>.5?i.y+lp:i.y-lp})));for(let i=0;i<t;i++)for(let o=0;o<r;o++)rAe(i/t,o/t,a)||(n.set(yb*n.get(0,o,i,0),0,o,i,0),n.set(yb*n.get(0,o,i,1),0,o,i,1),n.set(yb*n.get(0,o,i,2),0,o,i,2));let s=n.toTensor();return ee(n),s}var aAe=e=>{let t=(h,p)=>Math.atan2(h[1]-p[1],h[0]-p[0]);if(!e.annotations.rightEyeIris||!e.annotations.leftEyeIris)return{bearing:0,strength:0};let r=[0,-.1],n=1,a=(e.mesh[33][2]||0)>(e.mesh[263][2]||0),s=a?e.mesh[473]:e.mesh[468],i=a?[(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],o=a?[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=[(i[0]-s[0])/o[0]-r[0],n*(s[1]-i[1])/o[1]-r[1]],u=Math.sqrt(l[0]*l[0]+l[1]*l[1]);return u=Math.min(u,e.boxRaw[2]/2,e.boxRaw[3]/2),{bearing:(t([0,0],l)+Math.PI/2)%Math.PI,strength:u}},aE=(e,t)=>{let r=f=>{let g=Math.sqrt(f[0]*f[0]+f[1]*f[1]+f[2]*f[2]);return f[0]/=g,f[1]/=g,f[2]/=g,f},n=(f,g)=>{let y=f[0]-g[0],A=f[1]-g[1],x=f[2]-g[2];return[y,A,x]},a=(f,g)=>{let y=f[1]*g[2]-f[2]*g[1],A=f[2]*g[0]-f[0]*g[2],x=f[0]*g[1]-f[1]*g[0];return[y,A,x]},s=f=>{let[g,y,A,x,b,w,I,T,E]=f,R,F,$;return x<1?x>-1?($=Math.asin(x),F=Math.atan2(-I,g),R=Math.atan2(-w,b)):($=-Math.PI/2,F=-Math.atan2(T,E),R=0):($=Math.PI/2,F=Math.atan2(T,E),R=0),isNaN(R)&&(R=0),isNaN(F)&&(F=0),isNaN($)&&($=0),{pitch:2*-R,yaw:2*-F,roll:2*-$}},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 o=Math.max(e.boxRaw[2]*t[0],e.boxRaw[3]*t[1])/1.5,l=[i[10],i[152],i[234],i[454]].map(f=>[f[0]*t[0]/o,f[1]*t[1]/o,f[2]]),u=r(n(l[1],l[0])),d=r(n(l[3],l[2])),h=r(a(d,u));d=a(u,h);let p=[d[0],d[1],d[2],u[0],u[1],u[2],h[0],h[1],h[2]],c=s(p),m=i.length===478?aAe(e):{bearing:0,strength:0};return{angle:c,matrix:p,gaze:m}};var Ab=async(e,t)=>{var c,m,f,g,y,A,x,b,w,I,T,E,R,F,$,S,z,O,j,K,D,Y;let r=oe(),n,a,s,i,o,l,u,d,h=[];e.state="run:face";let p=await ZT(t,e.config);if(e.performance.face=he.perfadd?(e.performance.face||0)+Math.trunc(oe()-r):Math.trunc(oe()-r),!t.shape||t.shape.length!==4)return[];if(!p)return[];for(let V=0;V<p.length;V++){if(e.analyze("Get Face"),!p[V].tensor||p[V].tensor.isDisposedInternal){se("Face object is disposed:",p[V].tensor);continue}if((c=e.config.face.detector)!=null&&c.mask){let ae=await nE(p[V]);ee(p[V].tensor),p[V].tensor=ae}let re=p[V].mesh&&p[V].mesh.length>200?aE(p[V],[t.shape[2],t.shape[1]]):null;e.analyze("Start Emotion:"),e.config.async?i=(m=e.config.face.emotion)!=null&&m.enabled?Sx(p[V].tensor||ft([]),e.config,V,p.length):[]:(e.state="run:emotion",r=oe(),i=(f=e.config.face.emotion)!=null&&f.enabled?await Sx(p[V].tensor||ft([]),e.config,V,p.length):[],e.performance.emotion=he.perfadd?(e.performance.emotion||0)+Math.trunc(oe()-r):Math.trunc(oe()-r)),e.analyze("End Emotion:"),e.analyze("Start AntiSpoof:"),e.config.async?l=(g=e.config.face.antispoof)!=null&&g.enabled?ix(p[V].tensor||ft([]),e.config,V,p.length):0:(e.state="run:antispoof",r=oe(),l=(y=e.config.face.antispoof)!=null&&y.enabled?await ix(p[V].tensor||ft([]),e.config,V,p.length):0,e.performance.antispoof=he.perfadd?(e.performance.antispoof||0)+Math.trunc(oe()-r):Math.trunc(oe()-r)),e.analyze("End AntiSpoof:"),e.analyze("Start Liveness:"),e.config.async?u=(A=e.config.face.liveness)!=null&&A.enabled?jx(p[V].tensor||ft([]),e.config,V,p.length):0:(e.state="run:liveness",r=oe(),u=(x=e.config.face.liveness)!=null&&x.enabled?await jx(p[V].tensor||ft([]),e.config,V,p.length):0,e.performance.liveness=he.perfadd?(e.performance.antispoof||0)+Math.trunc(oe()-r):Math.trunc(oe()-r)),e.analyze("End Liveness:"),e.analyze("Start GEAR:"),e.config.async?a=(b=e.config.face.gear)!=null&&b.enabled?QA(p[V].tensor||ft([]),e.config,V,p.length):null:(e.state="run:gear",r=oe(),a=(w=e.config.face.gear)!=null&&w.enabled?await QA(p[V].tensor||ft([]),e.config,V,p.length):null,e.performance.gear=Math.trunc(oe()-r)),e.analyze("End GEAR:"),e.analyze("Start SSRNet:"),e.config.async?(n=(I=e.config.face.ssrnet)!=null&&I.enabled?tx(p[V].tensor||ft([]),e.config,V,p.length):null,s=(T=e.config.face.ssrnet)!=null&&T.enabled?ax(p[V].tensor||ft([]),e.config,V,p.length):null):(e.state="run:ssrnet",r=oe(),n=(E=e.config.face.ssrnet)!=null&&E.enabled?await tx(p[V].tensor||ft([]),e.config,V,p.length):null,s=(R=e.config.face.ssrnet)!=null&&R.enabled?await ax(p[V].tensor||ft([]),e.config,V,p.length):null,e.performance.ssrnet=Math.trunc(oe()-r)),e.analyze("End SSRNet:"),e.analyze("Start MobileFaceNet:"),e.config.async?o=(F=e.config.face.mobilefacenet)!=null&&F.enabled?Tx(p[V].tensor||ft([]),e.config,V,p.length):null:(e.state="run:mobilefacenet",r=oe(),o=($=e.config.face.mobilefacenet)!=null&&$.enabled?await Tx(p[V].tensor||ft([]),e.config,V,p.length):null,e.performance.mobilefacenet=Math.trunc(oe()-r)),e.analyze("End MobileFaceNet:"),e.analyze("Start Description:"),e.config.async?d=(S=e.config.face.description)!=null&&S.enabled?Fx(p[V].tensor||ft([]),e.config,V,p.length):null:(e.state="run:description",r=oe(),d=(z=e.config.face.description)!=null&&z.enabled?await Fx(p[V].tensor||ft([]),e.config,V,p.length):null,e.performance.description=he.perfadd?(e.performance.description||0)+Math.trunc(oe()-r):Math.trunc(oe()-r)),e.analyze("End Description:"),e.config.async&&([n,s,i,o,d,a,l,u]=await Promise.all([n,s,i,o,d,a,l,u])),e.analyze("Finish Face:"),((O=e.config.face.ssrnet)==null?void 0:O.enabled)&&n&&s&&(d={...d,age:n.age,gender:s.gender,genderScore:s.genderScore}),((j=e.config.face.gear)==null?void 0:j.enabled)&&a&&(d={...d,age:a.age,gender:a.gender,genderScore:a.genderScore,race:a.race}),((K=e.config.face.mobilefacenet)==null?void 0:K.enabled)&&o&&(d.descriptor=o),(D=e.config.face.iris)!=null&&D.enabled;let Q=p[V].annotations&&p[V].annotations.leftEyeIris&&p[V].annotations.leftEyeIris[0]&&p[V].annotations.rightEyeIris&&p[V].annotations.rightEyeIris[0]&&p[V].annotations.leftEyeIris.length>0&&p[V].annotations.rightEyeIris.length>0&&p[V].annotations.leftEyeIris[0]!==null&&p[V].annotations.rightEyeIris[0]!==null?Math.max(Math.abs(p[V].annotations.leftEyeIris[3][0]-p[V].annotations.leftEyeIris[1][0]),Math.abs(p[V].annotations.rightEyeIris[4][1]-p[V].annotations.rightEyeIris[2][1]))/t.shape[2]:0,ie=(Y=e.config.face.detector)!=null&&Y.return?et(p[V].tensor):null;ee(p[V].tensor),p[V].tensor&&delete p[V].tensor;let J={...p[V],id:V};d!=null&&d.age&&(J.age=d.age),d!=null&&d.gender&&(J.gender=d.gender),d!=null&&d.genderScore&&(J.genderScore=d==null?void 0:d.genderScore),d!=null&&d.descriptor&&(J.embedding=d==null?void 0:d.descriptor),d!=null&&d.race&&(J.race=d==null?void 0:d.race),i&&(J.emotion=i),l&&(J.real=l),u&&(J.live=u),Q&&Q!==0&&(J.iris=Math.trunc(500/Q/11.7)/100),re&&(J.rotation=re),ie&&(J.tensor=ie),h.push(J),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),h};var sE=e=>{if(!e)return[];let t=[];for(let r=0;r<e.length;r++){let n=e[r].keypoints.find(l=>l.part==="leftWrist"),a=e[r].keypoints.find(l=>l.part==="rightWrist"),s=e[r].keypoints.find(l=>l.part==="nose");s&&n&&a&&n.position[1]<s.position[1]&&a.position[1]<s.position[1]?t.push({body:r,gesture:"i give up"}):s&&n&&n.position[1]<s.position[1]?t.push({body:r,gesture:"raise left hand"}):s&&a&&a.position[1]<s.position[1]&&t.push({body:r,gesture:"raise right hand"});let i=e[r].keypoints.find(l=>l.part==="leftShoulder"),o=e[r].keypoints.find(l=>l.part==="rightShoulder");i&&o&&Math.abs(i.positionRaw[1]-o.positionRaw[1])>.1&&t.push({body:r,gesture:`leaning ${i.position[1]>o.position[1]?"left":"right"}`})}return t},iE=e=>{if(!e)return[];let t=[];for(let r=0;r<e.length;r++)if(e[r].mesh&&e[r].mesh.length>450){let n=(e[r].mesh[33][2]||0)-(e[r].mesh[263][2]||0),a=e[r].mesh[33][0]-e[r].mesh[263][0];Math.abs(n/a)<=.15?t.push({face:r,gesture:"facing center"}):t.push({face:r,gesture:`facing ${n<0?"left":"right"}`}),Math.abs(e[r].mesh[374][1]-e[r].mesh[386][1])/Math.abs(e[r].mesh[443][1]-e[r].mesh[450][1])<.2&&t.push({face:r,gesture:"blink left eye"}),Math.abs(e[r].mesh[145][1]-e[r].mesh[159][1])/Math.abs(e[r].mesh[223][1]-e[r].mesh[230][1])<.2&&t.push({face:r,gesture:"blink right eye"});let o=Math.min(100,500*Math.abs(e[r].mesh[13][1]-e[r].mesh[14][1])/Math.abs(e[r].mesh[10][1]-e[r].mesh[152][1]));o>10&&t.push({face:r,gesture:`mouth ${Math.trunc(o)}% open`});let l=e[r].mesh[152][2]||0;Math.abs(l)>10&&t.push({face:r,gesture:`head ${l<0?"up":"down"}`})}return t},oE=e=>{if(!e)return[];let t=[];for(let r=0;r<e.length;r++){if(!e[r].annotations||!e[r].annotations.leftEyeIris||!e[r].annotations.leftEyeIris[0]||!e[r].annotations.rightEyeIris||!e[r].annotations.rightEyeIris[0])continue;let n=e[r].annotations.leftEyeIris[3][0]-e[r].annotations.leftEyeIris[1][0],a=e[r].annotations.leftEyeIris[4][1]-e[r].annotations.leftEyeIris[2][1],s=Math.abs(n*a),i=e[r].annotations.rightEyeIris[3][0]-e[r].annotations.rightEyeIris[1][0],o=e[r].annotations.rightEyeIris[4][1]-e[r].annotations.rightEyeIris[2][1],l=Math.abs(i*o),u=!1;Math.abs(s-l)/Math.max(s,l)<.25&&(u=!0,t.push({iris:r,gesture:"facing center"}));let h=Math.abs(e[r].mesh[263][0]-e[r].annotations.leftEyeIris[0][0])/e[r].box[2],p=Math.abs(e[r].mesh[33][0]-e[r].annotations.rightEyeIris[0][0])/e[r].box[2];(h>.06||p>.06)&&(u=!1),h>p?h>.05&&t.push({iris:r,gesture:"looking right"}):p>.05&&t.push({iris:r,gesture:"looking left"});let c=Math.abs(e[r].mesh[145][1]-e[r].annotations.rightEyeIris[0][1])/e[r].box[3],m=Math.abs(e[r].mesh[374][1]-e[r].annotations.leftEyeIris[0][1])/e[r].box[3];(m<.01||c<.01||m>.022||c>.022)&&(u=!1),(m<.01||c<.01)&&t.push({iris:r,gesture:"looking down"}),(m>.022||c>.022)&&t.push({iris:r,gesture:"looking up"}),u&&t.push({iris:r,gesture:"looking center"})}return t},lE=e=>{if(!e)return[];let t=[];for(let r=0;r<e.length;r++){let n=[];if(e[r].annotations)for(let[a,s]of Object.entries(e[r].annotations))a!=="palmBase"&&Array.isArray(s)&&s[0]&&n.push({name:a.toLowerCase(),position:s[0]});if(n&&n.length>0){let a=n.reduce((i,o)=>(i.position[2]||0)<(o.position[2]||0)?i:o);t.push({hand:r,gesture:`${a.name} forward`});let s=n.reduce((i,o)=>i.position[1]<o.position[1]?i:o);t.push({hand:r,gesture:`${s.name} up`})}if(e[r].keypoints){let a=vN(e[r].keypoints);for(let s of a)t.push({hand:r,gesture:s.name})}}return t};var Ne={face:[],body:[],hand:[],gesture:[],object:[],persons:[],performance:{},timestamp:0,error:null},xb=0;function uE(e,t){var i,o,l,u,d,h,p,c,m,f,g,y,A,x,b,w,I,T,E,R,F,$,S,z,O,j,K;let r=oe();if(!e)return{face:[],body:[],hand:[],gesture:[],object:[],persons:[],performance:{},timestamp:0,error:null};let n=Date.now()-e.timestamp,a=n<1e3?8-Math.log(n+1):1;if(e.canvas&&(Ne.canvas=e.canvas),e.error&&(Ne.error=e.error),!Ne.body||e.body.length!==Ne.body.length)Ne.body=JSON.parse(JSON.stringify(e.body));else for(let D=0;D<e.body.length;D++){let Y=e.body[D].box.map((J,ae)=>((a-1)*Ne.body[D].box[ae]+J)/a),V=e.body[D].boxRaw.map((J,ae)=>((a-1)*Ne.body[D].boxRaw[ae]+J)/a),re=e.body[D].keypoints.map((J,ae)=>{var de,be,ve,Ee,$e,ze,We,Ke,ot;return{score:J.score,part:J.part,position:[Ne.body[D].keypoints[ae]?((a-1)*(Ne.body[D].keypoints[ae].position[0]||0)+(J.position[0]||0))/a:J.position[0],Ne.body[D].keypoints[ae]?((a-1)*(Ne.body[D].keypoints[ae].position[1]||0)+(J.position[1]||0))/a:J.position[1],Ne.body[D].keypoints[ae]?((a-1)*(Ne.body[D].keypoints[ae].position[2]||0)+(J.position[2]||0))/a:J.position[2]],positionRaw:[Ne.body[D].keypoints[ae]?((a-1)*(Ne.body[D].keypoints[ae].positionRaw[0]||0)+(J.positionRaw[0]||0))/a:J.positionRaw[0],Ne.body[D].keypoints[ae]?((a-1)*(Ne.body[D].keypoints[ae].positionRaw[1]||0)+(J.positionRaw[1]||0))/a:J.positionRaw[1],Ne.body[D].keypoints[ae]?((a-1)*(Ne.body[D].keypoints[ae].positionRaw[2]||0)+(J.positionRaw[2]||0))/a:J.positionRaw[2]],distance:[Ne.body[D].keypoints[ae]?((a-1)*(((de=Ne.body[D].keypoints[ae].distance)==null?void 0:de[0])||0)+(((be=J.distance)==null?void 0:be[0])||0))/a:(ve=J.distance)==null?void 0:ve[0],Ne.body[D].keypoints[ae]?((a-1)*(((Ee=Ne.body[D].keypoints[ae].distance)==null?void 0:Ee[1])||0)+((($e=J.distance)==null?void 0:$e[1])||0))/a:(ze=J.distance)==null?void 0:ze[1],Ne.body[D].keypoints[ae]?((a-1)*(((We=Ne.body[D].keypoints[ae].distance)==null?void 0:We[2])||0)+(((Ke=J.distance)==null?void 0:Ke[2])||0))/a:(ot=J.distance)==null?void 0:ot[2]]}}),Q={},ie={connected:{}};(o=(i=t.body)==null?void 0:i.modelPath)!=null&&o.includes("efficientpose")?ie=s1:(u=(l=t.body)==null?void 0:l.modelPath)!=null&&u.includes("blazepose")?ie=e1:(h=(d=t.body)==null?void 0:d.modelPath)!=null&&h.includes("movenet")&&(ie=dc);for(let[J,ae]of Object.entries(ie.connected)){let de=[];for(let be=0;be<ae.length-1;be++){let ve=re.find($e=>$e.part===ae[be]),Ee=re.find($e=>$e.part===ae[be+1]);ve&&Ee&&de.push([ve.position,Ee.position])}Q[J]=de}Ne.body[D]={...e.body[D],box:Y,boxRaw:V,keypoints:re,annotations:Q}}if(!Ne.hand||e.hand.length!==Ne.hand.length)Ne.hand=JSON.parse(JSON.stringify(e.hand));else for(let D=0;D<e.hand.length;D++){let Y=e.hand[D].box.map((ie,J)=>((a-1)*Ne.hand[D].box[J]+ie)/a),V=e.hand[D].boxRaw.map((ie,J)=>((a-1)*Ne.hand[D].boxRaw[J]+ie)/a);Ne.hand[D].keypoints.length!==e.hand[D].keypoints.length&&(Ne.hand[D].keypoints=e.hand[D].keypoints);let re=e.hand[D].keypoints&&e.hand[D].keypoints.length>0?e.hand[D].keypoints.map((ie,J)=>ie.map((ae,de)=>((a-1)*(Ne.hand[D].keypoints[J][de]||1)+(ae||0))/a)):[],Q={};if(Object.keys(Ne.hand[D].annotations).length!==Object.keys(e.hand[D].annotations).length)Ne.hand[D].annotations=e.hand[D].annotations,Q=Ne.hand[D].annotations;else if(e.hand[D].annotations)for(let ie of Object.keys(e.hand[D].annotations))Q[ie]=e.hand[D].annotations[ie]&&e.hand[D].annotations[ie][0]?e.hand[D].annotations[ie].map((J,ae)=>J.map((de,be)=>((a-1)*Ne.hand[D].annotations[ie][ae][be]+de)/a)):null;Ne.hand[D]={...e.hand[D],box:Y,boxRaw:V,keypoints:re,annotations:Q}}if(!Ne.face||e.face.length!==Ne.face.length)Ne.face=JSON.parse(JSON.stringify(e.face));else for(let D=0;D<e.face.length;D++){let Y=e.face[D].box.map((re,Q)=>((a-1)*Ne.face[D].box[Q]+re)/a),V=e.face[D].boxRaw.map((re,Q)=>((a-1)*Ne.face[D].boxRaw[Q]+re)/a);if(e.face[D].rotation){let re={matrix:[0,0,0,0,0,0,0,0,0],angle:{roll:0,yaw:0,pitch:0},gaze:{bearing:0,strength:0}};re.matrix=(p=e.face[D].rotation)==null?void 0:p.matrix,re.angle={roll:((a-1)*(((m=(c=Ne.face[D].rotation)==null?void 0:c.angle)==null?void 0:m.roll)||0)+(((g=(f=e.face[D].rotation)==null?void 0:f.angle)==null?void 0:g.roll)||0))/a,yaw:((a-1)*(((A=(y=Ne.face[D].rotation)==null?void 0:y.angle)==null?void 0:A.yaw)||0)+(((b=(x=e.face[D].rotation)==null?void 0:x.angle)==null?void 0:b.yaw)||0))/a,pitch:((a-1)*(((I=(w=Ne.face[D].rotation)==null?void 0:w.angle)==null?void 0:I.pitch)||0)+(((E=(T=e.face[D].rotation)==null?void 0:T.angle)==null?void 0:E.pitch)||0))/a},re.gaze={bearing:((a-1)*(((F=(R=Ne.face[D].rotation)==null?void 0:R.gaze)==null?void 0:F.bearing)||0)+(((S=($=e.face[D].rotation)==null?void 0:$.gaze)==null?void 0:S.bearing)||0))/a,strength:((a-1)*(((O=(z=Ne.face[D].rotation)==null?void 0:z.gaze)==null?void 0:O.strength)||0)+(((K=(j=e.face[D].rotation)==null?void 0:j.gaze)==null?void 0:K.strength)||0))/a},Ne.face[D]={...e.face[D],rotation:re,box:Y,boxRaw:V}}Ne.face[D]={...e.face[D],box:Y,boxRaw:V}}if(!Ne.object||e.object.length!==Ne.object.length)Ne.object=JSON.parse(JSON.stringify(e.object));else for(let D=0;D<e.object.length;D++){let Y=e.object[D].box.map((re,Q)=>((a-1)*Ne.object[D].box[Q]+re)/a),V=e.object[D].boxRaw.map((re,Q)=>((a-1)*Ne.object[D].boxRaw[Q]+re)/a);Ne.object[D]={...e.object[D],box:Y,boxRaw:V}}if(e.persons){let D=e.persons;if(!Ne.persons||D.length!==Ne.persons.length)Ne.persons=JSON.parse(JSON.stringify(D));else for(let Y=0;Y<D.length;Y++)Ne.persons[Y].box=D[Y].box.map((V,re)=>((a-1)*Ne.persons[Y].box[re]+V)/a)}e.gesture&&(Ne.gesture=e.gesture);let s=oe();return xb=he.perfadd?xb+Math.round(s-r):Math.round(s-r),e.performance&&(Ne.performance={...e.performance,interpolate:xb}),Ne}var wb={};ws(wb,{distance:()=>fc,match:()=>vb,similarity:()=>bb});function fc(e,t,r={order:2,multiplier:25}){let n=0;for(let a=0;a<e.length;a++){let s=!r.order||r.order===2?e[a]-t[a]:Math.abs(e[a]-t[a]);n+=!r.order||r.order===2?s*s:s**r.order}return(r.multiplier||20)*n}var dE=(e,t,r,n)=>{if(e===0)return 1;let a=t===2?Math.sqrt(e):e**(1/t),s=(1-a/100-r)/(n-r);return Math.max(Math.min(s,1),0)};function bb(e,t,r={order:2,multiplier:25,min:.2,max:.8}){let n=fc(e,t,r);return dE(n,r.order||2,r.min||0,r.max||1)}function vb(e,t,r={order:2,multiplier:25,threshold:0,min:.2,max:.8}){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 n=Number.MAX_SAFE_INTEGER,a=-1;for(let i=0;i<t.length;i++){let o=fc(e,t[i],r);if(o<n&&(n=o,a=i),n<(r.threshold||0))break}let s=dE(n,r.order||2,r.min||0,r.max||1);return{index:a,distance:n,similarity:s}}function pE(e,t,r,n,a){var o,l,u,d,h,p,c,m,f,g,y,A,x,b,w,I;let s=0,i=[];for(let T of e){let E={id:s++,face:T,body:null,hands:{left:null,right:null},gestures:[],box:[0,0,0,0]};for(let O of t)T.box[0]>O.box[0]&&T.box[0]<O.box[0]+O.box[2]&&T.box[1]+T.box[3]>O.box[1]&&T.box[1]+T.box[3]<O.box[1]+O.box[3]&&(E.body=O);if(E.body)for(let O of r)O.box[0]+O.box[2]>E.body.box[0]&&O.box[0]+O.box[2]<E.body.box[0]+E.body.box[2]&&O.box[1]+O.box[3]>E.body.box[1]&&O.box[1]+O.box[3]<E.body.box[1]+E.body.box[3]&&E.hands&&(E.hands.left=O),O.box[0]<E.body.box[0]+E.body.box[2]&&O.box[0]>E.body.box[0]&&O.box[1]+O.box[3]>E.body.box[1]&&O.box[1]+O.box[3]<E.body.box[1]+E.body.box[3]&&E.hands&&(E.hands.right=O);for(let O of n)O.face!==void 0&&O.face===T.id?(o=E.gestures)==null||o.push(O):O.iris!==void 0&&O.iris===T.id?(l=E.gestures)==null||l.push(O):O.body!==void 0&&O.body===((u=E.body)==null?void 0:u.id)?(d=E.gestures)==null||d.push(O):O.hand!==void 0&&O.hand===((p=(h=E.hands)==null?void 0:h.left)==null?void 0:p.id)?(c=E.gestures)==null||c.push(O):O.hand!==void 0&&O.hand===((f=(m=E.hands)==null?void 0:m.right)==null?void 0:f.id)&&((g=E.gestures)==null||g.push(O));let R=[],F=[],$=O=>{O&&O.length===4&&(R.push(O[0],O[0]+O[2]),F.push(O[1],O[1]+O[3]))};$((y=E.face)==null?void 0:y.box),$((A=E.body)==null?void 0:A.box),$((b=(x=E.hands)==null?void 0:x.left)==null?void 0:b.box),$((I=(w=E.hands)==null?void 0:w.right)==null?void 0:I.box);let S=Math.min(...R),z=Math.min(...F);E.box=[S,z,Math.max(...R)-S,Math.max(...F)-z],a&&a[1]&&a[2]&&(E.boxRaw=[E.box[0]/a[2],E.box[1]/a[1],E.box[2]/a[2],E.box[3]/a[1]]),i.push(E)}return i}var E1=`
|
|
/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==`,R1=`
|
|
/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 dAe(e){let t=(a,s="application/octet-stream")=>fetch(`data:${s};base64,${a}`).then(i=>i.blob()),r,n;switch(e.config.warmup){case"face":r=await t(E1);break;case"body":case"full":r=await t(R1);break;default:r=null}if(r){let a=await createImageBitmap(r);n=await e.detect(a,e.config),a.close()}return n}async function pAe(e){return new Promise(t=>{let r;switch(e.config.warmup){case"face":r="data:image/jpeg;base64,"+E1;break;case"full":case"body":r="data:image/jpeg;base64,"+R1;break;default:r=null}let n;if(typeof Image!="undefined")n=new Image;else if(he.Image)n=new he.Image;else return;n.onload=async()=>{let a=Zr(n.naturalWidth,n.naturalHeight);if(!a)se("Warmup: Canvas not found"),t(void 0);else{let s=a.getContext("2d");s&&s.drawImage(n,0,0);let i=await e.image(a),o=await e.detect(i.tensor,e.config);t(o)}},r?n.src=r:t(void 0)})}async function hAe(e){let t=a=>Buffer.from(a,"base64"),r;e.config.warmup==="face"?r=t(E1):r=t(R1);let n;if("node"in Ue){let a=(void 0).decodeJpeg(r),s=a.expandDims(0);e.tf.dispose(a),n=await e.detect(s,e.config),e.tf.dispose(s)}else e.config.debug&&se("Warmup tfjs-node not loaded");return n}async function cAe(e){let t;return typeof createImageBitmap=="function"?t=await dAe(e):typeof Image!="undefined"||he.Canvas!==void 0?t=await pAe(e):t=await hAe(e),t}async function fAe(e){let t=Hr(),r=Dn();if(t!=="webgl"&&t!=="humangl"||!r||!r.checkCompileCompletion)return;Z().set("ENGINE_COMPILE_ONLY",!0);let n=Xt().state.numTensors,a=[];for(let[o,l]of Object.entries(e).filter(([u,d])=>u!==null&&d!==null)){let u=l.inputs&&l.inputs[0]&&l.inputs[0].shape?[...l.inputs[0].shape]:[1,64,64,3],d=l.inputs&&l.inputs[0]&&l.inputs[0].dtype?l.inputs[0].dtype:"float32";for(let p=0;p<u.length;p++)u[p]===-1&&(u[p]=p===0?1:64);let h=Ot(u,d);try{let p=l.execute(h);a.push(o),Array.isArray(p)?p.forEach(c=>ee(c)):ee(p)}catch(p){se("compile fail model:",o)}ee(h)}let s=await r.checkCompileCompletionAsync();r.getUniformLocations(),se("compile pass models:",a),se("compile pass kernels:",s.length),Z().set("ENGINE_COMPILE_ONLY",!1);let i=Xt().state.numTensors;i-n>0&&se("tensor leak:",i-n)}async function hE(e,t){let r=oe();return e.state="warmup",t&&(e.config=Gt(e.config,t)),!e.config.warmup||e.config.warmup.length===0||e.config.warmup==="none"?{face:[],body:[],hand:[],gesture:[],object:[],performance:e.performance,timestamp:oe(),persons:[],error:null}:new Promise(async n=>{await fAe(e.models);let a=await cAe(e),s=oe();e.config.debug&&se("warmup",e.config.warmup,Math.round(s-r),"ms"),e.emit("warmup"),n(a)})}var up,mc,gc,$1,kb=class{constructor(t){fe(this,"version");fe(this,"config");fe(this,"result");fe(this,"state");fe(this,"process");fe(this,"tf");fe(this,"env");fe(this,"draw");fe(this,"models");fe(this,"events");fe(this,"faceTriangulation");fe(this,"faceUVMap");fe(this,"performance");kp(this,up,void 0);kp(this,mc,void 0);kp(this,gc,void 0);fe(this,"gl");fe(this,"analyze",(...t)=>{if(!wp(this,mc))return;let r=this.tf.engine().state.numTensors,n=wp(this,up);Ip(this,up,r);let a=r-n;a!==0&&se(...t,a)});kp(this,$1,t=>{if(!wp(this,gc))return null;if(!t)return"input is not defined";if(this.env.node&&!(t instanceof nt))return"input must be a tensor";try{this.tf.getBackend()}catch(r){return"backend not loaded"}return null});fe(this,"similarity",bb);fe(this,"distance",fc);fe(this,"match",vb);fe(this,"emit",t=>{var r;this.events&&this.events.dispatchEvent&&((r=this.events)==null||r.dispatchEvent(new Event(t)))});fe(this,"getModelStats",()=>ob());var n;this.env=he;let r=(((n=nc)==null?void 0:n.tfjs)||Zy).replace(/-(.*)/,"");ks.wasmPath=`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${r}/dist/`,ks.modelBasePath=he.browser?"../models/":"file://models/",ks.backend=he.browser?"humangl":"tensorflow",this.version=ZA,Object.defineProperty(this,"version",{value:ZA}),this.config=JSON.parse(JSON.stringify(ks)),Object.seal(this.config),this.config.cacheModels=typeof indexedDB!="undefined",t&&(this.config=Gt(this.config,t)),BC(this.config),this.tf=Ue,this.state="idle",Ip(this,up,0),Ip(this,mc,!1),Ip(this,gc,!1),this.performance={},this.events=typeof EventTarget!="undefined"?new EventTarget:void 0,this.models=new cc,this.draw={options:_r,canvas:(a,s)=>fb(a,s),face:(a,s,i)=>np(a,s,i),body:(a,s,i)=>ap(a,s,i),hand:(a,s,i)=>sp(a,s,i),gesture:(a,s,i)=>op(a,s,i),object:(a,s,i)=>ip(a,s,i),person:(a,s,i)=>cb(a,s,i),all:(a,s,i)=>mb(a,s,i)},this.result={face:[],body:[],hand:[],gesture:[],object:[],performance:{},timestamp:0,persons:[],error:null},this.process={tensor:null,canvas:null},this.faceTriangulation=JT,this.faceUVMap=QT,this.gl=Rt,this.emit("create")}reset(){let t=this.config.backend;this.config=JSON.parse(JSON.stringify(ks)),this.config.backend=t}validate(t){return hg(ks,t||this.config)}now(){return oe()}image(t,r=!0){return Ud(t,this.config,r)}async segmentation(t,r){return JN(t,r,this.config)}enhance(t){return Mx(t)}compare(t,r){return LC(this.config,t,r)}async init(){await N1(this,!0),await this.tf.ready()}async load(t){this.state="load";let r=oe(),n=Object.values(this.models).filter(i=>i).length;t&&(this.config=Gt(this.config,t)),this.env.initial&&(this.config.debug&&se(`version: ${this.version}`),this.config.debug&&se(`tfjs version: ${this.tf.version["tfjs-core"]}`),await N1(this)||se("error: backend check failed"),await xd(),this.env.browser&&(this.config.debug&&se("configuration:",this.config),this.config.debug&&se("environment:",this.env),this.config.debug&&se("tf flags:",this.tf.ENV.flags))),await lb(this),this.env.initial&&this.config.debug&&se("tf engine state:",this.tf.engine().state.numBytes,"bytes",this.tf.engine().state.numTensors,"tensors"),this.env.initial=!1,Object.values(this.models).filter(i=>i).length!==n&&(await ub(this),this.emit("load"));let s=Math.trunc(oe()-r);s>(this.performance.loadModels||0)&&(this.performance.loadModels=this.env.perfadd?(this.performance.loadModels||0)+s:s)}next(t=this.result){return uE(t,this.config)}async warmup(t){let r=oe(),n=await hE(this,t),a=oe();return this.performance.warmup=Math.trunc(a-r),n}async profile(t,r){let n=await this.tf.profile(()=>this.detect(t,r)),a={};for(let o of n.kernels)a[o.name]?a[o.name]+=o.kernelTimeMs:a[o.name]=o.kernelTimeMs;let s=[];Object.entries(a).forEach(o=>s.push({name:o[0],ms:o[1]})),s.sort((o,l)=>l.ms-o.ms),s.length=20;let i={};for(let o of s)i[o.name]=o.ms;return i}async detect(t,r){return this.state="detect",new Promise(async n=>{var g,y,A,x,b,w,I,T,E,R,F,$,S,z,O,j,K,D,Y,V,re,Q;this.state="config";let a;this.config=Gt(this.config,r),this.state="check";let s=wp(this,$1).call(this,t);s&&(se(s,t),this.emit("error"),n({face:[],body:[],hand:[],gesture:[],object:[],performance:this.performance,timestamp:oe(),persons:[],error:s}));let i=oe();await N1(this),await this.load(),a=oe(),this.state="image";let o=await Ud(t,this.config);if(this.process=o,this.performance.inputProcess=this.env.perfadd?(this.performance.inputProcess||0)+Math.trunc(oe()-a):Math.trunc(oe()-a),this.analyze("Get Image:"),!o.tensor){this.config.debug&&se("could not convert input to tensor"),this.emit("error"),n({face:[],body:[],hand:[],gesture:[],object:[],performance:this.performance,timestamp:oe(),persons:[],error:"could not convert input to tensor"});return}this.emit("image"),a=oe(),this.config.skipAllowed=await DC(this.config,o.tensor),this.performance.totalFrames||(this.performance.totalFrames=0),this.performance.cachedFrames||(this.performance.cachedFrames=0),this.performance.totalFrames++,this.config.skipAllowed&&this.performance.cachedFrames++,this.performance.cacheCheck=this.env.perfadd?(this.performance.cacheCheck||0)+Math.trunc(oe()-a):Math.trunc(oe()-a),this.analyze("Check Changed:");let l=[],u=[],d=[],h=[];this.state="detect:face",this.config.async?(l=this.config.face.enabled?Ab(this,o.tensor):[],this.performance.face&&delete this.performance.face):(a=oe(),l=this.config.face.enabled?await Ab(this,o.tensor):[],this.performance.face=this.env.perfadd?(this.performance.face||0)+Math.trunc(oe()-a):Math.trunc(oe()-a)),this.config.async&&(this.config.body.maxDetected===-1||this.config.hand.maxDetected===-1)&&(l=await l),this.analyze("Start Body:"),this.state="detect:body";let p=this.config.body.maxDetected===-1?Gt(this.config,{body:{maxDetected:this.config.face.enabled?1*l.length:1}}):this.config;this.config.async?((g=this.config.body.modelPath)!=null&&g.includes("posenet")?u=this.config.body.enabled?ab(o.tensor,p):[]:(y=this.config.body.modelPath)!=null&&y.includes("blazepose")?u=this.config.body.enabled?gx(o.tensor,p):[]:(A=this.config.body.modelPath)!=null&&A.includes("efficientpose")?u=this.config.body.enabled?kx(o.tensor,p):[]:(x=this.config.body.modelPath)!=null&&x.includes("movenet")&&(u=this.config.body.enabled?Yx(o.tensor,p):[]),this.performance.body&&delete this.performance.body):(a=oe(),(b=this.config.body.modelPath)!=null&&b.includes("posenet")?u=this.config.body.enabled?await ab(o.tensor,p):[]:(w=this.config.body.modelPath)!=null&&w.includes("blazepose")?u=this.config.body.enabled?await gx(o.tensor,p):[]:(I=this.config.body.modelPath)!=null&&I.includes("efficientpose")?u=this.config.body.enabled?await kx(o.tensor,p):[]:(T=this.config.body.modelPath)!=null&&T.includes("movenet")&&(u=this.config.body.enabled?await Yx(o.tensor,p):[]),this.performance.body=this.env.perfadd?(this.performance.body||0)+Math.trunc(oe()-a):Math.trunc(oe()-a)),this.analyze("End Body:"),this.analyze("Start Hand:"),this.state="detect:hand";let c=this.config.hand.maxDetected===-1?Gt(this.config,{hand:{maxDetected:this.config.face.enabled?2*l.length:1}}):this.config;this.config.async?((R=(E=this.config.hand.detector)==null?void 0:E.modelPath)!=null&&R.includes("handdetect")?d=this.config.hand.enabled?Lx(o.tensor,c):[]:($=(F=this.config.hand.detector)==null?void 0:F.modelPath)!=null&&$.includes("handtrack")&&(d=this.config.hand.enabled?Ux(o.tensor,c):[]),this.performance.hand&&delete this.performance.hand):(a=oe(),(z=(S=this.config.hand.detector)==null?void 0:S.modelPath)!=null&&z.includes("handdetect")?d=this.config.hand.enabled?await Lx(o.tensor,c):[]:(j=(O=this.config.hand.detector)==null?void 0:O.modelPath)!=null&&j.includes("handtrack")&&(d=this.config.hand.enabled?await Ux(o.tensor,c):[]),this.performance.hand=this.env.perfadd?(this.performance.hand||0)+Math.trunc(oe()-a):Math.trunc(oe()-a)),this.analyze("End Hand:"),this.analyze("Start Object:"),this.state="detect:object",this.config.async?((K=this.config.object.modelPath)!=null&&K.includes("nanodet")?h=this.config.object.enabled?Qx(o.tensor,this.config):[]:(D=this.config.object.modelPath)!=null&&D.includes("centernet")&&(h=this.config.object.enabled?xx(o.tensor,this.config):[]),this.performance.object&&delete this.performance.object):(a=oe(),(Y=this.config.object.modelPath)!=null&&Y.includes("nanodet")?h=this.config.object.enabled?await Qx(o.tensor,this.config):[]:(V=this.config.object.modelPath)!=null&&V.includes("centernet")&&(h=this.config.object.enabled?await xx(o.tensor,this.config):[]),this.performance.object=this.env.perfadd?(this.performance.object||0)+Math.trunc(oe()-a):Math.trunc(oe()-a)),this.analyze("End Object:"),this.state="detect:await",this.config.async&&([l,u,d,h]=await Promise.all([l,u,d,h])),this.state="detect:gesture";let m=[];this.config.gesture.enabled&&(a=oe(),m=[...iE(l),...sE(u),...lE(d),...oE(l)],this.config.async?this.performance.gesture&&delete this.performance.gesture:this.performance.gesture=this.env.perfadd?(this.performance.gesture||0)+Math.trunc(oe()-a):Math.trunc(oe()-a)),this.performance.total=this.env.perfadd?(this.performance.total||0)+Math.trunc(oe()-i):Math.trunc(oe()-i);let f=((Q=(re=this.process)==null?void 0:re.tensor)==null?void 0:Q.shape)||[];this.result={face:l,body:u,hand:d,gesture:m,object:h,performance:this.performance,canvas:this.process.canvas,timestamp:Date.now(),error:null,get persons(){return pE(l,u,d,m,f)}},ee(o.tensor),this.emit("detect"),this.state="idle",n(this.result)})}};up=new WeakMap,mc=new WeakMap,gc=new WeakMap,$1=new WeakMap;return pR(gAe);})();
|
|
/**
|
|
* @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 2022 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 2022 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 2022 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 2022 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.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* Human main module
|
|
* @default Human Library
|
|
* @summary <https://github.com/vladmandic/human>
|
|
* @author <https://github.com/vladmandic>
|
|
* @copyright <https://github.com/vladmandic>
|
|
* @license 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 See the LICENSE file. */
|