s[m.id]=!0),p=!0,r[u.id]=!0;break}if(p)break}}let a={};a[n.id]=!0;let o={};for(let l=e.length-1;l>=0;l--){let u=e[l],c=u.inputs;for(let d=0;d=0;r--){let a=t[r],o=[];if(a.outputs.forEach(l=>{let u=e[l.id];u!=null?o.push(u):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 u=n(()=>i[l]());if(u.dtype!=="float32")throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);let c=a.inputs[l];if(!br(u.shape,c.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${c.shape}'`);if(e[c.id]==null)e[c.id]=u;else{let d=e[c.id];e[c.id]=s(d,u),d.dispose()}}}}var L5=20,ec=3,Hm=7;function i9(e,t,n,s){let r=wi(t),a=l9(e,t,n,r),o=t.length,i=Ph(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(u=>" "+u).join(`
+var Human=(()=>{var d5=Object.defineProperty;var WI=e=>d5(e,"__esModule",{value:!0});var Dm=typeof require!="undefined"?require:e=>{throw new Error('Dynamic require of "'+e+'" is not supported')};var $m=(e,t)=>{WI(e);for(var n in t)d5(e,n,{get:t[n],enumerable:!0})};var h5=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var mn=(e,t,n)=>(h5(e,t,"read from private field"),n?n.call(e):t.get(e)),as=(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)},Ds=(e,t,n,s)=>(h5(e,t,"write to private field"),s?s.call(e,n):t.set(e,n),n);var Ele={};$m(Ele,{Human:()=>J8,default:()=>J8});function gt(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(`Human: ModelPath Error: ${r} Expecting JSON file`);return r}function ue(...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 Ye=()=>typeof performance!="undefined"?performance.now():parseInt((Number(process.hrtime.bigint())/1e3/1e3).toString());function gn(...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]=gn(a,o):n[r]=o}),n),{})}var Fm={backend:"webgl",modelBasePath:"../models/",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:15,skipFrames:15,minConfidence:.2,iouThreshold:.1,return:!1},mesh:{enabled:!0,modelPath:"facemesh.json"},iris:{enabled:!0,modelPath:"iris.json"},description:{enabled:!0,modelPath:"faceres.json",skipFrames:11,minConfidence:.1},emotion:{enabled:!0,minConfidence:.1,skipFrames:17,modelPath:"emotion.json"}},body:{enabled:!0,modelPath:"movenet-lightning.json",maxDetected:1,minConfidence:.2,skipFrames:1},hand:{enabled:!0,rotation:!0,skipFrames:18,minConfidence:.8,iouThreshold:.2,maxDetected:1,landmarks:!0,detector:{modelPath:"handdetect.json"},skeleton:{modelPath:"handskeleton.json"}},object:{enabled:!1,modelPath:"mb3-centernet.json",minConfidence:.2,iouThreshold:.4,maxDetected:10,skipFrames:19},segmentation:{enabled:!1,modelPath:"selfie.json"}};function p5(){let e="",t="";if(typeof navigator!="undefined"){let n=navigator.userAgent.match(/\(([^()]+)\)/g);if(n&&n[0]){let s=n[0].match(/\(([^()]+)\)/g);e=s&&s[0]?s[0].replace(/\(|\)/g,""):"",t=navigator.userAgent.replace(n[0],""),e[1]&&(t=t.replace(n[1],"")),t=t.replace(/ /g," ")}}else typeof process!="undefined"&&(e=`${process.platform} ${process.arch}`,t=`NodeJS ${process.version}`);return{platform:e,agent:t}}var id={};$m(id,{Abs:()=>Ii,Acos:()=>Si,Acosh:()=>Ci,AdadeltaOptimizer:()=>gp,AdagradOptimizer:()=>Ap,AdamOptimizer:()=>yp,AdamaxOptimizer:()=>xp,Add:()=>Vr,AddN:()=>Na,All:()=>Ti,Any:()=>Ni,ArgMax:()=>Ea,ArgMin:()=>Pu,Asin:()=>Ei,Asinh:()=>Ri,Atan:()=>_i,Atan2:()=>$i,Atanh:()=>Di,AvgPool:()=>Ra,AvgPool3D:()=>Mu,AvgPool3DGrad:()=>Zd,AvgPoolGrad:()=>Kd,BackendWasm:()=>Bk,BatchMatMul:()=>_a,BatchToSpaceND:()=>Fi,Bincount:()=>Yd,BroadcastArgs:()=>Wm,BroadcastTo:()=>D5,Callback:()=>zv,CallbackList:()=>R3,Cast:()=>Da,Ceil:()=>$a,ClipByValue:()=>Ur,Complex:()=>Jd,ComplexAbs:()=>zu,Concat:()=>Oi,Conv2D:()=>Fa,Conv2DBackpropFilter:()=>Qd,Conv2DBackpropInput:()=>Oa,Conv3D:()=>Lu,Conv3DBackpropFilterV2:()=>eh,Conv3DBackpropInputV2:()=>th,Cos:()=>Pa,Cosh:()=>Ma,CropAndResize:()=>Pi,Cumsum:()=>za,CustomCallback:()=>D3,DataStorage:()=>Hd,DenseBincount:()=>nh,DepthToSpace:()=>Mi,DepthwiseConv2dNative:()=>La,DepthwiseConv2dNativeBackpropFilter:()=>sh,DepthwiseConv2dNativeBackpropInput:()=>rh,Diag:()=>ah,Dilation2D:()=>Bu,Dilation2DBackpropFilter:()=>ih,Dilation2DBackpropInput:()=>oh,ENV:()=>os,EarlyStopping:()=>Bv,Einsum:()=>lh,Elu:()=>Wa,EluGrad:()=>uh,Environment:()=>R5,Equal:()=>Li,Erf:()=>zi,Exp:()=>Va,ExpandDims:()=>Bi,Expm1:()=>Wi,FFT:()=>ch,Fill:()=>Wu,FlipLeftRight:()=>Vi,Floor:()=>Ua,FloorDiv:()=>Ha,FromPixels:()=>_h,FusedBatchNorm:()=>Ga,FusedConv2D:()=>Co,FusedDepthwiseConv2D:()=>To,GPGPUContext:()=>wf,GatherNd:()=>Hi,GatherV2:()=>Ui,GraphModel:()=>y7,Greater:()=>Gi,GreaterEqual:()=>ja,History:()=>_3,IFFT:()=>dh,Identity:()=>qa,Imag:()=>hh,InputSpec:()=>zt,IsFinite:()=>ji,IsInf:()=>qi,IsNan:()=>Xi,KernelBackend:()=>$u,LRN:()=>Hu,LRNGrad:()=>fh,LayerVariable:()=>S3,LayersModel:()=>Nr,LeakyRelu:()=>Xa,Less:()=>Ki,LessEqual:()=>Zi,LinSpace:()=>ph,Log:()=>Ka,Log1p:()=>Yi,LogSoftmax:()=>$5,LogicalAnd:()=>Ji,LogicalNot:()=>Vu,LogicalOr:()=>Uu,MathBackendCPU:()=>of,MathBackendWebGL:()=>uu,Max:()=>Za,MaxPool:()=>Ja,MaxPool3D:()=>Gu,MaxPool3DGrad:()=>gh,MaxPoolGrad:()=>mh,MaxPoolWithArgmax:()=>Ah,Maximum:()=>Ya,Mean:()=>Qa,Min:()=>eo,Minimum:()=>to,MirrorPad:()=>no,Mod:()=>Qi,MomentumOptimizer:()=>bp,Multinomial:()=>yh,Multiply:()=>so,Neg:()=>el,NonMaxSuppressionV3:()=>nl,NonMaxSuppressionV4:()=>sl,NonMaxSuppressionV5:()=>rl,NotEqual:()=>tl,OP_SCOPE_SUFFIX:()=>X5,OneHot:()=>ro,OnesLike:()=>al,Optimizer:()=>Sr,Pack:()=>ol,PadV2:()=>ao,Pool:()=>GS,Pow:()=>oo,Prelu:()=>io,Prod:()=>il,RMSPropOptimizer:()=>vp,RNN:()=>ur,Range:()=>ju,Rank:()=>jm,Real:()=>xh,RealDiv:()=>Ba,Reciprocal:()=>ll,Reduction:()=>vn,Relu:()=>lo,Relu6:()=>co,Reshape:()=>ul,ResizeBilinear:()=>uo,ResizeBilinearGrad:()=>vh,ResizeNearestNeighbor:()=>qu,ResizeNearestNeighborGrad:()=>bh,Reverse:()=>ho,RotateWithOffset:()=>Il,Round:()=>po,Rsqrt:()=>fo,SGDOptimizer:()=>bc,ScatterNd:()=>cl,Select:()=>dl,Selu:()=>hl,Sequential:()=>Kl,Sigmoid:()=>go,Sign:()=>ml,Sin:()=>mo,Sinh:()=>fl,Slice:()=>pl,Softmax:()=>xo,Softplus:()=>gl,SpaceToBatchND:()=>Al,SparseFillEmptyRows:()=>wh,SparseReshape:()=>kh,SparseSegmentMean:()=>Ih,SparseSegmentSum:()=>Sh,SparseToDense:()=>Ch,SplitV:()=>yl,Sqrt:()=>Ao,Square:()=>Xu,SquaredDifference:()=>bo,Step:()=>Gr,StridedSlice:()=>xl,StringNGrams:()=>Th,StringSplit:()=>Nh,StringToHashBucketFast:()=>Eh,Sub:()=>vo,Sum:()=>yo,SymbolicTensor:()=>Vs,Tan:()=>wo,Tanh:()=>ko,Tensor:()=>Ge,TensorBuffer:()=>Ut,Tile:()=>Hr,TopK:()=>bl,Transform:()=>vl,Transpose:()=>Io,Unique:()=>Rh,Unpack:()=>wl,UnsortedSegmentSum:()=>Ku,Variable:()=>sc,ZerosLike:()=>kl,_FusedMatMul:()=>So,abs:()=>Ht,acos:()=>$x,acosh:()=>Fx,add:()=>ae,addN:()=>Uh,all:()=>vg,any:()=>Hh,argMax:()=>er,argMin:()=>Ox,asin:()=>Px,asinh:()=>Mx,atan:()=>zx,atan2:()=>Lx,atanh:()=>Bx,avgPool:()=>jh,avgPool3d:()=>Ig,backend:()=>Dx,backend_util:()=>D,basicLSTMCell:()=>ET,batchNorm:()=>Ol,batchNorm2d:()=>Hx,batchNorm3d:()=>Gx,batchNorm4d:()=>jx,batchToSpaceND:()=>qh,bincount:()=>Sg,booleanMaskAsync:()=>VR,broadcastArgs:()=>qx,broadcastTo:()=>cc,browser:()=>ls,buffer:()=>We,callbacks:()=>rL,cast:()=>ce,ceil:()=>Xx,clipByValue:()=>Gn,clone:()=>Os,complex:()=>qr,concat:()=>ft,concat1d:()=>Kx,concat2d:()=>Pl,concat3d:()=>Zx,concat4d:()=>Yx,constraints:()=>r3,conv1d:()=>Cg,conv2d:()=>Jr,conv2dTranspose:()=>Ng,conv3d:()=>Eg,conv3dTranspose:()=>Qx,copyRegisteredKernels:()=>XS,cos:()=>Xh,cosh:()=>Rg,cosineWindow:()=>tA,cumsum:()=>_g,customGrad:()=>nr,data:()=>x7,denseBincount:()=>eb,deprecationWarn:()=>yg,depthToSpace:()=>tb,depthwiseConv2d:()=>dc,deregisterOp:()=>oL,device_util:()=>ac,diag:()=>aN,dilation2d:()=>nb,disableDeprecationWarnings:()=>VC,dispose:()=>Z,disposeVariables:()=>UC,div:()=>de,divNoNan:()=>sb,dot:()=>pN,dropout:()=>$b,einsum:()=>rb,elu:()=>hc,enableDebugMode:()=>WC,enableProdMode:()=>BC,enclosingPowerOfTwo:()=>Fb,engine:()=>wr,env:()=>Q,equal:()=>us,erf:()=>ab,exp:()=>cs,expandDims:()=>Ot,expm1:()=>ob,eye:()=>Dg,fft:()=>lp,fill:()=>Ml,findBackend:()=>xg,findBackendFactory:()=>ZC,floor:()=>pc,floorDiv:()=>bg,forceHalfFloat:()=>G6,fused:()=>ta,gather:()=>zl,gatherND:()=>Db,gather_util:()=>dg,getBackend:()=>XC,getGradient:()=>Vm,getKernel:()=>Dh,getKernelsForBackend:()=>Cl,gpgpu_util:()=>x6,grad:()=>zN,grads:()=>LN,greater:()=>jn,greaterEqual:()=>Po,ifft:()=>Ac,imag:()=>Kh,image:()=>_e,inTopKAsync:()=>QR,initializers:()=>d3,input:()=>tv,io:()=>_n,irfft:()=>Kg,isFinite:()=>NN,isInf:()=>RN,isNaN:()=>ib,keep:()=>Jt,kernel_impls:()=>rr,layers:()=>w3,leakyRelu:()=>Zh,less:()=>$g,lessEqual:()=>Mo,linalg:()=>Hb,linspace:()=>lb,loadGraphModel:()=>mt,loadLayersModel:()=>fM,localResponseNormalization:()=>ub,log:()=>ds,log1p:()=>Yh,logSigmoid:()=>GN,logSoftmax:()=>Fg,logSumExp:()=>fb,logicalAnd:()=>Ps,logicalNot:()=>Qh,logicalOr:()=>Mg,logicalXor:()=>sE,losses:()=>MD,matMul:()=>Ve,math:()=>hx,max:()=>hs,maxPool:()=>ep,maxPool3d:()=>zg,maxPoolWithArgmax:()=>mb,maximum:()=>kr,mean:()=>_t,memory:()=>Vh,meshgrid:()=>uE,metrics:()=>Ov,min:()=>tp,minimum:()=>fc,mirrorPad:()=>gb,mod:()=>Ab,model:()=>hM,models:()=>Pv,moments:()=>np,movingAverage:()=>GR,mul:()=>L,multiRNNCell:()=>AE,multinomial:()=>yb,neg:()=>Tt,nextFrame:()=>wp,norm:()=>Qg,notEqual:()=>Bl,oneHot:()=>lc,ones:()=>qn,onesLike:()=>ps,op:()=>W,outerProduct:()=>wE,pad:()=>Qr,pad1d:()=>SE,pad2d:()=>TE,pad3d:()=>EE,pad4d:()=>_E,pool:()=>PE,pow:()=>ea,prelu:()=>rp,print:()=>ox,prod:()=>Lg,profile:()=>HC,rand:()=>WE,randomGamma:()=>GE,randomNormal:()=>xb,randomUniform:()=>Wl,range:()=>Vl,ready:()=>qC,real:()=>mc,reciprocal:()=>bb,registerBackend:()=>Dl,registerCallbackConstructor:()=>mM,registerGradient:()=>F5,registerKernel:()=>No,registerOp:()=>aL,regularizers:()=>Mv,relu:()=>sr,relu6:()=>Vg,removeBackend:()=>KC,reshape:()=>U,reverse:()=>fs,reverse1d:()=>eR,reverse2d:()=>nR,reverse3d:()=>rR,reverse4d:()=>oR,rfft:()=>up,round:()=>Ug,rsqrt:()=>Hg,scalar:()=>Ie,scatterND:()=>_b,scatter_util:()=>hg,selu:()=>Gg,separableConv2d:()=>vb,sequential:()=>pM,serialization:()=>oe,setBackend:()=>jC,setPlatform:()=>YC,setWasmPath:()=>Lie,setWasmPaths:()=>Bie,setWebGLContext:()=>pf,setdiff1dAsync:()=>wb,shared:()=>d2,sigmoid:()=>Hn,sign:()=>kb,signal:()=>PD,sin:()=>jg,sinh:()=>qg,slice:()=>Re,slice1d:()=>ap,slice2d:()=>Xg,slice3d:()=>op,slice4d:()=>gc,slice_util:()=>xn,softmax:()=>ip,softplus:()=>Ll,spaceToBatchND:()=>sp,sparse:()=>xc,sparseToDense:()=>eA,spectral:()=>OD,split:()=>an,sqrt:()=>hn,square:()=>ct,squaredDifference:()=>Zg,squeeze:()=>lt,stack:()=>Dn,step:()=>yc,stridedSlice:()=>Ib,string:()=>mp,sub:()=>ge,sum:()=>ve,sumOutType:()=>Mh,tan:()=>Sb,tanh:()=>Fl,tensor:()=>dn,tensor1d:()=>Mt,tensor2d:()=>Ms,tensor3d:()=>Bh,tensor4d:()=>DR,tensor5d:()=>$R,tensor6d:()=>FR,tensor_util:()=>$s,test_util:()=>Nx,tidy:()=>H,tile:()=>Ts,time:()=>GC,topk:()=>Cb,train:()=>Bo,transpose:()=>Xe,truncatedNormal:()=>cp,unique:()=>Yg,unregisterGradient:()=>qS,unregisterKernel:()=>jS,unsortedSegmentSum:()=>Tb,unstack:()=>ms,upcastType:()=>Cs,util:()=>w,valueAndGrad:()=>BN,valueAndGrads:()=>WN,variable:()=>Nb,variableGrads:()=>cb,version:()=>Uie,version_converter:()=>uB,version_core:()=>_x,version_cpu:()=>KW,version_layers:()=>PA,version_wasm:()=>Wie,version_webgl:()=>wK,webgl:()=>kK,webgl_util:()=>Uw,where:()=>bn,whereAsync:()=>Jg,zeros:()=>Pt,zerosLike:()=>Ke});var VI=Object.create,Ud=Object.defineProperty,UI=Object.getOwnPropertyDescriptor,HI=Object.getOwnPropertyNames,GI=Object.getPrototypeOf,jI=Object.prototype.hasOwnProperty,f5=e=>Ud(e,"__esModule",{value:!0}),vi=typeof Dm!="undefined"?Dm:e=>{throw new Error('Dynamic require of "'+e+'" is not supported')},vt=(e,t)=>function(){return t||(0,e[Object.keys(e)[0]])((t={exports:{}}).exports,t),t.exports},Pe=(e,t)=>{f5(e);for(var n in t)Ud(e,n,{get:t[n],enumerable:!0})},qI=(e,t,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of HI(t))!jI.call(e,s)&&s!=="default"&&Ud(e,s,{get:()=>t[s],enumerable:!(n=UI(t,s))||n.enumerable});return e},Sa=e=>qI(f5(Ud(e!=null?VI(GI(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e),XI=vt({"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(R){}function s(R,T,P){this.low=R|0,this.high=T|0,this.unsigned=!!P}s.prototype.__isLong__,Object.defineProperty(s.prototype,"__isLong__",{value:!0});function r(R){return(R&&R.__isLong__)===!0}s.isLong=r;var a={},o={};function i(R,T){var P,V,j;return T?(R>>>=0,(j=0<=R&&R<256)&&(V=o[R],V)?V:(P=u(R,(R|0)<0?-1:0,!0),j&&(o[R]=P),P)):(R|=0,(j=-128<=R&&R<128)&&(V=a[R],V)?V:(P=u(R,R<0?-1:0,!1),j&&(a[R]=P),P))}s.fromInt=i;function l(R,T){if(isNaN(R))return T?b:x;if(T){if(R<0)return b;if(R>=g)return _}else{if(R<=-A)return O;if(R+1>=A)return C}return R<0?l(-R,T).neg():u(R%m|0,R/m|0,T)}s.fromNumber=l;function u(R,T,P){return new s(R,T,P)}s.fromBits=u;var c=Math.pow;function d(R,T,P){if(R.length===0)throw Error("empty string");if(R==="NaN"||R==="Infinity"||R==="+Infinity"||R==="-Infinity")return x;if(typeof T=="number"?(P=T,T=!1):T=!!T,P=P||10,P<2||360)throw Error("interior hyphen");if(V===0)return d(R.substring(1),T,P).neg();for(var j=l(c(P,8)),q=x,X=0;X>>0:this.low},E.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},E.toString=function(T){if(T=T||10,T<2||36>>0,se=ne.toString(T);if(X=te,X.isZero())return se+ee;for(;se.length<6;)se="0"+se;ee=""+se+ee}},E.getHighBits=function(){return this.high},E.getHighBitsUnsigned=function(){return this.high>>>0},E.getLowBits=function(){return this.low},E.getLowBitsUnsigned=function(){return this.low>>>0},E.getNumBitsAbs=function(){if(this.isNegative())return this.eq(O)?64:this.neg().getNumBitsAbs();for(var T=this.high!=0?this.high:this.low,P=31;P>0&&(T&1<=0},E.isOdd=function(){return(this.low&1)==1},E.isEven=function(){return(this.low&1)==0},E.equals=function(T){return r(T)||(T=h(T)),this.unsigned!==T.unsigned&&this.high>>>31==1&&T.high>>>31==1?!1:this.high===T.high&&this.low===T.low},E.eq=E.equals,E.notEquals=function(T){return!this.eq(T)},E.neq=E.notEquals,E.ne=E.notEquals,E.lessThan=function(T){return this.comp(T)<0},E.lt=E.lessThan,E.lessThanOrEqual=function(T){return this.comp(T)<=0},E.lte=E.lessThanOrEqual,E.le=E.lessThanOrEqual,E.greaterThan=function(T){return this.comp(T)>0},E.gt=E.greaterThan,E.greaterThanOrEqual=function(T){return this.comp(T)>=0},E.gte=E.greaterThanOrEqual,E.ge=E.greaterThanOrEqual,E.compare=function(T){if(r(T)||(T=h(T)),this.eq(T))return 0;var P=this.isNegative(),V=T.isNegative();return P&&!V?-1:!P&&V?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},E.comp=E.compare,E.negate=function(){return!this.unsigned&&this.eq(O)?O:this.not().add(v)},E.neg=E.negate,E.add=function(T){r(T)||(T=h(T));var P=this.high>>>16,V=this.high&65535,j=this.low>>>16,q=this.low&65535,X=T.high>>>16,ee=T.high&65535,te=T.low>>>16,ne=T.low&65535,se=0,J=0,ie=0,le=0;return le+=q+ne,ie+=le>>>16,le&=65535,ie+=j+te,J+=ie>>>16,ie&=65535,J+=V+ee,se+=J>>>16,J&=65535,se+=P+X,se&=65535,u(ie<<16|le,se<<16|J,this.unsigned)},E.subtract=function(T){return r(T)||(T=h(T)),this.add(T.neg())},E.sub=E.subtract,E.multiply=function(T){if(this.isZero())return x;if(r(T)||(T=h(T)),n){var P=n.mul(this.low,this.high,T.low,T.high);return u(P,n.get_high(),this.unsigned)}if(T.isZero())return x;if(this.eq(O))return T.isOdd()?O:x;if(T.eq(O))return this.isOdd()?O: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 V=this.high>>>16,j=this.high&65535,q=this.low>>>16,X=this.low&65535,ee=T.high>>>16,te=T.high&65535,ne=T.low>>>16,se=T.low&65535,J=0,ie=0,le=0,he=0;return he+=X*se,le+=he>>>16,he&=65535,le+=q*se,ie+=le>>>16,le&=65535,le+=X*ne,ie+=le>>>16,le&=65535,ie+=j*se,J+=ie>>>16,ie&=65535,ie+=q*ne,J+=ie>>>16,ie&=65535,ie+=X*te,J+=ie>>>16,ie&=65535,J+=V*se+j*ne+q*te+X*ee,J&=65535,u(le<<16|he,J<<16|ie,this.unsigned)},E.mul=E.multiply,E.divide=function(T){if(r(T)||(T=h(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 P=(this.unsigned?n.div_u:n.div_s)(this.low,this.high,T.low,T.high);return u(P,n.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?b:x;var V,j,q;if(this.unsigned){if(T.unsigned||(T=T.toUnsigned()),T.gt(this))return b;if(T.gt(this.shru(1)))return k;q=b}else{if(this.eq(O)){if(T.eq(v)||T.eq(S))return O;if(T.eq(O))return v;var X=this.shr(1);return V=X.div(T).shl(1),V.eq(x)?T.isNegative()?v:S:(j=this.sub(T.mul(V)),q=V.add(j.div(T)),q)}else if(T.eq(O))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();q=x}for(j=this;j.gte(T);){V=Math.max(1,Math.floor(j.toNumber()/T.toNumber()));for(var ee=Math.ceil(Math.log(V)/Math.LN2),te=ee<=48?1:c(2,ee-48),ne=l(V),se=ne.mul(T);se.isNegative()||se.gt(j);)V-=te,ne=l(V,this.unsigned),se=ne.mul(T);ne.isZero()&&(ne=v),q=q.add(ne),j=j.sub(se)}return q},E.div=E.divide,E.modulo=function(T){if(r(T)||(T=h(T)),n){var P=(this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,T.low,T.high);return u(P,n.get_high(),this.unsigned)}return this.sub(this.div(T).mul(T))},E.mod=E.modulo,E.rem=E.modulo,E.not=function(){return u(~this.low,~this.high,this.unsigned)},E.and=function(T){return r(T)||(T=h(T)),u(this.low&T.low,this.high&T.high,this.unsigned)},E.or=function(T){return r(T)||(T=h(T)),u(this.low|T.low,this.high|T.high,this.unsigned)},E.xor=function(T){return r(T)||(T=h(T)),u(this.low^T.low,this.high^T.high,this.unsigned)},E.shiftLeft=function(T){return r(T)&&(T=T.toInt()),(T&=63)===0?this:T<32?u(this.low<>>32-T,this.unsigned):u(0,this.low<>>T|this.high<<32-T,this.high>>T,this.unsigned):u(this.high>>T-32,this.high>=0?0:-1,this.unsigned)},E.shr=E.shiftRight,E.shiftRightUnsigned=function(T){if(r(T)&&(T=T.toInt()),T&=63,T===0)return this;var P=this.high;if(T<32){var V=this.low;return u(V>>>T|P<<32-T,P>>>T,this.unsigned)}else return T===32?u(P,0,this.unsigned):u(P>>>T-32,0,this.unsigned)},E.shru=E.shiftRightUnsigned,E.shr_u=E.shiftRightUnsigned,E.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},E.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},E.toBytes=function(T){return T?this.toBytesLE():this.toBytesBE()},E.toBytesLE=function(){var T=this.high,P=this.low;return[P&255,P>>>8&255,P>>>16&255,P>>>24,T&255,T>>>8&255,T>>>16&255,T>>>24]},E.toBytesBE=function(){var T=this.high,P=this.low;return[T>>>24,T>>>16&255,T>>>8&255,T&255,P>>>24,P>>>16&255,P>>>8&255,P&255]},s.fromBytes=function(T,P,V){return V?s.fromBytesLE(T,P):s.fromBytesBE(T,P)},s.fromBytesLE=function(T,P){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,P)},s.fromBytesBE=function(T,P){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],P)}}}),KI=vt({"(disabled):node_modules/.pnpm/node-fetch@2.6.2/node_modules/node-fetch/browser.js"(){}}),ZI=vt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/alea.js"(e,t){(function(n,s,r){function a(u){var c=this,d=l();c.next=function(){var h=2091639*c.s0+c.c*23283064365386963e-26;return c.s0=c.s1,c.s1=c.s2,c.s2=h-(c.c=h|0)},c.c=1,c.s0=d(" "),c.s1=d(" "),c.s2=d(" "),c.s0-=d(u),c.s0<0&&(c.s0+=1),c.s1-=d(u),c.s1<0&&(c.s1+=1),c.s2-=d(u),c.s2<0&&(c.s2+=1),d=null}function o(u,c){return c.c=u.c,c.s0=u.s0,c.s1=u.s1,c.s2=u.s2,c}function i(u,c){var d=new a(u),h=c&&c.state,p=d.next;return p.int32=function(){return d.next()*4294967296|0},p.double=function(){return p()+(p()*2097152|0)*11102230246251565e-32},p.quick=p,h&&(typeof h=="object"&&o(h,d),p.state=function(){return o(d,{})}),p}function l(){var u=4022871197,c=function(d){d=d.toString();for(var h=0;h>>0,p-=u,p*=u,u=p>>>0,p-=u,u+=p*4294967296}return(u>>>0)*23283064365386963e-26};return c}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)}}),YI=vt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xor128.js"(e,t){(function(n,s,r){function a(l){var u=this,c="";u.x=0,u.y=0,u.z=0,u.w=0,u.next=function(){var h=u.x^u.x<<11;return u.x=u.y,u.y=u.z,u.z=u.w,u.w^=u.w>>>19^h^h>>>8},l===(l|0)?u.x=l:c+=l;for(var d=0;d>>0)/4294967296};return h.double=function(){do var p=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(p+f)/(1<<21);while(m===0);return m},h.int32=c.next,h.quick=h,d&&(typeof d=="object"&&o(d,c),h.state=function(){return o(c,{})}),h}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)}}),JI=vt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xorwow.js"(e,t){(function(n,s,r){function a(l){var u=this,c="";u.next=function(){var h=u.x^u.x>>>2;return u.x=u.y,u.y=u.z,u.z=u.w,u.w=u.v,(u.d=u.d+362437|0)+(u.v=u.v^u.v<<4^(h^h<<1))|0},u.x=0,u.y=0,u.z=0,u.w=0,u.v=0,l===(l|0)?u.x=l:c+=l;for(var d=0;d>>4),u.next()}function o(l,u){return u.x=l.x,u.y=l.y,u.z=l.z,u.w=l.w,u.v=l.v,u.d=l.d,u}function i(l,u){var c=new a(l),d=u&&u.state,h=function(){return(c.next()>>>0)/4294967296};return h.double=function(){do var p=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(p+f)/(1<<21);while(m===0);return m},h.int32=c.next,h.quick=h,d&&(typeof d=="object"&&o(d,c),h.state=function(){return o(c,{})}),h}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)}}),QI=vt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xorshift7.js"(e,t){(function(n,s,r){function a(l){var u=this;u.next=function(){var d=u.x,h=u.i,p,f,m;return p=d[h],p^=p>>>7,f=p^p<<24,p=d[h+1&7],f^=p^p>>>10,p=d[h+3&7],f^=p^p>>>3,p=d[h+4&7],f^=p^p<<7,p=d[h+7&7],p=p^p<<13,f^=p^p<<9,d[h]=f,u.i=h+1&7,f};function c(d,h){var p,f,m=[];if(h===(h|0))f=m[0]=h;else for(h=""+h,p=0;p0;--p)d.next()}c(u,l)}function o(l,u){return u.x=l.x.slice(),u.i=l.i,u}function i(l,u){l==null&&(l=+new Date);var c=new a(l),d=u&&u.state,h=function(){return(c.next()>>>0)/4294967296};return h.double=function(){do var p=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(p+f)/(1<<21);while(m===0);return m},h.int32=c.next,h.quick=h,d&&(d.x&&o(d,c),h.state=function(){return o(c,{})}),h}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)}}),eS=vt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xor4096.js"(e,t){(function(n,s,r){function a(l){var u=this;u.next=function(){var d=u.w,h=u.X,p=u.i,f,m;return u.w=d=d+1640531527|0,m=h[p+34&127],f=h[p=p+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,m=h[p]=m^f,u.i=p,m+(d^d>>>16)|0};function c(d,h){var p,f,m,g,A,y=[],x=128;for(h===(h|0)?(f=h,h=null):(h=h+"\0",f=0,x=Math.max(x,h.length)),m=0,g=-32;g>>15,f^=f<<4,f^=f>>>13,g>=0&&(A=A+1640531527|0,p=y[g&127]^=f+A,m=p==0?m+1:0);for(m>=128&&(y[(h&&h.length||0)&127]=-1),m=127,g=4*128;g>0;--g)f=y[m+34&127],p=y[m=m+1&127],f^=f<<13,p^=p<<17,f^=f>>>15,p^=p>>>12,y[m]=f^p;d.w=A,d.X=y,d.i=m}c(u,l)}function o(l,u){return u.i=l.i,u.w=l.w,u.X=l.X.slice(),u}function i(l,u){l==null&&(l=+new Date);var c=new a(l),d=u&&u.state,h=function(){return(c.next()>>>0)/4294967296};return h.double=function(){do var p=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(p+f)/(1<<21);while(m===0);return m},h.int32=c.next,h.quick=h,d&&(d.X&&o(d,c),h.state=function(){return o(c,{})}),h}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)}}),tS=vt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/tychei.js"(e,t){(function(n,s,r){function a(l){var u=this,c="";u.next=function(){var h=u.b,p=u.c,f=u.d,m=u.a;return h=h<<25^h>>>7^p,p=p-f|0,f=f<<24^f>>>8^m,m=m-h|0,u.b=h=h<<20^h>>>12^p,u.c=p=p-f|0,u.d=f<<16^p>>>16^m,u.a=m-h|0},u.a=0,u.b=0,u.c=2654435769|0,u.d=1367130551,l===Math.floor(l)?(u.a=l/4294967296|0,u.b=l|0):c+=l;for(var d=0;d>>0)/4294967296};return h.double=function(){do var p=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(p+f)/(1<<21);while(m===0);return m},h.int32=c.next,h.quick=h,d&&(typeof d=="object"&&o(d,c),h.state=function(){return o(c,{})}),h}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)}}),m5=vt({"(disabled):crypto"(){}}),nS=vt({"node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/seedrandom.js"(e,t){(function(n,s){var r=this,a=256,o=6,i=52,l="random",u=s.pow(a,o),c=s.pow(2,i),d=c*2,h=a-1,p;function f(v,k,S){var C=[];k=k==!0?{entropy:!0}:k||{};var _=y(A(k.entropy?[v,b(n)]:v==null?x():v,3),C),O=new m(C),E=function(){for(var R=O.g(o),T=u,P=0;R=d;)R/=2,T/=2,P>>>=1;return(R+P)/T};return E.int32=function(){return O.g(4)|0},E.quick=function(){return O.g(4)/4294967296},E.double=E,y(b(O.S),n),(k.pass||S||function(R,T,P,V){return V&&(V.S&&g(V,O),R.state=function(){return g(O,{})}),P?(s[l]=R,T):R})(E,_,"global"in k?k.global:this==s,k.state)}s["seed"+l]=f;function m(v){var k,S=v.length,C=this,_=0,O=C.i=C.j=0,E=C.S=[];for(S||(v=[S++]);_>>0,p-=u,p*=u,u=p>>>0,p-=u,u+=p*4294967296}return(u>>>0)*23283064365386963e-26};return c}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)}}),rS=vt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js"(e,t){(function(n,s,r){function a(l){var u=this,c="";u.x=0,u.y=0,u.z=0,u.w=0,u.next=function(){var h=u.x^u.x<<11;return u.x=u.y,u.y=u.z,u.z=u.w,u.w^=u.w>>>19^h^h>>>8},l===(l|0)?u.x=l:c+=l;for(var d=0;d>>0)/4294967296};return h.double=function(){do var p=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(p+f)/(1<<21);while(m===0);return m},h.int32=c.next,h.quick=h,d&&(typeof d=="object"&&o(d,c),h.state=function(){return o(c,{})}),h}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)}}),aS=vt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js"(e,t){(function(n,s,r){function a(l){var u=this,c="";u.next=function(){var h=u.x^u.x>>>2;return u.x=u.y,u.y=u.z,u.z=u.w,u.w=u.v,(u.d=u.d+362437|0)+(u.v=u.v^u.v<<4^(h^h<<1))|0},u.x=0,u.y=0,u.z=0,u.w=0,u.v=0,l===(l|0)?u.x=l:c+=l;for(var d=0;d>>4),u.next()}function o(l,u){return u.x=l.x,u.y=l.y,u.z=l.z,u.w=l.w,u.v=l.v,u.d=l.d,u}function i(l,u){var c=new a(l),d=u&&u.state,h=function(){return(c.next()>>>0)/4294967296};return h.double=function(){do var p=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(p+f)/(1<<21);while(m===0);return m},h.int32=c.next,h.quick=h,d&&(typeof d=="object"&&o(d,c),h.state=function(){return o(c,{})}),h}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)}}),oS=vt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js"(e,t){(function(n,s,r){function a(l){var u=this;u.next=function(){var d=u.x,h=u.i,p,f,m;return p=d[h],p^=p>>>7,f=p^p<<24,p=d[h+1&7],f^=p^p>>>10,p=d[h+3&7],f^=p^p>>>3,p=d[h+4&7],f^=p^p<<7,p=d[h+7&7],p=p^p<<13,f^=p^p<<9,d[h]=f,u.i=h+1&7,f};function c(d,h){var p,f,m=[];if(h===(h|0))f=m[0]=h;else for(h=""+h,p=0;p0;--p)d.next()}c(u,l)}function o(l,u){return u.x=l.x.slice(),u.i=l.i,u}function i(l,u){l==null&&(l=+new Date);var c=new a(l),d=u&&u.state,h=function(){return(c.next()>>>0)/4294967296};return h.double=function(){do var p=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(p+f)/(1<<21);while(m===0);return m},h.int32=c.next,h.quick=h,d&&(d.x&&o(d,c),h.state=function(){return o(c,{})}),h}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)}}),iS=vt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js"(e,t){(function(n,s,r){function a(l){var u=this;u.next=function(){var d=u.w,h=u.X,p=u.i,f,m;return u.w=d=d+1640531527|0,m=h[p+34&127],f=h[p=p+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,m=h[p]=m^f,u.i=p,m+(d^d>>>16)|0};function c(d,h){var p,f,m,g,A,y=[],x=128;for(h===(h|0)?(f=h,h=null):(h=h+"\0",f=0,x=Math.max(x,h.length)),m=0,g=-32;g>>15,f^=f<<4,f^=f>>>13,g>=0&&(A=A+1640531527|0,p=y[g&127]^=f+A,m=p==0?m+1:0);for(m>=128&&(y[(h&&h.length||0)&127]=-1),m=127,g=4*128;g>0;--g)f=y[m+34&127],p=y[m=m+1&127],f^=f<<13,p^=p<<17,f^=f>>>15,p^=p>>>12,y[m]=f^p;d.w=A,d.X=y,d.i=m}c(u,l)}function o(l,u){return u.i=l.i,u.w=l.w,u.X=l.X.slice(),u}function i(l,u){l==null&&(l=+new Date);var c=new a(l),d=u&&u.state,h=function(){return(c.next()>>>0)/4294967296};return h.double=function(){do var p=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(p+f)/(1<<21);while(m===0);return m},h.int32=c.next,h.quick=h,d&&(d.X&&o(d,c),h.state=function(){return o(c,{})}),h}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)}}),lS=vt({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js"(e,t){(function(n,s,r){function a(l){var u=this,c="";u.next=function(){var h=u.b,p=u.c,f=u.d,m=u.a;return h=h<<25^h>>>7^p,p=p-f|0,f=f<<24^f>>>8^m,m=m-h|0,u.b=h=h<<20^h>>>12^p,u.c=p=p-f|0,u.d=f<<16^p>>>16^m,u.a=m-h|0},u.a=0,u.b=0,u.c=2654435769|0,u.d=1367130551,l===Math.floor(l)?(u.a=l/4294967296|0,u.b=l|0):c+=l;for(var d=0;d>>0)/4294967296};return h.double=function(){do var p=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(p+f)/(1<<21);while(m===0);return m},h.int32=c.next,h.quick=h,d&&(typeof d=="object"&&o(d,c),h.state=function(){return o(c,{})}),h}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)}}),uS=vt({"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",u=r.pow(a,o),c=r.pow(2,i),d=c*2,h=a-1,p;function f(v,k,S){var C=[];k=k==!0?{entropy:!0}:k||{};var _=y(A(k.entropy?[v,b(s)]:v==null?x():v,3),C),O=new m(C),E=function(){for(var R=O.g(o),T=u,P=0;R=d;)R/=2,T/=2,P>>>=1;return(R+P)/T};return E.int32=function(){return O.g(4)|0},E.quick=function(){return O.g(4)/4294967296},E.double=E,y(b(O.S),s),(k.pass||S||function(R,T,P,V){return V&&(V.S&&g(V,O),R.state=function(){return g(O,{})}),P?(r[l]=R,T):R})(E,_,"global"in k?k.global:this==r,k.state)}function m(v){var k,S=v.length,C=this,_=0,O=C.i=C.j=0,E=C.S=[];for(S||(v=[S++]);_1&&(g=process.argv[1].replace(/\\/g,"/")),m=process.argv.slice(2),process.on("uncaughtException",function(N){if(!(N instanceof _u))throw N}),process.on("unhandledRejection",Ar),A=function(N){process.exit(N)},c.inspect=function(){return"[Emscripten Module object]"};var V;try{V=cS()}catch(N){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),N}global.Worker=V.Worker}else v?(typeof read!="undefined"&&(_=function(F){return read(F)}),E=function(F){var B;return typeof readbuffer=="function"?new Uint8Array(readbuffer(F)):(B=read(F,"binary"),Ae(typeof B=="object"),B)},typeof scriptArgs!="undefined"?m=scriptArgs:typeof arguments!="undefined"&&(m=arguments),typeof quit=="function"&&(A=function(N){quit(N)}),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(F,B){return T||(T=vi("fs")),P||(P=Du()),F=P.normalize(F),T.readFileSync(F,B?null:"utf8")},E=function(F){var B=_(F,!0);return B.buffer||(B=new Uint8Array(B)),Ae(B.buffer),B}):(_=function(N){var F=new XMLHttpRequest;return F.open("GET",N,!1),F.send(null),F.responseText},x&&(E=function(N){var F=new XMLHttpRequest;return F.open("GET",N,!1),F.responseType="arraybuffer",F.send(null),new Uint8Array(F.response)}),O=function(N,F,B){var K=new XMLHttpRequest;K.open("GET",N,!0),K.responseType="arraybuffer",K.onload=function(){if(K.status==200||K.status==0&&K.response){F(K.response);return}B()},K.onerror=B,K.send(null)}),R=function(N){document.title=N});b&&typeof performance=="undefined"&&(global.performance=dS().performance);var j=c.print||console.log.bind(console),q=c.printErr||console.warn.bind(console);for(f in p)p.hasOwnProperty(f)&&(c[f]=p[f]);p=null,c.arguments&&(m=c.arguments),c.thisProgram&&(g=c.thisProgram),c.quit&&(A=c.quit);var X=Atomics.load,ee=Atomics.store,te=Atomics.compareExchange,ne;c.wasmBinary&&(ne=c.wasmBinary);var se=c.noExitRuntime||!0;typeof WebAssembly!="object"&&Ar("no native wasm support detected");var J,ie,le=!1,he;function Ae(N,F){N||Ar("Assertion failed: "+F)}function Ce(N){var F=c["_"+N];return Ae(F,"Cannot call unknown function "+N+", make sure it is exported"),F}function Te(N,F,B,K,me){var pe={string:function(fn){var bi=0;if(fn!=null&&fn!==0){var c5=(fn.length<<2)+1;bi=Ai(c5),nt(fn,bi,c5)}return bi},array:function(fn){var bi=Ai(fn.length);return et(fn,bi),bi}};function fe(fn){return F==="string"?Fe(fn):F==="boolean"?Boolean(fn):fn}var we=Ce(N),rt=[],Kt=0;if(K)for(var Vt=0;Vt=K);){var pe=N[F++];if(!pe)return me;if(!(pe&128)){me+=String.fromCharCode(pe);continue}var fe=N[F++]&63;if((pe&224)==192){me+=String.fromCharCode((pe&31)<<6|fe);continue}var we=N[F++]&63;if((pe&240)==224?pe=(pe&15)<<12|fe<<6|we:pe=(pe&7)<<18|fe<<12|we<<6|N[F++]&63,pe<65536)me+=String.fromCharCode(pe);else{var rt=pe-65536;me+=String.fromCharCode(55296|rt>>10,56320|rt&1023)}}return me}function Fe(N,F){return N?Me(o(),N,F):""}function ut(N,F,B,K){if(!(K>0))return 0;for(var me=B,pe=B+K-1,fe=0;fe=55296&&we<=57343){var rt=N.charCodeAt(++fe);we=65536+((we&1023)<<10)|rt&1023}if(we<=127){if(B>=pe)break;F[B++]=we}else if(we<=2047){if(B+1>=pe)break;F[B++]=192|we>>6,F[B++]=128|we&63}else if(we<=65535){if(B+2>=pe)break;F[B++]=224|we>>12,F[B++]=128|we>>6&63,F[B++]=128|we&63}else{if(B+3>=pe)break;F[B++]=240|we>>18,F[B++]=128|we>>12&63,F[B++]=128|we>>6&63,F[B++]=128|we&63}}return F[B]=0,B-me}function nt(N,F,B){return ut(N,o(),F,B)}function st(N){for(var F=0,B=0;B=55296&&K<=57343&&(K=65536+((K&1023)<<10)|N.charCodeAt(++B)&1023),K<=127?++F:K<=2047?F+=2:K<=65535?F+=3:F+=4}return F}function et(N,F){a().set(N,F)}function it(N,F){return N%F>0&&(N+=F-N%F),N}var He,Nn,St,Wn,nn,ks,pn,ts,ns;function sn(N){He=N,c.HEAP8=Nn=new Int8Array(N),c.HEAP16=Wn=new Int16Array(N),c.HEAP32=ks=new Int32Array(N),c.HEAPU8=St=new Uint8Array(N),c.HEAPU16=nn=new Uint16Array(N),c.HEAPU32=pn=new Uint32Array(N),c.HEAPF32=ts=new Float32Array(N),c.HEAPF64=ns=new Float64Array(N)}var ss=c.INITIAL_MEMORY||16777216;if(k)J=c.wasmMemory,He=c.buffer;else if(c.wasmMemory)J=c.wasmMemory;else if(J=new WebAssembly.Memory({initial:ss/65536,maximum:2147483648/65536,shared:!0}),!(J.buffer instanceof SharedArrayBuffer))throw q("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),b&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");J&&(He=J.buffer),ss=He.byteLength,sn(He);var rs,Vn=[],Ks=[],mr=[],Fr=[],ci=[],Zs=!1,vd=!1;k||Ks.push({func:function(){Pd()}});function o0(){if(!k){if(c.preRun)for(typeof c.preRun=="function"&&(c.preRun=[c.preRun]);c.preRun.length;)kd(c.preRun.shift());hi(Vn)}}function vu(){Zs=!0,!k&&hi(Ks)}function i0(){k||hi(mr)}function wd(){k||(vd=!0)}function En(){if(!k){if(c.postRun)for(typeof c.postRun=="function"&&(c.postRun=[c.postRun]);c.postRun.length;)l0(c.postRun.shift());hi(ci)}}function kd(N){Vn.unshift(N)}function l0(N){ci.unshift(N)}var gr=0,Or=null,wa=null;function u0(N){Ae(!k,"addRunDependency cannot be used in a pthread worker"),gr++,c.monitorRunDependencies&&c.monitorRunDependencies(gr)}function c0(N){if(gr--,c.monitorRunDependencies&&c.monitorRunDependencies(gr),gr==0&&(Or!==null&&(clearInterval(Or),Or=null),wa)){var F=wa;wa=null,F()}}c.preloadedImages={},c.preloadedAudios={};function Ar(N){c.onAbort&&c.onAbort(N),k&&console.error("Pthread aborting at "+new Error().stack),N+="",q(N),le=!0,he=1,N="abort("+N+"). Build with -s ASSERTIONS=1 for more info.";var F=new WebAssembly.RuntimeError(N);throw h(F),F}function Id(N,F){return String.prototype.startsWith?N.startsWith(F):N.indexOf(F)===0}var di="data:application/octet-stream;base64,";function Sd(N){return Id(N,di)}var d0="file://";function Cd(N){return Id(N,d0)}var Rn="tfjs-backend-wasm-threaded-simd.wasm";Sd(Rn)||(Rn=C(Rn));function Td(N){try{if(N==Rn&&ne)return new Uint8Array(ne);if(E)return E(N);throw"both async and sync fetching of the wasm failed"}catch(F){Ar(F)}}function h0(){if(!ne&&(y||x)){if(typeof fetch=="function"&&!Cd(Rn))return fetch(Rn,{credentials:"same-origin"}).then(function(N){if(!N.ok)throw"failed to load wasm binary file at '"+Rn+"'";return N.arrayBuffer()}).catch(function(){return Td(Rn)});if(O)return new Promise(function(N,F){O(Rn,function(B){N(new Uint8Array(B))},F)})}return Promise.resolve().then(function(){return Td(Rn)})}function p0(){var N={a:sm};function F(fe,we){var rt=fe.exports;if(c.asm=rt,rs=c.asm.F,ie=we,!k){var Kt=Se.unusedWorkers.length;Se.unusedWorkers.forEach(function(Vt){Se.loadWasmModuleToWorker(Vt,function(){--Kt||c0("wasm-instantiate")})})}}k||u0("wasm-instantiate");function B(fe){F(fe.instance,fe.module)}function K(fe){return h0().then(function(we){return WebAssembly.instantiate(we,N)}).then(fe,function(we){q("failed to asynchronously prepare wasm: "+we),Ar(we)})}function me(){return!ne&&typeof WebAssembly.instantiateStreaming=="function"&&!Sd(Rn)&&!Cd(Rn)&&typeof fetch=="function"?fetch(Rn,{credentials:"same-origin"}).then(function(fe){var we=WebAssembly.instantiateStreaming(fe,N);return we.then(B,function(rt){return q("wasm streaming compile failed: "+rt),q("falling back to ArrayBuffer instantiation"),K(B)})}):K(B)}if(c.instantiateWasm)try{var pe=c.instantiateWasm(N,F);return pe}catch(fe){return q("Module.instantiateWasm callback failed with error: "+fe),!1}return me().catch(h),{}}var f0={10024:function(){throw"Canceled!"},10042:function(N,F){setTimeout(function(){r5(N,F)},0)}};function Nd(){Se.initRuntime()}function hi(N){for(;N.length>0;){var F=N.shift();if(typeof F=="function"){F(c);continue}var B=F.func;typeof B=="number"?F.arg===void 0?rs.get(B)():rs.get(B)(F.arg):B(F.arg===void 0?null:F.arg)}}function wu(N,F){if(N<=0||N>a().length||N&!0||F<0)return-28;if(F==0)return 0;F>=2147483647&&(F=1/0);var B=Atomics.load(i(),yi>>2),K=0;if(B==N){var me=Atomics.compareExchange(i(),yi>>2,B,0);if(me==B&&(--F,K=1,F<=0))return 1}var pe=Atomics.notify(i(),N>>2,F);if(pe>=0)return pe+K;throw"Atomics.notify returned an unexpected value "+pe}c._emscripten_futex_wake=wu;function m0(N){if(k)throw"Internal Error! killThread() can only ever be called from main application thread!";if(!N)throw"Internal Error! Null pthread_ptr in killThread!";i()[N+12>>2]=0;var F=Se.pthreads[N];F.worker.terminate(),Se.freeThreadData(F),Se.runningWorkers.splice(Se.runningWorkers.indexOf(F.worker),1),F.worker.pthread=void 0}function g0(N){if(k)throw"Internal Error! cancelThread() can only ever be called from main application thread!";if(!N)throw"Internal Error! Null pthread_ptr in cancelThread!";var F=Se.pthreads[N];F.worker.postMessage({cmd:"cancel"})}function A0(N){if(k)throw"Internal Error! cleanupThread() can only ever be called from main application thread!";if(!N)throw"Internal Error! Null pthread_ptr in cleanupThread!";var F=Se.pthreads[N];if(F){i()[N+12>>2]=0;var B=F.worker;Se.returnWorkerToPool(B)}}var Se={unusedWorkers:[],runningWorkers:[],initMainThreadBlock:function(){for(var N=Math.min(4,Math.max(1,(navigator.hardwareConcurrency||1)/2)),F=0;F>2]=N;var B=N+152;i()[B>>2]=B;for(var K=Ia(512),F=0;F<128;++F)l()[K/4+F]=0;Atomics.store(l(),N+100>>2,K),Atomics.store(l(),N+40>>2,N),Rm(N,!x,1),s5(N)},initWorker:function(){},pthreads:{},threadExitHandlers:[],setThreadStatus:function(){},runExitHandlers:function(){for(;Se.threadExitHandlers.length>0;)Se.threadExitHandlers.pop()();k&&mi()&&n5()},runExitHandlersAndDeinitThread:function(N,F){Atomics.store(l(),N+56>>2,1),Atomics.store(l(),N+60>>2,0),Se.runExitHandlers(),Atomics.store(l(),N+4>>2,F),Atomics.store(l(),N+0>>2,1),wu(N+0,2147483647),Rm(0,0,0)},threadExit:function(N){var F=mi();F&&(Se.runExitHandlersAndDeinitThread(F,N),k&&postMessage({cmd:"exit"}))},threadCancel:function(){Se.runExitHandlersAndDeinitThread(mi(),-1),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var N in Se.pthreads){var F=Se.pthreads[N];F&&F.worker&&Se.returnWorkerToPool(F.worker)}Se.pthreads={};for(var B=0;B>2];i()[N.threadInfoStruct+100>>2]=0,Eu(F),Eu(N.threadInfoStruct)}N.threadInfoStruct=0,N.allocatedOwnStack&&N.stackBase&&Eu(N.stackBase),N.stackBase=0,N.worker&&(N.worker.pthread=null)}},returnWorkerToPool:function(N){Se.runWithoutMainThreadQueuedCalls(function(){delete Se.pthreads[N.pthread.threadInfoStruct],Se.unusedWorkers.push(N),Se.runningWorkers.splice(Se.runningWorkers.indexOf(N),1),Se.freeThreadData(N.pthread),N.pthread=void 0})},runWithoutMainThreadQueuedCalls:function(N){i()[u5>>2]=0;try{N()}finally{i()[u5>>2]=1}},receiveObjectTransfer:function(N){},loadWasmModuleToWorker:function(N,F){N.onmessage=function(B){var K=B.data,me=K.cmd;if(N.pthread&&(Se.currentProxiedOperationCallerThread=N.pthread.threadInfoStruct),K.targetThread&&K.targetThread!=mi()){var pe=Se.pthreads[K.targetThread];pe?pe.worker.postMessage(B.data,K.transferList):console.error('Internal error! Worker sent a message "'+me+'" to target pthread '+K.targetThread+", but that thread no longer exists!"),Se.currentProxiedOperationCallerThread=void 0;return}if(me==="processQueuedMainThreadWork")Nm();else if(me==="spawnThread")Fd(B.data);else if(me==="cleanupThread")A0(K.thread);else if(me==="killThread")m0(K.thread);else if(me==="cancelThread")g0(K.thread);else if(me==="loaded")N.loaded=!0,F&&F(N),N.runPthread&&(N.runPthread(),delete N.runPthread);else if(me==="print")j("Thread "+K.threadId+": "+K.text);else if(me==="printErr")q("Thread "+K.threadId+": "+K.text);else if(me==="alert")alert("Thread "+K.threadId+": "+K.text);else if(me==="exit"){var fe=N.pthread&&Atomics.load(l(),N.pthread.threadInfoStruct+64>>2);fe&&Se.returnWorkerToPool(N)}else if(me==="exitProcess")try{BI(K.returnCode)}catch(we){if(we instanceof _u)return;throw we}else me==="cancelDone"?Se.returnWorkerToPool(N):me==="objectTransfer"?Se.receiveObjectTransfer(B.data):B.data.target==="setimmediate"?N.postMessage(B.data):q("worker sent an unknown command "+me);Se.currentProxiedOperationCallerThread=void 0},N.onerror=function(B){q("pthread sent an error! "+B.filename+":"+B.lineno+": "+B.message)},b&&(N.on("message",function(B){N.onmessage({data:B})}),N.on("error",function(B){N.onerror(B)}),N.on("exit",function(B){})),N.postMessage({cmd:"load",urlOrBlob:c.mainScriptUrlOrBlob||s,wasmMemory:J,wasmModule:ie})},allocateUnusedWorker:function(){var N=C("tfjs-backend-wasm-threaded-simd.worker.js");Se.unusedWorkers.push(new Worker(N))},getNewWorker:function(){return Se.unusedWorkers.length==0&&(Se.allocateUnusedWorker(),Se.loadWasmModuleToWorker(Se.unusedWorkers[0])),Se.unusedWorkers.length>0?Se.unusedWorkers.pop():null},busySpinWait:function(N){for(var F=performance.now()+N;performance.now()>2]=N,N}function I0(N,F){if(k)return Pr(1,1,N,F)}function S0(N,F){if(N==F)postMessage({cmd:"processQueuedMainThreadWork"});else if(k)postMessage({targetThread:N,cmd:"processThreadQueue"});else{var B=Se.pthreads[N],K=B&&B.worker;if(!K)return;K.postMessage({cmd:"processThreadQueue"})}return 1}function C0(){Ar()}function T0(N,F,B){var K=D0(F,B);return f0[N].apply(null,K)}function N0(N,F){}function E0(N,F,B){if(N<=0||N>a().length||N&!0)return-28;if(y){if(Atomics.load(i(),N>>2)!=F)return-6;for(var me=performance.now(),pe=me+B,fe=Atomics.exchange(i(),yi>>2,N);;){if(me=performance.now(),me>pe)return fe=Atomics.exchange(i(),yi>>2,0),-73;if(fe=Atomics.exchange(i(),yi>>2,0),fe==0)break;if(Nm(),Atomics.load(i(),N>>2)!=F)return-6;fe=Atomics.exchange(i(),yi>>2,N)}return 0}else{var K=Atomics.wait(i(),N>>2,F,B);if(K==="timed-out")return-73;if(K==="not-equal")return-6;if(K==="ok")return 0;throw"Atomics.wait returned an unexpected value "+K}}function R0(N,F,B){o().copyWithin(N,F,F+B)}function _0(){return b?vi("os").cpus().length:navigator.hardwareConcurrency}function Pr(N,F){for(var B=arguments.length-2,K=Ru(),me=B,pe=Ai(me*8),fe=pe>>3,we=0;we>=2;B=o()[N++];){var K=B<105;K&&F&1&&F++,Iu.push(K?u()[F++>>1]:i()[F]),++F}return Iu}function $0(N,F,B){ku.length=F;for(var K=B>>3,me=0;me>>16),sn(J.buffer),1}catch(F){}}function P0(N){var F=F0();if(N<=F)return!1;var B=2147483648;if(N>B)return!1;for(var K=1;K<=4;K*=2){var me=F*(1+.2/K);me=Math.min(me,N+100663296);var pe=Math.min(B,it(Math.max(N,me),65536)),fe=O0(pe);if(fe)return!0}return!1}var Le={inEventHandler:0,removeAllEventListeners:function(){for(var N=Le.eventHandlers.length-1;N>=0;--N)Le._removeHandler(N);Le.eventHandlers=[],Le.deferredCalls=[]},registerRemoveEventListeners:function(){Le.removeEventListenersRegistered||(Fr.push(Le.removeAllEventListeners),Le.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(N,F,B){function K(fe,we){if(fe.length!=we.length)return!1;for(var rt in fe)if(fe[rt]!=we[rt])return!1;return!0}for(var me in Le.deferredCalls){var pe=Le.deferredCalls[me];if(pe.targetFunction==N&&K(pe.argsList,B))return}Le.deferredCalls.push({targetFunction:N,precedence:F,argsList:B}),Le.deferredCalls.sort(function(fe,we){return fe.precedence>2]=B,i()[fe+4>>2]=K,i()[fe+8>>2]=me,Em(0,N,637534208,F,K,fe),gi(pe)},getTargetThreadForEventCallback:function(N){switch(N){case 1:return 0;case 2:return Se.currentProxiedOperationCallerThread;default:return N}},getNodeNameForTarget:function(N){return N?N==window?"#window":N==screen?"#screen":N&&N.nodeName?N.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function M0(N){var F=st(N)+1,B=Ia(F);return nt(N,B,F),B}function z0(N,F,B,K){var me=Ru(),pe=Ai(12),fe=0;F&&(fe=M0(F)),i()[pe>>2]=fe,i()[pe+4>>2]=B,i()[pe+8>>2]=K,Em(0,N,657457152,0,fe,pe),gi(me)}function L0(N,F,B,K){F=F?Fe(F):"",z0(N,F,B,K)}function B0(N){return N>2?Fe(N):N}var W0=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function V0(N){N=B0(N);var F=W0[N]||(typeof document!="undefined"?document.querySelector(N):void 0);return F}function Su(N){return V0(N)}function Ed(N,F,B){var K=Su(N);if(!K)return-4;if(K.canvasSharedPtr&&(i()[K.canvasSharedPtr>>2]=F,i()[K.canvasSharedPtr+4>>2]=B),K.offscreenCanvas||!K.controlTransferredOffscreen){K.offscreenCanvas&&(K=K.offscreenCanvas);var me=!1;if(K.GLctxObject&&K.GLctxObject.GLctx){var pe=K.GLctxObject.GLctx.getParameter(2978);me=pe[0]===0&&pe[1]===0&&pe[2]===K.width&&pe[3]===K.height}K.width=F,K.height=B,me&&K.GLctxObject.GLctx.viewport(0,0,F,B)}else if(K.canvasSharedPtr){var fe=i()[K.canvasSharedPtr+8>>2];return L0(fe,N,F,B),1}else return-4;return 0}function Rd(N,F,B){return k?Pr(2,1,N,F,B):Ed(N,F,B)}function U0(N,F,B){var K=Su(N);return K?Ed(N,F,B):Rd(N,F,B)}function H0(N){}function G0(N,F){}function j0(N){var F=N.getExtension("ANGLE_instanced_arrays");if(F)return N.vertexAttribDivisor=function(B,K){F.vertexAttribDivisorANGLE(B,K)},N.drawArraysInstanced=function(B,K,me,pe){F.drawArraysInstancedANGLE(B,K,me,pe)},N.drawElementsInstanced=function(B,K,me,pe,fe){F.drawElementsInstancedANGLE(B,K,me,pe,fe)},1}function q0(N){var F=N.getExtension("OES_vertex_array_object");if(F)return N.createVertexArray=function(){return F.createVertexArrayOES()},N.deleteVertexArray=function(B){F.deleteVertexArrayOES(B)},N.bindVertexArray=function(B){F.bindVertexArrayOES(B)},N.isVertexArray=function(B){return F.isVertexArrayOES(B)},1}function X0(N){var F=N.getExtension("WEBGL_draw_buffers");if(F)return N.drawBuffers=function(B,K){F.drawBuffersWEBGL(B,K)},1}function K0(N){return!!(N.multiDrawWebgl=N.getExtension("WEBGL_multi_draw"))}var tt={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,recordError:function(F){tt.lastError||(tt.lastError=F)},getNewId:function(N){for(var F=tt.counter++,B=N.length;B>2]:-1;me+=Fe(i()[B+pe*4>>2],fe<0?void 0:fe)}return me},createContext:function(N,F){var B=N.getContext("webgl",F);if(!B)return 0;var K=tt.registerContext(B,F);return K},registerContext:function(N,F){var B=Ia(8);i()[B+4>>2]=mi();var K={handle:B,attributes:F,version:F.majorVersion,GLctx:N};return N.canvas&&(N.canvas.GLctxObject=K),tt.contexts[B]=K,(typeof F.enableExtensionsByDefault=="undefined"||F.enableExtensionsByDefault)&&tt.initExtensions(K),B},makeContextCurrent:function(N){return tt.currentContext=tt.contexts[N],c.ctx=Mr=tt.currentContext&&tt.currentContext.GLctx,!(N&&!Mr)},getContext:function(N){return tt.contexts[N]},deleteContext:function(N){tt.currentContext===tt.contexts[N]&&(tt.currentContext=null),typeof Le=="object"&&Le.removeAllHandlersOnTarget(tt.contexts[N].GLctx.canvas),tt.contexts[N]&&tt.contexts[N].GLctx.canvas&&(tt.contexts[N].GLctx.canvas.GLctxObject=void 0),Eu(tt.contexts[N].handle),tt.contexts[N]=null},initExtensions:function(N){if(N||(N=tt.currentContext),!N.initExtensionsDone){N.initExtensionsDone=!0;var F=N.GLctx;j0(F),q0(F),X0(F),F.disjointTimerQueryExt=F.getExtension("EXT_disjoint_timer_query"),K0(F);var B=F.getSupportedExtensions()||[];B.forEach(function(K){K.indexOf("lose_context")<0&&K.indexOf("debug")<0&&F.getExtension(K)})}},populateUniformTable:function(N){for(var F=tt.programs[N],B=tt.programInfos[N]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},K=B.uniforms,me=Mr.getProgramParameter(F,35718),pe=0;pe>2,K=i()[B+(24>>2)],me={alpha:!!i()[B+(0>>2)],depth:!!i()[B+(4>>2)],stencil:!!i()[B+(8>>2)],antialias:!!i()[B+(12>>2)],premultipliedAlpha:!!i()[B+(16>>2)],preserveDrawingBuffer:!!i()[B+(20>>2)],powerPreference:Z0[K],failIfMajorPerformanceCaveat:!!i()[B+(28>>2)],majorVersion:i()[B+(32>>2)],minorVersion:i()[B+(36>>2)],enableExtensionsByDefault:i()[B+(40>>2)],explicitSwapControl:i()[B+(44>>2)],proxyContextToMainThread:i()[B+(48>>2)],renderViaOffscreenBackBuffer:i()[B+(52>>2)]},pe=Su(N);if(!pe||me.explicitSwapControl)return 0;var fe=tt.createContext(pe,me);return fe}function J0(N,F){return Y0(N,F)}var pi={mappings:{},buffers:[null,[],[]],printChar:function(N,F){var B=pi.buffers[N];F===0||F===10?((N===1?j:q)(Me(B,0)),B.length=0):B.push(F)},varargs:void 0,get:function(){pi.varargs+=4;var N=i()[pi.varargs-4>>2];return N},getStr:function(N){var F=Fe(N);return F},get64:function(N,F){return N}};function _d(N){return k?Pr(3,1,N):0}function Dd(N,F,B,K,me){if(k)return Pr(4,1,N,F,B,K,me)}function $d(N,F,B,K){if(k)return Pr(5,1,N,F,B,K);for(var me=0,pe=0;pe>2],we=i()[F+(pe*8+4)>>2],rt=0;rt>2]=me,0}function Q0(N){var F=Se.threadExitHandlers.pop();N&&F()}function em(N,F){Se.threadExitHandlers.push(function(){rs.get(N)(F)})}function Fd(N){if(k)throw"Internal Error! spawnThread() can only ever be called from main application thread!";var F=Se.getNewWorker();if(F.pthread!==void 0)throw"Internal error!";if(!N.pthread_ptr)throw"Internal error, no pthread ptr!";Se.runningWorkers.push(F);for(var B=Ia(128*4),K=0;K<128;++K)i()[B+K*4>>2]=0;var me=N.stackBase+N.stackSize,pe=Se.pthreads[N.pthread_ptr]={worker:F,stackBase:N.stackBase,stackSize:N.stackSize,allocatedOwnStack:N.allocatedOwnStack,threadInfoStruct:N.pthread_ptr},fe=pe.threadInfoStruct>>2;Atomics.store(l(),fe+(64>>2),N.detached),Atomics.store(l(),fe+(100>>2),B),Atomics.store(l(),fe+(40>>2),pe.threadInfoStruct),Atomics.store(l(),fe+(80>>2),N.stackSize),Atomics.store(l(),fe+(76>>2),me),Atomics.store(l(),fe+(104>>2),N.stackSize),Atomics.store(l(),fe+(104+8>>2),me),Atomics.store(l(),fe+(104+12>>2),N.detached);var we=t5(),rt=we+40;Atomics.store(l(),fe+(172>>2),rt),F.pthread=pe;var Kt={cmd:"run",start_routine:N.startRoutine,arg:N.arg,threadInfoStruct:N.pthread_ptr,stackBase:N.stackBase,stackSize:N.stackSize};F.runPthread=function(){Kt.time=performance.now(),F.postMessage(Kt,N.transferList)},F.loaded&&(F.runPthread(),delete F.runPthread)}function tm(N,F,B,K){if(typeof SharedArrayBuffer=="undefined")return q("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;if(!N)return q("pthread_create called with a null thread pointer!"),28;var me=[],pe=0;if(k&&(me.length===0||pe))return a5(687865856,N,F,B,K);if(pe)return pe;var fe=0,we=0,rt=0;F&&F!=-1?(fe=i()[F>>2],fe+=81920,we=i()[F+8>>2],rt=i()[F+12>>2]!==0):fe=2097152;var Kt=we==0;Kt?we=l5(16,fe):(we-=fe,Ae(we>0));for(var Vt=Ia(228),Lr=0;Lr<228>>2;++Lr)l()[(Vt>>2)+Lr]=0;i()[N>>2]=Vt,i()[Vt+12>>2]=Vt;var xi=Vt+152;i()[xi>>2]=xi;var fn={stackBase:we,stackSize:fe,allocatedOwnStack:Kt,detached:rt,startRoutine:B,pthread_ptr:Vt,arg:K,transferList:me};return k?(fn.cmd="spawnThread",postMessage(fn,me)):Fd(fn),0}function Od(N){if(k)return Pr(6,1,N);switch(N){case 30:return 16384;case 85:var F=2147483648;return F/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 k0(28),-1}k||Se.initMainThreadBlock();var Mr,nm=[null,I0,Rd,_d,Dd,$d,Od],sm={e:v0,r:w0,x:S0,b:C0,y:T0,j:N0,c:E0,d:wu,f:ka,p:R0,z:_0,u:$0,q:P0,v:U0,i:H0,t:G0,w:J0,m:_d,n:Dd,g:$d,o:Nd,a:J||c.wasmMemory,k:Q0,l:em,h:tm,s:Od},Qy=p0(),Pd=c.___wasm_call_ctors=function(){return(Pd=c.___wasm_call_ctors=c.asm.A).apply(null,arguments)},rm=c._init=function(){return(rm=c._init=c.asm.B).apply(null,arguments)},am=c._register_tensor=function(){return(am=c._register_tensor=c.asm.C).apply(null,arguments)},om=c._dispose_data=function(){return(om=c._dispose_data=c.asm.D).apply(null,arguments)},im=c._dispose=function(){return(im=c._dispose=c.asm.E).apply(null,arguments)},lm=c._Abs=function(){return(lm=c._Abs=c.asm.G).apply(null,arguments)},um=c._Add=function(){return(um=c._Add=c.asm.H).apply(null,arguments)},cm=c._AddN=function(){return(cm=c._AddN=c.asm.I).apply(null,arguments)},dm=c._All=function(){return(dm=c._All=c.asm.J).apply(null,arguments)},hm=c._Any=function(){return(hm=c._Any=c.asm.K).apply(null,arguments)},pm=c._ArgMax=function(){return(pm=c._ArgMax=c.asm.L).apply(null,arguments)},fm=c._AvgPool=function(){return(fm=c._AvgPool=c.asm.M).apply(null,arguments)},mm=c._BatchMatMul=function(){return(mm=c._BatchMatMul=c.asm.N).apply(null,arguments)},gm=c._Ceil=function(){return(gm=c._Ceil=c.asm.O).apply(null,arguments)},Am=c._ClipByValue=function(){return(Am=c._ClipByValue=c.asm.P).apply(null,arguments)},ym=c._Conv2D=function(){return(ym=c._Conv2D=c.asm.Q).apply(null,arguments)},xm=c._Conv2DBackpropInput=function(){return(xm=c._Conv2DBackpropInput=c.asm.R).apply(null,arguments)},bm=c._Cos=function(){return(bm=c._Cos=c.asm.S).apply(null,arguments)},vm=c._Cosh=function(){return(vm=c._Cosh=c.asm.T).apply(null,arguments)},wm=c._CropAndResize=function(){return(wm=c._CropAndResize=c.asm.U).apply(null,arguments)},km=c._Cumsum=function(){return(km=c._Cumsum=c.asm.V).apply(null,arguments)},Im=c._DepthToSpace=function(){return(Im=c._DepthToSpace=c.asm.W).apply(null,arguments)},Sm=c._DepthwiseConv2dNative=function(){return(Sm=c._DepthwiseConv2dNative=c.asm.X).apply(null,arguments)},Cm=c._Elu=function(){return(Cm=c._Elu=c.asm.Y).apply(null,arguments)},Md=c._Equal=function(){return(Md=c._Equal=c.asm.Z).apply(null,arguments)},zd=c._Exp=function(){return(zd=c._Exp=c.asm._).apply(null,arguments)},Ld=c._FlipLeftRight=function(){return(Ld=c._FlipLeftRight=c.asm.$).apply(null,arguments)},Cu=c._Floor=function(){return(Cu=c._Floor=c.asm.aa).apply(null,arguments)},fi=c._FloorDiv=function(){return(fi=c._FloorDiv=c.asm.ba).apply(null,arguments)},Tm=c._FusedBatchNorm=function(){return(Tm=c._FusedBatchNorm=c.asm.ca).apply(null,arguments)},Tu=c._FusedConv2D=function(){return(Tu=c._FusedConv2D=c.asm.da).apply(null,arguments)},Y=c._FusedDepthwiseConv2D=function(){return(Y=c._FusedDepthwiseConv2D=c.asm.ea).apply(null,arguments)},re=c._Gather=function(){return(re=c._Gather=c.asm.fa).apply(null,arguments)},xe=c._GatherNd=function(){return(xe=c._GatherNd=c.asm.ga).apply(null,arguments)},Qe=c._Greater=function(){return(Qe=c._Greater=c.asm.ha).apply(null,arguments)},Et=c._GreaterEqual=function(){return(Et=c._GreaterEqual=c.asm.ia).apply(null,arguments)},bt=c._LeakyRelu=function(){return(bt=c._LeakyRelu=c.asm.ja).apply(null,arguments)},je=c._Less=function(){return(je=c._Less=c.asm.ka).apply(null,arguments)},qe=c._LessEqual=function(){return(qe=c._LessEqual=c.asm.la).apply(null,arguments)},rn=c._Log=function(){return(rn=c._Log=c.asm.ma).apply(null,arguments)},yr=c._LogicalAnd=function(){return(yr=c._LogicalAnd=c.asm.na).apply(null,arguments)},xr=c._Max=function(){return(xr=c._Max=c.asm.oa).apply(null,arguments)},Bd=c._MaxPool=function(){return(Bd=c._MaxPool=c.asm.pa).apply(null,arguments)},Nu=c._Maximum=function(){return(Nu=c._Maximum=c.asm.qa).apply(null,arguments)},Un=c._Mean=function(){return(Un=c._Mean=c.asm.ra).apply(null,arguments)},zr=c._Min=function(){return(zr=c._Min=c.asm.sa).apply(null,arguments)},Wd=c._Minimum=function(){return(Wd=c._Minimum=c.asm.ta).apply(null,arguments)},Q8=c._MirrorPad=function(){return(Q8=c._MirrorPad=c.asm.ua).apply(null,arguments)},eI=c._Multiply=function(){return(eI=c._Multiply=c.asm.va).apply(null,arguments)},tI=c._Neg=function(){return(tI=c._Neg=c.asm.wa).apply(null,arguments)},nI=c._NonMaxSuppressionV3=function(){return(nI=c._NonMaxSuppressionV3=c.asm.xa).apply(null,arguments)},sI=c._NonMaxSuppressionV4=function(){return(sI=c._NonMaxSuppressionV4=c.asm.ya).apply(null,arguments)},rI=c._NonMaxSuppressionV5=function(){return(rI=c._NonMaxSuppressionV5=c.asm.za).apply(null,arguments)},aI=c._NotEqual=function(){return(aI=c._NotEqual=c.asm.Aa).apply(null,arguments)},oI=c._OneHot=function(){return(oI=c._OneHot=c.asm.Ba).apply(null,arguments)},iI=c._PadV2=function(){return(iI=c._PadV2=c.asm.Ca).apply(null,arguments)},lI=c._Pow=function(){return(lI=c._Pow=c.asm.Da).apply(null,arguments)},uI=c._Prelu=function(){return(uI=c._Prelu=c.asm.Ea).apply(null,arguments)},cI=c._Prod=function(){return(cI=c._Prod=c.asm.Fa).apply(null,arguments)},dI=c._RealDiv=function(){return(dI=c._RealDiv=c.asm.Ga).apply(null,arguments)},hI=c._Relu=function(){return(hI=c._Relu=c.asm.Ha).apply(null,arguments)},pI=c._Relu6=function(){return(pI=c._Relu6=c.asm.Ia).apply(null,arguments)},fI=c._ResizeBilinear=function(){return(fI=c._ResizeBilinear=c.asm.Ja).apply(null,arguments)},mI=c._Reverse=function(){return(mI=c._Reverse=c.asm.Ka).apply(null,arguments)},gI=c._RotateWithOffset=function(){return(gI=c._RotateWithOffset=c.asm.La).apply(null,arguments)},AI=c._Round=function(){return(AI=c._Round=c.asm.Ma).apply(null,arguments)},yI=c._Rsqrt=function(){return(yI=c._Rsqrt=c.asm.Na).apply(null,arguments)},xI=c._ScatterNd=function(){return(xI=c._ScatterNd=c.asm.Oa).apply(null,arguments)},bI=c._SelectV2=function(){return(bI=c._SelectV2=c.asm.Pa).apply(null,arguments)},vI=c._Sigmoid=function(){return(vI=c._Sigmoid=c.asm.Qa).apply(null,arguments)},wI=c._Sin=function(){return(wI=c._Sin=c.asm.Ra).apply(null,arguments)},kI=c._Softmax=function(){return(kI=c._Softmax=c.asm.Sa).apply(null,arguments)},II=c._Sqrt=function(){return(II=c._Sqrt=c.asm.Ta).apply(null,arguments)},SI=c._Square=function(){return(SI=c._Square=c.asm.Ua).apply(null,arguments)},CI=c._SquaredDifference=function(){return(CI=c._SquaredDifference=c.asm.Va).apply(null,arguments)},TI=c._Step=function(){return(TI=c._Step=c.asm.Wa).apply(null,arguments)},NI=c._StridedSlice=function(){return(NI=c._StridedSlice=c.asm.Xa).apply(null,arguments)},EI=c._Sub=function(){return(EI=c._Sub=c.asm.Ya).apply(null,arguments)},RI=c._Sum=function(){return(RI=c._Sum=c.asm.Za).apply(null,arguments)},_I=c._Tan=function(){return(_I=c._Tan=c.asm._a).apply(null,arguments)},DI=c._Tanh=function(){return(DI=c._Tanh=c.asm.$a).apply(null,arguments)},$I=c._Tile=function(){return($I=c._Tile=c.asm.ab).apply(null,arguments)},FI=c._TopK=function(){return(FI=c._TopK=c.asm.bb).apply(null,arguments)},OI=c._Transform=function(){return(OI=c._Transform=c.asm.cb).apply(null,arguments)},PI=c._Transpose=function(){return(PI=c._Transpose=c.asm.db).apply(null,arguments)},MI=c.__FusedMatMul=function(){return(MI=c.__FusedMatMul=c.asm.eb).apply(null,arguments)},Ia=c._malloc=function(){return(Ia=c._malloc=c.asm.fb).apply(null,arguments)},Eu=c._free=function(){return(Eu=c._free=c.asm.gb).apply(null,arguments)},e5=c.___errno_location=function(){return(e5=c.___errno_location=c.asm.hb).apply(null,arguments)},t5=c._emscripten_get_global_libc=function(){return(t5=c._emscripten_get_global_libc=c.asm.ib).apply(null,arguments)},mi=c._pthread_self=function(){return(mi=c._pthread_self=c.asm.jb).apply(null,arguments)},n5=c.___pthread_tsd_run_dtors=function(){return(n5=c.___pthread_tsd_run_dtors=c.asm.kb).apply(null,arguments)},Nm=c._emscripten_main_thread_process_queued_calls=function(){return(Nm=c._emscripten_main_thread_process_queued_calls=c.asm.lb).apply(null,arguments)},zI=c._emscripten_current_thread_process_queued_calls=function(){return(zI=c._emscripten_current_thread_process_queued_calls=c.asm.mb).apply(null,arguments)},s5=c._emscripten_register_main_browser_thread_id=function(){return(s5=c._emscripten_register_main_browser_thread_id=c.asm.nb).apply(null,arguments)},r5=c.__emscripten_do_dispatch_to_thread=function(){return(r5=c.__emscripten_do_dispatch_to_thread=c.asm.ob).apply(null,arguments)},a5=c._emscripten_sync_run_in_main_thread_4=function(){return(a5=c._emscripten_sync_run_in_main_thread_4=c.asm.pb).apply(null,arguments)},o5=c._emscripten_run_in_main_runtime_thread_js=function(){return(o5=c._emscripten_run_in_main_runtime_thread_js=c.asm.qb).apply(null,arguments)},Em=c.__emscripten_call_on_thread=function(){return(Em=c.__emscripten_call_on_thread=c.asm.rb).apply(null,arguments)},LI=c._emscripten_tls_init=function(){return(LI=c._emscripten_tls_init=c.asm.sb).apply(null,arguments)},Rm=c.__emscripten_thread_init=function(){return(Rm=c.__emscripten_thread_init=c.asm.tb).apply(null,arguments)},Ru=c.stackSave=function(){return(Ru=c.stackSave=c.asm.ub).apply(null,arguments)},gi=c.stackRestore=function(){return(gi=c.stackRestore=c.asm.vb).apply(null,arguments)},Ai=c.stackAlloc=function(){return(Ai=c.stackAlloc=c.asm.wb).apply(null,arguments)},i5=c._emscripten_stack_set_limits=function(){return(i5=c._emscripten_stack_set_limits=c.asm.xb).apply(null,arguments)},l5=c._memalign=function(){return(l5=c._memalign=c.asm.yb).apply(null,arguments)},u5=c.__emscripten_allow_main_runtime_queued_calls=10016,yi=c.__emscripten_main_thread_futex=11652;c.cwrap=De,c.PThread=Se,c.PThread=Se,c.wasmMemory=J,c.ExitStatus=_u;var Vd;function _u(N){this.name="ExitStatus",this.message="Program terminated with exit("+N+")",this.status=N}wa=function N(){Vd||_m(),Vd||(wa=N)};function _m(N){if(N=N||m,gr>0)return;if(k){d(c),vu(),postMessage({cmd:"loaded"});return}if(o0(),gr>0)return;function F(){Vd||(Vd=!0,c.calledRun=!0,!le&&(vu(),i0(),d(c),c.onRuntimeInitialized&&c.onRuntimeInitialized(),En()))}c.setStatus?(c.setStatus("Running..."),setTimeout(function(){setTimeout(function(){c.setStatus("")},1),F()},1)):F()}c.run=_m;function BI(N,F){if(!(F&&se&&N===0)){if(!F&&k)throw postMessage({cmd:"exitProcess",returnCode:N}),new _u(N);se||(Se.terminateAllThreads(),he=N,wd(),c.onExit&&c.onExit(N),le=!0),A(N,new _u(N))}}if(c.preInit)for(typeof c.preInit=="function"&&(c.preInit=[c.preInit]);c.preInit.length>0;)c.preInit.pop()();return k&&(se=!1,Se.initWorker()),_m(),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)}}),pS=vt({"node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.9.0_@tensorflow+tfjs-core@3.9.0/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js"(e,t){var n=function(){var s=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(s=s||__filename),function(r){r=r||{};var a=typeof r!="undefined"?r:{},o,i;a.ready=new Promise(function(Y,re){o=Y,i=re});var l={},u;for(u in a)a.hasOwnProperty(u)&&(l[u]=a[u]);var c=[],d="./this.program",h=function(Y,re){throw re},p=!1,f=!1,m=!1,g=!1;p=typeof window=="object",f=typeof importScripts=="function",m=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g=!p&&!m&&!f;var A="";function y(Y){return a.locateFile?a.locateFile(Y,A):A+Y}var x,b,v,k,S,C;m?(f?A=Du().dirname(A)+"/":A=__dirname+"/",x=function(re,xe){return S||(S=vi("fs")),C||(C=Du()),re=C.normalize(re),S.readFileSync(re,xe?null:"utf8")},v=function(re){var xe=x(re,!0);return xe.buffer||(xe=new Uint8Array(xe)),j(xe.buffer),xe},process.argv.length>1&&(d=process.argv[1].replace(/\\/g,"/")),c=process.argv.slice(2),process.on("uncaughtException",function(Y){if(!(Y instanceof Tm))throw Y}),process.on("unhandledRejection",Zs),h=function(Y){process.exit(Y)},a.inspect=function(){return"[Emscripten Module object]"}):g?(typeof read!="undefined"&&(x=function(re){return read(re)}),v=function(re){var xe;return typeof readbuffer=="function"?new Uint8Array(readbuffer(re)):(xe=read(re,"binary"),j(typeof xe=="object"),xe)},typeof scriptArgs!="undefined"?c=scriptArgs:typeof arguments!="undefined"&&(c=arguments),typeof quit=="function"&&(h=function(Y){quit(Y)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(p||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(Y){var re=new XMLHttpRequest;return re.open("GET",Y,!1),re.send(null),re.responseText},f&&(v=function(Y){var re=new XMLHttpRequest;return re.open("GET",Y,!1),re.responseType="arraybuffer",re.send(null),new Uint8Array(re.response)}),b=function(Y,re,xe){var Qe=new XMLHttpRequest;Qe.open("GET",Y,!0),Qe.responseType="arraybuffer",Qe.onload=function(){if(Qe.status==200||Qe.status==0&&Qe.response){re(Qe.response);return}xe()},Qe.onerror=xe,Qe.send(null)},k=function(Y){document.title=Y});var _=a.print||console.log.bind(console),O=a.printErr||console.warn.bind(console);for(u in l)l.hasOwnProperty(u)&&(a[u]=l[u]);l=null,a.arguments&&(c=a.arguments),a.thisProgram&&(d=a.thisProgram),a.quit&&(h=a.quit);var E;a.wasmBinary&&(E=a.wasmBinary);var R=a.noExitRuntime||!0;typeof WebAssembly!="object"&&Zs("no native wasm support detected");var T,P=!1,V;function j(Y,re){Y||Zs("Assertion failed: "+re)}function q(Y){var re=a["_"+Y];return j(re,"Cannot call unknown function "+Y+", make sure it is exported"),re}function X(Y,re,xe,Qe,Et){var bt={string:function(Un){var zr=0;if(Un!=null&&Un!==0){var Wd=(Un.length<<2)+1;zr=Cu(Wd),ie(Un,zr,Wd)}return zr},array:function(Un){var zr=Cu(Un.length);return le(Un,zr),zr}};function je(Un){return re==="string"?se(Un):re==="boolean"?Boolean(Un):Un}var qe=q(Y),rn=[],yr=0;if(Qe)for(var xr=0;xr=Qe);)++Et;if(Et-re>16&&Y.subarray&&te)return te.decode(Y.subarray(re,Et));for(var bt="";re>10,56320|yr&1023)}}return bt}function se(Y,re){return Y?ne(Te,Y,re):""}function J(Y,re,xe,Qe){if(!(Qe>0))return 0;for(var Et=xe,bt=xe+Qe-1,je=0;je=55296&&qe<=57343){var rn=Y.charCodeAt(++je);qe=65536+((qe&1023)<<10)|rn&1023}if(qe<=127){if(xe>=bt)break;re[xe++]=qe}else if(qe<=2047){if(xe+1>=bt)break;re[xe++]=192|qe>>6,re[xe++]=128|qe&63}else if(qe<=65535){if(xe+2>=bt)break;re[xe++]=224|qe>>12,re[xe++]=128|qe>>6&63,re[xe++]=128|qe&63}else{if(xe+3>=bt)break;re[xe++]=240|qe>>18,re[xe++]=128|qe>>12&63,re[xe++]=128|qe>>6&63,re[xe++]=128|qe&63}}return re[xe]=0,xe-Et}function ie(Y,re,xe){return J(Y,Te,re,xe)}function le(Y,re){Ce.set(Y,re)}function he(Y,re){return Y%re>0&&(Y+=re-Y%re),Y}var Ae,Ce,Te,De,Me,Fe,ut,nt,st;function et(Y){Ae=Y,a.HEAP8=Ce=new Int8Array(Y),a.HEAP16=De=new Int16Array(Y),a.HEAP32=Fe=new Int32Array(Y),a.HEAPU8=Te=new Uint8Array(Y),a.HEAPU16=Me=new Uint16Array(Y),a.HEAPU32=ut=new Uint32Array(Y),a.HEAPF32=nt=new Float32Array(Y),a.HEAPF64=st=new Float64Array(Y)}var it=a.INITIAL_MEMORY||16777216,He,Nn=[],St=[],Wn=[],nn=[],ks=!1;St.push({func:function(){Nd()}});function pn(){if(a.preRun)for(typeof a.preRun=="function"&&(a.preRun=[a.preRun]);a.preRun.length;)ss(a.preRun.shift());Or(Nn)}function ts(){ks=!0,Or(St)}function ns(){Or(Wn)}function sn(){if(a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;)rs(a.postRun.shift());Or(nn)}function ss(Y){Nn.unshift(Y)}function rs(Y){nn.unshift(Y)}var Vn=0,Ks=null,mr=null;function Fr(Y){Vn++,a.monitorRunDependencies&&a.monitorRunDependencies(Vn)}function ci(Y){if(Vn--,a.monitorRunDependencies&&a.monitorRunDependencies(Vn),Vn==0&&(Ks!==null&&(clearInterval(Ks),Ks=null),mr)){var re=mr;mr=null,re()}}a.preloadedImages={},a.preloadedAudios={};function Zs(Y){a.onAbort&&a.onAbort(Y),Y+="",O(Y),P=!0,V=1,Y="abort("+Y+"). Build with -s ASSERTIONS=1 for more info.";var re=new WebAssembly.RuntimeError(Y);throw i(re),re}function vd(Y,re){return String.prototype.startsWith?Y.startsWith(re):Y.indexOf(re)===0}var o0="data:application/octet-stream;base64,";function vu(Y){return vd(Y,o0)}var i0="file://";function wd(Y){return vd(Y,i0)}var En="tfjs-backend-wasm.wasm";vu(En)||(En=y(En));function kd(Y){try{if(Y==En&&E)return new Uint8Array(E);if(v)return v(Y);throw"both async and sync fetching of the wasm failed"}catch(re){Zs(re)}}function l0(){if(!E&&(p||f)){if(typeof fetch=="function"&&!wd(En))return fetch(En,{credentials:"same-origin"}).then(function(Y){if(!Y.ok)throw"failed to load wasm binary file at '"+En+"'";return Y.arrayBuffer()}).catch(function(){return kd(En)});if(b)return new Promise(function(Y,re){b(En,function(xe){Y(new Uint8Array(xe))},re)})}return Promise.resolve().then(function(){return kd(En)})}function gr(){var Y={a:p0};function re(je,qe){var rn=je.exports;a.asm=rn,T=a.asm.i,et(T.buffer),He=a.asm.o,ci("wasm-instantiate")}Fr("wasm-instantiate");function xe(je){re(je.instance)}function Qe(je){return l0().then(function(qe){return WebAssembly.instantiate(qe,Y)}).then(je,function(qe){O("failed to asynchronously prepare wasm: "+qe),Zs(qe)})}function Et(){return!E&&typeof WebAssembly.instantiateStreaming=="function"&&!vu(En)&&!wd(En)&&typeof fetch=="function"?fetch(En,{credentials:"same-origin"}).then(function(je){var qe=WebAssembly.instantiateStreaming(je,Y);return qe.then(xe,function(rn){return O("wasm streaming compile failed: "+rn),O("falling back to ArrayBuffer instantiation"),Qe(xe)})}):Qe(xe)}if(a.instantiateWasm)try{var bt=a.instantiateWasm(Y,re);return bt}catch(je){return O("Module.instantiateWasm callback failed with error: "+je),!1}return Et().catch(i),{}}function Or(Y){for(;Y.length>0;){var re=Y.shift();if(typeof re=="function"){re(a);continue}var xe=re.func;typeof xe=="number"?re.arg===void 0?He.get(xe)():He.get(xe)(re.arg):xe(re.arg===void 0?null:re.arg)}}function wa(){Zs()}function u0(Y,re,xe){Te.copyWithin(Y,re,re+xe)}function c0(){return Te.length}function Ar(Y){try{return T.grow(Y-Ae.byteLength+65535>>>16),et(T.buffer),1}catch(re){}}function Id(Y){var re=c0(),xe=2147483648;if(Y>xe)return!1;for(var Qe=1;Qe<=4;Qe*=2){var Et=re*(1+.2/Qe);Et=Math.min(Et,Y+100663296);var bt=Math.min(xe,he(Math.max(Y,Et),65536)),je=Ar(bt);if(je)return!0}return!1}var di={mappings:{},buffers:[null,[],[]],printChar:function(Y,re){var xe=di.buffers[Y];re===0||re===10?((Y===1?_:O)(ne(xe,0)),xe.length=0):xe.push(re)},varargs:void 0,get:function(){di.varargs+=4;var Y=Fe[di.varargs-4>>2];return Y},getStr:function(Y){var re=se(Y);return re},get64:function(Y,re){return Y}};function Sd(Y){return 0}function d0(Y,re,xe,Qe,Et){}function Cd(Y,re,xe,Qe){for(var Et=0,bt=0;bt>2],qe=Fe[re+(bt*8+4)>>2],rn=0;rn>2]=Et,0}function Rn(){return 6}function Td(Y){return Fe[Md()>>2]=Y,Y}function h0(Y){switch(Y){case 30:return 16384;case 85:var re=2147483648;return re/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 Td(28),-1}var p0={a:wa,d:u0,e:Id,f:Sd,c:d0,b:Cd,g:Rn,h:h0},f0=gr(),Nd=a.___wasm_call_ctors=function(){return(Nd=a.___wasm_call_ctors=a.asm.j).apply(null,arguments)},hi=a._init=function(){return(hi=a._init=a.asm.k).apply(null,arguments)},wu=a._register_tensor=function(){return(wu=a._register_tensor=a.asm.l).apply(null,arguments)},m0=a._dispose_data=function(){return(m0=a._dispose_data=a.asm.m).apply(null,arguments)},g0=a._dispose=function(){return(g0=a._dispose=a.asm.n).apply(null,arguments)},A0=a._Abs=function(){return(A0=a._Abs=a.asm.p).apply(null,arguments)},Se=a._Add=function(){return(Se=a._Add=a.asm.q).apply(null,arguments)},y0=a._AddN=function(){return(y0=a._AddN=a.asm.r).apply(null,arguments)},x0=a._All=function(){return(x0=a._All=a.asm.s).apply(null,arguments)},b0=a._Any=function(){return(b0=a._Any=a.asm.t).apply(null,arguments)},v0=a._ArgMax=function(){return(v0=a._ArgMax=a.asm.u).apply(null,arguments)},w0=a._AvgPool=function(){return(w0=a._AvgPool=a.asm.v).apply(null,arguments)},ka=a._BatchMatMul=function(){return(ka=a._BatchMatMul=a.asm.w).apply(null,arguments)},k0=a._Ceil=function(){return(k0=a._Ceil=a.asm.x).apply(null,arguments)},I0=a._ClipByValue=function(){return(I0=a._ClipByValue=a.asm.y).apply(null,arguments)},S0=a._Conv2D=function(){return(S0=a._Conv2D=a.asm.z).apply(null,arguments)},C0=a._Conv2DBackpropInput=function(){return(C0=a._Conv2DBackpropInput=a.asm.A).apply(null,arguments)},T0=a._Cos=function(){return(T0=a._Cos=a.asm.B).apply(null,arguments)},N0=a._Cosh=function(){return(N0=a._Cosh=a.asm.C).apply(null,arguments)},E0=a._CropAndResize=function(){return(E0=a._CropAndResize=a.asm.D).apply(null,arguments)},R0=a._Cumsum=function(){return(R0=a._Cumsum=a.asm.E).apply(null,arguments)},_0=a._DepthToSpace=function(){return(_0=a._DepthToSpace=a.asm.F).apply(null,arguments)},Pr=a._DepthwiseConv2dNative=function(){return(Pr=a._DepthwiseConv2dNative=a.asm.G).apply(null,arguments)},ku=a._Elu=function(){return(ku=a._Elu=a.asm.H).apply(null,arguments)},Iu=a._Equal=function(){return(Iu=a._Equal=a.asm.I).apply(null,arguments)},D0=a._Exp=function(){return(D0=a._Exp=a.asm.J).apply(null,arguments)},$0=a._FlipLeftRight=function(){return($0=a._FlipLeftRight=a.asm.K).apply(null,arguments)},F0=a._Floor=function(){return(F0=a._Floor=a.asm.L).apply(null,arguments)},O0=a._FloorDiv=function(){return(O0=a._FloorDiv=a.asm.M).apply(null,arguments)},P0=a._FusedBatchNorm=function(){return(P0=a._FusedBatchNorm=a.asm.N).apply(null,arguments)},Le=a._FusedConv2D=function(){return(Le=a._FusedConv2D=a.asm.O).apply(null,arguments)},M0=a._FusedDepthwiseConv2D=function(){return(M0=a._FusedDepthwiseConv2D=a.asm.P).apply(null,arguments)},z0=a._Gather=function(){return(z0=a._Gather=a.asm.Q).apply(null,arguments)},L0=a._GatherNd=function(){return(L0=a._GatherNd=a.asm.R).apply(null,arguments)},B0=a._Greater=function(){return(B0=a._Greater=a.asm.S).apply(null,arguments)},W0=a._GreaterEqual=function(){return(W0=a._GreaterEqual=a.asm.T).apply(null,arguments)},V0=a._LeakyRelu=function(){return(V0=a._LeakyRelu=a.asm.U).apply(null,arguments)},Su=a._Less=function(){return(Su=a._Less=a.asm.V).apply(null,arguments)},Ed=a._LessEqual=function(){return(Ed=a._LessEqual=a.asm.W).apply(null,arguments)},Rd=a._Log=function(){return(Rd=a._Log=a.asm.X).apply(null,arguments)},U0=a._LogicalAnd=function(){return(U0=a._LogicalAnd=a.asm.Y).apply(null,arguments)},H0=a._Max=function(){return(H0=a._Max=a.asm.Z).apply(null,arguments)},G0=a._MaxPool=function(){return(G0=a._MaxPool=a.asm._).apply(null,arguments)},j0=a._Maximum=function(){return(j0=a._Maximum=a.asm.$).apply(null,arguments)},q0=a._Mean=function(){return(q0=a._Mean=a.asm.aa).apply(null,arguments)},X0=a._Min=function(){return(X0=a._Min=a.asm.ba).apply(null,arguments)},K0=a._Minimum=function(){return(K0=a._Minimum=a.asm.ca).apply(null,arguments)},tt=a._MirrorPad=function(){return(tt=a._MirrorPad=a.asm.da).apply(null,arguments)},Z0=a._Multiply=function(){return(Z0=a._Multiply=a.asm.ea).apply(null,arguments)},Y0=a._Neg=function(){return(Y0=a._Neg=a.asm.fa).apply(null,arguments)},J0=a._NonMaxSuppressionV3=function(){return(J0=a._NonMaxSuppressionV3=a.asm.ga).apply(null,arguments)},pi=a._NonMaxSuppressionV4=function(){return(pi=a._NonMaxSuppressionV4=a.asm.ha).apply(null,arguments)},_d=a._NonMaxSuppressionV5=function(){return(_d=a._NonMaxSuppressionV5=a.asm.ia).apply(null,arguments)},Dd=a._NotEqual=function(){return(Dd=a._NotEqual=a.asm.ja).apply(null,arguments)},$d=a._OneHot=function(){return($d=a._OneHot=a.asm.ka).apply(null,arguments)},Q0=a._PadV2=function(){return(Q0=a._PadV2=a.asm.la).apply(null,arguments)},em=a._Pow=function(){return(em=a._Pow=a.asm.ma).apply(null,arguments)},Fd=a._Prelu=function(){return(Fd=a._Prelu=a.asm.na).apply(null,arguments)},tm=a._Prod=function(){return(tm=a._Prod=a.asm.oa).apply(null,arguments)},Od=a._RealDiv=function(){return(Od=a._RealDiv=a.asm.pa).apply(null,arguments)},Mr=a._Relu=function(){return(Mr=a._Relu=a.asm.qa).apply(null,arguments)},nm=a._Relu6=function(){return(nm=a._Relu6=a.asm.ra).apply(null,arguments)},sm=a._ResizeBilinear=function(){return(sm=a._ResizeBilinear=a.asm.sa).apply(null,arguments)},Qy=a._Reverse=function(){return(Qy=a._Reverse=a.asm.ta).apply(null,arguments)},Pd=a._RotateWithOffset=function(){return(Pd=a._RotateWithOffset=a.asm.ua).apply(null,arguments)},rm=a._Round=function(){return(rm=a._Round=a.asm.va).apply(null,arguments)},am=a._Rsqrt=function(){return(am=a._Rsqrt=a.asm.wa).apply(null,arguments)},om=a._ScatterNd=function(){return(om=a._ScatterNd=a.asm.xa).apply(null,arguments)},im=a._SelectV2=function(){return(im=a._SelectV2=a.asm.ya).apply(null,arguments)},lm=a._Sigmoid=function(){return(lm=a._Sigmoid=a.asm.za).apply(null,arguments)},um=a._Sin=function(){return(um=a._Sin=a.asm.Aa).apply(null,arguments)},cm=a._Softmax=function(){return(cm=a._Softmax=a.asm.Ba).apply(null,arguments)},dm=a._Sqrt=function(){return(dm=a._Sqrt=a.asm.Ca).apply(null,arguments)},hm=a._Square=function(){return(hm=a._Square=a.asm.Da).apply(null,arguments)},pm=a._SquaredDifference=function(){return(pm=a._SquaredDifference=a.asm.Ea).apply(null,arguments)},fm=a._Step=function(){return(fm=a._Step=a.asm.Fa).apply(null,arguments)},mm=a._StridedSlice=function(){return(mm=a._StridedSlice=a.asm.Ga).apply(null,arguments)},gm=a._Sub=function(){return(gm=a._Sub=a.asm.Ha).apply(null,arguments)},Am=a._Sum=function(){return(Am=a._Sum=a.asm.Ia).apply(null,arguments)},ym=a._Tan=function(){return(ym=a._Tan=a.asm.Ja).apply(null,arguments)},xm=a._Tanh=function(){return(xm=a._Tanh=a.asm.Ka).apply(null,arguments)},bm=a._Tile=function(){return(bm=a._Tile=a.asm.La).apply(null,arguments)},vm=a._TopK=function(){return(vm=a._TopK=a.asm.Ma).apply(null,arguments)},wm=a._Transform=function(){return(wm=a._Transform=a.asm.Na).apply(null,arguments)},km=a._Transpose=function(){return(km=a._Transpose=a.asm.Oa).apply(null,arguments)},Im=a.__FusedMatMul=function(){return(Im=a.__FusedMatMul=a.asm.Pa).apply(null,arguments)},Sm=a._malloc=function(){return(Sm=a._malloc=a.asm.Qa).apply(null,arguments)},Cm=a._free=function(){return(Cm=a._free=a.asm.Ra).apply(null,arguments)},Md=a.___errno_location=function(){return(Md=a.___errno_location=a.asm.Sa).apply(null,arguments)},zd=a.stackSave=function(){return(zd=a.stackSave=a.asm.Ta).apply(null,arguments)},Ld=a.stackRestore=function(){return(Ld=a.stackRestore=a.asm.Ua).apply(null,arguments)},Cu=a.stackAlloc=function(){return(Cu=a.stackAlloc=a.asm.Va).apply(null,arguments)};a.cwrap=ee;var fi;function Tm(Y){this.name="ExitStatus",this.message="Program terminated with exit("+Y+")",this.status=Y}mr=function Y(){fi||Tu(),fi||(mr=Y)};function Tu(Y){if(Y=Y||c,Vn>0||(pn(),Vn>0))return;function re(){fi||(fi=!0,a.calledRun=!0,!P&&(ts(),ns(),o(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),sn()))}a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),re()},1)):re()}if(a.run=Tu,a.preInit)for(typeof a.preInit=="function"&&(a.preInit=[a.preInit]);a.preInit.length>0;)a.preInit.pop()();return Tu(),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)}}),fS="3.9.0",mS="3.9.0",gS="3.9.0",AS="3.9.0",yS="3.9.0",xS="3.9.0",bS="3.9.0",vS="3.9.0",wS=1e-7,kS=1e-4,Hd=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}},$u=class{refCount(e){return Is("refCount")}incRef(e){return Is("incRef")}timerAvailable(){return!0}time(e){return Is("time")}read(e){return Is("read")}readSync(e){return Is("readSync")}numDataIds(){return Is("numDataIds")}disposeData(e,t){return Is("disposeData")}write(e,t,n){return Is("write")}move(e,t,n,s,r){return Is("move")}memory(){return Is("memory")}floatPrecision(){return Is("floatPrecision")}epsilon(){return this.floatPrecision()===32?wS:kS}dispose(){return Is("dispose")}};function Is(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 x5(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,Gd(e,t,n)}function IS(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--,Gd(e,n,s),Gd(t,n,s)}function Fu(e,t,n){return Math.max(e,Math.min(t,n))}function SS(e){return e%2==0?e:e+1}function Gd(e,t,n){let s=e[t];e[t]=e[n],e[n]=s}function CS(e){let t=0;for(let n=0;nn+` Shapes ${e} and ${t} must match`)}function Ca(e){M(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Ta(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||cn(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 FS(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 Ss(e,t){let n=t.length;return e=e==null?t.map((s,r)=>r):[].concat(e),M(e.every(s=>s>=-n&&s`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),M(e.every(s=>Zt(s)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(s=>s<0?n+s:s)}function b5(e,t){let n=[],s=[],r=t!=null&&Array.isArray(t)&&t.length===0,a=t==null||r?null:Ss(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 v5(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 w5(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 k5(e,t){for(let n=0;nt+=n.length),t}function Br(e){return typeof e=="string"||e instanceof String}function C5(e){return typeof e=="boolean"}function T5(e){return typeof e=="number"}function jd(e){return Array.isArray(e)?jd(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":T5(e)?"float32":Br(e)?"string":C5(e)?"bool":"float32"}function Wr(e){return!!(e&&e.constructor&&e.call&&e.apply)}function qd(e,t){for(let n=t;n=0;--s)n[s]=n[s+1]*e[s+1];return n}function N5(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*u)*(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 N5(0,e,t,n)}function Pm(e,t){let n=Xd(e,t);for(let s=0;ss*r,1);if(t==null||t==="float32")return ki(e,new Float32Array(n));if(t==="int32")return ki(e,new Int32Array(n));if(t==="bool")return ki(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function Mm(e){e.forEach(t=>{M(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function MS(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]=VS(s,r)})}};function BS(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...s)=>(WS(t,s[0],s[1]),s.join("="))),t}function WS(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function VS(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 Q(){return os}var os=null;function US(e){os=e}var Lm;function _5(){if(Lm==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");Lm=e}return Lm}function HS(){let e=_5();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function Bm(e,t){let n=HS();if(n.has(e))return n.get(e);{let s=t();return n.set(e,s),n.get(e)}}var Ii="Abs",Si="Acos",Ci="Acosh",Vr="Add",Na="AddN",Ti="All",Ni="Any",Ea="ArgMax",Pu="ArgMin",Ei="Asin",Ri="Asinh",_i="Atan",Di="Atanh",$i="Atan2",Ra="AvgPool",Kd="AvgPoolGrad",Mu="AvgPool3D",Zd="AvgPool3DGrad",_a="BatchMatMul",Fi="BatchToSpaceND",Yd="Bincount",D5="BroadcastTo",Wm="BroadcastArgs",Da="Cast",$a="Ceil",Ur="ClipByValue",Jd="Complex",zu="ComplexAbs",Oi="Concat",Fa="Conv2D",Qd="Conv2DBackpropFilter",Oa="Conv2DBackpropInput",Lu="Conv3D",eh="Conv3DBackpropFilterV2",th="Conv3DBackpropInputV2",Pa="Cos",Ma="Cosh",za="Cumsum",Pi="CropAndResize",nh="DenseBincount",Mi="DepthToSpace",La="DepthwiseConv2dNative",sh="DepthwiseConv2dNativeBackpropFilter",rh="DepthwiseConv2dNativeBackpropInput",ah="Diag",Bu="Dilation2D",oh="Dilation2DBackpropInput",ih="Dilation2DBackpropFilter",Ba="RealDiv",lh="Einsum",Wa="Elu",uh="EluGrad",zi="Erf",Li="Equal",Va="Exp",Bi="ExpandDims",Wi="Expm1",ch="FFT",Wu="Fill",Vi="FlipLeftRight",Ua="Floor",Ha="FloorDiv",Ga="FusedBatchNorm",Ui="GatherV2",Hi="GatherNd",Gi="Greater",ja="GreaterEqual",qa="Identity",dh="IFFT",hh="Imag",ji="IsFinite",qi="IsInf",Xi="IsNan",Xa="LeakyRelu",Ki="Less",Zi="LessEqual",ph="LinSpace",Ka="Log",Yi="Log1p",Ji="LogicalAnd",Vu="LogicalNot",Uu="LogicalOr",$5="LogSoftmax",Hu="LRN",fh="LRNGrad",Za="Max",Ya="Maximum",Ja="MaxPool",mh="MaxPoolGrad",Gu="MaxPool3D",gh="MaxPool3DGrad",Ah="MaxPoolWithArgmax",Qa="Mean",eo="Min",to="Minimum",no="MirrorPad",Qi="Mod",yh="Multinomial",so="Multiply",el="Neg",tl="NotEqual",nl="NonMaxSuppressionV3",sl="NonMaxSuppressionV4",rl="NonMaxSuppressionV5",al="OnesLike",ro="OneHot",ol="Pack",ao="PadV2",GS="Pool",oo="Pow",io="Prelu",il="Prod",ju="Range",xh="Real",ll="Reciprocal",lo="Relu",ul="Reshape",qu="ResizeNearestNeighbor",bh="ResizeNearestNeighborGrad",uo="ResizeBilinear",vh="ResizeBilinearGrad",co="Relu6",ho="Reverse",po="Round",fo="Rsqrt",cl="ScatterNd",dl="Select",hl="Selu",pl="Slice",mo="Sin",fl="Sinh",ml="Sign",go="Sigmoid",gl="Softplus",Ao="Sqrt",yo="Sum",Al="SpaceToBatchND",yl="SplitV",xo="Softmax",wh="SparseFillEmptyRows",kh="SparseReshape",Ih="SparseSegmentMean",Sh="SparseSegmentSum",Ch="SparseToDense",bo="SquaredDifference",Xu="Square",xl="StridedSlice",Th="StringNGrams",Nh="StringSplit",Eh="StringToHashBucketFast",vo="Sub",wo="Tan",ko="Tanh",Hr="Tile",bl="TopK",vl="Transform",Io="Transpose",Rh="Unique",wl="Unpack",Ku="UnsortedSegmentSum",kl="ZerosLike",Gr="Step",_h="FromPixels",Il="RotateWithOffset",So="_FusedMatMul",Co="FusedConv2D",To="FusedDepthwiseConv2D",Sl=Bm("kernelRegistry",()=>new Map),Zu=Bm("gradRegistry",()=>new Map);function Dh(e,t){let n=Um(e,t);return Sl.get(n)}function Vm(e){return Zu.get(e)}function Cl(e){let t=Sl.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 No(e){let{kernelName:t,backendName:n}=e,s=Um(t,n);Sl.has(s)&&Ys(`The kernel '${t}' for backend '${n}' is already registered`),Sl.set(s,e)}function F5(e){let{kernelName:t}=e;Zu.has(t)&&Q().getBool("DEBUG")&&Ys(`Overriding the gradient for '${t}'`),Zu.set(t,e)}function jS(e,t){let n=Um(e,t);if(!Sl.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);Sl.delete(n)}function qS(e){if(!Zu.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Zu.delete(e)}function XS(e,t){Cl(e).forEach(s=>{let r=Object.assign({},s,{backendName:t});No(r)})}function Um(e,t){return`${t}_${e}`}var w={};Pe(w,{arraysEqual:()=>br,assert:()=>M,assertNonNegativeIntegerDimensions:()=>Mm,assertNonNull:()=>Ca,assertShapesMatch:()=>An,bytesFromStringArray:()=>S5,bytesPerElement:()=>Om,checkConversionForErrors:()=>k5,clamp:()=>Fu,computeStrides:()=>wi,createScalarValue:()=>e9,createShuffledIndices:()=>DS,decodeString:()=>Oh,distSquared:()=>NS,encodeString:()=>Qu,fetch:()=>n9,fingerPrint64:()=>QS,flatten:()=>Ta,getArrayFromDType:()=>w5,getTypedArrayFromDType:()=>v5,hasEncodingLoss:()=>OS,hexToLong:()=>Yu,indexToLoc:()=>zS,inferDtype:()=>jd,inferFromImplicitShape:()=>FS,isBoolean:()=>C5,isFunction:()=>Wr,isInt:()=>Zt,isNumber:()=>T5,isPromise:()=>zm,isScalarShape:()=>ES,isString:()=>Br,isTypedArray:()=>cn,isValidDtype:()=>I5,locToIndex:()=>MS,makeOnesTypedArray:()=>Pm,makeZerosNestedTypedArray:()=>PS,makeZerosTypedArray:()=>Xd,nearestDivisor:()=>qd,nearestLargerEven:()=>SS,now:()=>Ju,parseAxisParam:()=>Ss,randUniform:()=>TS,repeatedTry:()=>$S,rightPad:()=>Ou,shuffle:()=>x5,shuffleCombo:()=>IS,sizeFromShape:()=>$t,sizeToSquarishShape:()=>_S,squeezeShape:()=>b5,sum:()=>CS,swap:()=>Gd,tanh:()=>RS,toNestedArray:()=>ki,toTypedArray:()=>Fh});var O5=Sa(XI()),Eo=O5.default||O5;function Yu(e){return Eo.fromString(e,!0,16)}var P5=Yu("c3a5c85c97cb3127"),Ro=Yu("b492b66fbe98f273"),yn=Yu("9ae16a3b2f90404f");function Hm(e){return e.xor(e.shru(47))}function M5(e,t,n){let s=e.slice(t,t+n);return Eo.fromBytes(Array.from(s),!0,!0)}function pt(e,t){return M5(e,t,8)}function z5(e,t){return M5(e,t,4)}function Yt(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function jr(e,t,n=Yu("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 KS(e,t,n,s,r,a){r=r.add(e),a=Yt(a.add(r).add(s),21);let o=r;return r=r.add(t),r=r.add(n),a=a.add(Yt(r,44)),[r.add(s),a.add(o)]}function $h(e,t,n,s){return KS(pt(e,t),pt(e,t+8),pt(e,t+16),pt(e,t+24),n,s)}function ZS(e,t=e.length){if(t>=8){let n=yn.add(t*2),s=pt(e,0).add(yn),r=pt(e,t-8),a=Yt(r,37).mul(n).add(s),o=Yt(s,25).add(r).mul(n);return jr(a,o,n)}if(t>=4){let n=yn.add(t*2),s=z5(e,0);return jr(s.shl(3).add(t),z5(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 Hm(yn.mul(a).xor(P5.mul(o))).mul(yn)}return yn}function YS(e,t=e.length){let n=yn.add(t*2),s=pt(e,0).mul(Ro),r=pt(e,8),a=pt(e,t-8).mul(n),o=pt(e,t-16).mul(yn);return jr(Yt(s.add(r),43).add(Yt(a,30)).add(o),s.add(Yt(r.add(yn),18)).add(a),n)}function JS(e,t=e.length){let n=yn.add(t*2),s=pt(e,0).mul(yn),r=pt(e,8),a=pt(e,t-8).mul(n),o=pt(e,t-16).mul(yn),i=Yt(s.add(r),43).add(Yt(a,30)).add(o),l=jr(i,s.add(Yt(r.add(yn),18)).add(a),n),u=pt(e,16).mul(n),c=pt(e,24),d=i.add(pt(e,t-32)).mul(n),h=l.add(pt(e,t-24)).mul(n);return jr(Yt(u.add(c),43).add(Yt(d,30)).add(h),u.add(Yt(c.add(s),18)).add(d),n)}function QS(e,t=e.length){let n=Eo.fromNumber(81,!0);if(t<=32)return t<=16?ZS(e,t):YS(e,t);if(t<=64)return JS(e,t);let s=n,r=n.mul(Ro).add(113),a=Hm(r.mul(yn).add(113)).mul(yn),o=[Eo.UZERO,Eo.UZERO],i=[Eo.UZERO,Eo.UZERO];s=s.mul(yn).add(pt(e,0));let l=0,u=(t-1>>6)*64,c=u+(t-1&63)-63;do s=Yt(s.add(r).add(o[0]).add(pt(e,l+8)),37).mul(Ro),r=Yt(r.add(o[1]).add(pt(e,l+48)),42).mul(Ro),s=s.xor(i[1]),r=r.add(o[0]).add(pt(e,l+40)),a=Yt(a.add(i[0]),33).mul(Ro),o=$h(e,l,o[1].mul(Ro),s.add(i[0])),i=$h(e,l+32,a.add(i[1]),r.add(pt(e,l+16))),[a,s]=[s,a],l+=64;while(l!==u);let d=Ro.add(a.and(255).shl(1));return l=c,i[0]=i[0].add(t-1&63),o[0]=o[0].add(i[0]),i[0]=i[0].add(o[0]),s=Yt(s.add(r).add(o[0]).add(pt(e,l+8)),37).mul(d),r=Yt(r.add(o[1]).add(pt(e,l+48)),42).mul(d),s=s.xor(i[1].mul(9)),r=r.add(o[0].mul(9).add(pt(e,l+40))),a=Yt(a.add(i[0]),33).mul(d),o=$h(e,l,o[1].mul(d),s.add(i[0])),i=$h(e,l+32,a.add(i[1]),r.add(pt(e,l+16))),[a,s]=[s,a],jr(jr(o[0],i[0],d).add(Hm(r).mul(P5)).add(a),jr(o[1],i[1],d).add(s),d)}function e9(e,t){return t==="string"?Qu(e):Fh([e],t)}function t9(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Fh(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Ta(e)),Q().getBool("DEBUG")&&k5(e,t),t9(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=Ju();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(r);else{r();for(let l of s)l.dataSync();a=Promise.resolve({kernelMs:Ju()-o})}if(Q().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let l=0;l{r9(c,u.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 r9(e,t,n){if(t!=="float32")return!1;for(let s=0;s0?f:""} `}}console.log(`%c${i} %c${o} %c${l}D ${c} %c${u} %c${d} %c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function o9(e,t,n){let s={},r={};for(let l=0;ls[m.id]=!0),p=!0,r[u.id]=!0;break}if(p)break}}let a={};a[n.id]=!0;let o={};for(let l=e.length-1;l>=0;l--){let u=e[l],c=u.inputs;for(let d=0;d=0;r--){let a=t[r],o=[];if(a.outputs.forEach(l=>{let u=e[l.id];u!=null?o.push(u):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 u=n(()=>i[l]());if(u.dtype!=="float32")throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);let c=a.inputs[l];if(!br(u.shape,c.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${c.shape}'`);if(e[c.id]==null)e[c.id]=u;else{let d=e[c.id];e[c.id]=s(d,u),d.dispose()}}}}var L5=20,ec=3,Gm=7;function l9(e,t,n,s){let r=wi(t),a=u9(e,t,n,r),o=t.length,i=Ph(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(u=>" "+u).join(`
`)),l.join(`
-`)}function l9(e,t,n,s){let r=$t(t),a=s[s.length-1],o=new Array(a).fill(0),i=t.length,l=n==="complex64"?nc(e):e;if(i>1)for(let u=0;uL5){let g=ec*o,A=Array.from(e.slice(0,g)),y=Array.from(e.slice((i-ec)*o,i*o));return n==="complex64"&&(A=nc(A),y=nc(y)),["["+A.map((x,b)=>tc(x,r[b],n)).join(", ")+", ..., "+y.map((x,b)=>tc(x,r[i-ec+b],n)).join(", ")+"]"]}let m=n==="complex64"?nc(e):Array.from(e);return["["+m.map((g,A)=>tc(g,r[A],n)).join(", ")+"]"]}let u=t.slice(1),c=s.slice(1),d=s[0]*o,h=[];if(i>L5){for(let m=0;m1)for(let u=0;uL5){let g=ec*o,A=Array.from(e.slice(0,g)),y=Array.from(e.slice((i-ec)*o,i*o));return n==="complex64"&&(A=nc(A),y=nc(y)),["["+A.map((x,b)=>tc(x,r[b],n)).join(", ")+", ..., "+y.map((x,b)=>tc(x,r[i-ec+b],n)).join(", ")+"]"]}let m=n==="complex64"?nc(e):Array.from(e);return["["+m.map((g,A)=>tc(g,r[A],n)).join(", ")+"]"]}let u=t.slice(1),c=s.slice(1),d=s[0]*o,h=[];if(i>L5){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||w5(t,this.size),this.strides=wi(e)}set(e,...t){t.length===0&&(t=[0]),M(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let s of e){if(s<0||s>=this.shape[t]){let r=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(r)}t++}let n=e[e.length-1];for(let s=0;sOh(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=Js().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Oh(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 Js().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Js().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Tl.print(this,e)}clone(){return this.throwIfDisposed(),Tl.clone(this)}toString(e=!1){let t=this.dataSync();return i9(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Tl.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Js().makeVariable(this,e,t,n)}};Object.defineProperty(Ge,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function p9(){return Lm("Tensor",()=>Ge)}p9();var sc=class extends Ge{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(!br(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Js().disposeTensor(this),this.dataId=e.dataId,Js().incRef(this,null)}dispose(){Js().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(sc,Symbol.hasInstance,{value:e=>e instanceof Ge&&e.assign!=null&&e.assign instanceof Function});var $s={};Pe($s,{assertTypesMatch:()=>W5,getTensorsInContainer:()=>Zm,isTensorInList:()=>m9,makeTypesMatch:()=>Ct});var Gm;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(Gm||(Gm={}));var jm;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(jm||(jm={}));var qm;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(qm||(qm={}));var Xm;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(Xm||(Xm={}));var Km;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(Km||(Km={}));var f9={float32:Xm,int32:jm,bool:qm,complex64:Km};function Cs(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return f9[e][t]}function Mh(e){return Cs(e,"int32")}function Ct(e,t){if(e.dtype===t.dtype)return[e,t];let n=Cs(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function W5(e,t){M(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function m9(e,t){return t.some(n=>n.id===e.id)}function Zm(e){let t=[],n=new Set;return V5(e,t,n),t}function V5(e,t,n){if(e==null)return;if(e instanceof Ge){t.push(e);return}if(!g9(e))return;let s=e;for(let r in s){let a=s[r];n.has(a)||(n.add(a),V5(a,t,n))}}function g9(e){return Array.isArray(e)||typeof e=="object"}function Ym(e){return e.kernelName!=null}var U5=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()}},rc=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new U5}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){Cl(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 $u)&&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 rc.nextTensorId++}nextVariableId(){return rc.nextVariableId++}clone(e){let t=z.runKernel(qa,{x:e}),n={x:e},s=a=>({x:()=>{let o="float32",i={x:a},l={dtype:o};return z.runKernel(Da,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,!(Dh(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=Ym(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(Ym(e)){let{kernelName:p,inputs:f,attrs:m}=e;this.backendName==null&&this.backend;let g=Dh(p,this.backendName);M(g!=null,()=>`Cannot find registered kernel '${p}' 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(p,A,y);let x=y.map(b=>{if(b.rank!=null)return b;let{dataId:v,shape:k,dtype:S}=b;return this.makeTensorFromDataId(v,k,S)});if(s){let b=this.getTensorsForGradient(p,f,x);n=this.saveTensorsForBackwardMode(b)}return x}}else{let{forwardFunc:p}=e,f=m=>{!s||(n=m.map(g=>this.keep(this.clone(g))))};o=()=>{let m=this.backend.numDataIds();i=this.tidy(()=>p(this.backend,f));let g=Array.isArray(i)?i:[i];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,m,g),g}}let{inputs:u,attrs:c}=e,d=Ym(e)?null:e.backwardsFunc,h;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=o():(h=this.profiler.profileKernel(l,u,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(h),t=h.outputs)}),s&&this.addTapeNode(l,u,t,d,n,c),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(u).map(p=>u[p]!=null?u[p].shape:null),outputShapes:t.map(p=>p.shape),kernelTimeMs:h.timeMs,extraInfo:h.extraInfo}),Array.isArray(i)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(n=>this.keep(this.clone(n)))}getTensorsForGradient(e,t,n){let s=Wm(e);if(s!=null){let r=s.inputsToSave||[],a=s.outputsToSave||[],o;s.saveAllInputs?(M(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),o=Object.keys(t).map(l=>t[l])):o=r.map(l=>t[l]);let i=n.filter((l,u)=>a[u]);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"&&Br(e[0])&&(r=e.map(i=>Qu(i)));let a=s.write(r,t,n),o=new Ge(t,n,a,this.nextTensorId());if(this.trackTensor(o,s),n==="string"){let i=this.state.tensorInfo.get(a),l=S5(r);this.state.numBytes+=l-i.bytes,i.bytes=l}return o}makeTensorFromDataId(e,t,n,s){n=n||"float32";let r=new Ge(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 sc(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*Fm(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 sc||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*Fm(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=Wm(e);i!=null&&(s=i.gradFunc),s!=null&&(o.gradient=l=>(l=l.map((u,c)=>{if(u==null){let d=n[c],h=Xd(d.size,d.dtype);return this.makeTensor(h,d.shape,d.dtype)}return u}),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=Zm(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(M(t.length>0,()=>"gradients() received an empty list of xs."),n!=null&&n.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);let r=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));M(r instanceof Ge,()=>"The result y returned by f() must be a tensor.");let a=a9(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?A9(r.shape):n,o9(o,a,l=>this.tidy(l),y9);let i=t.map(l=>o[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let u of l.saved)u.dispose()}),this.state.activeTape=null),{value:r,grads:i}})}customGrad(e){return M(Wr(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{M(t.every(o=>o instanceof Ge),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,s={};t.forEach((o,i)=>{s[i]=o});let r=(o,i)=>(n=e(...t,i),M(n.value instanceof Ge,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),M(Wr(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),u=Array.isArray(l)?l:[l];M(u.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),M(u.every(d=>d instanceof Ge),()=>"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 c={};return u.forEach((d,h)=>{c[h]=()=>d}),c};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=Ju(),n=await this.backend.time(e);return n.wallMs=Ju()-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 U5;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}};rc.nextTensorId=0;rc.nextVariableId=0;function A9(e){let t=Om($t(e),"float32");return z.makeTensor(t,e,"float32")}function H5(){let e=_5();if(e._tfengine==null){let t=new R5(e);e._tfengine=new rc(t)}return VS(e._tfengine.ENV),c9(()=>e._tfengine),e._tfengine}var z=H5();function y9(e,t){let n={a:e,b:t};return z.runKernel(Vr,n)}var ac={};Pe(ac,{isBrowser:()=>G5,isMobile:()=>b9});function x9(){return typeof navigator!="undefined"&&navigator!=null}function b9(e){if(e||x9()){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 G5(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Fs=Q();Fs.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.")});Fs.registerFlag("IS_BROWSER",()=>G5());Fs.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Fs.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Fs.registerFlag("PROD",()=>!1);Fs.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Fs.getBool("DEBUG"));Fs.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Fs.registerFlag("IS_TEST",()=>!1);Fs.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);Fs.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function Qs(e,t){let n=e;if(cn(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let s=[];for(;Array.isArray(n)||cn(n)&&t!=="string";)s.push(n.length),n=n[0];return Array.isArray(e)&&Q().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&j5(e,s,[]),s}function j5(e,t,n){if(n=n||[],!Array.isArray(e)&&!cn(e)){M(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}M(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),M(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let s=t.slice(1);for(let r=0;r=0&&(r=s),q5(s,r,t,n),e==null||!cn(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=Qs(e,r);!cn(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?Fh(e,r):Ta(e,[],!0);return z.makeTensor(i,a,r)}function oc(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 X5="__op";function W(e){let t=Object.keys(e);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0],s=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+X5;let r=(...a)=>{z.startScope(n);try{let o=s(...a);return Mm(o)&&console.error("Cannot return a Promise inside of tidy."),z.endScope(o),o}catch(o){throw z.endScope(null),o}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}function v9(e,t){let n=$(e,"real","complex"),s=$(t,"imag","complex");An(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 z.runKernel(Jd,r)}var qr=W({complex_:v9});function Xr(e,t,n,s){if(s==null&&(s=jd(e)),s==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!cn(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){Pm(t);let r=$t(t),a=$t(n);M(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!cn(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=s!=="string"?Fh(e,s):Ta(e,[],!0),z.makeTensor(e,t,s)}function dn(e,t,n){let s=Qs(e,n);return Xr(e,t,s,n)}var Jm={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},zh=4;async function w9(e,t){let n=[],s=[],r=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);for(let o=0;o{let h=await l.bytes(),p=h.reduce((g,A)=>g+A.length,0)+zh*h.length,f=new Uint8Array(p),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 Qm=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function Z5(e){return Qm?Buffer.byteLength(e):new Blob([e]).size}function I9(e){if(Qm)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 Y5(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 J5(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 tg(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 ic(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:Z5(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:Z5(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function C9(){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 T9(){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 N9(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function E9(){let e=C9(),t=T9(),n=N9();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 Rt=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Rt.instance==null&&(Rt.instance=new Rt),Rt.instance}static registerSaveRouter(e){Rt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Rt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Rt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Rt.getHandlers(e,"load",t)}static getHandlers(e,t,n){let s=[];return(t==="load"?Rt.getInstance().loadRouters:Rt.getInstance().saveRouters).forEach(a=>{let o=a(e,n);o!==null&&s.push(o)}),s}},R9=e=>Rt.registerSaveRouter(e),_9=e=>Rt.registerLoadRouter(e),D9=e=>Rt.getSaveHandlers(e),$9=(e,t)=>Rt.getLoadHandlers(e,t),ng="tensorflowjs",sg=1,_o="models_store",Kr="model_info_store";function Q5(){if(!Q().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 rg(e){let t=e.result;t.createObjectStore(_o,{keyPath:"modelPath"}),t.createObjectStore(Kr,{keyPath:"modelPath"})}var Do=class{constructor(e){if(this.indexedDB=Q5(),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(ng,sg);r.onupgradeneeded=()=>rg(r),r.onsuccess=()=>{let a=r.result;if(t==null){let o=a.transaction(_o,"readonly"),l=o.objectStore(_o).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=u=>(a.close(),s(l.error)),o.oncomplete=()=>a.close()}else{let o=ic(t),i=a.transaction(Kr,"readwrite"),l=i.objectStore(Kr),u=l.put({modelPath:this.modelPath,modelArtifactsInfo:o}),c;u.onsuccess=()=>{c=a.transaction(_o,"readwrite");let h=c.objectStore(_o).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:o});h.onsuccess=()=>n({modelArtifactsInfo:o}),h.onerror=p=>{l=i.objectStore(Kr);let f=l.delete(this.modelPath);f.onsuccess=()=>(a.close(),s(h.error)),f.onerror=m=>(a.close(),s(h.error))}},u.onerror=d=>(a.close(),s(u.error)),i.oncomplete=()=>{c==null?a.close():c.oncomplete=()=>a.close()}}},r.onerror=a=>s(r.error)})}};Do.URL_SCHEME="indexeddb://";var ex=e=>Q().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Do.URL_SCHEME)?F9(e.slice(Do.URL_SCHEME.length)):null;Rt.registerSaveRouter(ex);Rt.registerLoadRouter(ex);function F9(e){return new Do(e)}function O9(e){return e.startsWith(Do.URL_SCHEME)?e.slice(Do.URL_SCHEME.length):e}var P9=class{constructor(){this.indexedDB=Q5()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(ng,sg);n.onupgradeneeded=()=>rg(n),n.onsuccess=()=>{let s=n.result,r=s.transaction(Kr,"readonly"),o=r.objectStore(Kr).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=O9(e),new Promise((t,n)=>{let s=this.indexedDB.open(ng,sg);s.onupgradeneeded=()=>rg(s),s.onsuccess=()=>{let r=s.result,a=r.transaction(Kr,"readwrite"),o=a.objectStore(Kr),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 u=o.delete(e),c=()=>{l=r.transaction(_o,"readwrite");let h=l.objectStore(_o).delete(e);h.onsuccess=()=>t(i.result.modelArtifactsInfo),h.onerror=p=>n(i.error)};u.onsuccess=c,u.onerror=d=>(c(),r.close(),n(i.error))}},i.onerror=u=>(r.close(),n(i.error)),a.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},s.onerror=r=>n(s.error)})}},vr="/",Nl="tensorflowjs_models",tx="info",M9="model_topology",z9="weight_specs",L9="weight_data",B9="model_metadata";function nx(e){return{info:[Nl,e,tx].join(vr),topology:[Nl,e,M9].join(vr),weightSpecs:[Nl,e,z9].join(vr),weightData:[Nl,e,L9].join(vr),modelMetadata:[Nl,e,B9].join(vr)}}function sx(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function W9(e){let t=e.split(vr);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(vr)}function V9(e){return e.startsWith($o.URL_SCHEME)?e.slice($o.URL_SCHEME.length):e}var $o=class{constructor(e){if(!Q().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=nx(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=ic(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,I9(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 sx(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=S9(a),t}};$o.URL_SCHEME="localstorage://";var rx=e=>Q().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith($o.URL_SCHEME)?U9(e.slice($o.URL_SCHEME.length)):null;Rt.registerSaveRouter(rx);Rt.registerLoadRouter(rx);function U9(e){return new $o(e)}var H9=class{constructor(){M(Q().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),M(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Nl+vr,n=vr+tx;for(let s=0;s"scheme must not be undefined or null."),e.endsWith(El)&&(e=e.slice(0,e.indexOf(El))),M(e.length>0,()=>"scheme must not be an empty string.");let n=is.getInstance();M(n.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){let t=this.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(this.getInstance().managers)}};function Lh(e){if(e.indexOf(El)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${is.getSchemes().join(",")}`);return{scheme:e.split(El)[0],path:e.split(El)[1]}}async function ax(e,t,n=!1){M(e!==t,()=>`Old path and new path are the same: '${e}'`);let s=Rt.getLoadHandlers(e);M(s.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),M(s.length<2,()=>`Copying failed because more than one (${s.length}) load handlers for source URL ${e}.`);let r=s[0],a=Rt.getSaveHandlers(t);M(a.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),M(a.length<2,()=>`Copying failed because more than one (${s.length}) save handlers for destination URL ${t}.`);let o=a[0],i=Lh(e).scheme,l=Lh(e).path,u=i===Lh(e).scheme,c=await r.load();n&&u&&await is.getManager(i).removeModel(l);let d=await o.save(c);return n&&!u&&await is.getManager(i).removeModel(l),d.modelArtifactsInfo}async function G9(){let e=is.getSchemes(),t={};for(let n of e){let s=await is.getManager(n).listModels();for(let r in s){let a=n+El+r;t[a]=s[r]}}return t}async function j9(e){let t=Lh(e);return is.getManager(t.scheme).removeModel(t.path)}async function q9(e,t){return ax(e,t,!1)}async function X9(e,t){return ax(e,t,!0)}var K9=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(Q().get("IS_BROWSER")){Q().setPlatform("browser",new K9);try{is.registerManager($o.URL_SCHEME,new H9)}catch(e){}try{is.registerManager(Do.URL_SCHEME,new P9)}catch(e){}}var Z9={importFetch:()=>XI()},ag,Y9=class{constructor(){this.util=vi("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return Q().global.fetch!=null?Q().global.fetch(e,t):(ag==null&&(ag=Z9.importFetch()),ag(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)}};Q().get("IS_NODE")&&Q().setPlatform("node",new Y9);function We(e,t="float32",n){return t=t||"float32",Pm(e),new Ut(e,t,n)}function J9(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 z.runKernel(Da,s,r)}var ce=W({cast_:J9});function Q9(e){let n={x:$(e,"x","clone","string_or_numeric")};return z.runKernel(qa,n)}var Os=W({clone_:Q9});function ox(e,t=!1){console.log(e.toString(t))}H5();var eC={buffer:We,cast:ce,clone:Os,print:ox};d9(eC);var _n={};Pe(_n,{browserFiles:()=>iC,browserHTTPRequest:()=>hC,concatenateArrayBuffers:()=>eg,copyModel:()=>q9,decodeWeights:()=>K5,encodeWeights:()=>w9,fromMemory:()=>fC,getLoadHandlers:()=>$9,getModelArtifactsForJSON:()=>tg,getModelArtifactsInfoForJSON:()=>ic,getSaveHandlers:()=>D9,http:()=>lg,isHTTPScheme:()=>ig,listModels:()=>G9,loadWeights:()=>lC,moveModel:()=>X9,registerLoadRouter:()=>_9,registerSaveRouter:()=>R9,removeModel:()=>j9,weightsLoaderFactory:()=>cx,withSaveHandler:()=>mC});var tC="model",nC=".json",sC=".weights.bin";function ix(e){return new Promise(t=>setTimeout(t)).then(e)}var Rl=class{constructor(e){if(!Q().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Rl.URL_SCHEME)&&(e=e.slice(Rl.URL_SCHEME.length)),(e==null||e.length===0)&&(e=tC),this.modelJsonFileName=e+nC,this.weightDataFileName=e+sC}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=J5(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 ix(()=>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 ix(()=>o.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:ic(e)}}}};Rl.URL_SCHEME="downloads://";var rC=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=tg(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,eg(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=>Y5(r.name)),s={};for(let r of e)r.paths.forEach(a=>{let o=Y5(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}},aC=e=>Q().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Rl.URL_SCHEME)?oC(e.slice(Rl.URL_SCHEME.length)):null;Rt.registerSaveRouter(aC);function oC(e="model"){return new Rl(e)}function iC(e){return new rC(e)}function lx(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(u=>{let c=n+ ++r/e.length*(s-n);return t(c),u}),l);function o(l){M(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function i(l,u){M(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),M(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),M(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(e.map(a))}async function ux(e,t){t==null&&(t={});let n=t.fetchFunc==null?Q().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 lx(s,t.onProgress,r,a)).map(d=>d.arrayBuffer()),l=.5,u=1;return t.onProgress==null?await Promise.all(i):await lx(i,t.onProgress,l,u)}async function lC(e,t="",n,s){return cx(o=>ux(o,{requestInit:s}))(e,t,n)}function cx(e){return async(t,n="",s)=>{let r=t.map(()=>!1),a={},o=s!=null?s.map(()=>!1):[],i=[];if(t.forEach((p,f)=>{let m=0;p.weights.forEach(g=>{let A="quantization"in g?g.quantization.dtype:g.dtype,y=Jm[A]*$t(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,v)=>{b===g.name&&(x(),o[v]=!0)}):x(),i.push(g.name),m+=y})}),!o.every(p=>p)){let p=s.filter((f,m)=>!o[m]);throw new Error(`Could not find weights in manifest with names: ${p.join(", ")}.
-Manifest JSON has weights with names: ${i.join(", ")}.`)}let l=r.reduce((p,f,m)=>(f&&p.push(m),p),[]),u=[];l.forEach(p=>{t[p].paths.forEach(f=>{let m=n+(n.endsWith("/")?"":"/")+f;u.push(m)})});let c=await e(u),d={},h=0;return l.forEach(p=>{let f=t[p].paths.length,m=0;for(let b=0;b{let v=g.slice(b.groupOffset,b.groupOffset+b.sizeBytes),k=K5(v,[b.manifestEntry]);for(let S in k)d[S]=k[S]}),h+=f}),d}}var uC="application/octet-stream",cC="application/json",og=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(M(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=Q().platform.fetch,M(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&M(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],s=J5(e,n);t.body.append("model.json",new Blob([JSON.stringify(s)],{type:cC}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:uC}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:ic(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 tg(t,r=>this.loadWeights(r))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=dC(t),r=this.weightPathPrefix||n,a=[];for(let u of e)a.push(...u.weights);let o=[],i=[];for(let u of e)for(let c of u.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(c)):o.push(r+c+s);this.weightUrlConverter&&o.push(...await Promise.all(i));let l=await ux(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,eg(l)]}};og.URL_SCHEME_REGEX=/^https?:\/\//;function dC(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),s=e.substring(0,t),r=n>t?e.substring(n):"";return[s+"/",r]}function ig(e){return e.match(og.URL_SCHEME_REGEX)!=null}var dx=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(s=>ig(s)):n=ig(e),n)return lg(e,t)}return null};Rt.registerSaveRouter(dx);Rt.registerLoadRouter(dx);function lg(e,t){return new og(e,t)}function hC(e,t){return lg(e,t)}var ug=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},pC=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function fC(e,t,n,s){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new ug(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 ug({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 ug({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:s}))}function mC(e){return new pC(e)}var hx={};Pe(hx,{confusionMatrix:()=>bC});function gC(e,t,n=!1,s=!1){let r=$(e,"a","matMul"),a=$(t,"b","matMul");[r,a]=Ct(r,a);let o={a:r,b:a},i={transposeA:n,transposeB:s};return z.runKernel(_a,o,i)}var Ve=W({matMul_:gC});function AC(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 z.runKernel(ro,a,o)}var lc=W({oneHot_:AC});function yC(e,t){let n=$(e,"x","transpose");if(t==null&&(t=n.shape.map((a,o)=>o).reverse()),M(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(a=>{M(a>=0&&a`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 z.runKernel(Io,s,r)}var Xe=W({transpose_:yC});function xC(e,t,n){let s=$(e,"labels","confusionMatrix"),r=$(t,"predictions","confusionMatrix");M(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),M(s.rank===1,()=>`Expected the rank of labels to be 1, but got ${s.rank}`),M(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),M(s.shape[0]===r.shape[0],()=>`Mismatch in the number of examples: ${s.shape[0]} vs. ${r.shape[0]}. Labels and predictions should have the same number of elements.`),M(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);let a=lc(ce(s,"int32"),n),o=lc(ce(r,"int32"),n),i=Xe(a),l=Ve(i,o);return ce(l,"int32")}var bC=W({confusionMatrix_:xC}),ls={};Pe(ls,{fromPixels:()=>TC,fromPixelsAsync:()=>SC,toPixels:()=>CC});function Bh(e,t,n){if(Ca(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let s=Qs(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 Xr(e,t,s,n)}var _l;function px(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(Dh(_h,z.backendName)!=null){let f={pixels:e},m={numChannels:t};return z.runKernel(_h,f,m)}let[u,c]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height],d;o?d=e.getContext("2d").getImageData(0,0,u,c).data:s||n?d=e.data:(a||r||i)&&(_l==null&&(_l=document.createElement("canvas").getContext("2d")),_l.canvas.width=u,_l.canvas.height=c,_l.drawImage(e,0,0,u,c),d=_l.getImageData(0,0,u,c).data);let h;if(t===4)h=new Int32Array(d);else{let f=u*c;h=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 u=0;u1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${p}.`)}else if(n.dtype==="int32"&&(p<0||p>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${p}.`);a===1?(c[0]=p*i,c[1]=p*i,c[2]=p*i):c[h]=p*i}let d=u*4;l[d+0]=Math.round(c[0]),l[d+1]=Math.round(c[1]),l[d+2]=Math.round(c[2]),l[d+3]=Math.round(c[3])}if(t!=null){t.width=r,t.height=s;let u=t.getContext("2d"),c=new ImageData(l,r,s);u.putImageData(c,0,0)}return n!==e&&n.dispose(),l}var TC=W({fromPixels_:px}),cg={};Pe(cg,{prepareAndValidate:()=>fx});function fx(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($t(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/u),1].slice(0,a);return[l,o,u,c]}var dg={};Pe(dg,{calculateShapes:()=>mx,validateInput:()=>pg,validateUpdateShape:()=>hg});function hg(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;dNC,computeFlatOffset:()=>RC,computeOutShape:()=>gx,getNormalizedAxes:()=>bx,isSliceContinous:()=>EC,maskToAxes:()=>Wh,parseSliceParams:()=>Cx,sliceInfo:()=>_C,startForAxis:()=>Ix,startIndicesWithElidedDims:()=>vx,stopForAxis:()=>Sx,stopIndicesWithElidedDims:()=>wx,stridesForAxis:()=>kx,stridesWithElidedDims:()=>Ax});function NC(e,t,n){let s=e.shape.length;M(s===t.length,()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`),M(s===n.length,()=>`Error in slice${s}D: Length of size ${n} must match the rank of the array (${s}).`);for(let r=0;r`Error in slice${s}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`)}function Wh(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function gx(e,t,n){let s=[];for(let r=0;r0){let p=t[0],f=n+1;c=vx(o,p,f,s,e),d=wx(i,p,f,r,e),h=Ax(a,p,f,e)}else for(let p=0;p-1)a[i]=0;else{let l=yx(t,n,i),u=s[l];e&1<-1)a[i]=Number.MAX_SAFE_INTEGER;else{let l=yx(t,n,i),u=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=Fu(0,o,l-1),o}function Sx(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=Fu(0,o,l):o=Fu(-1,o,l-1),o}function EC(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 RC(e,t){let n=e.length>0?e[e.length-1]:1;for(let s=0;s{M(o!==-1,()=>"slice() does not support negative begin indexing.")});let a;return n==null?a=new Array(r).fill(-1):typeof n=="number"?a=[n,...new Array(r-1).fill(-1)]:n.lengtho>=0?o:(M(o===-1,()=>`Negative size values should be exactly -1 but got ${o} for the slice() size at index ${i}.`),e.shape[i]-s[i])),[s,a]}function _C(e,t,n,s,r,a,o,i,l){let u=t.slice(),c=n.slice(),d=s;s==null&&(d=new Array(u.length));let h=Wh(o);if(h.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 p=e.length-u.length,f=Wh(i),m=e.slice();f.forEach(S=>{u[S]=0,c[S]=1,m.splice(S,0,1)});let{begin:g,end:A,strides:y}=bx(m,h,p,u,c,d,r,a,o);u=g,c=A,d=y;let x=Wh(l);x.forEach(S=>{c[S]=u[S]+1,d[S]=1});let b=gx(u,c,d),v=b.filter((S,C)=>x.indexOf(C)===-1);return{nonStrided:d.every(S=>S===1),$begin:u,$end:c,$strides:d,size:b,newShape:m,outShape:v}}var oe={};Pe(oe,{Serializable:()=>Tx,SerializationMap:()=>Fo,registerClass:()=>Zr});var Tx=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},Fo=class{constructor(){this.classNameMap={}}static getMap(){return Fo.instance==null&&(Fo.instance=new Fo),Fo.instance}static register(e){Fo.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function Zr(e){M(e.className!=null,()=>"Class being registered does not have the static className property defined."),M(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),M(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Fo.register(e)}var Nx={};Pe(Nx,{TEST_EPSILON_FLOAT16:()=>Ex,encodeStrings:()=>Rx,expectArrayBuffersEqual:()=>zC,expectArraysClose:()=>$C,expectArraysEqual:()=>OC,expectNumbersClose:()=>PC,expectPromiseToFail:()=>FC,expectValuesInRange:()=>MC,testEpsilon:()=>fg});var DC=.001,Ex=.1;function $C(e,t,n){return n==null&&(n=fg()),mg(e,t,(s,r)=>gg(s,r,n))}function fg(){return z.backend.floatPrecision()===32?DC:Ex}function mg(e,t,n){let s=!0;if((cn(e)||cn(t))&&(s=!1),cn(e)&&cn(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=Qs(e),i=Qs(t);if(!br(o,i))throw new Error(`Arrays have different shapes. Actual: [${o}]. Expected: [${i}]`)}let r=cn(e)?e:Ta(e),a=cn(t)?t:Ta(t);if(r.length!==a.length)throw new Error(`Arrays have different lengths actual: ${r.length} vs expected: ${a.length}.
+`;return h[h.length-1]=" "+h[h.length-1]+"]"+(a?"":f),h}function nc(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||w5(t,this.size),this.strides=wi(e)}set(e,...t){t.length===0&&(t=[0]),M(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let s of e){if(s<0||s>=this.shape[t]){let r=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(r)}t++}let n=e[e.length-1];for(let s=0;sOh(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=Js().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Oh(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 Js().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Js().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Tl.print(this,e)}clone(){return this.throwIfDisposed(),Tl.clone(this)}toString(e=!1){let t=this.dataSync();return l9(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Tl.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Js().makeVariable(this,e,t,n)}};Object.defineProperty(Ge,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function f9(){return Bm("Tensor",()=>Ge)}f9();var sc=class extends Ge{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(!br(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Js().disposeTensor(this),this.dataId=e.dataId,Js().incRef(this,null)}dispose(){Js().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(sc,Symbol.hasInstance,{value:e=>e instanceof Ge&&e.assign!=null&&e.assign instanceof Function});var $s={};Pe($s,{assertTypesMatch:()=>W5,getTensorsInContainer:()=>Ym,isTensorInList:()=>g9,makeTypesMatch:()=>Ct});var jm;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(jm||(jm={}));var qm;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(qm||(qm={}));var Xm;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(Xm||(Xm={}));var Km;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(Km||(Km={}));var Zm;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(Zm||(Zm={}));var m9={float32:Km,int32:qm,bool:Xm,complex64:Zm};function Cs(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return m9[e][t]}function Mh(e){return Cs(e,"int32")}function Ct(e,t){if(e.dtype===t.dtype)return[e,t];let n=Cs(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function W5(e,t){M(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function g9(e,t){return t.some(n=>n.id===e.id)}function Ym(e){let t=[],n=new Set;return V5(e,t,n),t}function V5(e,t,n){if(e==null)return;if(e instanceof Ge){t.push(e);return}if(!A9(e))return;let s=e;for(let r in s){let a=s[r];n.has(a)||(n.add(a),V5(a,t,n))}}function A9(e){return Array.isArray(e)||typeof e=="object"}function Jm(e){return e.kernelName!=null}var U5=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()}},rc=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new U5}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){Cl(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 $u)&&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 rc.nextTensorId++}nextVariableId(){return rc.nextVariableId++}clone(e){let t=z.runKernel(qa,{x:e}),n={x:e},s=a=>({x:()=>{let o="float32",i={x:a},l={dtype:o};return z.runKernel(Da,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,!(Dh(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=Jm(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(Jm(e)){let{kernelName:p,inputs:f,attrs:m}=e;this.backendName==null&&this.backend;let g=Dh(p,this.backendName);M(g!=null,()=>`Cannot find registered kernel '${p}' 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(p,A,y);let x=y.map(b=>{if(b.rank!=null)return b;let{dataId:v,shape:k,dtype:S}=b;return this.makeTensorFromDataId(v,k,S)});if(s){let b=this.getTensorsForGradient(p,f,x);n=this.saveTensorsForBackwardMode(b)}return x}}else{let{forwardFunc:p}=e,f=m=>{!s||(n=m.map(g=>this.keep(this.clone(g))))};o=()=>{let m=this.backend.numDataIds();i=this.tidy(()=>p(this.backend,f));let g=Array.isArray(i)?i:[i];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,m,g),g}}let{inputs:u,attrs:c}=e,d=Jm(e)?null:e.backwardsFunc,h;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=o():(h=this.profiler.profileKernel(l,u,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(h),t=h.outputs)}),s&&this.addTapeNode(l,u,t,d,n,c),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(u).map(p=>u[p]!=null?u[p].shape:null),outputShapes:t.map(p=>p.shape),kernelTimeMs:h.timeMs,extraInfo:h.extraInfo}),Array.isArray(i)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(n=>this.keep(this.clone(n)))}getTensorsForGradient(e,t,n){let s=Vm(e);if(s!=null){let r=s.inputsToSave||[],a=s.outputsToSave||[],o;s.saveAllInputs?(M(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),o=Object.keys(t).map(l=>t[l])):o=r.map(l=>t[l]);let i=n.filter((l,u)=>a[u]);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"&&Br(e[0])&&(r=e.map(i=>Qu(i)));let a=s.write(r,t,n),o=new Ge(t,n,a,this.nextTensorId());if(this.trackTensor(o,s),n==="string"){let i=this.state.tensorInfo.get(a),l=S5(r);this.state.numBytes+=l-i.bytes,i.bytes=l}return o}makeTensorFromDataId(e,t,n,s){n=n||"float32";let r=new Ge(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 sc(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*Om(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 sc||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*Om(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=Vm(e);i!=null&&(s=i.gradFunc),s!=null&&(o.gradient=l=>(l=l.map((u,c)=>{if(u==null){let d=n[c],h=Xd(d.size,d.dtype);return this.makeTensor(h,d.shape,d.dtype)}return u}),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=Ym(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(M(t.length>0,()=>"gradients() received an empty list of xs."),n!=null&&n.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);let r=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));M(r instanceof Ge,()=>"The result y returned by f() must be a tensor.");let a=o9(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?y9(r.shape):n,i9(o,a,l=>this.tidy(l),x9);let i=t.map(l=>o[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let u of l.saved)u.dispose()}),this.state.activeTape=null),{value:r,grads:i}})}customGrad(e){return M(Wr(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{M(t.every(o=>o instanceof Ge),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,s={};t.forEach((o,i)=>{s[i]=o});let r=(o,i)=>(n=e(...t,i),M(n.value instanceof Ge,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),M(Wr(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),u=Array.isArray(l)?l:[l];M(u.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),M(u.every(d=>d instanceof Ge),()=>"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 c={};return u.forEach((d,h)=>{c[h]=()=>d}),c};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=Ju(),n=await this.backend.time(e);return n.wallMs=Ju()-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 U5;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}};rc.nextTensorId=0;rc.nextVariableId=0;function y9(e){let t=Pm($t(e),"float32");return z.makeTensor(t,e,"float32")}function H5(){let e=_5();if(e._tfengine==null){let t=new R5(e);e._tfengine=new rc(t)}return US(e._tfengine.ENV),d9(()=>e._tfengine),e._tfengine}var z=H5();function x9(e,t){let n={a:e,b:t};return z.runKernel(Vr,n)}var ac={};Pe(ac,{isBrowser:()=>G5,isMobile:()=>v9});function b9(){return typeof navigator!="undefined"&&navigator!=null}function v9(e){if(e||b9()){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 G5(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Fs=Q();Fs.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.")});Fs.registerFlag("IS_BROWSER",()=>G5());Fs.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Fs.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Fs.registerFlag("PROD",()=>!1);Fs.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Fs.getBool("DEBUG"));Fs.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Fs.registerFlag("IS_TEST",()=>!1);Fs.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);Fs.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function Qs(e,t){let n=e;if(cn(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let s=[];for(;Array.isArray(n)||cn(n)&&t!=="string";)s.push(n.length),n=n[0];return Array.isArray(e)&&Q().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&j5(e,s,[]),s}function j5(e,t,n){if(n=n||[],!Array.isArray(e)&&!cn(e)){M(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}M(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),M(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let s=t.slice(1);for(let r=0;r=0&&(r=s),q5(s,r,t,n),e==null||!cn(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=Qs(e,r);!cn(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?Fh(e,r):Ta(e,[],!0);return z.makeTensor(i,a,r)}function oc(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 X5="__op";function W(e){let t=Object.keys(e);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0],s=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+X5;let r=(...a)=>{z.startScope(n);try{let o=s(...a);return zm(o)&&console.error("Cannot return a Promise inside of tidy."),z.endScope(o),o}catch(o){throw z.endScope(null),o}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}function w9(e,t){let n=$(e,"real","complex"),s=$(t,"imag","complex");An(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 z.runKernel(Jd,r)}var qr=W({complex_:w9});function Xr(e,t,n,s){if(s==null&&(s=jd(e)),s==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!cn(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){Mm(t);let r=$t(t),a=$t(n);M(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!cn(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=s!=="string"?Fh(e,s):Ta(e,[],!0),z.makeTensor(e,t,s)}function dn(e,t,n){let s=Qs(e,n);return Xr(e,t,s,n)}var Qm={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},zh=4;async function k9(e,t){let n=[],s=[],r=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);for(let o=0;o{let h=await l.bytes(),p=h.reduce((g,A)=>g+A.length,0)+zh*h.length,f=new Uint8Array(p),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 eg=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function Z5(e){return eg?Buffer.byteLength(e):new Blob([e]).size}function S9(e){if(eg)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 Y5(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 J5(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 ng(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 ic(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:Z5(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:Z5(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function T9(){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 N9(){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 E9(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function R9(){let e=T9(),t=N9(),n=E9();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 Rt=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Rt.instance==null&&(Rt.instance=new Rt),Rt.instance}static registerSaveRouter(e){Rt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Rt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Rt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Rt.getHandlers(e,"load",t)}static getHandlers(e,t,n){let s=[];return(t==="load"?Rt.getInstance().loadRouters:Rt.getInstance().saveRouters).forEach(a=>{let o=a(e,n);o!==null&&s.push(o)}),s}},_9=e=>Rt.registerSaveRouter(e),D9=e=>Rt.registerLoadRouter(e),$9=e=>Rt.getSaveHandlers(e),F9=(e,t)=>Rt.getLoadHandlers(e,t),sg="tensorflowjs",rg=1,_o="models_store",Kr="model_info_store";function Q5(){if(!Q().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 ag(e){let t=e.result;t.createObjectStore(_o,{keyPath:"modelPath"}),t.createObjectStore(Kr,{keyPath:"modelPath"})}var Do=class{constructor(e){if(this.indexedDB=Q5(),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(sg,rg);r.onupgradeneeded=()=>ag(r),r.onsuccess=()=>{let a=r.result;if(t==null){let o=a.transaction(_o,"readonly"),l=o.objectStore(_o).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=u=>(a.close(),s(l.error)),o.oncomplete=()=>a.close()}else{let o=ic(t),i=a.transaction(Kr,"readwrite"),l=i.objectStore(Kr),u=l.put({modelPath:this.modelPath,modelArtifactsInfo:o}),c;u.onsuccess=()=>{c=a.transaction(_o,"readwrite");let h=c.objectStore(_o).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:o});h.onsuccess=()=>n({modelArtifactsInfo:o}),h.onerror=p=>{l=i.objectStore(Kr);let f=l.delete(this.modelPath);f.onsuccess=()=>(a.close(),s(h.error)),f.onerror=m=>(a.close(),s(h.error))}},u.onerror=d=>(a.close(),s(u.error)),i.oncomplete=()=>{c==null?a.close():c.oncomplete=()=>a.close()}}},r.onerror=a=>s(r.error)})}};Do.URL_SCHEME="indexeddb://";var ex=e=>Q().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Do.URL_SCHEME)?O9(e.slice(Do.URL_SCHEME.length)):null;Rt.registerSaveRouter(ex);Rt.registerLoadRouter(ex);function O9(e){return new Do(e)}function P9(e){return e.startsWith(Do.URL_SCHEME)?e.slice(Do.URL_SCHEME.length):e}var M9=class{constructor(){this.indexedDB=Q5()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(sg,rg);n.onupgradeneeded=()=>ag(n),n.onsuccess=()=>{let s=n.result,r=s.transaction(Kr,"readonly"),o=r.objectStore(Kr).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=P9(e),new Promise((t,n)=>{let s=this.indexedDB.open(sg,rg);s.onupgradeneeded=()=>ag(s),s.onsuccess=()=>{let r=s.result,a=r.transaction(Kr,"readwrite"),o=a.objectStore(Kr),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 u=o.delete(e),c=()=>{l=r.transaction(_o,"readwrite");let h=l.objectStore(_o).delete(e);h.onsuccess=()=>t(i.result.modelArtifactsInfo),h.onerror=p=>n(i.error)};u.onsuccess=c,u.onerror=d=>(c(),r.close(),n(i.error))}},i.onerror=u=>(r.close(),n(i.error)),a.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},s.onerror=r=>n(s.error)})}},vr="/",Nl="tensorflowjs_models",tx="info",z9="model_topology",L9="weight_specs",B9="weight_data",W9="model_metadata";function nx(e){return{info:[Nl,e,tx].join(vr),topology:[Nl,e,z9].join(vr),weightSpecs:[Nl,e,L9].join(vr),weightData:[Nl,e,B9].join(vr),modelMetadata:[Nl,e,W9].join(vr)}}function sx(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function V9(e){let t=e.split(vr);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(vr)}function U9(e){return e.startsWith($o.URL_SCHEME)?e.slice($o.URL_SCHEME.length):e}var $o=class{constructor(e){if(!Q().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=nx(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=ic(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,S9(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 sx(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=C9(a),t}};$o.URL_SCHEME="localstorage://";var rx=e=>Q().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith($o.URL_SCHEME)?H9(e.slice($o.URL_SCHEME.length)):null;Rt.registerSaveRouter(rx);Rt.registerLoadRouter(rx);function H9(e){return new $o(e)}var G9=class{constructor(){M(Q().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),M(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Nl+vr,n=vr+tx;for(let s=0;s"scheme must not be undefined or null."),e.endsWith(El)&&(e=e.slice(0,e.indexOf(El))),M(e.length>0,()=>"scheme must not be an empty string.");let n=is.getInstance();M(n.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){let t=this.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(this.getInstance().managers)}};function Lh(e){if(e.indexOf(El)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${is.getSchemes().join(",")}`);return{scheme:e.split(El)[0],path:e.split(El)[1]}}async function ax(e,t,n=!1){M(e!==t,()=>`Old path and new path are the same: '${e}'`);let s=Rt.getLoadHandlers(e);M(s.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),M(s.length<2,()=>`Copying failed because more than one (${s.length}) load handlers for source URL ${e}.`);let r=s[0],a=Rt.getSaveHandlers(t);M(a.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),M(a.length<2,()=>`Copying failed because more than one (${s.length}) save handlers for destination URL ${t}.`);let o=a[0],i=Lh(e).scheme,l=Lh(e).path,u=i===Lh(e).scheme,c=await r.load();n&&u&&await is.getManager(i).removeModel(l);let d=await o.save(c);return n&&!u&&await is.getManager(i).removeModel(l),d.modelArtifactsInfo}async function j9(){let e=is.getSchemes(),t={};for(let n of e){let s=await is.getManager(n).listModels();for(let r in s){let a=n+El+r;t[a]=s[r]}}return t}async function q9(e){let t=Lh(e);return is.getManager(t.scheme).removeModel(t.path)}async function X9(e,t){return ax(e,t,!1)}async function K9(e,t){return ax(e,t,!0)}var Z9=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(Q().get("IS_BROWSER")){Q().setPlatform("browser",new Z9);try{is.registerManager($o.URL_SCHEME,new G9)}catch(e){}try{is.registerManager(Do.URL_SCHEME,new M9)}catch(e){}}var Y9={importFetch:()=>KI()},og,J9=class{constructor(){this.util=vi("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return Q().global.fetch!=null?Q().global.fetch(e,t):(og==null&&(og=Y9.importFetch()),og(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)}};Q().get("IS_NODE")&&Q().setPlatform("node",new J9);function We(e,t="float32",n){return t=t||"float32",Mm(e),new Ut(e,t,n)}function Q9(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 z.runKernel(Da,s,r)}var ce=W({cast_:Q9});function eC(e){let n={x:$(e,"x","clone","string_or_numeric")};return z.runKernel(qa,n)}var Os=W({clone_:eC});function ox(e,t=!1){console.log(e.toString(t))}H5();var tC={buffer:We,cast:ce,clone:Os,print:ox};h9(tC);var _n={};Pe(_n,{browserFiles:()=>lC,browserHTTPRequest:()=>pC,concatenateArrayBuffers:()=>tg,copyModel:()=>X9,decodeWeights:()=>K5,encodeWeights:()=>k9,fromMemory:()=>mC,getLoadHandlers:()=>F9,getModelArtifactsForJSON:()=>ng,getModelArtifactsInfoForJSON:()=>ic,getSaveHandlers:()=>$9,http:()=>ug,isHTTPScheme:()=>lg,listModels:()=>j9,loadWeights:()=>uC,moveModel:()=>K9,registerLoadRouter:()=>D9,registerSaveRouter:()=>_9,removeModel:()=>q9,weightsLoaderFactory:()=>cx,withSaveHandler:()=>gC});var nC="model",sC=".json",rC=".weights.bin";function ix(e){return new Promise(t=>setTimeout(t)).then(e)}var Rl=class{constructor(e){if(!Q().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Rl.URL_SCHEME)&&(e=e.slice(Rl.URL_SCHEME.length)),(e==null||e.length===0)&&(e=nC),this.modelJsonFileName=e+sC,this.weightDataFileName=e+rC}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=J5(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 ix(()=>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 ix(()=>o.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:ic(e)}}}};Rl.URL_SCHEME="downloads://";var aC=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=ng(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,tg(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=>Y5(r.name)),s={};for(let r of e)r.paths.forEach(a=>{let o=Y5(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}},oC=e=>Q().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Rl.URL_SCHEME)?iC(e.slice(Rl.URL_SCHEME.length)):null;Rt.registerSaveRouter(oC);function iC(e="model"){return new Rl(e)}function lC(e){return new aC(e)}function lx(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(u=>{let c=n+ ++r/e.length*(s-n);return t(c),u}),l);function o(l){M(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function i(l,u){M(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),M(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),M(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(e.map(a))}async function ux(e,t){t==null&&(t={});let n=t.fetchFunc==null?Q().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 lx(s,t.onProgress,r,a)).map(d=>d.arrayBuffer()),l=.5,u=1;return t.onProgress==null?await Promise.all(i):await lx(i,t.onProgress,l,u)}async function uC(e,t="",n,s){return cx(o=>ux(o,{requestInit:s}))(e,t,n)}function cx(e){return async(t,n="",s)=>{let r=t.map(()=>!1),a={},o=s!=null?s.map(()=>!1):[],i=[];if(t.forEach((p,f)=>{let m=0;p.weights.forEach(g=>{let A="quantization"in g?g.quantization.dtype:g.dtype,y=Qm[A]*$t(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,v)=>{b===g.name&&(x(),o[v]=!0)}):x(),i.push(g.name),m+=y})}),!o.every(p=>p)){let p=s.filter((f,m)=>!o[m]);throw new Error(`Could not find weights in manifest with names: ${p.join(", ")}.
+Manifest JSON has weights with names: ${i.join(", ")}.`)}let l=r.reduce((p,f,m)=>(f&&p.push(m),p),[]),u=[];l.forEach(p=>{t[p].paths.forEach(f=>{let m=n+(n.endsWith("/")?"":"/")+f;u.push(m)})});let c=await e(u),d={},h=0;return l.forEach(p=>{let f=t[p].paths.length,m=0;for(let b=0;b{let v=g.slice(b.groupOffset,b.groupOffset+b.sizeBytes),k=K5(v,[b.manifestEntry]);for(let S in k)d[S]=k[S]}),h+=f}),d}}var cC="application/octet-stream",dC="application/json",ig=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(M(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=Q().platform.fetch,M(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&M(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],s=J5(e,n);t.body.append("model.json",new Blob([JSON.stringify(s)],{type:dC}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:cC}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:ic(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 ng(t,r=>this.loadWeights(r))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=hC(t),r=this.weightPathPrefix||n,a=[];for(let u of e)a.push(...u.weights);let o=[],i=[];for(let u of e)for(let c of u.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(c)):o.push(r+c+s);this.weightUrlConverter&&o.push(...await Promise.all(i));let l=await ux(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,tg(l)]}};ig.URL_SCHEME_REGEX=/^https?:\/\//;function hC(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),s=e.substring(0,t),r=n>t?e.substring(n):"";return[s+"/",r]}function lg(e){return e.match(ig.URL_SCHEME_REGEX)!=null}var dx=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(s=>lg(s)):n=lg(e),n)return ug(e,t)}return null};Rt.registerSaveRouter(dx);Rt.registerLoadRouter(dx);function ug(e,t){return new ig(e,t)}function pC(e,t){return ug(e,t)}var cg=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},fC=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function mC(e,t,n,s){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new cg(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 cg({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 cg({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:s}))}function gC(e){return new fC(e)}var hx={};Pe(hx,{confusionMatrix:()=>vC});function AC(e,t,n=!1,s=!1){let r=$(e,"a","matMul"),a=$(t,"b","matMul");[r,a]=Ct(r,a);let o={a:r,b:a},i={transposeA:n,transposeB:s};return z.runKernel(_a,o,i)}var Ve=W({matMul_:AC});function yC(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 z.runKernel(ro,a,o)}var lc=W({oneHot_:yC});function xC(e,t){let n=$(e,"x","transpose");if(t==null&&(t=n.shape.map((a,o)=>o).reverse()),M(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(a=>{M(a>=0&&a`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 z.runKernel(Io,s,r)}var Xe=W({transpose_:xC});function bC(e,t,n){let s=$(e,"labels","confusionMatrix"),r=$(t,"predictions","confusionMatrix");M(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),M(s.rank===1,()=>`Expected the rank of labels to be 1, but got ${s.rank}`),M(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),M(s.shape[0]===r.shape[0],()=>`Mismatch in the number of examples: ${s.shape[0]} vs. ${r.shape[0]}. Labels and predictions should have the same number of elements.`),M(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);let a=lc(ce(s,"int32"),n),o=lc(ce(r,"int32"),n),i=Xe(a),l=Ve(i,o);return ce(l,"int32")}var vC=W({confusionMatrix_:bC}),ls={};Pe(ls,{fromPixels:()=>NC,fromPixelsAsync:()=>CC,toPixels:()=>TC});function Bh(e,t,n){if(Ca(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let s=Qs(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 Xr(e,t,s,n)}var _l;function px(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(Dh(_h,z.backendName)!=null){let f={pixels:e},m={numChannels:t};return z.runKernel(_h,f,m)}let[u,c]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height],d;o?d=e.getContext("2d").getImageData(0,0,u,c).data:s||n?d=e.data:(a||r||i)&&(_l==null&&(_l=document.createElement("canvas").getContext("2d")),_l.canvas.width=u,_l.canvas.height=c,_l.drawImage(e,0,0,u,c),d=_l.getImageData(0,0,u,c).data);let h;if(t===4)h=new Int32Array(d);else{let f=u*c;h=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 u=0;u1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${p}.`)}else if(n.dtype==="int32"&&(p<0||p>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${p}.`);a===1?(c[0]=p*i,c[1]=p*i,c[2]=p*i):c[h]=p*i}let d=u*4;l[d+0]=Math.round(c[0]),l[d+1]=Math.round(c[1]),l[d+2]=Math.round(c[2]),l[d+3]=Math.round(c[3])}if(t!=null){t.width=r,t.height=s;let u=t.getContext("2d"),c=new ImageData(l,r,s);u.putImageData(c,0,0)}return n!==e&&n.dispose(),l}var NC=W({fromPixels_:px}),dg={};Pe(dg,{prepareAndValidate:()=>fx});function fx(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($t(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/u),1].slice(0,a);return[l,o,u,c]}var hg={};Pe(hg,{calculateShapes:()=>mx,validateInput:()=>fg,validateUpdateShape:()=>pg});function pg(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;dEC,computeFlatOffset:()=>_C,computeOutShape:()=>gx,getNormalizedAxes:()=>bx,isSliceContinous:()=>RC,maskToAxes:()=>Wh,parseSliceParams:()=>Cx,sliceInfo:()=>DC,startForAxis:()=>Ix,startIndicesWithElidedDims:()=>vx,stopForAxis:()=>Sx,stopIndicesWithElidedDims:()=>wx,stridesForAxis:()=>kx,stridesWithElidedDims:()=>Ax});function EC(e,t,n){let s=e.shape.length;M(s===t.length,()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`),M(s===n.length,()=>`Error in slice${s}D: Length of size ${n} must match the rank of the array (${s}).`);for(let r=0;r`Error in slice${s}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`)}function Wh(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function gx(e,t,n){let s=[];for(let r=0;r0){let p=t[0],f=n+1;c=vx(o,p,f,s,e),d=wx(i,p,f,r,e),h=Ax(a,p,f,e)}else for(let p=0;p-1)a[i]=0;else{let l=yx(t,n,i),u=s[l];e&1<-1)a[i]=Number.MAX_SAFE_INTEGER;else{let l=yx(t,n,i),u=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=Fu(0,o,l-1),o}function Sx(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=Fu(0,o,l):o=Fu(-1,o,l-1),o}function RC(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 _C(e,t){let n=e.length>0?e[e.length-1]:1;for(let s=0;s{M(o!==-1,()=>"slice() does not support negative begin indexing.")});let a;return n==null?a=new Array(r).fill(-1):typeof n=="number"?a=[n,...new Array(r-1).fill(-1)]:n.lengtho>=0?o:(M(o===-1,()=>`Negative size values should be exactly -1 but got ${o} for the slice() size at index ${i}.`),e.shape[i]-s[i])),[s,a]}function DC(e,t,n,s,r,a,o,i,l){let u=t.slice(),c=n.slice(),d=s;s==null&&(d=new Array(u.length));let h=Wh(o);if(h.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 p=e.length-u.length,f=Wh(i),m=e.slice();f.forEach(S=>{u[S]=0,c[S]=1,m.splice(S,0,1)});let{begin:g,end:A,strides:y}=bx(m,h,p,u,c,d,r,a,o);u=g,c=A,d=y;let x=Wh(l);x.forEach(S=>{c[S]=u[S]+1,d[S]=1});let b=gx(u,c,d),v=b.filter((S,C)=>x.indexOf(C)===-1);return{nonStrided:d.every(S=>S===1),$begin:u,$end:c,$strides:d,size:b,newShape:m,outShape:v}}var oe={};Pe(oe,{Serializable:()=>Tx,SerializationMap:()=>Fo,registerClass:()=>Zr});var Tx=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},Fo=class{constructor(){this.classNameMap={}}static getMap(){return Fo.instance==null&&(Fo.instance=new Fo),Fo.instance}static register(e){Fo.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function Zr(e){M(e.className!=null,()=>"Class being registered does not have the static className property defined."),M(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),M(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Fo.register(e)}var Nx={};Pe(Nx,{TEST_EPSILON_FLOAT16:()=>Ex,encodeStrings:()=>Rx,expectArrayBuffersEqual:()=>LC,expectArraysClose:()=>FC,expectArraysEqual:()=>PC,expectNumbersClose:()=>MC,expectPromiseToFail:()=>OC,expectValuesInRange:()=>zC,testEpsilon:()=>mg});var $C=.001,Ex=.1;function FC(e,t,n){return n==null&&(n=mg()),gg(e,t,(s,r)=>Ag(s,r,n))}function mg(){return z.backend.floatPrecision()===32?$C:Ex}function gg(e,t,n){let s=!0;if((cn(e)||cn(t))&&(s=!1),cn(e)&&cn(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=Qs(e),i=Qs(t);if(!br(o,i))throw new Error(`Arrays have different shapes. Actual: [${o}]. Expected: [${i}]`)}let r=cn(e)?e:Ta(e),a=cn(t)?t:Ta(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 OC(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Br(e)||Br(e[0])||Br(t)||Br(t[0])?mg(e,n,(s,r)=>s==r):mg(e,t,(s,r)=>gg(s,r,0))}function PC(e,t,n){if(n==null&&(n=fg()),!gg(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function gg(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function MC(e,t,n){for(let s=0;sn)throw new Error(`Value out of range:${e[s]} low: ${t}, high: ${n}`)}function zC(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function Rx(e){for(let t=0;tn.dispose())}function Jt(e){return z.keep(e)}function HC(e){return z.time(e)}function GC(e){return z.setBackend(e)}function jC(){return z.ready()}function qC(){return z.backendName}function XC(e){z.removeBackend(e)}function yg(e){return z.findBackend(e)}function KC(e){return z.findBackendFactory(e)}function Dl(e,t,n=1){return z.registerBackend(e,t,n)}function Dx(){return z.backend}function ZC(e,t){Q().setPlatform(e,t)}function YC(e,t){let n=$(e,"a","add"),s=$(t,"b","add");[n,s]=Ct(n,s);let r={a:n,b:s};return z.runKernel(Vr,r)}var ae=W({add_:YC});function JC(e,t){let n=$(e,"a","floorDiv"),s=$(t,"b","floorDiv");[n,s]=Ct(n,s);let r={a:n,b:s};return z.runKernel(Ha,r)}var xg=W({floorDiv_:JC});function QC(e,t){let n=$(e,"a","div"),s=$(t,"b","div");if([n,s]=Ct(n,s),n.dtype==="int32"&&s.dtype==="int32")return xg(n,s);let r={a:n,b:s},a={};return z.runKernel(Ba,r,a)}var de=W({div_:QC});function eT(e,t){let n=$(e,"a","mul"),s=$(t,"b","mul");[n,s]=Ct(n,s);let r={a:n,b:s};return z.runKernel(so,r)}var L=W({mul_:eT});function tT(e){let t=$(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return z.runKernel(zu,n)}else{let n={x:t};return z.runKernel(Ii,n)}}var Ht=W({abs_:tT});function nT(e){let n={x:$(e,"x","acos")};return z.runKernel(Si,n)}var $x=W({acos_:nT});function sT(e){let n={x:$(e,"x","acosh")};return z.runKernel(Ci,n)}var Fx=W({acosh_:sT});function rT(e){M(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),M(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((r,a)=>$(r,`tensors${a}`,"addN")),n=t[0];t.forEach(r=>{if(r.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!br(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let s=t;return z.runKernel(Na,s)}var Uh=W({addN_:rT});function aT(e,t=null,n=!1){let r={x:$(e,"x","all","bool")},a={axis:t,keepDims:n};return z.runKernel(Ti,r,a)}var bg=W({all_:aT});function oT(e,t=null,n=!1){let r={x:$(e,"x","any","bool")},a={axis:t,keepDims:n};return z.runKernel(Ni,r,a)}var Hh=W({any_:oT});function iT(e,t=0){let s={x:$(e,"x","argMax")},r={axis:t};return z.runKernel(Ea,s,r)}var er=W({argMax_:iT});function lT(e,t=0){let s={x:$(e,"x","argMin")},r={axis:t};return z.runKernel(Pu,s,r)}var Ox=W({argMin_:lT});function uT(e){let n={x:$(e,"x","asin")};return z.runKernel(Ei,n)}var Px=W({asin_:uT});function cT(e){let n={x:$(e,"x","asinh")};return z.runKernel(Ri,n)}var Mx=W({asinh_:cT});function dT(e){let n={x:$(e,"x","atan")};return z.runKernel(_i,n)}var zx=W({atan_:dT});function hT(e,t){let n=$(e,"a","atan2"),s=$(t,"b","atan2");[n,s]=Ct(n,s);let r={a:n,b:s};return z.runKernel($i,r)}var Lx=W({atan2_:hT});function pT(e){let n={x:$(e,"x","atanh")};return z.runKernel(Di,n)}var Bx=W({atanh_:pT});function fT(e,t,n,s,r="NHWC",a){let o=e[3],i=[...t,o],l=Ux(r);return uc(e,i,n,a,s,null,null,l)}function Wx(e,t,n,s,r,a,o="channelsLast"){let[i,l]=Gh(t),u;if(o==="channelsLast")u=[i,l,e[3],e[3]];else if(o==="channelsFirst")u=[i,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return uc(e,u,n,s,r,a,!1,o)}function mT(e,t,n,s,r,a,o="NDHWC"){let[i,l,u]=wg(t),c,d;if(o==="NDHWC")d="channelsLast",c=[i,l,u,e[4],e[4]];else if(o==="NCDHW")d="channelsFirst",c=[i,l,u,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return Vx(e,c,n,s,r,!1,d,a)}function uc(e,t,n,s,r,a,o=!1,i="channelsLast"){let[l,u,c,d]=[-1,-1,-1,-1];if(i==="channelsLast")[l,u,c,d]=e;else if(i==="channelsFirst")[l,d,u,c]=e;else throw new Error(`Unknown dataFormat ${i}`);let[h,p,,f]=t,[m,g]=Gh(n),[A,y]=Gh(s),x=$l(h,A),b=$l(p,y),{padInfo:v,outHeight:k,outWidth:S}=yT(r,u,c,m,g,x,b,a,i),C=o?f*d:f,_;return i==="channelsFirst"?_=[l,C,k,S]:i==="channelsLast"&&(_=[l,k,S,C]),{batchSize:l,dataFormat:i,inHeight:u,inWidth:c,inChannels:d,outHeight:k,outWidth:S,outChannels:C,padInfo:v,strideHeight:m,strideWidth:g,filterHeight:h,filterWidth:p,effectiveFilterHeight:x,effectiveFilterWidth:b,dilationHeight:A,dilationWidth:y,inShape:e,outShape:_,filterShape:t}}function Vx(e,t,n,s,r,a=!1,o="channelsLast",i){let[l,u,c,d,h]=[-1,-1,-1,-1,-1];if(o==="channelsLast")[l,u,c,d,h]=e;else if(o==="channelsFirst")[l,h,u,c,d]=e;else throw new Error(`Unknown dataFormat ${o}`);let[p,f,m,,g]=t,[A,y,x]=wg(n),[b,v,k]=wg(s),S=$l(p,b),C=$l(f,v),_=$l(m,k),{padInfo:O,outDepth:E,outHeight:R,outWidth:T}=xT(r,u,c,d,A,y,x,S,C,_,i),P=a?g*h:g,V;return o==="channelsFirst"?V=[l,P,E,R,T]:o==="channelsLast"&&(V=[l,E,R,T,P]),{batchSize:l,dataFormat:o,inDepth:u,inHeight:c,inWidth:d,inChannels:h,outDepth:E,outHeight:R,outWidth:T,outChannels:P,padInfo:O,strideDepth:A,strideHeight:y,strideWidth:x,filterDepth:p,filterHeight:f,filterWidth:m,effectiveFilterDepth:S,effectiveFilterHeight:C,effectiveFilterWidth:_,dilationDepth:b,dilationHeight:v,dilationWidth:k,inShape:e,outShape:V,filterShape:t}}function gT(e,t,n,s,r){s==null&&(s=vg(e,t,n));let a=e[0],o=e[1],i=Oo((a-t+2*s)/n+1,r),l=Oo((o-t+2*s)/n+1,r);return[i,l]}function AT(e,t,n,s,r,a){r==null&&(r=vg(e,t,s));let o=e[0],i=e[1],l=e[2],u=Oo((o-t+2*r)/s+1,a),c=Oo((i-t+2*r)/s+1,a),d=Oo((l-t+2*r)/s+1,a);return[u,c,d,n]}function vg(e,t,n,s=1){let r=$l(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 wg(e){return typeof e=="number"?[e,e,e]:e}function $l(e,t){return t<=1?e:e+(e-1)*(t-1)}function yT(e,t,n,s,r,a,o,i,l){let u,c,d;if(typeof e=="number"){u={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let p=gT([t,n],a,s,e,i);c=p[0],d=p[1]}else if(e==="same"){c=Math.ceil(t/s),d=Math.ceil(n/r);let h=Math.max(0,(c-1)*s+a-t),p=Math.max(0,(d-1)*r+o-n),f=Math.floor(h/2),m=h-f,g=Math.floor(p/2),A=p-g;u={top:f,bottom:m,left:g,right:A,type:"SAME"}}else if(e==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-a+1)/s),d=Math.ceil((n-o+1)/r);else if(typeof e=="object"){let h=l==="channelsLast"?e[1][0]:e[2][0],p=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];u={top:h,bottom:p,left:f,right:m,type:h===0&&p===0&&f===0&&m===0?"VALID":"EXPLICIT"},c=Oo((t-a+h+p)/s+1,i),d=Oo((n-o+f+m)/r+1,i)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outHeight:c,outWidth:d}}function xT(e,t,n,s,r,a,o,i,l,u,c){let d,h,p,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=AT([t,n,s,1],i,1,r,e,c);h=g[0],p=g[1],f=g[2]}else if(e==="same"){h=Math.ceil(t/r),p=Math.ceil(n/a),f=Math.ceil(s/o);let m=(h-1)*r+i-t,g=(p-1)*a+l-n,A=(f-1)*o+u-s,y=Math.floor(m/2),x=m-y,b=Math.floor(g/2),v=g-b,k=Math.floor(A/2),S=A-k;d={top:b,bottom:v,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"},h=Math.ceil((t-i+1)/r),p=Math.ceil((n-l+1)/a),f=Math.ceil((s-u+1)/o);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:d,outDepth:h,outHeight:p,outWidth:f}}function Oo(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 Yr(e){let[t,n,s]=Gh(e);return t===1&&n===1&&s===1}function tr(e,t){return Yr(e)||Yr(t)}function Ux(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function bT(e,t){let s={x:$(e,"x","reshape","string_or_numeric")},r={shape:t};return z.runKernel(ul,s,r)}var U=W({reshape_:bT});function vT(e,t,n,s,r){let a=$(e,"x","avgPool","float32"),o=1;M(tr(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=U(a,[1,a.shape[0],a.shape[1],a.shape[2]])),M(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),r!=null&&M(Zt(s),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let u={x:i},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r},d=z.runKernel(Ra,u,c);return d=ce(d,a.dtype),l?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var jh=W({avgPool_:vT});function wT(e,t,n,s,r,a="NDHWC"){let o=$(e,"x","avgPool3d","float32"),i=o,l=!1;o.rank===4&&(l=!0,i=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),M(i.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`),M(a==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),r!=null&&M(Zt(s),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let u={x:i},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},d=z.runKernel(Mu,u,c);return d=ce(d,i.dtype),l?U(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var kg=W({avgPool3d_:wT});function kT(e,t=0){M(e.length>=1,()=>"Pass at least one tensor to concat");let n=oc(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 Os(n[0]);let s=n,r={axis:t};return z.runKernel(Oi,s,r)}var ft=W({concat_:kT});function IT(e){let n={x:$(e,"x","sigmoid")};return z.runKernel(go,n)}var Hn=W({sigmoid_:IT});function ST(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 z.runKernel(pl,r,a)}var Re=W({slice_:ST});function CT(e){let n={x:$(e,"x","tanh")};return z.runKernel(ko,n)}var Fl=W({tanh_:CT});function TT(e,t,n,s,r,a){let o=$(e,"forgetBias","basicLSTMCell"),i=$(t,"lstmKernel","basicLSTMCell"),l=$(n,"lstmBias","basicLSTMCell"),u=$(s,"data","basicLSTMCell"),c=$(r,"c","basicLSTMCell"),d=$(a,"h","basicLSTMCell"),h=ft([u,d],1),p=Ve(h,i),f=ae(p,l),m=f.shape[0],g=f.shape[1]/4,A=[m,g],y=Re(f,[0,0],A),x=Re(f,[0,g],A),b=Re(f,[0,g*2],A),v=Re(f,[0,g*3],A),k=ae(L(Hn(y),Fl(x)),L(c,Hn(ae(o,b)))),S=L(Fl(k),Hn(v));return[k,S]}var NT=W({basicLSTMCell_:TT});function ET(e,t,n){let s=$(e,"x","batchToSpaceND"),r=t.reduce((i,l)=>i*l);M(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),M(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),M(s.shape[0]%r==0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`);let a={x:s},o={blockShape:t,crops:n};return z.runKernel(Fi,a,o)}var qh=W({batchToSpaceND_:ET});function RT(e){let t;return e.rank===0||e.rank===1?t=U(e,[1,1,1,e.size]):e.rank===2?t=U(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function _T(e,t,n,s,r,a){a==null&&(a=.001);let o=$(e,"x","batchNorm"),i=$(t,"mean","batchNorm"),l=$(n,"variance","batchNorm"),u;r!=null&&(u=$(r,"scale","batchNorm"));let c;s!=null&&(c=$(s,"offset","batchNorm")),M(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),M(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),M(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let h={x:RT(o),scale:u,offset:c,mean:i,variance:l},p={varianceEpsilon:a},f=z.runKernel(Ga,h,p);return U(f,o.shape)}var Ol=W({batchNorm_:_T});function DT(e,t,n,s,r,a){let o=$(e,"x","batchNorm"),i=$(t,"mean","batchNorm"),l=$(n,"variance","batchNorm"),u;r!=null&&(u=$(r,"scale","batchNorm"));let c;return s!=null&&(c=$(s,"offset","batchNorm")),M(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),M(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),M(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&M(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),c!=null&&M(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`),Ol(o,i,l,c,u,a)}var Hx=W({batchNorm2d_:DT});function $T(e,t,n,s,r,a){let o=$(e,"x","batchNorm"),i=$(t,"mean","batchNorm"),l=$(n,"variance","batchNorm"),u;r!=null&&(u=$(r,"scale","batchNorm"));let c;return s!=null&&(c=$(s,"offset","batchNorm")),M(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),M(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),M(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&M(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),c!=null&&M(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`),Ol(o,i,l,c,u,a)}var Gx=W({batchNorm3d_:$T});function FT(e,t,n,s,r,a){let o=$(e,"x","batchNorm"),i=$(t,"mean","batchNorm"),l=$(n,"variance","batchNorm"),u;r!=null&&(u=$(r,"scale","batchNorm"));let c;return s!=null&&(c=$(s,"offset","batchNorm")),M(o.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),M(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),M(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&M(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),c!=null&&M(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`),Ol(o,i,l,c,u,a)}var jx=W({batchNorm4d_:FT});function OT(e,t,n){let s=$(e,"x","bincount"),r=$(t,"weights","bincount");M(s.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`),M(n>=0,()=>`size must be non-negative, but got ${n}.`),M(r.size===s.size||r.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${r.shape}.`);let a={x:s,weights:r},o={size:n};return z.runKernel(Yd,a,o)}var Ig=W({bincount_:OT});function PT(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 z.runKernel(Bm,r)}var qx=W({broadcastArgs_:PT});function MT(e,t){let n=$(e,"broadcastTo","x"),s=n.shape;if(t.some(u=>!(u>0)||u%1!=0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.lengthn.rank){let u=n.shape.slice();for(;u.length=0;u--)if(r[u]===t[u])a[u]=1;else if(n.shape[u]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);if(a.map((u,c)=>u>1?c:-1).filter(u=>u>=0).length===0)return Os(n);let i={x:n},l={reps:a};return z.runKernel(Hr,i,l)}var cc=W({broadcastTo_:MT});function zT(e){let n={x:$(e,"x","ceil")};return z.runKernel($a,n)}var Xx=W({ceil_:zT});function LT(e,t,n){let s=$(e,"x","clipByValue");M(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);let r={x:s},a={clipValueMin:t,clipValueMax:n};return z.runKernel(Ur,r,a)}var Gn=W({clipByValue_:LT});function BT(e){return ft(e,0)}var Kx=W({concat1d_:BT});function WT(e,t){return ft(e,t)}var Pl=W({concat2d_:WT});function VT(e,t){return ft(e,t)}var Zx=W({concat3d_:VT});function UT(e,t){return ft(e,t)}var Yx=W({concat4d_:UT});function HT(e,t,n,s,r="NHWC",a=[1,1],o){let i=$(e,"x","conv2d"),l=$(t,"filter","conv2d"),u=i,c=!1;i.rank===3&&(c=!0,u=U(i,[1,i.shape[0],i.shape[1],i.shape[2]])),M(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),M(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),o!=null&&M(Zt(s),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let d=r==="NHWC"?u.shape[3]:u.shape[1];M(d===l.shape[2],()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${l.shape[2]}.`),M(tr(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let h={x:u,filter:l},p={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},f=z.runKernel(Fa,h,p);return c?U(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Jr=W({conv2d_:HT});function GT(e,t,n,s,r="NWC",a=1,o){let i=$(e,"x","conv1d"),l=$(t,"filter","conv1d"),u=i,c=!1;i.rank===2&&(c=!0,u=U(i,[1,i.shape[0],i.shape[1]])),M(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),M(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),o!=null&&M(Zt(s),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`),M(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),M(tr(n,a),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`),M(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);let d=U(l,[1,l.shape[0],l.shape[1],l.shape[2]]),h=U(u,[u.shape[0],1,u.shape[1],u.shape[2]]),g=Jr(h,d,[1,n],s,"NHWC",[1,a],o);return c?U(g,[g.shape[2],g.shape[3]]):U(g,[g.shape[0],g.shape[2],g.shape[3]])}var Sg=W({conv1d_:GT});function jT(e,t,n,s,r,a="NHWC",o){M(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let i=e,l=t,u=!1;t.rank===3&&(u=!0,l=U(t,[1,t.shape[0],t.shape[1],t.shape[2]]),i=[1,e[0],e[1],e[2]]),M(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),M(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),M(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);let c=a==="NHWC"?i[3]:i[1],d=a==="NHWC"?l.shape[3]:l.shape[1];M(c===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[2]}.`),M(d===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${n.shape[3]}.`),o!=null&&M(Zt(r),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let h={dy:l,filter:n},p={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,inputShape:i},f=z.runKernel(Oa,h,p);return u?U(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Cg=W({conv2DBackpropInput_:jT});function qT(e,t,n,s,r,a){let o=$(e,"x","conv2dTranspose"),i=$(t,"filter","conv2dTranspose");return Cg(n,o,i,s,r,"NHWC",a)}var Tg=W({conv2dTranspose_:qT});function XT(e,t,n,s,r="NDHWC",a=[1,1,1]){let o=$(e,"x","conv3d"),i=$(t,"filter","conv3d"),l=o,u=!1;o.rank===4&&(u=!0,l=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),M(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),M(i.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`),M(l.shape[4]===i.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${i.shape[3]}.`),M(tr(n,a),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),M(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`);let c={x:l,filter:i},d={strides:n,pad:s,dataFormat:r,dilations:a},h=z.runKernel(Lu,c,d);return u?U(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var Ng=W({conv3d_:XT});function KT(e,t,n,s,r){M(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let a=e,o=t,i=!1;t.rank===4&&(i=!0,o=U(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],u=o.shape[4];M(a.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`),M(o.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),M(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),M(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),M(u===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${n.shape[4]}.`);let c={dy:o,filter:n},d={pad:r,strides:s,inputShape:a},h=z.runKernel(th,c,d);return i?U(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var Jx=W({conv3DBackpropInput_:KT});function ZT(e,t,n,s,r){let a=$(e,"x","conv3dTranspose"),o=$(t,"filter","conv3dTranspose");return Jx(n,a,o,s,r)}var Qx=W({conv3dTranspose_:ZT});function YT(e){let n={x:$(e,"x","cos")};return z.runKernel(Pa,n)}var Xh=W({cos_:YT});function JT(e){let n={x:$(e,"x","cosh")};return z.runKernel(Ma,n)}var Eg=W({cosh_:JT});function QT(e,t=0,n=!1,s=!1){let a={x:$(e,"x","cumsum")},o={axis:t,exclusive:n,reverse:s};return z.runKernel(za,a,o)}var Rg=W({cumsum_:QT});function eN(e,t,n,s=!1){let r=$(e,"x","denseBincount"),a=$(t,"weights","denseBincount");M(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),M(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),M(n>=0,()=>`size must be non-negative, but got ${n}.`),M(a.size===r.size||a.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${a.shape}.`);let o={x:r,weights:a},i={size:n,binaryOutput:s};return z.runKernel(nh,o,i)}var eb=W({denseBincount_:eN});function tN(e,t,n="NHWC"){let s=$(e,"x","depthToSpace"),r=n==="NHWC"?s.shape[1]:s.shape[2],a=n==="NHWC"?s.shape[2]:s.shape[3],o=n==="NHWC"?s.shape[3]:s.shape[1];M(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying
+Expected: ${a}.`)}}function OC(e,t){e().then(()=>t.fail(),()=>t())}function PC(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Br(e)||Br(e[0])||Br(t)||Br(t[0])?gg(e,n,(s,r)=>s==r):gg(e,t,(s,r)=>Ag(s,r,0))}function MC(e,t,n){if(n==null&&(n=mg()),!Ag(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function Ag(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function zC(e,t,n){for(let s=0;sn)throw new Error(`Value out of range:${e[s]} low: ${t}, high: ${n}`)}function LC(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function Rx(e){for(let t=0;tn.dispose())}function Jt(e){return z.keep(e)}function GC(e){return z.time(e)}function jC(e){return z.setBackend(e)}function qC(){return z.ready()}function XC(){return z.backendName}function KC(e){z.removeBackend(e)}function xg(e){return z.findBackend(e)}function ZC(e){return z.findBackendFactory(e)}function Dl(e,t,n=1){return z.registerBackend(e,t,n)}function Dx(){return z.backend}function YC(e,t){Q().setPlatform(e,t)}function JC(e,t){let n=$(e,"a","add"),s=$(t,"b","add");[n,s]=Ct(n,s);let r={a:n,b:s};return z.runKernel(Vr,r)}var ae=W({add_:JC});function QC(e,t){let n=$(e,"a","floorDiv"),s=$(t,"b","floorDiv");[n,s]=Ct(n,s);let r={a:n,b:s};return z.runKernel(Ha,r)}var bg=W({floorDiv_:QC});function eT(e,t){let n=$(e,"a","div"),s=$(t,"b","div");if([n,s]=Ct(n,s),n.dtype==="int32"&&s.dtype==="int32")return bg(n,s);let r={a:n,b:s},a={};return z.runKernel(Ba,r,a)}var de=W({div_:eT});function tT(e,t){let n=$(e,"a","mul"),s=$(t,"b","mul");[n,s]=Ct(n,s);let r={a:n,b:s};return z.runKernel(so,r)}var L=W({mul_:tT});function nT(e){let t=$(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return z.runKernel(zu,n)}else{let n={x:t};return z.runKernel(Ii,n)}}var Ht=W({abs_:nT});function sT(e){let n={x:$(e,"x","acos")};return z.runKernel(Si,n)}var $x=W({acos_:sT});function rT(e){let n={x:$(e,"x","acosh")};return z.runKernel(Ci,n)}var Fx=W({acosh_:rT});function aT(e){M(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),M(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((r,a)=>$(r,`tensors${a}`,"addN")),n=t[0];t.forEach(r=>{if(r.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!br(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let s=t;return z.runKernel(Na,s)}var Uh=W({addN_:aT});function oT(e,t=null,n=!1){let r={x:$(e,"x","all","bool")},a={axis:t,keepDims:n};return z.runKernel(Ti,r,a)}var vg=W({all_:oT});function iT(e,t=null,n=!1){let r={x:$(e,"x","any","bool")},a={axis:t,keepDims:n};return z.runKernel(Ni,r,a)}var Hh=W({any_:iT});function lT(e,t=0){let s={x:$(e,"x","argMax")},r={axis:t};return z.runKernel(Ea,s,r)}var er=W({argMax_:lT});function uT(e,t=0){let s={x:$(e,"x","argMin")},r={axis:t};return z.runKernel(Pu,s,r)}var Ox=W({argMin_:uT});function cT(e){let n={x:$(e,"x","asin")};return z.runKernel(Ei,n)}var Px=W({asin_:cT});function dT(e){let n={x:$(e,"x","asinh")};return z.runKernel(Ri,n)}var Mx=W({asinh_:dT});function hT(e){let n={x:$(e,"x","atan")};return z.runKernel(_i,n)}var zx=W({atan_:hT});function pT(e,t){let n=$(e,"a","atan2"),s=$(t,"b","atan2");[n,s]=Ct(n,s);let r={a:n,b:s};return z.runKernel($i,r)}var Lx=W({atan2_:pT});function fT(e){let n={x:$(e,"x","atanh")};return z.runKernel(Di,n)}var Bx=W({atanh_:fT});function mT(e,t,n,s,r="NHWC",a){let o=e[3],i=[...t,o],l=Ux(r);return uc(e,i,n,a,s,null,null,l)}function Wx(e,t,n,s,r,a,o="channelsLast"){let[i,l]=Gh(t),u;if(o==="channelsLast")u=[i,l,e[3],e[3]];else if(o==="channelsFirst")u=[i,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return uc(e,u,n,s,r,a,!1,o)}function gT(e,t,n,s,r,a,o="NDHWC"){let[i,l,u]=kg(t),c,d;if(o==="NDHWC")d="channelsLast",c=[i,l,u,e[4],e[4]];else if(o==="NCDHW")d="channelsFirst",c=[i,l,u,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return Vx(e,c,n,s,r,!1,d,a)}function uc(e,t,n,s,r,a,o=!1,i="channelsLast"){let[l,u,c,d]=[-1,-1,-1,-1];if(i==="channelsLast")[l,u,c,d]=e;else if(i==="channelsFirst")[l,d,u,c]=e;else throw new Error(`Unknown dataFormat ${i}`);let[h,p,,f]=t,[m,g]=Gh(n),[A,y]=Gh(s),x=$l(h,A),b=$l(p,y),{padInfo:v,outHeight:k,outWidth:S}=xT(r,u,c,m,g,x,b,a,i),C=o?f*d:f,_;return i==="channelsFirst"?_=[l,C,k,S]:i==="channelsLast"&&(_=[l,k,S,C]),{batchSize:l,dataFormat:i,inHeight:u,inWidth:c,inChannels:d,outHeight:k,outWidth:S,outChannels:C,padInfo:v,strideHeight:m,strideWidth:g,filterHeight:h,filterWidth:p,effectiveFilterHeight:x,effectiveFilterWidth:b,dilationHeight:A,dilationWidth:y,inShape:e,outShape:_,filterShape:t}}function Vx(e,t,n,s,r,a=!1,o="channelsLast",i){let[l,u,c,d,h]=[-1,-1,-1,-1,-1];if(o==="channelsLast")[l,u,c,d,h]=e;else if(o==="channelsFirst")[l,h,u,c,d]=e;else throw new Error(`Unknown dataFormat ${o}`);let[p,f,m,,g]=t,[A,y,x]=kg(n),[b,v,k]=kg(s),S=$l(p,b),C=$l(f,v),_=$l(m,k),{padInfo:O,outDepth:E,outHeight:R,outWidth:T}=bT(r,u,c,d,A,y,x,S,C,_,i),P=a?g*h:g,V;return o==="channelsFirst"?V=[l,P,E,R,T]:o==="channelsLast"&&(V=[l,E,R,T,P]),{batchSize:l,dataFormat:o,inDepth:u,inHeight:c,inWidth:d,inChannels:h,outDepth:E,outHeight:R,outWidth:T,outChannels:P,padInfo:O,strideDepth:A,strideHeight:y,strideWidth:x,filterDepth:p,filterHeight:f,filterWidth:m,effectiveFilterDepth:S,effectiveFilterHeight:C,effectiveFilterWidth:_,dilationDepth:b,dilationHeight:v,dilationWidth:k,inShape:e,outShape:V,filterShape:t}}function AT(e,t,n,s,r){s==null&&(s=wg(e,t,n));let a=e[0],o=e[1],i=Oo((a-t+2*s)/n+1,r),l=Oo((o-t+2*s)/n+1,r);return[i,l]}function yT(e,t,n,s,r,a){r==null&&(r=wg(e,t,s));let o=e[0],i=e[1],l=e[2],u=Oo((o-t+2*r)/s+1,a),c=Oo((i-t+2*r)/s+1,a),d=Oo((l-t+2*r)/s+1,a);return[u,c,d,n]}function wg(e,t,n,s=1){let r=$l(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 kg(e){return typeof e=="number"?[e,e,e]:e}function $l(e,t){return t<=1?e:e+(e-1)*(t-1)}function xT(e,t,n,s,r,a,o,i,l){let u,c,d;if(typeof e=="number"){u={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let p=AT([t,n],a,s,e,i);c=p[0],d=p[1]}else if(e==="same"){c=Math.ceil(t/s),d=Math.ceil(n/r);let h=Math.max(0,(c-1)*s+a-t),p=Math.max(0,(d-1)*r+o-n),f=Math.floor(h/2),m=h-f,g=Math.floor(p/2),A=p-g;u={top:f,bottom:m,left:g,right:A,type:"SAME"}}else if(e==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-a+1)/s),d=Math.ceil((n-o+1)/r);else if(typeof e=="object"){let h=l==="channelsLast"?e[1][0]:e[2][0],p=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];u={top:h,bottom:p,left:f,right:m,type:h===0&&p===0&&f===0&&m===0?"VALID":"EXPLICIT"},c=Oo((t-a+h+p)/s+1,i),d=Oo((n-o+f+m)/r+1,i)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outHeight:c,outWidth:d}}function bT(e,t,n,s,r,a,o,i,l,u,c){let d,h,p,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=yT([t,n,s,1],i,1,r,e,c);h=g[0],p=g[1],f=g[2]}else if(e==="same"){h=Math.ceil(t/r),p=Math.ceil(n/a),f=Math.ceil(s/o);let m=(h-1)*r+i-t,g=(p-1)*a+l-n,A=(f-1)*o+u-s,y=Math.floor(m/2),x=m-y,b=Math.floor(g/2),v=g-b,k=Math.floor(A/2),S=A-k;d={top:b,bottom:v,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"},h=Math.ceil((t-i+1)/r),p=Math.ceil((n-l+1)/a),f=Math.ceil((s-u+1)/o);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:d,outDepth:h,outHeight:p,outWidth:f}}function Oo(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 Yr(e){let[t,n,s]=Gh(e);return t===1&&n===1&&s===1}function tr(e,t){return Yr(e)||Yr(t)}function Ux(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function vT(e,t){let s={x:$(e,"x","reshape","string_or_numeric")},r={shape:t};return z.runKernel(ul,s,r)}var U=W({reshape_:vT});function wT(e,t,n,s,r){let a=$(e,"x","avgPool","float32"),o=1;M(tr(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=U(a,[1,a.shape[0],a.shape[1],a.shape[2]])),M(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),r!=null&&M(Zt(s),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let u={x:i},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r},d=z.runKernel(Ra,u,c);return d=ce(d,a.dtype),l?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var jh=W({avgPool_:wT});function kT(e,t,n,s,r,a="NDHWC"){let o=$(e,"x","avgPool3d","float32"),i=o,l=!1;o.rank===4&&(l=!0,i=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),M(i.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`),M(a==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),r!=null&&M(Zt(s),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let u={x:i},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},d=z.runKernel(Mu,u,c);return d=ce(d,i.dtype),l?U(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var Ig=W({avgPool3d_:kT});function IT(e,t=0){M(e.length>=1,()=>"Pass at least one tensor to concat");let n=oc(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 Os(n[0]);let s=n,r={axis:t};return z.runKernel(Oi,s,r)}var ft=W({concat_:IT});function ST(e){let n={x:$(e,"x","sigmoid")};return z.runKernel(go,n)}var Hn=W({sigmoid_:ST});function CT(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 z.runKernel(pl,r,a)}var Re=W({slice_:CT});function TT(e){let n={x:$(e,"x","tanh")};return z.runKernel(ko,n)}var Fl=W({tanh_:TT});function NT(e,t,n,s,r,a){let o=$(e,"forgetBias","basicLSTMCell"),i=$(t,"lstmKernel","basicLSTMCell"),l=$(n,"lstmBias","basicLSTMCell"),u=$(s,"data","basicLSTMCell"),c=$(r,"c","basicLSTMCell"),d=$(a,"h","basicLSTMCell"),h=ft([u,d],1),p=Ve(h,i),f=ae(p,l),m=f.shape[0],g=f.shape[1]/4,A=[m,g],y=Re(f,[0,0],A),x=Re(f,[0,g],A),b=Re(f,[0,g*2],A),v=Re(f,[0,g*3],A),k=ae(L(Hn(y),Fl(x)),L(c,Hn(ae(o,b)))),S=L(Fl(k),Hn(v));return[k,S]}var ET=W({basicLSTMCell_:NT});function RT(e,t,n){let s=$(e,"x","batchToSpaceND"),r=t.reduce((i,l)=>i*l);M(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),M(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),M(s.shape[0]%r==0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`);let a={x:s},o={blockShape:t,crops:n};return z.runKernel(Fi,a,o)}var qh=W({batchToSpaceND_:RT});function _T(e){let t;return e.rank===0||e.rank===1?t=U(e,[1,1,1,e.size]):e.rank===2?t=U(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function DT(e,t,n,s,r,a){a==null&&(a=.001);let o=$(e,"x","batchNorm"),i=$(t,"mean","batchNorm"),l=$(n,"variance","batchNorm"),u;r!=null&&(u=$(r,"scale","batchNorm"));let c;s!=null&&(c=$(s,"offset","batchNorm")),M(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),M(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),M(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let h={x:_T(o),scale:u,offset:c,mean:i,variance:l},p={varianceEpsilon:a},f=z.runKernel(Ga,h,p);return U(f,o.shape)}var Ol=W({batchNorm_:DT});function $T(e,t,n,s,r,a){let o=$(e,"x","batchNorm"),i=$(t,"mean","batchNorm"),l=$(n,"variance","batchNorm"),u;r!=null&&(u=$(r,"scale","batchNorm"));let c;return s!=null&&(c=$(s,"offset","batchNorm")),M(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),M(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),M(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&M(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),c!=null&&M(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`),Ol(o,i,l,c,u,a)}var Hx=W({batchNorm2d_:$T});function FT(e,t,n,s,r,a){let o=$(e,"x","batchNorm"),i=$(t,"mean","batchNorm"),l=$(n,"variance","batchNorm"),u;r!=null&&(u=$(r,"scale","batchNorm"));let c;return s!=null&&(c=$(s,"offset","batchNorm")),M(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),M(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),M(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&M(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),c!=null&&M(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`),Ol(o,i,l,c,u,a)}var Gx=W({batchNorm3d_:FT});function OT(e,t,n,s,r,a){let o=$(e,"x","batchNorm"),i=$(t,"mean","batchNorm"),l=$(n,"variance","batchNorm"),u;r!=null&&(u=$(r,"scale","batchNorm"));let c;return s!=null&&(c=$(s,"offset","batchNorm")),M(o.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),M(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),M(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&M(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),c!=null&&M(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`),Ol(o,i,l,c,u,a)}var jx=W({batchNorm4d_:OT});function PT(e,t,n){let s=$(e,"x","bincount"),r=$(t,"weights","bincount");M(s.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`),M(n>=0,()=>`size must be non-negative, but got ${n}.`),M(r.size===s.size||r.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${r.shape}.`);let a={x:s,weights:r},o={size:n};return z.runKernel(Yd,a,o)}var Sg=W({bincount_:PT});function MT(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 z.runKernel(Wm,r)}var qx=W({broadcastArgs_:MT});function zT(e,t){let n=$(e,"broadcastTo","x"),s=n.shape;if(t.some(u=>!(u>0)||u%1!=0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.lengthn.rank){let u=n.shape.slice();for(;u.length=0;u--)if(r[u]===t[u])a[u]=1;else if(n.shape[u]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);if(a.map((u,c)=>u>1?c:-1).filter(u=>u>=0).length===0)return Os(n);let i={x:n},l={reps:a};return z.runKernel(Hr,i,l)}var cc=W({broadcastTo_:zT});function LT(e){let n={x:$(e,"x","ceil")};return z.runKernel($a,n)}var Xx=W({ceil_:LT});function BT(e,t,n){let s=$(e,"x","clipByValue");M(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);let r={x:s},a={clipValueMin:t,clipValueMax:n};return z.runKernel(Ur,r,a)}var Gn=W({clipByValue_:BT});function WT(e){return ft(e,0)}var Kx=W({concat1d_:WT});function VT(e,t){return ft(e,t)}var Pl=W({concat2d_:VT});function UT(e,t){return ft(e,t)}var Zx=W({concat3d_:UT});function HT(e,t){return ft(e,t)}var Yx=W({concat4d_:HT});function GT(e,t,n,s,r="NHWC",a=[1,1],o){let i=$(e,"x","conv2d"),l=$(t,"filter","conv2d"),u=i,c=!1;i.rank===3&&(c=!0,u=U(i,[1,i.shape[0],i.shape[1],i.shape[2]])),M(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),M(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),o!=null&&M(Zt(s),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let d=r==="NHWC"?u.shape[3]:u.shape[1];M(d===l.shape[2],()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${l.shape[2]}.`),M(tr(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let h={x:u,filter:l},p={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},f=z.runKernel(Fa,h,p);return c?U(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Jr=W({conv2d_:GT});function jT(e,t,n,s,r="NWC",a=1,o){let i=$(e,"x","conv1d"),l=$(t,"filter","conv1d"),u=i,c=!1;i.rank===2&&(c=!0,u=U(i,[1,i.shape[0],i.shape[1]])),M(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),M(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),o!=null&&M(Zt(s),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`),M(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),M(tr(n,a),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`),M(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);let d=U(l,[1,l.shape[0],l.shape[1],l.shape[2]]),h=U(u,[u.shape[0],1,u.shape[1],u.shape[2]]),g=Jr(h,d,[1,n],s,"NHWC",[1,a],o);return c?U(g,[g.shape[2],g.shape[3]]):U(g,[g.shape[0],g.shape[2],g.shape[3]])}var Cg=W({conv1d_:jT});function qT(e,t,n,s,r,a="NHWC",o){M(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let i=e,l=t,u=!1;t.rank===3&&(u=!0,l=U(t,[1,t.shape[0],t.shape[1],t.shape[2]]),i=[1,e[0],e[1],e[2]]),M(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),M(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),M(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);let c=a==="NHWC"?i[3]:i[1],d=a==="NHWC"?l.shape[3]:l.shape[1];M(c===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[2]}.`),M(d===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${n.shape[3]}.`),o!=null&&M(Zt(r),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let h={dy:l,filter:n},p={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,inputShape:i},f=z.runKernel(Oa,h,p);return u?U(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Tg=W({conv2DBackpropInput_:qT});function XT(e,t,n,s,r,a){let o=$(e,"x","conv2dTranspose"),i=$(t,"filter","conv2dTranspose");return Tg(n,o,i,s,r,"NHWC",a)}var Ng=W({conv2dTranspose_:XT});function KT(e,t,n,s,r="NDHWC",a=[1,1,1]){let o=$(e,"x","conv3d"),i=$(t,"filter","conv3d"),l=o,u=!1;o.rank===4&&(u=!0,l=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),M(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),M(i.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`),M(l.shape[4]===i.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${i.shape[3]}.`),M(tr(n,a),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),M(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`);let c={x:l,filter:i},d={strides:n,pad:s,dataFormat:r,dilations:a},h=z.runKernel(Lu,c,d);return u?U(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var Eg=W({conv3d_:KT});function ZT(e,t,n,s,r){M(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let a=e,o=t,i=!1;t.rank===4&&(i=!0,o=U(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],u=o.shape[4];M(a.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`),M(o.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),M(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),M(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),M(u===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${n.shape[4]}.`);let c={dy:o,filter:n},d={pad:r,strides:s,inputShape:a},h=z.runKernel(th,c,d);return i?U(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var Jx=W({conv3DBackpropInput_:ZT});function YT(e,t,n,s,r){let a=$(e,"x","conv3dTranspose"),o=$(t,"filter","conv3dTranspose");return Jx(n,a,o,s,r)}var Qx=W({conv3dTranspose_:YT});function JT(e){let n={x:$(e,"x","cos")};return z.runKernel(Pa,n)}var Xh=W({cos_:JT});function QT(e){let n={x:$(e,"x","cosh")};return z.runKernel(Ma,n)}var Rg=W({cosh_:QT});function eN(e,t=0,n=!1,s=!1){let a={x:$(e,"x","cumsum")},o={axis:t,exclusive:n,reverse:s};return z.runKernel(za,a,o)}var _g=W({cumsum_:eN});function tN(e,t,n,s=!1){let r=$(e,"x","denseBincount"),a=$(t,"weights","denseBincount");M(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),M(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),M(n>=0,()=>`size must be non-negative, but got ${n}.`),M(a.size===r.size||a.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${a.shape}.`);let o={x:r,weights:a},i={size:n,binaryOutput:s};return z.runKernel(nh,o,i)}var eb=W({denseBincount_:tN});function nN(e,t,n="NHWC"){let s=$(e,"x","depthToSpace"),r=n==="NHWC"?s.shape[1]:s.shape[2],a=n==="NHWC"?s.shape[2]:s.shape[3],o=n==="NHWC"?s.shape[3]:s.shape[1];M(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${r} and ${t} for depthToSpace with input shape
${s.shape}`),M(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${a} and ${t} for depthToSpace with input shape
- ${s.shape}`),M(o%(t*t)==0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${s.shape}`);let i={x:s},l={blockSize:t,dataFormat:n};return z.runKernel(Mi,i,l)}var tb=W({depthToSpace_:tN});function nN(e,t,n,s,r="NHWC",a=[1,1],o){let i=$(e,"x","depthwiseConv2d"),l=$(t,"filter","depthwiseConv2d"),u=i,c=!1;i.rank===3&&(c=!0,u=U(i,[1,i.shape[0],i.shape[1],i.shape[2]])),M(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),M(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),M(u.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),o!=null&&M(Zt(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let d={x:u,filter:l},h={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},p=z.runKernel(La,d,h);return c?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var dc=W({depthwiseConv2d_:nN});function sN(e){let n={x:$(e,"x","diag")};return z.runKernel(ah,n)}var rN=W({diag_:sN});function aN(e,t,n,s,r=[1,1],a="NHWC"){let o=$(e,"x","dilation2d"),i=$(t,"filter","dilation2d");M(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),M(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),M(a==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);let l=o,u=!1;o.rank===3&&(l=U(o,[1,o.shape[0],o.shape[1],o.shape[2]]),u=!0);let c={x:l,filter:i},d={strides:n,pad:s,dilations:r},h=z.runKernel(Bu,c,d);return u?U(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var nb=W({dilation2d_:aN});function oN(e,t){let n=e.length,s=[];for(let r=0;r1&&o===1&&s.unshift(a)}return s}function Gt(e,t){let n=[];for(let s=0;s1)&&n.unshift(a)}return n}function At(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(M(r===a,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${a}.`),n.rank===1&&s.rank===1){let o=U(n,[1,-1]),i=U(s,[-1,1]),l=Ve(o,i);return U(l,[])}else if(n.rank===1&&s.rank===2){let o=U(n,[1,-1]),i=U(s,[s.shape[0],s.shape[1]]),l=Ve(o,i);return U(l,[l.size])}else if(n.rank===2&&s.rank===1){let o=U(s,[-1,1]),i=Ve(n,o);return U(i,[i.size])}else{let o=U(s,[s.shape[0],s.shape[1]]);return Ve(n,o)}}var hN=W({dot_:dN});function pN(e,...t){let n=t.map((r,a)=>$(r,`tensors${a}`,"einsum")),s={equation:e};return z.runKernel(lh,n,s)}var rb=W({einsum_:pN});function fN(e){let n={x:$(e,"x","elu")};return z.runKernel(Wa,n)}var hc=W({elu_:fN});function mN(e){let t=$(e,"x","erf");M(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=ce(t,"float32"));let n={x:t};return z.runKernel(zi,n)}var ab=W({erf_:mN});function gN(e){let n={x:$(e,"x","exp")};return z.runKernel(Va,n)}var cs=W({exp_:gN});function AN(e,t=0){let n=$(e,"x","expandDims","string_or_numeric");M(t<=n.rank,()=>"Axis must be <= rank of the tensor");let s={input:n},r={dim:t};return z.runKernel(Bi,s,r)}var Ot=W({expandDims_:AN});function yN(e){let n={x:$(e,"x","expm1")};return z.runKernel(Wi,n)}var ob=W({expm1_:yN});function xN(e,t){let n=$(e,"x","tile","string_or_numeric");M(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);let s={x:n},r={reps:t};return z.runKernel(Hr,s,r)}var Ts=W({tile_:xN});function bN(e,t,n,s="float32"){t==null&&(t=e);let r=We([e,t],s),a=e<=t?e:t;for(let i=0;i`Error in localResponseNormalization: x must be rank 3 or 4 but got
- rank ${a.rank}.`),M(Zt(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=a,i=!1;a.rank===3&&(i=!0,o=U(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let l={x:o},u={depthRadius:t,bias:n,alpha:s,beta:r},c=z.runKernel(Hu,l,u);return i?U(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var ub=W({localResponseNormalization_:FN});function ON(e){let n={x:$(e,"x","log")};return z.runKernel(Ka,n)}var ds=W({log_:ON});function PN(e){let n={x:$(e,"x","log1p")};return z.runKernel(Yi,n)}var Yh=W({log1p_:PN});function MN(e){return M(Wr(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 z.tidy(()=>{let{value:a,grads:o}=z.gradients(()=>e(s),[s],r);return r!=null&&An(a.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Jh(o),o[0]})}}function zN(e){return M(Wr(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{M(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let s=oc(t,"args","tf.grads","string_or_numeric"),r=n!=null?$(n,"dy","tf.grads"):null;return z.tidy(()=>{let{value:a,grads:o}=z.gradients(()=>e(...s),s,r);return r!=null&&An(a.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Jh(o),o})}}function LN(e){return M(Wr(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{M(t instanceof Ge,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),M(n==null||n instanceof Ge,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:s,value:r}=z.gradients(()=>e(t),[t],n);return Jh(s),{grad:s[0],value:r}}}function BN(e){return M(Wr(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{M(Array.isArray(t)&&t.every(r=>r instanceof Ge),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),M(n==null||n instanceof Ge,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let s=z.gradients(()=>e(...t),t,n);return n!=null&&An(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Jh(s.grads),s}}function cb(e,t){M(Wr(e),()=>"The f passed in variableGrads(f) must be a function"),M(t==null||Array.isArray(t)&&t.every(u=>u instanceof sc),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let u in z.registeredVariables)t.push(z.registeredVariables[u])}let s=n?t.filter(u=>!u.trainable):null,r=t.length;t=t.filter(u=>u.trainable),M(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);let a=!0,{value:o,grads:i}=z.gradients(e,t,null,a);M(i.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),M(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);let l={};return t.forEach((u,c)=>{i[c]!=null&&(l[u.name]=i[c])}),s!=null&&s.forEach(u=>l[u.name]=null),{value:o,grads:l}}function nr(e){return z.customGrad(e)}function Jh(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 WN(e){let n={x:$(e,"x","neg")};return z.runKernel(el,n)}var Tt=W({neg_:WN});function VN(e){let n={x:$(e,"x","softplus")};return z.runKernel(gl,n)}var Ll=W({softplus_:VN});function UN(e){let t=$(e,"x","logSigmoid");return nr(s=>({value:Tt(Ll(Tt(s))),gradFunc:o=>L(o,Hn(Tt(s)))}))(t)}var HN=W({logSigmoid_:UN});function GN(e,t=null,n=!1){let r={x:$(e,"x","max")},a={reductionIndices:t,keepDims:n};return z.runKernel(Za,r,a)}var hs=W({max_:GN});function jN(e,t){let n=$(e,"a","sub"),s=$(t,"b","sub");[n,s]=Ct(n,s);let r={a:n,b:s};return z.runKernel(vo,r)}var ge=W({sub_:jN});function qN(e,t=null,n=!1){let s=$(e,"x","sum");s.dtype==="bool"&&(s=ce(s,"int32"));let r={x:s},a={axis:t,keepDims:n};return z.runKernel(yo,r,a)}var ve=W({sum_:qN});function XN(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 nr((r,a)=>{let o=!0,i=hs(r,t,!0),l=ge(r,i),u=ge(ce(l,"float32"),ds(ve(cs(l),t,o)));return a([u]),{value:u,gradFunc:(d,h)=>{let[p]=h,f=!0,m=cs(p);return ge(d,L(ve(d,t,f),m))}}})(n)}var $g=W({logSoftmax_:XN});function Fg(e,t){for(let n=0;ne[a]);return[n,r]}function zo(e,t){let n=t.map(s=>1);return db(e,n,t)}function KN(e,t,n){M(Fg(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function pb(e,t){if(Fg(e,t))return null;let n=[];for(let s=0;sn.push(s)),n}function Og(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function ZN(e,t){let n=[];for(let s=t-e;s`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),M(tr(n,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),r!=null&&M(Zt(s),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let u={x:i},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r},d=z.runKernel(Ja,u,c);return l?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var ep=W({maxPool_:sE});function rE(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=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),M(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),M(a==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),r!=null&&M(Zt(s),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let u={x:i},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},d=z.runKernel(Gu,u,c);return l?U(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var Mg=W({maxPool3d_:rE});function aE(e,t,n,s,r=!1){let o={x:$(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:s,includeBatchInIndex:r},l=z.runKernel(Ah,o,i);return{result:l[0],indexes:l[1]}}var mb=W({maxPoolWithArgmax_:aE});function oE(e,t){let n=$(e,"a","maximum"),s=$(t,"b","maximum");[n,s]=Ct(n,s),n.dtype==="bool"&&(n=ce(n,"int32"),s=ce(s,"int32")),At(n.shape,s.shape);let r={a:n,b:s};return z.runKernel(Ya,r)}var kr=W({maximum_:oE});function iE(e,t=null,n=!1){let r={x:$(e,"x","mean")},a={axis:t,keepDims:n};return z.runKernel(Qa,r,a)}var _t=W({mean_:iE});function Pt(e,t="float32"){if(t==="complex64"){let s=Pt(e,"float32"),r=Pt(e,"float32");return qr(s,r)}let n=Xd($t(e),t);return z.makeTensor(n,e,t)}function qn(e,t="float32"){if(t==="complex64"){let s=qn(e,"float32"),r=Pt(e,"float32");return qr(s,r)}let n=Om($t(e),t);return z.makeTensor(n,e,t)}function lE(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 Ge?e.dtype:"float32");if(t===void 0)return[s];let r=$(t,"y","meshgrid",t instanceof Ge?t.dtype:"float32"),a=$t(s.shape),o=$t(r.shape);return n==="xy"?(s=U(s,[1,-1]),r=U(r,[-1,1]),[Ve(qn([o,1],s.dtype),s),Ve(r,qn([1,a],r.dtype))]):(s=U(s,[-1,1]),r=U(r,[1,-1]),[Ve(s,qn([1,o],s.dtype)),Ve(qn([a,1],r.dtype),r)])}function uE(e,t=null,n=!1){let r={x:$(e,"x","min")},a={axis:t,keepDims:n};return z.runKernel(eo,r,a)}var tp=W({min_:uE});function cE(e,t){let n=$(e,"a","minimum"),s=$(t,"b","minimum");[n,s]=Ct(n,s),n.dtype==="bool"&&(n=ce(n,"int32"),s=ce(s,"int32")),At(n.shape,s.shape);let r={a:n,b:s};return z.runKernel(to,r)}var fc=W({minimum_:cE});function dE(e,t,n){M(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let s=$(e,"x","mirrorPad");if(s.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");M(t.length===s.rank,()=>`Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`);let r=n==="reflect"?1:0;for(let i=0;i"Invalid number of paddings. Must be length of 2 each."),M(t[i][0]>=0&&t[i][0]<=s.shape[i]-r&&t[i][1]>=0&&t[i][1]<=s.shape[i]-r,()=>`Padding in dimension ${i} cannot be greater than or equal to ${s.shape[i]-r} or less than 0 for input of shape ${s.shape}`);let a={paddings:t,mode:n},o={x:s};return z.runKernel(no,o,a)}var gb=W({mirrorPad_:dE});function hE(e,t){let n=$(e,"a","mod"),s=$(t,"b","mod");[n,s]=Ct(n,s);let r={a:n,b:s};return z.runKernel(Qi,r)}var Ab=W({mod_:hE});function pE(e){let t=$(e,"x","square"),n={};return z.runKernel("Square",{x:t},n)}var ct=W({square_:pE});function fE(e,t=null,n=!1){e=$(e,"x","moments");let s=Ss(t,e.shape),r=_t(e,s,n),a=r.shape;n||(a=zo(r.shape,s));let o=ct(ge(ce(e,"float32"),U(r,a))),i=_t(o,s,n);return{mean:r,variance:i}}var np=W({moments_:fE});function mE(e,t,n,s){let r=$(t,"data","multiRNNCell"),a=oc(n,"c","multiRNNCell"),o=oc(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?U(r,[1,-1]):r},u={numSamples:t,seed:n,normalized:s},c=z.runKernel(yh,l,u);return o===1?U(c,[c.size]):c}var yb=W({multinomial_:AE});function yE(e,t){let n=$(e,"a","notEqual","string_or_numeric"),s=$(t,"b","notEqual","string_or_numeric");[n,s]=Ct(n,s),At(n.shape,s.shape);let r={a:n,b:s};return z.runKernel(tl,r)}var Bl=W({notEqual_:yE});function xE(e){let n={x:$(e,"x","onesLike")};return z.runKernel(al,n)}var ps=W({onesLike_:xE});function bE(e,t){let n=$(e,"v1","outerProduct"),s=$(t,"v2","outerProduct");M(n.rank===1&&s.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${s.rank}.`);let r=U(n,[-1,1]),a=U(s,[1,-1]);return Ve(r,a)}var vE=W({outerProduct_:bE});function wE(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 z.runKernel(ao,a,r)}var Qr=W({pad_:wE});function kE(e,t,n=0){return M(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),Qr(e,[t],n)}var IE=W({pad1d_:kE});function SE(e,t,n=0){return M(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Qr(e,t,n)}var CE=W({pad2d_:SE});function TE(e,t,n=0){return M(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Qr(e,t,n)}var NE=W({pad3d_:TE});function EE(e,t,n=0){return M(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Qr(e,t,n)}var RE=W({pad4d_:EE});function _E(e,t,n){let s=$(e,"x","spaceToBatchND");M(s.rank>=1+t.length,()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`),M(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),M(s.shape.reduce((o,i,l)=>l>0&&l<=t.length?o&&(i+n[l-1][0]+n[l-1][1])%t[l-1]==0:o,!0),()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);let r={x:s},a={blockShape:t,paddings:n};return z.runKernel(Al,r,a)}var sp=W({spaceToBatchND_:_E});function DE(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=U(o,[1,o.shape[0],o.shape[1],o.shape[2]])),M(tr(a,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${r}'`);let u=Wx(i.shape,t,a,r,s),c=[u.dilationHeight,u.dilationWidth],d;s==="same"?d=FE([u.filterHeight,u.filterWidth],c):d=[[0,0],[0,0]];let h=c[0]===1&&c[1]===1,[p,f]=$E([u.inHeight,u.inWidth],c,d),m=h?s:"valid",g=h?i:sp(i,c,p),y=(n==="avg"?()=>jh(g,t,a,m):()=>ep(g,t,a,m))(),x=h?y:qh(y,c,f);return l?U(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function $E(e,t,n){let s=n.map(c=>c[0]),r=n.map(c=>c[1]),a=e.concat(s,r),o=t.map((c,d)=>(c-a[d]%c)%c),i=r.map((c,d)=>c+o[d]),l=t.map((c,d)=>[s[d],i[d]]),u=t.map((c,d)=>[0,o[d]]);return[l,u]}function FE(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 OE=W({pool_:DE});function PE(e,t){let n=$(e,"base","pow"),s=$(t,"exp","pow");[n,s]=Ct(n,s);let r={a:n,b:s};return z.runKernel(oo,r)}var ea=W({pow_:PE});function ME(e,t){let n=$(e,"x","prelu"),s=$(t,"alpha","prelu"),r={x:n,alpha:s};return z.runKernel(io,r)}var rp=W({prelu_:ME});function zE(e,t=null,n=!1){let s=$(e,"x","prod");s.dtype==="bool"&&(s=ce(s,"int32"));let r={x:s},a={axis:t,keepDims:n};return z.runKernel(il,r,a)}var zg=W({prod_:zE});function LE(e,t,n){let s=$t(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}},WE=class{constructor(e,t,n,s){this.alpha=e,this.beta=1/t,this.dtype=n;let r=s||Math.random();this.randu=Lg.alea(r.toString()),this.randn=new Bg(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=Lg.alea(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function UE(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 WE(t,n,s,r),o=We(e,s);for(let i=0;i`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),fs(t,0)}var QE=W({reverse1d_:JE});function eR(e,t){let n=$(e,"x","reverse");return M(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),fs(n,t)}var tR=W({reverse2d_:eR});function nR(e,t){let n=$(e,"x","reverse");return M(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),fs(n,t)}var sR=W({reverse3d_:nR});function rR(e,t){let n=$(e,"x","reverse");return M(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),fs(n,t)}var aR=W({reverse4d_:rR});function oR(e){let n={x:$(e,"x","round")};return z.runKernel(po,n)}var Vg=W({round_:oR});function iR(e){let n={x:$(e,"x","rsqrt")};return z.runKernel(fo,n)}var Ug=W({rsqrt_:iR});function Ie(e,t){if((cn(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"&&cn(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Xr(e,[],[],t)}function lR(e){let n={x:$(e,"x","selu")};return z.runKernel(hl,n)}var Hg=W({selu_:lR});function uR(e,t,n,s,r,a=[1,1],o="NHWC"){let i=$(e,"x","separableConv2d"),l=$(t,"depthwiseFilter","separableConv2d"),u=$(n,"pointwiseFilter","separableConv2d"),c=i,d=!1;if(i.rank===3&&(d=!0,c=U(i,[1,i.shape[0],i.shape[1],i.shape[2]])),o==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");M(c.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`),M(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),M(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),M(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),M(u.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);let h=l.shape[2],p=l.shape[3];M(u.shape[2]===h*p,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${h*p}, but got ${u.shape[2]}.`);let f=dc(c,l,s,r,o,a),g=Jr(f,u,1,"valid",o);return d?U(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var vb=W({separableConv2d_:uR});async function cR(e,t){let n=$(e,"x","setdiff1d"),s=$(t,"y","setdiff1d");M(n.dtype===s.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`),M(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),M(s.rank===1,()=>`y should be 1D tensor, but got y (${s.shape}).`);let r=await n.data(),a=await s.data(),o=new Set(a),i=0;for(let c=0;c`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),Re(s,[t],[n])}var ap=W({slice1d_:fR});function mR(e,t,n){let s=$(e,"x","slice2d");return M(s.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),Re(s,t,n)}var qg=W({slice2d_:mR});function gR(e,t,n){let s=$(e,"x","slice3d");return M(s.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),Re(s,t,n)}var op=W({slice3d_:gR});function AR(e,t,n){let s=$(e,"x","slice4d");return M(s.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),Re(s,t,n)}var gc=W({slice4d_:AR});function yR(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 z.runKernel(xo,s,r)}var ip=W({softmax_:yR});function xR(e){M(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return z.runKernel(ch,t)}var lp=W({fft_:xR});function bR(e){M(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return z.runKernel(dh,t)}var Ac=W({ifft_:bR});function vR(e){let t=e.shape[e.shape.length-1],n=e.size/t,s;if(t<=2){let r=U(e,[n,t]);s=Ac(r)}else{let r=[n,2*(t-1)],a=U(mc(e),[n,t]),o=U(Kh(e),[n,t]),i=fs(Re(a,[0,1],[n,t-2]),1),l=L(fs(Re(o,[0,1],[n,t-2]),1),Ie(-1)),u=ft([a,i],1),c=ft([o,l],1),d=U(qr(u,c),[r[0],r[1]]);s=Ac(d)}if(s=mc(s),e.rank===3&&e.shape[0]!==0){let r=s,a=e.shape[0];s=U(s,[a,s.shape[0]/a,s.shape[1]]),r.dispose()}return s}var Xg=W({irfft_:vR});function wR(e,t,n=0){let r={x:$(e,"x","split")},a={numOrSizeSplits:t,axis:n};return z.runKernel(yl,r,a)}var an=W({split_:wR});function kR(e,t){M(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1],s=e.size/n,r;if(t!=null&&t0),m=e.shape.map(g=>g);m[e.shape.length-1]=t,r=Re(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=ft([e,Pt(f)],e.shape.length-1),n=t}else r=e;let a=Ke(r),o=U(qr(r,a),[s,n]),i=lp(o),l=Math.floor(n/2)+1,u=mc(i),c=Kh(i),d=an(u,[l,n-l],u.shape.length-1),h=an(c,[l,n-l],c.shape.length-1),p=r.shape.slice();return p[r.shape.length-1]=l,U(qr(d[0],h[0]),p)}var up=W({rfft_:kR});function IR(e){let n={x:$(e,"x","sqrt")};return z.runKernel(Ao,n)}var hn=W({sqrt_:IR});function SR(e,t){let n=$(e,"a","squaredDifference"),s=$(t,"b","squaredDifference");[n,s]=Ct(n,s),At(n.shape,s.shape);let r={a:n,b:s},a={};return z.runKernel(bo,r,a)}var Kg=W({squaredDifference_:SR});function CR(e,t){let n=$(e,"x","squeeze");return U(n,b5(n.shape,t).newShape)}var lt=W({squeeze_:CR});function TR(e,t=0){let n=oc(e,"tensors","stack","string_or_numeric");M(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&M(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let s=n,r={axis:t};return z.runKernel(ol,s,r)}var Dn=W({stack_:TR});function NR(e,t=0){let s={x:$(e,"x","step")},r={alpha:t};return z.runKernel(Gr,s,r)}var yc=W({step_:NR});function ER(e,t,n,s,r=0,a=0,o=0,i=0,l=0){let c={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 z.runKernel(xl,c,d)}var Ib=W({stridedSlice_:ER});function RR(e){let n={x:$(e,"x","tan")};return z.runKernel(wo,n)}var Sb=W({tan_:RR});function Mt(e,t){Ca(e);let n=Qs(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Xr(e,null,n,t)}function Ms(e,t,n){if(Ca(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let s=Qs(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 Xr(e,t,s,n)}function _R(e,t,n){if(Ca(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let s=Qs(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 Xr(e,t,s,n)}function DR(e,t,n){if(Ca(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let s=Qs(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 Xr(e,t,s,n)}function $R(e,t,n){if(Ca(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let s=Qs(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,Xr(e,t,s,n)}function FR(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]=z.runKernel(bl,a,o);return{values:i,indices:l}}var Cb=W({topk_:FR});function OR(e,t=0,n=1,s,r){if(s!=null&&s==="bool")throw new Error("Unsupported data type $ { dtype }");let a=new Bg(t,n,s,!0,r),o=We(e,s);for(let i=0;i0,()=>"The input tensor must be at least 1D");let s={x:n},r={axis:t},[a,o]=z.runKernel(Rh,s,r);return{values:a,indices:o}}var Zg=W({unique_:PR});function MR(e,t,n){let s=$(e,"x","unsortedSegmentSum"),r=$(t,"segmentIds","unsortedSegmentSum","int32");M(Zt(n),()=>"numSegments must be of dtype int");let a={x:s,segmentIds:r},o={numSegments:n};return z.runKernel(Ku,a,o)}var Tb=W({unsortedSegmentSum_:MR});function zR(e,t=0){let n=$(e,"x","unstack","string_or_numeric");M(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);let s={value:n},r={axis:t};return z.runKernel(wl,s,r)}var ms=W({unstack_:zR});function Nb(e,t=!0,n,s){return z.makeVariable(e,t,n,s)}function Eb(e,t){let n=[];for(let a=0;a0,()=>"mask cannot be scalar"),An(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=Ie(1),u=ge(l,i),c=L(ge(o,a),u);if(r){M(s!=null,()=>"When using zeroDebias: true, step is required.");let d=$(s,"step","movingAverage");c=de(c,ge(l,ea(i,d)))}return ae(a,c)}var HR=W({movingAverage_:UR});function GR(e,t,n){let s=$(e,"indices","scatterND","int32"),r=$(t,"updates","scatterND");pg(r,s,n);let a={indices:s,updates:r},o={shape:n};return z.runKernel(cl,a,o)}var _b=W({scatterND_:GR});function jR(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 qR(e,t,n,s=0){let r=$(e,"sparseIndices","sparseToDense","int32"),a=$(t,"sparseValues","sparseToDense"),o=$(s,"defaultValue","sparseToDense",a.dtype);jR(r,a,n,o);let i={sparseIndices:r,sparseValues:a,defaultValue:o},l={outputShape:n};return z.runKernel(Ch,i,l)}var Qg=W({sparseToDense_:qR});function XR(e,t){let n=$(t,"indices","gatherND","int32"),r={params:$(e,"x","gatherND","string_or_numeric"),indices:n};return z.runKernel(Hi,r)}var Db=W({gatherND_:XR});function KR(e,t){if(t==null)return e.shape.slice();if(br(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.`),M(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof Ge?r.clone():r;let a=KR(r,n),o=1-t,i=de(pc(ae(Wl(a,0,1,"float32",s),o)),o);return L(r,i)}var $b=W({dropout_:ZR});function Fb(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function eA(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}`),M(s.rank-1===r.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${s.rank} and targets rank ${r.rank}`),An(s.shape.slice(0,s.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let a=s.shape[s.shape.length-1];M(n>0&&n<=a,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`);let o=await s.data(),i=await r.data(),[l,u]=[o.length/a,a],c=v5("bool",l);for(let d=0;dg.value-m.value),c[d]=0;for(let m=0;mt_,depthwiseConv2d:()=>a_,matMul:()=>i_});function QR(e,t,n,s,r,a="NHWC",o){let i=e;e.rank===3&&(i=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=U(t,[1,t.shape[0],t.shape[1],t.shape[2]])),M(i.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),M(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),M(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);let u=a==="NHWC"?i.shape[3]:i.shape[1],c=a==="NHWC"?l.shape[3]:l.shape[1];M(u===n[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${n[2]}.`),M(c===n[3],()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${n[3]}).`),o!=null&&M(Zt(r),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let d={x:i,dy:l},h={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,filterShape:n};return z.runKernel(Qd,d,h)}var tA=W({conv2DBackpropFilter_:QR});function dp(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return L(e,yc(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function hp(e,t){let n=t,s=Gt(e.shape,t.shape);return s.length>0&&(n=ve(n,s)),U(n,e.shape)}function pp(e,t,n,s){if(t==="linear")return e;if(t==="relu")return sr(e);if(t==="elu")return hc(e);if(t==="relu6")return Wg(e);if(t==="prelu")return rp(e,n);if(t==="leakyrelu")return Zh(e,s);if(t==="sigmoid")return Hn(e);throw new Error(`Unknown fused activation ${t}.`)}var fp=(e,t)=>!(e>0)||t==="linear";function e_({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(l=l||"linear",fp(z.state.gradientDepth,l)===!1){let v=Jr(e,t,n,s,r,a,o);return i!=null&&(v=ae(v,i)),pp(v,l,u,c)}let d=$(e,"x","conv2d"),h=$(t,"filter","conv2d"),p=d,f=!1;d.rank===3&&(f=!0,p=U(d,[1,d.shape[0],d.shape[1],d.shape[2]])),M(p.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${p.rank}.`),M(h.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${h.rank}.`),o!=null&&M(Zt(s),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`),M(p.shape[3]===h.shape[2],()=>`Error in conv2d: depth of input (${p.shape[3]}) must match input depth for filter ${h.shape[2]}.`),M(tr(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),M(r==="NHWC",()=>`Error in conv2d: got dataFormat of ${r} but only NHWC is currently supported.`);let m=uc(p.shape,h.shape,n,a,s,o),g;i!=null&&(g=$(i,"bias","fused conv2d"),[g]=Ct(g,d),At(m.outShape,g.shape));let A;u!=null&&(A=$(u,"prelu weights","fused conv2d"));let y=(v,k)=>{let[S,C,_,O]=k,E=dp(v,_,l);M(Yr(a),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);let R=Cg(C.shape,E,S,n,s),T=tA(C,E,S.shape,n,s),P=[R,T];if(O!=null){let V=hp(O,E);P.push(V)}return P},x={x:p,filter:h,bias:g,preluActivationWeights:A},b={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:c};return i==null?nr((k,S,C)=>{let _=z.runKernel(Co,x,b);return C([S,k,_]),f&&(_=U(_,[_.shape[1],_.shape[2],_.shape[3]])),{value:_,gradFunc:y}})(p,h):nr((k,S,C,_)=>{let O=z.runKernel(Co,x,b);return _([S,k,O,C]),f&&(O=U(O,[O.shape[1],O.shape[2],O.shape[3]])),{value:O,gradFunc:y}})(p,h,g)}var t_=W({fusedConv2d_:e_});function n_(e,t,n,s,r,a=[1,1],o){let i=e;e.rank===3&&(i=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=U(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={x:i,dy:l},c={strides:s,pad:r,dimRoundingMode:o,dilations:a,filterShape:n};return z.runKernel(sh,u,c)}var Ob=W({depthwiseConv2dNativeBackpropFilter_:n_});function s_(e,t,n,s,r,a=[1,1],o){let i=t,l=!1;t.rank===3&&(l=!0,i=U(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={dy:i,filter:n},c={strides:s,pad:r,dimRoundingMode:o,dilations:a,inputShape:e},d=z.runKernel(rh,u,c);return l?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Pb=W({depthwiseConv2dNativeBackpropInput_:s_});function r_({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(fp(z.state.gradientDepth,l)===!1){let v=dc(e,t,n,s,r,a,o);return i!=null&&(v=ae(v,i)),pp(v,l,u,c)}let d=$(e,"x","depthwiseConv2d"),h=$(t,"filter","depthwiseConv2d"),p=d,f=!1;d.rank===3&&(f=!0,p=U(d,[1,d.shape[0],d.shape[1],d.shape[2]])),M(p.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${p.rank}.`),M(h.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`),M(p.shape[3]===h.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${p.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`),a==null&&(a=[1,1]),M(tr(n,a),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o!=null&&M(Zt(s),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${o} but got pad ${s}.`);let m=uc(p.shape,h.shape,n,a,s,o,!0),g;i!=null&&(g=$(i,"bias","fused conv2d"),[g]=Ct(g,d),At(m.outShape,g.shape));let A;u!=null&&(A=$(u,"prelu weights","fused depthwiseConv2d"));let y=(v,k)=>{M(Yr(a),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);let[S,C,_,O]=k,E=dp(v,_,l),R=Pb(C.shape,E,S,n,s,a,o),T=Ob(C,E,S.shape,n,s,a,o);if(O!=null){let P=hp(g,E);return[R,T,P]}return[R,T]},x={x:p,filter:h,bias:g,preluActivationWeights:A},b={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:c};return i==null?nr((k,S,C)=>{let _=z.runKernel(To,x,b);return C([S,k,_]),f&&(_=U(_,[_.shape[1],_.shape[2],_.shape[3]])),{value:_,gradFunc:y}})(p,h):nr((k,S,C,_)=>{let O=z.runKernel(To,x,b);return _([S,k,O,C]),f&&(O=U(O,[O.shape[1],O.shape[2],O.shape[3]])),{value:O,gradFunc:y}})(p,h,g)}var a_=W({fusedDepthwiseConv2d_:r_});function o_({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:r,activation:a="linear",preluActivationWeights:o,leakyreluAlpha:i}){if(fp(z.state.gradientDepth,a)===!1){let O=Ve(e,t,n,s);return r!=null&&(O=ae(O,r)),pp(O,a,o,i)}let l=$(e,"a","fused matMul"),u=$(t,"b","fused matMul");[l,u]=Ct(l,u);let c=n?l.shape[l.rank-2]:l.shape[l.rank-1],d=s?u.shape[u.rank-1]:u.shape[u.rank-2],h=n?l.shape[l.rank-1]:l.shape[l.rank-2],p=s?u.shape[u.rank-2]:u.shape[u.rank-1],f=l.shape.slice(0,-2),m=u.shape.slice(0,-2),g=$t(f),A=$t(m);M(l.rank>=2&&u.rank>=2&&l.rank===u.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${l.rank} and ${u.rank}.`),M(br(f,m),()=>`Error in fused matMul: outer dimensions (${f}) and (${m}) of Tensors with shapes ${l.shape} and ${u.shape} must match.`),M(c===d,()=>`Error in fused matMul: inner shapes (${c}) and (${d}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${n} and transposeB=${s} must match.`);let y=l.shape.slice(0,-2).concat([h,p]),x=n?U(l,[g,c,h]):U(l,[g,h,c]),b=s?U(u,[A,p,d]):U(u,[A,d,p]),v;r!=null&&(v=$(r,"bias","fused matMul"),[v]=Ct(v,l),At(y,v.shape));let k;o!=null&&(k=$(o,"prelu weights","fused matMul"));let S=(O,E)=>{let[R,T,P,V]=E,j=dp(U(O,P.shape),P,a),q,X;if(!n&&!s?(q=Ve(j,T,!1,!0),X=Ve(R,j,!0,!1)):!n&&s?(q=Ve(j,T,!1,!1),X=Ve(j,R,!0,!1)):n&&!s?(q=Ve(T,j,!1,!0),X=Ve(R,j,!1,!1)):(q=Ve(T,j,!0,!0),X=Ve(j,R,!0,!0)),r!=null){let ee=hp(V,j);return[q,X,ee]}else return[q,X]},C={a:x,b,bias:v,preluActivationWeights:k},_={transposeA:n,transposeB:s,activation:a,leakyreluAlpha:i};return r==null?nr((E,R,T)=>{let P=z.runKernel(So,C,_);return T([E,R,P]),{value:U(P,y),gradFunc:S}})(x,b):nr((E,R,T,P)=>{let V=z.runKernel(So,C,_);return P([E,R,V,T]),{value:U(V,y),gradFunc:S}})(x,b,v)}var i_=W({fusedMatMul_:o_});function l_(e){return eA(e,.54,.46)}var u_=W({hammingWindow_:l_});function c_(e){return eA(e,.5,.5)}var Mb=W({hannWindow_:c_});function d_(e,t,n,s=!1,r=0){let a=0,o=[];for(;a+t<=e.size;)o.push(Re(e,a,t)),a+=n;if(s)for(;a`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),M(i.rank===2&&i.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${i.shape}.`),M(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${i.shape}.`),M(s.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),M(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),M(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);let c={image:o,boxes:i,boxInd:l},d={method:r,extrapolationValue:a,cropSize:s};return z.runKernel(Pi,c,d)}var m_=W({cropAndResize_:f_});function g_(e){let t=$(e,"image","flipLeftRight","float32");M(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return z.runKernel(Vi,n,{})}var A_=W({flipLeftRight_:g_});function y_(e){let t=$(e,"image","grayscaleToRGB"),n=t.rank-1,s=t.shape[n];M(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),M(s===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${s}.`);let r=new Array(t.rank);return r.fill(1,0,n),r[n]=3,Ts(t,r)}var x_=W({grayscaleToRGB_:y_});function b_(e,t,n=0,s=.5){let r=$(e,"image","rotateWithOffset","float32");M(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);let a={image:r},o={radians:t,fillValue:n,center:s};return z.runKernel(Il,a,o)}var v_=W({rotateWithOffset_:b_});function Ul(e,t,n,s,r,a){s==null&&(s=.5),r==null&&(r=Number.NEGATIVE_INFINITY),a==null&&(a=0);let o=e.shape[0];return n=Math.min(n,o),M(0<=s&&s<=1,()=>`iouThreshold must be in [0, 1], but was '${s}'`),M(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),M(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),M(t.rank===1,()=>"scores must be a 1D tensor"),M(t.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`),M(0<=a&&a<=1,()=>`softNmsSigma must be in [0, 1], but was '${a}'`),{maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a}}function w_(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=$(e,"boxes","nonMaxSuppression"),o=$(t,"scores","nonMaxSuppression"),i=Ul(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l={maxOutputSize:n,iouThreshold:s,scoreThreshold:r};return z.runKernel(nl,{boxes:a,scores:o},l)}var k_=W({nonMaxSuppression_:w_});function I_(e,t,n){let s=S_(e,t,n),r=s<0?-(s+1):s;e.splice(r,0,t)}function S_(e,t,n){return T_(e,t,n||C_)}function C_(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 Lb(e,t,n,s,r){return nA(e,t,n,s,r,0)}function Bb(e,t,n,s,r,a){return nA(e,t,n,s,r,0,!1,a,!0)}function Wb(e,t,n,s,r,a){return nA(e,t,n,s,r,a,!0)}function nA(e,t,n,s,r,a,o=!1,i=!1,l=!1){let u=[];for(let g=0;gr&&u.push({score:t[g],boxIndex:g,suppressBeginIndex:0});u.sort(Vb);let c=a>0?-.5/a:0,d=[],h=[];for(;d.length0;){let g=u.pop(),{score:A,boxIndex:y,suppressBeginIndex:x}=g;if(A=x;--v){let k=N_(e,y,d[v]);if(k>=s){b=!0;break}if(g.score=g.score*E_(s,c,k),g.score<=r)break}g.suppressBeginIndex=d.length,b||(g.score===A?(d.push(y),h.push(g.score)):g.score>r&&I_(u,g,Vb))}let p=d.length,f=n-p;i&&f>0&&(d.push(...new Array(f).fill(0)),h.push(...new Array(f).fill(0)));let m={selectedIndices:d};return o&&(m.selectedScores=h),l&&(m.validOutputs=p),m}function N_(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]),u=Math.min(r[0],r[2]),c=Math.min(r[1],r[3]),d=Math.max(r[0],r[2]),h=Math.max(r[1],r[3]),p=(i-a)*(l-o),f=(d-u)*(h-c);if(p<=0||f<=0)return 0;let m=Math.max(a,u),g=Math.max(o,c),A=Math.min(i,d),y=Math.min(l,h),x=Math.max(A-m,0)*Math.max(y-g,0);return x/(p+f-x)}function E_(e,t,n){let s=Math.exp(t*n*n);return n<=e?s:0}function Vb(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function R_(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=$(e,"boxes","nonMaxSuppressionAsync"),o=$(t,"scores","nonMaxSuppressionAsync"),i=Ul(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l=await Promise.all([a.data(),o.data()]),u=l[0],c=l[1],{selectedIndices:d}=Lb(u,c,n,s,r);return a!==e&&a.dispose(),o!==t&&o.dispose(),Mt(d,"int32")}var __=R_;function D_(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=$(e,"boxes","nonMaxSuppression"),i=$(t,"scores","nonMaxSuppression"),l=Ul(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let u={boxes:o,scores:i},c={maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a},d=z.runKernel(rl,u,c);return{selectedIndices:d[0],selectedScores:d[1]}}var $_=W({nonMaxSuppressionWithScore_:D_});async function F_(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=$(e,"boxes","nonMaxSuppressionAsync"),i=$(t,"scores","nonMaxSuppressionAsync"),l=Ul(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let u=await Promise.all([o.data(),i.data()]),c=u[0],d=u[1],{selectedIndices:h,selectedScores:p}=Wb(c,d,n,s,r,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Mt(h,"int32"),selectedScores:Mt(p)}}var O_=F_;function P_(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=$(e,"boxes","nonMaxSuppression"),i=$(t,"scores","nonMaxSuppression"),l=Ul(o,i,n,s,r,null),u=l.maxOutputSize,c=l.iouThreshold,d=l.scoreThreshold,h={boxes:o,scores:i},p={maxOutputSize:u,iouThreshold:c,scoreThreshold:d,padToMaxOutputSize:a},f=z.runKernel(sl,h,p);return{selectedIndices:f[0],validOutputs:f[1]}}var M_=W({nonMaxSuppressionPadded_:P_});async function z_(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=$(e,"boxes","nonMaxSuppressionAsync"),i=$(t,"scores","nonMaxSuppressionAsync"),l=Ul(o,i,n,s,r,null),u=l.maxOutputSize,c=l.iouThreshold,d=l.scoreThreshold,[h,p]=await Promise.all([o.data(),i.data()]),{selectedIndices:f,validOutputs:m}=Bb(h,p,u,c,d,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Mt(f,"int32"),validOutputs:Ie(m,"int32")}}var L_=z_;function B_(e,t,n=!1,s=!1){let r=$(e,"images","resizeBilinear");M(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),M(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),M(s===!1||n===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let a=r,o=!1;r.rank===3&&(o=!0,a=U(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},u=z.runKernel(uo,i,l);return o?U(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var W_=W({resizeBilinear_:B_});function V_(e,t,n=!1,s=!1){let r=$(e,"images","resizeNearestNeighbor");M(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),M(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),M(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),M(s===!1||n===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let a=r,o=!1;r.rank===3&&(o=!0,a=U(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},u=z.runKernel(qu,i,l);return o?U(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var U_=W({resizeNearestNeighbor_:V_});function H_(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],u=L(Mt([s]),255),c,d,h,p;if(M(r.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`),M(r.shape[2]===3||r.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`),M(r.dtype==="int32"||r.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`),M(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),r.shape[2]===3){[c,d,h]=an(r,[1,1,1],-1);let g=L(c,a),A=L(d,o),y=L(h,i);p=ae(ae(g,A),y)}else p=e;if(t==="otsu"){let g=Ig(ce(Vg(p),"int32"),dn([]),256);u=G_(g,l)}let f=n?Mo(p,u):jn(p,u);return ce(L(f,255),"int32")}function G_(e,t){let n=Mt([-1]),s=Mt([0]),r=Mt([0]),a,o,i,l,u,c;for(let d=0;d`Error in transform: image must be rank 4,but got rank ${o.rank}.`),M(i.rank===2&&(i.shape[0]===o.shape[0]||i.shape[0]===1)&&i.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),M(a==null||a.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`);let l={image:o,transforms:i},u={interpolation:n,fillMode:s,fillValue:r,outputShape:a};return z.runKernel(vl,l,u)}var X_=W({transform_:q_});function K_(e,t,n){M(t%1==0,()=>`bandPart(): numLower must be an integer, got ${t}.`),M(n%1==0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);let s=$(e,"a","bandPart");M(s.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`);let r=s.shape,[a,o]=s.shape.slice(-2);if(!(t<=a))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`);if(!(n<=o))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`);t<0&&(t=a),n<0&&(n=o);let i=U(Vl(0,a,1,"int32"),[-1,1]),l=Vl(0,o,1,"int32"),u=ge(i,l),c=Ps(Mo(u,Ie(+t,"int32")),Po(u,Ie(-n,"int32"))),d=Pt([a,o],s.dtype);return U(Dn(ms(U(s,[-1,a,o])).map(h=>bn(c,h,d))),r)}var Z_=W({bandPart_:K_});function Y_(e){let t;if(Array.isArray(e)){t=!1,M(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let r=e[0].shape[0];for(let a=1;a`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[a].shape[0]} vs. ${r})`)}else t=!0,e=an(e,e.shape[0],0).map(r=>lt(r,[0]));M(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let n=[],s=e;for(let r=0;r{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 Ub(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,u)=>l*u),s=ms(U(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],a=[];s.forEach(l=>{let[u,c]=Ub(l,t);r.push(u),a.push(c)});let o=U(Dn(r,0),e.shape),i=U(Dn(a,0),e.shape);return[o,i]}}function Ub(e,t=!1){return z.tidy(()=>{M(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let n=e.shape[0],s=e.shape[1],r=_g(n),a=Os(e),o=Ms([[1]],[1,1]),i=Os(o),l=n>=s?s:n;for(let u=0;u{let p=Re(a,[u,u],[n-u,1]),f=Jg(p),m=Re(a,[u,u],[1,1]),g=bn(jn(m,0),Ms([[-1]]),Ms([[1]])),A=ge(m,L(g,f)),y=de(p,A);y.shape[0]===1?i=Os(o):i=ft([o,Re(y,[1,0],[y.shape[0]-1,y.shape[1]])],0);let x=Tt(de(Ve(g,A),f)),b=Re(a,[u,0],[n-u,s]),v=L(x,i),k=Xe(i);if(u===0)a=ge(b,Ve(v,Ve(k,b)));else{let _=ge(b,Ve(v,Ve(k,b)));a=ft([Re(a,[0,0],[u,s]),_],0)}let S=Xe(v),C=Re(r,[0,u],[n,r.shape[1]-u]);if(u===0)r=ge(C,Ve(Ve(C,i),S));else{let _=ge(C,Ve(Ve(C,i),S));r=ft([Re(r,[0,0],[n,u]),_],1)}return[i,a,r]}),Z([c,d,h])}return!t&&n>s&&(r=Re(r,[0,0],[n,s]),a=Re(a,[0,0],[s,s])),[r,a]})}var eD=W({qr_:Q_}),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 tD(e,t,n=vn.SUM_BY_NONZERO_WEIGHTS){let s=$(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=$(t,"weights","computeWeightedLoss"));let a=r==null?s:L(s,r);if(n===vn.NONE)return a;if(n===vn.SUM)return ve(a);if(n===vn.MEAN){if(r==null)return _t(a);{let o=s.size/r.size,i=de(ve(a),ve(r));return o>1?de(i,Ie(o)):i}}if(n===vn.SUM_BY_NONZERO_WEIGHTS){if(r==null)return de(ve(a),Ie(s.size));{let o=L(r,qn(s.shape)),i=ce(ve(Bl(o,Ie(0))),"float32");return de(ve(a),i)}}throw Error(`Unknown reduction: ${n}`)}var Ir=W({computeWeightedLoss_:tD});function nD(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")),An(r.shape,a.shape,"Error in absoluteDifference: ");let i=Ht(ge(r,a));return Ir(i,o,s)}var sD=W({absoluteDifference_:nD});function rD(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")),An(a.shape,o.shape,"Error in cosineDistance: ");let l=Ie(1),u=ge(l,ve(L(a,o),n,!0));return Ir(u,i,r)}var aD=W({cosineDistance_:rD});function oD(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")),An(r.shape,a.shape,"Error in hingeLoss: ");let i=Ie(1);r=ge(L(Ie(2),r),i);let l=sr(ge(i,L(r,a)));return Ir(l,o,s)}var iD=W({hingeLoss_:oD});function lD(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")),An(a.shape,o.shape,"Error in huberLoss: ");let l=Ie(s),u=Ht(ge(o,a)),c=fc(u,l),d=ge(u,c),h=ae(L(Ie(.5),ct(c)),L(l,d));return Ir(h,i,r)}var uD=W({huberLoss_:lD});function cD(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")),An(a.shape,o.shape,"Error in logLoss: ");let l=Ie(1),u=Ie(s),c=Tt(L(a,ds(ae(o,u)))),d=L(ge(l,a),ds(ae(ge(l,o),u))),h=ge(c,d);return Ir(h,i,r)}var dD=W({logLoss_:cD});function hD(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")),An(r.shape,a.shape,"Error in meanSquaredError: ");let i=Kg(r,a);return Ir(i,o,s)}var pD=W({meanSquaredError_:hD});function fD(e,t){let n=$(e,"labels","sigmoidCrossEntropyWithLogits"),s=$(t,"logits","sigmoidCrossEntropyWithLogits");An(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=sr(s),a=L(s,n),o=Yh(cs(Tt(Ht(s))));return ae(ge(r,a),o)}function mD(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")),An(a.shape,o.shape,"Error in sigmoidCrossEntropy: "),s>0){let u=Ie(s),c=Ie(1),d=Ie(.5);a=ae(L(a,ge(c,u)),L(d,u))}let l=fD(a,o);return Ir(l,i,r)}var gD=W({sigmoidCrossEntropy_:mD});function AD(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 nr((r,a,o)=>{let l=fb(a,[n],!0),u=ge(ce(a,"float32"),l);o([r,u]);let c=Tt(L(u,r));return{value:ve(c,[n]),gradFunc:(p,f)=>{let[m,g]=f,A=zo(p.shape,[n]);return[L(U(p,A),ge(ce(m,"float32"),cs(g))),L(U(p,A),ge(cs(g),ce(m,"float32")))]}}})(e,t)}function yD(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")),An(a.shape,o.shape,"Error in softmaxCrossEntropy: "),s>0){let u=Ie(s),c=Ie(1),d=Ie(a.shape[1]);a=ae(L(a,ge(c,u)),de(u,d))}let l=AD(a,o);return Ir(l,i,r)}var xD=W({softmaxCrossEntropy_:yD});function bD(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},u=z.runKernel(wh,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var vD=W({sparseFillEmptyRows_:bD});function wD(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=z.runKernel(kh,o);return{outputIndices:i[0],outputShape:i[1]}}var kD=W({sparseReshape_:wD});function ID(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
+ ${s.shape}`),M(o%(t*t)==0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${s.shape}`);let i={x:s},l={blockSize:t,dataFormat:n};return z.runKernel(Mi,i,l)}var tb=W({depthToSpace_:nN});function sN(e,t,n,s,r="NHWC",a=[1,1],o){let i=$(e,"x","depthwiseConv2d"),l=$(t,"filter","depthwiseConv2d"),u=i,c=!1;i.rank===3&&(c=!0,u=U(i,[1,i.shape[0],i.shape[1],i.shape[2]])),M(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),M(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),M(u.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),o!=null&&M(Zt(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let d={x:u,filter:l},h={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},p=z.runKernel(La,d,h);return c?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var dc=W({depthwiseConv2d_:sN});function rN(e){let n={x:$(e,"x","diag")};return z.runKernel(ah,n)}var aN=W({diag_:rN});function oN(e,t,n,s,r=[1,1],a="NHWC"){let o=$(e,"x","dilation2d"),i=$(t,"filter","dilation2d");M(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),M(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),M(a==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);let l=o,u=!1;o.rank===3&&(l=U(o,[1,o.shape[0],o.shape[1],o.shape[2]]),u=!0);let c={x:l,filter:i},d={strides:n,pad:s,dilations:r},h=z.runKernel(Bu,c,d);return u?U(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var nb=W({dilation2d_:oN});function iN(e,t){let n=e.length,s=[];for(let r=0;r1&&o===1&&s.unshift(a)}return s}function Gt(e,t){let n=[];for(let s=0;s1)&&n.unshift(a)}return n}function At(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(M(r===a,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${a}.`),n.rank===1&&s.rank===1){let o=U(n,[1,-1]),i=U(s,[-1,1]),l=Ve(o,i);return U(l,[])}else if(n.rank===1&&s.rank===2){let o=U(n,[1,-1]),i=U(s,[s.shape[0],s.shape[1]]),l=Ve(o,i);return U(l,[l.size])}else if(n.rank===2&&s.rank===1){let o=U(s,[-1,1]),i=Ve(n,o);return U(i,[i.size])}else{let o=U(s,[s.shape[0],s.shape[1]]);return Ve(n,o)}}var pN=W({dot_:hN});function fN(e,...t){let n=t.map((r,a)=>$(r,`tensors${a}`,"einsum")),s={equation:e};return z.runKernel(lh,n,s)}var rb=W({einsum_:fN});function mN(e){let n={x:$(e,"x","elu")};return z.runKernel(Wa,n)}var hc=W({elu_:mN});function gN(e){let t=$(e,"x","erf");M(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=ce(t,"float32"));let n={x:t};return z.runKernel(zi,n)}var ab=W({erf_:gN});function AN(e){let n={x:$(e,"x","exp")};return z.runKernel(Va,n)}var cs=W({exp_:AN});function yN(e,t=0){let n=$(e,"x","expandDims","string_or_numeric");M(t<=n.rank,()=>"Axis must be <= rank of the tensor");let s={input:n},r={dim:t};return z.runKernel(Bi,s,r)}var Ot=W({expandDims_:yN});function xN(e){let n={x:$(e,"x","expm1")};return z.runKernel(Wi,n)}var ob=W({expm1_:xN});function bN(e,t){let n=$(e,"x","tile","string_or_numeric");M(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);let s={x:n},r={reps:t};return z.runKernel(Hr,s,r)}var Ts=W({tile_:bN});function vN(e,t,n,s="float32"){t==null&&(t=e);let r=We([e,t],s),a=e<=t?e:t;for(let i=0;i`Error in localResponseNormalization: x must be rank 3 or 4 but got
+ rank ${a.rank}.`),M(Zt(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=a,i=!1;a.rank===3&&(i=!0,o=U(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let l={x:o},u={depthRadius:t,bias:n,alpha:s,beta:r},c=z.runKernel(Hu,l,u);return i?U(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var ub=W({localResponseNormalization_:ON});function PN(e){let n={x:$(e,"x","log")};return z.runKernel(Ka,n)}var ds=W({log_:PN});function MN(e){let n={x:$(e,"x","log1p")};return z.runKernel(Yi,n)}var Yh=W({log1p_:MN});function zN(e){return M(Wr(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 z.tidy(()=>{let{value:a,grads:o}=z.gradients(()=>e(s),[s],r);return r!=null&&An(a.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Jh(o),o[0]})}}function LN(e){return M(Wr(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{M(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let s=oc(t,"args","tf.grads","string_or_numeric"),r=n!=null?$(n,"dy","tf.grads"):null;return z.tidy(()=>{let{value:a,grads:o}=z.gradients(()=>e(...s),s,r);return r!=null&&An(a.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Jh(o),o})}}function BN(e){return M(Wr(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{M(t instanceof Ge,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),M(n==null||n instanceof Ge,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:s,value:r}=z.gradients(()=>e(t),[t],n);return Jh(s),{grad:s[0],value:r}}}function WN(e){return M(Wr(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{M(Array.isArray(t)&&t.every(r=>r instanceof Ge),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),M(n==null||n instanceof Ge,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let s=z.gradients(()=>e(...t),t,n);return n!=null&&An(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Jh(s.grads),s}}function cb(e,t){M(Wr(e),()=>"The f passed in variableGrads(f) must be a function"),M(t==null||Array.isArray(t)&&t.every(u=>u instanceof sc),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let u in z.registeredVariables)t.push(z.registeredVariables[u])}let s=n?t.filter(u=>!u.trainable):null,r=t.length;t=t.filter(u=>u.trainable),M(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);let a=!0,{value:o,grads:i}=z.gradients(e,t,null,a);M(i.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),M(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);let l={};return t.forEach((u,c)=>{i[c]!=null&&(l[u.name]=i[c])}),s!=null&&s.forEach(u=>l[u.name]=null),{value:o,grads:l}}function nr(e){return z.customGrad(e)}function Jh(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 VN(e){let n={x:$(e,"x","neg")};return z.runKernel(el,n)}var Tt=W({neg_:VN});function UN(e){let n={x:$(e,"x","softplus")};return z.runKernel(gl,n)}var Ll=W({softplus_:UN});function HN(e){let t=$(e,"x","logSigmoid");return nr(s=>({value:Tt(Ll(Tt(s))),gradFunc:o=>L(o,Hn(Tt(s)))}))(t)}var GN=W({logSigmoid_:HN});function jN(e,t=null,n=!1){let r={x:$(e,"x","max")},a={reductionIndices:t,keepDims:n};return z.runKernel(Za,r,a)}var hs=W({max_:jN});function qN(e,t){let n=$(e,"a","sub"),s=$(t,"b","sub");[n,s]=Ct(n,s);let r={a:n,b:s};return z.runKernel(vo,r)}var ge=W({sub_:qN});function XN(e,t=null,n=!1){let s=$(e,"x","sum");s.dtype==="bool"&&(s=ce(s,"int32"));let r={x:s},a={axis:t,keepDims:n};return z.runKernel(yo,r,a)}var ve=W({sum_:XN});function KN(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 nr((r,a)=>{let o=!0,i=hs(r,t,!0),l=ge(r,i),u=ge(ce(l,"float32"),ds(ve(cs(l),t,o)));return a([u]),{value:u,gradFunc:(d,h)=>{let[p]=h,f=!0,m=cs(p);return ge(d,L(ve(d,t,f),m))}}})(n)}var Fg=W({logSoftmax_:KN});function Og(e,t){for(let n=0;ne[a]);return[n,r]}function zo(e,t){let n=t.map(s=>1);return db(e,n,t)}function ZN(e,t,n){M(Og(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function pb(e,t){if(Og(e,t))return null;let n=[];for(let s=0;sn.push(s)),n}function Pg(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function YN(e,t){let n=[];for(let s=t-e;s`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),M(tr(n,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),r!=null&&M(Zt(s),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let u={x:i},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r},d=z.runKernel(Ja,u,c);return l?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var ep=W({maxPool_:rE});function aE(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=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),M(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),M(a==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),r!=null&&M(Zt(s),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let u={x:i},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},d=z.runKernel(Gu,u,c);return l?U(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var zg=W({maxPool3d_:aE});function oE(e,t,n,s,r=!1){let o={x:$(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:s,includeBatchInIndex:r},l=z.runKernel(Ah,o,i);return{result:l[0],indexes:l[1]}}var mb=W({maxPoolWithArgmax_:oE});function iE(e,t){let n=$(e,"a","maximum"),s=$(t,"b","maximum");[n,s]=Ct(n,s),n.dtype==="bool"&&(n=ce(n,"int32"),s=ce(s,"int32")),At(n.shape,s.shape);let r={a:n,b:s};return z.runKernel(Ya,r)}var kr=W({maximum_:iE});function lE(e,t=null,n=!1){let r={x:$(e,"x","mean")},a={axis:t,keepDims:n};return z.runKernel(Qa,r,a)}var _t=W({mean_:lE});function Pt(e,t="float32"){if(t==="complex64"){let s=Pt(e,"float32"),r=Pt(e,"float32");return qr(s,r)}let n=Xd($t(e),t);return z.makeTensor(n,e,t)}function qn(e,t="float32"){if(t==="complex64"){let s=qn(e,"float32"),r=Pt(e,"float32");return qr(s,r)}let n=Pm($t(e),t);return z.makeTensor(n,e,t)}function uE(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 Ge?e.dtype:"float32");if(t===void 0)return[s];let r=$(t,"y","meshgrid",t instanceof Ge?t.dtype:"float32"),a=$t(s.shape),o=$t(r.shape);return n==="xy"?(s=U(s,[1,-1]),r=U(r,[-1,1]),[Ve(qn([o,1],s.dtype),s),Ve(r,qn([1,a],r.dtype))]):(s=U(s,[-1,1]),r=U(r,[1,-1]),[Ve(s,qn([1,o],s.dtype)),Ve(qn([a,1],r.dtype),r)])}function cE(e,t=null,n=!1){let r={x:$(e,"x","min")},a={axis:t,keepDims:n};return z.runKernel(eo,r,a)}var tp=W({min_:cE});function dE(e,t){let n=$(e,"a","minimum"),s=$(t,"b","minimum");[n,s]=Ct(n,s),n.dtype==="bool"&&(n=ce(n,"int32"),s=ce(s,"int32")),At(n.shape,s.shape);let r={a:n,b:s};return z.runKernel(to,r)}var fc=W({minimum_:dE});function hE(e,t,n){M(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let s=$(e,"x","mirrorPad");if(s.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");M(t.length===s.rank,()=>`Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`);let r=n==="reflect"?1:0;for(let i=0;i"Invalid number of paddings. Must be length of 2 each."),M(t[i][0]>=0&&t[i][0]<=s.shape[i]-r&&t[i][1]>=0&&t[i][1]<=s.shape[i]-r,()=>`Padding in dimension ${i} cannot be greater than or equal to ${s.shape[i]-r} or less than 0 for input of shape ${s.shape}`);let a={paddings:t,mode:n},o={x:s};return z.runKernel(no,o,a)}var gb=W({mirrorPad_:hE});function pE(e,t){let n=$(e,"a","mod"),s=$(t,"b","mod");[n,s]=Ct(n,s);let r={a:n,b:s};return z.runKernel(Qi,r)}var Ab=W({mod_:pE});function fE(e){let t=$(e,"x","square"),n={};return z.runKernel("Square",{x:t},n)}var ct=W({square_:fE});function mE(e,t=null,n=!1){e=$(e,"x","moments");let s=Ss(t,e.shape),r=_t(e,s,n),a=r.shape;n||(a=zo(r.shape,s));let o=ct(ge(ce(e,"float32"),U(r,a))),i=_t(o,s,n);return{mean:r,variance:i}}var np=W({moments_:mE});function gE(e,t,n,s){let r=$(t,"data","multiRNNCell"),a=oc(n,"c","multiRNNCell"),o=oc(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?U(r,[1,-1]):r},u={numSamples:t,seed:n,normalized:s},c=z.runKernel(yh,l,u);return o===1?U(c,[c.size]):c}var yb=W({multinomial_:yE});function xE(e,t){let n=$(e,"a","notEqual","string_or_numeric"),s=$(t,"b","notEqual","string_or_numeric");[n,s]=Ct(n,s),At(n.shape,s.shape);let r={a:n,b:s};return z.runKernel(tl,r)}var Bl=W({notEqual_:xE});function bE(e){let n={x:$(e,"x","onesLike")};return z.runKernel(al,n)}var ps=W({onesLike_:bE});function vE(e,t){let n=$(e,"v1","outerProduct"),s=$(t,"v2","outerProduct");M(n.rank===1&&s.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${s.rank}.`);let r=U(n,[-1,1]),a=U(s,[1,-1]);return Ve(r,a)}var wE=W({outerProduct_:vE});function kE(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 z.runKernel(ao,a,r)}var Qr=W({pad_:kE});function IE(e,t,n=0){return M(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),Qr(e,[t],n)}var SE=W({pad1d_:IE});function CE(e,t,n=0){return M(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Qr(e,t,n)}var TE=W({pad2d_:CE});function NE(e,t,n=0){return M(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Qr(e,t,n)}var EE=W({pad3d_:NE});function RE(e,t,n=0){return M(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Qr(e,t,n)}var _E=W({pad4d_:RE});function DE(e,t,n){let s=$(e,"x","spaceToBatchND");M(s.rank>=1+t.length,()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`),M(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),M(s.shape.reduce((o,i,l)=>l>0&&l<=t.length?o&&(i+n[l-1][0]+n[l-1][1])%t[l-1]==0:o,!0),()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);let r={x:s},a={blockShape:t,paddings:n};return z.runKernel(Al,r,a)}var sp=W({spaceToBatchND_:DE});function $E(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=U(o,[1,o.shape[0],o.shape[1],o.shape[2]])),M(tr(a,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${r}'`);let u=Wx(i.shape,t,a,r,s),c=[u.dilationHeight,u.dilationWidth],d;s==="same"?d=OE([u.filterHeight,u.filterWidth],c):d=[[0,0],[0,0]];let h=c[0]===1&&c[1]===1,[p,f]=FE([u.inHeight,u.inWidth],c,d),m=h?s:"valid",g=h?i:sp(i,c,p),y=(n==="avg"?()=>jh(g,t,a,m):()=>ep(g,t,a,m))(),x=h?y:qh(y,c,f);return l?U(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function FE(e,t,n){let s=n.map(c=>c[0]),r=n.map(c=>c[1]),a=e.concat(s,r),o=t.map((c,d)=>(c-a[d]%c)%c),i=r.map((c,d)=>c+o[d]),l=t.map((c,d)=>[s[d],i[d]]),u=t.map((c,d)=>[0,o[d]]);return[l,u]}function OE(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 PE=W({pool_:$E});function ME(e,t){let n=$(e,"base","pow"),s=$(t,"exp","pow");[n,s]=Ct(n,s);let r={a:n,b:s};return z.runKernel(oo,r)}var ea=W({pow_:ME});function zE(e,t){let n=$(e,"x","prelu"),s=$(t,"alpha","prelu"),r={x:n,alpha:s};return z.runKernel(io,r)}var rp=W({prelu_:zE});function LE(e,t=null,n=!1){let s=$(e,"x","prod");s.dtype==="bool"&&(s=ce(s,"int32"));let r={x:s},a={axis:t,keepDims:n};return z.runKernel(il,r,a)}var Lg=W({prod_:LE});function BE(e,t,n){let s=$t(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}},VE=class{constructor(e,t,n,s){this.alpha=e,this.beta=1/t,this.dtype=n;let r=s||Math.random();this.randu=Bg.alea(r.toString()),this.randn=new Wg(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=Bg.alea(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function HE(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 VE(t,n,s,r),o=We(e,s);for(let i=0;i`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),fs(t,0)}var eR=W({reverse1d_:QE});function tR(e,t){let n=$(e,"x","reverse");return M(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),fs(n,t)}var nR=W({reverse2d_:tR});function sR(e,t){let n=$(e,"x","reverse");return M(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),fs(n,t)}var rR=W({reverse3d_:sR});function aR(e,t){let n=$(e,"x","reverse");return M(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),fs(n,t)}var oR=W({reverse4d_:aR});function iR(e){let n={x:$(e,"x","round")};return z.runKernel(po,n)}var Ug=W({round_:iR});function lR(e){let n={x:$(e,"x","rsqrt")};return z.runKernel(fo,n)}var Hg=W({rsqrt_:lR});function Ie(e,t){if((cn(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"&&cn(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Xr(e,[],[],t)}function uR(e){let n={x:$(e,"x","selu")};return z.runKernel(hl,n)}var Gg=W({selu_:uR});function cR(e,t,n,s,r,a=[1,1],o="NHWC"){let i=$(e,"x","separableConv2d"),l=$(t,"depthwiseFilter","separableConv2d"),u=$(n,"pointwiseFilter","separableConv2d"),c=i,d=!1;if(i.rank===3&&(d=!0,c=U(i,[1,i.shape[0],i.shape[1],i.shape[2]])),o==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");M(c.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`),M(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),M(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),M(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),M(u.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);let h=l.shape[2],p=l.shape[3];M(u.shape[2]===h*p,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${h*p}, but got ${u.shape[2]}.`);let f=dc(c,l,s,r,o,a),g=Jr(f,u,1,"valid",o);return d?U(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var vb=W({separableConv2d_:cR});async function dR(e,t){let n=$(e,"x","setdiff1d"),s=$(t,"y","setdiff1d");M(n.dtype===s.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`),M(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),M(s.rank===1,()=>`y should be 1D tensor, but got y (${s.shape}).`);let r=await n.data(),a=await s.data(),o=new Set(a),i=0;for(let c=0;c`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),Re(s,[t],[n])}var ap=W({slice1d_:mR});function gR(e,t,n){let s=$(e,"x","slice2d");return M(s.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),Re(s,t,n)}var Xg=W({slice2d_:gR});function AR(e,t,n){let s=$(e,"x","slice3d");return M(s.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),Re(s,t,n)}var op=W({slice3d_:AR});function yR(e,t,n){let s=$(e,"x","slice4d");return M(s.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),Re(s,t,n)}var gc=W({slice4d_:yR});function xR(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 z.runKernel(xo,s,r)}var ip=W({softmax_:xR});function bR(e){M(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return z.runKernel(ch,t)}var lp=W({fft_:bR});function vR(e){M(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return z.runKernel(dh,t)}var Ac=W({ifft_:vR});function wR(e){let t=e.shape[e.shape.length-1],n=e.size/t,s;if(t<=2){let r=U(e,[n,t]);s=Ac(r)}else{let r=[n,2*(t-1)],a=U(mc(e),[n,t]),o=U(Kh(e),[n,t]),i=fs(Re(a,[0,1],[n,t-2]),1),l=L(fs(Re(o,[0,1],[n,t-2]),1),Ie(-1)),u=ft([a,i],1),c=ft([o,l],1),d=U(qr(u,c),[r[0],r[1]]);s=Ac(d)}if(s=mc(s),e.rank===3&&e.shape[0]!==0){let r=s,a=e.shape[0];s=U(s,[a,s.shape[0]/a,s.shape[1]]),r.dispose()}return s}var Kg=W({irfft_:wR});function kR(e,t,n=0){let r={x:$(e,"x","split")},a={numOrSizeSplits:t,axis:n};return z.runKernel(yl,r,a)}var an=W({split_:kR});function IR(e,t){M(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1],s=e.size/n,r;if(t!=null&&t0),m=e.shape.map(g=>g);m[e.shape.length-1]=t,r=Re(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=ft([e,Pt(f)],e.shape.length-1),n=t}else r=e;let a=Ke(r),o=U(qr(r,a),[s,n]),i=lp(o),l=Math.floor(n/2)+1,u=mc(i),c=Kh(i),d=an(u,[l,n-l],u.shape.length-1),h=an(c,[l,n-l],c.shape.length-1),p=r.shape.slice();return p[r.shape.length-1]=l,U(qr(d[0],h[0]),p)}var up=W({rfft_:IR});function SR(e){let n={x:$(e,"x","sqrt")};return z.runKernel(Ao,n)}var hn=W({sqrt_:SR});function CR(e,t){let n=$(e,"a","squaredDifference"),s=$(t,"b","squaredDifference");[n,s]=Ct(n,s),At(n.shape,s.shape);let r={a:n,b:s},a={};return z.runKernel(bo,r,a)}var Zg=W({squaredDifference_:CR});function TR(e,t){let n=$(e,"x","squeeze");return U(n,b5(n.shape,t).newShape)}var lt=W({squeeze_:TR});function NR(e,t=0){let n=oc(e,"tensors","stack","string_or_numeric");M(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&M(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let s=n,r={axis:t};return z.runKernel(ol,s,r)}var Dn=W({stack_:NR});function ER(e,t=0){let s={x:$(e,"x","step")},r={alpha:t};return z.runKernel(Gr,s,r)}var yc=W({step_:ER});function RR(e,t,n,s,r=0,a=0,o=0,i=0,l=0){let c={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 z.runKernel(xl,c,d)}var Ib=W({stridedSlice_:RR});function _R(e){let n={x:$(e,"x","tan")};return z.runKernel(wo,n)}var Sb=W({tan_:_R});function Mt(e,t){Ca(e);let n=Qs(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Xr(e,null,n,t)}function Ms(e,t,n){if(Ca(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let s=Qs(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 Xr(e,t,s,n)}function DR(e,t,n){if(Ca(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let s=Qs(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 Xr(e,t,s,n)}function $R(e,t,n){if(Ca(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let s=Qs(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 Xr(e,t,s,n)}function FR(e,t,n){if(Ca(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let s=Qs(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,Xr(e,t,s,n)}function OR(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]=z.runKernel(bl,a,o);return{values:i,indices:l}}var Cb=W({topk_:OR});function PR(e,t=0,n=1,s,r){if(s!=null&&s==="bool")throw new Error("Unsupported data type $ { dtype }");let a=new Wg(t,n,s,!0,r),o=We(e,s);for(let i=0;i0,()=>"The input tensor must be at least 1D");let s={x:n},r={axis:t},[a,o]=z.runKernel(Rh,s,r);return{values:a,indices:o}}var Yg=W({unique_:MR});function zR(e,t,n){let s=$(e,"x","unsortedSegmentSum"),r=$(t,"segmentIds","unsortedSegmentSum","int32");M(Zt(n),()=>"numSegments must be of dtype int");let a={x:s,segmentIds:r},o={numSegments:n};return z.runKernel(Ku,a,o)}var Tb=W({unsortedSegmentSum_:zR});function LR(e,t=0){let n=$(e,"x","unstack","string_or_numeric");M(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);let s={value:n},r={axis:t};return z.runKernel(wl,s,r)}var ms=W({unstack_:LR});function Nb(e,t=!0,n,s){return z.makeVariable(e,t,n,s)}function Eb(e,t){let n=[];for(let a=0;a0,()=>"mask cannot be scalar"),An(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=Ie(1),u=ge(l,i),c=L(ge(o,a),u);if(r){M(s!=null,()=>"When using zeroDebias: true, step is required.");let d=$(s,"step","movingAverage");c=de(c,ge(l,ea(i,d)))}return ae(a,c)}var GR=W({movingAverage_:HR});function jR(e,t,n){let s=$(e,"indices","scatterND","int32"),r=$(t,"updates","scatterND");fg(r,s,n);let a={indices:s,updates:r},o={shape:n};return z.runKernel(cl,a,o)}var _b=W({scatterND_:jR});function qR(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 XR(e,t,n,s=0){let r=$(e,"sparseIndices","sparseToDense","int32"),a=$(t,"sparseValues","sparseToDense"),o=$(s,"defaultValue","sparseToDense",a.dtype);qR(r,a,n,o);let i={sparseIndices:r,sparseValues:a,defaultValue:o},l={outputShape:n};return z.runKernel(Ch,i,l)}var eA=W({sparseToDense_:XR});function KR(e,t){let n=$(t,"indices","gatherND","int32"),r={params:$(e,"x","gatherND","string_or_numeric"),indices:n};return z.runKernel(Hi,r)}var Db=W({gatherND_:KR});function ZR(e,t){if(t==null)return e.shape.slice();if(br(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.`),M(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof Ge?r.clone():r;let a=ZR(r,n),o=1-t,i=de(pc(ae(Wl(a,0,1,"float32",s),o)),o);return L(r,i)}var $b=W({dropout_:YR});function Fb(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function tA(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}`),M(s.rank-1===r.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${s.rank} and targets rank ${r.rank}`),An(s.shape.slice(0,s.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let a=s.shape[s.shape.length-1];M(n>0&&n<=a,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`);let o=await s.data(),i=await r.data(),[l,u]=[o.length/a,a],c=v5("bool",l);for(let d=0;dg.value-m.value),c[d]=0;for(let m=0;mn_,depthwiseConv2d:()=>o_,matMul:()=>l_});function e_(e,t,n,s,r,a="NHWC",o){let i=e;e.rank===3&&(i=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=U(t,[1,t.shape[0],t.shape[1],t.shape[2]])),M(i.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),M(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),M(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);let u=a==="NHWC"?i.shape[3]:i.shape[1],c=a==="NHWC"?l.shape[3]:l.shape[1];M(u===n[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${n[2]}.`),M(c===n[3],()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${n[3]}).`),o!=null&&M(Zt(r),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let d={x:i,dy:l},h={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,filterShape:n};return z.runKernel(Qd,d,h)}var nA=W({conv2DBackpropFilter_:e_});function dp(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return L(e,yc(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function hp(e,t){let n=t,s=Gt(e.shape,t.shape);return s.length>0&&(n=ve(n,s)),U(n,e.shape)}function pp(e,t,n,s){if(t==="linear")return e;if(t==="relu")return sr(e);if(t==="elu")return hc(e);if(t==="relu6")return Vg(e);if(t==="prelu")return rp(e,n);if(t==="leakyrelu")return Zh(e,s);if(t==="sigmoid")return Hn(e);throw new Error(`Unknown fused activation ${t}.`)}var fp=(e,t)=>!(e>0)||t==="linear";function t_({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(l=l||"linear",fp(z.state.gradientDepth,l)===!1){let v=Jr(e,t,n,s,r,a,o);return i!=null&&(v=ae(v,i)),pp(v,l,u,c)}let d=$(e,"x","conv2d"),h=$(t,"filter","conv2d"),p=d,f=!1;d.rank===3&&(f=!0,p=U(d,[1,d.shape[0],d.shape[1],d.shape[2]])),M(p.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${p.rank}.`),M(h.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${h.rank}.`),o!=null&&M(Zt(s),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`),M(p.shape[3]===h.shape[2],()=>`Error in conv2d: depth of input (${p.shape[3]}) must match input depth for filter ${h.shape[2]}.`),M(tr(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),M(r==="NHWC",()=>`Error in conv2d: got dataFormat of ${r} but only NHWC is currently supported.`);let m=uc(p.shape,h.shape,n,a,s,o),g;i!=null&&(g=$(i,"bias","fused conv2d"),[g]=Ct(g,d),At(m.outShape,g.shape));let A;u!=null&&(A=$(u,"prelu weights","fused conv2d"));let y=(v,k)=>{let[S,C,_,O]=k,E=dp(v,_,l);M(Yr(a),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);let R=Tg(C.shape,E,S,n,s),T=nA(C,E,S.shape,n,s),P=[R,T];if(O!=null){let V=hp(O,E);P.push(V)}return P},x={x:p,filter:h,bias:g,preluActivationWeights:A},b={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:c};return i==null?nr((k,S,C)=>{let _=z.runKernel(Co,x,b);return C([S,k,_]),f&&(_=U(_,[_.shape[1],_.shape[2],_.shape[3]])),{value:_,gradFunc:y}})(p,h):nr((k,S,C,_)=>{let O=z.runKernel(Co,x,b);return _([S,k,O,C]),f&&(O=U(O,[O.shape[1],O.shape[2],O.shape[3]])),{value:O,gradFunc:y}})(p,h,g)}var n_=W({fusedConv2d_:t_});function s_(e,t,n,s,r,a=[1,1],o){let i=e;e.rank===3&&(i=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=U(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={x:i,dy:l},c={strides:s,pad:r,dimRoundingMode:o,dilations:a,filterShape:n};return z.runKernel(sh,u,c)}var Ob=W({depthwiseConv2dNativeBackpropFilter_:s_});function r_(e,t,n,s,r,a=[1,1],o){let i=t,l=!1;t.rank===3&&(l=!0,i=U(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={dy:i,filter:n},c={strides:s,pad:r,dimRoundingMode:o,dilations:a,inputShape:e},d=z.runKernel(rh,u,c);return l?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Pb=W({depthwiseConv2dNativeBackpropInput_:r_});function a_({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(fp(z.state.gradientDepth,l)===!1){let v=dc(e,t,n,s,r,a,o);return i!=null&&(v=ae(v,i)),pp(v,l,u,c)}let d=$(e,"x","depthwiseConv2d"),h=$(t,"filter","depthwiseConv2d"),p=d,f=!1;d.rank===3&&(f=!0,p=U(d,[1,d.shape[0],d.shape[1],d.shape[2]])),M(p.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${p.rank}.`),M(h.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`),M(p.shape[3]===h.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${p.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`),a==null&&(a=[1,1]),M(tr(n,a),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o!=null&&M(Zt(s),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${o} but got pad ${s}.`);let m=uc(p.shape,h.shape,n,a,s,o,!0),g;i!=null&&(g=$(i,"bias","fused conv2d"),[g]=Ct(g,d),At(m.outShape,g.shape));let A;u!=null&&(A=$(u,"prelu weights","fused depthwiseConv2d"));let y=(v,k)=>{M(Yr(a),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);let[S,C,_,O]=k,E=dp(v,_,l),R=Pb(C.shape,E,S,n,s,a,o),T=Ob(C,E,S.shape,n,s,a,o);if(O!=null){let P=hp(g,E);return[R,T,P]}return[R,T]},x={x:p,filter:h,bias:g,preluActivationWeights:A},b={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:c};return i==null?nr((k,S,C)=>{let _=z.runKernel(To,x,b);return C([S,k,_]),f&&(_=U(_,[_.shape[1],_.shape[2],_.shape[3]])),{value:_,gradFunc:y}})(p,h):nr((k,S,C,_)=>{let O=z.runKernel(To,x,b);return _([S,k,O,C]),f&&(O=U(O,[O.shape[1],O.shape[2],O.shape[3]])),{value:O,gradFunc:y}})(p,h,g)}var o_=W({fusedDepthwiseConv2d_:a_});function i_({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:r,activation:a="linear",preluActivationWeights:o,leakyreluAlpha:i}){if(fp(z.state.gradientDepth,a)===!1){let O=Ve(e,t,n,s);return r!=null&&(O=ae(O,r)),pp(O,a,o,i)}let l=$(e,"a","fused matMul"),u=$(t,"b","fused matMul");[l,u]=Ct(l,u);let c=n?l.shape[l.rank-2]:l.shape[l.rank-1],d=s?u.shape[u.rank-1]:u.shape[u.rank-2],h=n?l.shape[l.rank-1]:l.shape[l.rank-2],p=s?u.shape[u.rank-2]:u.shape[u.rank-1],f=l.shape.slice(0,-2),m=u.shape.slice(0,-2),g=$t(f),A=$t(m);M(l.rank>=2&&u.rank>=2&&l.rank===u.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${l.rank} and ${u.rank}.`),M(br(f,m),()=>`Error in fused matMul: outer dimensions (${f}) and (${m}) of Tensors with shapes ${l.shape} and ${u.shape} must match.`),M(c===d,()=>`Error in fused matMul: inner shapes (${c}) and (${d}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${n} and transposeB=${s} must match.`);let y=l.shape.slice(0,-2).concat([h,p]),x=n?U(l,[g,c,h]):U(l,[g,h,c]),b=s?U(u,[A,p,d]):U(u,[A,d,p]),v;r!=null&&(v=$(r,"bias","fused matMul"),[v]=Ct(v,l),At(y,v.shape));let k;o!=null&&(k=$(o,"prelu weights","fused matMul"));let S=(O,E)=>{let[R,T,P,V]=E,j=dp(U(O,P.shape),P,a),q,X;if(!n&&!s?(q=Ve(j,T,!1,!0),X=Ve(R,j,!0,!1)):!n&&s?(q=Ve(j,T,!1,!1),X=Ve(j,R,!0,!1)):n&&!s?(q=Ve(T,j,!1,!0),X=Ve(R,j,!1,!1)):(q=Ve(T,j,!0,!0),X=Ve(j,R,!0,!0)),r!=null){let ee=hp(V,j);return[q,X,ee]}else return[q,X]},C={a:x,b,bias:v,preluActivationWeights:k},_={transposeA:n,transposeB:s,activation:a,leakyreluAlpha:i};return r==null?nr((E,R,T)=>{let P=z.runKernel(So,C,_);return T([E,R,P]),{value:U(P,y),gradFunc:S}})(x,b):nr((E,R,T,P)=>{let V=z.runKernel(So,C,_);return P([E,R,V,T]),{value:U(V,y),gradFunc:S}})(x,b,v)}var l_=W({fusedMatMul_:i_});function u_(e){return tA(e,.54,.46)}var c_=W({hammingWindow_:u_});function d_(e){return tA(e,.5,.5)}var Mb=W({hannWindow_:d_});function h_(e,t,n,s=!1,r=0){let a=0,o=[];for(;a+t<=e.size;)o.push(Re(e,a,t)),a+=n;if(s)for(;a`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),M(i.rank===2&&i.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${i.shape}.`),M(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${i.shape}.`),M(s.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),M(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),M(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);let c={image:o,boxes:i,boxInd:l},d={method:r,extrapolationValue:a,cropSize:s};return z.runKernel(Pi,c,d)}var g_=W({cropAndResize_:m_});function A_(e){let t=$(e,"image","flipLeftRight","float32");M(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return z.runKernel(Vi,n,{})}var y_=W({flipLeftRight_:A_});function x_(e){let t=$(e,"image","grayscaleToRGB"),n=t.rank-1,s=t.shape[n];M(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),M(s===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${s}.`);let r=new Array(t.rank);return r.fill(1,0,n),r[n]=3,Ts(t,r)}var b_=W({grayscaleToRGB_:x_});function v_(e,t,n=0,s=.5){let r=$(e,"image","rotateWithOffset","float32");M(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);let a={image:r},o={radians:t,fillValue:n,center:s};return z.runKernel(Il,a,o)}var w_=W({rotateWithOffset_:v_});function Ul(e,t,n,s,r,a){s==null&&(s=.5),r==null&&(r=Number.NEGATIVE_INFINITY),a==null&&(a=0);let o=e.shape[0];return n=Math.min(n,o),M(0<=s&&s<=1,()=>`iouThreshold must be in [0, 1], but was '${s}'`),M(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),M(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),M(t.rank===1,()=>"scores must be a 1D tensor"),M(t.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`),M(0<=a&&a<=1,()=>`softNmsSigma must be in [0, 1], but was '${a}'`),{maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a}}function k_(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=$(e,"boxes","nonMaxSuppression"),o=$(t,"scores","nonMaxSuppression"),i=Ul(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l={maxOutputSize:n,iouThreshold:s,scoreThreshold:r};return z.runKernel(nl,{boxes:a,scores:o},l)}var I_=W({nonMaxSuppression_:k_});function S_(e,t,n){let s=C_(e,t,n),r=s<0?-(s+1):s;e.splice(r,0,t)}function C_(e,t,n){return N_(e,t,n||T_)}function T_(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 Lb(e,t,n,s,r){return sA(e,t,n,s,r,0)}function Bb(e,t,n,s,r,a){return sA(e,t,n,s,r,0,!1,a,!0)}function Wb(e,t,n,s,r,a){return sA(e,t,n,s,r,a,!0)}function sA(e,t,n,s,r,a,o=!1,i=!1,l=!1){let u=[];for(let g=0;gr&&u.push({score:t[g],boxIndex:g,suppressBeginIndex:0});u.sort(Vb);let c=a>0?-.5/a:0,d=[],h=[];for(;d.length0;){let g=u.pop(),{score:A,boxIndex:y,suppressBeginIndex:x}=g;if(A=x;--v){let k=E_(e,y,d[v]);if(k>=s){b=!0;break}if(g.score=g.score*R_(s,c,k),g.score<=r)break}g.suppressBeginIndex=d.length,b||(g.score===A?(d.push(y),h.push(g.score)):g.score>r&&S_(u,g,Vb))}let p=d.length,f=n-p;i&&f>0&&(d.push(...new Array(f).fill(0)),h.push(...new Array(f).fill(0)));let m={selectedIndices:d};return o&&(m.selectedScores=h),l&&(m.validOutputs=p),m}function E_(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]),u=Math.min(r[0],r[2]),c=Math.min(r[1],r[3]),d=Math.max(r[0],r[2]),h=Math.max(r[1],r[3]),p=(i-a)*(l-o),f=(d-u)*(h-c);if(p<=0||f<=0)return 0;let m=Math.max(a,u),g=Math.max(o,c),A=Math.min(i,d),y=Math.min(l,h),x=Math.max(A-m,0)*Math.max(y-g,0);return x/(p+f-x)}function R_(e,t,n){let s=Math.exp(t*n*n);return n<=e?s:0}function Vb(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function __(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=$(e,"boxes","nonMaxSuppressionAsync"),o=$(t,"scores","nonMaxSuppressionAsync"),i=Ul(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l=await Promise.all([a.data(),o.data()]),u=l[0],c=l[1],{selectedIndices:d}=Lb(u,c,n,s,r);return a!==e&&a.dispose(),o!==t&&o.dispose(),Mt(d,"int32")}var D_=__;function $_(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=$(e,"boxes","nonMaxSuppression"),i=$(t,"scores","nonMaxSuppression"),l=Ul(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let u={boxes:o,scores:i},c={maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a},d=z.runKernel(rl,u,c);return{selectedIndices:d[0],selectedScores:d[1]}}var F_=W({nonMaxSuppressionWithScore_:$_});async function O_(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=$(e,"boxes","nonMaxSuppressionAsync"),i=$(t,"scores","nonMaxSuppressionAsync"),l=Ul(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let u=await Promise.all([o.data(),i.data()]),c=u[0],d=u[1],{selectedIndices:h,selectedScores:p}=Wb(c,d,n,s,r,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Mt(h,"int32"),selectedScores:Mt(p)}}var P_=O_;function M_(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=$(e,"boxes","nonMaxSuppression"),i=$(t,"scores","nonMaxSuppression"),l=Ul(o,i,n,s,r,null),u=l.maxOutputSize,c=l.iouThreshold,d=l.scoreThreshold,h={boxes:o,scores:i},p={maxOutputSize:u,iouThreshold:c,scoreThreshold:d,padToMaxOutputSize:a},f=z.runKernel(sl,h,p);return{selectedIndices:f[0],validOutputs:f[1]}}var z_=W({nonMaxSuppressionPadded_:M_});async function L_(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=$(e,"boxes","nonMaxSuppressionAsync"),i=$(t,"scores","nonMaxSuppressionAsync"),l=Ul(o,i,n,s,r,null),u=l.maxOutputSize,c=l.iouThreshold,d=l.scoreThreshold,[h,p]=await Promise.all([o.data(),i.data()]),{selectedIndices:f,validOutputs:m}=Bb(h,p,u,c,d,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Mt(f,"int32"),validOutputs:Ie(m,"int32")}}var B_=L_;function W_(e,t,n=!1,s=!1){let r=$(e,"images","resizeBilinear");M(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),M(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),M(s===!1||n===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let a=r,o=!1;r.rank===3&&(o=!0,a=U(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},u=z.runKernel(uo,i,l);return o?U(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var V_=W({resizeBilinear_:W_});function U_(e,t,n=!1,s=!1){let r=$(e,"images","resizeNearestNeighbor");M(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),M(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),M(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),M(s===!1||n===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let a=r,o=!1;r.rank===3&&(o=!0,a=U(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},u=z.runKernel(qu,i,l);return o?U(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var H_=W({resizeNearestNeighbor_:U_});function G_(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],u=L(Mt([s]),255),c,d,h,p;if(M(r.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`),M(r.shape[2]===3||r.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`),M(r.dtype==="int32"||r.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`),M(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),r.shape[2]===3){[c,d,h]=an(r,[1,1,1],-1);let g=L(c,a),A=L(d,o),y=L(h,i);p=ae(ae(g,A),y)}else p=e;if(t==="otsu"){let g=Sg(ce(Ug(p),"int32"),dn([]),256);u=j_(g,l)}let f=n?Mo(p,u):jn(p,u);return ce(L(f,255),"int32")}function j_(e,t){let n=Mt([-1]),s=Mt([0]),r=Mt([0]),a,o,i,l,u,c;for(let d=0;d`Error in transform: image must be rank 4,but got rank ${o.rank}.`),M(i.rank===2&&(i.shape[0]===o.shape[0]||i.shape[0]===1)&&i.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),M(a==null||a.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`);let l={image:o,transforms:i},u={interpolation:n,fillMode:s,fillValue:r,outputShape:a};return z.runKernel(vl,l,u)}var K_=W({transform_:X_});function Z_(e,t,n){M(t%1==0,()=>`bandPart(): numLower must be an integer, got ${t}.`),M(n%1==0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);let s=$(e,"a","bandPart");M(s.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`);let r=s.shape,[a,o]=s.shape.slice(-2);if(!(t<=a))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`);if(!(n<=o))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`);t<0&&(t=a),n<0&&(n=o);let i=U(Vl(0,a,1,"int32"),[-1,1]),l=Vl(0,o,1,"int32"),u=ge(i,l),c=Ps(Mo(u,Ie(+t,"int32")),Po(u,Ie(-n,"int32"))),d=Pt([a,o],s.dtype);return U(Dn(ms(U(s,[-1,a,o])).map(h=>bn(c,h,d))),r)}var Y_=W({bandPart_:Z_});function J_(e){let t;if(Array.isArray(e)){t=!1,M(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let r=e[0].shape[0];for(let a=1;a`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[a].shape[0]} vs. ${r})`)}else t=!0,e=an(e,e.shape[0],0).map(r=>lt(r,[0]));M(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let n=[],s=e;for(let r=0;r{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 Ub(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,u)=>l*u),s=ms(U(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],a=[];s.forEach(l=>{let[u,c]=Ub(l,t);r.push(u),a.push(c)});let o=U(Dn(r,0),e.shape),i=U(Dn(a,0),e.shape);return[o,i]}}function Ub(e,t=!1){return z.tidy(()=>{M(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let n=e.shape[0],s=e.shape[1],r=Dg(n),a=Os(e),o=Ms([[1]],[1,1]),i=Os(o),l=n>=s?s:n;for(let u=0;u{let p=Re(a,[u,u],[n-u,1]),f=Qg(p),m=Re(a,[u,u],[1,1]),g=bn(jn(m,0),Ms([[-1]]),Ms([[1]])),A=ge(m,L(g,f)),y=de(p,A);y.shape[0]===1?i=Os(o):i=ft([o,Re(y,[1,0],[y.shape[0]-1,y.shape[1]])],0);let x=Tt(de(Ve(g,A),f)),b=Re(a,[u,0],[n-u,s]),v=L(x,i),k=Xe(i);if(u===0)a=ge(b,Ve(v,Ve(k,b)));else{let _=ge(b,Ve(v,Ve(k,b)));a=ft([Re(a,[0,0],[u,s]),_],0)}let S=Xe(v),C=Re(r,[0,u],[n,r.shape[1]-u]);if(u===0)r=ge(C,Ve(Ve(C,i),S));else{let _=ge(C,Ve(Ve(C,i),S));r=ft([Re(r,[0,0],[n,u]),_],1)}return[i,a,r]}),Z([c,d,h])}return!t&&n>s&&(r=Re(r,[0,0],[n,s]),a=Re(a,[0,0],[s,s])),[r,a]})}var tD=W({qr_:eD}),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 nD(e,t,n=vn.SUM_BY_NONZERO_WEIGHTS){let s=$(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=$(t,"weights","computeWeightedLoss"));let a=r==null?s:L(s,r);if(n===vn.NONE)return a;if(n===vn.SUM)return ve(a);if(n===vn.MEAN){if(r==null)return _t(a);{let o=s.size/r.size,i=de(ve(a),ve(r));return o>1?de(i,Ie(o)):i}}if(n===vn.SUM_BY_NONZERO_WEIGHTS){if(r==null)return de(ve(a),Ie(s.size));{let o=L(r,qn(s.shape)),i=ce(ve(Bl(o,Ie(0))),"float32");return de(ve(a),i)}}throw Error(`Unknown reduction: ${n}`)}var Ir=W({computeWeightedLoss_:nD});function sD(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")),An(r.shape,a.shape,"Error in absoluteDifference: ");let i=Ht(ge(r,a));return Ir(i,o,s)}var rD=W({absoluteDifference_:sD});function aD(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")),An(a.shape,o.shape,"Error in cosineDistance: ");let l=Ie(1),u=ge(l,ve(L(a,o),n,!0));return Ir(u,i,r)}var oD=W({cosineDistance_:aD});function iD(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")),An(r.shape,a.shape,"Error in hingeLoss: ");let i=Ie(1);r=ge(L(Ie(2),r),i);let l=sr(ge(i,L(r,a)));return Ir(l,o,s)}var lD=W({hingeLoss_:iD});function uD(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")),An(a.shape,o.shape,"Error in huberLoss: ");let l=Ie(s),u=Ht(ge(o,a)),c=fc(u,l),d=ge(u,c),h=ae(L(Ie(.5),ct(c)),L(l,d));return Ir(h,i,r)}var cD=W({huberLoss_:uD});function dD(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")),An(a.shape,o.shape,"Error in logLoss: ");let l=Ie(1),u=Ie(s),c=Tt(L(a,ds(ae(o,u)))),d=L(ge(l,a),ds(ae(ge(l,o),u))),h=ge(c,d);return Ir(h,i,r)}var hD=W({logLoss_:dD});function pD(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")),An(r.shape,a.shape,"Error in meanSquaredError: ");let i=Zg(r,a);return Ir(i,o,s)}var fD=W({meanSquaredError_:pD});function mD(e,t){let n=$(e,"labels","sigmoidCrossEntropyWithLogits"),s=$(t,"logits","sigmoidCrossEntropyWithLogits");An(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=sr(s),a=L(s,n),o=Yh(cs(Tt(Ht(s))));return ae(ge(r,a),o)}function gD(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")),An(a.shape,o.shape,"Error in sigmoidCrossEntropy: "),s>0){let u=Ie(s),c=Ie(1),d=Ie(.5);a=ae(L(a,ge(c,u)),L(d,u))}let l=mD(a,o);return Ir(l,i,r)}var AD=W({sigmoidCrossEntropy_:gD});function yD(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 nr((r,a,o)=>{let l=fb(a,[n],!0),u=ge(ce(a,"float32"),l);o([r,u]);let c=Tt(L(u,r));return{value:ve(c,[n]),gradFunc:(p,f)=>{let[m,g]=f,A=zo(p.shape,[n]);return[L(U(p,A),ge(ce(m,"float32"),cs(g))),L(U(p,A),ge(cs(g),ce(m,"float32")))]}}})(e,t)}function xD(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")),An(a.shape,o.shape,"Error in softmaxCrossEntropy: "),s>0){let u=Ie(s),c=Ie(1),d=Ie(a.shape[1]);a=ae(L(a,ge(c,u)),de(u,d))}let l=yD(a,o);return Ir(l,i,r)}var bD=W({softmaxCrossEntropy_:xD});function vD(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},u=z.runKernel(wh,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var wD=W({sparseFillEmptyRows_:vD});function kD(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=z.runKernel(kh,o);return{outputIndices:i[0],outputShape:i[1]}}var ID=W({sparseReshape_:kD});function SD(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 z.runKernel(Ih,o)}var SD=W({sparseSegmentMean_:ID});function CD(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
+ ${a.shape}`);let o={data:s,indices:r,segmentIds:a};return z.runKernel(Ih,o)}var CD=W({sparseSegmentMean_:SD});function TD(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 z.runKernel(Sh,o)}var TD=W({sparseSegmentSum_:CD});function ND(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 u=$(t,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let c={separator:n,nGramWidths:s,leftPad:r,rightPad:a,padWidth:o,preserveShortSequences:i},d={data:l,dataSplits:u},h=z.runKernel(Th,d,c);return{nGrams:h[0],nGramsSplits:h[1]}}var ED=W({stringNGrams_:ND});function RD(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=z.runKernel(Nh,o,a);return{indices:i[0],values:i[1],shape:i[2]}}var _D=W({stringSplit_:RD});function DD(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 z.runKernel(Eh,r,s)}var $D=W({stringToHashBucketFast_:DD}),FD={fft:lp,ifft:Ac,rfft:up,irfft:Xg},OD={hammingWindow:u_,hannWindow:Mb,frame:zb,stft:p_},_e={flipLeftRight:A_,grayscaleToRGB:x_,resizeNearestNeighbor:U_,resizeBilinear:W_,rotateWithOffset:v_,cropAndResize:m_,nonMaxSuppression:k_,nonMaxSuppressionAsync:__,nonMaxSuppressionWithScore:$_,nonMaxSuppressionWithScoreAsync:O_,nonMaxSuppressionPadded:M_,nonMaxSuppressionPaddedAsync:L_,threshold:j_,transform:X_},Hb={bandPart:Z_,gramSchmidt:J_,qr:eD},PD={absoluteDifference:sD,computeWeightedLoss:Ir,cosineDistance:aD,hingeLoss:iD,huberLoss:uD,logLoss:dD,meanSquaredError:pD,sigmoidCrossEntropy:gD,softmaxCrossEntropy:xD},xc={sparseFillEmptyRows:vD,sparseReshape:kD,sparseSegmentMean:SD,sparseSegmentSum:TD},mp={stringNGrams:ED,stringSplit:_D,stringToHashBucketFast:$D},Sr=class extends Tx{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 Z(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 cb(e,t)}dispose(){this.iterations_!=null&&Z(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Ie(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(Sr,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var gp=class extends Sr{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=z.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=z.registeredVariables[n],a=!1;this.accumulatedGrads[s]==null&&(this.accumulatedGrads[s]={originalName:`${n}/accum_grad`,variable:H(()=>Ke(r).variable(a))}),this.accumulatedUpdates[s]==null&&(this.accumulatedUpdates[s]={originalName:`${n}/accum_var`,variable:H(()=>Ke(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;H(()=>{let u=ae(L(i,this.rho),L(ct(o),1-this.rho)),c=L(de(hn(ae(l,this.epsilon)),hn(ae(i,this.epsilon))),o),d=ae(L(l,this.rho),L(ct(c),1-this.rho));i.assign(u),l.assign(d);let h=ae(L(c,-this.learningRate),r);r.assign(h)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Z(this.accumulatedGrads.map(e=>e.variable)),Z(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)}};gp.className="Adadelta";Zr(gp);var Ap=class extends Sr{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=z.registeredVariables[n];if(this.accumulatedGrads[s]==null){let i=!1;this.accumulatedGrads[s]={originalName:`${n}/accumulator`,variable:H(()=>Ml(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;H(()=>{let i=ae(o,ct(a));o.assign(i);let l=ae(L(de(a,hn(ae(i,z.backend.epsilon()))),-this.learningRate),r);r.assign(l)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Z(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)}};Ap.className="Adagrad";Zr(Ap);var yp=class extends Sr{constructor(e,t,n,s=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],H(()=>{this.accBeta1=Ie(t).variable(),this.accBeta2=Ie(n).variable()}),s==null&&(this.epsilon=z.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);H(()=>{let n=ge(1,this.accBeta1),s=ge(1,this.accBeta2);t.forEach((r,a)=>{let o=z.registeredVariables[r],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${r}/m`,variable:H(()=>Ke(o).variable(i))}),this.accumulatedSecondMoment[a]==null&&(this.accumulatedSecondMoment[a]={originalName:`${r}/v`,variable:H(()=>Ke(o).variable(i))});let l=Array.isArray(e)?e[a].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[a].variable,c=this.accumulatedSecondMoment[a].variable,d=ae(L(u,this.beta1),L(l,1-this.beta1)),h=ae(L(c,this.beta2),L(ct(l),1-this.beta2)),p=de(d,n),f=de(h,s);u.assign(d),c.assign(h);let m=ae(L(de(p,ae(hn(f),this.epsilon)),-this.learningRate),o);o.assign(m)}),this.accBeta1.assign(L(this.accBeta1,this.beta1)),this.accBeta2.assign(L(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Z(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Z(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),H(()=>{this.accBeta1.assign(ea(this.beta1,this.iterations_+1)),this.accBeta2.assign(ea(this.beta2,this.iterations_+1))});let t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}};yp.className="Adam";Zr(yp);var xp=class extends Sr{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=[],H(()=>{this.iteration=Ie(0).variable(),this.accBeta1=Ie(t).variable()}),s==null&&(this.epsilon=z.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);H(()=>{let n=ge(1,this.accBeta1),s=de(-this.learningRate,ae(L(this.iteration,this.decay),1));t.forEach((r,a)=>{let o=z.registeredVariables[r],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${r}/m`,variable:Ke(o).variable(i)}),this.accumulatedWeightedInfNorm[a]==null&&(this.accumulatedWeightedInfNorm[a]={originalName:`${r}/v`,variable:Ke(o).variable(i)});let l=Array.isArray(e)?e[a].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[a].variable,c=this.accumulatedWeightedInfNorm[a].variable,d=ae(L(u,this.beta1),L(l,1-this.beta1)),h=L(c,this.beta2),p=Ht(l),f=kr(h,p);u.assign(d),c.assign(f);let m=ae(L(de(s,n),de(d,ae(f,this.epsilon))),o);o.assign(m)}),this.iteration.assign(ae(this.iteration,1)),this.accBeta1.assign(L(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Z(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Z(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)}};xp.className="Adamax";Zr(xp);var bc=class extends Sr{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=z.registeredVariables[n];H(()=>{let o=ae(L(this.c,r),a);a.assign(o)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=Jt(Ie(-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)}};bc.className="SGD";Zr(bc);var bp=class extends bc{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ie(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=z.registeredVariables[n];if(this.accumulations[s]==null){let i=!1;this.accumulations[s]={originalName:`${n}/momentum`,variable:H(()=>Ke(r).variable(i))}}let a=this.accumulations[s].variable,o=Array.isArray(e)?e[s].tensor:e[n];o!=null&&H(()=>{let i,l=ae(L(this.m,a),o);this.useNesterov?i=ae(L(this.c,ae(o,L(l,this.m))),r):i=ae(L(this.c,l),r),a.assign(l),r.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Z(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)}};bp.className="Momentum";Zr(bp);var vp=class extends Sr{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=z.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=z.registeredVariables[n],a=!1;this.accumulatedMeanSquares[s]==null&&(this.accumulatedMeanSquares[s]={originalName:`${n}/rms`,variable:H(()=>Ke(r).variable(a))}),this.accumulatedMoments[s]==null&&(this.accumulatedMoments[s]={originalName:`${n}/momentum`,variable:H(()=>Ke(r).variable(a))}),this.accumulatedMeanGrads[s]==null&&this.centered&&(this.accumulatedMeanGrads[s]={originalName:`${n}/mg`,variable:H(()=>Ke(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;H(()=>{let u=ae(L(i,this.decay),L(ct(o),1-this.decay));if(this.centered){let c=this.accumulatedMeanGrads[s].variable,d=ae(L(c,this.decay),L(o,1-this.decay)),h=de(L(o,this.learningRate),hn(ge(u,ae(ct(d),this.epsilon)))),p=ae(L(l,this.momentum),h);i.assign(u),c.assign(d),l.assign(p);let f=ge(r,p);r.assign(f)}else{let c=ae(L(i,this.decay),L(ct(o),1-this.decay)),d=ae(L(l,this.momentum),de(L(o,this.learningRate),hn(ae(c,this.epsilon))));i.assign(c),l.assign(d);let h=ge(r,d);r.assign(h)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Z(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Z(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Z(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)}};vp.className="RMSProp";Zr(vp);var Lo=class{static sgd(e){return new bc(e)}static momentum(e,t,n=!1){return new bp(e,t,n)}static rmsprop(e,t=.9,n=0,s=null,r=!1){return new vp(e,t,n,s,r)}static adam(e=.001,t=.9,n=.999,s=null){return new yp(e,t,n,s)}static adadelta(e=.001,t=.95,n=null){return new gp(e,t,n)}static adamax(e=.002,t=.9,n=.999,s=null,r=0){return new xp(e,t,n,s,r)}static adagrad(e,t=.1){return new Ap(e,t)}},Bo={sgd:Lo.sgd,momentum:Lo.momentum,adadelta:Lo.adadelta,adagrad:Lo.adagrad,rmsprop:Lo.rmsprop,adamax:Lo.adamax,adam:Lo.adam},MD=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function wp(){return new Promise(e=>MD(()=>e()))}var D={};Pe(D,{ERF_A1:()=>XD,ERF_A2:()=>KD,ERF_A3:()=>ZD,ERF_A4:()=>YD,ERF_A5:()=>JD,ERF_P:()=>qD,PARALLELIZE_THRESHOLD:()=>sA,SELU_SCALE:()=>jb,SELU_SCALEALPHA:()=>Gb,applyActivation:()=>pp,assertAndGetBroadcastShape:()=>At,assertAxesAreInnerMostDims:()=>KN,assertParamsConsistent:()=>zD,assignToTypedArray:()=>r$,axesAreInnerMostDims:()=>Fg,calculateShapes:()=>mx,checkEinsumDimSizes:()=>c$,combineLocations:()=>db,complexWithEvenIndex:()=>t$,complexWithOddIndex:()=>n$,computeConv2DInfo:()=>uc,computeConv3DInfo:()=>Vx,computeDefaultPad:()=>vg,computeDilation2DInfo:()=>fT,computeOptimalWindowSize:()=>BD,computeOutAndReduceShapes:()=>hb,computeOutShape:()=>LD,computePool2DInfo:()=>Wx,computePool3DInfo:()=>mT,convertConv2DDataFormat:()=>Ux,decodeEinsumEquation:()=>l$,eitherStridesOrDilationsAreOne:()=>tr,expandShapeToKeepDim:()=>zo,exponent:()=>o$,exponents:()=>a$,fromStringArrayToUint8:()=>x$,fromUint8ToStringArray:()=>y$,getAxesPermutation:()=>pb,getBroadcastDims:()=>oN,getComplexWithIndex:()=>s$,getEinsumComputePath:()=>d$,getEinsumPermutation:()=>u$,getFusedBiasGradient:()=>hp,getFusedDyActivation:()=>dp,getImageCenter:()=>WD,getInnerMostAxes:()=>ZN,getPermuted:()=>UD,getReductionAxes:()=>Gt,getReshaped:()=>VD,getReshapedPermuted:()=>HD,getSliceBeginCoords:()=>GD,getSliceSize:()=>jD,getUndoAxesPermutation:()=>Og,isIdentityPermutation:()=>h$,log:()=>zS,mergeRealAndImagArrays:()=>QD,prepareAndValidate:()=>fx,prepareSplitSize:()=>f$,segment_util:()=>Kb,shouldFuse:()=>fp,slice_util:()=>xn,splitRealAndImagArrays:()=>e$,tupleValuesAreOne:()=>Yr,upcastType:()=>Cs,validateInput:()=>pg,validateUpdateShape:()=>hg,warn:()=>Ys});function zD(e,t){let n=e[0].length;e.forEach((r,a)=>{M(r.length===n,()=>`Error in concat${n}D: rank of tensors[${a}] must be the same as the rank of the rest (${n})`)}),M(t>=0&&t`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 LD(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 HD(e,t,n,s=!0){let r=[];s?r.push(e[0]/n):r.push(e[0]*n);for(let a=1;a/g,qb=",",Xb="...";function l$(e,t){e=e.replace(/\s/g,"");let n=(e.length-e.replace(i$,"").length)/rA.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 ("${rA}").`);let[s,r]=e.split(rA);M(s.indexOf(Xb)===-1,()=>`The ellipsis notation ("${Xb}") is not supported yet.`);let a=s.split(qb),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 h=0;hf.indexOf(p)!==-1))throw new Error(`Output subscripts contain the label ${p} not present in the input subscripts.`);i.indexOf(p)===-1&&i.push(p)}for(let h=0;h