diff --git a/README.md b/README.md
index 5806289d..2b5866d6 100644
--- a/README.md
+++ b/README.md
@@ -60,6 +60,7 @@ Check out [**Live Demo**](https://vladmandic.github.io/human/demo/index.html) ap
- [**Usage & Functions**](https://github.com/vladmandic/human/wiki/Usage)
- [**Configuration Details**](https://github.com/vladmandic/human/wiki/Configuration)
- [**Output Details**](https://github.com/vladmandic/human/wiki/Outputs)
+- [**Caching & Smoothing**](https://github.com/vladmandic/human/wiki/Caching)
- [**Face Recognition & Face Description**](https://github.com/vladmandic/human/wiki/Embedding)
- [**Gesture Recognition**](https://github.com/vladmandic/human/wiki/Gesture)
- [**Common Issues**](https://github.com/vladmandic/human/wiki/Issues)
diff --git a/TODO.md b/TODO.md
index 9c405006..e16da45a 100644
--- a/TODO.md
+++ b/TODO.md
@@ -2,16 +2,14 @@
## Work in Progress
-- `skipTime`: testing, documentation
-
### Exploring
-- Optical Flow:
-- TFLite Models:
-- Histogram Equalization: Regular, Adaptive, Contrast Limited
- Switch to custom `tfjs` for main `human` ESM bundle
+- Optical Flow:
+- Histogram Equalization: Regular, Adaptive, Contrast Limited
+- TFLite Models:
- Body segmentation: `robust-video-matting`
#### WebGPU
@@ -55,6 +53,7 @@ Object detection using CenterNet or NanoDet models is not working when using WAS
## Pending Release
- Update to TFJS 3.10.0
+- Time based caching
- Multiple bug fixes
- Utility class `human.env`
- Add `skipTime` in addition to `skipFrames`
diff --git a/demo/index.js b/demo/index.js
index e358eebe..1875f21f 100644
--- a/demo/index.js
+++ b/demo/index.js
@@ -1016,6 +1016,7 @@ async function main() {
// create instance of human
human = new Human(userConfig);
+ human.env.perfadd = true;
log('human version:', human.version);
// we've merged human defaults with user config and now lets store it back so it can be accessed by methods such as menu
diff --git a/dist/human.custom.esm.js b/dist/human.custom.esm.js
index 4f068824..c64fa574 100644
--- a/dist/human.custom.esm.js
+++ b/dist/human.custom.esm.js
@@ -4,47 +4,47 @@
author: '
*/
-var Og=Object.defineProperty;var vN=(e,t,n)=>t in e?Og(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var wN=e=>Og(e,"__esModule",{value:!0});var xa=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof require!="undefined"?require:t)[n]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var qp=(e,t)=>{wN(e);for(var n in t)Og(e,n,{get:t[n],enumerable:!0})};var pe=(e,t,n)=>(vN(e,typeof t!="symbol"?t+"":t,n),n),Qb=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var Ec=(e,t,n)=>(Qb(e,t,"read from private field"),n?n.call(e):t.get(e)),Rc=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},$c=(e,t,n,s)=>(Qb(e,t,"write to private field"),s?s.call(e,n):t.set(e,n),n);function at(e,t){let n=e.endsWith("/")?"":"/",r=t.startsWith(".")||t.startsWith("/")||t.startsWith("http:")||t.startsWith("https:")||t.startsWith("file:")?`${t}`:`${e}${n}${t}`;if(!r.toLocaleLowerCase().includes(".json"))throw new Error(`modelpath error: ${r} expecting json file`);return r}function ae(...e){let t=new Date,n=`${t.getHours().toString().padStart(2,"0")}:${t.getMinutes().toString().padStart(2,"0")}:${t.getSeconds().toString().padStart(2,"0")}.${t.getMilliseconds().toString().padStart(3,"0")}`;e&&console.log(n,"Human:",...e)}var Ae=()=>typeof performance!="undefined"?performance.now():parseInt((Number(process.hrtime.bigint())/1e3/1e3).toString());function Mg(e,t,n="config",s=[]){for(let r of Object.keys(t))if(typeof t[r]=="object")Mg(e[r],t[r],r,s);else{let a=e&&typeof e[r]!="undefined";a||s.push({reason:"unknown property",where:`${n}.${r} = ${t[r]}`});let o=e&&typeof e[r]==typeof t[r];a&&!o&&s.push({reason:"property type mismatch",where:`${n}.${r} = ${t[r]}`,expected:typeof e[r]})}return t.debug&&n==="config"&&s.length>0&&ae("invalid configuration",s),s}function $n(...e){let t=n=>n&&typeof n=="object";return e.reduce((n,s)=>(Object.keys(s||{}).forEach(r=>{let a=n[r],o=s[r];Array.isArray(a)&&Array.isArray(o)?n[r]=a.concat(...o):t(a)&&t(o)?n[r]=$n(a,o):n[r]=o}),n),{})}var Jo={backend:"",modelBasePath:"",wasmPath:"",debug:!0,async:!0,warmup:"full",cacheSensitivity:.75,skipFrame:!1,filter:{enabled:!0,width:0,height:0,flip:!1,return:!0,brightness:0,contrast:0,sharpness:0,blur:0,saturation:0,hue:0,negative:!1,sepia:!1,vintage:!1,kodachrome:!1,technicolor:!1,polaroid:!1,pixelate:0},gesture:{enabled:!0},face:{enabled:!0,detector:{modelPath:"blazeface.json",rotation:!0,maxDetected:1,skipFrames:11,skipTime:2e3,minConfidence:.2,iouThreshold:.1,return:!1},mesh:{enabled:!0,modelPath:"facemesh.json"},iris:{enabled:!0,modelPath:"iris.json"},emotion:{enabled:!0,minConfidence:.1,skipFrames:12,skipTime:2e3,modelPath:"emotion.json"},description:{enabled:!0,modelPath:"faceres.json",skipFrames:13,skipTime:2e3,minConfidence:.1},antispoof:{enabled:!1,skipFrames:14,skipTime:2e3,modelPath:"antispoof.json"}},body:{enabled:!0,modelPath:"movenet-lightning.json",detector:{modelPath:""},maxDetected:-1,minConfidence:.3,skipFrames:1,skipTime:2e3},hand:{enabled:!0,rotation:!0,skipFrames:2,skipTime:2e3,minConfidence:.5,iouThreshold:.2,maxDetected:-1,landmarks:!0,detector:{modelPath:"handtrack.json"},skeleton:{modelPath:"handskeleton.json"}},object:{enabled:!1,modelPath:"mb3-centernet.json",minConfidence:.2,iouThreshold:.4,maxDetected:10,skipFrames:15,skipTime:2e3},segmentation:{enabled:!1,modelPath:"selfie.json",blur:8}};var wl={};qp(wl,{Abs:()=>ni,Acos:()=>Vl,Acosh:()=>Ul,AdadeltaOptimizer:()=>ff,AdagradOptimizer:()=>mf,AdamOptimizer:()=>gf,AdamaxOptimizer:()=>Af,Add:()=>Hr,AddN:()=>wa,All:()=>Gl,Any:()=>Hl,ArgMax:()=>ka,ArgMin:()=>jl,Asin:()=>ql,Asinh:()=>Xl,Atan:()=>Kl,Atan2:()=>Yl,Atanh:()=>Zl,AvgPool:()=>Ia,AvgPool3D:()=>Fc,AvgPool3DGrad:()=>th,AvgPoolGrad:()=>eh,BackendWasm:()=>y6,BatchMatMul:()=>Sa,BatchToSpaceND:()=>si,Bincount:()=>nh,BroadcastArgs:()=>sh,BroadcastTo:()=>m5,Callback:()=>Tk,CallbackList:()=>mw,Cast:()=>Ca,Ceil:()=>Ta,ClipByValue:()=>jr,Complex:()=>Oc,ComplexAbs:()=>Mc,Concat:()=>ri,Conv2D:()=>Na,Conv2DBackpropFilter:()=>rh,Conv2DBackpropInput:()=>Ea,Conv3D:()=>zc,Conv3DBackpropFilterV2:()=>ah,Conv3DBackpropInputV2:()=>oh,Cos:()=>Ra,Cosh:()=>$a,CropAndResize:()=>oi,Cumsum:()=>ai,CustomCallback:()=>Aw,DataStorage:()=>Dc,DenseBincount:()=>ih,DepthToSpace:()=>ii,DepthwiseConv2dNative:()=>Da,DepthwiseConv2dNativeBackpropFilter:()=>lh,DepthwiseConv2dNativeBackpropInput:()=>uh,Diag:()=>ch,Dilation2D:()=>Lc,Dilation2DBackpropFilter:()=>ph,Dilation2DBackpropInput:()=>dh,ENV:()=>Ir,EarlyStopping:()=>Ek,Einsum:()=>Bc,Elu:()=>Pa,EluGrad:()=>hh,Environment:()=>h5,Equal:()=>li,Erf:()=>Jl,Exp:()=>Fa,ExpandDims:()=>ui,Expm1:()=>ci,FFT:()=>fh,Fill:()=>Ql,FlipLeftRight:()=>di,Floor:()=>Oa,FloorDiv:()=>Ma,FromPixels:()=>Kc,FusedBatchNorm:()=>za,FusedConv2D:()=>mo,FusedDepthwiseConv2D:()=>go,GPGPUContext:()=>vm,GatherNd:()=>hi,GatherV2:()=>pi,GraphModel:()=>i7,Greater:()=>fi,GreaterEqual:()=>La,History:()=>gw,IFFT:()=>mh,Identity:()=>Ba,Imag:()=>Wc,InputSpec:()=>Yt,IsFinite:()=>eu,IsInf:()=>tu,IsNan:()=>nu,KernelBackend:()=>Ll,LRN:()=>Uc,LRNGrad:()=>Ah,LayerVariable:()=>cw,LayersModel:()=>na,LeakyRelu:()=>mi,Less:()=>gi,LessEqual:()=>Ai,LinSpace:()=>gh,Log:()=>Wa,Log1p:()=>su,LogSoftmax:()=>g5,LogicalAnd:()=>yi,LogicalNot:()=>ru,LogicalOr:()=>Vc,MathBackendCPU:()=>xy,MathBackendWebGL:()=>Kd,Max:()=>Va,MaxPool:()=>Ga,MaxPool3D:()=>Gc,MaxPool3DGrad:()=>xh,MaxPoolGrad:()=>yh,MaxPoolWithArgmax:()=>bh,Maximum:()=>Ua,Mean:()=>Ha,Min:()=>ja,Minimum:()=>qa,MirrorPad:()=>Xa,Mod:()=>au,MomentumOptimizer:()=>yf,Multinomial:()=>vh,Multiply:()=>Ka,Neg:()=>xi,NonMaxSuppressionV3:()=>vi,NonMaxSuppressionV4:()=>ou,NonMaxSuppressionV5:()=>wi,NotEqual:()=>bi,OP_SCOPE_SUFFIX:()=>$5,OneHot:()=>Ii,OnesLike:()=>ki,Optimizer:()=>Qr,Pack:()=>Si,PadV2:()=>Za,Pool:()=>dE,Pow:()=>Ya,Prelu:()=>Ja,Prod:()=>Ci,RMSPropOptimizer:()=>xf,RNN:()=>sa,Range:()=>iu,Rank:()=>Xg,Real:()=>Hc,RealDiv:()=>_a,Reciprocal:()=>lu,Reduction:()=>Vn,Relu:()=>Qa,Relu6:()=>to,Reshape:()=>Ti,ResizeBilinear:()=>eo,ResizeBilinearGrad:()=>kh,ResizeNearestNeighbor:()=>uu,ResizeNearestNeighborGrad:()=>wh,Reverse:()=>Ni,RotateWithOffset:()=>Vi,Round:()=>Ei,Rsqrt:()=>no,SGDOptimizer:()=>xd,ScatterNd:()=>Ri,Select:()=>$i,Selu:()=>cu,Sequential:()=>Gf,Sigmoid:()=>ro,Sign:()=>du,Sin:()=>so,Sinh:()=>_i,Slice:()=>Di,Softmax:()=>io,Softplus:()=>pu,SpaceToBatchND:()=>Pi,SparseFillEmptyRows:()=>Ih,SparseReshape:()=>Sh,SparseSegmentMean:()=>Ch,SparseSegmentSum:()=>Th,SparseToDense:()=>jc,SplitV:()=>Fi,Sqrt:()=>ao,Square:()=>hu,SquaredDifference:()=>lo,Step:()=>ho,StridedSlice:()=>Oi,StringNGrams:()=>qc,StringSplit:()=>Nh,StringToHashBucketFast:()=>Eh,Sub:()=>uo,Sum:()=>oo,SymbolicTensor:()=>fr,Tan:()=>Mi,Tanh:()=>co,Tensor:()=>Ye,TensorBuffer:()=>sn,Tile:()=>qr,TopK:()=>zi,Transform:()=>Li,Transpose:()=>po,Unique:()=>Rh,Unpack:()=>Bi,UnsortedSegmentSum:()=>Xc,Variable:()=>sd,ZerosLike:()=>Wi,_FusedMatMul:()=>fo,abs:()=>rn,acos:()=>A3,acosh:()=>y3,add:()=>ie,addN:()=>Vh,all:()=>T2,any:()=>Uh,argMax:()=>Hs,argMin:()=>x3,asin:()=>b3,asinh:()=>v3,atan:()=>w3,atan2:()=>k3,atanh:()=>I3,avgPool:()=>Hh,avgPool3d:()=>R2,backend:()=>Tr,backend_util:()=>N,basicLSTMCell:()=>jR,batchNorm:()=>wu,batchNorm2d:()=>N3,batchNorm3d:()=>E3,batchNorm4d:()=>R3,batchToSpaceND:()=>jh,bincount:()=>$2,booleanMaskAsync:()=>aP,broadcastArgs:()=>$3,broadcastTo:()=>ud,browser:()=>Gs,buffer:()=>Le,callbacks:()=>bV,cast:()=>de,ceil:()=>D3,clipByValue:()=>fs,clone:()=>or,complex:()=>yo,concat:()=>It,concat1d:()=>_3,concat2d:()=>ku,concat3d:()=>P3,concat4d:()=>F3,constraints:()=>Uv,conv1d:()=>D2,conv2d:()=>ko,conv2dTranspose:()=>P2,conv3d:()=>F2,conv3dTranspose:()=>M3,copyRegisteredKernels:()=>fE,cos:()=>qh,cosh:()=>O2,cosineWindow:()=>i1,cumsum:()=>M2,customGrad:()=>Er,data:()=>l7,denseBincount:()=>z3,deprecationWarn:()=>I2,depthToSpace:()=>L3,depthwiseConv2d:()=>cd,deregisterOp:()=>wV,device_util:()=>gu,diag:()=>w$,dilation2d:()=>B3,disableDeprecationWarnings:()=>lR,dispose:()=>Q,disposeVariables:()=>uR,div:()=>he,divNoNan:()=>W3,dot:()=>R$,dropout:()=>Av,einsum:()=>V3,elu:()=>dd,enableDebugMode:()=>iR,enableProdMode:()=>m3,enclosingPowerOfTwo:()=>yv,engine:()=>ss,env:()=>K,equal:()=>Cs,erf:()=>U3,exp:()=>Ts,expandDims:()=>Kt,expm1:()=>G3,eye:()=>z2,fft:()=>af,fill:()=>Iu,findBackend:()=>S2,findBackendFactory:()=>hR,floor:()=>pd,floorDiv:()=>C2,forceHalfFloat:()=>zS,fused:()=>So,gather:()=>Su,gatherND:()=>gv,gather_util:()=>A2,getBackend:()=>ir,getGradient:()=>Gg,getKernel:()=>$h,getKernelsForBackend:()=>Xr,getThreadsCount:()=>q0e,gpgpu_util:()=>dS,grad:()=>tD,grads:()=>nD,greater:()=>ms,greaterEqual:()=>Yi,ifft:()=>gd,imag:()=>Xh,image:()=>$e,inTopKAsync:()=>gP,initializers:()=>Zv,input:()=>Bw,io:()=>ns,irfft:()=>t1,isFinite:()=>H$,isInf:()=>q$,isNaN:()=>H3,keep:()=>yn,kernel_impls:()=>Xs,layers:()=>iw,leakyRelu:()=>Kh,less:()=>L2,lessEqual:()=>Ji,linalg:()=>Nv,linspace:()=>j3,loadGraphModel:()=>st,loadLayersModel:()=>$B,localResponseNormalization:()=>q3,log:()=>Ns,log1p:()=>Zh,logSigmoid:()=>lD,logSoftmax:()=>B2,logSumExp:()=>J3,logicalAnd:()=>lr,logicalNot:()=>Jh,logicalOr:()=>U2,logicalXor:()=>bD,losses:()=>eO,matMul:()=>He,math:()=>K5,max:()=>rs,maxPool:()=>Qh,maxPool3d:()=>G2,maxPoolWithArgmax:()=>Q3,maximum:()=>Yr,mean:()=>Wt,memory:()=>Bh,meshgrid:()=>CD,metrics:()=>Ik,min:()=>ef,minimum:()=>hd,mirrorPad:()=>ev,mod:()=>tv,model:()=>EB,models:()=>Sk,moments:()=>tf,movingAverage:()=>lP,mul:()=>W,multiRNNCell:()=>PD,multinomial:()=>nv,neg:()=>Ot,nextFrame:()=>Ev,norm:()=>a1,notEqual:()=>Tu,oneHot:()=>id,ones:()=>gs,onesLike:()=>Es,op:()=>V,outerProduct:()=>LD,pad:()=>qs,pad1d:()=>VD,pad2d:()=>GD,pad3d:()=>jD,pad4d:()=>XD,pool:()=>QD,pow:()=>Io,prelu:()=>sf,print:()=>U5,prod:()=>H2,profile:()=>cR,rand:()=>r_,randomGamma:()=>l_,randomNormal:()=>sv,randomUniform:()=>Nu,range:()=>Eu,ready:()=>Wh,real:()=>fd,reciprocal:()=>rv,registerBackend:()=>Ki,registerCallbackConstructor:()=>DB,registerGradient:()=>A5,registerKernel:()=>Kr,registerOp:()=>vV,regularizers:()=>Ck,relu:()=>Rr,relu6:()=>X2,removeBackend:()=>pR,reshape:()=>G,reverse:()=>Rs,reverse1d:()=>A_,reverse2d:()=>x_,reverse3d:()=>v_,reverse4d:()=>k_,rfft:()=>of,round:()=>K2,rsqrt:()=>Z2,scalar:()=>Ee,scatterND:()=>mv,scatter_util:()=>y2,selu:()=>Y2,separableConv2d:()=>av,sequential:()=>RB,serialization:()=>le,setBackend:()=>g3,setPlatform:()=>fR,setThreadsCount:()=>j0e,setWasmPath:()=>H0e,setWasmPaths:()=>b6,setWebGLContext:()=>pm,setdiff1dAsync:()=>ov,shared:()=>om,sigmoid:()=>hs,sign:()=>iv,signal:()=>QF,sin:()=>J2,sinh:()=>Q2,slice:()=>_e,slice1d:()=>rf,slice2d:()=>e1,slice3d:()=>Ru,slice4d:()=>md,slice_util:()=>An,softmax:()=>$u,softplus:()=>Cu,spaceToBatchND:()=>nf,sparse:()=>yd,sparseToDense:()=>o1,spectral:()=>JF,split:()=>Sn,sqrt:()=>_n,square:()=>xt,squaredDifference:()=>n1,squeeze:()=>pt,stack:()=>Pn,step:()=>Ad,stridedSlice:()=>lv,string:()=>hf,sub:()=>ye,sum:()=>Ie,sumOutType:()=>rd,tan:()=>uv,tanh:()=>vu,tensor:()=>Gt,tensor1d:()=>Zt,tensor2d:()=>ur,tensor3d:()=>Z5,tensor4d:()=>K_,tensor5d:()=>Z_,tensor6d:()=>Y_,tensor_util:()=>rr,test_util:()=>p3,tidy:()=>j,tile:()=>js,time:()=>dR,topk:()=>cv,train:()=>tl,transpose:()=>et,truncatedNormal:()=>lf,unique:()=>s1,unregisterGradient:()=>hE,unregisterKernel:()=>pE,unsortedSegmentSum:()=>dv,unstack:()=>as,upcastType:()=>Bn,util:()=>v,valueAndGrad:()=>sD,valueAndGrads:()=>rD,variable:()=>pv,variableGrads:()=>X3,version:()=>w6,version_converter:()=>SU,version_core:()=>up,version_cpu:()=>dH,version_layers:()=>U1,version_wasm:()=>X0e,version_webgl:()=>zJ,webgl:()=>LJ,webgl_util:()=>FI,webgpu:()=>bC,where:()=>Wn,whereAsync:()=>r1,zeros:()=>Ht,zerosLike:()=>tt});var zl=(e=>typeof xa!="undefined"?xa:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof xa!="undefined"?xa:t)[n]}):e)(function(e){if(typeof xa!="undefined")return xa.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')}),kN=Object.create,Xp=Object.defineProperty,IN=Object.getOwnPropertyDescriptor,SN=Object.getOwnPropertyNames,CN=Object.getPrototypeOf,TN=Object.prototype.hasOwnProperty,e5=e=>Xp(e,"__esModule",{value:!0}),Ws=(e=>typeof zl!="undefined"?zl:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof zl!="undefined"?zl:t)[n]}):e)(function(e){if(typeof zl!="undefined")return zl.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')}),ts=(e,t)=>function(){return t||(0,e[Object.keys(e)[0]])((t={exports:{}}).exports,t),t.exports},ze=(e,t)=>{e5(e);for(var n in t)Xp(e,n,{get:t[n],enumerable:!0})},NN=(e,t,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of SN(t))!TN.call(e,s)&&s!=="default"&&Xp(e,s,{get:()=>t[s],enumerable:!(n=IN(t,s))||n.enumerable});return e},Qo=e=>NN(e5(Xp(e!=null?kN(CN(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e),EN=ts({"node_modules/.pnpm/long@4.0.0/node_modules/long/src/long.js"(e,t){t.exports=s;var n=null;try{n=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(_){}function s(_,T,M){this.low=_|0,this.high=T|0,this.unsigned=!!M}s.prototype.__isLong__,Object.defineProperty(s.prototype,"__isLong__",{value:!0});function r(_){return(_&&_.__isLong__)===!0}s.isLong=r;var a={},o={};function i(_,T){var M,U,H;return T?(_>>>=0,(H=0<=_&&_<256)&&(U=o[_],U)?U:(M=c(_,(_|0)<0?-1:0,!0),H&&(o[_]=M),M)):(_|=0,(H=-128<=_&&_<128)&&(U=a[_],U)?U:(M=c(_,_<0?-1:0,!1),H&&(a[_]=M),M))}s.fromInt=i;function l(_,T){if(isNaN(_))return T?b:x;if(T){if(_<0)return b;if(_>=g)return P}else{if(_<=-A)return F;if(_+1>=A)return E}return _<0?l(-_,T).neg():c(_%m|0,_/m|0,T)}s.fromNumber=l;function c(_,T,M){return new s(_,T,M)}s.fromBits=c;var u=Math.pow;function d(_,T,M){if(_.length===0)throw Error("empty string");if(_==="NaN"||_==="Infinity"||_==="+Infinity"||_==="-Infinity")return x;if(typeof T=="number"?(M=T,T=!1):T=!!T,M=M||10,M<2||360)throw Error("interior hyphen");if(U===0)return d(_.substring(1),T,M).neg();for(var H=l(u(M,8)),z=x,X=0;X<_.length;X+=8){var ee=Math.min(8,_.length-X),Y=parseInt(_.substring(X,X+ee),M);if(ee<8){var se=l(u(M,ee));z=z.mul(se).add(l(Y))}else z=z.mul(H),z=z.add(l(Y))}return z.unsigned=T,z}s.fromString=d;function p(_,T){return typeof _=="number"?l(_,T):typeof _=="string"?d(_,T):c(_.low,_.high,typeof T=="boolean"?T:_.unsigned)}s.fromValue=p;var h=1<<16,f=1<<24,m=h*h,g=m*m,A=g/2,y=i(f),x=i(0);s.ZERO=x;var b=i(0,!0);s.UZERO=b;var w=i(1);s.ONE=w;var k=i(1,!0);s.UONE=k;var S=i(-1);s.NEG_ONE=S;var E=c(4294967295|0,2147483647|0,!1);s.MAX_VALUE=E;var P=c(4294967295|0,4294967295|0,!0);s.MAX_UNSIGNED_VALUE=P;var F=c(0,2147483648|0,!1);s.MIN_VALUE=F;var R=s.prototype;R.toInt=function(){return this.unsigned?this.low>>>0:this.low},R.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},R.toString=function(T){if(T=T||10,T<2||36>>0,ne=se.toString(T);if(X=Y,X.isZero())return ne+ee;for(;ne.length<6;)ne="0"+ne;ee=""+ne+ee}},R.getHighBits=function(){return this.high},R.getHighBitsUnsigned=function(){return this.high>>>0},R.getLowBits=function(){return this.low},R.getLowBitsUnsigned=function(){return this.low>>>0},R.getNumBitsAbs=function(){if(this.isNegative())return this.eq(F)?64:this.neg().getNumBitsAbs();for(var T=this.high!=0?this.high:this.low,M=31;M>0&&(T&1<=0},R.isOdd=function(){return(this.low&1)==1},R.isEven=function(){return(this.low&1)==0},R.equals=function(T){return r(T)||(T=p(T)),this.unsigned!==T.unsigned&&this.high>>>31==1&&T.high>>>31==1?!1:this.high===T.high&&this.low===T.low},R.eq=R.equals,R.notEquals=function(T){return!this.eq(T)},R.neq=R.notEquals,R.ne=R.notEquals,R.lessThan=function(T){return this.comp(T)<0},R.lt=R.lessThan,R.lessThanOrEqual=function(T){return this.comp(T)<=0},R.lte=R.lessThanOrEqual,R.le=R.lessThanOrEqual,R.greaterThan=function(T){return this.comp(T)>0},R.gt=R.greaterThan,R.greaterThanOrEqual=function(T){return this.comp(T)>=0},R.gte=R.greaterThanOrEqual,R.ge=R.greaterThanOrEqual,R.compare=function(T){if(r(T)||(T=p(T)),this.eq(T))return 0;var M=this.isNegative(),U=T.isNegative();return M&&!U?-1:!M&&U?1:this.unsigned?T.high>>>0>this.high>>>0||T.high===this.high&&T.low>>>0>this.low>>>0?-1:1:this.sub(T).isNegative()?-1:1},R.comp=R.compare,R.negate=function(){return!this.unsigned&&this.eq(F)?F:this.not().add(w)},R.neg=R.negate,R.add=function(T){r(T)||(T=p(T));var M=this.high>>>16,U=this.high&65535,H=this.low>>>16,z=this.low&65535,X=T.high>>>16,ee=T.high&65535,Y=T.low>>>16,se=T.low&65535,ne=0,J=0,te=0,ue=0;return ue+=z+se,te+=ue>>>16,ue&=65535,te+=H+Y,J+=te>>>16,te&=65535,J+=U+ee,ne+=J>>>16,J&=65535,ne+=M+X,ne&=65535,c(te<<16|ue,ne<<16|J,this.unsigned)},R.subtract=function(T){return r(T)||(T=p(T)),this.add(T.neg())},R.sub=R.subtract,R.multiply=function(T){if(this.isZero())return x;if(r(T)||(T=p(T)),n){var M=n.mul(this.low,this.high,T.low,T.high);return c(M,n.get_high(),this.unsigned)}if(T.isZero())return x;if(this.eq(F))return T.isOdd()?F:x;if(T.eq(F))return this.isOdd()?F:x;if(this.isNegative())return T.isNegative()?this.neg().mul(T.neg()):this.neg().mul(T).neg();if(T.isNegative())return this.mul(T.neg()).neg();if(this.lt(y)&&T.lt(y))return l(this.toNumber()*T.toNumber(),this.unsigned);var U=this.high>>>16,H=this.high&65535,z=this.low>>>16,X=this.low&65535,ee=T.high>>>16,Y=T.high&65535,se=T.low>>>16,ne=T.low&65535,J=0,te=0,ue=0,ce=0;return ce+=X*ne,ue+=ce>>>16,ce&=65535,ue+=z*ne,te+=ue>>>16,ue&=65535,ue+=X*se,te+=ue>>>16,ue&=65535,te+=H*ne,J+=te>>>16,te&=65535,te+=z*se,J+=te>>>16,te&=65535,te+=X*Y,J+=te>>>16,te&=65535,J+=U*ne+H*se+z*Y+X*ee,J&=65535,c(ue<<16|ce,J<<16|te,this.unsigned)},R.mul=R.multiply,R.divide=function(T){if(r(T)||(T=p(T)),T.isZero())throw Error("division by zero");if(n){if(!this.unsigned&&this.high===-2147483648&&T.low===-1&&T.high===-1)return this;var M=(this.unsigned?n.div_u:n.div_s)(this.low,this.high,T.low,T.high);return c(M,n.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?b:x;var U,H,z;if(this.unsigned){if(T.unsigned||(T=T.toUnsigned()),T.gt(this))return b;if(T.gt(this.shru(1)))return k;z=b}else{if(this.eq(F)){if(T.eq(w)||T.eq(S))return F;if(T.eq(F))return w;var X=this.shr(1);return U=X.div(T).shl(1),U.eq(x)?T.isNegative()?w:S:(H=this.sub(T.mul(U)),z=U.add(H.div(T)),z)}else if(T.eq(F))return this.unsigned?b:x;if(this.isNegative())return T.isNegative()?this.neg().div(T.neg()):this.neg().div(T).neg();if(T.isNegative())return this.div(T.neg()).neg();z=x}for(H=this;H.gte(T);){U=Math.max(1,Math.floor(H.toNumber()/T.toNumber()));for(var ee=Math.ceil(Math.log(U)/Math.LN2),Y=ee<=48?1:u(2,ee-48),se=l(U),ne=se.mul(T);ne.isNegative()||ne.gt(H);)U-=Y,se=l(U,this.unsigned),ne=se.mul(T);se.isZero()&&(se=w),z=z.add(se),H=H.sub(ne)}return z},R.div=R.divide,R.modulo=function(T){if(r(T)||(T=p(T)),n){var M=(this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,T.low,T.high);return c(M,n.get_high(),this.unsigned)}return this.sub(this.div(T).mul(T))},R.mod=R.modulo,R.rem=R.modulo,R.not=function(){return c(~this.low,~this.high,this.unsigned)},R.and=function(T){return r(T)||(T=p(T)),c(this.low&T.low,this.high&T.high,this.unsigned)},R.or=function(T){return r(T)||(T=p(T)),c(this.low|T.low,this.high|T.high,this.unsigned)},R.xor=function(T){return r(T)||(T=p(T)),c(this.low^T.low,this.high^T.high,this.unsigned)},R.shiftLeft=function(T){return r(T)&&(T=T.toInt()),(T&=63)==0?this:T<32?c(this.low<>>32-T,this.unsigned):c(0,this.low<>>T|this.high<<32-T,this.high>>T,this.unsigned):c(this.high>>T-32,this.high>=0?0:-1,this.unsigned)},R.shr=R.shiftRight,R.shiftRightUnsigned=function(T){if(r(T)&&(T=T.toInt()),T&=63,T===0)return this;var M=this.high;if(T<32){var U=this.low;return c(U>>>T|M<<32-T,M>>>T,this.unsigned)}else return T===32?c(M,0,this.unsigned):c(M>>>T-32,0,this.unsigned)},R.shru=R.shiftRightUnsigned,R.shr_u=R.shiftRightUnsigned,R.toSigned=function(){return this.unsigned?c(this.low,this.high,!1):this},R.toUnsigned=function(){return this.unsigned?this:c(this.low,this.high,!0)},R.toBytes=function(T){return T?this.toBytesLE():this.toBytesBE()},R.toBytesLE=function(){var T=this.high,M=this.low;return[M&255,M>>>8&255,M>>>16&255,M>>>24,T&255,T>>>8&255,T>>>16&255,T>>>24]},R.toBytesBE=function(){var T=this.high,M=this.low;return[T>>>24,T>>>16&255,T>>>8&255,T&255,M>>>24,M>>>16&255,M>>>8&255,M&255]},s.fromBytes=function(T,M,U){return U?s.fromBytesLE(T,M):s.fromBytesBE(T,M)},s.fromBytesLE=function(T,M){return new s(T[0]|T[1]<<8|T[2]<<16|T[3]<<24,T[4]|T[5]<<8|T[6]<<16|T[7]<<24,M)},s.fromBytesBE=function(T,M){return new s(T[4]<<24|T[5]<<16|T[6]<<8|T[7],T[0]<<24|T[1]<<16|T[2]<<8|T[3],M)}}}),RN=ts({"(disabled):node-fetch"(){}}),$N=ts({"(disabled):util"(){}}),DN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js"(e,t){(function(n,s,r){function a(c){var u=this,d=l();u.next=function(){var p=2091639*u.s0+u.c*23283064365386963e-26;return u.s0=u.s1,u.s1=u.s2,u.s2=p-(u.c=p|0)},u.c=1,u.s0=d(" "),u.s1=d(" "),u.s2=d(" "),u.s0-=d(c),u.s0<0&&(u.s0+=1),u.s1-=d(c),u.s1<0&&(u.s1+=1),u.s2-=d(c),u.s2<0&&(u.s2+=1),d=null}function o(c,u){return u.c=c.c,u.s0=c.s0,u.s1=c.s1,u.s2=c.s2,u}function i(c,u){var d=new a(c),p=u&&u.state,h=d.next;return h.int32=function(){return d.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,p&&(typeof p=="object"&&o(p,d),h.state=function(){return o(d,{})}),h}function l(){var c=4022871197,u=function(d){d=String(d);for(var p=0;p>>0,h-=c,h*=c,c=h>>>0,h-=c,c+=h*4294967296}return(c>>>0)*23283064365386963e-26};return u}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.alea=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),_N=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.x=0,c.y=0,c.z=0,c.w=0,c.next=function(){var p=c.x^c.x<<11;return c.x=c.y,c.y=c.z,c.z=c.w,c.w^=c.w>>>19^p^p>>>8},l===(l|0)?c.x=l:u+=l;for(var d=0;d>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xor128=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),PN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.next=function(){var p=c.x^c.x>>>2;return c.x=c.y,c.y=c.z,c.z=c.w,c.w=c.v,(c.d=c.d+362437|0)+(c.v=c.v^c.v<<4^(p^p<<1))|0},c.x=0,c.y=0,c.z=0,c.w=0,c.v=0,l===(l|0)?c.x=l:u+=l;for(var d=0;d>>4),c.next()}function o(l,c){return c.x=l.x,c.y=l.y,c.z=l.z,c.w=l.w,c.v=l.v,c.d=l.d,c}function i(l,c){var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xorwow=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),FN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js"(e,t){(function(n,s,r){function a(l){var c=this;c.next=function(){var d=c.x,p=c.i,h,f,m;return h=d[p],h^=h>>>7,f=h^h<<24,h=d[p+1&7],f^=h^h>>>10,h=d[p+3&7],f^=h^h>>>3,h=d[p+4&7],f^=h^h<<7,h=d[p+7&7],h=h^h<<13,f^=h^h<<9,d[p]=f,c.i=p+1&7,f};function u(d,p){var h,f,m=[];if(p===(p|0))f=m[0]=p;else for(p=""+p,h=0;h0;--h)d.next()}u(c,l)}function o(l,c){return c.x=l.x.slice(),c.i=l.i,c}function i(l,c){l==null&&(l=+new Date);var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.x&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xorshift7=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),ON=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js"(e,t){(function(n,s,r){function a(l){var c=this;c.next=function(){var d=c.w,p=c.X,h=c.i,f,m;return c.w=d=d+1640531527|0,m=p[h+34&127],f=p[h=h+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,m=p[h]=m^f,c.i=h,m+(d^d>>>16)|0};function u(d,p){var h,f,m,g,A,y=[],x=128;for(p===(p|0)?(f=p,p=null):(p=p+"\0",f=0,x=Math.max(x,p.length)),m=0,g=-32;g>>15,f^=f<<4,f^=f>>>13,g>=0&&(A=A+1640531527|0,h=y[g&127]^=f+A,m=h==0?m+1:0);for(m>=128&&(y[(p&&p.length||0)&127]=-1),m=127,g=4*128;g>0;--g)f=y[m+34&127],h=y[m=m+1&127],f^=f<<13,h^=h<<17,f^=f>>>15,h^=h>>>12,y[m]=f^h;d.w=A,d.X=y,d.i=m}u(c,l)}function o(l,c){return c.i=l.i,c.w=l.w,c.X=l.X.slice(),c}function i(l,c){l==null&&(l=+new Date);var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.X&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xor4096=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),MN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.next=function(){var p=c.b,h=c.c,f=c.d,m=c.a;return p=p<<25^p>>>7^h,h=h-f|0,f=f<<24^f>>>8^m,m=m-p|0,c.b=p=p<<20^p>>>12^h,c.c=h=h-f|0,c.d=f<<16^h>>>16^m,c.a=m-p|0},c.a=0,c.b=0,c.c=2654435769|0,c.d=1367130551,l===Math.floor(l)?(c.a=l/4294967296|0,c.b=l|0):u+=l;for(var d=0;d>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.tychei=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),zN=ts({"(disabled):crypto"(){}}),LN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js"(e,t){(function(n,s,r){var a=256,o=6,i=52,l="random",c=r.pow(a,o),u=r.pow(2,i),d=u*2,p=a-1,h;function f(w,k,S){var E=[];k=k==!0?{entropy:!0}:k||{};var P=y(A(k.entropy?[w,b(s)]:w==null?x():w,3),E),F=new m(E),R=function(){for(var _=F.g(o),T=c,M=0;_=d;)_/=2,T/=2,M>>>=1;return(_+M)/T};return R.int32=function(){return F.g(4)|0},R.quick=function(){return F.g(4)/4294967296},R.double=R,y(b(F.S),s),(k.pass||S||function(_,T,M,U){return U&&(U.S&&g(U,F),_.state=function(){return g(F,{})}),M?(r[l]=_,T):_})(R,P,"global"in k?k.global:this==r,k.state)}function m(w){var k,S=w.length,E=this,P=0,F=E.i=E.j=0,R=E.S=[];for(S||(w=[S++]);P1&&(g=process.argv[1].replace(/\\/g,"/")),m=process.argv.slice(2),process.on("uncaughtException",function(C){if(!(C instanceof Nc))throw C}),process.on("unhandledRejection",Wr),A=function(C){process.exit(C)},u.inspect=function(){return"[Emscripten Module object]"};var U;try{U=Ws("worker_threads")}catch(C){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),C}global.Worker=U.Worker}else w?(typeof read!="undefined"&&(P=function($){return read($)}),R=function($){var L;return typeof readbuffer=="function"?new Uint8Array(readbuffer($)):(L=read($,"binary"),we(typeof L=="object"),L)},typeof scriptArgs!="undefined"?m=scriptArgs:typeof arguments!="undefined"&&(m=arguments),typeof quit=="function"&&(A=function(C){quit(C)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(y||x)&&(x?S=self.location.href:typeof document!="undefined"&&document.currentScript&&(S=document.currentScript.src),typeof s!="undefined"&&s&&(S=s),S.indexOf("blob:")!==0?S=S.substr(0,S.lastIndexOf("/")+1):S="",b?(P=function($,L){return T||(T=Ws("fs")),M||(M=Ws("path")),$=M.normalize($),T.readFileSync($,L?null:"utf8")},R=function($){var L=P($,!0);return L.buffer||(L=new Uint8Array(L)),we(L.buffer),L}):(P=function(C){var $=new XMLHttpRequest;return $.open("GET",C,!1),$.send(null),$.responseText},x&&(R=function(C){var $=new XMLHttpRequest;return $.open("GET",C,!1),$.responseType="arraybuffer",$.send(null),new Uint8Array($.response)}),F=function(C,$,L){var Z=new XMLHttpRequest;Z.open("GET",C,!0),Z.responseType="arraybuffer",Z.onload=function(){if(Z.status==200||Z.status==0&&Z.response){$(Z.response);return}L()},Z.onerror=L,Z.send(null)}),_=function(C){document.title=C});b&&typeof performance=="undefined"&&(global.performance=Ws("perf_hooks").performance);var H=u.print||console.log.bind(console),z=u.printErr||console.warn.bind(console);for(f in h)h.hasOwnProperty(f)&&(u[f]=h[f]);h=null,u.arguments&&(m=u.arguments),u.thisProgram&&(g=u.thisProgram),u.quit&&(A=u.quit);function X(C){X.shown||(X.shown={}),X.shown[C]||(X.shown[C]=1,z(C))}var ee=Atomics.load,Y=Atomics.store,se=Atomics.compareExchange,ne;u.wasmBinary&&(ne=u.wasmBinary);var J=u.noExitRuntime||!0;typeof WebAssembly!="object"&&Wr("no native wasm support detected");var te,ue,ce=!1,xe;function we(C,$){C||Wr("Assertion failed: "+$)}function Ce(C){var $=u["_"+C];return we($,"Cannot call unknown function "+C+", make sure it is exported"),$}function Oe(C,$,L,Z,ge){var fe={string:function(Mn){var Ml=0;if(Mn!=null&&Mn!==0){var Jb=(Mn.length<<2)+1;Ml=Pl(Jb),ut(Mn,Ml,Jb)}return Ml},array:function(Mn){var Ml=Pl(Mn.length);return At(Mn,Ml),Ml}};function me(Mn){return $==="string"?rt(Mn):$==="boolean"?Boolean(Mn):Mn}var Te=Ce(C),ht=[],fn=0;if(Z)for(var nn=0;nn=Z);){var fe=C[$++];if(!fe)return ge;if(!(fe&128)){ge+=String.fromCharCode(fe);continue}var me=C[$++]&63;if((fe&224)==192){ge+=String.fromCharCode((fe&31)<<6|me);continue}var Te=C[$++]&63;if((fe&240)==224?fe=(fe&15)<<12|me<<6|Te:fe=(fe&7)<<18|me<<12|Te<<6|C[$++]&63,fe<65536)ge+=String.fromCharCode(fe);else{var ht=fe-65536;ge+=String.fromCharCode(55296|ht>>10,56320|ht&1023)}}return ge}function rt(C,$){return C?Xe(o(),C,$):""}function ft(C,$,L,Z){if(!(Z>0))return 0;for(var ge=L,fe=L+Z-1,me=0;me=55296&&Te<=57343){var ht=C.charCodeAt(++me);Te=65536+((Te&1023)<<10)|ht&1023}if(Te<=127){if(L>=fe)break;$[L++]=Te}else if(Te<=2047){if(L+1>=fe)break;$[L++]=192|Te>>6,$[L++]=128|Te&63}else if(Te<=65535){if(L+2>=fe)break;$[L++]=224|Te>>12,$[L++]=128|Te>>6&63,$[L++]=128|Te&63}else{if(L+3>=fe)break;$[L++]=240|Te>>18,$[L++]=128|Te>>12&63,$[L++]=128|Te>>6&63,$[L++]=128|Te&63}}return $[L]=0,L-ge}function ut(C,$,L){return ft(C,o(),$,L)}function ct(C){for(var $=0,L=0;L=55296&&Z<=57343&&(Z=65536+((Z&1023)<<10)|C.charCodeAt(++L)&1023),Z<=127?++$:Z<=2047?$+=2:Z<=65535?$+=3:$+=4}return $}function At(C,$){a().set(C,$)}function yt(C,$){return C%$>0&&(C+=$-C%$),C}var Et,Pt,Jn,wn,nr,On,ds,Ls,Is;function kn(C){Et=C,u.HEAP8=Pt=new Int8Array(C),u.HEAP16=wn=new Int16Array(C),u.HEAP32=On=new Int32Array(C),u.HEAPU8=Jn=new Uint8Array(C),u.HEAPU16=nr=new Uint16Array(C),u.HEAPU32=ds=new Uint32Array(C),u.HEAPF32=Ls=new Float32Array(C),u.HEAPF64=Is=new Float64Array(C)}var br=u.INITIAL_MEMORY||16777216;if(k)te=u.wasmMemory,Et=u.buffer;else if(u.wasmMemory)te=u.wasmMemory;else if(te=new WebAssembly.Memory({initial:br/65536,maximum:2147483648/65536,shared:!0}),!(te.buffer instanceof SharedArrayBuffer))throw z("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),b&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");te&&(Et=te.buffer),br=Et.byteLength,kn(Et);var Rn,vr=[],wr=[],pa=[],Ac=[],sr=[],wp=!1,f0=!1;k||wr.push({func:function(){Bp()}});function kp(){if(!k){if(u.preRun)for(typeof u.preRun=="function"&&(u.preRun=[u.preRun]);u.preRun.length;)m0(u.preRun.shift());Rl(vr)}}function Ip(){wp=!0,!k&&Rl(wr)}function Sp(){k||Rl(pa)}function Qn(){k||(f0=!0)}function Cp(){if(!k){if(u.postRun)for(typeof u.postRun=="function"&&(u.postRun=[u.postRun]);u.postRun.length;)g0(u.postRun.shift());Rl(sr)}}function m0(C){vr.unshift(C)}function g0(C){sr.unshift(C)}var Bs=0,yc=null,Xo=null;function A0(C){we(!k,"addRunDependency cannot be used in a pthread worker"),Bs++,u.monitorRunDependencies&&u.monitorRunDependencies(Bs)}function y0(C){if(Bs--,u.monitorRunDependencies&&u.monitorRunDependencies(Bs),Bs==0&&(yc!==null&&(clearInterval(yc),yc=null),Xo)){var $=Xo;Xo=null,$()}}u.preloadedImages={},u.preloadedAudios={};function Wr(C){u.onAbort&&u.onAbort(C),k&&console.error("Pthread aborting at "+new Error().stack),C+="",z(C),ce=!0,xe=1,C="abort("+C+"). Build with -s ASSERTIONS=1 for more info.";var $=new WebAssembly.RuntimeError(C);throw p($),$}function Ko(C,$){return String.prototype.startsWith?C.startsWith($):C.indexOf($)===0}var x0="data:application/octet-stream;base64,";function Tp(C){return Ko(C,x0)}var b0="file://";function Np(C){return Ko(C,b0)}var es="tfjs-backend-wasm-threaded-simd.wasm";Tp(es)||(es=E(es));function v0(C){try{if(C==es&&ne)return new Uint8Array(ne);if(R)return R(C);throw"both async and sync fetching of the wasm failed"}catch($){Wr($)}}function Ep(){if(!ne&&(y||x)){if(typeof fetch=="function"&&!Np(es))return fetch(es,{credentials:"same-origin"}).then(function(C){if(!C.ok)throw"failed to load wasm binary file at '"+es+"'";return C.arrayBuffer()}).catch(function(){return v0(es)});if(F)return new Promise(function(C,$){F(es,function(L){C(new Uint8Array(L))},$)})}return Promise.resolve().then(function(){return v0(es)})}function w0(){var C={a:fg};function $(me,Te){var ht=me.exports;if(u.asm=ht,Rn=u.asm.kb,ue=Te,!k){var fn=Re.unusedWorkers.length;Re.unusedWorkers.forEach(function(nn){Re.loadWasmModuleToWorker(nn,function(){--fn||y0("wasm-instantiate")})})}}k||A0("wasm-instantiate");function L(me){$(me.instance,me.module)}function Z(me){return Ep().then(function(Te){return WebAssembly.instantiate(Te,C)}).then(me,function(Te){z("failed to asynchronously prepare wasm: "+Te),Wr(Te)})}function ge(){return!ne&&typeof WebAssembly.instantiateStreaming=="function"&&!Tp(es)&&!Np(es)&&typeof fetch=="function"?fetch(es,{credentials:"same-origin"}).then(function(me){var Te=WebAssembly.instantiateStreaming(me,C);return Te.then(L,function(ht){return z("wasm streaming compile failed: "+ht),z("falling back to ArrayBuffer instantiation"),Z(L)})}):Z(L)}if(u.instantiateWasm)try{var fe=u.instantiateWasm(C,$);return fe}catch(me){return z("Module.instantiateWasm callback failed with error: "+me),!1}return ge().catch(p),{}}var Rp={10072:function(){throw"Canceled!"},10090:function(C,$){setTimeout(function(){jb(C,$)},0)}};function k0(){Re.initRuntime()}function Rl(C){for(;C.length>0;){var $=C.shift();if(typeof $=="function"){$(u);continue}var L=$.func;typeof L=="number"?$.arg===void 0?Rn.get(L)():Rn.get(L)($.arg):L($.arg===void 0?null:$.arg)}}var ha={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135};function xc(C,$){if(C<=0||C>a().length||C&!0||$<0)return-28;if($==0)return 0;$>=2147483647&&($=1/0);var L=Atomics.load(i(),Fl>>2),Z=0;if(L==C){var ge=Atomics.compareExchange(i(),Fl>>2,L,0);if(ge==L&&(--$,Z=1,$<=0))return 1}var fe=Atomics.notify(i(),C>>2,$);if(fe>=0)return fe+Z;throw"Atomics.notify returned an unexpected value "+fe}u._emscripten_futex_wake=xc;function I0(C){if(k)throw"Internal Error! killThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in killThread!";i()[C+12>>2]=0;var $=Re.pthreads[C];$.worker.terminate(),Re.freeThreadData($),Re.runningWorkers.splice(Re.runningWorkers.indexOf($.worker),1),$.worker.pthread=void 0}function S0(C){if(k)throw"Internal Error! cancelThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in cancelThread!";var $=Re.pthreads[C];$.worker.postMessage({cmd:"cancel"})}function $p(C){if(k)throw"Internal Error! cleanupThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in cleanupThread!";var $=Re.pthreads[C];if($){i()[C+12>>2]=0;var L=$.worker;Re.returnWorkerToPool(L)}}var Re={unusedWorkers:[],runningWorkers:[],initMainThreadBlock:function(){for(var C=8,$=0;$>2]=C;var L=C+152;i()[L>>2]=L;for(var Z=Yo(512),$=0;$<128;++$)l()[Z/4+$]=0;Atomics.store(l(),C+100>>2,Z),Atomics.store(l(),C+40>>2,C),Pg(C,!x,1),Gb(C)},initWorker:function(){},pthreads:{},threadExitHandlers:[],setThreadStatus:function(){},runExitHandlers:function(){for(;Re.threadExitHandlers.length>0;)Re.threadExitHandlers.pop()();k&&Aa()&&Ub()},runExitHandlersAndDeinitThread:function(C,$){Atomics.store(l(),C+56>>2,1),Atomics.store(l(),C+60>>2,0),Re.runExitHandlers(),Atomics.store(l(),C+4>>2,$),Atomics.store(l(),C+0>>2,1),xc(C+0,2147483647),Pg(0,0,0)},threadExit:function(C){var $=Aa();$&&(Re.runExitHandlersAndDeinitThread($,C),k&&postMessage({cmd:"exit"}))},threadCancel:function(){Re.runExitHandlersAndDeinitThread(Aa(),-1),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var C in Re.pthreads){var $=Re.pthreads[C];$&&$.worker&&Re.returnWorkerToPool($.worker)}Re.pthreads={};for(var L=0;L>2];i()[C.threadInfoStruct+100>>2]=0,Cc($),Cc(C.threadInfoStruct)}C.threadInfoStruct=0,C.allocatedOwnStack&&C.stackBase&&Cc(C.stackBase),C.stackBase=0,C.worker&&(C.worker.pthread=null)}},returnWorkerToPool:function(C){Re.runWithoutMainThreadQueuedCalls(function(){delete Re.pthreads[C.pthread.threadInfoStruct],Re.unusedWorkers.push(C),Re.runningWorkers.splice(Re.runningWorkers.indexOf(C),1),Re.freeThreadData(C.pthread),C.pthread=void 0})},runWithoutMainThreadQueuedCalls:function(C){i()[Yb>>2]=0;try{C()}finally{i()[Yb>>2]=1}},receiveObjectTransfer:function(C){},loadWasmModuleToWorker:function(C,$){C.onmessage=function(L){var Z=L.data,ge=Z.cmd;if(C.pthread&&(Re.currentProxiedOperationCallerThread=C.pthread.threadInfoStruct),Z.targetThread&&Z.targetThread!=Aa()){var fe=Re.pthreads[Z.targetThread];fe?fe.worker.postMessage(L.data,Z.transferList):console.error('Internal error! Worker sent a message "'+ge+'" to target pthread '+Z.targetThread+", but that thread no longer exists!"),Re.currentProxiedOperationCallerThread=void 0;return}if(ge==="processQueuedMainThreadWork")Hp();else if(ge==="spawnThread")zp(L.data);else if(ge==="cleanupThread")$p(Z.thread);else if(ge==="killThread")I0(Z.thread);else if(ge==="cancelThread")S0(Z.thread);else if(ge==="loaded")C.loaded=!0,$&&$(C),C.runPthread&&(C.runPthread(),delete C.runPthread);else if(ge==="print")H("Thread "+Z.threadId+": "+Z.text);else if(ge==="printErr")z("Thread "+Z.threadId+": "+Z.text);else if(ge==="alert")alert("Thread "+Z.threadId+": "+Z.text);else if(ge==="exit"){var me=C.pthread&&Atomics.load(l(),C.pthread.threadInfoStruct+64>>2);me&&Re.returnWorkerToPool(C)}else if(ge==="exitProcess")try{bN(Z.returnCode)}catch(Te){if(Te instanceof Nc)return;throw Te}else ge==="cancelDone"?Re.returnWorkerToPool(C):ge==="objectTransfer"?Re.receiveObjectTransfer(L.data):L.data.target==="setimmediate"?C.postMessage(L.data):z("worker sent an unknown command "+ge);Re.currentProxiedOperationCallerThread=void 0},C.onerror=function(L){z("pthread sent an error! "+L.filename+":"+L.lineno+": "+L.message)},b&&(C.on("message",function(L){C.onmessage({data:L})}),C.on("error",function(L){C.onerror(L)}),C.on("exit",function(L){})),C.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||s,wasmMemory:te,wasmModule:ue})},allocateUnusedWorker:function(){var C=E("tfjs-backend-wasm-threaded-simd.worker.js");Re.unusedWorkers.push(new Worker(C))},getNewWorker:function(){return Re.unusedWorkers.length==0&&(Re.allocateUnusedWorker(),Re.loadWasmModuleToWorker(Re.unusedWorkers[0])),Re.unusedWorkers.length>0?Re.unusedWorkers.pop():null},busySpinWait:function(C){for(var $=performance.now()+C;performance.now()<$;);}};function C0(C,$){Kb(C,$),_l(C)}u.establishStackSpace=C0;function T0(){return J}u.getNoExitRuntime=T0;function N0(C,$){return Rn.get(C)($)}u.invokeEntryPoint=N0;function E0(C,$,L,Z){Wr("Assertion failed: "+rt(C)+", at: "+[$?rt($):"unknown filename",L,Z?rt(Z):"unknown function"])}function R0(C,$){var L=_main(C,$)}var Zo;b?Zo=function(){var C=process.hrtime();return C[0]*1e3+C[1]/1e6}:k?Zo=function(){return performance.now()-u.__performance_now_clock_drift}:typeof dateNow!="undefined"?Zo=dateNow:Zo=function(){return performance.now()};function $0(C){return i()[Wb()>>2]=C,C}function D0(C,$){if(k)return fa(1,1,C,$)}function _0(C,$){if(C==$)postMessage({cmd:"processQueuedMainThreadWork"});else if(k)postMessage({targetThread:C,cmd:"processThreadQueue"});else{var L=Re.pthreads[C],Z=L&&L.worker;if(!Z)return;Z.postMessage({cmd:"processThreadQueue"})}return 1}function P0(){Wr()}function F0(C,$,L){var Z=L0($,L);return Rp[C].apply(null,Z)}function O0(C,$){}function Dp(C,$,L){if(C<=0||C>a().length||C&!0)return-28;if(y){if(Atomics.load(i(),C>>2)!=$)return-6;for(var ge=performance.now(),fe=ge+L,me=Atomics.exchange(i(),Fl>>2,C);;){if(ge=performance.now(),ge>fe)return me=Atomics.exchange(i(),Fl>>2,0),-73;if(me=Atomics.exchange(i(),Fl>>2,0),me==0)break;if(Hp(),Atomics.load(i(),C>>2)!=$)return-6;me=Atomics.exchange(i(),Fl>>2,C)}return 0}else{var Z=Atomics.wait(i(),C>>2,$,L);if(Z==="timed-out")return-73;if(Z==="not-equal")return-6;if(Z==="ok")return 0;throw"Atomics.wait returned an unexpected value "+Z}}function M0(C,$,L){o().copyWithin(C,$,$+L)}function z0(){return b?Ws("os").cpus().length:navigator.hardwareConcurrency}function fa(C,$){for(var L=arguments.length-2,Z=Tc(),ge=L,fe=Pl(ge*8),me=fe>>3,Te=0;Te>=2;L=o()[C++];){var Z=L<105;Z&&$&1&&$++,vc.push(Z?c()[$++>>1]:i()[$]),++$}return vc}function B0(C,$,L){bc.length=$;for(var Z=L>>3,ge=0;ge<$;ge++)bc[ge]=c()[Z+ge];var fe=C<0,me=fe?Rp[-C-1]:hg[C];return me.apply(null,bc)}function W0(){return o().length}function V0(C){try{return te.grow(C-Et.byteLength+65535>>>16),kn(te.buffer),1}catch($){}}function U0(C){var $=W0();if(C<=$)return!1;var L=2147483648;if(C>L)return!1;for(var Z=1;Z<=4;Z*=2){var ge=$*(1+.2/Z);ge=Math.min(ge,C+100663296);var fe=Math.min(L,yt(Math.max(C,ge),65536)),me=V0(fe);if(me)return!0}return!1}var Ge={inEventHandler:0,removeAllEventListeners:function(){for(var C=Ge.eventHandlers.length-1;C>=0;--C)Ge._removeHandler(C);Ge.eventHandlers=[],Ge.deferredCalls=[]},registerRemoveEventListeners:function(){Ge.removeEventListenersRegistered||(Ac.push(Ge.removeAllEventListeners),Ge.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(C,$,L){function Z(me,Te){if(me.length!=Te.length)return!1;for(var ht in me)if(me[ht]!=Te[ht])return!1;return!0}for(var ge in Ge.deferredCalls){var fe=Ge.deferredCalls[ge];if(fe.targetFunction==C&&Z(fe.argsList,L))return}Ge.deferredCalls.push({targetFunction:C,precedence:$,argsList:L}),Ge.deferredCalls.sort(function(me,Te){return me.precedence>2]=L,i()[me+4>>2]=Z,i()[me+8>>2]=ge,_g(0,C,637534208,$,Z,me),_l(fe)},getTargetThreadForEventCallback:function(C){switch(C){case 1:return 0;case 2:return Re.currentProxiedOperationCallerThread;default:return C}},getNodeNameForTarget:function(C){return C?C==window?"#window":C==screen?"#screen":C&&C.nodeName?C.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function G0(C){var $=ct(C)+1,L=Yo($);return ut(C,L,$),L}function H0(C,$,L,Z){var ge=Tc(),fe=Pl(12),me=0;$&&(me=G0($)),i()[fe>>2]=me,i()[fe+4>>2]=L,i()[fe+8>>2]=Z,_g(0,C,657457152,0,me,fe),_l(ge)}function j0(C,$,L,Z){$=$?rt($):"",H0(C,$,L,Z)}function q0(C){return C>2?rt(C):C}var X0=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function K0(C){C=q0(C);var $=X0[C]||(typeof document!="undefined"?document.querySelector(C):void 0);return $}function wc(C){return K0(C)}function _p(C,$,L){var Z=wc(C);if(!Z)return-4;if(Z.canvasSharedPtr&&(i()[Z.canvasSharedPtr>>2]=$,i()[Z.canvasSharedPtr+4>>2]=L),Z.offscreenCanvas||!Z.controlTransferredOffscreen){Z.offscreenCanvas&&(Z=Z.offscreenCanvas);var ge=!1;if(Z.GLctxObject&&Z.GLctxObject.GLctx){var fe=Z.GLctxObject.GLctx.getParameter(2978);ge=fe[0]===0&&fe[1]===0&&fe[2]===Z.width&&fe[3]===Z.height}Z.width=$,Z.height=L,ge&&Z.GLctxObject.GLctx.viewport(0,0,$,L)}else if(Z.canvasSharedPtr){var me=i()[Z.canvasSharedPtr+8>>2];return j0(me,C,$,L),1}else return-4;return 0}function Pp(C,$,L){return k?fa(2,1,C,$,L):_p(C,$,L)}function Z0(C,$,L){var Z=wc(C);return Z?_p(C,$,L):Pp(C,$,L)}function Y0(C){}function J0(C,$){}function Q0(C){var $=C.getExtension("ANGLE_instanced_arrays");if($)return C.vertexAttribDivisor=function(L,Z){$.vertexAttribDivisorANGLE(L,Z)},C.drawArraysInstanced=function(L,Z,ge,fe){$.drawArraysInstancedANGLE(L,Z,ge,fe)},C.drawElementsInstanced=function(L,Z,ge,fe,me){$.drawElementsInstancedANGLE(L,Z,ge,fe,me)},1}function eg(C){var $=C.getExtension("OES_vertex_array_object");if($)return C.createVertexArray=function(){return $.createVertexArrayOES()},C.deleteVertexArray=function(L){$.deleteVertexArrayOES(L)},C.bindVertexArray=function(L){$.bindVertexArrayOES(L)},C.isVertexArray=function(L){return $.isVertexArrayOES(L)},1}function tg(C){var $=C.getExtension("WEBGL_draw_buffers");if($)return C.drawBuffers=function(L,Z){$.drawBuffersWEBGL(L,Z)},1}function ng(C){return!!(C.multiDrawWebgl=C.getExtension("WEBGL_multi_draw"))}var dt={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,recordError:function($){dt.lastError||(dt.lastError=$)},getNewId:function(C){for(var $=dt.counter++,L=C.length;L<$;L++)C[L]=null;return $},getSource:function(C,$,L,Z){for(var ge="",fe=0;fe<$;++fe){var me=Z?i()[Z+fe*4>>2]:-1;ge+=rt(i()[L+fe*4>>2],me<0?void 0:me)}return ge},createContext:function(C,$){var L=C.getContext("webgl",$);if(!L)return 0;var Z=dt.registerContext(L,$);return Z},registerContext:function(C,$){var L=Yo(8);i()[L+4>>2]=Aa();var Z={handle:L,attributes:$,version:$.majorVersion,GLctx:C};return C.canvas&&(C.canvas.GLctxObject=Z),dt.contexts[L]=Z,(typeof $.enableExtensionsByDefault=="undefined"||$.enableExtensionsByDefault)&&dt.initExtensions(Z),L},makeContextCurrent:function(C){return dt.currentContext=dt.contexts[C],u.ctx=ma=dt.currentContext&&dt.currentContext.GLctx,!(C&&!ma)},getContext:function(C){return dt.contexts[C]},deleteContext:function(C){dt.currentContext===dt.contexts[C]&&(dt.currentContext=null),typeof Ge=="object"&&Ge.removeAllHandlersOnTarget(dt.contexts[C].GLctx.canvas),dt.contexts[C]&&dt.contexts[C].GLctx.canvas&&(dt.contexts[C].GLctx.canvas.GLctxObject=void 0),Cc(dt.contexts[C].handle),dt.contexts[C]=null},initExtensions:function(C){if(C||(C=dt.currentContext),!C.initExtensionsDone){C.initExtensionsDone=!0;var $=C.GLctx;Q0($),eg($),tg($),$.disjointTimerQueryExt=$.getExtension("EXT_disjoint_timer_query"),ng($);var L=$.getSupportedExtensions()||[];L.forEach(function(Z){Z.indexOf("lose_context")<0&&Z.indexOf("debug")<0&&$.getExtension(Z)})}},populateUniformTable:function(C){for(var $=dt.programs[C],L=dt.programInfos[C]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},Z=L.uniforms,ge=ma.getProgramParameter($,35718),fe=0;fe>2,Z=i()[L+(24>>2)],ge={alpha:!!i()[L+(0>>2)],depth:!!i()[L+(4>>2)],stencil:!!i()[L+(8>>2)],antialias:!!i()[L+(12>>2)],premultipliedAlpha:!!i()[L+(16>>2)],preserveDrawingBuffer:!!i()[L+(20>>2)],powerPreference:sg[Z],failIfMajorPerformanceCaveat:!!i()[L+(28>>2)],majorVersion:i()[L+(32>>2)],minorVersion:i()[L+(36>>2)],enableExtensionsByDefault:i()[L+(40>>2)],explicitSwapControl:i()[L+(44>>2)],proxyContextToMainThread:i()[L+(48>>2)],renderViaOffscreenBackBuffer:i()[L+(52>>2)]},fe=wc(C);if(!fe||ge.explicitSwapControl)return 0;var me=dt.createContext(fe,ge);return me}function ag(C,$){return rg(C,$)}var $l={mappings:{},buffers:[null,[],[]],printChar:function(C,$){var L=$l.buffers[C];$===0||$===10?((C===1?H:z)(Xe(L,0)),L.length=0):L.push($)},varargs:void 0,get:function(){$l.varargs+=4;var C=i()[$l.varargs-4>>2];return C},getStr:function(C){var $=rt(C);return $},get64:function(C,$){return C}};function Fp(C){return k?fa(3,1,C):0}function Op(C,$,L,Z,ge){if(k)return fa(4,1,C,$,L,Z,ge)}function Mp(C,$,L,Z){if(k)return fa(5,1,C,$,L,Z);for(var ge=0,fe=0;fe>2],Te=i()[$+(fe*8+4)>>2],ht=0;ht>2]=ge,0}function og(C){var $=Re.threadExitHandlers.pop();C&&$()}function ig(C,$){Re.threadExitHandlers.push(function(){Rn.get(C)($)})}function zp(C){if(k)throw"Internal Error! spawnThread() can only ever be called from main application thread!";var $=Re.getNewWorker();if($.pthread!==void 0)throw"Internal error!";if(!C.pthread_ptr)throw"Internal error, no pthread ptr!";Re.runningWorkers.push($);for(var L=Yo(128*4),Z=0;Z<128;++Z)i()[L+Z*4>>2]=0;var ge=C.stackBase+C.stackSize,fe=Re.pthreads[C.pthread_ptr]={worker:$,stackBase:C.stackBase,stackSize:C.stackSize,allocatedOwnStack:C.allocatedOwnStack,threadInfoStruct:C.pthread_ptr},me=fe.threadInfoStruct>>2;Atomics.store(l(),me+(64>>2),C.detached),Atomics.store(l(),me+(100>>2),L),Atomics.store(l(),me+(40>>2),fe.threadInfoStruct),Atomics.store(l(),me+(80>>2),C.stackSize),Atomics.store(l(),me+(76>>2),ge),Atomics.store(l(),me+(104>>2),C.stackSize),Atomics.store(l(),me+(104+8>>2),ge),Atomics.store(l(),me+(104+12>>2),C.detached);var Te=Vb(),ht=Te+40;Atomics.store(l(),me+(172>>2),ht),$.pthread=fe;var fn={cmd:"run",start_routine:C.startRoutine,arg:C.arg,threadInfoStruct:C.pthread_ptr,stackBase:C.stackBase,stackSize:C.stackSize};$.runPthread=function(){fn.time=performance.now(),$.postMessage(fn,C.transferList)},$.loaded&&($.runPthread(),delete $.runPthread)}function lg(C,$,L,Z){if(typeof SharedArrayBuffer=="undefined")return z("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;if(!C)return z("pthread_create called with a null thread pointer!"),28;var ge=[],fe=0;if(k&&(ge.length===0||fe))return qb(687865856,C,$,L,Z);if(fe)return fe;var me=0,Te=0,ht=0;$&&$!=-1?(me=i()[$>>2],me+=81920,Te=i()[$+8>>2],ht=i()[$+12>>2]!==0):me=2097152;var fn=Te==0;fn?Te=Zb(16,me):(Te-=me,we(Te>0));for(var nn=Yo(228),ya=0;ya<228>>2;++ya)l()[(nn>>2)+ya]=0;i()[C>>2]=nn,i()[nn+12>>2]=nn;var Ol=nn+152;i()[Ol>>2]=Ol;var Mn={stackBase:Te,stackSize:me,allocatedOwnStack:fn,detached:ht,startRoutine:L,pthread_ptr:nn,arg:Z,transferList:ge};return k?(Mn.cmd="spawnThread",postMessage(Mn,ge)):zp(Mn),0}function ug(){if(!!k){var C=Aa();if(!!C){var $=Atomics.load(l(),C+56>>2);if(!$){var L=Atomics.load(l(),C+0>>2);if(L==2)throw"Canceled!"}}}}function cg(){b||x||X("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function dg(C,$,L){if(!C)return z("pthread_join attempted on a null thread pointer!"),ha.ESRCH;if(k&&Aa()==C)return z("PThread "+C+" is attempting to join to itself!"),ha.EDEADLK;if(!k&&Hb()==C)return z("Main thread "+C+" is attempting to join to itself!"),ha.EDEADLK;var Z=i()[C+12>>2];if(Z!==C)return z("pthread_join attempted on thread "+C+", which does not point to a valid thread, or does not exist anymore!"),ha.ESRCH;var ge=Atomics.load(l(),C+64>>2);if(ge)return z("Attempted to join thread "+C+", which was already detached!"),ha.EINVAL;for(L&&cg();;){var fe=Atomics.load(l(),C+0>>2);if(fe==1){var me=Atomics.load(l(),C+4>>2);return $&&(i()[$>>2]=me),Atomics.store(l(),C+64>>2,1),k?postMessage({cmd:"cleanupThread",thread:C}):$p(C),0}if(!L)return ha.EBUSY;ug(),k||Hp(),Dp(C+0,fe,k?100:1)}}function pg(C,$){return dg(C,$,!0)}function Lp(C){if(k)return fa(6,1,C);switch(C){case 30:return 16384;case 85:var $=2147483648;return $/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return typeof navigator=="object"&&navigator.hardwareConcurrency||1}return $0(28),-1}k||Re.initMainThreadBlock();var ma,hg=[null,D0,Pp,Fp,Op,Mp,Lp],fg={e:E0,r:R0,x:_0,b:P0,y:F0,j:O0,d:Dp,c:xc,f:Zo,p:M0,A:z0,u:B0,q:U0,v:Z0,i:Y0,s:J0,w:ag,l:Fp,n:Op,g:Mp,o:k0,a:te||u.wasmMemory,z:og,k:ig,h:lg,m:pg,t:Lp},Bb=w0(),Bp=u.___wasm_call_ctors=function(){return(Bp=u.___wasm_call_ctors=u.asm.B).apply(null,arguments)},mg=u._init=function(){return(mg=u._init=u.asm.C).apply(null,arguments)},gg=u._init_with_threads_count=function(){return(gg=u._init_with_threads_count=u.asm.D).apply(null,arguments)},Ag=u._get_threads_count=function(){return(Ag=u._get_threads_count=u.asm.E).apply(null,arguments)},yg=u._register_tensor=function(){return(yg=u._register_tensor=u.asm.F).apply(null,arguments)},xg=u._dispose_data=function(){return(xg=u._dispose_data=u.asm.G).apply(null,arguments)},bg=u._dispose=function(){return(bg=u._dispose=u.asm.H).apply(null,arguments)},vg=u._Abs=function(){return(vg=u._Abs=u.asm.I).apply(null,arguments)},wg=u._Add=function(){return(wg=u._Add=u.asm.J).apply(null,arguments)},kg=u._AddN=function(){return(kg=u._AddN=u.asm.K).apply(null,arguments)},Ig=u._All=function(){return(Ig=u._All=u.asm.L).apply(null,arguments)},Sg=u._Any=function(){return(Sg=u._Any=u.asm.M).apply(null,arguments)},Cg=u._ArgMax=function(){return(Cg=u._ArgMax=u.asm.N).apply(null,arguments)},Tg=u._AvgPool=function(){return(Tg=u._AvgPool=u.asm.O).apply(null,arguments)},Ng=u._BatchMatMul=function(){return(Ng=u._BatchMatMul=u.asm.P).apply(null,arguments)},Eg=u._Ceil=function(){return(Eg=u._Ceil=u.asm.Q).apply(null,arguments)},Rg=u._ClipByValue=function(){return(Rg=u._ClipByValue=u.asm.R).apply(null,arguments)},$g=u._Conv2D=function(){return($g=u._Conv2D=u.asm.S).apply(null,arguments)},Wp=u._Conv2DBackpropInput=function(){return(Wp=u._Conv2DBackpropInput=u.asm.T).apply(null,arguments)},Vp=u._Cos=function(){return(Vp=u._Cos=u.asm.U).apply(null,arguments)},kc=u._Cosh=function(){return(kc=u._Cosh=u.asm.V).apply(null,arguments)},Dl=u._CropAndResize=function(){return(Dl=u._CropAndResize=u.asm.W).apply(null,arguments)},Dg=u._Cumsum=function(){return(Dg=u._Cumsum=u.asm.X).apply(null,arguments)},Ic=u._DepthToSpace=function(){return(Ic=u._DepthToSpace=u.asm.Y).apply(null,arguments)},re=u._DepthwiseConv2dNative=function(){return(re=u._DepthwiseConv2dNative=u.asm.Z).apply(null,arguments)},oe=u._Elu=function(){return(oe=u._Elu=u.asm._).apply(null,arguments)},ke=u._Equal=function(){return(ke=u._Equal=u.asm.$).apply(null,arguments)},it=u._Exp=function(){return(it=u._Exp=u.asm.aa).apply(null,arguments)},Lt=u._FlipLeftRight=function(){return(Lt=u._FlipLeftRight=u.asm.ba).apply(null,arguments)},Rt=u._Floor=function(){return(Rt=u._Floor=u.asm.ca).apply(null,arguments)},Je=u._FloorDiv=function(){return(Je=u._FloorDiv=u.asm.da).apply(null,arguments)},Qe=u._FusedBatchNorm=function(){return(Qe=u._FusedBatchNorm=u.asm.ea).apply(null,arguments)},In=u._FusedConv2D=function(){return(In=u._FusedConv2D=u.asm.fa).apply(null,arguments)},Vr=u._FusedDepthwiseConv2D=function(){return(Vr=u._FusedDepthwiseConv2D=u.asm.ga).apply(null,arguments)},Ur=u._Gather=function(){return(Ur=u._Gather=u.asm.ha).apply(null,arguments)},Up=u._GatherNd=function(){return(Up=u._GatherNd=u.asm.ia).apply(null,arguments)},Sc=u._Greater=function(){return(Sc=u._Greater=u.asm.ja).apply(null,arguments)},ps=u._GreaterEqual=function(){return(ps=u._GreaterEqual=u.asm.ka).apply(null,arguments)},ga=u._LeakyRelu=function(){return(ga=u._LeakyRelu=u.asm.la).apply(null,arguments)},Gp=u._Less=function(){return(Gp=u._Less=u.asm.ma).apply(null,arguments)},IT=u._LessEqual=function(){return(IT=u._LessEqual=u.asm.na).apply(null,arguments)},ST=u._Log=function(){return(ST=u._Log=u.asm.oa).apply(null,arguments)},CT=u._LogicalAnd=function(){return(CT=u._LogicalAnd=u.asm.pa).apply(null,arguments)},TT=u._Max=function(){return(TT=u._Max=u.asm.qa).apply(null,arguments)},NT=u._MaxPool=function(){return(NT=u._MaxPool=u.asm.ra).apply(null,arguments)},ET=u._Maximum=function(){return(ET=u._Maximum=u.asm.sa).apply(null,arguments)},RT=u._Mean=function(){return(RT=u._Mean=u.asm.ta).apply(null,arguments)},$T=u._Min=function(){return($T=u._Min=u.asm.ua).apply(null,arguments)},DT=u._Minimum=function(){return(DT=u._Minimum=u.asm.va).apply(null,arguments)},_T=u._MirrorPad=function(){return(_T=u._MirrorPad=u.asm.wa).apply(null,arguments)},PT=u._Multiply=function(){return(PT=u._Multiply=u.asm.xa).apply(null,arguments)},FT=u._Neg=function(){return(FT=u._Neg=u.asm.ya).apply(null,arguments)},OT=u._NonMaxSuppressionV3=function(){return(OT=u._NonMaxSuppressionV3=u.asm.za).apply(null,arguments)},MT=u._NonMaxSuppressionV4=function(){return(MT=u._NonMaxSuppressionV4=u.asm.Aa).apply(null,arguments)},zT=u._NonMaxSuppressionV5=function(){return(zT=u._NonMaxSuppressionV5=u.asm.Ba).apply(null,arguments)},LT=u._NotEqual=function(){return(LT=u._NotEqual=u.asm.Ca).apply(null,arguments)},BT=u._OneHot=function(){return(BT=u._OneHot=u.asm.Da).apply(null,arguments)},WT=u._PadV2=function(){return(WT=u._PadV2=u.asm.Ea).apply(null,arguments)},VT=u._Pow=function(){return(VT=u._Pow=u.asm.Fa).apply(null,arguments)},UT=u._Prelu=function(){return(UT=u._Prelu=u.asm.Ga).apply(null,arguments)},GT=u._Prod=function(){return(GT=u._Prod=u.asm.Ha).apply(null,arguments)},HT=u._RealDiv=function(){return(HT=u._RealDiv=u.asm.Ia).apply(null,arguments)},jT=u._Relu=function(){return(jT=u._Relu=u.asm.Ja).apply(null,arguments)},qT=u._Relu6=function(){return(qT=u._Relu6=u.asm.Ka).apply(null,arguments)},XT=u._ResizeBilinear=function(){return(XT=u._ResizeBilinear=u.asm.La).apply(null,arguments)},KT=u._Reverse=function(){return(KT=u._Reverse=u.asm.Ma).apply(null,arguments)},ZT=u._RotateWithOffset=function(){return(ZT=u._RotateWithOffset=u.asm.Na).apply(null,arguments)},YT=u._Round=function(){return(YT=u._Round=u.asm.Oa).apply(null,arguments)},JT=u._Rsqrt=function(){return(JT=u._Rsqrt=u.asm.Pa).apply(null,arguments)},QT=u._ScatterNd=function(){return(QT=u._ScatterNd=u.asm.Qa).apply(null,arguments)},eN=u._SelectV2=function(){return(eN=u._SelectV2=u.asm.Ra).apply(null,arguments)},tN=u._Sigmoid=function(){return(tN=u._Sigmoid=u.asm.Sa).apply(null,arguments)},nN=u._Sin=function(){return(nN=u._Sin=u.asm.Ta).apply(null,arguments)},sN=u._Softmax=function(){return(sN=u._Softmax=u.asm.Ua).apply(null,arguments)},rN=u._Sqrt=function(){return(rN=u._Sqrt=u.asm.Va).apply(null,arguments)},aN=u._Square=function(){return(aN=u._Square=u.asm.Wa).apply(null,arguments)},oN=u._SquaredDifference=function(){return(oN=u._SquaredDifference=u.asm.Xa).apply(null,arguments)},iN=u._Step=function(){return(iN=u._Step=u.asm.Ya).apply(null,arguments)},lN=u._StridedSlice=function(){return(lN=u._StridedSlice=u.asm.Za).apply(null,arguments)},uN=u._Sub=function(){return(uN=u._Sub=u.asm._a).apply(null,arguments)},cN=u._Sum=function(){return(cN=u._Sum=u.asm.$a).apply(null,arguments)},dN=u._Tan=function(){return(dN=u._Tan=u.asm.ab).apply(null,arguments)},pN=u._Tanh=function(){return(pN=u._Tanh=u.asm.bb).apply(null,arguments)},hN=u._Tile=function(){return(hN=u._Tile=u.asm.cb).apply(null,arguments)},fN=u._TopK=function(){return(fN=u._TopK=u.asm.db).apply(null,arguments)},mN=u._Transform=function(){return(mN=u._Transform=u.asm.eb).apply(null,arguments)},gN=u._Transpose=function(){return(gN=u._Transpose=u.asm.fb).apply(null,arguments)},AN=u.__FusedMatMul=function(){return(AN=u.__FusedMatMul=u.asm.gb).apply(null,arguments)},Yo=u._malloc=function(){return(Yo=u._malloc=u.asm.hb).apply(null,arguments)},Cc=u._free=function(){return(Cc=u._free=u.asm.ib).apply(null,arguments)},Wb=u.___errno_location=function(){return(Wb=u.___errno_location=u.asm.jb).apply(null,arguments)},Vb=u._emscripten_get_global_libc=function(){return(Vb=u._emscripten_get_global_libc=u.asm.lb).apply(null,arguments)},Aa=u._pthread_self=function(){return(Aa=u._pthread_self=u.asm.mb).apply(null,arguments)},Ub=u.___pthread_tsd_run_dtors=function(){return(Ub=u.___pthread_tsd_run_dtors=u.asm.nb).apply(null,arguments)},Hp=u._emscripten_main_thread_process_queued_calls=function(){return(Hp=u._emscripten_main_thread_process_queued_calls=u.asm.ob).apply(null,arguments)},yN=u._emscripten_current_thread_process_queued_calls=function(){return(yN=u._emscripten_current_thread_process_queued_calls=u.asm.pb).apply(null,arguments)},Gb=u._emscripten_register_main_browser_thread_id=function(){return(Gb=u._emscripten_register_main_browser_thread_id=u.asm.qb).apply(null,arguments)},Hb=u._emscripten_main_browser_thread_id=function(){return(Hb=u._emscripten_main_browser_thread_id=u.asm.rb).apply(null,arguments)},jb=u.__emscripten_do_dispatch_to_thread=function(){return(jb=u.__emscripten_do_dispatch_to_thread=u.asm.sb).apply(null,arguments)},qb=u._emscripten_sync_run_in_main_thread_4=function(){return(qb=u._emscripten_sync_run_in_main_thread_4=u.asm.tb).apply(null,arguments)},Xb=u._emscripten_run_in_main_runtime_thread_js=function(){return(Xb=u._emscripten_run_in_main_runtime_thread_js=u.asm.ub).apply(null,arguments)},_g=u.__emscripten_call_on_thread=function(){return(_g=u.__emscripten_call_on_thread=u.asm.vb).apply(null,arguments)},xN=u._emscripten_tls_init=function(){return(xN=u._emscripten_tls_init=u.asm.wb).apply(null,arguments)},Pg=u.__emscripten_thread_init=function(){return(Pg=u.__emscripten_thread_init=u.asm.xb).apply(null,arguments)},Tc=u.stackSave=function(){return(Tc=u.stackSave=u.asm.yb).apply(null,arguments)},_l=u.stackRestore=function(){return(_l=u.stackRestore=u.asm.zb).apply(null,arguments)},Pl=u.stackAlloc=function(){return(Pl=u.stackAlloc=u.asm.Ab).apply(null,arguments)},Kb=u._emscripten_stack_set_limits=function(){return(Kb=u._emscripten_stack_set_limits=u.asm.Bb).apply(null,arguments)},Zb=u._memalign=function(){return(Zb=u._memalign=u.asm.Cb).apply(null,arguments)},Yb=u.__emscripten_allow_main_runtime_queued_calls=10064,Fl=u.__emscripten_main_thread_futex=10268;u.cwrap=Ue,u.PThread=Re,u.PThread=Re,u.wasmMemory=te,u.ExitStatus=Nc;var jp;function Nc(C){this.name="ExitStatus",this.message="Program terminated with exit("+C+")",this.status=C}Xo=function C(){jp||Fg(),jp||(Xo=C)};function Fg(C){if(C=C||m,Bs>0)return;if(k){d(u),Ip(),postMessage({cmd:"loaded"});return}if(kp(),Bs>0)return;function $(){jp||(jp=!0,u.calledRun=!0,!ce&&(Ip(),Sp(),d(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),Cp()))}u.setStatus?(u.setStatus("Running..."),setTimeout(function(){setTimeout(function(){u.setStatus("")},1),$()},1)):$()}u.run=Fg;function bN(C,$){if(!($&&J&&C===0)){if(!$&&k)throw postMessage({cmd:"exitProcess",returnCode:C}),new Nc(C);J||(Re.terminateAllThreads(),xe=C,Qn(),u.onExit&&u.onExit(C),ce=!0),A(C,new Nc(C))}}if(u.preInit)for(typeof u.preInit=="function"&&(u.preInit=[u.preInit]);u.preInit.length>0;)u.preInit.pop()();return k&&(J=!1,Re.initWorker()),Fg(),r.ready}}();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModuleThreadedSimd=n)}}),WN=ts({"src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js"(e,t){var n=function(){var s=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(s=s||__filename),function(r){r=r||{};var a=typeof r!="undefined"?r:{},o,i;a.ready=new Promise(function(re,oe){o=re,i=oe});var l={},c;for(c in a)a.hasOwnProperty(c)&&(l[c]=a[c]);var u=[],d="./this.program",p=function(re,oe){throw oe},h=!1,f=!1,m=!1,g=!1;h=typeof window=="object",f=typeof importScripts=="function",m=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g=!h&&!m&&!f;var A="";function y(re){return a.locateFile?a.locateFile(re,A):A+re}var x,b,w,k,S,E;m?(f?A=Ws("path").dirname(A)+"/":A=__dirname+"/",x=function(oe,ke){return S||(S=Ws("fs")),E||(E=Ws("path")),oe=E.normalize(oe),S.readFileSync(oe,ke?null:"utf8")},w=function(oe){var ke=x(oe,!0);return ke.buffer||(ke=new Uint8Array(ke)),H(ke.buffer),ke},process.argv.length>1&&(d=process.argv[1].replace(/\\/g,"/")),u=process.argv.slice(2),process.on("uncaughtException",function(re){if(!(re instanceof Dg))throw re}),process.on("unhandledRejection",sr),p=function(re){process.exit(re)},a.inspect=function(){return"[Emscripten Module object]"}):g?(typeof read!="undefined"&&(x=function(oe){return read(oe)}),w=function(oe){var ke;return typeof readbuffer=="function"?new Uint8Array(readbuffer(oe)):(ke=read(oe,"binary"),H(typeof ke=="object"),ke)},typeof scriptArgs!="undefined"?u=scriptArgs:typeof arguments!="undefined"&&(u=arguments),typeof quit=="function"&&(p=function(re){quit(re)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(h||f)&&(f?A=self.location.href:typeof document!="undefined"&&document.currentScript&&(A=document.currentScript.src),s&&(A=s),A.indexOf("blob:")!==0?A=A.substr(0,A.lastIndexOf("/")+1):A="",x=function(re){var oe=new XMLHttpRequest;return oe.open("GET",re,!1),oe.send(null),oe.responseText},f&&(w=function(re){var oe=new XMLHttpRequest;return oe.open("GET",re,!1),oe.responseType="arraybuffer",oe.send(null),new Uint8Array(oe.response)}),b=function(re,oe,ke){var it=new XMLHttpRequest;it.open("GET",re,!0),it.responseType="arraybuffer",it.onload=function(){if(it.status==200||it.status==0&&it.response){oe(it.response);return}ke()},it.onerror=ke,it.send(null)},k=function(re){document.title=re});var P=a.print||console.log.bind(console),F=a.printErr||console.warn.bind(console);for(c in l)l.hasOwnProperty(c)&&(a[c]=l[c]);l=null,a.arguments&&(u=a.arguments),a.thisProgram&&(d=a.thisProgram),a.quit&&(p=a.quit);var R;a.wasmBinary&&(R=a.wasmBinary);var _=a.noExitRuntime||!0;typeof WebAssembly!="object"&&sr("no native wasm support detected");var T,M=!1,U;function H(re,oe){re||sr("Assertion failed: "+oe)}function z(re){var oe=a["_"+re];return H(oe,"Cannot call unknown function "+re+", make sure it is exported"),oe}function X(re,oe,ke,it,Lt){var Rt={string:function(ps){var ga=0;if(ps!=null&&ps!==0){var Gp=(ps.length<<2)+1;ga=kc(Gp),te(ps,ga,Gp)}return ga},array:function(ps){var ga=kc(ps.length);return ue(ps,ga),ga}};function Je(ps){return oe==="string"?ne(ps):oe==="boolean"?Boolean(ps):ps}var Qe=z(re),In=[],Vr=0;if(it)for(var Ur=0;Ur=it);)++Lt;if(Lt-oe>16&&re.subarray&&Y)return Y.decode(re.subarray(oe,Lt));for(var Rt="";oe>10,56320|Vr&1023)}}return Rt}function ne(re,oe){return re?se(Ce,re,oe):""}function J(re,oe,ke,it){if(!(it>0))return 0;for(var Lt=ke,Rt=ke+it-1,Je=0;Je=55296&&Qe<=57343){var In=re.charCodeAt(++Je);Qe=65536+((Qe&1023)<<10)|In&1023}if(Qe<=127){if(ke>=Rt)break;oe[ke++]=Qe}else if(Qe<=2047){if(ke+1>=Rt)break;oe[ke++]=192|Qe>>6,oe[ke++]=128|Qe&63}else if(Qe<=65535){if(ke+2>=Rt)break;oe[ke++]=224|Qe>>12,oe[ke++]=128|Qe>>6&63,oe[ke++]=128|Qe&63}else{if(ke+3>=Rt)break;oe[ke++]=240|Qe>>18,oe[ke++]=128|Qe>>12&63,oe[ke++]=128|Qe>>6&63,oe[ke++]=128|Qe&63}}return oe[ke]=0,ke-Lt}function te(re,oe,ke){return J(re,Ce,oe,ke)}function ue(re,oe){we.set(re,oe)}function ce(re,oe){return re%oe>0&&(re+=oe-re%oe),re}var xe,we,Ce,Oe,Ue,Xe,rt,ft,ut;function ct(re){xe=re,a.HEAP8=we=new Int8Array(re),a.HEAP16=Oe=new Int16Array(re),a.HEAP32=Xe=new Int32Array(re),a.HEAPU8=Ce=new Uint8Array(re),a.HEAPU16=Ue=new Uint16Array(re),a.HEAPU32=rt=new Uint32Array(re),a.HEAPF32=ft=new Float32Array(re),a.HEAPF64=ut=new Float64Array(re)}var At=a.INITIAL_MEMORY||16777216,yt,Et=[],Pt=[],Jn=[],wn=[],nr=!1;Pt.push({func:function(){Ep()}});function On(){if(a.preRun)for(typeof a.preRun=="function"&&(a.preRun=[a.preRun]);a.preRun.length;)kn(a.preRun.shift());Bs(Et)}function ds(){nr=!0,Bs(Pt)}function Ls(){Bs(Jn)}function Is(){if(a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;)br(a.postRun.shift());Bs(wn)}function kn(re){Et.unshift(re)}function br(re){wn.unshift(re)}var Rn=0,vr=null,wr=null;function pa(re){Rn++,a.monitorRunDependencies&&a.monitorRunDependencies(Rn)}function Ac(re){if(Rn--,a.monitorRunDependencies&&a.monitorRunDependencies(Rn),Rn==0&&(vr!==null&&(clearInterval(vr),vr=null),wr)){var oe=wr;wr=null,oe()}}a.preloadedImages={},a.preloadedAudios={};function sr(re){a.onAbort&&a.onAbort(re),re+="",F(re),M=!0,U=1,re="abort("+re+"). Build with -s ASSERTIONS=1 for more info.";var oe=new WebAssembly.RuntimeError(re);throw i(oe),oe}function wp(re,oe){return String.prototype.startsWith?re.startsWith(oe):re.indexOf(oe)===0}var f0="data:application/octet-stream;base64,";function kp(re){return wp(re,f0)}var Ip="file://";function Sp(re){return wp(re,Ip)}var Qn="tfjs-backend-wasm.wasm";kp(Qn)||(Qn=y(Qn));function Cp(re){try{if(re==Qn&&R)return new Uint8Array(R);if(w)return w(re);throw"both async and sync fetching of the wasm failed"}catch(oe){sr(oe)}}function m0(){if(!R&&(h||f)){if(typeof fetch=="function"&&!Sp(Qn))return fetch(Qn,{credentials:"same-origin"}).then(function(re){if(!re.ok)throw"failed to load wasm binary file at '"+Qn+"'";return re.arrayBuffer()}).catch(function(){return Cp(Qn)});if(b)return new Promise(function(re,oe){b(Qn,function(ke){re(new Uint8Array(ke))},oe)})}return Promise.resolve().then(function(){return Cp(Qn)})}function g0(){var re={a:es};function oe(Je,Qe){var In=Je.exports;a.asm=In,T=a.asm.h,ct(T.buffer),yt=a.asm.Sa,Ac("wasm-instantiate")}pa("wasm-instantiate");function ke(Je){oe(Je.instance)}function it(Je){return m0().then(function(Qe){return WebAssembly.instantiate(Qe,re)}).then(Je,function(Qe){F("failed to asynchronously prepare wasm: "+Qe),sr(Qe)})}function Lt(){return!R&&typeof WebAssembly.instantiateStreaming=="function"&&!kp(Qn)&&!Sp(Qn)&&typeof fetch=="function"?fetch(Qn,{credentials:"same-origin"}).then(function(Je){var Qe=WebAssembly.instantiateStreaming(Je,re);return Qe.then(ke,function(In){return F("wasm streaming compile failed: "+In),F("falling back to ArrayBuffer instantiation"),it(ke)})}):it(ke)}if(a.instantiateWasm)try{var Rt=a.instantiateWasm(re,oe);return Rt}catch(Je){return F("Module.instantiateWasm callback failed with error: "+Je),!1}return Lt().catch(i),{}}function Bs(re){for(;re.length>0;){var oe=re.shift();if(typeof oe=="function"){oe(a);continue}var ke=oe.func;typeof ke=="number"?oe.arg===void 0?yt.get(ke)():yt.get(ke)(oe.arg):ke(oe.arg===void 0?null:oe.arg)}}function yc(){sr()}function Xo(re,oe,ke){Ce.copyWithin(re,oe,oe+ke)}function A0(){return Ce.length}function y0(re){try{return T.grow(re-xe.byteLength+65535>>>16),ct(T.buffer),1}catch(oe){}}function Wr(re){var oe=A0(),ke=2147483648;if(re>ke)return!1;for(var it=1;it<=4;it*=2){var Lt=oe*(1+.2/it);Lt=Math.min(Lt,re+100663296);var Rt=Math.min(ke,ce(Math.max(re,Lt),65536)),Je=y0(Rt);if(Je)return!0}return!1}var Ko={mappings:{},buffers:[null,[],[]],printChar:function(re,oe){var ke=Ko.buffers[re];oe===0||oe===10?((re===1?P:F)(se(ke,0)),ke.length=0):ke.push(oe)},varargs:void 0,get:function(){Ko.varargs+=4;var re=Xe[Ko.varargs-4>>2];return re},getStr:function(re){var oe=ne(re);return oe},get64:function(re,oe){return re}};function x0(re){return 0}function Tp(re,oe,ke,it,Lt){}function b0(re,oe,ke,it){for(var Lt=0,Rt=0;Rt>2],Qe=Xe[oe+(Rt*8+4)>>2],In=0;In>2]=Lt,0}function Np(){return 28}var es={a:yc,d:Xo,e:Wr,f:x0,c:Tp,b:b0,g:Np},v0=g0(),Ep=a.___wasm_call_ctors=function(){return(Ep=a.___wasm_call_ctors=a.asm.i).apply(null,arguments)},w0=a._init=function(){return(w0=a._init=a.asm.j).apply(null,arguments)},Rp=a._init_with_threads_count=function(){return(Rp=a._init_with_threads_count=a.asm.k).apply(null,arguments)},k0=a._get_threads_count=function(){return(k0=a._get_threads_count=a.asm.l).apply(null,arguments)},Rl=a._register_tensor=function(){return(Rl=a._register_tensor=a.asm.m).apply(null,arguments)},ha=a._dispose_data=function(){return(ha=a._dispose_data=a.asm.n).apply(null,arguments)},xc=a._dispose=function(){return(xc=a._dispose=a.asm.o).apply(null,arguments)},I0=a._Abs=function(){return(I0=a._Abs=a.asm.p).apply(null,arguments)},S0=a._Add=function(){return(S0=a._Add=a.asm.q).apply(null,arguments)},$p=a._AddN=function(){return($p=a._AddN=a.asm.r).apply(null,arguments)},Re=a._All=function(){return(Re=a._All=a.asm.s).apply(null,arguments)},C0=a._Any=function(){return(C0=a._Any=a.asm.t).apply(null,arguments)},T0=a._ArgMax=function(){return(T0=a._ArgMax=a.asm.u).apply(null,arguments)},N0=a._AvgPool=function(){return(N0=a._AvgPool=a.asm.v).apply(null,arguments)},E0=a._BatchMatMul=function(){return(E0=a._BatchMatMul=a.asm.w).apply(null,arguments)},R0=a._Ceil=function(){return(R0=a._Ceil=a.asm.x).apply(null,arguments)},Zo=a._ClipByValue=function(){return(Zo=a._ClipByValue=a.asm.y).apply(null,arguments)},$0=a._Conv2D=function(){return($0=a._Conv2D=a.asm.z).apply(null,arguments)},D0=a._Conv2DBackpropInput=function(){return(D0=a._Conv2DBackpropInput=a.asm.A).apply(null,arguments)},_0=a._Cos=function(){return(_0=a._Cos=a.asm.B).apply(null,arguments)},P0=a._Cosh=function(){return(P0=a._Cosh=a.asm.C).apply(null,arguments)},F0=a._CropAndResize=function(){return(F0=a._CropAndResize=a.asm.D).apply(null,arguments)},O0=a._Cumsum=function(){return(O0=a._Cumsum=a.asm.E).apply(null,arguments)},Dp=a._DepthToSpace=function(){return(Dp=a._DepthToSpace=a.asm.F).apply(null,arguments)},M0=a._DepthwiseConv2dNative=function(){return(M0=a._DepthwiseConv2dNative=a.asm.G).apply(null,arguments)},z0=a._Elu=function(){return(z0=a._Elu=a.asm.H).apply(null,arguments)},fa=a._Equal=function(){return(fa=a._Equal=a.asm.I).apply(null,arguments)},bc=a._Exp=function(){return(bc=a._Exp=a.asm.J).apply(null,arguments)},vc=a._FlipLeftRight=function(){return(vc=a._FlipLeftRight=a.asm.K).apply(null,arguments)},L0=a._Floor=function(){return(L0=a._Floor=a.asm.L).apply(null,arguments)},B0=a._FloorDiv=function(){return(B0=a._FloorDiv=a.asm.M).apply(null,arguments)},W0=a._FusedBatchNorm=function(){return(W0=a._FusedBatchNorm=a.asm.N).apply(null,arguments)},V0=a._FusedConv2D=function(){return(V0=a._FusedConv2D=a.asm.O).apply(null,arguments)},U0=a._FusedDepthwiseConv2D=function(){return(U0=a._FusedDepthwiseConv2D=a.asm.P).apply(null,arguments)},Ge=a._Gather=function(){return(Ge=a._Gather=a.asm.Q).apply(null,arguments)},G0=a._GatherNd=function(){return(G0=a._GatherNd=a.asm.R).apply(null,arguments)},H0=a._Greater=function(){return(H0=a._Greater=a.asm.S).apply(null,arguments)},j0=a._GreaterEqual=function(){return(j0=a._GreaterEqual=a.asm.T).apply(null,arguments)},q0=a._LeakyRelu=function(){return(q0=a._LeakyRelu=a.asm.U).apply(null,arguments)},X0=a._Less=function(){return(X0=a._Less=a.asm.V).apply(null,arguments)},K0=a._LessEqual=function(){return(K0=a._LessEqual=a.asm.W).apply(null,arguments)},wc=a._Log=function(){return(wc=a._Log=a.asm.X).apply(null,arguments)},_p=a._LogicalAnd=function(){return(_p=a._LogicalAnd=a.asm.Y).apply(null,arguments)},Pp=a._Max=function(){return(Pp=a._Max=a.asm.Z).apply(null,arguments)},Z0=a._MaxPool=function(){return(Z0=a._MaxPool=a.asm._).apply(null,arguments)},Y0=a._Maximum=function(){return(Y0=a._Maximum=a.asm.$).apply(null,arguments)},J0=a._Mean=function(){return(J0=a._Mean=a.asm.aa).apply(null,arguments)},Q0=a._Min=function(){return(Q0=a._Min=a.asm.ba).apply(null,arguments)},eg=a._Minimum=function(){return(eg=a._Minimum=a.asm.ca).apply(null,arguments)},tg=a._MirrorPad=function(){return(tg=a._MirrorPad=a.asm.da).apply(null,arguments)},ng=a._Multiply=function(){return(ng=a._Multiply=a.asm.ea).apply(null,arguments)},dt=a._Neg=function(){return(dt=a._Neg=a.asm.fa).apply(null,arguments)},sg=a._NonMaxSuppressionV3=function(){return(sg=a._NonMaxSuppressionV3=a.asm.ga).apply(null,arguments)},rg=a._NonMaxSuppressionV4=function(){return(rg=a._NonMaxSuppressionV4=a.asm.ha).apply(null,arguments)},ag=a._NonMaxSuppressionV5=function(){return(ag=a._NonMaxSuppressionV5=a.asm.ia).apply(null,arguments)},$l=a._NotEqual=function(){return($l=a._NotEqual=a.asm.ja).apply(null,arguments)},Fp=a._OneHot=function(){return(Fp=a._OneHot=a.asm.ka).apply(null,arguments)},Op=a._PadV2=function(){return(Op=a._PadV2=a.asm.la).apply(null,arguments)},Mp=a._Pow=function(){return(Mp=a._Pow=a.asm.ma).apply(null,arguments)},og=a._Prelu=function(){return(og=a._Prelu=a.asm.na).apply(null,arguments)},ig=a._Prod=function(){return(ig=a._Prod=a.asm.oa).apply(null,arguments)},zp=a._RealDiv=function(){return(zp=a._RealDiv=a.asm.pa).apply(null,arguments)},lg=a._Relu=function(){return(lg=a._Relu=a.asm.qa).apply(null,arguments)},ug=a._Relu6=function(){return(ug=a._Relu6=a.asm.ra).apply(null,arguments)},cg=a._ResizeBilinear=function(){return(cg=a._ResizeBilinear=a.asm.sa).apply(null,arguments)},dg=a._Reverse=function(){return(dg=a._Reverse=a.asm.ta).apply(null,arguments)},pg=a._RotateWithOffset=function(){return(pg=a._RotateWithOffset=a.asm.ua).apply(null,arguments)},Lp=a._Round=function(){return(Lp=a._Round=a.asm.va).apply(null,arguments)},ma=a._Rsqrt=function(){return(ma=a._Rsqrt=a.asm.wa).apply(null,arguments)},hg=a._ScatterNd=function(){return(hg=a._ScatterNd=a.asm.xa).apply(null,arguments)},fg=a._SelectV2=function(){return(fg=a._SelectV2=a.asm.ya).apply(null,arguments)},Bb=a._Sigmoid=function(){return(Bb=a._Sigmoid=a.asm.za).apply(null,arguments)},Bp=a._Sin=function(){return(Bp=a._Sin=a.asm.Aa).apply(null,arguments)},mg=a._Softmax=function(){return(mg=a._Softmax=a.asm.Ba).apply(null,arguments)},gg=a._Sqrt=function(){return(gg=a._Sqrt=a.asm.Ca).apply(null,arguments)},Ag=a._Square=function(){return(Ag=a._Square=a.asm.Da).apply(null,arguments)},yg=a._SquaredDifference=function(){return(yg=a._SquaredDifference=a.asm.Ea).apply(null,arguments)},xg=a._Step=function(){return(xg=a._Step=a.asm.Fa).apply(null,arguments)},bg=a._StridedSlice=function(){return(bg=a._StridedSlice=a.asm.Ga).apply(null,arguments)},vg=a._Sub=function(){return(vg=a._Sub=a.asm.Ha).apply(null,arguments)},wg=a._Sum=function(){return(wg=a._Sum=a.asm.Ia).apply(null,arguments)},kg=a._Tan=function(){return(kg=a._Tan=a.asm.Ja).apply(null,arguments)},Ig=a._Tanh=function(){return(Ig=a._Tanh=a.asm.Ka).apply(null,arguments)},Sg=a._Tile=function(){return(Sg=a._Tile=a.asm.La).apply(null,arguments)},Cg=a._TopK=function(){return(Cg=a._TopK=a.asm.Ma).apply(null,arguments)},Tg=a._Transform=function(){return(Tg=a._Transform=a.asm.Na).apply(null,arguments)},Ng=a._Transpose=function(){return(Ng=a._Transpose=a.asm.Oa).apply(null,arguments)},Eg=a.__FusedMatMul=function(){return(Eg=a.__FusedMatMul=a.asm.Pa).apply(null,arguments)},Rg=a._malloc=function(){return(Rg=a._malloc=a.asm.Qa).apply(null,arguments)},$g=a._free=function(){return($g=a._free=a.asm.Ra).apply(null,arguments)},Wp=a.stackSave=function(){return(Wp=a.stackSave=a.asm.Ta).apply(null,arguments)},Vp=a.stackRestore=function(){return(Vp=a.stackRestore=a.asm.Ua).apply(null,arguments)},kc=a.stackAlloc=function(){return(kc=a.stackAlloc=a.asm.Va).apply(null,arguments)};a.cwrap=ee;var Dl;function Dg(re){this.name="ExitStatus",this.message="Program terminated with exit("+re+")",this.status=re}wr=function re(){Dl||Ic(),Dl||(wr=re)};function Ic(re){if(re=re||u,Rn>0||(On(),Rn>0))return;function oe(){Dl||(Dl=!0,a.calledRun=!0,!M&&(ds(),Ls(),o(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),Is()))}a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),oe()},1)):oe()}if(a.run=Ic,a.preInit)for(typeof a.preInit=="function"&&(a.preInit=[a.preInit]);a.preInit.length>0;)a.preInit.pop()();return Ic(),r.ready}}();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModule=n)}}),VN=1e-7,UN=1e-4,Dc=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}},Ll=class{refCount(e){return Vs("refCount")}incRef(e){return Vs("incRef")}timerAvailable(){return!0}time(e){return Vs("time")}read(e){return Vs("read")}readSync(e){return Vs("readSync")}numDataIds(){return Vs("numDataIds")}disposeData(e,t){return Vs("disposeData")}write(e,t,n){return Vs("write")}move(e,t,n,s,r){return Vs("move")}memory(){return Vs("memory")}floatPrecision(){return Vs("floatPrecision")}epsilon(){return this.floatPrecision()===32?VN:UN}dispose(){return Vs("dispose")}};function Vs(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 n5(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,Zp(e,t,n)}function GN(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,s=0;for(;n>0;)s=Math.random()*n|0,n--,Zp(e,n,s),Zp(t,n,s)}function _c(e,t,n){return Math.max(e,Math.min(t,n))}function HN(e){return e%2==0?e:e+1}function Zp(e,t,n){let s=e[t];e[t]=e[n],e[n]=s}function jN(e){let t=0;for(let n=0;nn+` Shapes ${e} and ${t} must match`)}function ei(e){O(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function ti(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||Dn(e)&&!n)for(let s=0;s0,n){return new Promise((s,r)=>{let a=0,o=()=>{if(e()){s();return}a++;let i=t(a);if(n!=null&&a>=n){r();return}setTimeout(o,i)};o()})}function eE(e,t){let n=1,s=-1;for(let a=0;a=0)n*=e[a];else if(e[a]===-1){if(s!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${a}`);s=a}else if(e[a]<0)throw Error(`Shapes can not be < 0. Found ${e[a]} at dim ${a}`);if(s===-1){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(n===0)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);let r=e.slice();return r[s]=t/n,r}function Us(e,t){let n=t.length;return e=e==null?t.map((s,r)=>r):[].concat(e),O(e.every(s=>s>=-n&&s`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),O(e.every(s=>mn(s)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(s=>s<0?n+s:s)}function s5(e,t){let n=[],s=[],r=t!=null&&Array.isArray(t)&&t.length===0,a=t==null||r?null:Us(t,e).sort(),o=0;for(let i=0;ii)&&e[i]===1&&(n.push(e[i]),s.push(i)),a[o]<=i&&o++}e[i]!==1&&(n.push(e[i]),s.push(i))}return{newShape:n,keptDims:s}}function r5(e,t){let n=null;if(e==null||e==="float32")n=new Float32Array(t);else if(e==="int32")n=new Int32Array(t);else if(e==="bool")n=new Uint8Array(t);else throw new Error(`Unknown data type ${e}`);return n}function a5(e,t){let n=null;if(e==null||e==="float32")n=new Float32Array(t);else if(e==="int32")n=new Int32Array(t);else if(e==="bool")n=new Uint8Array(t);else if(e==="string")n=new Array(t);else throw new Error(`Unknown data type ${e}`);return n}function o5(e,t){for(let n=0;nt+=n.length),t}function ba(e){return typeof e=="string"||e instanceof String}function u5(e){return typeof e=="boolean"}function c5(e){return typeof e=="number"}function Yp(e){return Array.isArray(e)?Yp(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":c5(e)?"float32":ba(e)?"string":u5(e)?"bool":"float32"}function va(e){return!!(e&&e.constructor&&e.call&&e.apply)}function Jp(e,t){for(let n=t;n=0;--s)n[s]=n[s+1]*e[s+1];return n}function d5(e,t,n,s=!1){let r=new Array;if(t.length===1){let a=t[0]*(s?2:1);for(let o=0;ol*c)*(s?2:1);for(let l=0;lr*a)*(n?2:1);if(s===0)return[];if(s!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return d5(0,e,t,n)}function Lg(e,t){let n=Qp(e,t);for(let s=0;ss*r,1);if(t==null||t==="float32")return Wl(e,new Float32Array(n));if(t==="int32")return Wl(e,new Int32Array(n));if(t==="bool")return Wl(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function Bg(e){e.forEach(t=>{O(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function sE(e,t,n){if(t===0)return 0;if(t===1)return e[0];let s=e[e.length-1];for(let r=0;r{let[s,r]=n.split(":");this.urlFlags[s]=lE(s,r)})}};function oE(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...s)=>(iE(t,s[0],s[1]),s.join("="))),t}function iE(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function lE(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 K(){return Ir}var Ir=null;function uE(e){Ir=e}var Vg;function f5(){if(Vg==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");Vg=e}return Vg}function cE(){let e=f5();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function Ug(e,t){let n=cE();if(n.has(e))return n.get(e);{let s=t();return n.set(e,s),n.get(e)}}var ni="Abs",Vl="Acos",Ul="Acosh",Hr="Add",wa="AddN",Gl="All",Hl="Any",ka="ArgMax",jl="ArgMin",ql="Asin",Xl="Asinh",Kl="Atan",Zl="Atanh",Yl="Atan2",Ia="AvgPool",eh="AvgPoolGrad",Fc="AvgPool3D",th="AvgPool3DGrad",Sa="BatchMatMul",si="BatchToSpaceND",nh="Bincount",m5="BroadcastTo",sh="BroadcastArgs",Ca="Cast",Ta="Ceil",jr="ClipByValue",Oc="Complex",Mc="ComplexAbs",ri="Concat",Na="Conv2D",rh="Conv2DBackpropFilter",Ea="Conv2DBackpropInput",zc="Conv3D",ah="Conv3DBackpropFilterV2",oh="Conv3DBackpropInputV2",Ra="Cos",$a="Cosh",ai="Cumsum",oi="CropAndResize",ih="DenseBincount",ii="DepthToSpace",Da="DepthwiseConv2dNative",lh="DepthwiseConv2dNativeBackpropFilter",uh="DepthwiseConv2dNativeBackpropInput",ch="Diag",Lc="Dilation2D",dh="Dilation2DBackpropInput",ph="Dilation2DBackpropFilter",_a="RealDiv",Bc="Einsum",Pa="Elu",hh="EluGrad",Jl="Erf",li="Equal",Fa="Exp",ui="ExpandDims",ci="Expm1",fh="FFT",Ql="Fill",di="FlipLeftRight",Oa="Floor",Ma="FloorDiv",za="FusedBatchNorm",pi="GatherV2",hi="GatherNd",fi="Greater",La="GreaterEqual",Ba="Identity",mh="IFFT",Wc="Imag",eu="IsFinite",tu="IsInf",nu="IsNan",mi="LeakyRelu",gi="Less",Ai="LessEqual",gh="LinSpace",Wa="Log",su="Log1p",yi="LogicalAnd",ru="LogicalNot",Vc="LogicalOr",g5="LogSoftmax",Uc="LRN",Ah="LRNGrad",Va="Max",Ua="Maximum",Ga="MaxPool",yh="MaxPoolGrad",Gc="MaxPool3D",xh="MaxPool3DGrad",bh="MaxPoolWithArgmax",Ha="Mean",ja="Min",qa="Minimum",Xa="MirrorPad",au="Mod",vh="Multinomial",Ka="Multiply",xi="Neg",bi="NotEqual",vi="NonMaxSuppressionV3",ou="NonMaxSuppressionV4",wi="NonMaxSuppressionV5",ki="OnesLike",Ii="OneHot",Si="Pack",Za="PadV2",dE="Pool",Ya="Pow",Ja="Prelu",Ci="Prod",iu="Range",Hc="Real",lu="Reciprocal",Qa="Relu",Ti="Reshape",uu="ResizeNearestNeighbor",wh="ResizeNearestNeighborGrad",eo="ResizeBilinear",kh="ResizeBilinearGrad",to="Relu6",Ni="Reverse",Ei="Round",no="Rsqrt",Ri="ScatterNd",$i="Select",cu="Selu",Di="Slice",so="Sin",_i="Sinh",du="Sign",ro="Sigmoid",pu="Softplus",ao="Sqrt",oo="Sum",Pi="SpaceToBatchND",Fi="SplitV",io="Softmax",Ih="SparseFillEmptyRows",Sh="SparseReshape",Ch="SparseSegmentMean",Th="SparseSegmentSum",jc="SparseToDense",lo="SquaredDifference",hu="Square",Oi="StridedSlice",qc="StringNGrams",Nh="StringSplit",Eh="StringToHashBucketFast",uo="Sub",Mi="Tan",co="Tanh",qr="Tile",zi="TopK",Li="Transform",po="Transpose",Rh="Unique",Bi="Unpack",Xc="UnsortedSegmentSum",Wi="ZerosLike",ho="Step",Kc="FromPixels",Vi="RotateWithOffset",fo="_FusedMatMul",mo="FusedConv2D",go="FusedDepthwiseConv2D",fu=Ug("kernelRegistry",()=>new Map),Zc=Ug("gradRegistry",()=>new Map);function $h(e,t){let n=Hg(e,t);return fu.get(n)}function Gg(e){return Zc.get(e)}function Xr(e){let t=fu.entries(),n=[];for(;;){let{done:s,value:r}=t.next();if(s)break;let[a,o]=r,[i]=a.split("_");i===e&&n.push(o)}return n}function Kr(e){let{kernelName:t,backendName:n}=e,s=Hg(t,n);fu.has(s)&&kr(`The kernel '${t}' for backend '${n}' is already registered`),fu.set(s,e)}function A5(e){let{kernelName:t}=e;Zc.has(t)&&K().getBool("DEBUG")&&kr(`Overriding the gradient for '${t}'`),Zc.set(t,e)}function pE(e,t){let n=Hg(e,t);if(!fu.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);fu.delete(n)}function hE(e){if(!Zc.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Zc.delete(e)}function fE(e,t){Xr(e).forEach(s=>{let r=Object.assign({},s,{backendName:t});Kr(r)})}function Hg(e,t){return`${t}_${e}`}var v={};ze(v,{arraysEqual:()=>Gr,assert:()=>O,assertNonNegativeIntegerDimensions:()=>Bg,assertNonNull:()=>ei,assertShapesMatch:()=>zn,bytesFromStringArray:()=>l5,bytesPerElement:()=>zg,checkConversionForErrors:()=>o5,clamp:()=>_c,computeStrides:()=>Bl,createScalarValue:()=>bE,createShuffledIndices:()=>JN,decodeString:()=>Ph,distSquared:()=>XN,encodeString:()=>Qc,fetch:()=>wE,fingerPrint64:()=>xE,flatten:()=>ti,getArrayFromDType:()=>a5,getTypedArrayFromDType:()=>r5,hasEncodingLoss:()=>tE,hexToLong:()=>Yc,indexToLoc:()=>rE,inferDtype:()=>Yp,inferFromImplicitShape:()=>eE,isBoolean:()=>u5,isFunction:()=>va,isInt:()=>mn,isNumber:()=>c5,isPromise:()=>Wg,isScalarShape:()=>KN,isString:()=>ba,isTypedArray:()=>Dn,isValidDtype:()=>i5,locToIndex:()=>sE,makeOnesTypedArray:()=>Lg,makeZerosNestedTypedArray:()=>nE,makeZerosTypedArray:()=>Qp,nearestDivisor:()=>Jp,nearestLargerEven:()=>HN,now:()=>Jc,parseAxisParam:()=>Us,randUniform:()=>qN,repeatedTry:()=>QN,rightPad:()=>Pc,shuffle:()=>n5,shuffleCombo:()=>GN,sizeFromShape:()=>Ut,sizeToSquarishShape:()=>YN,squeezeShape:()=>s5,sum:()=>jN,swap:()=>Zp,tanh:()=>ZN,toNestedArray:()=>Wl,toTypedArray:()=>_h});var y5=Qo(EN()),Ui=y5.default||y5;function Yc(e){return Ui.fromString(e,!0,16)}var x5=Yc("c3a5c85c97cb3127"),Gi=Yc("b492b66fbe98f273"),Ln=Yc("9ae16a3b2f90404f");function jg(e){return e.xor(e.shru(47))}function b5(e,t,n){let s=e.slice(t,t+n);return Ui.fromBytes(Array.from(s),!0,!0)}function kt(e,t){return b5(e,t,8)}function v5(e,t){return b5(e,t,4)}function gn(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function Ao(e,t,n=Yc("9ddfea08eb382d69")){let s=e.xor(t).mul(n);s=s.xor(s.shru(47));let r=t.xor(s).mul(n);return r=r.xor(r.shru(47)),r=r.mul(n),r}function mE(e,t,n,s,r,a){r=r.add(e),a=gn(a.add(r).add(s),21);let o=r;return r=r.add(t),r=r.add(n),a=a.add(gn(r,44)),[r.add(s),a.add(o)]}function Dh(e,t,n,s){return mE(kt(e,t),kt(e,t+8),kt(e,t+16),kt(e,t+24),n,s)}function gE(e,t=e.length){if(t>=8){let n=Ln.add(t*2),s=kt(e,0).add(Ln),r=kt(e,t-8),a=gn(r,37).mul(n).add(s),o=gn(s,25).add(r).mul(n);return Ao(a,o,n)}if(t>=4){let n=Ln.add(t*2),s=v5(e,0);return Ao(s.shl(3).add(t),v5(e,t-4),n)}if(t>0){let n=e[0],s=e[t>>1],r=e[t-1],a=n+(s<<8),o=t+(r<<2);return jg(Ln.mul(a).xor(x5.mul(o))).mul(Ln)}return Ln}function AE(e,t=e.length){let n=Ln.add(t*2),s=kt(e,0).mul(Gi),r=kt(e,8),a=kt(e,t-8).mul(n),o=kt(e,t-16).mul(Ln);return Ao(gn(s.add(r),43).add(gn(a,30)).add(o),s.add(gn(r.add(Ln),18)).add(a),n)}function yE(e,t=e.length){let n=Ln.add(t*2),s=kt(e,0).mul(Ln),r=kt(e,8),a=kt(e,t-8).mul(n),o=kt(e,t-16).mul(Ln),i=gn(s.add(r),43).add(gn(a,30)).add(o),l=Ao(i,s.add(gn(r.add(Ln),18)).add(a),n),c=kt(e,16).mul(n),u=kt(e,24),d=i.add(kt(e,t-32)).mul(n),p=l.add(kt(e,t-24)).mul(n);return Ao(gn(c.add(u),43).add(gn(d,30)).add(p),c.add(gn(u.add(s),18)).add(d),n)}function xE(e,t=e.length){let n=Ui.fromNumber(81,!0);if(t<=32)return t<=16?gE(e,t):AE(e,t);if(t<=64)return yE(e,t);let s=n,r=n.mul(Gi).add(113),a=jg(r.mul(Ln).add(113)).mul(Ln),o=[Ui.UZERO,Ui.UZERO],i=[Ui.UZERO,Ui.UZERO];s=s.mul(Ln).add(kt(e,0));let l=0,c=(t-1>>6)*64,u=c+(t-1&63)-63;do s=gn(s.add(r).add(o[0]).add(kt(e,l+8)),37).mul(Gi),r=gn(r.add(o[1]).add(kt(e,l+48)),42).mul(Gi),s=s.xor(i[1]),r=r.add(o[0]).add(kt(e,l+40)),a=gn(a.add(i[0]),33).mul(Gi),o=Dh(e,l,o[1].mul(Gi),s.add(i[0])),i=Dh(e,l+32,a.add(i[1]),r.add(kt(e,l+16))),[a,s]=[s,a],l+=64;while(l!==c);let d=Gi.add(a.and(255).shl(1));return l=u,i[0]=i[0].add(t-1&63),o[0]=o[0].add(i[0]),i[0]=i[0].add(o[0]),s=gn(s.add(r).add(o[0]).add(kt(e,l+8)),37).mul(d),r=gn(r.add(o[1]).add(kt(e,l+48)),42).mul(d),s=s.xor(i[1].mul(9)),r=r.add(o[0].mul(9).add(kt(e,l+40))),a=gn(a.add(i[0]),33).mul(d),o=Dh(e,l,o[1].mul(d),s.add(i[0])),i=Dh(e,l+32,a.add(i[1]),r.add(kt(e,l+16))),[a,s]=[s,a],Ao(Ao(o[0],i[0],d).add(jg(r).mul(x5)).add(a),Ao(o[1],i[1],d).add(s),d)}function bE(e,t){return t==="string"?Qc(e):_h([e],t)}function vE(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function _h(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=ti(e)),K().getBool("DEBUG")&&o5(e,t),vE(e,t))return e;if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"){let n=new Uint8Array(e.length);for(let s=0;s{s=n()},a,o=Jc();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(r);else{r();for(let l of s)l.dataSync();a=Promise.resolve({kernelMs:Jc()-o})}if(K().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let l=0;l{IE(u,c.dtype,e)})}return{kernelName:e,outputs:s,inputs:t,timeMs:a.then(l=>l.kernelMs),extraInfo:a.then(l=>l.getExtraProfileInfo!=null?l.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:s,inputs:r,extraInfo:a}=e;n.forEach(o=>{Promise.all([o.data(),s,a]).then(i=>{this.logger.logKernelProfile(t,o,i[0],i[1],r,i[2])})})}};function IE(e,t,n){if(t!=="float32")return!1;for(let s=0;s0?f:""} `}}console.log(`%c${i} %c${o} %c${l}D ${u} %c${c} %c${d} %c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function CE(e,t,n){let s={},r={};for(let l=0;ls[m.id]=!0),h=!0,r[c.id]=!0;break}if(h)break}}let a={};a[n.id]=!0;let o={};for(let l=e.length-1;l>=0;l--){let c=e[l],u=c.inputs;for(let d=0;d=0;r--){let a=t[r],o=[];if(a.outputs.forEach(l=>{let c=e[l.id];c!=null?o.push(c):o.push(null)}),a.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);let i=a.gradient(o);for(let l in a.inputs){if(!(l in i))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(i)}.`);let c=n(()=>i[l]());if(c.dtype!=="float32")throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${c.dtype}'`);let u=a.inputs[l];if(!Gr(c.shape,u.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${l}' has shape '${c.shape}', which does not match the shape of the input '${u.shape}'`);if(e[u.id]==null)e[u.id]=c;else{let d=e[u.id];e[u.id]=s(d,c),d.dispose()}}}}var w5=20,ed=3,qg=7;function NE(e,t,n,s){let r=Bl(t),a=EE(e,t,n,r),o=t.length,i=Fh(e,t,n,r,a),l=["Tensor"];return s&&(l.push(` dtype: ${n}`),l.push(` rank: ${o}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(i.map(c=>" "+c).join(`
+var Og=Object.defineProperty;var vN=(e,t,n)=>t in e?Og(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var wN=e=>Og(e,"__esModule",{value:!0});var xa=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof require!="undefined"?require:t)[n]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var qp=(e,t)=>{wN(e);for(var n in t)Og(e,n,{get:t[n],enumerable:!0})};var de=(e,t,n)=>(vN(e,typeof t!="symbol"?t+"":t,n),n),Qb=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var Ec=(e,t,n)=>(Qb(e,t,"read from private field"),n?n.call(e):t.get(e)),Rc=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},$c=(e,t,n,s)=>(Qb(e,t,"write to private field"),s?s.call(e,n):t.set(e,n),n);function at(e,t){let n=e.endsWith("/")?"":"/",r=t.startsWith(".")||t.startsWith("/")||t.startsWith("http:")||t.startsWith("https:")||t.startsWith("file:")?`${t}`:`${e}${n}${t}`;if(!r.toLocaleLowerCase().includes(".json"))throw new Error(`modelpath error: ${r} expecting json file`);return r}function ae(...e){let t=new Date,n=`${t.getHours().toString().padStart(2,"0")}:${t.getMinutes().toString().padStart(2,"0")}:${t.getSeconds().toString().padStart(2,"0")}.${t.getMilliseconds().toString().padStart(3,"0")}`;e&&console.log(n,"Human:",...e)}var pe=()=>typeof performance!="undefined"?performance.now():parseInt((Number(process.hrtime.bigint())/1e3/1e3).toString());function Mg(e,t,n="config",s=[]){for(let r of Object.keys(t))if(typeof t[r]=="object")Mg(e[r],t[r],r,s);else{let a=e&&typeof e[r]!="undefined";a||s.push({reason:"unknown property",where:`${n}.${r} = ${t[r]}`});let o=e&&typeof e[r]==typeof t[r];a&&!o&&s.push({reason:"property type mismatch",where:`${n}.${r} = ${t[r]}`,expected:typeof e[r]})}return t.debug&&n==="config"&&s.length>0&&ae("invalid configuration",s),s}function $n(...e){let t=n=>n&&typeof n=="object";return e.reduce((n,s)=>(Object.keys(s||{}).forEach(r=>{let a=n[r],o=s[r];Array.isArray(a)&&Array.isArray(o)?n[r]=a.concat(...o):t(a)&&t(o)?n[r]=$n(a,o):n[r]=o}),n),{})}var Jo={backend:"",modelBasePath:"",wasmPath:"",debug:!0,async:!0,warmup:"full",cacheSensitivity:.7,skipAllowed:!1,filter:{enabled:!0,width:0,height:0,flip:!1,return:!0,brightness:0,contrast:0,sharpness:0,blur:0,saturation:0,hue:0,negative:!1,sepia:!1,vintage:!1,kodachrome:!1,technicolor:!1,polaroid:!1,pixelate:0},gesture:{enabled:!0},face:{enabled:!0,detector:{modelPath:"blazeface.json",rotation:!0,maxDetected:1,skipFrames:99,skipTime:2500,minConfidence:.2,iouThreshold:.1,return:!1},mesh:{enabled:!0,modelPath:"facemesh.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"}},body:{enabled:!0,modelPath:"movenet-lightning.json",detector:{modelPath:""},maxDetected:-1,minConfidence:.3,skipFrames:1,skipTime:200},hand:{enabled:!0,rotation:!0,skipFrames:99,skipTime:2e3,minConfidence:.5,iouThreshold:.2,maxDetected:-1,landmarks:!0,detector:{modelPath:"handtrack.json"},skeleton:{modelPath:"handskeleton.json"}},object:{enabled:!1,modelPath:"mb3-centernet.json",minConfidence:.2,iouThreshold:.4,maxDetected:10,skipFrames:99,skipTime:1e3},segmentation:{enabled:!1,modelPath:"selfie.json",blur:8}};var wl={};qp(wl,{Abs:()=>ni,Acos:()=>Vl,Acosh:()=>Ul,AdadeltaOptimizer:()=>ff,AdagradOptimizer:()=>mf,AdamOptimizer:()=>gf,AdamaxOptimizer:()=>Af,Add:()=>Hr,AddN:()=>wa,All:()=>Gl,Any:()=>Hl,ArgMax:()=>ka,ArgMin:()=>jl,Asin:()=>ql,Asinh:()=>Xl,Atan:()=>Kl,Atan2:()=>Yl,Atanh:()=>Zl,AvgPool:()=>Ia,AvgPool3D:()=>Fc,AvgPool3DGrad:()=>th,AvgPoolGrad:()=>eh,BackendWasm:()=>y6,BatchMatMul:()=>Sa,BatchToSpaceND:()=>si,Bincount:()=>nh,BroadcastArgs:()=>sh,BroadcastTo:()=>m5,Callback:()=>Tk,CallbackList:()=>mw,Cast:()=>Ca,Ceil:()=>Ta,ClipByValue:()=>jr,Complex:()=>Oc,ComplexAbs:()=>Mc,Concat:()=>ri,Conv2D:()=>Na,Conv2DBackpropFilter:()=>rh,Conv2DBackpropInput:()=>Ea,Conv3D:()=>zc,Conv3DBackpropFilterV2:()=>ah,Conv3DBackpropInputV2:()=>oh,Cos:()=>Ra,Cosh:()=>$a,CropAndResize:()=>oi,Cumsum:()=>ai,CustomCallback:()=>Aw,DataStorage:()=>Dc,DenseBincount:()=>ih,DepthToSpace:()=>ii,DepthwiseConv2dNative:()=>Da,DepthwiseConv2dNativeBackpropFilter:()=>lh,DepthwiseConv2dNativeBackpropInput:()=>uh,Diag:()=>ch,Dilation2D:()=>Lc,Dilation2DBackpropFilter:()=>ph,Dilation2DBackpropInput:()=>dh,ENV:()=>Ir,EarlyStopping:()=>Ek,Einsum:()=>Bc,Elu:()=>Pa,EluGrad:()=>hh,Environment:()=>h5,Equal:()=>li,Erf:()=>Jl,Exp:()=>Fa,ExpandDims:()=>ui,Expm1:()=>ci,FFT:()=>fh,Fill:()=>Ql,FlipLeftRight:()=>di,Floor:()=>Oa,FloorDiv:()=>Ma,FromPixels:()=>Kc,FusedBatchNorm:()=>za,FusedConv2D:()=>mo,FusedDepthwiseConv2D:()=>go,GPGPUContext:()=>vm,GatherNd:()=>hi,GatherV2:()=>pi,GraphModel:()=>i7,Greater:()=>fi,GreaterEqual:()=>La,History:()=>gw,IFFT:()=>mh,Identity:()=>Ba,Imag:()=>Wc,InputSpec:()=>Yt,IsFinite:()=>eu,IsInf:()=>tu,IsNan:()=>nu,KernelBackend:()=>Ll,LRN:()=>Uc,LRNGrad:()=>Ah,LayerVariable:()=>cw,LayersModel:()=>na,LeakyRelu:()=>mi,Less:()=>gi,LessEqual:()=>Ai,LinSpace:()=>gh,Log:()=>Wa,Log1p:()=>su,LogSoftmax:()=>g5,LogicalAnd:()=>yi,LogicalNot:()=>ru,LogicalOr:()=>Vc,MathBackendCPU:()=>xy,MathBackendWebGL:()=>Kd,Max:()=>Va,MaxPool:()=>Ga,MaxPool3D:()=>Gc,MaxPool3DGrad:()=>xh,MaxPoolGrad:()=>yh,MaxPoolWithArgmax:()=>bh,Maximum:()=>Ua,Mean:()=>Ha,Min:()=>ja,Minimum:()=>qa,MirrorPad:()=>Xa,Mod:()=>au,MomentumOptimizer:()=>yf,Multinomial:()=>vh,Multiply:()=>Ka,Neg:()=>xi,NonMaxSuppressionV3:()=>vi,NonMaxSuppressionV4:()=>ou,NonMaxSuppressionV5:()=>wi,NotEqual:()=>bi,OP_SCOPE_SUFFIX:()=>$5,OneHot:()=>Ii,OnesLike:()=>ki,Optimizer:()=>Qr,Pack:()=>Si,PadV2:()=>Za,Pool:()=>dE,Pow:()=>Ya,Prelu:()=>Ja,Prod:()=>Ci,RMSPropOptimizer:()=>xf,RNN:()=>sa,Range:()=>iu,Rank:()=>Xg,Real:()=>Hc,RealDiv:()=>_a,Reciprocal:()=>lu,Reduction:()=>Vn,Relu:()=>Qa,Relu6:()=>to,Reshape:()=>Ti,ResizeBilinear:()=>eo,ResizeBilinearGrad:()=>kh,ResizeNearestNeighbor:()=>uu,ResizeNearestNeighborGrad:()=>wh,Reverse:()=>Ni,RotateWithOffset:()=>Vi,Round:()=>Ei,Rsqrt:()=>no,SGDOptimizer:()=>xd,ScatterNd:()=>Ri,Select:()=>$i,Selu:()=>cu,Sequential:()=>Gf,Sigmoid:()=>ro,Sign:()=>du,Sin:()=>so,Sinh:()=>_i,Slice:()=>Di,Softmax:()=>io,Softplus:()=>pu,SpaceToBatchND:()=>Pi,SparseFillEmptyRows:()=>Ih,SparseReshape:()=>Sh,SparseSegmentMean:()=>Ch,SparseSegmentSum:()=>Th,SparseToDense:()=>jc,SplitV:()=>Fi,Sqrt:()=>ao,Square:()=>hu,SquaredDifference:()=>lo,Step:()=>ho,StridedSlice:()=>Oi,StringNGrams:()=>qc,StringSplit:()=>Nh,StringToHashBucketFast:()=>Eh,Sub:()=>uo,Sum:()=>oo,SymbolicTensor:()=>fr,Tan:()=>Mi,Tanh:()=>co,Tensor:()=>Ye,TensorBuffer:()=>sn,Tile:()=>qr,TopK:()=>zi,Transform:()=>Li,Transpose:()=>po,Unique:()=>Rh,Unpack:()=>Bi,UnsortedSegmentSum:()=>Xc,Variable:()=>sd,ZerosLike:()=>Wi,_FusedMatMul:()=>fo,abs:()=>rn,acos:()=>A3,acosh:()=>y3,add:()=>ie,addN:()=>Vh,all:()=>T2,any:()=>Uh,argMax:()=>Hs,argMin:()=>x3,asin:()=>b3,asinh:()=>v3,atan:()=>w3,atan2:()=>k3,atanh:()=>I3,avgPool:()=>Hh,avgPool3d:()=>R2,backend:()=>Tr,backend_util:()=>N,basicLSTMCell:()=>jR,batchNorm:()=>wu,batchNorm2d:()=>N3,batchNorm3d:()=>E3,batchNorm4d:()=>R3,batchToSpaceND:()=>jh,bincount:()=>$2,booleanMaskAsync:()=>aP,broadcastArgs:()=>$3,broadcastTo:()=>ud,browser:()=>Gs,buffer:()=>Le,callbacks:()=>bV,cast:()=>he,ceil:()=>D3,clipByValue:()=>fs,clone:()=>or,complex:()=>yo,concat:()=>It,concat1d:()=>_3,concat2d:()=>ku,concat3d:()=>P3,concat4d:()=>F3,constraints:()=>Uv,conv1d:()=>D2,conv2d:()=>ko,conv2dTranspose:()=>P2,conv3d:()=>F2,conv3dTranspose:()=>M3,copyRegisteredKernels:()=>fE,cos:()=>qh,cosh:()=>O2,cosineWindow:()=>i1,cumsum:()=>M2,customGrad:()=>Er,data:()=>l7,denseBincount:()=>z3,deprecationWarn:()=>I2,depthToSpace:()=>L3,depthwiseConv2d:()=>cd,deregisterOp:()=>wV,device_util:()=>gu,diag:()=>w$,dilation2d:()=>B3,disableDeprecationWarnings:()=>lR,dispose:()=>Q,disposeVariables:()=>uR,div:()=>fe,divNoNan:()=>W3,dot:()=>R$,dropout:()=>Av,einsum:()=>V3,elu:()=>dd,enableDebugMode:()=>iR,enableProdMode:()=>m3,enclosingPowerOfTwo:()=>yv,engine:()=>ss,env:()=>K,equal:()=>Cs,erf:()=>U3,exp:()=>Ts,expandDims:()=>Kt,expm1:()=>G3,eye:()=>z2,fft:()=>af,fill:()=>Iu,findBackend:()=>S2,findBackendFactory:()=>hR,floor:()=>pd,floorDiv:()=>C2,forceHalfFloat:()=>zS,fused:()=>So,gather:()=>Su,gatherND:()=>gv,gather_util:()=>A2,getBackend:()=>ir,getGradient:()=>Gg,getKernel:()=>$h,getKernelsForBackend:()=>Xr,getThreadsCount:()=>q0e,gpgpu_util:()=>dS,grad:()=>tD,grads:()=>nD,greater:()=>ms,greaterEqual:()=>Yi,ifft:()=>gd,imag:()=>Xh,image:()=>$e,inTopKAsync:()=>gP,initializers:()=>Zv,input:()=>Bw,io:()=>ns,irfft:()=>t1,isFinite:()=>H$,isInf:()=>q$,isNaN:()=>H3,keep:()=>yn,kernel_impls:()=>Xs,layers:()=>iw,leakyRelu:()=>Kh,less:()=>L2,lessEqual:()=>Ji,linalg:()=>Nv,linspace:()=>j3,loadGraphModel:()=>st,loadLayersModel:()=>$B,localResponseNormalization:()=>q3,log:()=>Ns,log1p:()=>Zh,logSigmoid:()=>lD,logSoftmax:()=>B2,logSumExp:()=>J3,logicalAnd:()=>lr,logicalNot:()=>Jh,logicalOr:()=>U2,logicalXor:()=>bD,losses:()=>eO,matMul:()=>He,math:()=>K5,max:()=>rs,maxPool:()=>Qh,maxPool3d:()=>G2,maxPoolWithArgmax:()=>Q3,maximum:()=>Yr,mean:()=>Wt,memory:()=>Bh,meshgrid:()=>CD,metrics:()=>Ik,min:()=>ef,minimum:()=>hd,mirrorPad:()=>ev,mod:()=>tv,model:()=>EB,models:()=>Sk,moments:()=>tf,movingAverage:()=>lP,mul:()=>W,multiRNNCell:()=>PD,multinomial:()=>nv,neg:()=>Ot,nextFrame:()=>Ev,norm:()=>a1,notEqual:()=>Tu,oneHot:()=>id,ones:()=>gs,onesLike:()=>Es,op:()=>V,outerProduct:()=>LD,pad:()=>qs,pad1d:()=>VD,pad2d:()=>GD,pad3d:()=>jD,pad4d:()=>XD,pool:()=>QD,pow:()=>Io,prelu:()=>sf,print:()=>U5,prod:()=>H2,profile:()=>cR,rand:()=>r_,randomGamma:()=>l_,randomNormal:()=>sv,randomUniform:()=>Nu,range:()=>Eu,ready:()=>Wh,real:()=>fd,reciprocal:()=>rv,registerBackend:()=>Ki,registerCallbackConstructor:()=>DB,registerGradient:()=>A5,registerKernel:()=>Kr,registerOp:()=>vV,regularizers:()=>Ck,relu:()=>Rr,relu6:()=>X2,removeBackend:()=>pR,reshape:()=>G,reverse:()=>Rs,reverse1d:()=>A_,reverse2d:()=>x_,reverse3d:()=>v_,reverse4d:()=>k_,rfft:()=>of,round:()=>K2,rsqrt:()=>Z2,scalar:()=>Ee,scatterND:()=>mv,scatter_util:()=>y2,selu:()=>Y2,separableConv2d:()=>av,sequential:()=>RB,serialization:()=>le,setBackend:()=>g3,setPlatform:()=>fR,setThreadsCount:()=>j0e,setWasmPath:()=>H0e,setWasmPaths:()=>b6,setWebGLContext:()=>pm,setdiff1dAsync:()=>ov,shared:()=>om,sigmoid:()=>hs,sign:()=>iv,signal:()=>QF,sin:()=>J2,sinh:()=>Q2,slice:()=>_e,slice1d:()=>rf,slice2d:()=>e1,slice3d:()=>Ru,slice4d:()=>md,slice_util:()=>An,softmax:()=>$u,softplus:()=>Cu,spaceToBatchND:()=>nf,sparse:()=>yd,sparseToDense:()=>o1,spectral:()=>JF,split:()=>Sn,sqrt:()=>_n,square:()=>xt,squaredDifference:()=>n1,squeeze:()=>pt,stack:()=>Pn,step:()=>Ad,stridedSlice:()=>lv,string:()=>hf,sub:()=>xe,sum:()=>Ie,sumOutType:()=>rd,tan:()=>uv,tanh:()=>vu,tensor:()=>Gt,tensor1d:()=>Zt,tensor2d:()=>ur,tensor3d:()=>Z5,tensor4d:()=>K_,tensor5d:()=>Z_,tensor6d:()=>Y_,tensor_util:()=>rr,test_util:()=>p3,tidy:()=>j,tile:()=>js,time:()=>dR,topk:()=>cv,train:()=>tl,transpose:()=>et,truncatedNormal:()=>lf,unique:()=>s1,unregisterGradient:()=>hE,unregisterKernel:()=>pE,unsortedSegmentSum:()=>dv,unstack:()=>as,upcastType:()=>Bn,util:()=>v,valueAndGrad:()=>sD,valueAndGrads:()=>rD,variable:()=>pv,variableGrads:()=>X3,version:()=>w6,version_converter:()=>SU,version_core:()=>up,version_cpu:()=>dH,version_layers:()=>U1,version_wasm:()=>X0e,version_webgl:()=>zJ,webgl:()=>LJ,webgl_util:()=>FI,webgpu:()=>bC,where:()=>Wn,whereAsync:()=>r1,zeros:()=>Ht,zerosLike:()=>tt});var zl=(e=>typeof xa!="undefined"?xa:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof xa!="undefined"?xa:t)[n]}):e)(function(e){if(typeof xa!="undefined")return xa.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')}),kN=Object.create,Xp=Object.defineProperty,IN=Object.getOwnPropertyDescriptor,SN=Object.getOwnPropertyNames,CN=Object.getPrototypeOf,TN=Object.prototype.hasOwnProperty,e5=e=>Xp(e,"__esModule",{value:!0}),Ws=(e=>typeof zl!="undefined"?zl:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof zl!="undefined"?zl:t)[n]}):e)(function(e){if(typeof zl!="undefined")return zl.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')}),ts=(e,t)=>function(){return t||(0,e[Object.keys(e)[0]])((t={exports:{}}).exports,t),t.exports},ze=(e,t)=>{e5(e);for(var n in t)Xp(e,n,{get:t[n],enumerable:!0})},NN=(e,t,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of SN(t))!TN.call(e,s)&&s!=="default"&&Xp(e,s,{get:()=>t[s],enumerable:!(n=IN(t,s))||n.enumerable});return e},Qo=e=>NN(e5(Xp(e!=null?kN(CN(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e),EN=ts({"node_modules/.pnpm/long@4.0.0/node_modules/long/src/long.js"(e,t){t.exports=s;var n=null;try{n=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(P){}function s(P,T,M){this.low=P|0,this.high=T|0,this.unsigned=!!M}s.prototype.__isLong__,Object.defineProperty(s.prototype,"__isLong__",{value:!0});function r(P){return(P&&P.__isLong__)===!0}s.isLong=r;var a={},o={};function i(P,T){var M,U,H;return T?(P>>>=0,(H=0<=P&&P<256)&&(U=o[P],U)?U:(M=c(P,(P|0)<0?-1:0,!0),H&&(o[P]=M),M)):(P|=0,(H=-128<=P&&P<128)&&(U=a[P],U)?U:(M=c(P,P<0?-1:0,!1),H&&(a[P]=M),M))}s.fromInt=i;function l(P,T){if(isNaN(P))return T?b:x;if(T){if(P<0)return b;if(P>=g)return $}else{if(P<=-A)return F;if(P+1>=A)return E}return P<0?l(-P,T).neg():c(P%m|0,P/m|0,T)}s.fromNumber=l;function c(P,T,M){return new s(P,T,M)}s.fromBits=c;var u=Math.pow;function d(P,T,M){if(P.length===0)throw Error("empty string");if(P==="NaN"||P==="Infinity"||P==="+Infinity"||P==="-Infinity")return x;if(typeof T=="number"?(M=T,T=!1):T=!!T,M=M||10,M<2||360)throw Error("interior hyphen");if(U===0)return d(P.substring(1),T,M).neg();for(var H=l(u(M,8)),z=x,X=0;X>>0:this.low},R.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},R.toString=function(T){if(T=T||10,T<2||36>>0,se=ne.toString(T);if(X=Y,X.isZero())return se+ee;for(;se.length<6;)se="0"+se;ee=""+se+ee}},R.getHighBits=function(){return this.high},R.getHighBitsUnsigned=function(){return this.high>>>0},R.getLowBits=function(){return this.low},R.getLowBitsUnsigned=function(){return this.low>>>0},R.getNumBitsAbs=function(){if(this.isNegative())return this.eq(F)?64:this.neg().getNumBitsAbs();for(var T=this.high!=0?this.high:this.low,M=31;M>0&&(T&1<=0},R.isOdd=function(){return(this.low&1)==1},R.isEven=function(){return(this.low&1)==0},R.equals=function(T){return r(T)||(T=p(T)),this.unsigned!==T.unsigned&&this.high>>>31==1&&T.high>>>31==1?!1:this.high===T.high&&this.low===T.low},R.eq=R.equals,R.notEquals=function(T){return!this.eq(T)},R.neq=R.notEquals,R.ne=R.notEquals,R.lessThan=function(T){return this.comp(T)<0},R.lt=R.lessThan,R.lessThanOrEqual=function(T){return this.comp(T)<=0},R.lte=R.lessThanOrEqual,R.le=R.lessThanOrEqual,R.greaterThan=function(T){return this.comp(T)>0},R.gt=R.greaterThan,R.greaterThanOrEqual=function(T){return this.comp(T)>=0},R.gte=R.greaterThanOrEqual,R.ge=R.greaterThanOrEqual,R.compare=function(T){if(r(T)||(T=p(T)),this.eq(T))return 0;var M=this.isNegative(),U=T.isNegative();return M&&!U?-1:!M&&U?1:this.unsigned?T.high>>>0>this.high>>>0||T.high===this.high&&T.low>>>0>this.low>>>0?-1:1:this.sub(T).isNegative()?-1:1},R.comp=R.compare,R.negate=function(){return!this.unsigned&&this.eq(F)?F:this.not().add(w)},R.neg=R.negate,R.add=function(T){r(T)||(T=p(T));var M=this.high>>>16,U=this.high&65535,H=this.low>>>16,z=this.low&65535,X=T.high>>>16,ee=T.high&65535,Y=T.low>>>16,ne=T.low&65535,se=0,J=0,te=0,ue=0;return ue+=z+ne,te+=ue>>>16,ue&=65535,te+=H+Y,J+=te>>>16,te&=65535,J+=U+ee,se+=J>>>16,J&=65535,se+=M+X,se&=65535,c(te<<16|ue,se<<16|J,this.unsigned)},R.subtract=function(T){return r(T)||(T=p(T)),this.add(T.neg())},R.sub=R.subtract,R.multiply=function(T){if(this.isZero())return x;if(r(T)||(T=p(T)),n){var M=n.mul(this.low,this.high,T.low,T.high);return c(M,n.get_high(),this.unsigned)}if(T.isZero())return x;if(this.eq(F))return T.isOdd()?F:x;if(T.eq(F))return this.isOdd()?F:x;if(this.isNegative())return T.isNegative()?this.neg().mul(T.neg()):this.neg().mul(T).neg();if(T.isNegative())return this.mul(T.neg()).neg();if(this.lt(y)&&T.lt(y))return l(this.toNumber()*T.toNumber(),this.unsigned);var U=this.high>>>16,H=this.high&65535,z=this.low>>>16,X=this.low&65535,ee=T.high>>>16,Y=T.high&65535,ne=T.low>>>16,se=T.low&65535,J=0,te=0,ue=0,ce=0;return ce+=X*se,ue+=ce>>>16,ce&=65535,ue+=z*se,te+=ue>>>16,ue&=65535,ue+=X*ne,te+=ue>>>16,ue&=65535,te+=H*se,J+=te>>>16,te&=65535,te+=z*ne,J+=te>>>16,te&=65535,te+=X*Y,J+=te>>>16,te&=65535,J+=U*se+H*ne+z*Y+X*ee,J&=65535,c(ue<<16|ce,J<<16|te,this.unsigned)},R.mul=R.multiply,R.divide=function(T){if(r(T)||(T=p(T)),T.isZero())throw Error("division by zero");if(n){if(!this.unsigned&&this.high===-2147483648&&T.low===-1&&T.high===-1)return this;var M=(this.unsigned?n.div_u:n.div_s)(this.low,this.high,T.low,T.high);return c(M,n.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?b:x;var U,H,z;if(this.unsigned){if(T.unsigned||(T=T.toUnsigned()),T.gt(this))return b;if(T.gt(this.shru(1)))return k;z=b}else{if(this.eq(F)){if(T.eq(w)||T.eq(S))return F;if(T.eq(F))return w;var X=this.shr(1);return U=X.div(T).shl(1),U.eq(x)?T.isNegative()?w:S:(H=this.sub(T.mul(U)),z=U.add(H.div(T)),z)}else if(T.eq(F))return this.unsigned?b:x;if(this.isNegative())return T.isNegative()?this.neg().div(T.neg()):this.neg().div(T).neg();if(T.isNegative())return this.div(T.neg()).neg();z=x}for(H=this;H.gte(T);){U=Math.max(1,Math.floor(H.toNumber()/T.toNumber()));for(var ee=Math.ceil(Math.log(U)/Math.LN2),Y=ee<=48?1:u(2,ee-48),ne=l(U),se=ne.mul(T);se.isNegative()||se.gt(H);)U-=Y,ne=l(U,this.unsigned),se=ne.mul(T);ne.isZero()&&(ne=w),z=z.add(ne),H=H.sub(se)}return z},R.div=R.divide,R.modulo=function(T){if(r(T)||(T=p(T)),n){var M=(this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,T.low,T.high);return c(M,n.get_high(),this.unsigned)}return this.sub(this.div(T).mul(T))},R.mod=R.modulo,R.rem=R.modulo,R.not=function(){return c(~this.low,~this.high,this.unsigned)},R.and=function(T){return r(T)||(T=p(T)),c(this.low&T.low,this.high&T.high,this.unsigned)},R.or=function(T){return r(T)||(T=p(T)),c(this.low|T.low,this.high|T.high,this.unsigned)},R.xor=function(T){return r(T)||(T=p(T)),c(this.low^T.low,this.high^T.high,this.unsigned)},R.shiftLeft=function(T){return r(T)&&(T=T.toInt()),(T&=63)==0?this:T<32?c(this.low<>>32-T,this.unsigned):c(0,this.low<>>T|this.high<<32-T,this.high>>T,this.unsigned):c(this.high>>T-32,this.high>=0?0:-1,this.unsigned)},R.shr=R.shiftRight,R.shiftRightUnsigned=function(T){if(r(T)&&(T=T.toInt()),T&=63,T===0)return this;var M=this.high;if(T<32){var U=this.low;return c(U>>>T|M<<32-T,M>>>T,this.unsigned)}else return T===32?c(M,0,this.unsigned):c(M>>>T-32,0,this.unsigned)},R.shru=R.shiftRightUnsigned,R.shr_u=R.shiftRightUnsigned,R.toSigned=function(){return this.unsigned?c(this.low,this.high,!1):this},R.toUnsigned=function(){return this.unsigned?this:c(this.low,this.high,!0)},R.toBytes=function(T){return T?this.toBytesLE():this.toBytesBE()},R.toBytesLE=function(){var T=this.high,M=this.low;return[M&255,M>>>8&255,M>>>16&255,M>>>24,T&255,T>>>8&255,T>>>16&255,T>>>24]},R.toBytesBE=function(){var T=this.high,M=this.low;return[T>>>24,T>>>16&255,T>>>8&255,T&255,M>>>24,M>>>16&255,M>>>8&255,M&255]},s.fromBytes=function(T,M,U){return U?s.fromBytesLE(T,M):s.fromBytesBE(T,M)},s.fromBytesLE=function(T,M){return new s(T[0]|T[1]<<8|T[2]<<16|T[3]<<24,T[4]|T[5]<<8|T[6]<<16|T[7]<<24,M)},s.fromBytesBE=function(T,M){return new s(T[4]<<24|T[5]<<16|T[6]<<8|T[7],T[0]<<24|T[1]<<16|T[2]<<8|T[3],M)}}}),RN=ts({"(disabled):node-fetch"(){}}),$N=ts({"(disabled):util"(){}}),DN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js"(e,t){(function(n,s,r){function a(c){var u=this,d=l();u.next=function(){var p=2091639*u.s0+u.c*23283064365386963e-26;return u.s0=u.s1,u.s1=u.s2,u.s2=p-(u.c=p|0)},u.c=1,u.s0=d(" "),u.s1=d(" "),u.s2=d(" "),u.s0-=d(c),u.s0<0&&(u.s0+=1),u.s1-=d(c),u.s1<0&&(u.s1+=1),u.s2-=d(c),u.s2<0&&(u.s2+=1),d=null}function o(c,u){return u.c=c.c,u.s0=c.s0,u.s1=c.s1,u.s2=c.s2,u}function i(c,u){var d=new a(c),p=u&&u.state,h=d.next;return h.int32=function(){return d.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,p&&(typeof p=="object"&&o(p,d),h.state=function(){return o(d,{})}),h}function l(){var c=4022871197,u=function(d){d=String(d);for(var p=0;p>>0,h-=c,h*=c,c=h>>>0,h-=c,c+=h*4294967296}return(c>>>0)*23283064365386963e-26};return u}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.alea=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),_N=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.x=0,c.y=0,c.z=0,c.w=0,c.next=function(){var p=c.x^c.x<<11;return c.x=c.y,c.y=c.z,c.z=c.w,c.w^=c.w>>>19^p^p>>>8},l===(l|0)?c.x=l:u+=l;for(var d=0;d>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xor128=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),PN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.next=function(){var p=c.x^c.x>>>2;return c.x=c.y,c.y=c.z,c.z=c.w,c.w=c.v,(c.d=c.d+362437|0)+(c.v=c.v^c.v<<4^(p^p<<1))|0},c.x=0,c.y=0,c.z=0,c.w=0,c.v=0,l===(l|0)?c.x=l:u+=l;for(var d=0;d>>4),c.next()}function o(l,c){return c.x=l.x,c.y=l.y,c.z=l.z,c.w=l.w,c.v=l.v,c.d=l.d,c}function i(l,c){var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xorwow=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),FN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js"(e,t){(function(n,s,r){function a(l){var c=this;c.next=function(){var d=c.x,p=c.i,h,f,m;return h=d[p],h^=h>>>7,f=h^h<<24,h=d[p+1&7],f^=h^h>>>10,h=d[p+3&7],f^=h^h>>>3,h=d[p+4&7],f^=h^h<<7,h=d[p+7&7],h=h^h<<13,f^=h^h<<9,d[p]=f,c.i=p+1&7,f};function u(d,p){var h,f,m=[];if(p===(p|0))f=m[0]=p;else for(p=""+p,h=0;h0;--h)d.next()}u(c,l)}function o(l,c){return c.x=l.x.slice(),c.i=l.i,c}function i(l,c){l==null&&(l=+new Date);var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.x&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xorshift7=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),ON=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js"(e,t){(function(n,s,r){function a(l){var c=this;c.next=function(){var d=c.w,p=c.X,h=c.i,f,m;return c.w=d=d+1640531527|0,m=p[h+34&127],f=p[h=h+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,m=p[h]=m^f,c.i=h,m+(d^d>>>16)|0};function u(d,p){var h,f,m,g,A,y=[],x=128;for(p===(p|0)?(f=p,p=null):(p=p+"\0",f=0,x=Math.max(x,p.length)),m=0,g=-32;g>>15,f^=f<<4,f^=f>>>13,g>=0&&(A=A+1640531527|0,h=y[g&127]^=f+A,m=h==0?m+1:0);for(m>=128&&(y[(p&&p.length||0)&127]=-1),m=127,g=4*128;g>0;--g)f=y[m+34&127],h=y[m=m+1&127],f^=f<<13,h^=h<<17,f^=f>>>15,h^=h>>>12,y[m]=f^h;d.w=A,d.X=y,d.i=m}u(c,l)}function o(l,c){return c.i=l.i,c.w=l.w,c.X=l.X.slice(),c}function i(l,c){l==null&&(l=+new Date);var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.X&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xor4096=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),MN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.next=function(){var p=c.b,h=c.c,f=c.d,m=c.a;return p=p<<25^p>>>7^h,h=h-f|0,f=f<<24^f>>>8^m,m=m-p|0,c.b=p=p<<20^p>>>12^h,c.c=h=h-f|0,c.d=f<<16^h>>>16^m,c.a=m-p|0},c.a=0,c.b=0,c.c=2654435769|0,c.d=1367130551,l===Math.floor(l)?(c.a=l/4294967296|0,c.b=l|0):u+=l;for(var d=0;d>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.tychei=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),zN=ts({"(disabled):crypto"(){}}),LN=ts({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js"(e,t){(function(n,s,r){var a=256,o=6,i=52,l="random",c=r.pow(a,o),u=r.pow(2,i),d=u*2,p=a-1,h;function f(w,k,S){var E=[];k=k==!0?{entropy:!0}:k||{};var $=y(A(k.entropy?[w,b(s)]:w==null?x():w,3),E),F=new m(E),R=function(){for(var P=F.g(o),T=c,M=0;P=d;)P/=2,T/=2,M>>>=1;return(P+M)/T};return R.int32=function(){return F.g(4)|0},R.quick=function(){return F.g(4)/4294967296},R.double=R,y(b(F.S),s),(k.pass||S||function(P,T,M,U){return U&&(U.S&&g(U,F),P.state=function(){return g(F,{})}),M?(r[l]=P,T):P})(R,$,"global"in k?k.global:this==r,k.state)}function m(w){var k,S=w.length,E=this,$=0,F=E.i=E.j=0,R=E.S=[];for(S||(w=[S++]);$1&&(g=process.argv[1].replace(/\\/g,"/")),m=process.argv.slice(2),process.on("uncaughtException",function(C){if(!(C instanceof Nc))throw C}),process.on("unhandledRejection",Wr),A=function(C){process.exit(C)},u.inspect=function(){return"[Emscripten Module object]"};var U;try{U=Ws("worker_threads")}catch(C){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),C}global.Worker=U.Worker}else w?(typeof read!="undefined"&&($=function(D){return read(D)}),R=function(D){var L;return typeof readbuffer=="function"?new Uint8Array(readbuffer(D)):(L=read(D,"binary"),we(typeof L=="object"),L)},typeof scriptArgs!="undefined"?m=scriptArgs:typeof arguments!="undefined"&&(m=arguments),typeof quit=="function"&&(A=function(C){quit(C)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(y||x)&&(x?S=self.location.href:typeof document!="undefined"&&document.currentScript&&(S=document.currentScript.src),typeof s!="undefined"&&s&&(S=s),S.indexOf("blob:")!==0?S=S.substr(0,S.lastIndexOf("/")+1):S="",b?($=function(D,L){return T||(T=Ws("fs")),M||(M=Ws("path")),D=M.normalize(D),T.readFileSync(D,L?null:"utf8")},R=function(D){var L=$(D,!0);return L.buffer||(L=new Uint8Array(L)),we(L.buffer),L}):($=function(C){var D=new XMLHttpRequest;return D.open("GET",C,!1),D.send(null),D.responseText},x&&(R=function(C){var D=new XMLHttpRequest;return D.open("GET",C,!1),D.responseType="arraybuffer",D.send(null),new Uint8Array(D.response)}),F=function(C,D,L){var Z=new XMLHttpRequest;Z.open("GET",C,!0),Z.responseType="arraybuffer",Z.onload=function(){if(Z.status==200||Z.status==0&&Z.response){D(Z.response);return}L()},Z.onerror=L,Z.send(null)}),P=function(C){document.title=C});b&&typeof performance=="undefined"&&(global.performance=Ws("perf_hooks").performance);var H=u.print||console.log.bind(console),z=u.printErr||console.warn.bind(console);for(f in h)h.hasOwnProperty(f)&&(u[f]=h[f]);h=null,u.arguments&&(m=u.arguments),u.thisProgram&&(g=u.thisProgram),u.quit&&(A=u.quit);function X(C){X.shown||(X.shown={}),X.shown[C]||(X.shown[C]=1,z(C))}var ee=Atomics.load,Y=Atomics.store,ne=Atomics.compareExchange,se;u.wasmBinary&&(se=u.wasmBinary);var J=u.noExitRuntime||!0;typeof WebAssembly!="object"&&Wr("no native wasm support detected");var te,ue,ce=!1,be;function we(C,D){C||Wr("Assertion failed: "+D)}function Ce(C){var D=u["_"+C];return we(D,"Cannot call unknown function "+C+", make sure it is exported"),D}function Oe(C,D,L,Z,Ae){var me={string:function(Mn){var Ml=0;if(Mn!=null&&Mn!==0){var Jb=(Mn.length<<2)+1;Ml=Pl(Jb),ut(Mn,Ml,Jb)}return Ml},array:function(Mn){var Ml=Pl(Mn.length);return At(Mn,Ml),Ml}};function ge(Mn){return D==="string"?rt(Mn):D==="boolean"?Boolean(Mn):Mn}var Te=Ce(C),ht=[],fn=0;if(Z)for(var nn=0;nn=Z);){var me=C[D++];if(!me)return Ae;if(!(me&128)){Ae+=String.fromCharCode(me);continue}var ge=C[D++]&63;if((me&224)==192){Ae+=String.fromCharCode((me&31)<<6|ge);continue}var Te=C[D++]&63;if((me&240)==224?me=(me&15)<<12|ge<<6|Te:me=(me&7)<<18|ge<<12|Te<<6|C[D++]&63,me<65536)Ae+=String.fromCharCode(me);else{var ht=me-65536;Ae+=String.fromCharCode(55296|ht>>10,56320|ht&1023)}}return Ae}function rt(C,D){return C?Xe(o(),C,D):""}function ft(C,D,L,Z){if(!(Z>0))return 0;for(var Ae=L,me=L+Z-1,ge=0;ge=55296&&Te<=57343){var ht=C.charCodeAt(++ge);Te=65536+((Te&1023)<<10)|ht&1023}if(Te<=127){if(L>=me)break;D[L++]=Te}else if(Te<=2047){if(L+1>=me)break;D[L++]=192|Te>>6,D[L++]=128|Te&63}else if(Te<=65535){if(L+2>=me)break;D[L++]=224|Te>>12,D[L++]=128|Te>>6&63,D[L++]=128|Te&63}else{if(L+3>=me)break;D[L++]=240|Te>>18,D[L++]=128|Te>>12&63,D[L++]=128|Te>>6&63,D[L++]=128|Te&63}}return D[L]=0,L-Ae}function ut(C,D,L){return ft(C,o(),D,L)}function ct(C){for(var D=0,L=0;L=55296&&Z<=57343&&(Z=65536+((Z&1023)<<10)|C.charCodeAt(++L)&1023),Z<=127?++D:Z<=2047?D+=2:Z<=65535?D+=3:D+=4}return D}function At(C,D){a().set(C,D)}function yt(C,D){return C%D>0&&(C+=D-C%D),C}var Et,Pt,Jn,wn,nr,On,ds,Ls,Is;function kn(C){Et=C,u.HEAP8=Pt=new Int8Array(C),u.HEAP16=wn=new Int16Array(C),u.HEAP32=On=new Int32Array(C),u.HEAPU8=Jn=new Uint8Array(C),u.HEAPU16=nr=new Uint16Array(C),u.HEAPU32=ds=new Uint32Array(C),u.HEAPF32=Ls=new Float32Array(C),u.HEAPF64=Is=new Float64Array(C)}var br=u.INITIAL_MEMORY||16777216;if(k)te=u.wasmMemory,Et=u.buffer;else if(u.wasmMemory)te=u.wasmMemory;else if(te=new WebAssembly.Memory({initial:br/65536,maximum:2147483648/65536,shared:!0}),!(te.buffer instanceof SharedArrayBuffer))throw z("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),b&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");te&&(Et=te.buffer),br=Et.byteLength,kn(Et);var Rn,vr=[],wr=[],pa=[],Ac=[],sr=[],wp=!1,f0=!1;k||wr.push({func:function(){Bp()}});function kp(){if(!k){if(u.preRun)for(typeof u.preRun=="function"&&(u.preRun=[u.preRun]);u.preRun.length;)m0(u.preRun.shift());Rl(vr)}}function Ip(){wp=!0,!k&&Rl(wr)}function Sp(){k||Rl(pa)}function Qn(){k||(f0=!0)}function Cp(){if(!k){if(u.postRun)for(typeof u.postRun=="function"&&(u.postRun=[u.postRun]);u.postRun.length;)g0(u.postRun.shift());Rl(sr)}}function m0(C){vr.unshift(C)}function g0(C){sr.unshift(C)}var Bs=0,yc=null,Xo=null;function A0(C){we(!k,"addRunDependency cannot be used in a pthread worker"),Bs++,u.monitorRunDependencies&&u.monitorRunDependencies(Bs)}function y0(C){if(Bs--,u.monitorRunDependencies&&u.monitorRunDependencies(Bs),Bs==0&&(yc!==null&&(clearInterval(yc),yc=null),Xo)){var D=Xo;Xo=null,D()}}u.preloadedImages={},u.preloadedAudios={};function Wr(C){u.onAbort&&u.onAbort(C),k&&console.error("Pthread aborting at "+new Error().stack),C+="",z(C),ce=!0,be=1,C="abort("+C+"). Build with -s ASSERTIONS=1 for more info.";var D=new WebAssembly.RuntimeError(C);throw p(D),D}function Ko(C,D){return String.prototype.startsWith?C.startsWith(D):C.indexOf(D)===0}var x0="data:application/octet-stream;base64,";function Tp(C){return Ko(C,x0)}var b0="file://";function Np(C){return Ko(C,b0)}var es="tfjs-backend-wasm-threaded-simd.wasm";Tp(es)||(es=E(es));function v0(C){try{if(C==es&&se)return new Uint8Array(se);if(R)return R(C);throw"both async and sync fetching of the wasm failed"}catch(D){Wr(D)}}function Ep(){if(!se&&(y||x)){if(typeof fetch=="function"&&!Np(es))return fetch(es,{credentials:"same-origin"}).then(function(C){if(!C.ok)throw"failed to load wasm binary file at '"+es+"'";return C.arrayBuffer()}).catch(function(){return v0(es)});if(F)return new Promise(function(C,D){F(es,function(L){C(new Uint8Array(L))},D)})}return Promise.resolve().then(function(){return v0(es)})}function w0(){var C={a:fg};function D(ge,Te){var ht=ge.exports;if(u.asm=ht,Rn=u.asm.kb,ue=Te,!k){var fn=Re.unusedWorkers.length;Re.unusedWorkers.forEach(function(nn){Re.loadWasmModuleToWorker(nn,function(){--fn||y0("wasm-instantiate")})})}}k||A0("wasm-instantiate");function L(ge){D(ge.instance,ge.module)}function Z(ge){return Ep().then(function(Te){return WebAssembly.instantiate(Te,C)}).then(ge,function(Te){z("failed to asynchronously prepare wasm: "+Te),Wr(Te)})}function Ae(){return!se&&typeof WebAssembly.instantiateStreaming=="function"&&!Tp(es)&&!Np(es)&&typeof fetch=="function"?fetch(es,{credentials:"same-origin"}).then(function(ge){var Te=WebAssembly.instantiateStreaming(ge,C);return Te.then(L,function(ht){return z("wasm streaming compile failed: "+ht),z("falling back to ArrayBuffer instantiation"),Z(L)})}):Z(L)}if(u.instantiateWasm)try{var me=u.instantiateWasm(C,D);return me}catch(ge){return z("Module.instantiateWasm callback failed with error: "+ge),!1}return Ae().catch(p),{}}var Rp={10072:function(){throw"Canceled!"},10090:function(C,D){setTimeout(function(){jb(C,D)},0)}};function k0(){Re.initRuntime()}function Rl(C){for(;C.length>0;){var D=C.shift();if(typeof D=="function"){D(u);continue}var L=D.func;typeof L=="number"?D.arg===void 0?Rn.get(L)():Rn.get(L)(D.arg):L(D.arg===void 0?null:D.arg)}}var ha={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135};function xc(C,D){if(C<=0||C>a().length||C&!0||D<0)return-28;if(D==0)return 0;D>=2147483647&&(D=1/0);var L=Atomics.load(i(),Fl>>2),Z=0;if(L==C){var Ae=Atomics.compareExchange(i(),Fl>>2,L,0);if(Ae==L&&(--D,Z=1,D<=0))return 1}var me=Atomics.notify(i(),C>>2,D);if(me>=0)return me+Z;throw"Atomics.notify returned an unexpected value "+me}u._emscripten_futex_wake=xc;function I0(C){if(k)throw"Internal Error! killThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in killThread!";i()[C+12>>2]=0;var D=Re.pthreads[C];D.worker.terminate(),Re.freeThreadData(D),Re.runningWorkers.splice(Re.runningWorkers.indexOf(D.worker),1),D.worker.pthread=void 0}function S0(C){if(k)throw"Internal Error! cancelThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in cancelThread!";var D=Re.pthreads[C];D.worker.postMessage({cmd:"cancel"})}function $p(C){if(k)throw"Internal Error! cleanupThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in cleanupThread!";var D=Re.pthreads[C];if(D){i()[C+12>>2]=0;var L=D.worker;Re.returnWorkerToPool(L)}}var Re={unusedWorkers:[],runningWorkers:[],initMainThreadBlock:function(){for(var C=8,D=0;D>2]=C;var L=C+152;i()[L>>2]=L;for(var Z=Yo(512),D=0;D<128;++D)l()[Z/4+D]=0;Atomics.store(l(),C+100>>2,Z),Atomics.store(l(),C+40>>2,C),Pg(C,!x,1),Gb(C)},initWorker:function(){},pthreads:{},threadExitHandlers:[],setThreadStatus:function(){},runExitHandlers:function(){for(;Re.threadExitHandlers.length>0;)Re.threadExitHandlers.pop()();k&&Aa()&&Ub()},runExitHandlersAndDeinitThread:function(C,D){Atomics.store(l(),C+56>>2,1),Atomics.store(l(),C+60>>2,0),Re.runExitHandlers(),Atomics.store(l(),C+4>>2,D),Atomics.store(l(),C+0>>2,1),xc(C+0,2147483647),Pg(0,0,0)},threadExit:function(C){var D=Aa();D&&(Re.runExitHandlersAndDeinitThread(D,C),k&&postMessage({cmd:"exit"}))},threadCancel:function(){Re.runExitHandlersAndDeinitThread(Aa(),-1),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var C in Re.pthreads){var D=Re.pthreads[C];D&&D.worker&&Re.returnWorkerToPool(D.worker)}Re.pthreads={};for(var L=0;L>2];i()[C.threadInfoStruct+100>>2]=0,Cc(D),Cc(C.threadInfoStruct)}C.threadInfoStruct=0,C.allocatedOwnStack&&C.stackBase&&Cc(C.stackBase),C.stackBase=0,C.worker&&(C.worker.pthread=null)}},returnWorkerToPool:function(C){Re.runWithoutMainThreadQueuedCalls(function(){delete Re.pthreads[C.pthread.threadInfoStruct],Re.unusedWorkers.push(C),Re.runningWorkers.splice(Re.runningWorkers.indexOf(C),1),Re.freeThreadData(C.pthread),C.pthread=void 0})},runWithoutMainThreadQueuedCalls:function(C){i()[Yb>>2]=0;try{C()}finally{i()[Yb>>2]=1}},receiveObjectTransfer:function(C){},loadWasmModuleToWorker:function(C,D){C.onmessage=function(L){var Z=L.data,Ae=Z.cmd;if(C.pthread&&(Re.currentProxiedOperationCallerThread=C.pthread.threadInfoStruct),Z.targetThread&&Z.targetThread!=Aa()){var me=Re.pthreads[Z.targetThread];me?me.worker.postMessage(L.data,Z.transferList):console.error('Internal error! Worker sent a message "'+Ae+'" to target pthread '+Z.targetThread+", but that thread no longer exists!"),Re.currentProxiedOperationCallerThread=void 0;return}if(Ae==="processQueuedMainThreadWork")Hp();else if(Ae==="spawnThread")zp(L.data);else if(Ae==="cleanupThread")$p(Z.thread);else if(Ae==="killThread")I0(Z.thread);else if(Ae==="cancelThread")S0(Z.thread);else if(Ae==="loaded")C.loaded=!0,D&&D(C),C.runPthread&&(C.runPthread(),delete C.runPthread);else if(Ae==="print")H("Thread "+Z.threadId+": "+Z.text);else if(Ae==="printErr")z("Thread "+Z.threadId+": "+Z.text);else if(Ae==="alert")alert("Thread "+Z.threadId+": "+Z.text);else if(Ae==="exit"){var ge=C.pthread&&Atomics.load(l(),C.pthread.threadInfoStruct+64>>2);ge&&Re.returnWorkerToPool(C)}else if(Ae==="exitProcess")try{bN(Z.returnCode)}catch(Te){if(Te instanceof Nc)return;throw Te}else Ae==="cancelDone"?Re.returnWorkerToPool(C):Ae==="objectTransfer"?Re.receiveObjectTransfer(L.data):L.data.target==="setimmediate"?C.postMessage(L.data):z("worker sent an unknown command "+Ae);Re.currentProxiedOperationCallerThread=void 0},C.onerror=function(L){z("pthread sent an error! "+L.filename+":"+L.lineno+": "+L.message)},b&&(C.on("message",function(L){C.onmessage({data:L})}),C.on("error",function(L){C.onerror(L)}),C.on("exit",function(L){})),C.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||s,wasmMemory:te,wasmModule:ue})},allocateUnusedWorker:function(){var C=E("tfjs-backend-wasm-threaded-simd.worker.js");Re.unusedWorkers.push(new Worker(C))},getNewWorker:function(){return Re.unusedWorkers.length==0&&(Re.allocateUnusedWorker(),Re.loadWasmModuleToWorker(Re.unusedWorkers[0])),Re.unusedWorkers.length>0?Re.unusedWorkers.pop():null},busySpinWait:function(C){for(var D=performance.now()+C;performance.now()>2]=C,C}function D0(C,D){if(k)return fa(1,1,C,D)}function _0(C,D){if(C==D)postMessage({cmd:"processQueuedMainThreadWork"});else if(k)postMessage({targetThread:C,cmd:"processThreadQueue"});else{var L=Re.pthreads[C],Z=L&&L.worker;if(!Z)return;Z.postMessage({cmd:"processThreadQueue"})}return 1}function P0(){Wr()}function F0(C,D,L){var Z=L0(D,L);return Rp[C].apply(null,Z)}function O0(C,D){}function Dp(C,D,L){if(C<=0||C>a().length||C&!0)return-28;if(y){if(Atomics.load(i(),C>>2)!=D)return-6;for(var Ae=performance.now(),me=Ae+L,ge=Atomics.exchange(i(),Fl>>2,C);;){if(Ae=performance.now(),Ae>me)return ge=Atomics.exchange(i(),Fl>>2,0),-73;if(ge=Atomics.exchange(i(),Fl>>2,0),ge==0)break;if(Hp(),Atomics.load(i(),C>>2)!=D)return-6;ge=Atomics.exchange(i(),Fl>>2,C)}return 0}else{var Z=Atomics.wait(i(),C>>2,D,L);if(Z==="timed-out")return-73;if(Z==="not-equal")return-6;if(Z==="ok")return 0;throw"Atomics.wait returned an unexpected value "+Z}}function M0(C,D,L){o().copyWithin(C,D,D+L)}function z0(){return b?Ws("os").cpus().length:navigator.hardwareConcurrency}function fa(C,D){for(var L=arguments.length-2,Z=Tc(),Ae=L,me=Pl(Ae*8),ge=me>>3,Te=0;Te>=2;L=o()[C++];){var Z=L<105;Z&&D&1&&D++,vc.push(Z?c()[D++>>1]:i()[D]),++D}return vc}function B0(C,D,L){bc.length=D;for(var Z=L>>3,Ae=0;Ae>>16),kn(te.buffer),1}catch(D){}}function U0(C){var D=W0();if(C<=D)return!1;var L=2147483648;if(C>L)return!1;for(var Z=1;Z<=4;Z*=2){var Ae=D*(1+.2/Z);Ae=Math.min(Ae,C+100663296);var me=Math.min(L,yt(Math.max(C,Ae),65536)),ge=V0(me);if(ge)return!0}return!1}var Ge={inEventHandler:0,removeAllEventListeners:function(){for(var C=Ge.eventHandlers.length-1;C>=0;--C)Ge._removeHandler(C);Ge.eventHandlers=[],Ge.deferredCalls=[]},registerRemoveEventListeners:function(){Ge.removeEventListenersRegistered||(Ac.push(Ge.removeAllEventListeners),Ge.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(C,D,L){function Z(ge,Te){if(ge.length!=Te.length)return!1;for(var ht in ge)if(ge[ht]!=Te[ht])return!1;return!0}for(var Ae in Ge.deferredCalls){var me=Ge.deferredCalls[Ae];if(me.targetFunction==C&&Z(me.argsList,L))return}Ge.deferredCalls.push({targetFunction:C,precedence:D,argsList:L}),Ge.deferredCalls.sort(function(ge,Te){return ge.precedence>2]=L,i()[ge+4>>2]=Z,i()[ge+8>>2]=Ae,_g(0,C,637534208,D,Z,ge),_l(me)},getTargetThreadForEventCallback:function(C){switch(C){case 1:return 0;case 2:return Re.currentProxiedOperationCallerThread;default:return C}},getNodeNameForTarget:function(C){return C?C==window?"#window":C==screen?"#screen":C&&C.nodeName?C.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function G0(C){var D=ct(C)+1,L=Yo(D);return ut(C,L,D),L}function H0(C,D,L,Z){var Ae=Tc(),me=Pl(12),ge=0;D&&(ge=G0(D)),i()[me>>2]=ge,i()[me+4>>2]=L,i()[me+8>>2]=Z,_g(0,C,657457152,0,ge,me),_l(Ae)}function j0(C,D,L,Z){D=D?rt(D):"",H0(C,D,L,Z)}function q0(C){return C>2?rt(C):C}var X0=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function K0(C){C=q0(C);var D=X0[C]||(typeof document!="undefined"?document.querySelector(C):void 0);return D}function wc(C){return K0(C)}function _p(C,D,L){var Z=wc(C);if(!Z)return-4;if(Z.canvasSharedPtr&&(i()[Z.canvasSharedPtr>>2]=D,i()[Z.canvasSharedPtr+4>>2]=L),Z.offscreenCanvas||!Z.controlTransferredOffscreen){Z.offscreenCanvas&&(Z=Z.offscreenCanvas);var Ae=!1;if(Z.GLctxObject&&Z.GLctxObject.GLctx){var me=Z.GLctxObject.GLctx.getParameter(2978);Ae=me[0]===0&&me[1]===0&&me[2]===Z.width&&me[3]===Z.height}Z.width=D,Z.height=L,Ae&&Z.GLctxObject.GLctx.viewport(0,0,D,L)}else if(Z.canvasSharedPtr){var ge=i()[Z.canvasSharedPtr+8>>2];return j0(ge,C,D,L),1}else return-4;return 0}function Pp(C,D,L){return k?fa(2,1,C,D,L):_p(C,D,L)}function Z0(C,D,L){var Z=wc(C);return Z?_p(C,D,L):Pp(C,D,L)}function Y0(C){}function J0(C,D){}function Q0(C){var D=C.getExtension("ANGLE_instanced_arrays");if(D)return C.vertexAttribDivisor=function(L,Z){D.vertexAttribDivisorANGLE(L,Z)},C.drawArraysInstanced=function(L,Z,Ae,me){D.drawArraysInstancedANGLE(L,Z,Ae,me)},C.drawElementsInstanced=function(L,Z,Ae,me,ge){D.drawElementsInstancedANGLE(L,Z,Ae,me,ge)},1}function eg(C){var D=C.getExtension("OES_vertex_array_object");if(D)return C.createVertexArray=function(){return D.createVertexArrayOES()},C.deleteVertexArray=function(L){D.deleteVertexArrayOES(L)},C.bindVertexArray=function(L){D.bindVertexArrayOES(L)},C.isVertexArray=function(L){return D.isVertexArrayOES(L)},1}function tg(C){var D=C.getExtension("WEBGL_draw_buffers");if(D)return C.drawBuffers=function(L,Z){D.drawBuffersWEBGL(L,Z)},1}function ng(C){return!!(C.multiDrawWebgl=C.getExtension("WEBGL_multi_draw"))}var dt={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,recordError:function(D){dt.lastError||(dt.lastError=D)},getNewId:function(C){for(var D=dt.counter++,L=C.length;L>2]:-1;Ae+=rt(i()[L+me*4>>2],ge<0?void 0:ge)}return Ae},createContext:function(C,D){var L=C.getContext("webgl",D);if(!L)return 0;var Z=dt.registerContext(L,D);return Z},registerContext:function(C,D){var L=Yo(8);i()[L+4>>2]=Aa();var Z={handle:L,attributes:D,version:D.majorVersion,GLctx:C};return C.canvas&&(C.canvas.GLctxObject=Z),dt.contexts[L]=Z,(typeof D.enableExtensionsByDefault=="undefined"||D.enableExtensionsByDefault)&&dt.initExtensions(Z),L},makeContextCurrent:function(C){return dt.currentContext=dt.contexts[C],u.ctx=ma=dt.currentContext&&dt.currentContext.GLctx,!(C&&!ma)},getContext:function(C){return dt.contexts[C]},deleteContext:function(C){dt.currentContext===dt.contexts[C]&&(dt.currentContext=null),typeof Ge=="object"&&Ge.removeAllHandlersOnTarget(dt.contexts[C].GLctx.canvas),dt.contexts[C]&&dt.contexts[C].GLctx.canvas&&(dt.contexts[C].GLctx.canvas.GLctxObject=void 0),Cc(dt.contexts[C].handle),dt.contexts[C]=null},initExtensions:function(C){if(C||(C=dt.currentContext),!C.initExtensionsDone){C.initExtensionsDone=!0;var D=C.GLctx;Q0(D),eg(D),tg(D),D.disjointTimerQueryExt=D.getExtension("EXT_disjoint_timer_query"),ng(D);var L=D.getSupportedExtensions()||[];L.forEach(function(Z){Z.indexOf("lose_context")<0&&Z.indexOf("debug")<0&&D.getExtension(Z)})}},populateUniformTable:function(C){for(var D=dt.programs[C],L=dt.programInfos[C]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},Z=L.uniforms,Ae=ma.getProgramParameter(D,35718),me=0;me>2,Z=i()[L+(24>>2)],Ae={alpha:!!i()[L+(0>>2)],depth:!!i()[L+(4>>2)],stencil:!!i()[L+(8>>2)],antialias:!!i()[L+(12>>2)],premultipliedAlpha:!!i()[L+(16>>2)],preserveDrawingBuffer:!!i()[L+(20>>2)],powerPreference:sg[Z],failIfMajorPerformanceCaveat:!!i()[L+(28>>2)],majorVersion:i()[L+(32>>2)],minorVersion:i()[L+(36>>2)],enableExtensionsByDefault:i()[L+(40>>2)],explicitSwapControl:i()[L+(44>>2)],proxyContextToMainThread:i()[L+(48>>2)],renderViaOffscreenBackBuffer:i()[L+(52>>2)]},me=wc(C);if(!me||Ae.explicitSwapControl)return 0;var ge=dt.createContext(me,Ae);return ge}function ag(C,D){return rg(C,D)}var $l={mappings:{},buffers:[null,[],[]],printChar:function(C,D){var L=$l.buffers[C];D===0||D===10?((C===1?H:z)(Xe(L,0)),L.length=0):L.push(D)},varargs:void 0,get:function(){$l.varargs+=4;var C=i()[$l.varargs-4>>2];return C},getStr:function(C){var D=rt(C);return D},get64:function(C,D){return C}};function Fp(C){return k?fa(3,1,C):0}function Op(C,D,L,Z,Ae){if(k)return fa(4,1,C,D,L,Z,Ae)}function Mp(C,D,L,Z){if(k)return fa(5,1,C,D,L,Z);for(var Ae=0,me=0;me>2],Te=i()[D+(me*8+4)>>2],ht=0;ht>2]=Ae,0}function og(C){var D=Re.threadExitHandlers.pop();C&&D()}function ig(C,D){Re.threadExitHandlers.push(function(){Rn.get(C)(D)})}function zp(C){if(k)throw"Internal Error! spawnThread() can only ever be called from main application thread!";var D=Re.getNewWorker();if(D.pthread!==void 0)throw"Internal error!";if(!C.pthread_ptr)throw"Internal error, no pthread ptr!";Re.runningWorkers.push(D);for(var L=Yo(128*4),Z=0;Z<128;++Z)i()[L+Z*4>>2]=0;var Ae=C.stackBase+C.stackSize,me=Re.pthreads[C.pthread_ptr]={worker:D,stackBase:C.stackBase,stackSize:C.stackSize,allocatedOwnStack:C.allocatedOwnStack,threadInfoStruct:C.pthread_ptr},ge=me.threadInfoStruct>>2;Atomics.store(l(),ge+(64>>2),C.detached),Atomics.store(l(),ge+(100>>2),L),Atomics.store(l(),ge+(40>>2),me.threadInfoStruct),Atomics.store(l(),ge+(80>>2),C.stackSize),Atomics.store(l(),ge+(76>>2),Ae),Atomics.store(l(),ge+(104>>2),C.stackSize),Atomics.store(l(),ge+(104+8>>2),Ae),Atomics.store(l(),ge+(104+12>>2),C.detached);var Te=Vb(),ht=Te+40;Atomics.store(l(),ge+(172>>2),ht),D.pthread=me;var fn={cmd:"run",start_routine:C.startRoutine,arg:C.arg,threadInfoStruct:C.pthread_ptr,stackBase:C.stackBase,stackSize:C.stackSize};D.runPthread=function(){fn.time=performance.now(),D.postMessage(fn,C.transferList)},D.loaded&&(D.runPthread(),delete D.runPthread)}function lg(C,D,L,Z){if(typeof SharedArrayBuffer=="undefined")return z("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;if(!C)return z("pthread_create called with a null thread pointer!"),28;var Ae=[],me=0;if(k&&(Ae.length===0||me))return qb(687865856,C,D,L,Z);if(me)return me;var ge=0,Te=0,ht=0;D&&D!=-1?(ge=i()[D>>2],ge+=81920,Te=i()[D+8>>2],ht=i()[D+12>>2]!==0):ge=2097152;var fn=Te==0;fn?Te=Zb(16,ge):(Te-=ge,we(Te>0));for(var nn=Yo(228),ya=0;ya<228>>2;++ya)l()[(nn>>2)+ya]=0;i()[C>>2]=nn,i()[nn+12>>2]=nn;var Ol=nn+152;i()[Ol>>2]=Ol;var Mn={stackBase:Te,stackSize:ge,allocatedOwnStack:fn,detached:ht,startRoutine:L,pthread_ptr:nn,arg:Z,transferList:Ae};return k?(Mn.cmd="spawnThread",postMessage(Mn,Ae)):zp(Mn),0}function ug(){if(!!k){var C=Aa();if(!!C){var D=Atomics.load(l(),C+56>>2);if(!D){var L=Atomics.load(l(),C+0>>2);if(L==2)throw"Canceled!"}}}}function cg(){b||x||X("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function dg(C,D,L){if(!C)return z("pthread_join attempted on a null thread pointer!"),ha.ESRCH;if(k&&Aa()==C)return z("PThread "+C+" is attempting to join to itself!"),ha.EDEADLK;if(!k&&Hb()==C)return z("Main thread "+C+" is attempting to join to itself!"),ha.EDEADLK;var Z=i()[C+12>>2];if(Z!==C)return z("pthread_join attempted on thread "+C+", which does not point to a valid thread, or does not exist anymore!"),ha.ESRCH;var Ae=Atomics.load(l(),C+64>>2);if(Ae)return z("Attempted to join thread "+C+", which was already detached!"),ha.EINVAL;for(L&&cg();;){var me=Atomics.load(l(),C+0>>2);if(me==1){var ge=Atomics.load(l(),C+4>>2);return D&&(i()[D>>2]=ge),Atomics.store(l(),C+64>>2,1),k?postMessage({cmd:"cleanupThread",thread:C}):$p(C),0}if(!L)return ha.EBUSY;ug(),k||Hp(),Dp(C+0,me,k?100:1)}}function pg(C,D){return dg(C,D,!0)}function Lp(C){if(k)return fa(6,1,C);switch(C){case 30:return 16384;case 85:var D=2147483648;return D/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return typeof navigator=="object"&&navigator.hardwareConcurrency||1}return $0(28),-1}k||Re.initMainThreadBlock();var ma,hg=[null,D0,Pp,Fp,Op,Mp,Lp],fg={e:E0,r:R0,x:_0,b:P0,y:F0,j:O0,d:Dp,c:xc,f:Zo,p:M0,A:z0,u:B0,q:U0,v:Z0,i:Y0,s:J0,w:ag,l:Fp,n:Op,g:Mp,o:k0,a:te||u.wasmMemory,z:og,k:ig,h:lg,m:pg,t:Lp},Bb=w0(),Bp=u.___wasm_call_ctors=function(){return(Bp=u.___wasm_call_ctors=u.asm.B).apply(null,arguments)},mg=u._init=function(){return(mg=u._init=u.asm.C).apply(null,arguments)},gg=u._init_with_threads_count=function(){return(gg=u._init_with_threads_count=u.asm.D).apply(null,arguments)},Ag=u._get_threads_count=function(){return(Ag=u._get_threads_count=u.asm.E).apply(null,arguments)},yg=u._register_tensor=function(){return(yg=u._register_tensor=u.asm.F).apply(null,arguments)},xg=u._dispose_data=function(){return(xg=u._dispose_data=u.asm.G).apply(null,arguments)},bg=u._dispose=function(){return(bg=u._dispose=u.asm.H).apply(null,arguments)},vg=u._Abs=function(){return(vg=u._Abs=u.asm.I).apply(null,arguments)},wg=u._Add=function(){return(wg=u._Add=u.asm.J).apply(null,arguments)},kg=u._AddN=function(){return(kg=u._AddN=u.asm.K).apply(null,arguments)},Ig=u._All=function(){return(Ig=u._All=u.asm.L).apply(null,arguments)},Sg=u._Any=function(){return(Sg=u._Any=u.asm.M).apply(null,arguments)},Cg=u._ArgMax=function(){return(Cg=u._ArgMax=u.asm.N).apply(null,arguments)},Tg=u._AvgPool=function(){return(Tg=u._AvgPool=u.asm.O).apply(null,arguments)},Ng=u._BatchMatMul=function(){return(Ng=u._BatchMatMul=u.asm.P).apply(null,arguments)},Eg=u._Ceil=function(){return(Eg=u._Ceil=u.asm.Q).apply(null,arguments)},Rg=u._ClipByValue=function(){return(Rg=u._ClipByValue=u.asm.R).apply(null,arguments)},$g=u._Conv2D=function(){return($g=u._Conv2D=u.asm.S).apply(null,arguments)},Wp=u._Conv2DBackpropInput=function(){return(Wp=u._Conv2DBackpropInput=u.asm.T).apply(null,arguments)},Vp=u._Cos=function(){return(Vp=u._Cos=u.asm.U).apply(null,arguments)},kc=u._Cosh=function(){return(kc=u._Cosh=u.asm.V).apply(null,arguments)},Dl=u._CropAndResize=function(){return(Dl=u._CropAndResize=u.asm.W).apply(null,arguments)},Dg=u._Cumsum=function(){return(Dg=u._Cumsum=u.asm.X).apply(null,arguments)},Ic=u._DepthToSpace=function(){return(Ic=u._DepthToSpace=u.asm.Y).apply(null,arguments)},re=u._DepthwiseConv2dNative=function(){return(re=u._DepthwiseConv2dNative=u.asm.Z).apply(null,arguments)},oe=u._Elu=function(){return(oe=u._Elu=u.asm._).apply(null,arguments)},ke=u._Equal=function(){return(ke=u._Equal=u.asm.$).apply(null,arguments)},it=u._Exp=function(){return(it=u._Exp=u.asm.aa).apply(null,arguments)},Lt=u._FlipLeftRight=function(){return(Lt=u._FlipLeftRight=u.asm.ba).apply(null,arguments)},Rt=u._Floor=function(){return(Rt=u._Floor=u.asm.ca).apply(null,arguments)},Je=u._FloorDiv=function(){return(Je=u._FloorDiv=u.asm.da).apply(null,arguments)},Qe=u._FusedBatchNorm=function(){return(Qe=u._FusedBatchNorm=u.asm.ea).apply(null,arguments)},In=u._FusedConv2D=function(){return(In=u._FusedConv2D=u.asm.fa).apply(null,arguments)},Vr=u._FusedDepthwiseConv2D=function(){return(Vr=u._FusedDepthwiseConv2D=u.asm.ga).apply(null,arguments)},Ur=u._Gather=function(){return(Ur=u._Gather=u.asm.ha).apply(null,arguments)},Up=u._GatherNd=function(){return(Up=u._GatherNd=u.asm.ia).apply(null,arguments)},Sc=u._Greater=function(){return(Sc=u._Greater=u.asm.ja).apply(null,arguments)},ps=u._GreaterEqual=function(){return(ps=u._GreaterEqual=u.asm.ka).apply(null,arguments)},ga=u._LeakyRelu=function(){return(ga=u._LeakyRelu=u.asm.la).apply(null,arguments)},Gp=u._Less=function(){return(Gp=u._Less=u.asm.ma).apply(null,arguments)},IT=u._LessEqual=function(){return(IT=u._LessEqual=u.asm.na).apply(null,arguments)},ST=u._Log=function(){return(ST=u._Log=u.asm.oa).apply(null,arguments)},CT=u._LogicalAnd=function(){return(CT=u._LogicalAnd=u.asm.pa).apply(null,arguments)},TT=u._Max=function(){return(TT=u._Max=u.asm.qa).apply(null,arguments)},NT=u._MaxPool=function(){return(NT=u._MaxPool=u.asm.ra).apply(null,arguments)},ET=u._Maximum=function(){return(ET=u._Maximum=u.asm.sa).apply(null,arguments)},RT=u._Mean=function(){return(RT=u._Mean=u.asm.ta).apply(null,arguments)},$T=u._Min=function(){return($T=u._Min=u.asm.ua).apply(null,arguments)},DT=u._Minimum=function(){return(DT=u._Minimum=u.asm.va).apply(null,arguments)},_T=u._MirrorPad=function(){return(_T=u._MirrorPad=u.asm.wa).apply(null,arguments)},PT=u._Multiply=function(){return(PT=u._Multiply=u.asm.xa).apply(null,arguments)},FT=u._Neg=function(){return(FT=u._Neg=u.asm.ya).apply(null,arguments)},OT=u._NonMaxSuppressionV3=function(){return(OT=u._NonMaxSuppressionV3=u.asm.za).apply(null,arguments)},MT=u._NonMaxSuppressionV4=function(){return(MT=u._NonMaxSuppressionV4=u.asm.Aa).apply(null,arguments)},zT=u._NonMaxSuppressionV5=function(){return(zT=u._NonMaxSuppressionV5=u.asm.Ba).apply(null,arguments)},LT=u._NotEqual=function(){return(LT=u._NotEqual=u.asm.Ca).apply(null,arguments)},BT=u._OneHot=function(){return(BT=u._OneHot=u.asm.Da).apply(null,arguments)},WT=u._PadV2=function(){return(WT=u._PadV2=u.asm.Ea).apply(null,arguments)},VT=u._Pow=function(){return(VT=u._Pow=u.asm.Fa).apply(null,arguments)},UT=u._Prelu=function(){return(UT=u._Prelu=u.asm.Ga).apply(null,arguments)},GT=u._Prod=function(){return(GT=u._Prod=u.asm.Ha).apply(null,arguments)},HT=u._RealDiv=function(){return(HT=u._RealDiv=u.asm.Ia).apply(null,arguments)},jT=u._Relu=function(){return(jT=u._Relu=u.asm.Ja).apply(null,arguments)},qT=u._Relu6=function(){return(qT=u._Relu6=u.asm.Ka).apply(null,arguments)},XT=u._ResizeBilinear=function(){return(XT=u._ResizeBilinear=u.asm.La).apply(null,arguments)},KT=u._Reverse=function(){return(KT=u._Reverse=u.asm.Ma).apply(null,arguments)},ZT=u._RotateWithOffset=function(){return(ZT=u._RotateWithOffset=u.asm.Na).apply(null,arguments)},YT=u._Round=function(){return(YT=u._Round=u.asm.Oa).apply(null,arguments)},JT=u._Rsqrt=function(){return(JT=u._Rsqrt=u.asm.Pa).apply(null,arguments)},QT=u._ScatterNd=function(){return(QT=u._ScatterNd=u.asm.Qa).apply(null,arguments)},eN=u._SelectV2=function(){return(eN=u._SelectV2=u.asm.Ra).apply(null,arguments)},tN=u._Sigmoid=function(){return(tN=u._Sigmoid=u.asm.Sa).apply(null,arguments)},nN=u._Sin=function(){return(nN=u._Sin=u.asm.Ta).apply(null,arguments)},sN=u._Softmax=function(){return(sN=u._Softmax=u.asm.Ua).apply(null,arguments)},rN=u._Sqrt=function(){return(rN=u._Sqrt=u.asm.Va).apply(null,arguments)},aN=u._Square=function(){return(aN=u._Square=u.asm.Wa).apply(null,arguments)},oN=u._SquaredDifference=function(){return(oN=u._SquaredDifference=u.asm.Xa).apply(null,arguments)},iN=u._Step=function(){return(iN=u._Step=u.asm.Ya).apply(null,arguments)},lN=u._StridedSlice=function(){return(lN=u._StridedSlice=u.asm.Za).apply(null,arguments)},uN=u._Sub=function(){return(uN=u._Sub=u.asm._a).apply(null,arguments)},cN=u._Sum=function(){return(cN=u._Sum=u.asm.$a).apply(null,arguments)},dN=u._Tan=function(){return(dN=u._Tan=u.asm.ab).apply(null,arguments)},pN=u._Tanh=function(){return(pN=u._Tanh=u.asm.bb).apply(null,arguments)},hN=u._Tile=function(){return(hN=u._Tile=u.asm.cb).apply(null,arguments)},fN=u._TopK=function(){return(fN=u._TopK=u.asm.db).apply(null,arguments)},mN=u._Transform=function(){return(mN=u._Transform=u.asm.eb).apply(null,arguments)},gN=u._Transpose=function(){return(gN=u._Transpose=u.asm.fb).apply(null,arguments)},AN=u.__FusedMatMul=function(){return(AN=u.__FusedMatMul=u.asm.gb).apply(null,arguments)},Yo=u._malloc=function(){return(Yo=u._malloc=u.asm.hb).apply(null,arguments)},Cc=u._free=function(){return(Cc=u._free=u.asm.ib).apply(null,arguments)},Wb=u.___errno_location=function(){return(Wb=u.___errno_location=u.asm.jb).apply(null,arguments)},Vb=u._emscripten_get_global_libc=function(){return(Vb=u._emscripten_get_global_libc=u.asm.lb).apply(null,arguments)},Aa=u._pthread_self=function(){return(Aa=u._pthread_self=u.asm.mb).apply(null,arguments)},Ub=u.___pthread_tsd_run_dtors=function(){return(Ub=u.___pthread_tsd_run_dtors=u.asm.nb).apply(null,arguments)},Hp=u._emscripten_main_thread_process_queued_calls=function(){return(Hp=u._emscripten_main_thread_process_queued_calls=u.asm.ob).apply(null,arguments)},yN=u._emscripten_current_thread_process_queued_calls=function(){return(yN=u._emscripten_current_thread_process_queued_calls=u.asm.pb).apply(null,arguments)},Gb=u._emscripten_register_main_browser_thread_id=function(){return(Gb=u._emscripten_register_main_browser_thread_id=u.asm.qb).apply(null,arguments)},Hb=u._emscripten_main_browser_thread_id=function(){return(Hb=u._emscripten_main_browser_thread_id=u.asm.rb).apply(null,arguments)},jb=u.__emscripten_do_dispatch_to_thread=function(){return(jb=u.__emscripten_do_dispatch_to_thread=u.asm.sb).apply(null,arguments)},qb=u._emscripten_sync_run_in_main_thread_4=function(){return(qb=u._emscripten_sync_run_in_main_thread_4=u.asm.tb).apply(null,arguments)},Xb=u._emscripten_run_in_main_runtime_thread_js=function(){return(Xb=u._emscripten_run_in_main_runtime_thread_js=u.asm.ub).apply(null,arguments)},_g=u.__emscripten_call_on_thread=function(){return(_g=u.__emscripten_call_on_thread=u.asm.vb).apply(null,arguments)},xN=u._emscripten_tls_init=function(){return(xN=u._emscripten_tls_init=u.asm.wb).apply(null,arguments)},Pg=u.__emscripten_thread_init=function(){return(Pg=u.__emscripten_thread_init=u.asm.xb).apply(null,arguments)},Tc=u.stackSave=function(){return(Tc=u.stackSave=u.asm.yb).apply(null,arguments)},_l=u.stackRestore=function(){return(_l=u.stackRestore=u.asm.zb).apply(null,arguments)},Pl=u.stackAlloc=function(){return(Pl=u.stackAlloc=u.asm.Ab).apply(null,arguments)},Kb=u._emscripten_stack_set_limits=function(){return(Kb=u._emscripten_stack_set_limits=u.asm.Bb).apply(null,arguments)},Zb=u._memalign=function(){return(Zb=u._memalign=u.asm.Cb).apply(null,arguments)},Yb=u.__emscripten_allow_main_runtime_queued_calls=10064,Fl=u.__emscripten_main_thread_futex=10268;u.cwrap=Ue,u.PThread=Re,u.PThread=Re,u.wasmMemory=te,u.ExitStatus=Nc;var jp;function Nc(C){this.name="ExitStatus",this.message="Program terminated with exit("+C+")",this.status=C}Xo=function C(){jp||Fg(),jp||(Xo=C)};function Fg(C){if(C=C||m,Bs>0)return;if(k){d(u),Ip(),postMessage({cmd:"loaded"});return}if(kp(),Bs>0)return;function D(){jp||(jp=!0,u.calledRun=!0,!ce&&(Ip(),Sp(),d(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),Cp()))}u.setStatus?(u.setStatus("Running..."),setTimeout(function(){setTimeout(function(){u.setStatus("")},1),D()},1)):D()}u.run=Fg;function bN(C,D){if(!(D&&J&&C===0)){if(!D&&k)throw postMessage({cmd:"exitProcess",returnCode:C}),new Nc(C);J||(Re.terminateAllThreads(),be=C,Qn(),u.onExit&&u.onExit(C),ce=!0),A(C,new Nc(C))}}if(u.preInit)for(typeof u.preInit=="function"&&(u.preInit=[u.preInit]);u.preInit.length>0;)u.preInit.pop()();return k&&(J=!1,Re.initWorker()),Fg(),r.ready}}();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModuleThreadedSimd=n)}}),WN=ts({"src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js"(e,t){var n=function(){var s=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(s=s||__filename),function(r){r=r||{};var a=typeof r!="undefined"?r:{},o,i;a.ready=new Promise(function(re,oe){o=re,i=oe});var l={},c;for(c in a)a.hasOwnProperty(c)&&(l[c]=a[c]);var u=[],d="./this.program",p=function(re,oe){throw oe},h=!1,f=!1,m=!1,g=!1;h=typeof window=="object",f=typeof importScripts=="function",m=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g=!h&&!m&&!f;var A="";function y(re){return a.locateFile?a.locateFile(re,A):A+re}var x,b,w,k,S,E;m?(f?A=Ws("path").dirname(A)+"/":A=__dirname+"/",x=function(oe,ke){return S||(S=Ws("fs")),E||(E=Ws("path")),oe=E.normalize(oe),S.readFileSync(oe,ke?null:"utf8")},w=function(oe){var ke=x(oe,!0);return ke.buffer||(ke=new Uint8Array(ke)),H(ke.buffer),ke},process.argv.length>1&&(d=process.argv[1].replace(/\\/g,"/")),u=process.argv.slice(2),process.on("uncaughtException",function(re){if(!(re instanceof Dg))throw re}),process.on("unhandledRejection",sr),p=function(re){process.exit(re)},a.inspect=function(){return"[Emscripten Module object]"}):g?(typeof read!="undefined"&&(x=function(oe){return read(oe)}),w=function(oe){var ke;return typeof readbuffer=="function"?new Uint8Array(readbuffer(oe)):(ke=read(oe,"binary"),H(typeof ke=="object"),ke)},typeof scriptArgs!="undefined"?u=scriptArgs:typeof arguments!="undefined"&&(u=arguments),typeof quit=="function"&&(p=function(re){quit(re)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(h||f)&&(f?A=self.location.href:typeof document!="undefined"&&document.currentScript&&(A=document.currentScript.src),s&&(A=s),A.indexOf("blob:")!==0?A=A.substr(0,A.lastIndexOf("/")+1):A="",x=function(re){var oe=new XMLHttpRequest;return oe.open("GET",re,!1),oe.send(null),oe.responseText},f&&(w=function(re){var oe=new XMLHttpRequest;return oe.open("GET",re,!1),oe.responseType="arraybuffer",oe.send(null),new Uint8Array(oe.response)}),b=function(re,oe,ke){var it=new XMLHttpRequest;it.open("GET",re,!0),it.responseType="arraybuffer",it.onload=function(){if(it.status==200||it.status==0&&it.response){oe(it.response);return}ke()},it.onerror=ke,it.send(null)},k=function(re){document.title=re});var $=a.print||console.log.bind(console),F=a.printErr||console.warn.bind(console);for(c in l)l.hasOwnProperty(c)&&(a[c]=l[c]);l=null,a.arguments&&(u=a.arguments),a.thisProgram&&(d=a.thisProgram),a.quit&&(p=a.quit);var R;a.wasmBinary&&(R=a.wasmBinary);var P=a.noExitRuntime||!0;typeof WebAssembly!="object"&&sr("no native wasm support detected");var T,M=!1,U;function H(re,oe){re||sr("Assertion failed: "+oe)}function z(re){var oe=a["_"+re];return H(oe,"Cannot call unknown function "+re+", make sure it is exported"),oe}function X(re,oe,ke,it,Lt){var Rt={string:function(ps){var ga=0;if(ps!=null&&ps!==0){var Gp=(ps.length<<2)+1;ga=kc(Gp),te(ps,ga,Gp)}return ga},array:function(ps){var ga=kc(ps.length);return ue(ps,ga),ga}};function Je(ps){return oe==="string"?se(ps):oe==="boolean"?Boolean(ps):ps}var Qe=z(re),In=[],Vr=0;if(it)for(var Ur=0;Ur=it);)++Lt;if(Lt-oe>16&&re.subarray&&Y)return Y.decode(re.subarray(oe,Lt));for(var Rt="";oe>10,56320|Vr&1023)}}return Rt}function se(re,oe){return re?ne(Ce,re,oe):""}function J(re,oe,ke,it){if(!(it>0))return 0;for(var Lt=ke,Rt=ke+it-1,Je=0;Je=55296&&Qe<=57343){var In=re.charCodeAt(++Je);Qe=65536+((Qe&1023)<<10)|In&1023}if(Qe<=127){if(ke>=Rt)break;oe[ke++]=Qe}else if(Qe<=2047){if(ke+1>=Rt)break;oe[ke++]=192|Qe>>6,oe[ke++]=128|Qe&63}else if(Qe<=65535){if(ke+2>=Rt)break;oe[ke++]=224|Qe>>12,oe[ke++]=128|Qe>>6&63,oe[ke++]=128|Qe&63}else{if(ke+3>=Rt)break;oe[ke++]=240|Qe>>18,oe[ke++]=128|Qe>>12&63,oe[ke++]=128|Qe>>6&63,oe[ke++]=128|Qe&63}}return oe[ke]=0,ke-Lt}function te(re,oe,ke){return J(re,Ce,oe,ke)}function ue(re,oe){we.set(re,oe)}function ce(re,oe){return re%oe>0&&(re+=oe-re%oe),re}var be,we,Ce,Oe,Ue,Xe,rt,ft,ut;function ct(re){be=re,a.HEAP8=we=new Int8Array(re),a.HEAP16=Oe=new Int16Array(re),a.HEAP32=Xe=new Int32Array(re),a.HEAPU8=Ce=new Uint8Array(re),a.HEAPU16=Ue=new Uint16Array(re),a.HEAPU32=rt=new Uint32Array(re),a.HEAPF32=ft=new Float32Array(re),a.HEAPF64=ut=new Float64Array(re)}var At=a.INITIAL_MEMORY||16777216,yt,Et=[],Pt=[],Jn=[],wn=[],nr=!1;Pt.push({func:function(){Ep()}});function On(){if(a.preRun)for(typeof a.preRun=="function"&&(a.preRun=[a.preRun]);a.preRun.length;)kn(a.preRun.shift());Bs(Et)}function ds(){nr=!0,Bs(Pt)}function Ls(){Bs(Jn)}function Is(){if(a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;)br(a.postRun.shift());Bs(wn)}function kn(re){Et.unshift(re)}function br(re){wn.unshift(re)}var Rn=0,vr=null,wr=null;function pa(re){Rn++,a.monitorRunDependencies&&a.monitorRunDependencies(Rn)}function Ac(re){if(Rn--,a.monitorRunDependencies&&a.monitorRunDependencies(Rn),Rn==0&&(vr!==null&&(clearInterval(vr),vr=null),wr)){var oe=wr;wr=null,oe()}}a.preloadedImages={},a.preloadedAudios={};function sr(re){a.onAbort&&a.onAbort(re),re+="",F(re),M=!0,U=1,re="abort("+re+"). Build with -s ASSERTIONS=1 for more info.";var oe=new WebAssembly.RuntimeError(re);throw i(oe),oe}function wp(re,oe){return String.prototype.startsWith?re.startsWith(oe):re.indexOf(oe)===0}var f0="data:application/octet-stream;base64,";function kp(re){return wp(re,f0)}var Ip="file://";function Sp(re){return wp(re,Ip)}var Qn="tfjs-backend-wasm.wasm";kp(Qn)||(Qn=y(Qn));function Cp(re){try{if(re==Qn&&R)return new Uint8Array(R);if(w)return w(re);throw"both async and sync fetching of the wasm failed"}catch(oe){sr(oe)}}function m0(){if(!R&&(h||f)){if(typeof fetch=="function"&&!Sp(Qn))return fetch(Qn,{credentials:"same-origin"}).then(function(re){if(!re.ok)throw"failed to load wasm binary file at '"+Qn+"'";return re.arrayBuffer()}).catch(function(){return Cp(Qn)});if(b)return new Promise(function(re,oe){b(Qn,function(ke){re(new Uint8Array(ke))},oe)})}return Promise.resolve().then(function(){return Cp(Qn)})}function g0(){var re={a:es};function oe(Je,Qe){var In=Je.exports;a.asm=In,T=a.asm.h,ct(T.buffer),yt=a.asm.Sa,Ac("wasm-instantiate")}pa("wasm-instantiate");function ke(Je){oe(Je.instance)}function it(Je){return m0().then(function(Qe){return WebAssembly.instantiate(Qe,re)}).then(Je,function(Qe){F("failed to asynchronously prepare wasm: "+Qe),sr(Qe)})}function Lt(){return!R&&typeof WebAssembly.instantiateStreaming=="function"&&!kp(Qn)&&!Sp(Qn)&&typeof fetch=="function"?fetch(Qn,{credentials:"same-origin"}).then(function(Je){var Qe=WebAssembly.instantiateStreaming(Je,re);return Qe.then(ke,function(In){return F("wasm streaming compile failed: "+In),F("falling back to ArrayBuffer instantiation"),it(ke)})}):it(ke)}if(a.instantiateWasm)try{var Rt=a.instantiateWasm(re,oe);return Rt}catch(Je){return F("Module.instantiateWasm callback failed with error: "+Je),!1}return Lt().catch(i),{}}function Bs(re){for(;re.length>0;){var oe=re.shift();if(typeof oe=="function"){oe(a);continue}var ke=oe.func;typeof ke=="number"?oe.arg===void 0?yt.get(ke)():yt.get(ke)(oe.arg):ke(oe.arg===void 0?null:oe.arg)}}function yc(){sr()}function Xo(re,oe,ke){Ce.copyWithin(re,oe,oe+ke)}function A0(){return Ce.length}function y0(re){try{return T.grow(re-be.byteLength+65535>>>16),ct(T.buffer),1}catch(oe){}}function Wr(re){var oe=A0(),ke=2147483648;if(re>ke)return!1;for(var it=1;it<=4;it*=2){var Lt=oe*(1+.2/it);Lt=Math.min(Lt,re+100663296);var Rt=Math.min(ke,ce(Math.max(re,Lt),65536)),Je=y0(Rt);if(Je)return!0}return!1}var Ko={mappings:{},buffers:[null,[],[]],printChar:function(re,oe){var ke=Ko.buffers[re];oe===0||oe===10?((re===1?$:F)(ne(ke,0)),ke.length=0):ke.push(oe)},varargs:void 0,get:function(){Ko.varargs+=4;var re=Xe[Ko.varargs-4>>2];return re},getStr:function(re){var oe=se(re);return oe},get64:function(re,oe){return re}};function x0(re){return 0}function Tp(re,oe,ke,it,Lt){}function b0(re,oe,ke,it){for(var Lt=0,Rt=0;Rt>2],Qe=Xe[oe+(Rt*8+4)>>2],In=0;In>2]=Lt,0}function Np(){return 28}var es={a:yc,d:Xo,e:Wr,f:x0,c:Tp,b:b0,g:Np},v0=g0(),Ep=a.___wasm_call_ctors=function(){return(Ep=a.___wasm_call_ctors=a.asm.i).apply(null,arguments)},w0=a._init=function(){return(w0=a._init=a.asm.j).apply(null,arguments)},Rp=a._init_with_threads_count=function(){return(Rp=a._init_with_threads_count=a.asm.k).apply(null,arguments)},k0=a._get_threads_count=function(){return(k0=a._get_threads_count=a.asm.l).apply(null,arguments)},Rl=a._register_tensor=function(){return(Rl=a._register_tensor=a.asm.m).apply(null,arguments)},ha=a._dispose_data=function(){return(ha=a._dispose_data=a.asm.n).apply(null,arguments)},xc=a._dispose=function(){return(xc=a._dispose=a.asm.o).apply(null,arguments)},I0=a._Abs=function(){return(I0=a._Abs=a.asm.p).apply(null,arguments)},S0=a._Add=function(){return(S0=a._Add=a.asm.q).apply(null,arguments)},$p=a._AddN=function(){return($p=a._AddN=a.asm.r).apply(null,arguments)},Re=a._All=function(){return(Re=a._All=a.asm.s).apply(null,arguments)},C0=a._Any=function(){return(C0=a._Any=a.asm.t).apply(null,arguments)},T0=a._ArgMax=function(){return(T0=a._ArgMax=a.asm.u).apply(null,arguments)},N0=a._AvgPool=function(){return(N0=a._AvgPool=a.asm.v).apply(null,arguments)},E0=a._BatchMatMul=function(){return(E0=a._BatchMatMul=a.asm.w).apply(null,arguments)},R0=a._Ceil=function(){return(R0=a._Ceil=a.asm.x).apply(null,arguments)},Zo=a._ClipByValue=function(){return(Zo=a._ClipByValue=a.asm.y).apply(null,arguments)},$0=a._Conv2D=function(){return($0=a._Conv2D=a.asm.z).apply(null,arguments)},D0=a._Conv2DBackpropInput=function(){return(D0=a._Conv2DBackpropInput=a.asm.A).apply(null,arguments)},_0=a._Cos=function(){return(_0=a._Cos=a.asm.B).apply(null,arguments)},P0=a._Cosh=function(){return(P0=a._Cosh=a.asm.C).apply(null,arguments)},F0=a._CropAndResize=function(){return(F0=a._CropAndResize=a.asm.D).apply(null,arguments)},O0=a._Cumsum=function(){return(O0=a._Cumsum=a.asm.E).apply(null,arguments)},Dp=a._DepthToSpace=function(){return(Dp=a._DepthToSpace=a.asm.F).apply(null,arguments)},M0=a._DepthwiseConv2dNative=function(){return(M0=a._DepthwiseConv2dNative=a.asm.G).apply(null,arguments)},z0=a._Elu=function(){return(z0=a._Elu=a.asm.H).apply(null,arguments)},fa=a._Equal=function(){return(fa=a._Equal=a.asm.I).apply(null,arguments)},bc=a._Exp=function(){return(bc=a._Exp=a.asm.J).apply(null,arguments)},vc=a._FlipLeftRight=function(){return(vc=a._FlipLeftRight=a.asm.K).apply(null,arguments)},L0=a._Floor=function(){return(L0=a._Floor=a.asm.L).apply(null,arguments)},B0=a._FloorDiv=function(){return(B0=a._FloorDiv=a.asm.M).apply(null,arguments)},W0=a._FusedBatchNorm=function(){return(W0=a._FusedBatchNorm=a.asm.N).apply(null,arguments)},V0=a._FusedConv2D=function(){return(V0=a._FusedConv2D=a.asm.O).apply(null,arguments)},U0=a._FusedDepthwiseConv2D=function(){return(U0=a._FusedDepthwiseConv2D=a.asm.P).apply(null,arguments)},Ge=a._Gather=function(){return(Ge=a._Gather=a.asm.Q).apply(null,arguments)},G0=a._GatherNd=function(){return(G0=a._GatherNd=a.asm.R).apply(null,arguments)},H0=a._Greater=function(){return(H0=a._Greater=a.asm.S).apply(null,arguments)},j0=a._GreaterEqual=function(){return(j0=a._GreaterEqual=a.asm.T).apply(null,arguments)},q0=a._LeakyRelu=function(){return(q0=a._LeakyRelu=a.asm.U).apply(null,arguments)},X0=a._Less=function(){return(X0=a._Less=a.asm.V).apply(null,arguments)},K0=a._LessEqual=function(){return(K0=a._LessEqual=a.asm.W).apply(null,arguments)},wc=a._Log=function(){return(wc=a._Log=a.asm.X).apply(null,arguments)},_p=a._LogicalAnd=function(){return(_p=a._LogicalAnd=a.asm.Y).apply(null,arguments)},Pp=a._Max=function(){return(Pp=a._Max=a.asm.Z).apply(null,arguments)},Z0=a._MaxPool=function(){return(Z0=a._MaxPool=a.asm._).apply(null,arguments)},Y0=a._Maximum=function(){return(Y0=a._Maximum=a.asm.$).apply(null,arguments)},J0=a._Mean=function(){return(J0=a._Mean=a.asm.aa).apply(null,arguments)},Q0=a._Min=function(){return(Q0=a._Min=a.asm.ba).apply(null,arguments)},eg=a._Minimum=function(){return(eg=a._Minimum=a.asm.ca).apply(null,arguments)},tg=a._MirrorPad=function(){return(tg=a._MirrorPad=a.asm.da).apply(null,arguments)},ng=a._Multiply=function(){return(ng=a._Multiply=a.asm.ea).apply(null,arguments)},dt=a._Neg=function(){return(dt=a._Neg=a.asm.fa).apply(null,arguments)},sg=a._NonMaxSuppressionV3=function(){return(sg=a._NonMaxSuppressionV3=a.asm.ga).apply(null,arguments)},rg=a._NonMaxSuppressionV4=function(){return(rg=a._NonMaxSuppressionV4=a.asm.ha).apply(null,arguments)},ag=a._NonMaxSuppressionV5=function(){return(ag=a._NonMaxSuppressionV5=a.asm.ia).apply(null,arguments)},$l=a._NotEqual=function(){return($l=a._NotEqual=a.asm.ja).apply(null,arguments)},Fp=a._OneHot=function(){return(Fp=a._OneHot=a.asm.ka).apply(null,arguments)},Op=a._PadV2=function(){return(Op=a._PadV2=a.asm.la).apply(null,arguments)},Mp=a._Pow=function(){return(Mp=a._Pow=a.asm.ma).apply(null,arguments)},og=a._Prelu=function(){return(og=a._Prelu=a.asm.na).apply(null,arguments)},ig=a._Prod=function(){return(ig=a._Prod=a.asm.oa).apply(null,arguments)},zp=a._RealDiv=function(){return(zp=a._RealDiv=a.asm.pa).apply(null,arguments)},lg=a._Relu=function(){return(lg=a._Relu=a.asm.qa).apply(null,arguments)},ug=a._Relu6=function(){return(ug=a._Relu6=a.asm.ra).apply(null,arguments)},cg=a._ResizeBilinear=function(){return(cg=a._ResizeBilinear=a.asm.sa).apply(null,arguments)},dg=a._Reverse=function(){return(dg=a._Reverse=a.asm.ta).apply(null,arguments)},pg=a._RotateWithOffset=function(){return(pg=a._RotateWithOffset=a.asm.ua).apply(null,arguments)},Lp=a._Round=function(){return(Lp=a._Round=a.asm.va).apply(null,arguments)},ma=a._Rsqrt=function(){return(ma=a._Rsqrt=a.asm.wa).apply(null,arguments)},hg=a._ScatterNd=function(){return(hg=a._ScatterNd=a.asm.xa).apply(null,arguments)},fg=a._SelectV2=function(){return(fg=a._SelectV2=a.asm.ya).apply(null,arguments)},Bb=a._Sigmoid=function(){return(Bb=a._Sigmoid=a.asm.za).apply(null,arguments)},Bp=a._Sin=function(){return(Bp=a._Sin=a.asm.Aa).apply(null,arguments)},mg=a._Softmax=function(){return(mg=a._Softmax=a.asm.Ba).apply(null,arguments)},gg=a._Sqrt=function(){return(gg=a._Sqrt=a.asm.Ca).apply(null,arguments)},Ag=a._Square=function(){return(Ag=a._Square=a.asm.Da).apply(null,arguments)},yg=a._SquaredDifference=function(){return(yg=a._SquaredDifference=a.asm.Ea).apply(null,arguments)},xg=a._Step=function(){return(xg=a._Step=a.asm.Fa).apply(null,arguments)},bg=a._StridedSlice=function(){return(bg=a._StridedSlice=a.asm.Ga).apply(null,arguments)},vg=a._Sub=function(){return(vg=a._Sub=a.asm.Ha).apply(null,arguments)},wg=a._Sum=function(){return(wg=a._Sum=a.asm.Ia).apply(null,arguments)},kg=a._Tan=function(){return(kg=a._Tan=a.asm.Ja).apply(null,arguments)},Ig=a._Tanh=function(){return(Ig=a._Tanh=a.asm.Ka).apply(null,arguments)},Sg=a._Tile=function(){return(Sg=a._Tile=a.asm.La).apply(null,arguments)},Cg=a._TopK=function(){return(Cg=a._TopK=a.asm.Ma).apply(null,arguments)},Tg=a._Transform=function(){return(Tg=a._Transform=a.asm.Na).apply(null,arguments)},Ng=a._Transpose=function(){return(Ng=a._Transpose=a.asm.Oa).apply(null,arguments)},Eg=a.__FusedMatMul=function(){return(Eg=a.__FusedMatMul=a.asm.Pa).apply(null,arguments)},Rg=a._malloc=function(){return(Rg=a._malloc=a.asm.Qa).apply(null,arguments)},$g=a._free=function(){return($g=a._free=a.asm.Ra).apply(null,arguments)},Wp=a.stackSave=function(){return(Wp=a.stackSave=a.asm.Ta).apply(null,arguments)},Vp=a.stackRestore=function(){return(Vp=a.stackRestore=a.asm.Ua).apply(null,arguments)},kc=a.stackAlloc=function(){return(kc=a.stackAlloc=a.asm.Va).apply(null,arguments)};a.cwrap=ee;var Dl;function Dg(re){this.name="ExitStatus",this.message="Program terminated with exit("+re+")",this.status=re}wr=function re(){Dl||Ic(),Dl||(wr=re)};function Ic(re){if(re=re||u,Rn>0||(On(),Rn>0))return;function oe(){Dl||(Dl=!0,a.calledRun=!0,!M&&(ds(),Ls(),o(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),Is()))}a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),oe()},1)):oe()}if(a.run=Ic,a.preInit)for(typeof a.preInit=="function"&&(a.preInit=[a.preInit]);a.preInit.length>0;)a.preInit.pop()();return Ic(),r.ready}}();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModule=n)}}),VN=1e-7,UN=1e-4,Dc=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}},Ll=class{refCount(e){return Vs("refCount")}incRef(e){return Vs("incRef")}timerAvailable(){return!0}time(e){return Vs("time")}read(e){return Vs("read")}readSync(e){return Vs("readSync")}numDataIds(){return Vs("numDataIds")}disposeData(e,t){return Vs("disposeData")}write(e,t,n){return Vs("write")}move(e,t,n,s,r){return Vs("move")}memory(){return Vs("memory")}floatPrecision(){return Vs("floatPrecision")}epsilon(){return this.floatPrecision()===32?VN:UN}dispose(){return Vs("dispose")}};function Vs(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 n5(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,Zp(e,t,n)}function GN(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,s=0;for(;n>0;)s=Math.random()*n|0,n--,Zp(e,n,s),Zp(t,n,s)}function _c(e,t,n){return Math.max(e,Math.min(t,n))}function HN(e){return e%2==0?e:e+1}function Zp(e,t,n){let s=e[t];e[t]=e[n],e[n]=s}function jN(e){let t=0;for(let n=0;nn+` Shapes ${e} and ${t} must match`)}function ei(e){O(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function ti(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||Dn(e)&&!n)for(let s=0;s0,n){return new Promise((s,r)=>{let a=0,o=()=>{if(e()){s();return}a++;let i=t(a);if(n!=null&&a>=n){r();return}setTimeout(o,i)};o()})}function eE(e,t){let n=1,s=-1;for(let a=0;a=0)n*=e[a];else if(e[a]===-1){if(s!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${a}`);s=a}else if(e[a]<0)throw Error(`Shapes can not be < 0. Found ${e[a]} at dim ${a}`);if(s===-1){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(n===0)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);let r=e.slice();return r[s]=t/n,r}function Us(e,t){let n=t.length;return e=e==null?t.map((s,r)=>r):[].concat(e),O(e.every(s=>s>=-n&&s`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),O(e.every(s=>mn(s)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(s=>s<0?n+s:s)}function s5(e,t){let n=[],s=[],r=t!=null&&Array.isArray(t)&&t.length===0,a=t==null||r?null:Us(t,e).sort(),o=0;for(let i=0;ii)&&e[i]===1&&(n.push(e[i]),s.push(i)),a[o]<=i&&o++}e[i]!==1&&(n.push(e[i]),s.push(i))}return{newShape:n,keptDims:s}}function r5(e,t){let n=null;if(e==null||e==="float32")n=new Float32Array(t);else if(e==="int32")n=new Int32Array(t);else if(e==="bool")n=new Uint8Array(t);else throw new Error(`Unknown data type ${e}`);return n}function a5(e,t){let n=null;if(e==null||e==="float32")n=new Float32Array(t);else if(e==="int32")n=new Int32Array(t);else if(e==="bool")n=new Uint8Array(t);else if(e==="string")n=new Array(t);else throw new Error(`Unknown data type ${e}`);return n}function o5(e,t){for(let n=0;nt+=n.length),t}function ba(e){return typeof e=="string"||e instanceof String}function u5(e){return typeof e=="boolean"}function c5(e){return typeof e=="number"}function Yp(e){return Array.isArray(e)?Yp(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":c5(e)?"float32":ba(e)?"string":u5(e)?"bool":"float32"}function va(e){return!!(e&&e.constructor&&e.call&&e.apply)}function Jp(e,t){for(let n=t;n=0;--s)n[s]=n[s+1]*e[s+1];return n}function d5(e,t,n,s=!1){let r=new Array;if(t.length===1){let a=t[0]*(s?2:1);for(let o=0;ol*c)*(s?2:1);for(let l=0;lr*a)*(n?2:1);if(s===0)return[];if(s!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return d5(0,e,t,n)}function Lg(e,t){let n=Qp(e,t);for(let s=0;ss*r,1);if(t==null||t==="float32")return Wl(e,new Float32Array(n));if(t==="int32")return Wl(e,new Int32Array(n));if(t==="bool")return Wl(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function Bg(e){e.forEach(t=>{O(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function sE(e,t,n){if(t===0)return 0;if(t===1)return e[0];let s=e[e.length-1];for(let r=0;r{let[s,r]=n.split(":");this.urlFlags[s]=lE(s,r)})}};function oE(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...s)=>(iE(t,s[0],s[1]),s.join("="))),t}function iE(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function lE(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 K(){return Ir}var Ir=null;function uE(e){Ir=e}var Vg;function f5(){if(Vg==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");Vg=e}return Vg}function cE(){let e=f5();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function Ug(e,t){let n=cE();if(n.has(e))return n.get(e);{let s=t();return n.set(e,s),n.get(e)}}var ni="Abs",Vl="Acos",Ul="Acosh",Hr="Add",wa="AddN",Gl="All",Hl="Any",ka="ArgMax",jl="ArgMin",ql="Asin",Xl="Asinh",Kl="Atan",Zl="Atanh",Yl="Atan2",Ia="AvgPool",eh="AvgPoolGrad",Fc="AvgPool3D",th="AvgPool3DGrad",Sa="BatchMatMul",si="BatchToSpaceND",nh="Bincount",m5="BroadcastTo",sh="BroadcastArgs",Ca="Cast",Ta="Ceil",jr="ClipByValue",Oc="Complex",Mc="ComplexAbs",ri="Concat",Na="Conv2D",rh="Conv2DBackpropFilter",Ea="Conv2DBackpropInput",zc="Conv3D",ah="Conv3DBackpropFilterV2",oh="Conv3DBackpropInputV2",Ra="Cos",$a="Cosh",ai="Cumsum",oi="CropAndResize",ih="DenseBincount",ii="DepthToSpace",Da="DepthwiseConv2dNative",lh="DepthwiseConv2dNativeBackpropFilter",uh="DepthwiseConv2dNativeBackpropInput",ch="Diag",Lc="Dilation2D",dh="Dilation2DBackpropInput",ph="Dilation2DBackpropFilter",_a="RealDiv",Bc="Einsum",Pa="Elu",hh="EluGrad",Jl="Erf",li="Equal",Fa="Exp",ui="ExpandDims",ci="Expm1",fh="FFT",Ql="Fill",di="FlipLeftRight",Oa="Floor",Ma="FloorDiv",za="FusedBatchNorm",pi="GatherV2",hi="GatherNd",fi="Greater",La="GreaterEqual",Ba="Identity",mh="IFFT",Wc="Imag",eu="IsFinite",tu="IsInf",nu="IsNan",mi="LeakyRelu",gi="Less",Ai="LessEqual",gh="LinSpace",Wa="Log",su="Log1p",yi="LogicalAnd",ru="LogicalNot",Vc="LogicalOr",g5="LogSoftmax",Uc="LRN",Ah="LRNGrad",Va="Max",Ua="Maximum",Ga="MaxPool",yh="MaxPoolGrad",Gc="MaxPool3D",xh="MaxPool3DGrad",bh="MaxPoolWithArgmax",Ha="Mean",ja="Min",qa="Minimum",Xa="MirrorPad",au="Mod",vh="Multinomial",Ka="Multiply",xi="Neg",bi="NotEqual",vi="NonMaxSuppressionV3",ou="NonMaxSuppressionV4",wi="NonMaxSuppressionV5",ki="OnesLike",Ii="OneHot",Si="Pack",Za="PadV2",dE="Pool",Ya="Pow",Ja="Prelu",Ci="Prod",iu="Range",Hc="Real",lu="Reciprocal",Qa="Relu",Ti="Reshape",uu="ResizeNearestNeighbor",wh="ResizeNearestNeighborGrad",eo="ResizeBilinear",kh="ResizeBilinearGrad",to="Relu6",Ni="Reverse",Ei="Round",no="Rsqrt",Ri="ScatterNd",$i="Select",cu="Selu",Di="Slice",so="Sin",_i="Sinh",du="Sign",ro="Sigmoid",pu="Softplus",ao="Sqrt",oo="Sum",Pi="SpaceToBatchND",Fi="SplitV",io="Softmax",Ih="SparseFillEmptyRows",Sh="SparseReshape",Ch="SparseSegmentMean",Th="SparseSegmentSum",jc="SparseToDense",lo="SquaredDifference",hu="Square",Oi="StridedSlice",qc="StringNGrams",Nh="StringSplit",Eh="StringToHashBucketFast",uo="Sub",Mi="Tan",co="Tanh",qr="Tile",zi="TopK",Li="Transform",po="Transpose",Rh="Unique",Bi="Unpack",Xc="UnsortedSegmentSum",Wi="ZerosLike",ho="Step",Kc="FromPixels",Vi="RotateWithOffset",fo="_FusedMatMul",mo="FusedConv2D",go="FusedDepthwiseConv2D",fu=Ug("kernelRegistry",()=>new Map),Zc=Ug("gradRegistry",()=>new Map);function $h(e,t){let n=Hg(e,t);return fu.get(n)}function Gg(e){return Zc.get(e)}function Xr(e){let t=fu.entries(),n=[];for(;;){let{done:s,value:r}=t.next();if(s)break;let[a,o]=r,[i]=a.split("_");i===e&&n.push(o)}return n}function Kr(e){let{kernelName:t,backendName:n}=e,s=Hg(t,n);fu.has(s)&&kr(`The kernel '${t}' for backend '${n}' is already registered`),fu.set(s,e)}function A5(e){let{kernelName:t}=e;Zc.has(t)&&K().getBool("DEBUG")&&kr(`Overriding the gradient for '${t}'`),Zc.set(t,e)}function pE(e,t){let n=Hg(e,t);if(!fu.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);fu.delete(n)}function hE(e){if(!Zc.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Zc.delete(e)}function fE(e,t){Xr(e).forEach(s=>{let r=Object.assign({},s,{backendName:t});Kr(r)})}function Hg(e,t){return`${t}_${e}`}var v={};ze(v,{arraysEqual:()=>Gr,assert:()=>O,assertNonNegativeIntegerDimensions:()=>Bg,assertNonNull:()=>ei,assertShapesMatch:()=>zn,bytesFromStringArray:()=>l5,bytesPerElement:()=>zg,checkConversionForErrors:()=>o5,clamp:()=>_c,computeStrides:()=>Bl,createScalarValue:()=>bE,createShuffledIndices:()=>JN,decodeString:()=>Ph,distSquared:()=>XN,encodeString:()=>Qc,fetch:()=>wE,fingerPrint64:()=>xE,flatten:()=>ti,getArrayFromDType:()=>a5,getTypedArrayFromDType:()=>r5,hasEncodingLoss:()=>tE,hexToLong:()=>Yc,indexToLoc:()=>rE,inferDtype:()=>Yp,inferFromImplicitShape:()=>eE,isBoolean:()=>u5,isFunction:()=>va,isInt:()=>mn,isNumber:()=>c5,isPromise:()=>Wg,isScalarShape:()=>KN,isString:()=>ba,isTypedArray:()=>Dn,isValidDtype:()=>i5,locToIndex:()=>sE,makeOnesTypedArray:()=>Lg,makeZerosNestedTypedArray:()=>nE,makeZerosTypedArray:()=>Qp,nearestDivisor:()=>Jp,nearestLargerEven:()=>HN,now:()=>Jc,parseAxisParam:()=>Us,randUniform:()=>qN,repeatedTry:()=>QN,rightPad:()=>Pc,shuffle:()=>n5,shuffleCombo:()=>GN,sizeFromShape:()=>Ut,sizeToSquarishShape:()=>YN,squeezeShape:()=>s5,sum:()=>jN,swap:()=>Zp,tanh:()=>ZN,toNestedArray:()=>Wl,toTypedArray:()=>_h});var y5=Qo(EN()),Ui=y5.default||y5;function Yc(e){return Ui.fromString(e,!0,16)}var x5=Yc("c3a5c85c97cb3127"),Gi=Yc("b492b66fbe98f273"),Ln=Yc("9ae16a3b2f90404f");function jg(e){return e.xor(e.shru(47))}function b5(e,t,n){let s=e.slice(t,t+n);return Ui.fromBytes(Array.from(s),!0,!0)}function kt(e,t){return b5(e,t,8)}function v5(e,t){return b5(e,t,4)}function gn(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function Ao(e,t,n=Yc("9ddfea08eb382d69")){let s=e.xor(t).mul(n);s=s.xor(s.shru(47));let r=t.xor(s).mul(n);return r=r.xor(r.shru(47)),r=r.mul(n),r}function mE(e,t,n,s,r,a){r=r.add(e),a=gn(a.add(r).add(s),21);let o=r;return r=r.add(t),r=r.add(n),a=a.add(gn(r,44)),[r.add(s),a.add(o)]}function Dh(e,t,n,s){return mE(kt(e,t),kt(e,t+8),kt(e,t+16),kt(e,t+24),n,s)}function gE(e,t=e.length){if(t>=8){let n=Ln.add(t*2),s=kt(e,0).add(Ln),r=kt(e,t-8),a=gn(r,37).mul(n).add(s),o=gn(s,25).add(r).mul(n);return Ao(a,o,n)}if(t>=4){let n=Ln.add(t*2),s=v5(e,0);return Ao(s.shl(3).add(t),v5(e,t-4),n)}if(t>0){let n=e[0],s=e[t>>1],r=e[t-1],a=n+(s<<8),o=t+(r<<2);return jg(Ln.mul(a).xor(x5.mul(o))).mul(Ln)}return Ln}function AE(e,t=e.length){let n=Ln.add(t*2),s=kt(e,0).mul(Gi),r=kt(e,8),a=kt(e,t-8).mul(n),o=kt(e,t-16).mul(Ln);return Ao(gn(s.add(r),43).add(gn(a,30)).add(o),s.add(gn(r.add(Ln),18)).add(a),n)}function yE(e,t=e.length){let n=Ln.add(t*2),s=kt(e,0).mul(Ln),r=kt(e,8),a=kt(e,t-8).mul(n),o=kt(e,t-16).mul(Ln),i=gn(s.add(r),43).add(gn(a,30)).add(o),l=Ao(i,s.add(gn(r.add(Ln),18)).add(a),n),c=kt(e,16).mul(n),u=kt(e,24),d=i.add(kt(e,t-32)).mul(n),p=l.add(kt(e,t-24)).mul(n);return Ao(gn(c.add(u),43).add(gn(d,30)).add(p),c.add(gn(u.add(s),18)).add(d),n)}function xE(e,t=e.length){let n=Ui.fromNumber(81,!0);if(t<=32)return t<=16?gE(e,t):AE(e,t);if(t<=64)return yE(e,t);let s=n,r=n.mul(Gi).add(113),a=jg(r.mul(Ln).add(113)).mul(Ln),o=[Ui.UZERO,Ui.UZERO],i=[Ui.UZERO,Ui.UZERO];s=s.mul(Ln).add(kt(e,0));let l=0,c=(t-1>>6)*64,u=c+(t-1&63)-63;do s=gn(s.add(r).add(o[0]).add(kt(e,l+8)),37).mul(Gi),r=gn(r.add(o[1]).add(kt(e,l+48)),42).mul(Gi),s=s.xor(i[1]),r=r.add(o[0]).add(kt(e,l+40)),a=gn(a.add(i[0]),33).mul(Gi),o=Dh(e,l,o[1].mul(Gi),s.add(i[0])),i=Dh(e,l+32,a.add(i[1]),r.add(kt(e,l+16))),[a,s]=[s,a],l+=64;while(l!==c);let d=Gi.add(a.and(255).shl(1));return l=u,i[0]=i[0].add(t-1&63),o[0]=o[0].add(i[0]),i[0]=i[0].add(o[0]),s=gn(s.add(r).add(o[0]).add(kt(e,l+8)),37).mul(d),r=gn(r.add(o[1]).add(kt(e,l+48)),42).mul(d),s=s.xor(i[1].mul(9)),r=r.add(o[0].mul(9).add(kt(e,l+40))),a=gn(a.add(i[0]),33).mul(d),o=Dh(e,l,o[1].mul(d),s.add(i[0])),i=Dh(e,l+32,a.add(i[1]),r.add(kt(e,l+16))),[a,s]=[s,a],Ao(Ao(o[0],i[0],d).add(jg(r).mul(x5)).add(a),Ao(o[1],i[1],d).add(s),d)}function bE(e,t){return t==="string"?Qc(e):_h([e],t)}function vE(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function _h(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=ti(e)),K().getBool("DEBUG")&&o5(e,t),vE(e,t))return e;if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"){let n=new Uint8Array(e.length);for(let s=0;s{s=n()},a,o=Jc();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(r);else{r();for(let l of s)l.dataSync();a=Promise.resolve({kernelMs:Jc()-o})}if(K().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let l=0;l{IE(u,c.dtype,e)})}return{kernelName:e,outputs:s,inputs:t,timeMs:a.then(l=>l.kernelMs),extraInfo:a.then(l=>l.getExtraProfileInfo!=null?l.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:s,inputs:r,extraInfo:a}=e;n.forEach(o=>{Promise.all([o.data(),s,a]).then(i=>{this.logger.logKernelProfile(t,o,i[0],i[1],r,i[2])})})}};function IE(e,t,n){if(t!=="float32")return!1;for(let s=0;s0?f:""} `}}console.log(`%c${i} %c${o} %c${l}D ${u} %c${c} %c${d} %c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function CE(e,t,n){let s={},r={};for(let l=0;ls[m.id]=!0),h=!0,r[c.id]=!0;break}if(h)break}}let a={};a[n.id]=!0;let o={};for(let l=e.length-1;l>=0;l--){let c=e[l],u=c.inputs;for(let d=0;d=0;r--){let a=t[r],o=[];if(a.outputs.forEach(l=>{let c=e[l.id];c!=null?o.push(c):o.push(null)}),a.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);let i=a.gradient(o);for(let l in a.inputs){if(!(l in i))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(i)}.`);let c=n(()=>i[l]());if(c.dtype!=="float32")throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${c.dtype}'`);let u=a.inputs[l];if(!Gr(c.shape,u.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${l}' has shape '${c.shape}', which does not match the shape of the input '${u.shape}'`);if(e[u.id]==null)e[u.id]=c;else{let d=e[u.id];e[u.id]=s(d,c),d.dispose()}}}}var w5=20,ed=3,qg=7;function NE(e,t,n,s){let r=Bl(t),a=EE(e,t,n,r),o=t.length,i=Fh(e,t,n,r,a),l=["Tensor"];return s&&(l.push(` dtype: ${n}`),l.push(` rank: ${o}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(i.map(c=>" "+c).join(`
`)),l.join(`
`)}function EE(e,t,n,s){let r=Ut(t),a=s[s.length-1],o=new Array(a).fill(0),i=t.length,l=n==="complex64"?nd(e):e;if(i>1)for(let c=0;cw5){let g=ed*o,A=Array.from(e.slice(0,g)),y=Array.from(e.slice((i-ed)*o,i*o));return n==="complex64"&&(A=nd(A),y=nd(y)),["["+A.map((x,b)=>td(x,r[b],n)).join(", ")+", ..., "+y.map((x,b)=>td(x,r[i-ed+b],n)).join(", ")+"]"]}let m=n==="complex64"?nd(e):Array.from(e);return["["+m.map((g,A)=>td(g,r[A],n)).join(", ")+"]"]}let c=t.slice(1),u=s.slice(1),d=s[0]*o,p=[];if(i>w5){for(let m=0;m`Length of values '${s}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||a5(t,this.size),this.strides=Bl(e)}set(e,...t){t.length===0&&(t=[0]),O(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let s of e){if(s<0||s>=this.shape[t]){let r=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(r)}t++}let n=e[e.length-1];for(let s=0;sPh(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();let e=Sr().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Ph(t))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();let e=await Sr().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Sr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return mu.print(this,e)}clone(){return this.throwIfDisposed(),mu.clone(this)}toString(e=!1){let t=this.dataSync();return NE(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),mu.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Sr().makeVariable(this,e,t,n)}};Object.defineProperty(Ye,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function PE(){return Ug("Tensor",()=>Ye)}PE();var sd=class extends Ye{constructor(e,t,n,s){super(e.shape,e.dtype,e.dataId,s);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!Gr(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Sr().disposeTensor(this),this.dataId=e.dataId,Sr().incRef(this,null)}dispose(){Sr().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(sd,Symbol.hasInstance,{value:e=>e instanceof Ye&&e.assign!=null&&e.assign instanceof Function});var rr={};ze(rr,{assertTypesMatch:()=>I5,getTensorsInContainer:()=>Qg,isTensorInList:()=>OE,makeTypesMatch:()=>Ft});var Xg;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(Xg||(Xg={}));var Kg;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(Kg||(Kg={}));var Zg;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(Zg||(Zg={}));var Yg;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(Yg||(Yg={}));var Jg;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(Jg||(Jg={}));var FE={float32:Yg,int32:Kg,bool:Zg,complex64:Jg};function Bn(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return FE[e][t]}function rd(e){return Bn(e,"int32")}function Ft(e,t){if(e.dtype===t.dtype)return[e,t];let n=Bn(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function I5(e,t){O(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function OE(e,t){return t.some(n=>n.id===e.id)}function Qg(e){let t=[],n=new Set;return S5(e,t,n),t}function S5(e,t,n){if(e==null)return;if(e instanceof Ye){t.push(e);return}if(!ME(e))return;let s=e;for(let r in s){let a=s[r];n.has(a)||(n.add(a),S5(a,t,n))}}function ME(e){return Array.isArray(e)||typeof e=="object"}function e2(e){return e.kernelName!=null}var C5=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()}},t2=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new C5}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let e=this.getSortedBackends();for(let t=0;t{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Xr(e).forEach(n=>{n.disposeFunc!=null&&n.disposeFunc(this.registry[e])})}initializeBackend(e){let t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{let n=t.factory();if(n&&!(n instanceof Ll)&&typeof n.then=="function"){let s=++this.pendingBackendInitId,r=n.then(a=>s(sthis.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;tthis.startScope(n),()=>this.endScope(s),()=>(s=t(),s instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),s))}scopedRun(e,t,n){e();try{let s=n();return t(),s}catch(s){throw t(),s}}nextTensorId(){return t2.nextTensorId++}nextVariableId(){return t2.nextVariableId++}clone(e){let t=B.runKernel(Ba,{x:e}),n={x:e},s=a=>({x:()=>{let o="float32",i={x:a},l={dtype:o};return B.runKernel(Ca,i,l)}}),r=[];return this.addTapeNode(this.state.activeScope.name,n,[t],s,r,{}),t}runKernel(e,t,n){if(this.backendName==null&&this.backend,!($h(e,this.backendName)!=null))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){let s=this.backend.numDataIds(),r=0;n.forEach(i=>{r+=i.dtype==="complex64"?3:1});let a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=s-t-r-a;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[],s=this.isTapeOn(),r=this.state.numBytes,a=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let o;this.backendName==null&&this.backend;let i,l=e2(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(e2(e)){let{kernelName:h,inputs:f,attrs:m}=e;this.backendName==null&&this.backend;let g=$h(h,this.backendName);O(g!=null,()=>`Cannot find registered kernel '${h}' for backend '${this.backendName}'`),o=()=>{let A=this.backend.numDataIds();i=g.kernelFunc({inputs:f,attrs:m,backend:this.backend});let y=Array.isArray(i)?i:[i];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(h,A,y);let x=y.map(b=>{if(b.rank!=null)return b;let{dataId:w,shape:k,dtype:S}=b;return this.makeTensorFromDataId(w,k,S)});if(s){let b=this.getTensorsForGradient(h,f,x);n=this.saveTensorsForBackwardMode(b)}return x}}else{let{forwardFunc:h}=e,f=m=>{!s||(n=m.map(g=>this.keep(this.clone(g))))};o=()=>{let m=this.backend.numDataIds();i=this.tidy(()=>h(this.backend,f));let g=Array.isArray(i)?i:[i];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,m,g),g}}let{inputs:c,attrs:u}=e,d=e2(e)?null:e.backwardsFunc,p;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=o():(p=this.profiler.profileKernel(l,c,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs)}),s&&this.addTapeNode(l,c,t,d,n,u),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map(h=>c[h]!=null?c[h].shape:null),outputShapes:t.map(h=>h.shape),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(i)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(n=>this.keep(this.clone(n)))}getTensorsForGradient(e,t,n){let s=Gg(e);if(s!=null){let r=s.inputsToSave||[],a=s.outputsToSave||[],o;s.saveAllInputs?(O(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),o=Object.keys(t).map(l=>t[l])):o=r.map(l=>t[l]);let i=n.filter((l,c)=>a[c]);return o.concat(i)}return[]}makeTensor(e,t,n,s){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",s=s||this.backend;let r=e;n==="string"&&ba(e[0])&&(r=e.map(i=>Qc(i)));let a=s.write(r,t,n),o=new Ye(t,n,a,this.nextTensorId());if(this.trackTensor(o,s),n==="string"){let i=this.state.tensorInfo.get(a),l=l5(r);this.state.numBytes+=l-i.bytes,i.bytes=l}return o}makeTensorFromDataId(e,t,n,s){n=n||"float32";let r=new Ye(t,n,e,this.nextTensorId());return this.trackTensor(r,s),r}makeVariable(e,t=!0,n,s){n=n||this.nextVariableId().toString(),s!=null&&s!==e.dtype&&(e=e.cast(s));let r=new sd(e,t,n,this.nextTensorId());if(this.state.registeredVariables[r.name]!=null)throw new Error(`Variable with name ${r.name} was already registered`);return this.state.registeredVariables[r.name]=r,this.incRef(r,this.backend),r}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let n=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(n=e.size*zg(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof sd||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;let t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,e.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),e.dtype!=="complex64"&&e.dtype!=="string"){let n=e.size*zg(e.dtype);this.state.numBytes-=n}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(let e in this.state.registeredVariables){let t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]}memory(){let e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,e.reasons==null&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;let t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(s=>s.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(let s of this.state.activeProfile.kernels)s.kernelTimeMs=await s.kernelTimeMs,s.extraInfo=await s.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,s,r,a){let o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:r},i=Gg(e);i!=null&&(s=i.gradFunc),s!=null&&(o.gradient=l=>(l=l.map((c,u)=>{if(c==null){let d=n[u],p=Qp(d.size,d.dtype);return this.makeTensor(p,d.shape,d.dtype)}return c}),s(l.length>1?l:l[0],r,a))),this.state.activeTape.push(o)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=Qg(e),n=new Set(t.map(r=>r.id));for(let r=0;r{!r.kept&&r.scopeId===s.id&&this.track(r)})}gradients(e,t,n,s=!1){if(O(t.length>0,()=>"gradients() received an empty list of xs."),n!=null&&n.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);let r=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));O(r instanceof Ye,()=>"The result y returned by f() must be a tensor.");let a=CE(this.state.activeTape,t,r);if(!s&&a.length===0&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{let o={};o[r.id]=n==null?zE(r.shape):n,TE(o,a,l=>this.tidy(l),LE);let i=t.map(l=>o[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let c of l.saved)c.dispose()}),this.state.activeTape=null),{value:r,grads:i}})}customGrad(e){return O(va(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{O(t.every(o=>o instanceof Ye),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,s={};t.forEach((o,i)=>{s[i]=o});let r=(o,i)=>(n=e(...t,i),O(n.value instanceof Ye,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),O(va(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),a=(o,i)=>{let l=n.gradFunc(o,i),c=Array.isArray(l)?l:[l];O(c.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),O(c.every(d=>d instanceof Ye),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let u={};return c.forEach((d,p)=>{u[p]=()=>d}),u};return this.runKernelFunc({forwardFunc:r,backwardsFunc:a,inputs:s})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}async time(e){let t=Jc(),n=await this.backend.time(e);return n.wallMs=Jc()-t,n}track(e){return this.state.activeScope!=null&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new C5;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}},n2=t2;n2.nextTensorId=0;n2.nextVariableId=0;function zE(e){let t=Lg(Ut(e),"float32");return B.makeTensor(t,e,"float32")}function T5(){let e=f5();if(e._tfengine==null){let t=new h5(e);e._tfengine=new n2(t)}return uE(e._tfengine.ENV),$E(()=>e._tfengine),e._tfengine}var B=T5();function LE(e,t){let n={a:e,b:t};return B.runKernel(Hr,n)}var gu={};ze(gu,{isBrowser:()=>N5,isMobile:()=>VE,mockIsMobile:()=>WE});function BE(){return typeof navigator!="undefined"&&navigator!=null}var s2;function WE(e){s2=e}function VE(e){if(s2!==void 0)return s2;if(e||BE()){if(e||(e=navigator),e.product==="ReactNative")return!0;let t=e.userAgent||e.vendor||(typeof window!="undefined"?window.opera:"");if(!t){let n=e;return n.userAgentData&&n.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}return!1}function N5(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var ar=K();ar.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.")});ar.registerFlag("IS_BROWSER",()=>N5());ar.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");ar.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));ar.registerFlag("PROD",()=>!1);ar.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>ar.getBool("DEBUG"));ar.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);ar.registerFlag("IS_TEST",()=>!1);ar.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);ar.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function Cr(e,t){let n=e;if(Dn(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let s=[];for(;Array.isArray(n)||Dn(n)&&t!=="string";)s.push(n.length),n=n[0];return Array.isArray(e)&&K().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&E5(e,s,[]),s}function E5(e,t,n){if(n=n||[],!Array.isArray(e)&&!Dn(e)){O(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}O(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),O(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let s=t.slice(1);for(let r=0;r=0&&(r=s),R5(s,r,t,n),e==null||!Dn(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){let l=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${l}'`)}let a=Cr(e,r);!Dn(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?_h(e,r):ti(e,[],!0);return B.makeTensor(i,a,r)}function ad(e,t,n,s="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((a,o)=>D(a,`${t}[${o}]`,n,s))}var $5="__op";function V(e){let t=Object.keys(e);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0],s=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+$5;let r=(...a)=>{B.startScope(n);try{let o=s(...a);return Wg(o)&&console.error("Cannot return a Promise inside of tidy."),B.endScope(o),o}catch(o){throw B.endScope(null),o}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}function UE(e,t){let n=D(e,"real","complex"),s=D(t,"imag","complex");zn(n.shape,s.shape,`real and imag shapes, ${n.shape} and ${s.shape}, must match in call to tf.complex().`);let r={real:n,imag:s};return B.runKernel(Oc,r)}var yo=V({complex_:UE});function xo(e,t,n,s){if(s==null&&(s=Yp(e)),s==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Dn(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){Bg(t);let r=Ut(t),a=Ut(n);O(r===a,()=>`Based on the provided shape, [${t}], the tensor should have ${r} values but has ${a}`);for(let o=0;o`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!Dn(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=s!=="string"?_h(e,s):ti(e,[],!0),B.makeTensor(e,t,s)}function Gt(e,t,n){let s=Cr(e,n);return xo(e,t,s,n)}var r2={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},Oh=4;async function GE(e,t){let n=[],s=[],r=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);for(let o=0;o{let p=await l.bytes(),h=p.reduce((g,A)=>g+A.length,0)+Oh*p.length,f=new Uint8Array(h),m=0;for(let g=0;g{if(t+=a.byteLength,n.push(a.byteLength===a.buffer.byteLength?a:new a.constructor(a)),!(a instanceof Float32Array||a instanceof Int32Array||a instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${a.constructor.name}`)});let s=new Uint8Array(t),r=0;return n.forEach(a=>{s.set(new Uint8Array(a.buffer),r),r+=a.byteLength}),s.buffer}var a2=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function _5(e){return a2?Buffer.byteLength(e):new Blob([e]).size}function jE(e){if(a2)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),n="";for(let s=0,r=t.length;s{t+=r.byteLength});let n=new Uint8Array(t),s=0;return e.forEach(r=>{n.set(new Uint8Array(r),s),s+=r.byteLength}),n.buffer}function P5(e){let t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);let n=e.split(t);return n[n.length-1]}function F5(e,t){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),n}async function i2(e,t){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),e.weightsManifest!=null){let[s,r]=await t(e.weightsManifest);n.weightSpecs=s,n.weightData=r}return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),n}function od(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:_5(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:_5(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function XE(){let e=n=>{let s=n<<13,r=0;for(;(s&8388608)==0;)r-=8388608,s<<=1;return s&=~8388608,r+=947912704,s|r},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let n=1024;n<2048;n++)t[n]=939524096+(n-1024<<13);return t}function KE(){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 ZE(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function YE(){let e=XE(),t=KE(),n=ZE();return s=>{let r=new ArrayBuffer(4*s.length),a=new Uint32Array(r);for(let o=0;o>10]+(i&1023)]+t[i>>10];a[o]=l}return new Float32Array(r)}}var Bt=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Bt.instance==null&&(Bt.instance=new Bt),Bt.instance}static registerSaveRouter(e){Bt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Bt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Bt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Bt.getHandlers(e,"load",t)}static getHandlers(e,t,n){let s=[];return(t==="load"?Bt.getInstance().loadRouters:Bt.getInstance().saveRouters).forEach(a=>{let o=a(e,n);o!==null&&s.push(o)}),s}},JE=e=>Bt.registerSaveRouter(e),QE=e=>Bt.registerLoadRouter(e),e9=e=>Bt.getSaveHandlers(e),t9=(e,t)=>Bt.getLoadHandlers(e,t),l2="tensorflowjs",u2=1,Hi="models_store",bo="model_info_store";function O5(){if(!K().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 c2(e){let t=e.result;t.createObjectStore(Hi,{keyPath:"modelPath"}),t.createObjectStore(bo,{keyPath:"modelPath"})}var ji=class{constructor(e){if(this.indexedDB=O5(),e==null||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((n,s)=>{let r=this.indexedDB.open(l2,u2);r.onupgradeneeded=()=>c2(r),r.onsuccess=()=>{let a=r.result;if(t==null){let o=a.transaction(Hi,"readonly"),l=o.objectStore(Hi).get(this.modelPath);l.onsuccess=()=>{if(l.result==null)return a.close(),s(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(l.result.modelArtifacts)},l.onerror=c=>(a.close(),s(l.error)),o.oncomplete=()=>a.close()}else{let o=od(t),i=a.transaction(bo,"readwrite"),l=i.objectStore(bo),c=l.put({modelPath:this.modelPath,modelArtifactsInfo:o}),u;c.onsuccess=()=>{u=a.transaction(Hi,"readwrite");let p=u.objectStore(Hi).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:o});p.onsuccess=()=>n({modelArtifactsInfo:o}),p.onerror=h=>{l=i.objectStore(bo);let f=l.delete(this.modelPath);f.onsuccess=()=>(a.close(),s(p.error)),f.onerror=m=>(a.close(),s(p.error))}},c.onerror=d=>(a.close(),s(c.error)),i.oncomplete=()=>{u==null?a.close():u.oncomplete=()=>a.close()}}},r.onerror=a=>s(r.error)})}};ji.URL_SCHEME="indexeddb://";var M5=e=>K().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ji.URL_SCHEME)?n9(e.slice(ji.URL_SCHEME.length)):null;Bt.registerSaveRouter(M5);Bt.registerLoadRouter(M5);function n9(e){return new ji(e)}function s9(e){return e.startsWith(ji.URL_SCHEME)?e.slice(ji.URL_SCHEME.length):e}var r9=class{constructor(){this.indexedDB=O5()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(l2,u2);n.onupgradeneeded=()=>c2(n),n.onsuccess=()=>{let s=n.result,r=s.transaction(bo,"readonly"),o=r.objectStore(bo).getAll();o.onsuccess=()=>{let i={};for(let l of o.result)i[l.modelPath]=l.modelArtifactsInfo;e(i)},o.onerror=i=>(s.close(),t(o.error)),r.oncomplete=()=>s.close()},n.onerror=s=>t(n.error)})}async removeModel(e){return e=s9(e),new Promise((t,n)=>{let s=this.indexedDB.open(l2,u2);s.onupgradeneeded=()=>c2(s),s.onsuccess=()=>{let r=s.result,a=r.transaction(bo,"readwrite"),o=a.objectStore(bo),i=o.get(e),l;i.onsuccess=()=>{if(i.result==null)return r.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let c=o.delete(e),u=()=>{l=r.transaction(Hi,"readwrite");let p=l.objectStore(Hi).delete(e);p.onsuccess=()=>t(i.result.modelArtifactsInfo),p.onerror=h=>n(i.error)};c.onsuccess=u,c.onerror=d=>(u(),r.close(),n(i.error))}},i.onerror=c=>(r.close(),n(i.error)),a.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},s.onerror=r=>n(s.error)})}},Zr="/",Au="tensorflowjs_models",z5="info",a9="model_topology",o9="weight_specs",i9="weight_data",l9="model_metadata";function L5(e){return{info:[Au,e,z5].join(Zr),topology:[Au,e,a9].join(Zr),weightSpecs:[Au,e,o9].join(Zr),weightData:[Au,e,i9].join(Zr),modelMetadata:[Au,e,l9].join(Zr)}}function B5(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function u9(e){let t=e.split(Zr);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Zr)}function c9(e){return e.startsWith(qi.URL_SCHEME)?e.slice(qi.URL_SCHEME.length):e}var qi=class{constructor(e){if(!K().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=L5(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{let t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),s=od(e);try{this.LS.setItem(this.keys.info,JSON.stringify(s)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,jE(e.weightData));let r={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:e.signature!=null?e.signature:void 0,userDefinedMetadata:e.userDefinedMetadata!=null?e.userDefinedMetadata:void 0,modelInitializer:e.modelInitializer!=null?e.modelInitializer:void 0,trainingConfig:e.trainingConfig!=null?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(r)),{modelArtifactsInfo:s}}catch(r){throw B5(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${s.modelTopologyBytes}, weightSpecsBytes=${s.weightSpecsBytes}, weightDataBytes=${s.weightDataBytes}.`)}}}async load(){let e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");let t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(n==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;let s=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(s==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=s;let r=this.LS.getItem(this.keys.modelMetadata);if(r!=null){let o=JSON.parse(r);t.format=o.format,t.generatedBy=o.generatedBy,t.convertedBy=o.convertedBy,o.signature!=null&&(t.signature=o.signature),o.userDefinedMetadata!=null&&(t.userDefinedMetadata=o.userDefinedMetadata),o.modelInitializer!=null&&(t.modelInitializer=o.modelInitializer),o.trainingConfig!=null&&(t.trainingConfig=o.trainingConfig)}let a=this.LS.getItem(this.keys.weightData);if(a==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=qE(a),t}};qi.URL_SCHEME="localstorage://";var W5=e=>K().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(qi.URL_SCHEME)?d9(e.slice(qi.URL_SCHEME.length)):null;Bt.registerSaveRouter(W5);Bt.registerLoadRouter(W5);function d9(e){return new qi(e)}var p9=class{constructor(){O(K().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),O(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Au+Zr,n=Zr+z5;for(let s=0;s"scheme must not be undefined or null."),e.endsWith(yu)&&(e=e.slice(0,e.indexOf(yu))),O(e.length>0,()=>"scheme must not be an empty string.");let n=Ss.getInstance();O(n.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){let t=this.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(this.getInstance().managers)}};function Mh(e){if(e.indexOf(yu)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Ss.getSchemes().join(",")}`);return{scheme:e.split(yu)[0],path:e.split(yu)[1]}}async function V5(e,t,n=!1){O(e!==t,()=>`Old path and new path are the same: '${e}'`);let s=Bt.getLoadHandlers(e);O(s.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),O(s.length<2,()=>`Copying failed because more than one (${s.length}) load handlers for source URL ${e}.`);let r=s[0],a=Bt.getSaveHandlers(t);O(a.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),O(a.length<2,()=>`Copying failed because more than one (${s.length}) save handlers for destination URL ${t}.`);let o=a[0],i=Mh(e).scheme,l=Mh(e).path,c=i===Mh(e).scheme,u=await r.load();n&&c&&await Ss.getManager(i).removeModel(l);let d=await o.save(u);return n&&!c&&await Ss.getManager(i).removeModel(l),d.modelArtifactsInfo}async function h9(){let e=Ss.getSchemes(),t={};for(let n of e){let s=await Ss.getManager(n).listModels();for(let r in s){let a=n+yu+r;t[a]=s[r]}}return t}async function f9(e){let t=Mh(e);return Ss.getManager(t.scheme).removeModel(t.path)}async function m9(e,t){return V5(e,t,!1)}async function g9(e,t){return V5(e,t,!0)}var A9=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(K().get("IS_BROWSER")){K().setPlatform("browser",new A9);try{Ss.registerManager(qi.URL_SCHEME,new p9)}catch(e){}try{Ss.registerManager(ji.URL_SCHEME,new r9)}catch(e){}}var y9={importFetch:()=>RN()},d2,x9=class{constructor(){this.util=$N(),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return K().global.fetch!=null?K().global.fetch(e,t):(d2==null&&(d2=y9.importFetch()),d2(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)}};K().get("IS_NODE")&&K().setPlatform("node",new x9);function Le(e,t="float32",n){return t=t||"float32",Bg(e),new sn(e,t,n)}function b9(e,t){let n=D(e,"x","cast");if(!i5(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&n.dtype!=="string"||t!=="string"&&n.dtype==="string")throw new Error("Only strings can be casted to strings");let s={x:n},r={dtype:t};return B.runKernel(Ca,s,r)}var de=V({cast_:b9});function v9(e){let n={x:D(e,"x","clone","string_or_numeric")};return B.runKernel(Ba,n)}var or=V({clone_:v9});function U5(e,t=!1){console.log(e.toString(t))}T5();var w9={buffer:Le,cast:de,clone:or,print:U5};DE(w9);var ns={};ze(ns,{browserFiles:()=>E9,browserHTTPRequest:()=>P9,concatenateArrayBuffers:()=>o2,copyModel:()=>m9,decodeWeights:()=>D5,encodeWeights:()=>GE,fromMemory:()=>O9,getLoadHandlers:()=>t9,getModelArtifactsForJSON:()=>i2,getModelArtifactsInfoForJSON:()=>od,getSaveHandlers:()=>e9,http:()=>m2,isHTTPScheme:()=>f2,listModels:()=>h9,loadWeights:()=>R9,moveModel:()=>g9,registerLoadRouter:()=>QE,registerSaveRouter:()=>JE,removeModel:()=>f9,weightsLoaderFactory:()=>q5,withSaveHandler:()=>M9});var k9="model",I9=".json",S9=".weights.bin";function G5(e){return new Promise(t=>setTimeout(t)).then(e)}var p2=class{constructor(e){if(!K().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(p2.URL_SCHEME)&&(e=e.slice(p2.URL_SCHEME.length)),(e==null||e.length===0)&&(e=k9),this.modelJsonFileName=e+I9,this.weightDataFileName=e+S9}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");let t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{let n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],s=F5(e,n),r=window.URL.createObjectURL(new Blob([JSON.stringify(s)],{type:"application/json"})),a=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(a.download=this.modelJsonFileName,a.href=r,await G5(()=>a.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let o=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;o.download=this.weightDataFileName,o.href=t,await G5(()=>o.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:od(e)}}}},zh=p2;zh.URL_SCHEME="downloads://";var C9=class{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise((e,t)=>{let n=new FileReader;n.onload=s=>{let r=JSON.parse(s.target.result),a=r.modelTopology;if(a==null){t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));return}if(r.weightsManifest==null){t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));return}if(this.weightsFiles.length===0){e({modelTopology:a});return}let i=i2(r,l=>this.loadWeights(l));e(i)},n.onerror=s=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)})}loadWeights(e){let t=[],n=[];for(let a of e)t.push(...a.weights),n.push(...a.paths);let s=this.checkManifestAndWeightFiles(e),r=n.map(a=>this.loadWeightsFile(a,s[a]));return Promise.all(r).then(a=>[t,o2(a)])}loadWeightsFile(e,t){return new Promise((n,s)=>{let r=new FileReader;r.onload=a=>{let o=a.target.result;n(o)},r.onerror=a=>s(`Failed to weights data from file of path '${e}'.`),r.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){let t=[],n=this.weightsFiles.map(r=>P5(r.name)),s={};for(let r of e)r.paths.forEach(a=>{let o=P5(a);if(t.indexOf(o)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${o}'`);if(t.push(o),n.indexOf(o)===-1)throw new Error(`Weight file with basename '${o}' is not provided.`);s[a]=this.weightsFiles[n.indexOf(o)]});if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return s}},T9=e=>K().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(zh.URL_SCHEME)?N9(e.slice(zh.URL_SCHEME.length)):null;Bt.registerSaveRouter(T9);function N9(e="model"){return new zh(e)}function E9(e){return new C9(e)}function H5(e,t,n,s){o(e),n=n==null?0:n,s=s==null?1:s,i(n,s);let r=0,a=l=>(l.then(c=>{let u=n+ ++r/e.length*(s-n);return t(u),c}),l);function o(l){O(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function i(l,c){O(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),O(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${c}`),O(c>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${c}`)}return Promise.all(e.map(a))}async function j5(e,t){t==null&&(t={});let n=t.fetchFunc==null?K().platform.fetch:t.fetchFunc,s=e.map(d=>n(d,t.requestInit,{isBinary:!0})),r=0,a=.5,i=(t.onProgress==null?await Promise.all(s):await H5(s,t.onProgress,r,a)).map(d=>d.arrayBuffer()),l=.5,c=1;return t.onProgress==null?await Promise.all(i):await H5(i,t.onProgress,l,c)}async function R9(e,t="",n,s){return q5(o=>j5(o,{requestInit:s}))(e,t,n)}function q5(e){return async(t,n="",s)=>{let r=t.map(()=>!1),a={},o=s!=null?s.map(()=>!1):[],i=[];if(t.forEach((h,f)=>{let m=0;h.weights.forEach(g=>{let A="quantization"in g?g.quantization.dtype:g.dtype,y=r2[A]*Ut(g.shape),x=()=>{r[f]=!0,a[f]==null&&(a[f]=[]),a[f].push({manifestEntry:g,groupOffset:m,sizeBytes:y})};s!=null?s.forEach((b,w)=>{b===g.name&&(x(),o[w]=!0)}):x(),i.push(g.name),m+=y})}),!o.every(h=>h)){let h=s.filter((f,m)=>!o[m]);throw new Error(`Could not find weights in manifest with names: ${h.join(", ")}.
-Manifest JSON has weights with names: ${i.join(", ")}.`)}let l=r.reduce((h,f,m)=>(f&&h.push(m),h),[]),c=[];l.forEach(h=>{t[h].paths.forEach(f=>{let m=n+(n.endsWith("/")?"":"/")+f;c.push(m)})});let u=await e(c),d={},p=0;return l.forEach(h=>{let f=t[h].paths.length,m=0;for(let b=0;b{let w=g.slice(b.groupOffset,b.groupOffset+b.sizeBytes),k=D5(w,[b.manifestEntry]);for(let S in k)d[S]=k[S]}),p+=f}),d}}var $9="application/octet-stream",D9="application/json",h2=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?(O(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=K().platform.fetch,O(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&O(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],s=F5(e,n);t.body.append("model.json",new Blob([JSON.stringify(s)],{type:D9}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:$9}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:od(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async load(){let e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(r){let a=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?a+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":a+=" Please make sure the server is serving valid JSON for this request.",new Error(a)}let n=t.modelTopology,s=t.weightsManifest;if(n==null&&s==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return i2(t,r=>this.loadWeights(r))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=_9(t),r=this.weightPathPrefix||n,a=[];for(let c of e)a.push(...c.weights);let o=[],i=[];for(let c of e)for(let u of c.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(u)):o.push(r+u+s);this.weightUrlConverter&&o.push(...await Promise.all(i));let l=await j5(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,o2(l)]}};h2.URL_SCHEME_REGEX=/^https?:\/\//;function _9(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),s=e.substring(0,t),r=n>t?e.substring(n):"";return[s+"/",r]}function f2(e){return e.match(h2.URL_SCHEME_REGEX)!=null}var X5=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(s=>f2(s)):n=f2(e),n)return m2(e,t)}return null};Bt.registerSaveRouter(X5);Bt.registerLoadRouter(X5);function m2(e,t){return new h2(e,t)}function P9(e,t){return m2(e,t)}var g2=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},F9=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function O9(e,t,n,s){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new g2(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 g2({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 g2({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:s}))}function M9(e){return new F9(e)}var K5={};ze(K5,{confusionMatrix:()=>V9});function z9(e,t,n=!1,s=!1){let r=D(e,"a","matMul"),a=D(t,"b","matMul");[r,a]=Ft(r,a);let o={a:r,b:a},i={transposeA:n,transposeB:s};return B.runKernel(Sa,o,i)}var He=V({matMul_:z9});function L9(e,t,n=1,s=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let a={indices:D(e,"indices","oneHot","int32")},o={depth:t,onValue:n,offValue:s};return B.runKernel(Ii,a,o)}var id=V({oneHot_:L9});function B9(e,t){let n=D(e,"x","transpose");if(t==null&&(t=n.shape.map((a,o)=>o).reverse()),O(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(a=>{O(a>=0&&a`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();let s={x:n},r={perm:t};return B.runKernel(po,s,r)}var et=V({transpose_:B9});function W9(e,t,n){let s=D(e,"labels","confusionMatrix"),r=D(t,"predictions","confusionMatrix");O(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),O(s.rank===1,()=>`Expected the rank of labels to be 1, but got ${s.rank}`),O(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),O(s.shape[0]===r.shape[0],()=>`Mismatch in the number of examples: ${s.shape[0]} vs. ${r.shape[0]}. Labels and predictions should have the same number of elements.`),O(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);let a=id(de(s,"int32"),n),o=id(de(r,"int32"),n),i=et(a),l=He(i,o);return de(l,"int32")}var V9=V({confusionMatrix_:W9}),Gs={};ze(Gs,{fromPixels:()=>K9,fromPixelsAsync:()=>q9,toPixels:()=>X9});function Z5(e,t,n){if(ei(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let s=Cr(e,n);if(s.length!==3&&s.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return xo(e,t,s,n)}var xu;function Y5(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(e==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,s=!1,r=!1,a=!1,o=!1,i=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)s=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)r=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)a=!0;else if(e.getContext!=null)o=!0;else if(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)i=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);if(r){let f=2;if(r&&e.readyState element.")}if($h(Kc,B.backendName)!=null){let f={pixels:e},m={numChannels:t};return B.runKernel(Kc,f,m)}let[c,u]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height],d;o?d=e.getContext("2d").getImageData(0,0,c,u).data:s||n?d=e.data:(a||r||i)&&(xu==null&&(xu=document.createElement("canvas").getContext("2d")),xu.canvas.width=c,xu.canvas.height=u,xu.drawImage(e,0,0,c,u),d=xu.getImageData(0,0,c,u).data);let p;if(t===4)p=new Int32Array(d);else{let f=c*u;p=new Int32Array(f*t);for(let m=0;m4||a===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${a}`);if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);let o=await n.data(),i=n.dtype==="float32"?255:1,l=new Uint8ClampedArray(r*s*4);for(let c=0;c1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${h}.`)}else if(n.dtype==="int32"&&(h<0||h>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${h}.`);a===1?(u[0]=h*i,u[1]=h*i,u[2]=h*i):u[p]=h*i}let d=c*4;l[d+0]=Math.round(u[0]),l[d+1]=Math.round(u[1]),l[d+2]=Math.round(u[2]),l[d+3]=Math.round(u[3])}if(t!=null){t.width=r,t.height=s;let c=t.getContext("2d"),u=new ImageData(l,r,s);c.putImageData(u,0,0)}return n!==e&&n.dispose(),l}var K9=V({fromPixels_:Y5}),A2={};ze(A2,{prepareAndValidate:()=>J5});function J5(e,t){let n=e.shape.length,s=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(s<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${s}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[s-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[s-1]} vs. ${n}`);if(Ut(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let r=t.shape,a=r[r.length-1],o=1;for(let d=0;dd/c),1].slice(0,a);return[l,o,c,u]}var y2={};ze(y2,{calculateShapes:()=>Q5,validateInput:()=>b2,validateUpdateShape:()=>x2});function x2(e,t,n){let s=t.rank>1?t.shape[t.rank-1]:1,r=t.rank>1?t.rank-1:1,a=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${s}, and batchDim: ${r}.`;if(n.rank1?t.shape[s-1]:1,a=n.length,o=1;for(let d=r;dZ9,computeFlatOffset:()=>J9,computeOutShape:()=>e3,getNormalizedAxes:()=>r3,isSliceContinous:()=>Y9,maskToAxes:()=>Lh,parseSliceParams:()=>c3,sliceInfo:()=>Q9,startForAxis:()=>l3,startIndicesWithElidedDims:()=>a3,stopForAxis:()=>u3,stopIndicesWithElidedDims:()=>o3,stridesForAxis:()=>i3,stridesWithElidedDims:()=>t3});function Z9(e,t,n){let s=e.shape.length;O(s===t.length,()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`),O(s===n.length,()=>`Error in slice${s}D: Length of size ${n} must match the rank of the array (${s}).`);for(let r=0;r`Error in slice${s}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`)}function Lh(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function e3(e,t,n){let s=[];for(let r=0;r0){let h=t[0],f=n+1;u=a3(o,h,f,s,e),d=o3(i,h,f,r,e),p=t3(a,h,f,e)}else for(let h=0;h-1)a[i]=0;else{let l=n3(t,n,i),c=s[l];e&1<-1)a[i]=Number.MAX_SAFE_INTEGER;else{let l=n3(t,n,i),c=s[l];e&1<0?o=Number.MIN_SAFE_INTEGER:o=Number.MAX_SAFE_INTEGER);let l=s[r];return o<0&&(o+=l),o=_c(0,o,l-1),o}function u3(e,t,n,s,r,a){let o=t[r],i=n[r]||1;(e&1<0?o=Number.MAX_SAFE_INTEGER:o=Number.MIN_SAFE_INTEGER);let l=s[r];return o<0&&(o+=l),i>0?o=_c(0,o,l):o=_c(-1,o,l-1),o}function Y9(e,t,n){let s=n.length;for(let r=0;r1){s=r;break}for(let r=s+1;r0||n[r]!==e[r])return!1;return!0}function J9(e,t){let n=e.length>0?e[e.length-1]:1;for(let s=0;s{O(o!==-1,()=>"slice() does not support negative begin indexing.")});let a;return n==null?a=new Array(r).fill(-1):typeof n=="number"?a=[n,...new Array(r-1).fill(-1)]:n.lengtho>=0?o:(O(o===-1,()=>`Negative size values should be exactly -1 but got ${o} for the slice() size at index ${i}.`),e.shape[i]-s[i])),[s,a]}function Q9(e,t,n,s,r,a,o,i,l){let c=t.slice(),u=n.slice(),d=s;s==null&&(d=new Array(c.length));let p=Lh(o);if(p.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(o!==0&&i!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(o!==0&&l!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let h=e.length-c.length,f=Lh(i),m=e.slice();f.forEach(S=>{c[S]=0,u[S]=1,m.splice(S,0,1)});let{begin:g,end:A,strides:y}=r3(m,p,h,c,u,d,r,a,o);c=g,u=A,d=y;let x=Lh(l);x.forEach(S=>{u[S]=c[S]+1,d[S]=1});let b=e3(c,u,d),w=b.filter((S,E)=>x.indexOf(E)===-1);return{nonStrided:d.every(S=>S===1),$begin:c,$end:u,$strides:d,size:b,newShape:m,outShape:w}}var le={};ze(le,{Serializable:()=>d3,SerializationMap:()=>Xi,registerClass:()=>vo});var d3=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},Xi=class{constructor(){this.classNameMap={}}static getMap(){return Xi.instance==null&&(Xi.instance=new Xi),Xi.instance}static register(e){Xi.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function vo(e){O(e.className!=null,()=>"Class being registered does not have the static className property defined."),O(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),O(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Xi.register(e)}var p3={};ze(p3,{TEST_EPSILON_FLOAT16:()=>h3,encodeStrings:()=>f3,expectArrayBuffersEqual:()=>oR,expectArraysClose:()=>tR,expectArraysEqual:()=>sR,expectNumbersClose:()=>rR,expectPromiseToFail:()=>nR,expectValuesInRange:()=>aR,testEpsilon:()=>v2});var eR=.001,h3=.1;function tR(e,t,n){return n==null&&(n=v2()),w2(e,t,(s,r)=>k2(s,r,n))}function v2(){return B.backend.floatPrecision()===32?eR:h3}function w2(e,t,n){let s=!0;if((Dn(e)||Dn(t))&&(s=!1),Dn(e)&&Dn(t)&&(s=!0),s){let o=e.constructor.name,i=t.constructor.name;if(o!==i)throw new Error(`Arrays are of different type. Actual: ${o}. Expected: ${i}`)}if(Array.isArray(e)&&Array.isArray(t)){let o=Cr(e),i=Cr(t);if(!Gr(o,i))throw new Error(`Arrays have different shapes. Actual: [${o}]. Expected: [${i}]`)}let r=Dn(e)?e:ti(e),a=Dn(t)?t:ti(t);if(r.length!==a.length)throw new Error(`Arrays have different lengths actual: ${r.length} vs expected: ${a.length}.
+`;return p[p.length-1]=" "+p[p.length-1]+"]"+(a?"":f),p}function nd(e){let t=[];for(let n=0;n`Length of values '${s}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||a5(t,this.size),this.strides=Bl(e)}set(e,...t){t.length===0&&(t=[0]),O(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let s of e){if(s<0||s>=this.shape[t]){let r=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(r)}t++}let n=e[e.length-1];for(let s=0;sPh(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();let e=Sr().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Ph(t))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();let e=await Sr().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Sr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return mu.print(this,e)}clone(){return this.throwIfDisposed(),mu.clone(this)}toString(e=!1){let t=this.dataSync();return NE(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),mu.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Sr().makeVariable(this,e,t,n)}};Object.defineProperty(Ye,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function PE(){return Ug("Tensor",()=>Ye)}PE();var sd=class extends Ye{constructor(e,t,n,s){super(e.shape,e.dtype,e.dataId,s);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!Gr(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Sr().disposeTensor(this),this.dataId=e.dataId,Sr().incRef(this,null)}dispose(){Sr().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(sd,Symbol.hasInstance,{value:e=>e instanceof Ye&&e.assign!=null&&e.assign instanceof Function});var rr={};ze(rr,{assertTypesMatch:()=>I5,getTensorsInContainer:()=>Qg,isTensorInList:()=>OE,makeTypesMatch:()=>Ft});var Xg;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(Xg||(Xg={}));var Kg;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(Kg||(Kg={}));var Zg;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(Zg||(Zg={}));var Yg;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(Yg||(Yg={}));var Jg;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(Jg||(Jg={}));var FE={float32:Yg,int32:Kg,bool:Zg,complex64:Jg};function Bn(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return FE[e][t]}function rd(e){return Bn(e,"int32")}function Ft(e,t){if(e.dtype===t.dtype)return[e,t];let n=Bn(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function I5(e,t){O(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function OE(e,t){return t.some(n=>n.id===e.id)}function Qg(e){let t=[],n=new Set;return S5(e,t,n),t}function S5(e,t,n){if(e==null)return;if(e instanceof Ye){t.push(e);return}if(!ME(e))return;let s=e;for(let r in s){let a=s[r];n.has(a)||(n.add(a),S5(a,t,n))}}function ME(e){return Array.isArray(e)||typeof e=="object"}function e2(e){return e.kernelName!=null}var C5=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()}},t2=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new C5}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let e=this.getSortedBackends();for(let t=0;t{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Xr(e).forEach(n=>{n.disposeFunc!=null&&n.disposeFunc(this.registry[e])})}initializeBackend(e){let t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{let n=t.factory();if(n&&!(n instanceof Ll)&&typeof n.then=="function"){let s=++this.pendingBackendInitId,r=n.then(a=>s(sthis.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;tthis.startScope(n),()=>this.endScope(s),()=>(s=t(),s instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),s))}scopedRun(e,t,n){e();try{let s=n();return t(),s}catch(s){throw t(),s}}nextTensorId(){return t2.nextTensorId++}nextVariableId(){return t2.nextVariableId++}clone(e){let t=B.runKernel(Ba,{x:e}),n={x:e},s=a=>({x:()=>{let o="float32",i={x:a},l={dtype:o};return B.runKernel(Ca,i,l)}}),r=[];return this.addTapeNode(this.state.activeScope.name,n,[t],s,r,{}),t}runKernel(e,t,n){if(this.backendName==null&&this.backend,!($h(e,this.backendName)!=null))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){let s=this.backend.numDataIds(),r=0;n.forEach(i=>{r+=i.dtype==="complex64"?3:1});let a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=s-t-r-a;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[],s=this.isTapeOn(),r=this.state.numBytes,a=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let o;this.backendName==null&&this.backend;let i,l=e2(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(e2(e)){let{kernelName:h,inputs:f,attrs:m}=e;this.backendName==null&&this.backend;let g=$h(h,this.backendName);O(g!=null,()=>`Cannot find registered kernel '${h}' for backend '${this.backendName}'`),o=()=>{let A=this.backend.numDataIds();i=g.kernelFunc({inputs:f,attrs:m,backend:this.backend});let y=Array.isArray(i)?i:[i];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(h,A,y);let x=y.map(b=>{if(b.rank!=null)return b;let{dataId:w,shape:k,dtype:S}=b;return this.makeTensorFromDataId(w,k,S)});if(s){let b=this.getTensorsForGradient(h,f,x);n=this.saveTensorsForBackwardMode(b)}return x}}else{let{forwardFunc:h}=e,f=m=>{!s||(n=m.map(g=>this.keep(this.clone(g))))};o=()=>{let m=this.backend.numDataIds();i=this.tidy(()=>h(this.backend,f));let g=Array.isArray(i)?i:[i];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,m,g),g}}let{inputs:c,attrs:u}=e,d=e2(e)?null:e.backwardsFunc,p;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=o():(p=this.profiler.profileKernel(l,c,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs)}),s&&this.addTapeNode(l,c,t,d,n,u),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map(h=>c[h]!=null?c[h].shape:null),outputShapes:t.map(h=>h.shape),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(i)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(n=>this.keep(this.clone(n)))}getTensorsForGradient(e,t,n){let s=Gg(e);if(s!=null){let r=s.inputsToSave||[],a=s.outputsToSave||[],o;s.saveAllInputs?(O(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),o=Object.keys(t).map(l=>t[l])):o=r.map(l=>t[l]);let i=n.filter((l,c)=>a[c]);return o.concat(i)}return[]}makeTensor(e,t,n,s){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",s=s||this.backend;let r=e;n==="string"&&ba(e[0])&&(r=e.map(i=>Qc(i)));let a=s.write(r,t,n),o=new Ye(t,n,a,this.nextTensorId());if(this.trackTensor(o,s),n==="string"){let i=this.state.tensorInfo.get(a),l=l5(r);this.state.numBytes+=l-i.bytes,i.bytes=l}return o}makeTensorFromDataId(e,t,n,s){n=n||"float32";let r=new Ye(t,n,e,this.nextTensorId());return this.trackTensor(r,s),r}makeVariable(e,t=!0,n,s){n=n||this.nextVariableId().toString(),s!=null&&s!==e.dtype&&(e=e.cast(s));let r=new sd(e,t,n,this.nextTensorId());if(this.state.registeredVariables[r.name]!=null)throw new Error(`Variable with name ${r.name} was already registered`);return this.state.registeredVariables[r.name]=r,this.incRef(r,this.backend),r}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let n=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(n=e.size*zg(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof sd||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;let t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,e.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),e.dtype!=="complex64"&&e.dtype!=="string"){let n=e.size*zg(e.dtype);this.state.numBytes-=n}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(let e in this.state.registeredVariables){let t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]}memory(){let e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,e.reasons==null&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;let t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(s=>s.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(let s of this.state.activeProfile.kernels)s.kernelTimeMs=await s.kernelTimeMs,s.extraInfo=await s.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,s,r,a){let o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:r},i=Gg(e);i!=null&&(s=i.gradFunc),s!=null&&(o.gradient=l=>(l=l.map((c,u)=>{if(c==null){let d=n[u],p=Qp(d.size,d.dtype);return this.makeTensor(p,d.shape,d.dtype)}return c}),s(l.length>1?l:l[0],r,a))),this.state.activeTape.push(o)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=Qg(e),n=new Set(t.map(r=>r.id));for(let r=0;r{!r.kept&&r.scopeId===s.id&&this.track(r)})}gradients(e,t,n,s=!1){if(O(t.length>0,()=>"gradients() received an empty list of xs."),n!=null&&n.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);let r=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));O(r instanceof Ye,()=>"The result y returned by f() must be a tensor.");let a=CE(this.state.activeTape,t,r);if(!s&&a.length===0&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{let o={};o[r.id]=n==null?zE(r.shape):n,TE(o,a,l=>this.tidy(l),LE);let i=t.map(l=>o[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let c of l.saved)c.dispose()}),this.state.activeTape=null),{value:r,grads:i}})}customGrad(e){return O(va(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{O(t.every(o=>o instanceof Ye),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,s={};t.forEach((o,i)=>{s[i]=o});let r=(o,i)=>(n=e(...t,i),O(n.value instanceof Ye,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),O(va(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),a=(o,i)=>{let l=n.gradFunc(o,i),c=Array.isArray(l)?l:[l];O(c.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),O(c.every(d=>d instanceof Ye),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let u={};return c.forEach((d,p)=>{u[p]=()=>d}),u};return this.runKernelFunc({forwardFunc:r,backwardsFunc:a,inputs:s})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}async time(e){let t=Jc(),n=await this.backend.time(e);return n.wallMs=Jc()-t,n}track(e){return this.state.activeScope!=null&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new C5;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}},n2=t2;n2.nextTensorId=0;n2.nextVariableId=0;function zE(e){let t=Lg(Ut(e),"float32");return B.makeTensor(t,e,"float32")}function T5(){let e=f5();if(e._tfengine==null){let t=new h5(e);e._tfengine=new n2(t)}return uE(e._tfengine.ENV),$E(()=>e._tfengine),e._tfengine}var B=T5();function LE(e,t){let n={a:e,b:t};return B.runKernel(Hr,n)}var gu={};ze(gu,{isBrowser:()=>N5,isMobile:()=>VE,mockIsMobile:()=>WE});function BE(){return typeof navigator!="undefined"&&navigator!=null}var s2;function WE(e){s2=e}function VE(e){if(s2!==void 0)return s2;if(e||BE()){if(e||(e=navigator),e.product==="ReactNative")return!0;let t=e.userAgent||e.vendor||(typeof window!="undefined"?window.opera:"");if(!t){let n=e;return n.userAgentData&&n.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}return!1}function N5(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var ar=K();ar.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.")});ar.registerFlag("IS_BROWSER",()=>N5());ar.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");ar.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));ar.registerFlag("PROD",()=>!1);ar.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>ar.getBool("DEBUG"));ar.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);ar.registerFlag("IS_TEST",()=>!1);ar.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);ar.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function Cr(e,t){let n=e;if(Dn(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let s=[];for(;Array.isArray(n)||Dn(n)&&t!=="string";)s.push(n.length),n=n[0];return Array.isArray(e)&&K().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&E5(e,s,[]),s}function E5(e,t,n){if(n=n||[],!Array.isArray(e)&&!Dn(e)){O(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}O(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),O(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let s=t.slice(1);for(let r=0;r=0&&(r=s),R5(s,r,t,n),e==null||!Dn(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){let l=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${l}'`)}let a=Cr(e,r);!Dn(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?_h(e,r):ti(e,[],!0);return B.makeTensor(i,a,r)}function ad(e,t,n,s="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((a,o)=>_(a,`${t}[${o}]`,n,s))}var $5="__op";function V(e){let t=Object.keys(e);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0],s=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+$5;let r=(...a)=>{B.startScope(n);try{let o=s(...a);return Wg(o)&&console.error("Cannot return a Promise inside of tidy."),B.endScope(o),o}catch(o){throw B.endScope(null),o}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}function UE(e,t){let n=_(e,"real","complex"),s=_(t,"imag","complex");zn(n.shape,s.shape,`real and imag shapes, ${n.shape} and ${s.shape}, must match in call to tf.complex().`);let r={real:n,imag:s};return B.runKernel(Oc,r)}var yo=V({complex_:UE});function xo(e,t,n,s){if(s==null&&(s=Yp(e)),s==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Dn(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){Bg(t);let r=Ut(t),a=Ut(n);O(r===a,()=>`Based on the provided shape, [${t}], the tensor should have ${r} values but has ${a}`);for(let o=0;o`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!Dn(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=s!=="string"?_h(e,s):ti(e,[],!0),B.makeTensor(e,t,s)}function Gt(e,t,n){let s=Cr(e,n);return xo(e,t,s,n)}var r2={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},Oh=4;async function GE(e,t){let n=[],s=[],r=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);for(let o=0;o{let p=await l.bytes(),h=p.reduce((g,A)=>g+A.length,0)+Oh*p.length,f=new Uint8Array(h),m=0;for(let g=0;g{if(t+=a.byteLength,n.push(a.byteLength===a.buffer.byteLength?a:new a.constructor(a)),!(a instanceof Float32Array||a instanceof Int32Array||a instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${a.constructor.name}`)});let s=new Uint8Array(t),r=0;return n.forEach(a=>{s.set(new Uint8Array(a.buffer),r),r+=a.byteLength}),s.buffer}var a2=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function _5(e){return a2?Buffer.byteLength(e):new Blob([e]).size}function jE(e){if(a2)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),n="";for(let s=0,r=t.length;s{t+=r.byteLength});let n=new Uint8Array(t),s=0;return e.forEach(r=>{n.set(new Uint8Array(r),s),s+=r.byteLength}),n.buffer}function P5(e){let t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);let n=e.split(t);return n[n.length-1]}function F5(e,t){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),n}async function i2(e,t){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),e.weightsManifest!=null){let[s,r]=await t(e.weightsManifest);n.weightSpecs=s,n.weightData=r}return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),n}function od(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:_5(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:_5(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function XE(){let e=n=>{let s=n<<13,r=0;for(;(s&8388608)==0;)r-=8388608,s<<=1;return s&=~8388608,r+=947912704,s|r},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let n=1024;n<2048;n++)t[n]=939524096+(n-1024<<13);return t}function KE(){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 ZE(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function YE(){let e=XE(),t=KE(),n=ZE();return s=>{let r=new ArrayBuffer(4*s.length),a=new Uint32Array(r);for(let o=0;o>10]+(i&1023)]+t[i>>10];a[o]=l}return new Float32Array(r)}}var Bt=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Bt.instance==null&&(Bt.instance=new Bt),Bt.instance}static registerSaveRouter(e){Bt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Bt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Bt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Bt.getHandlers(e,"load",t)}static getHandlers(e,t,n){let s=[];return(t==="load"?Bt.getInstance().loadRouters:Bt.getInstance().saveRouters).forEach(a=>{let o=a(e,n);o!==null&&s.push(o)}),s}},JE=e=>Bt.registerSaveRouter(e),QE=e=>Bt.registerLoadRouter(e),e9=e=>Bt.getSaveHandlers(e),t9=(e,t)=>Bt.getLoadHandlers(e,t),l2="tensorflowjs",u2=1,Hi="models_store",bo="model_info_store";function O5(){if(!K().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 c2(e){let t=e.result;t.createObjectStore(Hi,{keyPath:"modelPath"}),t.createObjectStore(bo,{keyPath:"modelPath"})}var ji=class{constructor(e){if(this.indexedDB=O5(),e==null||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((n,s)=>{let r=this.indexedDB.open(l2,u2);r.onupgradeneeded=()=>c2(r),r.onsuccess=()=>{let a=r.result;if(t==null){let o=a.transaction(Hi,"readonly"),l=o.objectStore(Hi).get(this.modelPath);l.onsuccess=()=>{if(l.result==null)return a.close(),s(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(l.result.modelArtifacts)},l.onerror=c=>(a.close(),s(l.error)),o.oncomplete=()=>a.close()}else{let o=od(t),i=a.transaction(bo,"readwrite"),l=i.objectStore(bo),c=l.put({modelPath:this.modelPath,modelArtifactsInfo:o}),u;c.onsuccess=()=>{u=a.transaction(Hi,"readwrite");let p=u.objectStore(Hi).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:o});p.onsuccess=()=>n({modelArtifactsInfo:o}),p.onerror=h=>{l=i.objectStore(bo);let f=l.delete(this.modelPath);f.onsuccess=()=>(a.close(),s(p.error)),f.onerror=m=>(a.close(),s(p.error))}},c.onerror=d=>(a.close(),s(c.error)),i.oncomplete=()=>{u==null?a.close():u.oncomplete=()=>a.close()}}},r.onerror=a=>s(r.error)})}};ji.URL_SCHEME="indexeddb://";var M5=e=>K().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ji.URL_SCHEME)?n9(e.slice(ji.URL_SCHEME.length)):null;Bt.registerSaveRouter(M5);Bt.registerLoadRouter(M5);function n9(e){return new ji(e)}function s9(e){return e.startsWith(ji.URL_SCHEME)?e.slice(ji.URL_SCHEME.length):e}var r9=class{constructor(){this.indexedDB=O5()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(l2,u2);n.onupgradeneeded=()=>c2(n),n.onsuccess=()=>{let s=n.result,r=s.transaction(bo,"readonly"),o=r.objectStore(bo).getAll();o.onsuccess=()=>{let i={};for(let l of o.result)i[l.modelPath]=l.modelArtifactsInfo;e(i)},o.onerror=i=>(s.close(),t(o.error)),r.oncomplete=()=>s.close()},n.onerror=s=>t(n.error)})}async removeModel(e){return e=s9(e),new Promise((t,n)=>{let s=this.indexedDB.open(l2,u2);s.onupgradeneeded=()=>c2(s),s.onsuccess=()=>{let r=s.result,a=r.transaction(bo,"readwrite"),o=a.objectStore(bo),i=o.get(e),l;i.onsuccess=()=>{if(i.result==null)return r.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let c=o.delete(e),u=()=>{l=r.transaction(Hi,"readwrite");let p=l.objectStore(Hi).delete(e);p.onsuccess=()=>t(i.result.modelArtifactsInfo),p.onerror=h=>n(i.error)};c.onsuccess=u,c.onerror=d=>(u(),r.close(),n(i.error))}},i.onerror=c=>(r.close(),n(i.error)),a.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},s.onerror=r=>n(s.error)})}},Zr="/",Au="tensorflowjs_models",z5="info",a9="model_topology",o9="weight_specs",i9="weight_data",l9="model_metadata";function L5(e){return{info:[Au,e,z5].join(Zr),topology:[Au,e,a9].join(Zr),weightSpecs:[Au,e,o9].join(Zr),weightData:[Au,e,i9].join(Zr),modelMetadata:[Au,e,l9].join(Zr)}}function B5(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function u9(e){let t=e.split(Zr);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Zr)}function c9(e){return e.startsWith(qi.URL_SCHEME)?e.slice(qi.URL_SCHEME.length):e}var qi=class{constructor(e){if(!K().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=L5(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{let t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),s=od(e);try{this.LS.setItem(this.keys.info,JSON.stringify(s)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,jE(e.weightData));let r={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:e.signature!=null?e.signature:void 0,userDefinedMetadata:e.userDefinedMetadata!=null?e.userDefinedMetadata:void 0,modelInitializer:e.modelInitializer!=null?e.modelInitializer:void 0,trainingConfig:e.trainingConfig!=null?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(r)),{modelArtifactsInfo:s}}catch(r){throw B5(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${s.modelTopologyBytes}, weightSpecsBytes=${s.weightSpecsBytes}, weightDataBytes=${s.weightDataBytes}.`)}}}async load(){let e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");let t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(n==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;let s=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(s==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=s;let r=this.LS.getItem(this.keys.modelMetadata);if(r!=null){let o=JSON.parse(r);t.format=o.format,t.generatedBy=o.generatedBy,t.convertedBy=o.convertedBy,o.signature!=null&&(t.signature=o.signature),o.userDefinedMetadata!=null&&(t.userDefinedMetadata=o.userDefinedMetadata),o.modelInitializer!=null&&(t.modelInitializer=o.modelInitializer),o.trainingConfig!=null&&(t.trainingConfig=o.trainingConfig)}let a=this.LS.getItem(this.keys.weightData);if(a==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=qE(a),t}};qi.URL_SCHEME="localstorage://";var W5=e=>K().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(qi.URL_SCHEME)?d9(e.slice(qi.URL_SCHEME.length)):null;Bt.registerSaveRouter(W5);Bt.registerLoadRouter(W5);function d9(e){return new qi(e)}var p9=class{constructor(){O(K().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),O(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Au+Zr,n=Zr+z5;for(let s=0;s"scheme must not be undefined or null."),e.endsWith(yu)&&(e=e.slice(0,e.indexOf(yu))),O(e.length>0,()=>"scheme must not be an empty string.");let n=Ss.getInstance();O(n.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){let t=this.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(this.getInstance().managers)}};function Mh(e){if(e.indexOf(yu)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Ss.getSchemes().join(",")}`);return{scheme:e.split(yu)[0],path:e.split(yu)[1]}}async function V5(e,t,n=!1){O(e!==t,()=>`Old path and new path are the same: '${e}'`);let s=Bt.getLoadHandlers(e);O(s.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),O(s.length<2,()=>`Copying failed because more than one (${s.length}) load handlers for source URL ${e}.`);let r=s[0],a=Bt.getSaveHandlers(t);O(a.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),O(a.length<2,()=>`Copying failed because more than one (${s.length}) save handlers for destination URL ${t}.`);let o=a[0],i=Mh(e).scheme,l=Mh(e).path,c=i===Mh(e).scheme,u=await r.load();n&&c&&await Ss.getManager(i).removeModel(l);let d=await o.save(u);return n&&!c&&await Ss.getManager(i).removeModel(l),d.modelArtifactsInfo}async function h9(){let e=Ss.getSchemes(),t={};for(let n of e){let s=await Ss.getManager(n).listModels();for(let r in s){let a=n+yu+r;t[a]=s[r]}}return t}async function f9(e){let t=Mh(e);return Ss.getManager(t.scheme).removeModel(t.path)}async function m9(e,t){return V5(e,t,!1)}async function g9(e,t){return V5(e,t,!0)}var A9=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(K().get("IS_BROWSER")){K().setPlatform("browser",new A9);try{Ss.registerManager(qi.URL_SCHEME,new p9)}catch(e){}try{Ss.registerManager(ji.URL_SCHEME,new r9)}catch(e){}}var y9={importFetch:()=>RN()},d2,x9=class{constructor(){this.util=$N(),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return K().global.fetch!=null?K().global.fetch(e,t):(d2==null&&(d2=y9.importFetch()),d2(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)}};K().get("IS_NODE")&&K().setPlatform("node",new x9);function Le(e,t="float32",n){return t=t||"float32",Bg(e),new sn(e,t,n)}function b9(e,t){let n=_(e,"x","cast");if(!i5(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&n.dtype!=="string"||t!=="string"&&n.dtype==="string")throw new Error("Only strings can be casted to strings");let s={x:n},r={dtype:t};return B.runKernel(Ca,s,r)}var he=V({cast_:b9});function v9(e){let n={x:_(e,"x","clone","string_or_numeric")};return B.runKernel(Ba,n)}var or=V({clone_:v9});function U5(e,t=!1){console.log(e.toString(t))}T5();var w9={buffer:Le,cast:he,clone:or,print:U5};DE(w9);var ns={};ze(ns,{browserFiles:()=>E9,browserHTTPRequest:()=>P9,concatenateArrayBuffers:()=>o2,copyModel:()=>m9,decodeWeights:()=>D5,encodeWeights:()=>GE,fromMemory:()=>O9,getLoadHandlers:()=>t9,getModelArtifactsForJSON:()=>i2,getModelArtifactsInfoForJSON:()=>od,getSaveHandlers:()=>e9,http:()=>m2,isHTTPScheme:()=>f2,listModels:()=>h9,loadWeights:()=>R9,moveModel:()=>g9,registerLoadRouter:()=>QE,registerSaveRouter:()=>JE,removeModel:()=>f9,weightsLoaderFactory:()=>q5,withSaveHandler:()=>M9});var k9="model",I9=".json",S9=".weights.bin";function G5(e){return new Promise(t=>setTimeout(t)).then(e)}var p2=class{constructor(e){if(!K().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(p2.URL_SCHEME)&&(e=e.slice(p2.URL_SCHEME.length)),(e==null||e.length===0)&&(e=k9),this.modelJsonFileName=e+I9,this.weightDataFileName=e+S9}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");let t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{let n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],s=F5(e,n),r=window.URL.createObjectURL(new Blob([JSON.stringify(s)],{type:"application/json"})),a=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(a.download=this.modelJsonFileName,a.href=r,await G5(()=>a.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let o=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;o.download=this.weightDataFileName,o.href=t,await G5(()=>o.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:od(e)}}}},zh=p2;zh.URL_SCHEME="downloads://";var C9=class{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise((e,t)=>{let n=new FileReader;n.onload=s=>{let r=JSON.parse(s.target.result),a=r.modelTopology;if(a==null){t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));return}if(r.weightsManifest==null){t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));return}if(this.weightsFiles.length===0){e({modelTopology:a});return}let i=i2(r,l=>this.loadWeights(l));e(i)},n.onerror=s=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)})}loadWeights(e){let t=[],n=[];for(let a of e)t.push(...a.weights),n.push(...a.paths);let s=this.checkManifestAndWeightFiles(e),r=n.map(a=>this.loadWeightsFile(a,s[a]));return Promise.all(r).then(a=>[t,o2(a)])}loadWeightsFile(e,t){return new Promise((n,s)=>{let r=new FileReader;r.onload=a=>{let o=a.target.result;n(o)},r.onerror=a=>s(`Failed to weights data from file of path '${e}'.`),r.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){let t=[],n=this.weightsFiles.map(r=>P5(r.name)),s={};for(let r of e)r.paths.forEach(a=>{let o=P5(a);if(t.indexOf(o)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${o}'`);if(t.push(o),n.indexOf(o)===-1)throw new Error(`Weight file with basename '${o}' is not provided.`);s[a]=this.weightsFiles[n.indexOf(o)]});if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return s}},T9=e=>K().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(zh.URL_SCHEME)?N9(e.slice(zh.URL_SCHEME.length)):null;Bt.registerSaveRouter(T9);function N9(e="model"){return new zh(e)}function E9(e){return new C9(e)}function H5(e,t,n,s){o(e),n=n==null?0:n,s=s==null?1:s,i(n,s);let r=0,a=l=>(l.then(c=>{let u=n+ ++r/e.length*(s-n);return t(u),c}),l);function o(l){O(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function i(l,c){O(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),O(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${c}`),O(c>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${c}`)}return Promise.all(e.map(a))}async function j5(e,t){t==null&&(t={});let n=t.fetchFunc==null?K().platform.fetch:t.fetchFunc,s=e.map(d=>n(d,t.requestInit,{isBinary:!0})),r=0,a=.5,i=(t.onProgress==null?await Promise.all(s):await H5(s,t.onProgress,r,a)).map(d=>d.arrayBuffer()),l=.5,c=1;return t.onProgress==null?await Promise.all(i):await H5(i,t.onProgress,l,c)}async function R9(e,t="",n,s){return q5(o=>j5(o,{requestInit:s}))(e,t,n)}function q5(e){return async(t,n="",s)=>{let r=t.map(()=>!1),a={},o=s!=null?s.map(()=>!1):[],i=[];if(t.forEach((h,f)=>{let m=0;h.weights.forEach(g=>{let A="quantization"in g?g.quantization.dtype:g.dtype,y=r2[A]*Ut(g.shape),x=()=>{r[f]=!0,a[f]==null&&(a[f]=[]),a[f].push({manifestEntry:g,groupOffset:m,sizeBytes:y})};s!=null?s.forEach((b,w)=>{b===g.name&&(x(),o[w]=!0)}):x(),i.push(g.name),m+=y})}),!o.every(h=>h)){let h=s.filter((f,m)=>!o[m]);throw new Error(`Could not find weights in manifest with names: ${h.join(", ")}.
+Manifest JSON has weights with names: ${i.join(", ")}.`)}let l=r.reduce((h,f,m)=>(f&&h.push(m),h),[]),c=[];l.forEach(h=>{t[h].paths.forEach(f=>{let m=n+(n.endsWith("/")?"":"/")+f;c.push(m)})});let u=await e(c),d={},p=0;return l.forEach(h=>{let f=t[h].paths.length,m=0;for(let b=0;b{let w=g.slice(b.groupOffset,b.groupOffset+b.sizeBytes),k=D5(w,[b.manifestEntry]);for(let S in k)d[S]=k[S]}),p+=f}),d}}var $9="application/octet-stream",D9="application/json",h2=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?(O(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=K().platform.fetch,O(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&O(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],s=F5(e,n);t.body.append("model.json",new Blob([JSON.stringify(s)],{type:D9}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:$9}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:od(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async load(){let e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(r){let a=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?a+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":a+=" Please make sure the server is serving valid JSON for this request.",new Error(a)}let n=t.modelTopology,s=t.weightsManifest;if(n==null&&s==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return i2(t,r=>this.loadWeights(r))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=_9(t),r=this.weightPathPrefix||n,a=[];for(let c of e)a.push(...c.weights);let o=[],i=[];for(let c of e)for(let u of c.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(u)):o.push(r+u+s);this.weightUrlConverter&&o.push(...await Promise.all(i));let l=await j5(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,o2(l)]}};h2.URL_SCHEME_REGEX=/^https?:\/\//;function _9(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),s=e.substring(0,t),r=n>t?e.substring(n):"";return[s+"/",r]}function f2(e){return e.match(h2.URL_SCHEME_REGEX)!=null}var X5=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(s=>f2(s)):n=f2(e),n)return m2(e,t)}return null};Bt.registerSaveRouter(X5);Bt.registerLoadRouter(X5);function m2(e,t){return new h2(e,t)}function P9(e,t){return m2(e,t)}var g2=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},F9=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function O9(e,t,n,s){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new g2(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 g2({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 g2({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:s}))}function M9(e){return new F9(e)}var K5={};ze(K5,{confusionMatrix:()=>V9});function z9(e,t,n=!1,s=!1){let r=_(e,"a","matMul"),a=_(t,"b","matMul");[r,a]=Ft(r,a);let o={a:r,b:a},i={transposeA:n,transposeB:s};return B.runKernel(Sa,o,i)}var He=V({matMul_:z9});function L9(e,t,n=1,s=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let a={indices:_(e,"indices","oneHot","int32")},o={depth:t,onValue:n,offValue:s};return B.runKernel(Ii,a,o)}var id=V({oneHot_:L9});function B9(e,t){let n=_(e,"x","transpose");if(t==null&&(t=n.shape.map((a,o)=>o).reverse()),O(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(a=>{O(a>=0&&a`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();let s={x:n},r={perm:t};return B.runKernel(po,s,r)}var et=V({transpose_:B9});function W9(e,t,n){let s=_(e,"labels","confusionMatrix"),r=_(t,"predictions","confusionMatrix");O(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),O(s.rank===1,()=>`Expected the rank of labels to be 1, but got ${s.rank}`),O(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),O(s.shape[0]===r.shape[0],()=>`Mismatch in the number of examples: ${s.shape[0]} vs. ${r.shape[0]}. Labels and predictions should have the same number of elements.`),O(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);let a=id(he(s,"int32"),n),o=id(he(r,"int32"),n),i=et(a),l=He(i,o);return he(l,"int32")}var V9=V({confusionMatrix_:W9}),Gs={};ze(Gs,{fromPixels:()=>K9,fromPixelsAsync:()=>q9,toPixels:()=>X9});function Z5(e,t,n){if(ei(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let s=Cr(e,n);if(s.length!==3&&s.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return xo(e,t,s,n)}var xu;function Y5(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(e==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,s=!1,r=!1,a=!1,o=!1,i=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)s=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)r=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)a=!0;else if(e.getContext!=null)o=!0;else if(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)i=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);if(r){let f=2;if(r&&e.readyState element.")}if($h(Kc,B.backendName)!=null){let f={pixels:e},m={numChannels:t};return B.runKernel(Kc,f,m)}let[c,u]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height],d;o?d=e.getContext("2d").getImageData(0,0,c,u).data:s||n?d=e.data:(a||r||i)&&(xu==null&&(xu=document.createElement("canvas").getContext("2d")),xu.canvas.width=c,xu.canvas.height=u,xu.drawImage(e,0,0,c,u),d=xu.getImageData(0,0,c,u).data);let p;if(t===4)p=new Int32Array(d);else{let f=c*u;p=new Int32Array(f*t);for(let m=0;m4||a===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${a}`);if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);let o=await n.data(),i=n.dtype==="float32"?255:1,l=new Uint8ClampedArray(r*s*4);for(let c=0;c1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${h}.`)}else if(n.dtype==="int32"&&(h<0||h>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${h}.`);a===1?(u[0]=h*i,u[1]=h*i,u[2]=h*i):u[p]=h*i}let d=c*4;l[d+0]=Math.round(u[0]),l[d+1]=Math.round(u[1]),l[d+2]=Math.round(u[2]),l[d+3]=Math.round(u[3])}if(t!=null){t.width=r,t.height=s;let c=t.getContext("2d"),u=new ImageData(l,r,s);c.putImageData(u,0,0)}return n!==e&&n.dispose(),l}var K9=V({fromPixels_:Y5}),A2={};ze(A2,{prepareAndValidate:()=>J5});function J5(e,t){let n=e.shape.length,s=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(s<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${s}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[s-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[s-1]} vs. ${n}`);if(Ut(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let r=t.shape,a=r[r.length-1],o=1;for(let d=0;dd/c),1].slice(0,a);return[l,o,c,u]}var y2={};ze(y2,{calculateShapes:()=>Q5,validateInput:()=>b2,validateUpdateShape:()=>x2});function x2(e,t,n){let s=t.rank>1?t.shape[t.rank-1]:1,r=t.rank>1?t.rank-1:1,a=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${s}, and batchDim: ${r}.`;if(n.rank1?t.shape[s-1]:1,a=n.length,o=1;for(let d=r;dZ9,computeFlatOffset:()=>J9,computeOutShape:()=>e3,getNormalizedAxes:()=>r3,isSliceContinous:()=>Y9,maskToAxes:()=>Lh,parseSliceParams:()=>c3,sliceInfo:()=>Q9,startForAxis:()=>l3,startIndicesWithElidedDims:()=>a3,stopForAxis:()=>u3,stopIndicesWithElidedDims:()=>o3,stridesForAxis:()=>i3,stridesWithElidedDims:()=>t3});function Z9(e,t,n){let s=e.shape.length;O(s===t.length,()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`),O(s===n.length,()=>`Error in slice${s}D: Length of size ${n} must match the rank of the array (${s}).`);for(let r=0;r`Error in slice${s}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`)}function Lh(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function e3(e,t,n){let s=[];for(let r=0;r0){let h=t[0],f=n+1;u=a3(o,h,f,s,e),d=o3(i,h,f,r,e),p=t3(a,h,f,e)}else for(let h=0;h-1)a[i]=0;else{let l=n3(t,n,i),c=s[l];e&1<-1)a[i]=Number.MAX_SAFE_INTEGER;else{let l=n3(t,n,i),c=s[l];e&1<0?o=Number.MIN_SAFE_INTEGER:o=Number.MAX_SAFE_INTEGER);let l=s[r];return o<0&&(o+=l),o=_c(0,o,l-1),o}function u3(e,t,n,s,r,a){let o=t[r],i=n[r]||1;(e&1<0?o=Number.MAX_SAFE_INTEGER:o=Number.MIN_SAFE_INTEGER);let l=s[r];return o<0&&(o+=l),i>0?o=_c(0,o,l):o=_c(-1,o,l-1),o}function Y9(e,t,n){let s=n.length;for(let r=0;r1){s=r;break}for(let r=s+1;r0||n[r]!==e[r])return!1;return!0}function J9(e,t){let n=e.length>0?e[e.length-1]:1;for(let s=0;s{O(o!==-1,()=>"slice() does not support negative begin indexing.")});let a;return n==null?a=new Array(r).fill(-1):typeof n=="number"?a=[n,...new Array(r-1).fill(-1)]:n.lengtho>=0?o:(O(o===-1,()=>`Negative size values should be exactly -1 but got ${o} for the slice() size at index ${i}.`),e.shape[i]-s[i])),[s,a]}function Q9(e,t,n,s,r,a,o,i,l){let c=t.slice(),u=n.slice(),d=s;s==null&&(d=new Array(c.length));let p=Lh(o);if(p.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(o!==0&&i!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(o!==0&&l!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let h=e.length-c.length,f=Lh(i),m=e.slice();f.forEach(S=>{c[S]=0,u[S]=1,m.splice(S,0,1)});let{begin:g,end:A,strides:y}=r3(m,p,h,c,u,d,r,a,o);c=g,u=A,d=y;let x=Lh(l);x.forEach(S=>{u[S]=c[S]+1,d[S]=1});let b=e3(c,u,d),w=b.filter((S,E)=>x.indexOf(E)===-1);return{nonStrided:d.every(S=>S===1),$begin:c,$end:u,$strides:d,size:b,newShape:m,outShape:w}}var le={};ze(le,{Serializable:()=>d3,SerializationMap:()=>Xi,registerClass:()=>vo});var d3=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},Xi=class{constructor(){this.classNameMap={}}static getMap(){return Xi.instance==null&&(Xi.instance=new Xi),Xi.instance}static register(e){Xi.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function vo(e){O(e.className!=null,()=>"Class being registered does not have the static className property defined."),O(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),O(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Xi.register(e)}var p3={};ze(p3,{TEST_EPSILON_FLOAT16:()=>h3,encodeStrings:()=>f3,expectArrayBuffersEqual:()=>oR,expectArraysClose:()=>tR,expectArraysEqual:()=>sR,expectNumbersClose:()=>rR,expectPromiseToFail:()=>nR,expectValuesInRange:()=>aR,testEpsilon:()=>v2});var eR=.001,h3=.1;function tR(e,t,n){return n==null&&(n=v2()),w2(e,t,(s,r)=>k2(s,r,n))}function v2(){return B.backend.floatPrecision()===32?eR:h3}function w2(e,t,n){let s=!0;if((Dn(e)||Dn(t))&&(s=!1),Dn(e)&&Dn(t)&&(s=!0),s){let o=e.constructor.name,i=t.constructor.name;if(o!==i)throw new Error(`Arrays are of different type. Actual: ${o}. Expected: ${i}`)}if(Array.isArray(e)&&Array.isArray(t)){let o=Cr(e),i=Cr(t);if(!Gr(o,i))throw new Error(`Arrays have different shapes. Actual: [${o}]. Expected: [${i}]`)}let r=Dn(e)?e:ti(e),a=Dn(t)?t:ti(t);if(r.length!==a.length)throw new Error(`Arrays have different lengths actual: ${r.length} vs expected: ${a.length}.
Actual: ${r}.
Expected: ${a}.`);for(let o=0;ot.fail(),()=>t())}function sR(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return ba(e)||ba(e[0])||ba(t)||ba(t[0])?w2(e,n,(s,r)=>s==r):w2(e,t,(s,r)=>k2(s,r,0))}function rR(e,t,n){if(n==null&&(n=v2()),!k2(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function k2(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function aR(e,t,n){for(let s=0;sn)throw new Error(`Value out of range:${e[s]} low: ${t}, high: ${n}`)}function oR(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function f3(e){for(let t=0;tn.dispose())}function yn(e){return B.keep(e)}function dR(e){return B.time(e)}function g3(e){return B.setBackend(e)}function Wh(){return B.ready()}function ir(){return B.backendName}function pR(e){B.removeBackend(e)}function S2(e){return B.findBackend(e)}function hR(e){return B.findBackendFactory(e)}function Ki(e,t,n=1){return B.registerBackend(e,t,n)}function Tr(){return B.backend}function fR(e,t){K().setPlatform(e,t)}function mR(e,t){let n=D(e,"a","add"),s=D(t,"b","add");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Hr,r)}var ie=V({add_:mR});function gR(e,t){let n=D(e,"a","floorDiv"),s=D(t,"b","floorDiv");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Ma,r)}var C2=V({floorDiv_:gR});function AR(e,t){let n=D(e,"a","div"),s=D(t,"b","div");if([n,s]=Ft(n,s),n.dtype==="int32"&&s.dtype==="int32")return C2(n,s);let r={a:n,b:s},a={};return B.runKernel(_a,r,a)}var he=V({div_:AR});function yR(e,t){let n=D(e,"a","mul"),s=D(t,"b","mul");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Ka,r)}var W=V({mul_:yR});function xR(e){let t=D(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return B.runKernel(Mc,n)}else{let n={x:t};return B.runKernel(ni,n)}}var rn=V({abs_:xR});function bR(e){let n={x:D(e,"x","acos")};return B.runKernel(Vl,n)}var A3=V({acos_:bR});function vR(e){let n={x:D(e,"x","acosh")};return B.runKernel(Ul,n)}var y3=V({acosh_:vR});function wR(e){O(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),O(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((r,a)=>D(r,`tensors${a}`,"addN")),n=t[0];t.forEach(r=>{if(r.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!Gr(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let s=t;return B.runKernel(wa,s)}var Vh=V({addN_:wR});function kR(e,t=null,n=!1){let r={x:D(e,"x","all","bool")},a={axis:t,keepDims:n};return B.runKernel(Gl,r,a)}var T2=V({all_:kR});function IR(e,t=null,n=!1){let r={x:D(e,"x","any","bool")},a={axis:t,keepDims:n};return B.runKernel(Hl,r,a)}var Uh=V({any_:IR});function SR(e,t=0){let s={x:D(e,"x","argMax")},r={axis:t};return B.runKernel(ka,s,r)}var Hs=V({argMax_:SR});function CR(e,t=0){let s={x:D(e,"x","argMin")},r={axis:t};return B.runKernel(jl,s,r)}var x3=V({argMin_:CR});function TR(e){let n={x:D(e,"x","asin")};return B.runKernel(ql,n)}var b3=V({asin_:TR});function NR(e){let n={x:D(e,"x","asinh")};return B.runKernel(Xl,n)}var v3=V({asinh_:NR});function ER(e){let n={x:D(e,"x","atan")};return B.runKernel(Kl,n)}var w3=V({atan_:ER});function RR(e,t){let n=D(e,"a","atan2"),s=D(t,"b","atan2");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Yl,r)}var k3=V({atan2_:RR});function $R(e){let n={x:D(e,"x","atanh")};return B.runKernel(Zl,n)}var I3=V({atanh_:$R});function DR(e,t,n,s,r="NHWC",a){let o=e[3],i=[...t,o],l=T3(r);return ld(e,i,n,a,s,null,null,l)}function S3(e,t,n,s,r,a,o="channelsLast"){let[i,l]=Gh(t),c;if(o==="channelsLast")c=[i,l,e[3],e[3]];else if(o==="channelsFirst")c=[i,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return ld(e,c,n,s,r,a,!1,o)}function _R(e,t,n,s,r,a,o="NDHWC"){let[i,l,c]=E2(t),u,d;if(o==="NDHWC")d="channelsLast",u=[i,l,c,e[4],e[4]];else if(o==="NCDHW")d="channelsFirst",u=[i,l,c,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return C3(e,u,n,s,r,!1,d,a)}function ld(e,t,n,s,r,a,o=!1,i="channelsLast"){let[l,c,u,d]=[-1,-1,-1,-1];if(i==="channelsLast")[l,c,u,d]=e;else if(i==="channelsFirst")[l,d,c,u]=e;else throw new Error(`Unknown dataFormat ${i}`);let[p,h,,f]=t,[m,g]=Gh(n),[A,y]=Gh(s),x=bu(p,A),b=bu(h,y),{padInfo:w,outHeight:k,outWidth:S}=OR(r,c,u,m,g,x,b,a,i),E=o?f*d:f,P;return i==="channelsFirst"?P=[l,E,k,S]:i==="channelsLast"&&(P=[l,k,S,E]),{batchSize:l,dataFormat:i,inHeight:c,inWidth:u,inChannels:d,outHeight:k,outWidth:S,outChannels:E,padInfo:w,strideHeight:m,strideWidth:g,filterHeight:p,filterWidth:h,effectiveFilterHeight:x,effectiveFilterWidth:b,dilationHeight:A,dilationWidth:y,inShape:e,outShape:P,filterShape:t}}function C3(e,t,n,s,r,a=!1,o="channelsLast",i){let[l,c,u,d,p]=[-1,-1,-1,-1,-1];if(o==="channelsLast")[l,c,u,d,p]=e;else if(o==="channelsFirst")[l,p,c,u,d]=e;else throw new Error(`Unknown dataFormat ${o}`);let[h,f,m,,g]=t,[A,y,x]=E2(n),[b,w,k]=E2(s),S=bu(h,b),E=bu(f,w),P=bu(m,k),{padInfo:F,outDepth:R,outHeight:_,outWidth:T}=MR(r,c,u,d,A,y,x,S,E,P,i),M=a?g*p:g,U;return o==="channelsFirst"?U=[l,M,R,_,T]:o==="channelsLast"&&(U=[l,R,_,T,M]),{batchSize:l,dataFormat:o,inDepth:c,inHeight:u,inWidth:d,inChannels:p,outDepth:R,outHeight:_,outWidth:T,outChannels:M,padInfo:F,strideDepth:A,strideHeight:y,strideWidth:x,filterDepth:h,filterHeight:f,filterWidth:m,effectiveFilterDepth:S,effectiveFilterHeight:E,effectiveFilterWidth:P,dilationDepth:b,dilationHeight:w,dilationWidth:k,inShape:e,outShape:U,filterShape:t}}function PR(e,t,n,s,r){s==null&&(s=N2(e,t,n));let a=e[0],o=e[1],i=Zi((a-t+2*s)/n+1,r),l=Zi((o-t+2*s)/n+1,r);return[i,l]}function FR(e,t,n,s,r,a){r==null&&(r=N2(e,t,s));let o=e[0],i=e[1],l=e[2],c=Zi((o-t+2*r)/s+1,a),u=Zi((i-t+2*r)/s+1,a),d=Zi((l-t+2*r)/s+1,a);return[c,u,d,n]}function N2(e,t,n,s=1){let r=bu(t,s);return Math.floor((e[0]*(n-1)-n+r)/2)}function Gh(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function E2(e){return typeof e=="number"?[e,e,e]:e}function bu(e,t){return t<=1?e:e+(e-1)*(t-1)}function OR(e,t,n,s,r,a,o,i,l){let c,u,d;if(typeof e=="number"){c={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let h=PR([t,n],a,s,e,i);u=h[0],d=h[1]}else if(e==="same"){u=Math.ceil(t/s),d=Math.ceil(n/r);let p=Math.max(0,(u-1)*s+a-t),h=Math.max(0,(d-1)*r+o-n),f=Math.floor(p/2),m=p-f,g=Math.floor(h/2),A=h-g;c={top:f,bottom:m,left:g,right:A,type:"SAME"}}else if(e==="valid")c={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((t-a+1)/s),d=Math.ceil((n-o+1)/r);else if(typeof e=="object"){let p=l==="channelsLast"?e[1][0]:e[2][0],h=l==="channelsLast"?e[1][1]:e[2][1],f=l==="channelsLast"?e[2][0]:e[3][0],m=l==="channelsLast"?e[2][1]:e[3][1];c={top:p,bottom:h,left:f,right:m,type:p===0&&h===0&&f===0&&m===0?"VALID":"EXPLICIT"},u=Zi((t-a+p+h)/s+1,i),d=Zi((n-o+f+m)/r+1,i)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:c,outHeight:u,outWidth:d}}function MR(e,t,n,s,r,a,o,i,l,c,u){let d,p,h,f;if(typeof e=="number"){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let g=FR([t,n,s,1],i,1,r,e,u);p=g[0],h=g[1],f=g[2]}else if(e==="same"){p=Math.ceil(t/r),h=Math.ceil(n/a),f=Math.ceil(s/o);let m=(p-1)*r+i-t,g=(h-1)*a+l-n,A=(f-1)*o+c-s,y=Math.floor(m/2),x=m-y,b=Math.floor(g/2),w=g-b,k=Math.floor(A/2),S=A-k;d={top:b,bottom:w,left:k,right:S,front:y,back:x,type:"SAME"}}else if(e==="valid")d={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-i+1)/r),h=Math.ceil((n-l+1)/a),f=Math.ceil((s-c+1)/o);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:d,outDepth:p,outHeight:h,outWidth:f}}function Zi(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function wo(e){let[t,n,s]=Gh(e);return t===1&&n===1&&s===1}function Nr(e,t){return wo(e)||wo(t)}function T3(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function zR(e,t){let s={x:D(e,"x","reshape","string_or_numeric")},r={shape:t};return B.runKernel(Ti,s,r)}var G=V({reshape_:zR});function LR(e,t,n,s,r){let a=D(e,"x","avgPool","float32"),o=1;O(Nr(n,o),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);let i=a,l=!1;a.rank===3&&(l=!0,i=G(a,[1,a.shape[0],a.shape[1],a.shape[2]])),O(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),r!=null&&O(mn(s),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r},d=B.runKernel(Ia,c,u);return d=de(d,a.dtype),l?G(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Hh=V({avgPool_:LR});function BR(e,t,n,s,r,a="NDHWC"){let o=D(e,"x","avgPool3d","float32"),i=o,l=!1;o.rank===4&&(l=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),O(i.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`),O(a==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),r!=null&&O(mn(s),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},d=B.runKernel(Fc,c,u);return d=de(d,i.dtype),l?G(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var R2=V({avgPool3d_:BR});function WR(e,t=0){O(e.length>=1,()=>"Pass at least one tensor to concat");let n=ad(e,"tensors","concat","string_or_numeric");if(n[0].dtype==="complex64"&&n.forEach(a=>{if(a.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
- with dtype ${a.dtype}. `)}),n.length===1)return or(n[0]);let s=n,r={axis:t};return B.runKernel(ri,s,r)}var It=V({concat_:WR});function VR(e){let n={x:D(e,"x","sigmoid","float32")};return B.runKernel(ro,n)}var hs=V({sigmoid_:VR});function UR(e,t,n){let s=D(e,"x","slice","string_or_numeric");if(s.rank===0)throw new Error("Slicing scalar is not possible");let r={x:s},a={begin:t,size:n};return B.runKernel(Di,r,a)}var _e=V({slice_:UR});function GR(e){let n={x:D(e,"x","tanh","float32")};return B.runKernel(co,n)}var vu=V({tanh_:GR});function HR(e,t,n,s,r,a){let o=D(e,"forgetBias","basicLSTMCell"),i=D(t,"lstmKernel","basicLSTMCell"),l=D(n,"lstmBias","basicLSTMCell"),c=D(s,"data","basicLSTMCell"),u=D(r,"c","basicLSTMCell"),d=D(a,"h","basicLSTMCell"),p=It([c,d],1),h=He(p,i),f=ie(h,l),m=f.shape[0],g=f.shape[1]/4,A=[m,g],y=_e(f,[0,0],A),x=_e(f,[0,g],A),b=_e(f,[0,g*2],A),w=_e(f,[0,g*3],A),k=ie(W(hs(y),vu(x)),W(u,hs(ie(o,b)))),S=W(vu(k),hs(w));return[k,S]}var jR=V({basicLSTMCell_:HR});function qR(e,t,n){let s=D(e,"x","batchToSpaceND"),r=t.reduce((i,l)=>i*l);O(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),O(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),O(s.shape[0]%r==0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`);let a={x:s},o={blockShape:t,crops:n};return B.runKernel(si,a,o)}var jh=V({batchToSpaceND_:qR});function XR(e){let t;return e.rank===0||e.rank===1?t=G(e,[1,1,1,e.size]):e.rank===2?t=G(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function KR(e,t,n,s,r,a){a==null&&(a=.001);let o=D(e,"x","batchNorm"),i=D(t,"mean","batchNorm"),l=D(n,"variance","batchNorm"),c;r!=null&&(c=D(r,"scale","batchNorm"));let u;s!=null&&(u=D(s,"offset","batchNorm")),O(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),O(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),O(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let p={x:XR(o),scale:c,offset:u,mean:i,variance:l},h={varianceEpsilon:a},f=B.runKernel(za,p,h);return G(f,o.shape)}var wu=V({batchNorm_:KR});function ZR(e,t,n,s,r,a){let o=D(e,"x","batchNorm"),i=D(t,"mean","batchNorm"),l=D(n,"variance","batchNorm"),c;r!=null&&(c=D(r,"scale","batchNorm"));let u;return s!=null&&(u=D(s,"offset","batchNorm")),O(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),O(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),O(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),c!=null&&O(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),u!=null&&O(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`),wu(o,i,l,u,c,a)}var N3=V({batchNorm2d_:ZR});function YR(e,t,n,s,r,a){let o=D(e,"x","batchNorm"),i=D(t,"mean","batchNorm"),l=D(n,"variance","batchNorm"),c;r!=null&&(c=D(r,"scale","batchNorm"));let u;return s!=null&&(u=D(s,"offset","batchNorm")),O(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),O(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),O(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),c!=null&&O(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`),u!=null&&O(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`),wu(o,i,l,u,c,a)}var E3=V({batchNorm3d_:YR});function JR(e,t,n,s,r,a){let o=D(e,"x","batchNorm"),i=D(t,"mean","batchNorm"),l=D(n,"variance","batchNorm"),c;r!=null&&(c=D(r,"scale","batchNorm"));let u;return s!=null&&(u=D(s,"offset","batchNorm")),O(o.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),O(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),O(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),c!=null&&O(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`),u!=null&&O(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`),wu(o,i,l,u,c,a)}var R3=V({batchNorm4d_:JR});function QR(e,t,n){let s=D(e,"x","bincount"),r=D(t,"weights","bincount");O(s.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`),O(n>=0,()=>`size must be non-negative, but got ${n}.`),O(r.size===s.size||r.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${r.shape}.`);let a={x:s,weights:r},o={size:n};return B.runKernel(nh,a,o)}var $2=V({bincount_:QR});function e$(e,t){let n=D(e,"s0","broadcastArgs","int32"),s=D(t,"s1","broadcastArgs","int32");if(n.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(s.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${s.rank}`);let r={s0:n,s1:s};return B.runKernel(sh,r)}var $3=V({broadcastArgs_:e$});function t$(e,t){let n=D(e,"broadcastTo","x"),s=n.shape;if(t.some(c=>!(c>0)||c%1!=0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.lengthn.rank){let c=n.shape.slice();for(;c.length=0;c--)if(r[c]===t[c])a[c]=1;else if(n.shape[c]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);if(a.map((c,u)=>c>1?u:-1).filter(c=>c>=0).length===0)return or(n);let i={x:n},l={reps:a};return B.runKernel(qr,i,l)}var ud=V({broadcastTo_:t$});function n$(e){let n={x:D(e,"x","ceil","float32")};return B.runKernel(Ta,n)}var D3=V({ceil_:n$});function s$(e,t,n){let s=D(e,"x","clipByValue");O(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);let r={x:s},a={clipValueMin:t,clipValueMax:n};return B.runKernel(jr,r,a)}var fs=V({clipByValue_:s$});function r$(e){return It(e,0)}var _3=V({concat1d_:r$});function a$(e,t){return It(e,t)}var ku=V({concat2d_:a$});function o$(e,t){return It(e,t)}var P3=V({concat3d_:o$});function i$(e,t){return It(e,t)}var F3=V({concat4d_:i$});function l$(e,t,n,s,r="NHWC",a=[1,1],o){let i=D(e,"x","conv2d","float32"),l=D(t,"filter","conv2d","float32"),c=i,u=!1;i.rank===3&&(u=!0,c=G(i,[1,i.shape[0],i.shape[1],i.shape[2]])),O(c.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`),O(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),o!=null&&O(mn(s),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let d=r==="NHWC"?c.shape[3]:c.shape[1];O(d===l.shape[2],()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${l.shape[2]}.`),O(Nr(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let p={x:c,filter:l},h={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},f=B.runKernel(Na,p,h);return u?G(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var ko=V({conv2d_:l$});function u$(e,t,n,s,r="NWC",a=1,o){let i=D(e,"x","conv1d"),l=D(t,"filter","conv1d"),c=i,u=!1;i.rank===2&&(u=!0,c=G(i,[1,i.shape[0],i.shape[1]])),O(c.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`),O(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),o!=null&&O(mn(s),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`),O(c.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`),O(Nr(n,a),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`),O(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);let d=G(l,[1,l.shape[0],l.shape[1],l.shape[2]]),p=G(c,[c.shape[0],1,c.shape[1],c.shape[2]]),g=ko(p,d,[1,n],s,"NHWC",[1,a],o);return u?G(g,[g.shape[2],g.shape[3]]):G(g,[g.shape[0],g.shape[2],g.shape[3]])}var D2=V({conv1d_:u$});function c$(e,t,n,s,r,a="NHWC",o){O(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let i=e,l=t,c=!1;t.rank===3&&(c=!0,l=G(t,[1,t.shape[0],t.shape[1],t.shape[2]]),i=[1,e[0],e[1],e[2]]),O(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),O(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),O(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);let u=a==="NHWC"?i[3]:i[1],d=a==="NHWC"?l.shape[3]:l.shape[1];O(u===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[2]}.`),O(d===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${n.shape[3]}.`),o!=null&&O(mn(r),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let p={dy:l,filter:n},h={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,inputShape:i},f=B.runKernel(Ea,p,h);return c?G(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var _2=V({conv2DBackpropInput_:c$});function d$(e,t,n,s,r,a){let o=D(e,"x","conv2dTranspose"),i=D(t,"filter","conv2dTranspose");return _2(n,o,i,s,r,"NHWC",a)}var P2=V({conv2dTranspose_:d$});function p$(e,t,n,s,r="NDHWC",a=[1,1,1]){let o=D(e,"x","conv3d"),i=D(t,"filter","conv3d"),l=o,c=!1;o.rank===4&&(c=!0,l=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),O(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),O(i.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`),O(l.shape[4]===i.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${i.shape[3]}.`),O(Nr(n,a),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),O(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`);let u={x:l,filter:i},d={strides:n,pad:s,dataFormat:r,dilations:a},p=B.runKernel(zc,u,d);return c?G(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var F2=V({conv3d_:p$});function h$(e,t,n,s,r){O(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let a=e,o=t,i=!1;t.rank===4&&(i=!0,o=G(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),a=[1,e[0],e[1],e[2],e[3]]);let l=a[4],c=o.shape[4];O(a.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`),O(o.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),O(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),O(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),O(c===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[4]}.`);let u={dy:o,filter:n},d={pad:r,strides:s,inputShape:a},p=B.runKernel(oh,u,d);return i?G(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var O3=V({conv3DBackpropInput_:h$});function f$(e,t,n,s,r){let a=D(e,"x","conv3dTranspose"),o=D(t,"filter","conv3dTranspose");return O3(n,a,o,s,r)}var M3=V({conv3dTranspose_:f$});function m$(e){let n={x:D(e,"x","cos","float32")};return B.runKernel(Ra,n)}var qh=V({cos_:m$});function g$(e){let n={x:D(e,"x","cosh","float32")};return B.runKernel($a,n)}var O2=V({cosh_:g$});function A$(e,t=0,n=!1,s=!1){let a={x:D(e,"x","cumsum")},o={axis:t,exclusive:n,reverse:s};return B.runKernel(ai,a,o)}var M2=V({cumsum_:A$});function y$(e,t,n,s=!1){let r=D(e,"x","denseBincount"),a=D(t,"weights","denseBincount");O(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),O(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),O(n>=0,()=>`size must be non-negative, but got ${n}.`),O(a.size===r.size||a.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${a.shape}.`);let o={x:r,weights:a},i={size:n,binaryOutput:s};return B.runKernel(ih,o,i)}var z3=V({denseBincount_:y$});function x$(e,t,n="NHWC"){let s=D(e,"x","depthToSpace","float32"),r=n==="NHWC"?s.shape[1]:s.shape[2],a=n==="NHWC"?s.shape[2]:s.shape[3],o=n==="NHWC"?s.shape[3]:s.shape[1];O(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),O(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying
+Expected: ${a}.`)}}function nR(e,t){e().then(()=>t.fail(),()=>t())}function sR(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return ba(e)||ba(e[0])||ba(t)||ba(t[0])?w2(e,n,(s,r)=>s==r):w2(e,t,(s,r)=>k2(s,r,0))}function rR(e,t,n){if(n==null&&(n=v2()),!k2(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function k2(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function aR(e,t,n){for(let s=0;sn)throw new Error(`Value out of range:${e[s]} low: ${t}, high: ${n}`)}function oR(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function f3(e){for(let t=0;tn.dispose())}function yn(e){return B.keep(e)}function dR(e){return B.time(e)}function g3(e){return B.setBackend(e)}function Wh(){return B.ready()}function ir(){return B.backendName}function pR(e){B.removeBackend(e)}function S2(e){return B.findBackend(e)}function hR(e){return B.findBackendFactory(e)}function Ki(e,t,n=1){return B.registerBackend(e,t,n)}function Tr(){return B.backend}function fR(e,t){K().setPlatform(e,t)}function mR(e,t){let n=_(e,"a","add"),s=_(t,"b","add");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Hr,r)}var ie=V({add_:mR});function gR(e,t){let n=_(e,"a","floorDiv"),s=_(t,"b","floorDiv");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Ma,r)}var C2=V({floorDiv_:gR});function AR(e,t){let n=_(e,"a","div"),s=_(t,"b","div");if([n,s]=Ft(n,s),n.dtype==="int32"&&s.dtype==="int32")return C2(n,s);let r={a:n,b:s},a={};return B.runKernel(_a,r,a)}var fe=V({div_:AR});function yR(e,t){let n=_(e,"a","mul"),s=_(t,"b","mul");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Ka,r)}var W=V({mul_:yR});function xR(e){let t=_(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return B.runKernel(Mc,n)}else{let n={x:t};return B.runKernel(ni,n)}}var rn=V({abs_:xR});function bR(e){let n={x:_(e,"x","acos")};return B.runKernel(Vl,n)}var A3=V({acos_:bR});function vR(e){let n={x:_(e,"x","acosh")};return B.runKernel(Ul,n)}var y3=V({acosh_:vR});function wR(e){O(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),O(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((r,a)=>_(r,`tensors${a}`,"addN")),n=t[0];t.forEach(r=>{if(r.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!Gr(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let s=t;return B.runKernel(wa,s)}var Vh=V({addN_:wR});function kR(e,t=null,n=!1){let r={x:_(e,"x","all","bool")},a={axis:t,keepDims:n};return B.runKernel(Gl,r,a)}var T2=V({all_:kR});function IR(e,t=null,n=!1){let r={x:_(e,"x","any","bool")},a={axis:t,keepDims:n};return B.runKernel(Hl,r,a)}var Uh=V({any_:IR});function SR(e,t=0){let s={x:_(e,"x","argMax")},r={axis:t};return B.runKernel(ka,s,r)}var Hs=V({argMax_:SR});function CR(e,t=0){let s={x:_(e,"x","argMin")},r={axis:t};return B.runKernel(jl,s,r)}var x3=V({argMin_:CR});function TR(e){let n={x:_(e,"x","asin")};return B.runKernel(ql,n)}var b3=V({asin_:TR});function NR(e){let n={x:_(e,"x","asinh")};return B.runKernel(Xl,n)}var v3=V({asinh_:NR});function ER(e){let n={x:_(e,"x","atan")};return B.runKernel(Kl,n)}var w3=V({atan_:ER});function RR(e,t){let n=_(e,"a","atan2"),s=_(t,"b","atan2");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Yl,r)}var k3=V({atan2_:RR});function $R(e){let n={x:_(e,"x","atanh")};return B.runKernel(Zl,n)}var I3=V({atanh_:$R});function DR(e,t,n,s,r="NHWC",a){let o=e[3],i=[...t,o],l=T3(r);return ld(e,i,n,a,s,null,null,l)}function S3(e,t,n,s,r,a,o="channelsLast"){let[i,l]=Gh(t),c;if(o==="channelsLast")c=[i,l,e[3],e[3]];else if(o==="channelsFirst")c=[i,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return ld(e,c,n,s,r,a,!1,o)}function _R(e,t,n,s,r,a,o="NDHWC"){let[i,l,c]=E2(t),u,d;if(o==="NDHWC")d="channelsLast",u=[i,l,c,e[4],e[4]];else if(o==="NCDHW")d="channelsFirst",u=[i,l,c,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return C3(e,u,n,s,r,!1,d,a)}function ld(e,t,n,s,r,a,o=!1,i="channelsLast"){let[l,c,u,d]=[-1,-1,-1,-1];if(i==="channelsLast")[l,c,u,d]=e;else if(i==="channelsFirst")[l,d,c,u]=e;else throw new Error(`Unknown dataFormat ${i}`);let[p,h,,f]=t,[m,g]=Gh(n),[A,y]=Gh(s),x=bu(p,A),b=bu(h,y),{padInfo:w,outHeight:k,outWidth:S}=OR(r,c,u,m,g,x,b,a,i),E=o?f*d:f,$;return i==="channelsFirst"?$=[l,E,k,S]:i==="channelsLast"&&($=[l,k,S,E]),{batchSize:l,dataFormat:i,inHeight:c,inWidth:u,inChannels:d,outHeight:k,outWidth:S,outChannels:E,padInfo:w,strideHeight:m,strideWidth:g,filterHeight:p,filterWidth:h,effectiveFilterHeight:x,effectiveFilterWidth:b,dilationHeight:A,dilationWidth:y,inShape:e,outShape:$,filterShape:t}}function C3(e,t,n,s,r,a=!1,o="channelsLast",i){let[l,c,u,d,p]=[-1,-1,-1,-1,-1];if(o==="channelsLast")[l,c,u,d,p]=e;else if(o==="channelsFirst")[l,p,c,u,d]=e;else throw new Error(`Unknown dataFormat ${o}`);let[h,f,m,,g]=t,[A,y,x]=E2(n),[b,w,k]=E2(s),S=bu(h,b),E=bu(f,w),$=bu(m,k),{padInfo:F,outDepth:R,outHeight:P,outWidth:T}=MR(r,c,u,d,A,y,x,S,E,$,i),M=a?g*p:g,U;return o==="channelsFirst"?U=[l,M,R,P,T]:o==="channelsLast"&&(U=[l,R,P,T,M]),{batchSize:l,dataFormat:o,inDepth:c,inHeight:u,inWidth:d,inChannels:p,outDepth:R,outHeight:P,outWidth:T,outChannels:M,padInfo:F,strideDepth:A,strideHeight:y,strideWidth:x,filterDepth:h,filterHeight:f,filterWidth:m,effectiveFilterDepth:S,effectiveFilterHeight:E,effectiveFilterWidth:$,dilationDepth:b,dilationHeight:w,dilationWidth:k,inShape:e,outShape:U,filterShape:t}}function PR(e,t,n,s,r){s==null&&(s=N2(e,t,n));let a=e[0],o=e[1],i=Zi((a-t+2*s)/n+1,r),l=Zi((o-t+2*s)/n+1,r);return[i,l]}function FR(e,t,n,s,r,a){r==null&&(r=N2(e,t,s));let o=e[0],i=e[1],l=e[2],c=Zi((o-t+2*r)/s+1,a),u=Zi((i-t+2*r)/s+1,a),d=Zi((l-t+2*r)/s+1,a);return[c,u,d,n]}function N2(e,t,n,s=1){let r=bu(t,s);return Math.floor((e[0]*(n-1)-n+r)/2)}function Gh(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function E2(e){return typeof e=="number"?[e,e,e]:e}function bu(e,t){return t<=1?e:e+(e-1)*(t-1)}function OR(e,t,n,s,r,a,o,i,l){let c,u,d;if(typeof e=="number"){c={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let h=PR([t,n],a,s,e,i);u=h[0],d=h[1]}else if(e==="same"){u=Math.ceil(t/s),d=Math.ceil(n/r);let p=Math.max(0,(u-1)*s+a-t),h=Math.max(0,(d-1)*r+o-n),f=Math.floor(p/2),m=p-f,g=Math.floor(h/2),A=h-g;c={top:f,bottom:m,left:g,right:A,type:"SAME"}}else if(e==="valid")c={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((t-a+1)/s),d=Math.ceil((n-o+1)/r);else if(typeof e=="object"){let p=l==="channelsLast"?e[1][0]:e[2][0],h=l==="channelsLast"?e[1][1]:e[2][1],f=l==="channelsLast"?e[2][0]:e[3][0],m=l==="channelsLast"?e[2][1]:e[3][1];c={top:p,bottom:h,left:f,right:m,type:p===0&&h===0&&f===0&&m===0?"VALID":"EXPLICIT"},u=Zi((t-a+p+h)/s+1,i),d=Zi((n-o+f+m)/r+1,i)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:c,outHeight:u,outWidth:d}}function MR(e,t,n,s,r,a,o,i,l,c,u){let d,p,h,f;if(typeof e=="number"){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let g=FR([t,n,s,1],i,1,r,e,u);p=g[0],h=g[1],f=g[2]}else if(e==="same"){p=Math.ceil(t/r),h=Math.ceil(n/a),f=Math.ceil(s/o);let m=(p-1)*r+i-t,g=(h-1)*a+l-n,A=(f-1)*o+c-s,y=Math.floor(m/2),x=m-y,b=Math.floor(g/2),w=g-b,k=Math.floor(A/2),S=A-k;d={top:b,bottom:w,left:k,right:S,front:y,back:x,type:"SAME"}}else if(e==="valid")d={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-i+1)/r),h=Math.ceil((n-l+1)/a),f=Math.ceil((s-c+1)/o);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:d,outDepth:p,outHeight:h,outWidth:f}}function Zi(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function wo(e){let[t,n,s]=Gh(e);return t===1&&n===1&&s===1}function Nr(e,t){return wo(e)||wo(t)}function T3(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function zR(e,t){let s={x:_(e,"x","reshape","string_or_numeric")},r={shape:t};return B.runKernel(Ti,s,r)}var G=V({reshape_:zR});function LR(e,t,n,s,r){let a=_(e,"x","avgPool","float32"),o=1;O(Nr(n,o),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);let i=a,l=!1;a.rank===3&&(l=!0,i=G(a,[1,a.shape[0],a.shape[1],a.shape[2]])),O(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),r!=null&&O(mn(s),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r},d=B.runKernel(Ia,c,u);return d=he(d,a.dtype),l?G(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Hh=V({avgPool_:LR});function BR(e,t,n,s,r,a="NDHWC"){let o=_(e,"x","avgPool3d","float32"),i=o,l=!1;o.rank===4&&(l=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),O(i.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`),O(a==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),r!=null&&O(mn(s),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},d=B.runKernel(Fc,c,u);return d=he(d,i.dtype),l?G(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var R2=V({avgPool3d_:BR});function WR(e,t=0){O(e.length>=1,()=>"Pass at least one tensor to concat");let n=ad(e,"tensors","concat","string_or_numeric");if(n[0].dtype==="complex64"&&n.forEach(a=>{if(a.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
+ with dtype ${a.dtype}. `)}),n.length===1)return or(n[0]);let s=n,r={axis:t};return B.runKernel(ri,s,r)}var It=V({concat_:WR});function VR(e){let n={x:_(e,"x","sigmoid","float32")};return B.runKernel(ro,n)}var hs=V({sigmoid_:VR});function UR(e,t,n){let s=_(e,"x","slice","string_or_numeric");if(s.rank===0)throw new Error("Slicing scalar is not possible");let r={x:s},a={begin:t,size:n};return B.runKernel(Di,r,a)}var _e=V({slice_:UR});function GR(e){let n={x:_(e,"x","tanh","float32")};return B.runKernel(co,n)}var vu=V({tanh_:GR});function HR(e,t,n,s,r,a){let o=_(e,"forgetBias","basicLSTMCell"),i=_(t,"lstmKernel","basicLSTMCell"),l=_(n,"lstmBias","basicLSTMCell"),c=_(s,"data","basicLSTMCell"),u=_(r,"c","basicLSTMCell"),d=_(a,"h","basicLSTMCell"),p=It([c,d],1),h=He(p,i),f=ie(h,l),m=f.shape[0],g=f.shape[1]/4,A=[m,g],y=_e(f,[0,0],A),x=_e(f,[0,g],A),b=_e(f,[0,g*2],A),w=_e(f,[0,g*3],A),k=ie(W(hs(y),vu(x)),W(u,hs(ie(o,b)))),S=W(vu(k),hs(w));return[k,S]}var jR=V({basicLSTMCell_:HR});function qR(e,t,n){let s=_(e,"x","batchToSpaceND"),r=t.reduce((i,l)=>i*l);O(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),O(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),O(s.shape[0]%r==0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`);let a={x:s},o={blockShape:t,crops:n};return B.runKernel(si,a,o)}var jh=V({batchToSpaceND_:qR});function XR(e){let t;return e.rank===0||e.rank===1?t=G(e,[1,1,1,e.size]):e.rank===2?t=G(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function KR(e,t,n,s,r,a){a==null&&(a=.001);let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),c;r!=null&&(c=_(r,"scale","batchNorm"));let u;s!=null&&(u=_(s,"offset","batchNorm")),O(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),O(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),O(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let p={x:XR(o),scale:c,offset:u,mean:i,variance:l},h={varianceEpsilon:a},f=B.runKernel(za,p,h);return G(f,o.shape)}var wu=V({batchNorm_:KR});function ZR(e,t,n,s,r,a){let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),c;r!=null&&(c=_(r,"scale","batchNorm"));let u;return s!=null&&(u=_(s,"offset","batchNorm")),O(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),O(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),O(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),c!=null&&O(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),u!=null&&O(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`),wu(o,i,l,u,c,a)}var N3=V({batchNorm2d_:ZR});function YR(e,t,n,s,r,a){let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),c;r!=null&&(c=_(r,"scale","batchNorm"));let u;return s!=null&&(u=_(s,"offset","batchNorm")),O(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),O(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),O(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),c!=null&&O(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`),u!=null&&O(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`),wu(o,i,l,u,c,a)}var E3=V({batchNorm3d_:YR});function JR(e,t,n,s,r,a){let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),c;r!=null&&(c=_(r,"scale","batchNorm"));let u;return s!=null&&(u=_(s,"offset","batchNorm")),O(o.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),O(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),O(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),c!=null&&O(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`),u!=null&&O(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`),wu(o,i,l,u,c,a)}var R3=V({batchNorm4d_:JR});function QR(e,t,n){let s=_(e,"x","bincount"),r=_(t,"weights","bincount");O(s.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`),O(n>=0,()=>`size must be non-negative, but got ${n}.`),O(r.size===s.size||r.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${r.shape}.`);let a={x:s,weights:r},o={size:n};return B.runKernel(nh,a,o)}var $2=V({bincount_:QR});function e$(e,t){let n=_(e,"s0","broadcastArgs","int32"),s=_(t,"s1","broadcastArgs","int32");if(n.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(s.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${s.rank}`);let r={s0:n,s1:s};return B.runKernel(sh,r)}var $3=V({broadcastArgs_:e$});function t$(e,t){let n=_(e,"broadcastTo","x"),s=n.shape;if(t.some(c=>!(c>0)||c%1!=0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.lengthn.rank){let c=n.shape.slice();for(;c.length=0;c--)if(r[c]===t[c])a[c]=1;else if(n.shape[c]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);if(a.map((c,u)=>c>1?u:-1).filter(c=>c>=0).length===0)return or(n);let i={x:n},l={reps:a};return B.runKernel(qr,i,l)}var ud=V({broadcastTo_:t$});function n$(e){let n={x:_(e,"x","ceil","float32")};return B.runKernel(Ta,n)}var D3=V({ceil_:n$});function s$(e,t,n){let s=_(e,"x","clipByValue");O(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);let r={x:s},a={clipValueMin:t,clipValueMax:n};return B.runKernel(jr,r,a)}var fs=V({clipByValue_:s$});function r$(e){return It(e,0)}var _3=V({concat1d_:r$});function a$(e,t){return It(e,t)}var ku=V({concat2d_:a$});function o$(e,t){return It(e,t)}var P3=V({concat3d_:o$});function i$(e,t){return It(e,t)}var F3=V({concat4d_:i$});function l$(e,t,n,s,r="NHWC",a=[1,1],o){let i=_(e,"x","conv2d","float32"),l=_(t,"filter","conv2d","float32"),c=i,u=!1;i.rank===3&&(u=!0,c=G(i,[1,i.shape[0],i.shape[1],i.shape[2]])),O(c.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`),O(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),o!=null&&O(mn(s),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let d=r==="NHWC"?c.shape[3]:c.shape[1];O(d===l.shape[2],()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${l.shape[2]}.`),O(Nr(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let p={x:c,filter:l},h={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},f=B.runKernel(Na,p,h);return u?G(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var ko=V({conv2d_:l$});function u$(e,t,n,s,r="NWC",a=1,o){let i=_(e,"x","conv1d"),l=_(t,"filter","conv1d"),c=i,u=!1;i.rank===2&&(u=!0,c=G(i,[1,i.shape[0],i.shape[1]])),O(c.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`),O(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),o!=null&&O(mn(s),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`),O(c.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`),O(Nr(n,a),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`),O(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);let d=G(l,[1,l.shape[0],l.shape[1],l.shape[2]]),p=G(c,[c.shape[0],1,c.shape[1],c.shape[2]]),g=ko(p,d,[1,n],s,"NHWC",[1,a],o);return u?G(g,[g.shape[2],g.shape[3]]):G(g,[g.shape[0],g.shape[2],g.shape[3]])}var D2=V({conv1d_:u$});function c$(e,t,n,s,r,a="NHWC",o){O(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let i=e,l=t,c=!1;t.rank===3&&(c=!0,l=G(t,[1,t.shape[0],t.shape[1],t.shape[2]]),i=[1,e[0],e[1],e[2]]),O(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),O(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),O(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);let u=a==="NHWC"?i[3]:i[1],d=a==="NHWC"?l.shape[3]:l.shape[1];O(u===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[2]}.`),O(d===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${n.shape[3]}.`),o!=null&&O(mn(r),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let p={dy:l,filter:n},h={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,inputShape:i},f=B.runKernel(Ea,p,h);return c?G(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var _2=V({conv2DBackpropInput_:c$});function d$(e,t,n,s,r,a){let o=_(e,"x","conv2dTranspose"),i=_(t,"filter","conv2dTranspose");return _2(n,o,i,s,r,"NHWC",a)}var P2=V({conv2dTranspose_:d$});function p$(e,t,n,s,r="NDHWC",a=[1,1,1]){let o=_(e,"x","conv3d"),i=_(t,"filter","conv3d"),l=o,c=!1;o.rank===4&&(c=!0,l=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),O(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),O(i.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`),O(l.shape[4]===i.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${i.shape[3]}.`),O(Nr(n,a),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),O(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`);let u={x:l,filter:i},d={strides:n,pad:s,dataFormat:r,dilations:a},p=B.runKernel(zc,u,d);return c?G(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var F2=V({conv3d_:p$});function h$(e,t,n,s,r){O(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let a=e,o=t,i=!1;t.rank===4&&(i=!0,o=G(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),a=[1,e[0],e[1],e[2],e[3]]);let l=a[4],c=o.shape[4];O(a.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`),O(o.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),O(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),O(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),O(c===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[4]}.`);let u={dy:o,filter:n},d={pad:r,strides:s,inputShape:a},p=B.runKernel(oh,u,d);return i?G(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var O3=V({conv3DBackpropInput_:h$});function f$(e,t,n,s,r){let a=_(e,"x","conv3dTranspose"),o=_(t,"filter","conv3dTranspose");return O3(n,a,o,s,r)}var M3=V({conv3dTranspose_:f$});function m$(e){let n={x:_(e,"x","cos","float32")};return B.runKernel(Ra,n)}var qh=V({cos_:m$});function g$(e){let n={x:_(e,"x","cosh","float32")};return B.runKernel($a,n)}var O2=V({cosh_:g$});function A$(e,t=0,n=!1,s=!1){let a={x:_(e,"x","cumsum")},o={axis:t,exclusive:n,reverse:s};return B.runKernel(ai,a,o)}var M2=V({cumsum_:A$});function y$(e,t,n,s=!1){let r=_(e,"x","denseBincount"),a=_(t,"weights","denseBincount");O(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),O(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),O(n>=0,()=>`size must be non-negative, but got ${n}.`),O(a.size===r.size||a.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${a.shape}.`);let o={x:r,weights:a},i={size:n,binaryOutput:s};return B.runKernel(ih,o,i)}var z3=V({denseBincount_:y$});function x$(e,t,n="NHWC"){let s=_(e,"x","depthToSpace","float32"),r=n==="NHWC"?s.shape[1]:s.shape[2],a=n==="NHWC"?s.shape[2]:s.shape[3],o=n==="NHWC"?s.shape[3]:s.shape[1];O(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),O(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${r} and ${t} for depthToSpace with input shape
${s.shape}`),O(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${a} and ${t} for depthToSpace with input shape
- ${s.shape}`),O(o%(t*t)==0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${s.shape}`);let i={x:s},l={blockSize:t,dataFormat:n};return B.runKernel(ii,i,l)}var L3=V({depthToSpace_:x$});function b$(e,t,n,s,r="NHWC",a=[1,1],o){let i=D(e,"x","depthwiseConv2d","float32"),l=D(t,"filter","depthwiseConv2d","float32"),c=i,u=!1;i.rank===3&&(u=!0,c=G(i,[1,i.shape[0],i.shape[1],i.shape[2]])),O(c.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),O(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),O(c.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),o!=null&&O(mn(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let d={x:c,filter:l},p={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},h=B.runKernel(Da,d,p);return u?G(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var cd=V({depthwiseConv2d_:b$});function v$(e){let n={x:D(e,"x","diag")};return B.runKernel(ch,n)}var w$=V({diag_:v$});function k$(e,t,n,s,r=[1,1],a="NHWC"){let o=D(e,"x","dilation2d"),i=D(t,"filter","dilation2d");O(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),O(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),O(a==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);let l=o,c=!1;o.rank===3&&(l=G(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=!0);let u={x:l,filter:i},d={strides:n,pad:s,dilations:r},p=B.runKernel(Lc,u,d);return c?G(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var B3=V({dilation2d_:k$});function I$(e,t){let n=e.length,s=[];for(let r=0;r1&&o===1&&s.unshift(a)}return s}function an(e,t){let n=[];for(let s=0;s1)&&n.unshift(a)}return n}function St(e,t){let n=[],s=Math.max(e.length,t.length);for(let r=0;r`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${s.rank}.`);let r=n.rank===1?n.size:n.shape[1],a=s.rank===1?s.size:s.shape[0];if(O(r===a,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${a}.`),n.rank===1&&s.rank===1){let o=G(n,[1,-1]),i=G(s,[-1,1]),l=He(o,i);return G(l,[])}else if(n.rank===1&&s.rank===2){let o=G(n,[1,-1]),i=G(s,[s.shape[0],s.shape[1]]),l=He(o,i);return G(l,[l.size])}else if(n.rank===2&&s.rank===1){let o=G(s,[-1,1]),i=He(n,o);return G(i,[i.size])}else{let o=G(s,[s.shape[0],s.shape[1]]);return He(n,o)}}var R$=V({dot_:E$});function $$(e,...t){let n=t.map((r,a)=>D(r,`tensors${a}`,"einsum")),s={equation:e};return B.runKernel(Bc,n,s)}var V3=V({einsum_:$$});function D$(e){let n={x:D(e,"x","elu","float32")};return B.runKernel(Pa,n)}var dd=V({elu_:D$});function _$(e){let t=D(e,"x","erf");O(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=de(t,"float32"));let n={x:t};return B.runKernel(Jl,n)}var U3=V({erf_:_$});function P$(e){let n={x:D(e,"x","exp")};return B.runKernel(Fa,n)}var Ts=V({exp_:P$});function F$(e,t=0){let n=D(e,"x","expandDims","string_or_numeric");O(t<=n.rank,()=>"Axis must be <= rank of the tensor");let s={input:n},r={dim:t};return B.runKernel(ui,s,r)}var Kt=V({expandDims_:F$});function O$(e){let n={x:D(e,"x","expm1")};return B.runKernel(ci,n)}var G3=V({expm1_:O$});function M$(e,t){let n=D(e,"x","tile","string_or_numeric");O(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);let s={x:n},r={reps:t};return B.runKernel(qr,s,r)}var js=V({tile_:M$});function z$(e,t,n,s="float32"){t==null&&(t=e);let r=Le([e,t],s),a=e<=t?e:t;for(let i=0;i`Error in localResponseNormalization: x must be rank 3 or 4 but got
- rank ${a.rank}.`),O(mn(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=a,i=!1;a.rank===3&&(i=!0,o=G(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let l={x:o},c={depthRadius:t,bias:n,alpha:s,beta:r},u=B.runKernel(Uc,l,c);return i?G(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var q3=V({localResponseNormalization_:J$});function Q$(e){let n={x:D(e,"x","log","float32")};return B.runKernel(Wa,n)}var Ns=V({log_:Q$});function eD(e){let n={x:D(e,"x","log1p")};return B.runKernel(su,n)}var Zh=V({log1p_:eD});function tD(e){return O(va(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let s=D(t,"x","tf.grad","string_or_numeric"),r=n!=null?D(n,"dy","tf.grad"):null;return B.tidy(()=>{let{value:a,grads:o}=B.gradients(()=>e(s),[s],r);return r!=null&&zn(a.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Yh(o),o[0]})}}function nD(e){return O(va(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{O(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let s=ad(t,"args","tf.grads","string_or_numeric"),r=n!=null?D(n,"dy","tf.grads"):null;return B.tidy(()=>{let{value:a,grads:o}=B.gradients(()=>e(...s),s,r);return r!=null&&zn(a.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Yh(o),o})}}function sD(e){return O(va(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{O(t instanceof Ye,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),O(n==null||n instanceof Ye,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:s,value:r}=B.gradients(()=>e(t),[t],n);return Yh(s),{grad:s[0],value:r}}}function rD(e){return O(va(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{O(Array.isArray(t)&&t.every(r=>r instanceof Ye),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),O(n==null||n instanceof Ye,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let s=B.gradients(()=>e(...t),t,n);return n!=null&&zn(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Yh(s.grads),s}}function X3(e,t){O(va(e),()=>"The f passed in variableGrads(f) must be a function"),O(t==null||Array.isArray(t)&&t.every(c=>c instanceof sd),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let c in B.registeredVariables)t.push(B.registeredVariables[c])}let s=n?t.filter(c=>!c.trainable):null,r=t.length;t=t.filter(c=>c.trainable),O(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);let a=!0,{value:o,grads:i}=B.gradients(e,t,null,a);O(i.some(c=>c!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),O(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);let l={};return t.forEach((c,u)=>{i[u]!=null&&(l[c.name]=i[u])}),s!=null&&s.forEach(c=>l[c.name]=null),{value:o,grads:l}}function Er(e){return B.customGrad(e)}function Yh(e){if(e.filter(n=>n==null).length>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
- the f you passed encloses all operations that lead from x to y.`)}function aD(e){let n={x:D(e,"x","neg")};return B.runKernel(xi,n)}var Ot=V({neg_:aD});function oD(e){let n={x:D(e,"x","softplus")};return B.runKernel(pu,n)}var Cu=V({softplus_:oD});function iD(e){let t=D(e,"x","logSigmoid");return Er(s=>({value:Ot(Cu(Ot(s))),gradFunc:o=>W(o,hs(Ot(s)))}))(t)}var lD=V({logSigmoid_:iD});function uD(e,t=null,n=!1){let r={x:D(e,"x","max")},a={reductionIndices:t,keepDims:n};return B.runKernel(Va,r,a)}var rs=V({max_:uD});function cD(e,t){let n=D(e,"a","sub"),s=D(t,"b","sub");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(uo,r)}var ye=V({sub_:cD});function dD(e,t=null,n=!1){let s=D(e,"x","sum");s.dtype==="bool"&&(s=de(s,"int32"));let r={x:s},a={axis:t,keepDims:n};return B.runKernel(oo,r,a)}var Ie=V({sum_:dD});function pD(e,t=-1){let n=D(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return Er((r,a)=>{let o=!0,i=rs(r,t,!0),l=ye(r,i),c=ye(de(l,"float32"),Ns(Ie(Ts(l),t,o)));return a([c]),{value:c,gradFunc:(d,p)=>{let[h]=p,f=!0,m=Ts(h);return ye(d,W(Ie(d,t,f),m))}}})(n)}var B2=V({logSoftmax_:pD});function W2(e,t){for(let n=0;ne[a]);return[n,r]}function Qi(e,t){let n=t.map(s=>1);return K3(e,n,t)}function hD(e,t,n){O(W2(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function Y3(e,t){if(W2(e,t))return null;let n=[];for(let s=0;sn.push(s)),n}function V2(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function fD(e,t){let n=[];for(let s=t-e;s`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),O(Nr(n,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),r!=null&&O(mn(s),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r},d=B.runKernel(Ga,c,u);return l?G(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Qh=V({maxPool_:vD});function wD(e,t=[1,1,1],n,s,r,a="NDHWC"){let o=D(e,"x","maxPool3d"),i=o,l=!1;o.rank===4&&(l=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),O(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),O(a==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),r!=null&&O(mn(s),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},d=B.runKernel(Gc,c,u);return l?G(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var G2=V({maxPool3d_:wD});function kD(e,t,n,s,r=!1){let o={x:D(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:s,includeBatchInIndex:r},l=B.runKernel(bh,o,i);return{result:l[0],indexes:l[1]}}var Q3=V({maxPoolWithArgmax_:kD});function ID(e,t){let n=D(e,"a","maximum"),s=D(t,"b","maximum");[n,s]=Ft(n,s),n.dtype==="bool"&&(n=de(n,"int32"),s=de(s,"int32")),St(n.shape,s.shape);let r={a:n,b:s};return B.runKernel(Ua,r)}var Yr=V({maximum_:ID});function SD(e,t=null,n=!1){let r={x:D(e,"x","mean")},a={axis:t,keepDims:n};return B.runKernel(Ha,r,a)}var Wt=V({mean_:SD});function Ht(e,t="float32"){if(t==="complex64"){let s=Ht(e,"float32"),r=Ht(e,"float32");return yo(s,r)}let n=Qp(Ut(e),t);return B.makeTensor(n,e,t)}function gs(e,t="float32"){if(t==="complex64"){let s=gs(e,"float32"),r=Ht(e,"float32");return yo(s,r)}let n=Lg(Ut(e),t);return B.makeTensor(n,e,t)}function CD(e,t,{indexing:n="xy"}={}){if(n!=="xy"&&n!=="ij")throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(e===void 0)return[];let s=D(e,"x","meshgrid",e instanceof Ye?e.dtype:"float32");if(t===void 0)return[s];let r=D(t,"y","meshgrid",t instanceof Ye?t.dtype:"float32"),a=Ut(s.shape),o=Ut(r.shape);return n==="xy"?(s=G(s,[1,-1]),r=G(r,[-1,1]),[He(gs([o,1],s.dtype),s),He(r,gs([1,a],r.dtype))]):(s=G(s,[-1,1]),r=G(r,[1,-1]),[He(s,gs([1,o],s.dtype)),He(gs([a,1],r.dtype),r)])}function TD(e,t=null,n=!1){let r={x:D(e,"x","min")},a={axis:t,keepDims:n};return B.runKernel(ja,r,a)}var ef=V({min_:TD});function ND(e,t){let n=D(e,"a","minimum"),s=D(t,"b","minimum");[n,s]=Ft(n,s),n.dtype==="bool"&&(n=de(n,"int32"),s=de(s,"int32")),St(n.shape,s.shape);let r={a:n,b:s};return B.runKernel(qa,r)}var hd=V({minimum_:ND});function ED(e,t,n){O(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let s=D(e,"x","mirrorPad");if(s.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");O(t.length===s.rank,()=>`Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`);let r=n==="reflect"?1:0;for(let i=0;i"Invalid number of paddings. Must be length of 2 each."),O(t[i][0]>=0&&t[i][0]<=s.shape[i]-r&&t[i][1]>=0&&t[i][1]<=s.shape[i]-r,()=>`Padding in dimension ${i} cannot be greater than or equal to ${s.shape[i]-r} or less than 0 for input of shape ${s.shape}`);let a={paddings:t,mode:n},o={x:s};return B.runKernel(Xa,o,a)}var ev=V({mirrorPad_:ED});function RD(e,t){let n=D(e,"a","mod"),s=D(t,"b","mod");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(au,r)}var tv=V({mod_:RD});function $D(e){let t=D(e,"x","square"),n={};return B.runKernel("Square",{x:t},n)}var xt=V({square_:$D});function DD(e,t=null,n=!1){e=D(e,"x","moments");let s=Us(t,e.shape),r=Wt(e,s,n),a=r.shape;n||(a=Qi(r.shape,s));let o=xt(ye(de(e,"float32"),G(r,a))),i=Wt(o,s,n);return{mean:r,variance:i}}var tf=V({moments_:DD});function _D(e,t,n,s){let r=D(t,"data","multiRNNCell"),a=ad(n,"c","multiRNNCell"),o=ad(s,"h","multiRNNCell"),i=r,l=[];for(let d=0;d2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);n=n||Math.random();let l={logits:o===1?G(r,[1,-1]):r},c={numSamples:t,seed:n,normalized:s},u=B.runKernel(vh,l,c);return o===1?G(u,[u.size]):u}var nv=V({multinomial_:FD});function OD(e,t){let n=D(e,"a","notEqual","string_or_numeric"),s=D(t,"b","notEqual","string_or_numeric");[n,s]=Ft(n,s),St(n.shape,s.shape);let r={a:n,b:s};return B.runKernel(bi,r)}var Tu=V({notEqual_:OD});function MD(e){let n={x:D(e,"x","onesLike")};return B.runKernel(ki,n)}var Es=V({onesLike_:MD});function zD(e,t){let n=D(e,"v1","outerProduct"),s=D(t,"v2","outerProduct");O(n.rank===1&&s.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${s.rank}.`);let r=G(n,[-1,1]),a=G(s,[1,-1]);return He(r,a)}var LD=V({outerProduct_:zD});function BD(e,t,n=0){let s=D(e,"x","pad");if(s.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let r={paddings:t,constantValue:n},a={x:s};return B.runKernel(Za,a,r)}var qs=V({pad_:BD});function WD(e,t,n=0){return O(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),qs(e,[t],n)}var VD=V({pad1d_:WD});function UD(e,t,n=0){return O(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),qs(e,t,n)}var GD=V({pad2d_:UD});function HD(e,t,n=0){return O(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."),qs(e,t,n)}var jD=V({pad3d_:HD});function qD(e,t,n=0){return O(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."),qs(e,t,n)}var XD=V({pad4d_:qD});function KD(e,t,n){let s=D(e,"x","spaceToBatchND");O(s.rank>=1+t.length,()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`),O(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),O(s.shape.reduce((o,i,l)=>l>0&&l<=t.length?o&&(i+n[l-1][0]+n[l-1][1])%t[l-1]==0:o,!0),()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);let r={x:s},a={blockShape:t,paddings:n};return B.runKernel(Pi,r,a)}var nf=V({spaceToBatchND_:KD});function ZD(e,t,n,s,r,a){r==null&&(r=[1,1]),a==null&&(a=1),s===0&&(s="valid");let o=D(e,"x","maxPool"),i=o,l=!1;o.rank===3&&(l=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2]])),O(Nr(a,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${r}'`);let c=S3(i.shape,t,a,r,s),u=[c.dilationHeight,c.dilationWidth],d;s==="same"?d=JD([c.filterHeight,c.filterWidth],u):d=[[0,0],[0,0]];let p=u[0]===1&&u[1]===1,[h,f]=YD([c.inHeight,c.inWidth],u,d),m=p?s:"valid",g=p?i:nf(i,u,h),y=(n==="avg"?()=>Hh(g,t,a,m):()=>Qh(g,t,a,m))(),x=p?y:jh(y,u,f);return l?G(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function YD(e,t,n){let s=n.map(u=>u[0]),r=n.map(u=>u[1]),a=e.concat(s,r),o=t.map((u,d)=>(u-a[d]%u)%u),i=r.map((u,d)=>u+o[d]),l=t.map((u,d)=>[s[d],i[d]]),c=t.map((u,d)=>[0,o[d]]);return[l,c]}function JD(e,t){let s=e.map((o,i)=>o+(o-1)*(t[i]-1)).map(o=>o-1),r=s.map(o=>Math.floor(o/2)),a=s.map((o,i)=>o-r[i]);return s.map((o,i)=>[r[i],a[i]])}var QD=V({pool_:ZD});function e_(e,t){let n=D(e,"base","pow"),s=D(t,"exp","pow");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Ya,r)}var Io=V({pow_:e_});function t_(e,t){let n=D(e,"x","prelu"),s=D(t,"alpha","prelu"),r={x:n,alpha:s};return B.runKernel(Ja,r)}var sf=V({prelu_:t_});function n_(e,t=null,n=!1){let s=D(e,"x","prod");s.dtype==="bool"&&(s=de(s,"int32"));let r={x:s},a={axis:t,keepDims:n};return B.runKernel(Ci,r,a)}var H2=V({prod_:n_});function s_(e,t,n){let s=Ut(e),r=null;if(n==null||n==="float32")r=new Float32Array(s);else if(n==="int32")r=new Int32Array(s);else if(n==="bool")r=new Uint8Array(s);else throw new Error(`Unknown data type ${n}`);for(let a=0;a=1||a===0);let o=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*s*o,t=this.mean+this.stdDev*r*o,(!this.truncated||this.isValidTruncated(e))&&(n=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}},a_=class{constructor(e,t,n,s){this.alpha=e,this.beta=1/t,this.dtype=n;let r=s||Math.random();this.randu=j2.alea(r.toString()),this.randn=new q2(0,1,n,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,s,r,a;for(;;){do s=this.randn.nextValue(),a=1+this.c*s;while(a<=0);if(a*=a*a,e=s*s,t=1-.331*e*e,n=.5*e+this.d*(1-a+Math.log(a)),r=this.randu(),rthis.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,s==null&&(s=Math.random()),typeof s=="number"&&(s=s.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=j2.alea(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function i_(e,t,n=1,s="float32",r){if(n==null&&(n=1),s==null&&(s="float32"),s!=="float32"&&s!=="int32")throw new Error(`Unsupported data type ${s}`);let a=new a_(t,n,s,r),o=Le(e,s);for(let i=0;i`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Rs(t,0)}var A_=V({reverse1d_:g_});function y_(e,t){let n=D(e,"x","reverse");return O(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),Rs(n,t)}var x_=V({reverse2d_:y_});function b_(e,t){let n=D(e,"x","reverse");return O(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),Rs(n,t)}var v_=V({reverse3d_:b_});function w_(e,t){let n=D(e,"x","reverse");return O(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),Rs(n,t)}var k_=V({reverse4d_:w_});function I_(e){let n={x:D(e,"x","round")};return B.runKernel(Ei,n)}var K2=V({round_:I_});function S_(e){let n={x:D(e,"x","rsqrt","float32")};return B.runKernel(no,n)}var Z2=V({rsqrt_:S_});function Ee(e,t){if((Dn(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"&&Dn(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return xo(e,[],[],t)}function C_(e){let n={x:D(e,"x","selu")};return B.runKernel(cu,n)}var Y2=V({selu_:C_});function T_(e,t,n,s,r,a=[1,1],o="NHWC"){let i=D(e,"x","separableConv2d"),l=D(t,"depthwiseFilter","separableConv2d"),c=D(n,"pointwiseFilter","separableConv2d"),u=i,d=!1;if(i.rank===3&&(d=!0,u=G(i,[1,i.shape[0],i.shape[1],i.shape[2]])),o==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");O(u.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`),O(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),O(c.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),O(c.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`),O(c.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`);let p=l.shape[2],h=l.shape[3];O(c.shape[2]===p*h,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*h}, but got ${c.shape[2]}.`);let f=cd(u,l,s,r,o,a),g=ko(f,c,1,"valid",o);return d?G(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var av=V({separableConv2d_:T_});async function N_(e,t){let n=D(e,"x","setdiff1d"),s=D(t,"y","setdiff1d");O(n.dtype===s.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`),O(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),O(s.rank===1,()=>`y should be 1D tensor, but got y (${s.shape}).`);let r=await n.data(),a=await s.data(),o=new Set(a),i=0;for(let u=0;u`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),_e(s,[t],[n])}var rf=V({slice1d_:D_});function __(e,t,n){let s=D(e,"x","slice2d");return O(s.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),_e(s,t,n)}var e1=V({slice2d_:__});function P_(e,t,n){let s=D(e,"x","slice3d");return O(s.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),_e(s,t,n)}var Ru=V({slice3d_:P_});function F_(e,t,n){let s=D(e,"x","slice4d");return O(s.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),_e(s,t,n)}var md=V({slice4d_:F_});function O_(e,t=-1){let n=D(e,"logits","softmax","float32");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);let s={logits:n},r={dim:t};return B.runKernel(io,s,r)}var $u=V({softmax_:O_});function M_(e){O(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return B.runKernel(fh,t)}var af=V({fft_:M_});function z_(e){O(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return B.runKernel(mh,t)}var gd=V({ifft_:z_});function L_(e){let t=e.shape[e.shape.length-1],n=e.size/t,s;if(t<=2){let r=G(e,[n,t]);s=gd(r)}else{let r=[n,2*(t-1)],a=G(fd(e),[n,t]),o=G(Xh(e),[n,t]),i=Rs(_e(a,[0,1],[n,t-2]),1),l=W(Rs(_e(o,[0,1],[n,t-2]),1),Ee(-1)),c=It([a,i],1),u=It([o,l],1),d=G(yo(c,u),[r[0],r[1]]);s=gd(d)}if(s=fd(s),e.rank===3&&e.shape[0]!==0){let r=s,a=e.shape[0];s=G(s,[a,s.shape[0]/a,s.shape[1]]),r.dispose()}return s}var t1=V({irfft_:L_});function B_(e,t,n=0){let r={x:D(e,"x","split")},a={numOrSizeSplits:t,axis:n};return B.runKernel(Fi,r,a)}var Sn=V({split_:B_});function W_(e,t){O(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1],s=e.size/n,r;if(t!=null&&t0),m=e.shape.map(g=>g);m[e.shape.length-1]=t,r=_e(e,f,m),n=t}else if(t!=null&&t>n){let f=e.shape.map(m=>m);f[e.shape.length-1]=t-n,r=It([e,Ht(f)],e.shape.length-1),n=t}else r=e;let a=tt(r),o=G(yo(r,a),[s,n]),i=af(o),l=Math.floor(n/2)+1,c=fd(i),u=Xh(i),d=Sn(c,[l,n-l],c.shape.length-1),p=Sn(u,[l,n-l],u.shape.length-1),h=r.shape.slice();return h[r.shape.length-1]=l,G(yo(d[0],p[0]),h)}var of=V({rfft_:W_});function V_(e){let n={x:D(e,"x","sqrt","float32")};return B.runKernel(ao,n)}var _n=V({sqrt_:V_});function U_(e,t){let n=D(e,"a","squaredDifference"),s=D(t,"b","squaredDifference");[n,s]=Ft(n,s),St(n.shape,s.shape);let r={a:n,b:s},a={};return B.runKernel(lo,r,a)}var n1=V({squaredDifference_:U_});function G_(e,t){let n=D(e,"x","squeeze");return G(n,s5(n.shape,t).newShape)}var pt=V({squeeze_:G_});function H_(e,t=0){let n=ad(e,"tensors","stack","string_or_numeric");O(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&O(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let s=n,r={axis:t};return B.runKernel(Si,s,r)}var Pn=V({stack_:H_});function j_(e,t=0){let s={x:D(e,"x","step")},r={alpha:t};return B.runKernel(ho,s,r)}var Ad=V({step_:j_});function q_(e,t,n,s,r=0,a=0,o=0,i=0,l=0){let u={x:D(e,"x","stridedSlice","string_or_numeric")},d={begin:t,end:n,strides:s,beginMask:r,endMask:a,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:l};return B.runKernel(Oi,u,d)}var lv=V({stridedSlice_:q_});function X_(e){let n={x:D(e,"x","tan","float32")};return B.runKernel(Mi,n)}var uv=V({tan_:X_});function Zt(e,t){ei(e);let n=Cr(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return xo(e,null,n,t)}function ur(e,t,n){if(ei(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let s=Cr(e,n);if(s.length!==2&&s.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return xo(e,t,s,n)}function K_(e,t,n){if(ei(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let s=Cr(e,n);if(s.length!==4&&s.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return xo(e,t,s,n)}function Z_(e,t,n){if(ei(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let s=Cr(e,n);if(s.length!==5&&s.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return xo(e,t,s,n)}function Y_(e,t,n){if(ei(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let s=Cr(e,n);if(s.length!==6&&s.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||s,xo(e,t,s,n)}function J_(e,t=1,n=!0){let s=D(e,"x","topk");if(s.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let r=s.shape[s.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);let a={x:s},o={k:t,sorted:n},[i,l]=B.runKernel(zi,a,o);return{values:i,indices:l}}var cv=V({topk_:J_});function Q_(e,t=0,n=1,s,r){if(s!=null&&s==="bool")throw new Error("Unsupported data type $ { dtype }");let a=new q2(t,n,s,!0,r),o=Le(e,s);for(let i=0;i0,()=>"The input tensor must be at least 1D");let s={x:n},r={axis:t},[a,o]=B.runKernel(Rh,s,r);return{values:a,indices:o}}var s1=V({unique_:eP});function tP(e,t,n){let s=D(e,"x","unsortedSegmentSum"),r=D(t,"segmentIds","unsortedSegmentSum","int32");O(mn(n),()=>"numSegments must be of dtype int");let a={x:s,segmentIds:r},o={numSegments:n};return B.runKernel(Xc,a,o)}var dv=V({unsortedSegmentSum_:tP});function nP(e,t=0){let n=D(e,"x","unstack","string_or_numeric");O(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);let s={value:n},r={axis:t};return B.runKernel(Bi,s,r)}var as=V({unstack_:nP});function pv(e,t=!0,n,s){return B.makeVariable(e,t,n,s)}function hv(e,t){let n=[];for(let a=0;a0,()=>"mask cannot be scalar"),zn(i.slice(a,a+o),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let m=a;m"Shape mismatch in v and x");let l=Ee(1),c=ye(l,i),u=W(ye(o,a),c);if(r){O(s!=null,()=>"When using zeroDebias: true, step is required.");let d=D(s,"step","movingAverage");u=he(u,ye(l,Io(i,d)))}return ie(a,u)}var lP=V({movingAverage_:iP});function uP(e,t,n){let s=D(e,"indices","scatterND","int32"),r=D(t,"updates","scatterND");b2(r,s,n);let a={indices:s,updates:r},o={shape:n};return B.runKernel(Ri,a,o)}var mv=V({scatterND_:uP});function cP(e,t,n,s){if(e.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);let r=e.rank>0?e.shape[0]:1,a=e.rank>1?e.shape[1]:1;if(n.length!==a)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${a}.`);let o=t.size;if(!(t.rank===0||t.rank===1&&o===r))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${r}]`);if(t.dtype!==s.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function dP(e,t,n,s=0){let r=D(e,"sparseIndices","sparseToDense","int32"),a=D(t,"sparseValues","sparseToDense"),o=D(s,"defaultValue","sparseToDense",a.dtype);cP(r,a,n,o);let i={sparseIndices:r,sparseValues:a,defaultValue:o},l={outputShape:n};return B.runKernel(jc,i,l)}var o1=V({sparseToDense_:dP});function pP(e,t){let n=D(t,"indices","gatherND","int32"),r={params:D(e,"x","gatherND","string_or_numeric"),indices:n};return B.runKernel(hi,r)}var gv=V({gatherND_:pP});function hP(e,t){if(t==null)return e.shape.slice();if(Gr(e.shape,t))return t;if(e.shape.length===t.length){let n=[];for(let s=0;s`x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`),O(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof Ye?r.clone():r;let a=hP(r,n),o=1-t,i=he(pd(ie(Nu(a,0,1,"float32",s),o)),o);return W(r,i)}var Av=V({dropout_:fP});function yv(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function i1(e,t,n){let s=1-e%2,r=new Float32Array(e);for(let a=0;a1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${s.rank}`),O(s.rank-1===r.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${s.rank} and targets rank ${r.rank}`),zn(s.shape.slice(0,s.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let a=s.shape[s.shape.length-1];O(n>0&&n<=a,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`);let o=await s.data(),i=await r.data(),[l,c]=[o.length/a,a],u=r5("bool",l);for(let d=0;dg.value-m.value),u[d]=0;for(let m=0;mxP,depthwiseConv2d:()=>kP,matMul:()=>SP});function AP(e,t,n,s,r,a="NHWC",o){let i=e;e.rank===3&&(i=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=G(t,[1,t.shape[0],t.shape[1],t.shape[2]])),O(i.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),O(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),O(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);let c=a==="NHWC"?i.shape[3]:i.shape[1],u=a==="NHWC"?l.shape[3]:l.shape[1];O(c===n[2],()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${n[2]}.`),O(u===n[3],()=>`Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${n[3]}).`),o!=null&&O(mn(r),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let d={x:i,dy:l},p={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,filterShape:n};return B.runKernel(rh,d,p)}var l1=V({conv2DBackpropFilter_:AP});function uf(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return W(e,Ad(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function cf(e,t){let n=t,s=an(e.shape,t.shape);return s.length>0&&(n=Ie(n,s)),G(n,e.shape)}function df(e,t,n,s){if(t==="linear")return e;if(t==="relu")return Rr(e);if(t==="elu")return dd(e);if(t==="relu6")return X2(e);if(t==="prelu")return sf(e,n);if(t==="leakyrelu")return Kh(e,s);if(t==="sigmoid")return hs(e);throw new Error(`Unknown fused activation ${t}.`)}var pf=(e,t)=>!(e>0)||t==="linear";function yP({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(l=l||"linear",pf(B.state.gradientDepth,l)===!1){let w=ko(e,t,n,s,r,a,o);return i!=null&&(w=ie(w,i)),df(w,l,c,u)}let d=D(e,"x","conv2d","float32"),p=D(t,"filter","conv2d","float32"),h=d,f=!1;d.rank===3&&(f=!0,h=G(d,[1,d.shape[0],d.shape[1],d.shape[2]])),O(h.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`),O(p.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`),o!=null&&O(mn(s),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`),O(h.shape[3]===p.shape[2],()=>`Error in conv2d: depth of input (${h.shape[3]}) must match input depth for filter ${p.shape[2]}.`),O(Nr(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),O(r==="NHWC",()=>`Error in conv2d: got dataFormat of ${r} but only NHWC is currently supported.`);let m=ld(h.shape,p.shape,n,a,s,o),g;i!=null&&(g=D(i,"bias","fused conv2d"),[g]=Ft(g,d),St(m.outShape,g.shape));let A;c!=null&&(A=D(c,"prelu weights","fused conv2d"));let y=(w,k)=>{let[S,E,P,F]=k,R=uf(w,P,l);O(wo(a),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);let _=_2(E.shape,R,S,n,s),T=l1(E,R,S.shape,n,s),M=[_,T];if(F!=null){let U=cf(F,R);M.push(U)}return M},x={x:h,filter:p,bias:g,preluActivationWeights:A},b={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:u};return i==null?Er((k,S,E)=>{let P=B.runKernel(mo,x,b);return E([S,k,P]),f&&(P=G(P,[P.shape[1],P.shape[2],P.shape[3]])),{value:P,gradFunc:y}})(h,p):Er((k,S,E,P)=>{let F=B.runKernel(mo,x,b);return P([S,k,F,E]),f&&(F=G(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:y}})(h,p,g)}var xP=V({fusedConv2d_:yP});function bP(e,t,n,s,r,a=[1,1],o){let i=e;e.rank===3&&(i=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=G(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let c={x:i,dy:l},u={strides:s,pad:r,dimRoundingMode:o,dilations:a,filterShape:n};return B.runKernel(lh,c,u)}var xv=V({depthwiseConv2dNativeBackpropFilter_:bP});function vP(e,t,n,s,r,a=[1,1],o){let i=t,l=!1;t.rank===3&&(l=!0,i=G(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let c={dy:i,filter:n},u={strides:s,pad:r,dimRoundingMode:o,dilations:a,inputShape:e},d=B.runKernel(uh,c,u);return l?G(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var bv=V({depthwiseConv2dNativeBackpropInput_:vP});function wP({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(pf(B.state.gradientDepth,l)===!1){let w=cd(e,t,n,s,r,a,o);return i!=null&&(w=ie(w,i)),df(w,l,c,u)}let d=D(e,"x","depthwiseConv2d","float32"),p=D(t,"filter","depthwiseConv2d","float32"),h=d,f=!1;d.rank===3&&(f=!0,h=G(d,[1,d.shape[0],d.shape[1],d.shape[2]])),O(h.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`),O(p.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`),O(h.shape[3]===p.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),a==null&&(a=[1,1]),O(Nr(n,a),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o!=null&&O(mn(s),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${o} but got pad ${s}.`);let m=ld(h.shape,p.shape,n,a,s,o,!0),g;i!=null&&(g=D(i,"bias","fused conv2d"),[g]=Ft(g,d),St(m.outShape,g.shape));let A;c!=null&&(A=D(c,"prelu weights","fused depthwiseConv2d"));let y=(w,k)=>{O(wo(a),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);let[S,E,P,F]=k,R=uf(w,P,l),_=bv(E.shape,R,S,n,s,a,o),T=xv(E,R,S.shape,n,s,a,o);if(F!=null){let M=cf(g,R);return[_,T,M]}return[_,T]},x={x:h,filter:p,bias:g,preluActivationWeights:A},b={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:u};return i==null?Er((k,S,E)=>{let P=B.runKernel(go,x,b);return E([S,k,P]),f&&(P=G(P,[P.shape[1],P.shape[2],P.shape[3]])),{value:P,gradFunc:y}})(h,p):Er((k,S,E,P)=>{let F=B.runKernel(go,x,b);return P([S,k,F,E]),f&&(F=G(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:y}})(h,p,g)}var kP=V({fusedDepthwiseConv2d_:wP});function IP({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:r,activation:a="linear",preluActivationWeights:o,leakyreluAlpha:i}){if(pf(B.state.gradientDepth,a)===!1){let F=He(e,t,n,s);return r!=null&&(F=ie(F,r)),df(F,a,o,i)}let l=D(e,"a","fused matMul"),c=D(t,"b","fused matMul");[l,c]=Ft(l,c);let u=n?l.shape[l.rank-2]:l.shape[l.rank-1],d=s?c.shape[c.rank-1]:c.shape[c.rank-2],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],h=s?c.shape[c.rank-2]:c.shape[c.rank-1],f=l.shape.slice(0,-2),m=c.shape.slice(0,-2),g=Ut(f),A=Ut(m);O(l.rank>=2&&c.rank>=2&&l.rank===c.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${l.rank} and ${c.rank}.`),O(Gr(f,m),()=>`Error in fused matMul: outer dimensions (${f}) and (${m}) of Tensors with shapes ${l.shape} and ${c.shape} must match.`),O(u===d,()=>`Error in fused matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${l.shape} and ${c.shape} and transposeA=${n} and transposeB=${s} must match.`);let y=l.shape.slice(0,-2).concat([p,h]),x=n?G(l,[g,u,p]):G(l,[g,p,u]),b=s?G(c,[A,h,d]):G(c,[A,d,h]),w;r!=null&&(w=D(r,"bias","fused matMul"),[w]=Ft(w,l),St(y,w.shape));let k;o!=null&&(k=D(o,"prelu weights","fused matMul"));let S=(F,R)=>{let[_,T,M,U]=R,H=uf(G(F,M.shape),M,a),z,X;if(!n&&!s?(z=He(H,T,!1,!0),X=He(_,H,!0,!1)):!n&&s?(z=He(H,T,!1,!1),X=He(H,_,!0,!1)):n&&!s?(z=He(T,H,!1,!0),X=He(_,H,!1,!1)):(z=He(T,H,!0,!0),X=He(H,_,!0,!0)),r!=null){let ee=cf(U,H);return[z,X,ee]}else return[z,X]},E={a:x,b,bias:w,preluActivationWeights:k},P={transposeA:n,transposeB:s,activation:a,leakyreluAlpha:i};return r==null?Er((R,_,T)=>{let M=B.runKernel(fo,E,P);return T([R,_,M]),{value:G(M,y),gradFunc:S}})(x,b):Er((R,_,T,M)=>{let U=B.runKernel(fo,E,P);return M([R,_,U,T]),{value:G(U,y),gradFunc:S}})(x,b,w)}var SP=V({fusedMatMul_:IP});function CP(e){return i1(e,.54,.46)}var TP=V({hammingWindow_:CP});function NP(e){return i1(e,.5,.5)}var vv=V({hannWindow_:NP});function EP(e,t,n,s=!1,r=0){let a=0,o=[];for(;a+t<=e.size;)o.push(_e(e,a,t)),a+=n;if(s)for(;a`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),O(i.rank===2&&i.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${i.shape}.`),O(l.rank===1&&l.shape[0]===c,()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${i.shape}.`),O(s.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),O(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),O(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);let u={image:o,boxes:i,boxInd:l},d={method:r,extrapolationValue:a,cropSize:s};return B.runKernel(oi,u,d)}var _P=V({cropAndResize_:DP});function PP(e){let t=D(e,"image","flipLeftRight","float32");O(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return B.runKernel(di,n,{})}var FP=V({flipLeftRight_:PP});function OP(e){let t=D(e,"image","grayscaleToRGB"),n=t.rank-1,s=t.shape[n];O(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),O(s===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${s}.`);let r=new Array(t.rank);return r.fill(1,0,n),r[n]=3,js(t,r)}var MP=V({grayscaleToRGB_:OP});function zP(e,t,n=0,s=.5){let r=D(e,"image","rotateWithOffset","float32");O(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);let a={image:r},o={radians:t,fillValue:n,center:s};return B.runKernel(Vi,a,o)}var LP=V({rotateWithOffset_:zP});function Du(e,t,n,s,r,a){s==null&&(s=.5),r==null&&(r=Number.NEGATIVE_INFINITY),a==null&&(a=0);let o=e.shape[0];return n=Math.min(n,o),O(0<=s&&s<=1,()=>`iouThreshold must be in [0, 1], but was '${s}'`),O(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),O(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),O(t.rank===1,()=>"scores must be a 1D tensor"),O(t.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`),O(0<=a&&a<=1,()=>`softNmsSigma must be in [0, 1], but was '${a}'`),{maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a}}function BP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=D(e,"boxes","nonMaxSuppression","float32"),o=D(t,"scores","nonMaxSuppression","float32"),i=Du(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l={maxOutputSize:n,iouThreshold:s,scoreThreshold:r};return B.runKernel(vi,{boxes:a,scores:o},l)}var WP=V({nonMaxSuppression_:BP});function VP(e,t,n){let s=UP(e,t,n),r=s<0?-(s+1):s;e.splice(r,0,t)}function UP(e,t,n){return HP(e,t,n||GP)}function GP(e,t){return e>t?1:e>>1);let i=n(t,e[a]);i>0?s=a+1:(r=a,o=!i)}return o?s:-s-1}function kv(e,t,n,s,r){return u1(e,t,n,s,r,0)}function Iv(e,t,n,s,r,a){return u1(e,t,n,s,r,0,!1,a,!0)}function Sv(e,t,n,s,r,a){return u1(e,t,n,s,r,a,!0)}function u1(e,t,n,s,r,a,o=!1,i=!1,l=!1){let c=[];for(let g=0;gr&&c.push({score:t[g],boxIndex:g,suppressBeginIndex:0});c.sort(Cv);let u=a>0?-.5/a:0,d=[],p=[];for(;d.length0;){let g=c.pop(),{score:A,boxIndex:y,suppressBeginIndex:x}=g;if(A=x;--w){let k=jP(e,y,d[w]);if(k>=s){b=!0;break}if(g.score=g.score*qP(s,u,k),g.score<=r)break}g.suppressBeginIndex=d.length,b||(g.score===A?(d.push(y),p.push(g.score)):g.score>r&&VP(c,g,Cv))}let h=d.length,f=n-h;i&&f>0&&(d.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));let m={selectedIndices:d};return o&&(m.selectedScores=p),l&&(m.validOutputs=h),m}function jP(e,t,n){let s=e.subarray(t*4,t*4+4),r=e.subarray(n*4,n*4+4),a=Math.min(s[0],s[2]),o=Math.min(s[1],s[3]),i=Math.max(s[0],s[2]),l=Math.max(s[1],s[3]),c=Math.min(r[0],r[2]),u=Math.min(r[1],r[3]),d=Math.max(r[0],r[2]),p=Math.max(r[1],r[3]),h=(i-a)*(l-o),f=(d-c)*(p-u);if(h<=0||f<=0)return 0;let m=Math.max(a,c),g=Math.max(o,u),A=Math.min(i,d),y=Math.min(l,p),x=Math.max(A-m,0)*Math.max(y-g,0);return x/(h+f-x)}function qP(e,t,n){let s=Math.exp(t*n*n);return n<=e?s:0}function Cv(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function XP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=D(e,"boxes","nonMaxSuppressionAsync"),o=D(t,"scores","nonMaxSuppressionAsync"),i=Du(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l=await Promise.all([a.data(),o.data()]),c=l[0],u=l[1],{selectedIndices:d}=kv(c,u,n,s,r);return a!==e&&a.dispose(),o!==t&&o.dispose(),Zt(d,"int32")}var KP=XP;function ZP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=D(e,"boxes","nonMaxSuppression"),i=D(t,"scores","nonMaxSuppression"),l=Du(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let c={boxes:o,scores:i},u={maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a},d=B.runKernel(wi,c,u);return{selectedIndices:d[0],selectedScores:d[1]}}var YP=V({nonMaxSuppressionWithScore_:ZP});async function JP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=D(e,"boxes","nonMaxSuppressionAsync"),i=D(t,"scores","nonMaxSuppressionAsync"),l=Du(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let c=await Promise.all([o.data(),i.data()]),u=c[0],d=c[1],{selectedIndices:p,selectedScores:h}=Sv(u,d,n,s,r,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Zt(p,"int32"),selectedScores:Zt(h)}}var QP=JP;function eF(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=D(e,"boxes","nonMaxSuppression"),i=D(t,"scores","nonMaxSuppression"),l=Du(o,i,n,s,r,null),c=l.maxOutputSize,u=l.iouThreshold,d=l.scoreThreshold,p={boxes:o,scores:i},h={maxOutputSize:c,iouThreshold:u,scoreThreshold:d,padToMaxOutputSize:a},f=B.runKernel(ou,p,h);return{selectedIndices:f[0],validOutputs:f[1]}}var tF=V({nonMaxSuppressionPadded_:eF});async function nF(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=D(e,"boxes","nonMaxSuppressionAsync"),i=D(t,"scores","nonMaxSuppressionAsync"),l=Du(o,i,n,s,r,null),c=l.maxOutputSize,u=l.iouThreshold,d=l.scoreThreshold,[p,h]=await Promise.all([o.data(),i.data()]),{selectedIndices:f,validOutputs:m}=Iv(p,h,c,u,d,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Zt(f,"int32"),validOutputs:Ee(m,"int32")}}var sF=nF;function rF(e,t,n=!1,s=!1){let r=D(e,"images","resizeBilinear");O(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),O(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),O(s===!1||n===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let a=r,o=!1;r.rank===3&&(o=!0,a=G(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},c=B.runKernel(eo,i,l);return o?G(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var aF=V({resizeBilinear_:rF});function oF(e,t,n=!1,s=!1){let r=D(e,"images","resizeNearestNeighbor");O(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),O(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),O(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),O(s===!1||n===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let a=r,o=!1;r.rank===3&&(o=!0,a=G(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},c=B.runKernel(uu,i,l);return o?G(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var iF=V({resizeNearestNeighbor_:oF});function lF(e,t="binary",n=!1,s=.5){let r=D(e,"image","threshold"),a=.2989,o=.587,i=.114,l=r.shape[0]*r.shape[1],c=W(Zt([s]),255),u,d,p,h;if(O(r.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`),O(r.shape[2]===3||r.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`),O(r.dtype==="int32"||r.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`),O(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),r.shape[2]===3){[u,d,p]=Sn(r,[1,1,1],-1);let g=W(u,a),A=W(d,o),y=W(p,i);h=ie(ie(g,A),y)}else h=e;if(t==="otsu"){let g=$2(de(K2(h),"int32"),Gt([]),256);c=uF(g,l)}let f=n?Ji(h,c):ms(h,c);return de(W(f,255),"int32")}function uF(e,t){let n=Zt([-1]),s=Zt([0]),r=Zt([0]),a,o,i,l,c,u;for(let d=0;d`Error in transform: image must be rank 4,but got rank ${o.rank}.`),O(i.rank===2&&(i.shape[0]===o.shape[0]||i.shape[0]===1)&&i.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),O(a==null||a.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`);let l={image:o,transforms:i},c={interpolation:n,fillMode:s,fillValue:r,outputShape:a};return B.runKernel(Li,l,c)}var pF=V({transform_:dF});function hF(e,t,n){O(t%1==0,()=>`bandPart(): numLower must be an integer, got ${t}.`),O(n%1==0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);let s=D(e,"a","bandPart");O(s.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`);let r=s.shape,[a,o]=s.shape.slice(-2);if(!(t<=a))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`);if(!(n<=o))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`);t<0&&(t=a),n<0&&(n=o);let i=G(Eu(0,a,1,"int32"),[-1,1]),l=Eu(0,o,1,"int32"),c=ye(i,l),u=lr(Ji(c,Ee(+t,"int32")),Yi(c,Ee(-n,"int32"))),d=Ht([a,o],s.dtype);return G(Pn(as(G(s,[-1,a,o])).map(p=>Wn(u,p,d))),r)}var fF=V({bandPart_:hF});function mF(e){let t;if(Array.isArray(e)){t=!1,O(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let r=e[0].shape[0];for(let a=1;a`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[a].shape[0]} vs. ${r})`)}else t=!0,e=Sn(e,e.shape[0],0).map(r=>pt(r,[0]));O(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let n=[],s=e;for(let r=0;r{let a=s[r];if(r>0)for(let o=0;o=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return Tv(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,c)=>l*c),s=as(G(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],a=[];s.forEach(l=>{let[c,u]=Tv(l,t);r.push(c),a.push(u)});let o=G(Pn(r,0),e.shape),i=G(Pn(a,0),e.shape);return[o,i]}}function Tv(e,t=!1){return B.tidy(()=>{O(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let n=e.shape[0],s=e.shape[1],r=z2(n),a=or(e),o=ur([[1]],[1,1]),i=or(o),l=n>=s?s:n;for(let c=0;c{let h=_e(a,[c,c],[n-c,1]),f=a1(h),m=_e(a,[c,c],[1,1]),g=Wn(ms(m,0),ur([[-1]]),ur([[1]])),A=ye(m,W(g,f)),y=he(h,A);y.shape[0]===1?i=or(o):i=It([o,_e(y,[1,0],[y.shape[0]-1,y.shape[1]])],0);let x=Ot(he(He(g,A),f)),b=_e(a,[c,0],[n-c,s]),w=W(x,i),k=et(i);if(c===0)a=ye(b,He(w,He(k,b)));else{let P=ye(b,He(w,He(k,b)));a=It([_e(a,[0,0],[c,s]),P],0)}let S=et(w),E=_e(r,[0,c],[n,r.shape[1]-c]);if(c===0)r=ye(E,He(He(E,i),S));else{let P=ye(E,He(He(E,i),S));r=It([_e(r,[0,0],[n,c]),P],1)}return[i,a,r]}),Q([u,d,p])}return!t&&n>s&&(r=_e(r,[0,0],[n,s]),a=_e(a,[0,0],[s,s])),[r,a]})}var yF=V({qr_:AF}),Vn;(function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(Vn||(Vn={}));function xF(e,t,n=Vn.SUM_BY_NONZERO_WEIGHTS){let s=D(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=D(t,"weights","computeWeightedLoss"));let a=r==null?s:W(s,r);if(n===Vn.NONE)return a;if(n===Vn.SUM)return Ie(a);if(n===Vn.MEAN){if(r==null)return Wt(a);{let o=s.size/r.size,i=he(Ie(a),Ie(r));return o>1?he(i,Ee(o)):i}}if(n===Vn.SUM_BY_NONZERO_WEIGHTS){if(r==null)return he(Ie(a),Ee(s.size));{let o=W(r,gs(s.shape)),i=de(Ie(Tu(o,Ee(0))),"float32");return he(Ie(a),i)}}throw Error(`Unknown reduction: ${n}`)}var Jr=V({computeWeightedLoss_:xF});function bF(e,t,n,s=Vn.SUM_BY_NONZERO_WEIGHTS){let r=D(e,"labels","absoluteDifference"),a=D(t,"predictions","absoluteDifference"),o=null;n!=null&&(o=D(n,"weights","absoluteDifference")),zn(r.shape,a.shape,"Error in absoluteDifference: ");let i=rn(ye(r,a));return Jr(i,o,s)}var vF=V({absoluteDifference_:bF});function wF(e,t,n,s,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=D(e,"labels","cosineDistance"),o=D(t,"predictions","cosineDistance"),i=null;s!=null&&(i=D(s,"weights","cosineDistance")),zn(a.shape,o.shape,"Error in cosineDistance: ");let l=Ee(1),c=ye(l,Ie(W(a,o),n,!0));return Jr(c,i,r)}var kF=V({cosineDistance_:wF});function IF(e,t,n,s=Vn.SUM_BY_NONZERO_WEIGHTS){let r=D(e,"labels","hingeLoss"),a=D(t,"predictions","hingeLoss"),o=null;n!=null&&(o=D(n,"weights","hingeLoss")),zn(r.shape,a.shape,"Error in hingeLoss: ");let i=Ee(1);r=ye(W(Ee(2),r),i);let l=Rr(ye(i,W(r,a)));return Jr(l,o,s)}var SF=V({hingeLoss_:IF});function CF(e,t,n,s=1,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=D(e,"labels","huberLoss"),o=D(t,"predictions","huberLoss"),i=null;n!=null&&(i=D(n,"weights","huberLoss")),zn(a.shape,o.shape,"Error in huberLoss: ");let l=Ee(s),c=rn(ye(o,a)),u=hd(c,l),d=ye(c,u),p=ie(W(Ee(.5),xt(u)),W(l,d));return Jr(p,i,r)}var TF=V({huberLoss_:CF});function NF(e,t,n,s=1e-7,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=D(e,"labels","logLoss"),o=D(t,"predictions","logLoss"),i=null;n!=null&&(i=D(n,"weights","logLoss")),zn(a.shape,o.shape,"Error in logLoss: ");let l=Ee(1),c=Ee(s),u=Ot(W(a,Ns(ie(o,c)))),d=W(ye(l,a),Ns(ie(ye(l,o),c))),p=ye(u,d);return Jr(p,i,r)}var EF=V({logLoss_:NF});function RF(e,t,n,s=Vn.SUM_BY_NONZERO_WEIGHTS){let r=D(e,"labels","meanSquaredError"),a=D(t,"predictions","meanSquaredError"),o=null;n!=null&&(o=D(n,"weights","meanSquaredError")),zn(r.shape,a.shape,"Error in meanSquaredError: ");let i=n1(r,a);return Jr(i,o,s)}var $F=V({meanSquaredError_:RF});function DF(e,t){let n=D(e,"labels","sigmoidCrossEntropyWithLogits"),s=D(t,"logits","sigmoidCrossEntropyWithLogits");zn(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=Rr(s),a=W(s,n),o=Zh(Ts(Ot(rn(s))));return ie(ye(r,a),o)}function _F(e,t,n,s=0,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=D(e,"multiClassLabels","sigmoidCrossEntropy"),o=D(t,"logits","sigmoidCrossEntropy"),i=null;if(n!=null&&(i=D(n,"weights","sigmoidCrossEntropy")),zn(a.shape,o.shape,"Error in sigmoidCrossEntropy: "),s>0){let c=Ee(s),u=Ee(1),d=Ee(.5);a=ie(W(a,ye(u,c)),W(d,c))}let l=DF(a,o);return Jr(l,i,r)}var PF=V({sigmoidCrossEntropy_:_F});function FF(e,t,n=-1){if(n===-1&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);return Er((r,a,o)=>{let l=J3(a,[n],!0),c=ye(de(a,"float32"),l);o([r,c]);let u=Ot(W(c,r));return{value:Ie(u,[n]),gradFunc:(h,f)=>{let[m,g]=f,A=Qi(h.shape,[n]);return[W(G(h,A),ye(de(m,"float32"),Ts(g))),W(G(h,A),ye(Ts(g),de(m,"float32")))]}}})(e,t)}function OF(e,t,n,s=0,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=D(e,"onehotLabels","softmaxCrossEntropy"),o=D(t,"logits","softmaxCrossEntropy"),i=null;if(n!=null&&(i=D(n,"weights","softmaxCrossEntropy")),zn(a.shape,o.shape,"Error in softmaxCrossEntropy: "),s>0){let c=Ee(s),u=Ee(1),d=Ee(a.shape[1]);a=ie(W(a,ye(u,c)),he(c,d))}let l=FF(a,o);return Jr(l,i,r)}var MF=V({softmaxCrossEntropy_:OF});function zF(e,t,n,s){let r=D(e,"indices","sparseFillEmptyRows"),a=D(t,"values","sparseFillEmptyRows"),o=D(n,"denseShape","sparseFillEmptyRows"),i=D(s,"defaultValue","sparseFillEmptyRows",a.dtype);if(r.rank!==2)throw new Error(`Indices should be Tensor2D but received shape
- ${r.shape}`);if(a.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(o.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(i.rank!==0)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);let l={indices:r,values:a,denseShape:o,defaultValue:i},c=B.runKernel(Ih,l);return{outputIndices:c[0],outputValues:c[1],emptyRowIndicator:c[2],reverseIndexMap:c[3]}}var LF=V({sparseFillEmptyRows_:zF});function BF(e,t,n){let s=D(e,"inputIndices","sparseReshape"),r=D(t,"inputShape","sparseReshape"),a=D(n,"newShape","sparseReshape");if(s.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
- ${s.shape}`);if(r.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${r.shape}`);if(a.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);let o={inputIndices:s,inputShape:r,newShape:a},i=B.runKernel(Sh,o);return{outputIndices:i[0],outputShape:i[1]}}var WF=V({sparseReshape_:BF});function VF(e,t,n){let s=D(e,"data","sparseSegmentMean"),r=D(t,"indices","sparseSegmentMean"),a=D(n,"segmentIds","sparseSegmentMean");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
+ ${s.shape}`),O(o%(t*t)==0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${s.shape}`);let i={x:s},l={blockSize:t,dataFormat:n};return B.runKernel(ii,i,l)}var L3=V({depthToSpace_:x$});function b$(e,t,n,s,r="NHWC",a=[1,1],o){let i=_(e,"x","depthwiseConv2d","float32"),l=_(t,"filter","depthwiseConv2d","float32"),c=i,u=!1;i.rank===3&&(u=!0,c=G(i,[1,i.shape[0],i.shape[1],i.shape[2]])),O(c.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),O(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),O(c.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),o!=null&&O(mn(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let d={x:c,filter:l},p={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},h=B.runKernel(Da,d,p);return u?G(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var cd=V({depthwiseConv2d_:b$});function v$(e){let n={x:_(e,"x","diag")};return B.runKernel(ch,n)}var w$=V({diag_:v$});function k$(e,t,n,s,r=[1,1],a="NHWC"){let o=_(e,"x","dilation2d"),i=_(t,"filter","dilation2d");O(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),O(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),O(a==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);let l=o,c=!1;o.rank===3&&(l=G(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=!0);let u={x:l,filter:i},d={strides:n,pad:s,dilations:r},p=B.runKernel(Lc,u,d);return c?G(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var B3=V({dilation2d_:k$});function I$(e,t){let n=e.length,s=[];for(let r=0;r1&&o===1&&s.unshift(a)}return s}function an(e,t){let n=[];for(let s=0;s1)&&n.unshift(a)}return n}function St(e,t){let n=[],s=Math.max(e.length,t.length);for(let r=0;r`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${s.rank}.`);let r=n.rank===1?n.size:n.shape[1],a=s.rank===1?s.size:s.shape[0];if(O(r===a,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${a}.`),n.rank===1&&s.rank===1){let o=G(n,[1,-1]),i=G(s,[-1,1]),l=He(o,i);return G(l,[])}else if(n.rank===1&&s.rank===2){let o=G(n,[1,-1]),i=G(s,[s.shape[0],s.shape[1]]),l=He(o,i);return G(l,[l.size])}else if(n.rank===2&&s.rank===1){let o=G(s,[-1,1]),i=He(n,o);return G(i,[i.size])}else{let o=G(s,[s.shape[0],s.shape[1]]);return He(n,o)}}var R$=V({dot_:E$});function $$(e,...t){let n=t.map((r,a)=>_(r,`tensors${a}`,"einsum")),s={equation:e};return B.runKernel(Bc,n,s)}var V3=V({einsum_:$$});function D$(e){let n={x:_(e,"x","elu","float32")};return B.runKernel(Pa,n)}var dd=V({elu_:D$});function _$(e){let t=_(e,"x","erf");O(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=he(t,"float32"));let n={x:t};return B.runKernel(Jl,n)}var U3=V({erf_:_$});function P$(e){let n={x:_(e,"x","exp")};return B.runKernel(Fa,n)}var Ts=V({exp_:P$});function F$(e,t=0){let n=_(e,"x","expandDims","string_or_numeric");O(t<=n.rank,()=>"Axis must be <= rank of the tensor");let s={input:n},r={dim:t};return B.runKernel(ui,s,r)}var Kt=V({expandDims_:F$});function O$(e){let n={x:_(e,"x","expm1")};return B.runKernel(ci,n)}var G3=V({expm1_:O$});function M$(e,t){let n=_(e,"x","tile","string_or_numeric");O(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);let s={x:n},r={reps:t};return B.runKernel(qr,s,r)}var js=V({tile_:M$});function z$(e,t,n,s="float32"){t==null&&(t=e);let r=Le([e,t],s),a=e<=t?e:t;for(let i=0;i`Error in localResponseNormalization: x must be rank 3 or 4 but got
+ rank ${a.rank}.`),O(mn(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=a,i=!1;a.rank===3&&(i=!0,o=G(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let l={x:o},c={depthRadius:t,bias:n,alpha:s,beta:r},u=B.runKernel(Uc,l,c);return i?G(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var q3=V({localResponseNormalization_:J$});function Q$(e){let n={x:_(e,"x","log","float32")};return B.runKernel(Wa,n)}var Ns=V({log_:Q$});function eD(e){let n={x:_(e,"x","log1p")};return B.runKernel(su,n)}var Zh=V({log1p_:eD});function tD(e){return O(va(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let s=_(t,"x","tf.grad","string_or_numeric"),r=n!=null?_(n,"dy","tf.grad"):null;return B.tidy(()=>{let{value:a,grads:o}=B.gradients(()=>e(s),[s],r);return r!=null&&zn(a.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Yh(o),o[0]})}}function nD(e){return O(va(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{O(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let s=ad(t,"args","tf.grads","string_or_numeric"),r=n!=null?_(n,"dy","tf.grads"):null;return B.tidy(()=>{let{value:a,grads:o}=B.gradients(()=>e(...s),s,r);return r!=null&&zn(a.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Yh(o),o})}}function sD(e){return O(va(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{O(t instanceof Ye,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),O(n==null||n instanceof Ye,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:s,value:r}=B.gradients(()=>e(t),[t],n);return Yh(s),{grad:s[0],value:r}}}function rD(e){return O(va(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{O(Array.isArray(t)&&t.every(r=>r instanceof Ye),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),O(n==null||n instanceof Ye,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let s=B.gradients(()=>e(...t),t,n);return n!=null&&zn(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Yh(s.grads),s}}function X3(e,t){O(va(e),()=>"The f passed in variableGrads(f) must be a function"),O(t==null||Array.isArray(t)&&t.every(c=>c instanceof sd),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let c in B.registeredVariables)t.push(B.registeredVariables[c])}let s=n?t.filter(c=>!c.trainable):null,r=t.length;t=t.filter(c=>c.trainable),O(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);let a=!0,{value:o,grads:i}=B.gradients(e,t,null,a);O(i.some(c=>c!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),O(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);let l={};return t.forEach((c,u)=>{i[u]!=null&&(l[c.name]=i[u])}),s!=null&&s.forEach(c=>l[c.name]=null),{value:o,grads:l}}function Er(e){return B.customGrad(e)}function Yh(e){if(e.filter(n=>n==null).length>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
+ the f you passed encloses all operations that lead from x to y.`)}function aD(e){let n={x:_(e,"x","neg")};return B.runKernel(xi,n)}var Ot=V({neg_:aD});function oD(e){let n={x:_(e,"x","softplus")};return B.runKernel(pu,n)}var Cu=V({softplus_:oD});function iD(e){let t=_(e,"x","logSigmoid");return Er(s=>({value:Ot(Cu(Ot(s))),gradFunc:o=>W(o,hs(Ot(s)))}))(t)}var lD=V({logSigmoid_:iD});function uD(e,t=null,n=!1){let r={x:_(e,"x","max")},a={reductionIndices:t,keepDims:n};return B.runKernel(Va,r,a)}var rs=V({max_:uD});function cD(e,t){let n=_(e,"a","sub"),s=_(t,"b","sub");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(uo,r)}var xe=V({sub_:cD});function dD(e,t=null,n=!1){let s=_(e,"x","sum");s.dtype==="bool"&&(s=he(s,"int32"));let r={x:s},a={axis:t,keepDims:n};return B.runKernel(oo,r,a)}var Ie=V({sum_:dD});function pD(e,t=-1){let n=_(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return Er((r,a)=>{let o=!0,i=rs(r,t,!0),l=xe(r,i),c=xe(he(l,"float32"),Ns(Ie(Ts(l),t,o)));return a([c]),{value:c,gradFunc:(d,p)=>{let[h]=p,f=!0,m=Ts(h);return xe(d,W(Ie(d,t,f),m))}}})(n)}var B2=V({logSoftmax_:pD});function W2(e,t){for(let n=0;ne[a]);return[n,r]}function Qi(e,t){let n=t.map(s=>1);return K3(e,n,t)}function hD(e,t,n){O(W2(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function Y3(e,t){if(W2(e,t))return null;let n=[];for(let s=0;sn.push(s)),n}function V2(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function fD(e,t){let n=[];for(let s=t-e;s`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),O(Nr(n,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),r!=null&&O(mn(s),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r},d=B.runKernel(Ga,c,u);return l?G(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Qh=V({maxPool_:vD});function wD(e,t=[1,1,1],n,s,r,a="NDHWC"){let o=_(e,"x","maxPool3d"),i=o,l=!1;o.rank===4&&(l=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),O(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),O(a==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),r!=null&&O(mn(s),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},d=B.runKernel(Gc,c,u);return l?G(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var G2=V({maxPool3d_:wD});function kD(e,t,n,s,r=!1){let o={x:_(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:s,includeBatchInIndex:r},l=B.runKernel(bh,o,i);return{result:l[0],indexes:l[1]}}var Q3=V({maxPoolWithArgmax_:kD});function ID(e,t){let n=_(e,"a","maximum"),s=_(t,"b","maximum");[n,s]=Ft(n,s),n.dtype==="bool"&&(n=he(n,"int32"),s=he(s,"int32")),St(n.shape,s.shape);let r={a:n,b:s};return B.runKernel(Ua,r)}var Yr=V({maximum_:ID});function SD(e,t=null,n=!1){let r={x:_(e,"x","mean")},a={axis:t,keepDims:n};return B.runKernel(Ha,r,a)}var Wt=V({mean_:SD});function Ht(e,t="float32"){if(t==="complex64"){let s=Ht(e,"float32"),r=Ht(e,"float32");return yo(s,r)}let n=Qp(Ut(e),t);return B.makeTensor(n,e,t)}function gs(e,t="float32"){if(t==="complex64"){let s=gs(e,"float32"),r=Ht(e,"float32");return yo(s,r)}let n=Lg(Ut(e),t);return B.makeTensor(n,e,t)}function CD(e,t,{indexing:n="xy"}={}){if(n!=="xy"&&n!=="ij")throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(e===void 0)return[];let s=_(e,"x","meshgrid",e instanceof Ye?e.dtype:"float32");if(t===void 0)return[s];let r=_(t,"y","meshgrid",t instanceof Ye?t.dtype:"float32"),a=Ut(s.shape),o=Ut(r.shape);return n==="xy"?(s=G(s,[1,-1]),r=G(r,[-1,1]),[He(gs([o,1],s.dtype),s),He(r,gs([1,a],r.dtype))]):(s=G(s,[-1,1]),r=G(r,[1,-1]),[He(s,gs([1,o],s.dtype)),He(gs([a,1],r.dtype),r)])}function TD(e,t=null,n=!1){let r={x:_(e,"x","min")},a={axis:t,keepDims:n};return B.runKernel(ja,r,a)}var ef=V({min_:TD});function ND(e,t){let n=_(e,"a","minimum"),s=_(t,"b","minimum");[n,s]=Ft(n,s),n.dtype==="bool"&&(n=he(n,"int32"),s=he(s,"int32")),St(n.shape,s.shape);let r={a:n,b:s};return B.runKernel(qa,r)}var hd=V({minimum_:ND});function ED(e,t,n){O(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let s=_(e,"x","mirrorPad");if(s.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");O(t.length===s.rank,()=>`Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`);let r=n==="reflect"?1:0;for(let i=0;i"Invalid number of paddings. Must be length of 2 each."),O(t[i][0]>=0&&t[i][0]<=s.shape[i]-r&&t[i][1]>=0&&t[i][1]<=s.shape[i]-r,()=>`Padding in dimension ${i} cannot be greater than or equal to ${s.shape[i]-r} or less than 0 for input of shape ${s.shape}`);let a={paddings:t,mode:n},o={x:s};return B.runKernel(Xa,o,a)}var ev=V({mirrorPad_:ED});function RD(e,t){let n=_(e,"a","mod"),s=_(t,"b","mod");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(au,r)}var tv=V({mod_:RD});function $D(e){let t=_(e,"x","square"),n={};return B.runKernel("Square",{x:t},n)}var xt=V({square_:$D});function DD(e,t=null,n=!1){e=_(e,"x","moments");let s=Us(t,e.shape),r=Wt(e,s,n),a=r.shape;n||(a=Qi(r.shape,s));let o=xt(xe(he(e,"float32"),G(r,a))),i=Wt(o,s,n);return{mean:r,variance:i}}var tf=V({moments_:DD});function _D(e,t,n,s){let r=_(t,"data","multiRNNCell"),a=ad(n,"c","multiRNNCell"),o=ad(s,"h","multiRNNCell"),i=r,l=[];for(let d=0;d2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);n=n||Math.random();let l={logits:o===1?G(r,[1,-1]):r},c={numSamples:t,seed:n,normalized:s},u=B.runKernel(vh,l,c);return o===1?G(u,[u.size]):u}var nv=V({multinomial_:FD});function OD(e,t){let n=_(e,"a","notEqual","string_or_numeric"),s=_(t,"b","notEqual","string_or_numeric");[n,s]=Ft(n,s),St(n.shape,s.shape);let r={a:n,b:s};return B.runKernel(bi,r)}var Tu=V({notEqual_:OD});function MD(e){let n={x:_(e,"x","onesLike")};return B.runKernel(ki,n)}var Es=V({onesLike_:MD});function zD(e,t){let n=_(e,"v1","outerProduct"),s=_(t,"v2","outerProduct");O(n.rank===1&&s.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${s.rank}.`);let r=G(n,[-1,1]),a=G(s,[1,-1]);return He(r,a)}var LD=V({outerProduct_:zD});function BD(e,t,n=0){let s=_(e,"x","pad");if(s.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let r={paddings:t,constantValue:n},a={x:s};return B.runKernel(Za,a,r)}var qs=V({pad_:BD});function WD(e,t,n=0){return O(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),qs(e,[t],n)}var VD=V({pad1d_:WD});function UD(e,t,n=0){return O(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),qs(e,t,n)}var GD=V({pad2d_:UD});function HD(e,t,n=0){return O(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."),qs(e,t,n)}var jD=V({pad3d_:HD});function qD(e,t,n=0){return O(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."),qs(e,t,n)}var XD=V({pad4d_:qD});function KD(e,t,n){let s=_(e,"x","spaceToBatchND");O(s.rank>=1+t.length,()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`),O(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),O(s.shape.reduce((o,i,l)=>l>0&&l<=t.length?o&&(i+n[l-1][0]+n[l-1][1])%t[l-1]==0:o,!0),()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);let r={x:s},a={blockShape:t,paddings:n};return B.runKernel(Pi,r,a)}var nf=V({spaceToBatchND_:KD});function ZD(e,t,n,s,r,a){r==null&&(r=[1,1]),a==null&&(a=1),s===0&&(s="valid");let o=_(e,"x","maxPool"),i=o,l=!1;o.rank===3&&(l=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2]])),O(Nr(a,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${r}'`);let c=S3(i.shape,t,a,r,s),u=[c.dilationHeight,c.dilationWidth],d;s==="same"?d=JD([c.filterHeight,c.filterWidth],u):d=[[0,0],[0,0]];let p=u[0]===1&&u[1]===1,[h,f]=YD([c.inHeight,c.inWidth],u,d),m=p?s:"valid",g=p?i:nf(i,u,h),y=(n==="avg"?()=>Hh(g,t,a,m):()=>Qh(g,t,a,m))(),x=p?y:jh(y,u,f);return l?G(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function YD(e,t,n){let s=n.map(u=>u[0]),r=n.map(u=>u[1]),a=e.concat(s,r),o=t.map((u,d)=>(u-a[d]%u)%u),i=r.map((u,d)=>u+o[d]),l=t.map((u,d)=>[s[d],i[d]]),c=t.map((u,d)=>[0,o[d]]);return[l,c]}function JD(e,t){let s=e.map((o,i)=>o+(o-1)*(t[i]-1)).map(o=>o-1),r=s.map(o=>Math.floor(o/2)),a=s.map((o,i)=>o-r[i]);return s.map((o,i)=>[r[i],a[i]])}var QD=V({pool_:ZD});function e_(e,t){let n=_(e,"base","pow"),s=_(t,"exp","pow");[n,s]=Ft(n,s);let r={a:n,b:s};return B.runKernel(Ya,r)}var Io=V({pow_:e_});function t_(e,t){let n=_(e,"x","prelu"),s=_(t,"alpha","prelu"),r={x:n,alpha:s};return B.runKernel(Ja,r)}var sf=V({prelu_:t_});function n_(e,t=null,n=!1){let s=_(e,"x","prod");s.dtype==="bool"&&(s=he(s,"int32"));let r={x:s},a={axis:t,keepDims:n};return B.runKernel(Ci,r,a)}var H2=V({prod_:n_});function s_(e,t,n){let s=Ut(e),r=null;if(n==null||n==="float32")r=new Float32Array(s);else if(n==="int32")r=new Int32Array(s);else if(n==="bool")r=new Uint8Array(s);else throw new Error(`Unknown data type ${n}`);for(let a=0;a=1||a===0);let o=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*s*o,t=this.mean+this.stdDev*r*o,(!this.truncated||this.isValidTruncated(e))&&(n=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}},a_=class{constructor(e,t,n,s){this.alpha=e,this.beta=1/t,this.dtype=n;let r=s||Math.random();this.randu=j2.alea(r.toString()),this.randn=new q2(0,1,n,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,s,r,a;for(;;){do s=this.randn.nextValue(),a=1+this.c*s;while(a<=0);if(a*=a*a,e=s*s,t=1-.331*e*e,n=.5*e+this.d*(1-a+Math.log(a)),r=this.randu(),rthis.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,s==null&&(s=Math.random()),typeof s=="number"&&(s=s.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=j2.alea(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function i_(e,t,n=1,s="float32",r){if(n==null&&(n=1),s==null&&(s="float32"),s!=="float32"&&s!=="int32")throw new Error(`Unsupported data type ${s}`);let a=new a_(t,n,s,r),o=Le(e,s);for(let i=0;i`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Rs(t,0)}var A_=V({reverse1d_:g_});function y_(e,t){let n=_(e,"x","reverse");return O(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),Rs(n,t)}var x_=V({reverse2d_:y_});function b_(e,t){let n=_(e,"x","reverse");return O(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),Rs(n,t)}var v_=V({reverse3d_:b_});function w_(e,t){let n=_(e,"x","reverse");return O(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),Rs(n,t)}var k_=V({reverse4d_:w_});function I_(e){let n={x:_(e,"x","round")};return B.runKernel(Ei,n)}var K2=V({round_:I_});function S_(e){let n={x:_(e,"x","rsqrt","float32")};return B.runKernel(no,n)}var Z2=V({rsqrt_:S_});function Ee(e,t){if((Dn(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"&&Dn(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return xo(e,[],[],t)}function C_(e){let n={x:_(e,"x","selu")};return B.runKernel(cu,n)}var Y2=V({selu_:C_});function T_(e,t,n,s,r,a=[1,1],o="NHWC"){let i=_(e,"x","separableConv2d"),l=_(t,"depthwiseFilter","separableConv2d"),c=_(n,"pointwiseFilter","separableConv2d"),u=i,d=!1;if(i.rank===3&&(d=!0,u=G(i,[1,i.shape[0],i.shape[1],i.shape[2]])),o==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");O(u.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`),O(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),O(c.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),O(c.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`),O(c.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`);let p=l.shape[2],h=l.shape[3];O(c.shape[2]===p*h,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*h}, but got ${c.shape[2]}.`);let f=cd(u,l,s,r,o,a),g=ko(f,c,1,"valid",o);return d?G(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var av=V({separableConv2d_:T_});async function N_(e,t){let n=_(e,"x","setdiff1d"),s=_(t,"y","setdiff1d");O(n.dtype===s.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`),O(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),O(s.rank===1,()=>`y should be 1D tensor, but got y (${s.shape}).`);let r=await n.data(),a=await s.data(),o=new Set(a),i=0;for(let u=0;u`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),_e(s,[t],[n])}var rf=V({slice1d_:D_});function __(e,t,n){let s=_(e,"x","slice2d");return O(s.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),_e(s,t,n)}var e1=V({slice2d_:__});function P_(e,t,n){let s=_(e,"x","slice3d");return O(s.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),_e(s,t,n)}var Ru=V({slice3d_:P_});function F_(e,t,n){let s=_(e,"x","slice4d");return O(s.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),_e(s,t,n)}var md=V({slice4d_:F_});function O_(e,t=-1){let n=_(e,"logits","softmax","float32");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);let s={logits:n},r={dim:t};return B.runKernel(io,s,r)}var $u=V({softmax_:O_});function M_(e){O(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return B.runKernel(fh,t)}var af=V({fft_:M_});function z_(e){O(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return B.runKernel(mh,t)}var gd=V({ifft_:z_});function L_(e){let t=e.shape[e.shape.length-1],n=e.size/t,s;if(t<=2){let r=G(e,[n,t]);s=gd(r)}else{let r=[n,2*(t-1)],a=G(fd(e),[n,t]),o=G(Xh(e),[n,t]),i=Rs(_e(a,[0,1],[n,t-2]),1),l=W(Rs(_e(o,[0,1],[n,t-2]),1),Ee(-1)),c=It([a,i],1),u=It([o,l],1),d=G(yo(c,u),[r[0],r[1]]);s=gd(d)}if(s=fd(s),e.rank===3&&e.shape[0]!==0){let r=s,a=e.shape[0];s=G(s,[a,s.shape[0]/a,s.shape[1]]),r.dispose()}return s}var t1=V({irfft_:L_});function B_(e,t,n=0){let r={x:_(e,"x","split")},a={numOrSizeSplits:t,axis:n};return B.runKernel(Fi,r,a)}var Sn=V({split_:B_});function W_(e,t){O(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1],s=e.size/n,r;if(t!=null&&t0),m=e.shape.map(g=>g);m[e.shape.length-1]=t,r=_e(e,f,m),n=t}else if(t!=null&&t>n){let f=e.shape.map(m=>m);f[e.shape.length-1]=t-n,r=It([e,Ht(f)],e.shape.length-1),n=t}else r=e;let a=tt(r),o=G(yo(r,a),[s,n]),i=af(o),l=Math.floor(n/2)+1,c=fd(i),u=Xh(i),d=Sn(c,[l,n-l],c.shape.length-1),p=Sn(u,[l,n-l],u.shape.length-1),h=r.shape.slice();return h[r.shape.length-1]=l,G(yo(d[0],p[0]),h)}var of=V({rfft_:W_});function V_(e){let n={x:_(e,"x","sqrt","float32")};return B.runKernel(ao,n)}var _n=V({sqrt_:V_});function U_(e,t){let n=_(e,"a","squaredDifference"),s=_(t,"b","squaredDifference");[n,s]=Ft(n,s),St(n.shape,s.shape);let r={a:n,b:s},a={};return B.runKernel(lo,r,a)}var n1=V({squaredDifference_:U_});function G_(e,t){let n=_(e,"x","squeeze");return G(n,s5(n.shape,t).newShape)}var pt=V({squeeze_:G_});function H_(e,t=0){let n=ad(e,"tensors","stack","string_or_numeric");O(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&O(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let s=n,r={axis:t};return B.runKernel(Si,s,r)}var Pn=V({stack_:H_});function j_(e,t=0){let s={x:_(e,"x","step")},r={alpha:t};return B.runKernel(ho,s,r)}var Ad=V({step_:j_});function q_(e,t,n,s,r=0,a=0,o=0,i=0,l=0){let u={x:_(e,"x","stridedSlice","string_or_numeric")},d={begin:t,end:n,strides:s,beginMask:r,endMask:a,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:l};return B.runKernel(Oi,u,d)}var lv=V({stridedSlice_:q_});function X_(e){let n={x:_(e,"x","tan","float32")};return B.runKernel(Mi,n)}var uv=V({tan_:X_});function Zt(e,t){ei(e);let n=Cr(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return xo(e,null,n,t)}function ur(e,t,n){if(ei(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let s=Cr(e,n);if(s.length!==2&&s.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return xo(e,t,s,n)}function K_(e,t,n){if(ei(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let s=Cr(e,n);if(s.length!==4&&s.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return xo(e,t,s,n)}function Z_(e,t,n){if(ei(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let s=Cr(e,n);if(s.length!==5&&s.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return xo(e,t,s,n)}function Y_(e,t,n){if(ei(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let s=Cr(e,n);if(s.length!==6&&s.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||s,xo(e,t,s,n)}function J_(e,t=1,n=!0){let s=_(e,"x","topk");if(s.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let r=s.shape[s.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);let a={x:s},o={k:t,sorted:n},[i,l]=B.runKernel(zi,a,o);return{values:i,indices:l}}var cv=V({topk_:J_});function Q_(e,t=0,n=1,s,r){if(s!=null&&s==="bool")throw new Error("Unsupported data type $ { dtype }");let a=new q2(t,n,s,!0,r),o=Le(e,s);for(let i=0;i0,()=>"The input tensor must be at least 1D");let s={x:n},r={axis:t},[a,o]=B.runKernel(Rh,s,r);return{values:a,indices:o}}var s1=V({unique_:eP});function tP(e,t,n){let s=_(e,"x","unsortedSegmentSum"),r=_(t,"segmentIds","unsortedSegmentSum","int32");O(mn(n),()=>"numSegments must be of dtype int");let a={x:s,segmentIds:r},o={numSegments:n};return B.runKernel(Xc,a,o)}var dv=V({unsortedSegmentSum_:tP});function nP(e,t=0){let n=_(e,"x","unstack","string_or_numeric");O(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);let s={value:n},r={axis:t};return B.runKernel(Bi,s,r)}var as=V({unstack_:nP});function pv(e,t=!0,n,s){return B.makeVariable(e,t,n,s)}function hv(e,t){let n=[];for(let a=0;a0,()=>"mask cannot be scalar"),zn(i.slice(a,a+o),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let m=a;m"Shape mismatch in v and x");let l=Ee(1),c=xe(l,i),u=W(xe(o,a),c);if(r){O(s!=null,()=>"When using zeroDebias: true, step is required.");let d=_(s,"step","movingAverage");u=fe(u,xe(l,Io(i,d)))}return ie(a,u)}var lP=V({movingAverage_:iP});function uP(e,t,n){let s=_(e,"indices","scatterND","int32"),r=_(t,"updates","scatterND");b2(r,s,n);let a={indices:s,updates:r},o={shape:n};return B.runKernel(Ri,a,o)}var mv=V({scatterND_:uP});function cP(e,t,n,s){if(e.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);let r=e.rank>0?e.shape[0]:1,a=e.rank>1?e.shape[1]:1;if(n.length!==a)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${a}.`);let o=t.size;if(!(t.rank===0||t.rank===1&&o===r))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${r}]`);if(t.dtype!==s.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function dP(e,t,n,s=0){let r=_(e,"sparseIndices","sparseToDense","int32"),a=_(t,"sparseValues","sparseToDense"),o=_(s,"defaultValue","sparseToDense",a.dtype);cP(r,a,n,o);let i={sparseIndices:r,sparseValues:a,defaultValue:o},l={outputShape:n};return B.runKernel(jc,i,l)}var o1=V({sparseToDense_:dP});function pP(e,t){let n=_(t,"indices","gatherND","int32"),r={params:_(e,"x","gatherND","string_or_numeric"),indices:n};return B.runKernel(hi,r)}var gv=V({gatherND_:pP});function hP(e,t){if(t==null)return e.shape.slice();if(Gr(e.shape,t))return t;if(e.shape.length===t.length){let n=[];for(let s=0;s`x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`),O(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof Ye?r.clone():r;let a=hP(r,n),o=1-t,i=fe(pd(ie(Nu(a,0,1,"float32",s),o)),o);return W(r,i)}var Av=V({dropout_:fP});function yv(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function i1(e,t,n){let s=1-e%2,r=new Float32Array(e);for(let a=0;a1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${s.rank}`),O(s.rank-1===r.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${s.rank} and targets rank ${r.rank}`),zn(s.shape.slice(0,s.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let a=s.shape[s.shape.length-1];O(n>0&&n<=a,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`);let o=await s.data(),i=await r.data(),[l,c]=[o.length/a,a],u=r5("bool",l);for(let d=0;dg.value-m.value),u[d]=0;for(let m=0;mxP,depthwiseConv2d:()=>kP,matMul:()=>SP});function AP(e,t,n,s,r,a="NHWC",o){let i=e;e.rank===3&&(i=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=G(t,[1,t.shape[0],t.shape[1],t.shape[2]])),O(i.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),O(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),O(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);let c=a==="NHWC"?i.shape[3]:i.shape[1],u=a==="NHWC"?l.shape[3]:l.shape[1];O(c===n[2],()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${n[2]}.`),O(u===n[3],()=>`Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${n[3]}).`),o!=null&&O(mn(r),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let d={x:i,dy:l},p={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,filterShape:n};return B.runKernel(rh,d,p)}var l1=V({conv2DBackpropFilter_:AP});function uf(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return W(e,Ad(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function cf(e,t){let n=t,s=an(e.shape,t.shape);return s.length>0&&(n=Ie(n,s)),G(n,e.shape)}function df(e,t,n,s){if(t==="linear")return e;if(t==="relu")return Rr(e);if(t==="elu")return dd(e);if(t==="relu6")return X2(e);if(t==="prelu")return sf(e,n);if(t==="leakyrelu")return Kh(e,s);if(t==="sigmoid")return hs(e);throw new Error(`Unknown fused activation ${t}.`)}var pf=(e,t)=>!(e>0)||t==="linear";function yP({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(l=l||"linear",pf(B.state.gradientDepth,l)===!1){let w=ko(e,t,n,s,r,a,o);return i!=null&&(w=ie(w,i)),df(w,l,c,u)}let d=_(e,"x","conv2d","float32"),p=_(t,"filter","conv2d","float32"),h=d,f=!1;d.rank===3&&(f=!0,h=G(d,[1,d.shape[0],d.shape[1],d.shape[2]])),O(h.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`),O(p.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`),o!=null&&O(mn(s),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`),O(h.shape[3]===p.shape[2],()=>`Error in conv2d: depth of input (${h.shape[3]}) must match input depth for filter ${p.shape[2]}.`),O(Nr(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),O(r==="NHWC",()=>`Error in conv2d: got dataFormat of ${r} but only NHWC is currently supported.`);let m=ld(h.shape,p.shape,n,a,s,o),g;i!=null&&(g=_(i,"bias","fused conv2d"),[g]=Ft(g,d),St(m.outShape,g.shape));let A;c!=null&&(A=_(c,"prelu weights","fused conv2d"));let y=(w,k)=>{let[S,E,$,F]=k,R=uf(w,$,l);O(wo(a),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);let P=_2(E.shape,R,S,n,s),T=l1(E,R,S.shape,n,s),M=[P,T];if(F!=null){let U=cf(F,R);M.push(U)}return M},x={x:h,filter:p,bias:g,preluActivationWeights:A},b={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:u};return i==null?Er((k,S,E)=>{let $=B.runKernel(mo,x,b);return E([S,k,$]),f&&($=G($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:y}})(h,p):Er((k,S,E,$)=>{let F=B.runKernel(mo,x,b);return $([S,k,F,E]),f&&(F=G(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:y}})(h,p,g)}var xP=V({fusedConv2d_:yP});function bP(e,t,n,s,r,a=[1,1],o){let i=e;e.rank===3&&(i=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=G(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let c={x:i,dy:l},u={strides:s,pad:r,dimRoundingMode:o,dilations:a,filterShape:n};return B.runKernel(lh,c,u)}var xv=V({depthwiseConv2dNativeBackpropFilter_:bP});function vP(e,t,n,s,r,a=[1,1],o){let i=t,l=!1;t.rank===3&&(l=!0,i=G(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let c={dy:i,filter:n},u={strides:s,pad:r,dimRoundingMode:o,dilations:a,inputShape:e},d=B.runKernel(uh,c,u);return l?G(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var bv=V({depthwiseConv2dNativeBackpropInput_:vP});function wP({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(pf(B.state.gradientDepth,l)===!1){let w=cd(e,t,n,s,r,a,o);return i!=null&&(w=ie(w,i)),df(w,l,c,u)}let d=_(e,"x","depthwiseConv2d","float32"),p=_(t,"filter","depthwiseConv2d","float32"),h=d,f=!1;d.rank===3&&(f=!0,h=G(d,[1,d.shape[0],d.shape[1],d.shape[2]])),O(h.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`),O(p.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`),O(h.shape[3]===p.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),a==null&&(a=[1,1]),O(Nr(n,a),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o!=null&&O(mn(s),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${o} but got pad ${s}.`);let m=ld(h.shape,p.shape,n,a,s,o,!0),g;i!=null&&(g=_(i,"bias","fused conv2d"),[g]=Ft(g,d),St(m.outShape,g.shape));let A;c!=null&&(A=_(c,"prelu weights","fused depthwiseConv2d"));let y=(w,k)=>{O(wo(a),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);let[S,E,$,F]=k,R=uf(w,$,l),P=bv(E.shape,R,S,n,s,a,o),T=xv(E,R,S.shape,n,s,a,o);if(F!=null){let M=cf(g,R);return[P,T,M]}return[P,T]},x={x:h,filter:p,bias:g,preluActivationWeights:A},b={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:u};return i==null?Er((k,S,E)=>{let $=B.runKernel(go,x,b);return E([S,k,$]),f&&($=G($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:y}})(h,p):Er((k,S,E,$)=>{let F=B.runKernel(go,x,b);return $([S,k,F,E]),f&&(F=G(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:y}})(h,p,g)}var kP=V({fusedDepthwiseConv2d_:wP});function IP({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:r,activation:a="linear",preluActivationWeights:o,leakyreluAlpha:i}){if(pf(B.state.gradientDepth,a)===!1){let F=He(e,t,n,s);return r!=null&&(F=ie(F,r)),df(F,a,o,i)}let l=_(e,"a","fused matMul"),c=_(t,"b","fused matMul");[l,c]=Ft(l,c);let u=n?l.shape[l.rank-2]:l.shape[l.rank-1],d=s?c.shape[c.rank-1]:c.shape[c.rank-2],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],h=s?c.shape[c.rank-2]:c.shape[c.rank-1],f=l.shape.slice(0,-2),m=c.shape.slice(0,-2),g=Ut(f),A=Ut(m);O(l.rank>=2&&c.rank>=2&&l.rank===c.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${l.rank} and ${c.rank}.`),O(Gr(f,m),()=>`Error in fused matMul: outer dimensions (${f}) and (${m}) of Tensors with shapes ${l.shape} and ${c.shape} must match.`),O(u===d,()=>`Error in fused matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${l.shape} and ${c.shape} and transposeA=${n} and transposeB=${s} must match.`);let y=l.shape.slice(0,-2).concat([p,h]),x=n?G(l,[g,u,p]):G(l,[g,p,u]),b=s?G(c,[A,h,d]):G(c,[A,d,h]),w;r!=null&&(w=_(r,"bias","fused matMul"),[w]=Ft(w,l),St(y,w.shape));let k;o!=null&&(k=_(o,"prelu weights","fused matMul"));let S=(F,R)=>{let[P,T,M,U]=R,H=uf(G(F,M.shape),M,a),z,X;if(!n&&!s?(z=He(H,T,!1,!0),X=He(P,H,!0,!1)):!n&&s?(z=He(H,T,!1,!1),X=He(H,P,!0,!1)):n&&!s?(z=He(T,H,!1,!0),X=He(P,H,!1,!1)):(z=He(T,H,!0,!0),X=He(H,P,!0,!0)),r!=null){let ee=cf(U,H);return[z,X,ee]}else return[z,X]},E={a:x,b,bias:w,preluActivationWeights:k},$={transposeA:n,transposeB:s,activation:a,leakyreluAlpha:i};return r==null?Er((R,P,T)=>{let M=B.runKernel(fo,E,$);return T([R,P,M]),{value:G(M,y),gradFunc:S}})(x,b):Er((R,P,T,M)=>{let U=B.runKernel(fo,E,$);return M([R,P,U,T]),{value:G(U,y),gradFunc:S}})(x,b,w)}var SP=V({fusedMatMul_:IP});function CP(e){return i1(e,.54,.46)}var TP=V({hammingWindow_:CP});function NP(e){return i1(e,.5,.5)}var vv=V({hannWindow_:NP});function EP(e,t,n,s=!1,r=0){let a=0,o=[];for(;a+t<=e.size;)o.push(_e(e,a,t)),a+=n;if(s)for(;a`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),O(i.rank===2&&i.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${i.shape}.`),O(l.rank===1&&l.shape[0]===c,()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${i.shape}.`),O(s.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),O(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),O(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);let u={image:o,boxes:i,boxInd:l},d={method:r,extrapolationValue:a,cropSize:s};return B.runKernel(oi,u,d)}var _P=V({cropAndResize_:DP});function PP(e){let t=_(e,"image","flipLeftRight","float32");O(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return B.runKernel(di,n,{})}var FP=V({flipLeftRight_:PP});function OP(e){let t=_(e,"image","grayscaleToRGB"),n=t.rank-1,s=t.shape[n];O(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),O(s===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${s}.`);let r=new Array(t.rank);return r.fill(1,0,n),r[n]=3,js(t,r)}var MP=V({grayscaleToRGB_:OP});function zP(e,t,n=0,s=.5){let r=_(e,"image","rotateWithOffset","float32");O(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);let a={image:r},o={radians:t,fillValue:n,center:s};return B.runKernel(Vi,a,o)}var LP=V({rotateWithOffset_:zP});function Du(e,t,n,s,r,a){s==null&&(s=.5),r==null&&(r=Number.NEGATIVE_INFINITY),a==null&&(a=0);let o=e.shape[0];return n=Math.min(n,o),O(0<=s&&s<=1,()=>`iouThreshold must be in [0, 1], but was '${s}'`),O(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),O(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),O(t.rank===1,()=>"scores must be a 1D tensor"),O(t.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`),O(0<=a&&a<=1,()=>`softNmsSigma must be in [0, 1], but was '${a}'`),{maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a}}function BP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=_(e,"boxes","nonMaxSuppression","float32"),o=_(t,"scores","nonMaxSuppression","float32"),i=Du(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l={maxOutputSize:n,iouThreshold:s,scoreThreshold:r};return B.runKernel(vi,{boxes:a,scores:o},l)}var WP=V({nonMaxSuppression_:BP});function VP(e,t,n){let s=UP(e,t,n),r=s<0?-(s+1):s;e.splice(r,0,t)}function UP(e,t,n){return HP(e,t,n||GP)}function GP(e,t){return e>t?1:e>>1);let i=n(t,e[a]);i>0?s=a+1:(r=a,o=!i)}return o?s:-s-1}function kv(e,t,n,s,r){return u1(e,t,n,s,r,0)}function Iv(e,t,n,s,r,a){return u1(e,t,n,s,r,0,!1,a,!0)}function Sv(e,t,n,s,r,a){return u1(e,t,n,s,r,a,!0)}function u1(e,t,n,s,r,a,o=!1,i=!1,l=!1){let c=[];for(let g=0;gr&&c.push({score:t[g],boxIndex:g,suppressBeginIndex:0});c.sort(Cv);let u=a>0?-.5/a:0,d=[],p=[];for(;d.length0;){let g=c.pop(),{score:A,boxIndex:y,suppressBeginIndex:x}=g;if(A=x;--w){let k=jP(e,y,d[w]);if(k>=s){b=!0;break}if(g.score=g.score*qP(s,u,k),g.score<=r)break}g.suppressBeginIndex=d.length,b||(g.score===A?(d.push(y),p.push(g.score)):g.score>r&&VP(c,g,Cv))}let h=d.length,f=n-h;i&&f>0&&(d.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));let m={selectedIndices:d};return o&&(m.selectedScores=p),l&&(m.validOutputs=h),m}function jP(e,t,n){let s=e.subarray(t*4,t*4+4),r=e.subarray(n*4,n*4+4),a=Math.min(s[0],s[2]),o=Math.min(s[1],s[3]),i=Math.max(s[0],s[2]),l=Math.max(s[1],s[3]),c=Math.min(r[0],r[2]),u=Math.min(r[1],r[3]),d=Math.max(r[0],r[2]),p=Math.max(r[1],r[3]),h=(i-a)*(l-o),f=(d-c)*(p-u);if(h<=0||f<=0)return 0;let m=Math.max(a,c),g=Math.max(o,u),A=Math.min(i,d),y=Math.min(l,p),x=Math.max(A-m,0)*Math.max(y-g,0);return x/(h+f-x)}function qP(e,t,n){let s=Math.exp(t*n*n);return n<=e?s:0}function Cv(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function XP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=_(e,"boxes","nonMaxSuppressionAsync"),o=_(t,"scores","nonMaxSuppressionAsync"),i=Du(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l=await Promise.all([a.data(),o.data()]),c=l[0],u=l[1],{selectedIndices:d}=kv(c,u,n,s,r);return a!==e&&a.dispose(),o!==t&&o.dispose(),Zt(d,"int32")}var KP=XP;function ZP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=_(e,"boxes","nonMaxSuppression"),i=_(t,"scores","nonMaxSuppression"),l=Du(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let c={boxes:o,scores:i},u={maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a},d=B.runKernel(wi,c,u);return{selectedIndices:d[0],selectedScores:d[1]}}var YP=V({nonMaxSuppressionWithScore_:ZP});async function JP(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=_(e,"boxes","nonMaxSuppressionAsync"),i=_(t,"scores","nonMaxSuppressionAsync"),l=Du(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let c=await Promise.all([o.data(),i.data()]),u=c[0],d=c[1],{selectedIndices:p,selectedScores:h}=Sv(u,d,n,s,r,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Zt(p,"int32"),selectedScores:Zt(h)}}var QP=JP;function eF(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=_(e,"boxes","nonMaxSuppression"),i=_(t,"scores","nonMaxSuppression"),l=Du(o,i,n,s,r,null),c=l.maxOutputSize,u=l.iouThreshold,d=l.scoreThreshold,p={boxes:o,scores:i},h={maxOutputSize:c,iouThreshold:u,scoreThreshold:d,padToMaxOutputSize:a},f=B.runKernel(ou,p,h);return{selectedIndices:f[0],validOutputs:f[1]}}var tF=V({nonMaxSuppressionPadded_:eF});async function nF(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=_(e,"boxes","nonMaxSuppressionAsync"),i=_(t,"scores","nonMaxSuppressionAsync"),l=Du(o,i,n,s,r,null),c=l.maxOutputSize,u=l.iouThreshold,d=l.scoreThreshold,[p,h]=await Promise.all([o.data(),i.data()]),{selectedIndices:f,validOutputs:m}=Iv(p,h,c,u,d,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Zt(f,"int32"),validOutputs:Ee(m,"int32")}}var sF=nF;function rF(e,t,n=!1,s=!1){let r=_(e,"images","resizeBilinear");O(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),O(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),O(s===!1||n===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let a=r,o=!1;r.rank===3&&(o=!0,a=G(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},c=B.runKernel(eo,i,l);return o?G(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var aF=V({resizeBilinear_:rF});function oF(e,t,n=!1,s=!1){let r=_(e,"images","resizeNearestNeighbor");O(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),O(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),O(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),O(s===!1||n===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let a=r,o=!1;r.rank===3&&(o=!0,a=G(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},c=B.runKernel(uu,i,l);return o?G(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var iF=V({resizeNearestNeighbor_:oF});function lF(e,t="binary",n=!1,s=.5){let r=_(e,"image","threshold"),a=.2989,o=.587,i=.114,l=r.shape[0]*r.shape[1],c=W(Zt([s]),255),u,d,p,h;if(O(r.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`),O(r.shape[2]===3||r.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`),O(r.dtype==="int32"||r.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`),O(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),r.shape[2]===3){[u,d,p]=Sn(r,[1,1,1],-1);let g=W(u,a),A=W(d,o),y=W(p,i);h=ie(ie(g,A),y)}else h=e;if(t==="otsu"){let g=$2(he(K2(h),"int32"),Gt([]),256);c=uF(g,l)}let f=n?Ji(h,c):ms(h,c);return he(W(f,255),"int32")}function uF(e,t){let n=Zt([-1]),s=Zt([0]),r=Zt([0]),a,o,i,l,c,u;for(let d=0;d`Error in transform: image must be rank 4,but got rank ${o.rank}.`),O(i.rank===2&&(i.shape[0]===o.shape[0]||i.shape[0]===1)&&i.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),O(a==null||a.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`);let l={image:o,transforms:i},c={interpolation:n,fillMode:s,fillValue:r,outputShape:a};return B.runKernel(Li,l,c)}var pF=V({transform_:dF});function hF(e,t,n){O(t%1==0,()=>`bandPart(): numLower must be an integer, got ${t}.`),O(n%1==0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);let s=_(e,"a","bandPart");O(s.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`);let r=s.shape,[a,o]=s.shape.slice(-2);if(!(t<=a))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`);if(!(n<=o))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`);t<0&&(t=a),n<0&&(n=o);let i=G(Eu(0,a,1,"int32"),[-1,1]),l=Eu(0,o,1,"int32"),c=xe(i,l),u=lr(Ji(c,Ee(+t,"int32")),Yi(c,Ee(-n,"int32"))),d=Ht([a,o],s.dtype);return G(Pn(as(G(s,[-1,a,o])).map(p=>Wn(u,p,d))),r)}var fF=V({bandPart_:hF});function mF(e){let t;if(Array.isArray(e)){t=!1,O(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let r=e[0].shape[0];for(let a=1;a`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[a].shape[0]} vs. ${r})`)}else t=!0,e=Sn(e,e.shape[0],0).map(r=>pt(r,[0]));O(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let n=[],s=e;for(let r=0;r{let a=s[r];if(r>0)for(let o=0;o=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return Tv(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,c)=>l*c),s=as(G(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],a=[];s.forEach(l=>{let[c,u]=Tv(l,t);r.push(c),a.push(u)});let o=G(Pn(r,0),e.shape),i=G(Pn(a,0),e.shape);return[o,i]}}function Tv(e,t=!1){return B.tidy(()=>{O(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let n=e.shape[0],s=e.shape[1],r=z2(n),a=or(e),o=ur([[1]],[1,1]),i=or(o),l=n>=s?s:n;for(let c=0;c{let h=_e(a,[c,c],[n-c,1]),f=a1(h),m=_e(a,[c,c],[1,1]),g=Wn(ms(m,0),ur([[-1]]),ur([[1]])),A=xe(m,W(g,f)),y=fe(h,A);y.shape[0]===1?i=or(o):i=It([o,_e(y,[1,0],[y.shape[0]-1,y.shape[1]])],0);let x=Ot(fe(He(g,A),f)),b=_e(a,[c,0],[n-c,s]),w=W(x,i),k=et(i);if(c===0)a=xe(b,He(w,He(k,b)));else{let $=xe(b,He(w,He(k,b)));a=It([_e(a,[0,0],[c,s]),$],0)}let S=et(w),E=_e(r,[0,c],[n,r.shape[1]-c]);if(c===0)r=xe(E,He(He(E,i),S));else{let $=xe(E,He(He(E,i),S));r=It([_e(r,[0,0],[n,c]),$],1)}return[i,a,r]}),Q([u,d,p])}return!t&&n>s&&(r=_e(r,[0,0],[n,s]),a=_e(a,[0,0],[s,s])),[r,a]})}var yF=V({qr_:AF}),Vn;(function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(Vn||(Vn={}));function xF(e,t,n=Vn.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=_(t,"weights","computeWeightedLoss"));let a=r==null?s:W(s,r);if(n===Vn.NONE)return a;if(n===Vn.SUM)return Ie(a);if(n===Vn.MEAN){if(r==null)return Wt(a);{let o=s.size/r.size,i=fe(Ie(a),Ie(r));return o>1?fe(i,Ee(o)):i}}if(n===Vn.SUM_BY_NONZERO_WEIGHTS){if(r==null)return fe(Ie(a),Ee(s.size));{let o=W(r,gs(s.shape)),i=he(Ie(Tu(o,Ee(0))),"float32");return fe(Ie(a),i)}}throw Error(`Unknown reduction: ${n}`)}var Jr=V({computeWeightedLoss_:xF});function bF(e,t,n,s=Vn.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","absoluteDifference"),a=_(t,"predictions","absoluteDifference"),o=null;n!=null&&(o=_(n,"weights","absoluteDifference")),zn(r.shape,a.shape,"Error in absoluteDifference: ");let i=rn(xe(r,a));return Jr(i,o,s)}var vF=V({absoluteDifference_:bF});function wF(e,t,n,s,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"labels","cosineDistance"),o=_(t,"predictions","cosineDistance"),i=null;s!=null&&(i=_(s,"weights","cosineDistance")),zn(a.shape,o.shape,"Error in cosineDistance: ");let l=Ee(1),c=xe(l,Ie(W(a,o),n,!0));return Jr(c,i,r)}var kF=V({cosineDistance_:wF});function IF(e,t,n,s=Vn.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","hingeLoss"),a=_(t,"predictions","hingeLoss"),o=null;n!=null&&(o=_(n,"weights","hingeLoss")),zn(r.shape,a.shape,"Error in hingeLoss: ");let i=Ee(1);r=xe(W(Ee(2),r),i);let l=Rr(xe(i,W(r,a)));return Jr(l,o,s)}var SF=V({hingeLoss_:IF});function CF(e,t,n,s=1,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"labels","huberLoss"),o=_(t,"predictions","huberLoss"),i=null;n!=null&&(i=_(n,"weights","huberLoss")),zn(a.shape,o.shape,"Error in huberLoss: ");let l=Ee(s),c=rn(xe(o,a)),u=hd(c,l),d=xe(c,u),p=ie(W(Ee(.5),xt(u)),W(l,d));return Jr(p,i,r)}var TF=V({huberLoss_:CF});function NF(e,t,n,s=1e-7,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"labels","logLoss"),o=_(t,"predictions","logLoss"),i=null;n!=null&&(i=_(n,"weights","logLoss")),zn(a.shape,o.shape,"Error in logLoss: ");let l=Ee(1),c=Ee(s),u=Ot(W(a,Ns(ie(o,c)))),d=W(xe(l,a),Ns(ie(xe(l,o),c))),p=xe(u,d);return Jr(p,i,r)}var EF=V({logLoss_:NF});function RF(e,t,n,s=Vn.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","meanSquaredError"),a=_(t,"predictions","meanSquaredError"),o=null;n!=null&&(o=_(n,"weights","meanSquaredError")),zn(r.shape,a.shape,"Error in meanSquaredError: ");let i=n1(r,a);return Jr(i,o,s)}var $F=V({meanSquaredError_:RF});function DF(e,t){let n=_(e,"labels","sigmoidCrossEntropyWithLogits"),s=_(t,"logits","sigmoidCrossEntropyWithLogits");zn(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=Rr(s),a=W(s,n),o=Zh(Ts(Ot(rn(s))));return ie(xe(r,a),o)}function _F(e,t,n,s=0,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"multiClassLabels","sigmoidCrossEntropy"),o=_(t,"logits","sigmoidCrossEntropy"),i=null;if(n!=null&&(i=_(n,"weights","sigmoidCrossEntropy")),zn(a.shape,o.shape,"Error in sigmoidCrossEntropy: "),s>0){let c=Ee(s),u=Ee(1),d=Ee(.5);a=ie(W(a,xe(u,c)),W(d,c))}let l=DF(a,o);return Jr(l,i,r)}var PF=V({sigmoidCrossEntropy_:_F});function FF(e,t,n=-1){if(n===-1&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);return Er((r,a,o)=>{let l=J3(a,[n],!0),c=xe(he(a,"float32"),l);o([r,c]);let u=Ot(W(c,r));return{value:Ie(u,[n]),gradFunc:(h,f)=>{let[m,g]=f,A=Qi(h.shape,[n]);return[W(G(h,A),xe(he(m,"float32"),Ts(g))),W(G(h,A),xe(Ts(g),he(m,"float32")))]}}})(e,t)}function OF(e,t,n,s=0,r=Vn.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"onehotLabels","softmaxCrossEntropy"),o=_(t,"logits","softmaxCrossEntropy"),i=null;if(n!=null&&(i=_(n,"weights","softmaxCrossEntropy")),zn(a.shape,o.shape,"Error in softmaxCrossEntropy: "),s>0){let c=Ee(s),u=Ee(1),d=Ee(a.shape[1]);a=ie(W(a,xe(u,c)),fe(c,d))}let l=FF(a,o);return Jr(l,i,r)}var MF=V({softmaxCrossEntropy_:OF});function zF(e,t,n,s){let r=_(e,"indices","sparseFillEmptyRows"),a=_(t,"values","sparseFillEmptyRows"),o=_(n,"denseShape","sparseFillEmptyRows"),i=_(s,"defaultValue","sparseFillEmptyRows",a.dtype);if(r.rank!==2)throw new Error(`Indices should be Tensor2D but received shape
+ ${r.shape}`);if(a.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(o.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(i.rank!==0)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);let l={indices:r,values:a,denseShape:o,defaultValue:i},c=B.runKernel(Ih,l);return{outputIndices:c[0],outputValues:c[1],emptyRowIndicator:c[2],reverseIndexMap:c[3]}}var LF=V({sparseFillEmptyRows_:zF});function BF(e,t,n){let s=_(e,"inputIndices","sparseReshape"),r=_(t,"inputShape","sparseReshape"),a=_(n,"newShape","sparseReshape");if(s.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
+ ${s.shape}`);if(r.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${r.shape}`);if(a.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);let o={inputIndices:s,inputShape:r,newShape:a},i=B.runKernel(Sh,o);return{outputIndices:i[0],outputShape:i[1]}}var WF=V({sparseReshape_:BF});function VF(e,t,n){let s=_(e,"data","sparseSegmentMean"),r=_(t,"indices","sparseSegmentMean"),a=_(n,"segmentIds","sparseSegmentMean");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
${r.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
- ${a.shape}`);let o={data:s,indices:r,segmentIds:a};return B.runKernel(Ch,o)}var UF=V({sparseSegmentMean_:VF});function GF(e,t,n){let s=D(e,"data","sparseSegmentSum"),r=D(t,"indices","sparseSegmentSum"),a=D(n,"segmentIds","sparseSegmentSum");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
+ ${a.shape}`);let o={data:s,indices:r,segmentIds:a};return B.runKernel(Ch,o)}var UF=V({sparseSegmentMean_:VF});function GF(e,t,n){let s=_(e,"data","sparseSegmentSum"),r=_(t,"indices","sparseSegmentSum"),a=_(n,"segmentIds","sparseSegmentSum");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
${r.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
- ${a.shape}`);let o={data:s,indices:r,segmentIds:a};return B.runKernel(Th,o)}var HF=V({sparseSegmentSum_:GF});function jF(e,t,n,s,r,a,o,i){let l=D(e,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);let c=D(t,"dataSplits","stringNGrams");if(c.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let u={separator:n,nGramWidths:s,leftPad:r,rightPad:a,padWidth:o,preserveShortSequences:i},d={data:l,dataSplits:c},p=B.runKernel(qc,d,u);return{nGrams:p[0],nGramsSplits:p[1]}}var qF=V({stringNGrams_:jF});function XF(e,t,n=!0){let s=D(e,"input","stringSplit","string"),r=D(t,"delimiter","stringSplit","string");if(s.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${s.shape}`);if(r.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);let a={skipEmpty:n},o={input:s,delimiter:r},i=B.runKernel(Nh,o,a);return{indices:i[0],values:i[1],shape:i[2]}}var KF=V({stringSplit_:XF});function ZF(e,t){let n=D(e,"input","stringToHashBucketFast","string"),s={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let r={input:n};return B.runKernel(Eh,r,s)}var YF=V({stringToHashBucketFast_:ZF}),JF={fft:af,ifft:gd,rfft:of,irfft:t1},QF={hammingWindow:TP,hannWindow:vv,frame:wv,stft:$P},$e={flipLeftRight:FP,grayscaleToRGB:MP,resizeNearestNeighbor:iF,resizeBilinear:aF,rotateWithOffset:LP,cropAndResize:_P,nonMaxSuppression:WP,nonMaxSuppressionAsync:KP,nonMaxSuppressionWithScore:YP,nonMaxSuppressionWithScoreAsync:QP,nonMaxSuppressionPadded:tF,nonMaxSuppressionPaddedAsync:sF,threshold:cF,transform:pF},Nv={bandPart:fF,gramSchmidt:gF,qr:yF},eO={absoluteDifference:vF,computeWeightedLoss:Jr,cosineDistance:kF,hingeLoss:SF,huberLoss:TF,logLoss:EF,meanSquaredError:$F,sigmoidCrossEntropy:PF,softmaxCrossEntropy:MF},yd={sparseFillEmptyRows:LF,sparseReshape:WF,sparseSegmentMean:UF,sparseSegmentSum:HF},hf={stringNGrams:qF,stringSplit:KF,stringToHashBucketFast:YF},Qr=class extends d3{minimize(e,t=!1,n){let{value:s,grads:r}=this.computeGradients(e,n);if(n!=null){let a=n.map(o=>({name:o.name,tensor:r[o.name]}));this.applyGradients(a)}else this.applyGradients(r);return Q(r),t?s:(s.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return X3(e,t)}dispose(){this.iterations_!=null&&Q(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Ee(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}};Object.defineProperty(Qr,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var ff=class extends Qr{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=B.registeredVariables[n],a=!1;this.accumulatedGrads[s]==null&&(this.accumulatedGrads[s]={originalName:`${n}/accum_grad`,variable:j(()=>tt(r).variable(a))}),this.accumulatedUpdates[s]==null&&(this.accumulatedUpdates[s]={originalName:`${n}/accum_var`,variable:j(()=>tt(r).variable(a))});let o=Array.isArray(e)?e[s].tensor:e[n];if(o==null)return;let i=this.accumulatedGrads[s].variable,l=this.accumulatedUpdates[s].variable;j(()=>{let c=ie(W(i,this.rho),W(xt(o),1-this.rho)),u=W(he(_n(ie(l,this.epsilon)),_n(ie(i,this.epsilon))),o),d=ie(W(l,this.rho),W(xt(u),1-this.rho));i.assign(c),l.assign(d);let p=ie(W(u,-this.learningRate),r);r.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Q(this.accumulatedGrads.map(e=>e.variable)),Q(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){let e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}};ff.className="Adadelta";vo(ff);var mf=class extends Qr{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=B.registeredVariables[n];if(this.accumulatedGrads[s]==null){let i=!1;this.accumulatedGrads[s]={originalName:`${n}/accumulator`,variable:j(()=>Iu(r.shape,this.initialAccumulatorValue).variable(i))}}let a=Array.isArray(e)?e[s].tensor:e[n];if(a==null)return;let o=this.accumulatedGrads[s].variable;j(()=>{let i=ie(o,xt(a));o.assign(i);let l=ie(W(he(a,_n(ie(i,B.backend.epsilon()))),-this.learningRate),r);r.assign(l)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Q(this.accumulatedGrads.map(e=>e.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=!1;this.accumulatedGrads=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}};mf.className="Adagrad";vo(mf);var gf=class extends Qr{constructor(e,t,n,s=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],j(()=>{this.accBeta1=Ee(t).variable(),this.accBeta2=Ee(n).variable()}),s==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);j(()=>{let n=ye(1,this.accBeta1),s=ye(1,this.accBeta2);t.forEach((r,a)=>{let o=B.registeredVariables[r],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${r}/m`,variable:j(()=>tt(o).variable(i))}),this.accumulatedSecondMoment[a]==null&&(this.accumulatedSecondMoment[a]={originalName:`${r}/v`,variable:j(()=>tt(o).variable(i))});let l=Array.isArray(e)?e[a].tensor:e[r];if(l==null)return;let c=this.accumulatedFirstMoment[a].variable,u=this.accumulatedSecondMoment[a].variable,d=ie(W(c,this.beta1),W(l,1-this.beta1)),p=ie(W(u,this.beta2),W(xt(l),1-this.beta2)),h=he(d,n),f=he(p,s);c.assign(d),u.assign(p);let m=ie(W(he(h,ie(_n(f),this.epsilon)),-this.learningRate),o);o.assign(m)}),this.accBeta1.assign(W(this.accBeta1,this.beta1)),this.accBeta2.assign(W(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Q(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Q(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){let e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e),j(()=>{this.accBeta1.assign(Io(this.beta1,this.iterations_+1)),this.accBeta2.assign(Io(this.beta2,this.iterations_+1))});let t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}};gf.className="Adam";vo(gf);var Af=class extends Qr{constructor(e,t,n,s=null,r=0){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],j(()=>{this.iteration=Ee(0).variable(),this.accBeta1=Ee(t).variable()}),s==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);j(()=>{let n=ye(1,this.accBeta1),s=he(-this.learningRate,ie(W(this.iteration,this.decay),1));t.forEach((r,a)=>{let o=B.registeredVariables[r],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${r}/m`,variable:tt(o).variable(i)}),this.accumulatedWeightedInfNorm[a]==null&&(this.accumulatedWeightedInfNorm[a]={originalName:`${r}/v`,variable:tt(o).variable(i)});let l=Array.isArray(e)?e[a].tensor:e[r];if(l==null)return;let c=this.accumulatedFirstMoment[a].variable,u=this.accumulatedWeightedInfNorm[a].variable,d=ie(W(c,this.beta1),W(l,1-this.beta1)),p=W(u,this.beta2),h=rn(l),f=Yr(p,h);c.assign(d),u.assign(f);let m=ie(W(he(s,n),he(d,ie(f,this.epsilon))),o);o.assign(m)}),this.iteration.assign(ie(this.iteration,1)),this.accBeta1.assign(W(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Q(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Q(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)}};Af.className="Adamax";vo(Af);var xd=class extends Qr{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=Array.isArray(e)?e[s].tensor:e[n];if(r==null)return;let a=B.registeredVariables[n];j(()=>{let o=ie(W(this.c,r),a);a.assign(o)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=yn(Ee(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(e=await this.extractIterations(e),e.length!==0)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}};xd.className="SGD";vo(xd);var yf=class extends xd{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ee(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=B.registeredVariables[n];if(this.accumulations[s]==null){let i=!1;this.accumulations[s]={originalName:`${n}/momentum`,variable:j(()=>tt(r).variable(i))}}let a=this.accumulations[s].variable,o=Array.isArray(e)?e[s].tensor:e[n];o!=null&&j(()=>{let i,l=ie(W(this.m,a),o);this.useNesterov?i=ie(W(this.c,ie(o,W(l,this.m))),r):i=ie(W(this.c,l),r),a.assign(l),r.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Q(this.accumulations.map(e=>e.variable))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=!1;this.accumulations=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}};yf.className="Momentum";vo(yf);var xf=class extends Qr{constructor(e,t=.9,n=0,s=null,r=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=s,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,s==null&&(this.epsilon=B.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=B.registeredVariables[n],a=!1;this.accumulatedMeanSquares[s]==null&&(this.accumulatedMeanSquares[s]={originalName:`${n}/rms`,variable:j(()=>tt(r).variable(a))}),this.accumulatedMoments[s]==null&&(this.accumulatedMoments[s]={originalName:`${n}/momentum`,variable:j(()=>tt(r).variable(a))}),this.accumulatedMeanGrads[s]==null&&this.centered&&(this.accumulatedMeanGrads[s]={originalName:`${n}/mg`,variable:j(()=>tt(r).variable(a))});let o=Array.isArray(e)?e[s].tensor:e[n];if(o==null)return;let i=this.accumulatedMeanSquares[s].variable,l=this.accumulatedMoments[s].variable;j(()=>{let c=ie(W(i,this.decay),W(xt(o),1-this.decay));if(this.centered){let u=this.accumulatedMeanGrads[s].variable,d=ie(W(u,this.decay),W(o,1-this.decay)),p=he(W(o,this.learningRate),_n(ye(c,ie(xt(d),this.epsilon)))),h=ie(W(l,this.momentum),p);i.assign(c),u.assign(d),l.assign(h);let f=ye(r,h);r.assign(f)}else{let u=ie(W(i,this.decay),W(xt(o),1-this.decay)),d=ie(W(l,this.momentum),he(W(o,this.learningRate),_n(ie(u,this.epsilon))));i.assign(u),l.assign(d);let p=ye(r,d);r.assign(p)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Q(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Q(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Q(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){let e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}};xf.className="RMSProp";vo(xf);var el=class{static sgd(e){return new xd(e)}static momentum(e,t,n=!1){return new yf(e,t,n)}static rmsprop(e,t=.9,n=0,s=null,r=!1){return new xf(e,t,n,s,r)}static adam(e=.001,t=.9,n=.999,s=null){return new gf(e,t,n,s)}static adadelta(e=.001,t=.95,n=null){return new ff(e,t,n)}static adamax(e=.002,t=.9,n=.999,s=null,r=0){return new Af(e,t,n,s,r)}static adagrad(e,t=.1){return new mf(e,t)}},tl={sgd:el.sgd,momentum:el.momentum,adadelta:el.adadelta,adagrad:el.adagrad,rmsprop:el.rmsprop,adamax:el.adamax,adam:el.adam},tO=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function Ev(){return new Promise(e=>tO(()=>e()))}var N={};ze(N,{ERF_A1:()=>pO,ERF_A2:()=>hO,ERF_A3:()=>fO,ERF_A4:()=>mO,ERF_A5:()=>gO,ERF_P:()=>dO,PARALLELIZE_THRESHOLD:()=>c1,SELU_SCALE:()=>$v,SELU_SCALEALPHA:()=>Rv,applyActivation:()=>df,assertAndGetBroadcastShape:()=>St,assertAxesAreInnerMostDims:()=>hD,assertParamsConsistent:()=>nO,assignToTypedArray:()=>wO,axesAreInnerMostDims:()=>W2,calculateShapes:()=>Q5,checkEinsumDimSizes:()=>NO,combineLocations:()=>K3,complexWithEvenIndex:()=>xO,complexWithOddIndex:()=>bO,computeConv2DInfo:()=>ld,computeConv3DInfo:()=>C3,computeDefaultPad:()=>N2,computeDilation2DInfo:()=>DR,computeOptimalWindowSize:()=>rO,computeOutAndReduceShapes:()=>Z3,computeOutShape:()=>sO,computePool2DInfo:()=>S3,computePool3DInfo:()=>_R,convertConv2DDataFormat:()=>T3,decodeEinsumEquation:()=>CO,eitherStridesOrDilationsAreOne:()=>Nr,expandShapeToKeepDim:()=>Qi,exponent:()=>IO,exponents:()=>kO,fromStringArrayToUint8:()=>MO,fromUint8ToStringArray:()=>OO,getAxesPermutation:()=>Y3,getBroadcastDims:()=>I$,getComplexWithIndex:()=>vO,getEinsumComputePath:()=>EO,getEinsumPermutation:()=>TO,getFusedBiasGradient:()=>cf,getFusedDyActivation:()=>uf,getImageCenter:()=>aO,getInnerMostAxes:()=>fD,getPermuted:()=>iO,getReductionAxes:()=>an,getReshaped:()=>oO,getReshapedPermuted:()=>lO,getSliceBeginCoords:()=>uO,getSliceSize:()=>cO,getUndoAxesPermutation:()=>V2,isIdentityPermutation:()=>RO,log:()=>aE,mergeRealAndImagArrays:()=>AO,prepareAndValidate:()=>J5,prepareSplitSize:()=>DO,segment_util:()=>Pv,shouldFuse:()=>pf,slice_util:()=>An,splitRealAndImagArrays:()=>yO,tupleValuesAreOne:()=>wo,upcastType:()=>Bn,validateInput:()=>b2,validateUpdateShape:()=>x2,warn:()=>kr});function nO(e,t){let n=e[0].length;e.forEach((r,a)=>{O(r.length===n,()=>`Error in concat${n}D: rank of tensors[${a}] must be the same as the rank of the rest (${n})`)}),O(t>=0&&t`Error in concat${n}D: axis must be between 0 and ${n-1}.`);let s=e[0];e.forEach((r,a)=>{for(let o=0;o`Error in concat${n}D: Shape of tensors[${a}] (${r}) does not match the shape of the rest (${s}) along the non-concatenated axis ${a}.`)})}function sO(e,t){let n=e[0].slice();for(let s=1;s=t*2+1||o%2==1?a.push(o):r.push(o);s.push(...r),s.push(0),s.push(...a)}return s}function lO(e,t,n,s=!0){let r=[];s?r.push(e[0]/n):r.push(e[0]*n);for(let a=1;a/g,Dv=",",_v="...";function CO(e,t){e=e.replace(/\s/g,"");let n=(e.length-e.replace(SO,"").length)/d1.length;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error(`Equation must contain exactly one arrow ("${d1}").`);let[s,r]=e.split(d1);O(s.indexOf(_v)===-1,()=>`The ellipsis notation ("${_v}") is not supported yet.`);let a=s.split(Dv),o=a.length;if(t!==o)throw new Error(`Expected ${o} input tensors, received ${t}`);if(o>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let i=[];for(let p=0;pf.indexOf(h)!==-1))throw new Error(`Output subscripts contain the label ${h} not present in the input subscripts.`);i.indexOf(h)===-1&&i.push(h)}for(let p=0;pr!==-1),{permutationIndices:n,expandDims:s}}function NO(e,t,n){let s=new Array(e);for(let r=0;r`Expected dimension ${s[t[r][o]]} at axis ${o} of input shaped ${JSON.stringify(a)}, but got dimension ${a[o]}`)}}function EO(e,t){let n=e,s=[],r=0;e.length===0&&n.push(-1),r=e.length+1;for(let o=0;ot===n)}function $O(e,t){let n=[];for(let s=0;s"Number of splits must evenly divide the axis."),s=new Array(t).fill(e.shape[n]/t);else{let r=t.reduce((o,i)=>(i===-1&&(o+=1),o),0);O(r<=1,()=>"There should be only one negative value in split array.");let a=t.indexOf(-1);if(a!==-1){let o=t.reduce((i,l)=>l>0?i+l:i);t[a]=e.shape[n]-o}O(e.shape[n]===t.reduce((o,i)=>o+i),()=>"The sum of sizes must match the size of the axis dimension."),s=t}return s}var Pv={};ze(Pv,{collectGatherOpShapeInfo:()=>FO,computeOutShape:()=>PO,segOpComputeOptimalWindowSize:()=>_O});function _O(e,t){let n=!1,s;for(e<=c1?(s=e,n=!0):s=Jp(e,Math.floor(Math.sqrt(e)));!n;)s>t||s===e?n=!0:s=Jp(e,s+1);return s}function PO(e,t,n){let s=[],r=e.length;for(let a=0;ar))throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${s}`);if(s<0&&(s+=r),s>a)throw new Error(`batchDims (${s}) must be less than rank(x) (
- ${a}).`);if(nPh(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function MO(e){return e.map(t=>Qc(t))}var Xs={};ze(Xs,{nonMaxSuppressionV3Impl:()=>kv,nonMaxSuppressionV4Impl:()=>Iv,nonMaxSuppressionV5Impl:()=>Sv,whereImpl:()=>hv});var Fv={kernelName:ni,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,Ad(de(n,"float32"),-1))}}},zO={kernelName:Vl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=xt(de(n,"float32")),r=_n(ye(Ee(1),s));return Ot(he(e,r))}}}},LO={kernelName:Ul,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=_n(ye(xt(de(n,"float32")),1));return he(e,s)}}}},BO={kernelName:Hr,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=e,l=an(n.shape,r);return l.length>0&&(i=Ie(i,l)),G(i,n.shape)},b:()=>{let i=e,l=an(s.shape,r);return l.length>0&&(i=Ie(i,l)),G(i,s.shape)}}}},WO={kernelName:wa,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((s,r)=>{n[r]=()=>e.clone()}),n}},VO={kernelName:ka,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>tt(n)}}},UO={kernelName:jl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>tt(n)}}},GO={kernelName:ql,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,_n(ye(Ee(1),xt(de(n,"float32")))))}}},HO={kernelName:Xl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=_n(ie(Ee(1),xt(de(n,"float32"))));return he(e,s)}}}},jO={kernelName:Yl,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=ie(xt(n),xt(s)),l=W(e,he(s,i)),c=an(n.shape,r);return c.length>0&&(l=Ie(l,c)),G(l,n.shape)},b:()=>{let i=ie(xt(n),xt(s)),l=Ot(W(e,he(n,i))),c=an(s.shape,r);return c.length>0&&(l=Ie(l,c)),G(l,s.shape)}}}},qO={kernelName:Kl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,ie(xt(de(n,"float32")),1))}}},XO={kernelName:Zl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,ye(Ee(1),xt(de(n,"float32"))))}}};function KO(e,t,n,s,r,a){let o=D(e,"dy","avgPool3dGrad"),i=D(t,"input","avgPool3dGrad"),l=o,c=i,u=!1;i.rank===4&&(u=!0,l=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),c=G(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),O(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),O(c.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${c.rank}.`),a!=null&&O(mn(r),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`);let d={dy:l,input:c},p={filterSize:n,strides:s,pad:r,dimRoundingMode:a},h=B.runKernel(th,d,p);return u?G(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var ZO=V({avgPool3dGrad_:KO}),YO={kernelName:Fc,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{filterSize:r,strides:a,pad:o,dimRoundingMode:i}=n;return{x:()=>ZO(e,s,r,a,o,i)}}};function JO(e,t,n,s,r){let a=D(e,"dy","avgPoolGrad"),o=D(t,"input","avgPoolGrad");O(o.rank===a.rank,()=>`Rank of input (${o.rank}) does not match rank of dy (${a.rank})`);let i=o,l=a,c=!1;o.rank===3&&(c=!0,i=G(o,[1,o.shape[0],o.shape[1],o.shape[2]]),l=G(a,[1,a.shape[0],a.shape[1],a.shape[2]])),O(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),O(i.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${i.rank}.`);let u={dy:l,input:i},d={filterSize:n,strides:s,pad:r},p=B.runKernel(eh,u,d);return c?G(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var QO=V({avgPoolGrad_:JO}),eM={kernelName:Ia,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{filterSize:r,strides:a,pad:o}=n;return{x:()=>QO(e,s,r,a,o)}}},tM={kernelName:Sa,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{let[s,r]=t,{transposeA:a,transposeB:o}=n;return!a&&!o?{a:()=>He(e,r,!1,!0),b:()=>He(s,e,!0,!1)}:!a&&o?{a:()=>He(e,r,!1,!1),b:()=>He(e,s,!0,!1)}:a&&!o?{a:()=>He(r,e,!1,!0),b:()=>He(s,e,!1,!1)}:{a:()=>He(r,e,!0,!0),b:()=>He(e,s,!0,!0)}}},nM={kernelName:si,gradFunc:(e,t,n)=>{let{blockShape:s,crops:r}=n;return{x:()=>nf(e,s,r)}}},sM={kernelName:m5,gradFunc:(e,t,n)=>{let s=n,r=s.inputShape,a=s.shape,o=Array.from(a);for(let l=r.length-1;l>=0;l--)if(r[l]===a[l])o[l]=1;else if(r[l]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${a}].`);let i=[];for(let l=0;l1&&i.push(l);return{x:()=>Ie(e,i,!0)}}},rM={kernelName:Ca,gradFunc:e=>({x:()=>e.clone()})},aM={kernelName:Ta,gradFunc:e=>({x:()=>tt(e)})},oM={kernelName:jr,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{clipValueMin:r,clipValueMax:a}=n;return{x:()=>Wn(lr(Yi(s,r),Ji(s,a)),e,tt(e))}}},iM={kernelName:Mc,inputsToSave:["x"],gradFunc:Fv.gradFunc},lM={kernelName:ri,saveAllInputs:!0,gradFunc:(e,t,n)=>{let s=t.map(l=>l.shape),{axis:r}=n,a=Us(r,t[0].shape)[0],o=s.map(l=>l[a]);return Sn(e,o,a).map(l=>()=>l)}},uM={kernelName:Na,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[s,r]=t,{dilations:a,strides:o,pad:i,dataFormat:l}=n;return O(wo(a),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`),{x:()=>_2(s.shape,e,r,o,i,l),filter:()=>l1(s,e,r.shape,o,i,l)}}},cM={kernelName:Ea,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{let[s,r]=t,{strides:a,pad:o,dataFormat:i,dimRoundingMode:l}=n;return{dy:()=>ko(e,r,a,o,i,1,l),filter:()=>l1(e,s,r.shape,a,o,i,l)}}};function dM(e,t,n,s,r){let a=e;e.rank===4&&(a=G(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let o=t;o.rank===4&&(o=G(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),O(a.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${a.shape}.`),O(o.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${o.shape}.`),O(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),O(a.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${a.shape[4]}) must match input depth in filter (${n[3]}.`),O(o.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${o.shape[4]}) must match output depth for filter (${n[4]}).`);let i={x:a,dy:o},l={strides:s,pad:r,filterShape:n};return B.runKernel(ah,i,l)}var pM=V({conv3DBackpropFilter_:dM}),hM={kernelName:zc,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:s,strides:r,pad:a}=n;O(wo(s),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let[o,i]=t;return{x:()=>O3(o.shape,e,i,r,a),filter:()=>pM(o,e,i.shape,r,a)}}},fM={kernelName:Ra,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(Ot(J2(de(n,"float32"))),e)}}},mM={kernelName:$a,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(Q2(de(n,"float32")),e)}}},gM={kernelName:ai,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{axis:r,exclusive:a,reverse:o}=n;return{x:()=>{let i=Y3([r],s.rank),l=M2(e,r,a,!o);return i!=null&&(l=et(l,i)),l}}}},AM={kernelName:Da,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:s,strides:r,pad:a,dimRoundingMode:o}=n,i=s==null?[1,1]:s;O(wo(i),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);let[l,c]=t;return O(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),O(c.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${c.rank}.`),O(l.shape[3]===c.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),O(Nr(r,i),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'.`),o!=null&&O(mn(a),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`),{x:()=>bv(l.shape,e,c,r,a,i,o),filter:()=>xv(l,e,c.shape,r,a,i,o)}}},yM={kernelName:Lc,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[s,r]=t,a={x:s,filter:r,dy:e},o={x:s,filter:r,dy:e};return{x:()=>B.runKernel(dh,a,n),filter:()=>B.runKernel(ph,o,n)}}},xM={kernelName:Pa,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t,s={dy:e,y:n};return{x:()=>B.runKernel(hh,s)}}},bM={kernelName:Jl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,s=W(Ts(Ot(xt(n))),2/Math.sqrt(Math.PI));return{x:()=>W(e,s)}}},vM={kernelName:Fa,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,n)}}},wM={kernelName:ui,inputsToSave:["input"],gradFunc:(e,t)=>{let[n]=t;return{input:()=>G(e,n.shape)}}},kM={kernelName:ci,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,Ts(n))}}},IM={kernelName:Oa,gradFunc:e=>({x:()=>tt(e)})},SM={kernelName:Ma,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=he(e,de(s,"float32")),l=an(n.shape,r);return l.length>0?G(Ie(i,l),n.shape):i},b:()=>{let i=W(e,de(n,"float32")),l=an(s.shape,r);l.length>0&&(i=G(Ie(i,l),s.shape));let c=xt(s);return Ot(he(i,de(c,"float32")))}}}},CM={kernelName:za,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{let{varianceEpsilon:s}=n,[r,a,o,i]=t,l=i==null?Ee(1):i,c=an(a.shape,r.shape),u=[];if(a.rank===1){for(let b=0;ba.rank===1?G(W(W(e,js(G(h,[1,1,1,a.shape[0]]),u)),l),r.shape):G(W(W(e,h),l),r.shape),mean:()=>{let b=W(W(h,Ee(-1)),p);return a.rank===1&&(b=Ie(b,c)),G(b,a.shape)},variance:()=>{let b=W(W(f,d),p);return a.rank===1&&(b=Ie(b,c)),G(b,a.shape)},scale:()=>{let b=W(d,h),w=W(e,b);return a.rank===1&&(w=Ie(w,c)),G(w,a.shape)},offset:()=>{let b=e;return a.rank===1&&(b=Ie(b,c)),G(b,a.shape)}}}},TM={kernelName:pi,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{let[s,r]=t,{axis:a}=n,o=Us(a,s.shape)[0];return{x:()=>{let l=s.shape,c=r.size,u=l.slice(0,o),d=u.length,p=l.slice(a,l.length).slice(1),h=p.length,f=Ov(0,d),m=Ov(d+1,d+1+h),g=Mv([u,[c],p]),A=G(e,g),y=G(r,[c]),x=Mv([[d],f,m]),b=et(A,x),w=dv(b,y,s.shape[o]),k=V2(x);return w=et(w,k),w},indices:()=>r}}};function Ov(e,t){let n=[];for(let s=e;s{let[n,s]=t;return{a:()=>tt(n),b:()=>tt(s)}}},EM={kernelName:Ba,gradFunc:e=>({x:()=>de(e,"float32")})},RM={kernelName:eu,gradFunc:e=>({x:()=>tt(e)})},$M={kernelName:tu,gradFunc:e=>({x:()=>tt(e)})},DM={kernelName:nu,gradFunc:e=>({x:()=>tt(e)})},_M={kernelName:mi,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{alpha:r}=n,a=ms(s,0);return{x:()=>Wn(a,e,W(e,r))}}},PM={kernelName:su,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,ie(n,1))}}},FM={kernelName:Wa,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,de(n,"float32"))}}},OM={kernelName:g5,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s]=t,{axis:r}=n;return{logits:()=>{let a=!0,o=Ts(s);return ye(e,W(Ie(e,r,a),o))}}}};function MM(e,t,n,s=5,r=1,a=1,o=.5){let i={x:e,y:t,dy:n},l={depthRadius:s,bias:r,alpha:a,beta:o};return B.runKernel(Ah,i,l)}var zM=V({localResponseNormalizationBackprop_:MM}),LM={kernelName:Uc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{depthRadius:a,bias:o,alpha:i,beta:l}=n;return{x:()=>zM(s,r,e,a,o,i,l)}}};function zv(e,t,n,s){return t.rankW(e,de(Cs(n,t),e.dtype))}}var Lv={kernelName:Va,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let s=n,{reductionIndices:r}=s,a=t[0],o=t[1],i=Us(r,a.shape),l=zv(e,o,a,i);return{x:()=>l.x()}}},BM={kernelName:Ua,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t;return{a:()=>W(e,de(Yi(n,s),"float32")),b:()=>W(e,de(L2(n,s),"float32"))}}};function WM(e,t,n,s,r,a,o){let i=D(e,"dy","maxPool3dGrad"),l=D(t,"input","maxPool3dGrad"),c=D(n,"output","maxPool3dGrad"),u=i,d=l,p=c,h=!1;l.rank===4&&(h=!0,u=G(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),d=G(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),p=G(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),O(u.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`),O(d.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${d.rank}.`),O(p.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${p.rank}.`),o!=null&&O(mn(a),()=>`Error in maxPool3dGrad: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`);let f={dy:u,input:d,output:p},m={filterSize:s,strides:r,pad:a,dimRoundingMode:o},g=B.runKernel(xh,f,m);return h?G(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var VM=V({maxPool3dGrad_:WM}),UM={kernelName:Gc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=n;return{x:()=>VM(e,s,r,a,o,i,l)}}};function GM(e,t,n,s,r,a,o){let i=D(e,"dy","maxPoolGrad"),l=D(t,"input","maxPoolGrad"),c=D(n,"output","maxPoolGrad");O(l.rank===i.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${i.rank})`),O(i.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${i.rank}.`),O(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),o!=null&&O(mn(a),()=>`Error in maxPoolGrad: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`);let u={dy:i,input:l,output:c},d={filterSize:s,strides:r,pad:a,dimRoundingMode:o};return B.runKernel(yh,u,d)}var HM=V({maxPoolGrad_:GM}),jM={kernelName:Ga,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{filterSize:a,strides:o,pad:i}=n;return{x:()=>HM(e,s,r,a,o,i)}}},qM={kernelName:Ha,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{axis:r}=n,a=Us(r,s.shape),i=Z3(s.shape,a)[1],l=Ut(i);return{x:()=>{let u=s.shape.slice();a.forEach(h=>{u[h]=1});let d=G(e,u);return he(W(d,gs(s.shape,"float32")),l)}}}},XM={kernelName:ja,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let s=n,{axis:r}=s,[a,o]=t,i=Us(r,a.shape),l=zv(e,o,a,i);return{x:()=>l.x()}}},KM={kernelName:qa,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t;return{a:()=>W(e,de(Ji(n,s),"float32")),b:()=>W(e,de(ms(n,s),"float32"))}}},ZM={kernelName:Xa,inputsToSave:["x"],gradFunc:(e,t,n)=>{let s=t[0],{paddings:r}=n,a=r.map(o=>o[0]);return{x:()=>_e(e,a,s.shape)}}},YM={kernelName:au,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=an(n.shape,r);return i.length>0?G(Ie(e,i),n.shape):e},b:()=>{let i=W(e,Ot(pd(he(n,s)))),l=an(s.shape,r);return l.length>0?G(Ie(i,l),s.shape):i}}}},JM={kernelName:Ka,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=W(e,de(s,"float32")),l=an(n.shape,r);return l.length>0?G(Ie(i,l),n.shape):i},b:()=>{let i=W(e,de(n,"float32")),l=an(s.shape,r);return l.length>0?G(Ie(i,l),s.shape):i}}}},QM={kernelName:xi,gradFunc:e=>({x:()=>Ot(e)})},ez={kernelName:Ii,inputsToSave:["indices"],gradFunc:(e,t)=>{let n=t[0];return{indices:()=>Ht(n.shape,"float32")}}},tz={kernelName:ki,gradFunc:e=>({x:()=>tt(e)})},nz={kernelName:Si,saveAllInputs:!0,gradFunc:(e,t,n)=>{let{axis:s}=n;return as(e,s).map(a=>()=>a)}},Bv={kernelName:Za,inputsToSave:["x"],gradFunc:(e,t,n)=>{let s=t[0],{paddings:r}=n,a=r.map(o=>o[0]);return{x:()=>_e(e,a,s.shape)}}},sz={kernelName:Ya,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[n,s,r]=t,a=n,o=s,i=St(a.shape,o.shape);return{a:()=>{let u=de(o,"float32"),d=W(e,W(u,Io(a,ye(u,Ee(1))))),p=an(a.shape,i);return p.length>0&&(d=Ie(d,p)),G(d,a.shape)},b:()=>{let u=ms(a,0),d=Wn(u,Ns(a),tt(a)),p=W(e,W(r,d)),h=an(o.shape,i);return h.length>0&&(p=Ie(p,h)),G(p,o.shape)}}}},rz={kernelName:Ja,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[n,s]=t,r=ms(n,0);return{x:()=>Wn(r,e,W(e,s)),alpha:()=>{let a=Wn(r,tt(e),W(e,n)),o=an(s.shape,e.shape);return o.length>0&&(a=Ie(a,o)),G(a,s.shape)}}}},az={kernelName:_a,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=he(e,de(s,"float32")),l=an(n.shape,r);return l.length>0?G(Ie(i,l),n.shape):i},b:()=>{let i=W(e,de(n,"float32")),l=an(s.shape,r);l.length>0&&(i=G(Ie(i,l),s.shape));let c=xt(s);return Ot(he(i,de(c,"float32")))}}}},oz={kernelName:lu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,Ot(xt(n)))}}},iz={kernelName:to,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,s=W(Ji(n,6),Ad(n));return{x:()=>W(e,de(s,"float32"))}}},lz={kernelName:Qa,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,de(Ad(n),"float32"))}}},uz={kernelName:Ti,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>G(e,n.shape)}}},cz={kernelName:eo,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[s]=t,r={dy:e,images:s};return{images:()=>B.runKernel(kh,r,n)}}},dz={kernelName:uu,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[s]=t,r={dy:e,images:s};return{images:()=>B.runKernel(wh,r,n)}}},pz={kernelName:Ni,gradFunc:(e,t,n)=>{let{dims:s}=n,r=Us(s,e.shape);return{x:()=>Rs(e,r)}}},hz={kernelName:Ei,gradFunc:e=>({x:()=>tt(e)})},fz={kernelName:no,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ot(he(e,W(Io(n,1.5),2)))}}},mz={kernelName:$i,inputsToSave:["condition"],gradFunc:(e,t)=>{let[n]=t;return{condition:()=>de(tt(n),"float32"),t:()=>W(e,de(n,e.dtype)),e:()=>W(e,de(Jh(n),e.dtype))}}},gz={kernelName:cu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=ms(n,Ee(0)),r=Ee(Rv),a=Ee($v),o=W(e,a),i=W(W(e,r),Ts(de(n,"float32")));return Wn(s,o,i)}}}},Az={kernelName:ro,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,W(n,ye(Ee(1),n)))}}},yz={kernelName:du,gradFunc:e=>({x:()=>tt(e)})},xz={kernelName:so,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(qh(de(n,"float32")),e)}}},bz={kernelName:_i,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(O2(de(n,"float32")),e)}}},vz={kernelName:Di,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{begin:r,size:a}=n,o=s.shape,[i,l]=c3(s,r,a),c=[];for(let u=0;uqs(e,c)}}},wz={kernelName:io,outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s]=t,{dim:r}=n,a=!0,o=W(e,s);return{logits:()=>ye(o,W(Ie(o,[r],a),s))}}},kz={kernelName:pu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,hs(n))}}},Wv={kernelName:Pi,gradFunc:(e,t,n)=>{let{blockShape:s,paddings:r}=n;return{x:()=>jh(e,s,r)}}},Vv={kernelName:Fi,gradFunc:(e,t,n)=>{let{axis:s}=n;return{x:()=>It(e,s)}}},Iz={kernelName:ao,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,W(_n(de(n,"float32")),2))}}},Sz={kernelName:hu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,W(de(n,"float32"),2))}}},Cz={kernelName:lo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=Ee(2);return{a:()=>W(e,W(r,ye(n,s))),b:()=>W(e,W(r,ye(s,n)))}}},Tz={kernelName:ho,gradFunc:e=>({x:()=>tt(e)})},Nz={kernelName:uo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=St(n.shape,s.shape);return{a:()=>{let i=e,l=an(n.shape,r);return l.length>0&&(i=Ie(i,l)),G(i,n.shape)},b:()=>{let i=e,l=an(s.shape,r);return l.length>0&&(i=Ie(i,l)),G(Ot(i),s.shape)}}}},Ez={kernelName:oo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,r=s.shape.slice(),{axis:a}=n;Us(a,s.shape).forEach(c=>{r[c]=1});let i=G(e,r),l=W(i,gs(s.shape,"float32"));return{x:()=>l}}},Rz={kernelName:Mi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>he(e,xt(qh(n)))}}},$z={kernelName:co,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(ye(Ee(1),xt(n)),e)}}},Dz={kernelName:qr,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{reps:r}=n;return{x:()=>{let o=tt(s);if(s.rank===1)for(let i=0;i{let s=n,{perm:r}=s,a=V2(r);return{x:()=>et(e,a)}}},Pz={kernelName:Bi,gradFunc:(e,t,n)=>{let s=n,{axis:r}=s;return{value:()=>Pn(e,r)}}},Fz={kernelName:Xc,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Oz(e,n)}}};function Oz(e,t){let n=Yr(t,tt(t)),s=Su(e,n),r=Yi(t,Ee(0,"int32")),a=s.rank-r.rank;for(let i=0;i({x:()=>tt(e)})},zz=[Fv,zO,LO,BO,WO,VO,UO,GO,HO,jO,qO,XO,YO,eM,tM,nM,sM,rM,aM,oM,iM,lM,cM,uM,hM,fM,mM,gM,AM,yM,az,xM,bM,vM,wM,kM,SM,IM,CM,TM,NM,EM,RM,$M,DM,_M,PM,FM,OM,LM,Lv,Lv,BM,UM,jM,qM,XM,KM,ZM,YM,JM,QM,ez,tz,nz,Bv,Bv,sz,rz,oz,iz,lz,uz,cz,dz,pz,hz,fz,mz,gz,Az,yz,xz,bz,vz,wz,kz,Wv,Wv,Vv,Vv,Iz,Cz,Sz,Tz,Nz,Ez,Rz,$z,Dz,_z,Pz,Fz,Mz];for(let e of zz)A5(e);var Uv={};ze(Uv,{maxNorm:()=>Vz,minMaxNorm:()=>Hz,nonNeg:()=>Gz,unitNorm:()=>Uz});var p1;function on(){return p1==null&&(p1=Tr().epsilon()),p1}function cr(){return"channelsLast"}var ea=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,ea.prototype)}},dr=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,dr.prototype)}},q=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,q.prototype)}},Be=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Be.prototype)}},Gv=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Gv.prototype)}};function nl(e,t){if(Array.isArray(e)){let n=[];for(let s=0;sn.toUpperCase())}var Ks={};function h1(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function f1(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>f1(t));else{let t=Object.keys(e);for(let n of t){let s=e[n];s!=null&&typeof s=="object"&&(!Array.isArray(s)&&s.type==="ndarray"&&typeof s.value=="number"?e[n]=s.value:f1(s))}}}function bd(e,t={},n={},s="object",r=!1){if(typeof e=="string"){let a=e,o;if(a in n)o=n[a];else if(a in Ks)o=Ks[a];else if(o=t[a],o==null)throw new q(`Unknown ${s}: ${e}. This may be due to one of the following reasons:
+ ${a.shape}`);let o={data:s,indices:r,segmentIds:a};return B.runKernel(Th,o)}var HF=V({sparseSegmentSum_:GF});function jF(e,t,n,s,r,a,o,i){let l=_(e,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);let c=_(t,"dataSplits","stringNGrams");if(c.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let u={separator:n,nGramWidths:s,leftPad:r,rightPad:a,padWidth:o,preserveShortSequences:i},d={data:l,dataSplits:c},p=B.runKernel(qc,d,u);return{nGrams:p[0],nGramsSplits:p[1]}}var qF=V({stringNGrams_:jF});function XF(e,t,n=!0){let s=_(e,"input","stringSplit","string"),r=_(t,"delimiter","stringSplit","string");if(s.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${s.shape}`);if(r.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);let a={skipEmpty:n},o={input:s,delimiter:r},i=B.runKernel(Nh,o,a);return{indices:i[0],values:i[1],shape:i[2]}}var KF=V({stringSplit_:XF});function ZF(e,t){let n=_(e,"input","stringToHashBucketFast","string"),s={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let r={input:n};return B.runKernel(Eh,r,s)}var YF=V({stringToHashBucketFast_:ZF}),JF={fft:af,ifft:gd,rfft:of,irfft:t1},QF={hammingWindow:TP,hannWindow:vv,frame:wv,stft:$P},$e={flipLeftRight:FP,grayscaleToRGB:MP,resizeNearestNeighbor:iF,resizeBilinear:aF,rotateWithOffset:LP,cropAndResize:_P,nonMaxSuppression:WP,nonMaxSuppressionAsync:KP,nonMaxSuppressionWithScore:YP,nonMaxSuppressionWithScoreAsync:QP,nonMaxSuppressionPadded:tF,nonMaxSuppressionPaddedAsync:sF,threshold:cF,transform:pF},Nv={bandPart:fF,gramSchmidt:gF,qr:yF},eO={absoluteDifference:vF,computeWeightedLoss:Jr,cosineDistance:kF,hingeLoss:SF,huberLoss:TF,logLoss:EF,meanSquaredError:$F,sigmoidCrossEntropy:PF,softmaxCrossEntropy:MF},yd={sparseFillEmptyRows:LF,sparseReshape:WF,sparseSegmentMean:UF,sparseSegmentSum:HF},hf={stringNGrams:qF,stringSplit:KF,stringToHashBucketFast:YF},Qr=class extends d3{minimize(e,t=!1,n){let{value:s,grads:r}=this.computeGradients(e,n);if(n!=null){let a=n.map(o=>({name:o.name,tensor:r[o.name]}));this.applyGradients(a)}else this.applyGradients(r);return Q(r),t?s:(s.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return X3(e,t)}dispose(){this.iterations_!=null&&Q(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Ee(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}};Object.defineProperty(Qr,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var ff=class extends Qr{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=B.registeredVariables[n],a=!1;this.accumulatedGrads[s]==null&&(this.accumulatedGrads[s]={originalName:`${n}/accum_grad`,variable:j(()=>tt(r).variable(a))}),this.accumulatedUpdates[s]==null&&(this.accumulatedUpdates[s]={originalName:`${n}/accum_var`,variable:j(()=>tt(r).variable(a))});let o=Array.isArray(e)?e[s].tensor:e[n];if(o==null)return;let i=this.accumulatedGrads[s].variable,l=this.accumulatedUpdates[s].variable;j(()=>{let c=ie(W(i,this.rho),W(xt(o),1-this.rho)),u=W(fe(_n(ie(l,this.epsilon)),_n(ie(i,this.epsilon))),o),d=ie(W(l,this.rho),W(xt(u),1-this.rho));i.assign(c),l.assign(d);let p=ie(W(u,-this.learningRate),r);r.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Q(this.accumulatedGrads.map(e=>e.variable)),Q(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){let e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}};ff.className="Adadelta";vo(ff);var mf=class extends Qr{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=B.registeredVariables[n];if(this.accumulatedGrads[s]==null){let i=!1;this.accumulatedGrads[s]={originalName:`${n}/accumulator`,variable:j(()=>Iu(r.shape,this.initialAccumulatorValue).variable(i))}}let a=Array.isArray(e)?e[s].tensor:e[n];if(a==null)return;let o=this.accumulatedGrads[s].variable;j(()=>{let i=ie(o,xt(a));o.assign(i);let l=ie(W(fe(a,_n(ie(i,B.backend.epsilon()))),-this.learningRate),r);r.assign(l)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Q(this.accumulatedGrads.map(e=>e.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=!1;this.accumulatedGrads=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}};mf.className="Adagrad";vo(mf);var gf=class extends Qr{constructor(e,t,n,s=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],j(()=>{this.accBeta1=Ee(t).variable(),this.accBeta2=Ee(n).variable()}),s==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);j(()=>{let n=xe(1,this.accBeta1),s=xe(1,this.accBeta2);t.forEach((r,a)=>{let o=B.registeredVariables[r],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${r}/m`,variable:j(()=>tt(o).variable(i))}),this.accumulatedSecondMoment[a]==null&&(this.accumulatedSecondMoment[a]={originalName:`${r}/v`,variable:j(()=>tt(o).variable(i))});let l=Array.isArray(e)?e[a].tensor:e[r];if(l==null)return;let c=this.accumulatedFirstMoment[a].variable,u=this.accumulatedSecondMoment[a].variable,d=ie(W(c,this.beta1),W(l,1-this.beta1)),p=ie(W(u,this.beta2),W(xt(l),1-this.beta2)),h=fe(d,n),f=fe(p,s);c.assign(d),u.assign(p);let m=ie(W(fe(h,ie(_n(f),this.epsilon)),-this.learningRate),o);o.assign(m)}),this.accBeta1.assign(W(this.accBeta1,this.beta1)),this.accBeta2.assign(W(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Q(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Q(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){let e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e),j(()=>{this.accBeta1.assign(Io(this.beta1,this.iterations_+1)),this.accBeta2.assign(Io(this.beta2,this.iterations_+1))});let t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}};gf.className="Adam";vo(gf);var Af=class extends Qr{constructor(e,t,n,s=null,r=0){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],j(()=>{this.iteration=Ee(0).variable(),this.accBeta1=Ee(t).variable()}),s==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);j(()=>{let n=xe(1,this.accBeta1),s=fe(-this.learningRate,ie(W(this.iteration,this.decay),1));t.forEach((r,a)=>{let o=B.registeredVariables[r],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${r}/m`,variable:tt(o).variable(i)}),this.accumulatedWeightedInfNorm[a]==null&&(this.accumulatedWeightedInfNorm[a]={originalName:`${r}/v`,variable:tt(o).variable(i)});let l=Array.isArray(e)?e[a].tensor:e[r];if(l==null)return;let c=this.accumulatedFirstMoment[a].variable,u=this.accumulatedWeightedInfNorm[a].variable,d=ie(W(c,this.beta1),W(l,1-this.beta1)),p=W(u,this.beta2),h=rn(l),f=Yr(p,h);c.assign(d),u.assign(f);let m=ie(W(fe(s,n),fe(d,ie(f,this.epsilon))),o);o.assign(m)}),this.iteration.assign(ie(this.iteration,1)),this.accBeta1.assign(W(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Q(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Q(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)}};Af.className="Adamax";vo(Af);var xd=class extends Qr{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=Array.isArray(e)?e[s].tensor:e[n];if(r==null)return;let a=B.registeredVariables[n];j(()=>{let o=ie(W(this.c,r),a);a.assign(o)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=yn(Ee(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(e=await this.extractIterations(e),e.length!==0)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}};xd.className="SGD";vo(xd);var yf=class extends xd{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ee(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=B.registeredVariables[n];if(this.accumulations[s]==null){let i=!1;this.accumulations[s]={originalName:`${n}/momentum`,variable:j(()=>tt(r).variable(i))}}let a=this.accumulations[s].variable,o=Array.isArray(e)?e[s].tensor:e[n];o!=null&&j(()=>{let i,l=ie(W(this.m,a),o);this.useNesterov?i=ie(W(this.c,ie(o,W(l,this.m))),r):i=ie(W(this.c,l),r),a.assign(l),r.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Q(this.accumulations.map(e=>e.variable))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=!1;this.accumulations=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}};yf.className="Momentum";vo(yf);var xf=class extends Qr{constructor(e,t=.9,n=0,s=null,r=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=s,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,s==null&&(this.epsilon=B.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=B.registeredVariables[n],a=!1;this.accumulatedMeanSquares[s]==null&&(this.accumulatedMeanSquares[s]={originalName:`${n}/rms`,variable:j(()=>tt(r).variable(a))}),this.accumulatedMoments[s]==null&&(this.accumulatedMoments[s]={originalName:`${n}/momentum`,variable:j(()=>tt(r).variable(a))}),this.accumulatedMeanGrads[s]==null&&this.centered&&(this.accumulatedMeanGrads[s]={originalName:`${n}/mg`,variable:j(()=>tt(r).variable(a))});let o=Array.isArray(e)?e[s].tensor:e[n];if(o==null)return;let i=this.accumulatedMeanSquares[s].variable,l=this.accumulatedMoments[s].variable;j(()=>{let c=ie(W(i,this.decay),W(xt(o),1-this.decay));if(this.centered){let u=this.accumulatedMeanGrads[s].variable,d=ie(W(u,this.decay),W(o,1-this.decay)),p=fe(W(o,this.learningRate),_n(xe(c,ie(xt(d),this.epsilon)))),h=ie(W(l,this.momentum),p);i.assign(c),u.assign(d),l.assign(h);let f=xe(r,h);r.assign(f)}else{let u=ie(W(i,this.decay),W(xt(o),1-this.decay)),d=ie(W(l,this.momentum),fe(W(o,this.learningRate),_n(ie(u,this.epsilon))));i.assign(u),l.assign(d);let p=xe(r,d);r.assign(p)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Q(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Q(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Q(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){let e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}};xf.className="RMSProp";vo(xf);var el=class{static sgd(e){return new xd(e)}static momentum(e,t,n=!1){return new yf(e,t,n)}static rmsprop(e,t=.9,n=0,s=null,r=!1){return new xf(e,t,n,s,r)}static adam(e=.001,t=.9,n=.999,s=null){return new gf(e,t,n,s)}static adadelta(e=.001,t=.95,n=null){return new ff(e,t,n)}static adamax(e=.002,t=.9,n=.999,s=null,r=0){return new Af(e,t,n,s,r)}static adagrad(e,t=.1){return new mf(e,t)}},tl={sgd:el.sgd,momentum:el.momentum,adadelta:el.adadelta,adagrad:el.adagrad,rmsprop:el.rmsprop,adamax:el.adamax,adam:el.adam},tO=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function Ev(){return new Promise(e=>tO(()=>e()))}var N={};ze(N,{ERF_A1:()=>pO,ERF_A2:()=>hO,ERF_A3:()=>fO,ERF_A4:()=>mO,ERF_A5:()=>gO,ERF_P:()=>dO,PARALLELIZE_THRESHOLD:()=>c1,SELU_SCALE:()=>$v,SELU_SCALEALPHA:()=>Rv,applyActivation:()=>df,assertAndGetBroadcastShape:()=>St,assertAxesAreInnerMostDims:()=>hD,assertParamsConsistent:()=>nO,assignToTypedArray:()=>wO,axesAreInnerMostDims:()=>W2,calculateShapes:()=>Q5,checkEinsumDimSizes:()=>NO,combineLocations:()=>K3,complexWithEvenIndex:()=>xO,complexWithOddIndex:()=>bO,computeConv2DInfo:()=>ld,computeConv3DInfo:()=>C3,computeDefaultPad:()=>N2,computeDilation2DInfo:()=>DR,computeOptimalWindowSize:()=>rO,computeOutAndReduceShapes:()=>Z3,computeOutShape:()=>sO,computePool2DInfo:()=>S3,computePool3DInfo:()=>_R,convertConv2DDataFormat:()=>T3,decodeEinsumEquation:()=>CO,eitherStridesOrDilationsAreOne:()=>Nr,expandShapeToKeepDim:()=>Qi,exponent:()=>IO,exponents:()=>kO,fromStringArrayToUint8:()=>MO,fromUint8ToStringArray:()=>OO,getAxesPermutation:()=>Y3,getBroadcastDims:()=>I$,getComplexWithIndex:()=>vO,getEinsumComputePath:()=>EO,getEinsumPermutation:()=>TO,getFusedBiasGradient:()=>cf,getFusedDyActivation:()=>uf,getImageCenter:()=>aO,getInnerMostAxes:()=>fD,getPermuted:()=>iO,getReductionAxes:()=>an,getReshaped:()=>oO,getReshapedPermuted:()=>lO,getSliceBeginCoords:()=>uO,getSliceSize:()=>cO,getUndoAxesPermutation:()=>V2,isIdentityPermutation:()=>RO,log:()=>aE,mergeRealAndImagArrays:()=>AO,prepareAndValidate:()=>J5,prepareSplitSize:()=>DO,segment_util:()=>Pv,shouldFuse:()=>pf,slice_util:()=>An,splitRealAndImagArrays:()=>yO,tupleValuesAreOne:()=>wo,upcastType:()=>Bn,validateInput:()=>b2,validateUpdateShape:()=>x2,warn:()=>kr});function nO(e,t){let n=e[0].length;e.forEach((r,a)=>{O(r.length===n,()=>`Error in concat${n}D: rank of tensors[${a}] must be the same as the rank of the rest (${n})`)}),O(t>=0&&t`Error in concat${n}D: axis must be between 0 and ${n-1}.`);let s=e[0];e.forEach((r,a)=>{for(let o=0;o`Error in concat${n}D: Shape of tensors[${a}] (${r}) does not match the shape of the rest (${s}) along the non-concatenated axis ${a}.`)})}function sO(e,t){let n=e[0].slice();for(let s=1;s=t*2+1||o%2==1?a.push(o):r.push(o);s.push(...r),s.push(0),s.push(...a)}return s}function lO(e,t,n,s=!0){let r=[];s?r.push(e[0]/n):r.push(e[0]*n);for(let a=1;a/g,Dv=",",_v="...";function CO(e,t){e=e.replace(/\s/g,"");let n=(e.length-e.replace(SO,"").length)/d1.length;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error(`Equation must contain exactly one arrow ("${d1}").`);let[s,r]=e.split(d1);O(s.indexOf(_v)===-1,()=>`The ellipsis notation ("${_v}") is not supported yet.`);let a=s.split(Dv),o=a.length;if(t!==o)throw new Error(`Expected ${o} input tensors, received ${t}`);if(o>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let i=[];for(let p=0;p