/* Human homepage: author: ' */ var Human=(()=>{var u2=Object.defineProperty;var TE=(e,t,n)=>t in e?u2(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var NE=e=>u2(e,"__esModule",{value:!0});var Ia=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof require!="undefined"?require:t)[n]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var Qc=(e,t)=>{NE(e);for(var n in t)u2(e,n,{get:t[n],enumerable:!0})};var he=(e,t,n)=>(TE(e,typeof t!="symbol"?t+"":t,n),n),L5=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var ed=(e,t,n)=>(L5(e,t,"read from private field"),n?n.call(e):t.get(e)),td=(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)},nd=(e,t,n,s)=>(L5(e,t,"write to private field"),s?s.call(e,n):t.set(e,n),n);var h1e={};Qc(h1e,{Human:()=>EN,default:()=>EN,defaults:()=>Ca,env:()=>de});function Z(...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)}function We(e,t){let n=e.endsWith("/")?"":"/",r=t.startsWith(".")||t.startsWith("/")||t.startsWith("http:")||t.startsWith("https:")||t.startsWith("file:")?`${t}`:`${e}${n}${t}`;if(!r.toLocaleLowerCase().includes(".json"))throw new Error(`modelpath error: expecting json file: ${r}`);return r}var ie=()=>typeof performance!="undefined"?performance.now():parseInt((Number(process.hrtime.bigint())/1e3/1e3).toString());function c2(e,t,n="config",s=[]){for(let r of Object.keys(t))if(typeof t[r]=="object")c2(e[r],t[r],r,s);else{let a=e&&typeof e[r]!="undefined";a||s.push({reason:"unknown property",where:`${n}.${r} = ${t[r]}`});let o=e&&typeof e[r]==typeof t[r];a&&!o&&s.push({reason:"property type mismatch",where:`${n}.${r} = ${t[r]}`,expected:typeof e[r]})}return t.debug&&n==="config"&&s.length>0&&Z("invalid configuration",s),s}function $n(...e){let t=n=>n&&typeof n=="object";return e.reduce((n,s)=>(Object.keys(s||{}).forEach(r=>{let a=n[r],o=s[r];Array.isArray(a)&&Array.isArray(o)?n[r]=a.concat(...o):t(a)&&t(o)?n[r]=$n(a,o):n[r]=o}),n),{})}var Ca={backend:"",modelBasePath:"",wasmPath:"",debug:!0,async:!0,warmup:"full",cacheSensitivity:.7,skipAllowed:!1,deallocate:!1,filter:{enabled:!0,equalization:!1,width:0,height:0,flip:!1,return:!0,brightness:0,contrast:0,sharpness:0,blur:0,saturation:0,hue:0,negative:!1,sepia:!1,vintage:!1,kodachrome:!1,technicolor:!1,polaroid:!1,pixelate:0},gesture:{enabled:!0},face:{enabled:!0,detector:{modelPath:"blazeface.json",rotation:!0,maxDetected:1,skipFrames:99,skipTime:2500,minConfidence:.2,iouThreshold:.1,cropFactor:1.6,mask:!1,return:!1},mesh:{enabled:!0,modelPath:"facemesh.json"},iris:{enabled:!0,modelPath:"iris.json"},emotion:{enabled:!0,minConfidence:.1,skipFrames:99,skipTime:1500,modelPath:"emotion.json"},description:{enabled:!0,modelPath:"faceres.json",skipFrames:99,skipTime:3e3,minConfidence:.1},antispoof:{enabled:!1,skipFrames:99,skipTime:4e3,modelPath:"antispoof.json"},liveness:{enabled:!1,skipFrames:99,skipTime:4e3,modelPath:"liveness.json"}},body:{enabled:!0,modelPath:"movenet-lightning.json",detector:{modelPath:""},maxDetected:-1,minConfidence:.3,skipFrames:1,skipTime:200},hand:{enabled:!0,rotation:!0,skipFrames:99,skipTime:1e3,minConfidence:.5,iouThreshold:.2,maxDetected:-1,landmarks:!0,detector:{modelPath:"handtrack.json"},skeleton:{modelPath:"handlandmark-full.json"}},object:{enabled:!1,modelPath:"mb3-centernet.json",minConfidence:.2,iouThreshold:.4,maxDetected:10,skipFrames:99,skipTime:2e3},segmentation:{enabled:!1,modelPath:"selfie.json",blur:8}};var Ml={};Qc(Ml,{Abs:()=>fi,Acos:()=>iu,Acosh:()=>lu,AdadeltaOptimizer:()=>Mf,AdagradOptimizer:()=>zf,AdamOptimizer:()=>Lf,AdamaxOptimizer:()=>Bf,Add:()=>Kr,AddN:()=>Ra,All:()=>uu,Any:()=>cu,ArgMax:()=>$a,ArgMin:()=>du,Asin:()=>pu,Asinh:()=>hu,Atan:()=>fu,Atan2:()=>gu,Atanh:()=>mu,AvgPool:()=>_a,AvgPool3D:()=>od,AvgPool3DGrad:()=>Ih,AvgPoolGrad:()=>Sh,BackendWasm:()=>s8,BatchMatMul:()=>Da,BatchToSpaceND:()=>mi,Bincount:()=>Ch,BroadcastArgs:()=>Th,BroadcastTo:()=>t3,Callback:()=>p7,CallbackList:()=>ek,Cast:()=>Pa,Ceil:()=>Fa,ClipByValue:()=>Zr,Complex:()=>id,ComplexAbs:()=>ld,Concat:()=>gi,Conv2D:()=>Oa,Conv2DBackpropFilter:()=>Nh,Conv2DBackpropInput:()=>Ma,Conv3D:()=>ud,Conv3DBackpropFilterV2:()=>Eh,Conv3DBackpropInputV2:()=>Rh,Cos:()=>za,Cosh:()=>La,CropAndResize:()=>yi,Cumsum:()=>Ai,CustomCallback:()=>nk,DataStorage:()=>sd,DenseBincount:()=>$h,DepthToSpace:()=>xi,DepthwiseConv2dNative:()=>Ba,DepthwiseConv2dNativeBackpropFilter:()=>_h,DepthwiseConv2dNativeBackpropInput:()=>Dh,Diag:()=>Ph,Dilation2D:()=>cd,Dilation2DBackpropFilter:()=>Oh,Dilation2DBackpropInput:()=>Fh,ENV:()=>Rr,EarlyStopping:()=>f7,Einsum:()=>dd,Elu:()=>Va,EluGrad:()=>Mh,Environment:()=>Q5,Equal:()=>bi,Erf:()=>Au,Exp:()=>Ua,ExpandDims:()=>vi,Expm1:()=>wi,FFT:()=>zh,Fill:()=>yu,FlipLeftRight:()=>ki,Floor:()=>Ga,FloorDiv:()=>Ha,FromPixels:()=>bd,FusedBatchNorm:()=>ja,FusedConv2D:()=>ko,FusedDepthwiseConv2D:()=>So,GPGPUContext:()=>Gm,GatherNd:()=>Ii,GatherV2:()=>Si,GraphModel:()=>j7,Greater:()=>Ci,GreaterEqual:()=>qa,History:()=>tk,IFFT:()=>Lh,Identity:()=>Xa,Imag:()=>pd,InputSpec:()=>Zt,IsFinite:()=>xu,IsInf:()=>bu,IsNan:()=>vu,KernelBackend:()=>ru,LRN:()=>fd,LRNGrad:()=>Wh,LayerVariable:()=>Kw,LayersModel:()=>aa,LeakyRelu:()=>Ti,Less:()=>Ni,LessEqual:()=>Ei,LinSpace:()=>Bh,Log:()=>Ka,Log1p:()=>wu,LogSoftmax:()=>n3,LogicalAnd:()=>Ri,LogicalNot:()=>ku,LogicalOr:()=>hd,MathBackendCPU:()=>jy,MathBackendWebGL:()=>bp,Max:()=>Za,MaxPool:()=>Ja,MaxPool3D:()=>md,MaxPool3DGrad:()=>Uh,MaxPoolGrad:()=>Vh,MaxPoolWithArgmax:()=>Gh,Maximum:()=>Ya,Mean:()=>Qa,Min:()=>eo,Minimum:()=>to,MirrorPad:()=>no,Mod:()=>Su,MomentumOptimizer:()=>Wf,Multinomial:()=>Hh,Multiply:()=>so,Neg:()=>$i,NonMaxSuppressionV3:()=>Di,NonMaxSuppressionV4:()=>Iu,NonMaxSuppressionV5:()=>Pi,NotEqual:()=>_i,OP_SCOPE_SUFFIX:()=>A3,OneHot:()=>Oi,OnesLike:()=>Fi,Optimizer:()=>na,OptimizerConstructors:()=>Oo,Pack:()=>Mi,PadV2:()=>ro,Pool:()=>g9,Pow:()=>ao,Prelu:()=>oo,Prod:()=>zi,RMSPropOptimizer:()=>Vf,RNN:()=>oa,Range:()=>Cu,Rank:()=>v2,Real:()=>gd,RealDiv:()=>Wa,Reciprocal:()=>Tu,Reduction:()=>Un,Relu:()=>io,Relu6:()=>uo,Reshape:()=>Li,ResizeBilinear:()=>lo,ResizeBilinearGrad:()=>qh,ResizeNearestNeighbor:()=>Nu,ResizeNearestNeighborGrad:()=>jh,Reverse:()=>Bi,RotateWithOffset:()=>el,Round:()=>Wi,Rsqrt:()=>co,SGDOptimizer:()=>Gd,ScatterNd:()=>Vi,Select:()=>Ui,Selu:()=>Eu,Sequential:()=>hm,Sigmoid:()=>ho,Sign:()=>Ru,Sin:()=>po,Sinh:()=>Hi,Slice:()=>Gi,Softmax:()=>go,Softplus:()=>$u,SpaceToBatchND:()=>ji,SparseFillEmptyRows:()=>Xh,SparseReshape:()=>Kh,SparseSegmentMean:()=>Zh,SparseSegmentSum:()=>Yh,SparseToDense:()=>Ad,SplitV:()=>qi,Sqrt:()=>fo,Square:()=>_u,SquaredDifference:()=>Ao,Step:()=>vo,StridedSlice:()=>Xi,StringNGrams:()=>yd,StringSplit:()=>Jh,StringToHashBucketFast:()=>Qh,Sub:()=>yo,Sum:()=>mo,SymbolicTensor:()=>xr,Tan:()=>Ki,Tanh:()=>xo,Tensor:()=>Je,TensorBuffer:()=>tn,Tile:()=>Yr,TopK:()=>Zi,Transform:()=>Yi,Transpose:()=>bo,Unique:()=>ef,Unpack:()=>Ji,UnsortedSegmentSum:()=>xd,Variable:()=>Nd,ZerosLike:()=>Qi,_FusedMatMul:()=>wo,abs:()=>nn,acos:()=>sv,acosh:()=>rv,add:()=>ue,addN:()=>hf,all:()=>e1,any:()=>ff,argMax:()=>Zs,argMin:()=>av,asin:()=>ov,asinh:()=>iv,atan:()=>lv,atan2:()=>uv,atanh:()=>cv,avgPool:()=>gf,avgPool3d:()=>s1,backend:()=>Dr,backend_util:()=>E,basicLSTMCell:()=>s_,batchNorm:()=>Bu,batchNorm2d:()=>fv,batchNorm3d:()=>mv,batchNorm4d:()=>gv,batchToSpaceND:()=>Af,bincount:()=>r1,booleanMaskAsync:()=>mF,broadcastArgs:()=>Av,broadcastTo:()=>Pd,broadcast_util:()=>ol,browser:()=>Ks,buffer:()=>ze,callbacks:()=>RU,cast:()=>me,ceil:()=>yv,clipByValue:()=>gs,clone:()=>Wn,complex:()=>To,concat:()=>wt,concat1d:()=>xv,concat2d:()=>Wu,concat3d:()=>bv,concat4d:()=>vv,constraints:()=>Nw,conv1d:()=>a1,conv2d:()=>_o,conv2dTranspose:()=>i1,conv3d:()=>l1,conv3dTranspose:()=>kv,copyRegisteredKernels:()=>b9,cos:()=>yf,cosh:()=>u1,cosineWindow:()=>P1,cumsum:()=>c1,customGrad:()=>Fr,data:()=>q7,denseBincount:()=>Sv,deprecationWarn:()=>J2,depthToSpace:()=>Iv,depthwiseConv2d:()=>Fd,deregisterOp:()=>DU,device_util:()=>Fu,diag:()=>D_,dilation2d:()=>Cv,disableDeprecationWarnings:()=>x$,dispose:()=>te,disposeVariables:()=>b$,div:()=>ge,divNoNan:()=>Tv,dot:()=>B_,dropout:()=>nw,einsum:()=>Nv,elu:()=>Od,enableDebugMode:()=>y$,enableProdMode:()=>tv,enclosingPowerOfTwo:()=>sw,engine:()=>as,env:()=>Y,equal:()=>$s,erf:()=>Ev,exp:()=>_s,expandDims:()=>Kt,expm1:()=>Rv,eye:()=>d1,fft:()=>Ef,fill:()=>Vu,findBackend:()=>Q2,findBackendFactory:()=>S$,floor:()=>Md,floorDiv:()=>pf,forceHalfFloat:()=>k4,fused:()=>Fo,gather:()=>Uu,gatherND:()=>tw,gather_util:()=>G2,getBackend:()=>Rs,getGradient:()=>A2,getKernel:()=>tf,getKernelsForBackend:()=>Jr,getThreadsCount:()=>o2e,gpgpu_util:()=>ZI,grad:()=>dD,grads:()=>pD,greater:()=>As,greaterEqual:()=>dl,ifft:()=>Wd,imag:()=>xf,image:()=>Ce,inTopKAsync:()=>CF,initializers:()=>Fw,input:()=>Ik,io:()=>rs,irfft:()=>N1,isFinite:()=>tD,isInf:()=>sD,isNaN:()=>$v,keep:()=>gn,kernel_impls:()=>Qs,layers:()=>jw,leakyRelu:()=>bf,less:()=>p1,lessEqual:()=>pl,linalg:()=>hw,linspace:()=>_v,loadGraphModel:()=>Be,loadLayersModel:()=>WW,localResponseNormalization:()=>Dv,log:()=>Ds,log1p:()=>vf,logSigmoid:()=>yD,logSoftmax:()=>h1,logSumExp:()=>zv,logicalAnd:()=>hr,logicalNot:()=>kf,logicalOr:()=>g1,logicalXor:()=>RD,losses:()=>cM,matMul:()=>He,math:()=>F3,max:()=>An,maxPool:()=>Sf,maxPool3d:()=>A1,maxPoolWithArgmax:()=>Lv,maximum:()=>ea,mean:()=>Wt,memory:()=>cf,meshgrid:()=>OD,metrics:()=>u7,min:()=>Do,minimum:()=>zd,mirrorPad:()=>Bv,mod:()=>Ld,model:()=>LW,models:()=>c7,moments:()=>If,movingAverage:()=>yF,mul:()=>L,multiRNNCell:()=>GD,multinomial:()=>Wv,neg:()=>Ot,nextFrame:()=>fw,norm:()=>_1,notEqual:()=>Hu,oneHot:()=>_d,ones:()=>ys,onesLike:()=>Ps,op:()=>V,outerProduct:()=>KD,pad:()=>Js,pad1d:()=>JD,pad2d:()=>eP,pad3d:()=>nP,pad4d:()=>rP,pool:()=>uP,pow:()=>Po,prelu:()=>Tf,print:()=>E3,prod:()=>y1,profile:()=>v$,rand:()=>fP,randomGamma:()=>yP,randomNormal:()=>Vv,randomUniform:()=>ju,range:()=>qu,ready:()=>df,real:()=>Bd,reciprocal:()=>Uv,registerBackend:()=>ul,registerCallbackConstructor:()=>VW,registerGradient:()=>s3,registerKernel:()=>cr,registerOp:()=>_U,regularizers:()=>d7,relu:()=>Or,relu6:()=>v1,removeBackend:()=>k$,reshape:()=>H,reverse:()=>Fs,reverse1d:()=>TP,reverse2d:()=>EP,reverse3d:()=>$P,reverse4d:()=>DP,rfft:()=>Rf,round:()=>w1,rsqrt:()=>k1,scalar:()=>Ie,scatterND:()=>ew,scatter_util:()=>H2,selu:()=>S1,separableConv2d:()=>Gv,sequential:()=>BW,serialization:()=>ce,setBackend:()=>nv,setPlatform:()=>I$,setThreadsCount:()=>a2e,setWasmPath:()=>r2e,setWasmPaths:()=>a8,setWebGLContext:()=>Fm,setdiff1dAsync:()=>Hv,shared:()=>Em,sigmoid:()=>ms,sign:()=>jv,signal:()=>uM,sin:()=>I1,sinh:()=>C1,slice:()=>Pe,slice1d:()=>Nf,slice2d:()=>T1,slice3d:()=>fl,slice4d:()=>ml,slice_util:()=>Ft,softmax:()=>Xu,softplus:()=>Gu,spaceToBatchND:()=>Cf,sparse:()=>Ud,sparseToDense:()=>D1,spectral:()=>lM,split:()=>sn,sqrt:()=>Dn,square:()=>At,squaredDifference:()=>E1,squeeze:()=>ot,stack:()=>yn,step:()=>Vd,stridedSlice:()=>qv,string:()=>Of,sub:()=>fe,sum:()=>ke,sumOutType:()=>Ed,tan:()=>Xv,tanh:()=>Lu,tensor:()=>ut,tensor1d:()=>Vt,tensor2d:()=>fr,tensor3d:()=>M3,tensor4d:()=>aF,tensor5d:()=>oF,tensor6d:()=>iF,tensor_util:()=>dr,test_util:()=>J3,tidy:()=>X,tile:()=>Ys,time:()=>w$,topk:()=>Kv,train:()=>gl,transpose:()=>Qe,truncatedNormal:()=>$f,unique:()=>R1,unregisterGradient:()=>x9,unregisterKernel:()=>y9,unsortedSegmentSum:()=>Zv,unstack:()=>os,upcastType:()=>Bn,util:()=>v,valueAndGrad:()=>hD,valueAndGrads:()=>fD,variable:()=>Yv,variableGrads:()=>Pv,version:()=>i8,version_converter:()=>OG,version_core:()=>Pp,version_cpu:()=>wj,version_layers:()=>gA,version_wasm:()=>i2e,version_webgl:()=>KQ,webgl:()=>ZQ,webgl_util:()=>bI,webgpu:()=>a6,where:()=>Vn,whereAsync:()=>$1,zeros:()=>Ht,zerosLike:()=>et});var su=(e=>typeof Ia!="undefined"?Ia:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof Ia!="undefined"?Ia:t)[n]}):e)(function(e){if(typeof Ia!="undefined")return Ia.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')}),EE=Object.create,yh=Object.defineProperty,RE=Object.getOwnPropertyDescriptor,$E=Object.getOwnPropertyNames,_E=Object.getPrototypeOf,DE=Object.prototype.hasOwnProperty,B5=e=>yh(e,"__esModule",{value:!0}),js=(e=>typeof su!="undefined"?su:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof su!="undefined"?su:t)[n]}):e)(function(e){if(typeof su!="undefined")return su.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')}),ss=(e,t)=>function(){return t||(0,e[Object.keys(e)[0]])((t={exports:{}}).exports,t),t.exports},Oe=(e,t)=>{B5(e);for(var n in t)yh(e,n,{get:t[n],enumerable:!0})},PE=(e,t,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of $E(t))!DE.call(e,s)&&s!=="default"&&yh(e,s,{get:()=>t[s],enumerable:!(n=RE(t,s))||n.enumerable});return e},di=e=>PE(B5(yh(e!=null?EE(_E(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e),FE=ss({"node_modules/.pnpm/long@4.0.0/node_modules/long/src/long.js"(e,t){t.exports=s;var n=null;try{n=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(P){}function s(P,T,F){this.low=P|0,this.high=T|0,this.unsigned=!!F}s.prototype.__isLong__,Object.defineProperty(s.prototype,"__isLong__",{value:!0});function r(P){return(P&&P.__isLong__)===!0}s.isLong=r;var a={},o={};function i(P,T){var F,U,q;return T?(P>>>=0,(q=0<=P&&P<256)&&(U=o[P],U)?U:(F=c(P,(P|0)<0?-1:0,!0),q&&(o[P]=F),F)):(P|=0,(q=-128<=P&&P<128)&&(U=a[P],U)?U:(F=c(P,P<0?-1:0,!1),q&&(a[P]=F),F))}s.fromInt=i;function l(P,T){if(isNaN(P))return T?b:y;if(T){if(P<0)return b;if(P>=g)return R}else{if(P<=-A)return O;if(P+1>=A)return N}return P<0?l(-P,T).neg():c(P%m|0,P/m|0,T)}s.fromNumber=l;function c(P,T,F){return new s(P,T,F)}s.fromBits=c;var u=Math.pow;function d(P,T,F){if(P.length===0)throw Error("empty string");if(P==="NaN"||P==="Infinity"||P==="+Infinity"||P==="-Infinity")return y;if(typeof T=="number"?(F=T,T=!1):T=!!T,F=F||10,F<2||360)throw Error("interior hyphen");if(U===0)return d(P.substring(1),T,F).neg();for(var q=l(u(F,8)),z=y,K=0;K>>0:this.low},$.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},$.toString=function(T){if(T=T||10,T<2||36>>0,re=ne.toString(T);if(K=Q,K.isZero())return re+J;for(;re.length<6;)re="0"+re;J=""+re+J}},$.getHighBits=function(){return this.high},$.getHighBitsUnsigned=function(){return this.high>>>0},$.getLowBits=function(){return this.low},$.getLowBitsUnsigned=function(){return this.low>>>0},$.getNumBitsAbs=function(){if(this.isNegative())return this.eq(O)?64:this.neg().getNumBitsAbs();for(var T=this.high!=0?this.high:this.low,F=31;F>0&&(T&1<=0},$.isOdd=function(){return(this.low&1)==1},$.isEven=function(){return(this.low&1)==0},$.equals=function(T){return r(T)||(T=p(T)),this.unsigned!==T.unsigned&&this.high>>>31==1&&T.high>>>31==1?!1:this.high===T.high&&this.low===T.low},$.eq=$.equals,$.notEquals=function(T){return!this.eq(T)},$.neq=$.notEquals,$.ne=$.notEquals,$.lessThan=function(T){return this.comp(T)<0},$.lt=$.lessThan,$.lessThanOrEqual=function(T){return this.comp(T)<=0},$.lte=$.lessThanOrEqual,$.le=$.lessThanOrEqual,$.greaterThan=function(T){return this.comp(T)>0},$.gt=$.greaterThan,$.greaterThanOrEqual=function(T){return this.comp(T)>=0},$.gte=$.greaterThanOrEqual,$.ge=$.greaterThanOrEqual,$.compare=function(T){if(r(T)||(T=p(T)),this.eq(T))return 0;var F=this.isNegative(),U=T.isNegative();return F&&!U?-1:!F&&U?1:this.unsigned?T.high>>>0>this.high>>>0||T.high===this.high&&T.low>>>0>this.low>>>0?-1:1:this.sub(T).isNegative()?-1:1},$.comp=$.compare,$.negate=function(){return!this.unsigned&&this.eq(O)?O:this.not().add(w)},$.neg=$.negate,$.add=function(T){r(T)||(T=p(T));var F=this.high>>>16,U=this.high&65535,q=this.low>>>16,z=this.low&65535,K=T.high>>>16,J=T.high&65535,Q=T.low>>>16,ne=T.low&65535,re=0,G=0,se=0,oe=0;return oe+=z+ne,se+=oe>>>16,oe&=65535,se+=q+Q,G+=se>>>16,se&=65535,G+=U+J,re+=G>>>16,G&=65535,re+=F+K,re&=65535,c(se<<16|oe,re<<16|G,this.unsigned)},$.subtract=function(T){return r(T)||(T=p(T)),this.add(T.neg())},$.sub=$.subtract,$.multiply=function(T){if(this.isZero())return y;if(r(T)||(T=p(T)),n){var F=n.mul(this.low,this.high,T.low,T.high);return c(F,n.get_high(),this.unsigned)}if(T.isZero())return y;if(this.eq(O))return T.isOdd()?O:y;if(T.eq(O))return this.isOdd()?O:y;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(x)&&T.lt(x))return l(this.toNumber()*T.toNumber(),this.unsigned);var U=this.high>>>16,q=this.high&65535,z=this.low>>>16,K=this.low&65535,J=T.high>>>16,Q=T.high&65535,ne=T.low>>>16,re=T.low&65535,G=0,se=0,oe=0,pe=0;return pe+=K*re,oe+=pe>>>16,pe&=65535,oe+=z*re,se+=oe>>>16,oe&=65535,oe+=K*ne,se+=oe>>>16,oe&=65535,se+=q*re,G+=se>>>16,se&=65535,se+=z*ne,G+=se>>>16,se&=65535,se+=K*Q,G+=se>>>16,se&=65535,G+=U*re+q*ne+z*Q+K*J,G&=65535,c(oe<<16|pe,G<<16|se,this.unsigned)},$.mul=$.multiply,$.divide=function(T){if(r(T)||(T=p(T)),T.isZero())throw Error("division by zero");if(n){if(!this.unsigned&&this.high===-2147483648&&T.low===-1&&T.high===-1)return this;var F=(this.unsigned?n.div_u:n.div_s)(this.low,this.high,T.low,T.high);return c(F,n.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?b:y;var U,q,z;if(this.unsigned){if(T.unsigned||(T=T.toUnsigned()),T.gt(this))return b;if(T.gt(this.shru(1)))return k;z=b}else{if(this.eq(O)){if(T.eq(w)||T.eq(I))return O;if(T.eq(O))return w;var K=this.shr(1);return U=K.div(T).shl(1),U.eq(y)?T.isNegative()?w:I:(q=this.sub(T.mul(U)),z=U.add(q.div(T)),z)}else if(T.eq(O))return this.unsigned?b:y;if(this.isNegative())return T.isNegative()?this.neg().div(T.neg()):this.neg().div(T).neg();if(T.isNegative())return this.div(T.neg()).neg();z=y}for(q=this;q.gte(T);){U=Math.max(1,Math.floor(q.toNumber()/T.toNumber()));for(var J=Math.ceil(Math.log(U)/Math.LN2),Q=J<=48?1:u(2,J-48),ne=l(U),re=ne.mul(T);re.isNegative()||re.gt(q);)U-=Q,ne=l(U,this.unsigned),re=ne.mul(T);ne.isZero()&&(ne=w),z=z.add(ne),q=q.sub(re)}return z},$.div=$.divide,$.modulo=function(T){if(r(T)||(T=p(T)),n){var F=(this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,T.low,T.high);return c(F,n.get_high(),this.unsigned)}return this.sub(this.div(T).mul(T))},$.mod=$.modulo,$.rem=$.modulo,$.not=function(){return c(~this.low,~this.high,this.unsigned)},$.and=function(T){return r(T)||(T=p(T)),c(this.low&T.low,this.high&T.high,this.unsigned)},$.or=function(T){return r(T)||(T=p(T)),c(this.low|T.low,this.high|T.high,this.unsigned)},$.xor=function(T){return r(T)||(T=p(T)),c(this.low^T.low,this.high^T.high,this.unsigned)},$.shiftLeft=function(T){return r(T)&&(T=T.toInt()),(T&=63)==0?this:T<32?c(this.low<>>32-T,this.unsigned):c(0,this.low<>>T|this.high<<32-T,this.high>>T,this.unsigned):c(this.high>>T-32,this.high>=0?0:-1,this.unsigned)},$.shr=$.shiftRight,$.shiftRightUnsigned=function(T){if(r(T)&&(T=T.toInt()),T&=63,T===0)return this;var F=this.high;if(T<32){var U=this.low;return c(U>>>T|F<<32-T,F>>>T,this.unsigned)}else return T===32?c(F,0,this.unsigned):c(F>>>T-32,0,this.unsigned)},$.shru=$.shiftRightUnsigned,$.shr_u=$.shiftRightUnsigned,$.toSigned=function(){return this.unsigned?c(this.low,this.high,!1):this},$.toUnsigned=function(){return this.unsigned?this:c(this.low,this.high,!0)},$.toBytes=function(T){return T?this.toBytesLE():this.toBytesBE()},$.toBytesLE=function(){var T=this.high,F=this.low;return[F&255,F>>>8&255,F>>>16&255,F>>>24,T&255,T>>>8&255,T>>>16&255,T>>>24]},$.toBytesBE=function(){var T=this.high,F=this.low;return[T>>>24,T>>>16&255,T>>>8&255,T&255,F>>>24,F>>>16&255,F>>>8&255,F&255]},s.fromBytes=function(T,F,U){return U?s.fromBytesLE(T,F):s.fromBytesBE(T,F)},s.fromBytesLE=function(T,F){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,F)},s.fromBytesBE=function(T,F){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],F)}}}),OE=ss({"(disabled):node-fetch"(){}}),ME=ss({"(disabled):util"(){}}),zE=ss({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js"(e,t){(function(n,s,r){function a(c){var u=this,d=l();u.next=function(){var p=2091639*u.s0+u.c*23283064365386963e-26;return u.s0=u.s1,u.s1=u.s2,u.s2=p-(u.c=p|0)},u.c=1,u.s0=d(" "),u.s1=d(" "),u.s2=d(" "),u.s0-=d(c),u.s0<0&&(u.s0+=1),u.s1-=d(c),u.s1<0&&(u.s1+=1),u.s2-=d(c),u.s2<0&&(u.s2+=1),d=null}function o(c,u){return u.c=c.c,u.s0=c.s0,u.s1=c.s1,u.s2=c.s2,u}function i(c,u){var d=new a(c),p=u&&u.state,h=d.next;return h.int32=function(){return d.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,p&&(typeof p=="object"&&o(p,d),h.state=function(){return o(d,{})}),h}function l(){var c=4022871197,u=function(d){d=String(d);for(var p=0;p>>0,h-=c,h*=c,c=h>>>0,h-=c,c+=h*4294967296}return(c>>>0)*23283064365386963e-26};return u}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.alea=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),LE=ss({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.x=0,c.y=0,c.z=0,c.w=0,c.next=function(){var p=c.x^c.x<<11;return c.x=c.y,c.y=c.z,c.z=c.w,c.w^=c.w>>>19^p^p>>>8},l===(l|0)?c.x=l:u+=l;for(var d=0;d>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xor128=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),BE=ss({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.next=function(){var p=c.x^c.x>>>2;return c.x=c.y,c.y=c.z,c.z=c.w,c.w=c.v,(c.d=c.d+362437|0)+(c.v=c.v^c.v<<4^(p^p<<1))|0},c.x=0,c.y=0,c.z=0,c.w=0,c.v=0,l===(l|0)?c.x=l:u+=l;for(var d=0;d>>4),c.next()}function o(l,c){return c.x=l.x,c.y=l.y,c.z=l.z,c.w=l.w,c.v=l.v,c.d=l.d,c}function i(l,c){var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xorwow=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),WE=ss({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js"(e,t){(function(n,s,r){function a(l){var c=this;c.next=function(){var d=c.x,p=c.i,h,f,m;return h=d[p],h^=h>>>7,f=h^h<<24,h=d[p+1&7],f^=h^h>>>10,h=d[p+3&7],f^=h^h>>>3,h=d[p+4&7],f^=h^h<<7,h=d[p+7&7],h=h^h<<13,f^=h^h<<9,d[p]=f,c.i=p+1&7,f};function u(d,p){var h,f,m=[];if(p===(p|0))f=m[0]=p;else for(p=""+p,h=0;h0;--h)d.next()}u(c,l)}function o(l,c){return c.x=l.x.slice(),c.i=l.i,c}function i(l,c){l==null&&(l=+new Date);var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.x&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xorshift7=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),VE=ss({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js"(e,t){(function(n,s,r){function a(l){var c=this;c.next=function(){var d=c.w,p=c.X,h=c.i,f,m;return c.w=d=d+1640531527|0,m=p[h+34&127],f=p[h=h+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,m=p[h]=m^f,c.i=h,m+(d^d>>>16)|0};function u(d,p){var h,f,m,g,A,x=[],y=128;for(p===(p|0)?(f=p,p=null):(p=p+"\0",f=0,y=Math.max(y,p.length)),m=0,g=-32;g>>15,f^=f<<4,f^=f>>>13,g>=0&&(A=A+1640531527|0,h=x[g&127]^=f+A,m=h==0?m+1:0);for(m>=128&&(x[(p&&p.length||0)&127]=-1),m=127,g=4*128;g>0;--g)f=x[m+34&127],h=x[m=m+1&127],f^=f<<13,h^=h<<17,f^=f>>>15,h^=h>>>12,x[m]=f^h;d.w=A,d.X=x,d.i=m}u(c,l)}function o(l,c){return c.i=l.i,c.w=l.w,c.X=l.X.slice(),c}function i(l,c){l==null&&(l=+new Date);var u=new a(l),d=c&&c.state,p=function(){return(u.next()>>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(d.X&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.xor4096=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),UE=ss({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js"(e,t){(function(n,s,r){function a(l){var c=this,u="";c.next=function(){var p=c.b,h=c.c,f=c.d,m=c.a;return p=p<<25^p>>>7^h,h=h-f|0,f=f<<24^f>>>8^m,m=m-p|0,c.b=p=p<<20^p>>>12^h,c.c=h=h-f|0,c.d=f<<16^h>>>16^m,c.a=m-p|0},c.a=0,c.b=0,c.c=2654435769|0,c.d=1367130551,l===Math.floor(l)?(c.a=l/4294967296|0,c.b=l|0):u+=l;for(var d=0;d>>0)/4294967296};return p.double=function(){do var h=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},p.int32=u.next,p.quick=p,d&&(typeof d=="object"&&o(d,u),p.state=function(){return o(u,{})}),p}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.tychei=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),GE=ss({"(disabled):crypto"(){}}),HE=ss({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js"(e,t){(function(n,s,r){var a=256,o=6,i=52,l="random",c=r.pow(a,o),u=r.pow(2,i),d=u*2,p=a-1,h;function f(w,k,I){var N=[];k=k==!0?{entropy:!0}:k||{};var R=x(A(k.entropy?[w,b(s)]:w==null?y():w,3),N),O=new m(N),$=function(){for(var P=O.g(o),T=c,F=0;P=d;)P/=2,T/=2,F>>>=1;return(P+F)/T};return $.int32=function(){return O.g(4)|0},$.quick=function(){return O.g(4)/4294967296},$.double=$,x(b(O.S),s),(k.pass||I||function(P,T,F,U){return U&&(U.S&&g(U,O),P.state=function(){return g(O,{})}),F?(r[l]=P,T):P})($,R,"global"in k?k.global:this==r,k.state)}function m(w){var k,I=w.length,N=this,R=0,O=N.i=N.j=0,$=N.S=[];for(I||(w=[I++]);R1&&(g=process.argv[1].replace(/\\/g,"/")),m=process.argv.slice(2),process.on("uncaughtException",function(C){if(!(C instanceof Jc))throw C}),process.on("unhandledRejection",jr),A=function(C){process.exit(C)},u.inspect=function(){return"[Emscripten Module object]"};var U;try{U=js("worker_threads")}catch(C){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),C}global.Worker=U.Worker}else w?(typeof read!="undefined"&&(R=function(_){return read(_)}),$=function(_){var B;return typeof readbuffer=="function"?new Uint8Array(readbuffer(_)):(B=read(_,"binary"),we(typeof B=="object"),B)},typeof scriptArgs!="undefined"?m=scriptArgs:typeof arguments!="undefined"&&(m=arguments),typeof quit=="function"&&(A=function(C){quit(C)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(x||y)&&(y?I=self.location.href:typeof document!="undefined"&&document.currentScript&&(I=document.currentScript.src),typeof s!="undefined"&&s&&(I=s),I.indexOf("blob:")!==0?I=I.substr(0,I.lastIndexOf("/")+1):I="",b?(R=function(_,B){return T||(T=js("fs")),F||(F=js("path")),_=F.normalize(_),T.readFileSync(_,B?null:"utf8")},$=function(_){var B=R(_,!0);return B.buffer||(B=new Uint8Array(B)),we(B.buffer),B}):(R=function(C){var _=new XMLHttpRequest;return _.open("GET",C,!1),_.send(null),_.responseText},y&&($=function(C){var _=new XMLHttpRequest;return _.open("GET",C,!1),_.responseType="arraybuffer",_.send(null),new Uint8Array(_.response)}),O=function(C,_,B){var ee=new XMLHttpRequest;ee.open("GET",C,!0),ee.responseType="arraybuffer",ee.onload=function(){if(ee.status==200||ee.status==0&&ee.response){_(ee.response);return}B()},ee.onerror=B,ee.send(null)}),P=function(C){document.title=C});b&&typeof performance=="undefined"&&(global.performance=js("perf_hooks").performance);var q=u.print||console.log.bind(console),z=u.printErr||console.warn.bind(console);for(f in h)h.hasOwnProperty(f)&&(u[f]=h[f]);h=null,u.arguments&&(m=u.arguments),u.thisProgram&&(g=u.thisProgram),u.quit&&(A=u.quit);function K(C){K.shown||(K.shown={}),K.shown[C]||(K.shown[C]=1,z(C))}var J=Atomics.load,Q=Atomics.store,ne=Atomics.compareExchange,re;u.wasmBinary&&(re=u.wasmBinary);var G=u.noExitRuntime||!0;typeof WebAssembly!="object"&&jr("no native wasm support detected");var se,oe,pe=!1,ye;function we(C,_){C||jr("Assertion failed: "+_)}function Ne(C){var _=u["_"+C];return we(_,"Cannot call unknown function "+C+", make sure it is exported"),_}function Me(C,_,B,ee,be){var Ae={string:function(Mn){var nu=0;if(Mn!=null&&Mn!==0){var z5=(Mn.length<<2)+1;nu=Ql(z5),pt(Mn,nu,z5)}return nu},array:function(Mn){var nu=Ql(Mn.length);return kt(Mn,nu),nu}};function xe(Mn){return _==="string"?Ke(Mn):_==="boolean"?Boolean(Mn):Mn}var Ee=Ne(C),ct=[],hn=0;if(ee)for(var en=0;en=ee);){var Ae=C[_++];if(!Ae)return be;if(!(Ae&128)){be+=String.fromCharCode(Ae);continue}var xe=C[_++]&63;if((Ae&224)==192){be+=String.fromCharCode((Ae&31)<<6|xe);continue}var Ee=C[_++]&63;if((Ae&240)==224?Ae=(Ae&15)<<12|xe<<6|Ee:Ae=(Ae&7)<<18|xe<<12|Ee<<6|C[_++]&63,Ae<65536)be+=String.fromCharCode(Ae);else{var ct=Ae-65536;be+=String.fromCharCode(55296|ct>>10,56320|ct&1023)}}return be}function Ke(C,_){return C?qe(o(),C,_):""}function dt(C,_,B,ee){if(!(ee>0))return 0;for(var be=B,Ae=B+ee-1,xe=0;xe=55296&&Ee<=57343){var ct=C.charCodeAt(++xe);Ee=65536+((Ee&1023)<<10)|ct&1023}if(Ee<=127){if(B>=Ae)break;_[B++]=Ee}else if(Ee<=2047){if(B+1>=Ae)break;_[B++]=192|Ee>>6,_[B++]=128|Ee&63}else if(Ee<=65535){if(B+2>=Ae)break;_[B++]=224|Ee>>12,_[B++]=128|Ee>>6&63,_[B++]=128|Ee&63}else{if(B+3>=Ae)break;_[B++]=240|Ee>>18,_[B++]=128|Ee>>12&63,_[B++]=128|Ee>>6&63,_[B++]=128|Ee&63}}return _[B]=0,B-be}function pt(C,_,B){return dt(C,o(),_,B)}function rt(C){for(var _=0,B=0;B=55296&&ee<=57343&&(ee=65536+((ee&1023)<<10)|C.charCodeAt(++B)&1023),ee<=127?++_:ee<=2047?_+=2:ee<=65535?_+=3:_+=4}return _}function kt(C,_){a().set(C,_)}function mt(C,_){return C%_>0&&(C+=_-C%_),C}var Nt,Dt,Ts,kn,lr,On,hs,Gs,Ns;function Sn(C){Nt=C,u.HEAP8=Dt=new Int8Array(C),u.HEAP16=kn=new Int16Array(C),u.HEAP32=On=new Int32Array(C),u.HEAPU8=Ts=new Uint8Array(C),u.HEAPU16=lr=new Uint16Array(C),u.HEAPU32=hs=new Uint32Array(C),u.HEAPF32=Gs=new Float32Array(C),u.HEAPF64=Ns=new Float64Array(C)}var Tr=u.INITIAL_MEMORY||16777216;if(k)se=u.wasmMemory,Nt=u.buffer;else if(u.wasmMemory)se=u.wasmMemory;else if(se=new WebAssembly.Memory({initial:Tr/65536,maximum:2147483648/65536,shared:!0}),!(se.buffer instanceof SharedArrayBuffer))throw z("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),b&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");se&&(Nt=se.buffer),Tr=Nt.byteLength,Sn(Nt);var Rn,Nr=[],Er=[],ya=[],Wc=[],ur=[],qp=!1,W0=!1;k||Er.push({func:function(){dh()}});function Xp(){if(!k){if(u.preRun)for(typeof u.preRun=="function"&&(u.preRun=[u.preRun]);u.preRun.length;)V0(u.preRun.shift());Kl(Nr)}}function Kp(){qp=!0,!k&&Kl(Er)}function Zp(){k||Kl(ya)}function ts(){k||(W0=!0)}function Yp(){if(!k){if(u.postRun)for(typeof u.postRun=="function"&&(u.postRun=[u.postRun]);u.postRun.length;)U0(u.postRun.shift());Kl(ur)}}function V0(C){Nr.unshift(C)}function U0(C){ur.unshift(C)}var Hs=0,Vc=null,ii=null;function G0(C){we(!k,"addRunDependency cannot be used in a pthread worker"),Hs++,u.monitorRunDependencies&&u.monitorRunDependencies(Hs)}function H0(C){if(Hs--,u.monitorRunDependencies&&u.monitorRunDependencies(Hs),Hs==0&&(Vc!==null&&(clearInterval(Vc),Vc=null),ii)){var _=ii;ii=null,_()}}u.preloadedImages={},u.preloadedAudios={};function jr(C){u.onAbort&&u.onAbort(C),k&&console.error("Pthread aborting at "+new Error().stack),C+="",z(C),pe=!0,ye=1,C="abort("+C+"). Build with -s ASSERTIONS=1 for more info.";var _=new WebAssembly.RuntimeError(C);throw p(_),_}function li(C,_){return String.prototype.startsWith?C.startsWith(_):C.indexOf(_)===0}var j0="data:application/octet-stream;base64,";function Jp(C){return li(C,j0)}var q0="file://";function Qp(C){return li(C,q0)}var ns="tfjs-backend-wasm-threaded-simd.wasm";Jp(ns)||(ns=N(ns));function X0(C){try{if(C==ns&&re)return new Uint8Array(re);if($)return $(C);throw"both async and sync fetching of the wasm failed"}catch(_){jr(_)}}function eh(){if(!re&&(x||y)){if(typeof fetch=="function"&&!Qp(ns))return fetch(ns,{credentials:"same-origin"}).then(function(C){if(!C.ok)throw"failed to load wasm binary file at '"+ns+"'";return C.arrayBuffer()}).catch(function(){return X0(ns)});if(O)return new Promise(function(C,_){O(ns,function(B){C(new Uint8Array(B))},_)})}return Promise.resolve().then(function(){return X0(ns)})}function K0(){var C={a:Wg};function _(xe,Ee){var ct=xe.exports;if(u.asm=ct,Rn=u.asm.kb,oe=Ee,!k){var hn=$e.unusedWorkers.length;$e.unusedWorkers.forEach(function(en){$e.loadWasmModuleToWorker(en,function(){--hn||H0("wasm-instantiate")})})}}k||G0("wasm-instantiate");function B(xe){_(xe.instance,xe.module)}function ee(xe){return eh().then(function(Ee){return WebAssembly.instantiate(Ee,C)}).then(xe,function(Ee){z("failed to asynchronously prepare wasm: "+Ee),jr(Ee)})}function be(){return!re&&typeof WebAssembly.instantiateStreaming=="function"&&!Jp(ns)&&!Qp(ns)&&typeof fetch=="function"?fetch(ns,{credentials:"same-origin"}).then(function(xe){var Ee=WebAssembly.instantiateStreaming(xe,C);return Ee.then(B,function(ct){return z("wasm streaming compile failed: "+ct),z("falling back to ArrayBuffer instantiation"),ee(B)})}):ee(B)}if(u.instantiateWasm)try{var Ae=u.instantiateWasm(C,_);return Ae}catch(xe){return z("Module.instantiateWasm callback failed with error: "+xe),!1}return be().catch(p),{}}var th={10072:function(){throw"Canceled!"},10090:function(C,_){setTimeout(function(){_5(C,_)},0)}};function Z0(){$e.initRuntime()}function Kl(C){for(;C.length>0;){var _=C.shift();if(typeof _=="function"){_(u);continue}var B=_.func;typeof B=="number"?_.arg===void 0?Rn.get(B)():Rn.get(B)(_.arg):B(_.arg===void 0?null:_.arg)}}var xa={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135};function Uc(C,_){if(C<=0||C>a().length||C&!0||_<0)return-28;if(_==0)return 0;_>=2147483647&&(_=1/0);var B=Atomics.load(i(),eu>>2),ee=0;if(B==C){var be=Atomics.compareExchange(i(),eu>>2,B,0);if(be==B&&(--_,ee=1,_<=0))return 1}var Ae=Atomics.notify(i(),C>>2,_);if(Ae>=0)return Ae+ee;throw"Atomics.notify returned an unexpected value "+Ae}u._emscripten_futex_wake=Uc;function Y0(C){if(k)throw"Internal Error! killThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in killThread!";i()[C+12>>2]=0;var _=$e.pthreads[C];_.worker.terminate(),$e.freeThreadData(_),$e.runningWorkers.splice($e.runningWorkers.indexOf(_.worker),1),_.worker.pthread=void 0}function J0(C){if(k)throw"Internal Error! cancelThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in cancelThread!";var _=$e.pthreads[C];_.worker.postMessage({cmd:"cancel"})}function nh(C){if(k)throw"Internal Error! cleanupThread() can only ever be called from main application thread!";if(!C)throw"Internal Error! Null pthread_ptr in cleanupThread!";var _=$e.pthreads[C];if(_){i()[C+12>>2]=0;var B=_.worker;$e.returnWorkerToPool(B)}}var $e={unusedWorkers:[],runningWorkers:[],initMainThreadBlock:function(){for(var C=8,_=0;_>2]=C;var B=C+152;i()[B>>2]=B;for(var ee=ci(512),_=0;_<128;++_)l()[ee/4+_]=0;Atomics.store(l(),C+100>>2,ee),Atomics.store(l(),C+40>>2,C),i2(C,!y,1),R5(C)},initWorker:function(){},pthreads:{},threadExitHandlers:[],setThreadStatus:function(){},runExitHandlers:function(){for(;$e.threadExitHandlers.length>0;)$e.threadExitHandlers.pop()();k&&ka()&&E5()},runExitHandlersAndDeinitThread:function(C,_){Atomics.store(l(),C+56>>2,1),Atomics.store(l(),C+60>>2,0),$e.runExitHandlers(),Atomics.store(l(),C+4>>2,_),Atomics.store(l(),C+0>>2,1),Uc(C+0,2147483647),i2(0,0,0)},threadExit:function(C){var _=ka();_&&($e.runExitHandlersAndDeinitThread(_,C),k&&postMessage({cmd:"exit"}))},threadCancel:function(){$e.runExitHandlersAndDeinitThread(ka(),-1),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var C in $e.pthreads){var _=$e.pthreads[C];_&&_.worker&&$e.returnWorkerToPool(_.worker)}$e.pthreads={};for(var B=0;B<$e.unusedWorkers.length;++B){var ee=$e.unusedWorkers[B];ee.terminate()}$e.unusedWorkers=[];for(var B=0;B<$e.runningWorkers.length;++B){var ee=$e.runningWorkers[B],_=ee.pthread;$e.freeThreadData(_),ee.terminate()}$e.runningWorkers=[]},freeThreadData:function(C){if(!!C){if(C.threadInfoStruct){var _=i()[C.threadInfoStruct+100>>2];i()[C.threadInfoStruct+100>>2]=0,Zc(_),Zc(C.threadInfoStruct)}C.threadInfoStruct=0,C.allocatedOwnStack&&C.stackBase&&Zc(C.stackBase),C.stackBase=0,C.worker&&(C.worker.pthread=null)}},returnWorkerToPool:function(C){$e.runWithoutMainThreadQueuedCalls(function(){delete $e.pthreads[C.pthread.threadInfoStruct],$e.unusedWorkers.push(C),$e.runningWorkers.splice($e.runningWorkers.indexOf(C),1),$e.freeThreadData(C.pthread),C.pthread=void 0})},runWithoutMainThreadQueuedCalls:function(C){i()[M5>>2]=0;try{C()}finally{i()[M5>>2]=1}},receiveObjectTransfer:function(C){},loadWasmModuleToWorker:function(C,_){C.onmessage=function(B){var ee=B.data,be=ee.cmd;if(C.pthread&&($e.currentProxiedOperationCallerThread=C.pthread.threadInfoStruct),ee.targetThread&&ee.targetThread!=ka()){var Ae=$e.pthreads[ee.targetThread];Ae?Ae.worker.postMessage(B.data,ee.transferList):console.error('Internal error! Worker sent a message "'+be+'" to target pthread '+ee.targetThread+", but that thread no longer exists!"),$e.currentProxiedOperationCallerThread=void 0;return}if(be==="processQueuedMainThreadWork")gh();else if(be==="spawnThread")uh(B.data);else if(be==="cleanupThread")nh(ee.thread);else if(be==="killThread")Y0(ee.thread);else if(be==="cancelThread")J0(ee.thread);else if(be==="loaded")C.loaded=!0,_&&_(C),C.runPthread&&(C.runPthread(),delete C.runPthread);else if(be==="print")q("Thread "+ee.threadId+": "+ee.text);else if(be==="printErr")z("Thread "+ee.threadId+": "+ee.text);else if(be==="alert")alert("Thread "+ee.threadId+": "+ee.text);else if(be==="exit"){var xe=C.pthread&&Atomics.load(l(),C.pthread.threadInfoStruct+64>>2);xe&&$e.returnWorkerToPool(C)}else if(be==="exitProcess")try{CE(ee.returnCode)}catch(Ee){if(Ee instanceof Jc)return;throw Ee}else be==="cancelDone"?$e.returnWorkerToPool(C):be==="objectTransfer"?$e.receiveObjectTransfer(B.data):B.data.target==="setimmediate"?C.postMessage(B.data):z("worker sent an unknown command "+be);$e.currentProxiedOperationCallerThread=void 0},C.onerror=function(B){z("pthread sent an error! "+B.filename+":"+B.lineno+": "+B.message)},b&&(C.on("message",function(B){C.onmessage({data:B})}),C.on("error",function(B){C.onerror(B)}),C.on("exit",function(B){})),C.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||s,wasmMemory:se,wasmModule:oe})},allocateUnusedWorker:function(){var C=N("tfjs-backend-wasm-threaded-simd.worker.js");$e.unusedWorkers.push(new Worker(C))},getNewWorker:function(){return $e.unusedWorkers.length==0&&($e.allocateUnusedWorker(),$e.loadWasmModuleToWorker($e.unusedWorkers[0])),$e.unusedWorkers.length>0?$e.unusedWorkers.pop():null},busySpinWait:function(C){for(var _=performance.now()+C;performance.now()<_;);}};function Q0(C,_){F5(C,_),Jl(C)}u.establishStackSpace=Q0;function eg(){return G}u.getNoExitRuntime=eg;function tg(C,_){return Rn.get(C)(_)}u.invokeEntryPoint=tg;function ng(C,_,B,ee){jr("Assertion failed: "+Ke(C)+", at: "+[_?Ke(_):"unknown filename",B,ee?Ke(ee):"unknown function"])}function sg(C,_){var B=_main(C,_)}var ui;b?ui=function(){var C=process.hrtime();return C[0]*1e3+C[1]/1e6}:k?ui=function(){return performance.now()-u.__performance_now_clock_drift}:typeof dateNow!="undefined"?ui=dateNow:ui=function(){return performance.now()};function rg(C){return i()[T5()>>2]=C,C}function ag(C,_){if(k)return ba(1,1,C,_)}function og(C,_){if(C==_)postMessage({cmd:"processQueuedMainThreadWork"});else if(k)postMessage({targetThread:C,cmd:"processThreadQueue"});else{var B=$e.pthreads[C],ee=B&&B.worker;if(!ee)return;ee.postMessage({cmd:"processThreadQueue"})}return 1}function ig(){jr()}function lg(C,_,B){var ee=pg(_,B);return th[C].apply(null,ee)}function ug(C,_){}function sh(C,_,B){if(C<=0||C>a().length||C&!0)return-28;if(x){if(Atomics.load(i(),C>>2)!=_)return-6;for(var be=performance.now(),Ae=be+B,xe=Atomics.exchange(i(),eu>>2,C);;){if(be=performance.now(),be>Ae)return xe=Atomics.exchange(i(),eu>>2,0),-73;if(xe=Atomics.exchange(i(),eu>>2,0),xe==0)break;if(gh(),Atomics.load(i(),C>>2)!=_)return-6;xe=Atomics.exchange(i(),eu>>2,C)}return 0}else{var ee=Atomics.wait(i(),C>>2,_,B);if(ee==="timed-out")return-73;if(ee==="not-equal")return-6;if(ee==="ok")return 0;throw"Atomics.wait returned an unexpected value "+ee}}function cg(C,_,B){o().copyWithin(C,_,_+B)}function dg(){return b?js("os").cpus().length:navigator.hardwareConcurrency}function ba(C,_){for(var B=arguments.length-2,ee=Yc(),be=B,Ae=Ql(be*8),xe=Ae>>3,Ee=0;Ee>=2;B=o()[C++];){var ee=B<105;ee&&_&1&&_++,Hc.push(ee?c()[_++>>1]:i()[_]),++_}return Hc}function hg(C,_,B){Gc.length=_;for(var ee=B>>3,be=0;be<_;be++)Gc[be]=c()[ee+be];var Ae=C<0,xe=Ae?th[-C-1]:Bg[C];return xe.apply(null,Gc)}function fg(){return o().length}function mg(C){try{return se.grow(C-Nt.byteLength+65535>>>16),Sn(se.buffer),1}catch(_){}}function gg(C){var _=fg();if(C<=_)return!1;var B=2147483648;if(C>B)return!1;for(var ee=1;ee<=4;ee*=2){var be=_*(1+.2/ee);be=Math.min(be,C+100663296);var Ae=Math.min(B,mt(Math.max(C,be),65536)),xe=mg(Ae);if(xe)return!0}return!1}var Ge={inEventHandler:0,removeAllEventListeners:function(){for(var C=Ge.eventHandlers.length-1;C>=0;--C)Ge._removeHandler(C);Ge.eventHandlers=[],Ge.deferredCalls=[]},registerRemoveEventListeners:function(){Ge.removeEventListenersRegistered||(Wc.push(Ge.removeAllEventListeners),Ge.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(C,_,B){function ee(xe,Ee){if(xe.length!=Ee.length)return!1;for(var ct in xe)if(xe[ct]!=Ee[ct])return!1;return!0}for(var be in Ge.deferredCalls){var Ae=Ge.deferredCalls[be];if(Ae.targetFunction==C&&ee(Ae.argsList,B))return}Ge.deferredCalls.push({targetFunction:C,precedence:_,argsList:B}),Ge.deferredCalls.sort(function(xe,Ee){return xe.precedence>2]=B,i()[xe+4>>2]=ee,i()[xe+8>>2]=be,o2(0,C,637534208,_,ee,xe),Jl(Ae)},getTargetThreadForEventCallback:function(C){switch(C){case 1:return 0;case 2:return $e.currentProxiedOperationCallerThread;default:return C}},getNodeNameForTarget:function(C){return C?C==window?"#window":C==screen?"#screen":C&&C.nodeName?C.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function Ag(C){var _=rt(C)+1,B=ci(_);return pt(C,B,_),B}function yg(C,_,B,ee){var be=Yc(),Ae=Ql(12),xe=0;_&&(xe=Ag(_)),i()[Ae>>2]=xe,i()[Ae+4>>2]=B,i()[Ae+8>>2]=ee,o2(0,C,657457152,0,xe,Ae),Jl(be)}function xg(C,_,B,ee){_=_?Ke(_):"",yg(C,_,B,ee)}function bg(C){return C>2?Ke(C):C}var vg=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function wg(C){C=bg(C);var _=vg[C]||(typeof document!="undefined"?document.querySelector(C):void 0);return _}function jc(C){return wg(C)}function rh(C,_,B){var ee=jc(C);if(!ee)return-4;if(ee.canvasSharedPtr&&(i()[ee.canvasSharedPtr>>2]=_,i()[ee.canvasSharedPtr+4>>2]=B),ee.offscreenCanvas||!ee.controlTransferredOffscreen){ee.offscreenCanvas&&(ee=ee.offscreenCanvas);var be=!1;if(ee.GLctxObject&&ee.GLctxObject.GLctx){var Ae=ee.GLctxObject.GLctx.getParameter(2978);be=Ae[0]===0&&Ae[1]===0&&Ae[2]===ee.width&&Ae[3]===ee.height}ee.width=_,ee.height=B,be&&ee.GLctxObject.GLctx.viewport(0,0,_,B)}else if(ee.canvasSharedPtr){var xe=i()[ee.canvasSharedPtr+8>>2];return xg(xe,C,_,B),1}else return-4;return 0}function ah(C,_,B){return k?ba(2,1,C,_,B):rh(C,_,B)}function kg(C,_,B){var ee=jc(C);return ee?rh(C,_,B):ah(C,_,B)}function Sg(C){}function Ig(C,_){}function Cg(C){var _=C.getExtension("ANGLE_instanced_arrays");if(_)return C.vertexAttribDivisor=function(B,ee){_.vertexAttribDivisorANGLE(B,ee)},C.drawArraysInstanced=function(B,ee,be,Ae){_.drawArraysInstancedANGLE(B,ee,be,Ae)},C.drawElementsInstanced=function(B,ee,be,Ae,xe){_.drawElementsInstancedANGLE(B,ee,be,Ae,xe)},1}function Tg(C){var _=C.getExtension("OES_vertex_array_object");if(_)return C.createVertexArray=function(){return _.createVertexArrayOES()},C.deleteVertexArray=function(B){_.deleteVertexArrayOES(B)},C.bindVertexArray=function(B){_.bindVertexArrayOES(B)},C.isVertexArray=function(B){return _.isVertexArrayOES(B)},1}function Ng(C){var _=C.getExtension("WEBGL_draw_buffers");if(_)return C.drawBuffers=function(B,ee){_.drawBuffersWEBGL(B,ee)},1}function Eg(C){return!!(C.multiDrawWebgl=C.getExtension("WEBGL_multi_draw"))}var lt={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,recordError:function(_){lt.lastError||(lt.lastError=_)},getNewId:function(C){for(var _=lt.counter++,B=C.length;B<_;B++)C[B]=null;return _},getSource:function(C,_,B,ee){for(var be="",Ae=0;Ae<_;++Ae){var xe=ee?i()[ee+Ae*4>>2]:-1;be+=Ke(i()[B+Ae*4>>2],xe<0?void 0:xe)}return be},createContext:function(C,_){var B=C.getContext("webgl",_);if(!B)return 0;var ee=lt.registerContext(B,_);return ee},registerContext:function(C,_){var B=ci(8);i()[B+4>>2]=ka();var ee={handle:B,attributes:_,version:_.majorVersion,GLctx:C};return C.canvas&&(C.canvas.GLctxObject=ee),lt.contexts[B]=ee,(typeof _.enableExtensionsByDefault=="undefined"||_.enableExtensionsByDefault)&<.initExtensions(ee),B},makeContextCurrent:function(C){return lt.currentContext=lt.contexts[C],u.ctx=va=lt.currentContext&<.currentContext.GLctx,!(C&&!va)},getContext:function(C){return lt.contexts[C]},deleteContext:function(C){lt.currentContext===lt.contexts[C]&&(lt.currentContext=null),typeof Ge=="object"&&Ge.removeAllHandlersOnTarget(lt.contexts[C].GLctx.canvas),lt.contexts[C]&<.contexts[C].GLctx.canvas&&(lt.contexts[C].GLctx.canvas.GLctxObject=void 0),Zc(lt.contexts[C].handle),lt.contexts[C]=null},initExtensions:function(C){if(C||(C=lt.currentContext),!C.initExtensionsDone){C.initExtensionsDone=!0;var _=C.GLctx;Cg(_),Tg(_),Ng(_),_.disjointTimerQueryExt=_.getExtension("EXT_disjoint_timer_query"),Eg(_);var B=_.getSupportedExtensions()||[];B.forEach(function(ee){ee.indexOf("lose_context")<0&&ee.indexOf("debug")<0&&_.getExtension(ee)})}},populateUniformTable:function(C){for(var _=lt.programs[C],B=lt.programInfos[C]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},ee=B.uniforms,be=va.getProgramParameter(_,35718),Ae=0;Ae>2,ee=i()[B+(24>>2)],be={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:Rg[ee],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)]},Ae=jc(C);if(!Ae||be.explicitSwapControl)return 0;var xe=lt.createContext(Ae,be);return xe}function _g(C,_){return $g(C,_)}var Zl={mappings:{},buffers:[null,[],[]],printChar:function(C,_){var B=Zl.buffers[C];_===0||_===10?((C===1?q:z)(qe(B,0)),B.length=0):B.push(_)},varargs:void 0,get:function(){Zl.varargs+=4;var C=i()[Zl.varargs-4>>2];return C},getStr:function(C){var _=Ke(C);return _},get64:function(C,_){return C}};function oh(C){return k?ba(3,1,C):0}function ih(C,_,B,ee,be){if(k)return ba(4,1,C,_,B,ee,be)}function lh(C,_,B,ee){if(k)return ba(5,1,C,_,B,ee);for(var be=0,Ae=0;Ae>2],Ee=i()[_+(Ae*8+4)>>2],ct=0;ct>2]=be,0}function Dg(C){var _=$e.threadExitHandlers.pop();C&&_()}function Pg(C,_){$e.threadExitHandlers.push(function(){Rn.get(C)(_)})}function uh(C){if(k)throw"Internal Error! spawnThread() can only ever be called from main application thread!";var _=$e.getNewWorker();if(_.pthread!==void 0)throw"Internal error!";if(!C.pthread_ptr)throw"Internal error, no pthread ptr!";$e.runningWorkers.push(_);for(var B=ci(128*4),ee=0;ee<128;++ee)i()[B+ee*4>>2]=0;var be=C.stackBase+C.stackSize,Ae=$e.pthreads[C.pthread_ptr]={worker:_,stackBase:C.stackBase,stackSize:C.stackSize,allocatedOwnStack:C.allocatedOwnStack,threadInfoStruct:C.pthread_ptr},xe=Ae.threadInfoStruct>>2;Atomics.store(l(),xe+(64>>2),C.detached),Atomics.store(l(),xe+(100>>2),B),Atomics.store(l(),xe+(40>>2),Ae.threadInfoStruct),Atomics.store(l(),xe+(80>>2),C.stackSize),Atomics.store(l(),xe+(76>>2),be),Atomics.store(l(),xe+(104>>2),C.stackSize),Atomics.store(l(),xe+(104+8>>2),be),Atomics.store(l(),xe+(104+12>>2),C.detached);var Ee=N5(),ct=Ee+40;Atomics.store(l(),xe+(172>>2),ct),_.pthread=Ae;var hn={cmd:"run",start_routine:C.startRoutine,arg:C.arg,threadInfoStruct:C.pthread_ptr,stackBase:C.stackBase,stackSize:C.stackSize};_.runPthread=function(){hn.time=performance.now(),_.postMessage(hn,C.transferList)},_.loaded&&(_.runPthread(),delete _.runPthread)}function Fg(C,_,B,ee){if(typeof SharedArrayBuffer=="undefined")return z("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;if(!C)return z("pthread_create called with a null thread pointer!"),28;var be=[],Ae=0;if(k&&(be.length===0||Ae))return D5(687865856,C,_,B,ee);if(Ae)return Ae;var xe=0,Ee=0,ct=0;_&&_!=-1?(xe=i()[_>>2],xe+=81920,Ee=i()[_+8>>2],ct=i()[_+12>>2]!==0):xe=2097152;var hn=Ee==0;hn?Ee=O5(16,xe):(Ee-=xe,we(Ee>0));for(var en=ci(228),Sa=0;Sa<228>>2;++Sa)l()[(en>>2)+Sa]=0;i()[C>>2]=en,i()[en+12>>2]=en;var tu=en+152;i()[tu>>2]=tu;var Mn={stackBase:Ee,stackSize:xe,allocatedOwnStack:hn,detached:ct,startRoutine:B,pthread_ptr:en,arg:ee,transferList:be};return k?(Mn.cmd="spawnThread",postMessage(Mn,be)):uh(Mn),0}function Og(){if(!!k){var C=ka();if(!!C){var _=Atomics.load(l(),C+56>>2);if(!_){var B=Atomics.load(l(),C+0>>2);if(B==2)throw"Canceled!"}}}}function Mg(){b||y||K("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function zg(C,_,B){if(!C)return z("pthread_join attempted on a null thread pointer!"),xa.ESRCH;if(k&&ka()==C)return z("PThread "+C+" is attempting to join to itself!"),xa.EDEADLK;if(!k&&$5()==C)return z("Main thread "+C+" is attempting to join to itself!"),xa.EDEADLK;var ee=i()[C+12>>2];if(ee!==C)return z("pthread_join attempted on thread "+C+", which does not point to a valid thread, or does not exist anymore!"),xa.ESRCH;var be=Atomics.load(l(),C+64>>2);if(be)return z("Attempted to join thread "+C+", which was already detached!"),xa.EINVAL;for(B&&Mg();;){var Ae=Atomics.load(l(),C+0>>2);if(Ae==1){var xe=Atomics.load(l(),C+4>>2);return _&&(i()[_>>2]=xe),Atomics.store(l(),C+64>>2,1),k?postMessage({cmd:"cleanupThread",thread:C}):nh(C),0}if(!B)return xa.EBUSY;Og(),k||gh(),sh(C+0,Ae,k?100:1)}}function Lg(C,_){return zg(C,_,!0)}function ch(C){if(k)return ba(6,1,C);switch(C){case 30:return 16384;case 85:var _=2147483648;return _/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return typeof navigator=="object"&&navigator.hardwareConcurrency||1}return rg(28),-1}k||$e.initMainThreadBlock();var va,Bg=[null,ag,ah,oh,ih,lh,ch],Wg={e:ng,r:sg,x:og,b:ig,y:lg,j:ug,d:sh,c:Uc,f:ui,p:cg,A:dg,u:hg,q:gg,v:kg,i:Sg,s:Ig,w:_g,l:oh,n:ih,g:lh,o:Z0,a:se||u.wasmMemory,z:Dg,k:Pg,h:Fg,m:Lg,t:ch},C5=K0(),dh=u.___wasm_call_ctors=function(){return(dh=u.___wasm_call_ctors=u.asm.B).apply(null,arguments)},Vg=u._init=function(){return(Vg=u._init=u.asm.C).apply(null,arguments)},Ug=u._init_with_threads_count=function(){return(Ug=u._init_with_threads_count=u.asm.D).apply(null,arguments)},Gg=u._get_threads_count=function(){return(Gg=u._get_threads_count=u.asm.E).apply(null,arguments)},Hg=u._register_tensor=function(){return(Hg=u._register_tensor=u.asm.F).apply(null,arguments)},jg=u._dispose_data=function(){return(jg=u._dispose_data=u.asm.G).apply(null,arguments)},qg=u._dispose=function(){return(qg=u._dispose=u.asm.H).apply(null,arguments)},Xg=u._Abs=function(){return(Xg=u._Abs=u.asm.I).apply(null,arguments)},Kg=u._Add=function(){return(Kg=u._Add=u.asm.J).apply(null,arguments)},Zg=u._AddN=function(){return(Zg=u._AddN=u.asm.K).apply(null,arguments)},Yg=u._All=function(){return(Yg=u._All=u.asm.L).apply(null,arguments)},Jg=u._Any=function(){return(Jg=u._Any=u.asm.M).apply(null,arguments)},Qg=u._ArgMax=function(){return(Qg=u._ArgMax=u.asm.N).apply(null,arguments)},e2=u._AvgPool=function(){return(e2=u._AvgPool=u.asm.O).apply(null,arguments)},t2=u._BatchMatMul=function(){return(t2=u._BatchMatMul=u.asm.P).apply(null,arguments)},n2=u._Ceil=function(){return(n2=u._Ceil=u.asm.Q).apply(null,arguments)},s2=u._ClipByValue=function(){return(s2=u._ClipByValue=u.asm.R).apply(null,arguments)},r2=u._Conv2D=function(){return(r2=u._Conv2D=u.asm.S).apply(null,arguments)},ph=u._Conv2DBackpropInput=function(){return(ph=u._Conv2DBackpropInput=u.asm.T).apply(null,arguments)},hh=u._Cos=function(){return(hh=u._Cos=u.asm.U).apply(null,arguments)},qc=u._Cosh=function(){return(qc=u._Cosh=u.asm.V).apply(null,arguments)},Yl=u._CropAndResize=function(){return(Yl=u._CropAndResize=u.asm.W).apply(null,arguments)},a2=u._Cumsum=function(){return(a2=u._Cumsum=u.asm.X).apply(null,arguments)},Xc=u._DepthToSpace=function(){return(Xc=u._DepthToSpace=u.asm.Y).apply(null,arguments)},ae=u._DepthwiseConv2dNative=function(){return(ae=u._DepthwiseConv2dNative=u.asm.Z).apply(null,arguments)},le=u._Elu=function(){return(le=u._Elu=u.asm._).apply(null,arguments)},Se=u._Equal=function(){return(Se=u._Equal=u.asm.$).apply(null,arguments)},at=u._Exp=function(){return(at=u._Exp=u.asm.aa).apply(null,arguments)},Lt=u._FlipLeftRight=function(){return(Lt=u._FlipLeftRight=u.asm.ba).apply(null,arguments)},Et=u._Floor=function(){return(Et=u._Floor=u.asm.ca).apply(null,arguments)},Ze=u._FloorDiv=function(){return(Ze=u._FloorDiv=u.asm.da).apply(null,arguments)},Ye=u._FusedBatchNorm=function(){return(Ye=u._FusedBatchNorm=u.asm.ea).apply(null,arguments)},In=u._FusedConv2D=function(){return(In=u._FusedConv2D=u.asm.fa).apply(null,arguments)},qr=u._FusedDepthwiseConv2D=function(){return(qr=u._FusedDepthwiseConv2D=u.asm.ga).apply(null,arguments)},Xr=u._Gather=function(){return(Xr=u._Gather=u.asm.ha).apply(null,arguments)},fh=u._GatherNd=function(){return(fh=u._GatherNd=u.asm.ia).apply(null,arguments)},Kc=u._Greater=function(){return(Kc=u._Greater=u.asm.ja).apply(null,arguments)},fs=u._GreaterEqual=function(){return(fs=u._GreaterEqual=u.asm.ka).apply(null,arguments)},wa=u._LeakyRelu=function(){return(wa=u._LeakyRelu=u.asm.la).apply(null,arguments)},mh=u._Less=function(){return(mh=u._Less=u.asm.ma).apply(null,arguments)},RN=u._LessEqual=function(){return(RN=u._LessEqual=u.asm.na).apply(null,arguments)},$N=u._Log=function(){return($N=u._Log=u.asm.oa).apply(null,arguments)},_N=u._LogicalAnd=function(){return(_N=u._LogicalAnd=u.asm.pa).apply(null,arguments)},DN=u._Max=function(){return(DN=u._Max=u.asm.qa).apply(null,arguments)},PN=u._MaxPool=function(){return(PN=u._MaxPool=u.asm.ra).apply(null,arguments)},FN=u._Maximum=function(){return(FN=u._Maximum=u.asm.sa).apply(null,arguments)},ON=u._Mean=function(){return(ON=u._Mean=u.asm.ta).apply(null,arguments)},MN=u._Min=function(){return(MN=u._Min=u.asm.ua).apply(null,arguments)},zN=u._Minimum=function(){return(zN=u._Minimum=u.asm.va).apply(null,arguments)},LN=u._MirrorPad=function(){return(LN=u._MirrorPad=u.asm.wa).apply(null,arguments)},BN=u._Multiply=function(){return(BN=u._Multiply=u.asm.xa).apply(null,arguments)},WN=u._Neg=function(){return(WN=u._Neg=u.asm.ya).apply(null,arguments)},VN=u._NonMaxSuppressionV3=function(){return(VN=u._NonMaxSuppressionV3=u.asm.za).apply(null,arguments)},UN=u._NonMaxSuppressionV4=function(){return(UN=u._NonMaxSuppressionV4=u.asm.Aa).apply(null,arguments)},GN=u._NonMaxSuppressionV5=function(){return(GN=u._NonMaxSuppressionV5=u.asm.Ba).apply(null,arguments)},HN=u._NotEqual=function(){return(HN=u._NotEqual=u.asm.Ca).apply(null,arguments)},jN=u._OneHot=function(){return(jN=u._OneHot=u.asm.Da).apply(null,arguments)},qN=u._PadV2=function(){return(qN=u._PadV2=u.asm.Ea).apply(null,arguments)},XN=u._Pow=function(){return(XN=u._Pow=u.asm.Fa).apply(null,arguments)},KN=u._Prelu=function(){return(KN=u._Prelu=u.asm.Ga).apply(null,arguments)},ZN=u._Prod=function(){return(ZN=u._Prod=u.asm.Ha).apply(null,arguments)},YN=u._RealDiv=function(){return(YN=u._RealDiv=u.asm.Ia).apply(null,arguments)},JN=u._Relu=function(){return(JN=u._Relu=u.asm.Ja).apply(null,arguments)},QN=u._Relu6=function(){return(QN=u._Relu6=u.asm.Ka).apply(null,arguments)},eE=u._ResizeBilinear=function(){return(eE=u._ResizeBilinear=u.asm.La).apply(null,arguments)},tE=u._Reverse=function(){return(tE=u._Reverse=u.asm.Ma).apply(null,arguments)},nE=u._RotateWithOffset=function(){return(nE=u._RotateWithOffset=u.asm.Na).apply(null,arguments)},sE=u._Round=function(){return(sE=u._Round=u.asm.Oa).apply(null,arguments)},rE=u._Rsqrt=function(){return(rE=u._Rsqrt=u.asm.Pa).apply(null,arguments)},aE=u._ScatterNd=function(){return(aE=u._ScatterNd=u.asm.Qa).apply(null,arguments)},oE=u._SelectV2=function(){return(oE=u._SelectV2=u.asm.Ra).apply(null,arguments)},iE=u._Sigmoid=function(){return(iE=u._Sigmoid=u.asm.Sa).apply(null,arguments)},lE=u._Sin=function(){return(lE=u._Sin=u.asm.Ta).apply(null,arguments)},uE=u._Softmax=function(){return(uE=u._Softmax=u.asm.Ua).apply(null,arguments)},cE=u._Sqrt=function(){return(cE=u._Sqrt=u.asm.Va).apply(null,arguments)},dE=u._Square=function(){return(dE=u._Square=u.asm.Wa).apply(null,arguments)},pE=u._SquaredDifference=function(){return(pE=u._SquaredDifference=u.asm.Xa).apply(null,arguments)},hE=u._Step=function(){return(hE=u._Step=u.asm.Ya).apply(null,arguments)},fE=u._StridedSlice=function(){return(fE=u._StridedSlice=u.asm.Za).apply(null,arguments)},mE=u._Sub=function(){return(mE=u._Sub=u.asm._a).apply(null,arguments)},gE=u._Sum=function(){return(gE=u._Sum=u.asm.$a).apply(null,arguments)},AE=u._Tan=function(){return(AE=u._Tan=u.asm.ab).apply(null,arguments)},yE=u._Tanh=function(){return(yE=u._Tanh=u.asm.bb).apply(null,arguments)},xE=u._Tile=function(){return(xE=u._Tile=u.asm.cb).apply(null,arguments)},bE=u._TopK=function(){return(bE=u._TopK=u.asm.db).apply(null,arguments)},vE=u._Transform=function(){return(vE=u._Transform=u.asm.eb).apply(null,arguments)},wE=u._Transpose=function(){return(wE=u._Transpose=u.asm.fb).apply(null,arguments)},kE=u.__FusedMatMul=function(){return(kE=u.__FusedMatMul=u.asm.gb).apply(null,arguments)},ci=u._malloc=function(){return(ci=u._malloc=u.asm.hb).apply(null,arguments)},Zc=u._free=function(){return(Zc=u._free=u.asm.ib).apply(null,arguments)},T5=u.___errno_location=function(){return(T5=u.___errno_location=u.asm.jb).apply(null,arguments)},N5=u._emscripten_get_global_libc=function(){return(N5=u._emscripten_get_global_libc=u.asm.lb).apply(null,arguments)},ka=u._pthread_self=function(){return(ka=u._pthread_self=u.asm.mb).apply(null,arguments)},E5=u.___pthread_tsd_run_dtors=function(){return(E5=u.___pthread_tsd_run_dtors=u.asm.nb).apply(null,arguments)},gh=u._emscripten_main_thread_process_queued_calls=function(){return(gh=u._emscripten_main_thread_process_queued_calls=u.asm.ob).apply(null,arguments)},SE=u._emscripten_current_thread_process_queued_calls=function(){return(SE=u._emscripten_current_thread_process_queued_calls=u.asm.pb).apply(null,arguments)},R5=u._emscripten_register_main_browser_thread_id=function(){return(R5=u._emscripten_register_main_browser_thread_id=u.asm.qb).apply(null,arguments)},$5=u._emscripten_main_browser_thread_id=function(){return($5=u._emscripten_main_browser_thread_id=u.asm.rb).apply(null,arguments)},_5=u.__emscripten_do_dispatch_to_thread=function(){return(_5=u.__emscripten_do_dispatch_to_thread=u.asm.sb).apply(null,arguments)},D5=u._emscripten_sync_run_in_main_thread_4=function(){return(D5=u._emscripten_sync_run_in_main_thread_4=u.asm.tb).apply(null,arguments)},P5=u._emscripten_run_in_main_runtime_thread_js=function(){return(P5=u._emscripten_run_in_main_runtime_thread_js=u.asm.ub).apply(null,arguments)},o2=u.__emscripten_call_on_thread=function(){return(o2=u.__emscripten_call_on_thread=u.asm.vb).apply(null,arguments)},IE=u._emscripten_tls_init=function(){return(IE=u._emscripten_tls_init=u.asm.wb).apply(null,arguments)},i2=u.__emscripten_thread_init=function(){return(i2=u.__emscripten_thread_init=u.asm.xb).apply(null,arguments)},Yc=u.stackSave=function(){return(Yc=u.stackSave=u.asm.yb).apply(null,arguments)},Jl=u.stackRestore=function(){return(Jl=u.stackRestore=u.asm.zb).apply(null,arguments)},Ql=u.stackAlloc=function(){return(Ql=u.stackAlloc=u.asm.Ab).apply(null,arguments)},F5=u._emscripten_stack_set_limits=function(){return(F5=u._emscripten_stack_set_limits=u.asm.Bb).apply(null,arguments)},O5=u._memalign=function(){return(O5=u._memalign=u.asm.Cb).apply(null,arguments)},M5=u.__emscripten_allow_main_runtime_queued_calls=10064,eu=u.__emscripten_main_thread_futex=10268;u.cwrap=Ue,u.PThread=$e,u.PThread=$e,u.wasmMemory=se,u.ExitStatus=Jc;var Ah;function Jc(C){this.name="ExitStatus",this.message="Program terminated with exit("+C+")",this.status=C}ii=function C(){Ah||l2(),Ah||(ii=C)};function l2(C){if(C=C||m,Hs>0)return;if(k){d(u),Kp(),postMessage({cmd:"loaded"});return}if(Xp(),Hs>0)return;function _(){Ah||(Ah=!0,u.calledRun=!0,!pe&&(Kp(),Zp(),d(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),Yp()))}u.setStatus?(u.setStatus("Running..."),setTimeout(function(){setTimeout(function(){u.setStatus("")},1),_()},1)):_()}u.run=l2;function CE(C,_){if(!(_&&G&&C===0)){if(!_&&k)throw postMessage({cmd:"exitProcess",returnCode:C}),new Jc(C);G||($e.terminateAllThreads(),ye=C,ts(),u.onExit&&u.onExit(C),pe=!0),A(C,new Jc(C))}}if(u.preInit)for(typeof u.preInit=="function"&&(u.preInit=[u.preInit]);u.preInit.length>0;)u.preInit.pop()();return k&&(G=!1,$e.initWorker()),l2(),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)}}),qE=ss({"src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js"(e,t){var n=function(){var s=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(s=s||__filename),function(r){r=r||{};var a=typeof r!="undefined"?r:{},o,i;a.ready=new Promise(function(ae,le){o=ae,i=le});var l={},c;for(c in a)a.hasOwnProperty(c)&&(l[c]=a[c]);var u=[],d="./this.program",p=function(ae,le){throw le},h=!1,f=!1,m=!1,g=!1;h=typeof window=="object",f=typeof importScripts=="function",m=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g=!h&&!m&&!f;var A="";function x(ae){return a.locateFile?a.locateFile(ae,A):A+ae}var y,b,w,k,I,N;m?(f?A=js("path").dirname(A)+"/":A=__dirname+"/",y=function(le,Se){return I||(I=js("fs")),N||(N=js("path")),le=N.normalize(le),I.readFileSync(le,Se?null:"utf8")},w=function(le){var Se=y(le,!0);return Se.buffer||(Se=new Uint8Array(Se)),q(Se.buffer),Se},process.argv.length>1&&(d=process.argv[1].replace(/\\/g,"/")),u=process.argv.slice(2),process.on("uncaughtException",function(ae){if(!(ae instanceof a2))throw ae}),process.on("unhandledRejection",ur),p=function(ae){process.exit(ae)},a.inspect=function(){return"[Emscripten Module object]"}):g?(typeof read!="undefined"&&(y=function(le){return read(le)}),w=function(le){var Se;return typeof readbuffer=="function"?new Uint8Array(readbuffer(le)):(Se=read(le,"binary"),q(typeof Se=="object"),Se)},typeof scriptArgs!="undefined"?u=scriptArgs:typeof arguments!="undefined"&&(u=arguments),typeof quit=="function"&&(p=function(ae){quit(ae)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(h||f)&&(f?A=self.location.href:typeof document!="undefined"&&document.currentScript&&(A=document.currentScript.src),s&&(A=s),A.indexOf("blob:")!==0?A=A.substr(0,A.lastIndexOf("/")+1):A="",y=function(ae){var le=new XMLHttpRequest;return le.open("GET",ae,!1),le.send(null),le.responseText},f&&(w=function(ae){var le=new XMLHttpRequest;return le.open("GET",ae,!1),le.responseType="arraybuffer",le.send(null),new Uint8Array(le.response)}),b=function(ae,le,Se){var at=new XMLHttpRequest;at.open("GET",ae,!0),at.responseType="arraybuffer",at.onload=function(){if(at.status==200||at.status==0&&at.response){le(at.response);return}Se()},at.onerror=Se,at.send(null)},k=function(ae){document.title=ae});var R=a.print||console.log.bind(console),O=a.printErr||console.warn.bind(console);for(c in l)l.hasOwnProperty(c)&&(a[c]=l[c]);l=null,a.arguments&&(u=a.arguments),a.thisProgram&&(d=a.thisProgram),a.quit&&(p=a.quit);var $;a.wasmBinary&&($=a.wasmBinary);var P=a.noExitRuntime||!0;typeof WebAssembly!="object"&&ur("no native wasm support detected");var T,F=!1,U;function q(ae,le){ae||ur("Assertion failed: "+le)}function z(ae){var le=a["_"+ae];return q(le,"Cannot call unknown function "+ae+", make sure it is exported"),le}function K(ae,le,Se,at,Lt){var Et={string:function(fs){var wa=0;if(fs!=null&&fs!==0){var mh=(fs.length<<2)+1;wa=qc(mh),se(fs,wa,mh)}return wa},array:function(fs){var wa=qc(fs.length);return oe(fs,wa),wa}};function Ze(fs){return le==="string"?re(fs):le==="boolean"?Boolean(fs):fs}var Ye=z(ae),In=[],qr=0;if(at)for(var Xr=0;Xr=at);)++Lt;if(Lt-le>16&&ae.subarray&&Q)return Q.decode(ae.subarray(le,Lt));for(var Et="";le>10,56320|qr&1023)}}return Et}function re(ae,le){return ae?ne(Ne,ae,le):""}function G(ae,le,Se,at){if(!(at>0))return 0;for(var Lt=Se,Et=Se+at-1,Ze=0;Ze=55296&&Ye<=57343){var In=ae.charCodeAt(++Ze);Ye=65536+((Ye&1023)<<10)|In&1023}if(Ye<=127){if(Se>=Et)break;le[Se++]=Ye}else if(Ye<=2047){if(Se+1>=Et)break;le[Se++]=192|Ye>>6,le[Se++]=128|Ye&63}else if(Ye<=65535){if(Se+2>=Et)break;le[Se++]=224|Ye>>12,le[Se++]=128|Ye>>6&63,le[Se++]=128|Ye&63}else{if(Se+3>=Et)break;le[Se++]=240|Ye>>18,le[Se++]=128|Ye>>12&63,le[Se++]=128|Ye>>6&63,le[Se++]=128|Ye&63}}return le[Se]=0,Se-Lt}function se(ae,le,Se){return G(ae,Ne,le,Se)}function oe(ae,le){we.set(ae,le)}function pe(ae,le){return ae%le>0&&(ae+=le-ae%le),ae}var ye,we,Ne,Me,Ue,qe,Ke,dt,pt;function rt(ae){ye=ae,a.HEAP8=we=new Int8Array(ae),a.HEAP16=Me=new Int16Array(ae),a.HEAP32=qe=new Int32Array(ae),a.HEAPU8=Ne=new Uint8Array(ae),a.HEAPU16=Ue=new Uint16Array(ae),a.HEAPU32=Ke=new Uint32Array(ae),a.HEAPF32=dt=new Float32Array(ae),a.HEAPF64=pt=new Float64Array(ae)}var kt=a.INITIAL_MEMORY||16777216,mt,Nt=[],Dt=[],Ts=[],kn=[],lr=!1;Dt.push({func:function(){eh()}});function On(){if(a.preRun)for(typeof a.preRun=="function"&&(a.preRun=[a.preRun]);a.preRun.length;)Sn(a.preRun.shift());Hs(Nt)}function hs(){lr=!0,Hs(Dt)}function Gs(){Hs(Ts)}function Ns(){if(a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;)Tr(a.postRun.shift());Hs(kn)}function Sn(ae){Nt.unshift(ae)}function Tr(ae){kn.unshift(ae)}var Rn=0,Nr=null,Er=null;function ya(ae){Rn++,a.monitorRunDependencies&&a.monitorRunDependencies(Rn)}function Wc(ae){if(Rn--,a.monitorRunDependencies&&a.monitorRunDependencies(Rn),Rn==0&&(Nr!==null&&(clearInterval(Nr),Nr=null),Er)){var le=Er;Er=null,le()}}a.preloadedImages={},a.preloadedAudios={};function ur(ae){a.onAbort&&a.onAbort(ae),ae+="",O(ae),F=!0,U=1,ae="abort("+ae+"). Build with -s ASSERTIONS=1 for more info.";var le=new WebAssembly.RuntimeError(ae);throw i(le),le}function qp(ae,le){return String.prototype.startsWith?ae.startsWith(le):ae.indexOf(le)===0}var W0="data:application/octet-stream;base64,";function Xp(ae){return qp(ae,W0)}var Kp="file://";function Zp(ae){return qp(ae,Kp)}var ts="tfjs-backend-wasm.wasm";Xp(ts)||(ts=x(ts));function Yp(ae){try{if(ae==ts&&$)return new Uint8Array($);if(w)return w(ae);throw"both async and sync fetching of the wasm failed"}catch(le){ur(le)}}function V0(){if(!$&&(h||f)){if(typeof fetch=="function"&&!Zp(ts))return fetch(ts,{credentials:"same-origin"}).then(function(ae){if(!ae.ok)throw"failed to load wasm binary file at '"+ts+"'";return ae.arrayBuffer()}).catch(function(){return Yp(ts)});if(b)return new Promise(function(ae,le){b(ts,function(Se){ae(new Uint8Array(Se))},le)})}return Promise.resolve().then(function(){return Yp(ts)})}function U0(){var ae={a:ns};function le(Ze,Ye){var In=Ze.exports;a.asm=In,T=a.asm.h,rt(T.buffer),mt=a.asm.Sa,Wc("wasm-instantiate")}ya("wasm-instantiate");function Se(Ze){le(Ze.instance)}function at(Ze){return V0().then(function(Ye){return WebAssembly.instantiate(Ye,ae)}).then(Ze,function(Ye){O("failed to asynchronously prepare wasm: "+Ye),ur(Ye)})}function Lt(){return!$&&typeof WebAssembly.instantiateStreaming=="function"&&!Xp(ts)&&!Zp(ts)&&typeof fetch=="function"?fetch(ts,{credentials:"same-origin"}).then(function(Ze){var Ye=WebAssembly.instantiateStreaming(Ze,ae);return Ye.then(Se,function(In){return O("wasm streaming compile failed: "+In),O("falling back to ArrayBuffer instantiation"),at(Se)})}):at(Se)}if(a.instantiateWasm)try{var Et=a.instantiateWasm(ae,le);return Et}catch(Ze){return O("Module.instantiateWasm callback failed with error: "+Ze),!1}return Lt().catch(i),{}}function Hs(ae){for(;ae.length>0;){var le=ae.shift();if(typeof le=="function"){le(a);continue}var Se=le.func;typeof Se=="number"?le.arg===void 0?mt.get(Se)():mt.get(Se)(le.arg):Se(le.arg===void 0?null:le.arg)}}function Vc(){ur()}function ii(ae,le,Se){Ne.copyWithin(ae,le,le+Se)}function G0(){return Ne.length}function H0(ae){try{return T.grow(ae-ye.byteLength+65535>>>16),rt(T.buffer),1}catch(le){}}function jr(ae){var le=G0(),Se=2147483648;if(ae>Se)return!1;for(var at=1;at<=4;at*=2){var Lt=le*(1+.2/at);Lt=Math.min(Lt,ae+100663296);var Et=Math.min(Se,pe(Math.max(ae,Lt),65536)),Ze=H0(Et);if(Ze)return!0}return!1}var li={mappings:{},buffers:[null,[],[]],printChar:function(ae,le){var Se=li.buffers[ae];le===0||le===10?((ae===1?R:O)(ne(Se,0)),Se.length=0):Se.push(le)},varargs:void 0,get:function(){li.varargs+=4;var ae=qe[li.varargs-4>>2];return ae},getStr:function(ae){var le=re(ae);return le},get64:function(ae,le){return ae}};function j0(ae){return 0}function Jp(ae,le,Se,at,Lt){}function q0(ae,le,Se,at){for(var Lt=0,Et=0;Et>2],Ye=qe[le+(Et*8+4)>>2],In=0;In>2]=Lt,0}function Qp(){return 28}var ns={a:Vc,d:ii,e:jr,f:j0,c:Jp,b:q0,g:Qp},X0=U0(),eh=a.___wasm_call_ctors=function(){return(eh=a.___wasm_call_ctors=a.asm.i).apply(null,arguments)},K0=a._init=function(){return(K0=a._init=a.asm.j).apply(null,arguments)},th=a._init_with_threads_count=function(){return(th=a._init_with_threads_count=a.asm.k).apply(null,arguments)},Z0=a._get_threads_count=function(){return(Z0=a._get_threads_count=a.asm.l).apply(null,arguments)},Kl=a._register_tensor=function(){return(Kl=a._register_tensor=a.asm.m).apply(null,arguments)},xa=a._dispose_data=function(){return(xa=a._dispose_data=a.asm.n).apply(null,arguments)},Uc=a._dispose=function(){return(Uc=a._dispose=a.asm.o).apply(null,arguments)},Y0=a._Abs=function(){return(Y0=a._Abs=a.asm.p).apply(null,arguments)},J0=a._Add=function(){return(J0=a._Add=a.asm.q).apply(null,arguments)},nh=a._AddN=function(){return(nh=a._AddN=a.asm.r).apply(null,arguments)},$e=a._All=function(){return($e=a._All=a.asm.s).apply(null,arguments)},Q0=a._Any=function(){return(Q0=a._Any=a.asm.t).apply(null,arguments)},eg=a._ArgMax=function(){return(eg=a._ArgMax=a.asm.u).apply(null,arguments)},tg=a._AvgPool=function(){return(tg=a._AvgPool=a.asm.v).apply(null,arguments)},ng=a._BatchMatMul=function(){return(ng=a._BatchMatMul=a.asm.w).apply(null,arguments)},sg=a._Ceil=function(){return(sg=a._Ceil=a.asm.x).apply(null,arguments)},ui=a._ClipByValue=function(){return(ui=a._ClipByValue=a.asm.y).apply(null,arguments)},rg=a._Conv2D=function(){return(rg=a._Conv2D=a.asm.z).apply(null,arguments)},ag=a._Conv2DBackpropInput=function(){return(ag=a._Conv2DBackpropInput=a.asm.A).apply(null,arguments)},og=a._Cos=function(){return(og=a._Cos=a.asm.B).apply(null,arguments)},ig=a._Cosh=function(){return(ig=a._Cosh=a.asm.C).apply(null,arguments)},lg=a._CropAndResize=function(){return(lg=a._CropAndResize=a.asm.D).apply(null,arguments)},ug=a._Cumsum=function(){return(ug=a._Cumsum=a.asm.E).apply(null,arguments)},sh=a._DepthToSpace=function(){return(sh=a._DepthToSpace=a.asm.F).apply(null,arguments)},cg=a._DepthwiseConv2dNative=function(){return(cg=a._DepthwiseConv2dNative=a.asm.G).apply(null,arguments)},dg=a._Elu=function(){return(dg=a._Elu=a.asm.H).apply(null,arguments)},ba=a._Equal=function(){return(ba=a._Equal=a.asm.I).apply(null,arguments)},Gc=a._Exp=function(){return(Gc=a._Exp=a.asm.J).apply(null,arguments)},Hc=a._FlipLeftRight=function(){return(Hc=a._FlipLeftRight=a.asm.K).apply(null,arguments)},pg=a._Floor=function(){return(pg=a._Floor=a.asm.L).apply(null,arguments)},hg=a._FloorDiv=function(){return(hg=a._FloorDiv=a.asm.M).apply(null,arguments)},fg=a._FusedBatchNorm=function(){return(fg=a._FusedBatchNorm=a.asm.N).apply(null,arguments)},mg=a._FusedConv2D=function(){return(mg=a._FusedConv2D=a.asm.O).apply(null,arguments)},gg=a._FusedDepthwiseConv2D=function(){return(gg=a._FusedDepthwiseConv2D=a.asm.P).apply(null,arguments)},Ge=a._Gather=function(){return(Ge=a._Gather=a.asm.Q).apply(null,arguments)},Ag=a._GatherNd=function(){return(Ag=a._GatherNd=a.asm.R).apply(null,arguments)},yg=a._Greater=function(){return(yg=a._Greater=a.asm.S).apply(null,arguments)},xg=a._GreaterEqual=function(){return(xg=a._GreaterEqual=a.asm.T).apply(null,arguments)},bg=a._LeakyRelu=function(){return(bg=a._LeakyRelu=a.asm.U).apply(null,arguments)},vg=a._Less=function(){return(vg=a._Less=a.asm.V).apply(null,arguments)},wg=a._LessEqual=function(){return(wg=a._LessEqual=a.asm.W).apply(null,arguments)},jc=a._Log=function(){return(jc=a._Log=a.asm.X).apply(null,arguments)},rh=a._LogicalAnd=function(){return(rh=a._LogicalAnd=a.asm.Y).apply(null,arguments)},ah=a._Max=function(){return(ah=a._Max=a.asm.Z).apply(null,arguments)},kg=a._MaxPool=function(){return(kg=a._MaxPool=a.asm._).apply(null,arguments)},Sg=a._Maximum=function(){return(Sg=a._Maximum=a.asm.$).apply(null,arguments)},Ig=a._Mean=function(){return(Ig=a._Mean=a.asm.aa).apply(null,arguments)},Cg=a._Min=function(){return(Cg=a._Min=a.asm.ba).apply(null,arguments)},Tg=a._Minimum=function(){return(Tg=a._Minimum=a.asm.ca).apply(null,arguments)},Ng=a._MirrorPad=function(){return(Ng=a._MirrorPad=a.asm.da).apply(null,arguments)},Eg=a._Multiply=function(){return(Eg=a._Multiply=a.asm.ea).apply(null,arguments)},lt=a._Neg=function(){return(lt=a._Neg=a.asm.fa).apply(null,arguments)},Rg=a._NonMaxSuppressionV3=function(){return(Rg=a._NonMaxSuppressionV3=a.asm.ga).apply(null,arguments)},$g=a._NonMaxSuppressionV4=function(){return($g=a._NonMaxSuppressionV4=a.asm.ha).apply(null,arguments)},_g=a._NonMaxSuppressionV5=function(){return(_g=a._NonMaxSuppressionV5=a.asm.ia).apply(null,arguments)},Zl=a._NotEqual=function(){return(Zl=a._NotEqual=a.asm.ja).apply(null,arguments)},oh=a._OneHot=function(){return(oh=a._OneHot=a.asm.ka).apply(null,arguments)},ih=a._PadV2=function(){return(ih=a._PadV2=a.asm.la).apply(null,arguments)},lh=a._Pow=function(){return(lh=a._Pow=a.asm.ma).apply(null,arguments)},Dg=a._Prelu=function(){return(Dg=a._Prelu=a.asm.na).apply(null,arguments)},Pg=a._Prod=function(){return(Pg=a._Prod=a.asm.oa).apply(null,arguments)},uh=a._RealDiv=function(){return(uh=a._RealDiv=a.asm.pa).apply(null,arguments)},Fg=a._Relu=function(){return(Fg=a._Relu=a.asm.qa).apply(null,arguments)},Og=a._Relu6=function(){return(Og=a._Relu6=a.asm.ra).apply(null,arguments)},Mg=a._ResizeBilinear=function(){return(Mg=a._ResizeBilinear=a.asm.sa).apply(null,arguments)},zg=a._Reverse=function(){return(zg=a._Reverse=a.asm.ta).apply(null,arguments)},Lg=a._RotateWithOffset=function(){return(Lg=a._RotateWithOffset=a.asm.ua).apply(null,arguments)},ch=a._Round=function(){return(ch=a._Round=a.asm.va).apply(null,arguments)},va=a._Rsqrt=function(){return(va=a._Rsqrt=a.asm.wa).apply(null,arguments)},Bg=a._ScatterNd=function(){return(Bg=a._ScatterNd=a.asm.xa).apply(null,arguments)},Wg=a._SelectV2=function(){return(Wg=a._SelectV2=a.asm.ya).apply(null,arguments)},C5=a._Sigmoid=function(){return(C5=a._Sigmoid=a.asm.za).apply(null,arguments)},dh=a._Sin=function(){return(dh=a._Sin=a.asm.Aa).apply(null,arguments)},Vg=a._Softmax=function(){return(Vg=a._Softmax=a.asm.Ba).apply(null,arguments)},Ug=a._Sqrt=function(){return(Ug=a._Sqrt=a.asm.Ca).apply(null,arguments)},Gg=a._Square=function(){return(Gg=a._Square=a.asm.Da).apply(null,arguments)},Hg=a._SquaredDifference=function(){return(Hg=a._SquaredDifference=a.asm.Ea).apply(null,arguments)},jg=a._Step=function(){return(jg=a._Step=a.asm.Fa).apply(null,arguments)},qg=a._StridedSlice=function(){return(qg=a._StridedSlice=a.asm.Ga).apply(null,arguments)},Xg=a._Sub=function(){return(Xg=a._Sub=a.asm.Ha).apply(null,arguments)},Kg=a._Sum=function(){return(Kg=a._Sum=a.asm.Ia).apply(null,arguments)},Zg=a._Tan=function(){return(Zg=a._Tan=a.asm.Ja).apply(null,arguments)},Yg=a._Tanh=function(){return(Yg=a._Tanh=a.asm.Ka).apply(null,arguments)},Jg=a._Tile=function(){return(Jg=a._Tile=a.asm.La).apply(null,arguments)},Qg=a._TopK=function(){return(Qg=a._TopK=a.asm.Ma).apply(null,arguments)},e2=a._Transform=function(){return(e2=a._Transform=a.asm.Na).apply(null,arguments)},t2=a._Transpose=function(){return(t2=a._Transpose=a.asm.Oa).apply(null,arguments)},n2=a.__FusedMatMul=function(){return(n2=a.__FusedMatMul=a.asm.Pa).apply(null,arguments)},s2=a._malloc=function(){return(s2=a._malloc=a.asm.Qa).apply(null,arguments)},r2=a._free=function(){return(r2=a._free=a.asm.Ra).apply(null,arguments)},ph=a.stackSave=function(){return(ph=a.stackSave=a.asm.Ta).apply(null,arguments)},hh=a.stackRestore=function(){return(hh=a.stackRestore=a.asm.Ua).apply(null,arguments)},qc=a.stackAlloc=function(){return(qc=a.stackAlloc=a.asm.Va).apply(null,arguments)};a.cwrap=J;var Yl;function a2(ae){this.name="ExitStatus",this.message="Program terminated with exit("+ae+")",this.status=ae}Er=function ae(){Yl||Xc(),Yl||(Er=ae)};function Xc(ae){if(ae=ae||u,Rn>0||(On(),Rn>0))return;function le(){Yl||(Yl=!0,a.calledRun=!0,!F&&(hs(),Gs(),o(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),Ns()))}a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),le()},1)):le()}if(a.run=Xc,a.preInit)for(typeof a.preInit=="function"&&(a.preInit=[a.preInit]);a.preInit.length>0;)a.preInit.pop()();return Xc(),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)}}),XE=1e-7,KE=1e-4,sd=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}},ru=class{refCount(e){return qs("refCount")}incRef(e){return qs("incRef")}timerAvailable(){return!0}time(e){return qs("time")}read(e){return qs("read")}readSync(e){return qs("readSync")}numDataIds(){return qs("numDataIds")}disposeData(e,t){return qs("disposeData")}write(e,t,n){return qs("write")}move(e,t,n,s,r){return qs("move")}memory(){return qs("memory")}floatPrecision(){return qs("floatPrecision")}epsilon(){return this.floatPrecision()===32?XE:KE}dispose(){return qs("dispose")}};function qs(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 V5(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,bh(e,t,n)}function ZE(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--,bh(e,n,s),bh(t,n,s)}function rd(e,t,n){return Math.max(e,Math.min(t,n))}function YE(e){return e%2==0?e:e+1}function bh(e,t,n){let s=e[t];e[t]=e[n],e[n]=s}function JE(e){let t=0;for(let n=0;nn+` Shapes ${e} and ${t} must match`)}function pi(e){M(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function hi(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||_n(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 o9(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 Xs(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=>fn(s)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(s=>s<0?n+s:s)}function U5(e,t){let n=[],s=[],r=t!=null&&Array.isArray(t)&&t.length===0,a=t==null||r?null:Xs(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 G5(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 H5(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 j5(e,t){for(let n=0;nt+=n.length),t}function Na(e){return typeof e=="string"||e instanceof String}function K5(e){return typeof e=="boolean"}function Z5(e){return typeof e=="number"}function vh(e){return Array.isArray(e)?vh(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":Z5(e)?"float32":Na(e)?"string":K5(e)?"bool":"float32"}function Ea(e){return!!(e&&e.constructor&&e.call&&e.apply)}function wh(e,t){for(let n=t;n=0;--s)n[s]=n[s+1]*e[s+1];return n}function Y5(e,t,n,s=!1){let r=new Array;if(t.length===1){let a=t[0]*(s?2:1);for(let o=0;ol*c)*(s?2:1);for(let l=0;lr*a)*(n?2:1);if(s===0)return[];if(s!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return Y5(0,e,t,n)}function p2(e,t){let n=kh(e,t);for(let s=0;ss*r,1);if(t==null||t==="float32")return ou(e,new Float32Array(n));if(t==="int32")return ou(e,new Int32Array(n));if(t==="bool")return ou(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function h2(e){e.forEach(t=>{M(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function u9(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]=h9(s,r)})}};function d9(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...s)=>(p9(t,s[0],s[1]),s.join("="))),t}function p9(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function h9(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 Y(){return Rr}var Rr=null;function f9(e){Rr=e}var m2;function e3(){if(m2==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");m2=e}return m2}function m9(){let e=e3();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function g2(e,t){let n=m9();if(n.has(e))return n.get(e);{let s=t();return n.set(e,s),n.get(e)}}var fi="Abs",iu="Acos",lu="Acosh",Kr="Add",Ra="AddN",uu="All",cu="Any",$a="ArgMax",du="ArgMin",pu="Asin",hu="Asinh",fu="Atan",mu="Atanh",gu="Atan2",_a="AvgPool",Sh="AvgPoolGrad",od="AvgPool3D",Ih="AvgPool3DGrad",Da="BatchMatMul",mi="BatchToSpaceND",Ch="Bincount",t3="BroadcastTo",Th="BroadcastArgs",Pa="Cast",Fa="Ceil",Zr="ClipByValue",id="Complex",ld="ComplexAbs",gi="Concat",Oa="Conv2D",Nh="Conv2DBackpropFilter",Ma="Conv2DBackpropInput",ud="Conv3D",Eh="Conv3DBackpropFilterV2",Rh="Conv3DBackpropInputV2",za="Cos",La="Cosh",Ai="Cumsum",yi="CropAndResize",$h="DenseBincount",xi="DepthToSpace",Ba="DepthwiseConv2dNative",_h="DepthwiseConv2dNativeBackpropFilter",Dh="DepthwiseConv2dNativeBackpropInput",Ph="Diag",cd="Dilation2D",Fh="Dilation2DBackpropInput",Oh="Dilation2DBackpropFilter",Wa="RealDiv",dd="Einsum",Va="Elu",Mh="EluGrad",Au="Erf",bi="Equal",Ua="Exp",vi="ExpandDims",wi="Expm1",zh="FFT",yu="Fill",ki="FlipLeftRight",Ga="Floor",Ha="FloorDiv",ja="FusedBatchNorm",Si="GatherV2",Ii="GatherNd",Ci="Greater",qa="GreaterEqual",Xa="Identity",Lh="IFFT",pd="Imag",xu="IsFinite",bu="IsInf",vu="IsNan",Ti="LeakyRelu",Ni="Less",Ei="LessEqual",Bh="LinSpace",Ka="Log",wu="Log1p",Ri="LogicalAnd",ku="LogicalNot",hd="LogicalOr",n3="LogSoftmax",fd="LRN",Wh="LRNGrad",Za="Max",Ya="Maximum",Ja="MaxPool",Vh="MaxPoolGrad",md="MaxPool3D",Uh="MaxPool3DGrad",Gh="MaxPoolWithArgmax",Qa="Mean",eo="Min",to="Minimum",no="MirrorPad",Su="Mod",Hh="Multinomial",so="Multiply",$i="Neg",_i="NotEqual",Di="NonMaxSuppressionV3",Iu="NonMaxSuppressionV4",Pi="NonMaxSuppressionV5",Fi="OnesLike",Oi="OneHot",Mi="Pack",ro="PadV2",g9="Pool",ao="Pow",oo="Prelu",zi="Prod",Cu="Range",gd="Real",Tu="Reciprocal",io="Relu",Li="Reshape",Nu="ResizeNearestNeighbor",jh="ResizeNearestNeighborGrad",lo="ResizeBilinear",qh="ResizeBilinearGrad",uo="Relu6",Bi="Reverse",Wi="Round",co="Rsqrt",Vi="ScatterNd",Ui="Select",Eu="Selu",Gi="Slice",po="Sin",Hi="Sinh",Ru="Sign",ho="Sigmoid",$u="Softplus",fo="Sqrt",mo="Sum",ji="SpaceToBatchND",qi="SplitV",go="Softmax",Xh="SparseFillEmptyRows",Kh="SparseReshape",Zh="SparseSegmentMean",Yh="SparseSegmentSum",Ad="SparseToDense",Ao="SquaredDifference",_u="Square",Xi="StridedSlice",yd="StringNGrams",Jh="StringSplit",Qh="StringToHashBucketFast",yo="Sub",Ki="Tan",xo="Tanh",Yr="Tile",Zi="TopK",Yi="Transform",bo="Transpose",ef="Unique",Ji="Unpack",xd="UnsortedSegmentSum",Qi="ZerosLike",vo="Step",bd="FromPixels",el="RotateWithOffset",wo="_FusedMatMul",ko="FusedConv2D",So="FusedDepthwiseConv2D";function Io(...e){Y().getBool("IS_TEST")||Y().getBool("PROD")||console.warn(...e)}function A9(...e){Y().getBool("IS_TEST")||Y().getBool("PROD")||console.log(...e)}var Du=g2("kernelRegistry",()=>new Map),vd=g2("gradRegistry",()=>new Map);function tf(e,t){let n=y2(e,t);return Du.get(n)}function A2(e){return vd.get(e)}function Jr(e){let t=Du.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 cr(e){let{kernelName:t,backendName:n}=e,s=y2(t,n);Du.has(s)&&Io(`The kernel '${t}' for backend '${n}' is already registered`),Du.set(s,e)}function s3(e){let{kernelName:t}=e;vd.has(t)&&Y().getBool("DEBUG")&&Io(`Overriding the gradient for '${t}'`),vd.set(t,e)}function y9(e,t){let n=y2(e,t);if(!Du.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);Du.delete(n)}function x9(e){if(!vd.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);vd.delete(e)}function b9(e,t){Jr(e).forEach(s=>{let r=Object.assign({},s,{backendName:t});cr(r)})}function y2(e,t){return`${t}_${e}`}var v={};Oe(v,{arraysEqual:()=>Ta,assert:()=>M,assertNonNegativeIntegerDimensions:()=>h2,assertNonNull:()=>pi,assertShapesMatch:()=>zn,bytesFromStringArray:()=>X5,bytesPerElement:()=>d2,checkConversionForErrors:()=>j5,clamp:()=>rd,computeStrides:()=>au,createScalarValue:()=>C9,createShuffledIndices:()=>r9,decodeString:()=>rf,distSquared:()=>e9,encodeString:()=>Sd,fetch:()=>N9,fingerPrint64:()=>I9,flatten:()=>hi,getArrayFromDType:()=>H5,getTypedArrayFromDType:()=>G5,hasEncodingLoss:()=>i9,hexToLong:()=>wd,indexToLoc:()=>c9,inferDtype:()=>vh,inferFromImplicitShape:()=>o9,isBoolean:()=>K5,isFunction:()=>Ea,isInt:()=>fn,isNumber:()=>Z5,isPromise:()=>f2,isScalarShape:()=>t9,isString:()=>Na,isTypedArray:()=>_n,isValidDtype:()=>q5,locToIndex:()=>u9,makeOnesTypedArray:()=>p2,makeZerosNestedTypedArray:()=>l9,makeZerosTypedArray:()=>kh,nearestDivisor:()=>wh,nearestLargerEven:()=>YE,now:()=>kd,parseAxisParam:()=>Xs,randUniform:()=>QE,repeatedTry:()=>a9,rightPad:()=>ad,shuffle:()=>V5,shuffleCombo:()=>ZE,sizeFromShape:()=>Gt,sizeToSquarishShape:()=>s9,squeezeShape:()=>U5,sum:()=>JE,swap:()=>bh,tanh:()=>n9,toNestedArray:()=>ou,toTypedArray:()=>sf});var r3=di(FE()),tl=r3.default||r3;function wd(e){return tl.fromString(e,!0,16)}var a3=wd("c3a5c85c97cb3127"),nl=wd("b492b66fbe98f273"),Ln=wd("9ae16a3b2f90404f");function x2(e){return e.xor(e.shru(47))}function o3(e,t,n){let s=e.slice(t,t+n);return tl.fromBytes(Array.from(s),!0,!0)}function vt(e,t){return o3(e,t,8)}function i3(e,t){return o3(e,t,4)}function mn(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function Co(e,t,n=wd("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 v9(e,t,n,s,r,a){r=r.add(e),a=mn(a.add(r).add(s),21);let o=r;return r=r.add(t),r=r.add(n),a=a.add(mn(r,44)),[r.add(s),a.add(o)]}function nf(e,t,n,s){return v9(vt(e,t),vt(e,t+8),vt(e,t+16),vt(e,t+24),n,s)}function w9(e,t=e.length){if(t>=8){let n=Ln.add(t*2),s=vt(e,0).add(Ln),r=vt(e,t-8),a=mn(r,37).mul(n).add(s),o=mn(s,25).add(r).mul(n);return Co(a,o,n)}if(t>=4){let n=Ln.add(t*2),s=i3(e,0);return Co(s.shl(3).add(t),i3(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 x2(Ln.mul(a).xor(a3.mul(o))).mul(Ln)}return Ln}function k9(e,t=e.length){let n=Ln.add(t*2),s=vt(e,0).mul(nl),r=vt(e,8),a=vt(e,t-8).mul(n),o=vt(e,t-16).mul(Ln);return Co(mn(s.add(r),43).add(mn(a,30)).add(o),s.add(mn(r.add(Ln),18)).add(a),n)}function S9(e,t=e.length){let n=Ln.add(t*2),s=vt(e,0).mul(Ln),r=vt(e,8),a=vt(e,t-8).mul(n),o=vt(e,t-16).mul(Ln),i=mn(s.add(r),43).add(mn(a,30)).add(o),l=Co(i,s.add(mn(r.add(Ln),18)).add(a),n),c=vt(e,16).mul(n),u=vt(e,24),d=i.add(vt(e,t-32)).mul(n),p=l.add(vt(e,t-24)).mul(n);return Co(mn(c.add(u),43).add(mn(d,30)).add(p),c.add(mn(u.add(s),18)).add(d),n)}function I9(e,t=e.length){let n=tl.fromNumber(81,!0);if(t<=32)return t<=16?w9(e,t):k9(e,t);if(t<=64)return S9(e,t);let s=n,r=n.mul(nl).add(113),a=x2(r.mul(Ln).add(113)).mul(Ln),o=[tl.UZERO,tl.UZERO],i=[tl.UZERO,tl.UZERO];s=s.mul(Ln).add(vt(e,0));let l=0,c=(t-1>>6)*64,u=c+(t-1&63)-63;do s=mn(s.add(r).add(o[0]).add(vt(e,l+8)),37).mul(nl),r=mn(r.add(o[1]).add(vt(e,l+48)),42).mul(nl),s=s.xor(i[1]),r=r.add(o[0]).add(vt(e,l+40)),a=mn(a.add(i[0]),33).mul(nl),o=nf(e,l,o[1].mul(nl),s.add(i[0])),i=nf(e,l+32,a.add(i[1]),r.add(vt(e,l+16))),[a,s]=[s,a],l+=64;while(l!==c);let d=nl.add(a.and(255).shl(1));return l=u,i[0]=i[0].add(t-1&63),o[0]=o[0].add(i[0]),i[0]=i[0].add(o[0]),s=mn(s.add(r).add(o[0]).add(vt(e,l+8)),37).mul(d),r=mn(r.add(o[1]).add(vt(e,l+48)),42).mul(d),s=s.xor(i[1].mul(9)),r=r.add(o[0].mul(9).add(vt(e,l+40))),a=mn(a.add(i[0]),33).mul(d),o=nf(e,l,o[1].mul(d),s.add(i[0])),i=nf(e,l+32,a.add(i[1]),r.add(vt(e,l+16))),[a,s]=[s,a],Co(Co(o[0],i[0],d).add(x2(r).mul(a3)).add(a),Co(o[1],i[1],d).add(s),d)}function C9(e,t){return t==="string"?Sd(e):sf([e],t)}function T9(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function sf(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=hi(e)),Y().getBool("DEBUG")&&j5(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=kd();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(r);else{r();for(let l of s)l.dataSync();a=Promise.resolve({kernelMs:kd()-o})}if(Y().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let l=0;l{R9(u,c.dtype,e)})}return{kernelName:e,outputs:s,inputs:t,timeMs:a.then(l=>l.kernelMs),extraInfo:a.then(l=>l.getExtraProfileInfo!=null?l.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:s,inputs:r,extraInfo:a}=e;n.forEach(o=>{Promise.all([o.data(),s,a]).then(i=>{this.logger.logKernelProfile(t,o,i[0],i[1],r,i[2])})})}};function R9(e,t,n){if(t!=="float32")return!1;for(let s=0;s0?f:""} `}}console.log(`%c${i} %c${o} %c${l}D ${u} %c${c} %c${d} %c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function _9(e,t,n){let s={},r={};for(let l=0;ls[m.id]=!0),h=!0,r[c.id]=!0;break}if(h)break}}let a={};a[n.id]=!0;let o={};for(let l=e.length-1;l>=0;l--){let c=e[l],u=c.inputs;for(let d=0;d=0;r--){let a=t[r],o=[];if(a.outputs.forEach(l=>{let c=e[l.id];c!=null?o.push(c):o.push(null)}),a.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);let i=a.gradient(o);for(let l in a.inputs){if(!(l in i))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(i)}.`);let c=n(()=>i[l]());if(c.dtype!=="float32")throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${c.dtype}'`);let u=a.inputs[l];if(!Ta(c.shape,u.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${l}' has shape '${c.shape}', which does not match the shape of the input '${u.shape}'`);if(e[u.id]==null)e[u.id]=c;else{let d=e[u.id];e[u.id]=s(d,c),d.dispose()}}}}var l3=20,Id=3,b2=7;function P9(e,t,n,s){let r=au(t),a=F9(e,t,n,r),o=t.length,i=af(e,t,n,r,a),l=["Tensor"];return s&&(l.push(` dtype: ${n}`),l.push(` rank: ${o}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(i.map(c=>" "+c).join(` `)),l.join(` `)}function F9(e,t,n,s){let r=Gt(t),a=s[s.length-1],o=new Array(a).fill(0),i=t.length,l=n==="complex64"?Td(e):e;if(i>1)for(let c=0;cl3){let g=Id*o,A=Array.from(e.slice(0,g)),x=Array.from(e.slice((i-Id)*o,i*o));return n==="complex64"&&(A=Td(A),x=Td(x)),["["+A.map((y,b)=>Cd(y,r[b],n)).join(", ")+", ..., "+x.map((y,b)=>Cd(y,r[i-Id+b],n)).join(", ")+"]"]}let m=n==="complex64"?Td(e):Array.from(e);return["["+m.map((g,A)=>Cd(g,r[A],n)).join(", ")+"]"]}let c=t.slice(1),u=s.slice(1),d=s[0]*o,p=[];if(i>l3){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||H5(t,this.size),this.strides=au(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;srf(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=$r().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>rf(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 $r().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||($r().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Pu.print(this,e)}clone(){return this.throwIfDisposed(),Pu.clone(this)}toString(e=!1){let t=this.dataSync();return P9(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Pu.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),$r().makeVariable(this,e,t,n)}};Object.defineProperty(Je,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function B9(){return g2("Tensor",()=>Je)}B9();var Nd=class extends Je{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(!Ta(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);$r().disposeTensor(this),this.dataId=e.dataId,$r().incRef(this,null)}dispose(){$r().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(Nd,Symbol.hasInstance,{value:e=>e instanceof Je&&e.assign!=null&&e.assign instanceof Function});var dr={};Oe(dr,{assertTypesMatch:()=>c3,getTensorsInContainer:()=>C2,isTensorInList:()=>V9,makeTypesMatch:()=>Pt});var v2;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(v2||(v2={}));var w2;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(w2||(w2={}));var k2;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(k2||(k2={}));var S2;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(S2||(S2={}));var I2;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(I2||(I2={}));var W9={float32:S2,int32:w2,bool:k2,complex64:I2};function Bn(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return W9[e][t]}function Ed(e){return Bn(e,"int32")}function Pt(e,t){if(e.dtype===t.dtype)return[e,t];let n=Bn(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function c3(e,t){M(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function V9(e,t){return t.some(n=>n.id===e.id)}function C2(e){let t=[],n=new Set;return d3(e,t,n),t}function d3(e,t,n){if(e==null)return;if(e instanceof Je){t.push(e);return}if(!U9(e))return;let s=e;for(let r in s){let a=s[r];n.has(a)||(n.add(a),d3(a,t,n))}}function U9(e){return Array.isArray(e)||typeof e=="object"}function T2(e){return e.kernelName!=null}var p3=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()}},N2=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new p3}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){Jr(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 ru)&&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 N2.nextTensorId++}nextVariableId(){return N2.nextVariableId++}clone(e){let t=W.runKernel(Xa,{x:e}),n={x:e},s=a=>({x:()=>{let o="float32",i={x:a},l={dtype:o};return W.runKernel(Pa,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,!(tf(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=T2(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(T2(e)){let{kernelName:h,inputs:f,attrs:m}=e;this.backendName==null&&this.backend;let g=tf(h,this.backendName);M(g!=null,()=>`Cannot find registered kernel '${h}' for backend '${this.backendName}'`),o=()=>{let A=this.backend.numDataIds();i=g.kernelFunc({inputs:f,attrs:m,backend:this.backend});let x=Array.isArray(i)?i:[i];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(h,A,x);let y=x.map(b=>{if(b.rank!=null)return b;let{dataId:w,shape:k,dtype:I}=b;return this.makeTensorFromDataId(w,k,I)});if(s){let b=this.getTensorsForGradient(h,f,y);n=this.saveTensorsForBackwardMode(b)}return y}}else{let{forwardFunc:h}=e,f=m=>{!s||(n=m.map(g=>this.keep(this.clone(g))))};o=()=>{let m=this.backend.numDataIds();i=this.tidy(()=>h(this.backend,f));let g=Array.isArray(i)?i:[i];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,m,g),g}}let{inputs:c,attrs:u}=e,d=T2(e)?null:e.backwardsFunc,p;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=o():(p=this.profiler.profileKernel(l,c,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs)}),s&&this.addTapeNode(l,c,t,d,n,u),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map(h=>c[h]!=null?c[h].shape:null),outputShapes:t.map(h=>h.shape),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(i)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(n=>this.keep(this.clone(n)))}getTensorsForGradient(e,t,n){let s=A2(e);if(s!=null){let r=s.inputsToSave||[],a=s.outputsToSave||[],o;s.saveAllInputs?(M(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),o=Object.keys(t).map(l=>t[l])):o=r.map(l=>t[l]);let i=n.filter((l,c)=>a[c]);return o.concat(i)}return[]}makeTensor(e,t,n,s){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",s=s||this.backend;let r=e;n==="string"&&Na(e[0])&&(r=e.map(i=>Sd(i)));let a=s.write(r,t,n),o=new Je(t,n,a,this.nextTensorId());if(this.trackTensor(o,s),n==="string"){let i=this.state.tensorInfo.get(a),l=X5(r);this.state.numBytes+=l-i.bytes,i.bytes=l}return o}makeTensorFromDataId(e,t,n,s){n=n||"float32";let r=new Je(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 Nd(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*d2(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 Nd||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*d2(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=A2(e);i!=null&&(s=i.gradFunc),s!=null&&(o.gradient=l=>(l=l.map((c,u)=>{if(c==null){let d=n[u],p=kh(d.size,d.dtype);return this.makeTensor(p,d.shape,d.dtype)}return c}),s(l.length>1?l:l[0],r,a))),this.state.activeTape.push(o)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=C2(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 Je,()=>"The result y returned by f() must be a tensor.");let a=_9(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?G9(r.shape):n,D9(o,a,l=>this.tidy(l),H9);let i=t.map(l=>o[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let c of l.saved)c.dispose()}),this.state.activeTape=null),{value:r,grads:i}})}customGrad(e){return M(Ea(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{M(t.every(o=>o instanceof Je),()=>"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 Je,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),M(Ea(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),a=(o,i)=>{let l=n.gradFunc(o,i),c=Array.isArray(l)?l:[l];M(c.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),M(c.every(d=>d instanceof Je),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let u={};return c.forEach((d,p)=>{u[p]=()=>d}),u};return this.runKernelFunc({forwardFunc:r,backwardsFunc:a,inputs:s})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}async time(e){let t=kd(),n=await this.backend.time(e);return n.wallMs=kd()-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 p3;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}},E2=N2;E2.nextTensorId=0;E2.nextVariableId=0;function G9(e){let t=p2(Gt(e),"float32");return W.makeTensor(t,e,"float32")}function h3(){let e=e3();if(e._tfengine==null){let t=new Q5(e);e._tfengine=new E2(t)}return f9(e._tfengine.ENV),M9(()=>e._tfengine),e._tfengine}var W=h3();function H9(e,t){let n={a:e,b:t};return W.runKernel(Kr,n)}var Fu={};Oe(Fu,{isBrowser:()=>f3,isMobile:()=>X9,mockIsMobile:()=>q9});function j9(){return typeof navigator!="undefined"&&navigator!=null}var R2;function q9(e){R2=e}function X9(e){if(R2!==void 0)return R2;if(e||j9()){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 f3(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var pr=Y();pr.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.")});pr.registerFlag("IS_BROWSER",()=>f3());pr.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");pr.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));pr.registerFlag("PROD",()=>!1);pr.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>pr.getBool("DEBUG"));pr.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);pr.registerFlag("IS_TEST",()=>!1);pr.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);pr.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function _r(e,t){let n=e;if(_n(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let s=[];for(;Array.isArray(n)||_n(n)&&t!=="string";)s.push(n.length),n=n[0];return Array.isArray(e)&&Y().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&m3(e,s,[]),s}function m3(e,t,n){if(n=n||[],!Array.isArray(e)&&!_n(e)){M(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}M(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),M(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let s=t.slice(1);for(let r=0;r=0&&(r=s),g3(s,r,t,n),e==null||!_n(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){let l=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${l}'`)}let a=_r(e,r);!_n(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?sf(e,r):hi(e,[],!0);return W.makeTensor(i,a,r)}function Rd(e,t,n,s="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((a,o)=>D(a,`${t}[${o}]`,n,s))}var A3="__op";function V(e){let t=Object.keys(e);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0],s=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+A3;let r=(...a)=>{W.startScope(n);try{let o=s(...a);return f2(o)&&console.error("Cannot return a Promise inside of tidy."),W.endScope(o),o}catch(o){throw W.endScope(null),o}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}function K9(e,t){let n=D(e,"real","complex"),s=D(t,"imag","complex");zn(n.shape,s.shape,`real and imag shapes, ${n.shape} and ${s.shape}, must match in call to tf.complex().`);let r={real:n,imag:s};return W.runKernel(id,r)}var To=V({complex_:K9});function No(e,t,n,s){if(s==null&&(s=vh(e)),s==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!_n(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string")throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(t!=null){h2(t);let r=Gt(t),a=Gt(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!_n(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=s!=="string"?sf(e,s):hi(e,[],!0),W.makeTensor(e,t,s)}function ut(e,t,n){let s=_r(e,n);return No(e,t,s,n)}var $2={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},of=4;async function Z9(e,t){let n=[],s=[],r=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);for(let o=0;o{let p=await l.bytes(),h=p.reduce((g,A)=>g+A.length,0)+of*p.length,f=new Uint8Array(h),m=0;for(let g=0;g{if(t+=a.byteLength,n.push(a.byteLength===a.buffer.byteLength?a:new a.constructor(a)),!(a instanceof Float32Array||a instanceof Int32Array||a instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${a.constructor.name}`)});let s=new Uint8Array(t),r=0;return n.forEach(a=>{s.set(new Uint8Array(a.buffer),r),r+=a.byteLength}),s.buffer}var _2=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function x3(e){return _2?Buffer.byteLength(e):new Blob([e]).size}function J9(e){if(_2)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 b3(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 v3(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 P2(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 $d(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:x3(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:x3(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function eR(){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 tR(){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 nR(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function sR(){let e=eR(),t=tR(),n=nR();return s=>{let r=new ArrayBuffer(4*s.length),a=new Uint32Array(r);for(let o=0;o>10]+(i&1023)]+t[i>>10];a[o]=l}return new Float32Array(r)}}var Bt=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Bt.instance==null&&(Bt.instance=new Bt),Bt.instance}static registerSaveRouter(e){Bt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Bt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Bt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Bt.getHandlers(e,"load",t)}static getHandlers(e,t,n){let s=[];return(t==="load"?Bt.getInstance().loadRouters:Bt.getInstance().saveRouters).forEach(a=>{let o=a(e,n);o!==null&&s.push(o)}),s}},rR=e=>Bt.registerSaveRouter(e),aR=e=>Bt.registerLoadRouter(e),oR=e=>Bt.getSaveHandlers(e),iR=(e,t)=>Bt.getLoadHandlers(e,t),F2="tensorflowjs",O2=1,sl="models_store",Eo="model_info_store";function w3(){if(!Y().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 M2(e){let t=e.result;t.createObjectStore(sl,{keyPath:"modelPath"}),t.createObjectStore(Eo,{keyPath:"modelPath"})}var rl=class{constructor(e){if(this.indexedDB=w3(),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(F2,O2);r.onupgradeneeded=()=>M2(r),r.onsuccess=()=>{let a=r.result;if(t==null){let o=a.transaction(sl,"readonly"),l=o.objectStore(sl).get(this.modelPath);l.onsuccess=()=>{if(l.result==null)return a.close(),s(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(l.result.modelArtifacts)},l.onerror=c=>(a.close(),s(l.error)),o.oncomplete=()=>a.close()}else{let o=$d(t),i=a.transaction(Eo,"readwrite"),l=i.objectStore(Eo),c=l.put({modelPath:this.modelPath,modelArtifactsInfo:o}),u;c.onsuccess=()=>{u=a.transaction(sl,"readwrite");let p=u.objectStore(sl).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:o});p.onsuccess=()=>n({modelArtifactsInfo:o}),p.onerror=h=>{l=i.objectStore(Eo);let f=l.delete(this.modelPath);f.onsuccess=()=>(a.close(),s(p.error)),f.onerror=m=>(a.close(),s(p.error))}},c.onerror=d=>(a.close(),s(c.error)),i.oncomplete=()=>{u==null?a.close():u.oncomplete=()=>a.close()}}},r.onerror=a=>s(r.error)})}};rl.URL_SCHEME="indexeddb://";var k3=e=>Y().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(rl.URL_SCHEME)?lR(e.slice(rl.URL_SCHEME.length)):null;Bt.registerSaveRouter(k3);Bt.registerLoadRouter(k3);function lR(e){return new rl(e)}function uR(e){return e.startsWith(rl.URL_SCHEME)?e.slice(rl.URL_SCHEME.length):e}var cR=class{constructor(){this.indexedDB=w3()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(F2,O2);n.onupgradeneeded=()=>M2(n),n.onsuccess=()=>{let s=n.result,r=s.transaction(Eo,"readonly"),o=r.objectStore(Eo).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=uR(e),new Promise((t,n)=>{let s=this.indexedDB.open(F2,O2);s.onupgradeneeded=()=>M2(s),s.onsuccess=()=>{let r=s.result,a=r.transaction(Eo,"readwrite"),o=a.objectStore(Eo),i=o.get(e),l;i.onsuccess=()=>{if(i.result==null)return r.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let c=o.delete(e),u=()=>{l=r.transaction(sl,"readwrite");let p=l.objectStore(sl).delete(e);p.onsuccess=()=>t(i.result.modelArtifactsInfo),p.onerror=h=>n(i.error)};c.onsuccess=u,c.onerror=d=>(u(),r.close(),n(i.error))}},i.onerror=c=>(r.close(),n(i.error)),a.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},s.onerror=r=>n(s.error)})}},Qr="/",Ou="tensorflowjs_models",S3="info",dR="model_topology",pR="weight_specs",hR="weight_data",fR="model_metadata";function I3(e){return{info:[Ou,e,S3].join(Qr),topology:[Ou,e,dR].join(Qr),weightSpecs:[Ou,e,pR].join(Qr),weightData:[Ou,e,hR].join(Qr),modelMetadata:[Ou,e,fR].join(Qr)}}function C3(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function mR(e){let t=e.split(Qr);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Qr)}function gR(e){return e.startsWith(al.URL_SCHEME)?e.slice(al.URL_SCHEME.length):e}var al=class{constructor(e){if(!Y().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=I3(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=$d(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,J9(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 C3(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=Q9(a),t}};al.URL_SCHEME="localstorage://";var T3=e=>Y().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(al.URL_SCHEME)?AR(e.slice(al.URL_SCHEME.length)):null;Bt.registerSaveRouter(T3);Bt.registerLoadRouter(T3);function AR(e){return new al(e)}var yR=class{constructor(){M(Y().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=Ou+Qr,n=Qr+S3;for(let s=0;s"scheme must not be undefined or null."),e.endsWith(Mu)&&(e=e.slice(0,e.indexOf(Mu))),M(e.length>0,()=>"scheme must not be an empty string.");let n=Es.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 lf(e){if(e.indexOf(Mu)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Es.getSchemes().join(",")}`);return{scheme:e.split(Mu)[0],path:e.split(Mu)[1]}}async function N3(e,t,n=!1){M(e!==t,()=>`Old path and new path are the same: '${e}'`);let s=Bt.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=Bt.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=lf(e).scheme,l=lf(e).path,c=i===lf(e).scheme,u=await r.load();n&&c&&await Es.getManager(i).removeModel(l);let d=await o.save(u);return n&&!c&&await Es.getManager(i).removeModel(l),d.modelArtifactsInfo}async function xR(){let e=Es.getSchemes(),t={};for(let n of e){let s=await Es.getManager(n).listModels();for(let r in s){let a=n+Mu+r;t[a]=s[r]}}return t}async function bR(e){let t=lf(e);return Es.getManager(t.scheme).removeModel(t.path)}async function vR(e,t){return N3(e,t,!1)}async function wR(e,t){return N3(e,t,!0)}var kR=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(Y().get("IS_BROWSER")){Y().setPlatform("browser",new kR);try{Es.registerManager(al.URL_SCHEME,new yR)}catch(e){}try{Es.registerManager(rl.URL_SCHEME,new cR)}catch(e){}}var SR={importFetch:()=>OE()},z2,IR=class{constructor(){this.util=ME(),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return Y().global.fetch!=null?Y().global.fetch(e,t):(z2==null&&(z2=SR.importFetch()),z2(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)}};Y().get("IS_NODE")&&Y().setPlatform("node",new IR);function ze(e,t="float32",n){return t=t||"float32",h2(e),new tn(e,t,n)}function CR(e,t){let n=D(e,"x","cast");if(!q5(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&n.dtype!=="string"||t!=="string"&&n.dtype==="string")throw new Error("Only strings can be casted to strings");let s={x:n},r={dtype:t};return W.runKernel(Pa,s,r)}var me=V({cast_:CR});function TR(e){let n={x:D(e,"x","clone","string_or_numeric")};return W.runKernel(Xa,n)}var Wn=V({clone_:TR});function E3(e,t=!1){console.log(e.toString(t))}h3();var NR={buffer:ze,cast:me,clone:Wn,print:E3};z9(NR);var rs={};Oe(rs,{browserFiles:()=>FR,browserHTTPRequest:()=>BR,concatenateArrayBuffers:()=>D2,copyModel:()=>vR,decodeWeights:()=>y3,encodeWeights:()=>Z9,fromMemory:()=>VR,getLoadHandlers:()=>iR,getModelArtifactsForJSON:()=>P2,getModelArtifactsInfoForJSON:()=>$d,getSaveHandlers:()=>oR,http:()=>V2,isHTTPScheme:()=>W2,listModels:()=>xR,loadWeights:()=>OR,moveModel:()=>wR,registerLoadRouter:()=>aR,registerSaveRouter:()=>rR,removeModel:()=>bR,weightsLoaderFactory:()=>D3,withSaveHandler:()=>UR});var ER="model",RR=".json",$R=".weights.bin";function R3(e){return new Promise(t=>setTimeout(t)).then(e)}var L2=class{constructor(e){if(!Y().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(L2.URL_SCHEME)&&(e=e.slice(L2.URL_SCHEME.length)),(e==null||e.length===0)&&(e=ER),this.modelJsonFileName=e+RR,this.weightDataFileName=e+$R}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=v3(e,n),r=window.URL.createObjectURL(new Blob([JSON.stringify(s)],{type:"application/json"})),a=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(a.download=this.modelJsonFileName,a.href=r,await R3(()=>a.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let o=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;o.download=this.weightDataFileName,o.href=t,await R3(()=>o.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:$d(e)}}}},uf=L2;uf.URL_SCHEME="downloads://";var _R=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=P2(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,D2(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=>b3(r.name)),s={};for(let r of e)r.paths.forEach(a=>{let o=b3(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}},DR=e=>Y().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(uf.URL_SCHEME)?PR(e.slice(uf.URL_SCHEME.length)):null;Bt.registerSaveRouter(DR);function PR(e="model"){return new uf(e)}function FR(e){return new _R(e)}function $3(e,t,n,s){o(e),n=n==null?0:n,s=s==null?1:s,i(n,s);let r=0,a=l=>(l.then(c=>{let u=n+ ++r/e.length*(s-n);return t(u),c}),l);function o(l){M(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function i(l,c){M(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),M(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${c}`),M(c>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${c}`)}return Promise.all(e.map(a))}async function _3(e,t){t==null&&(t={});let n=t.fetchFunc==null?Y().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 $3(s,t.onProgress,r,a)).map(d=>d.arrayBuffer()),l=.5,c=1;return t.onProgress==null?await Promise.all(i):await $3(i,t.onProgress,l,c)}async function OR(e,t="",n,s){return D3(o=>_3(o,{requestInit:s}))(e,t,n)}function D3(e){return async(t,n="",s)=>{let r=t.map(()=>!1),a={},o=s!=null?s.map(()=>!1):[],i=[];if(t.forEach((h,f)=>{let m=0;h.weights.forEach(g=>{let A="quantization"in g?g.quantization.dtype:g.dtype,x=$2[A]*Gt(g.shape),y=()=>{r[f]=!0,a[f]==null&&(a[f]=[]),a[f].push({manifestEntry:g,groupOffset:m,sizeBytes:x})};s!=null?s.forEach((b,w)=>{b===g.name&&(y(),o[w]=!0)}):y(),i.push(g.name),m+=x})}),!o.every(h=>h)){let h=s.filter((f,m)=>!o[m]);throw new Error(`Could not find weights in manifest with names: ${h.join(", ")}. Manifest JSON has weights with names: ${i.join(", ")}.`)}let l=r.reduce((h,f,m)=>(f&&h.push(m),h),[]),c=[];l.forEach(h=>{t[h].paths.forEach(f=>{let m=n+(n.endsWith("/")?"":"/")+f;c.push(m)})});let u=await e(c),d={},p=0;return l.forEach(h=>{let f=t[h].paths.length,m=0;for(let b=0;b{let w=g.slice(b.groupOffset,b.groupOffset+b.sizeBytes),k=y3(w,[b.manifestEntry]);for(let I in k)d[I]=k[I]}),p+=f}),d}}var MR="application/octet-stream",zR="application/json",B2=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=Y().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=v3(e,n);t.body.append("model.json",new Blob([JSON.stringify(s)],{type:zR}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:MR}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:$d(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 P2(t,r=>this.loadWeights(r))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=LR(t),r=this.weightPathPrefix||n,a=[];for(let c of e)a.push(...c.weights);let o=[],i=[];for(let c of e)for(let u of c.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(u)):o.push(r+u+s);this.weightUrlConverter&&o.push(...await Promise.all(i));let l=await _3(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,D2(l)]}};B2.URL_SCHEME_REGEX=/^https?:\/\//;function LR(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),s=e.substring(0,t),r=n>t?e.substring(n):"";return[s+"/",r]}function W2(e){return e.match(B2.URL_SCHEME_REGEX)!=null}var P3=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(s=>W2(s)):n=W2(e),n)return V2(e,t)}return null};Bt.registerSaveRouter(P3);Bt.registerLoadRouter(P3);function V2(e,t){return new B2(e,t)}function BR(e,t){return V2(e,t)}var U2=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},WR=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function VR(e,t,n,s){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new U2(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 U2({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 U2({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:s}))}function UR(e){return new WR(e)}var F3={};Oe(F3,{confusionMatrix:()=>XR});function GR(e,t,n=!1,s=!1){let r=D(e,"a","matMul"),a=D(t,"b","matMul");[r,a]=Pt(r,a);let o={a:r,b:a},i={transposeA:n,transposeB:s};return W.runKernel(Da,o,i)}var He=V({matMul_:GR});function HR(e,t,n=1,s=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let a={indices:D(e,"indices","oneHot","int32")},o={depth:t,onValue:n,offValue:s};return W.runKernel(Oi,a,o)}var _d=V({oneHot_:HR});function jR(e,t){let n=D(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 W.runKernel(bo,s,r)}var Qe=V({transpose_:jR});function qR(e,t,n){let s=D(e,"labels","confusionMatrix"),r=D(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=_d(me(s,"int32"),n),o=_d(me(r,"int32"),n),i=Qe(a),l=He(i,o);return me(l,"int32")}var XR=V({confusionMatrix_:qR}),ol={};Oe(ol,{assertAndGetBroadcastShape:()=>gt,getBroadcastDims:()=>O3,getReductionAxes:()=>Xt});function O3(e,t){let n=e.length,s=[];for(let r=0;r1&&o===1&&s.unshift(a)}return s}function Xt(e,t){let n=[];for(let s=0;s1)&&n.unshift(a)}return n}function gt(e,t){let n=[],s=Math.max(e.length,t.length);for(let r=0;rt$,fromPixelsAsync:()=>QR,toPixels:()=>e$});function M3(e,t,n){if(pi(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let s=_r(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 No(e,t,s,n)}var il;function z3(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(tf(bd,W.backendName)!=null){let f={pixels:e},m={numChannels:t};return W.runKernel(bd,f,m)}let[c,u]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height],d;if(o)d=e.getContext("2d").getImageData(0,0,c,u).data;else if(s||n)d=e.data;else if(a||r||i){if(il==null)if(typeof document=="undefined")if(typeof OffscreenCanvas!="undefined"&&typeof OffscreenCanvasRenderingContext2D!="undefined")il=new OffscreenCanvas(1,1).getContext("2d");else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");else il=document.createElement("canvas").getContext("2d");il.canvas.width=c,il.canvas.height=u,il.drawImage(e,0,0,c,u),d=il.getImageData(0,0,c,u).data}let p;if(t===4)p=new Int32Array(d);else{let f=c*u;p=new Int32Array(f*t);for(let m=0;m4||a===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${a}`);if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);let o=await n.data(),i=n.dtype==="float32"?255:1,l=new Uint8ClampedArray(r*s*4);for(let c=0;c1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${h}.`)}else if(n.dtype==="int32"&&(h<0||h>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${h}.`);a===1?(u[0]=h*i,u[1]=h*i,u[2]=h*i):u[p]=h*i}let d=c*4;l[d+0]=Math.round(u[0]),l[d+1]=Math.round(u[1]),l[d+2]=Math.round(u[2]),l[d+3]=Math.round(u[3])}if(t!=null){t.width=r,t.height=s;let c=t.getContext("2d"),u=new ImageData(l,r,s);c.putImageData(u,0,0)}return n!==e&&n.dispose(),l}var t$=V({fromPixels_:z3}),G2={};Oe(G2,{prepareAndValidate:()=>L3});function L3(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(Gt(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let r=t.shape,a=r[r.length-1],o=1;for(let d=0;dd/c),1].slice(0,a);return[l,o,c,u]}var H2={};Oe(H2,{calculateShapes:()=>B3,validateInput:()=>q2,validateUpdateShape:()=>j2});function j2(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;ds$,computeFlatOffset:()=>l$,computeOutShape:()=>a$,getNormalizedAxes:()=>o$,isSliceContinous:()=>i$,maskToAxes:()=>r$,parseSliceParams:()=>K3,sliceInfo:()=>u$,startForAxis:()=>q3,startIndicesWithElidedDims:()=>G3,stopForAxis:()=>X3,stopIndicesWithElidedDims:()=>H3,stridesForAxis:()=>j3,stridesWithElidedDims:()=>W3});var X2=-2,n$=-1;function s$(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 r$(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function a$(e,t,n){let s=[];for(let r=0;r0){let h=t[0],f=n+1;u=G3(o,h,f,s,e),d=H3(i,h,f,r,e),p=W3(a,h,f,e)}else for(let h=0;h-1)a[i]=0;else{let l=V3(t,n,i),c=s[l];e&1<-1)a[i]=Number.MAX_SAFE_INTEGER;else{let l=V3(t,n,i),c=s[l];e&1<0?o=Number.MIN_SAFE_INTEGER:o=Number.MAX_SAFE_INTEGER);let l=s[r];return o<0&&(o+=l),o=rd(0,o,l-1),o}function X3(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=rd(0,o,l):o=rd(-1,o,l-1),o}function i$(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 l$(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 u$(e,t,n,s,r,a,o,i,l){let c;if(s==null?(c=new Array(t.length),c.fill(1)):c=s,o!=null&&(o&o-1)!=0)throw new Error("Multiple ellipses in slice is not allowed.");let u=!1,d={dims:c.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:c.slice(),beginMask:r,endMask:a,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:l};for(let y=0;y0?0:-1,p.strides[y]>0?w:w-1];if(b&&p.strides[y]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&p.strides[y]===1;let N=!!(p.beginMask&1<=w)throw Error(`slice index ${p.begin[y]} of dimension ${y} out of bounds.`)}else p.begin[y]=Z3(p.begin[y],0,p.strides[y],w,k,I),p.end[y]=Z3(p.end[y],1,p.strides[y],w,k,I);let $=p.strides[y]===1&&p.begin[y]===0&&p.end[y]===w;h=h&&$,f=f&&(y===0&&p.strides[y]===1||$)}else h=h&&p.strides[y]===1&&N,f=f&&(y===0&&p.strides[y]===1||N);let R,O=!1;if(p.beginValid&&p.endValid?(R=p.end[y]-p.begin[y],O=!0):b?(R=1,O=!0):N&&w>=0&&(p.strides[y]<0?R=-w:R=w,O=!0),O){let $;R===0||R<0!=p.strides[y]<0?$=0:$=Math.trunc(R/p.strides[y])+(R%p.strides[y]!=0?1:0),g.push($)}else g.push(-1)}for(let y=0;y=0?A.push(g[b]):b===X2&&A.push(1)}return{finalShapeSparse:A.filter((y,b)=>p.finalShapeGatherIndices[b]!==X2),finalShape:A,isIdentity:h,sliceDim0:f,isSimpleSlice:m,begin:p.begin,end:p.end,strides:p.strides}}function c$(e,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let n=0;t.beginValid=e.begin!=null,t.endValid=e.end!=null,t.begin=new Array(t.dims),t.end=new Array(t.dims),t.strides=new Array(t.dims),t.finalShapeGatherIndices=[],t.finalShapeGatherIndicesSparse=[],t.inputShapeGatherIndicesSparse=new Array(t.dims);for(let s=0;s0?a[t]:a[t+1&1];{let o=e<0?s+e:e;return oa[1]?a[1]:o}}var ce={};Oe(ce,{Serializable:()=>Y3,SerializationMap:()=>ll,registerClass:()=>Ro});var Y3=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},ll=class{constructor(){this.classNameMap={}}static getMap(){return ll.instance==null&&(ll.instance=new ll),ll.instance}static register(e){ll.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function Ro(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."),ll.register(e)}var J3={};Oe(J3,{TEST_EPSILON_FLOAT16:()=>Q3,encodeStrings:()=>ev,expectArrayBuffersEqual:()=>A$,expectArraysClose:()=>p$,expectArraysEqual:()=>f$,expectNumbersClose:()=>m$,expectPromiseToFail:()=>h$,expectValuesInRange:()=>g$,testEpsilon:()=>K2});var d$=.001,Q3=.1;function p$(e,t,n){return n==null&&(n=K2()),Z2(e,t,(s,r)=>Y2(s,r,n))}function K2(){return W.backend.floatPrecision()===32?d$:Q3}function Z2(e,t,n){let s=!0;if((_n(e)||_n(t))&&(s=!1),_n(e)&&_n(t)&&(s=!0),s){let o=e.constructor.name,i=t.constructor.name;if(o!==i)throw new Error(`Arrays are of different type. Actual: ${o}. Expected: ${i}`)}if(Array.isArray(e)&&Array.isArray(t)){let o=_r(e),i=_r(t);if(!Ta(o,i))throw new Error(`Arrays have different shapes. Actual: [${o}]. Expected: [${i}]`)}let r=_n(e)?e:hi(e),a=_n(t)?t:hi(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 f$(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Na(e)||Na(e[0])||Na(t)||Na(t[0])?Z2(e,n,(s,r)=>s==r):Z2(e,t,(s,r)=>Y2(s,r,0))}function m$(e,t,n){if(n==null&&(n=K2()),!Y2(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function Y2(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function g$(e,t,n){for(let s=0;sn)throw new Error(`Value out of range:${e[s]} low: ${t}, high: ${n}`)}function A$(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function ev(e){for(let t=0;tn.dispose())}function gn(e){return W.keep(e)}function w$(e){return W.time(e)}function nv(e){return W.setBackend(e)}function df(){return W.ready()}function Rs(){return W.backendName}function k$(e){W.removeBackend(e)}function Q2(e){return W.findBackend(e)}function S$(e){return W.findBackendFactory(e)}function ul(e,t,n=1){return W.registerBackend(e,t,n)}function Dr(){return W.backend}function I$(e,t){Y().setPlatform(e,t)}function C$(e,t){let n=D(e,"a","add"),s=D(t,"b","add");[n,s]=Pt(n,s);let r={a:n,b:s};return W.runKernel(Kr,r)}var ue=V({add_:C$});function T$(e,t){let n=D(e,"a","floorDiv"),s=D(t,"b","floorDiv");[n,s]=Pt(n,s);let r={a:n,b:s};return W.runKernel(Ha,r)}var pf=V({floorDiv_:T$});function N$(e,t){let n=D(e,"a","div"),s=D(t,"b","div");if([n,s]=Pt(n,s),n.dtype==="int32"&&s.dtype==="int32")return pf(n,s);let r={a:n,b:s},a={};return W.runKernel(Wa,r,a)}var ge=V({div_:N$});function E$(e,t){let n=D(e,"a","mul"),s=D(t,"b","mul");[n,s]=Pt(n,s);let r={a:n,b:s};return W.runKernel(so,r)}var L=V({mul_:E$});function R$(e){let t=D(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return W.runKernel(ld,n)}else{let n={x:t};return W.runKernel(fi,n)}}var nn=V({abs_:R$});function $$(e){let n={x:D(e,"x","acos")};return W.runKernel(iu,n)}var sv=V({acos_:$$});function _$(e){let n={x:D(e,"x","acosh")};return W.runKernel(lu,n)}var rv=V({acosh_:_$});function D$(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)=>D(r,`tensors${a}`,"addN")),n=t[0];t.forEach(r=>{if(r.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!Ta(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let s=t;return W.runKernel(Ra,s)}var hf=V({addN_:D$});function P$(e,t=null,n=!1){let r={x:D(e,"x","all","bool")},a={axis:t,keepDims:n};return W.runKernel(uu,r,a)}var e1=V({all_:P$});function F$(e,t=null,n=!1){let r={x:D(e,"x","any","bool")},a={axis:t,keepDims:n};return W.runKernel(cu,r,a)}var ff=V({any_:F$});function O$(e,t=0){let s={x:D(e,"x","argMax")},r={axis:t};return W.runKernel($a,s,r)}var Zs=V({argMax_:O$});function M$(e,t=0){let s={x:D(e,"x","argMin")},r={axis:t};return W.runKernel(du,s,r)}var av=V({argMin_:M$});function z$(e){let n={x:D(e,"x","asin")};return W.runKernel(pu,n)}var ov=V({asin_:z$});function L$(e){let n={x:D(e,"x","asinh")};return W.runKernel(hu,n)}var iv=V({asinh_:L$});function B$(e){let n={x:D(e,"x","atan")};return W.runKernel(fu,n)}var lv=V({atan_:B$});function W$(e,t){let n=D(e,"a","atan2"),s=D(t,"b","atan2");[n,s]=Pt(n,s);let r={a:n,b:s};return W.runKernel(gu,r)}var uv=V({atan2_:W$});function V$(e){let n={x:D(e,"x","atanh")};return W.runKernel(mu,n)}var cv=V({atanh_:V$});function U$(e,t,n,s,r="NHWC",a){let o=e[3],i=[...t,o],l=hv(r);return Dd(e,i,n,a,s,null,null,l)}function dv(e,t,n,s,r,a,o="channelsLast"){let[i,l]=mf(t),c;if(o==="channelsLast")c=[i,l,e[3],e[3]];else if(o==="channelsFirst")c=[i,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return Dd(e,c,n,s,r,a,!1,o)}function G$(e,t,n,s,r,a,o="NDHWC"){let[i,l,c]=n1(t),u,d;if(o==="NDHWC")d="channelsLast",u=[i,l,c,e[4],e[4]];else if(o==="NCDHW")d="channelsFirst",u=[i,l,c,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return pv(e,u,n,s,r,!1,d,a)}function Dd(e,t,n,s,r,a,o=!1,i="channelsLast"){let[l,c,u,d]=[-1,-1,-1,-1];if(i==="channelsLast")[l,c,u,d]=e;else if(i==="channelsFirst")[l,d,c,u]=e;else throw new Error(`Unknown dataFormat ${i}`);let[p,h,,f]=t,[m,g]=mf(n),[A,x]=mf(s),y=zu(p,A),b=zu(h,x),{padInfo:w,outHeight:k,outWidth:I}=q$(r,c,u,m,g,y,b,a,i),N=o?f*d:f,R;return i==="channelsFirst"?R=[l,N,k,I]:i==="channelsLast"&&(R=[l,k,I,N]),{batchSize:l,dataFormat:i,inHeight:c,inWidth:u,inChannels:d,outHeight:k,outWidth:I,outChannels:N,padInfo:w,strideHeight:m,strideWidth:g,filterHeight:p,filterWidth:h,effectiveFilterHeight:y,effectiveFilterWidth:b,dilationHeight:A,dilationWidth:x,inShape:e,outShape:R,filterShape:t}}function pv(e,t,n,s,r,a=!1,o="channelsLast",i){let[l,c,u,d,p]=[-1,-1,-1,-1,-1];if(o==="channelsLast")[l,c,u,d,p]=e;else if(o==="channelsFirst")[l,p,c,u,d]=e;else throw new Error(`Unknown dataFormat ${o}`);let[h,f,m,,g]=t,[A,x,y]=n1(n),[b,w,k]=n1(s),I=zu(h,b),N=zu(f,w),R=zu(m,k),{padInfo:O,outDepth:$,outHeight:P,outWidth:T}=X$(r,c,u,d,A,x,y,I,N,R,i),F=a?g*p:g,U;return o==="channelsFirst"?U=[l,F,$,P,T]:o==="channelsLast"&&(U=[l,$,P,T,F]),{batchSize:l,dataFormat:o,inDepth:c,inHeight:u,inWidth:d,inChannels:p,outDepth:$,outHeight:P,outWidth:T,outChannels:F,padInfo:O,strideDepth:A,strideHeight:x,strideWidth:y,filterDepth:h,filterHeight:f,filterWidth:m,effectiveFilterDepth:I,effectiveFilterHeight:N,effectiveFilterWidth:R,dilationDepth:b,dilationHeight:w,dilationWidth:k,inShape:e,outShape:U,filterShape:t}}function H$(e,t,n,s,r){s==null&&(s=t1(e,t,n));let a=e[0],o=e[1],i=cl((a-t+2*s)/n+1,r),l=cl((o-t+2*s)/n+1,r);return[i,l]}function j$(e,t,n,s,r,a){r==null&&(r=t1(e,t,s));let o=e[0],i=e[1],l=e[2],c=cl((o-t+2*r)/s+1,a),u=cl((i-t+2*r)/s+1,a),d=cl((l-t+2*r)/s+1,a);return[c,u,d,n]}function t1(e,t,n,s=1){let r=zu(t,s);return Math.floor((e[0]*(n-1)-n+r)/2)}function mf(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function n1(e){return typeof e=="number"?[e,e,e]:e}function zu(e,t){return t<=1?e:e+(e-1)*(t-1)}function q$(e,t,n,s,r,a,o,i,l){let c,u,d;if(typeof e=="number"){c={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let h=H$([t,n],a,s,e,i);u=h[0],d=h[1]}else if(e==="same"){u=Math.ceil(t/s),d=Math.ceil(n/r);let p=Math.max(0,(u-1)*s+a-t),h=Math.max(0,(d-1)*r+o-n),f=Math.floor(p/2),m=p-f,g=Math.floor(h/2),A=h-g;c={top:f,bottom:m,left:g,right:A,type:"SAME"}}else if(e==="valid")c={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((t-a+1)/s),d=Math.ceil((n-o+1)/r);else if(typeof e=="object"){let p=l==="channelsLast"?e[1][0]:e[2][0],h=l==="channelsLast"?e[1][1]:e[2][1],f=l==="channelsLast"?e[2][0]:e[3][0],m=l==="channelsLast"?e[2][1]:e[3][1];c={top:p,bottom:h,left:f,right:m,type:p===0&&h===0&&f===0&&m===0?"VALID":"EXPLICIT"},u=cl((t-a+p+h)/s+1,i),d=cl((n-o+f+m)/r+1,i)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:c,outHeight:u,outWidth:d}}function X$(e,t,n,s,r,a,o,i,l,c,u){let d,p,h,f;if(typeof e=="number"){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let g=j$([t,n,s,1],i,1,r,e,u);p=g[0],h=g[1],f=g[2]}else if(e==="same"){p=Math.ceil(t/r),h=Math.ceil(n/a),f=Math.ceil(s/o);let m=(p-1)*r+i-t,g=(h-1)*a+l-n,A=(f-1)*o+c-s,x=Math.floor(m/2),y=m-x,b=Math.floor(g/2),w=g-b,k=Math.floor(A/2),I=A-k;d={top:b,bottom:w,left:k,right:I,front:x,back:y,type:"SAME"}}else if(e==="valid")d={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-i+1)/r),h=Math.ceil((n-l+1)/a),f=Math.ceil((s-c+1)/o);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:d,outDepth:p,outHeight:h,outWidth:f}}function cl(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 $o(e){let[t,n,s]=mf(e);return t===1&&n===1&&s===1}function Pr(e,t){return $o(e)||$o(t)}function hv(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function K$(e,t){let s={x:D(e,"x","reshape","string_or_numeric")},r={shape:t};return W.runKernel(Li,s,r)}var H=V({reshape_:K$});function Z$(e,t,n,s,r){let a=D(e,"x","avgPool","float32"),o=1;M(Pr(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=H(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(fn(s),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r},d=W.runKernel(_a,c,u);return d=me(d,a.dtype),l?H(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var gf=V({avgPool_:Z$});function Y$(e,t,n,s,r,a="NDHWC"){let o=D(e,"x","avgPool3d","float32"),i=o,l=!1;o.rank===4&&(l=!0,i=H(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(fn(s),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},d=W.runKernel(od,c,u);return d=me(d,i.dtype),l?H(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var s1=V({avgPool3d_:Y$});function J$(e,t=0){M(e.length>=1,()=>"Pass at least one tensor to concat");let n=Rd(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 Wn(n[0]);let s=n,r={axis:t};return W.runKernel(gi,s,r)}var wt=V({concat_:J$});function Q$(e){let n={x:D(e,"x","sigmoid","float32")};return W.runKernel(ho,n)}var ms=V({sigmoid_:Q$});function e_(e,t,n){let s=D(e,"x","slice","string_or_numeric");if(s.rank===0)throw new Error("Slicing scalar is not possible");let r={x:s},a={begin:t,size:n};return W.runKernel(Gi,r,a)}var Pe=V({slice_:e_});function t_(e){let n={x:D(e,"x","tanh","float32")};return W.runKernel(xo,n)}var Lu=V({tanh_:t_});function n_(e,t,n,s,r,a){let o=D(e,"forgetBias","basicLSTMCell"),i=D(t,"lstmKernel","basicLSTMCell"),l=D(n,"lstmBias","basicLSTMCell"),c=D(s,"data","basicLSTMCell"),u=D(r,"c","basicLSTMCell"),d=D(a,"h","basicLSTMCell"),p=wt([c,d],1),h=He(p,i),f=ue(h,l),m=f.shape[0],g=f.shape[1]/4,A=[m,g],x=Pe(f,[0,0],A),y=Pe(f,[0,g],A),b=Pe(f,[0,g*2],A),w=Pe(f,[0,g*3],A),k=ue(L(ms(x),Lu(y)),L(u,ms(ue(o,b)))),I=L(Lu(k),ms(w));return[k,I]}var s_=V({basicLSTMCell_:n_});function r_(e,t,n){let s=D(e,"x","batchToSpaceND"),r=t.reduce((i,l)=>i*l);M(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),M(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),M(s.shape[0]%r==0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`);let a={x:s},o={blockShape:t,crops:n};return W.runKernel(mi,a,o)}var Af=V({batchToSpaceND_:r_});function a_(e){let t;return e.rank===0||e.rank===1?t=H(e,[1,1,1,e.size]):e.rank===2?t=H(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=H(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function o_(e,t,n,s,r,a){a==null&&(a=.001);let o=D(e,"x","batchNorm"),i=D(t,"mean","batchNorm"),l=D(n,"variance","batchNorm"),c;r!=null&&(c=D(r,"scale","batchNorm"));let u;s!=null&&(u=D(s,"offset","batchNorm")),M(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),M(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),M(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let p={x:a_(o),scale:c,offset:u,mean:i,variance:l},h={varianceEpsilon:a},f=W.runKernel(ja,p,h);return H(f,o.shape)}var Bu=V({batchNorm_:o_});function i_(e,t,n,s,r,a){let o=D(e,"x","batchNorm"),i=D(t,"mean","batchNorm"),l=D(n,"variance","batchNorm"),c;r!=null&&(c=D(r,"scale","batchNorm"));let u;return s!=null&&(u=D(s,"offset","batchNorm")),M(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),M(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),M(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),c!=null&&M(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),u!=null&&M(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`),Bu(o,i,l,u,c,a)}var fv=V({batchNorm2d_:i_});function l_(e,t,n,s,r,a){let o=D(e,"x","batchNorm"),i=D(t,"mean","batchNorm"),l=D(n,"variance","batchNorm"),c;r!=null&&(c=D(r,"scale","batchNorm"));let u;return s!=null&&(u=D(s,"offset","batchNorm")),M(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),M(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),M(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),c!=null&&M(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`),u!=null&&M(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`),Bu(o,i,l,u,c,a)}var mv=V({batchNorm3d_:l_});function u_(e,t,n,s,r,a){let o=D(e,"x","batchNorm"),i=D(t,"mean","batchNorm"),l=D(n,"variance","batchNorm"),c;r!=null&&(c=D(r,"scale","batchNorm"));let u;return s!=null&&(u=D(s,"offset","batchNorm")),M(o.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),M(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),M(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),c!=null&&M(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`),u!=null&&M(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`),Bu(o,i,l,u,c,a)}var gv=V({batchNorm4d_:u_});function c_(e,t,n){let s=D(e,"x","bincount"),r=D(t,"weights","bincount");M(s.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`),M(n>=0,()=>`size must be non-negative, but got ${n}.`),M(r.size===s.size||r.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${r.shape}.`);let a={x:s,weights:r},o={size:n};return W.runKernel(Ch,a,o)}var r1=V({bincount_:c_});function d_(e,t){let n=D(e,"s0","broadcastArgs","int32"),s=D(t,"s1","broadcastArgs","int32");if(n.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(s.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${s.rank}`);let r={s0:n,s1:s};return W.runKernel(Th,r)}var Av=V({broadcastArgs_:d_});function p_(e,t){let n=D(e,"broadcastTo","x"),s=n.shape;if(t.some(c=>!(c>0)||c%1!=0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.lengthn.rank){let c=n.shape.slice();for(;c.length=0;c--)if(r[c]===t[c])a[c]=1;else if(n.shape[c]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);if(a.map((c,u)=>c>1?u:-1).filter(c=>c>=0).length===0)return Wn(n);let i={x:n},l={reps:a};return W.runKernel(Yr,i,l)}var Pd=V({broadcastTo_:p_});function h_(e){let n={x:D(e,"x","ceil","float32")};return W.runKernel(Fa,n)}var yv=V({ceil_:h_});function f_(e,t,n){let s=D(e,"x","clipByValue");M(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);let r={x:s},a={clipValueMin:t,clipValueMax:n};return W.runKernel(Zr,r,a)}var gs=V({clipByValue_:f_});function m_(e){return wt(e,0)}var xv=V({concat1d_:m_});function g_(e,t){return wt(e,t)}var Wu=V({concat2d_:g_});function A_(e,t){return wt(e,t)}var bv=V({concat3d_:A_});function y_(e,t){return wt(e,t)}var vv=V({concat4d_:y_});function x_(e,t,n,s,r="NHWC",a=[1,1],o){let i=D(e,"x","conv2d","float32"),l=D(t,"filter","conv2d","float32"),c=i,u=!1;i.rank===3&&(u=!0,c=H(i,[1,i.shape[0],i.shape[1],i.shape[2]])),M(c.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`),M(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),o!=null&&M(fn(s),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let d=r==="NHWC"?c.shape[3]:c.shape[1];M(d===l.shape[2],()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${l.shape[2]}.`),M(Pr(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let p={x:c,filter:l},h={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},f=W.runKernel(Oa,p,h);return u?H(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var _o=V({conv2d_:x_});function b_(e,t,n,s,r="NWC",a=1,o){let i=D(e,"x","conv1d"),l=D(t,"filter","conv1d"),c=i,u=!1;i.rank===2&&(u=!0,c=H(i,[1,i.shape[0],i.shape[1]])),M(c.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`),M(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),o!=null&&M(fn(s),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`),M(c.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`),M(Pr(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=H(l,[1,l.shape[0],l.shape[1],l.shape[2]]),p=H(c,[c.shape[0],1,c.shape[1],c.shape[2]]),g=_o(p,d,[1,n],s,"NHWC",[1,a],o);return u?H(g,[g.shape[2],g.shape[3]]):H(g,[g.shape[0],g.shape[2],g.shape[3]])}var a1=V({conv1d_:b_});function v_(e,t,n,s,r,a="NHWC",o){M(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let i=e,l=t,c=!1;t.rank===3&&(c=!0,l=H(t,[1,t.shape[0],t.shape[1],t.shape[2]]),i=[1,e[0],e[1],e[2]]),M(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),M(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),M(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);let u=a==="NHWC"?i[3]:i[1],d=a==="NHWC"?l.shape[3]:l.shape[1];M(u===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[2]}.`),M(d===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${n.shape[3]}.`),o!=null&&M(fn(r),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let p={dy:l,filter:n},h={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,inputShape:i},f=W.runKernel(Ma,p,h);return c?H(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var o1=V({conv2DBackpropInput_:v_});function w_(e,t,n,s,r,a){let o=D(e,"x","conv2dTranspose"),i=D(t,"filter","conv2dTranspose");return o1(n,o,i,s,r,"NHWC",a)}var i1=V({conv2dTranspose_:w_});function k_(e,t,n,s,r="NDHWC",a=[1,1,1]){let o=D(e,"x","conv3d"),i=D(t,"filter","conv3d"),l=o,c=!1;o.rank===4&&(c=!0,l=H(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(Pr(n,a),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),M(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`);let u={x:l,filter:i},d={strides:n,pad:s,dataFormat:r,dilations:a},p=W.runKernel(ud,u,d);return c?H(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var l1=V({conv3d_:k_});function S_(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=H(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),a=[1,e[0],e[1],e[2],e[3]]);let l=a[4],c=o.shape[4];M(a.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`),M(o.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),M(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),M(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),M(c===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[4]}.`);let u={dy:o,filter:n},d={pad:r,strides:s,inputShape:a},p=W.runKernel(Rh,u,d);return i?H(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var wv=V({conv3DBackpropInput_:S_});function I_(e,t,n,s,r){let a=D(e,"x","conv3dTranspose"),o=D(t,"filter","conv3dTranspose");return wv(n,a,o,s,r)}var kv=V({conv3dTranspose_:I_});function C_(e){let n={x:D(e,"x","cos","float32")};return W.runKernel(za,n)}var yf=V({cos_:C_});function T_(e){let n={x:D(e,"x","cosh","float32")};return W.runKernel(La,n)}var u1=V({cosh_:T_});function N_(e,t=0,n=!1,s=!1){let a={x:D(e,"x","cumsum")},o={axis:t,exclusive:n,reverse:s};return W.runKernel(Ai,a,o)}var c1=V({cumsum_:N_});function E_(e,t,n,s=!1){let r=D(e,"x","denseBincount"),a=D(t,"weights","denseBincount");M(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),M(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),M(n>=0,()=>`size must be non-negative, but got ${n}.`),M(a.size===r.size||a.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${a.shape}.`);let o={x:r,weights:a},i={size:n,binaryOutput:s};return W.runKernel($h,o,i)}var Sv=V({denseBincount_:E_});function R_(e,t,n="NHWC"){let s=D(e,"x","depthToSpace","float32"),r=n==="NHWC"?s.shape[1]:s.shape[2],a=n==="NHWC"?s.shape[2]:s.shape[3],o=n==="NHWC"?s.shape[3]:s.shape[1];M(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),M(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying ${r} and ${t} for depthToSpace with input shape ${s.shape}`),M(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying ${a} and ${t} for depthToSpace with input shape ${s.shape}`),M(o%(t*t)==0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${s.shape}`);let i={x:s},l={blockSize:t,dataFormat:n};return W.runKernel(xi,i,l)}var Iv=V({depthToSpace_:R_});function $_(e,t,n,s,r="NHWC",a=[1,1],o){let i=D(e,"x","depthwiseConv2d","float32"),l=D(t,"filter","depthwiseConv2d","float32"),c=i,u=!1;i.rank===3&&(u=!0,c=H(i,[1,i.shape[0],i.shape[1],i.shape[2]])),M(c.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),M(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),M(c.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),o!=null&&M(fn(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`);let d={x:c,filter:l},p={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},h=W.runKernel(Ba,d,p);return u?H(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var Fd=V({depthwiseConv2d_:$_});function __(e){let n={x:D(e,"x","diag")};return W.runKernel(Ph,n)}var D_=V({diag_:__});function P_(e,t,n,s,r=[1,1],a="NHWC"){let o=D(e,"x","dilation2d"),i=D(t,"filter","dilation2d");M(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),M(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),M(a==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);let l=o,c=!1;o.rank===3&&(l=H(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=!0);let u={x:l,filter:i},d={strides:n,pad:s,dilations:r},p=W.runKernel(cd,u,d);return c?H(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Cv=V({dilation2d_:P_});function F_(e,t){let n=D(e,"a","equal","string_or_numeric"),s=D(t,"b","equal","string_or_numeric");[n,s]=Pt(n,s),gt(n.shape,s.shape);let r={a:n,b:s};return W.runKernel(bi,r)}var $s=V({equal_:F_});function O_(e,t,n){let s=D(t,"a","where"),r=D(n,"b","where"),a=D(e,"condition","where","bool"),o=gt(gt(a.shape,s.shape),r.shape),i=Pd(a,o),l=Pd(s,o),c=Pd(r,o),u={condition:i,t:l,e:c};return W.runKernel(Ui,u)}var Vn=V({where_:O_});function M_(e){let n={x:D(e,"x","zerosLike")};return W.runKernel(Qi,n)}var et=V({zerosLike_:M_});function z_(e,t){let n=D(e,"a","div"),s=D(t,"b","div");[n,s]=Pt(n,s);let r=ge(n,s),a=et(r),o=$s(s,a);return Vn(o,a,r)}var Tv=V({divNoNan_:z_});function L_(e,t){let n=D(e,"t1","dot"),s=D(t,"t2","dot");M((n.rank===1||n.rank===2)&&(s.rank===1||s.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${s.rank}.`);let r=n.rank===1?n.size:n.shape[1],a=s.rank===1?s.size:s.shape[0];if(M(r===a,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${a}.`),n.rank===1&&s.rank===1){let o=H(n,[1,-1]),i=H(s,[-1,1]),l=He(o,i);return H(l,[])}else if(n.rank===1&&s.rank===2){let o=H(n,[1,-1]),i=H(s,[s.shape[0],s.shape[1]]),l=He(o,i);return H(l,[l.size])}else if(n.rank===2&&s.rank===1){let o=H(s,[-1,1]),i=He(n,o);return H(i,[i.size])}else{let o=H(s,[s.shape[0],s.shape[1]]);return He(n,o)}}var B_=V({dot_:L_});function W_(e,...t){let n=t.map((r,a)=>D(r,`tensors${a}`,"einsum")),s={equation:e};return W.runKernel(dd,n,s)}var Nv=V({einsum_:W_});function V_(e){let n={x:D(e,"x","elu","float32")};return W.runKernel(Va,n)}var Od=V({elu_:V_});function U_(e){let t=D(e,"x","erf");M(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=me(t,"float32"));let n={x:t};return W.runKernel(Au,n)}var Ev=V({erf_:U_});function G_(e){let n={x:D(e,"x","exp")};return W.runKernel(Ua,n)}var _s=V({exp_:G_});function H_(e,t=0){let n=D(e,"x","expandDims","string_or_numeric");M(t<=n.rank,()=>"Axis must be <= rank of the tensor");let s={input:n},r={dim:t};return W.runKernel(vi,s,r)}var Kt=V({expandDims_:H_});function j_(e){let n={x:D(e,"x","expm1")};return W.runKernel(wi,n)}var Rv=V({expm1_:j_});function q_(e,t){let n=D(e,"x","tile","string_or_numeric");M(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);let s={x:n},r={reps:t};return W.runKernel(Yr,s,r)}var Ys=V({tile_:q_});function X_(e,t,n,s="float32"){t==null&&(t=e);let r=ze([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(fn(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=a,i=!1;a.rank===3&&(i=!0,o=H(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let l={x:o},c={depthRadius:t,bias:n,alpha:s,beta:r},u=W.runKernel(fd,l,c);return i?H(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var Dv=V({localResponseNormalization_:lD});function uD(e){let n={x:D(e,"x","log","float32")};return W.runKernel(Ka,n)}var Ds=V({log_:uD});function cD(e){let n={x:D(e,"x","log1p")};return W.runKernel(wu,n)}var vf=V({log1p_:cD});function dD(e){return M(Ea(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let s=D(t,"x","tf.grad","string_or_numeric"),r=n!=null?D(n,"dy","tf.grad"):null;return W.tidy(()=>{let{value:a,grads:o}=W.gradients(()=>e(s),[s],r);return r!=null&&zn(a.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),wf(o),o[0]})}}function pD(e){return M(Ea(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=Rd(t,"args","tf.grads","string_or_numeric"),r=n!=null?D(n,"dy","tf.grads"):null;return W.tidy(()=>{let{value:a,grads:o}=W.gradients(()=>e(...s),s,r);return r!=null&&zn(a.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),wf(o),o})}}function hD(e){return M(Ea(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{M(t instanceof Je,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),M(n==null||n instanceof Je,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:s,value:r}=W.gradients(()=>e(t),[t],n);return wf(s),{grad:s[0],value:r}}}function fD(e){return M(Ea(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{M(Array.isArray(t)&&t.every(r=>r instanceof Je),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),M(n==null||n instanceof Je,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let s=W.gradients(()=>e(...t),t,n);return n!=null&&zn(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),wf(s.grads),s}}function Pv(e,t){M(Ea(e),()=>"The f passed in variableGrads(f) must be a function"),M(t==null||Array.isArray(t)&&t.every(c=>c instanceof Nd),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let c in W.registeredVariables)t.push(W.registeredVariables[c])}let s=n?t.filter(c=>!c.trainable):null,r=t.length;t=t.filter(c=>c.trainable),M(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);let a=!0,{value:o,grads:i}=W.gradients(e,t,null,a);M(i.some(c=>c!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),M(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);let l={};return t.forEach((c,u)=>{i[u]!=null&&(l[c.name]=i[u])}),s!=null&&s.forEach(c=>l[c.name]=null),{value:o,grads:l}}function Fr(e){return W.customGrad(e)}function wf(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 mD(e){let n={x:D(e,"x","neg")};return W.runKernel($i,n)}var Ot=V({neg_:mD});function gD(e){let n={x:D(e,"x","softplus")};return W.runKernel($u,n)}var Gu=V({softplus_:gD});function AD(e){let t=D(e,"x","logSigmoid");return Fr(s=>({value:Ot(Gu(Ot(s))),gradFunc:o=>L(o,ms(Ot(s)))}))(t)}var yD=V({logSigmoid_:AD});function xD(e,t=null,n=!1){let r={x:D(e,"x","max")},a={reductionIndices:t,keepDims:n};return W.runKernel(Za,r,a)}var An=V({max_:xD});function bD(e,t){let n=D(e,"a","sub"),s=D(t,"b","sub");[n,s]=Pt(n,s);let r={a:n,b:s};return W.runKernel(yo,r)}var fe=V({sub_:bD});function vD(e,t=null,n=!1){let s=D(e,"x","sum");s.dtype==="bool"&&(s=me(s,"int32"));let r={x:s},a={axis:t,keepDims:n};return W.runKernel(mo,r,a)}var ke=V({sum_:vD});function wD(e,t=-1){let n=D(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return Fr((r,a)=>{let o=!0,i=An(r,t,!0),l=fe(r,i),c=fe(me(l,"float32"),Ds(ke(_s(l),t,o)));return a([c]),{value:c,gradFunc:(d,p)=>{let[h]=p,f=!0,m=_s(h);return fe(d,L(ke(d,t,f),m))}}})(n)}var h1=V({logSoftmax_:wD});function f1(e,t){for(let n=0;ne[a]);return[n,r]}function hl(e,t){let n=t.map(s=>1);return Fv(e,n,t)}function kD(e,t,n){M(f1(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function Mv(e,t){if(f1(e,t))return null;let n=[];for(let s=0;sn.push(s)),n}function m1(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function SD(e,t){let n=[];for(let s=t-e;s`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),M(Pr(n,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),r!=null&&M(fn(s),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r},d=W.runKernel(Ja,c,u);return l?H(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Sf=V({maxPool_:$D});function _D(e,t=[1,1,1],n,s,r,a="NDHWC"){let o=D(e,"x","maxPool3d"),i=o,l=!1;o.rank===4&&(l=!0,i=H(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(fn(s),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${s}.`);let c={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},d=W.runKernel(md,c,u);return l?H(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var A1=V({maxPool3d_:_D});function DD(e,t,n,s,r=!1){let o={x:D(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:s,includeBatchInIndex:r},l=W.runKernel(Gh,o,i);return{result:l[0],indexes:l[1]}}var Lv=V({maxPoolWithArgmax_:DD});function PD(e,t){let n=D(e,"a","maximum"),s=D(t,"b","maximum");[n,s]=Pt(n,s),n.dtype==="bool"&&(n=me(n,"int32"),s=me(s,"int32")),gt(n.shape,s.shape);let r={a:n,b:s};return W.runKernel(Ya,r)}var ea=V({maximum_:PD});function FD(e,t=null,n=!1){let r={x:D(e,"x","mean")},a={axis:t,keepDims:n};return W.runKernel(Qa,r,a)}var Wt=V({mean_:FD});function Ht(e,t="float32"){if(t==="complex64"){let s=Ht(e,"float32"),r=Ht(e,"float32");return To(s,r)}let n=kh(Gt(e),t);return W.makeTensor(n,e,t)}function ys(e,t="float32"){if(t==="complex64"){let s=ys(e,"float32"),r=Ht(e,"float32");return To(s,r)}let n=p2(Gt(e),t);return W.makeTensor(n,e,t)}function OD(e,t,{indexing:n="xy"}={}){if(n!=="xy"&&n!=="ij")throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(e===void 0)return[];let s=D(e,"x","meshgrid",e instanceof Je?e.dtype:"float32");if(t===void 0)return[s];let r=D(t,"y","meshgrid",t instanceof Je?t.dtype:"float32"),a=Gt(s.shape),o=Gt(r.shape);return n==="xy"?(s=H(s,[1,-1]),r=H(r,[-1,1]),[He(ys([o,1],s.dtype),s),He(r,ys([1,a],r.dtype))]):(s=H(s,[-1,1]),r=H(r,[1,-1]),[He(s,ys([1,o],s.dtype)),He(ys([a,1],r.dtype),r)])}function MD(e,t=null,n=!1){let r={x:D(e,"x","min")},a={axis:t,keepDims:n};return W.runKernel(eo,r,a)}var Do=V({min_:MD});function zD(e,t){let n=D(e,"a","minimum"),s=D(t,"b","minimum");[n,s]=Pt(n,s),n.dtype==="bool"&&(n=me(n,"int32"),s=me(s,"int32")),gt(n.shape,s.shape);let r={a:n,b:s};return W.runKernel(to,r)}var zd=V({minimum_:zD});function LD(e,t,n){M(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let s=D(e,"x","mirrorPad");if(s.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");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 W.runKernel(no,o,a)}var Bv=V({mirrorPad_:LD});function BD(e,t){let n=D(e,"a","mod"),s=D(t,"b","mod");[n,s]=Pt(n,s);let r={a:n,b:s};return W.runKernel(Su,r)}var Ld=V({mod_:BD});function WD(e){let t=D(e,"x","square"),n={};return W.runKernel("Square",{x:t},n)}var At=V({square_:WD});function VD(e,t=null,n=!1){e=D(e,"x","moments");let s=Xs(t,e.shape),r=Wt(e,s,n),a=r.shape;n||(a=hl(r.shape,s));let o=At(fe(me(e,"float32"),H(r,a))),i=Wt(o,s,n);return{mean:r,variance:i}}var If=V({moments_:VD});function UD(e,t,n,s){let r=D(t,"data","multiRNNCell"),a=Rd(n,"c","multiRNNCell"),o=Rd(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?H(r,[1,-1]):r},c={numSamples:t,seed:n,normalized:s},u=W.runKernel(Hh,l,c);return o===1?H(u,[u.size]):u}var Wv=V({multinomial_:HD});function jD(e,t){let n=D(e,"a","notEqual","string_or_numeric"),s=D(t,"b","notEqual","string_or_numeric");[n,s]=Pt(n,s),gt(n.shape,s.shape);let r={a:n,b:s};return W.runKernel(_i,r)}var Hu=V({notEqual_:jD});function qD(e){let n={x:D(e,"x","onesLike")};return W.runKernel(Fi,n)}var Ps=V({onesLike_:qD});function XD(e,t){let n=D(e,"v1","outerProduct"),s=D(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=H(n,[-1,1]),a=H(s,[1,-1]);return He(r,a)}var KD=V({outerProduct_:XD});function ZD(e,t,n=0){let s=D(e,"x","pad");if(s.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let r={paddings:t,constantValue:n},a={x:s};return W.runKernel(ro,a,r)}var Js=V({pad_:ZD});function YD(e,t,n=0){return M(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),Js(e,[t],n)}var JD=V({pad1d_:YD});function QD(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."),Js(e,t,n)}var eP=V({pad2d_:QD});function tP(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."),Js(e,t,n)}var nP=V({pad3d_:tP});function sP(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."),Js(e,t,n)}var rP=V({pad4d_:sP});function aP(e,t,n){let s=D(e,"x","spaceToBatchND");M(s.rank>=1+t.length,()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`),M(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),M(s.shape.reduce((o,i,l)=>l>0&&l<=t.length?o&&(i+n[l-1][0]+n[l-1][1])%t[l-1]==0:o,!0),()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);let r={x:s},a={blockShape:t,paddings:n};return W.runKernel(ji,r,a)}var Cf=V({spaceToBatchND_:aP});function oP(e,t,n,s,r,a){r==null&&(r=[1,1]),a==null&&(a=1),s===0&&(s="valid");let o=D(e,"x","maxPool"),i=o,l=!1;o.rank===3&&(l=!0,i=H(o,[1,o.shape[0],o.shape[1],o.shape[2]])),M(Pr(a,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${r}'`);let c=dv(i.shape,t,a,r,s),u=[c.dilationHeight,c.dilationWidth],d;s==="same"?d=lP([c.filterHeight,c.filterWidth],u):d=[[0,0],[0,0]];let p=u[0]===1&&u[1]===1,[h,f]=iP([c.inHeight,c.inWidth],u,d),m=p?s:"valid",g=p?i:Cf(i,u,h),x=(n==="avg"?()=>gf(g,t,a,m):()=>Sf(g,t,a,m))(),y=p?x:Af(x,u,f);return l?H(y,[y.shape[1],y.shape[2],y.shape[3]]):y}function iP(e,t,n){let s=n.map(u=>u[0]),r=n.map(u=>u[1]),a=e.concat(s,r),o=t.map((u,d)=>(u-a[d]%u)%u),i=r.map((u,d)=>u+o[d]),l=t.map((u,d)=>[s[d],i[d]]),c=t.map((u,d)=>[0,o[d]]);return[l,c]}function lP(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 uP=V({pool_:oP});function cP(e,t){let n=D(e,"base","pow"),s=D(t,"exp","pow");[n,s]=Pt(n,s);let r={a:n,b:s};return W.runKernel(ao,r)}var Po=V({pow_:cP});function dP(e,t){let n=D(e,"x","prelu"),s=D(t,"alpha","prelu"),r={x:n,alpha:s};return W.runKernel(oo,r)}var Tf=V({prelu_:dP});function pP(e,t=null,n=!1){let s=D(e,"x","prod");s.dtype==="bool"&&(s=me(s,"int32"));let r={x:s},a={axis:t,keepDims:n};return W.runKernel(zi,r,a)}var y1=V({prod_:pP});function hP(e,t,n){let s=Gt(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}},mP=class{constructor(e,t,n,s){this.alpha=e,this.beta=1/t,this.dtype=n;let r=s||Math.random();this.randu=x1.alea(r.toString()),this.randn=new b1(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=x1.alea(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function AP(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 mP(t,n,s,r),o=ze(e,s);for(let i=0;i`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Fs(t,0)}var TP=V({reverse1d_:CP});function NP(e,t){let n=D(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 EP=V({reverse2d_:NP});function RP(e,t){let n=D(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 $P=V({reverse3d_:RP});function _P(e,t){let n=D(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 DP=V({reverse4d_:_P});function PP(e){let n={x:D(e,"x","round")};return W.runKernel(Wi,n)}var w1=V({round_:PP});function FP(e){let n={x:D(e,"x","rsqrt","float32")};return W.runKernel(co,n)}var k1=V({rsqrt_:FP});function Ie(e,t){if((_n(e)&&t!=="string"||Array.isArray(e))&&t!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(t==="string"&&_n(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return No(e,[],[],t)}function OP(e){let n={x:D(e,"x","selu")};return W.runKernel(Eu,n)}var S1=V({selu_:OP});function MP(e,t,n,s,r,a=[1,1],o="NHWC"){let i=D(e,"x","separableConv2d"),l=D(t,"depthwiseFilter","separableConv2d"),c=D(n,"pointwiseFilter","separableConv2d"),u=i,d=!1;if(i.rank===3&&(d=!0,u=H(i,[1,i.shape[0],i.shape[1],i.shape[2]])),o==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");M(u.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`),M(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),M(c.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),M(c.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`),M(c.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`);let p=l.shape[2],h=l.shape[3];M(c.shape[2]===p*h,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*h}, but got ${c.shape[2]}.`);let f=Fd(u,l,s,r,o,a),g=_o(f,c,1,"valid",o);return d?H(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var Gv=V({separableConv2d_:MP});async function zP(e,t){let n=D(e,"x","setdiff1d"),s=D(t,"y","setdiff1d");M(n.dtype===s.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`),M(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),M(s.rank===1,()=>`y should be 1D tensor, but got y (${s.shape}).`);let r=await n.data(),a=await s.data(),o=new Set(a),i=0;for(let u=0;u`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),Pe(s,[t],[n])}var Nf=V({slice1d_:VP});function UP(e,t,n){let s=D(e,"x","slice2d");return M(s.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),Pe(s,t,n)}var T1=V({slice2d_:UP});function GP(e,t,n){let s=D(e,"x","slice3d");return M(s.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),Pe(s,t,n)}var fl=V({slice3d_:GP});function HP(e,t,n){let s=D(e,"x","slice4d");return M(s.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),Pe(s,t,n)}var ml=V({slice4d_:HP});function jP(e,t=-1){let n=D(e,"logits","softmax","float32");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);let s={logits:n},r={dim:t};return W.runKernel(go,s,r)}var Xu=V({softmax_:jP});function qP(e){M(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return W.runKernel(zh,t)}var Ef=V({fft_:qP});function XP(e){M(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return W.runKernel(Lh,t)}var Wd=V({ifft_:XP});function KP(e){let t=e.shape[e.shape.length-1],n=e.size/t,s;if(t<=2){let r=H(e,[n,t]);s=Wd(r)}else{let r=[n,2*(t-1)],a=H(Bd(e),[n,t]),o=H(xf(e),[n,t]),i=Fs(Pe(a,[0,1],[n,t-2]),1),l=L(Fs(Pe(o,[0,1],[n,t-2]),1),Ie(-1)),c=wt([a,i],1),u=wt([o,l],1),d=H(To(c,u),[r[0],r[1]]);s=Wd(d)}if(s=Bd(s),e.rank===3&&e.shape[0]!==0){let r=s,a=e.shape[0];s=H(s,[a,s.shape[0]/a,s.shape[1]]),r.dispose()}return s}var N1=V({irfft_:KP});function ZP(e,t,n=0){let r={x:D(e,"x","split")},a={numOrSizeSplits:t,axis:n};return W.runKernel(qi,r,a)}var sn=V({split_:ZP});function YP(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=Pe(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=wt([e,Ht(f)],e.shape.length-1),n=t}else r=e;let a=et(r),o=H(To(r,a),[s,n]),i=Ef(o),l=Math.floor(n/2)+1,c=Bd(i),u=xf(i),d=sn(c,[l,n-l],c.shape.length-1),p=sn(u,[l,n-l],u.shape.length-1),h=r.shape.slice();return h[r.shape.length-1]=l,H(To(d[0],p[0]),h)}var Rf=V({rfft_:YP});function JP(e){let n={x:D(e,"x","sqrt","float32")};return W.runKernel(fo,n)}var Dn=V({sqrt_:JP});function QP(e,t){let n=D(e,"a","squaredDifference"),s=D(t,"b","squaredDifference");[n,s]=Pt(n,s),gt(n.shape,s.shape);let r={a:n,b:s},a={};return W.runKernel(Ao,r,a)}var E1=V({squaredDifference_:QP});function eF(e,t){let n=D(e,"x","squeeze");return H(n,U5(n.shape,t).newShape)}var ot=V({squeeze_:eF});function tF(e,t=0){let n=Rd(e,"tensors","stack","string_or_numeric");M(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&M(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let s=n,r={axis:t};return W.runKernel(Mi,s,r)}var yn=V({stack_:tF});function nF(e,t=0){let s={x:D(e,"x","step")},r={alpha:t};return W.runKernel(vo,s,r)}var Vd=V({step_:nF});function sF(e,t,n,s,r=0,a=0,o=0,i=0,l=0){let u={x:D(e,"x","stridedSlice","string_or_numeric")},d={begin:t,end:n,strides:s,beginMask:r,endMask:a,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:l};return W.runKernel(Xi,u,d)}var qv=V({stridedSlice_:sF});function rF(e){let n={x:D(e,"x","tan","float32")};return W.runKernel(Ki,n)}var Xv=V({tan_:rF});function Vt(e,t){pi(e);let n=_r(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return No(e,null,n,t)}function fr(e,t,n){if(pi(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let s=_r(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 No(e,t,s,n)}function aF(e,t,n){if(pi(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let s=_r(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 No(e,t,s,n)}function oF(e,t,n){if(pi(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let s=_r(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 No(e,t,s,n)}function iF(e,t,n){if(pi(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let s=_r(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,No(e,t,s,n)}function lF(e,t=1,n=!0){let s=D(e,"x","topk");if(s.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let r=s.shape[s.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);let a={x:s},o={k:t,sorted:n},[i,l]=W.runKernel(Zi,a,o);return{values:i,indices:l}}var Kv=V({topk_:lF});function uF(e,t=0,n=1,s,r){if(s!=null&&s==="bool")throw new Error("Unsupported data type $ { dtype }");let a=new b1(t,n,s,!0,r),o=ze(e,s);for(let i=0;i0,()=>"The input tensor must be at least 1D");let s={x:n},r={axis:t},[a,o]=W.runKernel(ef,s,r);return{values:a,indices:o}}var R1=V({unique_:cF});function dF(e,t,n){let s=D(e,"x","unsortedSegmentSum"),r=D(t,"segmentIds","unsortedSegmentSum","int32");M(fn(n),()=>"numSegments must be of dtype int");let a={x:s,segmentIds:r},o={numSegments:n};return W.runKernel(xd,a,o)}var Zv=V({unsortedSegmentSum_:dF});function pF(e,t=0){let n=D(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 W.runKernel(Ji,s,r)}var os=V({unstack_:pF});function Yv(e,t=!0,n,s){return W.makeVariable(e,t,n,s)}function Jv(e,t){let n=[];for(let a=0;a0,()=>"mask cannot be scalar"),zn(i.slice(a,a+o),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let m=a;m"Shape mismatch in v and x");let l=Ie(1),c=fe(l,i),u=L(fe(o,a),c);if(r){M(s!=null,()=>"When using zeroDebias: true, step is required.");let d=D(s,"step","movingAverage");u=ge(u,fe(l,Po(i,d)))}return ue(a,u)}var yF=V({movingAverage_:AF});function xF(e,t,n){let s=D(e,"indices","scatterND","int32"),r=D(t,"updates","scatterND");q2(r,s,n);let a={indices:s,updates:r},o={shape:n};return W.runKernel(Vi,a,o)}var ew=V({scatterND_:xF});function bF(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 vF(e,t,n,s=0){let r=D(e,"sparseIndices","sparseToDense","int32"),a=D(t,"sparseValues","sparseToDense"),o=D(s,"defaultValue","sparseToDense",a.dtype);bF(r,a,n,o);let i={sparseIndices:r,sparseValues:a,defaultValue:o},l={outputShape:n};return W.runKernel(Ad,i,l)}var D1=V({sparseToDense_:vF});function wF(e,t){let n=D(t,"indices","gatherND","int32"),r={params:D(e,"x","gatherND","string_or_numeric"),indices:n};return W.runKernel(Ii,r)}var tw=V({gatherND_:wF});function kF(e,t){if(t==null)return e.shape.slice();if(Ta(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 Je?r.clone():r;let a=kF(r,n),o=1-t,i=ge(Md(ue(ju(a,0,1,"float32",s),o)),o);return L(r,i)}var nw=V({dropout_:SF});function sw(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function P1(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}`),zn(s.shape.slice(0,s.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let a=s.shape[s.shape.length-1];M(n>0&&n<=a,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`);let o=await s.data(),i=await r.data(),[l,c]=[o.length/a,a],u=G5("bool",l);for(let d=0;dg.value-m.value),u[d]=0;for(let m=0;mEF,depthwiseConv2d:()=>DF,matMul:()=>FF});function TF(e,t,n,s,r,a="NHWC",o){let i=e;e.rank===3&&(i=H(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=H(t,[1,t.shape[0],t.shape[1],t.shape[2]])),M(i.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),M(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),M(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);let c=a==="NHWC"?i.shape[3]:i.shape[1],u=a==="NHWC"?l.shape[3]:l.shape[1];M(c===n[2],()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${n[2]}.`),M(u===n[3],()=>`Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${n[3]}).`),o!=null&&M(fn(r),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);let d={x:i,dy:l},p={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,filterShape:n};return W.runKernel(Nh,d,p)}var F1=V({conv2DBackpropFilter_:TF});function _f(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return L(e,Vd(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Df(e,t){let n=t,s=Xt(e.shape,t.shape);return s.length>0&&(n=ke(n,s)),H(n,e.shape)}function Pf(e,t,n,s){if(t==="linear")return e;if(t==="relu")return Or(e);if(t==="elu")return Od(e);if(t==="relu6")return v1(e);if(t==="prelu")return Tf(e,n);if(t==="leakyrelu")return bf(e,s);if(t==="sigmoid")return ms(e);throw new Error(`Unknown fused activation ${t}.`)}var Ff=(e,t)=>!(e>0)||t==="linear";function NF({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(l=l||"linear",Ff(W.state.gradientDepth,l)===!1){let w=_o(e,t,n,s,r,a,o);return i!=null&&(w=ue(w,i)),Pf(w,l,c,u)}let d=D(e,"x","conv2d","float32"),p=D(t,"filter","conv2d","float32"),h=d,f=!1;d.rank===3&&(f=!0,h=H(d,[1,d.shape[0],d.shape[1],d.shape[2]])),M(h.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`),M(p.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`),o!=null&&M(fn(s),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${s}.`),M(h.shape[3]===p.shape[2],()=>`Error in conv2d: depth of input (${h.shape[3]}) must match input depth for filter ${p.shape[2]}.`),M(Pr(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=Dd(h.shape,p.shape,n,a,s,o),g;i!=null&&(g=D(i,"bias","fused conv2d"),[g]=Pt(g,d),gt(m.outShape,g.shape));let A;c!=null&&(A=D(c,"prelu weights","fused conv2d"));let x=(w,k)=>{let[I,N,R,O]=k,$=_f(w,R,l);M($o(a),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);let P=o1(N.shape,$,I,n,s),T=F1(N,$,I.shape,n,s),F=[P,T];if(O!=null){let U=Df(O,$);F.push(U)}return F},y={x:h,filter:p,bias:g,preluActivationWeights:A},b={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:u};return i==null?Fr((k,I,N)=>{let R=W.runKernel(ko,y,b);return N([I,k,R]),f&&(R=H(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:x}})(h,p):Fr((k,I,N,R)=>{let O=W.runKernel(ko,y,b);return R([I,k,O,N]),f&&(O=H(O,[O.shape[1],O.shape[2],O.shape[3]])),{value:O,gradFunc:x}})(h,p,g)}var EF=V({fusedConv2d_:NF});function RF(e,t,n,s,r,a=[1,1],o){let i=e;e.rank===3&&(i=H(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=H(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let c={x:i,dy:l},u={strides:s,pad:r,dimRoundingMode:o,dilations:a,filterShape:n};return W.runKernel(_h,c,u)}var rw=V({depthwiseConv2dNativeBackpropFilter_:RF});function $F(e,t,n,s,r,a=[1,1],o){let i=t,l=!1;t.rank===3&&(l=!0,i=H(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let c={dy:i,filter:n},u={strides:s,pad:r,dimRoundingMode:o,dilations:a,inputShape:e},d=W.runKernel(Dh,c,u);return l?H(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var aw=V({depthwiseConv2dNativeBackpropInput_:$F});function _F({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(Ff(W.state.gradientDepth,l)===!1){let w=Fd(e,t,n,s,r,a,o);return i!=null&&(w=ue(w,i)),Pf(w,l,c,u)}let d=D(e,"x","depthwiseConv2d","float32"),p=D(t,"filter","depthwiseConv2d","float32"),h=d,f=!1;d.rank===3&&(f=!0,h=H(d,[1,d.shape[0],d.shape[1],d.shape[2]])),M(h.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`),M(p.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`),M(h.shape[3]===p.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),a==null&&(a=[1,1]),M(Pr(n,a),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o!=null&&M(fn(s),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${o} but got pad ${s}.`);let m=Dd(h.shape,p.shape,n,a,s,o,!0),g;i!=null&&(g=D(i,"bias","fused conv2d"),[g]=Pt(g,d),gt(m.outShape,g.shape));let A;c!=null&&(A=D(c,"prelu weights","fused depthwiseConv2d"));let x=(w,k)=>{M($o(a),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);let[I,N,R,O]=k,$=_f(w,R,l),P=aw(N.shape,$,I,n,s,a,o),T=rw(N,$,I.shape,n,s,a,o);if(O!=null){let F=Df(g,$);return[P,T,F]}return[P,T]},y={x:h,filter:p,bias:g,preluActivationWeights:A},b={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:u};return i==null?Fr((k,I,N)=>{let R=W.runKernel(So,y,b);return N([I,k,R]),f&&(R=H(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:x}})(h,p):Fr((k,I,N,R)=>{let O=W.runKernel(So,y,b);return R([I,k,O,N]),f&&(O=H(O,[O.shape[1],O.shape[2],O.shape[3]])),{value:O,gradFunc:x}})(h,p,g)}var DF=V({fusedDepthwiseConv2d_:_F});function PF({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:r,activation:a="linear",preluActivationWeights:o,leakyreluAlpha:i}){if(Ff(W.state.gradientDepth,a)===!1){let $=He(e,t,n,s);return r!=null&&($=ue($,r)),Pf($,a,o,i)}let l=D(e,"a","fused matMul"),c=D(t,"b","fused matMul");[l,c]=Pt(l,c);let u=n?l.shape[l.rank-2]:l.shape[l.rank-1],d=s?c.shape[c.rank-1]:c.shape[c.rank-2],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],h=s?c.shape[c.rank-2]:c.shape[c.rank-1],f=l.shape.slice(0,-2),m=c.shape.slice(0,-2),g=Gt(f),A=Gt(m);M(u===d,()=>`Error in fused matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${l.shape} and ${c.shape} and transposeA=${n} and transposeB=${s} must match.`);let y=gt(l.shape.slice(0,-2),c.shape.slice(0,-2)).concat([p,h]),b=n?H(l,[g,u,p]):H(l,[g,p,u]),w=s?H(c,[A,h,d]):H(c,[A,d,h]),k;r!=null&&(k=D(r,"bias","fused matMul"),[k]=Pt(k,l),gt(y,k.shape));let I;o!=null&&(I=D(o,"prelu weights","fused matMul"));let N=($,P)=>{let[T,F,U,q]=P,z=_f(H($,U.shape),U,a),K,J;if(!n&&!s?(K=He(z,F,!1,!0),J=He(T,z,!0,!1)):!n&&s?(K=He(z,F,!1,!1),J=He(z,T,!0,!1)):n&&!s?(K=He(F,z,!1,!0),J=He(T,z,!1,!1)):(K=He(F,z,!0,!0),J=He(z,T,!0,!0)),r!=null){let Q=Df(q,z);return[K,J,Q]}else return[K,J]},R={a:b,b:w,bias:k,preluActivationWeights:I},O={transposeA:n,transposeB:s,activation:a,leakyreluAlpha:i};return r==null?Fr((P,T,F)=>{let U=W.runKernel(wo,R,O);return F([P,T,U]),{value:H(U,y),gradFunc:N}})(b,w):Fr((P,T,F,U)=>{let q=W.runKernel(wo,R,O);return U([P,T,q,F]),{value:H(q,y),gradFunc:N}})(b,w,k)}var FF=V({fusedMatMul_:PF});function OF(e){return P1(e,.54,.46)}var MF=V({hammingWindow_:OF});function zF(e){return P1(e,.5,.5)}var ow=V({hannWindow_:zF});function LF(e,t,n,s=!1,r=0){let a=0,o=[];for(;a+t<=e.size;)o.push(Pe(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 [${c},4] but had shape ${i.shape}.`),M(l.rank===1&&l.shape[0]===c,()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${i.shape}.`),M(s.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),M(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),M(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);let u={image:o,boxes:i,boxInd:l},d={method:r,extrapolationValue:a,cropSize:s};return W.runKernel(yi,u,d)}var UF=V({cropAndResize_:VF});function GF(e){let t=D(e,"image","flipLeftRight","float32");M(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return W.runKernel(ki,n,{})}var HF=V({flipLeftRight_:GF});function jF(e){let t=D(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,Ys(t,r)}var qF=V({grayscaleToRGB_:jF});function XF(e,t,n=0,s=.5){let r=D(e,"image","rotateWithOffset","float32");M(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);let a={image:r},o={radians:t,fillValue:n,center:s};return W.runKernel(el,a,o)}var KF=V({rotateWithOffset_:XF});function Ku(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 ZF(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=D(e,"boxes","nonMaxSuppression","float32"),o=D(t,"scores","nonMaxSuppression","float32"),i=Ku(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l={maxOutputSize:n,iouThreshold:s,scoreThreshold:r};return W.runKernel(Di,{boxes:a,scores:o},l)}var YF=V({nonMaxSuppression_:ZF});function JF(e,t,n){let s=QF(e,t,n),r=s<0?-(s+1):s;e.splice(r,0,t)}function QF(e,t,n){return tO(e,t,n||eO)}function eO(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 lw(e,t,n,s,r){return O1(e,t,n,s,r,0)}function uw(e,t,n,s,r,a){return O1(e,t,n,s,r,0,!1,a,!0)}function cw(e,t,n,s,r,a){return O1(e,t,n,s,r,a,!0)}function O1(e,t,n,s,r,a,o=!1,i=!1,l=!1){let c=[];for(let g=0;gr&&c.push({score:t[g],boxIndex:g,suppressBeginIndex:0});c.sort(dw);let u=a>0?-.5/a:0,d=[],p=[];for(;d.length0;){let g=c.pop(),{score:A,boxIndex:x,suppressBeginIndex:y}=g;if(A=y;--w){let k=nO(e,x,d[w]);if(k>=s){b=!0;break}if(g.score=g.score*sO(s,u,k),g.score<=r)break}g.suppressBeginIndex=d.length,b||(g.score===A?(d.push(x),p.push(g.score)):g.score>r&&JF(c,g,dw))}let h=d.length,f=n-h;i&&f>0&&(d.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));let m={selectedIndices:d};return o&&(m.selectedScores=p),l&&(m.validOutputs=h),m}function nO(e,t,n){let s=e.subarray(t*4,t*4+4),r=e.subarray(n*4,n*4+4),a=Math.min(s[0],s[2]),o=Math.min(s[1],s[3]),i=Math.max(s[0],s[2]),l=Math.max(s[1],s[3]),c=Math.min(r[0],r[2]),u=Math.min(r[1],r[3]),d=Math.max(r[0],r[2]),p=Math.max(r[1],r[3]),h=(i-a)*(l-o),f=(d-c)*(p-u);if(h<=0||f<=0)return 0;let m=Math.max(a,c),g=Math.max(o,u),A=Math.min(i,d),x=Math.min(l,p),y=Math.max(A-m,0)*Math.max(x-g,0);return y/(h+f-y)}function sO(e,t,n){let s=Math.exp(t*n*n);return n<=e?s:0}function dw(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function rO(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=D(e,"boxes","nonMaxSuppressionAsync"),o=D(t,"scores","nonMaxSuppressionAsync"),i=Ku(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l=await Promise.all([a.data(),o.data()]),c=l[0],u=l[1],{selectedIndices:d}=lw(c,u,n,s,r);return a!==e&&a.dispose(),o!==t&&o.dispose(),Vt(d,"int32")}var aO=rO;function oO(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=D(e,"boxes","nonMaxSuppression"),i=D(t,"scores","nonMaxSuppression"),l=Ku(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let c={boxes:o,scores:i},u={maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a},d=W.runKernel(Pi,c,u);return{selectedIndices:d[0],selectedScores:d[1]}}var iO=V({nonMaxSuppressionWithScore_:oO});async function lO(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=D(e,"boxes","nonMaxSuppressionAsync"),i=D(t,"scores","nonMaxSuppressionAsync"),l=Ku(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let c=await Promise.all([o.data(),i.data()]),u=c[0],d=c[1],{selectedIndices:p,selectedScores:h}=cw(u,d,n,s,r,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Vt(p,"int32"),selectedScores:Vt(h)}}var uO=lO;function cO(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=D(e,"boxes","nonMaxSuppression"),i=D(t,"scores","nonMaxSuppression"),l=Ku(o,i,n,s,r,null),c=l.maxOutputSize,u=l.iouThreshold,d=l.scoreThreshold,p={boxes:o,scores:i},h={maxOutputSize:c,iouThreshold:u,scoreThreshold:d,padToMaxOutputSize:a},f=W.runKernel(Iu,p,h);return{selectedIndices:f[0],validOutputs:f[1]}}var dO=V({nonMaxSuppressionPadded_:cO});async function pO(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=D(e,"boxes","nonMaxSuppressionAsync"),i=D(t,"scores","nonMaxSuppressionAsync"),l=Ku(o,i,n,s,r,null),c=l.maxOutputSize,u=l.iouThreshold,d=l.scoreThreshold,[p,h]=await Promise.all([o.data(),i.data()]),{selectedIndices:f,validOutputs:m}=uw(p,h,c,u,d,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Vt(f,"int32"),validOutputs:Ie(m,"int32")}}var hO=pO;function fO(e,t,n=!1,s=!1){let r=D(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=H(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},c=W.runKernel(lo,i,l);return o?H(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var mO=V({resizeBilinear_:fO});function gO(e,t,n=!1,s=!1){let r=D(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=H(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},c=W.runKernel(Nu,i,l);return o?H(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var AO=V({resizeNearestNeighbor_:gO});function yO(e,t="binary",n=!1,s=.5){let r=D(e,"image","threshold"),a=.2989,o=.587,i=.114,l=r.shape[0]*r.shape[1],c=L(Vt([s]),255),u,d,p,h;if(M(r.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`),M(r.shape[2]===3||r.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`),M(r.dtype==="int32"||r.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`),M(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),r.shape[2]===3){[u,d,p]=sn(r,[1,1,1],-1);let g=L(u,a),A=L(d,o),x=L(p,i);h=ue(ue(g,A),x)}else h=e;if(t==="otsu"){let g=r1(me(w1(h),"int32"),ut([]),256);c=xO(g,l)}let f=n?pl(h,c):As(h,c);return me(L(f,255),"int32")}function xO(e,t){let n=Vt([-1]),s=Vt([0]),r=Vt([0]),a,o,i,l,c,u;for(let d=0;d`Error in transform: image must be rank 4,but got rank ${o.rank}.`),M(i.rank===2&&(i.shape[0]===o.shape[0]||i.shape[0]===1)&&i.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),M(a==null||a.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`);let l={image:o,transforms:i},c={interpolation:n,fillMode:s,fillValue:r,outputShape:a};return W.runKernel(Yi,l,c)}var wO=V({transform_:vO});function kO(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=D(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=H(qu(0,a,1,"int32"),[-1,1]),l=qu(0,o,1,"int32"),c=fe(i,l),u=hr(pl(c,Ie(+t,"int32")),dl(c,Ie(-n,"int32"))),d=Ht([a,o],s.dtype);return H(yn(os(H(s,[-1,a,o])).map(p=>Vn(u,p,d))),r)}var SO=V({bandPart_:kO});function IO(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=sn(e,e.shape[0],0).map(r=>ot(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 pw(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,c)=>l*c),s=os(H(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],a=[];s.forEach(l=>{let[c,u]=pw(l,t);r.push(c),a.push(u)});let o=H(yn(r,0),e.shape),i=H(yn(a,0),e.shape);return[o,i]}}function pw(e,t=!1){return W.tidy(()=>{M(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let n=e.shape[0],s=e.shape[1],r=d1(n),a=Wn(e),o=fr([[1]],[1,1]),i=Wn(o),l=n>=s?s:n;for(let c=0;c{let h=Pe(a,[c,c],[n-c,1]),f=_1(h),m=Pe(a,[c,c],[1,1]),g=Vn(As(m,0),fr([[-1]]),fr([[1]])),A=fe(m,L(g,f)),x=ge(h,A);x.shape[0]===1?i=Wn(o):i=wt([o,Pe(x,[1,0],[x.shape[0]-1,x.shape[1]])],0);let y=Ot(ge(He(g,A),f)),b=Pe(a,[c,0],[n-c,s]),w=L(y,i),k=Qe(i);if(c===0)a=fe(b,He(w,He(k,b)));else{let R=fe(b,He(w,He(k,b)));a=wt([Pe(a,[0,0],[c,s]),R],0)}let I=Qe(w),N=Pe(r,[0,c],[n,r.shape[1]-c]);if(c===0)r=fe(N,He(He(N,i),I));else{let R=fe(N,He(He(N,i),I));r=wt([Pe(r,[0,0],[n,c]),R],1)}return[i,a,r]}),te([u,d,p])}return!t&&n>s&&(r=Pe(r,[0,0],[n,s]),a=Pe(a,[0,0],[s,s])),[r,a]})}var NO=V({qr_:TO}),Un;(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"})(Un||(Un={}));function EO(e,t,n=Un.SUM_BY_NONZERO_WEIGHTS){let s=D(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=D(t,"weights","computeWeightedLoss"));let a=r==null?s:L(s,r);if(n===Un.NONE)return a;if(n===Un.SUM)return ke(a);if(n===Un.MEAN){if(r==null)return Wt(a);{let o=s.size/r.size,i=ge(ke(a),ke(r));return o>1?ge(i,Ie(o)):i}}if(n===Un.SUM_BY_NONZERO_WEIGHTS){if(r==null)return ge(ke(a),Ie(s.size));{let o=L(r,ys(s.shape)),i=me(ke(Hu(o,Ie(0))),"float32");return ge(ke(a),i)}}throw Error(`Unknown reduction: ${n}`)}var ta=V({computeWeightedLoss_:EO});function RO(e,t,n,s=Un.SUM_BY_NONZERO_WEIGHTS){let r=D(e,"labels","absoluteDifference"),a=D(t,"predictions","absoluteDifference"),o=null;n!=null&&(o=D(n,"weights","absoluteDifference")),zn(r.shape,a.shape,"Error in absoluteDifference: ");let i=nn(fe(r,a));return ta(i,o,s)}var $O=V({absoluteDifference_:RO});function _O(e,t,n,s,r=Un.SUM_BY_NONZERO_WEIGHTS){let a=D(e,"labels","cosineDistance"),o=D(t,"predictions","cosineDistance"),i=null;s!=null&&(i=D(s,"weights","cosineDistance")),zn(a.shape,o.shape,"Error in cosineDistance: ");let l=Ie(1),c=fe(l,ke(L(a,o),n,!0));return ta(c,i,r)}var DO=V({cosineDistance_:_O});function PO(e,t,n,s=Un.SUM_BY_NONZERO_WEIGHTS){let r=D(e,"labels","hingeLoss"),a=D(t,"predictions","hingeLoss"),o=null;n!=null&&(o=D(n,"weights","hingeLoss")),zn(r.shape,a.shape,"Error in hingeLoss: ");let i=Ie(1);r=fe(L(Ie(2),r),i);let l=Or(fe(i,L(r,a)));return ta(l,o,s)}var FO=V({hingeLoss_:PO});function OO(e,t,n,s=1,r=Un.SUM_BY_NONZERO_WEIGHTS){let a=D(e,"labels","huberLoss"),o=D(t,"predictions","huberLoss"),i=null;n!=null&&(i=D(n,"weights","huberLoss")),zn(a.shape,o.shape,"Error in huberLoss: ");let l=Ie(s),c=nn(fe(o,a)),u=zd(c,l),d=fe(c,u),p=ue(L(Ie(.5),At(u)),L(l,d));return ta(p,i,r)}var MO=V({huberLoss_:OO});function zO(e,t,n,s=1e-7,r=Un.SUM_BY_NONZERO_WEIGHTS){let a=D(e,"labels","logLoss"),o=D(t,"predictions","logLoss"),i=null;n!=null&&(i=D(n,"weights","logLoss")),zn(a.shape,o.shape,"Error in logLoss: ");let l=Ie(1),c=Ie(s),u=Ot(L(a,Ds(ue(o,c)))),d=L(fe(l,a),Ds(ue(fe(l,o),c))),p=fe(u,d);return ta(p,i,r)}var LO=V({logLoss_:zO});function BO(e,t,n,s=Un.SUM_BY_NONZERO_WEIGHTS){let r=D(e,"labels","meanSquaredError"),a=D(t,"predictions","meanSquaredError"),o=null;n!=null&&(o=D(n,"weights","meanSquaredError")),zn(r.shape,a.shape,"Error in meanSquaredError: ");let i=E1(r,a);return ta(i,o,s)}var WO=V({meanSquaredError_:BO});function VO(e,t){let n=D(e,"labels","sigmoidCrossEntropyWithLogits"),s=D(t,"logits","sigmoidCrossEntropyWithLogits");zn(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=Or(s),a=L(s,n),o=vf(_s(Ot(nn(s))));return ue(fe(r,a),o)}function UO(e,t,n,s=0,r=Un.SUM_BY_NONZERO_WEIGHTS){let a=D(e,"multiClassLabels","sigmoidCrossEntropy"),o=D(t,"logits","sigmoidCrossEntropy"),i=null;if(n!=null&&(i=D(n,"weights","sigmoidCrossEntropy")),zn(a.shape,o.shape,"Error in sigmoidCrossEntropy: "),s>0){let c=Ie(s),u=Ie(1),d=Ie(.5);a=ue(L(a,fe(u,c)),L(d,c))}let l=VO(a,o);return ta(l,i,r)}var GO=V({sigmoidCrossEntropy_:UO});function HO(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 Fr((r,a,o)=>{let l=zv(a,[n],!0),c=fe(me(a,"float32"),l);o([r,c]);let u=Ot(L(c,r));return{value:ke(u,[n]),gradFunc:(h,f)=>{let[m,g]=f,A=hl(h.shape,[n]);return[L(H(h,A),fe(me(m,"float32"),_s(g))),L(H(h,A),fe(_s(g),me(m,"float32")))]}}})(e,t)}function jO(e,t,n,s=0,r=Un.SUM_BY_NONZERO_WEIGHTS){let a=D(e,"onehotLabels","softmaxCrossEntropy"),o=D(t,"logits","softmaxCrossEntropy"),i=null;if(n!=null&&(i=D(n,"weights","softmaxCrossEntropy")),zn(a.shape,o.shape,"Error in softmaxCrossEntropy: "),s>0){let c=Ie(s),u=Ie(1),d=Ie(a.shape[1]);a=ue(L(a,fe(u,c)),ge(c,d))}let l=HO(a,o);return ta(l,i,r)}var qO=V({softmaxCrossEntropy_:jO});function XO(e,t,n,s){let r=D(e,"indices","sparseFillEmptyRows"),a=D(t,"values","sparseFillEmptyRows"),o=D(n,"denseShape","sparseFillEmptyRows"),i=D(s,"defaultValue","sparseFillEmptyRows",a.dtype);if(r.rank!==2)throw new Error(`Indices should be Tensor2D but received shape ${r.shape}`);if(a.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(o.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(i.rank!==0)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);let l={indices:r,values:a,denseShape:o,defaultValue:i},c=W.runKernel(Xh,l);return{outputIndices:c[0],outputValues:c[1],emptyRowIndicator:c[2],reverseIndexMap:c[3]}}var KO=V({sparseFillEmptyRows_:XO});function ZO(e,t,n){let s=D(e,"inputIndices","sparseReshape"),r=D(t,"inputShape","sparseReshape"),a=D(n,"newShape","sparseReshape");if(s.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape ${s.shape}`);if(r.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${r.shape}`);if(a.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);let o={inputIndices:s,inputShape:r,newShape:a},i=W.runKernel(Kh,o);return{outputIndices:i[0],outputShape:i[1]}}var YO=V({sparseReshape_:ZO});function JO(e,t,n){let s=D(e,"data","sparseSegmentMean"),r=D(t,"indices","sparseSegmentMean"),a=D(n,"segmentIds","sparseSegmentMean");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape ${r.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape ${a.shape}`);let o={data:s,indices:r,segmentIds:a};return W.runKernel(Zh,o)}var QO=V({sparseSegmentMean_:JO});function eM(e,t,n){let s=D(e,"data","sparseSegmentSum"),r=D(t,"indices","sparseSegmentSum"),a=D(n,"segmentIds","sparseSegmentSum");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape ${r.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape ${a.shape}`);let o={data:s,indices:r,segmentIds:a};return W.runKernel(Yh,o)}var tM=V({sparseSegmentSum_:eM});function nM(e,t,n,s,r,a,o,i){let l=D(e,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);let c=D(t,"dataSplits","stringNGrams");if(c.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let u={separator:n,nGramWidths:s,leftPad:r,rightPad:a,padWidth:o,preserveShortSequences:i},d={data:l,dataSplits:c},p=W.runKernel(yd,d,u);return{nGrams:p[0],nGramsSplits:p[1]}}var sM=V({stringNGrams_:nM});function rM(e,t,n=!0){let s=D(e,"input","stringSplit","string"),r=D(t,"delimiter","stringSplit","string");if(s.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${s.shape}`);if(r.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);let a={skipEmpty:n},o={input:s,delimiter:r},i=W.runKernel(Jh,o,a);return{indices:i[0],values:i[1],shape:i[2]}}var aM=V({stringSplit_:rM});function oM(e,t){let n=D(e,"input","stringToHashBucketFast","string"),s={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let r={input:n};return W.runKernel(Qh,r,s)}var iM=V({stringToHashBucketFast_:oM}),lM={fft:Ef,ifft:Wd,rfft:Rf,irfft:N1},uM={hammingWindow:MF,hannWindow:ow,frame:iw,stft:WF},Ce={flipLeftRight:HF,grayscaleToRGB:qF,resizeNearestNeighbor:AO,resizeBilinear:mO,rotateWithOffset:KF,cropAndResize:UF,nonMaxSuppression:YF,nonMaxSuppressionAsync:aO,nonMaxSuppressionWithScore:iO,nonMaxSuppressionWithScoreAsync:uO,nonMaxSuppressionPadded:dO,nonMaxSuppressionPaddedAsync:hO,threshold:bO,transform:wO},hw={bandPart:SO,gramSchmidt:CO,qr:NO},cM={absoluteDifference:$O,computeWeightedLoss:ta,cosineDistance:DO,hingeLoss:FO,huberLoss:MO,logLoss:LO,meanSquaredError:WO,sigmoidCrossEntropy:GO,softmaxCrossEntropy:qO},Ud={sparseFillEmptyRows:KO,sparseReshape:YO,sparseSegmentMean:QO,sparseSegmentSum:tM},Of={stringNGrams:sM,stringSplit:aM,stringToHashBucketFast:iM},na=class extends Y3{minimize(e,t=!1,n){let{value:s,grads:r}=this.computeGradients(e,n);if(n!=null){let a=n.map(o=>({name:o.name,tensor:r[o.name]}));this.applyGradients(a)}else this.applyGradients(r);return te(r),t?s:(s.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return Pv(e,t)}dispose(){this.iterations_!=null&&te(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(na,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var Mf=class extends na{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=W.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=W.registeredVariables[n],a=!1;this.accumulatedGrads[s]==null&&(this.accumulatedGrads[s]={originalName:`${n}/accum_grad`,variable:X(()=>et(r).variable(a))}),this.accumulatedUpdates[s]==null&&(this.accumulatedUpdates[s]={originalName:`${n}/accum_var`,variable:X(()=>et(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;X(()=>{let c=ue(L(i,this.rho),L(At(o),1-this.rho)),u=L(ge(Dn(ue(l,this.epsilon)),Dn(ue(i,this.epsilon))),o),d=ue(L(l,this.rho),L(At(u),1-this.rho));i.assign(c),l.assign(d);let p=ue(L(u,-this.learningRate),r);r.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(te(this.accumulatedGrads.map(e=>e.variable)),te(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){let e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}};Mf.className="Adadelta";Ro(Mf);var zf=class extends na{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=W.registeredVariables[n];if(this.accumulatedGrads[s]==null){let i=!1;this.accumulatedGrads[s]={originalName:`${n}/accumulator`,variable:X(()=>Vu(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;X(()=>{let i=ue(o,At(a));o.assign(i);let l=ue(L(ge(a,Dn(ue(i,W.backend.epsilon()))),-this.learningRate),r);r.assign(l)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&te(this.accumulatedGrads.map(e=>e.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=!1;this.accumulatedGrads=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}};zf.className="Adagrad";Ro(zf);var Lf=class extends na{constructor(e,t,n,s=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],X(()=>{this.accBeta1=Ie(t).variable(),this.accBeta2=Ie(n).variable()}),s==null&&(this.epsilon=W.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);X(()=>{let n=fe(1,this.accBeta1),s=fe(1,this.accBeta2);t.forEach((r,a)=>{let o=W.registeredVariables[r],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${r}/m`,variable:X(()=>et(o).variable(i))}),this.accumulatedSecondMoment[a]==null&&(this.accumulatedSecondMoment[a]={originalName:`${r}/v`,variable:X(()=>et(o).variable(i))});let l=Array.isArray(e)?e[a].tensor:e[r];if(l==null)return;let c=this.accumulatedFirstMoment[a].variable,u=this.accumulatedSecondMoment[a].variable,d=ue(L(c,this.beta1),L(l,1-this.beta1)),p=ue(L(u,this.beta2),L(At(l),1-this.beta2)),h=ge(d,n),f=ge(p,s);c.assign(d),u.assign(p);let m=ue(L(ge(h,ue(Dn(f),this.epsilon)),-this.learningRate),o);o.assign(m)}),this.accBeta1.assign(L(this.accBeta1,this.beta1)),this.accBeta2.assign(L(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&te(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&te(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){let e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e),X(()=>{this.accBeta1.assign(Po(this.beta1,this.iterations_+1)),this.accBeta2.assign(Po(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)}};Lf.className="Adam";Ro(Lf);var Bf=class extends na{constructor(e,t,n,s=null,r=0){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],X(()=>{this.iteration=Ie(0).variable(),this.accBeta1=Ie(t).variable()}),s==null&&(this.epsilon=W.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);X(()=>{let n=fe(1,this.accBeta1),s=ge(-this.learningRate,ue(L(this.iteration,this.decay),1));t.forEach((r,a)=>{let o=W.registeredVariables[r],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${r}/m`,variable:et(o).variable(i)}),this.accumulatedWeightedInfNorm[a]==null&&(this.accumulatedWeightedInfNorm[a]={originalName:`${r}/v`,variable:et(o).variable(i)});let l=Array.isArray(e)?e[a].tensor:e[r];if(l==null)return;let c=this.accumulatedFirstMoment[a].variable,u=this.accumulatedWeightedInfNorm[a].variable,d=ue(L(c,this.beta1),L(l,1-this.beta1)),p=L(u,this.beta2),h=nn(l),f=ea(p,h);c.assign(d),u.assign(f);let m=ue(L(ge(s,n),ge(d,ue(f,this.epsilon))),o);o.assign(m)}),this.iteration.assign(ue(this.iteration,1)),this.accBeta1.assign(L(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&te(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&te(this.accumulatedWeightedInfNorm.map(e=>e.variable))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}};Bf.className="Adamax";Ro(Bf);var Gd=class extends na{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=Array.isArray(e)?e[s].tensor:e[n];if(r==null)return;let a=W.registeredVariables[n];X(()=>{let o=ue(L(this.c,r),a);a.assign(o)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=gn(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)}};Gd.className="SGD";Ro(Gd);var Wf=class extends Gd{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=W.registeredVariables[n];if(this.accumulations[s]==null){let i=!1;this.accumulations[s]={originalName:`${n}/momentum`,variable:X(()=>et(r).variable(i))}}let a=this.accumulations[s].variable,o=Array.isArray(e)?e[s].tensor:e[n];o!=null&&X(()=>{let i,l=ue(L(this.m,a),o);this.useNesterov?i=ue(L(this.c,ue(o,L(l,this.m))),r):i=ue(L(this.c,l),r),a.assign(l),r.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&te(this.accumulations.map(e=>e.variable))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=!1;this.accumulations=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}};Wf.className="Momentum";Ro(Wf);var Vf=class extends na{constructor(e,t=.9,n=0,s=null,r=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=s,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,s==null&&(this.epsilon=W.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=W.registeredVariables[n],a=!1;this.accumulatedMeanSquares[s]==null&&(this.accumulatedMeanSquares[s]={originalName:`${n}/rms`,variable:X(()=>et(r).variable(a))}),this.accumulatedMoments[s]==null&&(this.accumulatedMoments[s]={originalName:`${n}/momentum`,variable:X(()=>et(r).variable(a))}),this.accumulatedMeanGrads[s]==null&&this.centered&&(this.accumulatedMeanGrads[s]={originalName:`${n}/mg`,variable:X(()=>et(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;X(()=>{let c=ue(L(i,this.decay),L(At(o),1-this.decay));if(this.centered){let u=this.accumulatedMeanGrads[s].variable,d=ue(L(u,this.decay),L(o,1-this.decay)),p=ge(L(o,this.learningRate),Dn(fe(c,ue(At(d),this.epsilon)))),h=ue(L(l,this.momentum),p);i.assign(c),u.assign(d),l.assign(h);let f=fe(r,h);r.assign(f)}else{let u=ue(L(i,this.decay),L(At(o),1-this.decay)),d=ue(L(l,this.momentum),ge(L(o,this.learningRate),Dn(ue(u,this.epsilon))));i.assign(u),l.assign(d);let p=fe(r,d);r.assign(p)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&te(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&te(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&te(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){let e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}};Vf.className="RMSProp";Ro(Vf);var Oo=class{static sgd(e){return new Gd(e)}static momentum(e,t,n=!1){return new Wf(e,t,n)}static rmsprop(e,t=.9,n=0,s=null,r=!1){return new Vf(e,t,n,s,r)}static adam(e=.001,t=.9,n=.999,s=null){return new Lf(e,t,n,s)}static adadelta(e=.001,t=.95,n=null){return new Mf(e,t,n)}static adamax(e=.002,t=.9,n=.999,s=null,r=0){return new Bf(e,t,n,s,r)}static adagrad(e,t=.1){return new zf(e,t)}},gl={sgd:Oo.sgd,momentum:Oo.momentum,adadelta:Oo.adadelta,adagrad:Oo.adagrad,rmsprop:Oo.rmsprop,adamax:Oo.adamax,adam:Oo.adam},dM=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function fw(){return new Promise(e=>dM(()=>e()))}var E={};Oe(E,{ERF_A1:()=>wM,ERF_A2:()=>kM,ERF_A3:()=>SM,ERF_A4:()=>IM,ERF_A5:()=>CM,ERF_P:()=>vM,PARALLELIZE_THRESHOLD:()=>M1,SELU_SCALE:()=>gw,SELU_SCALEALPHA:()=>mw,applyActivation:()=>Pf,assertAndGetBroadcastShape:()=>gt,assertAxesAreInnerMostDims:()=>kD,assertParamsConsistent:()=>pM,assignToTypedArray:()=>_M,axesAreInnerMostDims:()=>f1,calculateShapes:()=>B3,checkEinsumDimSizes:()=>zM,combineLocations:()=>Fv,complexWithEvenIndex:()=>EM,complexWithOddIndex:()=>RM,computeConv2DInfo:()=>Dd,computeConv3DInfo:()=>pv,computeDefaultPad:()=>t1,computeDilation2DInfo:()=>U$,computeOptimalWindowSize:()=>fM,computeOutAndReduceShapes:()=>Ov,computeOutShape:()=>hM,computePool2DInfo:()=>dv,computePool3DInfo:()=>G$,convertConv2DDataFormat:()=>hv,decodeEinsumEquation:()=>OM,eitherStridesOrDilationsAreOne:()=>Pr,expandShapeToKeepDim:()=>hl,exponent:()=>PM,exponents:()=>DM,fromStringArrayToUint8:()=>qM,fromUint8ToStringArray:()=>jM,getAxesPermutation:()=>Mv,getBroadcastDims:()=>O3,getComplexWithIndex:()=>$M,getEinsumComputePath:()=>LM,getEinsumPermutation:()=>MM,getFusedBiasGradient:()=>Df,getFusedDyActivation:()=>_f,getImageCenter:()=>mM,getInnerMostAxes:()=>SD,getPermuted:()=>AM,getReductionAxes:()=>Xt,getReshaped:()=>gM,getReshapedPermuted:()=>yM,getSliceBeginCoords:()=>xM,getSliceSize:()=>bM,getUndoAxesPermutation:()=>m1,isIdentityPermutation:()=>BM,log:()=>A9,mergeRealAndImagArrays:()=>TM,prepareAndValidate:()=>L3,prepareSplitSize:()=>VM,segment_util:()=>xw,shouldFuse:()=>Ff,slice_util:()=>Ft,splitRealAndImagArrays:()=>NM,tupleValuesAreOne:()=>$o,upcastType:()=>Bn,validateInput:()=>q2,validateUpdateShape:()=>j2,warn:()=>Io});function pM(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 hM(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 yM(e,t,n,s=!0){let r=[];s?r.push(e[0]/n):r.push(e[0]*n);for(let a=1;a/g,Aw=",",yw="...";function OM(e,t){e=e.replace(/\s/g,"");let n=(e.length-e.replace(FM,"").length)/z1.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 ("${z1}").`);let[s,r]=e.split(z1);M(s.indexOf(yw)===-1,()=>`The ellipsis notation ("${yw}") is not supported yet.`);let a=s.split(Aw),o=a.length;if(t!==o)throw new Error(`Expected ${o} input tensors, received ${t}`);if(o>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let i=[];for(let p=0;pf.indexOf(h)!==-1))throw new Error(`Output subscripts contain the label ${h} not present in the input subscripts.`);i.indexOf(h)===-1&&i.push(h)}for(let p=0;pr!==-1),{permutationIndices:n,expandDims:s}}function zM(e,t,n){let s=new Array(e);for(let r=0;r`Expected dimension ${s[t[r][o]]} at axis ${o} of input shaped ${JSON.stringify(a)}, but got dimension ${a[o]}`)}}function LM(e,t){let n=e,s=[],r=0;e.length===0&&n.push(-1),r=e.length+1;for(let o=0;ot===n)}function WM(e,t){let n=[];for(let s=0;s"Number of splits must evenly divide the axis."),s=new Array(t).fill(e.shape[n]/t);else{let r=t.reduce((o,i)=>(i===-1&&(o+=1),o),0);M(r<=1,()=>"There should be only one negative value in split array.");let a=t.indexOf(-1);if(a!==-1){let o=t.reduce((i,l)=>l>0?i+l:i);t[a]=e.shape[n]-o}M(e.shape[n]===t.reduce((o,i)=>o+i),()=>"The sum of sizes must match the size of the axis dimension."),s=t}return s}var xw={};Oe(xw,{collectGatherOpShapeInfo:()=>HM,computeOutShape:()=>GM,segOpComputeOptimalWindowSize:()=>UM});function UM(e,t){let n=!1,s;for(e<=M1?(s=e,n=!0):s=wh(e,Math.floor(Math.sqrt(e)));!n;)s>t||s===e?n=!0:s=wh(e,s+1);return s}function GM(e,t,n){let s=[],r=e.length;for(let a=0;ar))throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${s}`);if(s<0&&(s+=r),s>a)throw new Error(`batchDims (${s}) must be less than rank(x) ( ${a}).`);if(nrf(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function qM(e){return e.map(t=>Sd(t))}var Qs={};Oe(Qs,{nonMaxSuppressionV3Impl:()=>lw,nonMaxSuppressionV4Impl:()=>uw,nonMaxSuppressionV5Impl:()=>cw,whereImpl:()=>Jv});var bw={kernelName:fi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,Vd(me(n,"float32"),-1))}}},XM={kernelName:iu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=At(me(n,"float32")),r=Dn(fe(Ie(1),s));return Ot(ge(e,r))}}}},KM={kernelName:lu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=Dn(fe(At(me(n,"float32")),1));return ge(e,s)}}}},ZM={kernelName:Kr,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=gt(n.shape,s.shape);return{a:()=>{let i=e,l=Xt(n.shape,r);return l.length>0&&(i=ke(i,l)),H(i,n.shape)},b:()=>{let i=e,l=Xt(s.shape,r);return l.length>0&&(i=ke(i,l)),H(i,s.shape)}}}},YM={kernelName:Ra,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((s,r)=>{n[r]=()=>e.clone()}),n}},JM={kernelName:$a,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>et(n)}}},QM={kernelName:du,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>et(n)}}},ez={kernelName:pu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,Dn(fe(Ie(1),At(me(n,"float32")))))}}},tz={kernelName:hu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=Dn(ue(Ie(1),At(me(n,"float32"))));return ge(e,s)}}}},nz={kernelName:gu,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=gt(n.shape,s.shape);return{a:()=>{let i=ue(At(n),At(s)),l=L(e,ge(s,i)),c=Xt(n.shape,r);return c.length>0&&(l=ke(l,c)),H(l,n.shape)},b:()=>{let i=ue(At(n),At(s)),l=Ot(L(e,ge(n,i))),c=Xt(s.shape,r);return c.length>0&&(l=ke(l,c)),H(l,s.shape)}}}},sz={kernelName:fu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,ue(At(me(n,"float32")),1))}}},rz={kernelName:mu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,fe(Ie(1),At(me(n,"float32"))))}}};function az(e,t,n,s,r,a){let o=D(e,"dy","avgPool3dGrad"),i=D(t,"input","avgPool3dGrad"),l=o,c=i,u=!1;i.rank===4&&(u=!0,l=H(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),c=H(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),M(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),M(c.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${c.rank}.`),a!=null&&M(fn(r),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${a} but got pad ${r}.`);let d={dy:l,input:c},p={filterSize:n,strides:s,pad:r,dimRoundingMode:a},h=W.runKernel(Ih,d,p);return u?H(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var oz=V({avgPool3dGrad_:az}),iz={kernelName:od,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{filterSize:r,strides:a,pad:o,dimRoundingMode:i}=n;return{x:()=>oz(e,s,r,a,o,i)}}};function lz(e,t,n,s,r){let a=D(e,"dy","avgPoolGrad"),o=D(t,"input","avgPoolGrad");M(o.rank===a.rank,()=>`Rank of input (${o.rank}) does not match rank of dy (${a.rank})`);let i=o,l=a,c=!1;o.rank===3&&(c=!0,i=H(o,[1,o.shape[0],o.shape[1],o.shape[2]]),l=H(a,[1,a.shape[0],a.shape[1],a.shape[2]])),M(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),M(i.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${i.rank}.`);let u={dy:l,input:i},d={filterSize:n,strides:s,pad:r},p=W.runKernel(Sh,u,d);return c?H(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var uz=V({avgPoolGrad_:lz}),cz={kernelName:_a,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{filterSize:r,strides:a,pad:o}=n;return{x:()=>uz(e,s,r,a,o)}}},dz={kernelName:Da,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{let[s,r]=t,{transposeA:a,transposeB:o}=n;return!a&&!o?{a:()=>He(e,r,!1,!0),b:()=>He(s,e,!0,!1)}:!a&&o?{a:()=>He(e,r,!1,!1),b:()=>He(e,s,!0,!1)}:a&&!o?{a:()=>He(r,e,!1,!0),b:()=>He(s,e,!1,!1)}:{a:()=>He(r,e,!0,!0),b:()=>He(e,s,!0,!0)}}},pz={kernelName:mi,gradFunc:(e,t,n)=>{let{blockShape:s,crops:r}=n;return{x:()=>Cf(e,s,r)}}},hz={kernelName:t3,gradFunc:(e,t,n)=>{let s=n,r=s.inputShape,a=s.shape,o=Array.from(a);for(let l=r.length-1;l>=0;l--)if(r[l]===a[l])o[l]=1;else if(r[l]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${a}].`);let i=[];for(let l=0;l1&&i.push(l);return{x:()=>ke(e,i,!0)}}},fz={kernelName:Pa,gradFunc:e=>({x:()=>e.clone()})},mz={kernelName:Fa,gradFunc:e=>({x:()=>et(e)})},gz={kernelName:Zr,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{clipValueMin:r,clipValueMax:a}=n;return{x:()=>Vn(hr(dl(s,r),pl(s,a)),e,et(e))}}},Az={kernelName:ld,inputsToSave:["x"],gradFunc:bw.gradFunc},yz={kernelName:gi,saveAllInputs:!0,gradFunc:(e,t,n)=>{let s=t.map(l=>l.shape),{axis:r}=n,a=Xs(r,t[0].shape)[0],o=s.map(l=>l[a]);return sn(e,o,a).map(l=>()=>l)}},xz={kernelName:Oa,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[s,r]=t,{dilations:a,strides:o,pad:i,dataFormat:l}=n;return M($o(a),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`),{x:()=>o1(s.shape,e,r,o,i,l),filter:()=>F1(s,e,r.shape,o,i,l)}}},bz={kernelName:Ma,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{let[s,r]=t,{strides:a,pad:o,dataFormat:i,dimRoundingMode:l}=n;return{dy:()=>_o(e,r,a,o,i,1,l),filter:()=>F1(e,s,r.shape,a,o,i,l)}}};function vz(e,t,n,s,r){let a=e;e.rank===4&&(a=H(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let o=t;o.rank===4&&(o=H(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),M(a.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${a.shape}.`),M(o.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${o.shape}.`),M(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),M(a.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${a.shape[4]}) must match input depth in filter (${n[3]}.`),M(o.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${o.shape[4]}) must match output depth for filter (${n[4]}).`);let i={x:a,dy:o},l={strides:s,pad:r,filterShape:n};return W.runKernel(Eh,i,l)}var wz=V({conv3DBackpropFilter_:vz}),kz={kernelName:ud,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:s,strides:r,pad:a}=n;M($o(s),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let[o,i]=t;return{x:()=>wv(o.shape,e,i,r,a),filter:()=>wz(o,e,i.shape,r,a)}}},Sz={kernelName:za,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(Ot(I1(me(n,"float32"))),e)}}},Iz={kernelName:La,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(C1(me(n,"float32")),e)}}},Cz={kernelName:Ai,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{axis:r,exclusive:a,reverse:o}=n;return{x:()=>{let i=Mv([r],s.rank),l=c1(e,r,a,!o);return i!=null&&(l=Qe(l,i)),l}}}},Tz={kernelName:Ba,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:s,strides:r,pad:a,dimRoundingMode:o}=n,i=s==null?[1,1]:s;M($o(i),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);let[l,c]=t;return M(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),M(c.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${c.rank}.`),M(l.shape[3]===c.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),M(Pr(r,i),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'.`),o!=null&&M(fn(a),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`),{x:()=>aw(l.shape,e,c,r,a,i,o),filter:()=>rw(l,e,c.shape,r,a,i,o)}}},Nz={kernelName:cd,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[s,r]=t,a={x:s,filter:r,dy:e},o={x:s,filter:r,dy:e};return{x:()=>W.runKernel(Fh,a,n),filter:()=>W.runKernel(Oh,o,n)}}},Ez={kernelName:Va,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t,s={dy:e,y:n};return{x:()=>W.runKernel(Mh,s)}}},Rz={kernelName:Au,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,s=L(_s(Ot(At(n))),2/Math.sqrt(Math.PI));return{x:()=>L(e,s)}}},$z={kernelName:Ua,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,n)}}},_z={kernelName:vi,inputsToSave:["input"],gradFunc:(e,t)=>{let[n]=t;return{input:()=>H(e,n.shape)}}},Dz={kernelName:wi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,_s(n))}}},Pz={kernelName:Ga,gradFunc:e=>({x:()=>et(e)})},Fz={kernelName:Ha,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=gt(n.shape,s.shape);return{a:()=>{let i=ge(e,me(s,"float32")),l=Xt(n.shape,r);return l.length>0?H(ke(i,l),n.shape):i},b:()=>{let i=L(e,me(n,"float32")),l=Xt(s.shape,r);l.length>0&&(i=H(ke(i,l),s.shape));let c=At(s);return Ot(ge(i,me(c,"float32")))}}}},Oz={kernelName:ja,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{let{varianceEpsilon:s}=n,[r,a,o,i]=t,l=i==null?Ie(1):i,c=Xt(a.shape,r.shape),u=[];if(a.rank===1){for(let b=0;ba.rank===1?H(L(L(e,Ys(H(h,[1,1,1,a.shape[0]]),u)),l),r.shape):H(L(L(e,h),l),r.shape),mean:()=>{let b=L(L(h,Ie(-1)),p);return a.rank===1&&(b=ke(b,c)),H(b,a.shape)},variance:()=>{let b=L(L(f,d),p);return a.rank===1&&(b=ke(b,c)),H(b,a.shape)},scale:()=>{let b=L(d,h),w=L(e,b);return a.rank===1&&(w=ke(w,c)),H(w,a.shape)},offset:()=>{let b=e;return a.rank===1&&(b=ke(b,c)),H(b,a.shape)}}}},Mz={kernelName:Si,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{let[s,r]=t,{axis:a}=n,o=Xs(a,s.shape)[0];return{x:()=>{let l=s.shape,c=r.size,u=l.slice(0,o),d=u.length,p=l.slice(a,l.length).slice(1),h=p.length,f=vw(0,d),m=vw(d+1,d+1+h),g=ww([u,[c],p]),A=H(e,g),x=H(r,[c]),y=ww([[d],f,m]),b=Qe(A,y),w=Zv(b,x,s.shape[o]),k=m1(y);return w=Qe(w,k),w},indices:()=>r}}};function vw(e,t){let n=[];for(let s=e;s{let[n,s]=t;return{a:()=>et(n),b:()=>et(s)}}},Lz={kernelName:Xa,gradFunc:e=>({x:()=>me(e,"float32")})},Bz={kernelName:xu,gradFunc:e=>({x:()=>et(e)})},Wz={kernelName:bu,gradFunc:e=>({x:()=>et(e)})},Vz={kernelName:vu,gradFunc:e=>({x:()=>et(e)})},Uz={kernelName:Ti,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{alpha:r}=n,a=As(s,0);return{x:()=>Vn(a,e,L(e,r))}}},Gz={kernelName:wu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,ue(n,1))}}},Hz={kernelName:Ka,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,me(n,"float32"))}}},jz={kernelName:n3,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s]=t,{axis:r}=n;return{logits:()=>{let a=!0,o=_s(s);return fe(e,L(ke(e,r,a),o))}}}};function qz(e,t,n,s=5,r=1,a=1,o=.5){let i={x:e,y:t,dy:n},l={depthRadius:s,bias:r,alpha:a,beta:o};return W.runKernel(Wh,i,l)}var Xz=V({localResponseNormalizationBackprop_:qz}),Kz={kernelName:fd,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{depthRadius:a,bias:o,alpha:i,beta:l}=n;return{x:()=>Xz(s,r,e,a,o,i,l)}}};function kw(e,t,n,s){return t.rankL(e,me($s(n,t),e.dtype))}}var Sw={kernelName:Za,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let s=n,{reductionIndices:r}=s,a=t[0],o=t[1],i=Xs(r,a.shape),l=kw(e,o,a,i);return{x:()=>l.x()}}},Zz={kernelName:Ya,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t;return{a:()=>L(e,me(dl(n,s),"float32")),b:()=>L(e,me(p1(n,s),"float32"))}}};function Yz(e,t,n,s,r,a,o){let i=D(e,"dy","maxPool3dGrad"),l=D(t,"input","maxPool3dGrad"),c=D(n,"output","maxPool3dGrad"),u=i,d=l,p=c,h=!1;l.rank===4&&(h=!0,u=H(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),d=H(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),p=H(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),M(u.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`),M(d.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${d.rank}.`),M(p.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${p.rank}.`),o!=null&&M(fn(a),()=>`Error in maxPool3dGrad: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`);let f={dy:u,input:d,output:p},m={filterSize:s,strides:r,pad:a,dimRoundingMode:o},g=W.runKernel(Uh,f,m);return h?H(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var Jz=V({maxPool3dGrad_:Yz}),Qz={kernelName:md,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=n;return{x:()=>Jz(e,s,r,a,o,i,l)}}};function eL(e,t,n,s,r,a,o){let i=D(e,"dy","maxPoolGrad"),l=D(t,"input","maxPoolGrad"),c=D(n,"output","maxPoolGrad");M(l.rank===i.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${i.rank})`),M(i.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${i.rank}.`),M(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),o!=null&&M(fn(a),()=>`Error in maxPoolGrad: pad must be an integer when using, dimRoundingMode ${o} but got pad ${a}.`);let u={dy:i,input:l,output:c},d={filterSize:s,strides:r,pad:a,dimRoundingMode:o};return W.runKernel(Vh,u,d)}var tL=V({maxPoolGrad_:eL}),nL={kernelName:Ja,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{filterSize:a,strides:o,pad:i}=n;return{x:()=>tL(e,s,r,a,o,i)}}},sL={kernelName:Qa,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{axis:r}=n,a=Xs(r,s.shape),i=Ov(s.shape,a)[1],l=Gt(i);return{x:()=>{let u=s.shape.slice();a.forEach(h=>{u[h]=1});let d=H(e,u);return ge(L(d,ys(s.shape,"float32")),l)}}}},rL={kernelName:eo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let s=n,{axis:r}=s,[a,o]=t,i=Xs(r,a.shape),l=kw(e,o,a,i);return{x:()=>l.x()}}},aL={kernelName:to,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t;return{a:()=>L(e,me(pl(n,s),"float32")),b:()=>L(e,me(As(n,s),"float32"))}}},oL={kernelName:no,inputsToSave:["x"],gradFunc:(e,t,n)=>{let s=t[0],{paddings:r}=n,a=r.map(o=>o[0]);return{x:()=>Pe(e,a,s.shape)}}},iL={kernelName:Su,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=gt(n.shape,s.shape);return{a:()=>{let i=Xt(n.shape,r);return i.length>0?H(ke(e,i),n.shape):e},b:()=>{let i=L(e,Ot(Md(ge(n,s)))),l=Xt(s.shape,r);return l.length>0?H(ke(i,l),s.shape):i}}}},lL={kernelName:so,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=gt(n.shape,s.shape);return{a:()=>{let i=L(e,me(s,"float32")),l=Xt(n.shape,r);return l.length>0?H(ke(i,l),n.shape):i},b:()=>{let i=L(e,me(n,"float32")),l=Xt(s.shape,r);return l.length>0?H(ke(i,l),s.shape):i}}}},uL={kernelName:$i,gradFunc:e=>({x:()=>Ot(e)})},cL={kernelName:Oi,inputsToSave:["indices"],gradFunc:(e,t)=>{let n=t[0];return{indices:()=>Ht(n.shape,"float32")}}},dL={kernelName:Fi,gradFunc:e=>({x:()=>et(e)})},pL={kernelName:Mi,saveAllInputs:!0,gradFunc:(e,t,n)=>{let{axis:s}=n;return os(e,s).map(a=>()=>a)}},Iw={kernelName:ro,inputsToSave:["x"],gradFunc:(e,t,n)=>{let s=t[0],{paddings:r}=n,a=r.map(o=>o[0]);return{x:()=>Pe(e,a,s.shape)}}},hL={kernelName:ao,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[n,s,r]=t,a=n,o=s,i=gt(a.shape,o.shape);return{a:()=>{let u=me(o,"float32"),d=L(e,L(u,Po(a,fe(u,Ie(1))))),p=Xt(a.shape,i);return p.length>0&&(d=ke(d,p)),H(d,a.shape)},b:()=>{let u=As(a,0),d=Vn(u,Ds(a),et(a)),p=L(e,L(r,d)),h=Xt(o.shape,i);return h.length>0&&(p=ke(p,h)),H(p,o.shape)}}}},fL={kernelName:oo,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[n,s]=t,r=As(n,0);return{x:()=>Vn(r,e,L(e,s)),alpha:()=>{let a=Vn(r,et(e),L(e,n)),o=Xt(s.shape,e.shape);return o.length>0&&(a=ke(a,o)),H(a,s.shape)}}}},mL={kernelName:Wa,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=gt(n.shape,s.shape);return{a:()=>{let i=ge(e,me(s,"float32")),l=Xt(n.shape,r);return l.length>0?H(ke(i,l),n.shape):i},b:()=>{let i=L(e,me(n,"float32")),l=Xt(s.shape,r);l.length>0&&(i=H(ke(i,l),s.shape));let c=At(s);return Ot(ge(i,me(c,"float32")))}}}},gL={kernelName:Tu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,Ot(At(n)))}}},AL={kernelName:uo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,s=L(pl(n,6),Vd(n));return{x:()=>L(e,me(s,"float32"))}}},yL={kernelName:io,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,me(Vd(n),"float32"))}}},xL={kernelName:Li,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>H(e,n.shape)}}},bL={kernelName:lo,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[s]=t,r={dy:e,images:s};return{images:()=>W.runKernel(qh,r,n)}}},vL={kernelName:Nu,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[s]=t,r={dy:e,images:s};return{images:()=>W.runKernel(jh,r,n)}}},wL={kernelName:Bi,gradFunc:(e,t,n)=>{let{dims:s}=n,r=Xs(s,e.shape);return{x:()=>Fs(e,r)}}},kL={kernelName:Wi,gradFunc:e=>({x:()=>et(e)})},SL={kernelName:co,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Ot(ge(e,L(Po(n,1.5),2)))}}},IL={kernelName:Ui,inputsToSave:["condition"],gradFunc:(e,t)=>{let[n]=t;return{condition:()=>me(et(n),"float32"),t:()=>L(e,me(n,e.dtype)),e:()=>L(e,me(kf(n),e.dtype))}}},CL={kernelName:Eu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=As(n,Ie(0)),r=Ie(mw),a=Ie(gw),o=L(e,a),i=L(L(e,r),_s(me(n,"float32")));return Vn(s,o,i)}}}},TL={kernelName:ho,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,L(n,fe(Ie(1),n)))}}},NL={kernelName:Ru,gradFunc:e=>({x:()=>et(e)})},EL={kernelName:po,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(yf(me(n,"float32")),e)}}},RL={kernelName:Hi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(u1(me(n,"float32")),e)}}},$L={kernelName:Gi,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{begin:r,size:a}=n,o=s.shape,[i,l]=K3(s,r,a),c=[];for(let u=0;uJs(e,c)}}},_L={kernelName:go,outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s]=t,{dim:r}=n,a=!0,o=L(e,s);return{logits:()=>fe(o,L(ke(o,[r],a),s))}}},DL={kernelName:$u,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,ms(n))}}},Cw={kernelName:ji,gradFunc:(e,t,n)=>{let{blockShape:s,paddings:r}=n;return{x:()=>Af(e,s,r)}}},Tw={kernelName:qi,gradFunc:(e,t,n)=>{let{axis:s}=n;return{x:()=>wt(e,s)}}},PL={kernelName:fo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,L(Dn(me(n,"float32")),2))}}},FL={kernelName:_u,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,L(me(n,"float32"),2))}}},OL={kernelName:Ao,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=Ie(2);return{a:()=>L(e,L(r,fe(n,s))),b:()=>L(e,L(r,fe(s,n)))}}},ML={kernelName:vo,gradFunc:e=>({x:()=>et(e)})},zL={kernelName:yo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=gt(n.shape,s.shape);return{a:()=>{let i=e,l=Xt(n.shape,r);return l.length>0&&(i=ke(i,l)),H(i,n.shape)},b:()=>{let i=e,l=Xt(s.shape,r);return l.length>0&&(i=ke(i,l)),H(Ot(i),s.shape)}}}},LL={kernelName:mo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,r=s.shape.slice(),{axis:a}=n;Xs(a,s.shape).forEach(c=>{r[c]=1});let i=H(e,r),l=L(i,ys(s.shape,"float32"));return{x:()=>l}}},BL={kernelName:Ki,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,At(yf(n)))}}},WL={kernelName:xo,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(fe(Ie(1),At(n)),e)}}},VL={kernelName:Yr,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{reps:r}=n;return{x:()=>{let o=et(s);if(s.rank===1)for(let i=0;i{let s=n,{perm:r}=s,a=m1(r);return{x:()=>Qe(e,a)}}},GL={kernelName:Ji,gradFunc:(e,t,n)=>{let s=n,{axis:r}=s;return{value:()=>yn(e,r)}}},HL={kernelName:xd,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>jL(e,n)}}};function jL(e,t){let n=ea(t,et(t)),s=Uu(e,n),r=dl(t,Ie(0,"int32")),a=s.rank-r.rank;for(let i=0;i({x:()=>et(e)})},XL=[bw,XM,KM,ZM,YM,JM,QM,ez,tz,nz,sz,rz,iz,cz,dz,pz,hz,fz,mz,gz,Az,yz,bz,xz,kz,Sz,Iz,Cz,Tz,Nz,mL,Ez,Rz,$z,_z,Dz,Fz,Pz,Oz,Mz,zz,Lz,Bz,Wz,Vz,Uz,Gz,Hz,jz,Kz,Sw,Sw,Zz,Qz,nL,sL,rL,aL,oL,iL,lL,uL,cL,dL,pL,Iw,Iw,hL,fL,gL,AL,yL,xL,bL,vL,wL,kL,SL,IL,CL,TL,NL,EL,RL,$L,_L,DL,Cw,Cw,Tw,Tw,PL,OL,FL,ML,zL,LL,BL,WL,VL,UL,GL,HL,qL];for(let e of XL)s3(e);var Nw={};Oe(Nw,{maxNorm:()=>JL,minMaxNorm:()=>tB,nonNeg:()=>eB,unitNorm:()=>QL});var L1;function rn(){return L1==null&&(L1=Dr().epsilon()),L1}function mr(){return"channelsLast"}var sa=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,sa.prototype)}},gr=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,gr.prototype)}},j=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,j.prototype)}},Le=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Le.prototype)}},Ew=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Ew.prototype)}};function Al(e,t){if(Array.isArray(e)){let n=[];for(let s=0;sn.toUpperCase())}var er={};function B1(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function W1(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>W1(t));else{let t=Object.keys(e);for(let n of t){let s=e[n];s!=null&&typeof s=="object"&&(!Array.isArray(s)&&s.type==="ndarray"&&typeof s.value=="number"?e[n]=s.value:W1(s))}}}function Hd(e,t={},n={},s="object",r=!1){if(typeof e=="string"){let a=e,o;if(a in n)o=n[a];else if(a in er)o=er[a];else if(o=t[a],o==null)throw new j(`Unknown ${s}: ${e}. This may be due to one of the following reasons: 1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code. 2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return o}else{let a=e;if(a.className==null||a.config==null)throw new j(`${s}: Improper config format: ${JSON.stringify(a)}. 'className' and 'config' must set.`);let o=a.className,i,l;if(o in n?[i,l]=n[o]:o in er?[i,l]=er.className:o in t&&([i,l]=t[o]),i==null)throw new j(`Unknown ${s}: ${o}. This may be due to one of the following reasons: 1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code. 2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){let c={};for(let h of Object.keys(er))c[h]=er[h];for(let h of Object.keys(n))c[h]=n[h];let u=a.config;u.customObjects=c;let d={...er};for(let h of Object.keys(n))er[h]=n[h];W1(a.config);let p=l(i,a.config,n,r);return er={...d},p}else{let c={...er};for(let d of Object.keys(n))er[d]=n[d];let u=new i(a.config);return er={...c},u}}}function KL(e,t){return et?1:0}function Uf(e,t){return-1*KL(e,t)}function Mo(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function ZL(e){if(e==null)throw new j(`Invalid value in obj: ${JSON.stringify(e)}`);for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function xl(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new j(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function V1(e,t,n=0,s=1/0){return Mr(n>=0),Mr(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every(r=>typeof r===t)}function xn(e,t){Array.isArray(e)?(v.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,s)=>xn(n,`element ${s+1} of ${t}`))):v.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${$w(e)}.`)}function $w(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>$w(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function YL(e,t,n){let s=n!=null?n():v.now(),r;return(...o)=>{let i=n!=null?n():v.now();return i-sDn(ke(L(e,e),t,!0)))}var jd=class extends ce.Serializable{getConfig(){return{}}},G1=class extends jd{constructor(e){super();this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return X(()=>{let t=U1(e,this.axis),n=gs(t,0,this.maxValue);return L(e,ge(n,ue(rn(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};G1.className="MaxNorm";ce.registerClass(G1);var H1=class extends jd{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return X(()=>ge(e,ue(rn(),U1(e,this.axis))))}getConfig(){return{axis:this.axis}}};H1.className="UnitNorm";ce.registerClass(H1);var j1=class extends jd{apply(e){return Or(e)}};j1.className="NonNeg";ce.registerClass(j1);var q1=class extends jd{constructor(e){super();this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return X(()=>{let t=U1(e,this.axis),n=ue(L(this.rate,gs(t,this.minValue,this.maxValue)),L(1-this.rate,t));return L(e,ge(n,ue(rn(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};q1.className="MinMaxNorm";ce.registerClass(q1);var Dw={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function an(e){return B1(e)}function Pw(e,t={}){return Hd(e,ce.SerializationMap.getMap().classNameMap,t,"constraint")}function on(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in Dw?Dw[e]:e,config:{}};return Pw(n)}else return e instanceof jd?e:Pw(e)}function JL(e){return new G1(e)}function QL(e){return new H1(e)}function eB(){return new j1}function tB(e){return new q1(e)}var Fw={};Oe(Fw,{constant:()=>SB,glorotNormal:()=>$B,glorotUniform:()=>RB,heNormal:()=>_B,heUniform:()=>DB,identity:()=>NB,leCunNormal:()=>PB,leCunUniform:()=>FB,ones:()=>kB,orthogonal:()=>OB,randomNormal:()=>CB,randomUniform:()=>IB,truncatedNormal:()=>TB,varianceScaling:()=>EB,zeros:()=>wB});var nB=["channelsFirst","channelsLast"],sB=["nearest","bilinear"],rB=["valid","same","causal"],aB=["max","avg"],oB=["sum","mul","concat","ave"],Zu=new Map;function jt(e){xl(nB,"DataFormat",e)}function iB(e){xl(sB,"InterpolationFormat",e)}function Os(e){xl(rB,"PaddingMode",e)}function Ow(e){xl(aB,"PoolMode",e)}var qd=[],Mw="/";function bl(e,t){qd.push(e);try{let n=t();return qd.pop(),n}catch(n){throw qd.pop(),n}}function lB(){return qd.length===0?"":qd.join(Mw)+Mw}function zw(e){if(!Bw(e))throw new Error("Not a valid tensor name: '"+e+"'");return lB()+e}function Lw(e){if(!Bw(e))throw new Error("Not a valid tensor name: '"+e+"'");Zu.has(e)||Zu.set(e,0);let t=Zu.get(e);if(Zu.set(e,Zu.get(e)+1),t>0){let n=`${e}_${t}`;return Zu.set(n,1),n}else return e}var uB=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Bw(e){return!!e.match(uB)}function cB(e){return e===parseInt(e.toString(),10)}function zo(e,t,n){t==null&&(t=0),n==null&&(n=e.length);let s=1;for(let r=t;rt&&(t=s)}return t}function Ar(e,t){if(t{if(e.shape.length!==2)throw new j(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let n=Xd(e,1);return Z1(n,[1,t,1])})}function pB(e){let t=[zo(e.shape)];return H(e,t)}function hB(e){if(e.rank<=1)throw new j(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);let t=[e.shape[0],zo(e.shape,1)];return H(e,t)}function vl(e,t,n){return X(()=>{switch(e.rank){case 1:return Nf(e,t,n);case 2:return T1(e,[t,0],[n,e.shape[1]]);case 3:return fl(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return ml(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return Pe(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return Pe(e,[t,0,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new j(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function X1(e,t,n){return X(()=>{switch(e.rank){case 1:return Nf(e,t,n);case 2:return T1(e,[0,t],[e.shape[0],n]);case 3:return fl(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return ml(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new j(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Hf(e,t,n,s){return X(()=>{switch(e.rank){case 1:return Nf(e,t,n);case 2:switch(s){case 1:return vl(e,t,n);case 2:return X1(e,t,n);default:throw new j(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return vl(e,t,n);case 2:return fl(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return X1(e,t,n);default:throw new j(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return vl(e,t,n);case 2:return ml(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return ml(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return X1(e,t,n);default:throw new j(`The axis is not within the rank of the tensor ${s}`)}default:throw new j(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function K1(e,t=-1){let n;return t<0&&(n=e[0].rank,n!==0?t=n:t=0),t===e[0].rank&&(t=-1),wt(e,t)}function Ww(e,t){switch(e.rank){case 1:return xv([e,t]);case 2:return Wu([e,t],0);case 3:return bv([e,t],0);case 4:return vv([e,t],0);default:throw new j(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Z1(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new j(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Ys(e,t)}function jf(e,t=0,n=1,s,r){return Vv(e,t,n,s,r)}function zr(e,t,n,s){if(e.rank<2||t.rank<2)throw new Le(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){let r=e.shape.slice(-1)[0],a=t.shape.slice(-2)[0];if(r!==a)throw new Le(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and y shape = ${t.shape}`)}if(e.rank===2&&t.rank===2){let r=!1,a=!1;return Fo.matMul({a:e,b:t,transposeA:r,transposeB:a,bias:s?Y1(e.rank,s,mr()):null,activation:n})}else{let r=e.shape.slice(),a=r.pop();e=H(e,[-1,a]);let o=t.shape.slice(),i=o.pop(),l=o.pop(),c=[...o,i],u=Array.from({length:t.rank},(f,m)=>m===0?t.rank-2:m<=t.rank-2?m-1:m);t=H(Qe(t,u),[l,-1]);let d=[...r,...c],p=!1,h=!1;return H(Fo.matMul({a:e,b:t,transposeA:p,transposeB:h,bias:s?Y1(e.rank,s,mr()):null,activation:n}),d)}}function Vw(e,t,n){return X(()=>(Array.isArray(t)?t=Vt(t,"int32"):t=me(t,"int32"),Uu(e,t,n)))}function Kd(e){return L(e,e)}function Y1(e,t,n){let s=t.shape;if(t.rank!==1&&t.rank!==e)throw new j(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(n==="channelsFirst")return s.length===1?H(t,[1,s[0],1,1,1]):H(t,[1,s[3],s[0],s[1],s[2]]);if(n==="channelsLast")return s.length===1?H(t,[1,1,1,1,s[0]]):H(t,[1].concat(s))}else if(e===4){if(n==="channelsFirst")return s.length===1?H(t,[1,s[0],1,1]):H(t,[1,s[2],s[0],s[1]]);if(n==="channelsLast")return s.length===1?H(t,[1,1,1,s[0]]):H(t,[1].concat(s))}else if(e===3){if(n==="channelsFirst")return s.length===1?H(t,[1,s[0],1]):H(t,[1,s[1],s[0]]);if(n==="channelsLast")return s.length===1?H(t,[1,1,s[0]]):H(t,[1].concat(s))}else if(e<3)return t;throw new j(`Unsupported input rank by biasAdd: ${t.rank}`)}function yr(e,t,n){return X(()=>(n==null&&(n=mr()),jt(n),ue(e,Y1(e.rank,t,n))))}function fB(e,t=1){if(t!==1)throw new Le(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Od(e)}function mB(e){return X(()=>ge(e,ue(nn(e),1)))}function Uw(e,t,n,s){return X(()=>nw(e,t,n,s))}function gB(e){return X(()=>{let t=ue(.5,L(.2,e));return gs(t,0,1)})}function Zd(e,t,n=!1){return n?e():t()}var AB=["fanIn","fanOut","fanAvg"],yB=["normal","uniform","truncatedNormal"];function xB(e){xl(AB,"FanMode",e)}function bB(e){xl(yB,"Distribution",e)}var tr=class extends ce.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},J1=class extends tr{apply(e,t){return Ht(e,t)}};J1.className="Zeros";ce.registerClass(J1);var qf=class extends tr{apply(e,t){return ys(e,t)}};qf.className="Ones";ce.registerClass(qf);var Q1=class extends tr{constructor(e){super();if(typeof e!="object")throw new j(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new j(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return X(()=>L(Ie(this.value),ys(e,t)))}getConfig(){return{value:this.value}}};Q1.className="Constant";ce.registerClass(Q1);var eA=class extends tr{constructor(e){super();this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return ju(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};eA.className="RandomUniform";ce.registerClass(eA);var tA=class extends tr{constructor(e){super();this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Le(`randomNormal does not support dType ${t}.`);return jf(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};tA.className="RandomNormal";ce.registerClass(tA);var nA=class extends tr{constructor(e){super();this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Le(`truncatedNormal does not support dType ${t}.`);return $f(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};nA.className="TruncatedNormal";ce.registerClass(nA);var sA=class extends tr{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return X(()=>{if(e.length!==2||e[0]!==e[1])throw new j("Identity matrix initializer can only be used for 2D square matrices.");return L(this.gain,d1(e[0]))})}getConfig(){return{gain:this.gain}}};sA.className="Identity";ce.registerClass(sA);function vB(e,t="channelsLast"){let n,s;if(jt(t),e.length===2)n=e[0],s=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let r=zo(e,2);n=e[1]*r,s=e[0]*r}else if(t==="channelsLast"){let r=zo(e,0,e.length-2);n=e[e.length-2]*r,s=e[e.length-1]*r}}else{let r=zo(e);n=Math.sqrt(r),s=Math.sqrt(r)}return[n,s]}var ls=class extends tr{constructor(e){super();if(e.scale<0)throw new j(`scale must be a positive float. Got: ${e.scale}`);this.scale=e.scale==null?1:e.scale,this.mode=e.mode==null?"fanIn":e.mode,xB(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,bB(this.distribution),this.seed=e.seed}apply(e,t){let n=vB(e),s=n[0],r=n[1],a=this.scale;if(this.mode==="fanIn"?a/=Math.max(1,s):this.mode==="fanOut"?a/=Math.max(1,r):a/=Math.max(1,(s+r)/2),this.distribution==="normal"){let o=Math.sqrt(a);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Le(`${this.getClassName()} does not support dType ${t}.`);return $f(e,0,o,t,this.seed)}else{let o=Math.sqrt(3*a);return ju(e,-o,o,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};ls.className="VarianceScaling";ce.registerClass(ls);var Xf=class extends ls{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ls.className}};Xf.className="GlorotUniform";ce.registerClass(Xf);var Kf=class extends ls{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ls.className}};Kf.className="GlorotNormal";ce.registerClass(Kf);var Zf=class extends ls{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ls.className}};Zf.className="HeNormal";ce.registerClass(Zf);var Yf=class extends ls{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ls.className}};Yf.className="HeUniform";ce.registerClass(Yf);var Jf=class extends ls{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ls.className}};Jf.className="LeCunNormal";ce.registerClass(Jf);var Qf=class extends ls{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ls.className}};Qf.className="LeCunNormal";ce.registerClass(Qf);var rA=class extends tr{constructor(e){super();if(this.DEFAULT_GAIN=1,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,this.seed!=null)throw new Le("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return X(()=>{if(e.length<2)throw new Le("Shape must be at least 2D.");e[0]*e[1]>2e3&&console.warn(`Orthogonal initializer is being called on a matrix with more than 2000 (${e[0]*e[1]}) elements: Slowness may result.`);let n=e[0]>e[1]?[e[1],e[0]]:e,s=jf(n,0,1,"float32"),r=hw.gramSchmidt(s);return e[0]>e[1]&&(r=Qe(r)),L(this.gain,r)})}getConfig(){return{gain:this.gain,seed:this.seed}}};rA.className="Orthogonal";ce.registerClass(rA);var Gw={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function Hw(e,t={}){return Hd(e,ce.SerializationMap.getMap().classNameMap,t,"initializer")}function Mt(e){return B1(e)}function Rt(e){if(typeof e=="string"){let t=e in Gw?Gw[e]:e;if(t==="GlorotNormal")return new Kf;if(t==="GlorotUniform")return new Xf;if(t==="HeNormal")return new Zf;if(t==="HeUniform")return new Yf;if(t==="LeCunNormal")return new Jf;if(t==="LeCunUniform")return new Qf;{let n={};return n.className=t,n.config={},Hw(n)}}else return e instanceof tr?e:Hw(e)}function wB(){return new J1}function kB(){return new qf}function SB(e){return new Q1(e)}function IB(e){return new eA(e)}function CB(e){return new tA(e)}function TB(e){return new nA(e)}function NB(e){return new sA(e)}function EB(e){return new ls(e)}function RB(e){return new Xf(e)}function $B(e){return new Kf(e)}function _B(e){return new Zf(e)}function DB(e){return new Yf(e)}function PB(e){return new Jf(e)}function FB(e){return new Qf(e)}function OB(e){return new rA(e)}var jw={};Oe(jw,{Layer:()=>tt,RNN:()=>oa,RNNCell:()=>sp,activation:()=>AV,add:()=>CV,alphaDropout:()=>uU,average:()=>TV,averagePooling1d:()=>Iy,averagePooling2d:()=>Cy,averagePooling3d:()=>Ty,avgPool1d:()=>OV,avgPool2d:()=>zV,avgPool3d:()=>BV,avgPooling1d:()=>MV,avgPooling2d:()=>LV,avgPooling3d:()=>WV,batchNormalization:()=>DV,bidirectional:()=>tU,concatenate:()=>NV,conv1d:()=>lV,conv2d:()=>uV,conv2dTranspose:()=>cV,conv3d:()=>dV,conv3dTranspose:()=>pV,convLstm2d:()=>YV,convLstm2dCell:()=>JV,cropping2D:()=>fV,dense:()=>yV,depthwiseConv2d:()=>gV,dot:()=>_V,dropout:()=>xV,elu:()=>nV,embedding:()=>IV,flatten:()=>vV,gaussianDropout:()=>lU,gaussianNoise:()=>iU,globalAveragePooling1d:()=>VV,globalAveragePooling2d:()=>UV,globalMaxPool1d:()=>sU,globalMaxPool2d:()=>rU,globalMaxPooling1d:()=>a7,globalMaxPooling2d:()=>o7,gru:()=>HV,gruCell:()=>jV,input:()=>Ik,inputLayer:()=>tV,layerNormalization:()=>PV,leakyReLU:()=>rV,lstm:()=>qV,lstmCell:()=>XV,masking:()=>cU,maxPool1d:()=>aU,maxPool2d:()=>oU,maxPooling1d:()=>i7,maxPooling2d:()=>l7,maxPooling3d:()=>GV,maximum:()=>EV,minimum:()=>RV,multiply:()=>$V,permute:()=>SV,prelu:()=>aV,reLU:()=>sV,repeatVector:()=>wV,reshape:()=>kV,rnn:()=>QV,separableConv2d:()=>hV,simpleRNN:()=>KV,simpleRNNCell:()=>ZV,softmax:()=>oV,spatialDropout1d:()=>bV,stackedRNNCells:()=>eU,thresholdedReLU:()=>iV,timeDistributed:()=>nU,upSampling2d:()=>mV,zeroPadding2d:()=>FV});var MB=0;function qw(){return MB++}var em={};function tm(e=""){return e in em||(em[e]=0),em[e]+=1,e+em[e].toString()}function aA(e){return Array.isArray(e)&&Array.isArray(e[0])}function nm(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Ve(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new j(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function ht(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new j(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function sm(e){let t=0;for(let n of e)n.shape.length===0?t+=1:t+=n.shape.reduce((s,r)=>s*r);return t}var Xw="Variable",Kw=class{constructor(e,t="float32",n=Xw,s=!0,r=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=qw(),n=n==null?Xw:n,this.originalName=zw(n),this.name=Lw(this.originalName),this.trainable_=s,this.constraint=r,this.val=Yv(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),zB(this.val,e),this.val.id!==e.id&&(this.val.assign(e),this.constraint!=null&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}};function zB(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function oA(e){return e.map(t=>t.read())}function iA(e){e.forEach(t=>{t[0].write(t[1])})}var Zt=class{constructor(e){this.dtype=e.dtype,this.shape=e.shape,e.shape!=null?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}},xr=class{constructor(e,t,n,s,r,a,o){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=s,this.callArgs=r,this.outputTensorIndex=o,this.id=qw(),a!=null&&(this.originalName=zw(a),this.name=Lw(this.originalName)),this.rank=t.length}},LB=0,rm=class{constructor(e,t){this.callArgs=t,this.id=LB++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(let n of e.inboundLayers)n!=null&&n.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){let e=[];for(let t of this.inboundLayers)t!=null?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}},BB=0,tt=class extends ce.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=BB++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){let n=this.getClassName();t=ra(n)+"_"+tm(n)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let n;if(e.batchInputShape!=null)n=e.batchInputShape;else if(e.inputShape!=null){let r=null;e.batchSize!=null&&(r=e.batchSize),n=[r].concat(e.inputShape)}this.batchInputShape=n;let s=e.dtype;s==null&&(s=e.inputDType),s==null&&(s="float32"),this.dtype=s}e.weights!=null?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(this.inboundNodes.length===0)throw new gr(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new j(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return is(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return is(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new sa(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(this.inboundNodes.length===0)throw new sa(`Layer ${this.name} is not connected, no input to return.`);return is(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new sa(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new sa(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return is(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(e=>e())}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach(t=>t.trainable=e),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(e=>e.trainable):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(e=>!e.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){if(e=St(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=St(this.inputSpec);if(e.length!==t.length)throw new j(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;nr.maxNDim)throw new j(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${r.maxNDim}, found ndim=${a}`);if(r.minNDim!=null&&a=0?o[l]:o[o.length+l];if(c!=null&&[c,null].indexOf(u)===-1)throw new j(`Input ${n} is incompatible with layer ${this.name}: expected axis ${l} of input shape to have value ${c} but got shape ${o}.`)}}if(r.shape!=null)for(let o=0;o{if(!this.built){this.assertInputCompatibility(e);let a=[];for(let o of St(e))a.push(o.shape);this.build(is(a)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&r&&(this._refCount=1)}if(this.assertInputCompatibility(e),r){let a=this.call(e,t),o=St(a),i=[];for(let l of o)n.indexOf(l)!==-1&&(l=l.clone()),i.push(l);if(a=is(i),this.activityRegularizer!=null)throw new Le("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}else{let a=WB(e),o=this.computeOutputShape(a),i,l=VB(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?a[0]:a),o!=null&&o.length>0&&Array.isArray(o[0])?i=o.map((c,u)=>new xr(l,c,this,St(e),t,this.name,u)):i=new xr(l,o,this,St(e),t,this.name),this.addInboundNode(e,i,null,null,a,o,t),this._refCount++,this.activityRegularizer!=null)throw new Le("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape!=null)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach((n,s)=>{n!=null&&e[s]!=null&&e[s]!==n&&(t=!0)}),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new sa(`The layer ${this.name} has never been called and thus has no defined output shape.`);let e=[];for(let t of this.inboundNodes){let n=JSON.stringify(t.outputShapes);e.indexOf(n)===-1&&e.push(n)}if(e.length===1){let t=this.inboundNodes[0].outputShapes;return Array.isArray(t)&&Array.isArray(t[0])&&t.length===1?t[0]:t}else throw new sa(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new gr(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return sm(this.weights)}build(e){this.built=!0}getWeights(e=!1){return oA(e?this.trainableWeights:this.weights)}setWeights(e){X(()=>{let t=this.weights;if(t.length!==e.length)throw new j(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(t.length===0)return;let n=[],s=oA(t);for(let r=0;rr.apply(c.read())),a==null&&(a=!0),a?this._trainableWeights.push(c):this._nonTrainableWeights.push(c),c}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=St(e),this._losses!==void 0&&this._losses!==null&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(t!=null)if(Array.isArray(t))t.forEach(n=>{if(n!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)});else throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);return null}return t}addInboundNode(e,t,n,s,r,a,o=null){let i=St(e);t=St(t),n=St(n),s=St(s),r=nm(r),a=nm(a);let l=[],c=[],u=[];for(let d of i)l.push(d.sourceLayer),c.push(d.nodeIndex),u.push(d.tensorIndex);new rm({outboundLayer:this,inboundLayers:l,nodeIndices:c,tensorIndices:u,inputTensors:i,outputTensors:t,inputMasks:n,outputMasks:s,inputShapes:r,outputShapes:a},o);for(let d=0;de.dispose()),this.weights.length}assertNotDisposed(){if(this._refCount===0)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(this._refCount===null)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return--this._refCount==0&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}};function WB(e){e=St(e);let t=[];for(let n of e)t.push(n.shape);return is(t)}function VB(e){return"float32"}function Zw(e,t,n){if((t==null||n!=null&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),t.inboundNodes.length===0)return[e];{let s=t.inboundNodes[n];if(s.inboundLayers.length===0)return s.inputTensors;{let r=[];for(let a=0;a0){let r=await Promise.all(t);for(let a=0;aue(this.totals[s],L(r,n)));this.totals[s]=o,a!=null&&a.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(let n of this.params.metrics)this.totals[n]!=null&&(typeof this.totals[n]=="number"?t[n]=this.totals[n]/this.seen:X(()=>{let s=L(ge(1,this.seen),this.totals[n]);t[n]=s,this.totals[n].dispose(),gn(t[n])}))}},tk=class extends Qu{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(let n in t)this.history[n]==null&&(this.history[n]=[]),this.history[n].push(t[n])}async syncData(){let e=[],t=[],n=[];for(let r in this.history){let a=this.history[r];for(let o=0;onew nk(s,t))}var Lr=class{constructor(){}static registerCallbackConstructor(e,t){v.assert(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),Lr.checkForDuplicate(t),Lr.constructors[e]==null&&(Lr.constructors[e]=[]),Lr.constructors[e].push(t)}static checkForDuplicate(e){for(let t in Lr.constructors)Lr.constructors[+t].forEach(s=>{if(s===e)throw new j("Duplicate callback constructor.")})}static clear(){Lr.constructors={}}static createCallbacks(e){let t=[];for(let n in Lr.constructors){let s=+n;e>=s&&t.push(...Lr.constructors[s])}return t.map(n=>new n)}},lA=Lr;lA.constructors={};function rk(e,t,n,s,r,a,o,i,l){let c=new tk,u=[new GB,...lA.createCallbacks(t)];e!=null&&u.push(...e),u.push(c);let d=new ek(u);return d.setParams({epochs:n,initialEpoch:s,samples:r,steps:a,batchSize:o,verbose:t,doValidation:i,metrics:l}),{callbackList:d,history:c}}function br(e,t={},n=!1){return Hd(e,ce.SerializationMap.getMap().classNameMap,t,"layer",n)}function am(e,t){return X(()=>{e.dtype!=="float32"&&(e=me(e,"float32"));let n=ke(Kd(e),t,!0),s=Vu(n.shape,rn()),r=Dn(ea(n,s));return ge(e,r)})}function wl(e,t){return X(()=>Wt(Kd(fe(t,e)),-1))}function om(e,t){return X(()=>Wt(nn(fe(t,e)),-1))}function ec(e,t){return X(()=>{let n=fe(e,t),s=gs(nn(e),rn(),Number.MAX_VALUE),r=nn(ge(n,s));return L(100,Wt(r,-1))})}function HB(e,t){return X(()=>{let n=gs(t,rn(),Number.MAX_VALUE),s=Ds(ue(1,n)),r=gs(e,rn(),Number.MAX_VALUE),a=Ds(ue(1,r));return Wt(Kd(fe(s,a)),-1)})}function jB(e,t){return X(()=>{let n=ea(0,fe(1,L(e,t)));return Wt(Kd(n),-1)})}function qB(e,t){return X(()=>{let n=ea(0,fe(1,L(e,t)));return Wt(n,-1)})}function XB(e,t){return X(()=>{let n=ke(L(e,t),-1),s=An(L(fe(1,e),t),-1);return ea(0,ue(1,fe(s,n)))})}function KB(e,t){return X(()=>{let n=Math.log(2),s=fe(t,e),r=fe(ue(s,Gu(L(-2,s))),n);return Wt(r,-1)})}function Yd(e,t,n=!1){return X(()=>{if(n)t=Xu(t);else{let s=ke(t,t.shape.length-1,!0);t=ge(t,s)}return t=gs(t,rn(),1-rn()),Ot(ke(L(me(e,"float32"),Ds(t)),t.shape.length-1))})}function im(e,t,n=!1){return X(()=>{let s=me(Md(pB(e)),"int32");t=gs(t,rn(),1-rn());let r=t.shape,a=H(_d(s,r[r.length-1]),r);return Yd(a,t,n)})}function ZB(e,t){if(!v.arraysEqual(e.shape,t.shape))throw new j(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return X(()=>{let n=Or(t),s=Ot(nn(t));return ue(fe(n,L(t,e)),vf(_s(s)))})}function lm(e,t){return X(()=>{let n;return n=gs(t,rn(),1-rn()),n=Ds(ge(n,fe(1,n))),Wt(ZB(e,n),-1)})}function YB(e,t){return X(()=>{let n=gs(e,rn(),1),s=gs(t,rn(),1);return ke(L(e,Ds(ge(n,s))),-1)})}function JB(e,t){return X(()=>{let n=Ds(ue(rn(),t));return Wt(fe(t,L(e,n)),-1)})}function uA(e,t){return X(()=>{let n=am(e,-1),s=am(t,-1),r=L(n,s);return Ot(ke(r,-1))})}var um={meanSquaredError:wl,meanAbsoluteError:om,meanAbsolutePercentageError:ec,meanSquaredLogarithmicError:HB,squaredHinge:jB,hinge:qB,categoricalHinge:XB,logcosh:KB,categoricalCrossentropy:Yd,sparseCategoricalCrossentropy:im,binaryCrossentropy:lm,kullbackLeiblerDivergence:YB,poisson:JB,cosineProximity:uA};function cA(e){if(typeof e=="string"){if(e in um)return um[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new j(t)}else return e}function dA(e,t){return X(()=>{let n=L(.5,Ps(t)),s=Gf(As(t,n),e.dtype);return Wt($s(e,s),-1)})}function pA(e,t){return X(()=>Gf($s(Zs(e,-1),Zs(t,-1)),"float32"))}function ak(e,t){return X(()=>me(ke(hr($s(e,1),$s(t,1))),"float32"))}function QB(e,t){return X(()=>me(ke(hr($s(e,1),$s(t,0))),"float32"))}function eW(e,t){return X(()=>me(ke(hr($s(e,0),$s(t,1))),"float32"))}function ok(e,t){return X(()=>{let n=ak(e,t),s=eW(e,t),r=ue(n,s);return me(Vn(As(r,0),ge(n,r),0),"float32")})}function tW(e,t){return X(()=>{let n=ak(e,t),s=QB(e,t),r=ue(n,s);return me(Vn(As(r,0),ge(n,r),0),"float32")})}function ik(e,t){return lm(e,t)}function lk(e,t){return e.rank===t.rank&&(e=ot(e,[e.rank-1])),t=Zs(t,-1),t.dtype!==e.dtype&&(t=me(t,e.dtype)),me($s(e,t),"float32")}var nW=wl,sW=wl,rW=om,aW=om,oW=ec,iW=ec,hA=Yd,lW=uA,uk=im,cm={binaryAccuracy:dA,categoricalAccuracy:pA,precision:ok,categoricalCrossentropy:hA,sparseCategoricalCrossentropy:uk,mse:nW,MSE:sW,mae:rW,MAE:aW,mape:oW,MAPE:iW,cosine:lW};function uW(e){if(typeof e=="string"&&e in cm)return cm[e];if(typeof e!="string"&&e!=null)return e;throw new j(`Unknown metric ${e}`)}function dm(e){if(Mr(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let n of Object.keys(um))if(um[n]===e){t=n;break}if(t!==void 0)return t;for(let n of Object.keys(cm))if(cm[n]===e){t=n;break}return t!==void 0?t:e.name}}function cW(e){let t={Adagrad:()=>gl.adagrad(.01),Adadelta:()=>gl.adadelta(1,.95,rn()),Adam:()=>gl.adam(.001,.9,.999,rn()),Adamax:()=>gl.adamax(.002,.9,.999,rn(),0),RMSProp:()=>gl.rmsprop(.001,.9,0,rn()),SGD:()=>gl.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new j(`Unknown Optimizer ${e}`)}var ck=1*1024*1024;function dk(e,t,n=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!fA(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){let s=JSON.stringify(e);s.length>ck&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${s.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${ck}.`)}}function fA(e){if(e===null)return!0;if(typeof e=="object")if(Object.getPrototypeOf(e)===Object.prototype){let t=Object.keys(e);for(let n of t)if(typeof n!="string"||!fA(e[n]))return!1;return!0}else if(Array.isArray(e)){for(let t of e)if(!fA(t))return!1;return!0}else return!1;else{let t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function dW(e,t,n,s=console.log){let r=hW(e),a=["Layer (type)","Output shape","Param #"];r?(t=t||65,n=n||[.45,.85,1]):(t=t||98,n=n||[.33,.55,.67,1]),n[n.length-1]<=1&&(n=n.map(u=>Math.floor(t*u)));let o;if(!r){a.push("Receives inputs"),o=[];for(let u in e.nodesByDepth)o.push(...e.nodesByDepth[u])}s("_".repeat(t)),pm(a,n,s),s("=".repeat(t));let i=e.layers;for(let u=0;u1||r.length===1&&r[0].inboundLayers.length>1){t=!1;break}s.push(...r)}if(t)for(let r of e.layers){let a=!1;for(let o of r.inboundNodes)if(s.indexOf(o)!==-1)if(a){t=!1;break}else a=!0;if(!t)break}return t}function pm(e,t,n=console.log){let s="";for(let r=0;r0&&(s=s.slice(0,s.length-1)+" "),s+=e[r],s=s.slice(0,t[r]),s+=" ".repeat(t[r]-s.length);n(s)}function fW(e,t,n){let s;try{s=JSON.stringify(e.outputShape)}catch(i){s="multiple"}let r=e.name,a=e.getClassName(),o=[`${r} (${a})`,s,e.countParams().toString()];pm(o,t,n)}function mW(e,t,n,s){let r;try{r=JSON.stringify(e.outputShape)}catch(u){r="multiple"}let a=[];for(let u of e.inboundNodes)if(!(n!=null&&n.length>0&&n.indexOf(u)===-1))for(let d=0;df.name),l=[],c=t.names();for(let f of i)c.indexOf(f)!==-1?l.push(t.getValue(f)):l.push(null);s!=null&&(s.maxNumTensors=-1/0,s.minNumTensors=1/0);let u=i.join(",")+"|"+t.names().join(","),d,p;if(AA[u]==null){let f=AW(o,t);d=f.sorted,p=f.recipientCounts,AA[u]=d,hk[u]=p}d=AA[u],p={},r||Object.assign(p,hk[u]);let h=new kl(t);for(let f=0;fs.maxNumTensors&&(s.maxNumTensors=R),R0,()=>"Expected at least one fetch, got none");let n=[],s={};if(e.length===1){let r=fk(e[0],t);n=r.sorted,s=r.recipientMap}else{let r=new Set;for(let a of e){let{sorted:o,recipientMap:i}=fk(a,t);for(let l of o)r.has(l.name)||(n.push(l),r.add(l.name));for(let l in i)s[l]==null&&(s[l]=new Set),i[l].forEach(c=>s[l].add(c))}}return{sorted:n,recipientCounts:yW(s)}}function yW(e){let t={};for(let n in e)t[n]=e[n].size;return t}function fk(e,t){let n=new Set,s=[],r={};for(let i of t.names())n.add(i);let a=[],o=[];for(a.push(e);a.length>0;){let i=a[a.length-1];if(n.has(i.name)){a.pop();continue}let l=o[o.length-1]===a.length-1;if(i.inputs.length===0||l)a.pop(),s.push(i),n.add(i.name),l&&o.pop();else{o.push(a.length-1);for(let c of i.inputs)r[c.name]==null&&(r[c.name]=new Set),r[c.name].add(i.name),!n.has(c.name)&&a.push(c)}}return{sorted:s,recipientMap:r}}function xW(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let n=null;for(let s=0;sA.name)}`);Mo(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(A=>A.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(let A of this.outputs){let x=A.sourceLayer,y=A.nodeIndex,b=A.tensorIndex;this.outputLayers.push(x),this.outputLayersNodeIndices.push(y),this.outputLayersTensorIndices.push(b)}for(let A of this.inputs){let x=A.sourceLayer,y=A.nodeIndex,b=A.tensorIndex;Mr(y===0,"input layer has >1 nodes"),Mr(b===0,"input layer has >1 tensors"),this.inputLayers.push(x),this.inputLayersNodeIndices.push(y),this.inputLayersTensorIndices.push(b)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let A=0;AA.shape),this.internalOutputShapes=this.outputs.map(A=>A.shape);let t={},n={},s={},r={},a={},o=[],i=(A,x,y,b,w,k)=>{(b==null||w==null||k==null)&&(b=A.sourceLayer,w=A.nodeIndex,k=A.tensorIndex);let I=b.inboundNodes[w];if(y.indexOf(I)!==-1)throw new gr(`The tensor ${A.name} at layer "${b.name}" is part of a cycle.`);if(x.indexOf(I)!==-1)return;this.containerNodes.add(Br.nodeKey(b,w)),b.id in a||(a[b.id]=Object.keys(a).length),y.indexOf(I)===-1&&y.push(I);let N=I.inboundLayers.length;for(let R=0;R=0;)y.splice(y.indexOf(I),1);o.push(I)},l=[],c=[];for(let A of this.outputs)i(A,l,c);let u=o.slice().reverse();for(let A of u){n[A.id]=A,A.id in t||(t[A.id]=0);let x=t[A.id],y=s[A.outboundLayer.id]==null?0:s[A.outboundLayer.id];x=Math.max(x,y),s[A.outboundLayer.id]=x,r[A.outboundLayer.id]=A.outboundLayer,t[A.id]=x;for(let b=0;bparseInt(A,10)).sort(Uf);this.layers=[];for(let A of h){let x=p[A];x.sort((y,b)=>{let w=a[y.id],k=a[b.id];return wk?1:0});for(let y of x)y instanceof Br&&this.internalContainerRefs.push(y),this.layers.push(y)}this.layersByDepth=p,h=Object.keys(d).map(A=>parseInt(A,10)).sort(Uf);let f=this.inputs.slice(),m=[];for(let A of h)for(let x of d[A]){let y=x.outboundLayer;if(y!=null){for(let b of x.inputTensors)if(f.indexOf(b)===-1)throw new gr(`Graph disconnected: cannot obtain value for tensor ${b} at layer "${y.name}". The following previous layers were accessed without issue: ${m}`);for(let b of x.outputTensors)f.push(b);m.push(y.name)}}this.nodesByDepth=d;let g=this.layers.map(A=>A.name);for(let A of g){let x=g.filter(y=>y===A).length;if(x!==1)throw new gr(`The name "${A}" is used ${x} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new rm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(A=>null),outputMasks:this.outputs.map(A=>null),inputShapes:this.inputs.map(A=>A.shape),outputShapes:this.outputs.map(A=>A.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();let e={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount==0){for(let t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(let t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach(t=>{t._trainableWeights.forEach(n=>n.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new j("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(let t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.layers)t.push(...n.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){let n={},s=0;for(let a of this.layers)for(let o of a.weights){if(n[o.originalName]!=null)throw new j(`Duplicate weight name: ${o.originalName}`);n[o.originalName]=o,s++}let r=[];for(let a in e){let o=a;if(n[a]==null){let i=a.split("/");o=i.slice(0,-2).concat([i[i.length-1]]).join("/")}if(n[o]!=null)r.push([n[o],e[a]]);else if(t)throw new j(`Provided weight data has no target variable: ${a}`);delete n[o]}if(t){let a=[];for(let o in n)a.push(o);if(a.length>0)throw new j(`${a.length} of ${s} weights are not set: ${a}`)}iA(r)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${gA}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let n=mA(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return X(()=>{e=St(e);let n=new kl;for(let s=0;s{e=St(e);let n;return t==null?n=Al(null,e.length):n=St(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){let t=nm(e);if(t.length!==this.inputLayers.length)throw new j(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let n={};for(let o=0;oparseInt(o,10)).sort(Uf);if(s.length>1)for(let o of s){let i=this.nodesByDepth[o];for(let l of i){let c=l.outboundLayer;if(this.inputLayers.map(f=>f.id).indexOf(c.id)!==-1)continue;let u=[];for(let f=0;fparseInt(i,10)).sort(Uf);for(let i of s){let l=this.nodesByDepth[i];for(let c of l){let u=c.outboundLayer,d=c.inputTensors,p=c.outputTensors,h=new Array;for(let f of d)f.id in n&&h.push(n[f.id]);if(h.length===d.length){let f={},m,g,A,x;if(c.callArgs!=null&&(f=c.callArgs),h.length===1){let[y,b]=h[0];f.mask==null&&(f.mask=b),A=St(u.call(y,f)),x=St(u.computeMask(y,b)),m=[y],g=[b]}else m=h.map(y=>y[0]),g=h.map(y=>y[1]),f.mask==null&&(f.mask=g),A=St(u.call(m,f)),x=St(u.computeMask(m,g));if(u.activityRegularizer)throw new Le("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let y=0;y{let e=[];for(let t of this.layers)for(let n=0;n0){let f=[];for(let m=0;m0&&m.apply(is(A),x)}function l(m){let g=m.name,A=br(m,t.customObjects!=null?t.customObjects:{});A.setFastWeightInitDuringBuild(s),r[g]=A,m.inboundNodes.forEach(y=>{if(!(y instanceof Array))throw new j(`Corrupted configuration, expected array for nodeData: ${y}`);o(A,y)})}let c=t.name,u=t.layers;for(let m of u)l(m);for(;!ZL(a);)for(let m of u){let g=r[m.name];if(g.name in a){let A=a[g.name];delete a[g.name];for(let x of A)i(g,x)}}let d=[],p=[],h=t.inputLayers;for(let m of h){let g=m[0],A=m[1],x=m[2];Mr(g in r);let b=r[g].inboundNodes[A].outputTensors;d.push(b[x])}let f=t.outputLayers;for(let m of f){let g=m[0],A=m[1],x=m[2];Mr(g in r);let b=r[g].inboundNodes[A].outputTensors;p.push(b[x])}return new e({inputs:d,outputs:p,name:c})}get stateful(){if(this._stateful)throw new j("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(let e of this.layers)if(e.stateful)return!0;return!1}resetStates(){X(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}};function bW(e,t,n){let s=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(r=>null);if(s===1)return Array.isArray(e)&&e.length===1?e:typeof e=="object"&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==s)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);return e}else if(typeof e=="object"&&Object.keys(e).length>0&&typeof e[Object.keys(e)[0]]=="object"){let r=[];return t.forEach(a=>{a in e?r.push(e[a]):r.push(null)}),r}else throw new Error(`The model has multiple (${s}) outputs, so ${n} must be either an array with ${s} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}function mk(e,t){return bW(e,t,"classWeight")}async function gk(e,t,n,s){if(t!=null||s!=null)throw new Error("Support sampleWeight is not implemented yet");if(n!=null){let r=X(()=>{if(e.shape.length===1)return Wn(e);if(e.shape.length===2){if(e.shape[1]>1)return Zs(e,1);if(e.shape[1]===1)return H(e,[e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),a=Array.from(await r.data());te(r);let o=[];return a.forEach(i=>{if(n[i]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${i} exists in the data but not in classWeight`);o.push(n[i])}),Vt(o,"float32")}else return null}function vW(e,t){return L(e,t)}var wW=32;function Ak(e,t){let n,s,r=t;n=r.xs,s=r.ys,v.assert(n!=null&&s!=null,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`);let a=yk("input",e.inputNames,n),o=yk("output",e.outputNames,s),i=a[0].shape[0];v.assert(a.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${a.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`),v.assert(o.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${o.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let l=0;l`Batch size mismatch: input ${e.inputNames[l]} has ${a[l].shape[0]}; expected ${i} based on input ${e.inputNames[0]}.`);for(let l=0;l`Batch size mismatch: output ${e.outputNames[l]} has ${o[l].shape[0]}; expected ${i} based on input ${e.inputNames[0]}.`);return{xs:a,ys:o}}function yk(e,t,n){if(n instanceof Je)return[n];if(Array.isArray(n))return v.assert(n.length===t.length,()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),n;{let s=[];for(let r of t){if(n[r]==null)throw new j(`The feature data generated by the dataset lacks the required ${e} key '${r}'.`);s.push(n[r])}return s}}function kW(e){if(e.length===3)throw new Le("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function SW(e,t,n){let s=n.batchesPerEpoch!=null;if(v.assert(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),v.assert(n!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),v.assert(n.epochs!=null&&n.epochs>0&&Number.isInteger(n.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`),v.assert(!s||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`),v.assert(n.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{let r=n.validationData!=null,a,o;if(r)if(xk(n.validationData))v.assert(n.validationBatches==null||n.validationBatches>0&&Number.isInteger(n.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`);else{let g=kW(n.validationData);a=g.xs,o=g.ys}let i=e.makeTrainFunction(),l=e.getDedupedMetricsNames(),c;r?c=l.slice().concat(l.map(g=>"val_"+g)):c=l.slice();let u=sk(n.callbacks,n.yieldEvery),d=n.verbose==null?1:n.verbose,{callbackList:p,history:h}=rk(u,d,n.epochs,null,null,IW(t,n),null,r,c);p.setModel(e),e.history=h,await p.onTrainBegin(),e.stopTraining_=!1;let f=n.initialEpoch==null?0:n.initialEpoch,m=await t.iterator();for(;f=n.batchesPerEpoch:y.done){if(r){let b;xk(n.validationData)?b=St(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):b=St(e.evaluate(a,o,{batchSize:n.validationBatchSize==null?wW:n.validationBatchSize,verbose:0}));for(let w=0;w0)throw new Le("Verbose mode is not implemented yet.");v.assert(!s||n.batches>0&&Number.isInteger(n.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`);let o=CW(t)?t:await t.iterator(),i=0,l=0;for(;s?l{if(c.value){let{xs:u,ys:d}=Ak(e,c.value),p=u.concat(d),h=X(()=>r(p));if(te(p),l===0)for(let m=0;mue(a[m],L(f,g))),l>0&&te(A)}te(h),i+=f,++l}return a}),c.done){s&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let c=0;c0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function ep(e,t,n){return e==null?[null]:Array.isArray(e)?e.map(s=>vl(s,t,n-t)):vl(e,t,n-t)}function xA(e,t){return X(()=>e==null?null:Array.isArray(e)?e.map(n=>xA(n,t)):Vw(e,t.dtype==="int32"?t:me(t,"int32")))}function bA(e,t){let n=[],s=0,r=null;for(;s=e&&(r=e),n.push([s,r]),s=r;return n}async function NW(e,t,n,s,r,a,o,i,l,c,u,d,p,h,f){r==null&&(r=32),a==null&&(a=1),u==null&&(u=!0),p==null&&(p=0);let m=!1;if(l!=null&&c!=null&&(m=!0),f!=null&&(m=!0,h==null))throw new j("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let g=e.checkNumSamples(n,r,h,"steps_per_epoch"),A;g!=null&&(A=Ar(0,g)),o==null&&(o=1);let{callbackList:x,history:y}=rk(i,o,a,p,g,h,r,m,d);x.setModel(e),e.history=y,await x.onTrainBegin(),e.stopTraining_=!1;for(let b=p;b{let O=I[N][0],$=I[N][1],P=vl(k,O,$-O);R.batch=N,R.size=$-O;let T=xA(n,P),F=t(T);for(let U=0;U0){if(f=!0,s.validationData.length===2)o=s.validationData[0],i=s.validationData[1];else throw s.validationData.length===3?new Le("validationData including sample weights is not supported yet."):new j(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${s.validationData} is invalid.`);let I=!0,N=await e.standardizeUserData(o,i,null,null,I,d);l=N[0],c=N[1],m=l.concat(c)}else if(s.validationSplit!=null&&s.validationSplit>0&&s.validationSplit<1){f=!0;let I=Math.floor(r[0].shape[0]*(1-s.validationSplit)),N=r[0].shape[0];l=ep(r,I,N),r=ep(r,0,I),c=ep(a,I,N),a=ep(a,0,I),m=l.concat(c)}else s.validationSteps!=null&&(f=!0);let g=r.concat(a).concat(u);e.checkTrainableWeightsConsistency();let A=e.makeTrainFunction(),x=e.getDedupedMetricsNames(),y,b;f?(e.makeTestFunction(),y=e.testFunction,b=x.slice().concat(x.map(I=>"val_"+I))):(y=null,m=[],b=x.slice());let w=sk(s.callbacks,s.yieldEvery);return await NW(e,A,g,x,d,s.epochs,s.verbose,w,y,m,s.shuffle,b,s.initialEpoch,null,null)}finally{e.isTraining=!1,Sl(r,t),Sl(a,n),Sl(l,o),Sl(c,i),u!=null&&te(u)}}function bk(e){let t=[];e instanceof Je&&(e=[e]);for(let n=0;nn.push(r.id));else if(t!=null)for(let r in t){let a=t[r];n.push(a.id)}let s=[];if(e instanceof Je)n.indexOf(e.id)===-1&&s.push(e);else if(Array.isArray(e))e.forEach(r=>{n.indexOf(r.id)===-1&&s.push(r)});else if(e!=null)for(let r in e){let a=e[r];n.indexOf(a.id)===-1&&s.push(a)}s.forEach(r=>{r.isDisposed||r.dispose()})}function RW(e){return e instanceof Je}function vA(e){return Array.isArray(e)}function vk(e){return!RW(e)&&!vA(e)}function wk(e,t,n,s=!0,r=""){if(t==null||t.length===0){if(e!=null){let o=!1;if(vA(e)&&e.length>0)o=!0;else if(vk(e)){for(let i in e)if(e.hasOwnProperty(i)){o=!0;break}}else o=!0;if(o)throw new j(`Error when checking model ${r} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(o=>null);let a;if(vk(e)){e=e,a=[];for(let o of t){if(e[o]==null)throw new j(`No data provided for "${o}". Need data for each key in: ${t}`);a.push(e[o])}}else if(vA(e)){if(e=e,e.length!==t.length)throw new j(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);a=e}else{if(e=e,t.length>1)throw new j(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);a=[e]}if(a=bk(a),n!=null)for(let o=0;o=0&&c!==u)throw new j(`${r} expected a batch of elements where each example has shape [${n[o].slice(1,n[o].length)}] (i.e.,tensor shape [*,${n[o].slice(1,n[o].length)}]) but the ${r} received an input with ${i.shape[0]} examples, each with shape [${i.shape.slice(1,i.shape.length)}] (tensor shape [${i.shape}])`)}}return a}function $W(e,t,n){let s=Mo(e.map(a=>a.shape[0]));s.sort();let r=Mo(t.map(a=>a.shape[0]));if(r.sort(),s.length>1)throw new j(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(a=>a.shape))}`);if(r.length>1)throw new j(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(a=>a.shape))}`);if(s.length>0&&r.length>0&&!v.arraysEqual(s,r))throw new j(`Input Tensors should have the same number of samples as target Tensors. Found ${s[0]} input sample(s) and ${r[0]} target sample(s).`)}function _W(e,t,n){let s=[wl,lm,Yd];for(let r=0;r1)throw new j(`The model expects ${t.length} ${r} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);a=[e]}if(n!=null)for(let o=0;o[]);let n;if(typeof e=="string"||typeof e=="function")n=[e];else if(Array.isArray(e)||typeof e=="object")n=e;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);if(Array.isArray(n))return t.map(s=>n);{let s=[];for(let r of t){let a=n.hasOwnProperty(r)?n[r]:[];Array.isArray(a)||(a=[a]),s.push(a)}return s}}var PW="layers-model",aa=class extends Br{constructor(e){super(e);this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new j("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");dW(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=cW(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof na))throw new j("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(!Array.isArray(e.loss)&&typeof e.loss!="string"&&typeof e.loss!="function"){e.loss=e.loss;for(let a in e.loss)if(this.outputNames.indexOf(a)===-1)throw new j(`Unknown entry in loss dictionary: "${a}". Only expected the following keys: ${this.outputNames}`);for(let a of this.outputNames)e.loss[a]==null&&console.warn(`Output "${a}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${a} during training`),t.push(cA(e.loss[a]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new j(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);t=e.loss.map(o=>cA(o))}else{let a=cA(e.loss);this.outputs.forEach(o=>{t.push(a)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let a=0;a{for(let a=0;a1&&(this.metricsTensors.push([o,a]),this.metricsNames.push(this.outputNames[a]+"_loss"))}});let s=DW(e.metrics,this.outputNames),r=(a,o,i)=>{this.outputNames.length>1&&(o=this.outputNames[a]+"_"+o),this.metricsNames.push(o),this.metricsTensors.push([i,a])};bl("metric",()=>{for(let a=0;a{let c="",u,d,p;for(let h of l){if(typeof h=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(h)!==-1){let m=this.internalOutputShapes[a];m[m.length-1]===1||this.lossFunctions[a]===lm?["accuracy","acc"].indexOf(h)!==-1?d=dA:["crossentropy","ce"].indexOf(h)!==-1&&(d=ik):this.lossFunctions[a]===im?["accuracy","acc"].indexOf(h)!==-1?d=lk:["crossentropy","ce"].indexOf(h)!==-1&&(d=uk):["accuracy","acc"].indexOf(h)!==-1?d=pA:["crossentropy","ce"].indexOf(h)!==-1&&(d=hA);let g;["accuracy","acc"].indexOf(h)!==-1?g="acc":["crossentropy","ce"].indexOf(h)!==-1&&(g="ce"),p=d,u=c+g}else p=uW(h),u=c+dm(h);let f;bl(u,()=>{f=p}),r(a,u,f)}})(o)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){this.collectedTrainableWeights!=null&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){let s=n.batchSize==null?32:n.batchSize;yA(s);let r=!0,a=this.standardizeUserDataXY(e,t,r,s);try{let o=a[0].concat(a[1]);this.makeTestFunction();let i=this.testFunction,l=this.testLoop(i,o,s,n.verbose,n.steps);return is(l)}finally{Sl(a[0],e),Sl(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),TW(this,e,t)}checkNumSamples(e,t,n,s="steps"){let r;if(n!=null){if(r=null,t!=null)throw new j(`If ${s} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?r=e[0].shape[0]:r=e.shape[0];else throw new j(`Either the input data should have a defined shape, or ${s} shoud be specified.`);return r}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new j("`outputs` is an empty Array, which is not allowed.");let n=Array.isArray(t),s=n?t:[t],r=this.retrieveSymbolicTensors(s),a=new kl;if(e instanceof Je&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new j(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let i=0;io.name);for(let o=0;o0){let s=[];throw t.forEach((r,a)=>{r==null&&s.push(e[a])}),new j(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(s)}`)}return t}predictLoop(e,t=32,n=!1){return X(()=>{let s=this.checkNumSamples(e);if(n)throw new Le("Verbose predictLoop() is not implemented yet.");let r=bA(s,t),a=this.outputs.map(o=>[]);for(let o=0;o{let l=r[o][0],c=r[o][1],u=ep(e,l,c),d=[];if(Array.isArray(u))for(let h=0;ha[c].push(l));return is(a.map(o=>wt(o,0)))})}predict(e,t={}){let n=bk(e);kk(n,this.inputNames,this.feedInputShapes,!1);try{let s=t.batchSize==null?32:t.batchSize;return yA(s),this.predictLoop(n,s)}finally{Sl(n,e)}}predictOnBatch(e){kk(e,this.inputNames,this.feedInputShapes,!0);let t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,s){if(this.optimizer_==null)throw new gr("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let r=[];for(let a=0;a0&&e[0].shape[0]%s!=0)throw new j(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${s}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,s,r=!0,a){let[o,i]=this.standardizeUserDataXY(e,t,r,a);if(n!=null)throw new Error("sample weight is not supported yet.");let l=null;if(s!=null){let c=mk(s,this.outputNames);l=[];for(let u=0;u{let a=this.checkNumSamples(t,n,r,"steps"),o=[];if(s>0)throw new Le("Verbose mode is not implemented yet.");if(r!=null)throw new Le("steps mode in testLoop() is not implemented yet");{let i=bA(a,n),l=Vt(Ar(0,a));for(let c=0;c1&&(r+=`_${Rw(e.slice(0,n),s)}`),t.push(r)}return t}makeTrainFunction(){return e=>{let t=[],n=e.slice(0,this.inputs.length),s=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),r=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),a=[],o=()=>{let u=[];for(let f=0;f1&&f{h=ue(h,f)}),h},i=this.collectedTrainableWeights.map(u=>u.read()),l=!0;return[this.optimizer_.minimize(o,l,i)].concat(a)}}makeTestFunction(){this.testFunction=e=>X(()=>{let t=[],n,s=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=[];for(let l=0;lra(t))}else{let t=Object.keys(this.loss);e={};let n=this.loss;for(let s of t)if(typeof n[s]=="string")e[s]=ra(n[s]);else throw new Error("Serialization of non-string loss is not supported.")}return e}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[ra(dm(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>ra(dm(e)));{let e={};for(let t in this.metrics)e[t]=ra(dm(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(e.weighted_metrics!=null)throw new Error("Loading weight_metrics is not supported yet.");if(e.loss_weights!=null)throw new Error("Loading loss_weights is not supported yet.");if(e.sample_weight_mode!=null)throw new Error("Loading sample_weight_mode is not supported yet.");let t=Jd(e.optimizer_config),n=br(t),s;if(typeof e.loss=="string")s=yl(e.loss);else if(Array.isArray(e.loss))s=e.loss.map(a=>yl(a));else if(e.loss!=null){s={};for(let a in e.loss)s[a]=yl(e.loss[a])}let r;if(Array.isArray(e.metrics))r=e.metrics.map(a=>yl(a));else if(e.metrics!=null){r={};for(let a in e.metrics)r[a]=yl(e.metrics[a])}this.compile({loss:s,metrics:r,optimizer:n})}async save(e,t){if(typeof e=="string"){let l=rs.getSaveHandlers(e);if(l.length===0)throw new j(`Cannot find any save handlers for URL '${e}'`);if(l.length>1)throw new j(`Found more than one (${l.length}) save handlers for URL '${e}'`);e=l[0]}if(e.save==null)throw new j("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let n=await rs.encodeWeights(this.getNamedWeights(t)),s=!1,r=null,o={modelTopology:this.toJSON(r,s),format:PW,generatedBy:`TensorFlow.js tfjs-layers v${gA}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){o.trainingConfig=this.getTrainingConfig();let l="optimizer",{data:c,specs:u}=await rs.encodeWeights(await this.optimizer.getWeights(),l);n.specs.push(...u),n.data=rs.concatenateArrayBuffers([n.data,c])}if(this.userDefinedMetadata!=null){let l=!0;dk(this.userDefinedMetadata,this.name,l),o.userDefinedMetadata=this.userDefinedMetadata}return o.weightData=n.data,o.weightSpecs=n.specs,e.save(o)}setUserDefinedMetadata(e){dk(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};aa.className="Model";ce.registerClass(aa);var Sk=class extends aa{};Sk.className="Functional";ce.registerClass(Sk);async function FW(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);let s=Jd(n),r=br(s,t);if(e.weightsManifest!=null){let a=await rs.loadWeights(e.weightsManifest,e.pathPrefix,r.weights.map(i=>i.originalName)),o={};for(let i of r.weights)o[i.originalName]=a[i.originalName];r.loadWeights(o),te(a)}return r}async function OW(e,t){if(t==null&&(t={}),typeof e=="string"){let n=rs.getLoadHandlers(e,t);if(n.length===0)n.push(rs.browserHTTPRequest(e,t));else if(n.length>1)throw new j(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return MW(e,void 0,t)}async function MW(e,t,n){if(n==null&&(n={}),e.load==null)throw new j("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let s=await e.load(),r=s.modelTopology;r.model_config!=null&&(r=r.model_config);let a=n.strict==null?!0:n.strict,o=s.weightData!=null&&s.weightSpecs!=null&&a,i=br(Jd(r),t,o),l=s.trainingConfig;if(l!=null&&i.loadTrainingConfig(l),s.userDefinedMetadata!=null&&i.setUserDefinedMetadata(s.userDefinedMetadata),s.weightData!=null){if(s.weightSpecs==null)throw new j("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:c,optimizerWeights:u}=zW(s.weightData,s.weightSpecs);i.loadWeights(c,a),i.optimizer!=null&&u.length>0&&await i.optimizer.setWeights(u),te(c),te(u.map(d=>d.tensor))}return i}function zW(e,t){let n=rs.decodeWeights(e,t),s={},r=[];return t.forEach(a=>{a.group==="optimizer"?r.push({name:a.name,tensor:n[a.name]}):s[a.name]=n[a.name]}),{modelWeights:s,optimizerWeights:r}}var wA=class extends aa{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:tm("sequential_"),e.layers!=null)for(let t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(n=>n<0))throw new j(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof wA||e instanceof aa,n;if(t){if(n=e,n.outputs.length!==1)throw new j("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(n.inputs.length!==1)throw new j("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(this.outputs.length===0){if(e.inboundNodes.length===0){if(e.batchInputShape==null)throw new j("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let s=Yw({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(s)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(e.inboundNodes.length!==1)throw new j(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(e.inboundNodes[0].outputTensors.length!==1)throw new j("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=Zw(this.outputs[0])}this.inboundNodes=[],new rm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Al(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(s=>s.shape),outputShapes:this.outputs[0].shape})}else{let s=e.apply(this.outputs[0]);if(Array.isArray(s))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[s],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{let e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return this.model==null&&this.build(),this.model.call(e,t)}build(e){if(ht(e),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new aa({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new gr("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new gr("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return this.model==null&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return this.model==null&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return this.model==null?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new gr("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new gr("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},s=!1){let r,a={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new j("Legacy serialization format not supported yet.");r=t}else v.assert(t.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),r=t.layers,delete t.layers,a=t;let o=new e(a);if(!(o instanceof wA))throw new Le(`Sequential.fromConfig called on non-Sequential input: ${o}`);for(let i of r){let c=br(i,void 0,s);s&&c.setFastWeightInitDuringBuild(!0),o.add(c)}return o}set stopTraining(e){if(this.model==null)throw new j("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(this.model==null)throw new j("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){let e=[];for(let t of this.layers){let n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}},hm=wA;hm.className="Sequential";ce.registerClass(hm);function LW(e){return new aa(e)}function BW(e){return new hm(e)}function WW(e,t){return t==null&&(t={}),OW(e,t)}function Ik(e){return Yw(e)}function VW(e,t){lA.registerCallbackConstructor(e,t)}var us=class extends ce.Serializable{getConfig(){return{}}},Ck=class extends us{apply(e,t=1){return fB(e,t)}};Ck.className="elu";ce.registerClass(Ck);var Tk=class extends us{apply(e){return S1(e)}};Tk.className="selu";ce.registerClass(Tk);var Nk=class extends us{apply(e){return Or(e)}};Nk.className="relu";ce.registerClass(Nk);var Ek=class extends us{apply(e){return X(()=>zd(6,Or(e)))}};Ek.className="relu6";ce.registerClass(Ek);var Rk=class extends us{apply(e){return e}};Rk.className="linear";ce.registerClass(Rk);var $k=class extends us{apply(e){return ms(e)}};$k.className="sigmoid";ce.registerClass($k);var _k=class extends us{apply(e){return gB(e)}};_k.className="hardSigmoid";ce.registerClass(_k);var Dk=class extends us{apply(e){return Gu(e)}};Dk.className="softplus";ce.registerClass(Dk);var Pk=class extends us{apply(e){return mB(e)}};Pk.className="softsign";ce.registerClass(Pk);var Fk=class extends us{apply(e){return Lu(e)}};Fk.className="tanh";ce.registerClass(Fk);var kA=class extends us{apply(e,t=-1){return Xu(e,t)}};kA.className="softmax";ce.registerClass(kA);var Ok=class extends us{apply(e,t=-1){return h1(e,t)}};Ok.className="logSoftmax";ce.registerClass(Ok);var Mk=class extends us{apply(e,t=1){return X(()=>L(ms(L(e,t)),e))}};Mk.className="swish";ce.registerClass(Mk);var zk=class extends us{apply(e){return X(()=>L(e,Lu(Gu(e))))}};zk.className="mish";ce.registerClass(zk);function Wo(e){return e.getClassName()}function SA(e,t={}){return Hd(e,ce.SerializationMap.getMap().classNameMap,t,"activation")}function Vo(e){if(e==null){let t={};return t.className="linear",t.config={},SA(t)}if(typeof e=="string"){let t={};return t.className=e,t.config={},SA(t)}else return e instanceof us?e:SA(e)}function IA(e){if(e!=null&&typeof e!="object")throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}var Lk=class extends ce.Serializable{},tp=class extends Lk{constructor(e){super();IA(e),this.l1=e==null||e.l1==null?.01:e.l1,this.l2=e==null||e.l2==null?.01:e.l2,this.hasL1=this.l1!==0,this.hasL2=this.l2!==0}apply(e){return X(()=>{let t=Ht([1]);return this.hasL1&&(t=ue(t,ke(L(this.l1,nn(e))))),this.hasL2&&(t=ue(t,ke(L(this.l2,Kd(e))))),H(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};tp.className="L1L2";ce.registerClass(tp);function UW(e){return IA(e),new tp({l1:e!=null?e.l1:null,l2:0})}function GW(e){return IA(e),new tp({l2:e!=null?e.l2:null,l1:0})}var Bk={l1l2:"L1L2"};function yt(e){return B1(e)}function Wk(e,t={}){return Hd(e,ce.SerializationMap.getMap().classNameMap,t,"regularizer")}function $t(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in Bk?Bk[e]:e,config:{}};return Wk(n)}else return e instanceof Lk?e:Wk(e)}var CA=class extends tt{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Ve(e);let n=Or(e);return this.maxValue!=null&&(n=gs(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};CA.className="ReLU";ce.registerClass(CA);var TA=class extends tt{constructor(e){super(e==null?{}:e);this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let n=Ve(e);return bf(n,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};TA.className="LeakyReLU";ce.registerClass(TA);var NA=class extends tt{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Rt(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=$t(e.alphaRegularizer),this.alphaConstraint=on(e.alphaConstraint),e.sharedAxes==null)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else if(typeof e.sharedAxes=="number")this.sharedAxes=[e.sharedAxes];else throw new j(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=ht(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let s of this.sharedAxes)t[s-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let n={};if(this.sharedAxes!=null)for(let s=1;s(jt(t),t==="channelsFirst"?Qe(e,[0,2,3,1]):e))}function Vk(e,t){return X(()=>(jt(t),t==="channelsFirst"?Qe(e,[0,2,3,4,1]):e))}function HW(e,t,n,s=1,r="valid",a,o=1){return X(()=>{if(a==null&&(a=mr()),jt(a),e.shape.length!==3)throw new j(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new j(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new j(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(a==="channelsFirst"&&(e=Qe(e,[0,2,1])),r==="causal")throw new Le("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let i=a1(e,t,s,r==="same"?"same":"valid","NWC",o);return n!=null&&(i=yr(i,n)),i})}function Uk(e,t,n,s=[1,1],r="valid",a,o,i=null){return X(()=>{if(a==null&&(a=mr()),jt(a),e.rank!==3&&e.rank!==4)throw new j(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new j(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=_A(e,a);if(r==="causal")throw new Le("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=Fo.conv2d({x:l,filter:t,strides:s,pad:r==="same"?"same":"valid",dilations:o,dataFormat:"NHWC",bias:n,activation:i}),a==="channelsFirst"&&(l=Qe(l,[0,3,1,2])),l})}function jW(e,t,n,s=[1,1,1],r="valid",a,o){return X(()=>{if(a==null&&(a=mr()),jt(a),e.rank!==4&&e.rank!==5)throw new j(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new j(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let i=Vk(e,a);if(r==="causal")throw new Le("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return i=l1(i,t,s,r==="same"?"same":"valid","NDHWC",o),n!=null&&(i=yr(i,n)),a==="channelsFirst"&&(i=Qe(i,[0,4,1,2,3])),i})}var DA=class extends tt{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",DA.verifyArgs(t),this.rank=e,xn(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Le(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=tc(t.kernelSize,e,"kernelSize"),this.strides=tc(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,Os(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,jt(this.dataFormat),this.activation=Vo(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=Rt(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=on(t.biasConstraint),this.biasRegularizer=$t(t.biasRegularizer),this.activityRegularizer=$t(t.activityRegularizer),this.dilationRate=tc(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new j(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(this.rank===2){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==2)throw new j(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(this.rank===3){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==3)throw new j(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(Mr("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!V1(e.kernelSize,"number",1,3))throw new j(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){let e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Wo(this.activation),useBias:this.useBias,biasInitializer:Mt(this.biasInitializer),biasRegularizer:yt(this.biasRegularizer),activityRegularizer:yt(this.activityRegularizer),biasConstraint:an(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},np=class extends DA{constructor(e,t){super(e,t);this.kernel=null,np.verifyArgs(t),this.filters=t.filters,xn(this.filters,"filters"),this.kernelInitializer=Rt(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=on(t.kernelConstraint),this.kernelRegularizer=$t(t.kernelRegularizer)}build(e){e=ht(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new j(`The channel dimension of the input should be defined. Found ${e[t]}`);let n=e[t],s=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return X(()=>{e=Ve(e);let n,s=this.bias==null?null:this.bias.read(),r=_w(this.activation.getClassName());if(r!=null&&this.rank===2)n=Uk(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(this.rank===1)n=HW(e,this.kernel.read(),s,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=Uk(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=jW(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Le("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(e){e=ht(e);let t=[],n=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let r=0;r 0 but got ${JSON.stringify(e.filters)}`)}},Gk=class extends np{constructor(e){super(2,e);Gk.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!V1(e.kernelSize,"number",1,2))throw new j(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}},fm=Gk;fm.className="Conv2D";ce.registerClass(fm);var Hk=class extends np{constructor(e){super(3,e);Hk.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!(Array.isArray(e.kernelSize)&&(e.kernelSize.length===1||e.kernelSize.length===3)))throw new j(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}},mm=Hk;mm.className="Conv3D";ce.registerClass(mm);var PA=class extends fm{constructor(e){super(e);if(this.inputSpec=[new Zt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new j(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=ht(e),e.length!==4)throw new j("Input should have rank 4; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new j("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],s=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Zt({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return X(()=>{let n=Ve(e);if(n.shape.length!==4)throw new j(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let s=n.shape,r=s[0],a,o;this.dataFormat==="channelsFirst"?(a=2,o=3):(a=1,o=2);let i=s[a],l=s[o],c=this.kernelSize[0],u=this.kernelSize[1],d=this.strides[0],p=this.strides[1],h=Wr(i,d,c,this.padding),f=Wr(l,p,u,this.padding),m=[r,h,f,this.filters];this.dataFormat!=="channelsLast"&&(n=Qe(n,[0,2,3,1]));let g=i1(n,this.kernel.read(),m,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=Qe(g,[0,3,1,2])),this.bias!=null&&(g=yr(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=ht(e);let t=e.slice(),n,s,r;this.dataFormat==="channelsFirst"?(n=1,s=2,r=3):(n=3,s=1,r=2);let a=this.kernelSize[0],o=this.kernelSize[1],i=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[s]=Wr(t[s],i,a,this.padding),t[r]=Wr(t[r],l,o,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};PA.className="Conv2DTranspose";ce.registerClass(PA);var FA=class extends mm{constructor(e){super(e);if(this.inputSpec=[new Zt({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new j(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=ht(e),e.length!==5)throw new j("Input should have rank 5; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new j("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],s=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Zt({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return X(()=>{let n=Ve(e);if(n.shape.length!==5)throw new j(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let s=n.shape,r=s[0],a,o,i;this.dataFormat==="channelsFirst"?(i=2,a=3,o=4):(i=1,a=2,o=3);let l=s[i],c=s[a],u=s[o],d=this.kernelSize[0],p=this.kernelSize[1],h=this.kernelSize[2],f=this.strides[0],m=this.strides[1],g=this.strides[2],A=Wr(l,f,d,this.padding),x=Wr(c,m,p,this.padding),y=Wr(u,g,h,this.padding),b=[r,A,x,y,this.filters];this.dataFormat!=="channelsLast"&&(n=Qe(n,[0,2,3,4,1]));let w=kv(n,this.kernel.read(),b,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(w=Qe(w,[0,4,1,2,3])),this.bias!==null&&(w=yr(w,this.bias.read(),this.dataFormat)),this.activation!==null&&(w=this.activation.apply(w)),w})}computeOutputShape(e){e=ht(e);let t=e.slice(),n,s,r,a;this.dataFormat==="channelsFirst"?(n=1,s=2,r=3,a=4):(n=4,s=1,r=2,a=3);let o=this.kernelSize[0],i=this.kernelSize[1],l=this.kernelSize[2],c=this.strides[0],u=this.strides[1],d=this.strides[2];return t[n]=this.filters,t[s]=Wr(t[s],c,o,this.padding),t[r]=Wr(t[r],u,i,this.padding),t[a]=Wr(t[a],d,l,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};FA.className="Conv3DTranspose";ce.registerClass(FA);var jk=class extends np{constructor(e,t){super(e,t);if(this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new j("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new j("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(t.padding!=null&&t.padding!=="same"&&t.padding!=="valid")throw new j(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=Rt(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=$t(t.depthwiseRegularizer),this.depthwiseConstraint=on(t.depthwiseConstraint),this.pointwiseInitializer=Rt(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=$t(t.pointwiseRegularizer),this.pointwiseConstraint=on(t.pointwiseConstraint)}build(e){if(e=ht(e),e.length{e=Ve(e);let n;if(this.rank===1)throw new Le("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=Qe(e,[0,2,3,1])),n=Gv(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=yr(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=Qe(n,[0,3,1,2])),n})}getConfig(){let e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Mt(this.depthwiseInitializer),e.pointwiseInitializer=Mt(this.pointwiseInitializer),e.depthwiseRegularizer=yt(this.depthwiseRegularizer),e.pointwiseRegularizer=yt(this.pointwiseRegularizer),e.depthwiseConstraint=an(this.depthwiseConstraint),e.pointwiseConstraint=an(this.pointwiseConstraint),e}};jk.className="SeparableConv";var OA=class extends jk{constructor(e){super(2,e)}};OA.className="SeparableConv2D";ce.registerClass(OA);var qk=class extends np{constructor(e){super(1,e);qk.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){let e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!V1(e.kernelSize,"number",1,1))throw new j(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}},MA=qk;MA.className="Conv1D";ce.registerClass(MA);var zA=class extends tt{constructor(e){super(e);typeof e.cropping=="number"?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:typeof e.cropping[0]=="number"?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=e.dataFormat===void 0?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return this.dataFormat==="channelsFirst"?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return X(()=>{if(e=Ve(e),this.dataFormat==="channelsLast"){let n=Hf(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Hf(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let n=Hf(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Hf(n,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){let e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};zA.className="Cropping2D";ce.registerClass(zA);var LA=class extends tt{constructor(e){super(e);this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=e.size==null?this.DEFAULT_SIZE:e.size,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,iB(this.interpolation)}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){let t=e[2]==null?null:this.size[0]*e[2],n=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,n]}else{let t=e[1]==null?null:this.size[0]*e[1],n=e[2]==null?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return X(()=>{let n=Ve(e),s=n.shape;if(this.dataFormat==="channelsFirst"){n=Qe(n,[0,2,3,1]);let r=this.size[0]*s[2],a=this.size[1]*s[3],o=this.interpolation==="nearest"?Ce.resizeNearestNeighbor(n,[r,a]):Ce.resizeBilinear(n,[r,a]);return Qe(o,[0,3,1,2])}else{let r=this.size[0]*s[1],a=this.size[1]*s[2];return this.interpolation==="nearest"?Ce.resizeNearestNeighbor(n,[r,a]):Ce.resizeBilinear(n,[r,a])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};LA.className="UpSampling2D";ce.registerClass(LA);function qW(e,t,n=[1,1],s="valid",r,a){return X(()=>{r==null&&(r=mr()),jt(r);let o=_A(e,r);if(e.rank!==4)throw new j(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new j(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return o=Fd(o,t,n,s==="same"?"same":"valid","NHWC",a),r==="channelsFirst"&&(o=Qe(o,[0,3,1,2])),o})}var BA=class extends DA{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=Rt(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=on(e.depthwiseConstraint),this.depthwiseRegularizer=$t(e.depthwiseRegularizer)}build(e){if(e=ht(e),e.length<4)throw new j(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);let t=this.dataFormat==="channelsFirst"?1:3;if(e[t]==null||e[t]<0)throw new j(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);let n=e[t],s=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",s,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return X(()=>{e=Ve(e);let n=qW(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=yr(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=ht(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],s=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,r=vr(t,this.kernelSize[0],this.padding,this.strides[0]),a=vr(n,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],s,r,a]:[e[0],r,a,s]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Mt(this.depthwiseInitializer),e.depthwiseRegularizer=yt(this.depthwiseRegularizer),e.depthwiseConstraint=an(this.depthwiseRegularizer),e}};BA.className="DepthwiseConv2D";ce.registerClass(BA);function Xk(e,t,n,s){if(Array.isArray(e)){if(t!=null||n!=null)throw new j("When inputs is an array, neither initialState or constants should be provided");s!=null&&(n=e.slice(e.length-s,e.length),e=e.slice(0,e.length-s)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function r(a){return a==null||Array.isArray(a)?a:[a]}return t=r(t),n=r(n),{inputs:e,initialState:t,constants:n}}function Kk(e,t,n,s=!1,r,a,o=!1,i=!1){return X(()=>{let l=t.shape.length;if(l<3)throw new j(`Input should be at least 3D, but is ${l}D.`);let c=[1,0].concat(Ar(2,l));if(t=Qe(t,c),a!=null)throw new Le("The rnn() functoin of the deeplearn.js backend does not support constants yet.");o&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),r!=null&&(r=me(me(r,"bool"),"float32"),r.rank===l-1&&(r=Kt(r,-1)),r=Qe(r,c)),s&&(t=Fs(t,0),r!=null&&(r=Fs(r,0)));let u=[],d,p=n,h=t.shape[0],f=os(t),m;r!=null&&(m=os(r));for(let A=0;Ae(x,p));if(r==null)d=y[0],p=y[1];else{let b=X(()=>{let w=m[A],k=fe(Ps(w),w),I=ue(L(y[0],w),L(p[0],k)),N=p.map((R,O)=>ue(L(y[1][O],w),L(R,k)));return{output:I,newStates:N}});d=b.output,p=b.newStates}i&&u.push(d)}let g;return i&&(g=yn(u,1)),[d,g,p]})}var Zk=class extends tt{constructor(e){super(e);let t;if(e.cell==null)throw new j("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new ym({cells:e.cell}):t=e.cell,t.stateSize==null)throw new j("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=e.returnSequences==null?!1:e.returnSequences,this.returnState=e.returnState==null?!1:e.returnState,this.goBackwards=e.goBackwards==null?!1:e.goBackwards,this._stateful=e.stateful==null?!1:e.stateful,this.unroll=e.unroll==null?!1:e.unroll,this.supportsMasking=!0,this.inputSpec=[new Zt({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return Ar(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){aA(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);let n=t[0],s;if(this.returnSequences?s=[e[0],e[1],n]:s=[e[0],n],this.returnState){let r=[];for(let a of t)r.push([e[0],a]);return[s].concat(r)}else return s}computeMask(e,t){return X(()=>{Array.isArray(t)&&(t=t[0]);let n=this.returnSequences?t:null;if(this.returnState){let s=this.states.map(r=>null);return[n].concat(s)}else return n})}get states(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;no.shape[o.shape.length-1]),a))throw new j(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=a.map(o=>new Zt({shape:[null,o]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){X(()=>{if(!this.stateful)throw new sa("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape[0];if(n==null)throw new j("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(s=>Ht([n,s])):this.states_=[Ht([n,this.cell.stateSize])];else if(e==null)te(this.states_),this.keptStates!=null&&(te(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(s=>Ht([n,s])):this.states_[0]=Ht([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new j(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t===!0?this.keptStates.push(this.states_.slice()):te(this.states_);for(let s=0;sgn(s.clone()))})}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});let r=Xk(e,n,s,this.numConstants);e=r.inputs,n=r.initialState,s=r.constants;let a=[],o=[];if(n!=null){t.initialState=n,a=a.concat(n),this.stateSpec=[];for(let l of n)this.stateSpec.push(new Zt({shape:l.shape}));o=o.concat(this.stateSpec)}if(s!=null&&(t.constants=s,a=a.concat(s),this.numConstants=s.length),a[0]instanceof xr){let l=[e].concat(a),c=this.inputSpec.concat(o),u=this.inputSpec;this.inputSpec=c;let d=super.apply(l,t);return this.inputSpec=u,d}else return super.apply(e,t)}call(e,t){return X(()=>{let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;e=Ve(e),r==null&&(this.stateful?r=this.states_:r=this.getInitialState(e));let a=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(r.length!==a)throw new j(`RNN Layer has ${a} state(s) but was passed ${r.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");let o={training:s},l=Kk((h,f)=>{let m=this.cell.call([h].concat(f),o);return[m[0],m.slice(1)]},e,r,this.goBackwards,n,null,this.unroll,this.returnSequences),c=l[0],u=l[1],d=l[2];this.stateful&&this.resetStates(d,s);let p=this.returnSequences?u:c;return this.returnState?[p].concat(d):p})}getInitialState(e){return X(()=>{let t=Ht(e.shape);return t=ke(t,[1,2]),t=Xd(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?Z1(t,[1,n]):t):this.cell.stateSize>1?[Z1(t,[1,this.cell.stateSize])]:[t]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){let e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(t.numConstants=this.numConstants);let n=this.cell.getConfig();return this.getClassName()===Zk.className&&(t.cell={className:this.cell.getClassName(),config:n}),{...n,...e,...t}}static fromConfig(e,t,n={}){let s=t.cell,r=br(s,n);return new e(Object.assign(t,{cell:r}))}},oa=Zk;oa.className="RNN";ce.registerClass(oa);var sp=class extends tt{},gm=class extends sp{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,xn(this.units,"units"),this.activation=Vo(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Rt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Rt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Rt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=$t(e.kernelRegularizer),this.recurrentRegularizer=$t(e.recurrentRegularizer),this.biasRegularizer=$t(e.biasRegularizer),this.kernelConstraint=on(e.kernelConstraint),this.recurrentConstraint=on(e.recurrentConstraint),this.biasConstraint=on(e.biasConstraint),this.dropout=Yu([1,Lo([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Yu([1,Lo([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=ht(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return X(()=>{if(e=e,e.length!==2)throw new j(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];let s=t.training==null?!1:t.training;0Ps(e),rate:this.dropout,training:s,dropoutFunc:this.dropoutFunc})),0Ps(n),rate:this.recurrentDropout,training:s,dropoutFunc:this.dropoutFunc}));let r,a=this.dropoutMask,o=this.recurrentDropoutMask;a!=null?r=zr(L(e,a),this.kernel.read()):r=zr(e,this.kernel.read()),this.bias!=null&&(r=yr(r,this.bias.read())),o!=null&&(n=L(n,o));let i=ue(r,zr(n,this.recurrentKernel.read()));return this.activation!=null&&(i=this.activation.apply(i)),[i,i]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Wo(this.activation),useBias:this.useBias,kernelInitializer:Mt(this.kernelInitializer),recurrentInitializer:Mt(this.recurrentInitializer),biasInitializer:Mt(this.biasInitializer),kernelRegularizer:yt(this.kernelRegularizer),recurrentRegularizer:yt(this.recurrentRegularizer),biasRegularizer:yt(this.biasRegularizer),activityRegularizer:yt(this.activityRegularizer),kernelConstraint:an(this.kernelConstraint),recurrentConstraint:an(this.recurrentConstraint),biasConstraint:an(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return{...e,...t}}};gm.className="SimpleRNNCell";ce.registerClass(gm);var WA=class extends oa{constructor(e){e.cell=new gm(e);super(e)}call(e,t){return X(()=>{this.cell.dropoutMask!=null&&(te(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(te(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})})}static fromConfig(e,t){return new e(t)}};WA.className="SimpleRNN";ce.registerClass(WA);var Am=class extends sp{constructor(e){super(e);if(this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new j("GRUCell does not support reset_after parameter set to true.");this.units=e.units,xn(this.units,"units"),this.activation=Vo(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Vo(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Rt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Rt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Rt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=$t(e.kernelRegularizer),this.recurrentRegularizer=$t(e.recurrentRegularizer),this.biasRegularizer=$t(e.biasRegularizer),this.kernelConstraint=on(e.kernelConstraint),this.recurrentConstraint=on(e.recurrentConstraint),this.biasConstraint=on(e.biasConstraint),this.dropout=Yu([1,Lo([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Yu([1,Lo([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=ht(e);let t=e[e.length-1];this.kernel=this.addWeight("kernel",[t,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return X(()=>{if(e=e,e.length!==2)throw new j(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training==null?!1:t.training,s=e[1];e=e[0],0Ps(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0Ps(s),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));let r=this.dropoutMask,a=this.recurrentDropoutMask,o,i,l;0{this.cell.dropoutMask!=null&&(te(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(te(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};VA.className="GRU";ce.registerClass(VA);var rp=class extends sp{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,xn(this.units,"units"),this.activation=Vo(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Vo(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Rt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Rt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Rt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=$t(e.kernelRegularizer),this.recurrentRegularizer=$t(e.recurrentRegularizer),this.biasRegularizer=$t(e.biasRegularizer),this.kernelConstraint=on(e.kernelConstraint),this.recurrentConstraint=on(e.recurrentConstraint),this.biasConstraint=on(e.biasConstraint),this.dropout=Yu([1,Lo([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Yu([1,Lo([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;e=ht(e);let n=e[e.length-1];this.kernel=this.addWeight("kernel",[n,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let s;if(this.useBias){if(this.unitForgetBias){let r=this.biasInitializer,a=this.units;s=new(t=class extends tr{apply(o,i){let l=r.apply([a]),c=new qf().apply([a]),u=r.apply([a*2]);return Ww(Ww(l,c),u)}},t.className="CustomInit",t)}else s=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,s,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return X(()=>{let n=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new j(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let s=e[1],r=e[2];e=e[0],0Ps(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0Ps(s),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));let a=this.dropoutMask,o=this.recurrentDropoutMask,i,l,c,u;0{this.cell.dropoutMask!=null&&(te(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(te(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};UA.className="LSTM";ce.registerClass(UA);var ym=class extends sp{constructor(e){super(e);this.cells=e.cells}get stateSize(){let e=[];for(let t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return X(()=>{e=e;let n=e.slice(1),s=[];for(let o of this.cells.slice().reverse())Array.isArray(o.stateSize)?s.push(n.splice(0,o.stateSize.length)):s.push(n.splice(0,1));s.reverse();let r=[],a;for(let o=0;o{bl(`RNNCell_${s}`,()=>{n.build(e),Array.isArray(n.stateSize)?t=n.stateSize[0]:t=n.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){let e=super.getConfig(),t=r=>({className:r.getClassName(),config:r.getConfig()}),s={cells:this.cells.map(t)};return{...e,...s}}static fromConfig(e,t,n={}){let s=[];for(let r of t.cells)s.push(br(r,n));return new e({cells:s})}get trainableWeights(){if(!this.trainable)return[];let e=[];for(let t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.cells)t.push(...n.trainableWeights);return t.concat(e)}return e}getWeights(){let e=[];for(let t of this.cells)e.push(...t.weights);return oA(e)}setWeights(e){let t=[];for(let n of this.cells){let s=n.weights.length,r=e.splice(s);for(let a=0;aa!=null?a(t(),n):Uw(t(),n),i=()=>Zd(o,t,s);return!r||r<=1?gn(i().clone()):Array(r).fill(void 0).map(i).map(c=>gn(c.clone()))}var Yk=class extends oa{constructor(e){if(e.unroll)throw new Le("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Le("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new Zt({ndim:5})]}call(e,t){return X(()=>{if(this.cell.dropoutMask!=null&&(te(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(te(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new j("ConvRNN2D cell does not support constants");let n=t==null?null:t.mask,s=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})})}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return X(()=>{let{stateSize:t}=this.cell,n=e.shape,s=this.computeSingleOutputShape(n),r=[s[0],...s.slice(2)],a=Ht(r);return Array.isArray(t)?Array(t.length).fill(a):[a]})}resetStates(e,t=!1){X(()=>{if(!this.stateful)throw new sa("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape,s=this.computeSingleOutputShape(n),r=[s[0],...s.slice(2)];if(n[0]==null)throw new j("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.getStates()==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Ht(r)):this.states_=[Ht(r)];else if(e==null)te(this.states_),this.keptStates!=null&&(te(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Ht(r)):this.states_[0]=Ht(r);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new j(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):te(this.states_);for(let o=0;ogn(o.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:n,kernelSize:s,padding:r,strides:a,dilationRate:o}=this.cell,i=t==="channelsFirst",l=e[i?3:2],c=e[i?4:3],u=vr(l,s[0],r,a[0],o[0]),d=vr(c,s[1],r,a[1],o[1]);return[...e.slice(0,2),...i?[n,u,d]:[u,d,n]]}};Yk.className="ConvRNN2D";var xm=class extends rp{constructor(e){let{filters:t,kernelSize:n,strides:s,padding:r,dataFormat:a,dilationRate:o}=e;super({...e,units:t});this.filters=t,xn(this.filters,"filters"),this.kernelSize=tc(n,2,"kernelSize"),this.kernelSize.forEach(i=>xn(i,"kernelSize")),this.strides=tc(s||1,2,"strides"),this.strides.forEach(i=>xn(i,"strides")),this.padding=r||"valid",Os(this.padding),this.dataFormat=a||"channelsLast",jt(this.dataFormat),this.dilationRate=tc(o||1,2,"dilationRate"),this.dilationRate.forEach(i=>xn(i,"dilationRate"))}build(e){var t;e=ht(e);let n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new j(`The channel dimension of the input should be defined. Found ${e[n]}`);let s=e[n],r=4,a=this.kernelSize.concat([s,this.filters*r]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let o=this.kernelSize.concat([this.filters,this.filters*r]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",o,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let i;if(this.unitForgetBias){let l=this.biasInitializer,c=this.filters;i=new(t=class extends tr{apply(u,d){let p=l.apply([c]),h=ys([c]),f=l.apply([c*2]);return K1([p,h,f])}},t.className="CustomInit",t)}else i=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*r],null,i,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return X(()=>{if(e.length!==3)throw new j(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training||!1,s=e[0],r=e[1],a=e[2],o=4;0Ps(s),rate:this.dropout,training:n,count:o,dropoutFunc:this.dropoutFunc}));let i=this.dropoutMask,l=(J,Q,ne)=>!Q||!Q[ne]?J:L(Q[ne],J),c=l(s,i,0),u=l(s,i,1),d=l(s,i,2),p=l(s,i,3);0Ps(r),rate:this.recurrentDropout,training:n,count:o,dropoutFunc:this.dropoutFunc}));let h=this.recurrentDropoutMask,f=l(r,h,0),m=l(r,h,1),g=l(r,h,2),A=l(r,h,3),x=3,[y,b,w,k]=sn(this.kernel.read(),o,x),[I,N,R,O]=this.useBias?sn(this.bias.read(),o):[null,null,null,null];c=this.inputConv(c,y,I,this.padding),u=this.inputConv(u,b,N,this.padding),d=this.inputConv(d,w,R,this.padding),p=this.inputConv(p,k,O,this.padding);let[$,P,T,F]=sn(this.recurrentKernel.read(),o,x);f=this.recurrentConv(f,$),m=this.recurrentConv(m,P),g=this.recurrentConv(g,T),A=this.recurrentConv(A,F);let U=this.recurrentActivation.apply(ue(c,f)),q=this.recurrentActivation.apply(ue(u,m)),z=ue(L(q,a),L(U,this.activation.apply(ue(d,g)))),K=L(this.recurrentActivation.apply(ue(p,A)),this.activation.apply(z));return[K,K,z]})}getConfig(){let{units:e,...t}=super.getConfig(),n={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return{...t,...n}}inputConv(e,t,n,s){let r=_o(e,t,this.strides,s||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?yr(r,n,this.dataFormat):r}recurrentConv(e,t){return _o(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};xm.className="ConvLSTM2DCell";ce.registerClass(xm);var GA=class extends Yk{constructor(e){let t=new xm(e);super({...e,cell:t})}static fromConfig(e,t){return new e(t)}};GA.className="ConvLSTM2D";ce.registerClass(GA);var bm=class extends tt{constructor(e){super(e);this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(this.noiseShape==null)return this.noiseShape;let t=e.shape,n=[];for(let s=0;s{this.invokeCallHook(e,t);let n=Ve(e);if(0Uw(n,this.rate,r,this.seed),()=>n,s)}return e})}getConfig(){let e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}};bm.className="Dropout";ce.registerClass(bm);var HA=class extends bm{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};HA.className="SpatialDropout1D";ce.registerClass(HA);var jA=class extends tt{constructor(e){super(e);if(this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,xn(this.units,"units"),this.activation=Vo(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=Rt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Rt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=on(e.kernelConstraint),this.biasConstraint=on(e.biasConstraint),this.kernelRegularizer=$t(e.kernelRegularizer),this.biasRegularizer=$t(e.biasRegularizer),this.activityRegularizer=$t(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=ht(e);let t=e[e.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){e=ht(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return X(()=>{this.invokeCallHook(e,t);let n=Ve(e),s=_w(this.activation.getClassName()),r;return s!=null?r=zr(n,this.kernel.read(),s,this.bias?this.bias.read():null):(r=zr(n,this.kernel.read()),this.bias!=null&&(r=yr(r,this.bias.read())),this.activation!=null&&(r=this.activation.apply(r))),r})}getConfig(){let e={units:this.units,activation:Wo(this.activation),useBias:this.useBias,kernelInitializer:Mt(this.kernelInitializer),biasInitializer:Mt(this.biasInitializer),kernelRegularizer:yt(this.kernelRegularizer),biasRegularizer:yt(this.biasRegularizer),activityRegularizer:yt(this.activityRegularizer),kernelConstraint:an(this.kernelConstraint),biasConstraint:an(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};jA.className="Dense";ce.registerClass(jA);var qA=class extends tt{constructor(e){e=e||{};super(e);this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=ht(e);for(let t of e.slice(1))if(t==null)throw new j(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],zo(e,1)]}call(e,t){return X(()=>{this.invokeCallHook(e,t);let n=Ve(e);if(this.dataFormat==="channelsFirst"&&n.rank>1){let s=[0];for(let r=2;r{this.invokeCallHook(e,t);let n=Ve(e);return this.activation.apply(n)})}getConfig(){let e={activation:Wo(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};XA.className="Activation";ce.registerClass(XA);var KA=class extends tt{constructor(e){super(e);this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return X(()=>(e=Ve(e),dB(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};KA.className="RepeatVector";ce.registerClass(KA);var ZA=class extends tt{constructor(e){super(e);this.targetShape=e.targetShape;for(let t=0;t{this.invokeCallHook(e,t);let n=Ve(e),s=n.shape,r=s.slice(0,1).concat(this.fixUnknownDimension(s.slice(1),this.targetShape));return H(n,r)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};ZA.className="Reshape";ce.registerClass(ZA);var YA=class extends tt{constructor(e){super(e);if(e.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);let t=Ar(1,e.dims.length+1);if(!v.arraysEqual(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new Zt({ndim:this.dims.length+1})]}computeOutputShape(e){e=ht(e);let t=e.slice();return this.dims.forEach((n,s)=>{t[s+1]=e[n]}),t}call(e,t){return Qe(Ve(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};YA.className="Permute";ce.registerClass(YA);var JA=class extends tt{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null?this.maskValue=e.maskValue==null?0:e.maskValue:this.maskValue=0}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){let n=Ve(e),s=-1;return ff(Hu(n,this.maskValue),s)}call(e,t){return X(()=>{this.invokeCallHook(e,t);let n=Ve(e),s=-1,r=!0,a=ff(Hu(n,this.maskValue),s,r);return L(n,me(a,n.dtype))})}};JA.className="Masking";ce.registerClass(JA);var QA=class extends tt{constructor(e){super(e);if(this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(St(e.inputLength))}this.inputDim=e.inputDim,xn(this.inputDim,"inputDim"),this.outputDim=e.outputDim,xn(this.outputDim,"outputDim"),this.embeddingsInitializer=Rt(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=$t(e.embeddingsRegularizer),this.activityRegularizer=$t(e.activityRegularizer),this.embeddingsConstraint=on(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return X(()=>this.maskZero?(e=Ve(e),Hu(e,et(e))):null)}computeOutputShape(e){if(e=ht(e),this.inputLength==null)return[...e,this.outputDim];let t=St(this.inputLength);if(t.length!==e.length-1)throw new j(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let s=0;s{this.invokeCallHook(e,t);let n=Ve(e);n.dtype!=="int32"&&(n=Gf(n,"int32"));let s=Vw(this.embeddings.read(),H(n,[n.size]));return H(s,ht(this.computeOutputShape(n.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Mt(this.embeddingsInitializer),embeddingsRegularizer:yt(this.embeddingsRegularizer),activityRegularizer:yt(this.activityRegularizer),embeddingsConstraint:an(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};QA.className="Embedding";ce.registerClass(QA);var Il=class extends tt{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new Le}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length1)throw new j(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=e[0]==null?null:e[0].slice(1);for(let r=1;rr.length);e.indexOf(null)===-1&&Mo(s).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return X(()=>{if(e=e,this.reshapeRequired){let n=[],s=e.map(r=>r.rank);if(s.indexOf(null)===-1){let r=Lo(s);for(let a of e){let o=a.rank;for(let i=0;i1){let c=Ar(1,l).concat([0]);n.push(Qe(i,c)),r=!0}else n.push(i)}let a=this.mergeFunction(n),o=a.rank;if(r){if(o==null){let i=a.shape,l=i.length,c=i[l-1],u=[c].concat(i.slice(0,i.length-1));a=H(Qe(H(a,[-1,c]),[1,0]),u)}else if(o>1){let i=[o-1].concat(Ar(0,o-1));a=Qe(a,i)}}return a}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let s=1;s{if(t==null)return null;if(!Array.isArray(t))throw new j("`mask` should be an Array");if(!Array.isArray(e))throw new j("`inputs` should be an Array");if(t.length!==e.length)throw new j(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(s=>s==null))return null;t=t.map(s=>s==null?s:Kt(s,0));let n=t[0];for(let s=1;s{let t=e[0].clone();for(let n=1;n{let t=e[0].clone();for(let n=1;n{let t=e[0].clone();for(let n=1;n{let t=e[0];for(let n=1;n{let t=e[0];for(let n=1;n1)throw new j("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return X(()=>K1(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new j("A `Concatenate` layer should be called on a list of inputs.");let t=e,n=t[0].slice(),s=this.axis<0?n.length+this.axis:this.axis;for(let r of t.slice(1)){if(n[s]==null||r[s]==null){n[s]=null;break}n[s]+=r[s]}return n}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new j("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new j("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new j(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return X(()=>{let n=!0;if(t.forEach(a=>{if(a!=null){n=!1;return}}),n)return null;let s=[];for(let a=0;a3||t.shape.length>3)throw new Le("batchDot is not implemented for tensors of 4D or higher rank yet");if(v.assert(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),v.assert(e.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`),typeof n=="number"&&(n=[n,n]),e.dtype==="complex64"||t.dtype==="complex64")throw new Le("batchDot is not implemented for complex64-type Tensors yet.");let s=e.shape.length,r=t.shape.length;n==null&&(n=[s-1,r-2]);let a=n;return X(()=>{let o;if(s>r){o=s-r;let l=[];for(let c=0;cs){o=r-s;let l=[];for(let c=0;c0){let l;s>r?l=s+r-3:l=s-1;let c=[];for(let u=l;u"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0],n=e[1];if(t.length>3||n.length>3)throw new Le("Dot layer does not support tensors of 4D or higher rank yet.");let s=this.interpretAxes(t,n);if(t[s[0]]!==n[s[1]])throw new j(`Dimension incompatibility: ${t[s[0]]} !== ${n[s[1]]}`)}mergeFunction(e){if(e.length!==2)throw new j(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],n=e[1],s;return Array.isArray(this.axes)?s=this.axes.map((r,a)=>ap(r,e[a].shape.length)):s=[ap(this.axes,t.shape.length),ap(this.axes,n.shape.length)],this.normalize&&(t=am(t,s[0]),n=am(n,s[1])),XW(t,n,s)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[ap(this.axes,e.length),ap(this.axes,t.length)],n}computeOutputShape(e){v.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new Le("Dot layer does not support tensors of 4D or higher rank yet.");let s=this.interpretAxes(t,n);t.splice(s[0],1),n.splice(s[1],1),n.splice(0,1);let r=t.concat(n);return r.length===1&&r.push(1),r}computeMask(e,t){return null}getConfig(){let e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}};oy.className="Dot";ce.registerClass(oy);var iy=class extends tt{constructor(e){super(e);this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return X(()=>{this.invokeCallHook(e,t);let n=Ve(e);return Zd(()=>ue(jf(n.shape,0,this.stddev),n),()=>n,t.training||!1)})}};iy.className="GaussianNoise";ce.registerClass(iy);var ly=class extends tt{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return X(()=>{this.invokeCallHook(e,t);let n=Ve(e);return this.rate>0&&this.rate<1?Zd(()=>{let r=Math.sqrt(this.rate/(1-this.rate));return L(n,jf(n.shape,1,r))},()=>n,t.training||!1):n})}};ly.className="GaussianDropout";ce.registerClass(ly);var uy=class extends tt{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Ve(e).shape}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return X(()=>{if(this.rate<1&&this.rate>0){let n=this._getNoiseShape(e);return Zd(()=>{let r=Ve(e),a=1.6732632423543772,o=1.0507009873554805,i=-a*o,l=dl(ju(n),this.rate);l=Gf(l,"float32");let c=((1-this.rate)*(1+this.rate*i**2))**-.5,u=-c*i*this.rate,d=ue(L(r,l),L(ue(l,-1),i));return ue(L(d,c),u)},()=>Ve(e),t.training||!1)}return e})}};uy.className="AlphaDropout";ce.registerClass(uy);function op(e,t,n,s,r,a=.001){let o;if(e.rank===2)o=fv(e,t,n,s,r,a);else if(e.rank===3)o=mv(e,t,n,s,r,a);else if(e.rank===4)o=gv(e,t,n,s,r,a);else throw new Le(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return o}function KW(e,t,n,s,r=.001){return X(()=>{let a=If(e,s),o=a.mean,i=a.variance;return[op(e,o,i,n,t,r),o,i]})}function ZW(e,t,n,s,r=.001){return X(()=>{let a=If(e,s),o=a.mean,i=a.variance,l=[];for(let f of Ar(0,e.rank))s.indexOf(f)!==-1?l.push(1):l.push(e.shape[f]);let c=H(o,l),u=H(i,l),d=t==null?null:H(t,l),p=n==null?null:H(n,l);return[op(e,c,u,p,d,r),o,i]})}function YW(e,t,n,s,r=.001){return v.arraysEqual(s.slice().sort(),Ar(0,e.rank-1))?KW(e,t,n,s,r):ZW(e,t,n,s,r)}var cy=class extends tt{constructor(e){e==null&&(e={});super(e);this.supportsMasking=!0,this.axis=e.axis==null?-1:e.axis,this.momentum=e.momentum==null?.99:e.momentum,this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=Rt(e.betaInitializer||"zeros"),this.gammaInitializer=Rt(e.gammaInitializer||"ones"),this.movingMeanInitializer=Rt(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Rt(e.movingVarianceInitializer||"ones"),this.betaConstraint=on(e.betaConstraint),this.gammaConstraint=on(e.gammaConstraint),this.betaRegularizer=$t(e.betaRegularizer),this.gammaRegularizer=$t(e.gammaRegularizer)}build(e){e=ht(e);let t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new j(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Zt({ndim:e.length,axes:{[t]:n}})];let s=[n];this.scale&&(this.gamma=this.addWeight("gamma",s,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",s,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",s,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",s,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return X(()=>{let n=t.training==null?!1:t.training,s=Ve(e),r=s.shape,a=r.length,o=Ar(0,a),i=this.axis>=0?this.axis:this.axis+a;o.splice(i,1);let l=Al(1,a);l[i]=r[i];let c=o.slice();c.sort();let u=!v.arraysEqual(c,Ar(0,a).slice(0,a-1)),d=()=>{if(u){let A=H(this.movingMean.read(),l),x=H(this.movingVariance.read(),l),y=this.center?H(this.beta.read(),l):null,b=this.scale?H(this.gamma.read(),l):null;return op(s,A,x,y,b,this.epsilon)}else return op(s,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!n)return d();let[p,h,f]=YW(s,this.gamma.read(),this.beta.read(),o,this.epsilon),m=(A,x,y)=>{X(()=>{let b=1-y,w=A.read(),k=L(fe(w,x),b);A.write(fe(w,k))})};return(()=>{m(this.movingMean,h,this.momentum),m(this.movingVariance,f,this.momentum)})(),p})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Mt(this.betaInitializer),gammaInitializer:Mt(this.gammaInitializer),movingMeanInitializer:Mt(this.movingMeanInitializer),movingVarianceInitializer:Mt(this.movingVarianceInitializer),betaRegularizer:yt(this.betaRegularizer),gammaRegularizer:yt(this.gammaRegularizer),betaConstraint:an(this.betaConstraint),gammaConstraint:an(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};cy.className="BatchNormalization";ce.registerClass(cy);var dy=class extends tt{constructor(e){e==null&&(e={});super(e);if(this.axis=e.axis==null?-1:e.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(let t of this.axis)if(!Number.isInteger(t))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=Rt(e.betaInitializer||"zeros"),this.gammaInitializer=Rt(e.gammaInitializer||"ones"),this.betaRegularizer=$t(e.betaRegularizer),this.gammaRegularizer=$t(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=ht(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let r=0;r=t)throw new Error(`Invalid axis: ${r}`);if(this.axis.length!==Mo(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);let n=this.axis.map(r=>e[r]),s=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,s):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,s):this.beta=null,this.built=!0}call(e,t){let n=Ve(e),s=n.shape,r=s.length;return X(()=>{let a=!0,{mean:o,variance:i}=If(n,this.axis,a),l=Al(1,r);for(let f of this.axis)l[f]=s[f];let c=f=>f!=null&&f.shape.length!==r?H(f,l):f,u=c(this.gamma.read()),d=c(this.beta.read()),p=[],h=[];for(let f=0;f{if(e.rank!==4)throw new j(`temporalPadding expects input tensor to be 4-D, but received a ${e.rank}-D tensor.`);if(t==null&&(t=[[1,1],[1,1]]),t.length!==2||t[0].length!==2||t[1].length!==2)throw new j("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=mr()),n!=="channelsLast"&&n!=="channelsFirst")throw new j(`Unknown data format: ${n}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let s;return n==="channelsFirst"?s=[[0,0],[0,0],t[0],t[1]]:s=[[0,0],t[0],t[1],[0,0]],Js(e,s)})}var py=class extends tt{constructor(e){e==null&&(e={});super(e);if(this.dataFormat=e.dataFormat==null?mr():e.dataFormat,e.padding==null)this.padding=[[1,1],[1,1]];else if(typeof e.padding=="number")this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,e.padding.length!==2)throw new j(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new j(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],e.padding[1].length!==2)throw new j(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);n=e.padding[1]}this.padding=[t,n]}this.inputSpec=[new Zt({ndim:4})]}computeOutputShape(e){e=ht(e);let t,n;return this.dataFormat==="channelsFirst"?(e[2]!=null&&e[2]>=0?t=e[2]+this.padding[0][0]+this.padding[0][1]:t=null,e[3]!=null&&e[3]>=0?n=e[3]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],e[1],t,n]):(e[1]!=null&&e[1]>=0?t=e[1]+this.padding[0][0]+this.padding[0][1]:t=null,e[2]!=null&&e[2]>=0?n=e[2]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],t,n,e[3]])}call(e,t){return X(()=>JW(Ve(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};py.className="ZeroPadding2D";ce.registerClass(py);function vm(e,t,n,s,r,a){return X(()=>{jt(r),Ow(a),Os(s),n==null&&(n=[1,1]),s==null&&(s="valid"),r==null&&(r=mr()),a==null&&(a="max"),e=_A(e,r);let o,i=s==="same"?"same":"valid";return a==="max"?o=Sf(e,t,n,i):o=gf(e,t,n,i),r==="channelsFirst"&&(o=Qe(o,[0,3,1,2])),o})}function Jk(e,t,n,s,r,a){return X(()=>{jt(r),Ow(a),Os(s),n==null&&(n=[1,1,1]),s==null&&(s="valid"),r==null&&(r=mr()),a==null&&(a="max"),e=Vk(e,r);let o,i=s==="same"?"same":"valid";return a==="max"?o=A1(e,t,n,i):o=s1(e,t,n,i),r==="channelsFirst"&&(o=Qe(o,[0,4,1,2,3])),o})}var Qk=class extends tt{constructor(e){e.poolSize==null&&(e.poolSize=2);super(e);if(typeof e.poolSize=="number")this.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")this.poolSize=e.poolSize;else throw new j(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(xn(this.poolSize,"poolSize"),e.strides==null)this.strides=this.poolSize;else if(typeof e.strides=="number")this.strides=[e.strides];else if(Array.isArray(e.strides)&&e.strides.length===1&&typeof e.strides[0]=="number")this.strides=e.strides;else throw new j(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);xn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,Os(this.padding),this.inputSpec=[new Zt({ndim:3})]}computeOutputShape(e){e=ht(e);let t=vr(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return X(()=>{this.invokeCallHook(e,t),e=Xd(Ve(e),2);let n=this.poolingFunction(Ve(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return ot(n,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},hy=class extends Qk{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),Os(s),vm(e,t,n,s,r,"max")}};hy.className="MaxPooling1D";ce.registerClass(hy);var fy=class extends Qk{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),Os(s),vm(e,t,n,s,r,"avg")}};fy.className="AveragePooling1D";ce.registerClass(fy);var e7=class extends tt{constructor(e){e.poolSize==null&&(e.poolSize=[2,2]);super(e);if(this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new j(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];xn(this.poolSize,"poolSize"),xn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),Os(this.padding),this.inputSpec=[new Zt({ndim:4})]}computeOutputShape(e){e=ht(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=vr(t,this.poolSize[0],this.padding,this.strides[0]),n=vr(n,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return X(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ve(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},my=class extends e7{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),Os(s),vm(e,t,n,s,r,"max")}};my.className="MaxPooling2D";ce.registerClass(my);var gy=class extends e7{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),Os(s),vm(e,t,n,s,r,"avg")}};gy.className="AveragePooling2D";ce.registerClass(gy);var t7=class extends tt{constructor(e){e.poolSize==null&&(e.poolSize=[2,2,2]);super(e);if(this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new j(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];xn(this.poolSize,"poolSize"),xn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),Os(this.padding),this.inputSpec=[new Zt({ndim:5})]}computeOutputShape(e){e=ht(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],s=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=vr(t,this.poolSize[0],this.padding,this.strides[0]),n=vr(n,this.poolSize[1],this.padding,this.strides[1]),s=vr(s,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n,s]:[e[0],t,n,s,e[4]]}call(e,t){return X(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ve(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},Ay=class extends t7{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),Os(s),Jk(e,t,n,s,r,"max")}};Ay.className="MaxPooling3D";ce.registerClass(Ay);var yy=class extends t7{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return jt(r),Os(s),Jk(e,t,n,s,r,"avg")}};yy.className="AveragePooling3D";ce.registerClass(yy);var n7=class extends tt{constructor(e){super(e);this.inputSpec=[new Zt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Le}},xy=class extends n7{constructor(e){super(e||{})}call(e,t){return X(()=>{let n=Ve(e);return Wt(n,1)})}};xy.className="GlobalAveragePooling1D";ce.registerClass(xy);var by=class extends n7{constructor(e){super(e||{})}call(e,t){return X(()=>{let n=Ve(e);return An(n,1)})}};by.className="GlobalMaxPooling1D";ce.registerClass(by);var s7=class extends tt{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,jt(this.dataFormat),this.inputSpec=[new Zt({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Le}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},vy=class extends s7{call(e,t){return X(()=>{let n=Ve(e);return this.dataFormat==="channelsLast"?Wt(n,[1,2]):Wt(n,[2,3])})}};vy.className="GlobalAveragePooling2D";ce.registerClass(vy);var wy=class extends s7{call(e,t){return X(()=>{let n=Ve(e);return this.dataFormat==="channelsLast"?An(n,[1,2]):An(n,[2,3])})}};wy.className="GlobalMaxPooling2D";ce.registerClass(wy);var r7=class extends tt{constructor(e){super(e);this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(e){this.layer!=null&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){let e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){let s=t.layer,r=br(s,n);delete t.layer;let a={layer:r};return Object.assign(a,t),new e(a)}},ky=class extends r7{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=ht(e),e.length<3)throw new j(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];let t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=ht(e);let t=[e[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),s=e[1];return[n[0],s].concat(n.slice(1))}call(e,t){return X(()=>(e=Ve(e),Kk((a,o)=>[Ve(this.layer.call(a,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};ky.className="TimeDistributed";ce.registerClass(ky);function QW(e){xl(oB,"BidirectionalMergeMode",e)}var eV="concat",Sy=class extends r7{constructor(e){super(e);let t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=br(n),t.goBackwards=t.goBackwards!==!0;let s={};if(s.className=e.layer.getClassName(),s.config=t,this.backwardLayer=br(s),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?eV:e.mergeMode,QW(this.mergeMode),e.weights)throw new Le("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){let t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let n,s,r;return this.returnState&&(r=t.slice(1)),n=t[0],n=n,this.mergeMode==="concat"?(n[n.length-1]*=2,s=[n]):this.mergeMode==null?s=[n,n.slice()]:s=[n],this.returnState?this.mergeMode==null?s.concat(r).concat(r.slice()):[n].concat(r).concat(r.slice()):is(s)}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});let r=Xk(e,n,s,this.numConstants);if(e=r.inputs,n=r.initialState,s=r.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(n==null||n.length===0)&&s==null)return super.apply(e,t);let a=[],o=[];if(n!=null){let l=n.length;if(l%2>0)throw new j("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,a.push(...n);let c=n.map(u=>new Zt({shape:u.shape}));this.forwardLayer.stateSpec=c.slice(0,l/2),this.backwardLayer.stateSpec=c.slice(l/2),o.push(...c)}if(s!=null)throw new Le("Support for constants in Bidirectional layers is not implemented yet.");let i=a[0]instanceof xr;for(let l of a)if(l instanceof xr!==i)throw new j("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(i){let l=[e].concat(a),c=this.inputSpec.concat(o),u=this.inputSpec;this.inputSpec=c;let d=super.apply(l,t);return this.inputSpec=u,d}else return super.apply(e,t)}call(e,t){return X(()=>{let n=t.initialState,s,r;if(n==null)s=this.forwardLayer.call(e,t),r=this.backwardLayer.call(e,t);else{let i=n.slice(0,n.length/2),l=n.slice(n.length/2);s=this.forwardLayer.call(e,Object.assign(t,{initialState:i})),r=this.backwardLayer.call(e,Object.assign(t,{initialState:l}))}let a;this.returnState&&(Array.isArray(s)&&(a=s.slice(1).concat(r.slice(1))),s=s[0],r=r[0]),this.returnSequences&&(r=Fs(r,1));let o;return this.mergeMode==="concat"?o=K1([s,r]):this.mergeMode==="sum"?o=ue(s,r):this.mergeMode==="ave"?o=L(.5,ue(s,r)):this.mergeMode==="mul"?o=L(s,r):this.mergeMode==null&&(o=[s,r]),this.returnState?this.mergeMode==null?o.concat(a):[o].concat(a):o})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){bl(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),bl(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let n;if(this.returnSequences?this.mergeMode==null?n=[t,t]:n=t:this.mergeMode==null?n=[null,null]:n=null,this.returnState){let r=this.forwardLayer.states.map(a=>null);return Array.isArray(n)?n.concat(r).concat(r):[n].concat(r).concat(r)}else return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(e),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){let e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){let n=br(t.layer);if(delete t.layer,t.numConstants!=null)throw new Le("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let s=t;return s.layer=n,new e(s)}};Sy.className="Bidirectional";ce.registerClass(Sy);function tV(e){return new Ju(e)}function nV(e){return new EA(e)}function sV(e){return new CA(e)}function rV(e){return new TA(e)}function aV(e){return new NA(e)}function oV(e){return new $A(e)}function iV(e){return new RA(e)}function lV(e){return new MA(e)}function uV(e){return new fm(e)}function cV(e){return new PA(e)}function dV(e){return new mm(e)}function pV(e){return new FA(e)}function hV(e){return new OA(e)}function fV(e){return new zA(e)}function mV(e){return new LA(e)}function gV(e){return new BA(e)}function AV(e){return new XA(e)}function yV(e){return new jA(e)}function xV(e){return new bm(e)}function bV(e){return new HA(e)}function vV(e){return new qA(e)}function wV(e){return new KA(e)}function kV(e){return new ZA(e)}function SV(e){return new YA(e)}function IV(e){return new QA(e)}function CV(e){return new ey(e)}function TV(e){return new ny(e)}function NV(e){return new ay(e)}function EV(e){return new sy(e)}function RV(e){return new ry(e)}function $V(e){return new ty(e)}function _V(e){return new oy(e)}function DV(e){return new cy(e)}function PV(e){return new dy(e)}function FV(e){return new py(e)}function Iy(e){return new fy(e)}function OV(e){return Iy(e)}function MV(e){return Iy(e)}function Cy(e){return new gy(e)}function zV(e){return Cy(e)}function LV(e){return Cy(e)}function Ty(e){return new yy(e)}function BV(e){return Ty(e)}function WV(e){return Ty(e)}function VV(e){return new xy(e)}function UV(e){return new vy(e)}function a7(e){return new by(e)}function o7(e){return new wy(e)}function i7(e){return new hy(e)}function l7(e){return new my(e)}function GV(e){return new Ay(e)}function HV(e){return new VA(e)}function jV(e){return new Am(e)}function qV(e){return new UA(e)}function XV(e){return new rp(e)}function KV(e){return new WA(e)}function ZV(e){return new gm(e)}function YV(e){return new GA(e)}function JV(e){return new xm(e)}function QV(e){return new oa(e)}function eU(e){return new ym(e)}function tU(e){return new Sy(e)}function nU(e){return new ky(e)}var sU=a7,rU=o7,aU=i7,oU=l7;function iU(e){return new iy(e)}function lU(e){return new ly(e)}function uU(e){return new uy(e)}function cU(e){return new JA(e)}var u7={};Oe(u7,{MAPE:()=>vU,MSE:()=>SU,binaryAccuracy:()=>dU,binaryCrossentropy:()=>pU,categoricalAccuracy:()=>fU,categoricalCrossentropy:()=>mU,cosineProximity:()=>yU,mape:()=>wU,meanAbsoluteError:()=>xU,meanAbsolutePercentageError:()=>bU,meanSquaredError:()=>kU,mse:()=>IU,precision:()=>gU,recall:()=>AU,sparseCategoricalAccuracy:()=>hU});function dU(e,t){return dA(e,t)}function pU(e,t){return ik(e,t)}function hU(e,t){return lk(e,t)}function fU(e,t){return pA(e,t)}function mU(e,t){return hA(e,t)}function gU(e,t){return ok(e,t)}function AU(e,t){return tW(e,t)}function yU(e,t){return uA(e,t)}function xU(e,t){return om(e,t)}function bU(e,t){return ec(e,t)}function vU(e,t){return ec(e,t)}function wU(e,t){return ec(e,t)}function kU(e,t){return wl(e,t)}function SU(e,t){return wl(e,t)}function IU(e,t){return wl(e,t)}var c7={};Oe(c7,{modelFromJSON:()=>FW});var d7={};Oe(d7,{l1:()=>TU,l1l2:()=>CU,l2:()=>NU});function CU(e){return new tp(e)}function TU(e){return UW(e)}function NU(e){return GW(e)}var p7=class extends Qu{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof aa))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function wm(e,t){return et}var f7=class extends p7{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new Le("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=e.monitor||"val_loss",this.minDelta=Math.abs(e.minDelta||0),this.patience=e.patience||0,this.verbose=e.verbose||0,this.mode=e.mode||"auto",this.baseline=e.baseline,["auto","min","max"].indexOf(this.mode)===-1&&(console.warn(`EarlyStopping mode '${this.mode}' is invalid. Falling back to mode 'auto'.`),this.mode="auto"),this.mode==="min"?this.monitorFunc=wm:this.mode==="max"?this.monitorFunc=h7:this.monitor.indexOf("acc")!==-1?this.monitorFunc=h7:this.monitorFunc=wm,this.monitorFunc===wm&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===wm?1/0:-1/0}async onEpochEnd(e,t){await Bo(t);let n=this.getMonitorValue(t);n!=null&&(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){e==null&&(e={});let t=e[this.monitor];return t==null&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}};function EU(e){return new f7(e)}var RU={earlyStopping:EU},$U=Y();$U.registerFlag("KEEP_INTERMEDIATE_TENSORS",()=>!1,e=>{e&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")});var wr;(function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF"})(wr||(wr={}));var m7;(function(e){let t;(function(n){n[n.LEGACY=0]="LEGACY",n[n.V1=1]="V1",n[n.V2=2]="V2"})(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(m7||(m7={}));var Ny={};function _U(e,t){let n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};Ny[e]=n}function g7(e){return Ny[e]}function DU(e){delete Ny[e]}function S(e,t,n,s,r){let a=t.inputParams[e];if(a&&a.inputIndexStart!==void 0){let i=a.inputIndexStart,l=a.inputIndexEnd===0?void 0:a.inputIndexEnd===void 0?i+1:a.inputIndexEnd;if(a.type==="tensor")return Gn(t.inputNames[a.inputIndexStart],n,s,r);if(a.type==="tensors")return t.inputNames.slice(i,l).map(p=>Gn(p,n,s,r));let c=Gn(t.inputNames.slice(i)[0],n,s,r),u=c.dataSync();return a.type==="number"?u[0]:v.toNestedArray(c.shape,u)}let o=t.attrParams[e];return o&&o.value}function Gn(e,t,n,s){let[r,a]=xs(e);if(s!=null){let i=s.getHashTableHandleByName(r);if(i!=null)return i}let o=n.currentContextIds.find(i=>!!t[km(r,i)]);return o!==void 0?t[km(r,o)][a]:void 0}function PU(e,t,n){return t[km(e,n.currentContextId)]}function Vr(e,t){let[n,s,r]=xs(e);return[km(n,t&&t.currentContextId),s,r]}function km(e,t){return t?`${e}-${t}`:e}function xs(e){let t=e.split(":");if(t.length===1)return[e,0,void 0];let n=t[0],s=t.length===3?t[1]:void 0,r=Number(t[t.length-1]);return[n,r,s]}function Sm(e,t,n){let s=S("pad",e,t,n);if(s==="explicit"){s=S("explicitPaddings",e,t,n);let r=[[0,0],[0,0],[0,0],[0,0]];for(let a=0;a<4;a++)r[a][0]=s[a*2],r[a][1]=s[a*2+1];return r}return s}function ia(e){return e.kept?e:Wn(e)}var A7={};Oe(A7,{json:()=>FU});var FU=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],y7={};Oe(y7,{json:()=>OU});var OU=[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],x7={};Oe(x7,{json:()=>MU});var MU=[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]}],b7={};Oe(b7,{json:()=>zU});var zU=[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number"}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}],v7={};Oe(v7,{json:()=>LU});var LU=[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}],w7={};Oe(w7,{json:()=>BU});var BU=[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],k7={};Oe(k7,{json:()=>WU});var WU=[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}],S7={};Oe(S7,{json:()=>VU});var VU=[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}],I7={};Oe(I7,{json:()=>UU});var UU=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]}],C7={};Oe(C7,{json:()=>GU});var GU=[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]}],T7={};Oe(T7,{json:()=>HU});var HU=[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],N7={};Oe(N7,{json:()=>jU});var jU=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]}],E7={};Oe(E7,{json:()=>qU});var qU=[{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}],R7={};Oe(R7,{json:()=>XU});var XU=[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}],$7={};Oe($7,{json:()=>KU});var KU=[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}],_7={};Oe(_7,{json:()=>ZU});var ZU=[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}],D7={};Oe(D7,{json:()=>YU});var YU=[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}],P7={};Oe(P7,{json:()=>JU});var JU=[{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}],F7={};Oe(F7,{json:()=>QU});var QU=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}],O7=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[A7,y7,x7,b7,v7,w7,k7,S7,I7,C7,T7,N7,E7,R7,$7,_7,D7,P7,F7],t=[].concat(...e.map(n=>n.json));this.opMappers=t.reduce((n,s)=>(n[s.tfOpName]=s,n),{})}transformGraph(e,t={}){let n=e.node,s=[],r=[],a=[],o=n.reduce((f,m)=>(f[m.name]=this.mapNode(m),m.op.startsWith("Placeholder")?s.push(f[m.name]):m.op==="Const"?r.push(f[m.name]):(m.input==null||m.input.length===0)&&a.push(f[m.name]),f),{}),i=[],l=[],c={},u={};t!=null&&(c=this.mapSignatureEntries(t.inputs),u=this.mapSignatureEntries(t.outputs));let d=Object.keys(o);d.forEach(f=>{let m=o[f];m.inputNames.forEach((g,A)=>{let[x,,y]=Vr(g),b=o[x];if(b.outputs!=null){let w=b.outputs.indexOf(y);if(w!==-1){let k=`${x}:${w}`;m.inputNames[A]=k}}m.inputs.push(b),b.children.push(m)})}),Object.keys(u).length===0?d.forEach(f=>{let m=o[f];m.children.length===0&&l.push(m)}):Object.keys(u).forEach(f=>{let[m]=Vr(f),g=o[m];g!=null&&(g.signatureKey=u[f],l.push(g))}),Object.keys(c).length>0?Object.keys(c).forEach(f=>{let[m]=Vr(f),g=o[m];g&&(g.signatureKey=c[f],i.push(g))}):i=s;let p={};e.library!=null&&e.library.function!=null&&(p=e.library.function.reduce((f,m)=>(f[m.signature.name]=this.mapFunction(m),f),{}));let h={nodes:o,inputs:i,outputs:l,weights:r,placeholders:s,signature:t,functions:p};return a.length>0&&(h.initNodes=a),h}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){let t=g7(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});let n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(s=>s.startsWith("^")?s.substr(1):s),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return t.inputs!=null&&(n.inputParams=t.inputs.reduce((s,r)=>(s[r.name]={type:r.type,inputIndexStart:r.start,inputIndexEnd:r.end},s),{})),t.attrs!=null&&(n.attrParams=t.attrs.reduce((s,r)=>{let a=r.type,o;switch(r.type){case"string":o=Ey(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=Ey(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"string[]":o=My(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=My(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number":o=$y(e.attr,r.tfName,r.defaultValue||0),o===void 0&&!!r.tfDeprecatedName&&(o=$y(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number[]":o=Oy(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=Oy(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool":o=Ry(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=Ry(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool[]":o=Ly(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=Ly(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape":o=Fy(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=Fy(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape[]":o=zy(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=zy(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype":o=Dy(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=Dy(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype[]":o=Py(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=Py(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"func":o=z7(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=z7(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${r.type} for op: ${e.op}`)}return s[r.name]={value:o,type:a},s},{})),n}mapFunction(e){let t=e.nodeDef,n=[],s=[],r={};t!=null&&(r=t.reduce((u,d)=>(u[d.name]=this.mapNode(d),d.op==="Const"&&s.push(u[d.name]),u),{}));let a=[],o=[];e.signature.inputArg.forEach(u=>{let[d]=Vr(u.name),p={name:d,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:_y(u.type),type:"dtype"}},children:[]};p.signatureKey=u.name,a.push(p),r[d]=p}),Object.keys(r).forEach(u=>{let d=r[u];d.inputNames.forEach((p,h)=>{let[f,,m]=Vr(p),g=r[f];if(g.outputs!=null){let A=g.outputs.indexOf(m);if(A!==-1){let x=`${f}:${A}`;d.inputNames[h]=x}}d.inputs.push(g),g.children.push(d)})});let l=e.ret;e.signature.outputArg.forEach(u=>{let[d,p]=Vr(l[u.name]),h=r[d];h!=null&&(h.defaultOutput=p,o.push(h))});let c=this.mapArgsToSignature(e);return{nodes:r,inputs:a,outputs:o,weights:s,placeholders:n,signature:c}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n),t),{}),outputs:e.signature.outputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t),{})}}mapArgToTensorInfo(e,t){let n=e.name;return t!=null&&(n=t[n]),{name:n,dtype:e.type}}};function eG(e){let t=Y().global;if(typeof t.atob!="undefined")return t.atob(e);if(typeof Buffer!="undefined")return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function M7(e,t){let n=Array.isArray(e)?String.fromCharCode.apply(null,e):eG(e);return t?n:n.toLowerCase()}function Ey(e,t,n,s=!1){let r=e[t];return r!=null?M7(r.s,s):n}function Ry(e,t,n){let s=e[t];return s?s.b:n}function $y(e,t,n){let s=e[t]||{},r=s.i!=null?s.i:s.f!=null?s.f:n;return typeof r=="number"?r:parseInt(r,10)}function _y(e){switch(typeof e=="string"&&(e=wr[e]),e){case wr.DT_FLOAT:return"float32";case wr.DT_INT32:case wr.DT_INT64:case wr.DT_INT8:case wr.DT_UINT8:return"int32";case wr.DT_BOOL:return"bool";case wr.DT_DOUBLE:return"float32";case wr.DT_STRING:return"string";default:return null}}function z7(e,t,n){let s=e[t];return s&&s.func?s.func.name:n}function Dy(e,t,n){let s=e[t];return s&&s.type?_y(s.type):n}function Py(e,t,n){let s=e[t];return s&&s.list&&s.list.type?s.list.type.map(r=>_y(r)):n}function L7(e){if(!e.unknownRank)return e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function Fy(e,t,n){let s=e[t];return s&&s.shape?L7(s.shape):n}function Oy(e,t,n){let s=e[t];return s?((s.list.f&&s.list.f.length?s.list.f:s.list.i)||[]).map(r=>typeof r=="number"?r:parseInt(r,10)):n}function My(e,t,n,s=!1){let r=e[t];return r&&r.list&&r.list.s?r.list.s.map(a=>M7(a,s)):n}function zy(e,t,n){let s=e[t];return s&&s.list&&s.list.shape?s.list.shape.map(r=>L7(r)):n}function Ly(e,t,n){let s=e[t];return s&&s.list&&s.list.b?s.list.b:n}var tG=class{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(s=>this.getInput(s)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((s,r)=>(s[r]=this.getAttr(r),s),{}))}getInput(e){return Gn(e,this.tensorMap,this.context)}getAttr(e,t){let n=this.node.rawAttrs[e];if(n.tensor!=null)return Gn(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return $y(this.node.rawAttrs,e,t);if(n.s!=null)return Ey(this.node.rawAttrs,e,t);if(n.b!=null)return Ry(this.node.rawAttrs,e,t);if(n.shape!=null)return Fy(this.node.rawAttrs,e,t);if(n.type!=null)return Dy(this.node.rawAttrs,e,t);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return Oy(this.node.rawAttrs,e,t);if(n.list.s!=null)return My(this.node.rawAttrs,e,t);if(n.list.shape!=null)return zy(this.node.rawAttrs,e,t);if(n.list.b!=null)return Ly(this.node.rawAttrs,e,t);if(n.list.type!=null)return Py(this.node.rawAttrs,e,t)}return t}},nG=(e,t,n)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[ue(S("a",e,t,n),S("b",e,t,n))];case"AddN":return[hf(S("tensors",e,t,n))];case"FloorMod":case"Mod":return[Ld(S("a",e,t,n),S("b",e,t,n))];case"Mul":return[L(S("a",e,t,n),S("b",e,t,n))];case"RealDiv":case"Div":return[ge(S("a",e,t,n),S("b",e,t,n))];case"DivNoNan":return[Tv(S("a",e,t,n),S("b",e,t,n))];case"FloorDiv":return[pf(S("a",e,t,n),S("b",e,t,n))];case"Sub":return[fe(S("a",e,t,n),S("b",e,t,n))];case"Minimum":return[zd(S("a",e,t,n),S("b",e,t,n))];case"Maximum":return[ea(S("a",e,t,n),S("b",e,t,n))];case"Pow":return[Po(S("a",e,t,n),S("b",e,t,n))];case"SquaredDifference":return[E1(S("a",e,t,n),S("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},sG=(e,t,n)=>{switch(e.op){case"Abs":case"ComplexAbs":return[nn(S("x",e,t,n))];case"Acos":return[sv(S("x",e,t,n))];case"Acosh":return[rv(S("x",e,t,n))];case"Asin":return[ov(S("x",e,t,n))];case"Asinh":return[iv(S("x",e,t,n))];case"Atan":return[lv(S("x",e,t,n))];case"Atan2":return[uv(S("x",e,t,n),S("y",e,t,n))];case"Atanh":return[cv(S("x",e,t,n))];case"Ceil":return[yv(S("x",e,t,n))];case"Complex":return[To(S("real",e,t,n),S("imag",e,t,n))];case"Cos":return[yf(S("x",e,t,n))];case"Cosh":return[u1(S("x",e,t,n))];case"Elu":return[Od(S("x",e,t,n))];case"Erf":return[Ev(S("x",e,t,n))];case"Exp":return[_s(S("x",e,t,n))];case"Expm1":return[Rv(S("x",e,t,n))];case"Floor":return[Md(S("x",e,t,n))];case"Log":return[Ds(S("x",e,t,n))];case"Log1p":return[vf(S("x",e,t,n))];case"Imag":return[xf(S("x",e,t,n))];case"Neg":return[Ot(S("x",e,t,n))];case"Reciprocal":return[Uv(S("x",e,t,n))];case"Real":return[Bd(S("x",e,t,n))];case"Relu":return[Or(S("x",e,t,n))];case"Round":return[w1(S("x",e,t,n))];case"Selu":return[S1(S("x",e,t,n))];case"Sigmoid":return[ms(S("x",e,t,n))];case"Sin":return[I1(S("x",e,t,n))];case"Sign":return[jv(S("x",e,t,n))];case"Sinh":return[C1(S("x",e,t,n))];case"Softplus":return[Gu(S("x",e,t,n))];case"Sqrt":return[Dn(S("x",e,t,n))];case"Square":return[At(S("x",e,t,n))];case"Tanh":return[Lu(S("x",e,t,n))];case"Tan":return[Xv(S("x",e,t,n))];case"ClipByValue":return[gs(S("x",e,t,n),S("clipValueMin",e,t,n),S("clipValueMax",e,t,n))];case"Relu6":return[v1(S("x",e,t,n))];case"Rsqrt":return[k1(Gn(e.inputNames[0],t,n))];case"Prod":return[y1(S("x",e,t,n),S("axes",e,t,n))];case"LeakyRelu":return[bf(S("x",e,t,n),S("alpha",e,t,n))];case"Prelu":return[Tf(S("x",e,t,n),S("alpha",e,t,n))];case"IsNan":return[$v(Gn(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function nr(e,t,n=""){if(!(typeof e=="number"||typeof t=="number")){v.assert(e.length===t.length,()=>n+` Shapes ${e} and ${t} must match`);for(let s=0;sn+` Shapes ${e} and ${t} must match`)}}}function B7(e){return!(typeof e=="number"||e.some(t=>t<0))}function ip(e,t,n){let s=By(e,n),r=!B7(s);if(r&&t.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${s}`);if(r&&t.forEach(a=>{s=By(a.shape,s)}),!B7(s))throw new Error(`Non-fully-defined elementShape: ${s}`);return s}function By(e,t){if(typeof e=="number")return t;if(typeof t=="number")return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);let n=[];for(let s=0;s=0&&a>=0&&r!==a)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[s]=r>=0?r:a}return n}var rG=class{constructor(e,t,n,s,r,a,o){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=s,this.identicalElementShapes=r,this.dynamicSize=a,this.clearAfterRead=o,this.tensors=[],this.closed_=!1,this.idTensor=Ie(0),gn(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.tensor.id))&&t.tensor.dispose()}),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);let t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map(t=>this.read(t))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);let n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),nr(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,gn(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((n,s)=>this.write(n,t[s]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let s=0;s=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,os(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0,s=e.map(i=>(n+=i,n));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to tensor.shape[0], but sum of lengths is ${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);let r=n===0?0:t.size/n,a=[];X(()=>{t=H(t,[1,n,r]);for(let i=0;i{if(n!==r.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${r.dtype}`);nr(t,r.shape,"TensorList shape mismatch: "),gn(r)}),this.idTensor=Ie(0),this.maxNumElements=s,gn(this.idTensor)}get id(){return this.idTensor.id}copy(){return new lp([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(n!==-1&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);nr(e,this.elementShape,"TensorList shape mismatch: ");let s=ip(this.elementShape,this.tensors,e);return X(()=>{let r=this.tensors.map(a=>H(a,s));return yn(r,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n=ip(this.elementShape,this.tensors,e),s=this.tensors.pop();return nr(s.shape,e,"TensorList shape mismatch: "),H(s,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(nr(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");gn(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);this.tensors.length=e}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);nr(this.tensors[e].shape,t,"TensorList shape mismatch: ");let s=ip(this.elementShape,this.tensors,t);return H(this.tensors[e],s)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);nr(this.elementShape,t.shape,"TensorList shape mismatch: "),gn(t),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);nr(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let s=ip(this.elementShape,this.tensors,n);return e.length===0?ut([],[0].concat(s)):X(()=>{let r=e.map(a=>H(this.tensors[a],s));return yn(r,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);nr(this.elementShape,t,"TensorList shape mismatch: ");let n=ip(this.elementShape,this.tensors,t);return this.size()===0?ut([],[0].concat(n)):X(()=>{let s=this.tensors.map(r=>H(r,n));return wt(s,0)})}};function aG(e,t,n){let s=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);let r=e.shape.slice(1);nr(r,t,"TensorList shape mismatch: ");let a=os(e);return new lp(a,t,s)}function oG(e,t,n){return new lp([],e,t,n)}function iG(e,t,n,s){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);let r=Math.max(...t);if(s!=null&&s!==-1&&r>=s)throw new Error(`Max index must be < array size (${r} vs. ${s})`);let a=new lp([],n,e.dtype,s),o=os(e,0);return t.forEach((i,l)=>{a.setItem(i,o[l])}),a}function lG(e,t,n){let s=0,r=t.map(u=>(s+=u,s));if(s!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to tensor.shape[0], but sum of lengths is ${s}, and tensor's shape is: ${e.shape}`);let a=e.shape.slice(1),o=By(a,n),i=s===0?0:e.size/s,l=X(()=>{let u=[];e=H(e,[1,s,i]);for(let d=0;d{switch(e.op){case"If":case"StatelessIf":{let s=S("thenBranch",e,t,n),r=S("elseBranch",e,t,n),a=S("cond",e,t,n),o=S("args",e,t,n);return(await a.data())[0]?n.functionMap[s].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap):n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{let s=S("body",e,t,n),r=S("cond",e,t,n),a=S("args",e,t,n),o=await n.functionMap[r].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),i=a.map(u=>u.id),l=await o[0].data();o.forEach(u=>{!u.kept&&i.indexOf(u.id)===-1&&u.dispose()});let c=a;for(;l[0];){let u=c;c=await n.functionMap[s].executeFunctionAsync(c,n.tensorArrayMap,n.tensorListMap);let d=c.map(h=>h.id);u.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()});let p=await n.functionMap[r].executeFunctionAsync(c,n.tensorArrayMap,n.tensorListMap);l=await p[0].data(),p.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&d.indexOf(h.id)===-1&&h.dispose()})}return c}case"LoopCond":{let s=S("pred",e,t,n);return[ia(s)]}case"Switch":{let s=S("pred",e,t,n),r=S("data",e,t,n);return r.kept||(r=ia(r)),(await s.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{let s=e.inputNames.find(r=>Gn(r,t,n)!==void 0);if(s){let r=Gn(s,t,n);return[ia(r)]}return}case"Enter":{let s=S("frameName",e,t,n),r=S("tensor",e,t,n);return n.enterFrame(s),[ia(r)]}case"Exit":{let s=S("tensor",e,t,n);return n.exitFrame(),[ia(s)]}case"NextIteration":{let s=S("tensor",e,t,n);return n.nextIteration(),[ia(s)]}case"TensorArrayV3":{let s=S("size",e,t,n),r=S("dtype",e,t,n),a=S("elementShape",e,t,n),o=S("dynamicSize",e,t,n),i=S("clearAfterRead",e,t,n),l=S("identicalElementShapes",e,t,n),c=S("name",e,t,n),u=new rG(c,r,s,a,l,o,i);return n.addTensorArray(u),[u.idTensor,Ie(1)]}case"TensorArrayWriteV3":{let s=S("tensorArrayId",e,t,n),r=S("index",e,t,n),a=S("tensor",e,t,n),o=n.getTensorArray(s.id);return o.write(r,a),[o.idTensor]}case"TensorArrayReadV3":{let s=S("tensorArrayId",e,t,n),r=S("index",e,t,n);return[n.getTensorArray(s.id).read(r)]}case"TensorArrayGatherV3":{let s=S("tensorArrayId",e,t,n),r=S("indices",e,t,n),a=S("dtype",e,t,n);return[n.getTensorArray(s.id).gather(r,a)]}case"TensorArrayScatterV3":{let s=S("tensorArrayId",e,t,n),r=S("indices",e,t,n),a=S("tensor",e,t,n),o=n.getTensorArray(s.id);return o.scatter(r,a),[o.idTensor]}case"TensorArrayConcatV3":{let s=S("tensorArrayId",e,t,n),r=n.getTensorArray(s.id),a=S("dtype",e,t,n);return[r.concat(a)]}case"TensorArraySplitV3":{let s=S("tensorArrayId",e,t,n),r=S("tensor",e,t,n),a=S("lengths",e,t,n),o=n.getTensorArray(s.id);return o.split(a,r),[o.idTensor]}case"TensorArraySizeV3":{let s=S("tensorArrayId",e,t,n),r=n.getTensorArray(s.id);return[Ie(r.size(),"int32")]}case"TensorArrayCloseV3":{let s=S("tensorArrayId",e,t,n),r=n.getTensorArray(s.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{let s=S("tensorListId",e,t,n),r=S("index",e,t,n),a=S("tensor",e,t,n),o=n.getTensorList(s.id);return o.setItem(r,a),[o.idTensor]}case"TensorListGetItem":{let s=S("tensorListId",e,t,n),r=S("index",e,t,n),a=S("elementShape",e,t,n),o=S("elementDType",e,t,n);return[n.getTensorList(s.id).getItem(r,a,o)]}case"TensorListScatterV2":case"TensorListScatter":{let s=S("indices",e,t,n),r=S("tensor",e,t,n),a=S("elementShape",e,t,n),o=S("numElements",e,t,n),i=iG(r,s,a,o);return n.addTensorList(i),[i.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let s=S("elementShape",e,t,n),r=S("elementDType",e,t,n),a;e.op==="TensorListReserve"?a="numElements":a="maxNumElements";let o=S(a,e,t,n),i=oG(s,r,o);return n.addTensorList(i),[i.idTensor]}case"TensorListGather":{let s=S("tensorListId",e,t,n),r=S("indices",e,t,n),a=S("elementShape",e,t,n),o=S("elementDType",e,t,n);return[n.getTensorList(s.id).gather(r,o,a)]}case"TensorListStack":{let s=S("tensorListId",e,t,n),r=S("elementShape",e,t,n),a=S("elementDType",e,t,n),o=S("numElements",e,t,n);return[n.getTensorList(s.id).stack(r,a,o)]}case"TensorListFromTensor":{let s=S("tensor",e,t,n),r=S("elementShape",e,t,n),a=S("elementDType",e,t,n),o=aG(s,r,a);return n.addTensorList(o),[o.idTensor]}case"TensorListConcat":{let s=S("tensorListId",e,t,n),r=n.getTensorList(s.id),a=S("dtype",e,t,n),o=S("elementShape",e,t,n);return[r.concat(a,o)]}case"TensorListPushBack":{let s=S("tensorListId",e,t,n),r=S("tensor",e,t,n),a=n.getTensorList(s.id);return a.pushBack(r),[a.idTensor]}case"TensorListPopBack":{let s=S("tensorListId",e,t,n),r=S("elementShape",e,t,n),a=S("elementDType",e,t,n);return[n.getTensorList(s.id).popBack(r,a)]}case"TensorListSplit":{let s=S("tensor",e,t,n),r=S("elementShape",e,t,n),a=S("lengths",e,t,n),o=lG(s,a,r);return n.addTensorList(o),[o.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function W7(e,t,n){let[s,r]=S("fusedOps",e,t,n),a=s==="biasadd",o=!a,i=r==="prelu",l=s==="fusedbatchnorm",c=S("numArgs",e,t,n);if(a){if(i&&c!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&a&&c!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");let u=S("strides",e,t,n),d=Sm(e,t,n),p=S("dataFormat",e,t,n).toUpperCase(),h=S("dilations",e,t,n),[f,m]=S("args",e,t,n);o&&(m=f,f=void 0);let g=S("leakyreluAlpha",e,t,n);return{stride:u,pad:d,dataFormat:p,dilations:h,biasArg:f,preluArg:m,activationFunc:r,leakyreluAlpha:g}}var cG=(e,t,n)=>{switch(e.op){case"Conv1D":{let s=S("stride",e,t,n),r=S("pad",e,t,n),a=S("dataFormat",e,t,n).toUpperCase(),o=S("dilation",e,t,n);return[a1(S("x",e,t,n),S("filter",e,t,n),s,r,a,o)]}case"Conv2D":{let s=S("strides",e,t,n),r=Sm(e,t,n),a=S("dataFormat",e,t,n).toUpperCase(),o=S("dilations",e,t,n);return[_o(S("x",e,t,n),S("filter",e,t,n),[s[1],s[2]],r,a,[o[1],o[2]])]}case"_FusedConv2D":{let{stride:s,pad:r,dataFormat:a,dilations:o,biasArg:i,preluArg:l,activationFunc:c,leakyreluAlpha:u}=W7(e,t,n);return[Fo.conv2d({x:S("x",e,t,n),filter:S("filter",e,t,n),strides:[s[1],s[2]],pad:r,dataFormat:a,dilations:[o[1],o[2]],bias:i,activation:c,preluActivationWeights:l,leakyreluAlpha:u})]}case"FusedDepthwiseConv2dNative":{let{stride:s,pad:r,dataFormat:a,dilations:o,biasArg:i,preluArg:l,activationFunc:c,leakyreluAlpha:u}=W7(e,t,n);return[Fo.depthwiseConv2d({x:S("x",e,t,n),filter:S("filter",e,t,n),strides:[s[1],s[2]],pad:r,dataFormat:a,dilations:[o[1],o[2]],bias:i,activation:c,preluActivationWeights:l,leakyreluAlpha:u})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let s=S("outputShape",e,t,n),r=S("strides",e,t,n),a=Sm(e,t,n);return[i1(S("x",e,t,n),S("filter",e,t,n),s,[r[1],r[2]],a)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let s=S("strides",e,t,n),r=Sm(e,t,n),a=S("dilations",e,t,n),o=S("dataFormat",e,t,n).toUpperCase();return[Fd(S("input",e,t,n),S("filter",e,t,n),[s[1],s[2]],r,o,[a[1],a[2]])]}case"Conv3D":{let s=S("strides",e,t,n),r=S("pad",e,t,n),a=S("dataFormat",e,t,n).toUpperCase(),o=S("dilations",e,t,n);return[l1(S("x",e,t,n),S("filter",e,t,n),[s[1],s[2],s[3]],r,a,[o[1],o[2],o[3]])]}case"AvgPool":{let s=S("strides",e,t,n),r=S("pad",e,t,n),a=S("kernelSize",e,t,n);return[gf(S("x",e,t,n),[a[1],a[2]],[s[1],s[2]],r)]}case"MaxPool":{let s=S("strides",e,t,n),r=S("pad",e,t,n),a=S("kernelSize",e,t,n);return[Sf(S("x",e,t,n),[a[1],a[2]],[s[1],s[2]],r)]}case"MaxPoolWithArgmax":{let s=S("strides",e,t,n),r=S("pad",e,t,n),a=S("kernelSize",e,t,n),o=S("includeBatchInIndex",e,t,n),{result:i,indexes:l}=Lv(S("x",e,t,n),[a[1],a[2]],[s[1],s[2]],r,o);return[i,l]}case"AvgPool3D":{let s=S("strides",e,t,n),r=S("pad",e,t,n),a=S("kernelSize",e,t,n);return[s1(S("x",e,t,n),[a[1],a[2],a[3]],[s[1],s[2],s[3]],r)]}case"MaxPool3D":{let s=S("strides",e,t,n),r=S("pad",e,t,n),a=S("kernelSize",e,t,n);return[A1(S("x",e,t,n),[a[1],a[2],a[3]],[s[1],s[2],s[3]],r)]}case"Dilation2D":{let s=S("strides",e,t,n),r=S("pad",e,t,n),a=S("dilations",e,t,n),o=s[1],i=s[2],l=a[1],c=a[2];return[Cv(S("x",e,t,n),S("filter",e,t,n),[o,i],r,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},dG=(e,t,n)=>{switch(e.op){case"Fill":{let s=S("shape",e,t,n),r=S("dtype",e,t,n),a=S("value",e,t,n);return[Vu(s,a,r)]}case"LinSpace":{let s=S("start",e,t,n),r=S("stop",e,t,n),a=S("num",e,t,n);return[_v(s,r,a)]}case"Multinomial":{let s=S("logits",e,t,n),r=S("numSamples",e,t,n),a=S("seed",e,t,n);return[Wv(s,r,a)]}case"OneHot":{let s=S("indices",e,t,n),r=S("depth",e,t,n),a=S("onValue",e,t,n),o=S("offValue",e,t,n);return[_d(s,r,a,o)]}case"Ones":return[ys(S("shape",e,t,n),S("dtype",e,t,n))];case"OnesLike":return[Ps(S("x",e,t,n))];case"RandomUniform":return[ju(S("shape",e,t,n),S("minval",e,t,n),S("maxval",e,t,n),S("dtype",e,t,n))];case"Range":{let s=S("start",e,t,n),r=S("stop",e,t,n),a=S("step",e,t,n);return[qu(s,r,a,S("dtype",e,t,n))]}case"TruncatedNormal":{let s=S("shape",e,t,n),r=S("mean",e,t,n),a=S("stdDev",e,t,n),o=S("seed",e,t,n);return[$f(s,r,a,S("dtype",e,t,n),o)]}case"Zeros":return[Ht(S("shape",e,t,n),S("dtype",e,t,n))];case"ZerosLike":return[et(S("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Wy(e,t,n){let s=S("boxes",e,t,n),r=S("scores",e,t,n),a=S("maxOutputSize",e,t,n),o=S("iouThreshold",e,t,n),i=S("scoreThreshold",e,t,n),l=S("softNmsSigma",e,t,n);return{boxes:s,scores:r,maxOutputSize:a,iouThreshold:o,scoreThreshold:i,softNmsSigma:l}}var pG=async(e,t,n)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:s,scores:r,maxOutputSize:a,iouThreshold:o,scoreThreshold:i,softNmsSigma:l}=Wy(e,t,n),c=await Ce.nonMaxSuppressionWithScoreAsync(s,r,a,o,i,l);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:s,scores:r,maxOutputSize:a,iouThreshold:o,scoreThreshold:i}=Wy(e,t,n),l=S("padToMaxOutputSize",e,t,n),c=await Ce.nonMaxSuppressionPaddedAsync(s,r,a,o,i,l);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:s,scores:r,maxOutputSize:a,iouThreshold:o,scoreThreshold:i}=Wy(e,t,n);return[await Ce.nonMaxSuppressionAsync(s,r,a,o,i)]}case"Where":{let s=me(S("condition",e,t,n),"bool"),r=[await $1(s)];return s.dispose(),r}case"ListDiff":return Hv(S("x",e,t,n),S("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}},hG=(e,t,n)=>{switch(e.op){case"TopKV2":{let s=S("x",e,t,n),r=S("k",e,t,n),a=S("sorted",e,t,n),o=Kv(s,r,a);return[o.values,o.indices]}case"Unique":{let s=S("x",e,t,n),r=R1(s);return[r.values,r.indices]}case"UniqueV2":{let s=S("x",e,t,n),r=S("axis",e,t,n),a=R1(s,r);return[a.values,a.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},fG=(e,t,n)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let s=S("default",e,t,n);return[Gn(e.name,t,n)||s];case"Placeholder":return[Gn(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let c=S("x",e,t,n);return[ia(c)]}case"IdentityN":return S("x",e,t,n).map(c=>ia(c));case"Snapshot":let r=S("x",e,t,n);return[ia(r)];case"Shape":return[Vt(S("x",e,t,n).shape,"int32")];case"ShapeN":return S("x",e,t,n).map(c=>Vt(c.shape));case"Size":return[Ie(S("x",e,t,n).size,"int32")];case"Rank":return[Ie(S("x",e,t,n).rank,"int32")];case"NoOp":return[Ie(1)];case"Print":let a=S("x",e,t,n),o=S("data",e,t,n),i=S("message",e,t,n),l=S("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(i);for(let c=0;ce.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Ie(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return this.tensorMap.forEach(s=>s.dispose()),this.tensorMap.clear(),X(()=>{let s=os(t),r=n.length,a=s.length;v.assert(r===a,()=>`The number of elements doesn't match, keys has ${r} elements, the values has ${a} elements.`);for(let o=0;o{let s=[];for(let r=0;r{switch(e.op){case"HashTable":case"HashTableV2":{let r=S("keyDType",e,t,n),a=S("valueDType",e,t,n),o=new mG(r,a);return s.addHashTable(e.name,o),[o.handle]}case"LookupTableImport":case"LookupTableImportV2":{let r=S("tableHandle",e,t,n,s),a=S("keys",e,t,n),o=S("values",e,t,n);return[await s.getHashTableById(r.id).import(a,o)]}case"LookupTableFind":case"LookupTableFindV2":{let r=S("tableHandle",e,t,n,s),a=S("keys",e,t,n),o=S("defaultValue",e,t,n);return[await s.getHashTableById(r.id).find(a,o)]}case"LookupTableSize":case"LookupTableSizeV2":{let r=S("tableHandle",e,t,n,s);return[s.getHashTableById(r.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},AG=(e,t,n)=>{switch(e.op){case"ResizeBilinear":{let s=S("images",e,t,n),r=S("size",e,t,n),a=S("alignCorners",e,t,n),o=S("halfPixelCenters",e,t,n);return[Ce.resizeBilinear(s,[r[0],r[1]],a,o)]}case"ResizeNearestNeighbor":{let s=S("images",e,t,n),r=S("size",e,t,n),a=S("alignCorners",e,t,n),o=S("halfPixelCenters",e,t,n);return[Ce.resizeNearestNeighbor(s,[r[0],r[1]],a,o)]}case"CropAndResize":{let s=S("image",e,t,n),r=S("boxes",e,t,n),a=S("boxInd",e,t,n),o=S("cropSize",e,t,n),i=S("method",e,t,n),l=S("extrapolationValue",e,t,n);return[Ce.cropAndResize(s,r,a,o,i,l)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},yG=(e,t,n)=>{switch(e.op){case"Equal":return[$s(S("a",e,t,n),S("b",e,t,n))];case"NotEqual":return[Hu(S("a",e,t,n),S("b",e,t,n))];case"Greater":return[As(S("a",e,t,n),S("b",e,t,n))];case"GreaterEqual":return[dl(S("a",e,t,n),S("b",e,t,n))];case"Less":return[p1(S("a",e,t,n),S("b",e,t,n))];case"LessEqual":return[pl(S("a",e,t,n),S("b",e,t,n))];case"LogicalAnd":return[hr(S("a",e,t,n),S("b",e,t,n))];case"LogicalNot":return[kf(S("a",e,t,n))];case"LogicalOr":return[g1(S("a",e,t,n),S("b",e,t,n))];case"Select":case"SelectV2":return[Vn(S("condition",e,t,n),S("a",e,t,n),S("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},xG=(e,t,n)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[He(S("a",e,t,n),S("b",e,t,n),S("transposeA",e,t,n),S("transposeB",e,t,n))];case"Einsum":return[Nv(S("equation",e,t,n),...S("tensors",e,t,n))];case"Transpose":return[Qe(S("x",e,t,n),S("perm",e,t,n))];case"_FusedMatMul":let[s,r]=S("fusedOps",e,t,n),a=s==="biasadd",o=r==="prelu",i=S("numArgs",e,t,n),l=S("leakyreluAlpha",e,t,n);if(a){if(o&&i!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&i!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[c,u]=S("args",e,t,n);return[Fo.matMul({a:S("a",e,t,n),b:S("b",e,t,n),transposeA:S("transposeA",e,t,n),transposeB:S("transposeB",e,t,n),bias:c,activation:r,preluActivationWeights:u,leakyreluAlpha:l})];default:throw TypeError(`Node type ${e.op} is not implemented`)}},bG=(e,t,n)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[Bu(S("x",e,t,n),S("mean",e,t,n),S("variance",e,t,n),S("offset",e,t,n),S("scale",e,t,n),S("epsilon",e,t,n))];case"FusedBatchNormV3":return[Bu(S("x",e,t,n),S("mean",e,t,n),S("variance",e,t,n),S("offset",e,t,n),S("scale",e,t,n),S("epsilon",e,t,n))];case"LRN":return[Dv(S("x",e,t,n),S("radius",e,t,n),S("bias",e,t,n),S("alpha",e,t,n),S("beta",e,t,n))];case"Softmax":return[Xu(S("x",e,t,n))];case"LogSoftmax":return[h1(S("x",e,t,n))];case"SparseToDense":return[D1(S("sparseIndices",e,t,n),S("outputShape",e,t,n),S("sparseValues",e,t,n),S("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},vG=(e,t,n)=>{switch(e.op){case"Max":{let o=S("axis",e,t,n),i=S("keepDims",e,t,n);return[An(S("x",e,t,n),o,i)]}case"Mean":{let o=S("axis",e,t,n),i=S("keepDims",e,t,n);return[Wt(S("x",e,t,n),o,i)]}case"Min":{let o=S("axis",e,t,n),i=S("keepDims",e,t,n);return[Do(S("x",e,t,n),o,i)]}case"Sum":{let o=S("axis",e,t,n),i=S("keepDims",e,t,n);return[ke(S("x",e,t,n),o,i)]}case"All":{let o=S("axis",e,t,n),i=S("keepDims",e,t,n);return[e1(S("x",e,t,n),o,i)]}case"Any":{let o=S("axis",e,t,n),i=S("keepDims",e,t,n);return[ff(S("x",e,t,n),o,i)]}case"ArgMax":{let o=S("axis",e,t,n);return[Zs(S("x",e,t,n),o)]}case"ArgMin":{let o=S("axis",e,t,n);return[av(S("x",e,t,n),o)]}case"Prod":{let o=S("axis",e,t,n),i=S("keepDims",e,t,n);return[y1(S("x",e,t,n),o,i)]}case"Cumsum":{let o=S("axis",e,t,n),i=S("exclusive",e,t,n),l=S("reverse",e,t,n);return[c1(S("x",e,t,n),o,i,l)]}case"Bincount":let s=S("x",e,t,n),r=S("weights",e,t,n),a=S("size",e,t,n);return[r1(s,r,a)];case"DenseBincount":{let o=S("x",e,t,n),i=S("weights",e,t,n),l=S("size",e,t,n),c=S("binaryOutput",e,t,n);return[Sv(o,i,l,c)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},wG=(e,t,n)=>{switch(e.op){case"ConcatV2":case"Concat":{let s=S("n",e,t,n),r=S("axis",e,t,n),a=S("tensors",e,t,n);return a=a.slice(0,s),[wt(a,r)]}case"Gather":{let s=S("x",e,t,n),r=S("indices",e,t,n);return[Uu(s,me(r,"int32"),0)]}case"GatherV2":{let s=S("axis",e,t,n),r=S("batchDims",e,t,n),a=S("x",e,t,n),o=S("indices",e,t,n);return[Uu(a,me(o,"int32"),s,r)]}case"Reverse":{let s=S("dims",e,t,n),r=[];for(let o=0;o{let s=S("axis",e,t,n),r=S("tensors",e,t,n),a=r[0].shape,o=ot(r[0]).shape,i=r.map(l=>{let c=v.arraysEqual(l.shape,a);if(!c&&!v.arraysEqual(ot(l).shape,o))throw new Error("the input tensors shape does not match");return c?l:H(l,a)});return[yn(i,s)]});case"Unpack":{let s=S("axis",e,t,n),r=S("tensor",e,t,n);return os(r,s)}case"Tile":{let s=S("reps",e,t,n);return[Ys(S("x",e,t,n),s)]}case"Split":case"SplitV":{let s=S("axis",e,t,n),r=S("numOrSizeSplits",e,t,n),a=S("x",e,t,n);return sn(a,r,s)}case"ScatterNd":{let s=S("indices",e,t,n),r=S("values",e,t,n),a=S("shape",e,t,n);return[ew(s,r,a)]}case"GatherNd":{let s=S("x",e,t,n),r=S("indices",e,t,n);return[tw(s,r)]}case"SparseToDense":{let s=S("sparseIndices",e,t,n),r=S("outputShape",e,t,n),a=S("sparseValues",e,t,n),o=S("defaultValue",e,t,n);return[D1(s,a,r,a.dtype===o.dtype?o:me(o,a.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},kG=(e,t,n)=>{switch(e.op){case"SparseFillEmptyRows":{let{outputIndices:s,outputValues:r,emptyRowIndicator:a,reverseIndexMap:o}=Ud.sparseFillEmptyRows(S("indices",e,t,n),S("values",e,t,n),S("denseShape",e,t,n),S("defaultValue",e,t,n));return[s,r,a,o]}case"SparseReshape":{let{outputIndices:s,outputShape:r}=Ud.sparseReshape(S("inputIndices",e,t,n),S("inputShape",e,t,n),S("newShape",e,t,n));return[s,r]}case"SparseSegmentMean":return[Ud.sparseSegmentMean(S("data",e,t,n),S("indices",e,t,n),S("segmentIds",e,t,n))];case"SparseSegmentSum":return[Ud.sparseSegmentSum(S("data",e,t,n),S("indices",e,t,n),S("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},SG=(e,t,n)=>{switch(e.op){case"FFT":return[Ef(S("x",e,t,n))];case"IFFT":return[Wd(S("x",e,t,n))];case"RFFT":return[Rf(S("x",e,t,n))];case"IRFFT":return[N1(S("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},IG=(e,t,n)=>{switch(e.op){case"StringNGrams":{let{nGrams:s,nGramsSplits:r}=Of.stringNGrams(S("data",e,t,n),S("dataSplits",e,t,n),S("separator",e,t,n),S("nGramWidths",e,t,n),S("leftPad",e,t,n),S("rightPad",e,t,n),S("padWidth",e,t,n),S("preserveShortSequences",e,t,n));return[s,r]}case"StringSplit":{let{indices:s,values:r,shape:a}=Of.stringSplit(S("input",e,t,n),S("delimiter",e,t,n),S("skipEmpty",e,t,n));return[s,r,a]}case"StringToHashBucketFast":return[Of.stringToHashBucketFast(S("input",e,t,n),S("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},CG=(e,t,n)=>{switch(e.op){case"Cast":return[me(S("x",e,t,n),S("dtype",e,t,n))];case"ExpandDims":{let s=S("axis",e,t,n);return[Kt(S("x",e,t,n),s)]}case"Squeeze":{let s=S("axis",e,t,n);return[ot(S("x",e,t,n),s)]}case"Reshape":return[H(S("x",e,t,n),S("shape",e,t,n))];case"MirrorPad":return[Bv(S("x",e,t,n),S("padding",e,t,n),S("mode",e,t,n))];case"PadV2":case"Pad":return[Js(S("x",e,t,n),S("padding",e,t,n),S("constantValue",e,t,n))];case"SpaceToBatchND":{let s=S("blockShape",e,t,n),r=S("paddings",e,t,n);return[Cf(S("x",e,t,n),s,r)]}case"BatchToSpaceND":{let s=S("blockShape",e,t,n),r=S("crops",e,t,n);return[Af(S("x",e,t,n),s,r)]}case"DepthToSpace":{let s=S("blockSize",e,t,n),r=S("dataFormat",e,t,n).toUpperCase();return[Iv(S("x",e,t,n),s,r)]}case"BroadcastTo":return[Pd(S("x",e,t,n),S("shape",e,t,n))];case"BroadcastArgs":return[Av(S("s0",e,t,n),S("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function V7(e,t,n,s){let r=((a,o,i)=>{switch(a.category){case"arithmetic":return X(()=>nG(a,o,i));case"basic_math":return X(()=>sG(a,o,i));case"control":return uG(a,o,i);case"convolution":return X(()=>cG(a,o,i));case"creation":return X(()=>dG(a,o,i));case"dynamic":return pG(a,o,i);case"evaluation":return X(()=>hG(a,o,i));case"image":return X(()=>AG(a,o,i));case"graph":return X(()=>fG(a,o,i));case"logical":return X(()=>yG(a,o,i));case"matrices":return X(()=>xG(a,o,i));case"normalization":return X(()=>bG(a,o,i));case"reduction":return X(()=>vG(a,o,i));case"slice_join":return X(()=>wG(a,o,i));case"sparse":return X(()=>kG(a,o,i));case"spectral":return X(()=>SG(a,o,i));case"string":return X(()=>IG(a,o,i));case"transformation":return X(()=>CG(a,o,i));case"hash_table":return gG(a,o,i,s);case"custom":let l=g7(a.op);if(l&&l.customExecutor)return l.customExecutor(new tG(a,o,i));throw TypeError(`Custom op ${a.op} is not registered.`);default:throw TypeError(`Unknown op '${a.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return v.isPromise(r)?r.then(a=>[].concat(a)):[].concat(r)}var U7=class{constructor(e={},t={},n={},s={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=s,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){let e=[];for(let t=0;tt.id===0&&t.iterationId===0?"":`${t.frameName}-${t.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(this.contexts&&this.contexts.length>1)this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();else throw new Error("Cannot exit frame, the context is empty")}nextIteration(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice(),this.lastId++;let e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else throw new Error("Cannot increase frame iteration, the context is empty")}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(let t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(let t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}};function G7(e,t,n,s){let r=new Set,a=[],o=null,i=null,l=new Set,c=Object.keys(e).map(p=>xs(p)[0]),u=[];s!=null&&(u=s.map(p=>xs(p.name)[0]));let d=[...t];for(;d.length>0;){let p=d.pop();if((H7(p)||$G(p)||_G(p))&&o==null&&(o=p,i=o.children.map(h=>h.name).filter(h=>r.has(h))),r.add(p.name),n[p.name]==null&&c.indexOf(p.name)===-1&&u.indexOf(p.name)===-1){if(p.inputs.length===0){a.push(p.name);continue}p.inputs.forEach(h=>{l.has(h.name)||(l.add(h.name),d.push(h))})}}return{inputs:e,outputs:t,usedNodes:r,missingInputs:a,dynamicNode:o,syncInputs:i}}function TG(e,t,n){let{usedNodes:s,inputs:r}=n,a=[],o=Object.keys(r).map(u=>xs(u)[0]).map(u=>e.nodes[u]),i=e.initNodes;o.forEach(u=>{s.has(u.name)&&a.push(u)}),e.weights.forEach(u=>{s.has(u.name)&&a.push(u)}),i!=null&&i.forEach(u=>{s.has(u.name)&&a.push(u)});let l=new Set,c=[];for(;a.length>0;){let u=a.pop();l.add(u.name),t[u.name]||c.push(u),u.children.forEach(d=>{!l.has(d.name)&&s.has(d.name)&&d.inputs.every(p=>l.has(p.name))&&a.push(d)})}return c}var NG=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],EG=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],RG=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function H7(e){return NG.indexOf(e.op)>=0}function $G(e){return EG.indexOf(e.op)>=0}function _G(e){return RG.indexOf(e.op)>=0}var Vy=class{constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},this.intermediateTensors={},this.keepTensorForDebug=!1,this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,e.functions!=null&&Object.keys(e.functions).forEach(n=>{this._functionExecutorMap[n]=new Vy(e.functions[n],this)})}get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){let t=Object.keys(e).map(n=>e[n].map(s=>s.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{let t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}getCompilationKey(e,t){let n=e.map(r=>r.name).sort(),s=t.map(r=>r.name).sort();return n.join(this.SEPERATOR)+"--"+s.join(this.SEPERATOR)}compile(e,t){let n=G7(e,t,this.weightMap,this._initNodes),{missingInputs:s,dynamicNode:r,syncInputs:a}=n;if(r!=null)throw new Error(`This execution contains the node '${r.name}', which has the dynamic op '${r.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${a}]`);if(s.length>0){let o=t.map(l=>l.name),i=Object.keys(e);throw new Error(`Cannot compute the outputs [${o}] from the provided inputs [${i}]. Missing the following inputs: [${s}]`)}return TG(this.graph,this.weightMap,n)}execute(e,t){e=this.mapInputs(e);let n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);let s=n.map(u=>this.graph.nodes[xs(u)[0]]),r=t.map(u=>xs(u)[0]),a=r.map(u=>this.graph.nodes[u]);this.resetIntermediateTensors(),a.length===0&&(a=this._outputs);let o=this.getCompilationKey(s,a),i=this.compiledMap.get(o);i==null&&(i=this.compile(e,a),this.compiledMap.set(o,i));let l={},c={};return X(()=>{let u=new U7(this.weightMap,l,c,this.functionExecutorMap),d={...this.weightMap};Object.keys(e).forEach(f=>{let[m,g]=xs(f),A=[];A[g]=e[f],d[m]=A});let p=this.getFrozenTensorIds(d),h={};for(let f=0;fGn(f,d,u))})}getFrozenTensorIds(e){let t=[].concat.apply([],Object.keys(e).map(n=>e[n]).map(n=>n.map(s=>s.id)));return new Set(t)}checkTensorForDisposal(e,t,n,s,r,a,o){t.category==="control"||a.indexOf(e)!==-1||(n[e].forEach(i=>{i!=null&&(o[i.id]=(o[i.id]||0)+t.children.length)}),t.inputs.forEach(i=>{if(i.category!=="control"){let l=PU(i.name,n,s);l!=null&&l.forEach(c=>{if(c&&!c.kept&&!r.has(c.id)){let u=o[c.id];if(u===1){if(!this.keepTensorForDebug)c.dispose();else{let[d,p]=Vr(t.name,s);this.intermediateTensors[d]?this.intermediateTensors[d][p]=c:(this.intermediateTensors[d]=[],this.intermediateTensors[d][p]=c)}delete o[c.id]}else u!=null&&o[c.id]--}})}}))}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){!this.intermediateTensors||(Object.keys(this.intermediateTensors).forEach(e=>this.intermediateTensors[e].forEach(t=>t.dispose())),this.disposeTensorsMap())}disposeTensorsMap(){!this.tensorsMap||Object.keys(this.tensorsMap).forEach(e=>{this.tensorsMap[e].forEach(n=>{n&&!n.kept&&!n.isDisposed&&!this.keepIds.has(n.id)&&n.dispose()})})}getIntermediateTensors(){return this.tensorsMap}resetIntermediateTensors(){for(let e in this.intermediateTensors)this.intermediateTensors[e].forEach(t=>t.dispose()),delete this.intermediateTensors[e]}async _executeAsync(e,t,n=!1,s={},r={}){n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepTensorForDebug=Y().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(c){console.warn(c.message)}this.resetIntermediateTensors();let a=new U7(this.weightMap,s,r,this.functionExecutorMap);this.tensorsMap=await this.executeWithControlFlow(e,a,t,n);let o=t.map(c=>Gn(c,this.tensorsMap,a)),i=o.map(c=>c.id),l=Object.keys(e).map(c=>e[c].id);return this.keepIds=new Set([...i,...l,...this.weightIds]),this.keepTensorForDebug||this.disposeTensorsMap(),this.parent==null&&a.dispose(this.keepIds),o}async executeFunctionAsync(e,t,n){let s=e.reduce((r,a,o)=>(r[this.inputs[o].name]=a,r),{});return this._executeAsync(s,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,s){let r=Object.keys(e),a=r.map(x=>this.graph.nodes[xs(x)[0]]),o=n.map(x=>xs(x)[0]),i=o.map(x=>this.graph.nodes[x]);i.length===0&&(i=this._outputs);let{usedNodes:l,missingInputs:c,dynamicNode:u,syncInputs:d}=G7(e,i,this.weightMap,this._initNodes),p=[...a,...this.graph.weights,...this._initNodes||[]].map(x=>({node:x,contexts:t.currentContext})),h={...this.weightMap};Object.keys(e).forEach(x=>{let[y,b]=xs(x),w=[];w[b]=e[x],h[y]=w});let f={},m=this.getFrozenTensorIds(h),g={};for(;p.length>0;){let x=this.processStack(a,p,t,h,g,m,o,f,l);await Promise.all(x)}u==null&&!s&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let A=i.filter(x=>!H7(x)&&!Gn(x.name,h,t)).map(x=>x.name);if(A.length>0){let x="";throw u!=null&&(x=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${d}]`),new Error(`Cannot compute the outputs [${A}] from the provided inputs [${r}]. Consider providing the following inputs: [${c}]. ${x}`)}return h}processStack(e,t,n,s,r,a,o,i,l){let c=[];for(;t.length>0;){let u=t.pop();n.currentContext=u.contexts;let d="";if(u.node.op==="Enter"&&S("isConstant",u.node,s,n)&&([d]=Vr(u.node.name,n)),s[u.node.name]==null){let p=V7(u.node,s,n,this._resourceManager);d||([d]=Vr(u.node.name,n));let h=n.currentContext;v.isPromise(p)?c.push(p.then(f=>(s[d]=f,n.currentContext=h,this.checkTensorForDisposal(d,u.node,s,n,a,o,i),this.processChildNodes(u.node,t,n,s,r,l),f))):(s[d]=p,this.checkTensorForDisposal(d,u.node,s,n,a,o,i),this.processChildNodes(u.node,t,n,s,r,l))}else this.processChildNodes(u.node,t,n,s,r,l)}return c}processChildNodes(e,t,n,s,r,a){e.children.forEach(o=>{let[i]=Vr(o.name,n);r[i]||!a.has(o.name)||(o.op==="Merge"?o.inputNames.some(l=>!!Gn(l,s,n))&&(r[i]=!0,t.push({contexts:n.currentContext,node:o})):o.inputNames.every(l=>!!Gn(l,s,n))&&(r[i]=!0,t.push({contexts:n.currentContext,node:o})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{let n=e[t],[s]=xs(t),r=this.graph.nodes[s];if(r.attrParams.shape&&r.attrParams.shape.value){let a=r.attrParams.shape.value,o=a.length===n.shape.length&&n.shape.every((i,l)=>a[l]===-1||a[l]===i);v.assert(o,()=>`The shape of dict['${r.name}'] provided in model.execute(dict) must be [${a}], but was [${n.shape}]`)}r.attrParams.dtype&&r.attrParams.dtype.value&&v.assert(n.dtype===r.attrParams.dtype.value,()=>`The dtype of dict['${r.name}'] provided in model.execute(dict) must be ${r.attrParams.dtype.value}, but was ${n.dtype}`)})}mapInputs(e){let t={};for(let n in e)if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[n]!=null){let s=this._signature.inputs[n];t[s.name]=e[n]}else t[n]=e[n];return t}checkInputs(e){let t=Object.keys(e).filter(n=>{let[s]=xs(n);return this.graph.nodes[s]==null});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(t=>this._signature!=null&&this._signature.outputs!=null&&this._signature.outputs[t]!=null?this._signature.outputs[t].name:t,{})}checkOutputs(e){e.forEach(t=>{let[n]=xs(t);if(!this.graph.nodes[n])throw new Error(`The output '${t}' is not found in the graph`)})}},DG=class{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(let e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(let e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}},PG="?tfjs-format=file",FG="model.json",j7=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new DG}get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}findIOHandler(){let e=this.modelUrl;if(e.load!=null)this.handler=e;else if(this.loadOptions.requestInit!=null)this.handler=rs.browserHTTPRequest(e,this.loadOptions);else{let t=rs.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(rs.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}async load(){if(this.findIOHandler(),this.handler.load==null)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let e=await this.handler.load();return this.loadSync(e)}loadSync(e){this.artifacts=e;let t=this.artifacts.modelTopology,n;this.artifacts.userDefinedMetadata!=null&&this.artifacts.userDefinedMetadata.signature!=null?n=this.artifacts.userDefinedMetadata.signature:n=this.artifacts.signature,this.signature=n,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;let s=rs.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new Vy(O7.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(s),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){let r=O7.Instance.transformGraph(e.modelInitializer);this.initializer=new Vy(r),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializer.executeAsync({},[])}return!0}async save(e,t){if(typeof e=="string"){let n=rs.getSaveHandlers(e);if(n.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(n.length>1)throw new Error(`Found more than one (${n.length}) save handlers for URL '${e}'`);e=n[0]}if(e.save==null)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}predict(e,t){return this.execute(e,this.outputNodes)}normalizeInputs(e){if(!(e instanceof Je)&&!Array.isArray(e))return e;if(e=Array.isArray(e)?e:[e],e.length!==this.inputNodes.length)throw new Error(`Input tensor count mismatch,the graph model has ${this.inputNodes.length} placeholders, while there are ${e.length} input tensors.`);return this.inputNodes.reduce((t,n,s)=>(t[n]=e[s],t),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}execute(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,n)=>(t[n]=[e[n]],t),{})}dispose(){this.executor.dispose(),this.initializer&&this.initializer.dispose(),this.resourceManager.dispose()}};async function Be(e,t={}){if(e==null)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");t==null&&(t={}),t.fromTFHub&&e.load==null&&(e.endsWith("/")||(e=e+"/"),e=`${e}${FG}${PG}`);let n=new j7(e,t);return await n.load(),n}var OG="0.0.0",q7={};Oe(q7,{CSVDataset:()=>iS,Dataset:()=>sc,FileDataSource:()=>fS,TextLineDataset:()=>rS,URLDataSource:()=>mS,array:()=>aH,csv:()=>gH,func:()=>AH,generator:()=>yH,microphone:()=>bH,version_data:()=>vH,webcam:()=>xH,zip:()=>oH});var MG=di(xh()),zG=di(xh());function LG(e,t){return Im(e,t)}function Im(e,t,n=new Map,s=new Set){if(e==null)return null;if(typeof Blob=="function"&&e instanceof Blob)return e.slice();if(s.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);let r=t(e);if(r.recurse&&r.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(r.recurse)if(nc(e)){let a=Array.isArray(e)?[]:{};s.add(e);for(let o in e){let i=e[o],l=Im(i,t,n,s);a[o]=l}return s.delete(e),e.__proto__&&(a.__proto__=e.__proto__),a}else throw new Error(`Can't recurse into non-iterable type: ${e}`);else return n.set(e,r.value),r.value}function BG(e,t=K7){return X7(e,t)}function X7(e,t,n=new Set){let s=e[0];if(n.has(s))throw new Error("Circular references are not supported.");let r=t(e);if(r.recurse&&r.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(r.recurse)if(nc(s)){let a=Array.isArray(s)?[]:{};n.add(s);for(let o in s){let i=e.map(c=>c[o]),l=X7(i,t,n);a[o]=l}return n.delete(s),a}else throw new Error(`Can't recurse into non-iterable type: ${s}`);else return r.value}function K7(e){return e===null?null:nc(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function Z7(e,t){let n=new Map;Im(e,t,n);for(let r of Array.from(n.keys())){let a=n.get(r);if(v.isPromise(a)){let o=await a;n.set(r,o)}}return Im(e,t,n)}function nc(e){let t=!1;if(Y().get("IS_BROWSER"))t=e instanceof TextDecoder;else{let{StringDecoder:n}=W5();t=e instanceof n}return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof Je)&&!(e instanceof Promise)&&!t)}function WG(e){return e==null||VG(e)||Array.isArray(e)||typeof e=="object"&&e instanceof Je||v.isTypedArray(e)}function VG(e){return e===null||typeof e!="object"&&typeof e!="function"}function UG(e){return LG(e,GG)}function GG(e){return e instanceof Je?{value:e.clone(),recurse:!1}:nc(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}var Y7=class{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,e==null)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return this.length()===0}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(let t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);let e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");let e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");let t=this.wrap(this.begin+e),n=this.get(t);return this.set(t,this.pop()),n}},J7=class extends Y7{constructor(){super(J7.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){let e=this.capacity*2,t=new Array(e),n=this.length();for(let s=0;st===!0)}rowMajorBatch(e,t=!0){return new JG(this,e,t)}columnMajorBatch(e,t=!0,n=K7){return this.rowMajorBatch(e,t).map(r=>BG(r,n))}concatenate(e,t){return new nS(eS([this,e]),t)}take(e){return e<0||e==null?this:new YG(this,e)}skip(e){return e<0||e==null?this:new ZG(this,e)}prefetch(e){return new sS(this,e)}shuffle(e,t){return new rH(this,e,t)}serial(){return new KG(this)}},qG=class extends bn{constructor(e){super();this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};let e=this.items[this.trav];return this.trav++,{value:UG(e),done:!1}}},XG=class extends bn{constructor(e){super();this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}},KG=class extends bn{constructor(e){super();this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){return this.upstream.next()}},ZG=class extends bn{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.count++ Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}},JG=class extends bn{constructor(e,t,n=!0){super();this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=n,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){let e=[];for(;e.length0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}},QG=class extends bn{constructor(e,t){super();this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;){let e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;te(e.value)}}},eH=class extends bn{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=dr.getTensorsInContainer(e.value),n=this.transform(e.value),s=dr.getTensorsInContainer(n);for(let r of t)dr.isTensorInList(r,s)||r.dispose();return{value:n,done:!1}}},tH=class extends bn{constructor(e,t){super();this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}},tS=class extends bn{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=dr.getTensorsInContainer(e.value),n=await this.transform(e.value),s=dr.getTensorsInContainer(n);for(let r of t)dr.isTensorInList(r,s)||r.dispose();return{value:n,done:!1}}},Gy=class extends bn{constructor(){super();this.outputQueue=new Q7,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.outputQueue.length()===0;)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}},nH=class extends Gy{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){let e=await this.upstream.next();if(e.done)return!1;let t=dr.getTensorsInContainer(e.value),n=this.transform(e.value),s=dr.getTensorsInContainer(n);this.outputQueue.pushAll(n);for(let r of t)dr.isTensorInList(r,s)||r.dispose();return!0}},nS=class extends bn{constructor(e,t){super();this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,this.iterator==null){let n=await this.moreIterators.next();if(n.done)return{value:null,done:!0};this.iterator=n.value,this.baseErrorHandler!=null&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}let t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}},Cm;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(Cm||(Cm={}));var sH=class extends bn{constructor(e,t=0){super();this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){return"{TODO: fill in upstream of zip summaries} -> Zip"}async nextState(e){await e;let t=0,n=0;function s(a){return a instanceof bn?{value:a.next().then(i=>(t++,i.done&&n++,i.value)),recurse:!1}:{value:null,recurse:!0}}let r=await Z7(this.iterators,s);if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case 0:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case 1:return{value:null,done:!0};case 2:default:}return this.count++,{value:r,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},sS=class extends bn{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new Y7(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){let e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}},rH=class extends sS{constructor(e,t,n){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=zG.alea(n||v.now().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){let e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(t.done)this.upstreamExhausted=!0;else return this.refill(),t}return{value:null,done:!0}}},sc=class{constructor(){this.size=null}batch(e,t=!0){let n=this;v.assert(e>0,()=>`batchSize needs to be positive, but it is ${e}`);let s;return this.size===1/0||this.size==null?s=this.size:t?s=Math.ceil(this.size/e):s=Math.floor(this.size/e),bs(async()=>(await n.iterator()).columnMajorBatch(e,t,iH),s)}concatenate(e){let t=this,n;return this.size===1/0||e.size===1/0?n=1/0:this.size!=null&&e.size!=null?n=this.size+e.size:n=null,bs(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){let t=this,n;return this.size===1/0?n=1/0:n=null,bs(async()=>(await t.iterator()).filter(s=>X(()=>e(s))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return bs(async()=>(await t.iterator()).map(n=>X(()=>e(n))),this.size)}mapAsync(e){let t=this;return bs(async()=>(await t.iterator()).mapAsync(e),this.size)}prefetch(e){if(e==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");let t=this;return bs(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){let t=this,n;return this.size!=null&&e>0?n=this.size*e:e===0?n=0:this.size!=null&&(e===void 0||e<0)?n=1/0:n=null,bs(async()=>{let s=Uy(async()=>({value:await t.iterator(),done:!1}));return HG(s.take(e))},n)}skip(e){let t=this,n;return this.size!=null&&e>=0&&this.size>=e?n=this.size-e:this.size!=null&&(this.size(await t.iterator()).skip(e),n)}shuffle(e,t,n=!0){if(e==null||e<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);let s=this,r=MG.alea(t||v.now().toString());return bs(async()=>{let a=r.int32();return n&&(a+=r.int32()),(await s.iterator()).shuffle(e,a.toString())},this.size)}take(e){let t=this,n;return this.size!=null&&this.size>e?n=e:this.size!=null&&this.size<=e?n=this.size:n=null,bs(async()=>(await t.iterator()).take(e),n)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}};sc.MAX_BUFFER_SIZE=1e4;function bs(e,t=null){return new class extends sc{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function aH(e){return bs(async()=>eS(e),e.length)}function oH(e){if(!nc(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let n=0;n{let n=await Z7(e,s=>{if(s instanceof sc)return{value:s.iterator(),recurse:!1};if(nc(s))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return jG(n,Cm.SHORTEST)},t)}function iH(e){if(e===null)return null;let t=e[0];return WG(t)?{value:lH(e),recurse:!1}:{value:null,recurse:!0}}function lH(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Je?yn(e):ut(e)}var rS=class extends sc{constructor(e){super();this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split(` `).map(s=>(s.endsWith("\r")&&(s=s.slice(0,-1)),s))}},Tm='"',up=Symbol("out"),aS=Symbol("field"),Nm=Symbol("quote"),Hy=Symbol("quoteafterquote"),oS=Symbol("quoteinquote"),iS=class extends sc{constructor(e,t){super();this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new rS(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(v.assert(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&v.assert(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);let t=this.fullColumnNames.reduce((s,r)=>(s[r]=s[r]+1||1,s),{}),n=Object.keys(t).filter(s=>t[s]>1);if(v.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let s of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(s)===-1)throw new Error('The key "'+s+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let t=await(await this.base.iterator()).next();if(t.done)throw new Error("No data was found for CSV parsing.");let n=t.value;return this.parseRow(n,!1)}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){let t=this.parseRow(e),n={},s={};for(let r=0;r14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=e.includeSpectrogram!==!1,this.includeWaveform=e.includeWaveform===!0,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(Y().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");let t=new lS(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?!0:this.audioTrackConstraints,video:!1})}catch(n){throw new Error(`Error thrown while initializing video stream: ${n.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");let e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,!this.sampleRateHz)this.sampleRateHz=this.audioContext.sampleRate;else if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`);let t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.fftSize*2,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize)}async next(){if(this.isClosed)return{value:null,done:!0};let e,t,n=await this.getAudioData();if(this.includeSpectrogram){let s=this.flattenQueue(n.freqDataQueue);e=this.getTensorFromAudioDataArray(s,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){let s=this.flattenQueue(n.timeDataQueue);t=this.getTensorFromAudioDataArray(s,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){let e=[],t=[],n=0;return new Promise(s=>{let r=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&s({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(r),s({freqDataQueue:e,timeDataQueue:t}))},this.fftSize/this.sampleRateHz*1e3)})}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),this.stream!=null&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){let t=e[0].length,n=new Float32Array(e.length*t);return e.forEach((s,r)=>n.set(s,r*t)),n}getTensorFromAudioDataArray(e,t){let n=new Float32Array(v.sizeFromShape(t));return n.set(e,n.length-e.length),ut(n,t)}},uS=class extends bn{constructor(e,t){super();if(this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=Vt([0],"int32"),this.webcamConfig.centerCrop){let n=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,s=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,r=(1-n)/2,a=(1-s)/2,o=r+n,i=s+a;this.cropBox=fr([a,r,i,o],[1,4])}else this.cropBox=fr([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(Y().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}let n=new uS(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&v.assert(this.webcamConfig.facingMode==="user"||this.webcamConfig.facingMode==="environment",()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`);try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}})}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=Ks.fromPixels(this.webcamVideoElement)}catch(t){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(t)}`)}if(this.resize)try{return{value:this.cropAndResizeFrame(e),done:!1}}catch(t){throw new Error(`Error thrown cropping the video: ${t.message}`)}finally{e.dispose()}else return{value:e,done:!1}}needToResize(){return!!(this.webcamConfig.resizeWidth&&this.webcamConfig.resizeHeight&&(this.webcamVideoElement.width!==this.webcamConfig.resizeWidth||this.webcamVideoElement.height!==this.webcamConfig.resizeHeight))}cropAndResizeFrame(e){return X(()=>{let t=Kt(me(e,"float32"),0),n;n=Ce.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let s=n.shape;return H(n,s.slice(1))})}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach(t=>t.stop());try{this.webcamVideoElement.srcObject=null}catch(t){console.log(t),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}},cS=class{},dS=class extends bn{split(e){return new uH(this,e)}},uH=class extends dS{constructor(e,t){super();this.upstream=e,this.impl=new cH(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},cH=class extends Gy{constructor(e,t){super();this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){let e=await this.upstream.next();if(e.done)return this.carryover===""?!1:(this.outputQueue.push(this.carryover),this.carryover="",!0);let t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(let n of t.slice(0,-1))this.outputQueue.push(n);return this.carryover=t[t.length-1],!0}},dH=class extends bn{decodeUTF8(){return new pH(this)}},pH=class extends dS{constructor(e){super();this.upstream=e,this.impl=new hH(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},hH=class extends Gy{constructor(e){super();if(this.upstream=e,Y().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=W5();this.decoder=new t("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){let e=await this.upstream.next(),t;if(e.done)return!1;t=e.value;let n;return Y().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}},pS=class extends dH{constructor(e,t={}){super();this.file=e,this.options=t,v.assert(e instanceof Uint8Array||(Y().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1024*1024}summary(){return`FileChunks ${this.file}`}async next(){return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?{value:null,done:!0}:{value:await new Promise((t,n)=>{let s=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)t(new Uint8Array(this.file.slice(this.offset,s)));else{let r=new FileReader;r.onload=o=>{let i=r.result;if(i instanceof ArrayBuffer&&(i=new Uint8Array(i)),!(i instanceof Uint8Array))return n(new TypeError("FileReader returned unknown type."));t(i)},r.onabort=o=>n(new Error("Aborted")),r.onerror=o=>n(new Error(o.type));let a=this.file.slice(this.offset,s);r.readAsArrayBuffer(a)}this.offset=s}),done:!1}}};async function fH(e,t={},n){let s,r;typeof e=="string"?s=e:(s=e.url,r=mH(e));let a=await(n||v.fetch)(s,r);if(a.ok){let o=new Uint8Array(await a.arrayBuffer());return new pS(o,t)}else throw new Error(a.statusText)}var mH=e=>({method:e.method,headers:e.headers,body:e.body,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,integrity:e.integrity});function hS(e){return typeof e=="string"&&e.substr(0,7)==="file://"}var fS=class extends cS{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(hS(this.input)&&Y().get("IS_NODE")){let e=js("fs");this.input=e.readFileSync(this.input.substr(7))}return new pS(this.input,this.options)}},mS=class extends cS{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return hS(this.url)?new fS(this.url,this.fileOptions).iterator():fH(this.url,this.fileOptions)}};function gH(e,t={}){return new iS(new mS(e),t)}function AH(e){let t=Uy(e);return bs(async()=>t)}function yH(e){return bs(async()=>{let t=await e();return Uy(()=>t.next())})}async function xH(e,t){return uS.create(e,t)}async function bH(e){return lS.create(e)}var vH="0.0.0";function Re(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&v.assert(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}var wH=Qs.whereImpl,gS=class extends ru{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new sd(this,as())}nextDataId(){return gS.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,Y().get("IS_NODE")&&E.warn(` ============================ Hi there \u{1F44B}. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details. ============================`));let s={id:this.nextDataId()};return this.data.set(s,{values:e,dtype:n,refCount:1}),s}makeTensorInfo(e,t,n){let s;if(t==="string"&&n!=null&&n.length>0&&v.isString(n[0])){let r=n.map(a=>v.encodeString(a));s=this.write(r,e,t)}else s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,n,s,r){this.data.set(e,{values:t,dtype:s,refCount:r})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){let s=this.readSync(n.real.dataId),r=this.readSync(n.imag.dataId);return E.mergeRealAndImagArrays(s,r)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(s=>v.decodeString(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return ze(e.shape,e.dtype,n)}makeOutput(e,t,n){let s=this.write(e,t,n);return as().makeTensorFromDataId(s,t,n,this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(e);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){let t=v.now();return e(),{kernelMs:v.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){Re([e],"where");let t=this.readSync(e.dataId);return wH(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}},jy=gS;jy.nextDataId=0;var Em={};Oe(Em,{addImpl:()=>yS,bincountImpl:()=>Xy,bincountReduceImpl:()=>xS,ceilImpl:()=>bS,concatImpl:()=>Ky,equalImpl:()=>vS,expImpl:()=>kS,expm1Impl:()=>IS,floorImpl:()=>CS,gatherNdImpl:()=>TS,gatherV2Impl:()=>NS,greaterEqualImpl:()=>RS,greaterImpl:()=>ES,lessEqualImpl:()=>_S,lessImpl:()=>$S,linSpaceImpl:()=>DS,logImpl:()=>PS,maxImpl:()=>FS,maximumImpl:()=>OS,minimumImpl:()=>MS,multiplyImpl:()=>Zy,negImpl:()=>zS,notEqualImpl:()=>LS,prodImpl:()=>BS,rangeImpl:()=>Jy,rsqrtImpl:()=>WS,sigmoidImpl:()=>cj,simpleAbsImpl:()=>AS,sliceImpl:()=>_m,sparseFillEmptyRowsImpl:()=>US,sparseReshapeImpl:()=>GS,sparseSegmentReductionImpl:()=>Qy,sqrtImpl:()=>hj,squaredDifferenceImpl:()=>HS,stridedSliceImpl:()=>jS,stringNGramsImpl:()=>qS,stringSplitImpl:()=>XS,stringToHashBucketFastImpl:()=>KS,subImpl:()=>ZS,tileImpl:()=>YS,topKImpl:()=>QS,transposeImpl:()=>Yy,uniqueImpl:()=>eI});function AS(e){let t=new Float32Array(e.length);for(let n=0;n{let{x:t}=e.inputs,n=e.backend;Re(t,"abs");let s=new Float32Array(v.sizeFromShape(t.shape)),r=n.data.get(t.dataId).values;return s=AS(r),n.makeOutput(s,t.shape,t.dtype)},SH={kernelName:fi,backendName:"cpu",kernelFunc:kH};function Yt(e){return(t,n,s,r,a)=>{let o=E.assertAndGetBroadcastShape(t,n),i=o.length,l=v.computeStrides(o),c=v.sizeFromShape(o),u=v.getTypedArrayFromDType(a,c),d=t.length,p=n.length,h=v.computeStrides(t),f=v.computeStrides(n),m=E.getBroadcastDims(t,o),g=E.getBroadcastDims(n,o);if(m.length+g.length===0)for(let A=0;Ay[I]=0);let b=v.locToIndex(y,d,h),w=x.slice(-p);g.forEach(I=>w[I]=0);let k=v.locToIndex(w,p,f);u[A]=e(s[b],r[k])}return[u,o]}}function vs(e){let{inputs:t,backend:n}=e,{real:s,imag:r}=t,a=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,i=n.makeTensorInfo(s.shape,"complex64"),l=n.data.get(i.dataId);return l.complexTensorInfos={real:n.makeTensorInfo(s.shape,"float32",a),imag:n.makeTensorInfo(r.shape,"float32",o)},i}var IH={kernelName:id,backendName:"cpu",kernelFunc:vs};function Rm(e,t,n="float32"){if(n==="complex64"){let r=Rm(e,t,"float32"),a=Rm(e,t,"float32");return vs({inputs:{real:r,imag:a},backend:e})}let s=v.makeZerosTypedArray(v.sizeFromShape(t),n);return e.makeTensorInfo(t,n,s)}function Ur(e){let{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}var CH={kernelName:Xa,backendName:"cpu",kernelFunc:Ur};function Cl(e){let{inputs:t,backend:n}=e,{input:s}=t,r=n.data.get(s.dataId).complexTensorInfos.real,a=n.data.get(r.dataId).values;return n.makeTensorInfo(r.shape,r.dtype,a)}var TH={kernelName:gd,backendName:"cpu",kernelFunc:Cl};function Go(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dtype:a}=s;if(a==="complex64"){if(r.dtype==="complex64")return Ur({inputs:{x:r},backend:n});let o=Rm(n,r.shape,r.dtype),i=Go({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=vs({inputs:{real:i,imag:o},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),l}if(r.dtype==="complex64"){let o=Cl({inputs:{input:r},backend:n}),i=Go({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(o),i}if(!v.hasEncodingLoss(r.dtype,a)){let o=Ur({inputs:{x:r},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32"){let o=n.data.get(r.dataId).values,i=Int32Array.from(o);return n.makeTensorInfo(r.shape,"int32",i)}if(a==="bool"){let o=n.data.get(r.dataId).values,i=v.toTypedArray([0],r.dtype),[l,c]=Yt((u,d)=>u!==d?1:0)(r.shape,[],o,i,"bool");return n.makeTensorInfo(c,"bool",l)}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${a}`)}var NH={kernelName:Pa,backendName:"cpu",kernelFunc:Go};function vn(e,t,n,s){return n==null?({inputs:r,backend:a})=>{let{a:o,b:i}=r,l=a;Re([o,i],e);let c=l.data.get(o.dataId).values,u=l.data.get(i.dataId).values,d=o.dtype==="string"?E.fromUint8ToStringArray(c):c,p=o.dtype==="string"?E.fromUint8ToStringArray(u):u,h=s||o.dtype,[f,m]=t(o.shape,i.shape,d,p,h);return l.makeTensorInfo(m,h,f)}:({inputs:r,backend:a})=>{let{a:o,b:i}=r,l=a;if(o.dtype==="complex64"||i.dtype==="complex64"){let c=Go({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),u=l.data.get(c.dataId),d=u.complexTensorInfos.real,p=u.complexTensorInfos.imag,h=l.data.get(d.dataId).values,f=l.data.get(p.dataId).values,m=Go({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(m.dataId),A=g.complexTensorInfos.real,x=g.complexTensorInfos.imag,y=l.data.get(A.dataId).values,b=l.data.get(x.dataId).values,[w,k,I]=n(o.shape,i.shape,h,f,y,b),N=l.makeTensorInfo(I,"float32",w),R=l.makeTensorInfo(I,"float32",k),O=vs({inputs:{real:N,imag:R},backend:l});return l.disposeIntermediateTensorInfo(c),l.disposeIntermediateTensorInfo(m),l.disposeIntermediateTensorInfo(N),l.disposeIntermediateTensorInfo(R),O}else{let c=l.data.get(o.dataId).values,u=l.data.get(i.dataId).values,d=s||o.dtype,[p,h]=t(o.shape,i.shape,c,u,d);return l.makeTensorInfo(h,d,p)}}}function qy(e){return(t,n,s,r,a,o)=>{let i=E.assertAndGetBroadcastShape(t,n),l=v.sizeFromShape(i),c=i.length,u=v.computeStrides(i),d=v.getTypedArrayFromDType("float32",l),p=v.getTypedArrayFromDType("float32",l),h=E.getBroadcastDims(t,i),f=E.getBroadcastDims(n,i),m=E.mergeRealAndImagArrays(s,r),g=E.mergeRealAndImagArrays(a,o),A=t.length,x=v.computeStrides(t),y=n.length,b=v.computeStrides(n);if(h.length+f.length===0)for(let w=0;wI[P]=0);let N=v.locToIndex(I,A,x),R=k.slice(-y);f.forEach(P=>R[P]=0);let O=v.locToIndex(R,y,b),$=e(m[N*2],m[N*2+1],g[O*2],g[O*2+1]);d[w]=$.real,p[w]=$.imag}return[d,p,i]}}var yS=Yt((e,t)=>e+t),EH=qy((e,t,n,s)=>({real:e+n,imag:t+s})),cp=vn(Kr,yS,EH),RH={kernelName:Kr,backendName:"cpu",kernelFunc:cp};function Xy(e,t,n,s,r){let a=v.sizeFromShape(s),o=v.makeZerosTypedArray(r,n);for(let i=0;i=r||(a>0?o[l]+=t[i]:o[l]+=1)}return o}function xS(e,t,n,s=!1){let r=e.shape[0],a=e.shape[1],o=ze([r,n],t.dtype);for(let i=0;i=n||(s?o.set(1,i,c):t.size>0?o.set(o.get(i,c)+t.get(i,l),i,c):o.set(o.get(i,c)+1,i,c))}return o}function Ho(e){return(t,n,s)=>{let r=v.getTypedArrayFromDType(n,t.length);for(let a=0;a{let{x:o}=s;if(Re(o,e),o.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");let i=a,l=i.data.get(o.dataId).values,c=v.sizeFromShape(o.shape),u=n||o.dtype,d=v.getArrayFromDType(u,c);for(let p=0;p{let{x:o}=s;if(Re(o,e),o.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");let i=a,l=i.data.get(o.dataId).values,c=n||o.dtype,u=t(l,c,r);return i.makeTensorInfo(o.shape,c,u)}}var bS=Ho(e=>Math.ceil(e)),$H=rc(Fa,bS),_H={kernelName:Fa,backendName:"cpu",kernelFunc:$H};function Ky(e,t,n,s){let r=v.getArrayFromDType(n,v.sizeFromShape(t));if(s&&n!=="string"){let a=0;e.forEach(o=>{let i=v.sizeFromShape(o.shape);r.set(o.vals,a),a+=i})}else{let a=0;e.forEach(o=>{let i=n==="string"?E.fromUint8ToStringArray(o.vals):o.vals,l=0;for(let c=0;ce===t?1:0),wS=vn(bi,vS,null,"bool"),DH={kernelName:bi,backendName:"cpu",kernelFunc:wS},kS=Ho(e=>Math.exp(e)),SS=rc(Ua,kS,"float32"),PH={kernelName:Ua,backendName:"cpu",kernelFunc:SS},IS=Ho(e=>Math.expm1(e)),FH=rc(wi,IS),OH={kernelName:wi,backendName:"cpu",kernelFunc:FH},CS=Ho(e=>Math.floor(e)),MH=rc(Ga,CS),zH={kernelName:Ga,backendName:"cpu",kernelFunc:MH};function TS(e,t,n,s,r,a,o,i,l){let c=ze([s,a],n);for(let u=0;u=l/a)throw new Error(`Invalid indices: ${d} does not index into ${i}`);for(let h=0;he>t?1:0),LH=vn(Ci,ES,null,"bool"),BH={kernelName:Ci,backendName:"cpu",kernelFunc:LH},RS=Yt((e,t)=>e>=t?1:0),WH=vn(qa,RS,null,"bool"),VH={kernelName:qa,backendName:"cpu",kernelFunc:WH},$S=Yt((e,t)=>ee<=t?1:0),HH=vn(Ei,_S,null,"bool"),jH={kernelName:Ei,backendName:"cpu",kernelFunc:HH};function DS(e,t,n){let s=(t-e)/(n-1),r=v.makeZerosTypedArray(n,"float32");r[0]=e;for(let a=1;aMath.log(e)),qH=rc(Ka,PS),XH={kernelName:Ka,backendName:"cpu",kernelFunc:qH};function FS(e,t,n,s){let r=v.getTypedArrayFromDType(s,v.sizeFromShape(n));for(let a=0;ai)&&(i=c)}r[a]=i}return r}var OS=Yt((e,t)=>Math.max(e,t)),KH=vn(Ya,OS),ZH={kernelName:Ya,backendName:"cpu",kernelFunc:KH},MS=Yt((e,t)=>Math.min(e,t)),YH=vn(to,MS),JH={kernelName:to,backendName:"cpu",kernelFunc:YH},Zy=Yt((e,t)=>e*t),QH=qy((e,t,n,s)=>({real:e*n-t*s,imag:e*s+t*n})),$m=vn(so,Zy,QH),ej={kernelName:so,backendName:"cpu",kernelFunc:$m};function zS(e,t,n){let s=v.createScalarValue(-1,n);return Zy([],t,s,e,n)}function tj(e){let{inputs:t,backend:n}=e,{x:s}=t;Re(s,"neg");let r=n.data.get(s.dataId).values,[a,o]=zS(r,s.shape,s.dtype);return n.makeTensorInfo(o,s.dtype,a)}var nj={kernelName:$i,backendName:"cpu",kernelFunc:tj},LS=Yt((e,t)=>e!==t?1:0),sj=vn(_i,LS,null,"bool"),rj={kernelName:_i,backendName:"cpu",kernelFunc:sj};function Yy(e,t,n,s,r){let a=t.length,o=v.sizeFromShape(t),i=v.computeStrides(t),l=v.computeStrides(r),c=v.getTypedArrayFromDType(n,v.sizeFromShape(r));for(let u=0;un.disposeIntermediateTensorInfo(x)),n.makeTensorInfo(A,g,f)}var ij={kernelName:zi,backendName:"cpu",kernelFunc:oj};function Jy(e,t,n,s){let r=e===t,a=e1;if(r||a||o)return v.makeZerosTypedArray(0,s);let i=Math.abs(Math.ceil((t-e)/n)),l=v.makeZerosTypedArray(i,s);t1/Math.sqrt(e)),lj=rc(co,WS),uj={kernelName:co,backendName:"cpu",kernelFunc:lj},cj=Ho(e=>1/(1+Math.exp(-e))),VS=ft(ho,e=>1/(1+Math.exp(-e))),dj={kernelName:ho,backendName:"cpu",kernelFunc:VS};function _m(e,t,n,s,r){let a=Ft.isSliceContinous(s,t,n),o=v.sizeFromShape(n),i=v.computeStrides(s);if(a){let d=Ft.computeFlatOffset(t,i);return r==="string"?e.slice(d,d+o):e.subarray(d,d+o)}let l=r==="string"?E.fromUint8ToStringArray(e):e,c=ze(s,r,l),u=ze(n,r);for(let d=0;df+t[m]);u.set(c.get(...h),...p)}return r==="string"?E.fromStringArrayToUint8(u.values):u.values}function Tl(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:o}=s;Re(r,"slice");let[i,l]=Ft.parseSliceParams(r,a,o);Ft.assertParamsValid(r,i,l);let c=n.data.get(r.dataId).values,u=_m(c,i,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,u)}var pj={kernelName:Gi,backendName:"cpu",kernelFunc:Tl};function US(e,t,n,s,r,a,o){let i=t[0],l=a[0],c=new Array(l),u=new Array(i),d=t[1];if(l===0){if(i!==0)throw new Error(`Received SparseTensor with denseShape[0] = 0 but indices.shape[0] = ${i}`);let g=v.getArrayFromDType(n,0),A=v.getArrayFromDType(r,0);return[g,[0,d],A,c,u]}let p=!0,h=0,f=new Array(l).fill(0);for(let g=0;g=l)throw new Error(`indices(${g}, 0) is invalid: ${A} >= ${l}`);++f[A],p=p&&A>=h,h=A}let m=!0;for(let g=0;g0&&(f[g]+=f[g-1])}if(m&&p){let g=e,A=s;for(let x=0;x0){h[p-1]=1;for(let g=p-2;g>=0;--g)h[g]=h[g+1]*s[g+1]}let f=[];if(i>0){f[i-1]=1;for(let g=i-2;g>=0;--g)f[g]=f[g+1]*l[g+1]}let m=v.getArrayFromDType(n,o*i);for(let g=0;g0?r[i-1]+1:0;if(d<0)throw new Error("segment ids must be >= 0");let p=t.slice();p[0]=d;let h=p.reduce((y,b)=>y*b,1),f=v.getArrayFromDType(n,h);if(i===0)return d>0&&f.fill(o),[f,p];if(d<=0)throw new Error("segment ids must be >= 0");let m=0,g=1,A=0,x=r[m];for(;;){let y=0;if(g=y)throw new Error("segment ids are not increasing")}if(x<0||x>=d)throw new Error(`Segment id ${x} out of range [0, ${d}), possibly because segmentIds input is not sorted.`);x>A&&f.fill(o,A*c,x*c);for(let b=m;b=l[0])throw new Error(`Bad: indices[${b}] == ${s[b]} out of range [0, ${l[0]})`);for(let k=0;ki)break}return AMath.sqrt(e)),fj=ft(fo,e=>Math.sqrt(e)),mj={kernelName:fo,backendName:"cpu",kernelFunc:fj},HS=Yt((e,t)=>{let n=e-t;return n*n}),gj=vn(Ao,HS),Aj={kernelName:Ao,backendName:"cpu",kernelFunc:gj};function jS(e,t,n,s){let r=ze(e,t.dtype);for(let a=0;a0?0:o-i),p=0;p+=l*this.leftPad.length;for(let A=0;AA.forEach(x=>f[m++]=x);for(let A=0;A0){g(e[d+u-1]);for(let A=0;A0){let i=t[0];if(i!==0)throw new Error(`First split value must be 0, got ${i}`);for(let l=1;l=i;if(c=c&&t[l]<=n,!c)throw new Error(`Invalid split value ${t[l]}, must be in [${i}, ${n}]`);i=t[l]}if(i!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${i}`)}let r=s-1,a=v.getArrayFromDType("int32",s);if(n===0||s===0){let i=new Array(n);for(let l=0;l<=r;++l)a[l]=0;return[i,a]}a[0]=0;for(let i=1;i<=r;++i){let l=t[i]-t[i-1],c=0;this.nGramWidths.forEach(u=>{c+=this.getNumNGrams(l,u)}),this.preserveShort&&l>0&&c===0&&(c=1),a[i]=a[i-1]+c}let o=new Array(a[r]);for(let i=0;i{let d=t[i+1]-t[i],p=this.getNumNGrams(d,u);this.createNGrams(e,l,o,c,p,u),c+=p}),this.preserveShort&&c===a[i]){let u=t[i+1]-t[i];if(u===0)continue;let d=u+2*this.padWidth,p=1;this.createNGrams(e,l,o,c,p,d)}}return[o,a]}};function qS(e,t,n,s,r,a,o,i){return new yj(n,s,r,a,o,i).compute(e,t)}function xj(e,t,n,s){if(!e.length)return;if(t.length===0){for(let a=0;ae-t),bj=qy((e,t,n,s)=>({real:e-n,imag:t-s})),ex=vn(yo,ZS,bj),vj={kernelName:yo,backendName:"cpu",kernelFunc:ex};function YS(e,t){let n=new Array(e.rank);for(let r=0;r{let n=t.value-e.value;return n===0?e.index-t.index:n};function JS(e,t,n=0,s=e.length-1){for(;s>n;){if(s-n>600){let i=s-n+1,l=t-n+1,c=Math.log(i),u=.5*Math.exp(2*c/3),d=.5*Math.sqrt(c*u*(i-u)/i)*Math.sign(l-i/2),p=Math.max(n,Math.floor(t-l*u/i+d)),h=Math.min(s,Math.floor(t+(i-l)*u/i+d));JS(e,t,p,h)}let r=e[t],a=n,o=s;for(v.swap(e,n,t),dp(e[s],r)>0&&v.swap(e,n,s);a0;)o=o-1}dp(e[n],r)===0?v.swap(e,n,o):(o=o+1,v.swap(e,o,s)),o<=t&&(n=o+1),t<=o&&(s=o-1)}}function QS(e,t,n,s,r){let a=t[t.length-1],[o,i]=[e.length/a,a],l=v.getTypedArrayFromDType(n,o*s),c=v.getTypedArrayFromDType("int32",o*s);for(let d=0;df[y]={value:x,index:y}),s{for(let g=0;gnew jy,1);var tI=ft(Va,e=>e>=0?e:Math.exp(e)-1),kj={kernelName:Va,backendName:"cpu",kernelFunc:tI};function nI(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{alpha:a}=s;Re([r],"leakyRelu");let o=v.sizeFromShape(r.shape),i=n.data.get(r.dataId).values,l=v.getTypedArrayFromDType("float32",o);for(let c=0;ce<0?t*e:e);function sI(e){let{inputs:t,backend:n}=e,{x:s,alpha:r}=t;Re([s,r],"prelu");let a=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,[i,l]=Ij(s.shape,r.shape,a,o,"float32");return n.makeTensorInfo(l,"float32",i)}var Cj={kernelName:oo,backendName:"cpu",kernelFunc:sI},rI=ft(io,e=>Math.max(0,e)),Tj={kernelName:io,backendName:"cpu",kernelFunc:rI},aI=ft(uo,e=>Math.min(Math.max(0,e),6)),Nj={kernelName:uo,backendName:"cpu",kernelFunc:aI};function tx(e,t,n,s,r){if(n==="linear")return Ur({inputs:{x:t},backend:e});if(n==="relu")return rI({inputs:{x:t},backend:e});if(n==="elu")return tI({inputs:{x:t},backend:e});if(n==="relu6")return aI({inputs:{x:t},backend:e});if(n==="prelu")return sI({inputs:{x:t,alpha:s},backend:e});if(n==="leakyrelu")return nI({inputs:{x:t},backend:e,attrs:{alpha:r}});if(n==="sigmoid")return VS({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function _t(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{shape:a}=s,o=v.sizeFromShape(r.shape),i=v.inferFromImplicitShape(a,o),l=v.sizeFromShape(i);v.assert(o===l,()=>`The new shape (${i}) has ${l} elements and the old shape (${r.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`),n.incRef(r.dataId);let c=n.data.get(r.dataId);if(c.complexTensorInfos!=null){let u=c.complexTensorInfos.real,d=c.complexTensorInfos.imag;u.shape=i,d.shape=i}return{dataId:r.dataId,shape:i,dtype:r.dtype}}var Ej={kernelName:Li,backendName:"cpu",kernelFunc:_t};function oI(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:o,transposeB:i}=s;Re([r,a],"matMul");let l=r.shape.length,c=a.shape.length,u=o?r.shape[l-2]:r.shape[l-1],d=i?a.shape[c-1]:a.shape[c-2],p=o?r.shape[l-1]:r.shape[l-2],h=i?a.shape[c-2]:a.shape[c-1],f=r.shape.slice(0,-2),m=a.shape.slice(0,-2),g=v.sizeFromShape(f),A=v.sizeFromShape(m),y=ol.assertAndGetBroadcastShape(r.shape.slice(0,-2),a.shape.slice(0,-2)).concat([p,h]);v.assert(u===d,()=>`Error in matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${r.shape} and ${a.shape} and transposeA=${o} and transposeB=${i} must match.`);let b=o?[g,u,p]:[g,p,u],w=i?[A,h,d]:[A,d,h],k=_t({inputs:{x:r},backend:n,attrs:{shape:b}}),I=_t({inputs:{x:a},backend:n,attrs:{shape:w}}),N=o?k.shape[1]:k.shape[2],R=o?k.shape[2]:k.shape[1],O=i?I.shape[1]:I.shape[2],$=Math.max(g,A),P=n.data.get(k.dataId).values,T=n.data.get(I.dataId).values,F=v.computeStrides(k.shape),U=v.computeStrides(I.shape),[q,z,K]=o?[F[0],1,F[1]]:[F[0],F[1],1],[J,Q,ne]=i?[1,U[1],U[0]]:[U[1],1,U[0]],re=R*O,G=ze([$,R,O],k.dtype),se=G.values,oe=n.blockSize;for(let pe=0;pe<$;pe++)for(let ye=0;yeMath.acos(e)),Pj={kernelName:iu,backendName:"cpu",kernelFunc:Dj},Fj=ft(lu,e=>Math.acosh(e)),Oj={kernelName:lu,backendName:"cpu",kernelFunc:Fj};function Mj(e){let{inputs:t,backend:n}=e,s=t;Re(t,"addN");let r=s.map(i=>n.data.get(i.dataId).values),a=ze(s[0].shape,s[0].dtype),o=a.values;for(let i=0;ix&&(x=w,y=b)}h[g]=y}return c.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(u,"int32",h)}var Gj={kernelName:$a,backendName:"cpu",kernelFunc:Uj};function Hj(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;Re(r,"argMin");let o=v.parseAxisParam(a,r.shape),i=E.getAxesPermutation(o,r.shape.length),l=r,c=[];i!=null&&(l=Ms({inputs:{x:r},backend:n,attrs:{perm:i}}),c.push(l),o=E.getInnerMostAxes(o.length,l.shape.length)),o=[o[0]],E.assertAxesAreInnerMostDims("argMin",o,l.shape.length);let[u,d]=E.computeOutAndReduceShapes(l.shape,o),p=v.sizeFromShape(u),h=v.makeZerosTypedArray(p,"int32"),f=v.sizeFromShape(d),m=n.data.get(l.dataId).values;for(let g=0;gn.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(u,"int32",h)}var jj={kernelName:du,backendName:"cpu",kernelFunc:Hj},qj=ft(pu,e=>Math.asin(e)),Xj={kernelName:pu,backendName:"cpu",kernelFunc:qj},Kj=ft(hu,e=>Math.asinh(e)),Zj={kernelName:hu,backendName:"cpu",kernelFunc:Kj},Yj=ft(fu,e=>Math.atan(e)),Jj={kernelName:fu,backendName:"cpu",kernelFunc:Yj},Qj=Yt((e,t)=>Math.atan2(e,t)),eq=vn(gu,Qj),tq={kernelName:gu,backendName:"cpu",kernelFunc:eq},nq=ft(mu,e=>Math.atanh(e)),sq={kernelName:mu,backendName:"cpu",kernelFunc:nq};function nx(e,t,n,s,r,a){let o=r.strideHeight,i=r.strideWidth,l=r.dilationHeight,c=r.dilationWidth,u=r.effectiveFilterHeight,d=r.effectiveFilterWidth,p=r.padInfo.top,h=r.padInfo.left,f=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=ze(r.outShape,n),g=m.values,A=r.outShape[1]*r.outShape[2]*r.outShape[3],x=r.outShape[2]*r.outShape[3],y=r.outShape[3];for(let b=0;bz?z=oe:a==="avg"&&(K+=oe,J++)}if(isNaN(z))break}let Q=P+T*y+I;g[Q]=a==="avg"?K/J:z}}}return m}function iI(e,t,n,s,r=!1,a=!1){let o=ze(s.outShape,"int32"),i=s.strideHeight,l=s.strideWidth,c=s.dilationHeight,u=s.dilationWidth,d=s.effectiveFilterHeight,p=s.effectiveFilterWidth,h=s.padInfo.top,f=s.padInfo.left,m=ze(t,n,e);for(let g=0;gO&&(O=q,r?$=a?((g*s.inHeight+P)*s.inWidth+F)*s.inChannels+A:(P*s.inWidth+F)*s.inChannels+A:$=T*p+U)}}o.set($,g,x,k,A)}}return o}function lI(e,t,n,s,r,a){let o=r.strideDepth,i=r.strideHeight,l=r.strideWidth,c=r.dilationDepth,u=r.dilationHeight,d=r.dilationWidth,p=r.effectiveFilterDepth,h=r.effectiveFilterHeight,f=r.effectiveFilterWidth,m=r.padInfo.front,g=r.padInfo.top,A=r.padInfo.left,x=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,y=ze(r.outShape,n),b=y.values,w=r.outShape[1]*r.outShape[2]*r.outShape[3]*r.outShape[4],k=r.outShape[2]*r.outShape[3]*r.outShape[4],I=r.outShape[3]*r.outShape[4],N=r.outShape[4];for(let R=0;Rwe?we=mt:a==="avg"&&(Ne+=mt,Me++),isNaN(we))break}if(isNaN(we))break}if(isNaN(we))break}let Ue=ye+P;b[Ue]=a==="avg"?Ne/Me:we}}}}return y}function rq(e,t){let n=ze(t.outShape,"int32"),s=t.strideDepth,r=t.strideHeight,a=t.strideWidth,o=t.dilationDepth,i=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,u=t.effectiveFilterHeight,d=t.effectiveFilterWidth,p=t.padInfo.front,h=t.padInfo.top,f=t.padInfo.left;for(let m=0;m=T&&(T=ne,F=q*u*d+K*u+Q)}}}n.set(F,m,A,w,R,g)}}}return n}function aq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t;Re(r,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,c=1;v.assert(E.eitherStridesOrDilationsAreOne(o,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);let u=E.computePool2DInfo(r.shape,a,o,c,i,l),d;if(u.filterWidth===1&&u.filterHeight===1&&v.arraysEqual(u.inShape,u.outShape))d=Ur({inputs:{x:r},backend:n});else{let p=n.data.get(r.dataId).values,h=v.computeStrides(r.shape),f=nx(p,r.shape,r.dtype,h,u,"avg");d=n.makeTensorInfo(u.outShape,r.dtype,f.values)}return d}var oq={kernelName:_a,backendName:"cpu",kernelFunc:aq};function iq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l,dataFormat:c}=s;Re(r,"avgPool3d");let u=E.computePool3DInfo(r.shape,a,o,1,i,l,c),d=n.data.get(r.dataId).values,p=lI(d,r.shape,r.dtype,v.computeStrides(r.shape),u,"avg");return n.makeTensorInfo(p.shape,"float32",p.values)}var lq={kernelName:od,backendName:"cpu",kernelFunc:iq};function uq(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,{filterSize:o,strides:i,pad:l,dimRoundingMode:c}=s;Re([r,a],"avgPool3DGrad");let u=E.computePool3DInfo(a.shape,o,i,1,l,c),d=u.strideDepth,p=u.strideHeight,h=u.strideWidth,f=u.filterDepth,m=u.filterHeight,g=u.filterWidth,A=u.dilationDepth,x=u.dilationHeight,y=u.dilationWidth,b=u.effectiveFilterDepth,w=u.effectiveFilterHeight,k=u.effectiveFilterWidth,I=b-1-u.padInfo.front,N=k-1-u.padInfo.left,R=w-1-u.padInfo.top,O=ze(a.shape,"float32"),$=1/(f*m*g),P=n.bufferSync(r);for(let T=0;T=u.outDepth||Math.floor(G)!==G))for(let se=0;se=u.outHeight||Math.floor(oe)!==oe))for(let pe=0;pe=u.outWidth||Math.floor(ye)!==ye)continue;ne+=P.get(T,G,oe,ye,F)}}}O.set(ne*$,T,U,q,z,F)}return n.makeTensorInfo(O.shape,O.dtype,O.values)}var cq={kernelName:Ih,backendName:"cpu",kernelFunc:uq};function dq(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,o=a;Re([r,a],"avgPoolGrad");let{filterSize:i,strides:l,pad:c}=s,u=E.computePool2DInfo(o.shape,i,l,1,c),d=u.strideHeight,p=u.strideWidth,h=u.filterHeight,f=u.filterWidth,m=u.dilationHeight,g=u.dilationWidth,A=u.effectiveFilterHeight,x=u.effectiveFilterWidth,y=x-1-u.padInfo.left,b=A-1-u.padInfo.top,w=ze(o.shape,"float32"),k=1/(h*f),I=n.data.get(r.dataId).values,N=ze(r.shape,"float32",I);for(let R=0;R=u.outHeight||Math.floor(z)!==z))for(let K=0;K=u.outWidth||Math.floor(J)!==J)continue;U+=N.get(R,z,J,O)}}w.set(U*k,R,$,P,O)}return n.makeTensorInfo(w.shape,w.dtype,w.values)}var pq={kernelName:Sh,backendName:"cpu",kernelFunc:dq};function hq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,scale:a,offset:o,mean:i,variance:l}=t;v.assert(i.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),v.assert(o==null||i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),v.assert(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),Re([r,i,l,a,o],"batchNorm");let{varianceEpsilon:c}=s;c==null&&(c=.001);let u=n.data.get(r.dataId).values,d=n.data.get(i.dataId).values,p=n.data.get(l.dataId).values,h=a?n.data.get(a.dataId).values:new Float32Array([1]),f=o?n.data.get(o.dataId).values:new Float32Array([0]),m=new Float32Array(u.length),g=f.length,A=h.length,x=p.length,y=d.length,b=0,w=0,k=0,I=0;for(let N=0;N=g&&(b=0),w>=y&&(w=0),k>=A&&(k=0),I>=x&&(I=0);return n.makeTensorInfo(r.shape,r.dtype,m)}var fq={kernelName:ja,backendName:"cpu",kernelFunc:hq};function mq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:o}=s;Re([r],"batchToSpaceND");let i=a.reduce((A,x)=>A*x),l=E.getReshaped(r.shape,a,i),c=E.getPermuted(l.length,a.length),u=E.getReshapedPermuted(r.shape,a,i),d=E.getSliceBeginCoords(o,a.length),p=E.getSliceSize(u,o,a.length),h=_t({inputs:{x:r},backend:n,attrs:{shape:l}}),f=Ms({inputs:{x:h},backend:n,attrs:{perm:c}}),m=_t({inputs:{x:f},backend:n,attrs:{shape:u}}),g=Tl({inputs:{x:m},backend:n,attrs:{begin:d,size:p}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}var gq={kernelName:mi,backendName:"cpu",kernelFunc:mq};function Aq(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:o}=s,i=n.data.get(r.dataId).values,l=n.data.get(a.dataId).values,c=Xy(i,l,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,c)}var yq={kernelName:Ch,backendName:"cpu",kernelFunc:Aq};function xq(e){let{inputs:t,backend:n}=e,{s0:s,s1:r}=t,a=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,i=E.assertAndGetBroadcastShape(Array.from(a),Array.from(o));return n.makeTensorInfo([i.length],"int32",Int32Array.from(i))}var bq={kernelName:Th,backendName:"cpu",kernelFunc:xq},vq=ft(Zr,(e,t)=>{let n=t;return e>n.clipValueMax?n.clipValueMax:e{let{x:t}=e.inputs,n=e.backend,s=new Float32Array(v.sizeFromShape(t.shape)),r=n.data.get(t.dataId),a=r.complexTensorInfos.real,o=r.complexTensorInfos.imag,i=n.data.get(a.dataId).values,l=n.data.get(o.dataId).values;for(let c=0;cm.shape),a);if(v.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(m=>v.sizeFromShape(m.shape)>0);if(i.length===1)return Ur({inputs:{x:i[0]},backend:n});let l=i.map(m=>m.shape);if(E.assertParamsConsistent(l,a),i[0].dtype==="complex64"){let m=i.map(b=>Cl({inputs:{input:b},backend:n})),g=i.map(b=>ac({inputs:{input:b},backend:n})),A=oc({inputs:m,backend:n,attrs:{axis:a}}),x=oc({inputs:g,backend:n,attrs:{axis:a}}),y=vs({inputs:{real:A,imag:x},backend:n});return m.forEach(b=>n.disposeIntermediateTensorInfo(b)),g.forEach(b=>n.disposeIntermediateTensorInfo(b)),n.disposeIntermediateTensorInfo(A),n.disposeIntermediateTensorInfo(x),y}let c=i.map(m=>{let g=v.sizeFromShape(m.shape.slice(a));return _t({inputs:{x:m},backend:n,attrs:{shape:[-1,g]}})}),u=c.map(m=>({vals:n.data.get(m.dataId).values,shape:m.shape}));o=E.computeOutShape(c.map(m=>m.shape),1);let d=c[0].shape[0]===1,p=Ky(u,o,t[0].dtype,d),h=E.computeOutShape(i.map(m=>m.shape),a),f=n.makeTensorInfo(h,t[0].dtype,p);return c.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}var Cq={kernelName:gi,backendName:"cpu",kernelFunc:oc};function uI(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dataFormat:l,dilations:c,dimRoundingMode:u}=s;Re([r,a],"conv2d");let d=E.convertConv2DDataFormat(l),p=E.computeConv2DInfo(r.shape,a.shape,o,c,i,u,!1,d),h=p.filterHeight,f=p.filterWidth,m=p.dilationHeight,g=p.dilationWidth,A=p.padInfo.left,x=p.padInfo.top,y=p.dataFormat==="channelsLast",b=new tn(p.outShape,r.dtype),w=v.computeStrides(r.shape),k=v.computeStrides(a.shape),I=w[0],N=y?w[1]:w[2],R=y?w[2]:1,O=y?1:w[1],$=b.strides[0],P=y?b.strides[1]:b.strides[2],T=y?b.strides[2]:1,F=y?1:b.strides[1],U=n.data.get(r.dataId).values,q=n.data.get(a.dataId).values,z=b.values;for(let K=0;K=p.inHeight)continue;let pe=se*k[0],ye=J+oe*N;for(let we=0;we=p.inWidth)continue;let Ke=pe+Ue*k[1],dt=ye+qe*R,pt=Ke;for(let rt=0;rt=c.inDepth)continue;let K=q*R[0],J=$+z*N[1];for(let Q=0;Q=c.inHeight)continue;let oe=K+G*R[1],pe=J+se*N[2];for(let ye=0;ye=c.inWidth)continue;let qe=oe+Me*R[2],Ke=pe+Ue*c.inChannels,dt=qe;for(let pt=0;ptMath.cos(e)),Lq={kernelName:za,backendName:"cpu",kernelFunc:zq},Bq=ft(La,e=>Math.cosh(e)),Wq={kernelName:La,backendName:"cpu",kernelFunc:Bq};function Vq(e){let{inputs:t,backend:n,attrs:s}=e,{image:r,boxes:a,boxInd:o}=t,{cropSize:i,method:l,extrapolationValue:c}=s,[u,d,p,h]=r.shape,f=a.shape[0],[m,g]=i,A=ze([f,m,g,h],"float32"),x=n.data.get(a.dataId).values,y=n.data.get(o.dataId).values,b=n.data.get(r.dataId).values,w=v.computeStrides(r.shape),k=v.computeStrides(A.shape);for(let I=0;I=u)continue;let F=m>1?($-R)*(d-1)/(m-1):0,U=g>1?(P-O)*(p-1)/(g-1):0;for(let q=0;q1?R*(d-1)+q*F:.5*(R+$)*(d-1);if(z<0||z>d-1){for(let K=0;K1?O*(p-1)+ne*U:.5*(O+P)*(p-1);if(re<0||re>p-1){for(let pe=0;pe1?O*(p-1)+K*U:.5*(O+P)*(p-1);if(J<0||J>p-1){for(let re=0;reA+f-x-1:(A,x)=>A+x;for(let A=0;A`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${o}`);let i=r.shape[0],l=r.shape[1],c=r.shape[2],u=r.shape[3],d=l*a,p=c*a,h=u/(a*a),f=n.data.get(r.dataId).values,m=new Float32Array(i*d*p*h),g=0;for(let A=0;A`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${p}'`);let h=E.computeConv2DInfo(r.shape,a.shape,o,p,i,c,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:A,padInfo:x}=h,y=x.left,b=x.top,w=h.outChannels/h.inChannels,k=new tn(h.outShape,r.dtype),I=n.data.get(r.dataId).values,N=n.data.get(a.dataId).values,R=k.values;for(let O=0;O=h.inHeight)continue;let K=q*d[0],J=$+z*u[1];for(let Q=0;Q=h.inWidth)continue;let oe=K+G*d[1],pe=J+se*h.inChannels,ye=ne,we=oe;for(let Ne=0;Ne{let{x:s,filter:r}=e,{strides:a,pad:o,dilations:i}=n,l=t,c=l.data.get(s.dataId).values,u=s.shape.length,d=l.data.get(r.dataId).values,p=r.shape.length,{batchSize:h,inHeight:f,inWidth:m,inChannels:g,outHeight:A,outWidth:x,padInfo:y,strideHeight:b,strideWidth:w,filterHeight:k,filterWidth:I,dilationHeight:N,dilationWidth:R,outShape:O}=E.computeDilation2DInfo(s.shape,r.shape,a,o,"NHWC",i),$=v.sizeFromShape(O),P=O.length,T=v.getArrayFromDType(s.dtype,$);for(let U=0;U=0&&se=0&&pene&&(ne=Ne)}}}let re=v.locToIndex([U,q,K,Q],P,v.computeStrides(O));T[re]=ne}}}return{dataId:l.write(v.toTypedArray(T,s.dtype),O,s.dtype),shape:O,dtype:s.dtype}}},rX={kernelName:Oh,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:s,filter:r,dy:a}=e,{strides:o,pad:i,dilations:l}=n,c=t,u=v.toNestedArray(s.shape,c.data.get(s.dataId).values),d=v.toNestedArray(r.shape,c.data.get(r.dataId).values),{batchSize:p,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:A,padInfo:x,strideHeight:y,strideWidth:b,filterHeight:w,filterWidth:k,dilationHeight:I,dilationWidth:N,outShape:R}=E.computeDilation2DInfo(s.shape,r.shape,o,i,"NHWC",l);v.assert(a.rank===R.length,()=>`Error in ${Oh}, dy must have the same rank as output ${R.length}, but got ${a.rank}`);let O=v.toNestedArray(R,c.data.get(a.dataId).values),$=v.makeZerosNestedTypedArray(r.shape,r.dtype);for(let T=0;T=0&&G=0&&oeJ&&(J=pe,Q=re,ne=se)}}}$[Q][ne][K]+=O[T][F][q][K]}}}return{dataId:c.write(v.toTypedArray($,s.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},aX={kernelName:Fh,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:s,filter:r,dy:a}=e,{strides:o,pad:i,dilations:l}=n,c=t,u=v.toNestedArray(s.shape,c.data.get(s.dataId).values),d=v.toNestedArray(r.shape,c.data.get(r.dataId).values),{batchSize:p,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:A,padInfo:x,strideHeight:y,strideWidth:b,filterHeight:w,filterWidth:k,dilationHeight:I,dilationWidth:N,outShape:R}=E.computeDilation2DInfo(s.shape,r.shape,o,i,"NHWC",l);v.assert(a.rank===R.length,()=>`Error in ${Fh}, dy must have the same rank as output ${R.length}, but got ${a.rank}`);let O=v.toNestedArray(R,c.data.get(a.dataId).values),$=v.makeZerosNestedTypedArray(s.shape,s.dtype);for(let T=0;T=0&&G=0&&oeJ&&(J=pe,Q=G,ne=oe)}}}$[T][Q][ne][K]+=O[T][F][q][K]}}}return{dataId:c.write(v.toTypedArray($,s.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}};function pp(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;Re(r,"sum");let i;r.dtype==="bool"?i=Go({inputs:{x:r},backend:n,attrs:{dtype:"int32"}}):i=Ur({inputs:{x:r},backend:n});let l=i.shape.length,c=v.parseAxisParam(a,i.shape),u=E.getAxesPermutation(c,l),d=c,p=i;u!=null&&(p=Ms({inputs:{x:i},backend:n,attrs:{perm:u}}),d=E.getInnerMostAxes(d.length,l)),E.assertAxesAreInnerMostDims("sum",d,p.shape.length);let[h,f]=E.computeOutAndReduceShapes(p.shape,d),m=E.upcastType(p.dtype,"int32"),g=Rm(n,h,m),A=v.sizeFromShape(f),x=n.data.get(g.dataId).values,y=n.data.get(p.dataId).values;for(let b=0;b=0&&(p=pp({inputs:{x:p},backend:n,attrs:{axis:c[m]-(o.length-h),keepDims:!1}}),f.push(p)),h--)}for(let m of f)m!==p&&n.disposeIntermediateTensorInfo(m);return p}var lX={kernelName:dd,backendName:"cpu",kernelFunc:iX};function uX(e){let{inputs:t,backend:n}=e,{dy:s,y:r}=t;Re([s,r],"eluGrad");let a=new Float32Array(v.sizeFromShape(r.shape)),o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values;for(let l=0;l=1?a[l]=i[l]:a[l]=i[l]*(c+1)}return n.makeTensorInfo(r.shape,"float32",a)}var cX={kernelName:Mh,backendName:"cpu",kernelFunc:uX},dX=E.ERF_P,pX=E.ERF_A1,hX=E.ERF_A2,fX=E.ERF_A3,mX=E.ERF_A4,gX=E.ERF_A5,AX=ft(Au,e=>{let t=Math.sign(e),n=Math.abs(e),s=1/(1+dX*n);return t*(1-((((gX*s+mX)*s+fX)*s+hX)*s+pX)*s*Math.exp(-n*n))}),yX={kernelName:Au,backendName:"cpu",kernelFunc:AX};function Dm(e){let{inputs:t,backend:n,attrs:s}=e,{input:r}=t,{dim:a}=s,o=r.shape.length,i=r.shape.slice(),l=a;return a<0&&(v.assert(-(o+1)<=a,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+a+1),i.splice(l,0,1),_t({inputs:{x:r},backend:n,attrs:{shape:i}})}var xX={kernelName:vi,backendName:"cpu",kernelFunc:Dm},bX=Yt((e,t)=>e/t),sx=vn(Wa,bX),rx={kernelName:Wa,backendName:"cpu",kernelFunc:sx};function dI(e,t,n){let s=e.shape,r=s[0],a=s[1],o=n.data.get(e.dataId),i=o.complexTensorInfos.real,l=o.complexTensorInfos.imag,c=[r,a],u=v.sizeFromShape(c),d=v.getTypedArrayFromDType("float32",u),p=v.getTypedArrayFromDType("float32",u);for(let g=0;g{let{image:s}=e,r=n,a=v.getTypedArrayFromDType(s.dtype,v.sizeFromShape(s.shape)),[o,i,l,c]=s.shape,u=r.data.get(s.dataId).values;for(let p=0;p=0&&yMath.floor(e/t)),RX=vn(Ha,EX,null,"int32"),$X={kernelName:Ha,backendName:"cpu",kernelFunc:RX};function _X(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=s,m=uI({inputs:{x:r,filter:a},backend:n,attrs:{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p}});if(o){let g=m;m=cp({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=m;m=tx(n,m,h,i,f),n.disposeIntermediateTensorInfo(g)}return m}var DX={kernelName:ko,backendName:"cpu",kernelFunc:_X};function PX(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=s,m=cI({inputs:{x:r,filter:a},backend:n,attrs:{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p}});if(o){let g=m;m=cp({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=m;m=tx(n,m,h,i,f),n.disposeIntermediateTensorInfo(g)}return m}var FX={kernelName:So,backendName:"cpu",kernelFunc:PX};function OX(e){let{inputs:t,backend:n}=e,{params:s,indices:r}=t,a=v.sizeFromShape(s.shape),o=r.shape,i=o[o.length-1],[l,c,u,d]=E.prepareAndValidate(s,r);if(c===0)return n.makeTensorInfo(l,s.dtype,[]);let p=n.data.get(r.dataId).values,h=n.bufferSync(s),f=TS(p,h,s.dtype,c,i,u,d,s.shape,a);return n.makeTensorInfo(l,s.dtype,f.values)}var MX={kernelName:Ii,backendName:"cpu",kernelFunc:OX};function zX(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,indices:a}=t,{axis:o,batchDims:i}=s;Re([r,a],"gatherV2");let l=v.parseAxisParam(o,r.shape)[0],c=n.data.get(a.dataId).values,u=r.shape[l];for(let b=0;b=0,()=>`GatherV2: the index value ${w} is not in [0, ${u-1}]`)}let d=i;i==null&&(d=0);let p=v.sizeFromShape(a.shape),h=E.segment_util.collectGatherOpShapeInfo(r,a,l,d),f=_t({inputs:{x:r},backend:n,attrs:{shape:[h.batchSize,h.outerSize,h.dimSize,h.sliceSize]}}),m=_t({inputs:{x:a},backend:n,attrs:{shape:[h.batchSize,p/h.batchSize]}}),g=[h.batchSize,h.outerSize,p/h.batchSize,h.sliceSize],A=n.bufferSync(m),x=n.bufferSync(f),y=NS(x,A,g);return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.makeTensorInfo(h.outputShape,y.dtype,y.values)}var LX={kernelName:Si,backendName:"cpu",kernelFunc:zX};function BX(e){let{inputs:t,backend:n}=e,{input:s}=t,r=v.sizeFromShape(s.shape),a=s.shape[s.shape.length-1],o=r/a,i=_t({inputs:{x:s},backend:n,attrs:{shape:[o,a]}}),l=dI(i,!0,n),c=_t({inputs:{x:l},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),c}var WX={kernelName:Lh,backendName:"cpu",kernelFunc:BX},VX=ft(xu,e=>Number.isFinite(e)?1:0,"bool"),UX={kernelName:xu,backendName:"cpu",kernelFunc:VX},GX=ft(bu,e=>Math.abs(e)===1/0?1:0,"bool"),HX={kernelName:bu,backendName:"cpu",kernelFunc:GX},jX=ft(vu,e=>Number.isNaN(e)?1:0,"bool"),qX={kernelName:vu,backendName:"cpu",kernelFunc:jX};function XX(e){let{backend:t,attrs:n}=e,{start:s,stop:r,num:a}=n,o=DS(s,r,a);return t.makeTensorInfo([o.length],"float32",o)}var KX={kernelName:Bh,backendName:"cpu",kernelFunc:XX},ZX=ft(wu,e=>Math.log1p(e)),YX={kernelName:wu,backendName:"cpu",kernelFunc:ZX},JX=Yt((e,t)=>e&&t),QX=vn(Ri,JX,null,"bool"),eK={kernelName:Ri,backendName:"cpu",kernelFunc:QX},tK=ft(ku,e=>e?0:1,"bool"),nK={kernelName:ku,backendName:"cpu",kernelFunc:tK},sK=Yt((e,t)=>e||t),rK=vn(hd,sK,null,"bool"),aK={kernelName:hd,backendName:"cpu",kernelFunc:rK};function oK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{depthRadius:a,bias:o,alpha:i,beta:l}=s;Re(r,"LRN");let c=r.shape[3],u=c-1,d=n.data.get(r.dataId).values,p=v.sizeFromShape(r.shape),h=new Float32Array(p);function f(m){let g=m%c,A=m-g+Math.max(0,g-a),x=m-g+Math.min(g+a,u),y=0;for(;A<=x;A++){let b=d[A];y+=b*b}return y}for(let m=0;m`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);let u=E.computePool2DInfo(r.shape,a,o,c,i,l),d;if(u.filterWidth===1&&u.filterHeight===1&&v.arraysEqual(u.inShape,u.outShape))d=Ur({inputs:{x:r},backend:n});else{let p=n.data.get(r.dataId).values,h=v.computeStrides(r.shape),f=nx(p,r.shape,r.dtype,h,u,"max");d=n.makeTensorInfo(u.outShape,r.dtype,f.values)}return d}var pK={kernelName:Ja,backendName:"cpu",kernelFunc:dK};function hK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l,dataFormat:c}=s;Re(r,"maxPool3d");let u=E.computePool3DInfo(r.shape,a,o,1,i,l,c),d=n.data.get(r.dataId).values,p=lI(d,r.shape,r.dtype,v.computeStrides(r.shape),u,"max");return n.makeTensorInfo(p.shape,"float32",p.values)}var fK={kernelName:md,backendName:"cpu",kernelFunc:hK};function mK(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,{filterSize:o,strides:i,pad:l,dimRoundingMode:c}=s;Re([r,a],"maxPool3DGrad");let u=E.computePool3DInfo(a.shape,o,i,1,l,c),d=n.bufferSync(a),p=rq(d,u),h=u.strideDepth,f=u.strideHeight,m=u.strideWidth,g=u.dilationDepth,A=u.dilationHeight,x=u.dilationWidth,y=u.effectiveFilterDepth,b=u.effectiveFilterHeight,w=u.effectiveFilterWidth,k=y-1-u.padInfo.front,I=w-1-u.padInfo.left,N=b-1-u.padInfo.top,R=ze(a.shape,"float32"),O=n.bufferSync(r);for(let $=0;$=u.outDepth||Math.floor(ne)!==ne))for(let re=0;re=u.outHeight||Math.floor(G)!==G))for(let se=0;se=u.outWidth||Math.floor(oe)!==oe)continue;let pe=y*b*w-1-p.get($,ne,G,oe,P),ye=Q*b*w+re*w+se,we=pe===ye?1:0;if(we===0)continue;J+=O.get($,ne,G,oe,P)*we}}}R.set(J,$,T,F,U,P)}return n.makeTensorInfo(R.shape,R.dtype,R.values)}var gK={kernelName:Uh,backendName:"cpu",kernelFunc:mK};function AK(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a,output:o}=t,i=a;Re([a,o],"maxPoolGrad");let{filterSize:l,strides:c,pad:u,dimRoundingMode:d}=s,p=E.computePool2DInfo(i.shape,l,c,1,u,d),h=n.data.get(i.dataId).values,f=ze(p.outShape,i.dtype,iI(h,i.shape,i.dtype,p).values),m=p.strideHeight,g=p.strideWidth,A=p.dilationHeight,x=p.dilationWidth,y=p.effectiveFilterHeight,b=p.effectiveFilterWidth,w=b-1-p.padInfo.left,k=y-1-p.padInfo.top,I=ze(i.shape,"float32"),N=n.data.get(r.dataId).values,R=ze(r.shape,"float32",N);for(let O=0;O=p.outHeight||Math.floor(K)!==K))for(let J=0;J=p.outWidth||Math.floor(Q)!==Q)continue;let ne=y*b-1-f.get(O,K,Q,$),re=z*b+J,G=ne===re?1:0;if(G===0)continue;q+=R.get(O,K,Q,$)*G}}I.set(q,O,P,T,$)}return n.makeTensorInfo(I.shape,I.dtype,I.values)}var yK={kernelName:Vh,backendName:"cpu",kernelFunc:AK};function xK(e,t,n,s,r){let a=v.computeStrides(t),o=nx(e,t,n,a,r,"max"),i=iI(e,t,n,r,!0,s);return[o.values,i.values]}var bK={kernelName:Gh,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:s}=e,{filterSize:r,strides:a,pad:o,includeBatchInIndex:i}=t,l=n;Re(s,"MaxPoolWithArgmax");let c=l.data.get(s.dataId).values,u=E.computePool2DInfo(s.shape,r,a,[1,1],o),[d,p]=xK(c,s.shape,s.dtype,i,u),h=l.write(d,u.outShape,s.dtype),f=l.write(p,u.outShape,s.dtype);return[{dataId:h,shape:u.outShape,dtype:s.dtype},{dataId:f,shape:u.outShape,dtype:"int32"}]}};function vK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s,i=v.parseAxisParam(a,r.shape),c=E.computeOutAndReduceShapes(r.shape,i)[1],u=v.sizeFromShape(c),d=[],p=n.makeTensorInfo([],"float32",new Float32Array([u]));d.push(p);let h=Go({inputs:{x:r},backend:n,attrs:{dtype:"float32"}});d.push(h);let f=sx({inputs:{a:h,b:p},backend:n});d.push(f);let m=pp({inputs:{x:f},backend:n,attrs:{axis:a,keepDims:o}});return d.forEach(g=>n.disposeIntermediateTensorInfo(g)),m}var wK={kernelName:Qa,backendName:"cpu",kernelFunc:vK};function kK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;Re(r,"min");let i=v.parseAxisParam(a,r.shape),l=i,c=E.getAxesPermutation(l,r.shape.length),u=r;c!=null&&(u=Ms({inputs:{x:r},backend:n,attrs:{perm:c}}),l=E.getInnerMostAxes(l.length,r.shape.length)),E.assertAxesAreInnerMostDims("min",l,u.shape.length);let[d,p]=E.computeOutAndReduceShapes(u.shape,l),h=v.sizeFromShape(p),f=v.makeZerosTypedArray(v.sizeFromShape(d),u.dtype),m=n.data.get(u.dataId).values;for(let A=0;Ay[0]+r.shape[b]+y[1]),l=a.map(y=>y[0]),c=a.map((y,b)=>y[0]+r.shape[b]),u=o==="reflect"?0:1,d=n.data.get(r.dataId).values,p=r.shape.length,h=v.computeStrides(r.shape),f=v.sizeFromShape(i),m=i.length,g=v.computeStrides(i),A=v.getTypedArrayFromDType(r.dtype,f);for(let y=0;y=c[k]&&(b[k]=(c[k]-1)*2-b[k]+u);b=b.map((k,I)=>k-l[I]);let w=v.locToIndex(b,p,h);A[y]=d[w]}return{dataId:n.write(A,i,r.dtype),shape:i,dtype:r.dtype}}var CK={kernelName:no,backendName:"cpu",kernelFunc:IK},TK=Yt((e,t)=>{let n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}),NK=vn(Su,TK),EK={kernelName:Su,backendName:"cpu",kernelFunc:NK},RK=di(xh());function hI(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{dim:a}=s,o=r.shape.length,i=a;if(i===-1&&(i=o-1),i!==o-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${o} and dim was ${i}`);let l=v.parseAxisParam([i],r.shape),c=pI({inputs:{x:r},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),u=E.expandShapeToKeepDim(c.shape,l),d=_t({inputs:{x:c},backend:n,attrs:{shape:u}}),p=ex({inputs:{a:r,b:d},backend:n}),h=SS({inputs:{x:p},backend:n}),f=pp({inputs:{x:h},backend:n,attrs:{axis:l,keepDims:!1}}),m=_t({inputs:{x:f},backend:n,attrs:{shape:u}}),g=sx({inputs:{a:h,b:m},backend:n});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}var $K={kernelName:go,backendName:"cpu",kernelFunc:hI};function _K(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{numSamples:a,seed:o,normalized:i}=s;Re(r,"multinomial");let l=i?r:hI({inputs:{logits:r},backend:n,attrs:{dim:-1}}),c=l.shape[0],u=l.shape[1],d=n.data.get(l.dataId).values,p=[c,a],h=v.makeZerosTypedArray(v.sizeFromShape(p),"int32");for(let f=0;f=0&&u[d]{v.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),v.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(u=>{let d=Dm({inputs:{input:u},backend:n,attrs:{dim:r}});return i.push(d),d}),c=oc({inputs:l,backend:n,attrs:{axis:r}});return i.forEach(u=>n.disposeIntermediateTensorInfo(u)),c}var qK={kernelName:Mi,backendName:"cpu",kernelFunc:mI};function XK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,constantValue:o}=s;Re(r,"pad");let i=a.map((x,y)=>x[0]+r.shape[y]+x[1]),l=a.map(x=>x[0]),c=n.data.get(r.dataId).values,u=v.sizeFromShape(r.shape),d=r.shape.length,p=v.computeStrides(r.shape),h=v.sizeFromShape(i),f=i.length,m=v.computeStrides(i),g=v.getTypedArrayFromDType(r.dtype,h);o!==0&&g.fill(o);for(let x=0;xk+l[I]),w=v.locToIndex(b,f,m);g[w]=c[x]}return{dataId:n.write(g,i,r.dtype),shape:i,dtype:r.dtype}}var gI={kernelName:ro,backendName:"cpu",kernelFunc:XK},KK=Yt((e,t)=>Math.pow(e,t)),ZK=vn(ao,KK),YK={kernelName:ao,backendName:"cpu",kernelFunc:ZK};function JK(e){let{backend:t,attrs:n}=e,{start:s,stop:r,dtype:a,step:o}=n,i=Jy(s,r,o,a);return t.makeTensorInfo([i.length],a,i)}var QK={kernelName:Cu,backendName:"cpu",kernelFunc:JK},eZ=ft(Tu,e=>1/e),tZ={kernelName:Tu,backendName:"cpu",kernelFunc:eZ};function nZ(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:o,size:i}=s;Re(r,"resizeBilinear");let l=v.computeStrides(r.shape),[c,u]=i,[d,p,h,f]=r.shape,m=n.data.get(r.dataId).values,g=new Float32Array(v.sizeFromShape([d,c,u,f])),A=[a&&c>1?p-1:p,a&&u>1?h-1:h],x=[a&&c>1?c-1:c,a&&u>1?u-1:u],y=0,b=A[0]/x[0],w=A[1]/x[1];for(let k=0;k1?c-1:c,o&&h>1?u-1:u],g=[o&&p>1?p-1:p,o&&h>1?h-1:h],A=m[0]/g[0],x=m[1]/g[1],y=n.data.get(a.dataId).values,b=0;for(let w=0;w1?p-1:p,a&&u>1?h-1:h],x=[a&&c>1?c-1:c,a&&u>1?u-1:u],y=A[0]/x[0],b=A[1]/x[1],w=0;for(let k=0;k1?u-1:u,o&&f>1?d-1:d],x=[o&&h>1?h-1:h,o&&f>1?f-1:f],y=A[0]/x[0],b=A[1]/x[1],w=1/y,k=1/b,I=Math.ceil(w)*2+2,N=Math.ceil(k)*2+2;for(let R=0;R=h)continue;let G=O+re*l[1],se=re*y,oe=Math.min(u-1,o?Math.round(se):Math.floor(se));if($===oe)for(let pe=0;pe=f)continue;let we=G+ye*l[2],Ne=ye*b,Me=Math.min(d-1,o?Math.round(Ne):Math.floor(Ne));U===Me&&(Q+=g[we+J])}}m[q+J]=Q}}}}return n.makeTensorInfo(r.shape,r.dtype,m)}var uZ={kernelName:jh,backendName:"cpu",kernelFunc:lZ};function cZ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s;Re(r,"reverse");let o=r.shape.length,i=v.parseAxisParam(a,r.shape);if(o===0)return Ur({inputs:{x:r},backend:n});let l=new tn(r.shape,r.dtype),c=n.bufferSync(r);for(let u=0;up[h]=r.shape[h]-1-p[h]),l.set(c.get(...p),...d)}return n.makeTensorInfo(l.shape,l.dtype,l.values)}var dZ={kernelName:Bi,backendName:"cpu",kernelFunc:cZ},pZ={kernelName:el,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:s}=e,{radians:r,fillValue:a,center:o}=t,i=n,l=v.getTypedArrayFromDType(s.dtype,v.sizeFromShape(s.shape)),[c,u,d,p]=s.shape,[h,f]=E.getImageCenter(o,u,d),m=255,g=Math.sin(r),A=Math.cos(r),x=i.data.get(s.dataId).values;for(let b=0;b=0&&F=0&&U{let t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2==0?t:t+1}),fZ={kernelName:Wi,backendName:"cpu",kernelFunc:hZ};function AI(e,t,n,s,r,a,o,i,l,c){let u=[s/r,r],d=e.values,p=t.values;if(s===0)return ze(n,t.dtype);let h=ze(u,t.dtype);h.values.fill(l);for(let f=0;f=s/r)throw new Error(`Invalid indices: ${m} does not index into ${n}`);for(let A=0;A1||r.shape.length===1?1:v.sizeFromShape(r.shape.slice(1));for(let f=0;fe>=0?bZ*e:xZ*(Math.exp(e)-1)),wZ={kernelName:Eu,backendName:"cpu",kernelFunc:vZ},kZ=ft(Ru,e=>e<0?-1:e>0?1:0),SZ={kernelName:Ru,backendName:"cpu",kernelFunc:kZ},IZ=ft(po,e=>Math.sin(e)),CZ={kernelName:po,backendName:"cpu",kernelFunc:IZ},TZ=ft(Hi,e=>Math.sinh(e)),NZ={kernelName:Hi,backendName:"cpu",kernelFunc:TZ},EZ=11920928955078125e-23,yI=Math.log(EZ)+2,RZ=ft($u,e=>{let t=e>-yI,n=eNumber(g)))),n.makeTensorInfo([m.length],s.dtype,new Int32Array(m))]}var FZ={kernelName:Xh,backendName:"cpu",kernelFunc:PZ};function OZ(e){let{inputs:t,backend:n}=e,{inputIndices:s,inputShape:r,newShape:a}=t;if(s.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${s.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${r.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);let o=Array.from(n.data.get(r.dataId).values),i=n.data.get(s.dataId).values,l=Array.from(n.data.get(a.dataId).values),[c,u,d]=GS(i,s.shape,s.dtype,o,l);return[n.makeTensorInfo(u,s.dtype,c),n.makeTensorInfo([d.length],a.dtype,new Int32Array(d))]}var MZ={kernelName:Kh,backendName:"cpu",kernelFunc:OZ};function zZ(e){let{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape ${r.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape ${a.shape}`);let o=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values,l=n.data.get(a.dataId).values,[c,u]=Qy(o,s.shape,s.dtype,i,l,!0);return n.makeTensorInfo(u,s.dtype,c)}var LZ={kernelName:Zh,backendName:"cpu",kernelFunc:zZ};function BZ(e){let{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape ${r.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape ${a.shape}`);let o=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values,l=n.data.get(a.dataId).values,[c,u]=Qy(o,s.shape,s.dtype,i,l);return n.makeTensorInfo(u,s.dtype,c)}var WZ={kernelName:Yh,backendName:"cpu",kernelFunc:BZ};function VZ(e){let{inputs:t,backend:n,attrs:s}=e,{sparseIndices:r,sparseValues:a,defaultValue:o}=t,{outputShape:i}=s,{sliceRank:l,numUpdates:c,sliceSize:u,strides:d,outputSize:p}=E.calculateShapes(a,r,i),h=!1,f=n.bufferSync(r),m=n.bufferSync(a),g=n.data.get(o.dataId).values[0],A=AI(f,m,i,p,u,c,l,d,g,h);return n.makeTensorInfo(i,A.dtype,A.values)}var UZ={kernelName:Ad,backendName:"cpu",kernelFunc:VZ};function GZ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{numOrSizeSplits:a,axis:o}=s,i=v.parseAxisParam(o,r.shape)[0],l=E.prepareSplitSize(r,a,i),c=new Array(r.shape.length).fill(0),u=r.shape.slice();return l.map(d=>{let p=[...u];p[i]=d;let h=Tl({inputs:{x:r},backend:n,attrs:{begin:c,size:p}});return c[i]+=d,h})}var HZ={kernelName:qi,backendName:"cpu",kernelFunc:GZ},jZ={kernelName:_u,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,s=t;Re(n,"square");let r=s.data.get(n.dataId).values,a=new Float32Array(r.length);for(let i=0;i{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),XZ={kernelName:vo,backendName:"cpu",kernelFunc:qZ};function KZ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=s;Re(r,"stridedSlice");let{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:A,begin:x,end:y,strides:b}=Ft.sliceInfo(r.shape,a,o,i,l,c,u,d,p),w;if(m)w=_t({inputs:{x:r},backend:n,attrs:{shape:f}});else if(g||A){v.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let k=Ft.computeOutShape(x,y,b),I=Tl({inputs:{x:r},backend:n,attrs:{begin:x,size:k}});w=_t({inputs:{x:I},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(I)}else{let k=n.bufferSync(r),I=jS(h,k,b,x);w=n.makeTensorInfo(f,I.dtype,I.values)}return w}var ZZ={kernelName:Xi,backendName:"cpu",kernelFunc:KZ};function YZ(e){let{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:c}=s,{data:u,dataSplits:d}=t,p=n.data.get(u.dataId).values,h=n.data.get(d.dataId).values,[f,m]=qS(p,h,r,a,o,i,l,c);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var JZ={kernelName:yd,backendName:"cpu",kernelFunc:YZ};function QZ(e){let{inputs:t,backend:n,attrs:s}=e,{skipEmpty:r}=s,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.data.get(a.dataId).values,l=n.data.get(o.dataId).values[0],[c,u,d]=XS(i,l,r),p=u.length;return[n.makeTensorInfo([p,2],"int32",c),n.makeTensorInfo([p],"string",u),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var eY={kernelName:Jh,backendName:"cpu",kernelFunc:QZ};function tY(e){let{inputs:t,backend:n,attrs:s}=e,{numBuckets:r}=s,{input:a}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");let o=n.data.get(a.dataId).values,i=KS(o,r);return n.makeTensorInfo(a.shape,"int32",i)}var nY={kernelName:Qh,backendName:"cpu",kernelFunc:tY},sY=ft(Ki,e=>Math.tan(e)),rY={kernelName:Ki,backendName:"cpu",kernelFunc:sY},aY=ft(xo,e=>Math.tanh(e)),oY={kernelName:xo,backendName:"cpu",kernelFunc:aY};function iY(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reps:a}=s;Re(r,"tile");let o=YS(n.bufferSync(r),a);return n.makeTensorInfo(o.shape,o.dtype,o.values)}var lY={kernelName:Yr,backendName:"cpu",kernelFunc:iY};function uY(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{k:a,sorted:o}=s;Re(r,"topk");let i=n.data.get(r.dataId).values,[l,c]=QS(i,r.shape,r.dtype,a,o);return[n.makeTensorInfo(l.shape,l.dtype,l.values),n.makeTensorInfo(c.shape,c.dtype,c.values)]}var cY={kernelName:Zi,backendName:"cpu",kernelFunc:uY};function dY(e){let{inputs:t,attrs:n,backend:s}=e,{image:r,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:l,outputShape:c}=n,[u,d,p,h]=r.shape,[f,m]=c!=null?c:[d,p],g=[u,f,m,h],A=v.computeStrides(r.shape),x=A[0],y=A[1],b=A[2],w=v.getTypedArrayFromDType(r.dtype,v.sizeFromShape(g));w.fill(l);let k=s.data.get(r.dataId).values,I=s.data.get(a.dataId).values;for(let R=0;Rt-1)if(t<=1)n=0;else{let s=2*t;n-=s*Math.trunc(n/s),n>=t&&(n=s-n-1)}return v.clamp(0,n,t-1)}function fY(e,t){let n=e;if(n<0)if(t<=1)n=0;else{let s=t-1;n+=t*(Math.trunc(-n/s)+1)}else if(n>t-1)if(t<=1)n=0;else{let s=t-1;n-=t*Math.trunc(n/s)}return v.clamp(0,n,t-1)}function mY(e,t){return e}function gY(e,t){return v.clamp(0,e,t-1)}function hp(e,t,n,s,r,a,o,i,l,c,u){let d=o*s+i*r+l*a+c;return 0<=i&&in.disposeIntermediateTensorInfo(f)),h}var SY={kernelName:xd,backendName:"cpu",kernelFunc:kY},IY=[_j,SH,Pj,Oj,RH,zj,Bj,Vj,Gj,jj,Xj,Zj,Jj,tq,sq,oq,lq,cq,pq,Rj,fq,gq,yq,bq,NH,_H,wq,IH,Sq,Cq,Eq,$q,Tq,Fq,Mq,Dq,Lq,Wq,Uq,Hq,qq,Kq,Zq,Jq,eX,nX,sX,aX,rX,rx,lX,kj,cX,DH,yX,PH,xX,OH,IX,CX,NX,zH,$X,DX,FX,MX,LX,BH,VH,CH,WX,Iq,UX,HX,qX,Sj,GH,jH,KX,XH,YX,eK,nK,aK,iK,uK,ZH,pK,fK,gK,yK,bK,cK,wK,SK,JH,CK,EK,DK,ej,nj,OK,LK,VK,rj,GK,jK,qK,gI,YK,Cj,ij,QK,TH,tZ,Tj,Nj,Ej,sZ,aZ,iZ,uZ,dZ,pZ,fZ,uj,gZ,yZ,wZ,dj,SZ,CZ,NZ,pj,$K,$Z,DZ,FZ,MZ,LZ,WZ,UZ,HZ,mj,jZ,Aj,XZ,ZZ,JZ,eY,nY,vj,oX,rY,oY,lY,cY,aj,pY,bY,wY,SY,HK];for(let e of IY)cr(e);var bI={};Oe(bI,{assertNotComplex:()=>lc,bindCanvasToFramebuffer:()=>MY,bindColorTextureToFramebuffer:()=>zm,bindTextureToProgramUniformSampler:()=>FI,bindTextureUnit:()=>_I,bindVertexBufferToProgramAttribute:()=>ux,callAndCheck:()=>Te,canBeRepresented:()=>vI,createFragmentShader:()=>SI,createFramebuffer:()=>$I,createProgram:()=>II,createStaticIndexBuffer:()=>NI,createStaticVertexBuffer:()=>TI,createTexture:()=>EI,createVertexShader:()=>kI,getBatchDim:()=>El,getExtensionOrThrow:()=>gp,getFramebufferErrorMessage:()=>OI,getMaxTexturesInShader:()=>BI,getNumChannels:()=>FY,getProgramUniformLocation:()=>PI,getProgramUniformLocationOrThrow:()=>DI,getRowsCols:()=>Rl,getShapeAs3D:()=>Lm,getTextureShapeFromLogicalShape:()=>zI,getWebGLDisjointQueryTimerVersion:()=>WI,getWebGLErrorMessage:()=>wI,getWebGLMaxTextureSize:()=>LI,hasExtension:()=>Ls,isCapableOfRenderingToFloatTexture:()=>VI,isDownloadFloatTextureEnabled:()=>UI,isReshapeFree:()=>yp,isWebGLFenceEnabled:()=>GI,isWebGLVersionEnabled:()=>dx,linkProgram:()=>CI,resetMaxTextureSize:()=>zY,resetMaxTexturesInShader:()=>LY,unbindColorTextureFromFramebuffer:()=>cx,unbindTextureUnit:()=>OY,validateFramebuffer:()=>Ap,validateProgram:()=>Mm,validateTextureSize:()=>RI});var Nl={},ix={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Fm(e,t){Nl[e]=t}function Gr(e){if(!(e in Nl)){let n=TY(e);if(n!==null)Nl[e]=n;else return console.log("Could not get context for WebGL version",e),null}let t=Nl[e];return t==null||t.isContextLost()?(delete Nl[e],Gr(e)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),Nl[e])}function CY(e){if(typeof OffscreenCanvas!="undefined"&&e===2)return new OffscreenCanvas(300,150);if(typeof document!="undefined")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function TY(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let t=CY(e);return t.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete Nl[e]},!1),e===1?t.getContext("webgl",ix)||t.getContext("experimental-webgl",ix):t.getContext("webgl2",ix)}var fp;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(fp||(fp={}));var zs;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(zs||(zs={}));var Cn;(function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(Cn||(Cn={}));function mp(e,t){return[t,e]}function NY(e,t){return e*t}function Om(e){let t=v.sizeFromShape(e),n=Math.ceil(t/4);return v.sizeToSquarishShape(n)}function ic(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function EY(e,t){let[n,s]=ic(e,t);return n*s*4}function lx(e,t){let n=e,s,r,a,o,i,l,c,u,d,p;return Y().getNumber("WEBGL_VERSION")===2?(s=n.R32F,r=n.R16F,a=n.RGBA16F,o=n.RGBA32F,i=n.RED,c=4,u=1,d=n.HALF_FLOAT,p=n.FLOAT):(s=e.RGBA,r=e.RGBA,a=e.RGBA,o=n.RGBA,i=e.RGBA,c=4,u=4,d=t!=null?t.HALF_FLOAT_OES:null,p=e.FLOAT),l=e.RGBA,{internalFormatFloat:s,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:o,textureFormatFloat:i,downloadTextureFormat:l,downloadUnpackNumChannels:c,defaultNumChannels:u,textureTypeHalfFloat:d,textureTypeFloat:p}}function Te(e,t){let n=t();return Y().getBool("DEBUG")&&RY(e),n}function RY(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+wI(e,t))}var $Y=596e-10,_Y=65504;function vI(e){return!!(Y().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||$Ye.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function kI(e,t){let n=la(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(Te(e,()=>e.shaderSource(n,t)),Te(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}function SI(e,t){let n=la(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(Te(e,()=>e.shaderSource(n,t)),Te(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw PY(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}var DY=/ERROR: [0-9]+:([0-9]+):/g;function PY(e,t){let n=DY.exec(t);if(n==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}let s=+n[1],r=e.split(` `),a=r.length.toString().length+2,o=r.map((d,p)=>v.rightPad((p+1).toString(),a)+d),i=0;for(let d=0;de.createProgram(),"Unable to create WebGLProgram.")}function CI(e,t){if(Te(e,()=>e.linkProgram(t)),e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function Mm(e,t){if(Te(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function TI(e,t){let n=la(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Te(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Te(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function NI(e,t){let n=la(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Te(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),Te(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function FY(){return Y().getNumber("WEBGL_VERSION")===2?1:4}function EI(e){return la(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function RI(e,t){let n=Y().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let s=`[${e}x${t}]`;throw new Error("Requested texture size "+s+" is invalid.")}if(e>n||t>n){let s=`[${e}x${t}]`,r=`[${n}x${n}]`;throw new Error("Requested texture size "+s+" greater than WebGL maximum on this browser / GPU "+r+".")}}function $I(e){return la(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function ux(e,t,n,s,r,a,o){let i=e.getAttribLocation(t,n);return i===-1?!1:(Te(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s)),Te(e,()=>e.vertexAttribPointer(i,r,e.FLOAT,!1,a,o)),Te(e,()=>e.enableVertexAttribArray(i)),!0)}function _I(e,t,n){MI(e,n),Te(e,()=>e.activeTexture(e.TEXTURE0+n)),Te(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function OY(e,t){MI(e,t),Te(e,()=>e.activeTexture(e.TEXTURE0+t)),Te(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function DI(e,t,n){return la(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function PI(e,t,n){return e.getUniformLocation(t,n)}function FI(e,t,n,s){Te(e,()=>_I(e,t,s)),Te(e,()=>e.uniform1i(n,s))}function MY(e){Te(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Te(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),Te(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function zm(e,t,n){Te(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),Te(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function cx(e,t){Te(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),Te(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Ap(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+OI(e,t))}function OI(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function la(e,t,n){let s=Te(e,()=>t());if(s==null)throw new Error(n);return s}function MI(e,t){let n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,s=t+e.TEXTURE0;if(sn){let r=`[gl.TEXTURE0, gl.TEXTURE${n}]`;throw new Error(`textureUnit must be in ${r}.`)}}function El(e,t=2){return v.sizeFromShape(e.slice(0,e.length-t))}function Rl(e){if(e.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function Lm(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[El(e),...Rl(e)]),t}function zI(e,t=!1){let n=Y().getNumber("WEBGL_MAX_TEXTURE_SIZE");t&&(n=n*2,e=e.map((r,a)=>a>=e.length-2?v.nearestLargerEven(e[a]):e[a]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=v.squeezeShape(e).newShape);let s=v.sizeFromShape(e);if(e.length<=1&&s<=n)return[1,s];if(e.length===2&&e[0]<=n&&e[1]<=n)return e;if(e.length===3&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=n&&e[3]<=n)return[e[0]*e[1]*e[2],e[3]];if(e.length===4&&e[0]<=n&&e[1]*e[2]*e[3]<=n)return[e[0],e[1]*e[2]*e[3]];if(t){let r=El(e),a=2,o=2;return e.length&&([a,o]=Rl(e)),s=r*(a/2)*(o/2),v.sizeToSquarishShape(s).map(i=>i*2)}return v.sizeToSquarishShape(s)}function Bm(e){return e%2==0}function yp(e,t){if(e=e.slice(-2),t=t.slice(-2),v.arraysEqual(e,t)||!e.length||!t.length||e[0]===0||e[1]===0||t[0]===0||t[1]===0)return!0;if(e.length!==t.length){let n=e.slice(-1)[0],s=t.slice(-1)[0];if(n===s||Bm(n)&&Bm(s)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&Bm(e[0])&&Bm(t[0])}var Wm,Vm;function LI(e){if(Wm==null){let t=Gr(e);Wm=t.getParameter(t.MAX_TEXTURE_SIZE)}return Wm}function zY(){Wm=null}function LY(){Vm=null}function BI(e){if(Vm==null){let t=Gr(e);Vm=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Vm)}function WI(e){if(e===0)return 0;let t,n=Gr(e);return Ls(n,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:Ls(n,"EXT_disjoint_timer_query")?t=1:t=0,t}function Ls(e,t){return e.getExtension(t)!=null}function dx(e){try{if(Gr(e)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function VI(e){if(e===0)return!1;let t=Gr(e);if(e===1){if(!Ls(t,"OES_texture_float"))return!1}else if(!Ls(t,"EXT_color_buffer_float"))return!1;return px(t)}function UI(e){if(e===0)return!1;let t=Gr(e);if(e===1){if(!Ls(t,"OES_texture_float")||!Ls(t,"WEBGL_color_buffer_float"))return!1}else{if(Ls(t,"EXT_color_buffer_float"))return px(t);let s="EXT_color_buffer_half_float";if(Ls(t,s)){let r=t.getExtension(s);return BY(t,r)}return!1}return px(t)}function px(e){let t=lx(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);let s=1,r=1;e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,s,r,0,t.textureFormatFloat,t.textureTypeFloat,null);let a=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,a),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);let o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(a),o}function BY(e,t){let n=lx(e,t),s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s);let r=1,a=1;e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,r,a,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);let o=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,o),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);let i=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(s),e.deleteFramebuffer(o),i}function GI(e){return e!==2?!1:Gr(e).fenceSync!=null}function lc(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&v.assert(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}var _e=Y();_e.registerFlag("HAS_WEBGL",()=>_e.getNumber("WEBGL_VERSION")>0);_e.registerFlag("WEBGL_VERSION",()=>dx(2)?2:dx(1)?1:0);_e.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);_e.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>_e.get("WEBGL_VERSION")===2);_e.registerFlag("WEBGL_CPU_FORWARD",()=>!0);_e.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);_e.registerFlag("WEBGL_PACK",()=>_e.getBool("HAS_WEBGL"));_e.registerFlag("WEBGL_PACK_NORMALIZATION",()=>_e.getBool("WEBGL_PACK"));_e.registerFlag("WEBGL_PACK_CLIP",()=>_e.getBool("WEBGL_PACK"));_e.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>_e.getBool("WEBGL_PACK"));_e.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>_e.getBool("WEBGL_PACK"));_e.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>_e.getBool("WEBGL_PACK"));_e.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>_e.getBool("WEBGL_PACK"));_e.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>_e.getBool("WEBGL_PACK"));_e.registerFlag("WEBGL_PACK_REDUCE",()=>_e.getBool("WEBGL_PACK"));_e.registerFlag("WEBGL_LAZILY_UNPACK",()=>_e.getBool("WEBGL_PACK"));_e.registerFlag("WEBGL_CONV_IM2COL",()=>_e.getBool("WEBGL_PACK"));_e.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>LI(_e.getNumber("WEBGL_VERSION")));_e.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>BI(_e.getNumber("WEBGL_VERSION")));_e.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let e=_e.getNumber("WEBGL_VERSION");return e===0?0:WI(e)});_e.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>_e.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!Fu.isMobile());_e.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>VI(_e.getNumber("WEBGL_VERSION")));_e.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>_e.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:_e.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));_e.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>UI(_e.getNumber("WEBGL_VERSION")));_e.registerFlag("WEBGL_FENCE_API_ENABLED",()=>GI(_e.getNumber("WEBGL_VERSION")));_e.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>_e.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);_e.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,e=>{if(e<0&&e!==-1)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)});_e.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>Fu.isMobile()?1:-1,e=>{if(e<0&&e!==-1)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`)});_e.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);_e.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1);_e.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5);_e.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128);function Hn(){let e,t,n,s,r,a,o,i,l,c;return Y().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",n="out",s="in",r="texture",a="outputColor",o="out vec4 outputColor;",i=` bool isnan_custom(float val) { return (val > 0.0 || val < 0.0) ? false : val != 0.0; } bvec4 isnan_custom(vec4 val) { return bvec4(isnan_custom(val.x), isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w)); } #define isnan(value) isnan_custom(value) `,l="",c=` #define round(value) newRound(value) int newRound(float value) { return int(floor(value + 0.5)); } ivec4 newRound(vec4 value) { return ivec4(floor(value + vec4(0.5))); } `):(e="",t="attribute",n="varying",s="varying",r="texture2D",a="gl_FragColor",o="",i=` #define isnan(value) isnan_custom(value) bool isnan_custom(float val) { return (val > 0. || val < 1. || val == 0.) ? false : true; } bvec4 isnan_custom(vec4 val) { return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w)); } `,l=` uniform float INFINITY; bool isinf(float val) { return abs(val) == INFINITY; } bvec4 isinf(vec4 val) { return equal(abs(val), vec4(INFINITY)); } `,c=` int round(float value) { return int(floor(value + 0.5)); } ivec4 round(vec4 value) { return ivec4(floor(value + vec4(0.5))); } `),{version:e,attribute:t,varyingVs:n,varyingFs:s,texture2D:r,output:a,defineOutput:o,defineSpecialNaN:i,defineSpecialInf:l,defineRound:c}}function $l(e,t,n="index"){let s=v.computeStrides(t);return s.map((r,a)=>{let o=`int ${e[a]} = ${n} / ${r}`,i=a===s.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * ${r}`:`index -= ${e[a]} * ${r}`;return`${o}; ${i};`}).join("")}function Um(e,t,n="index"){let s=v.computeStrides(t);return s.map((r,a)=>{let o=`int ${e[a]} = ${n} / outShapeStrides[${a}]`,i=a===s.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * outShapeStrides[${a}]`:`index -= ${e[a]} * outShapeStrides[${a}]`;return`${o}; ${i};`}).join("")}function WY(e,t){let n=e.length,s=e.map(a=>`${t}[${a}]`),r=new Array(n-1);r[n-2]=s[n-1];for(let a=n-3;a>=0;--a)r[a]=`(${r[a+1]} * ${s[a+1]})`;return r}function VY(e,t,n="index"){let s=e.map((a,o)=>o),r=WY(s,t);return r.map((a,o)=>{let i=`int ${e[o]} = ${n} / ${r[o]}`,l=o===r.length-1?`int ${e[o+1]} = ${n} - ${e[o]} * ${r[o]}`:`index -= ${e[o]} * ${r[o]}`;return`${i}; ${l};`}).join("")}function hx(e){let t=v.computeStrides(e).map(n=>n.toString());return` int getFlatIndex(ivec3 coords) { return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z; } `}function fx(){return` int getFlatIndex(ivec3 coords) { return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z; } `}var HI=` const float FLOAT_MAX = 1.70141184e38; const float FLOAT_MIN = 1.17549435e-38; lowp vec4 encode_float(highp float v) { if (isnan(v)) { return vec4(255, 255, 255, 255); } highp float av = abs(v); if(av < FLOAT_MIN) { return vec4(0.0, 0.0, 0.0, 0.0); } else if(v > FLOAT_MAX) { return vec4(0.0, 0.0, 128.0, 127.0) / 255.0; } else if(v < -FLOAT_MAX) { return vec4(0.0, 0.0, 128.0, 255.0) / 255.0; } highp vec4 c = vec4(0,0,0,0); highp float e = floor(log2(av)); highp float m = exp2(fract(log2(av))) - 1.0; c[2] = floor(128.0 * m); m -= c[2] / 128.0; c[1] = floor(32768.0 * m); m -= c[1] / 32768.0; c[0] = floor(8388608.0 * m); highp float ebias = e + 127.0; c[3] = floor(ebias / 2.0); ebias -= c[3] * 2.0; c[2] += floor(ebias) * 128.0; c[3] += 128.0 * step(0.0, -v); return c / 255.0; } `,{getBroadcastDims:jI}=E;function UY(e,t,n){let s=[];if(e.forEach(h=>{let f=v.sizeFromShape(h.shapeInfo.logicalShape);if(h.shapeInfo.isUniform?s.push(`uniform float ${h.name}${f>1?`[${f}]`:""};`):(s.push(`uniform sampler2D ${h.name};`),s.push(`uniform int offset${h.name};`)),n.enableShapeUniforms){let{uniformShape:m}=mx(n.packedInputs,h.shapeInfo.logicalShape,h.shapeInfo.texShape);switch(m.length){case 1:s.push(`uniform int ${h.name}Shape;`);break;case 2:s.push(`uniform ivec2 ${h.name}Shape;`);break;case 3:s.push(`uniform ivec3 ${h.name}Shape;`);break;case 4:s.push(`uniform ivec4 ${h.name}Shape;`);break;default:break}s.push(`uniform ivec2 ${h.name}TexShape;`)}}),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:s.push("uniform int outShape;");break;case 2:s.push("uniform ivec2 outShape;"),s.push("uniform int outShapeStrides;");break;case 3:s.push("uniform ivec3 outShape;"),s.push("uniform ivec2 outShapeStrides;");break;case 4:s.push("uniform ivec4 outShape;"),s.push("uniform ivec3 outShapeStrides;");break;default:break}s.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach(h=>{s.push(`uniform ${h.type} ${h.name}${h.arrayIndex?`[${h.arrayIndex}]`:""};`)});let r=s.join(` `),a=e.map(h=>GY(h,t,n.packedInputs,n.enableShapeUniforms)).join(` `),o=t.texShape,i=Hn(),l=qY(i),c,u,d=ZY(i);return t.isPacked?(c=HY(t.logicalShape,o,n.enableShapeUniforms),u=KY(i)):(c=jY(t.logicalShape,o,n.enableShapeUniforms),u=XY(i)),n.packedInputs&&(d+=eJ),[d,l,u,r,c,a,n.userCode].join(` `)}function uc(e,t=!1){let n=e.shapeInfo.logicalShape;switch(n.length){case 0:return pJ(e,t);case 1:return fJ(e,t);case 2:return gJ(e,t);case 3:return yJ(e,t);case 4:return bJ(e,t);case 5:return vJ(e);case 6:return wJ(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function qI(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return dJ(e);case 1:return hJ(e,t);case 2:return mJ(e,t);case 3:return AJ(e,t);default:return xJ(e,t)}}function GY(e,t,n=!1,s){let r="";n?r+=qI(e,s):r+=uc(e,s);let a=e.shapeInfo.logicalShape,o=t.logicalShape;return a.length<=o.length&&(n?r+=kJ(e,t):r+=SJ(e,t)),r}function HY(e,t,n){switch(e.length){case 0:return XI();case 1:return tJ(e,t,n);case 2:return uJ(e,t,n);case 3:return sJ(e,t,n);default:return aJ(e,t,n)}}function jY(e,t,n){switch(e.length){case 0:return XI();case 1:return nJ(e,t,n);case 2:return cJ(e,t,n);case 3:return rJ(e,t,n);case 4:return oJ(e,t,n);case 5:return iJ(e,t);case 6:return lJ(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function qY(e){return` float sampleTexture(sampler2D textureSampler, vec2 uv) { return ${e.texture2D}(textureSampler, uv).r; } `}function XY(e){return` void setOutput(float val) { ${e.output} = vec4(val, 0, 0, 0); } `}function KY(e){return` void setOutput(vec4 val) { ${e.output} = val; } `}function ZY(e){return`${e.version} precision highp float; precision highp int; precision highp sampler2D; ${e.varyingFs} vec2 resultUV; ${e.defineOutput} const vec2 halfCR = vec2(0.5, 0.5); struct ivec5 { int x; int y; int z; int w; int u; }; struct ivec6 { int x; int y; int z; int w; int u; int v; }; uniform float NAN; ${e.defineSpecialNaN} ${e.defineSpecialInf} ${e.defineRound} int imod(int x, int y) { return x - y * (x / y); } int idiv(int a, int b, float sign) { int res = a / b; int mod = imod(a, b); if (sign < 0. && mod != 0) { res -= 1; } return res; } //Based on the work of Dave Hoskins //https://www.shadertoy.com/view/4djSRW #define HASHSCALE1 443.8975 float random(float seed){ vec2 p = resultUV * seed; vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1); p3 += dot(p3, p3.yzx + 19.19); return fract((p3.x + p3.y) * p3.z); } ${YY} ${JY} ${QY} `}var YY=` vec2 uvFromFlat(int texNumR, int texNumC, int index) { int texR = index / texNumC; int texC = index - texR * texNumC; return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); } vec2 packedUVfrom1D(int texNumR, int texNumC, int index) { int texelIndex = index / 2; int texR = texelIndex / texNumC; int texC = texelIndex - texR * texNumC; return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); } `,JY=` vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR, int texNumC, int row, int col) { int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2); int texR = texelIndex / texNumC; int texC = texelIndex - texR * texNumC; return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); } `,QY=` vec2 packedUVfrom3D(int texNumR, int texNumC, int texelsInBatch, int texelsInLogicalRow, int b, int row, int col) { int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2); int texR = index / texNumC; int texC = index - texR * texNumC; return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); } `,eJ=` float getChannel(vec4 frag, vec2 innerDims) { vec2 modCoord = mod(innerDims, 2.); return modCoord.x == 0. ? (modCoord.y == 0. ? frag.r : frag.g) : (modCoord.y == 0. ? frag.b : frag.a); } float getChannel(vec4 frag, int dim) { float modCoord = mod(float(dim), 2.); return modCoord == 0. ? frag.r : frag.g; } `;function XI(){return` int getOutputCoords() { return 0; } `}function tJ(e,t,n){let s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return s[0]===1?n?` int getOutputCoords() { return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0)); } `:` int getOutputCoords() { return 2 * int(resultUV.x * ${s[1]}.0); } `:s[1]===1?n?` int getOutputCoords() { return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0)); } `:` int getOutputCoords() { return 2 * int(resultUV.y * ${s[0]}.0); } `:n?` int getOutputCoords() { ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0)); ivec2 resTexRC = ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1])); return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y); } `:` int getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(${s[0]}, ${s[1]})); return 2 * (resTexRC.x * ${s[1]} + resTexRC.y); } `}function nJ(e,t,n){return t[0]===1?n?` int getOutputCoords() { return int(resultUV.x * float(outTexShape[1])); } `:` int getOutputCoords() { return int(resultUV.x * ${t[1]}.0); } `:t[1]===1?n?` int getOutputCoords() { return int(resultUV.y * float(outTexShape[0])); } `:` int getOutputCoords() { return int(resultUV.y * ${t[0]}.0); } `:n?` int getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1])); return resTexRC.x * outTexShape[1] + resTexRC.y; } `:` int getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]})); return resTexRC.x * ${t[1]} + resTexRC.y; } `}function sJ(e,t,n){if(n)return` ivec3 getOutputCoords() { ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0)); int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0)); int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0)); ivec2 resTexRC = ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1])); int index = resTexRC.x * packedTexShape[1] + resTexRC.y; int b = index / texelsInBatch; index -= b * texelsInBatch; int r = 2 * (index / texelsInLogicalRow); int c = imod(index, texelsInLogicalRow) * 2; return ivec3(b, r, c); } `;let s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[2]/2),a=r*Math.ceil(e[1]/2);return` ivec3 getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(${s[0]}, ${s[1]})); int index = resTexRC.x * ${s[1]} + resTexRC.y; int b = index / ${a}; index -= b * ${a}; int r = 2 * (index / ${r}); int c = imod(index, ${r}) * 2; return ivec3(b, r, c); } `}function rJ(e,t,n){if(n)return` ivec3 getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1])); int index = resTexRC.x * outTexShape[1] + resTexRC.y; ${Um(["r","c","d"],e)} return ivec3(r, c, d); } `;let s=$l(["r","c","d"],e);return` ivec3 getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]})); int index = resTexRC.x * ${t[1]} + resTexRC.y; ${s} return ivec3(r, c, d); } `}function aJ(e,t,n){if(n)return` ivec4 getOutputCoords() { ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0)); ivec2 resTexRC = ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1])); int index = resTexRC.x * packedTexShape[1] + resTexRC.y; int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0)); int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0)); int texelsInBatchN = texelsInBatch * outShape[1]; int b2 = index / texelsInBatchN; index -= b2 * texelsInBatchN; int b = index / texelsInBatch; index -= b * texelsInBatch; int r = 2 * (index / texelsInLogicalRow); int c = imod(index, texelsInLogicalRow) * 2; return ivec4(b2, b, r, c); } `;let s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[e.length-1]/2),a=r*Math.ceil(e[e.length-2]/2),o=a,i="",l="b, r, c";for(let c=2;c=1?u="coords = 0;":u=i.map(x=>`coords.${d[x+c]} = 0;`).join(` `);let p="";o<2&&a>0?p="coords":p=e.shapeInfo.logicalShape.map((x,y)=>`coords.${d[y+c]}`).join(", ");let h="return outputValue;",m=v.sizeFromShape(e.shapeInfo.logicalShape)===1,A=v.sizeFromShape(t.logicalShape)===1;if(a===1&&!m&&!A)h=` return vec4(outputValue.xy, outputValue.xy); `;else if(m&&!A)o===1?h=` return vec4(outputValue.x, outputValue.x, 0., 0.); `:h=` return vec4(outputValue.x); `;else if(i.length){let x=a-2,y=a-1;i.indexOf(x)>-1&&i.indexOf(y)>-1?h="return vec4(outputValue.x);":i.indexOf(x)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(y)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return` vec4 ${r}() { ${l} coords = getOutputCoords(); ${u} vec4 outputValue = get${s}(${p}); ${h} } `}function SJ(e,t){let n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),r="get"+s+"AtOutCoords",a=t.texShape,o=e.shapeInfo.texShape,i=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&i===l&&e.shapeInfo.flatOffset==null&&v.arraysEqual(o,a))return` float ${r}() { return sampleTexture(${n}, resultUV); } `;let c=xt(l),u=jI(e.shapeInfo.logicalShape,t.logicalShape),d=l-i,p,h=["x","y","z","w","u","v"];i===0?p="":l<2&&u.length>=1?p="coords = 0;":p=u.map(m=>`coords.${h[m+d]} = 0;`).join(` `);let f="";return l<2&&i>0?f="coords":f=e.shapeInfo.logicalShape.map((m,g)=>`coords.${h[g+d]}`).join(", "),` float ${r}() { ${c} coords = getOutputCoords(); ${p} return get${s}(${f}); } `}function xt(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function mx(e,t,n){let{newShape:s,keptDims:r}=v.squeezeShape(t),a=t.length,o=e&&a===3&&t[0]===1,i=o?t.slice(1):s,l=!e&&a>1&&!v.arraysEqual(t,n)&&s.lengthe[n]).join(", ")}function IJ(e,t,n,s){let r=n.map((b,w)=>{let k={logicalShape:b.shape,texShape:b.isUniform?null:b.texData.texShape,isUniform:b.isUniform,isPacked:b.isUniform?!1:b.texData.isPacked,flatOffset:null};return b.texData!=null&&b.texData.slice!=null&&b.texData.slice.flatOffset>0&&(k.flatOffset=b.texData.slice.flatOffset),{name:t.variableNames[w],shapeInfo:k}}),a=r.map(b=>b.shapeInfo),o={logicalShape:s.shape,texShape:s.texData.texShape,isUniform:!1,isPacked:s.texData.isPacked,flatOffset:null},i=UY(r,o,t),l=SI(e.gl,i),c=e.createProgram(l),u=null,d=e.getUniformLocation(c,"NAN",!1);Y().getNumber("WEBGL_VERSION")===1&&(u=e.getUniformLocation(c,"INFINITY",!1));let p=!1,h={},f={},m={};for(let b=0;b{y[w]=e.getUniformLocation(c,b.name,p)}),{program:t,fragmentShader:l,source:i,webGLProgram:c,uniformLocations:h,customUniformLocations:y,inShapeInfos:a,outShapeInfo:o,infLoc:u,nanLoc:d,inShapesLocations:f,inTexShapesLocations:m,outShapeLocation:g,outShapeStridesLocation:x,outTexShapeLocation:A}}function KI(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach((n,s)=>{let r=n.logicalShape,a=t[s],o=a.shape;if(!v.arraysEqual(r,o))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${r} and ${o} must match`);if(n.isUniform&&a.isUniform)return;let i=n.texShape,l=a.isUniform?null:a.texData.texShape;if(!v.arraysEqual(i,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${l} must match`)})}function CJ(e,t,n,s,r){t.program.enableShapeUniforms||(KI(t.inShapeInfos,n),KI([t.outShapeInfo],[s]));let a=s.texData.texture,o=s.texData.texShape;s.texData.isPacked?e.setOutputPackedMatrixTexture(a,o[0],o[1]):e.setOutputMatrixTexture(a,o[0],o[1]),e.setProgram(t.webGLProgram),Y().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach((l,c)=>{let u=t.program.variableNames[c],d=t.uniformLocations[u],p=t.uniformLocations[`offset${u}`],h=t.inShapesLocations[`${u}Shape`],f=t.inTexShapesLocations[`${u}TexShape`];if(h){let{uniformShape:m}=mx(t.program.packedInputs,l.shape,l.texData.texShape);switch(m.length){case 1:e.gl.uniform1iv(h,new Int32Array(m));break;case 2:e.gl.uniform2iv(h,new Int32Array(m));break;case 3:e.gl.uniform3iv(h,new Int32Array(m));break;case 4:e.gl.uniform4iv(h,new Int32Array(m));break;default:break}}if(f&&e.gl.uniform2i(f,l.texData.texShape[0],l.texData.texShape[1]),d!=null){if(l.isUniform){if(v.sizeFromShape(l.shape)<2)e.gl.uniform1f(d,l.uniformValues[0]);else{let m=l.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),e.gl.uniform1fv(d,m)}return}l.texData.slice!=null&&p!=null&&e.gl.uniform1i(p,l.texData.slice.flatOffset),e.setInputMatrixTexture(l.texData.texture,d,c)}});let i=t.outShapeLocation;if(i)switch(s.shape.length){case 1:e.gl.uniform1iv(i,new Int32Array(s.shape));break;case 2:e.gl.uniform2iv(i,new Int32Array(s.shape));break;case 3:e.gl.uniform3iv(i,new Int32Array(s.shape));break;case 4:e.gl.uniform4iv(i,new Int32Array(s.shape));break;default:break}if(t.outShapeStridesLocation){let l=v.computeStrides(s.shape);switch(s.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(l));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(l));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(l));break;default:break}}t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,s.texData.texShape[0],s.texData.texShape[1]),t.program.customUniforms&&r&&t.program.customUniforms.forEach((l,c)=>{let u=t.customUniformLocations[c],d=r[c];if(l.type==="float")e.gl.uniform1fv(u,d);else if(l.type==="vec2")e.gl.uniform2fv(u,d);else if(l.type==="vec3")e.gl.uniform3fv(u,d);else if(l.type==="vec4")e.gl.uniform4fv(u,d);else if(l.type==="int")e.gl.uniform1iv(u,d);else if(l.type==="ivec2")e.gl.uniform2iv(u,d);else if(l.type==="ivec3")e.gl.uniform3iv(u,d);else if(l.type==="ivec4")e.gl.uniform4iv(u,d);else throw Error(`uniform type ${l.type} is not supported yet.`)}),e.executeProgram()}function TJ(e,t,n){let s="";t.concat(n).forEach(o=>{let i=o.texData!=null&&o.texData.slice!=null&&o.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!o.isUniform){let l=o.texData.texShape,{useSqueezeShape:c,uniformShape:u,keptDims:d}=mx(e.packedInputs,o.shape,l),p="",h="",f="";if(u.length===1&&e.packedInputs){let w=[Math.ceil(l[0]/2),Math.ceil(l[1]/2)];p=`${w[0]>1}_${w[1]>1}`}else if(u.length===2&&!e.packedInputs)h=`${u[0]>1}_${u[1]>1}`;else if(u.length>2&&!e.packedInputs){let w=v.computeStrides(u);f=`${w[0]===l[1]}_${w[w.length-1]===l[1]}`}let m=o.shape.length,g=u.length===2&&v.arraysEqual(o.shape,l),A=v.sizeFromShape(o.shape)===1,x=E.getBroadcastDims(o.shape,n.shape),y=!e.packedInputs&&m===n.shape.length&&v.arraysEqual(l,n.texData.texShape),b=e.packedInputs||u.length>2?"":`${l[0]>1}_${l[1]>1}`;s+=`${m}_${y}_${c?d:""}_${u.length}_${A}_${x}_${g}_${p}_${h}_${f}_${b}_${i}`}else{let l=o.isUniform?"uniform":o.texData.texShape;s+=`${o.shape}_${l}_${i}`}});let r=e.userCode,a=e.constructor.name;return a+="_"+s+"_"+r+`${Y().getNumber("WEBGL_VERSION")}`,a}function Bs(e){return Y().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}var NJ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=fp.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Hn();this.outputShape=e,this.enableShapeUniforms=Bs(this.outputShape.length),this.userCode=` ivec3 outCoordsFromFlatIndex(int index) { ${this.enableShapeUniforms?Um(["r","c","d"],e):$l(["r","c","d"],e)} return ivec3(r, c, d); } void main() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1])); int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y); vec4 result = vec4(0.); for (int i=0; i<4; i++) { int flatIndex = index + i; ivec3 rc = outCoordsFromFlatIndex(flatIndex); result[i] = getA(rc.x, rc.y, rc.z); } ${t.output} = result; } `}},EJ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=fp.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Hn();this.outputShape=e,this.enableShapeUniforms=Bs(this.outputShape.length),this.userCode=` ivec3 outCoordsFromFlatIndex(int index) { ${this.enableShapeUniforms?Um(["r","c","d"],e):$l(["r","c","d"],e)} return ivec3(r, c, d); } void main() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1])); int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y); vec4 result = vec4(0.); for (int i=0; i<4; i++) { int flatIndex = index + i; ivec3 rc = outCoordsFromFlatIndex(flatIndex); result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z)); } ${t.output} = result; } `}},RJ=class{constructor(e){this.variableNames=["A"],this.outTexUsage=zs.DOWNLOAD;let t=Hn();this.outputShape=e,this.userCode=` ${HI} void main() { float x = getAAtOutCoords(); ${t.output} = encode_float(x); } `}},$J=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=zs.DOWNLOAD;let t=Hn();this.outputShape=e,this.userCode=` ${HI} void main() { ivec3 coords = getOutputCoords(); float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z)); ${t.output} = encode_float(x); } `}},_J=class{constructor(e,t=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Hn();this.outputShape=e,this.enableShapeUniforms=Bs(this.outputShape.length);let s="result";t&&(s="floor(result * 255. + 0.5)"),this.userCode=` ${this.enableShapeUniforms?fx():hx(e)} void main() { ivec3 coords = getOutputCoords(); int flatIndex = getFlatIndex(coords); int offset = imod(flatIndex, 4); flatIndex = idiv(flatIndex, 4, 1.); int r = flatIndex / texShape[1]; int c = imod(flatIndex, texShape[1]); vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]); vec4 values = ${n.texture2D}(A, uv); float result; if(offset == 0) { result = values[0]; } else if(offset == 1) { result = values[1]; } else if(offset == 2) { result = values[2]; } else { result = values[3]; } ${n.output} = vec4(${s}, 0., 0., 0.); } `}},DJ=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Hn();this.outputShape=e,this.enableShapeUniforms=Bs(this.outputShape.length);let s="",r="result";t&&(r="floor(result * 255. + 0.5)");for(let a=0;a<=1;a++)for(let o=0;o<=1;o++){let i=a*2+o;s+=` localCoords = coords; if(localCoords[2] + ${o} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) { localCoords[2] += ${o}; if (localCoords[1] + ${a} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) { localCoords[1] += ${a}; flatIndex = getFlatIndex(localCoords); offset = imod(flatIndex, 4); flatIndex = idiv(flatIndex, 4, 1.); int r = flatIndex / texShape[1]; int c = imod(flatIndex, texShape[1]); vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]); values = ${n.texture2D}(A, uv); if (offset == 0) { result[${i}] = values[0]; } else if (offset == 1) { result[${i}] = values[1]; } else if (offset == 2) { result[${i}] = values[2]; } else { result[${i}] = values[3]; } } } `}this.userCode=` ${this.enableShapeUniforms?fx():hx(e)} void main() { ivec3 coords = getOutputCoords(); vec4 result = vec4(0.); int flatIndex, r, c, offset; ivec3 localCoords; vec2 uv; vec4 values; ${s} ${n.output} = ${r}; } `}},ZI={};Oe(ZI,{bindVertexProgramAttributeStreams:()=>a4,createBufferFromOutputTexture:()=>l4,createFloat16MatrixTexture:()=>t4,createFloat16PackedMatrixTexture:()=>r4,createFloat32MatrixTexture:()=>e4,createIndexBuffer:()=>QI,createPackedMatrixTexture:()=>s4,createUnsignedBytesMatrixTexture:()=>n4,createVertexBuffer:()=>JI,createVertexShader:()=>YI,downloadByteEncodedFloatMatrixFromOutputTexture:()=>c4,downloadFloat32MatrixFromBuffer:()=>u4,downloadMatrixFromPackedOutputTexture:()=>p4,downloadPackedMatrixFromBuffer:()=>d4,getInternalFormatForFloat16MatrixTexture:()=>Ax,getInternalFormatForFloat16PackedMatrixTexture:()=>bx,getInternalFormatForFloat32MatrixTexture:()=>gx,getInternalFormatForPackedMatrixTexture:()=>xx,getInternalFormatForUnsignedBytesMatrixTexture:()=>yx,uploadDenseMatrixToTexture:()=>o4,uploadPixelDataToTexture:()=>i4});function YI(e){let t=Hn(),n=`${t.version} precision highp float; ${t.attribute} vec3 clipSpacePos; ${t.attribute} vec2 uv; ${t.varyingVs} vec2 resultUV; void main() { gl_Position = vec4(clipSpacePos, 1); resultUV = uv; }`;return kI(e,n)}function JI(e){let t=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return TI(e,t)}function QI(e){let t=new Uint16Array([0,1,2,2,1,3]);return NI(e,t)}function xp(e,t,n,s,r,a){RI(t,n);let o=EI(e),i=e.TEXTURE_2D;return Te(e,()=>e.bindTexture(i,o)),Te(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),Te(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),Te(e,()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST)),Te(e,()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST)),Te(e,()=>e.texImage2D(i,0,s,t,n,0,r,a,null)),Te(e,()=>e.bindTexture(e.TEXTURE_2D,null)),o}function gx(e){return e.internalFormatFloat}function e4(e,t,n,s){let[r,a]=mp(t,n);return xp(e,r,a,gx(s),s.textureFormatFloat,e.FLOAT)}function Ax(e){return e.internalFormatHalfFloat}function t4(e,t,n,s){let[r,a]=mp(t,n);return xp(e,r,a,Ax(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function yx(e){return e.downloadTextureFormat}function n4(e,t,n,s){let[r,a]=mp(t,n);return xp(e,r,a,yx(s),e.RGBA,e.UNSIGNED_BYTE)}function xx(e){return e.internalFormatPackedFloat}function s4(e,t,n,s){let[r,a]=ic(t,n);return xp(e,r,a,xx(s),e.RGBA,e.FLOAT)}function bx(e){return e.internalFormatPackedHalfFloat}function r4(e,t,n,s){let[r,a]=ic(t,n);return xp(e,r,a,bx(s),e.RGBA,s.textureTypeHalfFloat)}function a4(e,t,n){let s=0,r=3*4,a=3*4+2*4;return Te(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),ux(e,t,"clipSpacePos",n,3,a,s)&&ux(e,t,"uv",n,2,a,r)}function o4(e,t,n,s,r,a){Te(e,()=>e.bindTexture(e.TEXTURE_2D,t));let o,i,l;r instanceof Uint8Array?(o=new Uint8Array(n*s*4),i=e.UNSIGNED_BYTE,l=e.RGBA):(o=new Float32Array(n*s*4),i=e.FLOAT,l=a.internalFormatPackedFloat),o.set(r),Te(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,n,s,0,e.RGBA,i,o)),Te(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function i4(e,t,n){Te(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?Te(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):Te(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),Te(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function l4(e,t,n,s){let r=e.createBuffer();Te(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,r));let i=4*4*t*n;return Te(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,i,e.STREAM_READ)),Te(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),Te(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),r}function u4(e,t,n){let s=e,r=new Float32Array(n);return s.bindBuffer(s.PIXEL_PACK_BUFFER,t),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,r),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),r}function c4(e,t,n,s){let[r,a]=mp(t,n),o=4,i=new Uint8Array(NY(t*n,o));return Te(e,()=>e.readPixels(0,0,r,a,s.downloadTextureFormat,e.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function d4(e,t,n,s,r,a,o,i){let l=e,c=new Float32Array(EY(a,o));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,c),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),c}function p4(e,t,n){let s=new Float32Array(t*n*4);return Te(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,s)),s}var Gm=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=Y().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,Fm(t,e)):this.gl=Gr(t);let n="WEBGL_color_buffer_float",s="EXT_color_buffer_half_float";if(Y().getNumber("WEBGL_VERSION")===1){let r="OES_texture_float",a="OES_texture_half_float";if(this.textureFloatExtension=gp(this.gl,r),Ls(this.gl,a))this.textureHalfFloatExtension=gp(this.gl,a);else if(Y().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Ls(this.gl,s))this.colorBufferHalfFloatExtension=gp(this.gl,s);else if(Y().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Ls(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(Ls(this.gl,s))this.colorBufferHalfFloatExtension=this.gl.getExtension(s);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=JI(this.gl),this.indexBuffer=QI(this.gl),this.framebuffer=$I(this.gl),this.textureConfig=lx(this.gl,this.textureHalfFloatExtension)}get debug(){return Y().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");let e=this.gl;Te(e,()=>e.finish()),Te(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Te(e,()=>e.deleteFramebuffer(this.framebuffer)),Te(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),Te(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),Te(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),e4(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),t4(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),n4(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),i4(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,s){this.throwIfDisposed(),o4(this.gl,e,t,n,s,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),r4(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),s4(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(cx(this.gl,this.framebuffer),this.outputTexture=null),Te(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>c4(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,s,r,a){return d4(this.gl,e,t,n,s,r,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return u4(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);let s=l4(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),s}createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(Y().getBool("WEBGL_FENCE_API_ENABLED")){let s=e,r=s.fenceSync(s.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{let a=s.clientWaitSync(r,0,0);return a===s.ALREADY_SIGNALED||a===s.CONDITION_SATISFIED},t=r}else Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>p4(this.gl,t,n))}createProgram(e){this.throwIfDisposed();let t=this.gl;this.vertexShader==null&&(this.vertexShader=YI(t));let n=II(t);return Te(t,()=>t.attachShader(n,this.vertexShader)),Te(t,()=>t.attachShader(n,e)),CI(t,n),this.debug&&Mm(t,n),this.vertexAttrsAreBound||(this.setProgram(n),this.vertexAttrsAreBound=a4(t,this.program,this.vertexBuffer)),n}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&Te(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&Mm(this.gl,this.program),Te(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?DI(this.gl,e,t):PI(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),Te(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),FI(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();let[s,r]=ic(t,n);this.setOutputMatrixTextureDriver(e,s,r)}setOutputMatrixWriteRegion(e,t,n,s){this.setOutputMatrixWriteRegionDriver(n,e,s,t)}setOutputPackedMatrixWriteRegion(e,t,n,s){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&Mm(this.gl,this.program),Ap(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;this.debug&&this.debugValidate(),Te(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Te(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=gp(this.gl,Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let n=this.gl,s=this.getQueryTimerExtensionWebGL2(),r=n.createQuery();return n.beginQuery(s.TIME_ELAPSED_EXT,r),r}let e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let t=this.gl,n=this.getQueryTimerExtensionWebGL2();t.endQuery(n.TIME_ELAPSED_EXT);return}let e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await v.repeatedTry(()=>this.disposed||this.isQueryAvailable(e,Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){let n=this.gl;return n.getQueryParameter(e,n.QUERY_RESULT)/1e6}else{let n=this.getQueryTimerExtensionWebGL1();return n.getQueryObjectEXT(e,n.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){let n=this.gl,s=this.getQueryTimerExtensionWebGL2(),r=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(s.GPU_DISJOINT_EXT)),r&&!this.disjoint}else{let n=this.getQueryTimerExtensionWebGL1(),s=n.getQueryObjectEXT(e,n.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),s&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=PJ(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){let{resolveFn:n}=this.itemsToPoll[t];n()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),!(this.itemsToPoll.length>1)&&v.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),zm(this.gl,e,this.framebuffer),this.debug&&Ap(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(zm(this.gl,this.outputTexture,this.framebuffer),this.debug&&Ap(this.gl)):cx(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);let n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();let s=this.gl;zm(s,e,this.framebuffer),this.debug&&Ap(s),this.outputTexture=e,Te(s,()=>s.viewport(0,0,t,n)),Te(s,()=>s.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,s){this.throwIfDisposed(),Te(this.gl,()=>this.gl.scissor(e,t,n,s))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}};function PJ(e){let t=0;for(;t`${e}.${n}`)}function jn(e,t){return t===1?[e]:g4(e,t)}function xQ(e,t){if(e===1)return"rc";let n="";for(let s=0;s ${t[0]}`;let s="";for(let r=e-2;r= ${t[r]}`,r= ${t}; bool rEdge = rp1 >= ${n}; `}function SQ(e,t){let n=e.length,s=vQ(n,t);return n===1?`getA(rc), rc + 1 >= ${e[0]} ? 0. : getA(rc + 1), 0, 0`:`getA(${s[0]}), cEdge ? 0. : getA(${s[1]}), rEdge ? 0. : getA(${s[2]}), rEdge || cEdge ? 0. : getA(${s[3]})`}var A4=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=Bs(this.outputShape.length);let n="";for(let s=0;s<4;s++){let r="thisRC = rc;";s%2==1&&(r+="thisRC.z += 1;"),s>1&&(r+="thisRC.y += 1;"),n+=` ${r} ${s>0?"if(thisRC.y < rows && thisRC.z < cols){":""} int flatIndex = getFlatIndex(thisRC); ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex); vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z)); result[${s}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims); ${s>0?"}":""} `}this.userCode=` ${IQ(t,this.enableShapeUniforms)} ${this.enableShapeUniforms?fx():hx(e)} void main() { ivec3 rc = getOutputCoords(); vec4 result = vec4(0.); ivec3 thisRC; int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]}; int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]}; ${n} setOutput(result); } `}};function IQ(e,t){return` ivec3 inputCoordsFromReshapedOutCoords(int index) { ${t?VY(["r","c","d"],"inputShape"):$l(["r","c","d"],e)} return ivec3(r, c, d); } `}var CQ=class{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){let s=x4(t,n),r=b4(e,s,n);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);let a=y4(e,s,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[r].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();let i=this.freeTextures[r].shift();return this.usedTextures[r].push(i),i}let o;return s===Cn.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===Cn.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===Cn.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===Cn.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===Cn.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[r].push(o),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),o}releaseTexture(e,t,n,s){if(this.freeTextures==null)return;let r=x4(n,s),a=b4(t,r,s);a in this.freeTextures||(this.freeTextures[a]=[]);let o=y4(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,s),i=Y().get("WEBGL_DELETE_TEXTURE_THRESHOLD");i!==-1&&this._numBytesAllocated>i?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=o):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;let l=this.usedTextures[a],c=l.indexOf(e);if(c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(c,1),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);let t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function TQ(e,t){let n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;throw new Error(`Unknown internal format ${t}`)}function y4(e,t,n,s,r){let a=NQ(t,s),o;if(r){let[l,c]=ic(e[0],e[1]);o=l*c}else{let[l,c]=mp(e[0],e[1]);o=l*c}let i=TQ(n,a);return o*i}function NQ(e,t){switch(e){case Cn.PACKED_2X2_FLOAT32:return xx(t);case Cn.PACKED_2X2_FLOAT16:return bx(t);case Cn.UNPACKED_FLOAT32:return gx(t);case Cn.UNPACKED_FLOAT16:return Ax(t);case Cn.PACKED_4X1_UNSIGNED_BYTE:return yx(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function EQ(e){return Y().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Cn.PACKED_2X2_FLOAT32:Cn.UNPACKED_FLOAT32:e?Cn.PACKED_2X2_FLOAT16:Cn.UNPACKED_FLOAT16}function x4(e,t){if(e===zs.UPLOAD)return Cn.PACKED_2X2_FLOAT32;if(e===zs.RENDER||e==null)return EQ(t);if(e===zs.DOWNLOAD||e===zs.PIXELS)return Cn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function b4(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}var jo=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=Bs(this.outputShape.length),this.userCode=` float unaryOperation(float x) { ${t} } void main() { float x = getAAtOutCoords(); float y = unaryOperation(x); setOutput(y); } `}},kr="if (isnan(x)) return x;",RQ="return x;",v4="return abs(x);",$Q="return (x >= 0.0) ? x : (exp(x) - 1.0);",_Q=kr+` return (x < 0.0) ? 0.0 : x; `,DQ=kr+` return (x < 0.0) ? 0.0 : min(6.0, x); `,Hm="return x;",PQ="return 1.0 / (1.0 + exp(-1.0 * x));",FQ="return x;",OQ=` vec4 result; result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0); result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0); result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0); result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0); return result; `,MQ=` vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0))); bvec4 isNaN = isnan(x); result.r = isNaN.r ? x.r : result.r; result.g = isNaN.g ? x.g : result.g; result.b = isNaN.b ? x.b : result.b; result.a = isNaN.a ? x.a : result.a; return result; `,zQ=` vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0))); bvec4 isNaN = isnan(x); result.r = isNaN.r ? x.r : result.r; result.g = isNaN.g ? x.g : result.g; result.b = isNaN.b ? x.b : result.b; result.a = isNaN.a ? x.a : result.a; return result; `,LQ="return 1.0 / (1.0 + exp(-1.0 * x));",hc=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=Bs(this.outputShape.length),this.userCode=` vec4 unaryOperation(vec4 x) { ${t} } void main() { vec4 x = getAAtOutCoords(); vec4 y = unaryOperation(x); setOutput(y); } `}},BQ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;let t=e.length,n=jn("rc",t),s=xt(t),r=xQ(t,n),a=n.slice(-2),o=t<=1?"rc":`vec2(${a.join(",")})`;this.userCode=` void main() { ${s} rc = getOutputCoords(); vec4 packedInput = getA(${r}); setOutput(getChannel(packedInput, ${o})); } `}},WQ=Qs.whereImpl,VQ=1e-7,UQ=1e-4,jm={};function GQ(e){return e in jm||(jm[e]={}),jm[e]}var HQ=Y().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),jQ=600;function qQ(){return Y().global.screen==null?1024:Y().global.screen.height*Y().global.screen.width*window.devicePixelRatio*jQ/1024/1024}var w4=class extends ru{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!Y().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){let t=Gr(Y().getNumber("WEBGL_VERSION"));this.binaryCache=GQ(Y().getNumber("WEBGL_VERSION")),this.gpgpu=new Gm(t),this.canvas=t.canvas,this.gpgpuCreatedLocally=!0}else this.gpgpu=e,this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=e.gl.canvas;this.textureManager=new CQ(this.gpgpu),this.numMBBeforeWarning=qQ(),this.texData=new sd(this,as())}nextDataId(){return w4.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}write(e,t,n){if((Y().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||Y().getBool("DEBUG"))&&this.checkNumericalProblems(e),n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let s={id:this.nextDataId()};return this.texData.set(s,{shape:t,dtype:n,values:e,usage:zs.UPLOAD,refCount:1}),s}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,n,s,r){if(Y().getBool("DEBUG")&&this.checkNumericalProblems(t),s==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:s,values:t,usage:zs.UPLOAD,refCount:r})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){let t=this.texData.get(e),{values:n,dtype:s,complexTensorInfos:r,slice:a,shape:o,isPacked:i}=t;if(a!=null){let d;i?d=new hc(o,Hm):d=new jo(o,Hm);let p=this.runWebGLProgram(d,[{dataId:e,shape:o,dtype:s}],s),h=this.readSync(p.dataId);return this.disposeIntermediateTensorInfo(p),h}if(n!=null)return this.convertAndCacheOnCPU(e);if(s==="string")return n;let l=this.activeTimers!=null,c;l&&(c=v.now());let u;if(s==="complex64"){let d=this.readSync(r.real.dataId),p=this.readSync(r.imag.dataId);u=E.mergeRealAndImagArrays(d,p)}else u=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=v.now()-c),this.convertAndCacheOnCPU(e,u)}async read(e){if(this.pendingRead.has(e)){let h=this.pendingRead.get(e);return new Promise(f=>h.push(f))}let t=this.texData.get(e),{values:n,shape:s,slice:r,dtype:a,complexTensorInfos:o,isPacked:i}=t;if(r!=null){let h;i?h=new hc(s,Hm):h=new jo(s,Hm);let f=this.runWebGLProgram(h,[{dataId:e,shape:s,dtype:a}],a),m=this.read(f.dataId);return this.disposeIntermediateTensorInfo(f),m}if(n!=null)return this.convertAndCacheOnCPU(e);if(Y().getBool("DEBUG")&&!Y().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&Y().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l=null,c;if(a!=="complex64"&&Y().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(e);let h=this.texData.get(c.dataId);l=this.gpgpu.createBufferFromTexture(h.texture,...Om(s))}this.pendingRead.set(e,[]),a!=="complex64"&&await this.gpgpu.createAndWaitForFence();let u;if(a==="complex64"){let h=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]),f=h[0],m=h[1];u=E.mergeRealAndImagArrays(f,m)}else if(l==null)u=this.getValuesFromTexture(e);else{let h=v.sizeFromShape(s);u=this.gpgpu.downloadFloat32MatrixFromBuffer(l,h)}if(c!=null&&this.disposeIntermediateTensorInfo(c),l!=null){let h=this.gpgpu.gl;Te(h,()=>h.deleteBuffer(l))}let d=this.convertAndCacheOnCPU(e,u),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach(h=>h(d)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&as().removeDataId(e,this),this.pendingDeletes--),d}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(s=>v.decodeString(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return ze(e.shape,e.dtype,n)}checkNumericalProblems(e){if(e!=null)for(let t=0;t0}async time(e){let t=this.activeTimers,n=[],s=!1;this.programTimersStack==null?(this.programTimersStack=n,s=!0):this.activeTimers.push(n),this.activeTimers=n,e();let r=v.flatten(this.activeTimers.map(i=>i.query)).filter(i=>i!=null),a=v.flatten(this.activeTimers.map(i=>i.name)).filter(i=>i!=null);this.activeTimers=t,s&&(this.programTimersStack=null);let o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};if(Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let i=await Promise.all(r);o.kernelMs=v.sum(i),o.getExtraProfileInfo=()=>i.map((l,c)=>({name:a[c],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", ")}else o.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,o}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:v.now(),endMs:null}}endTimer(e){return Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=v.now(),e)}async getQueryTime(e){if(Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);let t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);let{complexTensorInfos:n}=this.texData.get(e);return n!=null&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){let{texture:t,dtype:n,texShape:s,usage:r,isPacked:a,slice:o}=this.texData.get(e),i=o&&o.origDataId||e,l=this.dataRefCount.get(i);l>1?this.dataRefCount.set(i,l-1):(this.dataRefCount.delete(i),t!=null&&(this.numBytesInGPU-=this.computeBytes(s,n),this.textureManager.releaseTexture(t,s,r,a)));let c=this.texData.get(e);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=HQ){return Y().getBool("WEBGL_CPU_FORWARD")&&e.every(n=>this.texData.get(n.dataId).texture==null&&v.sizeFromShape(n.shape)0&&v.isString(n[0])){let r=n.map(a=>v.encodeString(a));s=this.write(r,e,t)}else s=this.write(n,e,t);return this.texData.get(s).usage=null,{dataId:s,shape:e,dtype:t}}makeOutput(e,t,n){let{dataId:s}=this.makeTensorInfo(e,t,n);return as().makeTensorFromDataId(s,e,t,this)}unpackTensor(e){let t=new BQ(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new bQ(e.shape),n=!0;return this.runWebGLProgram(t,[e],e.dtype,null,n)}packedReshape(e,t){let n=[El(e.shape),...Rl(e.shape)],s={dtype:e.dtype,shape:n,dataId:e.dataId},r=[El(t),...Rl(t)],a=new A4(r,n),o=!0,i=[n],l=this.runWebGLProgram(a,[s],e.dtype,i,o);return{dataId:l.dataId,shape:t,dtype:l.dtype}}decode(e){let t=this.texData.get(e),{isPacked:n,shape:s,dtype:r}=t,a=Lm(s),o,i=Om(a);n?o=new EJ(a):o=new NJ(a);let l=!0,c=[i],u=this.runWebGLProgram(o,[{shape:a,dtype:r,dataId:e}],r,c,l);return{dtype:r,shape:s,dataId:u.dataId}}runWebGLProgram(e,t,n,s,r=!1){let a=this.makeTensorInfo(e.outputShape,n),o=this.texData.get(a.dataId);if(e.packedOutput&&(o.isPacked=!0),e.outPackingScheme===fp.DENSE){let m=Om(e.outputShape);o.texShape=m.map(g=>g*2)}if(e.outTexUsage!=null&&(o.usage=e.outTexUsage),v.sizeFromShape(a.shape)===0)return o.values=v.getTypedArrayFromDType(a.dtype,0),a;let i=[],l=t.map(m=>{if(m.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let g=this.texData.get(m.dataId);if(g.texture==null){if(!e.packedInputs&&v.sizeFromShape(m.shape)<=Y().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:m.shape,texData:null,isUniform:!0,uniformValues:g.values};e.packedInputs&&(g.isPacked=!0,g.shape=m.shape)}else if(!!g.isPacked!=!!e.packedInputs)m=g.isPacked?this.unpackTensor(m):this.packTensor(m),i.push(m),g=this.texData.get(m.dataId);else if(g.isPacked&&!yp(g.shape,m.shape)){let A=m,x=m.shape;m.shape=g.shape,m=this.packedReshape(m,x),i.push(m),g=this.texData.get(m.dataId),A.shape=x}return this.uploadToGPU(m.dataId),{shape:m.shape,texData:g,isUniform:!1}});this.uploadToGPU(a.dataId);let c={shape:a.shape,texData:o,isUniform:!1},u=TJ(e,l,c),d=this.getAndSaveBinary(u,()=>IJ(this.gpgpu,e,l,c)),p=this.activeTimers!=null,h;p&&(h=this.startTimer()),CJ(this.gpgpu,d,l,c,s),i.forEach(m=>this.disposeIntermediateTensorInfo(m)),p&&(h=this.endTimer(h),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(h)}));let f=Y().get("WEBGL_FLUSH_THRESHOLD");if(f>0){let m=v.now();m-this.lastGlFlushTime>f&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=m)}if(!Y().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&r===!1){let m=this.unpackTensor(a);return this.disposeIntermediateTensorInfo(a),m}return a}compileAndRun(e,t,n,s,r=!1){return n=n||t[0].dtype,this.runWebGLProgram(e,t,n,s,r)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(Y().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(t=>{this.gpgpu.deleteProgram(this.binaryCache[t].webGLProgram),delete this.binaryCache[t]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=X(()=>{if(!Y().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=Y().getBool("DEBUG");Y().set("DEBUG",!1);let t=this.abs(Ie(1e-8)).dataSync()[0];if(Y().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?VQ:UQ}uploadToGPU(e){let t=this.texData.get(e),{shape:n,dtype:s,values:r,texture:a,usage:o,isPacked:i}=t;if(a!=null)return;let l=this.activeTimers!=null,c;l&&(c=v.now());let u=t.texShape;if(u==null&&(u=zI(n,i),t.texShape=u),r!=null){let d=Lm(n),p,h=u[1],f=u[0],m=r instanceof Uint8Array||r instanceof Uint8ClampedArray;i?([h,f]=ic(u[0],u[1]),p=new DJ(d,m)):p=new _J(d,m);let g=this.makeTensorInfo([f,h],s);m?this.texData.get(g.dataId).usage=zs.PIXELS:this.texData.get(g.dataId).usage=zs.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(g.dataId),h,f,r);let A=[[f,h]],x=!0,y=this.runWebGLProgram(p,[g],s,A,x),b=this.texData.get(y.dataId);t.texture=b.texture,t.texShape=b.texShape,t.isPacked=b.isPacked,t.usage=b.usage,this.disposeIntermediateTensorInfo(g),this.texData.delete(y.dataId),t.values=null,l&&(this.uploadWaitMs+=v.now()-c)}else{let d=this.acquireTexture(u,o,s,i);t.texture=d}}convertAndCacheOnCPU(e,t){let n=this.texData.get(e),{dtype:s}=n;return this.releaseGPUData(e),t!=null&&(n.values=XQ(t,s)),n.values}acquireTexture(e,t,n,s){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){let r=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${r} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,s)}computeBytes(e,t){return e[0]*e[1]*v.bytesPerElement(t)}},bp=w4;bp.nextDataId=0;function XQ(e,t){if(t==="float32"||t==="complex64")return e;if(t==="int32"||t==="bool"){let n=t==="int32"?new Int32Array(e.length):new Uint8Array(e.length);for(let s=0;snew bp,2);var ZQ={forceHalfFloat:k4},S4=` if (isnan(a)) return a; if (isnan(b)) return b; `,fc=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=E.assertAndGetBroadcastShape(t,n),this.enableShapeUniforms=Bs(this.outputShape.length),this.userCode=` float binaryOperation(float a, float b) { ${e} } void main() { float a = getAAtOutCoords(); float b = getBAtOutCoords(); setOutput(binaryOperation(a, b)); } `}},qm=` result.r = isNaN.r > 0. ? NAN : result.r; result.g = isNaN.g > 0. ? NAN : result.g; result.b = isNaN.b > 0. ? NAN : result.b; result.a = isNaN.a > 0. ? NAN : result.a; `,vp=class{constructor(e,t,n,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=E.assertAndGetBroadcastShape(t,n);let r=this.outputShape.length;this.enableShapeUniforms=Bs(r);let a="";if(s)if(r===0||v.sizeFromShape(this.outputShape)===1)a=` result.y = 0.; result.z = 0.; result.w = 0.; `;else if(a=` ${xt(r)} coords = getOutputCoords(); `,r===1)this.enableShapeUniforms?a+=` result.y = (coords + 1) >= outShape ? 0. : result.y; result.z = 0.; result.w = 0.; `:a+=` result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y; result.z = 0.; result.w = 0.; `;else{let i=jn("coords",r);this.enableShapeUniforms?a+=` bool nextRowOutOfBounds = (${i[r-2]} + 1) >= outShape[${r} - 2]; bool nextColOutOfBounds = (${i[r-1]} + 1) >= outShape[${r} - 1]; result.y = nextColOutOfBounds ? 0. : result.y; result.z = nextRowOutOfBounds ? 0. : result.z; result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w; `:a+=` bool nextRowOutOfBounds = (${i[r-2]} + 1) >= ${this.outputShape[r-2]}; bool nextColOutOfBounds = (${i[r-1]} + 1) >= ${this.outputShape[r-1]}; result.y = nextColOutOfBounds ? 0. : result.y; result.z = nextRowOutOfBounds ? 0. : result.z; result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w; `}this.userCode=` vec4 binaryOperation(vec4 a, vec4 b) { ${e} } void main() { vec4 a = getAAtOutCoords(); vec4 b = getBAtOutCoords(); vec4 result = binaryOperation(a, b); ${a} setOutput(result); } `}};function ws(e){let{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}var YQ={kernelName:Xa,backendName:"webgl",kernelFunc:ws};function qo(e){let{inputs:t,backend:n}=e,{real:s,imag:r}=t,a=n.makeTensorInfo(s.shape,"complex64"),o=n.texData.get(a.dataId),i=ws({inputs:{x:s},backend:n}),l=ws({inputs:{x:r},backend:n});return o.complexTensorInfos={real:i,imag:l},a}var JQ={kernelName:id,backendName:"webgl",kernelFunc:qo},I4="return (a < 0.) ? b * a : a;",C4=` vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); `;function QQ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{alpha:a}=s,o=n.makeTensorInfo([],"float32",v.createScalarValue(a,"float32")),i=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new vp(C4,r.shape,o.shape):new fc(I4,r.shape,o.shape),l=n.runWebGLProgram(i,[r,o],"float32");return n.disposeIntermediateTensorInfo(o),l}var eee={kernelName:Ti,backendName:"webgl",kernelFunc:QQ},T4="return (a < 0.) ? b * a : a;",N4=` vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); `;function tee(e){let{inputs:t,backend:n}=e,{x:s,alpha:r}=t,a=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new vp(N4,s.shape,r.shape):new fc(T4,s.shape,r.shape);return n.runWebGLProgram(a,[s,r],"float32")}var nee={kernelName:oo,backendName:"webgl",kernelFunc:tee},E4="if (isnan(x)) return x;",see=` if (isnan(a)) return a; if (isnan(b)) return b; `,ree=` result.r = isNaN.r > 0. ? NAN : result.r; result.g = isNaN.g > 0. ? NAN : result.g; result.b = isNaN.b > 0. ? NAN : result.b; result.a = isNaN.a > 0. ? NAN : result.a; `;function st({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:s}){return({inputs:r,backend:a})=>{let{x:o}=r,i=a,l=s||o.dtype;if(i.shouldExecuteOnCPU([o])&&n!=null){let d=i.texData.get(o.dataId),p=n(d.values,l);return i.makeTensorInfo(o.shape,l,p)}let c=Y().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,u;return c?u=new hc(o.shape,t):u=new jo(o.shape,e),i.runWebGLProgram(u,[o],l)}}function Tn({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:s=!1,cpuKernelImpl:r,dtype:a}){return({inputs:o,backend:i})=>{let{a:l,b:c}=o,u=i;if(s&&l.dtype==="complex64"){let f=u.texData.get(l.dataId),m=u.texData.get(c.dataId),[g,A]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(y=>{let[b,w]=y,k={dataId:b.dataId,dtype:b.dtype,shape:l.shape},I={dataId:w.dataId,dtype:w.dtype,shape:c.shape},N=new fc(e,l.shape,c.shape);return u.runWebGLProgram(N,[k,I],Bn(b.dtype,w.dtype))}),x=qo({inputs:{real:g,imag:A},backend:u});return u.disposeIntermediateTensorInfo(g),u.disposeIntermediateTensorInfo(A),x}let d=a||Bn(l.dtype,c.dtype);if((l.dtype==="string"||c.dtype==="string"||u.shouldExecuteOnCPU([l,c]))&&r!=null){let f=u.texData.get(l.dataId).values,m=u.texData.get(c.dataId).values,g=l.dtype==="string"?E.fromUint8ToStringArray(f):f,A=l.dtype==="string"?E.fromUint8ToStringArray(m):m,[x,y]=r(l.shape,c.shape,g,A,d),b=u.makeTensorInfo(y,d),w=u.texData.get(b.dataId);return w.values=x,b}let p=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return p?h=new vp(t,l.shape,c.shape,n):h=new fc(e,l.shape,c.shape),u.runWebGLProgram(h,[l,c],d)}}function Xm(e,t=!1){if(e==="linear")return t?FQ:RQ;if(e==="relu")return t?MQ:_Q;if(e==="elu")return t?OQ:$Q;if(e==="relu6")return t?zQ:DQ;if(e==="prelu")return t?N4:T4;if(e==="leakyrelu")return t?C4:I4;if(e==="sigmoid")return t?LQ:PQ;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var R4=class{constructor(e,t,n,s=!1,r=!1,a=!1,o=null,i=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=Bs(this.outputShape.length);let c=s?e[1]:e[2],u=Math.ceil(c/2),d=s?"i * 2, rc.y":"rc.y, i * 2",p=r?"rc.z, i * 2":"i * 2, rc.z",h=s?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],m="",g="";o&&(i?m=`vec4 activation(vec4 a) { vec4 b = getPreluActivationWeightsAtOutCoords(); ${o} }`:l?m=`vec4 activation(vec4 a) { vec4 b = getLeakyreluAlphaAtOutCoords(); ${o} }`:m=`vec4 activation(vec4 x) { ${o} }`,g="result = activation(result);");let A=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let x="rc.x",y="rc.x";e[0]`The new shape (${l}) has ${c} elements and the old shape (${r.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);let u=o.texData.get(r.dataId);return u.isPacked&&!yp(r.shape,l)&&!(u.texture!==null&&yp(u.shape,l))?oee(r,l,o):(o.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype})}var iee={kernelName:Li,backendName:"webgl",kernelFunc:ve},P4=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:s,inSize:r,outSize:a}=e;this.outputShape=[s,a];let o=Math.floor(n/4)*4,i=n%4,l="sumValue += dot(values, ones);";if(t!=null){let u=1/t;l=`sumValue += dot(values * ${v.isInt(u)?u.toPrecision(2):u}, ones);`}let c="";r%n>0&&(c=` if (inIdx < 0 || inIdx >= ${r}) { return 0.0; } `),this.userCode=` const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); float getValue(int batch, int inIdx) { ${c} return getX(batch, inIdx); } void main() { ivec2 coords = getOutputCoords(); int batch = coords[0]; int outIdx = coords[1]; int inOffset = outIdx * ${n}; float sumValue = 0.0; for (int i = 0; i < ${o}; i += 4) { int inIdx = inOffset + i; vec4 values = vec4( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), getValue(batch, inIdx + 3) ); ${l} } int inIdx = inOffset + ${o}; if (${i===1}) { vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0); ${l} } else if (${i===2}) { vec4 values = vec4( getValue(batch, inIdx), getValue(batch, inIdx + 1), 0.0, 0.0); ${l} } else if (${i===3}) { vec4 values = vec4( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), 0.0); ${l} } setOutput(sumValue); } `}},lee=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:s,inSize:r,outSize:a}=e;this.outputShape=[s,a];let o="0.0",i="";t==="prod"?o="1.0":t==="min"?(o="1.0 / 1e-20",i="min"):t==="max"&&(o="-1.0 / 1e-20",i="max");let l=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?l="sumValue":t==="prod"?l="prodValue":t==="all"?l="allValue":t==="any"&&(l="anyValue");let c=Math.floor(n/4)*4,u=n%4,d=` if (${t==="sum"}) { sumValue += dot(values, ones); } else if (${t==="prod"}) { vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]); prodValue *= tmp[0] * tmp[1]; } else { minMaxValue = ${i}(values, minMaxValue); if (${t==="min"} || ${t==="max"}) { minMaxValue = ${i}(values, minMaxValue); bvec4 isNaN = isnan(values); if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) { minMaxValue = vec4(NAN); } } } `,p="vec4";t==="all"?(o="1.0",d=` bool reducedAllValue = all(values); float floatedReducedAllValue = float(reducedAllValue); allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0); `,p="bvec4"):t==="any"&&(o="0.0",d=` bool reducedAnyValue = any(values); float floatedReducedAnyValue = float(reducedAnyValue); anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0); `,p="bvec4");let h="";r%n>0&&(h=` if (inIdx < 0 || inIdx >= ${r}) { return initializationValue; } `),this.userCode=` const float initializationValue = ${o}; const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); float getValue(int batch, int inIdx) { ${h} return getX(batch, inIdx); } void main() { ivec2 coords = getOutputCoords(); int batch = coords[0]; int outIdx = coords[1]; int inOffset = outIdx * ${n}; vec4 minMaxValue = vec4(${o}); float prodValue = 1.0; float sumValue = 0.0; float allValue = 1.0; float anyValue = 0.0; for (int i = 0; i < ${c}; i += 4) { int inIdx = inOffset + i; ${p} values = ${p}( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), getValue(batch, inIdx + 3) ); ${d} } int inIdx = inOffset + ${c}; if (${u===1}) { ${p} values = ${p}( getValue(batch, inIdx), initializationValue, initializationValue, initializationValue ); ${d} } else if (${u===2}) { ${p} values = ${p}( getValue(batch, inIdx), getValue(batch, inIdx + 1), initializationValue, initializationValue ); ${d} } else if (${u===3}) { ${p} values = ${p}( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), initializationValue ); ${d} } setOutput(${l}); } `}};function uee(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let n=t.length?t[t.length-1].outSize:e[1],s=E.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:s,outSize:Math.ceil(n/s)})}return t}function Dl(e,t,n,s){let r=uee(e.shape),a=e;for(let o=0;o6)throw Error(`Transpose for rank ${t} is not yet supported`);let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],s=new Array(t);for(let r=0;r6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let s=xt(this.rank),r=g4("rc",this.rank),a=new Array(this.rank);for(let c=0;c`Error in matMul: inner shapes (${d}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${s} must match.`);let w=n?[A,d,h]:[A,h,d],k=s?[x,f,p]:[x,p,f],I=ve({inputs:{x:e},backend:r,attrs:{shape:w}}),N=ve({inputs:{x:t},backend:r,attrs:{shape:k}}),R=[I,N],O=Math.max(A,x),$=n?I.shape[1]:I.shape[2],P=a!=null,T=o!=null,F=l==="leakyrelu",U=l!=null?Xm(l,!0):null,q=P||T||F||U!=null,z;if((h===1||f===1)&&$>F4&&q===!1){let J=I,Q=N;n&&(J=qn({inputs:{x:I},backend:r,attrs:{perm:[0,2,1]}}),R.push(J)),s&&(Q=qn({inputs:{x:N},backend:r,attrs:{perm:[0,2,1]}}),R.push(Q));let ne=f!==1,re=f===1,G=J;ne&&(G=ve({inputs:{x:J},backend:r,attrs:{shape:[O,$,1]}}),R.push(G));let se=f===1?2:1,oe=Q;re&&(oe=ve({inputs:{x:Q},backend:r,attrs:{shape:[O,1,$]}}),R.push(oe));let pe=wx({inputs:{a:G,b:oe},backend:r});z=Zm({inputs:{x:pe},backend:r,attrs:{axis:se,keepDims:!0}}),R.push(pe)}else{let J=Bn(e.dtype,t.dtype),Q=new R4(w,k,[O,h,f],n,s,P,U,T,F),ne=[I,N];if(a!=null&&ne.push(a),T&&ne.push(o),F){let re=r.makeTensorInfo([],"float32",v.createScalarValue(i,"float32"));ne.push(re),R.push(re)}z=r.runWebGLProgram(Q,ne,J)}let K=ve({inputs:{x:z},backend:r,attrs:{shape:b}});R.push(z);for(let J of R)r.disposeIntermediateTensorInfo(J);return K}function gee(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:d}=s;return Ym({a:r,b:a,transposeA:l,transposeB:c,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:d,activation:u})}var Aee={kernelName:wo,backendName:"webgl",kernelFunc:gee},O4="return abs(x);";function yee(e){let{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])&&s.dtype!=="complex64"){let a=n.texData.get(s.dataId),o=f4(a.values);return n.makeTensorInfo(s.shape,s.dtype,o)}let r;return Y().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new hc(s.shape,O4):r=new jo(s.shape,O4),n.runWebGLProgram(r,[s],s.dtype)}var xee={kernelName:fi,backendName:"webgl",kernelFunc:yee},bee=kr+` if (abs(x) > 1.) { return NAN; } return acos(x); `,vee=st({opSnippet:bee}),wee={kernelName:iu,backendName:"webgl",kernelFunc:vee},kee=kr+` if (x < 1.0) return NAN; return log(x + sqrt(x * x - 1.0));`,See=st({opSnippet:kee}),Iee={kernelName:lu,backendName:"webgl",kernelFunc:See},M4="return a + b;",Cee=Tn({opSnippet:M4,packedOpSnippet:M4,supportsComplex:!0,cpuKernelImpl:FJ}),Tee={kernelName:Kr,backendName:"webgl",kernelFunc:Cee},Nee=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((r,a)=>`T${a}`);let n=[];this.variableNames.forEach(r=>{n.push(`float v${r} = get${r}AtOutCoords();`)});let s=this.variableNames.map(r=>`v${r}`).join(" + ");this.userCode=` void main() { ${n.join(` `)} float result = ${s}; setOutput(result); } `}},Eee=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((r,a)=>`T${a}`);let n=[];this.variableNames.forEach(r=>{n.push(`vec4 v${r} = get${r}AtOutCoords();`)});let s=this.variableNames.map(r=>`v${r}`).join(" + ");this.userCode=` void main() { ${n.join(` `)} vec4 result = ${s}; setOutput(result); } `}};function Jm(e){let{inputs:t,backend:n}=e,s=t;if(s.length===1)return ws({inputs:{x:s[0]},backend:n});if(s.length>Y().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let l=Math.floor(s.length/2),c=Jm({inputs:s.slice(0,l),backend:n}),u=Jm({inputs:s.slice(l),backend:n});return Jm({inputs:[c,u],backend:n})}let r=s.map(l=>l.dtype).reduce((l,c)=>Bn(l,c)),a=s.map(l=>l.shape),i=Y().getBool("WEBGL_PACK")?new Eee(s[0].shape,a):new Nee(s[0].shape,a);return n.runWebGLProgram(i,s,r)}var Ree={kernelName:Ra,backendName:"webgl",kernelFunc:Jm};function $ee(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s,i=r.shape.length,l=v.parseAxisParam(a,r.shape),c=l,u=E.getAxesPermutation(c,i),d=r;u!=null&&(d=qn({inputs:{x:r},backend:n,attrs:{perm:u}}),c=E.getInnerMostAxes(c.length,i)),E.assertAxesAreInnerMostDims("all",c,i);let[p,h]=E.computeOutAndReduceShapes(d.shape,c),f=v.sizeFromShape(h),m=ve({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=Dl(m,m.dtype,"all",n),A;if(o){let x=E.expandShapeToKeepDim(p,l);A=ve({inputs:{x:g},backend:n,attrs:{shape:x}})}else A=ve({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(d),A}var _ee={kernelName:uu,backendName:"webgl",kernelFunc:$ee};function Dee(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s,i=r.shape.length,l=v.parseAxisParam(a,r.shape),c=l,u=E.getAxesPermutation(c,i),d=r;u!=null&&(d=qn({inputs:{x:r},backend:n,attrs:{perm:u}}),c=E.getInnerMostAxes(c.length,i)),E.assertAxesAreInnerMostDims("any",c,i);let[p,h]=E.computeOutAndReduceShapes(d.shape,c),f=v.sizeFromShape(h),m=ve({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}}),g=Dl(m,m.dtype,"any",n),A;if(o){let x=E.expandShapeToKeepDim(p,l);A=ve({inputs:{x:g},backend:n,attrs:{shape:x}})}else A=ve({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),u!=null&&n.disposeIntermediateTensorInfo(d),A}var Pee={kernelName:cu,backendName:"webgl",kernelFunc:Dee},Fee=class{constructor(e,t,n){this.variableNames=["A"];let{windowSize:s,batchSize:r,outSize:a}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[r,a];let o=t==="max"?">":"<",i=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=` void main() { ivec2 coords = getOutputCoords(); int batch = coords[0]; int outIdx = coords[1]; int inOffset = outIdx * ${s}; int bestIndex = inOffset; float bestValue = getA(batch, bestIndex); for (int i = 0; i < ${s}; i++) { int inIdx = ${i}; float candidate = getA(batch, inIdx); if (candidate ${o} bestValue) { bestValue = candidate; bestIndex = inIdx; } } setOutput(float(bestIndex)); } `}},Oee=class{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,v.assert(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);let r=e[e.length-1],a=Math.ceil(r/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),s||this.variableNames.push("bestIndicesA");let o=this.outputShape,i=o.length,l=xt(i),c=jn("coords",i),u,d;if(a===1){d=i+1;let I=xt(d);u=` ${I} sourceLocR = ${I}(${c.join()}, 0); ++${c[i-1]}; ${I} sourceLocG = ${I}(${c.join()}, 0); ++${c[i-2]}; ${I} sourceLocA = ${I}(${c.join()}, 0); --${c[i-1]}; ${I} sourceLocB = ${I}(${c.join()}, 0); --${c[i-2]};`}else d=i,u=` ${l} sourceLocR = coords; ++${c[i-1]}; ${l} sourceLocG = coords; ++${c[i-2]}; ${l} sourceLocA = coords; --${c[i-1]}; ${l} sourceLocB = coords; --${c[i-2]};`;let p=["x","y","z","w","u","v"].slice(0,d),h="."+p[d-1],f=p.map(I=>"int "+I),m=jn("sourceLocR",d-1).concat("inIdx.r"),g=jn("sourceLocG",d-1).concat("inIdx.g"),A=jn("sourceLocB",d-1).concat("inIdx.b"),x=jn("sourceLocA",d-1).concat("inIdx.a"),y=n==="max"?"greaterThan":"lessThan",b=s?"":` inIdx = round(vec4(getBestIndicesAChannel(${m.join()}), getBestIndicesAChannel(${g.join()}), getBestIndicesAChannel(${A.join()}), getBestIndicesAChannel(${x.join()})));`,w=`vec4( getAChannel(${m.join()}), hasNextCol ? getAChannel(${g.join()}) : 0., hasNextRow ? getAChannel(${A.join()}) : 0., hasNextRow && hasNextCol ? getAChannel(${x.join()}) : 0.)`,k=s?"":` float getBestIndicesAChannel(${f.join()}) { return getChannel(getBestIndicesA(${p.join()}), vec2(${p.slice(-2).join()})); }`;this.userCode=` float getAChannel(${f.join()}) { return getChannel(getA(${p.join()}), vec2(${p.slice(-2).join()})); } ${k} void main() { ${l} coords = getOutputCoords(); bool hasNextCol = ${c[i-1]} < ${o[i-1]-1}; bool hasNextRow = ${c[i-2]} < ${o[i-2]-1}; ${u} ivec4 srcIdx = ivec4(sourceLocR${h}, sourceLocG${h}, sourceLocB${h}, sourceLocA${h}) * ${t}; ivec4 inIdx = srcIdx; vec4 bestIndex = vec4(inIdx); vec4 bestValue = ${w}; for (int i = 0; i < ${t}; i++) { inIdx = srcIdx; ${b} vec4 candidate = ${w}; bvec4 nan = isnan(candidate); bvec4 replace = bvec4( vec4(${y}(candidate, bestValue)) * (vec4(1.0) - vec4(nan))); bestValue = vec4(replace.x ? candidate.x : bestValue.x, replace.y ? candidate.y : bestValue.y, replace.z ? candidate.z : bestValue.z, replace.w ? candidate.w : bestValue.w); bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace)); srcIdx++; } setOutput(bestIndex); } `}};function z4(e,t,n,s=null){let r=t.shape[0],a=t.shape[1];s!=null&&(r=s.shape[0],a=s.shape[1]);let o=E.computeOptimalWindowSize(a),i={windowSize:o,inSize:a,batchSize:r,outSize:Math.ceil(a/o)},l=new Fee(i,n,s==null),c=[t];s!=null&&c.push(s);let u=e.runWebGLProgram(l,c,"int32");if(u.shape[1]===1)return u;let d=z4(e,t,n,u);return e.disposeIntermediateTensorInfo(u),d}function L4(e,t,n,s=null){let r=s!=null?s.shape:t.shape,a=r[r.length-1],o=E.computeOptimalWindowSize(a),i=new Oee(r,o,n,s==null),l=s==null?[t]:[t,s],c=e.runWebGLProgram(i,l,"int32");if(c.shape.length===t.shape.length){let u=L4(e,t,n,c);return e.disposeIntermediateTensorInfo(c),u}return c}function B4(e,t,n,s){let r=[n];if(E.assertAxesAreInnerMostDims("arg"+s.charAt(0).toUpperCase()+s.slice(1),r,t.shape.length),!Y().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let a=[],o=e.texData.get(t.dataId),i=o!==null&&o.isPacked,l=t;i&&(l=e.unpackTensor(t),a.push(l));let[c,u]=E.computeOutAndReduceShapes(l.shape,r),d=v.sizeFromShape(u),p=ve({inputs:{x:l},backend:e,attrs:{shape:[-1,d]}});a.push(p);let h=z4(e,p,s);a.push(h);let f=ve({inputs:{x:h},backend:e,attrs:{shape:c}});return a.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}return L4(e,t,s)}function Mee(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s,o=v.parseAxisParam(a,r.shape),i=E.getAxesPermutation(o,r.shape.length),l=r,c=[];i!=null&&(l=qn({inputs:{x:r},backend:n,attrs:{perm:i}}),c.push(l),o=E.getInnerMostAxes(o.length,l.shape.length)),E.assertAxesAreInnerMostDims("argMax",[o[0]],l.shape.length);let u=B4(n,l,o[0],"max");return c.forEach(d=>n.disposeIntermediateTensorInfo(d)),u}var zee={kernelName:$a,backendName:"webgl",kernelFunc:Mee};function Lee(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s,o=v.parseAxisParam(a,r.shape),i=E.getAxesPermutation(o,r.shape.length),l=r,c=[];i!=null&&(l=qn({inputs:{x:r},backend:n,attrs:{perm:i}}),c.push(l),o=E.getInnerMostAxes(o.length,l.shape.length)),E.assertAxesAreInnerMostDims("argMin",[o[0]],l.shape.length);let u=B4(n,l,o[0],"min");return c.forEach(d=>n.disposeIntermediateTensorInfo(d)),u}var Bee={kernelName:du,backendName:"webgl",kernelFunc:Lee},Wee=kr+` if (abs(x) > 1.) { return NAN; } return asin(x); `,Vee=st({opSnippet:Wee}),Uee={kernelName:pu,backendName:"webgl",kernelFunc:Vee},Gee=kr+"return log(x + sqrt(x * x + 1.0));",Hee=st({opSnippet:Gee}),jee={kernelName:hu,backendName:"webgl",kernelFunc:Hee},qee=kr+` return atan(x); `,Xee=st({opSnippet:qee}),Kee={kernelName:fu,backendName:"webgl",kernelFunc:Xee},Zee=see+` return atan(a, b); `,Yee=` vec4 result = atan(a, b); vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0)); `+ree+` return result; `,Jee=Tn({opSnippet:Zee,packedOpSnippet:Yee}),Qee={kernelName:gu,backendName:"webgl",kernelFunc:Jee},ete=kr+` if ((x < -1.0) || (x > 1.0)) return NAN; return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,tte=st({opSnippet:ete}),nte={kernelName:mu,backendName:"webgl",kernelFunc:tte},wp=class{constructor(e,t,n,s=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideHeight,i=e.strideWidth,l=e.dilationHeight,c=e.dilationWidth,u=e.effectiveFilterHeight,d=e.effectiveFilterWidth,p=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;let f=t==="avg",m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,A="0.0";if(f||(A="-1.0 / 1e-20"),n){let I=">=";this.userCode=` const ivec2 strides = ivec2(${o}, ${i}); const ivec2 pads = ivec2(${p}, ${h}); void main() { ivec4 coords = getOutputCoords(); int batch = coords[0]; int d = coords[3]; ivec2 xRCCorner = coords.yz * strides - pads; int xRCorner = xRCCorner.x; int xCCorner = xRCCorner.y; // max/min x(?, ?, d) to get y(yR, yC, d). // ? = to be determined float minMaxValue = 0.0; float minMaxValueFound = 0.0; int minMaxPosition = 0; float avgValue = 0.0; for (int wR = 0; wR < ${u}; wR += ${l}) { int xR = xRCorner + wR; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${d}; wC += ${c}) { int xC = xCCorner + wC; if (xC < 0 || xC >= ${e.inWidth}) { continue; } float value = getX(batch, xR, xC, d); // If a min / max value has already been found, use it. If not, // use the current value. float currMinMaxValue = mix( value, minMaxValue, minMaxValueFound); if (value ${I} currMinMaxValue) { minMaxValue = value; minMaxValueFound = 1.0; minMaxPosition = ${s?r?m:g:`wR * ${d} + wC`}; } } } setOutput(float(minMaxPosition)); } `;return}let x="max",y=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(y="avgValue / count");let b=Math.floor(a/4)*4,w=a%4,k=` if (${f}) { avgValue += dot(values, ones); } else { minMaxValue = ${x}(values, minMaxValue); } `;this.userCode=` const ivec2 strides = ivec2(${o}, ${i}); const ivec2 pads = ivec2(${p}, ${h}); const float initializationValue = ${A}; const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); float count = 0.0; float getValue(int batch, int xR, int xC, int d) { if (xC < 0 || xC >= ${e.inWidth}) { return initializationValue; } count += 1.0; return getX(batch, xR, xC, d); } void main() { ivec4 coords = getOutputCoords(); int batch = coords[0]; int d = coords[3]; ivec2 xRCCorner = coords.yz * strides - pads; int xRCorner = xRCCorner.x; int xCCorner = xRCCorner.y; // max/min x(?, ?, d) to get y(yR, yC, d). // ? = to be determined vec4 minMaxValue = vec4(${A}); float avgValue = 0.0; count = 0.0; for (int wR = 0; wR < ${u}; wR += ${l}) { int xR = xRCorner + wR; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${b}; wC += 4) { int xC = xCCorner + wC * ${c}; vec4 values = vec4( getValue(batch, xR, xC, d), getValue(batch, xR, xC + ${c}, d), getValue(batch, xR, xC + 2 * ${c}, d), getValue(batch, xR, xC + 3 * ${c}, d) ); ${k} } int xC = xCCorner + ${b}; if (${w===1}) { vec4 values = vec4( getValue(batch, xR, xC, d), initializationValue, initializationValue, initializationValue ); ${k} } else if (${w===2}) { vec4 values = vec4( getValue(batch, xR, xC, d), getValue(batch, xR, xC + ${c}, d), initializationValue, initializationValue ); ${k} } else if (${w===3}) { vec4 values = vec4( getValue(batch, xR, xC, d), getValue(batch, xR, xC + ${c}, d), getValue(batch, xR, xC + 2 * ${c}, d), initializationValue ); ${k} } } setOutput(${y}); } `}},kx=class{constructor(e,t,n,s=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideDepth,i=e.strideHeight,l=e.strideWidth,c=e.dilationDepth,u=e.dilationHeight,d=e.dilationWidth,p=e.effectiveFilterDepth,h=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,A=e.padInfo.left;this.outputShape=e.outShape;let x=t==="avg",y="0.0";if(x||(y="-1.0 / 1e-20"),n){let R=">=";this.userCode=` const ivec3 strides = ivec3(${o}, ${i}, ${l}); const ivec3 pads = ivec3(${m}, ${g}, ${A}); void main() { ivec5 coords = getOutputCoords(); int batch = coords.x; int ch = coords.u; ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; int xDCorner = xCorner.x; int xRCorner = xCorner.y; int xCCorner = xCorner.z; // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch). // ? = to be determined float minMaxValue = 0.0; float minMaxValueFound = 0.0; int minMaxPosition = 0; for (int wD = 0; wD < ${p}; wD += ${c}) { int xD = xDCorner + wD; if (xD < 0 || xD >= ${e.inDepth}) { continue; } for (int wR = 0; wR < ${h}; wR += ${u}) { int xR = xRCorner + wR; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${f}; wC += ${d}) { int xC = xCCorner + wC; if (xC < 0 || xC >= ${e.inWidth}) { continue; } float value = getX(batch, xD, xR, xC, ch); // If a min / max value has already been found, use it. If not, // use the current value. float currMinMaxValue = mix( value, minMaxValue, minMaxValueFound); if (value ${R} currMinMaxValue) { minMaxValue = value; minMaxValueFound = 1.0; minMaxPosition = ${s?r?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${h} * ${f} + wR * ${f} + wC`}; } } } } setOutput(float(minMaxPosition)); } `;return}let b="max",w=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(w="avgValue / count");let k=Math.floor(a/4)*4,I=a%4,N=` if (${x}) { avgValue += dot(values, ones); } else { minMaxValue = ${b}(values, minMaxValue); } `;this.userCode=` const ivec3 strides = ivec3(${o}, ${i}, ${l}); const ivec3 pads = ivec3(${m}, ${g}, ${A}); const float initializationValue = ${y}; const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); float count = 0.0; float getValue(int batch, int xD, int xR, int xC, int ch) { if (xC < 0 || xC >= ${e.inWidth}) { return initializationValue; } count += 1.0; return getX(batch, xD, xR, xC, ch); } void main() { ivec5 coords = getOutputCoords(); int batch = coords.x; int ch = coords.u; ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; int xDCorner = xCorner.x; int xRCorner = xCorner.y; int xCCorner = xCorner.z; // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch). // ? = to be determined vec4 minMaxValue = vec4(${y}); float avgValue = 0.0; count = 0.0; for (int wD = 0; wD < ${p}; wD += ${c}) { int xD = xDCorner + wD; if (xD < 0 || xD >= ${e.inDepth}) { continue; } for (int wR = 0; wR < ${h}; wR += ${u}) { int xR = xRCorner + wR; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${k}; wC += 4) { int xC = xCCorner + wC * ${d}; vec4 values = vec4( getValue(batch, xD, xR, xC, ch), getValue(batch, xD, xR, xC + ${d}, ch), getValue(batch, xD, xR, xC + 2 * ${d}, ch), getValue(batch, xD, xR, xC + 3 * ${d}, ch) ); ${N} } int xC = xCCorner + ${k}; if (${I===1}) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), initializationValue, initializationValue, initializationValue ); ${N} } else if (${I===2}) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), getValue(batch, xD, xR, xC + ${d}, ch), initializationValue, initializationValue ); ${N} } else if (${I===3}) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), getValue(batch, xD, xR, xC + ${d}, ch), getValue(batch, xD, xR, xC + 2 * ${d}, ch), initializationValue ); ${N} } } setOutput(${w}); } } `}};function ste(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t;lc(r,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,c=1;v.assert(E.eitherStridesOrDilationsAreOne(o,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);let u=E.computePool2DInfo(r.shape,a,o,c,i,l);if(u.filterWidth===1&&u.filterHeight===1&&v.arraysEqual(u.inShape,u.outShape))return ws({inputs:{x:r},backend:n});let d=new wp(u,"avg",!1);return n.runWebGLProgram(d,[r],"float32")}var rte={kernelName:_a,backendName:"webgl",kernelFunc:ste};function ate(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l,dataFormat:c}=s,u=[1,1,1],d=E.computePool3DInfo(r.shape,a,o,u,i,l,c),p=new kx(d,"avg",!1);return n.runWebGLProgram(p,[r],"float32")}var ote={kernelName:od,backendName:"webgl",kernelFunc:ate},ite=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,r=e.strideWidth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterHeight,l=e.effectiveFilterWidth,c=i-1-e.padInfo.top,u=l-1-e.padInfo.left,d=1/(t*n);this.userCode=` const ivec2 pads = ivec2(${c}, ${u}); const float avgMultiplier = float(${d}); void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; ivec2 dyRCCorner = coords.yz - pads; int dyRCorner = dyRCCorner.x; int dyCCorner = dyRCCorner.y; // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; for (int wR = 0; wR < ${i}; wR += ${a}) { float dyR = float(dyRCorner + wR) / ${s}.0; if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); for (int wC = 0; wC < ${l}; wC+= ${o}) { float dyC = float(dyCCorner + wC) / ${r}.0; if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); float dyValue = getDy(b, idyR, idyC, d); dotProd += dyValue * avgMultiplier; } } setOutput(dotProd); } `}},lte=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,r=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,l=e.dilationHeight,c=e.dilationWidth,u=e.effectiveFilterDepth,d=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=u-1-e.padInfo.front,f=d-1-e.padInfo.top,m=p-1-e.padInfo.left,g=1/(t*n*s);this.userCode=` const ivec3 pads = ivec3(${h}, ${f}, ${m}); const float avgMultiplier = float(${g}); void main() { ivec5 coords = getOutputCoords(); int batch = coords.x; int ch = coords.u; ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; int dyDCorner = dyCorner.x; int dyRCorner = dyCorner.y; int dyCCorner = dyCorner.z; // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get // dx(xD, xR, xC, ch). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; for (int wD = 0; wD < ${u}; wD += ${i}) { float dyD = float(dyDCorner + wD) / ${r}.0; if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) { continue; } int idyD = int(dyD); for (int wR = 0; wR < ${d}; wR += ${l}) { float dyR = float(dyRCorner + wR) / ${a}.0; if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); for (int wC = 0; wC < ${p}; wC += ${c}) { float dyC = float(dyCCorner + wC) / ${o}.0; if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); float dyValue = getDy(batch, idyD, idyR, idyC, ch); dotProd += dyValue * avgMultiplier; } } } setOutput(dotProd); } `}};function ute(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,o=a,{filterSize:i,strides:l,pad:c,dimRoundingMode:u}=s,d=[1,1,1],p=E.computePool3DInfo(o.shape,i,l,d,c,u),h=new lte(p);return n.runWebGLProgram(h,[r],o.dtype)}var cte={kernelName:Ih,backendName:"webgl",kernelFunc:ute};function dte(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,o=a;lc([r,a],"avgPoolGrad");let{filterSize:i,strides:l,pad:c}=s,u=E.computePool2DInfo(o.shape,i,l,1,c),d=new ite(u);return n.runWebGLProgram(d,[r],o.dtype)}var pte={kernelName:Sh,backendName:"webgl",kernelFunc:dte};function hte(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:o,transposeB:i}=s;return Ym({a:r,b:a,transposeA:o,transposeB:i,backend:n})}var fte={kernelName:Da,backendName:"webgl",kernelFunc:hte},mte=class{constructor(e,t,n,s,r,a){this.outputShape=[],this.variableNames=["x","mean","variance"],E.assertAndGetBroadcastShape(e,t),E.assertAndGetBroadcastShape(e,n);let o="0.0";s!=null&&(E.assertAndGetBroadcastShape(e,s),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="1.0";r!=null&&(E.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=` void main() { float x = getXAtOutCoords(); float mean = getMeanAtOutCoords(); float variance = getVarianceAtOutCoords(); float offset = ${o}; float scale = ${i}; float inv = scale * inversesqrt(variance + float(${a})); setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1))); } `}},gte=class{constructor(e,t,n,s,r,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],E.assertAndGetBroadcastShape(e,t),E.assertAndGetBroadcastShape(e,n);let o="vec4(0.0)";s!=null&&(E.assertAndGetBroadcastShape(e,s),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="vec4(1.0)";r!=null&&(E.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=` void main() { vec4 offset = ${o}; vec4 scale = ${i}; vec4 x = getXAtOutCoords(); vec4 mean = getMeanAtOutCoords(); vec4 variance = getVarianceAtOutCoords(); vec4 inv = scale * inversesqrt(variance + vec4(${a})); setOutput((x - mean) * inv + offset); } `}},Ate=({inputs:e,backend:t,attrs:n})=>{let{x:s,mean:r,variance:a,offset:o,scale:i}=e;v.assert(r.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),v.assert(o==null||r.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),v.assert(i==null||r.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=n;l==null&&(l=.001);let c=[s,r,a],u=null;o!=null&&(u=o.shape,c.push(o));let d=null;i!=null&&(d=i.shape,c.push(i));let p=Y().getBool("WEBGL_PACK_NORMALIZATION")?new gte(s.shape,r.shape,a.shape,u,d,l):new mte(s.shape,r.shape,a.shape,u,d,l);return t.runWebGLProgram(p,c,c[0].dtype)},yte={kernelName:ja,backendName:"webgl",kernelFunc:Ate},xte=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=xt(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let n=bte(this.rank),s,r=e.map((a,o)=>`sourceLoc.${Sx[o]} = start[${o}] + coords.${Sx[o]};`);s=` ${t} sourceLoc; ${t} coords = getOutputCoords(); ${r.join(` `)} `,this.userCode=` void main() { ${s} setOutput(getSource(${n})); } `}},Sx=["x","y","z","w","u","v"];function bte(e){if(e===1)return"sourceLoc";if(e<=6)return Sx.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var vte=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let t=xt(this.rank),n=jn("coords",this.rank),s=jn("sourceLoc",this.rank),r=this.rank===1?"sourceLoc":`vec2(${s.slice(-2).join()})`,a=`getChannel(getSource(${s.join()}), ${r})`,o=` result.x = ${a}; if (++${n[this.rank-1]} < ${e[this.rank-1]}) { ++${s[this.rank-1]}; result.y = ${a}; --${s[this.rank-1]}; } `,i=this.rank===1?"":` --${n[this.rank-1]}; if (++${n[this.rank-2]} < ${e[this.rank-2]}) { ++${s[this.rank-2]}; result.z = ${a}; if (++${n[this.rank-1]} < ${e[this.rank-1]}) { ++${s[this.rank-1]}; result.w = ${a}; } } `,l=this.rank<=4?`sourceLoc = coords + ${t}(${e.map((c,u)=>`start[${u}]`).join()});`:e.map((c,u)=>`${s[u]} = ${n[u]} + start[${u}];`).join(` `);this.userCode=` void main() { ${t} coords = getOutputCoords(); ${t} sourceLoc; ${l} vec4 result = vec4(0.); ${o} ${i} setOutput(result); } `}};function wte(e,t,n,s){let r=s.texData.get(e.dataId),a=s.makeTensorInfo(n,e.dtype),o=s.texData.get(a.dataId);Object.assign(o,r),o.refCount=1,o.shape=n,o.dtype=e.dtype;let i=Ft.computeFlatOffset(t,v.computeStrides(e.shape));r.slice&&(i+=r.slice.flatOffset),o.slice={flatOffset:i,origDataId:r.slice&&r.slice.origDataId||e.dataId};let l=s.dataRefCount.get(o.slice.origDataId)||1;return s.dataRefCount.set(o.slice.origDataId,l+1),a}function mc(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:o}=s,[i,l]=Ft.parseSliceParams(r,a,o);if(Ft.assertParamsValid(r,i,l),v.sizeFromShape(l)===0)return n.makeTensorInfo(l,r.dtype,[]);if(n.shouldExecuteOnCPU([r])||r.dtype==="string"){let d=n.texData.get(r.dataId),p=iQ(d.values,i,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,p)}let{isPacked:c}=n.texData.get(r.dataId),u=Ft.isSliceContinous(r.shape,i,l);if(c||!u){let d=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new vte(l):new xte(l),p=[i];return n.runWebGLProgram(d,[r],r.dtype,p)}return n.uploadToGPU(r.dataId),wte(r,i,l,n)}var kte={kernelName:Gi,backendName:"webgl",kernelFunc:mc},Ste=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:o}=s;v.assert(r.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((x,y)=>x*y),l=E.getReshaped(r.shape,a,i),c=E.getPermuted(l.length,a.length),u=E.getReshapedPermuted(r.shape,a,i),d=E.getSliceBeginCoords(o,a.length),p=E.getSliceSize(u,o,a.length),h=[],f=ve({inputs:{x:r},backend:n,attrs:{shape:l}}),m=qn({inputs:{x:f},backend:n,attrs:{perm:c}}),g=ve({inputs:{x:m},backend:n,attrs:{shape:u}}),A=mc({inputs:{x:g},backend:n,attrs:{begin:d,size:p}});return h.push(f),h.push(m),h.push(g),h.forEach(x=>n.disposeIntermediateTensorInfo(x)),A},Ite={kernelName:mi,backendName:"webgl",kernelFunc:Ste};function Cte(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:o}=s,i=n.readSync(r.dataId),l=n.readSync(a.dataId),c=h4(i,l,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,c)}var Tte={kernelName:Ch,backendName:"webgl",kernelFunc:Cte};function Nte(e){let{inputs:t,backend:n}=e,{s0:s,s1:r}=t,a=n.readSync(s.dataId),o=n.readSync(r.dataId),i=E.assertAndGetBroadcastShape(Array.from(a),Array.from(o));return n.makeTensorInfo([i.length],"int32",Int32Array.from(i))}var Ete={kernelName:Th,backendName:"webgl",kernelFunc:Nte},Rte="return float(a != b);",W4=Tn({opSnippet:Rte,cpuKernelImpl:nQ,dtype:"bool"}),$te={kernelName:_i,backendName:"webgl",kernelFunc:W4};function kp(e){let{inputs:t,backend:n}=e,{input:s}=t,r=n.texData.get(s.dataId);return ws({inputs:{x:r.complexTensorInfos.real},backend:n})}var _te={kernelName:gd,backendName:"webgl",kernelFunc:kp},Dte="return float(int(x));";function Pte(e,t){let n=new jo(e.shape,Dte),s=t.runWebGLProgram(n,[e],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}function Ix(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dtype:a}=s;if(a==="complex64"){if(r.dtype==="complex64")return ws({inputs:{x:r},backend:n});let o=Ht(r.shape),i=Ix({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=qo({inputs:{real:i,imag:o},backend:n});return o.dispose(),n.disposeIntermediateTensorInfo(i),l}if(r.dtype==="complex64"){let o=kp({inputs:{input:r},backend:n}),i=Ix({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(o),i}if(!v.hasEncodingLoss(r.dtype,a)){let o=ws({inputs:{x:r},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32")return Pte(r,n);if(a==="bool"){let o=n.makeTensorInfo([],"bool",v.getTypedArrayFromDType("bool",1)),l=W4({inputs:{a:r,b:o},backend:n});return n.disposeIntermediateTensorInfo(o),l}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${a}`)}var Fte={kernelName:Pa,backendName:"webgl",kernelFunc:Ix},V4="return ceil(x);",Ote=st({opSnippet:V4,packedOpSnippet:V4,cpuKernelImpl:MJ}),Mte={kernelName:Fa,backendName:"webgl",kernelFunc:Ote},zte=class{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=` void main() { float value = getAAtOutCoords(); if (isnan(value)) { setOutput(value); return; } setOutput(clamp(value, minVal, maxVal)); } `}},Lte=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=` void main() { vec4 value = getAAtOutCoords(); if (any(isnan(value))) { setOutput(value); return; } setOutput(clamp(value, vec4(minVal), vec4(maxVal))); } `}};function Bte(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{clipValueMin:a,clipValueMax:o}=s,i;Y().getBool("WEBGL_PACK_CLIP")?i=new Lte(r.shape):i=new zte(r.shape);let l=[[a],[o]];return n.runWebGLProgram(i,[r],r.dtype,l)}var Wte={kernelName:Zr,backendName:"webgl",kernelFunc:Bte},Vte=class{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=` void main() { float re = abs(getRealAtOutCoords()); float im = abs(getImagAtOutCoords()); float mx = max(re, im); // sadly the length function in glsl is not underflow-safe // (at least not on Intel GPUs). So the safe solution is // to ensure underflow-safety in all cases. setOutput( mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx)) ); } `}};function U4(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function Ute(e){let{inputs:t,backend:n}=e,{x:s}=t,r=n.texData.get(s.dataId),a=new Vte(s.shape),o=[U4(s,r.complexTensorInfos.real),U4(s,r.complexTensorInfos.imag)];return n.runWebGLProgram(a,o,o[0].dtype)}var Gte={kernelName:ld,backendName:"webgl",kernelFunc:Ute},Hte=class{constructor(e){this.outputShape=[],this.outputShape=E.computeOutShape(e,1),this.variableNames=e.map((a,o)=>`T${o}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let a=1;a`T${m}`);let i=new Array(e.length-1);i[0]=e[0][t];for(let f=1;f= ${i[f-1]}) { return getChannel( getT${f}(${Qm(o,l,m)}), vec2(${Qm(c,l,m)})); }`}let p=i.length,h=i[i.length-1];d+=` return getChannel( getT${p}(${Qm(o,l,h)}), vec2(${Qm(c,l,h)}));`,this.userCode=` float getValue(${o.map(f=>"int "+f)}) { ${d} } void main() { ${r} coords = getOutputCoords(); vec4 result = vec4(getValue(${a}), 0., 0., 0.); ${a[s-1]} = ${a[s-1]} + 1; if (${a[s-1]} < ${n[s-1]}) { result.g = getValue(${a}); } ${a[s-2]} = ${a[s-2]} + 1; if (${a[s-2]} < ${n[s-2]}) { result.a = getValue(${a}); } ${a[s-1]} = ${a[s-1]} - 1; if (${a[s-2]} < ${n[s-2]} && ${a[s-1]} < ${n[s-1]}) { result.b = getValue(${a}); } setOutput(result); } `}};function Qm(e,t,n){let s=e.indexOf(t);return e.map((a,o)=>o===s?`${a} - ${n}`:a).join()}function e0(e){let{inputs:t,backend:n}=e,{input:s}=t,r=n.texData.get(s.dataId);return ws({inputs:{x:r.complexTensorInfos.imag},backend:n})}var qte={kernelName:pd,backendName:"webgl",kernelFunc:e0};function gc(e,t,n){let s=e[0].dtype;if(s==="complex64"){let u=e.map(m=>kp({inputs:{input:m},backend:n})),d=e.map(m=>e0({inputs:{input:m},backend:n})),p=gc(u,t,n),h=gc(d,t,n),f=qo({inputs:{real:p,imag:h},backend:n});return u.forEach(m=>n.disposeIntermediateTensorInfo(m)),d.forEach(m=>n.disposeIntermediateTensorInfo(m)),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}let r=n.shouldExecuteOnCPU(e);if(s==="string"&&(r=!0),r){let u=e.map(A=>{let x=v.sizeFromShape(A.shape.slice(t));return ve({inputs:{x:A},backend:n,attrs:{shape:[-1,x]}})}),d=u.map(A=>({vals:n.readSync(A.dataId),shape:A.shape})),p=E.computeOutShape(u.map(A=>A.shape),1),h=u[0].shape[0]===1,f=zJ(d,p,s,h),m=E.computeOutShape(e.map(A=>A.shape),t),g=n.makeTensorInfo(m,s,f);return u.forEach(A=>n.disposeIntermediateTensorInfo(A)),g}if(e.length>Y().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let u=Math.floor(e.length/2),d=gc(e.slice(0,u),t,n),p=gc(e.slice(u),t,n),h=gc([d,p],t,n);return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),h}if(Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){let u=new jte(e.map(d=>d.shape),t);return n.runWebGLProgram(u,e,s)}let{tensors2D:a,outShape:o}=Xte(e,t,n),i=new Hte(a.map(u=>u.shape)),l=n.runWebGLProgram(i,a,s);a.forEach(u=>n.disposeIntermediateTensorInfo(u));let c=ve({inputs:{x:l},attrs:{shape:o},backend:n});return n.disposeIntermediateTensorInfo(l),c}function Xte(e,t,n){let s=E.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>ve({inputs:{x:a},attrs:{shape:[-1,v.sizeFromShape(a.shape.slice(t))]},backend:n})),outShape:s}}function G4(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s,a=v.parseAxisParam(r,t[0].shape)[0],o=E.computeOutShape(t.map(c=>c.shape),a);if(v.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(c=>v.sizeFromShape(c.shape)>0);if(i.length===1)return ws({inputs:{x:i[0]},backend:n});let l=i.map(c=>c.shape);return E.assertParamsConsistent(l,a),gc(i,a,n)}var Kte={kernelName:gi,backendName:"webgl",kernelFunc:G4},H4=class{constructor(e,t=!1,n=null,s=!1,r=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let a=e.padInfo.top,o=e.padInfo.left,i=e.strideHeight,l=e.strideWidth,c=e.dilationHeight,u=e.dilationWidth,d=e.filterHeight,p=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4,m=e.dataFormat==="channelsLast",g=m?1:2,A=m?2:3,x=m?3:1,y="",b="";n&&(s?y=`float activation(float a) { float b = getPreluActivationWeightsAtOutCoords(); ${n} }`:r?y=`float activation(float a) { float b = getLeakyreluAlphaAtOutCoords(); ${n} }`:y=` float activation(float x) { ${n} } `,b="result = activation(result);");let w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=` ${y} const ivec2 strides = ivec2(${i}, ${l}); const ivec2 pads = ivec2(${a}, ${o}); void main() { ivec4 coords = getOutputCoords(); int batch = coords[0]; int d2 = coords[${x}]; ivec2 xRCCorner = ivec2(coords[${g}], coords[${A}]) * strides - pads; int xRCorner = xRCCorner.x; int xCCorner = xRCCorner.y; // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; for (int wR = 0; wR < ${d}; wR++) { int xR = xRCorner + wR * ${c}; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${p}; wC++) { int xC = xCCorner + wC * ${u}; if (xC < 0 || xC >= ${e.inWidth}) { continue; } for (int d1 = 0; d1 < ${h}; d1 += 4) { vec4 wValues = vec4( getW(wR, wC, d1, d2), getW(wR, wC, d1 + 1, d2), getW(wR, wC, d1 + 2, d2), getW(wR, wC, d1 + 3, d2) ); if (${m}) { vec4 xValues = vec4( getX(batch, xR, xC, d1), getX(batch, xR, xC, d1 + 1), getX(batch, xR, xC, d1 + 2), getX(batch, xR, xC, d1 + 3) ); dotProd += dot(xValues, wValues); } else { vec4 xValues = vec4( getX(batch, d1, xR, xC), getX(batch, d1 + 1, xR, xC), getX(batch, d1 + 2, xR, xC), getX(batch, d1 + 3, xR, xC) ); dotProd += dot(xValues, wValues); } } if (${f===1}) { if (${m}) { dotProd += getX(batch, xR, xC, ${h}) * getW(wR, wC, ${h}, d2); } else { dotProd += getX(batch, ${h}, xR, xC) * getW(wR, wC, ${h}, d2); } } else if (${f===2}) { vec2 wValues = vec2( getW(wR, wC, ${h}, d2), getW(wR, wC, ${h} + 1, d2) ); if (${m}) { vec2 xValues = vec2( getX(batch, xR, xC, ${h}), getX(batch, xR, xC, ${h} + 1) ); dotProd += dot(xValues, wValues); } else { vec2 xValues = vec2( getX(batch, ${h}, xR, xC), getX(batch, ${h} + 1, xR, xC) ); dotProd += dot(xValues, wValues); } } else if (${f===3}) { vec3 wValues = vec3( getW(wR, wC, ${h}, d2), getW(wR, wC, ${h} + 1, d2), getW(wR, wC, ${h} + 2, d2) ); if (${m}) { vec3 xValues = vec3( getX(batch, xR, xC, ${h}), getX(batch, xR, xC, ${h} + 1), getX(batch, xR, xC, ${h} + 2) ); dotProd += dot(xValues, wValues); } else { vec3 xValues = vec3( getX(batch, ${h}, xR, xC), getX(batch, ${h} + 1, xR, xC), getX(batch, ${h} + 2, xR, xC) ); dotProd += dot(xValues, wValues); } } } } float result = dotProd; ${w} ${b} setOutput(result); } `}},Zte=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,n=e.padInfo.top,s=e.padInfo.left,r=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,l=e.dilationHeight,c=e.dilationWidth,u=e.filterDepth,d=e.filterHeight,p=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4;this.userCode=` const ivec3 strides = ivec3(${r}, ${a}, ${o}); const ivec3 pads = ivec3(${t}, ${n}, ${s}); void main() { ivec5 coords = getOutputCoords(); int batch = coords.x; int d2 = coords.u; ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; int xFCorner = xFRCCorner.x; int xRCorner = xFRCCorner.y; int xCCorner = xFRCCorner.z; // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get // y(yF, yR, yC, d2). ? = to be determined. : = across all // values in that axis. float dotProd = 0.0; for (int wF = 0; wF < ${u}; wF++) { int xF = xFCorner + wF * ${i}; if (xF < 0 || xF >= ${e.inDepth}) { continue; } for (int wR = 0; wR < ${d}; wR++) { int xR = xRCorner + wR * ${l}; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${p}; wC++) { int xC = xCCorner + wC * ${c}; if (xC < 0 || xC >= ${e.inWidth}) { continue; } for (int d1 = 0; d1 < ${h}; d1 += 4) { vec4 xValues = vec4( getX(batch, xF, xR, xC, d1), getX(batch, xF, xR, xC, d1 + 1), getX(batch, xF, xR, xC, d1 + 2), getX(batch, xF, xR, xC, d1 + 3) ); vec4 wValues = vec4( getW(wF, wR, wC, d1, d2), getW(wF, wR, wC, d1 + 1, d2), getW(wF, wR, wC, d1 + 2, d2), getW(wF, wR, wC, d1 + 3, d2) ); dotProd += dot(xValues, wValues); } if (${f===1}) { dotProd += getX(batch, xF, xR, xC, ${h}) * getW(wF, wR, wC, ${h}, d2); } else if (${f===2}) { vec2 xValues = vec2( getX(batch, xF, xR, xC, ${h}), getX(batch, xF, xR, xC, ${h} + 1) ); vec2 wValues = vec2( getW(wF, wR, wC, ${h}, d2), getW(wF, wR, wC, ${h} + 1, d2) ); dotProd += dot(xValues, wValues); } else if (${f===3}) { vec3 xValues = vec3( getX(batch, xF, xR, xC, ${h}), getX(batch, xF, xR, xC, ${h} + 1), getX(batch, xF, xR, xC, ${h} + 2) ); vec3 wValues = vec3( getW(wF, wR, wC, ${h}, d2), getW(wF, wR, wC, ${h} + 1, d2), getW(wF, wR, wC, ${h} + 2, d2) ); dotProd += dot(xValues, wValues); } } } } setOutput(dotProd); } `}},Yte=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=Bs(this.outputShape.length);let{dataFormat:n}=t,s=Hn(),r=n==="channelsLast",a=r?0:1,o=r?1:2,i=this.enableShapeUniforms?"if(blockIndex < outShape[1] && pos < outShape[0]) {":`if(blockIndex < ${e[1]} && pos < ${e[0]}) {`,l="";for(let c=0;c<=1;c++)for(let u=0;u<=1;u++)l+=` blockIndex = rc.y + ${u}; pos = rc.x + ${c}; ${i} offsetY = int(blockIndex / outWidth) * stride[0] - pad[0]; d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow); if(d0 < inputShape[${a}] && d0 >= 0) { // Use custom imod instead mod. On Intel GPU, mod may generate // unexpected value. // https://github.com/tensorflow/tfjs/issues/5447 offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1]; d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) / inChannels); if(d1 < inputShape[${o}] && d1 >= 0) { ch = imod(pos, inChannels); if (${r}) { innerDims = vec2(d1, ch); result[${c*2+u}] = getChannel( getA(d0, int(innerDims.x), int(innerDims.y)), innerDims); } else { innerDims = vec2(d0, d1); result[${c*2+u}] = getChannel( getA(ch, int(innerDims.x), int(innerDims.y)), innerDims); } } } } `;this.userCode=` void main() { ivec2 rc = getOutputCoords(); vec4 result = vec4(0); int blockIndex, pos, offsetY, d0, offsetX, d1, ch; vec2 innerDims; ${l} ${s.output} = result; } `}};function j4({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let l=e.shape,c=s.texData.get(e.dataId),u=n.inChannels,d=l[0]*l[1]*l[2],p=n.outChannels,h=n.dataFormat==="channelsLast",f=!1,m=!1,g,A=[];if(!((d===1||p===1)&&u>F4)&&c.isPacked&&h&&c.texture!=null&&l[2]%2!=0&&v.arraysEqual(c.shape.slice(-3),l.slice(-3))){let b=l[0]*l[1]*(l[2]+1),w={dataId:e.dataId,shape:[1,b,n.inChannels],dtype:e.dtype},k=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,v.assert(yp(c.shape,w.shape),()=>`packed reshape ${c.shape} to ${w.shape} isn't free`);let I=ve({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}});A.push(I);let N=Ym({a:w,b:I,backend:s,transposeA:f,transposeB:m,bias:r,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),R=s.texData.get(N.dataId);v.assert(R.isPacked,()=>"batchMatMul result is expected to be packed"),c.shape=k,R.shape=n.outShape,g=ws({inputs:{x:N},backend:s}),g.shape=n.outShape,A.push(N)}else{let b=h?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],w=ve({inputs:{x:e},backend:s,attrs:{shape:[1,b,n.inChannels]}}),k=ve({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}}),I=Ym({a:w,b:k,transposeA:f,transposeB:m,backend:s,bias:r,activation:i,preluActivationWeights:a,leakyreluAlpha:o});g=ve({inputs:{x:I},backend:s,attrs:{shape:n.outShape}}),A.push(w),A.push(k),A.push(I)}for(let b of A)s.disposeIntermediateTensorInfo(b);return g}function q4({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:l,filterHeight:c,inChannels:u,outWidth:d,outHeight:p,dataFormat:h}=n,f=h==="channelsLast",m=l*c*u,g=p*d,A=[m,g],x=!0,y=!1,b=[],w=ve({inputs:{x:e},backend:s,attrs:{shape:e.shape.slice(1)}}),k=ve({inputs:{x:t},backend:s,attrs:{shape:[1,m,v.sizeFromShape(t.shape)/m]}});b.push(w),b.push(k);let I=new Yte(A,n),N=[w.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],R=s.runWebGLProgram(I,[w],"float32",N),O=ve({inputs:{x:R},backend:s,attrs:{shape:[1,A[0],A[1]]}});b.push(R),b.push(O);let $=r!=null,P=a!=null,T=i==="leakyrelu",F=i?Xm(i,!0):null,U=new R4(O.shape,k.shape,[1,g,n.outChannels],x,y,$,F,P,T),q=[O,k];if(r&&q.push(r),P&&q.push(a),T){let Q=s.makeTensorInfo([],"float32",v.createScalarValue(o,"float32"));q.push(Q),b.push(Q)}let z=s.runWebGLProgram(U,q,"float32"),K=f?[1,p,d,n.outChannels]:[1,n.outChannels,p,d],J=ve({inputs:{x:z},backend:s,attrs:{shape:K}});b.push(z);for(let Q of b)s.disposeIntermediateTensorInfo(Q);return J}function Jte(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dataFormat:l,dilations:c,dimRoundingMode:u}=s,d=E.convertConv2DDataFormat(l),p=E.computeConv2DInfo(r.shape,a.shape,o,c,i,u,!1,d),h;if(p.filterHeight===1&&p.filterWidth===1&&p.dilationHeight===1&&p.dilationWidth===1&&p.strideHeight===1&&p.strideWidth===1&&(p.padInfo.type==="SAME"||p.padInfo.type==="VALID"))h=j4({x:r,filter:a,convInfo:p,backend:n});else if(Y().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)h=q4({x:r,filter:a,convInfo:p,backend:n});else{let m=new H4(p);h=n.runWebGLProgram(m,[r,a],"float32")}let f=ve({inputs:{x:h},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(h),f}var Qte={kernelName:Oa,backendName:"webgl",kernelFunc:Jte},ene=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,r=e.padInfo.left,a=e.dataFormat==="channelsLast";this.userCode=` void main() { ivec4 coords = getOutputCoords(); int wR = coords.x; int wC = coords.y; int d1 = coords.z; int d2 = coords.w; // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; for (int b = 0; b < ${e.batchSize}; b++) { for (int yR = 0; yR < ${e.outHeight}; yR++) { int xR = wR + yR * ${t} - ${s}; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int yC = 0; yC < ${e.outWidth}; yC++) { int xC = wC + yC * ${n} - ${r}; if (xC < 0 || xC >= ${e.inWidth}) { continue; } if (${a}) { float dyValue = getDy(b, yR, yC, d2); float xValue = getX(b, xR, xC, d1); dotProd += (xValue * dyValue); } else { float dyValue = getDy(b, d2, yR, yC); float xValue = getX(b, d1, xR, xC); dotProd += (xValue * dyValue); } } } } setOutput(dotProd); } `}},tne=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,r=e.strideWidth,a=e.dataFormat==="channelsLast",o=t-1-e.padInfo.top,i=n-1-e.padInfo.left,l=a?1:2,c=a?2:3,u=a?3:1;this.userCode=` const ivec2 pads = ivec2(${o}, ${i}); void main() { ivec4 coords = getOutputCoords(); int batch = coords[0]; int d1 = coords[${u}]; ivec2 dyCorner = ivec2(coords[${l}], coords[${c}]) - pads; int dyRCorner = dyCorner.x; int dyCCorner = dyCorner.y; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; for (int wR = 0; wR < ${t}; wR++) { float dyR = float(dyRCorner + wR) / ${s}.0; if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); int wRPerm = ${t} - 1 - wR; for (int wC = 0; wC < ${n}; wC++) { float dyC = float(dyCCorner + wC) / ${r}.0; if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); int wCPerm = ${n} - 1 - wC; for (int d2 = 0; d2 < ${e.outChannels}; d2++) { if (${a}) { float xValue = getDy(batch, idyR, idyC, d2); float wValue = getW(wRPerm, wCPerm, d1, d2); dotProd += xValue * wValue; } else { float xValue = getDy(batch, d2, idyR, idyC); float wValue = getW(wRPerm, wCPerm, d1, d2); dotProd += xValue * wValue; } } } } setOutput(dotProd); } `}},nne=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,r=e.padInfo.front,a=e.padInfo.top,o=e.padInfo.left;this.userCode=` void main() { ivec5 coords = getOutputCoords(); int wF = coords.x; int wR = coords.y; int wC = coords.z; int d1 = coords.w; int d2 = coords.u; float dotProd = 0.0; for (int b = 0; b < ${e.batchSize}; b++) { for (int yF = 0; yF < ${e.outDepth}; yF++) { int xF = wF + yF * ${t} - ${r}; if (xF < 0 || xF >= ${e.inDepth}) { continue; } for (int yR = 0; yR < ${e.outHeight}; yR++) { int xR = wR + yR * ${n} - ${a}; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int yC = 0; yC < ${e.outWidth}; yC++) { int xC = wC + yC * ${s} - ${o}; if (xC < 0 || xC >= ${e.inWidth}) { continue; } float dyValue = getDy(b, yF, yR, yC, d2); float xValue = getX(b, xF, xR, xC, d1); dotProd += (xValue * dyValue); } } } } setOutput(dotProd); } `}},sne=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,r=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=t-1-e.padInfo.front,l=n-1-e.padInfo.top,c=s-1-e.padInfo.left;this.userCode=` const ivec3 pads = ivec3(${i}, ${l}, ${c}); void main() { ivec5 coords = getOutputCoords(); int batch = coords.x; int d1 = coords.u; ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; int dyFCorner = dyCorner.x; int dyRCorner = dyCorner.y; int dyCCorner = dyCorner.z; float dotProd = 0.0; for (int wF = 0; wF < ${t}; wF++) { float dyF = float(dyFCorner + wF) / ${r}.0; if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) { continue; } int idyF = int(dyF); int wFPerm = ${t} - 1 - wF; for (int wR = 0; wR < ${n}; wR++) { float dyR = float(dyRCorner + wR) / ${a}.0; if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); int wRPerm = ${n} - 1 - wR; for (int wC = 0; wC < ${s}; wC++) { float dyC = float(dyCCorner + wC) / ${o}.0; if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); int wCPerm = ${s} - 1 - wC; for (int d2 = 0; d2 < ${e.outChannels}; d2++) { float xValue = getDy(batch, idyF, idyR, idyC, d2); float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2); dotProd += xValue * wValue; } } } } setOutput(dotProd); } `}};function rne(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:o,pad:i,dataFormat:l,dimRoundingMode:c,filterShape:u}=s,d=E.convertConv2DDataFormat(l),p=E.computeConv2DInfo(r.shape,u,o,1,i,c,!1,d),h=new ene(p);return n.runWebGLProgram(h,[r,a],"float32")}var ane={kernelName:Nh,backendName:"webgl",kernelFunc:rne};function one(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{inputShape:o,strides:i,pad:l,dataFormat:c,dimRoundingMode:u}=s,d=E.convertConv2DDataFormat(c),p=E.computeConv2DInfo(o,a.shape,i,1,l,u,!1,d),h=new tne(p);return n.runWebGLProgram(h,[r,a],"float32")}var ine={kernelName:Ma,backendName:"webgl",kernelFunc:one};function lne(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dilations:l}=s,c=E.computeConv3DInfo(r.shape,a.shape,o,l,i),u=new Zte(c);return n.runWebGLProgram(u,[r,a],"float32")}var une={kernelName:ud,backendName:"webgl",kernelFunc:lne};function cne(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:o,pad:i,filterShape:l}=s,c=E.computeConv3DInfo(r.shape,l,o,1,i),u=new nne(c);return n.runWebGLProgram(u,[r,a],"float32")}var dne={kernelName:Eh,backendName:"webgl",kernelFunc:cne};function pne(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{pad:o,strides:i,inputShape:l}=s,c=E.computeConv3DInfo(l,a.shape,i,1,o),u=new sne(c);return n.runWebGLProgram(u,[r,a],"float32")}var hne={kernelName:Rh,backendName:"webgl",kernelFunc:pne},fne=E4+` return cos(x); `,mne=st({opSnippet:fne}),gne={kernelName:za,backendName:"webgl",kernelFunc:mne},Ane=` float e2x = exp(-x); return (e2x + 1.0 / e2x) / 2.0; `,yne=st({opSnippet:Ane}),xne={kernelName:La,backendName:"webgl",kernelFunc:yne},bne=class{constructor(e,t,n,s,r){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[a,o,i,l]=e,[c]=t,[u,d]=n;this.outputShape=[c,u,d,l];let p=s==="bilinear"?1:0,[h,f]=[`${o-1}.0`,`${i-1}.0`],[m,g,A]=u>1?[`${(o-1)/(u-1)}`,"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${h}`],[x,y,b]=d>1?[`${(i-1)/(d-1)}`,"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=` const float height_ratio = float(${m}); const float width_ratio = float(${x}); void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int y = coords[1]; int x = coords[2]; int d = coords[3]; // get box vals float y1 = getBoxes(b,0); float x1 = getBoxes(b,1); float y2 = getBoxes(b,2); float x2 = getBoxes(b,3); // get image in batch index int bInd = round(getBoxInd(b)); if(bInd < 0 || bInd >= ${a}) { return; } float height_scale = ${g}; float width_scale = ${y}; float in_y = ${A}; if( in_y < 0.0 || in_y > ${h} ) { setOutput(float(${r})); return; } float in_x = ${b}; if( in_x < 0.0 || in_x > ${f} ) { setOutput(float(${r})); return; } vec2 sourceFracIndexCR = vec2(in_x,in_y); if(${p} == 1) { // Compute the four integer indices. ivec2 sourceFloorCR = ivec2(sourceFracIndexCR); ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR)); float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d); float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d); float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d); float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d); vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR); float top = topLeft + (topRight - topLeft) * fracCR.x; float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x; float newValue = top + (bottom - top) * fracCR.y; setOutput(newValue); } else { // Compute the coordinators of nearest neighbor point. ivec2 sourceNearestCR = ivec2(floor( sourceFracIndexCR + vec2(0.5,0.5))); float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d); setOutput(newValue); } } `}},vne=e=>{let{inputs:t,backend:n,attrs:s}=e,{image:r,boxes:a,boxInd:o}=t,{cropSize:i,method:l,extrapolationValue:c}=s,u=new bne(r.shape,a.shape,i,l,c);return n.runWebGLProgram(u,[r,a,o],"float32")},wne={kernelName:yi,backendName:"webgl",kernelFunc:vne},X4=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}],this.outputShape=e;let s=e.length,r=t?"0.0":`getX(${K4(s,"coords")})`,a=e[e.length-1],o="",i="";t?(o=n?`end != ${a-1}`:"end != 0",i=n?"end + 1":"end - 1"):(o=n?`end + pow2 < ${a}`:"end >= pow2",i=n?"end + pow2":"end - pow2"),this.userCode=` void main() { ${xt(s)} coords = getOutputCoords(); int end = ${Z4(s,"coords")}; float val = ${r}; int pow2 = int(pow(2.0, index)); if (${o}) { int idx = ${i}; ${Z4(s,"coords")} = idx; val += getX(${K4(s,"coords")}); } setOutput(val); } `}};function K4(e,t){if(e===1)return`${t}`;if(e===2)return`${t}.x, ${t}.y`;if(e===3)return`${t}.x, ${t}.y, ${t}.z`;if(e===4)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}function Z4(e,t){if(e===1)return`${t}`;if(e===2)return`${t}.y`;if(e===3)return`${t}.z`;if(e===4)return`${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}function kne(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:o,reverse:i}=s,l=r.shape.length,c=E.getAxesPermutation([a],l),u=r;c!=null&&(u=qn({inputs:{x:r},backend:n,attrs:{perm:c}}));let d=E.getInnerMostAxes(1,l)[0];if(d!==l-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${r.shape.length-1} but got axis=${a}`);let p=u.shape[d],h=ws({inputs:{x:u},backend:n});for(let f=0;f<=Math.ceil(Math.log2(p))-1;f++){let m=new X4(u.shape,!1,i),g=[[f]],A=h;h=n.runWebGLProgram(m,[h],h.dtype,g),n.disposeIntermediateTensorInfo(A)}if(o){let f=new X4(u.shape,o,i),m=h;h=n.runWebGLProgram(f,[h],h.dtype),n.disposeIntermediateTensorInfo(m)}if(c!=null){let f=E.getUndoAxesPermutation(c),m=qn({inputs:{x:h},backend:n,attrs:{perm:f}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(u),m}return h}var Sne={kernelName:Ai,backendName:"webgl",kernelFunc:kne};function Ine(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:o,binaryOutput:i}=s;if(r.shape.length===1){let l=n.readSync(r.dataId),c=n.readSync(a.dataId),u=h4(l,c,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,u)}else if(r.shape.length===2){let l=n.bufferSync(r),c=n.bufferSync(a),u=OJ(l,c,o,i);return n.makeTensorInfo(u.shape,a.dtype,u.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}var Cne={kernelName:$h,backendName:"webgl",kernelFunc:Ine},Tne=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int h = ${this.getHeightCoordString()}; int w = ${this.getWidthCoordString()}; int d = ${this.getDepthCoordString()}; int in_h = h / ${t}; int offset_h = imod(h, ${t}); int in_w = w / ${t}; int offset_w = imod(w, ${t}); int offset_d = (offset_h * ${t} + offset_w) * ${this.getOutputDepthSize()}; int in_d = d + offset_d; float result = ${this.getInputSamplingString()}; setOutput(result); } `}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}};function Nne(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockSize:a,dataFormat:o}=s,i=r.shape[0],l=o==="NHWC"?r.shape[1]:r.shape[2],c=o==="NHWC"?r.shape[2]:r.shape[3],u=o==="NHWC"?r.shape[3]:r.shape[1],d=l*a,p=c*a,h=u/(a*a),f=o==="NHWC"?[i,d,p,h]:[i,h,d,p],m=new Tne(f,a,o);return n.runWebGLProgram(m,[r],r.dtype)}var Ene={kernelName:xi,backendName:"webgl",kernelFunc:Nne},Y4=class{constructor(e,t=!1,n=null,s=!1,r=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Bs(this.outputShape.length);let a=e.filterHeight,o=e.filterWidth,i=e.outChannels/e.inChannels,l="",c="";n&&(s?l=`float activation(float a) { float b = getPreluActivationWeightsAtOutCoords(); ${n} }`:r?l=`float activation(float a) { float b = getLeakyreluAlphaAtOutCoords(); ${n} }`:l=` float activation(float x) { ${n} } `,c="result = activation(result);");let u=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=` ${l} void main() { ivec4 coords = getOutputCoords(); int batch = coords.x; ivec2 xRCCorner = coords.yz * strides - pads; int d2 = coords.w; int d1 = d2 / ${i}; int q = d2 - d1 * ${i}; int xRCorner = xRCCorner.x; int xCCorner = xRCCorner.y; // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations. for (int wR = 0; wR < ${a}; wR++) { int xR = xRCorner + wR * dilations[0]; if (xR < 0 || xR >= inDims[0]) { continue; } for (int wC = 0; wC < ${o}; wC++) { int xC = xCCorner + wC * dilations[1]; if (xC < 0 || xC >= inDims[1]) { continue; } float xVal = getX(batch, xR, xC, d1); float wVal = getW(wR, wC, d1, q); dotProd += xVal * wVal; } } float result = dotProd; ${u} ${c} setOutput(result); } `}},J4=class{constructor(e,t=!1,n=null,s=!1,r=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=Bs(this.outputShape.length);let a=e.outChannels/e.inChannels,o=e.padInfo.left,i=e.strideWidth,l=e.dilationWidth,c=e.filterHeight,u=e.filterWidth,d=u,p=` int xR; int xC; int xCOffset; vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g=0 && xR < inDims[0]) { `;for(let g=0;g<(d+1)/2;g++){let A=g*2;if(p+=` xC = xCCorner + ${A*l}; `,i===1){if(A= 0 && xCOffset < inDims[1] && xTexelC${A}Ready == 0) { xTexelC${A} = getX(batch, xR, xCOffset, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if (xCOffset + 1 >= inDims[1]) { xTexelC${A}.zw = vec2(0.0); } xTexelC${A}Ready = 1; } `,l===1&&A>0?p+=` xC${A} = vec4(xTexelC${A-2}.zw, xTexelC${A}.xy); `:p+=` xCOffset = xC + 1 - 2; if (xCOffset >= 0 && xCOffset < inDims[1]) { previous = getX(batch, xR, xCOffset, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if (xCOffset + 1 >= inDims[1]) { previous.zw = vec2(0.0); } xC${A} = vec4(previous.zw, xTexelC${A}.xy); } else { xC${A} = vec4(0.0, 0.0, xTexelC${A}.xy); } `):p+=` if (xC >= 0 && xC < inDims[1] && xTexelC${A}Ready == 0) { xTexelC${A} = getX(batch, xR, xC, d1); if (xC + 1 >= inDims[1]) { xTexelC${A}.zw = vec2(0.0); } xTexelC${A}Ready = 1; } xC${A} = xTexelC${A}; `,A+1= 0 && xCOffset < inDims[1] && xTexelC${A+1}Ready == 0) { xTexelC${A+1} = getX(batch, xR, xCOffset, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if (xCOffset + 1 >= inDims[1]) { xTexelC${A+1}.zw = vec2(0.0); } xTexelC${A+1}Ready = 1; } `,l>1&&(p+=` xCOffset -= 2; if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${A}Ready == 0) { xTexelC${A} = getX(batch, xR, xCOffset, d1); xTexelC${A}Ready = 1; } `),p+=` xC${A+1} = vec4(xTexelC${A}.zw, xTexelC${A+1}.xy); `):x===1?p+=` xC${A+1} = xTexelC${A}; `:p+=` xCOffset = xC + ${x}; if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${A+1}Ready == 0) { xTexelC${A+1} = getX(batch, xR, xCOffset, d1); if (xCOffset + 1 >= inDims[1]) { xTexelC${A+1}.zw = vec2(0.0); } xTexelC${A+1}Ready = 1; } xC${A+1} = xTexelC${A+1}; `}}else A= 0 && xCOffset < inDims[1] && xTexelC${A}Ready == 0) { xTexelC${A} = getX(batch, xR, xCOffset, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if (xCOffset + 1 >= inDims[1]) { xTexelC${A}.zw = vec2(0.0); } xTexelC${A}Ready = 1; } if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${A+1}Ready == 0) { xTexelC${A+1} = getX(batch, xR, xC + 1, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if (xC + 2 >= inDims[1]) { xTexelC${A+1}.zw = vec2(0.0); } xTexelC${A+1}Ready = 1; } xC${A} = vec4(xTexelC${A}.zw, xTexelC${A+1}.zw); `,A+1= 0 && xCOffset < inDims[1]) { final = getX(batch, xR, xCOffset, d1); } xC${A+1} = vec4(xTexelC${A+1}.xy, final.xy); `)):(p+=` if(xC >= 0 && xC < inDims[1] && xTexelC${A}Ready == 0) { xTexelC${A} = getX(batch, xR, xC, d1); if (xC + 1 >= inDims[1]) { xTexelC${A}.zw = vec2(0.0); } xTexelC${A}Ready = 1; } xCOffset = xC + strides[1]; if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${A+1}Ready == 0) { xTexelC${A+1} = getX(batch, xR, xCOffset, d1); if (xCOffset + 1 >= inDims[1]) { xTexelC${A+1}.zw = vec2(0.); } xTexelC${A+1}Ready = 1; } xC${A} = vec4( xTexelC${A}.xy, xTexelC${A+1}.xy); `,A+1`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);let d=E.computeConv2DInfo(r.shape,a.shape,o,u,i,c,!0),p;Y().getBool("WEBGL_PACK_DEPTHWISECONV")&&d.strideWidth<=2&&d.outChannels/d.inChannels==1?p=new J4(d):p=new Y4(d);let h=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];return n.runWebGLProgram(p,[r,a],"float32",h)}var $ne={kernelName:Ba,backendName:"webgl",kernelFunc:Rne},_ne=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,r=e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode=` void main() { ivec4 coords = getOutputCoords(); int wR = coords.x; int wC = coords.y; int d1 = coords.z; int dm = coords.w; int d2 = d1 * ${a} + dm; float dotProd = 0.0; // TO DO: Vec4 over the batch size for (int b = 0; b < ${e.batchSize}; b++) { for (int yR = 0; yR < ${e.outHeight}; yR++) { int xR = wR + yR * ${t} - ${s}; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int yC = 0; yC < ${e.outWidth}; yC++) { int xC = wC + yC * ${n} - ${r}; if (xC < 0 || xC >= ${e.inWidth}) { continue; } float dyValue = getDy(b, yR, yC, d2); float xValue = getX(b, xR, xC, d1); dotProd += (xValue * dyValue); } } } setOutput(dotProd); } `}},Dne=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,r=e.strideWidth,a=t-1-e.padInfo.top,o=n-1-e.padInfo.left,i=e.outChannels/e.inChannels;this.userCode=` const ivec2 pads = ivec2(${a}, ${o}); void main() { ivec4 coords = getOutputCoords(); int batch = coords[0]; int d1 = coords[3]; ivec2 dyCorner = coords.yz - pads; int dyRCorner = dyCorner.x; int dyCCorner = dyCorner.y; float dotProd = 0.0; for (int wR = 0; wR < ${t}; wR++) { float dyR = float(dyRCorner + wR) / ${s}.0; if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); int wRPerm = ${t} - 1 - wR; for (int wC = 0; wC < ${n}; wC++) { float dyC = float(dyCCorner + wC) / ${r}.0; if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); int wCPerm = ${n} - 1 - wC; // TO DO: Vec4 over the channelMul for (int dm = 0; dm < ${i}; dm++) { int d2 = d1 * ${i} + dm; float xValue = getDy(batch, idyR, idyC, d2); float wValue = getW(wRPerm, wCPerm, d1, dm); dotProd += xValue * wValue; } } } setOutput(dotProd); } `}};function Pne(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:o,dilations:i,pad:l,dimRoundingMode:c,filterShape:u}=s,d=E.computeConv2DInfo(r.shape,u,o,i,l,c,!0),p=new _ne(d);return n.runWebGLProgram(p,[r,a],"float32")}var Fne={kernelName:_h,backendName:"webgl",kernelFunc:Pne};function One(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{strides:o,dilations:i,pad:l,dimRoundingMode:c,inputShape:u}=s,d=E.computeConv2DInfo(u,a.shape,o,i,l,c,!0),p=new Dne(d);return n.runWebGLProgram(p,[r,a],"float32")}var Mne={kernelName:Dh,backendName:"webgl",kernelFunc:One},zne=class{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=` void main() { ivec2 coords = getOutputCoords(); float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0; setOutput(val); } `}};function Lne(e){let{inputs:t,backend:n}=e,{x:s}=t,r=[...s.shape,...s.shape],a=v.sizeFromShape(s.shape),o=ve({inputs:{x:s},backend:n,attrs:{shape:[a]}}),i=new zne(a),l=n.runWebGLProgram(i,[o],o.dtype),c=ve({inputs:{x:l},backend:n,attrs:{shape:r}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),c}var Bne={kernelName:Ph,backendName:"webgl",kernelFunc:Lne},Wne=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:n,padInfo:s,strideHeight:r,strideWidth:a,filterHeight:o,filterWidth:i,dilationHeight:l,dilationWidth:c}=e,{top:u,left:d}=s;this.userCode=` const ivec2 strides = ivec2(${r}, ${a}); const ivec2 pads = ivec2(${u}, ${d}); const float neg_infinity = -3.4e38; void main() { ivec4 coords = getOutputCoords(); int batch = coords.x; int d1 = coords.w; ivec2 outTopLeftCorner = coords.yz * strides - pads; int hBeg = outTopLeftCorner.x; int wBeg = outTopLeftCorner.y; float curVal = neg_infinity; for (int h = 0; h < ${o}; h++) { int hIn = hBeg + h * ${l}; if (hIn >= 0 && hIn < ${t}) { for (int w = 0; w < ${i}; w++) { int wIn = wBeg + w * ${c}; if (wIn >= 0 && wIn < ${n}) { float xVal = getX(batch, hIn, wIn, d1); float wVal = getW(h, w, d1); float val = xVal + wVal; if (val > curVal) { curVal = val; } } } } } float result = curVal; setOutput(result); } `}};function Vne(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dilations:l}=s,c=E.computeDilation2DInfo(r.shape,a.shape,o,i,"NHWC",l),u,d=new Wne(c);u=n.runWebGLProgram(d,[r,a],"float32");let p=ve({inputs:{x:u},backend:n,attrs:{shape:c.outShape}});return n.disposeIntermediateTensorInfo(u),p}var Une={kernelName:cd,backendName:"webgl",kernelFunc:Vne};function Gne(e){let{inputs:t,backend:n,attrs:s}=e,{equation:r}=s,a=t,{allDims:o,summedDims:i,idDims:l}=E.decodeEinsumEquation(r,a.length);E.checkEinsumDimSizes(o.length,l,a);let{path:c,steps:u}=E.getEinsumComputePath(i,l),d=u.length,p=null,h=o.length,f=[];for(let m=0;m=0&&(p=Zm({inputs:{x:p},backend:n,attrs:{axis:c[m]-(o.length-h),keepDims:!1}}),f.push(p)),h--)}for(let m of f)m!==p&&n.disposeIntermediateTensorInfo(m);return p}var Hne={kernelName:dd,backendName:"webgl",kernelFunc:Gne},jne="return (x >= 0.0) ? x : (exp(x) - 1.0);",qne=` vec4 result; result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0); result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0); result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0); result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0); return result; `,Xne=st({opSnippet:jne,packedOpSnippet:qne}),Kne={kernelName:Va,backendName:"webgl",kernelFunc:Xne},Zne="return (b >= 1.0) ? a : a * (b + 1.0);",Yne=` vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.))); return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0)))); `,Jne=e=>{let{inputs:t,backend:n}=e,{dy:s,y:r}=t,a=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new vp(Yne,s.shape,r.shape):new fc(Zne,s.shape,r.shape);return n.runWebGLProgram(a,[s,r],s.dtype)},Qne={kernelName:Mh,backendName:"webgl",kernelFunc:Jne},ese=` return vec4(equal(a, b)); `,tse="return float(a == b);",nse=Tn({opSnippet:tse,packedOpSnippet:ese,dtype:"bool",cpuKernelImpl:LJ}),sse={kernelName:bi,backendName:"webgl",kernelFunc:nse},rse=` // Error function is calculated approximately with elementary function. // See "Handbook of Mathematical Functions with Formulas, // Graphs, and Mathematical Tables", Abramowitz and Stegun. float p = ${E.ERF_P}; float a1 = ${E.ERF_A1}; float a2 = ${E.ERF_A2}; float a3 = ${E.ERF_A3}; float a4 = ${E.ERF_A4}; float a5 = ${E.ERF_A5}; float sign = sign(x); x = abs(x); float t = 1.0 / (1.0 + p * x); return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x)); `,ase=st({opSnippet:rse}),ose={kernelName:Au,backendName:"webgl",kernelFunc:ase},Q4="return exp(x);",eC=st({opSnippet:Q4,packedOpSnippet:Q4,cpuKernelImpl:BJ,dtype:"float32"}),ise={kernelName:Ua,backendName:"webgl",kernelFunc:eC};function Cx(e){let{inputs:t,attrs:n,backend:s}=e,{dim:r}=n,{input:a}=t,o=a.shape.length,i=a.shape.slice(),l=r;return r<0&&(v.assert(-(o+1)<=r,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+r+1),i.splice(l,0,1),ve({inputs:{x:a},backend:s,attrs:{shape:i}})}var lse={kernelName:vi,backendName:"webgl",kernelFunc:Cx},tC="return exp(x) - 1.0;",use=st({opSnippet:tC,packedOpSnippet:tC,cpuKernelImpl:WJ}),cse={kernelName:wi,backendName:"webgl",kernelFunc:use},nC=class{constructor(e,t,n){this.variableNames=["real","imag"];let s=t[1];this.outputShape=t;let r=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,a=n?`${s}.0`:"1.0",o;if(e==="real")o="return real * expR - imag * expI;";else if(e==="imag")o="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=` const float exponentMultiplier = ${r}; float unaryOpComplex(float real, float expR, float imag, float expI) { ${o} } float mulMatDFT(int batch, int index) { float indexRatio = float(index) / float(${s}); float exponentMultiplierTimesIndexRatio = exponentMultiplier * indexRatio; float result = 0.0; for (int i = 0; i < ${s}; i++) { // x = (-2|2 * PI / N) * index * i; float x = exponentMultiplierTimesIndexRatio * float(i); float expR = cos(x); float expI = sin(x); float real = getReal(batch, i); float imag = getImag(batch, i); result += unaryOpComplex(real, expR, imag, expI) / ${a}; } return result; } void main() { ivec2 coords = getOutputCoords(); setOutput(mulMatDFT(coords[0], coords[1])); } `}};function sC(e,t,n){let s=n.texData.get(e.dataId),r=v.sizeFromShape(e.shape),a=e.shape[e.shape.length-1],o=r/a,i=ve({inputs:{x:e},backend:n,attrs:{shape:[o,a]}}),l=i.shape,c=new nC("real",l,t),u=new nC("imag",l,t),d=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:l},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:l}],p=n.runWebGLProgram(c,d,"float32"),h=n.runWebGLProgram(u,d,"float32"),f=qo({inputs:{real:p,imag:h},backend:n});n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h);let m=ve({inputs:{x:f},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(f),m}function dse(e){let{inputs:t,backend:n}=e,{input:s}=t;return sC(s,!1,n)}var pse={kernelName:zh,backendName:"webgl",kernelFunc:dse},hse=class{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode=` void main() { // Input can be obtained from uniform value. setOutput(value); } `}};function Sp(e){let{backend:t,attrs:n}=e,{shape:s,value:r}=n,{dtype:a}=n;if(a=a||v.inferDtype(r),a==="string"){let o=v.getArrayFromDType(a,v.sizeFromShape(s));return o.fill(r),t.makeTensorInfo(s,a,o)}else{let o=new hse(s,r),i=[[r]];return t.runWebGLProgram(o,[],a,i)}}var fse={kernelName:yu,backendName:"webgl",kernelFunc:Sp},mse=class{constructor(e){this.variableNames=["Image"],this.outputShape=[];let t=e[2];this.outputShape=e,this.userCode=` void main() { ivec4 coords = getOutputCoords(); int x = coords[2]; int coordX = ${t} - x - 1; float outputValue; if(coordX >= 0 && coordX < ${t}) { outputValue = getImage(coords[0], coords[1], coordX, coords[3]); } else { outputValue = getImage(coords[0], coords[1], coords[2], coords[3]); } setOutput(outputValue); } `}},gse={kernelName:ki,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,s=t,r=new mse(n.shape);return s.runWebGLProgram(r,[n],n.dtype)}},rC="return floor(x);",Ase=st({opSnippet:rC,packedOpSnippet:rC,cpuKernelImpl:VJ}),yse={kernelName:Ga,backendName:"webgl",kernelFunc:Ase},xse=` float s = sign(a) * sign(b); int ia = round(a); int ib = round(b); if (ib != 0) { // Windows (D3D) wants guaranteed non-zero int division at compile-time. return float(idiv(ia, ib, s)); } else { return NAN; } `,bse=` ivec4 ia = round(a); ivec4 ib = round(b); bvec4 cond = notEqual(ib, ivec4(0)); ivec4 result = ivec4(0); vec4 s = sign(a) * sign(b); // Windows (D3D) wants guaranteed non-zero int division at compile-time. if (cond[0]) { result[0] = idiv(ia[0], ib[0], s[0]); } if (cond[1]) { result[1] = idiv(ia[1], ib[1], s[1]); } if (cond[2]) { result[2] = idiv(ia[2], ib[2], s[2]); } if (cond[3]) { result[3] = idiv(ia[3], ib[3], s[3]); } return vec4(result); `,vse=Tn({opSnippet:xse,packedOpSnippet:bse,dtype:"int32"}),wse={kernelName:Ha,backendName:"webgl",kernelFunc:vse},kse=class{constructor(e){this.variableNames=["A"];let t=Hn(),[n,s]=e;this.outputShape=e,this.userCode=` void main() { ivec3 coords = getOutputCoords(); int texR = coords[0]; int texC = coords[1]; int depth = coords[2]; vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}.0, ${n}.0); vec4 values = ${t.texture2D}(A, uv); float value; if (depth == 0) { value = values.r; } else if (depth == 1) { value = values.g; } else if (depth == 2) { value = values.b; } else if (depth == 3) { value = values.a; } setOutput(floor(value * 255.0 + 0.5)); } `}},Sse=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=Hn(),[n,s]=e;this.outputShape=e,this.userCode=` void main() { ivec3 coords = getOutputCoords(); int texR = coords[0]; int texC = coords[1]; int depth = coords[2]; vec4 result = vec4(0.); for(int row=0; row<=1; row++) { for(int col=0; col<=1; col++) { texC = coords[1] + row; depth = coords[2] + col; vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}.0, ${n}.0); vec4 values = ${t.texture2D}(A, uv); float value; if (depth == 0) { value = values.r; } else if (depth == 1) { value = values.g; } else if (depth == 2) { value = values.b; } else if (depth == 3) { value = values.a; } result[row * 2 + col] = floor(value * 255.0 + 0.5); } } ${t.output} = result; } `}},Ise={kernelName:bd,backendName:"webgl",kernelFunc:Cse},Ac;function Cse(e){let{inputs:t,backend:n,attrs:s}=e,{pixels:r}=t,{numChannels:a}=s,o=typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement,[l,c]=o?[r.videoWidth,r.videoHeight]:[r.width,r.height],u=[c,l],d=[c,l,a];(i||o)&&(Ac==null&&(Ac=document.createElement("canvas").getContext("2d")),Ac.canvas.width=l,Ac.canvas.height=c,Ac.drawImage(r,0,0,l,c),r=Ac.canvas);let p=n.makeTensorInfo(u,"int32");n.texData.get(p.dataId).usage=zs.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),r);let h=Y().getBool("WEBGL_PACK")?new Sse(d):new kse(d),f=n.runWebGLProgram(h,[p],"int32");return n.disposeData(p.dataId),f}function Tse(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=s,m=E.convertConv2DDataFormat(u),g=E.computeConv2DInfo(r.shape,a.shape,l,d,c,p,!1,m),A,x=[];if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))A=j4({x:r,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else if(Y().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)A=q4({x:r,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else{let b=o!=null,w=i!=null,k=h==="leakyrelu",I=h?Xm(h,!1):null,N=new H4(g,b,I,w,k),R=[r,a];if(o&&R.push(o),i&&R.push(i),k){let O=n.makeTensorInfo([],"float32",v.createScalarValue(f,"float32"));R.push(O),x.push(O)}A=n.runWebGLProgram(N,R,"float32")}let y=ve({inputs:{x:A},backend:n,attrs:{shape:g.outShape}});return x.push(A),x.forEach(b=>n.disposeIntermediateTensorInfo(b)),y}var Nse={kernelName:ko,backendName:"webgl",kernelFunc:Tse};function Ese(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dilations:u,dimRoundingMode:d,activation:p,leakyreluAlpha:h}=s,f=[],m=u;m==null&&(m=[1,1]),v.assert(E.eitherStridesOrDilationsAreOne(l,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`);let g=E.computeConv2DInfo(r.shape,a.shape,l,m,c,d,!0),A=Y().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,x=p?Xm(p,A):null,y=[r,a],b=o!=null,w=i!=null,k=p==="leakyrelu";if(b&&y.push(o),w&&y.push(i),k){let O=n.makeTensorInfo([],"float32",v.createScalarValue(h,"float32"));y.push(O),f.push(O)}let I;A?I=new J4(g,b,x,w,k):I=new Y4(g,b,x,w,k);let N=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],R=n.runWebGLProgram(I,y,"float32",N);return f.forEach(O=>n.disposeIntermediateTensorInfo(O)),R}var Rse={kernelName:So,backendName:"webgl",kernelFunc:Ese},$se=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let s=xt(t.length),r=xt(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode=` ${s} strides = ${s}(${this.strides}); void main() { ${r} coords = getOutputCoords(); int flattenIndex = 0; for (int j = 0; j < ${this.sliceDim}; j++) { int index = round(getIndices(coords[0], j)); flattenIndex += index * ${a}; } setOutput(getX(flattenIndex, coords[1])); } `}};function _se(e){let{inputs:t,backend:n}=e,{params:s,indices:r}=t,a=r.shape,o=a[a.length-1],i=v.sizeFromShape(s.shape),[l,c,u,d]=E.prepareAndValidate(s,r),p=ve({inputs:{x:r},backend:n,attrs:{shape:[c,o]}}),h=ve({inputs:{x:s},backend:n,attrs:{shape:[v.sizeFromShape(s.shape)/u,u]}});if(n.shouldExecuteOnCPU([s,r])||s.dtype==="string"){let A=n.readSync(r.dataId),x=n.bufferSync(s),y=UJ(A,x,s.dtype,c,o,u,d,s.shape,i);return n.makeTensorInfo(l,s.dtype,y.values)}let f=new $se(o,d,[c,u]),m=n.runWebGLProgram(f,[h,p],h.dtype),g=ve({inputs:{x:m},backend:n,attrs:{shape:l}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),g}var Dse={kernelName:Ii,backendName:"webgl",kernelFunc:_se},Pse=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=xt(this.rank),s=Fse(e,2);this.userCode=` void main() { ${n} resRC = getOutputCoords(); setOutput(getA(${s})); } `}};function Fse(e,t){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let r=0;r=0,()=>`GatherV2: the index value ${w} is not in [0, ${u-1}]`)}let d=E.segment_util.collectGatherOpShapeInfo(r,a,l,i),p=v.sizeFromShape(a.shape),h=[],f=ve({inputs:{x:r},backend:n,attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]}}),m=ve({inputs:{x:a},backend:n,attrs:{shape:[d.batchSize,p/d.batchSize]}});h.push(f),h.push(m);let g=[d.batchSize,d.outerSize,p/d.batchSize,d.sliceSize];if(n.shouldExecuteOnCPU([r,a])||r.dtype==="string"){let b=n.bufferSync(m),w=n.bufferSync(f),k=GJ(w,b,g);return h.forEach(I=>n.disposeIntermediateTensorInfo(I)),n.makeTensorInfo(d.outputShape,k.dtype,k.values)}let A=new Pse(f.shape,g),x=n.runWebGLProgram(A,[f,m],f.dtype);h.push(x);let y=ve({inputs:{x},backend:n,attrs:{shape:d.outputShape}});return h.forEach(b=>n.disposeIntermediateTensorInfo(b)),y}var Ose={kernelName:Si,backendName:"webgl",kernelFunc:aC},Mse="return float(a > b);",zse=` return vec4(greaterThan(a, b)); `,Lse=Tn({opSnippet:Mse,packedOpSnippet:zse,cpuKernelImpl:HJ,dtype:"bool"}),Bse={kernelName:Ci,backendName:"webgl",kernelFunc:Lse},Wse="return float(a >= b);",Vse=` return vec4(greaterThanEqual(a, b)); `,Use=Tn({opSnippet:Wse,packedOpSnippet:Vse,dtype:"bool",cpuKernelImpl:jJ}),Gse={kernelName:qa,backendName:"webgl",kernelFunc:Use};function Hse(e){let{inputs:t,backend:n}=e,{input:s}=t;return sC(s,!0,n)}var jse={kernelName:Lh,backendName:"webgl",kernelFunc:Hse},qse="return float(!isnan(x) && !isinf(x));",Xse=st({opSnippet:qse,dtype:"bool"}),Kse={kernelName:xu,backendName:"webgl",kernelFunc:Xse},Zse="return float(isinf(x));",Yse=st({opSnippet:Zse,dtype:"bool"}),Jse={kernelName:bu,backendName:"webgl",kernelFunc:Yse},Qse="return float(isnan(x));",ere=st({opSnippet:Qse,dtype:"bool"}),tre={kernelName:vu,backendName:"webgl",kernelFunc:ere},nre="return float(a < b);",sre=` return vec4(lessThan(a, b)); `,rre=Tn({opSnippet:nre,packedOpSnippet:sre,cpuKernelImpl:qJ,dtype:"bool"}),are={kernelName:Ni,backendName:"webgl",kernelFunc:rre},ore="return float(a <= b);",ire=` return vec4(lessThanEqual(a, b)); `,lre=Tn({opSnippet:ore,packedOpSnippet:ire,cpuKernelImpl:XJ,dtype:"bool"}),ure={kernelName:Ei,backendName:"webgl",kernelFunc:lre};function cre(e){let{backend:t,attrs:n}=e,{start:s,stop:r,num:a}=n,o=KJ(s,r,a);return t.makeTensorInfo([o.length],"float32",o)}var dre={kernelName:Bh,backendName:"webgl",kernelFunc:cre},pre=`if (x < 0.0) return NAN; return log(x);`,hre=` vec4 result = log(x); vec4 isNaN = vec4(lessThan(x, vec4(0.0))); result.r = isNaN.r == 1.0 ? NAN : result.r; result.g = isNaN.g == 1.0 ? NAN : result.g; result.b = isNaN.b == 1.0 ? NAN : result.b; result.a = isNaN.a == 1.0 ? NAN : result.a; return result; `,fre=st({opSnippet:pre,packedOpSnippet:hre,cpuKernelImpl:ZJ}),mre={kernelName:Ka,backendName:"webgl",kernelFunc:fre},gre="return log(1.0 + x);",Are=st({opSnippet:gre}),yre={kernelName:wu,backendName:"webgl",kernelFunc:Are},xre="return float(a >= 1.0 && b >= 1.0);",bre=` return vec4( vec4(greaterThanEqual(a, vec4(1.0))) * vec4(greaterThanEqual(b, vec4(1.0)))); `,vre=Tn({opSnippet:xre,packedOpSnippet:bre,dtype:"bool"}),wre={kernelName:Ri,backendName:"webgl",kernelFunc:vre},kre="return float(!(x >= 1.0));",Sre=st({opSnippet:kre}),Ire={kernelName:ku,backendName:"webgl",kernelFunc:Sre},Cre="return float(a >= 1.0 || b >= 1.0);",Tre=` return min( vec4(greaterThanEqual(a, vec4(1.0))) + vec4(greaterThanEqual(b, vec4(1.0))), vec4(1.0)); `,Nre=Tn({opSnippet:Cre,packedOpSnippet:Tre,dtype:"bool"}),Ere={kernelName:hd,backendName:"webgl",kernelFunc:Nre},Rre=class{constructor(e,t,n,s,r){this.variableNames=["x"],this.outputShape=[];let a=t,o=e[3]-1;this.outputShape=e;let i,l=`float(${n}) + float(${s}) * sum`;r===.5?i=`inversesqrt(${l})`:r===1?i=`1.0/(${l})`:i=`exp(log(${l}) * float(-${r}));`,this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int r = coords[1]; int c = coords[2]; int d = coords[3]; float x = getX(b, r, c, d); float sum = 0.0; for (int j = -${a}; j <= ${a}; j++) { int idx = d + j; if (idx >= 0 && idx <= ${o}) { float z = getX(b, r, c, idx); sum += z * z; } } float val = x * ${i}; setOutput(val); } `}},$re=class{constructor(e,t,n,s,r){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let a=t,o=e[3]-1;this.outputShape=e;let i,l=`float(${n}) + float(${s}) * sum`;r===.5?i=`inversesqrt(${l})`:r===1?i=`1.0/(${l})`:i=`exp(log(${l}) * float(-${r}));`,this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords.x; int r = coords.y; int c = coords.z; int d = coords.w; bool hasNextCol = d < ${this.outputShape[3]}; bool hasNextRow = c < ${this.outputShape[2]}; vec4 sum = vec4(0.); vec4 xFragAtOutputCoords = getX(b, r, c, d); vec4 xAtOutputCoords = vec4( getChannel(xFragAtOutputCoords, vec2(c, d)), hasNextCol ? getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0, hasNextRow ? getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0, (hasNextRow && hasNextCol) ? getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0 ); int firstChannel = d - ${a}; vec2 cache = vec2(0.); if(firstChannel >= 0){ vec4 firstChannelFrag = getX(b, r, c, firstChannel); cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel)); if(hasNextRow){ cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel)); } } ivec2 depth = ivec2(d, d + 1); for (int j = - ${a}; j <= ${a}; j++) { ivec2 idx = depth + j; bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0)); bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${o})); bool depthInRange = aboveLowerBound.x && belowUpperBound.x; bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y; if(depthInRange || depthPlusOneInRange){ vec4 z = vec4(0.); vec4 xFragAtCurrentDepth; z.xz = cache.xy; if(depthPlusOneInRange && hasNextCol){ xFragAtCurrentDepth = idx.y != d ? getX(b, r, c, idx.y) : xFragAtOutputCoords; z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y)); if(hasNextRow){ z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y)); } } cache.xy = z.yw; sum += z * z; } } vec4 result = xAtOutputCoords * ${i}; setOutput(result); } `}},_re=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{depthRadius:a,bias:o,alpha:i,beta:l}=s,c=Y().getBool("WEBGL_PACK_NORMALIZATION")?new $re(r.shape,a,o,i,l):new Rre(r.shape,a,o,i,l);return n.runWebGLProgram(c,[r],r.dtype)},Dre={kernelName:fd,backendName:"webgl",kernelFunc:_re},Pre=class{constructor(e,t,n,s,r){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=s,this.beta=r,this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int r = coords[1]; int c = coords[2]; float result = 0.0; for (int d = 0; d < ${this.depth}; ++d) { int depthBegin = int(max(0.0, float(d - ${t}))); int depthEnd = int(min(float(${this.depth}), float(d + ${t} + 1))); const int MIN_DEPTH_BEGIN = 0; const int MAX_DEPTH_END = ${this.depth}; float norm = 0.0; for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) { if (k < depthBegin){ continue; } else if (k >= depthBegin && k < depthEnd) { norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k); } else { break; } } norm = float(${s}) * norm + float(${n}); for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){ if (k < depthBegin){ continue; } else if (k >= depthBegin && k < depthEnd){ float dyi = -2.0 * float(${s}) * float(${r}) * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d) / norm; if (k == d) { dyi += pow(norm, -1.0 * ${r}); } if (k == coords[3]) { dyi *= getDy(b, r, c, d); result += dyi; } } else { break; } } } setOutput(result); } `}},Fre=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r,y:a,dy:o}=t,{depthRadius:i,bias:l,alpha:c,beta:u}=s,d=new Pre(r.shape,i,l,c,u);return n.runWebGLProgram(d,[r,a,o],r.dtype)},Ore={kernelName:Wh,backendName:"webgl",kernelFunc:Fre};function Mre(e,t,n,s){let r=v.sizeFromShape(t),o=v.sizeFromShape(e.shape)/r,i=ve({inputs:{x:e},attrs:{shape:[o,r]},backend:s}),l=Dl(i,e.dtype,"max",s),c=ve({inputs:{x:l},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(i),s.disposeIntermediateTensorInfo(l),c}function oC(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reductionIndices:a,keepDims:o}=s,i=r.shape.length,l=v.parseAxisParam(a,r.shape),c=l,u=E.getAxesPermutation(c,i),d=u!=null,p=n.shouldExecuteOnCPU([r]),h=r;if(d){if(p){let y=n.texData.get(h.dataId).values,b=new Array(i);for(let I=0;I`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);let u=E.computePool2DInfo(r.shape,a,o,c,i,l);if(u.filterWidth===1&&u.filterHeight===1&&v.arraysEqual(u.inShape,u.outShape))return ws({inputs:{x:r},backend:n});let d=new wp(u,"max",!1);return n.runWebGLProgram(d,[r],r.dtype)}var Gre={kernelName:Ja,backendName:"webgl",kernelFunc:Ure};function Hre(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dataFormat:l,dimRoundingMode:c}=s,u=[1,1,1],d=E.computePool3DInfo(r.shape,a,o,u,i,c,l),p=new kx(d,"max",!1);return n.runWebGLProgram(p,[r],r.dtype)}var jre={kernelName:md,backendName:"webgl",kernelFunc:Hre},qre=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,n=e.strideWidth,s=e.dilationHeight,r=e.effectiveFilterHeight,a=e.effectiveFilterWidth,o=r-1-e.padInfo.top,i=a-1-e.padInfo.left,l=r*a-1;this.userCode=` const ivec2 pads = ivec2(${o}, ${i}); void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; ivec2 dyRCCorner = coords.yz - pads; int dyRCorner = dyRCCorner.x; int dyCCorner = dyRCCorner.y; // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; for (int wR = 0; wR < ${r}; wR += ${s}) { float dyR = float(dyRCorner + wR) / ${t}.0; if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); for (int wC = 0; wC < ${a}; wC++) { float dyC = float(dyCCorner + wC) / ${n}.0; if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); float dyValue = getDy(b, idyR, idyC, d); int maxPosValue = ${l} - int(getMaxPos(b, idyR, idyC, d)); // Get the current value, check it against the value from the // position matrix. int curPosValue = wR * ${a} + wC; float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); dotProd += dyValue * mask; } } setOutput(dotProd); } `}},Xre=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,r=e.dilationDepth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterDepth,l=e.effectiveFilterHeight,c=e.effectiveFilterWidth,u=i-1-e.padInfo.front,d=l-1-e.padInfo.top,p=c-1-e.padInfo.left,h=i*l*c-1;this.userCode=` const ivec3 pads = ivec3(${u}, ${d}, ${p}); void main() { ivec5 coords = getOutputCoords(); int batch = coords.x; int ch = coords.u; ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; int dyDCorner = dyCorner.x; int dyRCorner = dyCorner.y; int dyCCorner = dyCorner.z; // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get // dx(xD, xR, xC, ch). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; for (int wD = 0; wD < ${i}; wD += ${r}) { float dyD = float(dyDCorner + wD) / ${t}.0; if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) { continue; } int idyD = int(dyD); for (int wR = 0; wR < ${l}; wR += ${a}) { float dyR = float(dyRCorner + wR) / ${n}.0; if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); for (int wC = 0; wC < ${c}; wC += ${o}) { float dyC = float(dyCCorner + wC) / ${s}.0; if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); float dyValue = getDy(batch, idyD, idyR, idyC, ch); int maxPosValue = ${h} - int(getMaxPos(batch, idyD, idyR, idyC, ch)); // Get the current value, check it against the value from the // position matrix. int curPosValue = wD * ${l} * ${c} + wR * ${c} + wC; float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); dotProd += dyValue * mask; } } } setOutput(dotProd); } `}};function Kre(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,o=a,{filterSize:i,strides:l,pad:c,dimRoundingMode:u}=s,d=[1,1,1],p=E.computePool3DInfo(o.shape,i,l,d,c,u),h=new kx(p,"max",!0),f=n.runWebGLProgram(h,[o],o.dtype),m=new Xre(p),g=n.runWebGLProgram(m,[r,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}var Zre={kernelName:Uh,backendName:"webgl",kernelFunc:Kre};function Yre(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a,output:o}=t,i=a;lc([a,o],"maxPoolGrad");let{filterSize:l,strides:c,pad:u,dimRoundingMode:d}=s,p=E.computePool2DInfo(i.shape,l,c,1,u,d),h=!0,f=new wp(p,"max",h),m=n.runWebGLProgram(f,[i],i.dtype),g=new qre(p),A=n.runWebGLProgram(g,[r,m],i.dtype);return n.disposeIntermediateTensorInfo(m),A}var Jre={kernelName:Vh,backendName:"webgl",kernelFunc:Yre};function Qre(e,t,n,s){let r=new wp(n,"max",!1),a=s.runWebGLProgram(r,[e],"float32");r=new wp(n,"max",!0,!0,t);let o=s.runWebGLProgram(r,[e],"float32");return[a,o]}var eae={kernelName:Gh,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:s}=e,{filterSize:r,strides:a,pad:o,includeBatchInIndex:i}=t,l=n;v.assert(s.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);let c=[1,1];v.assert(E.eitherStridesOrDilationsAreOne(a,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${c}'`);let u=E.computePool2DInfo(s.shape,r,a,c,o),[d,p]=Qre(s,i,u,l);return[d,p]}};function tae(e,t,n,s){let r=v.sizeFromShape(t),o=v.sizeFromShape(e.shape)/r,i=ve({inputs:{x:e},attrs:{shape:[o,r]},backend:s}),l=Dl(i,"float32","mean",s),c=ve({inputs:{x:l},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(i),s.disposeIntermediateTensorInfo(l),c}var nae={kernelName:Qa,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:s}=e,{keepDims:r,axis:a}=t,o=n,i=s.shape.length,l=v.parseAxisParam(a,s.shape),c=l,u=E.getAxesPermutation(c,i),d=u!=null,p=o.shouldExecuteOnCPU([s]),h=[],f=s;if(d){if(p){let b=o.texData.get(f.dataId).values,w=new Array(i);for(let N=0;Nc[0]+e[u]+c[1]);let s=e.length,r=xt(s),a=t.map(c=>c[0]).join(","),o=t.map((c,u)=>c[0]+e[u]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s),l=n==="reflect"?0:1;if(s===1){this.userCode=` int start = ${a}; int end = ${o}; void main() { int outC = getOutputCoords(); if (outC < start) { outC = start * 2 - outC - ${l}; } else if(outC >= end) { outC = (end - 1) * 2 - outC + ${l}; } setOutput(getX(outC - start)); } `;return}this.userCode=` ${r} start = ${r}(${a}); ${r} end = ${r}(${o}); void main() { ${r} outC = getOutputCoords(); for (int i = 0; i < ${s}; i++) { if (outC[i] < start[i]) { outC[i] = start[i] * 2 - outC[i] - ${l}; } else if(outC[i] >= end[i]) { outC[i] = (end[i] - 1) * 2 - outC[i] + ${l}; } } ${r} coords = outC - start; setOutput(getX(${i})); } `}},cae=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,f)=>h[0]+e[f]+h[1]);let s=e.length,r=xt(s),a=t.map(h=>h[0]).join(","),o=t.map((h,f)=>h[0]+e[f]).join(","),i=jn("rc",s),l=jn("source",s),c=`${i[s-1]} < ${this.outputShape[s-1]}`,u=s===1?"source":`vec2(${l.slice(-2).join()})`,d=n==="reflect"?0:1,p="";if(s===1){let h=` ${r} source = rc; if (source < start) { source = start * 2 - source - ${d}; } else if (source >= end) { source = (end - 1) * 2 - source + ${d}; } source -= start; `;p=` ${r} rc = outputLoc; ${h} result[0] = getChannel(getX(${l.join()}), ${u}); ${i[s-1]} += 1; if(${c}) { ${h} result[1] = getChannel(getX(${l.join()}), ${u}); } `}else{let h=` ${r} source = rc; ${r} lt = ${r}(lessThan(source, start)); ${r} gte = ${r}(greaterThanEqual(source, end)); ${r} orig = 1 - (lt + gte); source = orig * source + lt * (start * 2 - source - ${d}) + gte * ((end - 1) * 2 - source + ${d}); source -= start; `;p=` ${r} rc = outputLoc; ${h} result[0] = getChannel(getX(${l.join()}), ${u}); ${i[s-1]} += 1; if(${c}) { ${h} result[1] = getChannel(getX(${l.join()}), ${u}); } rc = outputLoc; ${i[s-2]} += 1; if(${i[s-2]} < ${this.outputShape[s-2]}) { ${h} result[2] = getChannel(getX(${l.join()}), ${u}); ${i[s-1]} += 1; if(${c}) { ${h} result[3] = getChannel(getX(${l.join()}), ${u}); } } `}this.userCode=` const ${r} start = ${r}(${a}); const ${r} end = ${r}(${o}); void main() { ${r} outputLoc = getOutputCoords(); vec4 result = vec4(0.); ${p} setOutput(result); } `}},dae=({inputs:e,backend:t,attrs:n})=>{let{x:s}=e,{paddings:r,mode:a}=n,o=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new cae(s.shape,r,a):new uae(s.shape,r,a);return t.runWebGLProgram(o,[s],s.dtype)},pae={kernelName:no,backendName:"webgl",kernelFunc:dae},hae=`if (b == 0.0) return NAN; return mod(a, b);`,fae=` vec4 result = mod(a, b); vec4 isNaN = vec4(equal(b, vec4(0.0))); `+qm+` return result; `,mae=Tn({opSnippet:hae,packedOpSnippet:fae}),gae={kernelName:Su,backendName:"webgl",kernelFunc:mae},Aae=class{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,n],this.userCode=` void main() { ivec2 coords = getOutputCoords(); int batch = coords[0]; float r = random(seed); float cdf = 0.0; for (int i = 0; i < ${t-1}; i++) { cdf += getProbs(batch, i); if (r < cdf) { setOutput(float(i)); return; } } // If no other event happened, last event happened. setOutput(float(${t-1})); } `}},yae=` if (a == b) { return 1.0; }; return a / b;`,xae=` // vec4 one = vec4(equal(a, b)); // return one + (vec4(1.0) - one) * a / b; vec4 result = a / b; if(a.x == b.x) { result.x = 1.; } if(a.y == b.y) { result.y = 1.; } if(a.z == b.z) { result.z = 1.; } if(a.w == b.w) { result.w = 1.; } return result; `,iC=Tn({opSnippet:yae,packedOpSnippet:xae,checkOutOfBounds:!0}),bae={kernelName:Wa,backendName:"webgl",kernelFunc:iC},lC="return a - b;",uC=Tn({opSnippet:lC,packedOpSnippet:lC,supportsComplex:!0,cpuKernelImpl:mQ}),vae={kernelName:yo,backendName:"webgl",kernelFunc:uC};function cC(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{dim:a}=s,o=v.parseAxisParam([a],r.shape),i=oC({inputs:{x:r},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),l=E.expandShapeToKeepDim(i.shape,o),c=ve({inputs:{x:i},backend:n,attrs:{shape:l}}),u=uC({inputs:{a:r,b:c},backend:n}),d=eC({inputs:{x:u},backend:n}),p=Zm({inputs:{x:d},backend:n,attrs:{axis:o,keepDims:!1}}),h=ve({inputs:{x:p},backend:n,attrs:{shape:l}}),f=iC({inputs:{a:d,b:h},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}var wae={kernelName:go,backendName:"webgl",kernelFunc:cC};function kae(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{numSamples:a,seed:o,normalized:i}=s,l=i?r:cC({inputs:{logits:r},backend:n,attrs:{dim:r.shape.length-1}}),c=l.shape[0],u=l.shape[1],d=new Aae(c,u,a),p=[[o]],h=n.runWebGLProgram(d,[l],"int32",p);return i||n.disposeIntermediateTensorInfo(l),h}var Sae={kernelName:Hh,backendName:"webgl",kernelFunc:kae},dC="return -x;";function Iae(e){let{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])){let a=n.texData.get(s.dataId),[o,i]=tQ(a.values,s.shape,s.dtype);return n.makeTensorInfo(i,s.dtype,o)}let r;return Y().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new hc(s.shape,dC):r=new jo(s.shape,dC),n.runWebGLProgram(r,[s],s.dtype)}var Cae={kernelName:$i,backendName:"webgl",kernelFunc:Iae},Tae=Qs.nonMaxSuppressionV3Impl;function Nae(e){E.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l}=s,c=n.readSync(r.dataId),u=n.readSync(a.dataId),{selectedIndices:d}=Tae(c,u,o,i,l);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}var Eae={kernelName:Di,backendName:"webgl",kernelFunc:Nae},Rae=Qs.nonMaxSuppressionV4Impl;function $ae(e){E.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l,padToMaxOutputSize:c}=s,u=n.readSync(r.dataId),d=n.readSync(a.dataId),{selectedIndices:p,validOutputs:h}=Rae(u,d,o,i,l,c);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var _ae={kernelName:Iu,backendName:"webgl",kernelFunc:$ae},Dae=Qs.nonMaxSuppressionV5Impl;function Pae(e){E.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l,softNmsSigma:c}=s,u=n.readSync(r.dataId),d=n.readSync(a.dataId),p=o,h=i,f=l,m=c,{selectedIndices:g,selectedScores:A}=Dae(u,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([A.length],"float32",new Float32Array(A))]}var Fae={kernelName:Pi,backendName:"webgl",kernelFunc:Pae},Oae=class{constructor(e,t,n,s){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=` void main() { ivec2 coords = getOutputCoords(); int index = round(getIndices(coords.x)); setOutput(mix(float(${s}), float(${n}), float(index == coords.y))); } `}},Mae=e=>{let{inputs:t,backend:n,attrs:s}=e,{indices:r}=t,{depth:a,onValue:o,offValue:i}=s,l=v.sizeFromShape(r.shape),c=new Oae(l,a,o,i),u=ve({inputs:{x:r},backend:n,attrs:{shape:[l]}}),d=n.runWebGLProgram(c,[u],r.dtype);n.disposeIntermediateTensorInfo(u);let p=[...r.shape,a],h=ve({inputs:{x:d},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(d),h},zae={kernelName:Oi,backendName:"webgl",kernelFunc:Mae};function t0(e){let{inputs:t,backend:n}=e,{x:s}=t;if(s.dtype==="complex64"){let r=kp({inputs:{input:s},backend:n}),a=t0({inputs:{x:r},backend:n}),o=e0({inputs:{input:s},backend:n}),i=t0({inputs:{x:o},backend:n}),l=qo({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),l}else return Sp({attrs:{shape:s.shape,dtype:s.dtype,value:s.dtype==="string"?"":0},backend:n})}var Lae={kernelName:Qi,backendName:"webgl",kernelFunc:t0};function pC(e){let{inputs:t,backend:n}=e,{x:s}=t;if(s.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(s.dtype==="complex64"){let r=kp({inputs:{input:s},backend:n}),a=pC({inputs:{x:r},backend:n}),o=e0({inputs:{input:s},backend:n}),i=t0({inputs:{x:o},backend:n}),l=qo({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),l}else return Sp({attrs:{shape:s.shape,dtype:s.dtype,value:1},backend:n})}var Bae={kernelName:Fi,backendName:"webgl",kernelFunc:pC};function Wae(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(t.length===1)return Cx({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let a=t[0].shape,o=t[0].dtype;t.forEach(u=>{v.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),v.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(u=>{let d=Cx({inputs:{input:u},backend:n,attrs:{dim:r}});return i.push(d),d}),c=G4({inputs:l,backend:n,attrs:{axis:r}});return i.forEach(u=>n.disposeIntermediateTensorInfo(u)),c}var Vae={kernelName:Mi,backendName:"webgl",kernelFunc:Wae},Uae=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((l,c)=>l[0]+e[c]+l[1]);let s=e.length,r=xt(s),a=t.map(l=>l[0]).join(","),o=t.map((l,c)=>l[0]+e[c]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s);if(s===1){this.userCode=` int start = ${a}; int end = ${o}; void main() { int outC = getOutputCoords(); if (outC < start || outC >= end) { setOutput(value); } else { setOutput(getX(outC - start)); } } `;return}this.userCode=` ${r} start = ${r}(${a}); ${r} end = ${r}(${o}); void main() { ${r} outC = getOutputCoords(); if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) { setOutput(value); } else { ${r} coords = outC - start; setOutput(getX(${i})); } } `}},Gae=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((f,m)=>f[0]+e[m]+f[1]);let s=e.length,r=xt(s),a=t.map(f=>f[0]).join(","),o=t.map((f,m)=>f[0]+e[m]).join(","),i=jn("rc",s),l=jn("source",s),c=`${i[s-1]} < ${this.outputShape[s-1]}`,u=s===1?"source":`vec2(${l.slice(-2).join()})`,d=[`${r} rc = outputLoc;`,`${i[s-1]} += 1; if(${c}) { `,s===1?"":`} rc = outputLoc; ${i[s-2]} += 1; if(${i[s-2]} < ${this.outputShape[s-2]}) {`,s===1?"":` ${i[s-1]} += 1; if(${c}) {`],p=s===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="";for(let f=0,m=s===1?2:4;f{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,constantValue:o}=s;if(v.sizeFromShape(r.shape)===0){let c=a.map((u,d)=>u[0]+r.shape[d]+u[1]);return Sp({backend:n,attrs:{shape:c,value:o,dtype:r.dtype}})}let i=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Gae(r.shape,a,o):new Uae(r.shape,a,o),l=[[o]];return n.runWebGLProgram(i,[r],r.dtype,l)},Hae={kernelName:ro,backendName:"webgl",kernelFunc:hC},jae=` if(a < 0.0 && floor(b) < b){ return NAN; } if (b == 0.0) { return 1.0; } return (round(mod(b, 2.0)) != 1) ? pow(abs(a), b) : sign(a) * pow(abs(a), b); `,qae=` // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise. vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1))); vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1); vec4 result = multiplier * pow(abs(a), b); // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS bvec4 isExpZero = equal(b, vec4(0.0)); result.r = isExpZero.r ? 1.0 : result.r; result.g = isExpZero.g ? 1.0 : result.g; result.b = isExpZero.b ? 1.0 : result.b; result.a = isExpZero.a ? 1.0 : result.a; vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b)); `+qm+` return result; `,Xae=Tn({opSnippet:jae,packedOpSnippet:qae}),Kae={kernelName:ao,backendName:"webgl",kernelFunc:Xae};function Zae(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s,i=r.shape.length,l=[],c=v.parseAxisParam(a,r.shape),u=c,d=E.getAxesPermutation(u,i),p=r;d!=null&&(p=qn({inputs:{x:r},backend:n,attrs:{perm:d}}),u=E.getInnerMostAxes(u.length,i),l.push(p)),E.assertAxesAreInnerMostDims("prod",u,i);let h;if(n.shouldExecuteOnCPU([p])){let f=n.texData.get(p.dataId).values,{outVals:m,outShape:g,outDtype:A}=sQ(p.shape,p.dtype,f,u);h=n.makeTensorInfo(g,A,m)}else{let[f,m]=E.computeOutAndReduceShapes(p.shape,u),g=v.sizeFromShape(m),A=ve({inputs:{x:p},backend:n,attrs:{shape:[-1,g]}}),x=Ed(r.dtype),y=Dl(A,x,"prod",n);h=ve({inputs:{x:y},backend:n,attrs:{shape:f}}),l.push(A),l.push(y)}if(o){l.push(h);let f=E.expandShapeToKeepDim(h.shape,c);h=ve({inputs:{x:h},backend:n,attrs:{shape:f}})}return l.forEach(f=>n.disposeIntermediateTensorInfo(f)),h}var Yae={kernelName:zi,backendName:"webgl",kernelFunc:Zae},fC=e=>{let{backend:t,attrs:n}=e,{start:s,stop:r,step:a,dtype:o}=n,i=rQ(s,r,a,o);return t.makeTensorInfo([i.length],o,i)},Jae={kernelName:Cu,backendName:"webgl",kernelFunc:fC},Qae="return 1.0 / x;",eoe=st({opSnippet:Qae}),toe={kernelName:Tu,backendName:"webgl",kernelFunc:eoe},noe=kr+` return (x < 0.0) ? 0.0 : x; `,soe=` vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0))); bvec4 isNaN = isnan(x); result.r = isNaN.r ? x.r : result.r; result.g = isNaN.g ? x.g : result.g; result.b = isNaN.b ? x.b : result.b; result.a = isNaN.a ? x.a : result.a; return result; `,roe=st({opSnippet:noe,packedOpSnippet:soe}),aoe={kernelName:io,backendName:"webgl",kernelFunc:roe},ooe=kr+` return (x < 0.0) ? 0.0 : min(6.0, x); `,ioe=` vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0))); bvec4 isNaN = isnan(x); result.r = isNaN.r ? x.r : result.r; result.g = isNaN.g ? x.g : result.g; result.b = isNaN.b ? x.b : result.b; result.a = isNaN.a ? x.a : result.a; return result; `,loe=st({opSnippet:ooe,packedOpSnippet:ioe}),uoe={kernelName:uo,backendName:"webgl",kernelFunc:loe},coe=class{constructor(e,t,n,s,r){this.variableNames=["A"],this.outputShape=[];let[a,o,i,l]=e;this.outputShape=[a,t,n,l];let c=[s&&t>1?o-1:o,s&&n>1?i-1:i],u=[s&&t>1?t-1:t,s&&n>1?n-1:n],d;r?d="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` const vec2 effectiveInputOverOutputRatioRC = vec2( ${c[0]/u[0]}, ${c[1]/u[1]}); const vec2 inputShapeRC = vec2(${o}.0, ${i}.0); void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; ivec2 yRC = coords.yz; // Fractional source index. vec2 sourceFracIndexRC = ${d}; // Compute the four integer indices. ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0))); ivec2 sourceCeilRC = ivec2( min(inputShapeRC - 1.0, ceil(sourceFracIndexRC))); float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d); float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d); float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d); float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d); vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC); float top = topLeft + (topRight - topLeft) * fracRC.y; float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y; float newValue = top + (bottom - top) * fracRC.x; setOutput(newValue); } `}},doe=class{constructor(e,t,n,s,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,l]=e;this.outputShape=[a,t,n,l];let c=[s&&t>1?o-1:o,s&&n>1?i-1:i],u=[s&&t>1?t-1:t,s&&n>1?n-1:n],d;r?d="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` const vec3 effectiveInputOverOutputRatioRC = vec3( ${c[0]/u[0]}, ${c[1]/u[1]}, ${c[1]/u[1]}); const vec3 inputShapeRC = vec3(${o}.0, ${i}.0, ${i}.0); float getAValue(int b, int r, int c, int d) { return getChannel(getA(b, r, c, d), vec2(c, d)); } void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; // Calculate values for next column in yRC.z. ivec3 yRC = coords.yzz + ivec3(0, 0, 1); // Fractional source index. vec3 sourceFracIndexRC = ${d}; // Compute the four integer indices. ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0))); ivec3 sourceCeilRC = ivec3( min(inputShapeRC - 1.0, ceil(sourceFracIndexRC))); // Should we calculate next column and row elements in 2x2 packed cell. bool hasNextCol = d < ${l-1}; bool hasNextRow = coords.z < ${n-1}; // In parallel, construct four corners for all four components in // packed 2x2 cell. vec4 topLeft = vec4( getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d), hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1) : 0.0, hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d) : 0.0, (hasNextRow && hasNextCol) ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0); vec4 bottomLeft = vec4( getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d), hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1) : 0.0, hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d) : 0.0, (hasNextRow && hasNextCol) ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0); vec4 topRight = vec4( getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d), hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1) : 0.0, hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d) : 0.0, (hasNextRow && hasNextCol) ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0); vec4 bottomRight = vec4( getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d), hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1) : 0.0, hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d) : 0.0, (hasNextRow && hasNextCol) ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0); vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC); vec4 top = mix(topLeft, topRight, fracRC.yyzz); vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz); vec4 newValue = mix(top, bottom, fracRC.x); setOutput(newValue); } `}};function poe(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:o,size:i}=s,[l,c]=i,u=Y().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new doe(r.shape,l,c,a,o):new coe(r.shape,l,c,a,o);return n.runWebGLProgram(u,[r],"float32")}var hoe={kernelName:lo,backendName:"webgl",kernelFunc:poe},foe=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,s,r]=t,[,a,o]=e,i=[n&&a>1?s-1:s,n&&o>1?r-1:r],l=[n&&a>1?a-1:a,n&&o>1?o-1:o],c=i[0]/l[0],u=i[1]/l[1],d=1/c,p=1/u,h=Math.ceil(d)*2+2,f=Math.ceil(p)*2+2;this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; int r = coords[1]; int c = coords[2]; float accumulator = 0.0; const float heightScale = float(${c}); const float widthScale = float(${u}); const float invHeightScale = float(${d}); const float invWidthScale = float(${p}); const int winHeight = int(${h}); const int winWidth = int(${f}); // Compute bounds for where in dy we will look float startRLerp = floor(float(r) * invHeightScale); int startDyR = int(startRLerp - float(winHeight / 2)); float startCLerp = floor(float(c) * invWidthScale); int startDyC = int(startCLerp - float(winWidth / 2)); // Loop over dy for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) { int dyR = dyROffset + startDyR; // Guard against the window exceeding the bounds of dy if (dyR < 0 || dyR >= ${a}) { continue; } for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) { int dyC = dyCOffset + startDyC; // Guard against the window exceeding the bounds of dy if (dyC < 0 || dyC >= ${o}) { continue; } float dxR = float(dyR) * heightScale; int topDxRIndex = int(floor(dxR)); int bottomDxRIndex = int(min(ceil(dxR), ${s-1}.0)); float dxRLerp = dxR - float(topDxRIndex); float inverseDxRLerp = 1.0 - dxRLerp; float dxC = float(dyC) * widthScale; int leftDxCIndex = int(floor(dxC)); int rightDxCIndex = int(min(ceil(dxC), ${r-1}.0)); float dxCLerp = dxC - float(leftDxCIndex); float inverseDxCLerp = 1.0 - dxCLerp; if (r == topDxRIndex && c == leftDxCIndex) { // topLeft accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp; } if (r == topDxRIndex && c == rightDxCIndex) { // topRight accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp; } if (r == bottomDxRIndex && c == leftDxCIndex) { // bottomLeft accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp; } if (r == bottomDxRIndex && c == rightDxCIndex) { // bottomRight accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp; } } } // End loop over dy setOutput(accumulator); } `}};function moe(e){let{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:o}=s,i=new foe(a.shape,r.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var goe={kernelName:qh,backendName:"webgl",kernelFunc:moe},Aoe=class{constructor(e,t,n,s,r){this.variableNames=["A"],this.outputShape=[];let[a,o,i,l]=e;this.outputShape=[a,t,n,l];let c=[s&&t>1?o-1:o,s&&n>1?i-1:i],u=[s&&t>1?t-1:t,s&&n>1?n-1:n],d=s?"0.5":"0.0",p;r?p="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` const vec2 effectiveInputOverOutputRatioRC = vec2( ${c[0]/u[0]}, ${c[1]/u[1]}); const vec2 inputShapeRC = vec2(${o}.0, ${i}.0); void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; ivec2 yRC = coords.yz; // Fractional source index. vec2 sourceFracIndexRC = ${p}; // Compute the coordinators of nearest neighbor point. ivec2 sourceNearestRC = ivec2( min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d}))); float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d); setOutput(newValue); } `}},yoe=class{constructor(e,t,n,s,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,l]=e;this.outputShape=[a,t,n,l];let c=[s&&t>1?o-1:o,s&&n>1?i-1:i],u=[s&&t>1?t-1:t,s&&n>1?n-1:n],d=s?"0.5":"0.0",p;r?p="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` const vec3 effectiveInputOverOutputRatioRC = vec3( ${c[0]/u[0]}, ${c[1]/u[1]}, ${c[1]/u[1]}); const vec3 inputShapeRC = vec3(${o}.0, ${i}.0, ${i}.0); float getAValue(int b, int r, int c, int d) { return getChannel(getA(b, r, c, d), vec2(c, d)); } void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; // Calculate values for next column in yRC.z. ivec3 yRC = coords.yzz + ivec3(0, 0, 1); // Fractional source index. vec3 sourceFracIndexRC = ${p}; // Compute the coordinators of nearest neighbor point. ivec3 sourceNearestRC = ivec3( min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d}))); // Should we calculate next column and row elements in 2x2 packed cell. bool hasNextCol = d < ${l-1}; bool hasNextRow = coords.z < ${n-1}; vec4 newValue = vec4( getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d), hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1) : 0.0, hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d) : 0.0, (hasNextRow && hasNextCol) ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0); setOutput(newValue); } `}};function xoe(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:o,size:i}=s,[l,c]=i,u=Y().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new yoe(r.shape,l,c,a,o):new Aoe(r.shape,l,c,a,o);return n.runWebGLProgram(u,[r],r.dtype)}var boe={kernelName:Nu,backendName:"webgl",kernelFunc:xoe},voe=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,s,r]=t,[,a,o]=e,i=[n&&a>1?s-1:s,n&&o>1?r-1:r],l=[n&&a>1?a-1:a,n&&o>1?o-1:o],c=i[0]/l[0],u=i[1]/l[1],d=1/c,p=1/u,h=Math.ceil(d)*2+2,f=Math.ceil(p)*2+2;this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; int r = coords[1]; int c = coords[2]; float accumulator = 0.0; const float heightScale = float(${c}); const float widthScale = float(${u}); const float invHeightScale = float(${d}); const float invWidthScale = float(${p}); const int winHeight = int(${h}); const int winWidth = int(${f}); // Compute bounds for where in dy we will look float startRLerp = floor(float(r) * invHeightScale); int startDyR = int(floor(startRLerp - float(winHeight / 2))); float startCLerp = floor(float(c) * invWidthScale); int startDyC = int(floor(startCLerp - float(winWidth / 2))); // Loop over dy for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) { int dyR = dyROffset + startDyR; // Guard against the window exceeding the bounds of dy if (dyR < 0 || dyR >= ${a}) { continue; } for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) { int dyC = dyCOffset + startDyC; // Guard against the window exceeding the bounds of dy if (dyC < 0 || dyC >= ${o}) { continue; } float sourceFracRow = float(${i[0]}) * (float(dyR) / float(${l[0]})); float sourceFracCol = float(${i[1]}) * (float(dyC) / float(${l[1]})); int sourceNearestRow = int(min( float(int(${s}) - 1), ${n} ? float(round(sourceFracRow)) : float(floor(sourceFracRow)))); int sourceNearestCol = int(min( float(int(${r}) - 1), ${n} ? float(round(sourceFracCol)) : float(floor(sourceFracCol)))); if (r == sourceNearestRow && c == sourceNearestCol) { accumulator += getDy(b, dyR, dyC, d); } } } // End loop over dy setOutput(accumulator); } `}};function woe(e){let{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:o}=s,i=new voe(a.shape,r.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var koe={kernelName:jh,backendName:"webgl",kernelFunc:woe},Soe=class{constructor(e,t){this.variableNames=["x"];let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,n===1){this.userCode=` void main() { int coord = getOutputCoords(); setOutput(getX(${e[0]} - coord - 1)); } `;return}let s=o=>t.indexOf(o)!==-1&&e[o]!==1?`${e[o]} - coords[${o}] - 1`:`coords[${o}]`,r=e.map((o,i)=>s(i)).join(","),a=xt(n);this.userCode=` void main() { ${a} coords = getOutputCoords(); setOutput(getX(${r})); } `}},Ioe=class{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;let s=jn("rc",n),r=`${s[n-1]} + 1 < ${this.outputShape[n-1]}`,a=`${s[n-2]} + 1 < ${this.outputShape[n-2]}`,o=xt(n);n===1?this.userCode=` void main(){ int rc = getOutputCoords(); vec4 result = vec4(0.); result.r = getChannel(getX(${e[0]} - rc - 1), ${e[0]} - rc - 1); if(${r}){ result.g = getChannel(getX(${e[0]} - (rc + 1) - 1), ${e[0]} - (rc + 1) - 1); } setOutput(result); } `:this.userCode=` void main() { ${o} rc = getOutputCoords(); vec4 result = vec4(0.); result.r = ${i(s.slice())}; if(${r}){ result.g = ${l(s.slice())}; } if(${a}) { result.b = ${c(s.slice())}; if(${r}) { result.a = ${u(s.slice())}; } } setOutput(result); } `;function i(h){return d(h)}function l(h){return h[n-1]="("+h[n-1]+" + 1)",d(h)}function c(h){return h[n-2]="("+h[n-2]+" + 1)",d(h)}function u(h){return h[n-1]="("+h[n-1]+" + 1)",h[n-2]="("+h[n-2]+" + 1)",d(h)}function d(h){let f=e.map((A,x)=>p(x,h)),m=f.join(","),g=f.slice(-2).join(",");return`getChannel(getX(${m}), vec2(${g}))`}function p(h,f){return t.indexOf(h)!==-1&&e[h]!==1?`${e[h]} - ${f[h]} - 1`:`${f[h]}`}}};function Coe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s,o=r.shape.length,i=v.parseAxisParam(a,r.shape);if(o===0)return ws({inputs:{x:r},backend:n});let l=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ioe(r.shape,i):new Soe(r.shape,i);return n.runWebGLProgram(l,[r],r.dtype)}var Toe={kernelName:Bi,backendName:"webgl",kernelFunc:Coe},Noe=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let n=e[1],s=e[2];this.outputShape=e;let r="";typeof t=="number"?r=`float outputValue = ${t.toFixed(2)};`:r=` vec3 fill = vec3(${t.join(",")}); float outputValue = fill[coords[3]];`,this.userCode=` void main() { ivec4 coords = getOutputCoords(); int x = coords[2]; int y = coords[1]; float coordXFloat = (float(x) - params[0]) * params[3] - (float(y) - params[1]) * params[2]; float coordYFloat = (float(x) - params[0]) * params[2] + (float(y) - params[1]) * params[3]; int coordX = int(round(coordXFloat + params[0])); int coordY = int(round(coordYFloat + params[1])); ${r} if(coordX >= 0 && coordX < ${s} && coordY >= 0 && coordY < ${n}) { outputValue = getImage(coords[0], coordY, coordX, coords[3]); } setOutput(outputValue); } `}},Eoe={kernelName:el,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:s}=e,{radians:r,fillValue:a,center:o}=t,i=n,l=new Noe(s.shape,a),[c,u]=E.getImageCenter(o,s.shape[1],s.shape[2]),d=[[c,u,Math.sin(r),Math.cos(r)]];return i.runWebGLProgram(l,[s],s.dtype,d)}},Roe=` // OpenGL ES does not support round function. // The algorithm is based on banker's rounding. float base = floor(x); if ((x - base) < 0.5) { return floor(x); } else if ((x - base) > 0.5) { return ceil(x); } else { if (mod(base, 2.0) == 0.0) { return base; } else { return base + 1.0; } } `,$oe=st({opSnippet:Roe}),_oe={kernelName:Wi,backendName:"webgl",kernelFunc:$oe},Doe="return inversesqrt(x);",Poe=st({opSnippet:Doe,cpuKernelImpl:aQ}),Foe={kernelName:co,backendName:"webgl",kernelFunc:Poe},mC=class{constructor(e,t,n,s,r,a,o=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;let i=xt(r.length),l=xt(a.length),c="";n===1?c="i":n===2&&(c="i, j");let u=`getIndices(${c})`,d="";s===1?d="i":s===2&&(d="i, coords[1]");let p=`getUpdates(${d})`,h=t>1?"strides[j]":"strides";this.userCode=` ${i} strides = ${i}(${r}); void main() { ${l} coords = getOutputCoords(); float sum = 0.0; bool found = false; for (int i = 0; i < ${e}; i++) { int flattenedIndex = 0; for (int j = 0; j < ${t}; j++) { int index = round(${u}); flattenedIndex += index * ${h}; } if (flattenedIndex == coords[0]) { sum += ${p}; found = true; } } setOutput(mix(getDefaultValue(), sum, float(found))); } `}};function Ooe(e){let{inputs:t,backend:n,attrs:s}=e,{indices:r,updates:a}=t,{shape:o}=s,{sliceRank:i,numUpdates:l,sliceSize:c,strides:u,outputSize:d}=E.calculateShapes(a,r,o),p=[d/c,c];if(d===0)return n.makeTensorInfo(o,r.dtype);let h=ve({inputs:{x:r},backend:n,attrs:{shape:[l,i]}}),f=ve({inputs:{x:a},backend:n,attrs:{shape:[l,c]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new mC(l,i,h.shape.length,f.shape.length,u,p),A=n.runWebGLProgram(g,[f,h,m],f.dtype),x=ve({inputs:{x:A},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(A),n.disposeIntermediateTensorInfo(m),x}var Moe={kernelName:Vi,backendName:"webgl",kernelFunc:Ooe},zoe=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let s,r;if(n>4)throw Error(`Where for rank ${n} is not yet supported`);if(n===1)r="resRC",s="resRC";else{let o=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],l=[];for(let c=0;c= 1.0) { setOutput(getA(${r})); } else { setOutput(getB(${r})); } } `}};function Loe(e){let{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t,o=new zoe(s.shape.length,r.shape,r.shape.length);return n.runWebGLProgram(o,[s,r,a],Bn(r.dtype,a.dtype))}var Boe={kernelName:Ui,backendName:"webgl",kernelFunc:Loe},Woe=` // Stable and Attracting Fixed Point (0, 1) for Normalized Weights. // see: https://arxiv.org/abs/1706.02515 float scaleAlpha = ${E.SELU_SCALEALPHA}; float scale = ${E.SELU_SCALE}; return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0); `,Voe=st({opSnippet:Woe}),Uoe={kernelName:Eu,backendName:"webgl",kernelFunc:Voe},gC="return 1.0 / (1.0 + exp(-1.0 * x));",Goe=st({opSnippet:gC,packedOpSnippet:gC,cpuKernelImpl:oQ}),Hoe={kernelName:ho,backendName:"webgl",kernelFunc:Goe},joe=` if (isnan(x)) { return 0.0; } return sign(x); `,qoe=st({opSnippet:joe}),Xoe={kernelName:Ru,backendName:"webgl",kernelFunc:qoe},Koe=E4+` return sin(x); `,Zoe=st({opSnippet:Koe}),Yoe={kernelName:po,backendName:"webgl",kernelFunc:Zoe},Joe=` float e2x = exp(x); return (e2x - 1.0 / e2x) / 2.0; `,Qoe=st({opSnippet:Joe}),eie={kernelName:Hi,backendName:"webgl",kernelFunc:Qoe},tie=` float epsilon = 1.1920928955078125e-7; float threshold = log(epsilon) + 2.0; bool too_large = x > -threshold; bool too_small = x < threshold; float result; float exp_x = exp(x); if (too_large){ result = x; } else if (too_small){ result = exp_x; } else{ result = log(exp_x + 1.0); } return result; `,nie=st({opSnippet:tie}),sie={kernelName:$u,backendName:"webgl",kernelFunc:nie},rie=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:o}=s;v.assert(r.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((A,x)=>A*x),l=[[0,0]];l.push(...o);for(let A=1+a.length;An.disposeIntermediateTensorInfo(A)),g},aie={kernelName:ji,backendName:"webgl",kernelFunc:rie};function oie(e){let{inputs:t,backend:n}=e,{indices:s,values:r,denseShape:a,defaultValue:o}=t;if(a.shape.length!==1)throw new Error(`Dense shape must be a vector, saw: ${a.shape}`);if(s.shape.length!==2)throw new Error(`Indices must be a matrix, saw: ${s.shape}`);if(r.shape.length!==1)throw new Error(`Values must be a vector, saw: ${r.shape}`);if(o.shape.length!==0)throw new Error(`Default value must be a scalar, saw: ${o.shape}`);let i=n.readSync(s.dataId),l=n.readSync(r.dataId),c=n.readSync(a.dataId),u=n.readSync(o.dataId)[0],[d,p,h,f,m]=lQ(i,s.shape,s.dtype,l,r.dtype,c,u);return[n.makeTensorInfo(p,s.dtype,d),n.makeTensorInfo([p[0]],r.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),n.makeTensorInfo([m.length],s.dtype,new Int32Array(m))]}var iie={kernelName:Xh,backendName:"webgl",kernelFunc:oie};function lie(e){let{inputs:t,backend:n}=e,{inputIndices:s,inputShape:r,newShape:a}=t;if(s.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${s.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${r.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);let o=Array.from(n.readSync(r.dataId)),i=n.readSync(s.dataId),l=Array.from(n.readSync(a.dataId)),[c,u,d]=uQ(i,s.shape,s.dtype,o,l);return[n.makeTensorInfo(u,s.dtype,c),n.makeTensorInfo([d.length],a.dtype,new Int32Array(d))]}var uie={kernelName:Kh,backendName:"webgl",kernelFunc:lie};function cie(e){let{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape ${r.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape ${a.shape}`);let o=n.readSync(s.dataId),i=n.readSync(r.dataId),l=n.readSync(a.dataId),[c,u]=m4(o,s.shape,s.dtype,i,l,!0);return n.makeTensorInfo(u,s.dtype,c)}var die={kernelName:Zh,backendName:"webgl",kernelFunc:cie};function pie(e){let{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape ${r.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape ${a.shape}`);let o=n.readSync(s.dataId),i=n.readSync(r.dataId),l=n.readSync(a.dataId),[c,u]=m4(o,s.shape,s.dtype,i,l);return n.makeTensorInfo(u,s.dtype,c)}var hie={kernelName:Yh,backendName:"webgl",kernelFunc:pie};function fie(e){let{inputs:t,backend:n,attrs:s}=e,{sparseIndices:r,sparseValues:a,defaultValue:o}=t,{outputShape:i}=s,{sliceRank:l,numUpdates:c,strides:u,outputSize:d}=E.calculateShapes(a,r,i),p=!1,h=new mC(c,l,r.shape.length,a.shape.length,u,[d,1],p),f=n.runWebGLProgram(h,[a,r,o],a.dtype),m=ve({inputs:{x:f},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(f),m}var mie={kernelName:Ad,backendName:"webgl",kernelFunc:fie};function gie(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{numOrSizeSplits:a,axis:o}=s,i=v.parseAxisParam(o,r.shape)[0],l=E.prepareSplitSize(r,a,i),c=r.shape.length,u=new Array(c).fill(0),d=r.shape.slice();return l.map(p=>{let h=[...d];h[i]=p;let f=mc({inputs:{x:r},backend:n,attrs:{begin:u,size:h}});return u[i]+=p,f})}var Aie={kernelName:qi,backendName:"webgl",kernelFunc:gie},AC="return sqrt(x);",yie=st({opSnippet:AC,packedOpSnippet:AC,cpuKernelImpl:cQ}),xie={kernelName:fo,backendName:"webgl",kernelFunc:yie},bie="return x * x;",vie=st({opSnippet:bie}),wie={kernelName:_u,backendName:"webgl",kernelFunc:vie},yC="return (a - b) * (a - b);",kie=Tn({opSnippet:yC,packedOpSnippet:yC}),Sie={kernelName:Ao,backendName:"webgl",kernelFunc:kie};function Iie({inputs:e,attrs:t,backend:n}){let{x:s}=e,r=kr+` return x > 0.0 ? 1.0 : float(${t.alpha}); `,a=new jo(s.shape,r);return n.runWebGLProgram(a,[s],s.dtype)}var Cie={kernelName:vo,backendName:"webgl",kernelFunc:Iie},Tie=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let s=n.length,r=xt(n.length),a=xt(n.length),o="";if(s===1)o="coords * strides + begin";else{let i=0;o=n.map((l,c)=>(i++,n.length===1?`coords * strides[${c}] + begin[${c}]`:`coords[${i-1}] * strides[${c}] + begin[${c}]`)).join(",")}this.userCode=` ${r} begin = ${r}(${e}); ${r} strides = ${r}(${t}); void main() { ${a} coords = getOutputCoords(); setOutput(getX(${o})); } `}};function Nie(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=s,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:A,begin:x,end:y,strides:b}=Ft.sliceInfo(r.shape,a,o,i,l,c,u,d,p),w;if(m)w=ve({inputs:{x:r},backend:n,attrs:{shape:f}});else if(g||A){v.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let I=Ft.computeOutShape(x,y,b),N=mc({inputs:{x:r},backend:n,attrs:{begin:x,size:I}});w=ve({inputs:{x:N},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(N)}else if(n.shouldExecuteOnCPU([r])){let N=n.readSync(r.dataId),R=ze(r.shape,r.dtype,N),O=dQ(h,R,b,x);w=n.makeTensorInfo(f,r.dtype,O.values)}else{let N=new Tie(x,b,h);w=n.runWebGLProgram(N,[r],r.dtype)}let k=ve({inputs:{x:w},backend:n,attrs:{shape:f}});return n.disposeIntermediateTensorInfo(w),k}var Eie={kernelName:Xi,backendName:"webgl",kernelFunc:Nie};function Rie(e){let{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:c}=s,{data:u,dataSplits:d}=t,p=n.readSync(u.dataId),h=n.readSync(d.dataId),[f,m]=pQ(p,h,r,a,o,i,l,c);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var $ie={kernelName:yd,backendName:"webgl",kernelFunc:Rie};function _ie(e){let{inputs:t,backend:n,attrs:s}=e,{skipEmpty:r}=s,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.readSync(a.dataId),l=n.readSync(o.dataId)[0],[c,u,d]=hQ(i,l,r),p=u.length;return[n.makeTensorInfo([p,2],"int32",c),n.makeTensorInfo([p],"string",u),n.makeTensorInfo([2],"int32",new Int32Array(d))]}var Die={kernelName:Jh,backendName:"webgl",kernelFunc:_ie};function Pie(e){let{inputs:t,backend:n,attrs:s}=e,{numBuckets:r}=s,{input:a}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");let o=n.readSync(a.dataId),i=fQ(o,r);return n.makeTensorInfo(a.shape,"int32",i)}var Fie={kernelName:Qh,backendName:"webgl",kernelFunc:Pie},Oie="return tan(x);",Mie=st({opSnippet:Oie}),zie={kernelName:Ki,backendName:"webgl",kernelFunc:Mie},Lie=` float e2x = exp(-2.0 * abs(x)); return sign(x) * (1.0 - e2x) / (1.0 + e2x); `,Bie=st({opSnippet:Lie}),Wie={kernelName:xo,backendName:"webgl",kernelFunc:Bie},Vie=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${e[0]})`;let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],s=[];for(let r=0;r5){let l=n.readSync(r.dataId),c=r.dtype==="string"?l.map(p=>v.decodeString(p)):l,u=ze(r.shape,r.dtype,c),d=gQ(u,a);return n.makeTensorInfo(d.shape,d.dtype,d.values)}let o=new Vie(r.shape,a);return n.runWebGLProgram(o,[r],r.dtype)}var Gie={kernelName:Yr,backendName:"webgl",kernelFunc:xC},Hie=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode=` void main() { ivec2 coords = getOutputCoords(); int batch = coords[0]; int elemIdx = coords[1]; // We compare elements pair-wise within a group of size 2 * inc. // The comparing rule for each group alternates between ascending // and descending. Within each group, we compare each pair at // positions i and i+inc. To decide whether an element at position i // is x0 or x1, we mod it by 2 * inc, if the result is smaller than // inc, it is in the first half of the group, we denote it as x0, // otherwise we denote it as x1. // For example, as shown in the Bitonic top K paper referenced above, // Figure5(a) shows that element[1] is in the // second half of the group when group size is 2, but it is in the // first half of the group when group size is 4. bool isFirstInPair = imod(elemIdx, 2 * inc) < inc; int i = isFirstInPair ? elemIdx : elemIdx - inc; int i0 = firstPass == 1 ? i : int(getIndices(batch, i)); int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc)); float x0 = i0 < n ? getX(batch, i0) : negativeInf; float x1 = i1 < n ? getX(batch, i1) : negativeInf; // Denotes which direction indices are in (ascending or descending). bool reverse = imod(elemIdx, 2 * dir) >= dir; bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0); if (reverse == isGreater) { // Elements in opposite order of direction int iTemp = i0; i0 = i1; i1 = iTemp; } if (isFirstInPair) { setOutput(float(i0)); } else { setOutput(float(i1)); } } `}},jie=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode=` void main() { // Takes max of indices (0, k), (1, k + 1), (2, k + 2) ... ivec2 coords = getOutputCoords(); int batch = coords[0]; int elemIdx = coords[1]; // The output size is half of the previous size. // If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4), // we only need to output the indices at positions |, the indices at // positions _ can be thrown away, see Figure5(b) After Phase 2 // (Merge phase) in the Bitonic Top K paper referenced above. // For example, the paper shows we only need to output the orange bars. // The output sequence should look like this | | | | | | | |. // Because the sequence is halved, to map the output index back // to the previous sequence to find the corresponding value, // we need to double the index. When we double the index, // we basically interpolate a position, so 2i looks like // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position // of each 2k positions by - elemIdx % k. E.g. for output at // index 4,5,6,7, we want to get the corresponding element at // original index 8,9,10,11, for output at index 8,9,10,11, // we want to get the corresponding element at original index // 16,17,18,19, so on and so forth. int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k)); int i0 = firstPass == 1 ? i : int(getIndices(batch, i)); int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k)); float x0 = getX(batch, i0); float x1 = i1 < n ? getX(batch, i1) : x0; setOutput(x0 >= x1 ? float(i0) : float(i1)); } `}};function Pl(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function bC(e){let t=1;for(;tl){let O=n.readSync(r.dataId),[$,P]=AQ(O,c,r.dtype,a,o);return[n.makeTensorInfo($.shape,$.dtype,$.values),n.makeTensorInfo(P.shape,P.dtype,P.values)]}if(a===0)return c[c.length-1]=0,[n.makeTensorInfo(c,r.dtype,[]),n.makeTensorInfo(c,"int32",[])];if(u===1)return[r,Sp({attrs:{shape:c,dtype:"int32",value:0},backend:n})];let d=n.texData.get(r.dataId),p=d!==null&&d.isPacked,h=p?n.unpackTensor(r):r,m=v.sizeFromShape(c)/u,g=ve({inputs:{x:h},attrs:{shape:[m,u]},backend:n});p&&Pl(n,h);let A=bC(a),x=bC(u),y=null,b=()=>y===null?[g,g]:[g,y],w=(O,$,P)=>{let T=b(),F=new Hie(P),q=[[u],[y===null?1:0],[Number.NEGATIVE_INFINITY],[O],[$]],z=y;y=n.runWebGLProgram(F,T,"int32",q),Pl(n,z)};for(let O=1;O=1;P/=2)w($,P,[m,x])}for(let O=x;O>A;O/=2){let $=b(),P=new jie([m,O/2]),F=[[u],[y===null?1:0],[A]],U=y;y=n.runWebGLProgram(P,$,"int32",F),Pl(n,U);let q=A/2,z=q*2;for(let K=q;K>=1;K/=2)w(z,K,y.shape)}let k=y;y=mc({inputs:{x:y},backend:n,attrs:{begin:0,size:[m,a]}}),Pl(n,k);let I=aC({inputs:{x:g,indices:y},backend:n,attrs:{axis:1,batchDims:1}});Pl(n,g);let N=c.slice(0,-1);N.push(a),k=y,y=ve({inputs:{x:y},attrs:{shape:N},backend:n}),Pl(n,k);let R=I;return I=ve({inputs:{x:I},attrs:{shape:N},backend:n}),Pl(n,R),[I,y]}var Xie={kernelName:Zi,backendName:"webgl",kernelFunc:qie},Kie=class{constructor(e,t,n,s,r,a){this.variableNames=["Image","Transforms"],this.outputShape=a;let o=n==="nearest"?1:2,i;switch(s){case"constant":i=1;break;case"reflect":i=2;break;case"wrap":i=3;break;case"nearest":i=4;break;default:i=1;break}this.userCode=` float mapCoord(float outCoord, float len) { float inCoord = outCoord; if(${i} == 2) { if (inCoord < 0.0) { if (len <= 1.0) { inCoord = 0.0; } else { float sz2 = 2.0 * len; if (inCoord < sz2) { inCoord = sz2 * float(int(float(-inCoord / sz2))) + inCoord; } inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0; } } else if (inCoord > len - 1.0) { if (len <= 1.0) { inCoord = 0.0; } else { float sz2 = 2.0 * len; inCoord -= sz2 * float(int(float(inCoord / sz2))); if (inCoord >= len) { inCoord = sz2 - inCoord - 1.0; } } } return clamp(inCoord, 0.0, len - 1.0); } else if (${i} == 3) { if (inCoord < 0.0) { if (len <= 1.0) { inCoord = 0.0; } else { float sz = len - 1.0; inCoord += len * (float(int(float(-inCoord / sz))) + 1.0); } } else if (inCoord > len - 1.0) { if (len <= 1.0) { inCoord = 0.0; } else { float sz = len - 1.0; inCoord -= len * float(int(float(inCoord / sz))); } } return clamp(inCoord, 0.0, len - 1.0); } else if (${i} == 4) { return clamp(outCoord, 0.0, len - 1.0); } else { return outCoord; } } float readWithFillValue(int batch, int coordY, int coordX, int channel) { float outputValue; if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) { outputValue = getImage(batch, coordY, coordX, channel); } else { outputValue = float(${r}); } return outputValue; } void main() { ivec4 coords = getOutputCoords(); float outputValue; int batch = coords[0]; int x = coords[2]; int y = coords[1]; int channel = coords[3]; float xf = float(x); float yf = float(y); float a1 = getTransforms(batch, 0); float a2 = getTransforms(batch, 1); float a3 = getTransforms(batch, 2); float b1 = getTransforms(batch, 3); float b2 = getTransforms(batch, 4); float b3 = getTransforms(batch, 5); float c1 = getTransforms(batch, 6); float c2 = getTransforms(batch, 7); float projection = c1 * xf + c2 * yf + 1.0; if (projection == 0.0) { outputValue = float(${r}); } else { float inX = (a1 * xf + a2 * yf + a3) / projection; float inY = (b1 * xf + b2 * yf + b3) / projection; float mapX = mapCoord(inX, float(${t})); float mapY = mapCoord(inY, float(${e})); if (${o} == 1) { int coordY = int(round(mapY)); int coordX = int(round(mapX)); outputValue = readWithFillValue(batch, coordY, coordX, channel); } else { float yFloor = floor(mapY); float xFloor = floor(mapX); float yCeil = yFloor + 1.0; float xCeil = xFloor + 1.0; float valueYFloor = (xCeil - mapX) * readWithFillValue(batch, int(yFloor), int(xFloor), channel) + (mapX - xFloor) * readWithFillValue(batch, int(yFloor), int(xCeil), channel); float valueYCeil = (xCeil - mapX) * readWithFillValue(batch, int(yCeil), int(xFloor), channel) + (mapX - xFloor) * readWithFillValue(batch, int(yCeil), int(xCeil), channel); outputValue = (yCeil - mapY) * valueYFloor + (mapY - yFloor) * valueYCeil; } } setOutput(outputValue); } `}};function Zie(e){let{inputs:t,backend:n,attrs:s}=e,{image:r,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:l,outputShape:c}=s,[u,d,p,h]=r.shape,[f,m]=c!=null?c:[d,p],g=[u,f,m,h],A=new Kie(d,p,o,i,l,g);return n.runWebGLProgram(A,[r,a],"float32")}var Yie={kernelName:Yi,backendName:"webgl",kernelFunc:Zie};function Jie(e){let{inputs:t,attrs:n,backend:s}=e,{axis:r}=n,{x:a}=t;lc(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let o=s.readSync(a.dataId),{outputValues:i,outputShape:l,indices:c}=yQ(o,r,a.shape,a.dtype);return[s.makeTensorInfo(l,a.dtype,i),s.makeTensorInfo([c.length],"int32",c)]}var Qie={kernelName:ef,backendName:"webgl",kernelFunc:Jie};function ele(e){let{inputs:t,backend:n,attrs:s}=e,{value:r}=t,{axis:a}=s;a<0&&(a+=r.shape.length);let o=r,i=o.shape.length,l=r.shape[a],c=new Array(i-1),u=0;for(let m=0;mn.disposeIntermediateTensorInfo(m)),f}var tle={kernelName:Ji,backendName:"webgl",kernelFunc:ele},nle=class{constructor(e,t){this.variableNames=["x","segmentIds"];let n=e.windowSize,s=e.batchSize,r=e.inSize,a=e.numSegments,o=a*Math.ceil(r/n);this.outputShape=[s,o];let i="0.0",l="sumValue",c=Math.floor(n/4)*4,u=n%4,d=` sumValue += dot(values, segFilter); `,p="";r%n>0&&(p=` if (inIdx < 0 || inIdx >= ${r}) { return initializationValue; } `);let h="";r%n>0&&(h=` if (inIdx < 0 || inIdx >= ${r}) { return -1.0; } `),this.userCode=` const float initializationValue = ${i}; float getValue(int batch, int inIdx) { ${p} return getX(batch, inIdx); } float getSegmentIdAtIndex(int inIdx) { ${h} return getSegmentIds(inIdx); } void main() { ivec2 coords = getOutputCoords(); int batch = coords[0]; int outIdx = coords[1]; int inOffset = int(floor(float(outIdx) / float( ${a})) * float(${n})); int currentSeg = int(mod(float(outIdx), float(${a}))); float sumValue = 0.0; for (int i = 0; i < ${c}; i += 4) { int inIdx = inOffset + i; vec4 values = vec4( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), getValue(batch, inIdx + 3) ); vec4 segFilter = vec4( int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0, int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0 ); ${d} } int inIdx = inOffset + ${c}; if (${u===1}) { vec4 values = vec4( getValue(batch, inIdx), initializationValue, initializationValue, initializationValue ); int inIdxSeg = int(getSegmentIdAtIndex(inIdx)); vec4 segFilter = vec4( int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, 0, 0, 0 ); ${d} } else if (${u===2}) { vec4 values = vec4( getValue(batch, inIdx), getValue(batch, inIdx + 1), initializationValue, initializationValue ); vec4 segFilter = vec4( int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, 0, 0 ); ${d} } else if (${u===3}) { vec4 values = vec4( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), initializationValue ); vec4 segFilter = vec4( int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0, 0 ); ${d} } setOutput(${l}); } `}};function sle(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,segmentIds:a}=t,{numSegments:o}=s,i=r.shape.length,l=[],c=0,u=E.getAxesPermutation([c],i),d=r;u!=null&&(d=qn({inputs:{x:r},backend:n,attrs:{perm:u}}),l.push(d),c=E.getInnerMostAxes(1,i)[0]);let p=E.segment_util.computeOutShape(d.shape,c,o),h=v.sizeFromShape([d.shape[c]]),f=ve({inputs:{x:d},backend:n,attrs:{shape:[-1,h]}});l.push(f);let m=Ed(r.dtype),g=(b,w,k,I,N)=>{let R=b.shape[0],O=b.shape[1],$=E.segment_util.segOpComputeOptimalWindowSize(O,N),P={windowSize:$,inSize:O,batchSize:R,numSegments:N},T=new nle(P,w),F=n.compileAndRun(T,[b,k],I);if(l.push(F),F.shape[1]===N)return F;let U=fC({backend:n,attrs:{start:0,stop:N,step:1,dtype:"float32"}}),q=xC({inputs:{x:U},backend:n,attrs:{reps:[O/$]}});return l.push(U),l.push(q),g(F,w,q,I,N)},A=g(f,"unsortedSegmentSum",a,m,o),x=ve({inputs:{x:A},backend:n,attrs:{shape:p}}),y=x;if(u!=null){l.push(x);let b=E.getUndoAxesPermutation(u);y=qn({inputs:{x:y},backend:n,attrs:{perm:b}})}return l.forEach(b=>n.disposeIntermediateTensorInfo(b)),y}var rle={kernelName:xd,backendName:"webgl",kernelFunc:sle},ale=[Dre,Ore,Aee,xee,wee,Iee,Tee,Ree,_ee,Pee,zee,Bee,Uee,jee,Qee,Kee,nte,ote,rte,cte,pte,fte,yte,Ite,Tte,Ete,Fte,Mte,Wte,Gte,JQ,Kte,ane,ine,Qte,dne,hne,une,gne,xne,wne,Sne,Cne,Ene,Fne,Mne,$ne,Bne,Une,Hne,Kne,Qne,sse,ose,ise,lse,cse,pse,fse,gse,yse,wse,Ise,Nse,Rse,Dse,Ose,Bse,Gse,YQ,jse,qte,Kse,Jse,tre,eee,are,ure,dre,yre,mre,wre,Ire,Ere,zre,jre,Gre,Zre,Jre,eae,Vre,nae,rae,lae,pae,gae,Sae,aee,Cae,Eae,_ae,Fae,$te,zae,Bae,Vae,Hae,Kae,nee,Yae,Jae,_te,bae,toe,uoe,aoe,iee,hoe,goe,boe,koe,Toe,Eoe,_oe,Foe,Moe,Boe,Uoe,Hoe,Xoe,Yoe,eie,kte,wae,sie,aie,iie,uie,die,hie,mie,Aie,xie,wie,Sie,Cie,Eie,$ie,Die,Fie,vae,fee,zie,Wie,Gie,Xie,Yie,mee,Qie,tle,rle,Lae];for(let e of ale)cr(e);var Hr=Y();Hr.registerFlag("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE",()=>15);Hr.registerFlag("WEBGPU_CPU_FORWARD",()=>!0);Hr.registerFlag("WEBGPU_MATMUL_WORK_PER_THREAD",()=>4);Hr.registerFlag("WEBGPU_USE_NAIVE_CONV2D",()=>!1);Hr.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE",()=>!1);Hr.registerFlag("WEBGPU_CONV_SEPARATE_IM2COL_SHADER",()=>!1);Hr.registerFlag("WEBGPU_USE_LOW_POWER_GPU",()=>!1);Hr.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e3);Hr.registerFlag("WEBGPU_USE_PROFILE_TOOL",()=>!1);Hr.registerFlag("WEBGPU_USE_IMPORT",()=>!1);function ole(e,t){if(Math.max(...e)>3)throw new Error("Cannot symbolically compute strides for rank > 4 tensor.");let n=e.length,s=e.map(a=>`${t}[${a}]`),r=new Array(n-1);r[n-2]=s[n-1];for(let a=n-3;a>=0;--a)r[a]=`(${r[a+1]} * ${s[a+1]})`;return r}function wn(e){if(e<=1)return"i32";if(e===2)return"vec2";if(e===3)return"vec3";if(e===4)return"vec4";throw Error(`GPU for rank ${e} is not yet supported`)}function n0(e,t){return e==="float32"?t?"vec4":"f32":e==="int32"||e==="bool"?t?"vec4":"i32":e}function s0(){return` [[stage(compute), workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)]] `}function Tx(){return` ${s0()} fn main([[builtin(local_invocation_id)]] localId : vec3, [[builtin(global_invocation_id)]] globalId : vec3, [[builtin(num_workgroups)]] numWorkgroups: vec3) `}function Xo(){return` ${s0()} fn main([[builtin(local_invocation_id)]] localId : vec3, [[builtin(global_invocation_id)]] globalId : vec3) `}function nt(){return` ${Tx()} { let index = getGlobalIndex(globalId, localId, numWorkgroups); `}function ile(e,t,n,s=!1){let r=` let workGroupSizeX = ${n.workGroupSize[0]}u; let workGroupSizeY = ${n.workGroupSize[1]}u; let workGroupSizeZ = ${n.workGroupSize[2]}u;`;if(s===!0){let h=kC(t.shape),f=` [[block]] struct Matrix0 { numbers: array<${n0(t.dtype,n.isVec4)}>; }; [[block]] struct Uniform { size : i32; numChannels : i32; outShapeStrides : vec2; dispatchSize : vec3; }; [[group(0), binding(0)]] var result : Matrix0; [[group(0), binding(2)]] var uniforms: Uniform; `;return[vC,f,r,wC,h,n.getUserCode()].join(` `)}let a=[],o="[[block]] struct Uniforms { NAN : f32; ";n.variableNames.forEach((h,f)=>{o+=`${h.charAt(0).toLowerCase()+h.slice(1)}Shape : ${wn(e[f].shape.length)}; `}),o+=`outShape : ${wn(t.shape.length)} ; `;let i=t.shape.length-1;o+=` outShapeStrides: ${wn(i)}; `,n.size&&(o+="size : i32; "),n.uniforms&&(o+=n.uniforms),o+="};",a.push(o),n.atomic?a.push(` [[block]] struct Matrix0 { numbers: array>; }; [[group(0), binding(0)]] var result : Matrix0; `):a.push(` [[block]] struct Matrix0 { numbers: array<${n0(t.dtype,n.isVec4)}>; }; [[group(0), binding(0)]] var result : Matrix0; `),n.variableNames.forEach((h,f)=>{a.push(` [[block]] struct Matrix${1+f} { numbers: array<${n0(e[f].dtype,n.isVec4)}>; }; [[group(0), binding(${1+f})]] var ${h} : Matrix${1+f}; `)}),o!==""&&a.push(` [[group(0), binding(${1+n.variableNames.length})]] var uniforms : Uniforms; `),a.push(r);let[l,c]=hle(t.shape,n.dispatchLayout),u=kC(t.shape),d=[vC,a.join(` `),wC,u,l,lle(t.shape.length)];if(n.atomic||d.push(ule(t.shape,t.dtype,n.isVec4)),c===t.shape.length){let h=e.map(f=>cle(f,t.shape,n.isVec4,n.dispatchLayout.x.length===t.shape.length)).join(` `);d.push(h)}return d.push(n.getUserCode()),d.join(` `)}var vC=` fn idiv(a: i32, b: i32, sign: f32) -> i32 { var res: i32 = a / b; let mod: i32 = a % b; if (sign < 0. && mod != 0) { res = res - 1; } return res; } fn isNanCustom(val : f32) -> bool { if (val > 0.0) { return false; } if (val < 0.0) { return false; } if (val == 0.0) { return false; } return true; } fn isNanCustomVec4F32(val : vec4) -> vec4 { var res = vec4 (0.0); for (var i = 0u; i < 4u; i = i + 1u) { if (isNanCustom(val[i])) { res[i] = 1.0; } else { res[i] = 0.0; } } return res; } // Checks whether coordinates lie within the bounds of the shape. fn coordsInBounds4D(coord : vec4, shape : vec4) -> bool { return all(coord >= vec4(0)) && all(coord < shape); } fn coordsInBounds3D(coord : vec3, shape : vec3) -> bool { return all(coord >= vec3(0)) && all(coord < shape); } fn coordsInBounds2D(coord : vec2, shape : vec2) -> bool { return all(coord >= vec2(0)) && all(coord < shape); } `,wC=` fn getFlatIndex1D(coord : i32, shape : i32) -> i32 { return coord; } fn getFlatIndex2D(coords : vec2, shape : vec2) -> i32 { return i32(dot(vec2(coords), vec2(f32(shape.y), 1.0))); } fn getFlatIndex3D(coords : vec3, shape : vec3) -> i32 { return i32(dot(vec3(coords), vec3(f32(shape.y) * f32(shape.z), f32(shape.z), 1.0))); } fn getFlatIndex4D(coords : vec4, shape : vec4) -> i32 { return i32(dot(vec4(coords), vec4( f32(shape.y) * f32(shape.z) * f32(shape.w), f32(shape.z) * f32(shape.w), f32(shape.w), 1.0))); } // Only used when the y/z dimension of workgroup size is 1. fn getGlobalIndex(globalId : vec3, localId : vec3, numWorkgroups: vec3) -> i32 { if (numWorkgroups.y == 1u && numWorkgroups.z == 1u) { return i32(globalId.x); } let localInvocationIndex = localId.z * workGroupSizeX * workGroupSizeY + localId.y * workGroupSizeX + localId.x; let workGroupID = (globalId - localId)/vec3( workGroupSizeX, workGroupSizeY, workGroupSizeZ); return i32((workGroupID.z * numWorkgroups.x * numWorkgroups.y + workGroupID.y * numWorkgroups.x + workGroupID.x) * (workGroupSizeX * workGroupSizeY * workGroupSizeZ) + localInvocationIndex); } `;function lle(e){let t="";switch(e){case 0:case 1:t+=` fn getOutputFlatIndex(coords : i32) -> i32 { return coords; } `;break;case 2:t+=` fn getOutputFlatIndex(coords : vec2) -> i32 { return i32(dot(vec2(coords), vec2(f32(uniforms.outShapeStrides), 1.0))); } `;break;case 3:t+=` fn getOutputFlatIndex(coords : vec3) -> i32 { return i32(dot(vec3(coords), vec3(f32(uniforms.outShapeStrides.x), f32(uniforms.outShapeStrides.y), 1.0))); } `;break;case 4:t+=` fn getOutputFlatIndex(coords : vec4) -> i32 { return i32(dot(vec4(coords), vec4( f32(uniforms.outShapeStrides.x), f32(uniforms.outShapeStrides.y), f32(uniforms.outShapeStrides.z), 1.0))); } `;break;default:v.assert(!1,()=>`Unsupported ${e}D shape`);break}return t}function ule(e,t,n){let s=e.length,r=n0(t,n),a;if(n?a=`fn setOutputFlat(flatIndex : i32, value : vec4) { result.numbers[flatIndex] = ${r}(value); } fn setOutputFlatI32(flatIndex : i32, value : vec4) { result.numbers[flatIndex] = ${r}(value); }`:a=`fn setOutputFlat(flatIndex : i32, value : f32) { result.numbers[flatIndex] = ${r}(value); } fn setOutputFlatI32(flatIndex : i32, value : i32) { result.numbers[flatIndex] = ${r}(value); }`,s>=2){let o=["d0","d1","d2","d3"].slice(0,s),i=wn(s);n?a+=` fn setOutput(${o.map(l=>`${l} : i32`).join(", ")}, value : vec4) { let flatIndex = getOutputFlatIndex(${i}(${o.join(", ")})); setOutputFlat(flatIndex / 4, value); } fn setOutputI32(${o.map(l=>`${l} : i32`).join(", ")}, value : vec4) { let flatIndex = getOutputFlatIndex(${i}(${o.join(", ")})); setOutputFlatI32(flatIndex / 4, value); } `:a+=` fn setOutput(${o.map(l=>`${l} : i32`).join(", ")}, value : f32) { let flatIndex = getOutputFlatIndex(${i}(${o.join(", ")})); setOutputFlat(flatIndex, value); } fn setOutputI32(${o.map(l=>`${l} : i32`).join(", ")}, value : i32) { let flatIndex = getOutputFlatIndex(${i}(${o.join(", ")})); setOutputFlatI32(flatIndex, value); } `}return a}function cle(e,t,n,s){let r=dle(e,n);return e.shape.length<=t.length&&(r+=ple(e,t,n,s)),r}function dle(e,t){let n=e.name,s=e.shape.length,r=wn(s),a="get"+n.charAt(0).toUpperCase()+n.slice(1),o=["d0","d1","d2","d3"].slice(0,s),i=o.map(u=>`${u} : i32`).join(", ");if(s<1)return t?` fn ${a}() -> vec4 { return vec4(${n}.numbers[0]); } `:` fn ${a}() ->f32 { return f32(${n}.numbers[0]); } `;let l=`uniforms.${n.charAt(0).toLowerCase()+n.slice(1)}Shape`,c=`${s}D`;return s===0&&(c="1D"),t?` fn ${a}(${i}) -> vec4 { return vec4(${n}.numbers[getFlatIndex${c}(${r}(${o.join(",")}), ${l}) / 4]); } `:` fn ${a}(${i}) -> f32 { return f32(${n}.numbers[getFlatIndex${c}(${r}(${o.join(",")}), ${l})]); } `}function ple(e,t,n,s){let r=e.name,a=r.charAt(0).toUpperCase()+r.slice(1),o="get"+a+"AtOutCoords",i=e.shape.length,l=t.length,c=wn(l);if(v.arraysEqual(e.shape,t)&&s)return n?` fn ${o}ByGlobalIndex(globalIndex : i32) -> vec4 { return vec4(${r}.numbers[globalIndex]); } fn ${o}ByCoords(coords : ${c}) -> vec4 { return vec4(${r}.numbers[${l>1?"getOutputFlatIndex(coords)":"coords"} / 4]); } `:` fn ${o}ByGlobalIndex(globalIndex : i32) -> f32 { return f32(${r}.numbers[globalIndex]); } fn ${o}ByCoords(coords : ${c}) -> f32 { return f32(${r}.numbers[${l>1?"getOutputFlatIndex(coords)":"coords"}]); } `;let u=E.getBroadcastDims(e.shape,t),d=l-i,p="";if(i===0)return n?` fn ${o}ByGlobalIndex(globalIndex : i32) -> vec4 { return get${a}(); } fn ${o}ByCoords(coords : ${c}) -> vec4 { return get${a}(); } `:` fn ${o}ByGlobalIndex(globalIndex : i32) -> f32{ return get${a}(); } fn ${o}ByCoords(coords : ${c}) -> f32{ return get${a}(); } `;l<2&&u.length>=1?p="coords = 0;":p=u.map(g=>`coords[${g+d}] = 0;`).join(` `);let h="";if(l<2&&i>0)h="coords";else if(l>1){let g=wn(i),A=e.shape.map((x,y)=>`coords[${y+d}]`).join(", ");h=`${g}(${A})`}else h="coords";let f=`uniforms.${r.charAt(0).toLowerCase()+r.slice(1)}Shape`,m=`${i}D`;return n?` fn ${o}ByGlobalIndex(globalIndex : i32) -> vec4 { var coords = getCoordsFromFlatIndex(globalIndex); ${p} return ${r}.numbers[getFlatIndex${m}(${h}, ${f}) / 4]; } fn ${o}ByCoords(coordsIn : ${c}) -> vec4 { var coords = coordsIn; ${p} return ${r}.numbers[getFlatIndex${m}(${h}, ${f}) / 4]; } `:` fn ${o}ByGlobalIndex(globalIndex : i32) -> f32 { var coords = getCoordsFromFlatIndex(globalIndex); ${p} return f32(${r}.numbers[getFlatIndex${m}(${h}, ${f})]); } fn ${o}ByCoords(coordsIn : ${c}) -> f32 { var coords = coordsIn; ${p} return f32(${r}.numbers[getFlatIndex${m}(${h}, ${f})]); } `}function hle(e,t){let{x:n,y:s=[],z:r=[]}=t,a=e.length;if(n.length===a)return[`fn getOutputCoordsWithFlatDispatchLayout(globalId : vec3, localId : vec3, numWorkgroups: vec3) -> ${wn(a)}{ let globalIndex = getGlobalIndex(globalId, localId, numWorkgroups); return getCoordsFromFlatIndex(globalIndex); } `,a];let o="",i=[n,s,r],l=0;for(let p=0;p) -> ${u} { ${o} `;return c.length===0?d+=`return ${u}(0); }`:d+=`return ${u}(${c.join(",")}); }`,[d,l]}function kC(e){let t=e.length;if(t<=1)return"fn getCoordsFromFlatIndex(index : i32) -> i32 { return index; }";let n=v.computeStrides(e),s=wn(t),r=[];for(let o=0;o vec2 { let d0 = index / uniforms.outShapeStrides; let d1 = index - d0 * uniforms.outShapeStrides; return vec2(d0, d1); }`;let a="var index2 = index;"+n.map((o,i)=>{let l=`let ${r[i]} = index2 / uniforms.outShapeStrides[${i}]`,c=i===n.length-1?`let ${r[i+1]} = index2 - ${r[i]} * uniforms.outShapeStrides[${i}]`:`index2 = index2 - ${r[i]} * uniforms.outShapeStrides[${i}]`;return`${l}; ${c};`}).join("");return` fn getCoordsFromFlatIndex(index : i32) -> ${s} { ${a} return ${s}(${r.join(",")}); } `}var SC={};Oe(SC,{ArrayBufferToTypedArray:()=>IC,GPUBytesPerElement:()=>$x,computeDispatch:()=>Fe,computeWorkGroupSizeForConv2d:()=>Nx,computeWorkGroupSizeForMatMul:()=>Ex,computeWorkPerThreadForConv2d:()=>Rx,flatDispatchLayout:()=>Xe,isWebGPUSupported:()=>_x,tilesFitEvenlyIntoShape:()=>ua});var yc=65535,Fl=e=>{let t=1;for(let n=0;nn%e[s]==0)}function Fe(e,t,n=[1,1,1],s=[1,1,1]){let[r,a,o]=[Math.ceil(Fl(e.x.map(l=>t[l]))/(n[0]*s[0])),e.y?Math.ceil(Fl(e.y.map(l=>t[l]))/(n[1]*s[1])):1,e.z?Math.ceil(Fl(e.z.map(l=>t[l]))/(n[2]*s[2])):1];if(r<=yc&&a<=yc&&o<=yc)return[r,a,o];v.assert(r>yc&&e.y===void 0&&e.z===void 0,()=>"Dispatch size exceeds WebGPU limits in Y or Z dimension.");let i=Math.ceil(Math.sqrt(r));return i>yc?(i=Math.ceil(Math.cbrt(r)),v.assert(i<=yc,()=>"Total dispatch size exceeds WebGPU maximum."),[i,i,i]):[i,i,1]}function Nx(e,t){let n=Fl(e.x.map(r=>t[r])),s=Fl(e.y.map(r=>t[r]));return n<=4?[4,16,1]:s<=4?[16,4,1]:[16,16,1]}function Ex(e,t,n){return e===1?[32,1,1]:n===1?[1,32,1]:[8,8,1]}function Rx(e,t){let n=Fl(e.x.map(r=>t[r])),s=Fl(e.y.map(r=>t[r]));return n<=4?[1,2,1]:s<=4?[2,1,1]:[2,2,1]}function Xe(e){return{x:e.map((t,n)=>n)}}function $x(e){if(e==="float32"||e==="int32"||e==="bool"||e==="string")return 4;if(e==="complex64")return 8;throw new Error(`Unknown dtype ${e}`)}function IC(e,t){if(t==="float32")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"||t==="string"){let n=new Int32Array(e),s=new ArrayBuffer(n.length),r=new Uint8Array(s);for(let a=0;a(a >= vec4(1.0)) * vec4(b >= vec4(1.0)));`,Dle=` if (isNanCustom(a)) { return a; } if (isNanCustom(b)) { return b; } `,CC=` if (isNaN.r > 0.) { resultTemp.r = uniforms.NAN; } if (isNaN.g > 0.) { resultTemp.g = uniforms.NAN; } if (isNaN.b > 0.) { resultTemp.b = uniforms.NAN; } if (isNaN.a > 0.) { resultTemp.a = uniforms.NAN; } `,Ple=` let s = sign(a) * sign(b); let ia = i32(round(a)); let ib = i32(round(b)); return f32(idiv(ia, ib, s)); `,Fle=` let ia = vec4(round(a)); let ib = vec4(round(b)); let cond = ib != vec4(0); var resultTemp = vec4(0); let s = sign(a) * sign(b); // Windows (D3D) wants guaranteed non-zero int division at compile-time. if (cond[0]) { resultTemp[0] = idiv(ia[0], ib[0], s[0]); } if (cond[1]) { resultTemp[1] = idiv(ia[1], ib[1], s[1]); } if (cond[2]) { resultTemp[2] = idiv(ia[2], ib[2], s[2]); } if (cond[3]) { resultTemp[3] = idiv(ia[3], ib[3], s[3]); } return vec4(resultTemp); `,Ole="return f32(a != b);",Mle="return vec4(a != b);",zle=` if(a < 0.0 && floor(b) < b) { return uniforms.NAN; } if (b == 0.0) { return 1.0; } if (round(abs(b) % 2.0) != 1.0) { return pow(abs(a), b); } return sign(a) * pow(abs(a), b); `,Lle=` let isModRound1Bool = vec4(round(abs(b) % vec4(2.0))) == vec4(1); let isModRound1 = vec4(isModRound1Bool); let multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1); var resultTemp = multiplier * pow(abs(a), b); // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS let isExpZero = b == vec4(0.0); if (isExpZero.r) { resultTemp.r = 1.0; } if (isExpZero.g) { resultTemp.g = 1.0; } if (isExpZero.b) { resultTemp.b = 1.0; } if (isExpZero.a) { resultTemp.a = 1.0; } let isNaN = vec4(a < vec4(0.0)) * vec4(floor(b) < b); ${CC} return resultTemp; `,Ble="if (a < 0.0) { return b * a; } return a;",Wle=` let aLessThanZero = vec4(a < vec4(0.0)); return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); `;function TC(e,t){let n=t?CC:Dle;return t?` var resultTemp = vec4(${e}(a, b)); let isNaN = min(vec4(isNanCustomVec4F32(a)) + vec4(isNanCustomVec4F32(b)), vec4(1.0)); `+n+` return resultTemp; `:n+` return ${e}(a, b); `}function Ip(e,t){switch(e){case 0:return yle;case 1:return fle;case 2:return ble;case 3:return Ale;case 4:return t?wle:vle;case 5:return t?Sle:kle;case 6:return t?Cle:Ile;case 7:return t?Nle:Tle;case 8:return t?Rle:Ele;case 9:return t?_le:$le;case 10:return t?Mle:Ole;case 11:return xle;case 12:return t?Fle:Ple;case 14:return t?Wle:Ble;case 15:return TC("max",t);case 16:return TC("min",t);case 13:return t?Lle:zle;case 17:return mle;case 18:return gle;default:throw new Error(`BinaryType ${e} is not implemented!`)}}var bt;(function(e){e[e.ABS=0]="ABS",e[e.CEIL=1]="CEIL",e[e.COS=2]="COS",e[e.COSH=3]="COSH",e[e.ELU=4]="ELU",e[e.EXP=5]="EXP",e[e.EXPM1=6]="EXPM1",e[e.FLOOR=7]="FLOOR",e[e.LINEAR=8]="LINEAR",e[e.LOG=9]="LOG",e[e.LOGICAL_NOT=10]="LOGICAL_NOT",e[e.NEG=11]="NEG",e[e.PRELU=12]="PRELU",e[e.RELU=13]="RELU",e[e.RELU6=14]="RELU6",e[e.RSQRT=15]="RSQRT",e[e.SIN=16]="SIN",e[e.SINH=17]="SINH",e[e.SIGMOID=18]="SIGMOID",e[e.SQRT=19]="SQRT",e[e.SQUARE=20]="SQUARE",e[e.TANH=21]="TANH",e[e.TO_INT=22]="TO_INT"})(bt||(bt={}));var Vle="return abs(a);",Ule="return ceil(a);",Gle="return cos(a);",Hle=` let e2x = exp(-a); return (e2x + 1.0 / e2x) / 2.0; `,jle="return exp(a) - 1.0;",qle="if (a >= 0.0) { return a; } return (exp(a) - 1.0);",Xle=` var resFloat = exp(a) - vec4(1.0); if (a.r >= 0.0) { resFloat.r = a.r; } if (a.g >= 0.0) { resFloat.g = a.g; } if (a.b >= 0.0) { resFloat.b = a.b; } if (a.a >= 0.0) { resFloat.a = a.a; } return resFloat; `,Kle="return exp(a);",Zle="return floor(a);",Yle="return a;",Jle=`if (a < 0.0) { return 1.0/0.0; } return log(a);`,Qle="return f32(!(a >= 1.0));",eue="return -a;",tue="return (a < 0.0) ? b * a : a;",nue="return max(a, 0.0);",sue="return clamp(a, 0.0, 6.0);",rue="return clamp(a, vec4(0.0, 0.0, 0.0, 0.0), vec4(6.0, 6.0, 6.0, 6.0));",aue=` var resFloat = a * vec4(a >= vec4(0.0)); let isNaN = isNan(a); if (isNaN.r) { resFloat.r = a.r; } if (isNaN.g) { resFloat.g = a.g; } if (isNaN.b) { resFloat.b = a.b; } if (isNaN.a) { resFloat.a = a.a; } return resFloat; `,oue="return 1.0/sqrt(a);",iue="return 1.0 / (1.0 + exp(-1.0 * a));",lue="return sin(a);",uue=` let e2x = exp(a); return (e2x - 1.0 / e2x) / 2.0; `,cue="return sqrt(a);",due="return a * a;",pue=` let e2x = exp(-2.0 * abs(a)); return sign(a) * (1.0 - e2x) / (1.0 + e2x); `,hue="return f32(i32((a)));";function xc(e,t){switch(e){case 0:return Vle;case 2:return Gle;case 3:return Hle;case 1:return Ule;case 4:return t?Xle:qle;case 5:return Kle;case 6:return jle;case 7:return Zle;case 8:return Yle;case 9:return Jle;case 10:return Qle;case 11:return eue;case 12:return tue;case 13:return t?aue:nue;case 14:return t?rue:sue;case 15:return oue;case 18:return iue;case 16:return lue;case 17:return uue;case 19:return cue;case 20:return due;case 21:return pue;case 22:return hue;default:throw new Error(`BinaryType ${e} is not implemented!`)}}function ca(e,t=!1){if(e===null)return null;if(e==="linear")return xc(bt.LINEAR);if(e==="relu")return xc(bt.RELU,t);if(e==="elu")return xc(bt.ELU,t);if(e==="relu6")return xc(bt.RELU6,t);if(e==="prelu")return Ip(Ut.PRELU,t);if(e==="sigmoid")return xc(bt.SIGMOID);throw new Error(`Activation ${e} has not been implemented for the WebGPU backend.`)}function NC(e,t){let n={RowPerThread:e[1],ColPerThread:e[0],TileAOuter:t[1]*e[1],TileBOuter:t[0]*e[0],TileInner:t[0]*e[0]};return` var mm_Asub : array, ${n.TileInner/n.ColPerThread}>, ${n.TileAOuter}>; var mm_Bsub : array, ${n.TileBOuter/n.ColPerThread}>, ${n.TileInner}>; let RowPerThread = ${n.RowPerThread}; let ColPerThread = ${n.ColPerThread}; // only support ColPerThread = 4 let TileAOuter = ${n.TileAOuter}; let TileBOuter = ${n.TileBOuter}; let TileInner = ${n.TileInner}; ${Xo()} { let tileRow = i32(localId.y) * RowPerThread; let tileCol = i32(localId.x); let globalRow = i32(globalId.y) * RowPerThread; let globalCol = i32(globalId.x); let numTiles = (uniforms.dimInner - 1) / TileInner + 1; var acc: array, ${n.RowPerThread}>; var ACached : vec4; var BCached : array, 4>; // Loop over shared dimension. var globalColA = tileCol; let RowPerThreadB = TileInner / ${t[1]}; let tileRowB = i32(localId.y) * RowPerThreadB; for (var t = 0; t < numTiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) { let inputRow = tileRow + innerRow; let inputCol = tileCol; mm_Asub[inputRow][inputCol] = mm_readA(globalRow + innerRow, globalColA, globalId); } globalColA = globalColA + TileInner / ColPerThread; // Load one tile of B into local memory. for (var innerRow = 0; innerRow < RowPerThreadB; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(t * TileInner + inputRow, globalCol, globalId); } workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < TileInner / ColPerThread; k = k + 1) { BCached[0] = mm_Bsub[k * ColPerThread][tileCol]; BCached[1] = mm_Bsub[k * ColPerThread + 1][tileCol]; BCached[2] = mm_Bsub[k * ColPerThread + 2][tileCol]; BCached[3] = mm_Bsub[k * ColPerThread + 3][tileCol]; for (var i = 0; i < RowPerThread; i = i + 1) { ACached = mm_Asub[tileRow + i][k]; acc[i] = BCached[0] * ACached.x + acc[i]; acc[i] = BCached[1] * ACached.y + acc[i]; acc[i] = BCached[2] * ACached.z + acc[i]; acc[i] = BCached[3] * ACached.w + acc[i]; } } workgroupBarrier(); } for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) { mm_write(globalRow + innerRow, globalCol, acc[innerRow], globalId); } }`}function fue(e){return` var mm_Asub : array, ${e[0]}>; let tileSize = ${e[0]*4}; ${Xo()} { let tileCol = i32(localId.x); let globalCol = i32(globalId.x); let globalRow = i32(globalId.y); let numTiles = (uniforms.dimInner - 1) / tileSize + 1; // Without this initialization strange values show up in acc. var acc = vec4(0.0); // Loop over shared dimension. for (var t = 0; t < numTiles; t = t + 1) { // Load one tile of A into local memory. let colA = t * tileSize / 4 + tileCol; mm_Asub[tileCol] = mm_readA(globalRow, colA, globalId); workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < tileSize / 4; k = k + 1) { let rowB = t * tileSize + k * 4; let BCached0 = mm_readB(rowB, globalCol, globalId); let BCached1 = mm_readB(rowB + 1, globalCol, globalId); let BCached2 = mm_readB(rowB + 2, globalCol, globalId); let BCached3 = mm_readB(rowB + 3, globalCol, globalId); let ACached = mm_Asub[k]; acc = acc + BCached0 * ACached.x; acc = acc + BCached1 * ACached.y; acc = acc + BCached2 * ACached.z; acc = acc + BCached3 * ACached.w; } workgroupBarrier(); } if (globalRow < uniforms.dimAOuter && globalCol < uniforms.dimBOuter) { mm_write(globalRow, globalCol, acc, globalId); } } `}var mue=class{constructor(e,t,n,s=null,r=null,a=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32; dimBOuter : i32; dimInner : i32;",this.workGroupSize=[16,16,1],this.isVec4=!0,this.vecSize=4,this.outputShape=t,this.workGroupSize=Ex(t[1],e[2],t[2]),this.dispatchLayout={x:[2],y:[1],z:[0]},t[1]===1&&(n=1),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.vecSize,n,1]);let o=s!=null,i=a!=null;o&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.workPerThread=n,this.aShape=e,this.addBias=o,this.activation=r,this.hasPreluActivationWeights=i,[this.fitA,this.fitB]=this.getShapeFit(),this.shaderKey=`matMulPackedVec4_${n}_${this.activation}_${this.fitA}_${this.fitB}_${this.outputShape[1]>1}`}getShapeFit(){let e=this.aShape[2],t=this.outputShape[2],n=[this.outputShape[0],e,t],s=this.workGroupSize[1]*this.workPerThread,r=this.workGroupSize[0]*this.vecSize,a=r,o=[s,a],i=[a,r];return[ua(o,this.aShape.slice(1)),ua(i,n.slice(1))]}getUserCode(){let e=this.fitA?"return A.numbers[batch * batchASize + row * uniforms.dimInner / 4 + col]":`if (coordsInBounds2D(vec2(row, col * 4), vec2(uniforms.dimAOuter, uniforms.dimInner))) { return A.numbers[batch * batchASize + row * uniforms.dimInner / 4 + col]; } return vec4(0.0)`,t=this.fitB?"return B.numbers[batch * batchBSize + row * uniforms.dimBOuter / 4 + col]":`if(coordsInBounds2D(vec2(row, col * 4), vec2(uniforms.dimInner, uniforms.dimBOuter))) { return B.numbers[batch * batchBSize + row * uniforms.dimBOuter / 4 + col]; } return vec4(0.0)`,n="",s="";if(this.activation){let o=ca(this.activation,this.isVec4);this.hasPreluActivationWeights?n=`fn activation(a : vec4, outCoord : vec3) -> vec4 { let b = getPreluActivationWeightsAtOutCoordsByCoords(outCoord); ${o} }`:n=` fn activation(a : vec4, outCoord : vec3) -> vec4 { ${o} }`,s="value = activation(value, outCoord);"}let r=this.addBias?"value = value + getBiasAtOutCoordsByCoords(outCoord);":"";return` ${n} fn mm_readA(row : i32, col : i32, globalId : vec3) -> vec4 { let batchASize = uniforms.aShape[1] * uniforms.aShape[2] / ${this.vecSize}; let batch = i32(globalId.z); ${e}; } fn mm_readB(row : i32, col : i32, globalId : vec3) -> vec4 { let batchBSize = uniforms.bShape[1] * uniforms.bShape[2] / ${this.vecSize}; let batch = i32(globalId.z); ${t}; } fn mm_write(row : i32, col : i32, valueIn : vec4, globalId : vec3) { if (row < uniforms.aShape[1] && col * 4 < uniforms.bShape[2]) { var value = valueIn; let batch = i32(globalId.z); let outCoord = vec3(batch, row, col * 4); ${r} ${s} setOutput(outCoord[0], outCoord[1], outCoord[2], value); } } ${this.outputShape[1]>1?NC([this.vecSize,this.workPerThread,1],this.workGroupSize):fue(this.workGroupSize)} `}};function Dx(e,t){let n=t[1]*e[1],s=t[0]*e[0],r=n>s?n:s;return` var mm_Asub : array, ${n}>; var mm_Bsub : array, ${r}>; ${Xo()} { let tileRow = i32(localId.y) * ${e[1]}; let tileCol = i32(localId.x) * ${e[0]}; let globalRow = i32(globalId.y) * ${e[1]}; let globalCol = i32(globalId.x) * ${e[0]}; let numTiles = (uniforms.dimInner - 1) / ${r} + 1; var acc : array, ${e[1]}>; var ACached : f32; var BCached : array; // Without this initialization strange values show up in acc. for (var innerRow = 0; innerRow < ${e[1]}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${e[0]}; innerCol = innerCol + 1) { acc[innerRow][innerCol] = 0.0; } } let ColPerThreadA = ${r} / ${t[0]}; let tileColA = i32(localId.x) * ColPerThreadA; let RowPerThreadB = ${r} / ${t[1]}; let tileRowB = i32(localId.y) * RowPerThreadB; // Loop over shared dimension. for (var t = 0; t < numTiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < ${e[1]}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ColPerThreadA; innerCol = innerCol + 1) { let inputRow = tileRow + innerRow; let inputCol = tileColA + innerCol; mm_Asub[inputRow][inputCol] = mm_readA( globalRow + innerRow, t * ${r} + inputCol, globalId); } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < RowPerThreadB; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${e[0]}; innerCol = innerCol + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol + innerCol; mm_Bsub[inputRow][inputCol] = mm_readB( t * ${r} + inputRow, globalCol + innerCol, globalId); } } workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < ${r}; k = k + 1) { for (var inner = 0; inner < ${e[0]}; inner = inner + 1) { BCached[inner] = mm_Bsub[k][tileCol + inner]; } for (var innerRow = 0; innerRow < ${e[1]}; innerRow = innerRow + 1) { ACached = mm_Asub[tileRow + innerRow][k]; for (var innerCol = 0; innerCol < ${e[0]}; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < ${e[1]}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${e[0]}; innerCol = innerCol + 1) { if ((globalCol + innerCol) < uniforms.dimBOuter && (globalRow + innerRow) < uniforms.dimAOuter) { mm_write(globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol], globalId); } } } } `}function gue(e){return` let TileSize = ${e[0]*4}; var mm_Asub : array, ${e[0]}>; ${Xo()} { let tileCol = i32(localId.x); let globalCol = i32(globalId.x); let globalRow = i32(globalId.y); let numTiles = (uniforms.dimInner - 1) / TileSize + 1; // Without this initialization strange values show up in acc. var acc = 0.0; // Loop over shared dimension. for (var t = 0; t < numTiles; t = t + 1) { // Load one tile of A into local memory. let colA = t * TileSize + tileCol * 4; mm_Asub[tileCol] = vec4(mm_readA(globalRow, colA, globalId), mm_readA(globalRow, colA + 1, globalId), mm_readA(globalRow, colA + 2, globalId), mm_readA(globalRow, colA + 3, globalId)); workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < TileSize / 4; k = k + 1) { let rowB = t * TileSize + k * 4; let BCached = vec4(mm_readB(rowB, globalCol, globalId), mm_readB(rowB + 1, globalCol, globalId), mm_readB(rowB + 2, globalCol, globalId), mm_readB(rowB + 3, globalCol, globalId)); let ACached = mm_Asub[k]; acc = acc + dot(ACached, BCached); } workgroupBarrier(); } if (globalRow < uniforms.dimAOuter && globalCol < uniforms.dimBOuter) { mm_write(globalRow, globalCol, acc, globalId); } } `}var EC=class{constructor(e,t,n,s=!1,r=!1,a=null,o=null,i=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32; dimBOuter : i32; dimInner : i32;",this.workGroupSize=[16,16,1],this.outputShape=t,this.dispatchLayout={x:[2],y:[1],z:[0]};let l=s?e[1]:e[2];this.workGroupSize=Ex(t[1],l,t[2]),(t[1]===1||t[2]===1)&&(n=1),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize,[n,n,1]),v.arraysEqual(this.dispatch,[1,1,1])&&(n=1,this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize,[n,n,1]));let c=a!=null,u=i!=null;c&&this.variableNames.push("bias"),u&&this.variableNames.push("preluActivationWeights"),this.workPerThread=n,this.aShape=e,this.transposeA=s,this.transposeB=r,this.addBias=c,this.activation=o,this.hasPreluActivationWeights=u;let d=this.outputShape[2],p=this.transposeB?[this.outputShape[0],d,l]:[this.outputShape[0],l,d];[this.fitA,this.fitB]=this.getShapeFit(p),this.shaderKey=`matMulPacked_${this.workPerThread}_${s}_${r}_${this.activation}_${this.fitA}_${this.fitB}_${this.outputShape[1]>1}`}getShapeFit(e){let t=this.workGroupSize[1]*this.workPerThread,n=this.workGroupSize[0]*this.workPerThread,s=t>n?t:n;this.outputShape[1]===1&&(s*=4),v.assert(s%this.workGroupSize[0]==0&&s%this.workGroupSize[1]==0,()=>"tileInner must be multiple of workgroupsize.x and workgroupsize.y");let r=[t,s],a=[s,n];return[ua(r,this.aShape.slice(1)),ua(a,e.slice(1))]}getUserCode(){let e;this.transposeA===!1?e=this.fitA?"return A.numbers[batch * batchASize + row * uniforms.dimInner + col];":`if(coordsInBounds2D(vec2(row, col), vec2(uniforms.dimAOuter, uniforms.dimInner))) { return A.numbers[batch * batchASize + row * uniforms.dimInner + col]; } return 0.0;`:e=this.fitA?"return A.numbers[batch * batchASize + col * uniforms.dimAOuter + row];":`if(coordsInBounds2D(vec2(row, col), vec2(uniforms.dimAOuter, uniforms.dimInner))) { return A.numbers[batch* batchASize + col * uniforms.dimAOuter + row]; } return 0.0;`;let t;this.transposeB===!1?t=this.fitB?"return B.numbers[batch * batchBSize + row * uniforms.dimBOuter + col];":`if(coordsInBounds2D(vec2(row, col), vec2(uniforms.dimInner, uniforms.dimBOuter))) { return B.numbers[batch * batchBSize + row * uniforms.dimBOuter + col]; } return 0.0;`:t=this.fitB?"return B.numbers[batch * batchBSize + col * uniforms.dimInner + row];":`if(coordsInBounds2D(vec2(row, col), vec2(uniforms.dimInner, uniforms.dimBOuter))) { return B.numbers[batch * batchBSize + col * uniforms.dimInner + row]; } return 0.0;`;let n="",s="";if(this.activation){let o=ca(this.activation,!1);this.hasPreluActivationWeights?n=`fn activation(a : f32, outCoord : vec3) -> f32 { let b = getPreluActivationWeightsAtOutCoordsByCoords(outCoord); ${o} }`:n=` fn activation(a : f32, outCoord : vec3) -> f32 { ${o} } `,s="value = activation(value, outCoord);"}let r=this.addBias?"value = value + getBiasAtOutCoordsByCoords(outCoord);":"";return` ${n} fn mm_readA(row : i32, col : i32, globalId : vec3) -> f32 { let batchASize = uniforms.aShape[1] * uniforms.aShape[2]; let batch = i32(globalId.z); ${e} } fn mm_readB(row : i32, col : i32, globalId : vec3) -> f32 { let batch = i32(globalId.z); let batchBSize = uniforms.bShape[1] * uniforms.bShape[2]; ${t} } fn mm_write(row : i32, col : i32, valueIn : f32, globalId : vec3) { var value = valueIn; let batch = i32(globalId.z); let outCoord = vec3(batch, row, col); ${r} ${s} setOutput(batch, row, col, value); } ${this.outputShape[1]>1?Dx([this.workPerThread,this.workPerThread,1],this.workGroupSize):gue(this.workGroupSize)} `}};function Aue(){return` var sumValues : array; ${Xo()} { let coords = getOutputCoordsWithNonFlatDispatchLayout(globalId); let batch = coords[0]; let row = coords[1]; let col = coords[2]; var sum = 0.0; let Length = uniforms.dimInner; for (var k = i32(localId.x); k < Length; k = k + i32(workGroupSizeX)) { let dataA = mm_readA(batch, row, k); let dataB = mm_readB(batch, k, col); sum = sum + dataA * dataB; } sumValues[localId.x] = sum; workgroupBarrier(); for(var currentSize = workGroupSizeX / 2u; currentSize > 1u; currentSize = currentSize / 2u) { if (localId.x < currentSize) { sumValues[localId.x] = sumValues[localId.x] + sumValues[localId.x + currentSize]; } workgroupBarrier(); } if (localId.x == 0u) { sum = sumValues[0] + sumValues[1]; mm_write(batch, row, col, sum); } } `}var yue=class{constructor(e,t=!1,n=!1,s=null,r=null,a=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32; dimBOuter : i32; dimInner : i32;",this.workGroupSize=[256,1,1],this.outputShape=e,this.dispatchLayout={x:[],y:[1,2],z:[0]},this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize);let o=s!=null,i=a!=null;o&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.transposeA=t,this.transposeB=n,this.addBias=o,this.activation=r,this.hasPreluActivationWeights=i,this.shaderKey=`matMulReduce_${this.activation}_${t}_${n}`}getUserCode(){let e;this.transposeA===!1?e="return A.numbers[batch * batchASize + row * uniforms.dimInner + col];":e="return A.numbers[batch * batchASize + col * uniforms.dimAOuter + row];";let t;this.transposeB===!1?t="return B.numbers[batch * batchBSize + row * uniforms.dimBOuter + col];":t="return B.numbers[batch * batchBSize + col * uniforms.dimInner + row];";let n="",s="";if(this.activation){let o=ca(this.activation,!1);this.hasPreluActivationWeights?n=`fn activation(a : f32, outCoord : vec3) -> f32 { let b = getPreluActivationWeightsAtOutCoordsByCoords(outCoord); ${o} }`:n=` fn activation(a : f32, outCoord : vec3) -> f32 { ${o} } `,s="value = activation(value, outCoord);"}let r=this.addBias?"value = value + getBiasAtOutCoordsByCoords(outCoord);":"";return` ${n} fn mm_readA(batch: i32, row : i32, col : i32) -> f32 { let batchASize = uniforms.aShape[1] * uniforms.aShape[2]; ${e} } fn mm_readB(batch: i32, row : i32, col : i32) -> f32 { let batchBSize = uniforms.bShape[1] * uniforms.bShape[2]; ${t} } fn mm_write(batch: i32, row : i32, col : i32, valueIn : f32) { var value = valueIn; let outCoord = vec3(batch, row, col); ${r} ${s} setOutput(batch, row, col, value); } ${Aue()} `}};function xue(e){let t=e[1]/2,n=e[0],s=t>n?t:n;return` var mm_Asub1 : array, ${t}>; var mm_Bsub1 : array, ${s}>; var mm_Asub2 : array, ${t}>; var mm_Bsub2 : array, ${s}>; // If the output size is small for matrix multiplication, avoid to use vec4 // and handle some elements per thread to optimally utilize the ALU. // Introduces two shared memory buffers, some logical threads could handle // arithmetic operations and others handle IO operations between barrier api, // makes ALUs and load/store units work simultaneously, could improves // the performance. ${Xo()} { let tileRow = i32(localId.y); let tileCol = i32(localId.x); let globalRow = i32(globalId.y); let globalCol = i32(globalId.x); // uniforms.dimInner should be greater than 0. let numTiles = (uniforms.dimInner - 1) / ${s} + 1; var acc = 0.0; var globalColA = tileCol; var globalRowB = tileRow; for (var t = 0; t < numTiles; t = t + 1) { if (t == 0) { if (tileRow < ${t}) { // Load one tile of A and B into local memory. // globalRow is always greater than or equal tileRow. mm_Asub1[tileRow][tileCol] = mm_readA((globalRow - tileRow) / 2 + tileRow, globalColA, globalId); globalColA = globalColA + ${s}; mm_Bsub1[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId); globalRowB = globalRowB + ${s}; } } else { if (tileRow < ${t}) { // Load one tile of A and B into local memory. // globalRow is always greater than or equal tileRow. mm_Asub1[tileRow][tileCol] = mm_readA((globalRow - tileRow) / 2 + tileRow, globalColA, globalId); globalColA = globalColA + ${s}; mm_Bsub1[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId); globalRowB = globalRowB + ${s}; } else { // Compute acc values for a single thread. for (var k = 0; k < ${s}; k = k + 1) { let subRow = tileRow - ${t}; if (subRow < 0) { continue; } acc = acc + mm_Asub2[subRow][k] * mm_Bsub2[k][tileCol]; } } } workgroupBarrier(); if (t != 0) { t = t + 1; } if (t < numTiles) { if (tileRow < ${t}) { // Load one tile of A and B into local memory. // globalRow is always greater than or equal tileRow. mm_Asub2[tileRow][tileCol] = mm_readA((globalRow - tileRow) / 2 + tileRow, globalColA, globalId); globalColA = globalColA + ${s}; mm_Bsub2[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId); globalRowB = globalRowB + ${s}; } else { // Compute acc values for a single thread. for (var k = 0; k < ${s}; k = k + 1) { let subRow = tileRow - ${t}; if (subRow < 0) { continue; } acc = acc + mm_Asub1[subRow][k] * mm_Bsub1[k][tileCol]; } } } workgroupBarrier(); } let writeCol = (globalRow - tileRow) / 2 + tileRow - ${t}; if (tileRow >= ${t} && writeCol >= 0) { mm_write(writeCol, globalCol, acc, globalId); } } `}var bue=class{constructor(e,t,n,s=null,r=null,a=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32; dimBOuter : i32; dimInner : i32;",this.workGroupSize=[8,16,1],v.assert(e[1]<=16||t[2]<=16,()=>"This program can be only used when A width or B Height are small"),this.outputShape=n,this.dispatchLayout={x:[2],y:[1],z:[0]},this.dispatch=[Math.ceil(n[2]/this.workGroupSize[0]),Math.ceil(n[1]*2/this.workGroupSize[1]),n[0]];let o=s!=null;o&&this.variableNames.push("bias");let i=a!=null;i&&this.variableNames.push("preluActivationWeights"),this.addBias=o,this.activation=r,this.hasPreluActivationWeights=i,this.shaderKey=`matMulSmallOutputSize_${this.activation}`}getUserCode(){let e=`if (coordsInBounds2D(vec2(row, col), vec2(uniforms.dimAOuter, uniforms.dimInner))) { return A.numbers[batch * batchASize + row * uniforms.dimInner + col]; } return 0.0;`,t=`if (coordsInBounds2D(vec2(row, col), vec2(uniforms.dimInner, uniforms.dimBOuter))) { return B.numbers[batch * batchBSize + row * uniforms.dimBOuter + col]; } return 0.0;`,n="",s="";if(this.activation){let o=ca(this.activation,!1);this.hasPreluActivationWeights?n=`fn activation(a : f32, outCoord : vec3) -> f32 { let b = getPreluActivationWeightsAtOutCoordsByCoords(outCoord); ${o} }`:n=`fn activation(a : f32, outCoord : vec3) -> f32 { ${o} }`,s="value = activation(value, outCoord);"}let r=this.addBias?"value = value + getBiasAtOutCoordsByCoords(outCoord);":"";return` ${n} fn mm_readA(row : i32, col : i32, globalId : vec3) -> f32 { let batchASize = uniforms.aShape[1] * uniforms.aShape[2]; let batch = i32(globalId.z); ${e} } fn mm_readB(row : i32, col : i32, globalId : vec3) -> f32 { let batch = i32(globalId.z); let batchBSize = uniforms.bShape[1] * uniforms.bShape[2]; ${t} } fn mm_write(row : i32, col : i32, valueIn : f32, globalId : vec3) { if (coordsInBounds2D(vec2(row, col), vec2(uniforms.dimAOuter, uniforms.dimBOuter))) { let batch = i32(globalId.z); let outCoord = vec3(batch, row, col); var value = valueIn; ${r} ${s} setOutput(batch, row, col, value); } } ${xue(this.workGroupSize)} `}};function je(e){let{inputs:t,attrs:n}=e,{x:s}=t,{shape:r}=n,a=v.sizeFromShape(s.shape),o=v.inferFromImplicitShape(r,a),i=v.sizeFromShape(o);return v.assert(a===i,()=>`The new shape (${o}) has ${i} elements and the old shape (${s.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`),e.backend.incRef(s.dataId),{dataId:s.dataId,shape:o,dtype:s.dtype}}var vue={kernelName:Li,backendName:"webgpu",kernelFunc:je};function Px({a:e,b:t,transposeA:n,transposeB:s,backend:r,bias:a=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:l=null}){let c=e.shape.length,u=t.shape.length,d=n?e.shape[c-2]:e.shape[c-1],p=s?t.shape[u-1]:t.shape[u-2],h=n?e.shape[c-1]:e.shape[c-2],f=s?t.shape[u-2]:t.shape[u-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),A=v.sizeFromShape(m),x=v.sizeFromShape(g),b=ol.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([h,f]);v.assert(d===p,()=>`Error in matMul: inner shapes (${d}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${s} must match.`);let w=n?[A,d,h]:[A,h,d],k=s?[x,f,p]:[x,p,f],I=je({inputs:{x:e},backend:r,attrs:{shape:w}}),N=je({inputs:{x:t},backend:r,attrs:{shape:k}}),R=[I,N],O=Math.max(A,x),$=d%4==0&&f%4==0&&!n&&!s&&f>=32,P;h*f<=32?P=new yue([O,h,f],n,s,a,l,o):!n&&!s&&(h<=16&&(f<=512||p>=2*f)||f<=16&&(h<=512||d>=2*h))?P=new bue(w,k,[O,h,f],a,l,o):$?P=new mue(w,[O,h,f],Y().get("WEBGPU_MATMUL_WORK_PER_THREAD"),a,l,o):P=new EC(w,[O,h,f],Y().get("WEBGPU_MATMUL_WORK_PER_THREAD"),n,s,a,l,o);let T=[I,N];a&&T.push(a),o&&T.push(o);let F=[{type:"int32",data:[h]},{type:"int32",data:[f]},{type:"int32",data:[d]}],U=r.runWebGPUProgram(P,T,e.dtype,F),q=je({inputs:{x:U},backend:r,attrs:{shape:b}});R.push(U);for(let z of R)r.disposeData(z.dataId);return q}function wue(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:d}=s;return Px({a:r,b:a,transposeA:l,transposeB:c,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:d,activation:u})}var kue={kernelName:wo,backendName:"webgpu",kernelFunc:wue},RC=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.workGroupSize=[128,1,1],this.size=!0,this.outputShape=E.assertAndGetBroadcastShape(t,n),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`binaryOpComplex_${e}`,this.op=e}getUserCode(){return` fn binaryOpComplex( areal : f32, aimag : f32, breal : f32, bimag : f32) -> f32 { ${Ip(this.op,!1)} } ${nt()} if(index < uniforms.size) { let areal = getARealAtOutCoordsByGlobalIndex(index); let aimag = getAImagAtOutCoordsByGlobalIndex(index); let breal = getBRealAtOutCoordsByGlobalIndex(index); let bimag = getBImagAtOutCoordsByGlobalIndex(index); setOutputFlat(index, binaryOpComplex(areal, aimag, breal, bimag)); } } `}},Sue=class{constructor(e,t,n,s){this.variableNames=["A","B"],this.size=!0;let r=256;this.workGroupSize=[r,1,1],this.outputShape=E.assertAndGetBroadcastShape(t,n),this.dispatchLayout=Xe(this.outputShape),this.lastDimensionSize=s?n[0]:t[0],this.lastDimensionSize<256?this.workPerThread=1:this.lastDimensionSize<512?this.workPerThread=2:this.workPerThread=4,this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.useSharedMemoryWithB=s,this.op=e,this.shaderKey=`binaryShared_${e}_${this.lastDimensionSize}_${this.useSharedMemoryWithB}`}getUserCode(){let e=this.lastDimensionSize>1?`coords[${this.outputShape.length-1}]`:"0",t=this.useSharedMemoryWithB?`let a = getAAtOutCoordsByCoords(coords); let b = sharedBuf[${e}];`:`let a = sharedBuf[${e}]; let b = getBAtOutCoordsByCoords(coords);`;return` fn binaryOperation(a : f32, b : f32) -> f32 { ${Ip(this.op,!1)} } var sharedBuf : array; ${nt()} // Fill in the shared memory buffer. Here we need a loop to make sure // that all data in A|B are uploaded when |sharedMemorySize| is larger // than work group size. for(var localIndex = i32(localId.x); localIndex < ${this.lastDimensionSize}; localIndex = localIndex + ${this.workGroupSize[0]}) { sharedBuf[localIndex] = f32(${this.useSharedMemoryWithB?"B":"A"}.numbers[localIndex]); } workgroupBarrier(); for(var i = 0; i < ${this.workPerThread}; i = i + 1) { let flatIndex = index * ${this.workPerThread} + i; if(flatIndex < uniforms.size) { let coords = getCoordsFromFlatIndex(flatIndex); ${t} setOutputFlat(flatIndex, binaryOperation(a, b)); } } } `}},Iue=class{constructor(e,t,n){this.variableNames=["A","B"],this.workPerThread=4,this.isVec4=!0,this.size=!0;let s=128;this.workGroupSize=[s,1,1],this.outputShape=E.assertAndGetBroadcastShape(t,n),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.op=e,this.shaderKey=`binaryVec4_${e}`}getUserCode(){return` fn binaryOperation(a : vec4, b : vec4) -> vec4 { ${Ip(this.op,this.isVec4)} } ${nt()} if (index < uniforms.size) { let a = getAAtOutCoordsByGlobalIndex(index); let b = getBAtOutCoordsByGlobalIndex(index); setOutputFlat(index, binaryOperation(a, b)); } } `}},$C=class{constructor(e,t,n){this.variableNames=["A","B"],this.size=!0;let s=128;this.workGroupSize=[s,1,1],this.outputShape=E.assertAndGetBroadcastShape(t,n),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`binary_${e}`,this.op=e}getUserCode(){return` fn binaryOperation(a : f32, b : f32) -> f32 { ${Ip(this.op,!1)} } ${nt()} if (index < uniforms.size) { let a = getAAtOutCoordsByGlobalIndex(index); let b = getBAtOutCoordsByGlobalIndex(index); setOutputFlat(index, binaryOperation(a, b)); } } `}};function _C(e,t,n){if(v.arraysEqual(t,n)&&v.sizeFromShape(t)%4==0)return new Iue(e,t,n);let r=t.length===1&&n.length>1&&t[0]<1024,a=n.length===1&&t.length>1&&n[0]<1024;return r||a?new Sue(e,t,n,a):new $C(e,t,n)}function sr(e){let{inputs:t}=e,{x:n}=t;return e.backend.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}var Cue={kernelName:Xa,backendName:"webgpu",kernelFunc:sr};function bc(e){let{inputs:t,backend:n}=e,{real:s,imag:r}=t,a=n.makeTensorInfo(s.shape,"complex64"),o=n.tensorMap.get(a.dataId),i=sr({inputs:{x:s},backend:n}),l=sr({inputs:{x:r},backend:n});return o.complexTensorInfos={real:i,imag:l},a}var Tue={kernelName:id,backendName:"webgpu",kernelFunc:bc},r0=class{constructor(e,t){this.variableNames=["A"],this.size=!0;let n=128;this.workGroupSize=[n,1,1],this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.op=t,this.shaderKey=`unary_${t}`}getUserCode(){return` fn unaryOperation(a : f32) -> f32 { ${xc(this.op,!1)} } ${nt()} if (index < uniforms.size) { let a = getAAtOutCoordsByGlobalIndex(index); setOutputFlat(index, unaryOperation(a)); } } `}};function Nn({opType:e,cpuKernelImpl:t,dtype:n}){return({inputs:s,backend:r})=>{let{x:a}=s,o=r,i=n||a.dtype;if(o.shouldExecuteOnCPU([a])&&t!=null){let c=o.tensorMap.get(a.dataId),u=t(c.values,i);return o.makeTensorInfo(a.shape,i,u)}let l=new r0(a.shape,e);return o.runWebGPUProgram(l,[a],i)}}function Xn({opSnippet:e,cpuKernelImpl:t,supportsComplex:n=!1,dtype:s}){return({inputs:r,backend:a})=>{let{a:o,b:i}=r,l=a;if(n&&o.dtype==="complex64"){let d=l.tensorMap.get(o.dataId),p=l.tensorMap.get(i.dataId),h,f;if(e!==Ut.MUL)[h,f]=[[d.complexTensorInfos.real,p.complexTensorInfos.real],[d.complexTensorInfos.imag,p.complexTensorInfos.imag]].map(g=>{let[A,x]=g,y={dataId:A.dataId,dtype:A.dtype,shape:o.shape},b={dataId:x.dataId,dtype:x.dtype,shape:i.shape},w=_C(e,o.shape,i.shape);return l.runWebGPUProgram(w,[y,b],Bn(A.dtype,x.dtype))});else{let g=new RC(Ut.COMPLEX_MULTIPLY_REAL,o.shape,i.shape),A=new RC(Ut.COMPLEX_MULTIPLY_IMAG,o.shape,i.shape),x=[{dataId:d.complexTensorInfos.real.dataId,dtype:d.complexTensorInfos.real.dtype,shape:o.shape},{dataId:d.complexTensorInfos.imag.dataId,dtype:d.complexTensorInfos.imag.dtype,shape:o.shape},{dataId:p.complexTensorInfos.real.dataId,dtype:p.complexTensorInfos.real.dtype,shape:i.shape},{dataId:p.complexTensorInfos.imag.dataId,dtype:p.complexTensorInfos.imag.dtype,shape:i.shape}];h=l.runWebGPUProgram(g,x,"float32"),f=l.runWebGPUProgram(A,x,"float32")}let m=bc({inputs:{real:h,imag:f},backend:l});return l.disposeData(h.dataId),l.disposeData(f.dataId),m}let c=s||Bn(o.dtype,i.dtype);if((o.dtype==="string"||i.dtype==="string"||l.shouldExecuteOnCPU([o,i]))&&t!=null){let d=l.tensorMap.get(o.dataId).values,p=l.tensorMap.get(i.dataId).values,h=o.dtype==="string"?E.fromUint8ToStringArray(d):d,f=o.dtype==="string"?E.fromUint8ToStringArray(p):p,[m,g]=t(o.shape,i.shape,h,f,c);return l.makeTensorInfo(g,c,m)}let u=_C(e,o.shape,i.shape);return l.runWebGPUProgram(u,[o,i],c)}}var{addImpl:Nue,ceilImpl:Eue,concatImpl:Rue,equalImpl:$ue,expImpl:_ue,expm1Impl:Due,floorImpl:Pue,gatherNdImpl:Fue,gatherV2Impl:Oue,greaterEqualImpl:Mue,greaterImpl:zue,lessEqualImpl:Lue,lessImpl:Bue,logImpl:Wue,maxImpl:Vue,maximumImpl:Uue,minimumImpl:Gue,multiplyImpl:Hue,negImpl:jue,notEqualImpl:que,prodImpl:Xue,rangeImpl:Kue,rsqrtImpl:Zue,simpleAbsImpl:Yue,sliceImpl:Jue,stridedSliceImpl:Que,stringNGramsImpl:ece,subImpl:tce,tileImpl:nce,topKImpl:sce,transposeImpl:rce,uniqueImpl:A1e}=Em,ace=Nn({opType:bt.ABS,cpuKernelImpl:Yue}),oce={kernelName:fi,backendName:"webgpu",kernelFunc:ace},ice=Xn({opSnippet:Ut.ADD,cpuKernelImpl:Nue,supportsComplex:!0}),lce={kernelName:Kr,backendName:"webgpu",kernelFunc:ice},uce=class{constructor(e){this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e[0],this.variableNames=e.map((t,n)=>`T${n}`),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.shaderKey="addN"}getUserCode(){let e=[];this.variableNames.forEach(s=>{e.push(`let v${s} = get${s}AtOutCoordsByCoords(coords);`)});let t=this.variableNames.map(s=>`v${s}`).join(" + ");return` ${nt()} for (var i = 0; i < ${this.workPerThread}; i = i + 1) { let flatIndex = index * ${this.workPerThread} + i; if (flatIndex < uniforms.size) { let coords = getCoordsFromFlatIndex(flatIndex); ${e.join(` `)} setOutputFlat(flatIndex, ${t}); } } } `}};function cce(e){let{inputs:t,backend:n}=e,s=t;if(s.length===1)return sr({inputs:{x:s[0]},backend:n});let r=s.map(i=>i.dtype).reduce((i,l)=>Bn(i,l)),a=s.map(i=>i.shape),o=new uce(a);return n.runWebGPUProgram(o,s,r)}var dce={kernelName:Ra,backendName:"webgpu",kernelFunc:cce},DC=class{constructor(e,t,n){this.variableNames=["x"],this.uniforms="axis : i32;";let s=[t];E.assertAxesAreInnerMostDims("arg"+n.charAt(0).toUpperCase()+n.slice(1),s,e.length),this.op=n==="min"?"<":">";let[r,a]=E.computeOutAndReduceShapes(e,s);this.outputShape=r.length===0?[1]:r;let o=v.sizeFromShape(a);this.reductionFactor=2;let i=256,l=Math.min(Math.ceil(o/this.reductionFactor),i);this.workGroupSize=[l,1,1],this.dispatchLayout={x:[],y:this.outputShape.map((c,u)=>u)},this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.inputShape=e,this.shaderKey=`argMinMax${this.op}`}getUserCode(){let e=this.workGroupSize[0]>1,t=` var xBestIndices : array; var xBestValues : array; `,n=` xBestIndices[localId.x] = bestIndex; xBestValues[localId.x] = bestValue; for(var currentSize = WorkGroupSize; currentSize > 1; currentSize = DIV_CEIL(currentSize, ${this.reductionFactor})) { workgroupBarrier(); for (var w = 0; w < ${this.reductionFactor}; w = w + 1) { let i = i32(localId.x) * ${this.reductionFactor} + w; if (i < currentSize) { let candidateIndex = xBestIndices[i]; let candidate = xBestValues[i]; if(candidate ${this.op} bestValue && !isNanCustom(candidate)) { bestValue = candidate; bestIndex = candidateIndex; } } } xBestIndices[localId.x] = bestIndex; xBestValues[localId.x] = bestValue; } if (localId.x == 0u) { setOutputFlatI32(flatOutputIndex, i32(bestIndex)); } `,s=(o,i)=>this.outputShape.length===1?o:`${o}[${i}]`,r=o=>this.inputShape.length===1?"uniforms.xShape":`uniforms.xShape[${o}]`;return` fn DIV_CEIL(a : i32, b : i32) -> i32 { return ((a - 1) / b + 1); } let WorkGroupSize = ${this.workGroupSize[0]}; ${e?t:""} // In order to get a flattened index into the input tensor, we need to // add back the index along the reduced dimension to |outputCoords|. // This function outputs the offset to the first value along // |axis| and the stride to get the next value of the input along |axis|. fn getInputCoordInfo(globalId : vec3) -> vec2{ let outputCoords = getOutputCoordsWithNonFlatDispatchLayout(globalId); var i = ${this.outputShape.length-1}; var stride = 1; var inputStride = 1; var offset = 0; for (var r = 1; r <= ${this.inputShape.length}; r = r + 1) { let length = ${r(`${this.inputShape.length} - r`)}; if (${this.inputShape.length} - r == uniforms.axis) { inputStride = stride; } else { offset = offset + ${s("outputCoords","i")} * stride; i = i - 1; } stride = stride * length; } return vec2(offset, inputStride); } fn getInputIndex(coordInfo : vec2, index : i32) -> i32{ return coordInfo[0] + coordInfo[1] * index; } ${Xo()} { let coordInfo = getInputCoordInfo(globalId); var bestIndex = 0; var bestValue = f32(x.numbers[getInputIndex(coordInfo, bestIndex)]); let Length = ${r("uniforms.axis")}; let WorkPerThread = DIV_CEIL(Length, WorkGroupSize); for (var w = 0; w < WorkPerThread; w = w + 1) { let i = i32(globalId.x) * WorkPerThread + w; if (i < Length) { let candidate = f32(x.numbers[getInputIndex(coordInfo, i)]); if (candidate ${this.op} bestValue && !isNanCustom(f32(candidate))) { bestValue = candidate; bestIndex = i; } } } let flatOutputIndex = i32(globalId.y); ${e?n:"setOutputFlatI32(flatOutputIndex, bestIndex);"} } `}},pce=class{constructor(e,t){this.variableNames=["A"],this.workGroupSize=[16,16,1];let n=new Array(e.length);for(let s=0;s tile : array, ${this.workGroupSize[0]}>; ${s0()} fn main([[builtin(local_invocation_id)]] localId : vec3, [[builtin(workgroup_id)]] workgroupId : vec3) { var x = i32(workgroupId.x) * TILE_DIM + i32(localId.x); var y = i32(workgroupId.y) * TILE_DIM + i32(localId.y); let width = uniforms.outShape[0]; let height = uniforms.outShape[1]; if (x < width && y < height) { tile[localId.y][localId.x] = A.numbers[y * width + x]; } workgroupBarrier(); x = i32(workgroupId.y) * TILE_DIM + i32(localId.x); y = i32(workgroupId.x) * TILE_DIM + i32(localId.y); if (x < height && y < width) { setOutputFlat((y * height + x), tile[localId.x] [localId.y]); } } `}},hce=class{constructor(e,t){this.variableNames=["A"],this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0;let n=new Array(e.length);for(let s=0;s4)throw Error(`Transpose for rank ${t} is not yet supported`);let n=new Array(t);for(let s=0;sn.disposeData(h.dataId)),p}var Ace={kernelName:$a,backendName:"webgpu",kernelFunc:gce};function yce(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s,o=v.parseAxisParam(a,r.shape),i=E.getAxesPermutation(o,r.shape.length),l=r,c=[];i!=null&&(l=Ol({inputs:{x:r},backend:n,attrs:{perm:i}}),c.push(l),o=E.getInnerMostAxes(o.length,l.shape.length)),E.assertAxesAreInnerMostDims("argMin",[o[0]],l.shape.length);let u=new DC(l.shape,o[0],"min"),d=[{type:"int32",data:[o[0]]}],p=n.runWebGPUProgram(u,[l],"int32",d);return c.forEach(h=>n.disposeData(h.dataId)),p}var xce={kernelName:du,backendName:"webgpu",kernelFunc:yce},PC=class{constructor(e,t){this.variableNames=["x"],this.uniforms="stride : vec2; pad : vec2; dilation : vec2; convDims : vec2; filterDims : vec2;",this.workGroupSize=[128,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`pool2D_${t}`,this.poolType=t}getUserCode(){let e="resultValue = max(value, resultValue);";this.poolType==="avg"&&(e="resultValue = resultValue + value; count = count + 1.0;");let t="resultValue";return this.poolType==="avg"&&(t="resultValue / count"),` ${nt()} if (index < uniforms.size) { let coords = getCoordsFromFlatIndex(index); let batch = coords[0]; let xRCCorner = vec2(coords.yz) * uniforms.stride - uniforms.pad; let xRCorner = xRCCorner.x; let xCCorner = xRCCorner.y; var resultValue = ${this.poolType==="avg"?"0.0":"-1.0 / pow(10.0, -20.0)"}; var count = 0.0; for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + uniforms.dilation.x) { let xR = xRCorner + wR; if (xR < 0 || xR >= uniforms.convDims.x) { continue; } for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + uniforms.dilation.y) { let xC = xCCorner + wC; if (xC < 0 || xC >= uniforms.convDims.y) { continue; } let value = getX(batch, xR, xC, coords[3]); ${e} } } setOutputFlat(index, ${t}); } } `}},FC=class{constructor(e){this.variableNames=["x"],this.uniforms="stride : vec2;",this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="poolWithFilterSizeEqualsOne"}getUserCode(){return` ${nt()} if (index < uniforms.size) { let coords = getCoordsFromFlatIndex(index); let batch = coords[0]; let d = coords[3]; let xRCCorner = coords.yz * uniforms.stride; let xRCorner = xRCCorner.x; let xCCorner = xRCCorner.y; let value = getX(batch, xRCorner, xCCorner, d); setOutputFlat(index, value); } } `}};function bce(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,c=1,u=E.computePool2DInfo(r.shape,a,o,c,i,l);if(u.filterWidth===1&&u.filterHeight===1&&v.arraysEqual(u.inShape,u.outShape))return sr({inputs:{x:r},backend:n});let d,p=[{type:"int32",data:[u.strideHeight,u.strideWidth]}];return u.filterHeight===1&&u.filterWidth===1?d=new FC(u):(d=new PC(u,"avg"),p.push({type:"int32",data:[u.padInfo.top,u.padInfo.left]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]},{type:"int32",data:[u.inHeight,u.inWidth]},{type:"int32",data:[u.effectiveFilterHeight,u.effectiveFilterWidth]})),n.runWebGPUProgram(d,[r],r.dtype,p)}var vce={kernelName:_a,backendName:"webgpu",kernelFunc:bce};function wce(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:o,transposeB:i}=s;return Px({a:r,b:a,transposeA:o,transposeB:i,backend:n})}var kce={kernelName:Da,backendName:"webgpu",kernelFunc:wce},Sce=class{constructor(e,t){this.variableNames=["source"],this.workPerThread=1,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.rank=t.length,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.start=e,this.uniforms=`start : ${wn(e.length)}; `,this.shaderKey="slice"}getUserCode(){let e=wn(this.rank),t=Ice(this.rank),n;return this.start.length===1?n=this.outputShape.map((r,a)=>"sourceLoc = uniforms.start + coords;"):n=this.outputShape.map((r,a)=>`sourceLoc.${Fx[a]} = uniforms.start[${a}] + coords.${Fx[a]};`),` ${nt()} if (index < uniforms.size) { var sourceLoc : ${e}; let coords = getCoordsFromFlatIndex(index); ${n.join(` `)} setOutputFlat(index, getSource(${t})); } } `}},Fx=["x","y","z","w","u","v"];function Ice(e){if(e===1)return"sourceLoc";if(e<=6)return Fx.slice(0,e).map(t=>`sourceLoc.${t}`).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}function vc(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:o}=s,[i,l]=Ft.parseSliceParams(r,a,o);if(Ft.assertParamsValid(r,i,l),n.shouldExecuteOnCPU([r])||r.dtype==="string"){let d=n.tensorMap.get(r.dataId),p=Jue(d.values,i,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,p)}if(v.sizeFromShape(l)===0)return n.makeTensorInfo(l,r.dtype,[]);let c=new Sce(i,l),u=[{type:"int32",data:i}];return n.runWebGPUProgram(c,[r],r.dtype,u)}var Cce={kernelName:Gi,backendName:"webgpu",kernelFunc:vc},Tce=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:o}=s;v.assert(r.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGPU backend not implemented yet");let i=a.reduce((x,y)=>x*y),l=E.getReshaped(r.shape,a,i),c=E.getPermuted(l.length,a.length),u=E.getReshapedPermuted(r.shape,a,i),d=E.getSliceBeginCoords(o,a.length),p=E.getSliceSize(u,o,a.length),h=[],f=je({inputs:{x:r},backend:n,attrs:{shape:l}}),m=Ol({inputs:{x:f},backend:n,attrs:{perm:c}}),g=je({inputs:{x:m},backend:n,attrs:{shape:u}}),A=vc({inputs:{x:g},backend:n,attrs:{begin:d,size:p}});return h.push(f),h.push(m),h.push(g),h.forEach(x=>n.disposeData(x.dataId)),A},Nce={kernelName:mi,backendName:"webgpu",kernelFunc:Tce},OC=Xn({opSnippet:Ut.NOT_EQUAL,dtype:"bool",cpuKernelImpl:que}),Ece={kernelName:_i,backendName:"webgpu",kernelFunc:OC};function Cp(e){let{inputs:t,backend:n}=e,{input:s}=t,r=n.tensorMap.get(s.dataId);return sr({inputs:{x:r.complexTensorInfos.real},backend:n})}var Rce={kernelName:gd,backendName:"webgpu",kernelFunc:Cp};function $ce(e,t){let n=new r0(e.shape,bt.TO_INT),s=t.runWebGPUProgram(n,[e],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}function Ox(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dtype:a}=s;if(a==="complex64"){if(r.dtype==="complex64")return sr({inputs:{x:r},backend:n});let o=Ht(r.shape),i=Ox({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=bc({inputs:{real:i,imag:o},backend:n});return o.dispose(),n.disposeData(i.dataId),l}if(r.dtype==="complex64"){let o=Cp({inputs:{input:r},backend:n}),i=Ox({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeData(o.dataId),i}if(!v.hasEncodingLoss(r.dtype,a)){let o=sr({inputs:{x:r},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32")return $ce(r,n);if(a==="bool"){let o=n.makeTensorInfo([],"bool",v.getTypedArrayFromDType("bool",1)),l=OC({inputs:{a:r,b:o},backend:n});return n.disposeData(o.dataId),l}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${a}`)}var _ce={kernelName:Pa,backendName:"webgpu",kernelFunc:Ox},Dce=Nn({opType:bt.CEIL,cpuKernelImpl:Eue}),Pce={kernelName:Fa,backendName:"webgpu",kernelFunc:Dce},Fce=class{constructor(e){this.variableNames=["A"],this.uniforms="minVal : f32; maxVal : f32;",this.workPerThread=4,this.workGroupSize=[64,1,1],this.isVec4=!0,this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.shaderKey="clipVec4"}getUserCode(){return` ${nt()} if(index < uniforms.size) { let value = getAAtOutCoordsByGlobalIndex(index); var clampedValue : vec4; for (var i = 0; i < 4; i = i + 1) { if (isNanCustom(value[i])) { clampedValue[i] = value[i]; } else { clampedValue[i] = clamp(value[i], uniforms.minVal, uniforms.maxVal); } } setOutputFlat(index, clampedValue); } } `}},Oce=class{constructor(e){this.variableNames=["A"],this.uniforms="minVal : f32; maxVal : f32;",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="clip"}getUserCode(){return` ${nt()} if(index < uniforms.size) { let value = getAAtOutCoordsByGlobalIndex(index); if (isNanCustom(value)) { setOutputFlat(index, value); return; } setOutputFlat(index, clamp(value, uniforms.minVal, uniforms.maxVal)); } } `}};function Mce(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{clipValueMin:a,clipValueMax:o}=s,i,l=[{type:"float32",data:[a]},{type:"float32",data:[o]}];return v.sizeFromShape(r.shape)%4==0?i=new Fce(r.shape):i=new Oce(r.shape),n.runWebGPUProgram(i,[r],r.dtype,l)}var zce={kernelName:Zr,backendName:"webgpu",kernelFunc:Mce},Lce=class{constructor(e){this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=E.computeOutShape(e,1),this.variableNames=e.map((t,n)=>`T${n}`),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.shapes=e,this.shaderKey=`concat${e}`}getUserCode(){let e=new Array(this.shapes.length-1),t=[];if(e.length>0){e[0]=this.shapes[0][1];for(let a=1;aCp({inputs:{input:m},backend:n})),d=e.map(m=>a0({inputs:{input:m},backend:n})),p=Mx(u,t,n),h=Mx(d,t,n),f=bc({inputs:{real:p,imag:h},backend:n});return u.forEach(m=>n.disposeData(m.dataId)),d.forEach(m=>n.disposeData(m.dataId)),n.disposeData(p.dataId),n.disposeData(h.dataId),f}let r=n.shouldExecuteOnCPU(e);if(s==="string"&&(r=!0),r){let u=e.map(A=>{let x=v.sizeFromShape(A.shape.slice(t));return je({inputs:{x:A},backend:n,attrs:{shape:[-1,x]}})}),d=u.map(A=>({vals:n.readSync(A.dataId),shape:A.shape})),p=E.computeOutShape(u.map(A=>A.shape),1),h=u[0].shape[0]===1,f=Rue(d,p,s,h),m=E.computeOutShape(e.map(A=>A.shape),t),g=n.makeTensorInfo(m,s,f);return u.forEach(A=>n.disposeData(A.dataId)),g}let{tensors2D:a,outShape:o}=Wce(e,t,n),i=new Lce(a.map(u=>u.shape)),l=n.runWebGPUProgram(i,a,a[0].dtype);a.forEach(u=>n.disposeData(u.dataId));let c=je({inputs:{x:l},backend:n,attrs:{shape:o}});return n.disposeData(l.dataId),c}function Wce(e,t,n){let s=E.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>je({inputs:{x:a},backend:n,attrs:{shape:[v.sizeFromShape(a.shape.slice(0,t)),v.sizeFromShape(a.shape.slice(t))]}})),outShape:s}}function MC(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s,a=v.parseAxisParam(r,t[0].shape)[0],o=E.computeOutShape(t.map(c=>c.shape),a);if(v.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(c=>v.sizeFromShape(c.shape)>0);if(i.length===1)return sr({inputs:{x:i[0]},backend:n});let l=i.map(c=>c.shape);return E.assertParamsConsistent(l,a),Mx(i,a,n)}var Vce={kernelName:gi,backendName:"webgpu",kernelFunc:MC},Uce=class{constructor(e,t){this.variableNames=["A"],this.uniforms=`pad : vec2; stride : vec2; dilation : vec2; outWidth : i32; itemsPerBlockRow : i32; inChannels : i32;`,this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.isChannelsLast=t,this.shaderKey=`im2col_${this.isChannelsLast}`}getUserCode(){let e=this.isChannelsLast?0:1,t=this.isChannelsLast?1:2;return` ${nt()} for(var i = 0; i<${this.workPerThread}; i = i + 1) { let flatIndex = index * ${this.workPerThread} + i; let rc = getCoordsFromFlatIndex(flatIndex); if(flatIndex < uniforms.size) { let blockIndex = rc[0]; let pos = rc[1]; let offsetY = blockIndex / uniforms.outWidth * uniforms.stride[1] - uniforms.pad[1]; let d0 = offsetY + uniforms.dilation[1] * pos / uniforms.itemsPerBlockRow; var value = 0.0; if(d0 < uniforms.aShape[${e}] && d0 >= 0) { let offsetX = (blockIndex % uniforms.outWidth) * uniforms.stride[0] - uniforms.pad[0]; let d1 = offsetX + uniforms.dilation[0] * ((pos % uniforms.itemsPerBlockRow) / uniforms.inChannels); let ch = pos % uniforms.inChannels; if(d1 < uniforms.aShape[${t}] && d1 >= 0) { value = getA(d0, d1, ch); } } setOutputFlat(flatIndex, value); } } } `}};function zC({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let l=e.shape,c=n.dataFormat==="channelsLast",u=!1,d=!1,p=c?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],h=je({inputs:{x:e},backend:s,attrs:{shape:[1,p,n.inChannels]}}),f=je({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}}),m=Px({a:h,b:f,transposeA:u,transposeB:d,backend:s,bias:r,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),g=je({inputs:{x:m},backend:s,attrs:{shape:n.outShape}});return s.disposeData(h.dataId),s.disposeData(f.dataId),s.disposeData(m.dataId),g}function Gce({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:l,filterHeight:c,inChannels:u,strideWidth:d,strideHeight:p,padInfo:h,outWidth:f,outHeight:m,dilationWidth:g,dilationHeight:A,dataFormat:x}=n,y=x==="channelsLast",b=l*c*u,w=m*f,k=[w,b],I=!1,N=!1,R=[],O=je({inputs:{x:e},backend:s,attrs:{shape:e.shape.slice(1)}}),$=je({inputs:{x:t},backend:s,attrs:{shape:[1,b,-1]}});R.push(O),R.push($);let P=new Uce(k,y),T=[{type:"int32",data:[h.left,h.top]},{type:"int32",data:[d,p]},{type:"int32",data:[g,A]},{type:"int32",data:[f]},{type:"int32",data:[u*l]},{type:"int32",data:[u]}],F=s.runWebGPUProgram(P,[O],O.dtype,T),U=je({inputs:{x:F},backend:s,attrs:{shape:[1,k[0],k[1]]}});R.push(F),R.push(U);let q=[1,k[0],k[1]],z=new EC(q,[1,w,n.outChannels],Y().get("WEBGPU_MATMUL_WORK_PER_THREAD"),I,N),K=q[1],J=q[2],Q=n.outChannels,ne=[{type:"int32",data:[K]},{type:"int32",data:[Q]},{type:"int32",data:[J]}],re=s.runWebGPUProgram(z,[U,$],U.dtype,ne),G=y?[1,m,f,n.outChannels]:[1,n.outChannels,m,f],se=je({inputs:{x:re},backend:s,attrs:{shape:G}});R.push(re);for(let oe of R)s.disposeData(oe.dataId);return se}var LC=class{constructor(e,t=!1,n=null,s=!1,r=!1){this.variableNames=["x","W"],this.uniforms=`filterDims : vec2; pad : vec2; stride : vec2; dilation : vec2; dimAOuter : i32; dimBOuter : i32; dimInner : i32;`,this.isVec4=!0,this.outputShape=e.outShape,v.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),this.dispatchLayout={x:[3],y:[1,2],z:[0]},this.workGroupSize=[8,8,1];let a=[4,4,1];this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize,a),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivationWeights=s,this.hasLeakyreluAlpha=r,this.addBias&&this.variableNames.push("bias"),this.hasPreluActivationWeights&&this.variableNames.push("preluActivationWeights"),this.hasLeakyreluAlpha&&this.variableNames.push("leakyreluAlpha"),[this.fitA,this.fitB]=this.getShapeFit(a),this.shaderKey=`conv2DMMVec4_${this.activation}_${this.fitA}_${this.fitB}`}getShapeFit(e){let t=this.workGroupSize[1]*e[1],n=this.workGroupSize[0]*e[0],s=n,r=[t,s],a=[s,n],o=this.outputShape[1]*this.outputShape[2],i=this.outputShape[3],l=this.convInfo.filterHeight*this.convInfo.filterWidth*this.convInfo.inChannels;return[ua(r,[o,l]),ua(a,[l,i])]}getSampleAWithRemainder(e){return`let flatIndex${e} = getFlatIndex4D(coord, uniforms.xShape); let divBy4Remainder${e} = flatIndex${e} % 4; let divBy4Index${e} = flatIndex${e} / 4; let curData${e} = x.numbers[divBy4Index${e}]; if (divBy4Remainder${e} == 0) { temp = curData${e}; } else { // TODO: This could end up being a redundant load with another one in // the same shader invocation. Perhaps there's an opportunity for // optimization let nextData${e} = x.numbers[divBy4Index${e} + 1]; if (divBy4Remainder${e} == 1) { temp = vec4(curData${e}.yzw, nextData${e}.x); } elseif (divBy4Remainder${e} == 2) { temp = vec4(curData${e}.zw, nextData${e}.xy); } elseif (divBy4Remainder${e} == 3) { temp = vec4(curData${e}.w, nextData${e}.xyz); } } `}getUserCode(){let t=NC([4,4,1],this.workGroupSize),r=`let outRow = r / uniforms.outShape[2]; let outCol = r % uniforms.outShape[2]; let WRow = c / (uniforms.filterDims[1] * uniforms.xShape[3]); let WCol = c / uniforms.xShape[3] % uniforms.filterDims[1]; let inChCoord = c % uniforms.xShape[3]; var coord = vec4( batch, outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0], outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1], inChCoord); var resData = vec4(0.0); ${this.convInfo.inChannels%4===0?`// The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (coordsInBounds4D(coord, uniforms.xShape)) { resData = x.numbers[getFlatIndex4D(coord, uniforms.xShape) / 4]; } else { resData = vec4(0.0); }`:`var temp = vec4(0.0); ${this.getSampleAWithRemainder(1)} resData = temp; if (WCol == (uniforms.filterDims[1] - 1)) { coord = vec4( coord.x, coord.y + 1, coord.z + 1 - uniforms.filterDims[1], 0); ${this.getSampleAWithRemainder(2)} if (inChCoord == 0) { resData = vec4(resData.xyz, temp.x); } elseif (inChCoord == 1) { resData = vec4(resData.xy, temp.xy); } else { resData = vec4(resData.x, temp.xyz); } } `} return resData;`,a=this.fitA?`${r}`:`if (r < uniforms.dimAOuter && c < uniforms.dimInner) { ${r} } return vec4(0.0); `,o=this.fitB?"return W.numbers[row * uniforms.dimBOuter / 4 + col];":`if(coordsInBounds2D(vec2(row, col * 4), vec2(uniforms.dimInner, uniforms.dimBOuter))) { return W.numbers[row * uniforms.dimBOuter / 4 + col]; } return vec4(0.0); `,i="",l="";if(this.activation){let d=ca(this.activation,this.isVec4);if(this.hasPreluActivationWeights)i=`fn activation(a : vec4, outCoord : vec4) -> vec4 { let b = getPreluActivationWeightsAtOutCoordsByCoords(outCoord); ${d} }`;else{if(this.hasLeakyreluAlpha)throw i=`fn activation(a: vec4) -> vec4 { let b = getLeakyreluAlphaAtOutCoords(); ${d} }`,new Error("Leakyrelu is not supported.");i=` fn activation(a : vec4, outCoord : vec4) -> vec4 { ${d} }`}l="value = activation(value, outCoord);"}let c=this.addBias?"value = value + getBiasAtOutCoordsByCoords(outCoord);":"";return` ${i} fn mm_readA(row : i32, col : i32, globalId : vec3) -> vec4 { let r = row; let c = col * 4; var batch = i32(globalId.z); ${a} } fn mm_readB(row : i32, col : i32, globalId : vec3) -> vec4 { ${o} } fn mm_write(row : i32, col : i32, valueInput : vec4, globalId : vec3) { var batch = i32(globalId.z); var value = valueInput; if (row < uniforms.dimAOuter && col * 4 < uniforms.dimBOuter) { let outCoord = vec4( batch, row / uniforms.outShape[2], row % uniforms.outShape[2], col * 4); ${c} ${l} setOutput(outCoord[0], outCoord[1], outCoord[2], outCoord[3], value); } } ${t} `}},BC=class{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.uniforms="filterDims : vec2; pad : vec2; stride : vec2; dilation : vec2; dimAOuter : i32; dimBOuter : i32; dimInner : i32;",this.outputShape=e.outShape,v.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),this.dispatchLayout={x:[3],y:[1,2],z:[0]},this.workGroupSize=Nx(this.dispatchLayout,this.outputShape),this.elementsPerThread=Rx(this.dispatchLayout,this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread),t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivationWeights=s,[this.fitA,this.fitB]=this.getShapeFit(),this.shaderKey=`conv2DMM_${this.elementsPerThread}_${this.activation}_${this.fitA}_${this.fitB}`}getShapeFit(){let e=this.workGroupSize[1]*this.elementsPerThread[1],t=this.workGroupSize[0]*this.elementsPerThread[0],n=e>t?e:t;v.assert(n%this.workGroupSize[0]==0&&n%this.workGroupSize[1]==0,()=>"tileInner must be multiple of workgroupsize.x and workgroupsize.y");let s=[e,n],r=[n,t],a=this.outputShape[1]*this.outputShape[2],o=this.outputShape[3],i=this.convInfo.filterHeight*this.convInfo.filterWidth*this.convInfo.inChannels;return[ua(s,[a,i]),ua(r,[i,o])]}getUserCode(){let e=Dx(this.elementsPerThread,this.workGroupSize),t=` let outRow = row / uniforms.outShape[2]; let outCol = row % uniforms.outShape[2]; let WRow = col / (uniforms.filterDims[1] * uniforms.xShape[3]); let WCol = col / uniforms.xShape[3] % uniforms.filterDims[1]; let coord = vec4( batch, outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0], outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1], col % uniforms.xShape[3]); // The bounds checking is always needed since we use it to pad zero for the // 'same' padding type. if(coordsInBounds4D(coord, uniforms.xShape)) { return x.numbers[getFlatIndex4D(coord, uniforms.xShape)]; } return 0.0;`,n=this.fitA?`${t}`:`if (row < uniforms.dimAOuter && col < uniforms.dimInner) { ${t} } return 0.0; `,s=this.fitB?"return W.numbers[row * uniforms.dimBOuter + col];":`if(coordsInBounds2D(vec2(row, col), vec2(uniforms.dimInner, uniforms.dimBOuter))) { return W.numbers[row * uniforms.dimBOuter + col]; } return 0.0; `,r="",a="";if(this.activation){let l=ca(this.activation,!1);this.hasPreluActivationWeights?r=`fn activation(a: f32, outCoord : vec4) -> f32 { let b = getPreluActivationWeightsAtOutCoordsByCoords(outCoord); ${l} }`:r=` fn activation(a : f32, outCoord : vec4) -> f32 { ${l} } `,a="value = activation(value, outCoord);"}let o=this.addBias?"value = value + getBiasAtOutCoordsByCoords(outCoord);":"";return` ${r} fn mm_readA(row : i32, col : i32, globalId : vec3) -> f32 { var batch = i32(globalId.z); ${n} } fn mm_readB(row : i32, col : i32, globalId : vec3) -> f32 { ${s} } fn mm_write(row : i32, col : i32, valueInput : f32, globalId : vec3) { var batch = i32(globalId.z); var value = valueInput; let outCoord = vec4( batch, row / uniforms.outShape[2], row % uniforms.outShape[2], col); ${o} ${a} result.numbers[getFlatIndex4D(outCoord, uniforms.outShape)] = value; } ${e} `}},WC=class{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.uniforms="filterDims : vec2; pad : vec2; stride : vec2; dilation : vec2;",this.workGroupSize=[128,1,1],this.outputShape=e.outShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),v.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivationWeights=s,this.shaderKey=`conv2DNaive_${this.activation}`}getUserCode(){let e="",t="";if(this.activation){let r=ca(this.activation);this.hasPreluActivationWeights?e=`fn activation(a : f32, outCoord : vec4) -> f32{ let b = getPreluActivationWeightsAtOutCoordsByCoords(outCoord); ${r} }`:e=` fn activation(a : f32, outCoord : vec4) -> f32{ ${r} } `,t="value = activation(value, outCoord);"}let n=this.addBias?"value = value + getBiasAtOutCoordsByCoords(outCoord);":"";return` ${e} fn readInp(batch : i32, row : i32, col : i32, chan : i32) -> f32 { let coord = vec4(batch, row, col, chan); if(coordsInBounds4D(coord, uniforms.xShape)) { return getX(batch, row, col, chan); } return 0.0; } fn readFilt(row : i32, col : i32, xChannel : i32, outChannel : i32) -> f32{ let coord = vec4(row, col, xChannel, outChannel); if(coordsInBounds4D(coord, uniforms.wShape)) { return getW(row, col, xChannel, outChannel); } return 0.0; } fn writeResult(batch : i32, row : i32, col : i32, chan : i32, value : f32) { let coord = vec4(batch, row, col, chan); if (coordsInBounds4D(coord, uniforms.outShape)) { ${n} ${t} setOutput(batch, row, col, chan, value); } } ${Tx()} { let coords = getOutputCoordsWithFlatDispatchLayout(globalId, localId, numWorkgroups); let batch = coords[0]; let outChannel = coords[3]; var acc = 0.0; for (var row = 0; row < uniforms.filterDims[0]; row = row + 1) { for (var col = 0; col < uniforms.filterDims[1]; col = col + 1) { for (var xChannel = 0; xChannel < uniforms.xShape[3]; xChannel = xChannel + 1) { let coordRow = coords[1] * uniforms.stride[0] + uniforms.dilation[0] * row - uniforms.pad[0]; let coordCol = coords[2] * uniforms.stride[1] + uniforms.dilation[1] * col - uniforms.pad[1]; let v = readInp(batch, coordRow, coordCol, xChannel); let f = readFilt(row, col, xChannel, outChannel); acc = acc + v * f; } } } writeResult(batch, coords[1], coords[2], outChannel, acc); } `}};function Hce(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dataFormat:l,dilations:c,dimRoundingMode:u}=n,d=E.convertConv2DDataFormat(l),p=E.computeConv2DInfo(r.shape,a.shape,o,c,i,u,!1,d);if(p.filterHeight===1&&p.filterWidth===1&&p.dilationHeight===1&&p.dilationWidth===1&&p.strideHeight===1&&p.strideWidth===1&&(p.padInfo.type==="SAME"||p.padInfo.type==="VALID"))return zC({x:r,filter:a,convInfo:p,backend:s});if(Y().getBool("WEBGPU_CONV_SEPARATE_IM2COL_SHADER")&&r.shape[0]===1)return Gce({x:r,filter:a,convInfo:p,backend:s});let h,f=[p.padInfo.top,p.padInfo.left],m=[{type:"int32",data:[p.filterHeight,p.filterWidth]},{type:"int32",data:[...f]},{type:"int32",data:[p.strideHeight,p.strideWidth]},{type:"int32",data:[p.dilationHeight,p.dilationWidth]}],g=Y().getBool("WEBGPU_USE_NAIVE_CONV2D");if(g?h=new WC(p):(p.inChannels%4==0||p.inChannels===3&&p.padInfo.type==="VALID")&&p.outChannels%4==0&&p.outChannels>=64?h=new LC(p):h=new BC(p),!g){let A=p.outShape[1]*p.outShape[2],x=p.outShape[3],y=p.filterHeight*p.filterWidth*p.inShape[3];m.push({type:"int32",data:[A]},{type:"int32",data:[x]},{type:"int32",data:[y]})}return s.runWebGPUProgram(h,[r,a],r.dtype,m)}var jce={kernelName:Oa,backendName:"webgpu",kernelFunc:Hce},qce=class{constructor(e){this.variableNames=["x","W"],this.uniforms="filterDims : vec2; pads : vec2; stride : vec2; outBackprop : vec4; dimAOuter : i32; dimBOuter : i32; dimInner : i32;",this.outputShape=e.inShape,v.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),this.dispatchLayout={x:[3],y:[1,2],z:[0]},this.workGroupSize=Nx(this.dispatchLayout,this.outputShape),this.elementsPerThread=Rx(this.dispatchLayout,this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread),this.shaderKey=`conv2DDerInputMM_${this.elementsPerThread}`}getUserCode(){return` fn mm_readA(row : i32, col : i32, globalId : vec3) -> f32 { var batch = i32(globalId.z); if (row < uniforms.dimAOuter && col < uniforms.dimInner) { let outRow = row / uniforms.outShape[2]; let outCol = row % uniforms.outShape[2]; let WRow = col / (uniforms.filterDims[1] * uniforms.outBackprop[3]); let WCol = col / uniforms.outBackprop[3] % uniforms.filterDims[1]; let xR = f32(outRow - uniforms.pads[0] + WRow) / f32(uniforms.stride[0]); let xC = f32(outCol - uniforms.pads[1] + WCol) / f32(uniforms.stride[1]); if (xR < 0.0 || xR >= f32(uniforms.outBackprop[1]) || fract(xR) > 0.0) { return 0.0; } if (xC < 0.0 || xC >= f32(uniforms.outBackprop[2]) || fract(xC) > 0.0) { return 0.0; } let coord = vec4( batch, i32(xR), i32(xC), col % uniforms.outBackprop[3]); return x.numbers[getFlatIndex4D(coord, uniforms.xShape)]; } return 0.0; } fn mm_readB(row : i32, col : i32, globalId : vec3) -> f32 { let coordX = uniforms.filterDims.x - 1 - row / (uniforms.filterDims[1] * uniforms.outBackprop[3]); let coordY = uniforms.filterDims.y - 1 - (row / uniforms.outBackprop[3]) % uniforms.filterDims[1]; if (row < uniforms.dimInner && col < uniforms.dimBOuter && coordX >= 0 && coordY >= 0) { let coord = vec4(coordX, coordY, col, row % uniforms.outBackprop[3]); return W.numbers[getFlatIndex4D(coord, uniforms.wShape)]; } return 0.0; } fn mm_write(row : i32, col : i32, valueInput : f32, globalId : vec3) { var batch = i32(globalId.z); var value = valueInput; let outCoord = vec4( batch, row / uniforms.outShape[2], row % uniforms.outShape[2], col); result.numbers[getFlatIndex4D(outCoord, uniforms.outShape)] = value; } ${Dx(this.elementsPerThread,this.workGroupSize)} `}},Xce=class{constructor(e){this.variableNames=["dy","W"],this.uniforms="filterDims : vec2; pads : vec2; stride : vec2; outBackprop : vec4;",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.isChannelsLast=e.dataFormat==="channelsLast",this.shaderKey=`conv2DDerInput_${this.isChannelsLast}`}getUserCode(){let e=this.isChannelsLast?1:2,t=this.isChannelsLast?2:3,n=this.isChannelsLast?3:1;return` ${nt()} { if(index < uniforms.size) { let coords = getCoordsFromFlatIndex(index); let batch = coords[0]; let d1 = coords[${n}]; let dyCorner = vec2(coords[${e}]), coords[${t}]) - uniforms.pads; let dyRCorner = dyCorner.x; let dyCCorner = dyCorner.y; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd = 0.0; for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + 1) { let dyR = (f32(dyRCorner) + f32(wR)) / f32(uniforms.stride.x); let wRPerm = uniforms.filterDims.x - 1 - wR; if (dyR < 0.0 || dyR >= f32(uniforms.outBackprop[1]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR = dyR; for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + 1) { let dyC = (f32(dyCCorner) + f32(wC)) / f32(uniforms.stride.y); let wCPerm = uniforms.filterDims.y - 1 - wC; if (dyC < 0.0 || dyC >= f32(uniforms.outBackprop[2]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } let idyC = dyC; for (var d2 = 0; d2 < uniforms.outBackprop[3]; d2 = d2 + 1) { if (${this.isChannelsLast}) { let xValue = getDy(batch, idyR, idyC, d2); let wValue = getW(wRPerm, wCPerm, d1, d2); dotProd = dotProd + xValue * wValue; } else { let xValue = getDy(batch, d2, idyR, idyC); let wValue = getW(wRPerm, wCPerm, d1, d2); dotProd = dotProd + xValue * wValue; } } } } setOutputFlat(index, dotProd); } } `}};function Kce(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{inputShape:o,strides:i,pad:l,dataFormat:c,dimRoundingMode:u}=s,d=E.convertConv2DDataFormat(c),p=E.computeConv2DInfo(o,a.shape,i,1,l,u,!1,d),h=[{type:"int32",data:[p.filterHeight,p.filterWidth]},{type:"int32",data:[p.filterHeight-1-p.padInfo.top,p.filterWidth-1-p.padInfo.left]},{type:"int32",data:[p.strideHeight,p.strideWidth]},{type:"int32",data:[p.batchSize,p.outHeight,p.outWidth,p.outChannels]}],f;if(Y().getBool("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE"))f=new Xce(p);else{f=new qce(p);let m=p.inShape[1]*p.inShape[2],g=p.inShape[3],A=p.filterHeight*p.filterWidth*p.outChannels;h.push({type:"uint32",data:[m]},{type:"uint32",data:[g]},{type:"uint32",data:[A]})}return n.runWebGPUProgram(f,[r,a],"float32",h)}var Zce={kernelName:Ma,backendName:"webgpu",kernelFunc:Kce},Yce=Nn({opType:bt.COS}),Jce={kernelName:za,backendName:"webgpu",kernelFunc:Yce},Qce=Nn({opType:bt.COSH}),ede={kernelName:La,backendName:"webgpu",kernelFunc:Qce},tde=class{constructor(e,t,n,s){this.variableNames=["Image","Boxes","BoxInd"],this.uniforms="extrapolationValue : f32;",this.workGroupSize=[64,1,1],this.size=!0;let[r]=t;this.outputShape=[r,n[0],n[1],e],this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.methodId=s==="bilinear"?1:0,this.cropHeightBiggerThan1=this.outputShape[1]>1,this.cropWidthBiggerThan1=this.outputShape[2]>1,this.shaderKey=`cropAndResize_${this.methodId}_${this.cropHeightBiggerThan1}_${this.cropWidthBiggerThan1}`}getUserCode(){let[e,t]=["f32(uniforms.imageShape[1] - 1)","f32(uniforms.imageShape[2] - 1)"],[n,s,r]=this.cropHeightBiggerThan1?[`(${e} / f32(uniforms.outShape[1] - 1))`,"(y2-y1) * height_ratio",`y1*${e} + f32(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${e}`],[a,o,i]=this.cropWidthBiggerThan1?[`(${t} / f32(uniforms.outShape[2] - 1))`,"(x2-x1) * width_ratio",`x1*${t} + f32(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${t}`];return` ${nt()} if (index < uniforms.size) { let coords = getCoordsFromFlatIndex(index); let height_ratio = f32(${n}); let width_ratio = f32(${a}); let b = coords[0]; let y = coords[1]; let x = coords[2]; let d = coords[3]; // get box vals let y1 = getBoxes(b, 0); let x1 = getBoxes(b, 1); let y2 = getBoxes(b, 2); let x2 = getBoxes(b, 3); // get image in batch index let bInd = i32(round(getBoxInd(b))); if(bInd < 0 || bInd >= uniforms.outShape[0]) { return; } let height_scale = ${s}; let width_scale = ${o}; let in_y = ${r}; if( in_y < 0.0 || in_y > ${e} ) { setOutputFlat(index, uniforms.extrapolationValue); return; } let in_x = ${i}; if( in_x < 0.0 || in_x > ${t} ) { setOutputFlat(index, uniforms.extrapolationValue); return; } let sourceFracIndexCR = vec2(in_x,in_y); if(${this.methodId} == 1) { // Compute the four integer indices. let sourceFloorCR = vec2(sourceFracIndexCR); let sourceCeilCR = vec2(ceil(sourceFracIndexCR)); let topLeft = getImage(bInd, sourceFloorCR.y, sourceFloorCR.x, d); let bottomLeft = getImage(bInd, sourceCeilCR.y, sourceFloorCR.x, d); let topRight = getImage(bInd, sourceFloorCR.y, sourceCeilCR.x, d); let bottomRight = getImage(bInd, sourceCeilCR.y, sourceCeilCR.x, d); let fracCR = sourceFracIndexCR - vec2(sourceFloorCR); let top = topLeft + (topRight - topLeft) * fracCR.x; let bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x; let newValue = top + (bottom - top) * fracCR.y; setOutputFlat(index, newValue); } else { // Compute the coordinators of nearest neighbor point. let sourceNearestCR = vec2(floor( sourceFracIndexCR + vec2(0.5,0.5))); let newValue = getImage( bInd, sourceNearestCR.y, sourceNearestCR.x, d); setOutputFlat(index, newValue); } } } `}},nde=e=>{let{inputs:t,backend:n,attrs:s}=e,{image:r,boxes:a,boxInd:o}=t,{cropSize:i,method:l,extrapolationValue:c}=s,u=new tde(r.shape[3],a.shape,i,l),d=[{type:"float32",data:[c]}];return n.runWebGPUProgram(u,[r,a,o],"float32",d)},sde={kernelName:yi,backendName:"webgpu",kernelFunc:nde},rde=class{constructor(e,t){this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.uniforms="blockSize : i32;",this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`depthToSpace_${t}`,this.dataFormat=t}getUserCode(){return` ${nt()} if (index < uniforms.size) { let coords = getCoordsFromFlatIndex(index); let b = coords[0]; let h = ${this.getHeightCoordString()}; let w = ${this.getWidthCoordString()}; let d = ${this.getDepthCoordString()}; let in_h = h / uniforms.blockSize; let offset_h = h % uniforms.blockSize; let in_w = w / uniforms.blockSize; let offset_w = w % uniforms.blockSize; let offset_d = (offset_h * uniforms.blockSize + offset_w) * ${this.getOutputDepthSize()}; let in_d = d + offset_d; let rlt = ${this.getInputSamplingString()}; setOutputFlat(index, rlt); } }`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?"uniforms.outShape[3]":"uniforms.outShape[1]"}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}};function ade(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockSize:a,dataFormat:o}=s,i=r.shape[0],l=o==="NHWC"?r.shape[1]:r.shape[2],c=o==="NHWC"?r.shape[2]:r.shape[3],u=o==="NHWC"?r.shape[3]:r.shape[1],d=l*a,p=c*a,h=u/(a*a),f=o==="NHWC"?[i,d,p,h]:[i,h,d,p],m=[{type:"int32",data:[a]}],g=new rde(f,o);return n.runWebGPUProgram(g,[r],r.dtype,m)}var ode={kernelName:xi,backendName:"webgpu",kernelFunc:ade},VC=class{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.uniforms="pad : vec2; stride : vec2; dilation : vec2; inDims : vec2;",this.workGroupSize=[4,4,4],this.isVec4=!0,this.outputShape=e.outShape,this.dispatchLayout={x:[0,1],y:[2],z:[3]},this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize,[1,4,4]),v.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivation=s,this.shaderKey=`depthwise3x3_${n}`}getUserCode(){let e="",t="";if(this.activation){let r=ca(this.activation,this.isVec4);this.hasPreluActivation?e=`fn activation(a : vec4, outCoord : vec4) -> vec4 { let b = getPreluActivationWeightsAtOutCoordsByCoords(outCoord); ${r} }`:e=` fn activation(a : vec4, outCoord : vec4) -> vec4 { ${r} } `,t="dotProd[i] = activation(dotProd[i], coords);"}let n=this.addBias?"dotProd[i] = dotProd[i] + getBiasAtOutCoordsByCoords(coords);":"";return` ${e} ${s0()} fn main([[builtin(global_invocation_id)]] globalId: vec3) { let batch = 0; let r = i32(globalId.x); let c = i32(globalId.y) * 4; let d2 = i32(globalId.z) * 4; let xRCCorner = vec2(r, c) * uniforms.stride - uniforms.pad; let d1 = d2; let q = 0; let xRCorner = xRCCorner.x; let xCCorner = xRCCorner.y; var wVals : array, 9>; wVals[0] = getW(0, 0, d1, q); wVals[1] = getW(0, 1, d1, q); wVals[2] = getW(0, 2, d1, q); wVals[3] = getW(1, 0, d1, q); wVals[4] = getW(1, 1, d1, q); wVals[5] = getW(1, 2, d1, q); wVals[6] = getW(2, 0, d1, q); wVals[7] = getW(2, 1, d1, q); wVals[8] = getW(2, 2, d1, q); var xVals : array, 6>, 3>; for (var wR = 0; wR < 3; wR = wR + 1) { let xR = xRCorner + wR * uniforms.dilation[0]; for (var wC = 0; wC < 6; wC = wC + 1) { let xC = xCCorner + wC * uniforms.dilation[1]; if (xR < 0 || xR >= uniforms.inDims[0] || xC < 0 || xC >= uniforms.inDims[1]) { xVals[wR][wC] = vec4(0.0); } else { xVals[wR][wC] = getX(batch, xR, xC, d1); } } } var dotProd : array, 4>; dotProd[0] = vec4(0.0); dotProd[1] = vec4(0.0); dotProd[2] = vec4(0.0); dotProd[3] = vec4(0.0); for (var wR = 0; wR < 3; wR = wR + 1) { for (var wC = 0; wC < 3; wC = wC + 1) { let indexW = wR * 3 + wC; dotProd[0] = dotProd[0] + xVals[wR][0 + wC] * wVals[indexW]; dotProd[1] = dotProd[1] + xVals[wR][1 + wC] * wVals[indexW]; dotProd[2] = dotProd[2] + xVals[wR][2 + wC] * wVals[indexW]; dotProd[3] = dotProd[3] + xVals[wR][3 + wC] * wVals[indexW]; } } for (var i = 0; i < 4; i = i + 1) { let coords = vec4(batch, r, c + i, d2); if (coordsInBounds4D(coords, uniforms.outShape)) { ${n} ${t} setOutput(coords[0], coords[1], coords[2], coords[3], dotProd[i]); } } } `}},UC=class{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.uniforms="pad : vec2; stride : vec2; dilation : vec2; inDims : vec2;",this.workGroupSize=[256,1,1],this.outputShape=e.outShape,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),v.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivation=s,this.shaderKey=`depthwise_${this.convInfo.filterHeight}_${this.convInfo.filterWidth}_${this.activation}_${this.convInfo.outChannels/this.convInfo.inChannels}`}getUserCode(){let e=this.convInfo.outChannels/this.convInfo.inChannels,t="",n="";if(this.activation){let a=ca(this.activation,!1);this.hasPreluActivation?t=`fn activation(a : f32, outCoord : vec4) -> f32 { let b = getPreluActivationWeightsAtOutCoordsByCoords(outCoord); ${a} }`:t=` fn activation(a : f32, outCoord : vec4) -> f32 { ${a} } `,n="dotProd = activation(dotProd, coords);"}let s=this.addBias?"dotProd = dotProd + getBiasAtOutCoordsByCoords(coords);":"";return` ${t} fn writeResult(batch : i32, row : i32, col : i32, chan : i32, value : f32) { let coord = vec4(batch, row, col, chan); if (coordsInBounds4D(coord, uniforms.outShape)) { setOutput(batch, row, col, chan, value); } } ${Tx()} { let coords = getOutputCoordsWithFlatDispatchLayout(globalId, localId, numWorkgroups); let batch = coords[0]; let xRCCorner = vec2(coords.yz) * uniforms.stride - uniforms.pad; let d2 = coords[3]; let d1 = d2 / ${e}; let q = d2 - d1 * ${e}; let inputRowStart = xRCCorner.x; let inputColStart = xRCCorner.y; let inputRowEnd = inputRowStart + ${this.convInfo.filterHeight} * uniforms.dilation[0]; let inputColEnd = inputColStart + ${this.convInfo.filterWidth} * uniforms.dilation[1]; // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2). // ? = to be determined. : = across all values in that axis. var dotProd = 0.0; // Extract if checking out of for loop for performance. if (inputRowStart >= 0 && inputColStart >= 0 && inputRowEnd < uniforms.inDims[0] && inputColEnd < uniforms.inDims[1]) { // Here using a constant value |this.convInfo.filterHeight| instead // of uniform value is in order to loop unrolling. for (var wR = 0; wR < ${this.convInfo.filterHeight}; wR = wR + 1) { let xR = inputRowStart + wR * uniforms.dilation[0]; for (var wC = 0; wC < ${this.convInfo.filterWidth}; wC = wC + 1) { let xC = inputColStart + wC * uniforms.dilation[1]; let xVal = getX(batch, xR, xC, d1); let wVal = getW(wR, wC, d1, q); dotProd = dotProd + xVal * wVal; } } } else { for (var wR = 0; wR < ${this.convInfo.filterHeight}; wR = wR + 1) { let xR = inputRowStart + wR * uniforms.dilation[0]; if (xR < 0 || xR >= uniforms.inDims[0]) { continue; } for (var wC = 0; wC < ${this.convInfo.filterWidth}; wC = wC + 1) { let xC = inputColStart + wC * uniforms.dilation[1]; if (xC < 0 || xC >= uniforms.inDims[1]) { continue; } let xVal = getX(batch, xR, xC, d1); let wVal = getW(wR, wC, d1, q); dotProd = dotProd + xVal * wVal; } } } ${s} ${n} writeResult(batch, coords[1], coords[2], d2, dotProd); } `}};function ide(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dilations:l,dimRoundingMode:c}=s,u=l;u==null&&(u=[1,1]);let d=E.computeConv2DInfo(r.shape,a.shape,o,u,i,c,!0),p;d.batchSize===1&&d.inHeight===d.outHeight&&d.inWidth===d.outWidth&&d.strideHeight===1&&d.strideWidth===1&&d.filterHeight===d.filterWidth&&d.inChannels===d.outChannels&&d.filterHeight===3&&d.inChannels%4==0?p=new VC(d):p=new UC(d);let h=[{type:"int32",data:[d.padInfo.top,d.padInfo.left]},{type:"int32",data:[d.strideHeight,d.strideWidth]},{type:"int32",data:[d.dilationHeight,d.dilationWidth]},{type:"int32",data:[d.inHeight,d.inWidth]}];return n.runWebGPUProgram(p,[r,a],r.dtype,h)}var lde={kernelName:Ba,backendName:"webgpu",kernelFunc:ide},GC=Xn({opSnippet:Ut.MUL,cpuKernelImpl:Hue,supportsComplex:!0}),ude={kernelName:so,backendName:"webgpu",kernelFunc:GC},cde=class{constructor(e,t,n){this.variableNames=["x"],this.uniforms="reduceSize : i32;",this.inputShape=[e.batchSize,e.inSize];let[s]=E.computeOutAndReduceShapes(this.inputShape,[1]);this.outputShape=s.length===0?[1]:s,this.reductionFactor=2;let r=256,a=Math.min(Math.ceil(e.inSize/this.reductionFactor),r);this.workGroupSize=[a,1,1],this.dispatchLayout={x:[],y:this.outputShape.map((o,i)=>i)},this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.reduceType=t,this.shaderKey=`reduce_${t}_${n}`}getUserCode(){let e=this.workGroupSize[0]>1,t="",n="0.0";this.reduceType==="min"||this.reduceType==="max"?(t=` if (isNanCustom(candidate)) { bestValue = uniforms.NAN; } elseif (candidate ${this.reduceType==="min"?"<":">"} bestValue) { bestValue = candidate; }`,n="f32(x.numbers[offset])"):this.reduceType==="sum"||this.reduceType==="mean"?t=" bestValue = bestValue + candidate; ":this.reduceType==="prod"&&(t=" bestValue = bestValue * candidate; ",n="1.0");let s=this.reduceType==="mean"?"setOutputFlat(flatOutputIndex, bestValue / f32(uniforms.reduceSize));":"setOutputFlat(flatOutputIndex, bestValue);",r=` var xBestValues : array; `,a=` xBestValues[localId.x] = bestValue; ${this.reduceType==="sum"||this.reduceType==="mean"||this.reduceType==="prod"?`bestValue = ${n};`:" "} var currentSize = WorkGroupSize; for(; currentSize > 1;) { workgroupBarrier(); for (var w = 0; w < ${this.reductionFactor}; w = w + 1) { let i = i32(localId.x) * ${this.reductionFactor} + w; if (i < currentSize) { let candidate = xBestValues[i]; ${t} } } workgroupBarrier(); xBestValues[localId.x] = bestValue; currentSize = DIV_CEIL(currentSize, ${this.reductionFactor}); ${this.reduceType==="sum"||this.reduceType==="mean"||this.reduceType==="prod"?`if(currentSize > 1) { bestValue = ${n}; }`:""} } if (localId.x == 0u) { ${s} } `;return` fn DIV_CEIL(a : i32, b : i32) -> i32 { return ((a - 1) / b + 1); } let WorkGroupSize = ${this.workGroupSize[0]}; ${e?r:""} fn getOffset(globalId : vec3) -> i32 { let outputCoords = getOutputCoordsWithNonFlatDispatchLayout(globalId); let offset = ${this.outputShape.length===1?"outputCoords":"outputCoords[0]"} * uniforms.reduceSize; return offset; } ${Xo()} { let offset = getOffset(globalId); var bestValue = ${n}; let Length = uniforms.reduceSize; let WorkPerThread = DIV_CEIL(Length, WorkGroupSize); for (var w = 0; w < WorkPerThread; w = w + 1) { let i = i32(globalId.x) * WorkPerThread + w; if (i < Length) { let candidate = f32(x.numbers[offset + i]); ${t} } } let flatOutputIndex = i32(globalId.y); ${e?a:s} } `}};function Tp(e,t,n,s,r){let a=e.shape.length,o=[],i=v.parseAxisParam(t,e.shape),l=i,c=E.getAxesPermutation(l,a),u=e;c!=null&&(u=Ol({inputs:{x:e},attrs:{perm:c},backend:r}),l=E.getInnerMostAxes(l.length,a),o.push(u)),E.assertAxesAreInnerMostDims(s,l,a);let[d,p]=E.computeOutAndReduceShapes(u.shape,l),h=d;n&&(h=E.expandShapeToKeepDim(d,i));let f;if((s==="max"||s==="prod")&&r.shouldExecuteOnCPU([u])){let m=r.tensorMap.get(u.dataId).values;switch(s){case"max":let g=Vue(m,v.sizeFromShape(p),h,e.dtype);f=r.makeTensorInfo(h,e.dtype,g);break;case"prod":let{outVals:A,outShape:x,outDtype:y}=Xue(u.shape,u.dtype,m,l);f=r.makeTensorInfo(x,y,A);break;default:throw new Error(`${s} CPU implementation is not yet supported.`)}}else{let m=v.sizeFromShape(p),A=v.sizeFromShape(u.shape)/m,x={windowSize:m,inSize:m,batchSize:A,outSize:1},y=s==="mean"?"float32":Ed(e.dtype),b=[{type:"int32",data:[m]}],w=new cde(x,s,y),k=r.runWebGPUProgram(w,[u],y,b);o.push(k),f=je({inputs:{x:k},attrs:{shape:h},backend:r})}return o.forEach(m=>r.disposeData(m.dataId)),f}function zx(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;return Tp(r,a,o,"sum",n)}var dde={kernelName:mo,backendName:"webgpu",kernelFunc:zx};function pde(e){let{inputs:t,backend:n,attrs:s}=e,{equation:r}=s,a=t,{allDims:o,summedDims:i,idDims:l}=E.decodeEinsumEquation(r,a.length);E.checkEinsumDimSizes(o.length,l,a);let{path:c,steps:u}=E.getEinsumComputePath(i,l),d=u.length,p=null,h=o.length,f=[];for(let m=0;m=0&&(p=zx({inputs:{x:p},backend:n,attrs:{axis:c[m]-(o.length-h),keepDims:!1}}),f.push(p)),h--)}for(let m of f)m!==p&&n.disposeData(m.dataId);return p}var hde={kernelName:dd,backendName:"webgpu",kernelFunc:pde},fde=Nn({opType:bt.ELU}),mde={kernelName:Va,backendName:"webgpu",kernelFunc:fde},gde=Xn({opSnippet:Ut.EQUAL,dtype:"bool",cpuKernelImpl:$ue}),Ade={kernelName:bi,backendName:"webgpu",kernelFunc:gde},HC=Nn({opType:bt.EXP,cpuKernelImpl:_ue,dtype:"float32"}),yde={kernelName:Ua,backendName:"webgpu",kernelFunc:HC};function Lx(e){let{inputs:t,attrs:n,backend:s}=e,{dim:r}=n,{input:a}=t,o=a.shape.length,i=a.shape.slice(),l=r;return r<0&&(v.assert(-(o+1)<=r,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+r+1),i.splice(l,0,1),je({inputs:{x:a},backend:s,attrs:{shape:i}})}var xde={kernelName:vi,backendName:"webgpu",kernelFunc:Lx},bde=Nn({opType:bt.EXPM1,cpuKernelImpl:Due}),vde={kernelName:wi,backendName:"webgpu",kernelFunc:bde},wde=class{constructor(e){this.variableNames=[],this.outputShape=[],this.uniforms="value : f32;",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="fill"}getUserCode(){return` ${nt()} if (index < uniforms.size) { setOutputFlat(index, uniforms.value); } } `}};function wc(e){let{backend:t,attrs:n}=e,{shape:s,value:r}=n,{dtype:a}=n;if(a=a||v.inferDtype(r),a==="string"){let o=v.getArrayFromDType(a,v.sizeFromShape(s));return o.fill(r),t.makeTensorInfo(s,a,o)}else{let o=new wde(s),i=[{type:"float32",data:[r]}];return t.runWebGPUProgram(o,[],a,i)}}var kde={kernelName:yu,backendName:"webgpu",kernelFunc:wc},Sde=class{constructor(e){this.outputShape=[],this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="flipLeftRight"}getUserCode(){return` ${nt()} if (index < uniforms.size) { let coords = getCoordsFromFlatIndex(index); let coordX = uniforms.xShape[2] - coords[2] - 1; let outputValue = getX(coords[0], coords[1], coordX, coords[3]); setOutputFlat(index, outputValue); } } `}},Ide={kernelName:ki,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,s=t,r=new Sde(n.shape);return s.runWebGPUProgram(r,[n],n.dtype)}},Cde=Nn({opType:bt.FLOOR,cpuKernelImpl:Pue}),Tde={kernelName:Ga,backendName:"webgpu",kernelFunc:Cde},Nde=Xn({opSnippet:Ut.INT_DIV,dtype:"int32"}),Ede={kernelName:Ha,backendName:"webgpu",kernelFunc:Nde},Rde=(e,t,n,s,r)=>{let a=[s,...n];return r&&a.push(r),e.createBindGroup({layout:t,entries:a.map((o,i)=>({binding:i,resource:o}))})},jC=(e,t,n,s,r,a=!1)=>{let o={dtype:r.dtype,shape:r.shape},i=ile(s,o,t,a),l=e.createShaderModule({code:i});return e.createComputePipeline({layout:n,compute:{module:l,entryPoint:"main"}})};function qC(e,t,n,s="",r=""){return e.shaderKey+"_"+(e.workGroupSize?e.workGroupSize.join(","):"")+t.map(o=>o.length).join(",")+n.join(",")+e.variableNames.join(",")+s+r}function XC(e){let{externalImage:t,backend:n,attrs:s,outShape:r,useImport:a}=e,{numChannels:o}=s,i=v.sizeFromShape(r),l=v.computeStrides(r),c=n.makeTensorInfo(r,"int32"),u=n.getFromPixelsProgram(a?"import":"copyExternal");u.updateOutputShape(r);let d=[c.shape],p=[c.dtype,a?"import":"copyExternal"],h=qC(u,d,p),f=u.getLayout(n.device),m=n.getAndSavePipeline(h,()=>jC(n.device,u,f.pipelineLayout,[],c,!0));u.setPipeline(m),a||n.queue.copyExternalImageToTexture({source:t,origin:{x:0,y:0}},{texture:u.makeInputTexture(n.device,r[1],r[0])},[r[1],r[0]]);let g=n.tensorMap.get(c.dataId);g.bufferInfo.buffer=n.acquireBuffer(g.bufferInfo.byteSize);let A=[i,o,...l,...u.dispatch];u.setUniform(n.device,A);let x;if(a){let y={source:t};x=n.device.importExternalTexture(y)}else x=u.inputTexture.createView();return n.runFromPixelsProgram(u,g.bufferInfo.buffer,f,x,c.dataId),c}var $de={kernelName:bd,backendName:"webgpu",kernelFunc:_de},kc;function _de(e){let{inputs:t,backend:n,attrs:s}=e,{pixels:r}=t,{numChannels:a}=s;if(r==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let o=typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement,l=typeof HTMLCanvasElement!="undefined"&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas!="undefined"&&r instanceof OffscreenCanvas,c=typeof ImageBitmap!="undefined"&&r instanceof ImageBitmap,[u,d]=o?[r.videoWidth,r.videoHeight]:[r.width,r.height],p=[d,u,a];if(Y().getBool("WEBGPU_USE_IMPORT")&&o)return XC({externalImage:r,backend:n,attrs:s,outShape:p,useImport:!0});if((o||i)&&(kc==null&&(kc=document.createElement("canvas").getContext("2d")),kc.canvas.width=u,kc.canvas.height=d,kc.drawImage(r,0,0,u,d),r=kc.canvas),c||l||o||i)return XC({externalImage:r,backend:n,attrs:s,outShape:p,useImport:!1});let h=r.data,f=h;if(a!=null&&a!==4){f=new Uint8Array(r.width*r.height*a);let A=h.length,x=0;for(let y=0;y(xValue, -meanValue, offsetValue), vec3(inv, inv, 1.0))); } } `}},Pde={kernelName:ja,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:s,scale:r,offset:a,mean:o,variance:i}=e,{varianceEpsilon:l}=t,c=n,u=[s,o,i],d=null;a!=null&&(d=a.shape,u.push(a));let p=null;r!=null&&(p=r.shape,u.push(r));let h=new Dde(s.shape,o.shape,i.shape,d,p),f=[{type:"float32",data:[l]}];return c.runWebGPUProgram(h,u,s.dtype,f)}};function Fde(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dataFormat:u,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=s,m=E.convertConv2DDataFormat(u),g=E.computeConv2DInfo(r.shape,a.shape,l,d,c,p,!1,m),A=o!=null,x=i!=null,y;if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))return zC({x:r,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});let b=Y().getBool("WEBGPU_USE_NAIVE_CONV2D"),w=g.inChannels%4==0&&g.outChannels%4==0,k=[g.padInfo.top,g.padInfo.left],I=[{type:"int32",data:[g.filterHeight,g.filterWidth]},{type:"int32",data:[...k]},{type:"int32",data:[g.strideHeight,g.strideWidth]},{type:"int32",data:[g.dilationHeight,g.dilationWidth]}];if(b)y=new WC(g,A,h,x);else{w?y=new LC(g,A,h,x):y=new BC(g,A,h,x);let R=g.outShape[1]*g.outShape[2],O=g.outShape[3],$=g.filterHeight*g.filterWidth*g.inShape[3];I.push({type:"int32",data:[R]},{type:"int32",data:[O]},{type:"int32",data:[$]})}let N=[r,a];return A&&N.push(o),x&&N.push(i),n.runWebGPUProgram(y,N,r.dtype,I)}var Ode={kernelName:ko,backendName:"webgpu",kernelFunc:Fde};function Mde(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dilations:u,dimRoundingMode:d,activation:p}=s,h=u;h==null&&(h=[1,1]),v.assert(E.eitherStridesOrDilationsAreOne(l,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${h}'`);let f=E.computeConv2DInfo(r.shape,a.shape,l,h,c,d,!0),m=[r,a],g=o!=null,A=i!=null;g&&m.push(o),A&&m.push(i);let x;f.batchSize===1&&f.inHeight===f.outHeight&&f.inWidth===f.outWidth&&f.strideHeight===1&&f.strideWidth===1&&f.filterHeight===f.filterWidth&&f.inChannels===f.outChannels&&f.filterHeight===3&&f.inChannels%4==0?x=new VC(f,g,p,A):x=new UC(f,g,p,A);let y=[{type:"int32",data:[f.padInfo.top,f.padInfo.left]},{type:"int32",data:[f.strideHeight,f.strideWidth]},{type:"int32",data:[f.dilationHeight,f.dilationWidth]},{type:"int32",data:[f.inHeight,f.inWidth]}];return n.runWebGPUProgram(x,m,"float32",y)}var zde={kernelName:So,backendName:"webgpu",kernelFunc:Mde},Lde=class{constructor(e,t){this.variableNames=["A","indices"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`gathernd_${e}`,this.sliceDim=e,this.uniforms=`sliceDim : i32; strides : ${wn(e)};`}getUserCode(){let e;return this.sliceDim>1?e="uniforms.strides[j]":e="uniforms.strides",` ${nt()} if (index < uniforms.size) { let coords = getCoordsFromFlatIndex(index); var flattenIndex = 0; for (var j = 0; j < uniforms.sliceDim; j = j + 1) { let indexTemp = i32(round(getIndices(coords[0], j))); let strideNum = ${e}; flattenIndex = flattenIndex + indexTemp * strideNum; } setOutputFlat(index, getA(flattenIndex, coords[1])); } } `}};function Bde(e){let{inputs:t,backend:n}=e,{params:s,indices:r}=t,a=r.shape,o=a[a.length-1],i=v.sizeFromShape(s.shape),[l,c,u,d]=E.prepareAndValidate(s,r),p=je({inputs:{x:r},backend:n,attrs:{shape:[c,o]}}),h=je({inputs:{x:s},backend:n,attrs:{shape:[v.sizeFromShape(s.shape)/u,u]}});if(n.shouldExecuteOnCPU([s,r])||s.dtype==="string"){let x=n.readSync(r.dataId),y=n.bufferSync(s),b=Fue(x,y,s.dtype,c,o,u,d,s.shape,i);return n.makeTensorInfo(l,s.dtype,b.values)}let f=new Lde(o,[c,u]),m=[{type:"int32",data:[o]},{type:"int32",data:d}],g=n.runWebGPUProgram(f,[h,p],h.dtype,m),A=je({inputs:{x:g},backend:n,attrs:{shape:l}});return n.disposeData(p.dataId),n.disposeData(h.dataId),n.disposeData(g.dataId),A}var Wde={kernelName:Ii,backendName:"webgpu",kernelFunc:Bde},Vde=class{constructor(e,t){this.variableNames=["A","indices"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e.slice(),this.aShape=e,this.outputShape=t,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="gather"}getUserCode(){let e=Ude(this.aShape,"i32");return` ${nt()} if (index < uniforms.size) { let resRC = getCoordsFromFlatIndex(index); setOutputFlat(index, getA(${e})); } } `}};function Ude(e,t="int"){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let r=0;rn.disposeData(R.dataId)),n.makeTensorInfo(c.outputShape,N.dtype,N.values)}let m=new Vde(p.shape,f),g=n.runWebGPUProgram(m,[p,h],p.dtype);d.push(g);let A=je({inputs:{x:g},backend:n,attrs:{shape:c.outputShape}});return d.forEach(x=>n.disposeData(x.dataId)),A}var Gde={kernelName:Si,backendName:"webgpu",kernelFunc:KC},Hde=Xn({opSnippet:Ut.GREATER,cpuKernelImpl:zue,dtype:"bool"}),jde={kernelName:Ci,backendName:"webgpu",kernelFunc:Hde},qde=Xn({opSnippet:Ut.GREATER_EQUAL,dtype:"bool",cpuKernelImpl:Mue}),Xde={kernelName:qa,backendName:"webgpu",kernelFunc:qde},Kde=Xn({opSnippet:Ut.LESS,dtype:"bool",cpuKernelImpl:Bue}),Zde={kernelName:Ni,backendName:"webgpu",kernelFunc:Kde},Yde=Xn({opSnippet:Ut.LESS_EQUAL,dtype:"bool",cpuKernelImpl:Lue}),Jde={kernelName:Ei,backendName:"webgpu",kernelFunc:Yde},Qde=Nn({opType:bt.LOG,cpuKernelImpl:Wue}),epe={kernelName:Ka,backendName:"webgpu",kernelFunc:Qde},tpe=Xn({opSnippet:Ut.LOGICAL_AND,dtype:"bool"}),npe={kernelName:Ri,backendName:"webgpu",kernelFunc:tpe},spe=Nn({opType:bt.LOGICAL_NOT}),rpe={kernelName:ku,backendName:"webgpu",kernelFunc:spe};function ZC(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reductionIndices:a,keepDims:o}=s;return Tp(r,a,o,"max",n)}var ape={kernelName:Za,backendName:"webgpu",kernelFunc:ZC},ope=Xn({opSnippet:Ut.MAX,cpuKernelImpl:Uue}),ipe={kernelName:Ya,backendName:"webgpu",kernelFunc:ope};function lpe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,c=1,u=E.computePool2DInfo(r.shape,a,o,c,i,l),d,p=[];if(u.filterHeight===1&&u.filterWidth===1){if(v.arraysEqual(u.inShape,u.outShape))return sr({inputs:{x:r},backend:n});d=new FC(u),p.push({type:"int32",data:[u.strideHeight,u.strideWidth]})}else d=new PC(u,"max"),p.push({type:"int32",data:[u.strideHeight,u.strideWidth]},{type:"int32",data:[u.padInfo.top,u.padInfo.left]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]},{type:"int32",data:[u.inHeight,u.inWidth]},{type:"int32",data:[u.effectiveFilterHeight,u.effectiveFilterWidth]});return n.runWebGPUProgram(d,[r],r.dtype,p)}var upe={kernelName:Ja,backendName:"webgpu",kernelFunc:lpe};function cpe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{keepDims:a,axis:o}=s;return Tp(r,o,a,"mean",n)}var dpe={kernelName:Qa,backendName:"webgpu",kernelFunc:cpe};function ppe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;return Tp(r,a,o,"min",n)}var hpe={kernelName:eo,backendName:"webgpu",kernelFunc:ppe},fpe=Xn({opSnippet:Ut.MIN,cpuKernelImpl:Gue}),mpe={kernelName:to,backendName:"webgpu",kernelFunc:fpe},gpe=class{constructor(e,t,n){this.uniforms="",this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((s,r)=>s[0]+e[r]+s[1]),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.xShape=e,t.map((s,r)=>{this.uniforms+=` pad${r} : vec2;`}),this.offset=n==="reflect"?0:1,this.shaderKey=`mirrorPad_${n}`}getUserCode(){let e=this.xShape.length,t=this.xShape.map((l,c)=>`uniforms.pad${c}[0]`).join(","),n=this.xShape.map((l,c)=>`uniforms.pad${c}[0] + uniforms.xShape${e>1?`[${c}]`:""}`).join(","),s=e===1?"start":"start[i]",r=e===1?"end":"end[i]",a=e===1?"outC":"outC[i]",o=wn(e),i=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return` ${nt()} if (index < uniforms.size) { let start = ${o}(${t}); let end = ${o}(${n}); var outC = getCoordsFromFlatIndex(index); for (var i = 0; i < ${e}; i = i + 1) { if (${a} < ${s}) { ${a} = ${s} * 2 - ${a} - ${this.offset}; } elseif(${a} >= ${r}) { ${a} = (${r} - 1) * 2 - ${a} + ${this.offset}; } } let coords = outC - start; setOutputFlat(index, getX(${i})); } } `}},Ape={kernelName:no,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:s}=e,{paddings:r,mode:a}=t,o=n,i=r.map(u=>({type:"int32",data:[u[0],u[1]]})),l=new gpe(s.shape,r,a);return o.runWebGPUProgram(l,[s],s.dtype,i)}};function ype(e){let{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])){let a=n.tensorMap.get(s.dataId),[o,i]=jue(a.values,s.shape,s.dtype);return n.makeTensorInfo(i,s.dtype,o)}let r=new r0(s.shape,bt.NEG);return n.runWebGPUProgram(r,[s],s.dtype)}var xpe={kernelName:$i,backendName:"webgpu",kernelFunc:ype};function bpe(e){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l}=s,c=n.readSync(r.dataId),u=n.readSync(a.dataId),{selectedIndices:d}=Qs.nonMaxSuppressionV3Impl(c,u,o,i,l);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}var vpe={kernelName:Di,backendName:"webgpu",kernelFunc:bpe};function wpe(e){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l,softNmsSigma:c}=s,u=n.readSync(r.dataId),d=n.readSync(a.dataId),p=o,h=i,f=l,m=c,{selectedIndices:g,selectedScores:A}=Qs.nonMaxSuppressionV5Impl(u,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([A.length],"float32",new Float32Array(A))]}var kpe={kernelName:Pi,backendName:"webgpu",kernelFunc:wpe};function o0(e){let{inputs:t,backend:n}=e,{x:s}=t;if(s.dtype==="complex64"){let r=Cp({inputs:{input:s},backend:n}),a=o0({inputs:{x:r},backend:n}),o=a0({inputs:{input:s},backend:n}),i=o0({inputs:{x:o},backend:n}),l=bc({inputs:{real:a,imag:i},backend:n});return n.disposeData(r.dataId),n.disposeData(a.dataId),n.disposeData(o.dataId),n.disposeData(i.dataId),l}else return wc({attrs:{shape:s.shape,dtype:s.dtype,value:s.dtype==="string"?"":0},backend:n})}var Spe={kernelName:Qi,backendName:"webgpu",kernelFunc:o0};function YC(e){let{inputs:t,backend:n}=e,{x:s}=t;if(s.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(s.dtype==="complex64"){let r=Cp({inputs:{input:s},backend:n}),a=YC({inputs:{x:r},backend:n}),o=a0({inputs:{input:s},backend:n}),i=o0({inputs:{x:o},backend:n}),l=bc({inputs:{real:a,imag:i},backend:n});return n.disposeData(r.dataId),n.disposeData(a.dataId),n.disposeData(o.dataId),n.disposeData(i.dataId),l}else return wc({attrs:{shape:s.shape,dtype:s.dtype,value:1},backend:n})}var Ipe={kernelName:Fi,backendName:"webgpu",kernelFunc:YC};function Cpe(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(t.length===1)return Lx({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let a=t[0].shape,o=t[0].dtype;t.forEach(u=>{v.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),v.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(u=>{let d=Lx({inputs:{input:u},backend:n,attrs:{dim:r}});return i.push(d),d}),c=MC({inputs:l,backend:n,attrs:{axis:r}});return i.forEach(u=>n.disposeData(u.dataId)),c}var Tpe={kernelName:Mi,backendName:"webgpu",kernelFunc:Cpe},Npe=class{constructor(e,t){this.variableNames=["x"],this.uniforms="constantValue : f32;",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((n,s)=>n[0]+e[s]+n[1]),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),t.map((n,s)=>{this.uniforms+=` pad${s} : vec2;`}),this.xShape=e,this.shaderKey="pad"}getUserCode(){let e=this.xShape.length,t=wn(e),n=this.xShape.map((u,d)=>`uniforms.pad${d}[0]`).join(","),s=this.xShape.map((u,d)=>`uniforms.pad${d}[0] + uniforms.xShape${e>1?`[${d}]`:""}`).join(","),r=e>1?`${t}(${n})`:`${n}`,a=e>1?`${t}(${s})`:`${s}`,o=e>1?"any(outC < start)":"outC < start",i=e>1?"any(outC >= end)":"outC >= end",l=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return` ${nt()} if (index < uniforms.size) { let start = ${r}; let end = ${a}; let outC = getCoordsFromFlatIndex(index); if (${o} || ${i}) { setOutputFlat(index, uniforms.constantValue); } else { let coords = outC - start; setOutputFlat(index, getX(${l})); } } } `}},JC=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,constantValue:o}=s;if(a.every(c=>v.arraysEqual(c,[0,0])))return sr({inputs:{x:r},backend:n});if(v.sizeFromShape(r.shape)===0){let c=a.map((u,d)=>u[0]+r.shape[d]+u[1]);return wc({backend:n,attrs:{shape:c,value:o,dtype:r.dtype}})}let i=[{type:"float32",data:[o]}];a.map(c=>i.push({type:"int32",data:[c[0],c[1]]}));let l=new Npe(r.shape,a);return n.runWebGPUProgram(l,[r],r.dtype,i)},Epe={kernelName:ro,backendName:"webgpu",kernelFunc:JC},Rpe=Xn({opSnippet:Ut.POW}),$pe={kernelName:ao,backendName:"webgpu",kernelFunc:Rpe};function _pe(e){let{inputs:t,backend:n}=e,{x:s,alpha:r}=t,a=new $C(Ut.PRELU,s.shape,r.shape);return n.runWebGPUProgram(a,[s,r],"float32")}var Dpe={kernelName:oo,backendName:"webgpu",kernelFunc:_pe};function Ppe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;return Tp(r,a,o,"prod",n)}var Fpe={kernelName:zi,backendName:"webgpu",kernelFunc:Ppe},Ope=e=>{let{backend:t,attrs:n}=e,{start:s,stop:r,step:a,dtype:o}=n,i=Kue(s,r,a,o);return t.makeTensorInfo([i.length],o,i)},Mpe={kernelName:Cu,backendName:"webgpu",kernelFunc:Ope},QC=Xn({opSnippet:Ut.DIV}),zpe={kernelName:Wa,backendName:"webgpu",kernelFunc:QC},Lpe=Nn({opType:bt.RELU}),Bpe={kernelName:io,backendName:"webgpu",kernelFunc:Lpe},Wpe=Nn({opType:bt.RELU6}),Vpe={kernelName:uo,backendName:"webgpu",kernelFunc:Wpe},Upe=class{constructor(e,t,n,s,r){this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,n,e[3]],this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.alignCorners=s,this.halfPixelCenters=r,this.shaderKey=`resizeBilinear_${s}_${r}_${this.outputShape[1]>1}_${this.outputShape[2]>1}`}getUserCode(){let e=this.alignCorners&&this.outputShape[1]>1,t=this.alignCorners&&this.outputShape[2]>1;return` ${nt()} if (index < uniforms.size) { let coords = getCoordsFromFlatIndex(index); let b = coords[0]; let d = coords[3]; let rc = coords.yz; let effectiveInSize = vec2( ${e?"f32(uniforms.xShape.y) - 1.0":"f32(uniforms.xShape.y)"}, ${t?"f32(uniforms.xShape.z) - 1.0":"f32(uniforms.xShape.z)"}); let effectiveOutSize = vec2( ${e?"f32(uniforms.outShape.y) - 1.0":"f32(uniforms.outShape.y)"}, ${t?"f32(uniforms.outShape.z) - 1.0":"f32(uniforms.outShape.z)"}); let effectiveInputOverOutputRatioRC = effectiveInSize / effectiveOutSize; // Fractional source index let sourceFracIndexRC = ${this.halfPixelCenters?"(vec2(rc) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":"vec2(rc) * effectiveInputOverOutputRatioRC"}; // Compute the four integer indices. let sourceFloorRC = vec2(sourceFracIndexRC); let sourceCeilRC = vec2( min(vec2(uniforms.xShape.yz) - vec2(1.0), ceil(sourceFracIndexRC))); let topLeft = getX(b, sourceFloorRC.x, sourceFloorRC.y, d); let bottomLeft = getX(b, sourceCeilRC.x, sourceFloorRC.y, d); let topRight = getX(b, sourceFloorRC.x, sourceCeilRC.y, d); let bottomRight = getX(b, sourceCeilRC.x, sourceCeilRC.y, d); let fracRC = sourceFracIndexRC - vec2(sourceFloorRC); let top = topLeft + (topRight - topLeft) * fracRC.y; let bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y; let newValue = top + (bottom - top) * fracRC.x; setOutputFlat(index, newValue); } } `}};function Gpe(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,size:o,halfPixelCenters:i}=s,[l,c]=o,u=new Upe(r.shape,l,c,a,i);return n.runWebGPUProgram(u,[r],"float32")}var Hpe={kernelName:lo,backendName:"webgpu",kernelFunc:Gpe},jpe=class{constructor(e,t,n,s,r){this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,n,e[3]],this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.alignCorners=s,this.halfPixelCenters=r,this.shaderKey=`resizeNearest_${s}_${this.outputShape[1]>1}_${this.outputShape[2]>1}_${r}`}getUserCode(){let e=this.alignCorners?"0.5":"0.0",t;this.halfPixelCenters?t="max((vec2(rc) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":t="vec2(rc) * effectiveInputOverOutputRatioRC";let n=this.alignCorners&&this.outputShape[1]>1,s=this.alignCorners&&this.outputShape[2]>1;return` ${nt()} if (index < uniforms.size) { let coords = getCoordsFromFlatIndex(index); let b = coords[0]; let d = coords[3]; let rc = coords.yz; let effectiveInSize = vec2( ${n?"f32(uniforms.xShape.y) - 1.0":"f32(uniforms.xShape.y)"}, ${s?"f32(uniforms.xShape.z) - 1.0":"f32(uniforms.xShape.z)"}); let effectiveOutSize = vec2( ${n?"f32(uniforms.outShape.y) - 1.0":"f32(uniforms.outShape.y)"}, ${s?"f32(uniforms.outShape.z) - 1.0":"f32(uniforms.outShape.z)"}); let effectiveInputOverOutputRatioRC = effectiveInSize / effectiveOutSize; // Fractional source index let sourceFracIndexRC = ${t}; // Compute the coordinators of nearest neighbor point. let inputShapeRC = vec2(f32(uniforms.xShape.y), f32(uniforms.xShape.z)); let sourceNearestRC = vec2( min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${e}))); let newValue = getX(b, sourceNearestRC.x, sourceNearestRC.y, d); setOutputFlat(index, newValue); } } `}};function qpe(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:o,size:i}=s,[l,c]=i,u=new jpe(r.shape,l,c,a,o);return n.runWebGPUProgram(u,[r],r.dtype)}var Xpe={kernelName:Nu,backendName:"webgpu",kernelFunc:qpe},Kpe=class{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms=`centerX : f32; centerY : f32; sinRadians : f32; cosRadians : f32;`,this.shaderKey="rotate",this.outputShape=e,typeof t=="number"?(this.uniforms+=" fillValue : f32;",this.fillSnippet="var outputValue = uniforms.fillValue;",this.shaderKey+="_float"):(this.uniforms+=" fillValue : vec3;",this.fillSnippet="var outputValue = uniforms.fillValue[coords[3]];",this.shaderKey+="_vec3")}getUserCode(){return` ${nt()} if (index < uniforms.size) { let coords = getCoordsFromFlatIndex(index); let coordXFloat = (f32(coords[2]) - uniforms.centerX) * uniforms.cosRadians - (f32(coords[1]) - uniforms.centerY) * uniforms.sinRadians; let coordYFloat = (f32(coords[2]) - uniforms.centerX) * uniforms.sinRadians + (f32(coords[1]) - uniforms.centerY) * uniforms.cosRadians; let coordX = i32(round(coordXFloat + uniforms.centerX)); let coordY = i32(round(coordYFloat + uniforms.centerY)); ${this.fillSnippet} if(coordX >= 0 && coordX < uniforms.xShape[2] && coordY >= 0 && coordY < uniforms.xShape[1]) { outputValue = getX(coords[0], coordY, coordX, coords[3]); } setOutputFlat(index, outputValue); } } `}},Zpe={kernelName:el,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:s}=e,{radians:r,fillValue:a,center:o}=t,i=n,l=new Kpe(s.shape,a),[c,u]=E.getImageCenter(o,s.shape[1],s.shape[2]),d=[{type:"float32",data:[c]},{type:"float32",data:[u]},{type:"float32",data:[Math.sin(r)]},{type:"float32",data:[Math.cos(r)]}];return typeof a=="number"?d.push({type:"float32",data:[Number.parseFloat(a.toFixed(2))]}):d.push({type:"float32",data:a}),i.runWebGPUProgram(l,[s],s.dtype,d)}},Ype=Nn({opType:bt.RSQRT,cpuKernelImpl:Zue}),Jpe={kernelName:co,backendName:"webgpu",kernelFunc:Ype},Qpe=class{constructor(e,t,n,s,r,a,o){this.variableNames=["updates","indices"],this.workGroupSize=[64,1,1],this.atomic=!0,this.outputShape=a,this.type=o,this.dispatchLayout=Xe(e),this.dispatch=Fe(this.dispatchLayout,e,this.workGroupSize),this.sliceDimGreaterThanOne=t>1,this.shaderKey=`scatter_${n}_${s}_${this.sliceDimGreaterThanOne}_${o}`;let i=wn(r.length);this.uniforms=`sliceDim : i32; strides: ${i}; size: i32;`,this.updatesRank=s,this.indicesRank=n}getUserCode(){let e="";this.indicesRank===1?e="coords[0]":this.indicesRank===2&&(e="coords[0], j");let t=`getIndices(${e})`,n=this.sliceDimGreaterThanOne?"uniforms.strides[j]":"uniforms.strides",s="",r="",a="";this.updatesRank===1?(s="coords[0]",r="flattenedIndex",a=` fn getUpdatesCoordsFromFlatIndex(index : i32) -> i32 { return index; } `):this.updatesRank===2&&(s="coords[0], coords[1]",r="vec2(flattenedIndex, coords[1])",a=` fn getUpdatesCoordsFromFlatIndex(index : i32) -> vec2 { let d0 = index / uniforms.updatesShape[1]; let d1 = index - d0 * uniforms.updatesShape[1]; return vec2(d0, d1); } `);let o=`getUpdates(${s})`,i=this.type==="int32"?"ignore(atomicAdd(&(result.numbers[flatIndex]), i32(updateValue)));":` var assumed = atomicLoad(&(result.numbers[flatIndex])); var success = 0; for (; success == 0;) { let new = bitcast(assumed) + updateValue; let newI32 = bitcast(new); let resValue = atomicCompareExchangeWeak(&(result.numbers[flatIndex]), assumed, newI32); assumed = resValue[0]; success = resValue[1]; } `;return` ${a} ${nt()} if (index < uniforms.size) { let coords = getUpdatesCoordsFromFlatIndex(index); var flattenedIndex = 0; for (var j = 0; j < uniforms.sliceDim; j = j + 1) { let indexInside = i32(round(${t})); flattenedIndex = flattenedIndex + indexInside * ${n}; } let updateValue = ${o}; let flatIndex = getOutputFlatIndex(${r}); ${i} } }`}};function ehe(e){let{inputs:t,backend:n,attrs:s}=e,{indices:r,updates:a}=t,{shape:o}=s,{sliceRank:i,numUpdates:l,sliceSize:c,strides:u,outputSize:d}=E.calculateShapes(a,r,o),p=[d/c,c];if(d===0)return n.makeTensorInfo(o,r.dtype);let h=je({inputs:{x:r},backend:n,attrs:{shape:[l,i]}}),f=je({inputs:{x:a},backend:n,attrs:{shape:[l,c]}}),m=f.dtype,g=wc({backend:n,attrs:{shape:p,value:0,dtype:m}}),A=v.sizeFromShape(f.shape),x=[{type:"int32",data:[i]},{type:"int32",data:u},{type:"int32",data:[A]}],y=new Qpe(f.shape,i,h.shape.length,f.shape.length,u,p,m),b=n.runWebGPUProgram(y,[f,h],m,x,g),w=je({inputs:{x:b},backend:n,attrs:{shape:o}});return n.disposeData(h.dataId),n.disposeData(f.dataId),n.disposeData(b.dataId),w}var the={kernelName:Vi,backendName:"webgpu",kernelFunc:ehe},nhe=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.cRank=e,this.rank=n,this.shaderKey="select"}getUserCode(){let e,t;if(this.rank>4)throw Error(`Where for rank ${this.rank} is not yet supported`);if(this.rank===1)t="resRC",e="resRC";else{let s=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[],a=[];for(let o=0;o= 1.0) { setOutputFlat(index, getA(${t})); } else { setOutputFlat(index, getB(${t})); } } } `}};function she(e){let{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t,o=new nhe(s.shape.length,r.shape,r.shape.length);return n.runWebGPUProgram(o,[s,r,a],Bn(r.dtype,a.dtype))}var rhe={kernelName:Ui,backendName:"webgpu",kernelFunc:she},ahe=Nn({opType:bt.SIGMOID}),ohe={kernelName:ho,backendName:"webgpu",kernelFunc:ahe},ihe=Nn({opType:bt.SIN}),lhe={kernelName:po,backendName:"webgpu",kernelFunc:ihe},uhe=Nn({opType:bt.SINH}),che={kernelName:Hi,backendName:"webgpu",kernelFunc:uhe},e6=Xn({opSnippet:Ut.SUB,cpuKernelImpl:tce,supportsComplex:!0}),dhe={kernelName:yo,backendName:"webgpu",kernelFunc:e6};function phe(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{dim:a}=s,o=v.parseAxisParam([a],r.shape),i=ZC({inputs:{x:r},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),l=E.expandShapeToKeepDim(i.shape,o),c=je({inputs:{x:i},backend:n,attrs:{shape:l}}),u=e6({inputs:{a:r,b:c},backend:n}),d=HC({inputs:{x:u},backend:n}),p=zx({inputs:{x:d},backend:n,attrs:{axis:o,keepDims:!1}}),h=je({inputs:{x:p},backend:n,attrs:{shape:l}}),f=QC({inputs:{a:d,b:h},backend:n});return n.disposeData(i.dataId),n.disposeData(c.dataId),n.disposeData(u.dataId),n.disposeData(d.dataId),n.disposeData(p.dataId),n.disposeData(h.dataId),f}var hhe={kernelName:go,backendName:"webgpu",kernelFunc:phe},fhe=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:o}=s;v.assert(r.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGPU backend not implemented yet");let i=a.reduce((A,x)=>A*x),l=[[0,0]];l.push(...o);for(let A=1+a.length;An.disposeData(A.dataId)),g},mhe={kernelName:ji,backendName:"webgpu",kernelFunc:fhe},ghe=class{constructor(e,t,n,s,r,a,o=!0){this.variableNames=["updates","indices","defaultValue"],this.workGroupSize=[64,1,1],this.workPerThread=4,this.size=!0,this.outputShape=a,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]);let i=t>1;this.shaderKey=`scatter_${n}_${s}_${i}`;let l=wn(r.length);this.uniforms=`updateSize : i32; sliceDim : i32; strides: ${l};`;let c="";n===1?c="i":n===2&&(c="i, j"),this.indicesSnippet=`getIndices(${c})`;let u="";s===1?u="i":s===2&&(u="i, coords[1]"),this.updatesSnippet=`getUpdates(${u})`,this.strideString=i?"uniforms.strides[j]":"uniforms.strides"}getUserCode(){return` ${nt()} let globalIndex = index * ${this.workPerThread}; if (globalIndex < uniforms.size) { var sum = vec4(0.0); var found = vec4(false); for (var i = 0; i < uniforms.updateSize; i = i + 1) { var flattenedIndex = 0; for (var j = 0; j < uniforms.sliceDim; j = j + 1) { let indexInside = i32(round(${this.indicesSnippet})); flattenedIndex = flattenedIndex + indexInside * ${this.strideString}; } for (var innerIndex = 0; innerIndex < ${this.workPerThread}; innerIndex = innerIndex + 1) { let curIndex = globalIndex + innerIndex; let coords = getCoordsFromFlatIndex(curIndex); if (flattenedIndex == coords[0]) { sum[innerIndex] = sum[innerIndex] + ${this.updatesSnippet}; found[innerIndex] = true; } } } for (var innerIndex = 0; innerIndex < ${this.workPerThread}; innerIndex = innerIndex + 1) { let curIndex = globalIndex + innerIndex; if (curIndex < uniforms.size) { setOutputFlat(curIndex, mix(getDefaultValue(), sum[innerIndex], f32(found[innerIndex]))); } } } }`}};function Ahe(e){let{inputs:t,backend:n,attrs:s}=e,{sparseIndices:r,sparseValues:a,defaultValue:o}=t,{outputShape:i}=s,{sliceRank:l,numUpdates:c,strides:u,outputSize:d}=E.calculateShapes(a,r,i),p=!1,h=[{type:"int32",data:[c]},{type:"int32",data:[l]},{type:"int32",data:u}],f=new ghe(c,l,r.shape.length,a.shape.length,u,[d,1],p),m=n.runWebGPUProgram(f,[a,r,o],a.dtype,h),g=je({inputs:{x:m},backend:n,attrs:{shape:i}});return n.disposeData(m.dataId),g}var yhe={kernelName:Ad,backendName:"webgpu",kernelFunc:Ahe};function xhe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{numOrSizeSplits:a,axis:o}=s,i=v.parseAxisParam(o,r.shape)[0],l=E.prepareSplitSize(r,a,i),c=r.shape.length,u=new Array(c).fill(0),d=r.shape.slice();return l.map(p=>{let h=[...d];h[i]=p;let f=vc({inputs:{x:r},backend:n,attrs:{begin:u,size:h}});return u[i]+=p,f})}var bhe={kernelName:qi,backendName:"webgpu",kernelFunc:xhe},vhe=Nn({opType:bt.SQRT}),whe={kernelName:fo,backendName:"webgpu",kernelFunc:vhe},khe={kernelName:_u,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,s=t,r=new r0(n.shape,bt.SQUARE);return s.runWebGPUProgram(r,[n],n.dtype)}},She=Xn({opSnippet:Ut.SQUARED_DIFFERENCE}),Ihe={kernelName:Ao,backendName:"webgpu",kernelFunc:She},Che=class{constructor(e){this.variableNames=["x"],this.workPerThread=1,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]);let t=wn(this.outputShape.length);this.uniforms=`begin : ${t}; strides : ${t}; `,this.shaderKey="stridedSlice"}getUserCode(){let e=this.outputShape.length,t="";if(e===1)t="coords * uniforms.strides + uniforms.begin";else{let s=0;t=this.outputShape.map((r,a)=>(s++,this.outputShape.length===1?`coords * uniforms.strides[${a}] + uniforms.begin[${a}]`:`coords[${s-1}] * uniforms.strides[${a}] + uniforms.begin[${a}]`)).join(",")}return` ${nt()} if (index < uniforms.size) { let coords = getCoordsFromFlatIndex(index); setOutputFlat(index, getX(${t})); } } `}};function The(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=s,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:A,begin:x,end:y,strides:b}=Ft.sliceInfo(r.shape,a,o,i,l,c,u,d,p),w;if(m)w=je({inputs:{x:r},backend:n,attrs:{shape:f}});else if(g||A){v.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let k=Ft.computeOutShape(x,y,b),I=vc({inputs:{x:r},backend:n,attrs:{begin:x,size:k}});w=je({inputs:{x:I},backend:n,attrs:{shape:f}}),n.disposeData(I.dataId)}else if(n.shouldExecuteOnCPU([r])){let I=n.readSync(r.dataId),N=ze(r.shape,r.dtype,I),R=Que(h,N,b,x);w=n.makeTensorInfo(f,r.dtype,R.values)}else{let I=new Che(h),N=[{type:"int32",data:x},{type:"int32",data:b}],R=n.runWebGPUProgram(I,[r],r.dtype,N);w=je({inputs:{x:R},backend:n,attrs:{shape:f}}),n.disposeData(R.dataId)}return w}var Nhe={kernelName:Xi,backendName:"webgpu",kernelFunc:The};function Ehe(e){let{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:c}=s,{data:u,dataSplits:d}=t,p=n.readSync(u.dataId),h=n.readSync(d.dataId),[f,m]=ece(p,h,r,a,o,i,l,c);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(d.shape,"int32",m)]}var Rhe={kernelName:yd,backendName:"webgpu",kernelFunc:Ehe},$he=Nn({opType:bt.TANH}),_he={kernelName:xo,backendName:"webgpu",kernelFunc:$he},Dhe=class{constructor(e,t){this.variableNames=["A"],this.workGroupSize=[64,1,1],this.size=!0;let n=new Array(e.length);for(let s=0;s=5)throw Error(`Tile for rank ${e} is not yet supported`);if(e===1)return`(resRC % ${t}aShape)`;let n=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let r=0;r=5){let l=n.readSync(r.dataId),c=r.dtype==="string"?l.map(p=>v.decodeString(p)):l,u=ze(r.shape,r.dtype,c),d=nce(u,a);return n.makeTensorInfo(d.shape,d.dtype,d.values)}let o=new Dhe(r.shape,a);return n.runWebGPUProgram(o,[r],r.dtype)}var Ohe={kernelName:Yr,backendName:"webgpu",kernelFunc:Fhe},Mhe=class{constructor(e){this.variableNames=["x","indices"],this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms=`inputSize : i32; firstPass : i32; negativeInf : f32; dir : i32; inc : i32;`,this.shaderKey="swap"}getUserCode(){return` ${nt()} if (index < uniforms.size) { let outC = getCoordsFromFlatIndex(index); let batch = outC[0]; let elemIdx = outC[1]; // We compare elements pair-wise within a group of size 2 * inc. // The comparing rule for each group alternates between ascending // and descending. Within each group, we compare each pair at // positions i and i+inc. To decide whether an element at position i // is x0 or x1, we mod it by 2 * inc, if the result is smaller than // inc, it is in the first half of the group, we denote it as x0, // otherwise we denote it as x1. // For example, as shown in the Bitonic top K paper referenced // above, Figure5(a) shows that element[1] is in the second half of // the group when group size is 2, but it is in the first half of // the group when group size is 4. let isFirstInPair = elemIdx % (2 * uniforms.inc) < uniforms.inc; var i = 0; if (isFirstInPair) { i = elemIdx; } else { i = elemIdx - uniforms.inc; } var i0 = 0; if (uniforms.firstPass == 1) { i0 = i; } else { i0 = i32(getIndices(batch, i)); } var i1 = 0; if (uniforms.firstPass == 1) { i1 = i + uniforms.inc; } else { i1 = i32(getIndices(batch, i + uniforms.inc)); } var x0 = f32(0.0); var x1 = f32(0.0); if (i0 < uniforms.inputSize) { x0 = getX(batch, i0); } else { x0 = uniforms.negativeInf; } if (i1 < uniforms.inputSize) { x1 = getX(batch, i1); } else { x1 = uniforms.negativeInf; } let reverse = elemIdx % (2 * uniforms.dir) >= uniforms.dir; let isGreater = x0 > x1 || (x0 == x1 && i1 > i0); if (reverse == isGreater) { // Elements in opposite order of direction let iTemp = i0; i0 = i1; i1 = iTemp; } if (isFirstInPair) { setOutputFlat(index, f32(i0)); } else { setOutputFlat(index, f32(i1)); } } } `}},zhe=class{constructor(e){this.variableNames=["x","indices"],this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms="inputSize : i32; firstPass : i32; k : i32;",this.shaderKey="merge"}getUserCode(){return` ${nt()} if (index < uniforms.size) { let outC = getCoordsFromFlatIndex(index); let batch = outC[0]; let elemIdx = outC[1]; // The output size is half of the previous size. // If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ // (k=4), we only need to output the indices at positions |, the // indices at positions _ can be thrown away, see Figure5(b) After // Phase 2 (Merge phase) in the Bitonic Top K paper referenced // above. // For example, the paper shows we only need to output the orange // bars. The output sequence should look like this | | | | | | | |. // Because the sequence is halved, to map the output index back to // the previous sequence to find the corresponding value, we need // to double the index. When we double the index, we basically // interpolate a position, so 2i looks like // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k // position of each 2k positions by - elemIdx % k. E.g. for output // at index 4,5,6,7, we want to get the corresponding element at // original index 8,9,10,11, for output at index 8,9,10,11, // we want to get the corresponding element at original index // 16,17,18,19, so on and so forth. var i = 0; if (elemIdx < uniforms.k) { i = elemIdx; } else { i = elemIdx * 2 - elemIdx % uniforms.k; } var i0 = 0; if (uniforms.firstPass == 1) { i0 = i; } else { i0 = i32(getIndices(batch, i)); } var i1 = 0; if (uniforms.firstPass == 1) { i1 = i + uniforms.k; } else { i1 = i32(getIndices(batch, i + uniforms.k)); } let x0 = getX(batch, i0); var x1 = f32(0.0); if (i1 < uniforms.inputSize) { x1 = getX(batch, i1); } else { x1 = x0; } if (x0 >= x1) { setOutputFlat(index, f32(i0)); } else { setOutputFlat(index, f32(i1)); } } } `}};function Sc(e,t){t!==null&&e.disposeData(t.dataId)}function t6(e){let t=1;for(;tf===null?[d,d]:[d,f],g=(w,k,I)=>{let N=m(),R=new Mhe(I),$=[{type:"int32",data:[l]},{type:"int32",data:[f===null?1:0]},{type:"float32",data:[Number.NEGATIVE_INFINITY]},{type:"int32",data:[w]},{type:"int32",data:[k]}],P=f;f=n.runWebGPUProgram(R,N,"int32",$),Sc(n,P)};for(let w=1;w=1;I/=2)g(k,I,[u,h])}for(let w=h;w>p;w/=2){let k=m(),I=new zhe([u,w/2]),R=[{type:"int32",data:[l]},{type:"int32",data:[f===null?1:0]},{type:"int32",data:[p]}],O=f;f=n.runWebGPUProgram(I,k,"int32",R),Sc(n,O);let $=p/2,P=$*2;for(let T=$;T>=1;T/=2)g(P,T,f.shape)}let A=f;f=vc({inputs:{x:f},backend:n,attrs:{begin:0,size:[u,a]}}),Sc(n,A);let x=KC({inputs:{x:d,indices:f},backend:n,attrs:{axis:1,batchDims:1}});Sc(n,d);let y=i.slice(0,-1);y.push(a),A=f,f=je({inputs:{x:f},attrs:{shape:y},backend:n}),Sc(n,A);let b=x;return x=je({inputs:{x},attrs:{shape:y},backend:n}),Sc(n,b),[x,f]}var Bhe={kernelName:Zi,backendName:"webgpu",kernelFunc:Lhe},Whe=class{constructor(e){this.variableNames=["Image","Transforms"],this.uniforms="interpolationModeId : i32; fillModeId : i32; fillValue : f32;",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="transform"}getUserCode(){return` fn mapCoord(outCoord : f32, len : f32) -> f32{ var inCoord = outCoord; if(uniforms.fillModeId == 2) { if (inCoord < 0.0) { if (len <= 1.0) { inCoord = 0.0; } else { let sz2 = 2.0 * len; if (inCoord < sz2) { inCoord = sz2 * f32(i32(f32(-inCoord / sz2))) + inCoord; } if (inCoord < -len) { inCoord = inCoord + sz2; } else { inCoord = -inCoord - 1.0; } } } elseif (inCoord > len - 1.0) { if (len <= 1.0) { inCoord = 0.0; } else { let sz2 = 2.0 * len; inCoord = inCoord - sz2 * f32(i32(f32(inCoord / sz2))); if (inCoord >= len) { inCoord = sz2 - inCoord - 1.0; } } } return clamp(inCoord, 0.0, len - 1.0); } elseif (uniforms.fillModeId == 3) { if (inCoord < 0.0) { if (len <= 1.0) { inCoord = 0.0; } else { let sz = len - 1.0; inCoord = inCoord + len * (f32(i32(f32(-inCoord / sz))) + 1.0); } } elseif (inCoord > len - 1.0) { if (len <= 1.0) { inCoord = 0.0; } else { let sz = len - 1.0; inCoord = inCoord - len * f32(i32(f32(inCoord / sz))); } } return clamp(inCoord, 0.0, len - 1.0); } elseif (uniforms.fillModeId == 4) { return clamp(outCoord, 0.0, len - 1.0); } return outCoord; } fn readWithFillValue(batch : i32, coordY : i32, coordX : i32, channel : i32) -> f32 { var outputValue : f32; if (0 <= coordY && coordY < uniforms.imageShape[1] && 0 <= coordX && coordX < uniforms.imageShape[2]) { outputValue = getImage(batch, coordY, coordX, channel); } else { outputValue = uniforms.fillValue; } return outputValue; } ${nt()} if (index < uniforms.size) { let coords = getCoordsFromFlatIndex(index); var outputValue : f32; let batch = coords[0]; let x = coords[2]; let y = coords[1]; let channel = coords[3]; let xf = f32(x); let yf = f32(y); let a1 = getTransforms(batch, 0); let a2 = getTransforms(batch, 1); let a3 = getTransforms(batch, 2); let b1 = getTransforms(batch, 3); let b2 = getTransforms(batch, 4); let b3 = getTransforms(batch, 5); let c1 = getTransforms(batch, 6); let c2 = getTransforms(batch, 7); let projection = c1 * xf + c2 * yf + 1.0; if (projection == 0.0) { outputValue = uniforms.fillValue; } else { let inX = (a1 * xf + a2 * yf + a3) / projection; let inY = (b1 * xf + b2 * yf + b3) / projection; let mapX = mapCoord(inX, f32(uniforms.imageShape[2])); let mapY = mapCoord(inY, f32(uniforms.imageShape[1])); if (uniforms.interpolationModeId == 1) { let coordY = i32(round(mapY)); let coordX = i32(round(mapX)); outputValue = readWithFillValue(batch, coordY, coordX, channel); } else { let yFloor = floor(mapY); let xFloor = floor(mapX); let yCeil = yFloor + 1.0; let xCeil = xFloor + 1.0; let valueYFloor = (xCeil - mapX) * readWithFillValue(batch, i32(yFloor), i32(xFloor), channel) + (mapX - xFloor) * readWithFillValue(batch, i32(yFloor), i32(xCeil), channel); let valueYCeil = (xCeil - mapX) * readWithFillValue(batch, i32(yCeil), i32(xFloor), channel) + (mapX - xFloor) * readWithFillValue(batch, i32(yCeil), i32(xCeil), channel); outputValue = (yCeil - mapY) * valueYFloor + (mapY - yFloor) * valueYCeil; } } setOutputFlat(index, outputValue); } } `}};function Vhe(e){let{inputs:t,backend:n,attrs:s}=e,{image:r,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:l,outputShape:c}=s,[u,d,p,h]=r.shape,[f,m]=c!=null?c:[d,p],g=[u,f,m,h],A=new Whe(g),x=o==="nearest"?1:2,y;switch(i){case"constant":y=1;break;case"reflect":y=2;break;case"wrap":y=3;break;case"nearest":y=4;break;default:y=1;break}let b=[{type:"int32",data:[x]},{type:"int32",data:[y]},{type:"float32",data:[l]}];return n.runWebGPUProgram(A,[r,a],"float32",b)}var Uhe={kernelName:Yi,backendName:"webgpu",kernelFunc:Vhe};function Ghe(e){let{inputs:t,backend:n,attrs:s}=e,{value:r}=t,{axis:a}=s;a<0&&(a+=r.shape.length);let o=r,i=o.shape.length,l=r.shape[a],c=new Array(i-1),u=0;for(let m=0;mn.disposeData(m.dataId)),f}var Hhe={kernelName:Ji,backendName:"webgpu",kernelFunc:Ghe},jhe=[kue,oce,lce,dce,Ace,xce,vce,kce,Nce,_ce,Pce,zce,Tue,Vce,jce,Zce,Jce,ede,sde,ode,lde,hde,mde,Ade,xde,yde,vde,kde,Ide,$de,Tde,Ede,Pde,Ode,zde,Wde,Gde,jde,Xde,Cue,Bce,Zde,Jde,epe,npe,rpe,ape,ipe,upe,dpe,hpe,mpe,Ape,ude,xpe,vpe,kpe,Ece,Ipe,Tpe,Epe,Dpe,Fpe,$pe,Mpe,Rce,zpe,Bpe,Vpe,vue,Hpe,Xpe,Zpe,Jpe,the,rhe,ohe,lhe,che,Cce,Nhe,Rhe,hhe,mhe,bhe,yhe,whe,khe,Ihe,dhe,dde,_he,Ohe,Bhe,Uhe,mce,Hhe,Spe];for(let e of jhe)cr(e);var qhe=class{constructor(e){this.device=e,this.numUsedBuffers=0,this.numFreeBuffers=0,this.freeBuffers=new Map,this.usedBuffers=new Map,this.numBytesUsed=0,this.numBytesAllocated=0}acquireBuffer(e,t){let n=n6(e,t);if(this.freeBuffers.has(n)||this.freeBuffers.set(n,[]),this.usedBuffers.has(n)||this.usedBuffers.set(n,[]),this.numBytesUsed+=e,this.numUsedBuffers++,this.freeBuffers.get(n).length>0){this.numFreeBuffers--;let r=this.freeBuffers.get(n).shift();return this.usedBuffers.get(n).push(r),r}this.numBytesAllocated+=e;let s=this.device.createBuffer({size:e,usage:t});return this.usedBuffers.get(n).push(s),s}releaseBuffer(e,t,n){if(this.freeBuffers==null)return;let s=n6(t,n);this.freeBuffers.has(s)||this.freeBuffers.set(s,[]),this.freeBuffers.get(s).push(e),this.numFreeBuffers++,this.numUsedBuffers--;let r=this.usedBuffers.get(s),a=r.indexOf(e);if(a<0)throw new Error("Cannot release a buffer that was never provided by this buffer manager");r.splice(a,1),this.numBytesUsed-=t}getNumUsedBuffers(){return this.numUsedBuffers}getNumFreeBuffers(){return this.numFreeBuffers}reset(){this.freeBuffers=new Map,this.usedBuffers=new Map,this.numUsedBuffers=0,this.numFreeBuffers=0,this.numBytesUsed=0,this.numBytesAllocated=0}dispose(){this.freeBuffers==null&&this.usedBuffers==null||(this.freeBuffers.forEach((e,t)=>{e.forEach(n=>{n.destroy()})}),this.usedBuffers.forEach((e,t)=>{e.forEach(n=>{n.destroy()})}),this.freeBuffers=null,this.usedBuffers=null,this.numUsedBuffers=0,this.numFreeBuffers=0,this.numBytesUsed=0,this.numBytesAllocated=0)}};function n6(e,t){return`${e}_${t}`}var s6=class{constructor(){this.outputShape=[0],this.variableNames=[],this.workGroupSize=[256,1,1],this.lastUniformData=[],this.inputTexture=null,this.layout=null,this.lastPixelSize={width:0,height:0},this.disposed=!1,this.shaderKey="fromPixels",this.useImport=!1}updateOutputShape(e){v.arraysEqual(this.outputShape,e)||(this.outputShape=e,this.workPerThread=e[2],this.dispatchLayout=Xe(this.outputShape),this.dispatch=Fe(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]))}makeFromPixelsSource(){let e=this.useImport?"textureLoad(src, vec2(coords.yx));":"textureLoad(src, vec2(coords.yx), 0)";return` [[binding(1), group(0)]] var src: ${this.useImport?"texture_external":"texture_2d"}; ${nt()} let flatIndexBase = index * uniforms.numChannels; for (var i = 0; i < uniforms.numChannels; i = i + 1) { let flatIndex = flatIndexBase + i; if (flatIndex < uniforms.size) { let coords = getCoordsFromFlatIndex(flatIndexBase); let values = ${e}; result.numbers[flatIndex] = i32(floor(255.0 * values[i])); } } } `}getUserCode(){return this.makeFromPixelsSource()}setPipeline(e){this.pipeline=e}setUniform(e,t){if(!this.uniform){let n=e.createBuffer({size:t.length*4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.uniform=n}!t||t.length===this.lastUniformData.length&&t.every((n,s)=>n===this.lastUniformData[s])||(e.queue.writeBuffer(this.uniform,0,new Uint32Array(t)),this.lastUniformData=t)}makeInputTexture(e,t,n){return(!this.inputTexture||this.lastPixelSize.width!==t||this.lastPixelSize.height!==n)&&(this.inputTexture&&this.inputTexture.destroy(),this.inputTexture=e.createTexture({size:[t,n],format:"rgba8unorm",usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),this.lastPixelSize.width=t,this.lastPixelSize.height=n),this.inputTexture}dispose(){this.disposed||(this.uniform&&this.uniform.destroy(),this.inputTexture&&this.inputTexture.destroy(),this.disposed=!0)}getLayout(e){return this.layout===null&&(this.layout=this.createTextureLayout(e)),this.layout}createTextureLayout(e){let t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}),t.push({binding:1,visibility:GPUShaderStage.COMPUTE,texture:{}}),t.push({binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{}});let n=e.createBindGroupLayout({entries:t}),s=e.createPipelineLayout({bindGroupLayouts:[n]});return{bindGroupLayout:n,pipelineLayout:s}}},Xhe=class extends s6{constructor(){super(...arguments);this.layout=null,this.useImport=!0}getUserCode(){return this.makeFromPixelsSource()}getLayout(e){return this.layout===null&&(this.layout=this.createTextureImportLayout(e)),this.layout}createTextureImportLayout(e){let t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}),t.push({binding:1,visibility:GPUShaderStage.COMPUTE,externalTexture:{}}),t.push({binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{}});let n=e.createBindGroupLayout({entries:t}),s=e.createPipelineLayout({bindGroupLayouts:[n]});return{bindGroupLayout:n,pipelineLayout:s}}},Khe=Y().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD"),r6=class extends ru{constructor(e,t=!1){super();if(this.commandQueueOwnedIds=new WeakSet,this.tensorDisposalQueue=[],this.uniformDisposalQueue=[],this.disposed=!1,this.uploadWaitMs=0,this.downloadWaitMs=0,this.dispatchNumberInEncoder=0,!_x())throw new Error("WebGPU is not supported on this device");this.layoutCache={},this.pipelineCache={},this.device=e,this.queue=e.queue,this.currentCommandEncoder=null,this.currentComputePass=null,this.supportTimeQuery=t,this.bufferManager=new qhe(this.device),this.tensorMap=new sd(this,as()),this.supportTimeQuery&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:2})),Y().getBool("WEBGPU_USE_PROFILE_TOOL")&&(this.dummyCanvas=document.createElement("canvas"),this.dummyCanvas.width=1,this.dummyCanvas.height=1,this.dummyContext=this.dummyCanvas.getContext("webgpu"),this.dummyContext.configure({device:e,format:"bgra8unorm"}),document.body.appendChild(this.dummyCanvas))}nextDataId(){return r6.nextDataId++}floatPrecision(){return 32}defaultGpuBufferUsage(){return GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}flushDisposalQueue(){this.tensorDisposalQueue.forEach(e=>{this.maybeReleaseBuffer(e),this.tensorMap.delete(e)}),this.uniformDisposalQueue.forEach(e=>this.bufferManager.releaseBuffer(e.buffer,e.byteSize,e.usage)),this.tensorDisposalQueue=[],this.uniformDisposalQueue=[]}disposeData(e,t=!1){if(this.tensorMap.has(e)){let n=this.tensorMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;if(this.commandQueueOwnedIds.has(e))return this.tensorDisposalQueue.push(e),!1;this.maybeReleaseBuffer(e);let{complexTensorInfos:s}=this.tensorMap.get(e);s!=null&&(this.disposeData(s.real.dataId,!0),this.disposeData(s.imag.dataId,!0)),this.tensorMap.delete(e)}return!0}memory(){return{numBytesInGPU:this.bufferManager.numBytesUsed,numBytesAllocatedInGPU:this.bufferManager.numBytesAllocated,unreliable:!1}}getBufferManager(){return this.bufferManager}acquireBuffer(e,t=this.defaultGpuBufferUsage()){return this.bufferManager.acquireBuffer(e,t)}maybeReleaseBuffer(e){let t=this.tensorMap.get(e);t!=null&&t.bufferInfo.buffer!=null&&(this.bufferManager.releaseBuffer(t.bufferInfo.buffer,t.bufferInfo.byteSize,t.bufferInfo.usage),t.bufferInfo.buffer=null)}refCount(e){return this.tensorMap.has(e)?this.tensorMap.get(e).refCount:0}incRef(e){let t=this.tensorMap.get(e);t.refCount++}decRef(e){if(this.tensorMap.has(e)){let t=this.tensorMap.get(e);t.refCount--}}write(e,t,n){if(n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let s={id:this.nextDataId()},r=v.sizeFromShape(t)*$x(n);return n==="bool"&&e instanceof Uint8Array&&(e=Int32Array.from(e)),this.tensorMap.set(s,{dtype:n,values:e,bufferInfo:{byteSize:r,usage:this.defaultGpuBufferUsage()},refCount:1}),s}move(e,t,n,s,r){if(s==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let a=v.sizeFromShape(n)*$x(s);this.tensorMap.set(e,{dtype:s,values:t,bufferInfo:{byteSize:a,usage:this.defaultGpuBufferUsage()},refCount:r})}submitQueue(){this.ensureComputePassEnded(),this.queue.submit([this.currentCommandEncoder.finish()]),this.currentCommandEncoder=null,this.dispatchNumberInEncoder=0,this.commandQueueOwnedIds=new WeakSet,this.flushDisposalQueue()}getBuffer(e){return this.uploadToGPU(e),this.tensorMap.get(e).bufferInfo.buffer}getFromPixelsProgram(e){switch(e){case"copyExternal":return this.fromPixelProgram||(this.fromPixelProgram=new s6),this.fromPixelProgram;case"import":return this.fromPixelImportProgram||(this.fromPixelImportProgram=new Xhe),this.fromPixelImportProgram;default:v.assert(!1,()=>"Unsupported fromPixels shape");return}}ensureCommandEncoderReady(){this.currentCommandEncoder||(this.currentCommandEncoder=this.device.createCommandEncoder())}ensureComputePassEnded(){this.currentComputePass&&(this.currentComputePass.endPass(),this.currentComputePass=null)}getComputePass(){return this.currentComputePass||(this.currentComputePass=this.currentCommandEncoder.beginComputePass()),this.currentComputePass}async getBufferData(e){if(e.values!=null)return e.values;let t=this.acquireBuffer(e.bufferInfo.byteSize,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(e.bufferInfo.buffer,0,t,0,e.bufferInfo.byteSize),this.submitQueue(),await t.mapAsync(GPUMapMode.READ);let n=t.getMappedRange().slice(0);return t.unmap(),t!=null&&this.bufferManager.releaseBuffer(t,e.bufferInfo.byteSize,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ),Y().getBool("WEBGPU_USE_PROFILE_TOOL")&&(v.assert(this.dummyContext!==void 0,()=>"Fail to get context for profiling tool"),this.dummyContext.getCurrentTexture()),n}convertAndCacheOnCPU(e,t){let n=this.tensorMap.get(e);return this.maybeReleaseBuffer(e),n.values=t,n.values}readSync(e){let t=this.tensorMap.get(e),{values:n}=t;if(n==null)throw new Error("WebGPU readSync is only available for CPU-resident tensors.");return n}async read(e){if(!this.tensorMap.has(e))throw new Error(`Tensor ${e} was not registered!`);let t=this.tensorMap.get(e),{values:n}=t;if(n!=null)return this.convertAndCacheOnCPU(e,n);let s;if(t.dtype==="complex64"){let r=await Promise.all([this.read(t.complexTensorInfos.real.dataId),this.read(t.complexTensorInfos.imag.dataId)]),a=r[0],o=r[1];s=E.mergeRealAndImagArrays(a,o)}else{let r=await this.getBufferData(t);s=IC(r,t.dtype)}return this.convertAndCacheOnCPU(e,s),s}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(s=>v.decodeString(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return ze(e.shape,e.dtype,n)}async time(e){let t=this.activeTimers,n=[],s=!1;this.programTimersStack==null?(this.programTimersStack=n,s=!0):this.activeTimers.push(n),this.activeTimers=n,e();let r=v.flatten(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),a=v.flatten(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=t,s&&(this.programTimersStack=null);let o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},i=await Promise.all(r);return o.kernelMs=v.sum(i),o.getExtraProfileInfo=()=>i.map((l,c)=>({name:a[c],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", "),this.uploadWaitMs=0,this.downloadWaitMs=0,o}getAndSavePipeline(e,t){return e in this.pipelineCache||(this.pipelineCache[e]=t()),this.pipelineCache[e]}makeTensorInfo(e,t,n){let s;if(t==="string"&&n!=null&&n.length>0&&v.isString(n[0])){let r=n.map(a=>v.encodeString(a));s=this.write(r,e,t)}else s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}tensorToBinding(e){if(!e)return null;let t=this.tensorMap.get(e.dataId);return{offset:0,size:t.bufferInfo.byteSize,buffer:t.bufferInfo.buffer}}async getQueryTime(e){return this.supportTimeQuery?this.getTimeFromQuerySet(e):0}uploadToGPU(e){let t=this.tensorMap.get(e);t.bufferInfo.buffer==null&&(t.bufferInfo.buffer=this.acquireBuffer(t.bufferInfo.byteSize),t.values&&this.queue.writeBuffer(t.bufferInfo.buffer,0,t.values))}makeUniformsDataView(e){let t=this.acquireBuffer(e.byteLength,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);return this.queue.writeBuffer(t,0,e),{offset:0,size:e.byteLength,buffer:t}}arrayToDataView(e,t){let n=4,s=new DataView(new ArrayBuffer(t*n)),r=0;return e.forEach(a=>{let o=a.data;if(a.type!=="int32"&&a.type!=="float32"&&a.type!=="uint32")throw new Error(`${a.type} not supported!`);a.type==="int32"?o.forEach(i=>{s.setInt32(r*n,i,!0),r++}):a.type==="uint32"?o.forEach(i=>{s.setUint32(r*n,i,!0),r++}):o.forEach(i=>{s.setFloat32(r*n,i,!0),r++})}),s}computePadding(e){let t=0,n=0,s=0,r=[];return e.forEach((a,o)=>{a.data.length===0&&(a.data=[1]);let i;switch(a.data.length){case 0:i=1;break;case 1:i=1;break;case 2:i=2;break;case 3:i=4;break;case 4:i=4;break;default:v.assert(!1,()=>`Unsupported ${a.data.length}D shape`)}n=Math.ceil(t/i)*i-t;for(let l=0;lN.shape),i="int32";o.map(N=>{a.push({type:i,data:N})});let l=v.computeStrides(r.shape);if(a.push({type:i,data:l}),e.size){let N=v.sizeFromShape(e.outputShape);a.push({type:i,data:[e.isVec4?N/4:N]})}s&&(a=[...a,...s]);let c=null,u=this.computePadding(a),d=u.byteLength;c=this.makeUniformsDataView(u);let p=t.map((N,R)=>{if(N.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");return this.uploadToGPU(N.dataId),{dtype:this.tensorMap.get(N.dataId).dtype,shape:N.shape,name:e.variableNames[R]}}),h=p.map(N=>N.dtype).concat(r.dtype),f=p.map(N=>E.getBroadcastDims(N.shape,r.shape)),m=p.map(N=>v.arraysEqual(N.shape,r.shape)).join("_"),g=f.map(N=>N.join("_")).join(";"),A=qC(e,o,h,g,m),{bindGroupLayout:x,pipelineLayout:y}=this.getCachedOrCreateLayout(e.variableNames.length),b=this.getAndSavePipeline(A,()=>jC(this.device,e,y,p,r)),w=this.activeTimers!=null,k=Rde(this.device,x,t.map(N=>this.tensorToBinding(N)),this.tensorToBinding(r),c);this.ensureCommandEncoderReady();let I=this.getComputePass();if(w&&this.supportTimeQuery&&I.writeTimestamp(this.querySet,0),I.setPipeline(b),I.setBindGroup(0,k),I.dispatch(e.dispatch[0],e.dispatch[1],e.dispatch[2]),w&&this.supportTimeQuery&&I.writeTimestamp(this.querySet,1),this.dispatchNumberInEncoder++,t.forEach(N=>{this.commandQueueOwnedIds.add(N.dataId)}),this.commandQueueOwnedIds.add(r.dataId),c){let N={byteSize:d,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM,buffer:c.buffer};this.uniformDisposalQueue.push(N)}return Y().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE")<=this.dispatchNumberInEncoder&&this.submitQueue(),w&&this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(this.querySet)}),r}runFromPixelsProgram(e,t,n,s,r){let a=this.device.createBindGroup({layout:n.bindGroupLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:s},{binding:2,resource:{buffer:e.uniform}}]});this.ensureCommandEncoderReady();let o=this.getComputePass(),i=this.activeTimers!=null;i&&this.supportTimeQuery&&o.writeTimestamp(this.querySet,0),o.setPipeline(e.pipeline),o.setBindGroup(0,a),o.dispatch(e.dispatch[0],e.dispatch[1],e.dispatch[2]),i&&this.supportTimeQuery&&o.writeTimestamp(this.querySet,1),this.commandQueueOwnedIds.add(r),this.submitQueue(),i&&this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(this.querySet)})}async getTimeFromQuerySet(e){let t=this.acquireBuffer(16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),n=this.acquireBuffer(16,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.resolveQuerySet(e,0,2,t,0),this.currentCommandEncoder.copyBufferToBuffer(t,0,n,0,16),this.submitQueue(),await n.mapAsync(GPUMapMode.READ);let s=new BigUint64Array(n.getMappedRange()),r=Number(s[1]-s[0]);return n.unmap(),this.bufferManager.releaseBuffer(n,16,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST),this.bufferManager.releaseBuffer(t,16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),r/1e6}shouldExecuteOnCPU(e,t=Khe){return Y().getBool("WEBGPU_CPU_FORWARD")&&e.every(n=>this.tensorMap.get(n.dataId).bufferInfo.buffer==null&&v.sizeFromShape(n.shape)Bx,webgpu_util:()=>SC});Fu.isBrowser()&&_x()&&ul("webgpu",async()=>{Y().set("CHECK_COMPUTATION_FOR_ERRORS",!1);let e={powerPreference:Y().get("WEBGPU_USE_LOW_POWER_GPU")?"low-power":"high-performance"},t=await navigator.gpu.requestAdapter(e),n={},s=t.features.has("timestamp-query");s?n={requiredFeatures:["timestamp-query"]}:console.warn("This device doesn't support timestamp-query extension. Start Chrome browser with flag --disable-dawn-features=disallow_unsafe_apis then try again. Or zero will shown for the kernel time when profiling mode isenabled. Using performance.now is not workable for webgpu sinceit doesn't support synchronously to read data from GPU.");let r=await t.requestDevice(n);return new Bx(r,s)},3);var Jt;(function(e){e[e.float32=0]="float32",e[e.int32=1]="int32",e[e.bool=2]="bool",e[e.string=3]="string",e[e.complex64=4]="complex64"})(Jt||(Jt={}));var Np;(function(e){e[e.linear=0]="linear",e[e.relu=1]="relu",e[e.relu6=2]="relu6",e[e.prelu=3]="prelu",e[e.leakyrelu=4]="leakyrelu",e[e.sigmoid=5]="sigmoid",e[e.elu=6]="elu"})(Np||(Np={}));var o6;function Zhe(e){o6=e.wasm.cwrap(wo,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function Yhe(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:o,preluActivationWeights:i}=t;if(r.dtype!=="float32"||a.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:d}=s,p=n.dataIdMap.get(r.dataId).id,h=n.dataIdMap.get(a.dataId).id,f=0;if(o!=null){let N=n.dataIdMap.get(o.dataId);if(N.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${N.shape.length}.`);f=N.id}let m=i==null?0:n.dataIdMap.get(i.dataId).id,g=Np[u];if(g==null)throw new Error(`${u} activation not yet supported for FusedConv2D in the wasm backend.`);let A=l?r.shape[2]:r.shape[1],x=c?a.shape[1]:a.shape[2],y=ol.assertAndGetBroadcastShape(r.shape.slice(0,-2),a.shape.slice(0,-2)),b=n.makeOutput([...y,A,x],r.dtype),w=n.dataIdMap.get(b.dataId).id,k=new Uint8Array(new Int32Array(r.shape).buffer),I=new Uint8Array(new Int32Array(a.shape).buffer);return o6(p,k,r.shape.length,h,I,a.shape.length,l,c,g,f,m,d||0,w),b}var Jhe={kernelName:wo,backendName:"wasm",setupFunc:Zhe,kernelFunc:Yhe};function En(e,t){let n;function s(a){n=a.wasm.cwrap(e,null,["number","number","number"])}function r(a){let{backend:o,inputs:{x:i}}=a,l=o.dataIdMap.get(i.dataId).id,c=o.makeOutput(i.shape,t||i.dtype),u=o.dataIdMap.get(c.dataId).id;return v.sizeFromShape(c.shape)===0||n(l,Jt[i.dtype],u),c}return{kernelName:e,backendName:"wasm",setupFunc:s,kernelFunc:r}}var Qhe=En(fi);function Kn(e,t,n){let s;function r(o){s=o.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function a(o){let{backend:i,inputs:l}=o,{a:c,b:u}=l,d=i.dataIdMap.get(c.dataId).id,p=i.dataIdMap.get(u.dataId).id,h=n!=null?n:c.dtype,f=E.assertAndGetBroadcastShape(c.shape,u.shape),m=i.makeOutput(f,h);if(v.sizeFromShape(f)===0)return m;let g=new Uint8Array(new Int32Array(c.shape).buffer),A=new Uint8Array(new Int32Array(u.shape).buffer),x=i.dataIdMap.get(m.dataId).id,y=()=>s(d,g,c.shape.length,p,A,u.shape.length,Jt[c.dtype],x);if(t&&c.dtype==="float32")return y(),m;let b=E.getBroadcastDims(c.shape,f),w=E.getBroadcastDims(u.shape,f),k=b.every((N,R)=>N===R),I=w.every((N,R)=>N===R);if(k&&I)return y(),m;throw new Error(`Broadcasting along outer dims is not yet supported for ${c.dtype} ${e}.`)}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:a}}var efe=!0,tfe=Kn(Kr,efe),i6;function nfe(e){i6=e.wasm.cwrap(Ra,null,["array","number","number","number"])}function sfe(e){let{inputs:t,backend:n}=e,s=n.makeOutput(t[0].shape,t[0].dtype);if(v.sizeFromShape(s.shape)===0)return s;let r=t.map(i=>n.dataIdMap.get(i.dataId).id),a=new Uint8Array(new Int32Array(r).buffer),o=n.dataIdMap.get(s.dataId).id;return i6(a,r.length,Jt[s.dtype],o),s}var rfe={kernelName:Ra,backendName:"wasm",setupFunc:nfe,kernelFunc:sfe};function i0(e){let{inputs:{x:t},backend:n}=e,s=n.makeOutput(t.shape,t.dtype),r=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(s).set(r),s}var afe={kernelName:Xa,backendName:"wasm",kernelFunc:i0},l6;function ofe(e){l6=e.wasm.cwrap(bo,null,["number","array","number","number","number","array","number"])}function Ic(e){let{inputs:t,backend:n,attrs:s}=e,[r,a]=lfe(t.x.shape,s.perm),o=!0;for(let f=0;f=r&&(a===-1||s[a]>s[o])&&(a=o);s[a]=r}return[n,s]}var ufe={kernelName:bo,backendName:"wasm",kernelFunc:Ic,setupFunc:ofe};function Ko(e,t,n){let s=e.shape,r=e.shape.length,a=v.parseAxisParam(t,s),o=a,i=E.getAxesPermutation(o,r),l=null,c=!1;if(i!=null){let u=new Array(r);for(let h=0;h`new shape: ${o}, old shape: ${s.shape}. New shape and old shape must have the same number of elements.`),e.backend.incRef(s.dataId),{dataId:s.dataId,shape:o,dtype:s.dtype}}var wfe={kernelName:Li,backendName:"wasm",kernelFunc:cs},h6;function kfe(e){h6=e.wasm.cwrap(Da,null,["number","array","number","number","array","number","number","number","number"])}function Sfe(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:o,transposeB:i}=s;if(r.dtype!=="float32"||a.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let l=r.shape.length,c=a.shape.length,u=o?r.shape[l-2]:r.shape[l-1],d=i?a.shape[c-1]:a.shape[c-2],p=o?r.shape[l-1]:r.shape[l-2],h=i?a.shape[c-2]:a.shape[c-1],f=r.shape.slice(0,-2),m=a.shape.slice(0,-2),g=v.sizeFromShape(f),A=v.sizeFromShape(m),y=ol.assertAndGetBroadcastShape(r.shape.slice(0,-2),a.shape.slice(0,-2)).concat([p,h]);v.assert(u===d,()=>`Error in matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${r.shape} and ${a.shape} and transposeA=${o} and transposeB=${i} must match.`);let b=o?[g,u,p]:[g,p,u],w=i?[A,h,d]:[A,d,h],k=cs({inputs:{x:r},backend:n,attrs:{shape:b}}),I=cs({inputs:{x:a},backend:n,attrs:{shape:w}}),N=n.dataIdMap.get(k.dataId).id,R=n.dataIdMap.get(I.dataId).id,O=o?k.shape[2]:k.shape[1],$=i?I.shape[1]:I.shape[2],P=Math.max(g,A),T=n.makeOutput([P,O,$],k.dtype),F=n.dataIdMap.get(T.dataId).id,U=new Uint8Array(new Int32Array(k.shape).buffer),q=new Uint8Array(new Int32Array(I.shape).buffer);return h6(N,U,k.shape.length,R,q,I.shape.length,o,i,F),n.disposeData(k.dataId),n.disposeData(I.dataId),T.shape=y,T}var Ife={kernelName:Da,backendName:"wasm",setupFunc:kfe,kernelFunc:Sfe};function Ep(e){let{inputs:{x:t},attrs:{begin:n,size:s},backend:r}=e,[a,o]=Ft.parseSliceParams(t,n,s),i=Ft.isSliceContinous(t.shape,a,o),l=r.readSync(t.dataId),c=r.makeOutput(o,t.dtype),u=v.computeStrides(t.shape),d=r.dataIdMap.get(c.dataId);if(i){let f=Ft.computeFlatOffset(a,u);return t.dtype==="string"?d.stringBytes=l.slice(f,f+v.sizeFromShape(o)):r.typedArrayFromHeap(c).set(l.subarray(f,f+v.sizeFromShape(o))),c}if(t.dtype==="string"){let f=_m(l,a,o,t.shape,t.dtype);return d.stringBytes=f,c}let p=r.typedArrayFromHeap(c),h=t.shape.length;if(h===2)Cfe(l,u[0],p,a,o);else if(h===3)Tfe(l,u[0],u[1],p,a,o);else if(h===4)Nfe(l,u[0],u[1],u[2],p,a,o);else{let f=_m(l,a,o,t.shape,t.dtype);p.set(f)}return c}function Cfe(e,t,n,s,r){let a=0,o=s[0],i=s[1],l=o+r[0];for(let c=o;cA*x),l=E.getReshaped(r.shape,a,i),c=E.getPermuted(l.length,a.length),u=E.getReshapedPermuted(r.shape,a,i),d=E.getSliceBeginCoords(o,a.length),p=E.getSliceSize(u,o,a.length),h=cs({inputs:{x:r},backend:n,attrs:{shape:l}}),f=Ic({inputs:{x:h},backend:n,attrs:{perm:c}}),m=cs({inputs:{x:f},backend:n,attrs:{shape:u}}),g=Ep({inputs:{x:m},backend:n,attrs:{begin:d,size:p}});return n.disposeData(h.dataId),n.disposeData(f.dataId),n.disposeData(h.dataId),g}var $fe={kernelName:mi,backendName:"wasm",kernelFunc:Rfe};function Rp(e){let{inputs:{x:t},attrs:{dtype:n},backend:s}=e,r=s.makeOutput(t.shape,n),a=s.typedArrayFromHeap(t);return s.typedArrayFromHeap(r).set(a),r}var _fe={kernelName:Pa,backendName:"wasm",kernelFunc:Rp},Dfe=En(Fa),f6;function Pfe(e){f6=e.wasm.cwrap(Zr,null,["number","number","number","number"])}function Ffe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{clipValueMin:a,clipValueMax:o}=s,i=n.dataIdMap.get(r.dataId).id,l=n.makeOutput(r.shape,r.dtype),c=n.dataIdMap.get(l.dataId).id;return f6(i,a,o,c),l}var Ofe={kernelName:Zr,backendName:"wasm",setupFunc:Pfe,kernelFunc:Ffe};function m6(e){let{inputs:t,backend:n}=e,s=v.parseAxisParam(e.attrs.axis,t[0].shape)[0],r=E.computeOutShape(t.map(h=>h.shape),s),a=t.filter(h=>v.sizeFromShape(h.shape)>0);if(a.length===1)return i0({inputs:{x:a[0]},backend:n});let o=n.makeOutput(r,t[0].dtype);if(v.sizeFromShape(r)===0)return o;let i=a.map(h=>h.shape);if(E.assertParamsConsistent(i,s),a[0].dtype==="string"){let h=a.map(y=>{let b=v.sizeFromShape(y.shape.slice(s));return cs({inputs:{x:y},backend:n,attrs:{shape:[-1,b]}})}),f=h.map(y=>({vals:n.readSync(y.dataId),shape:y.shape}));r=E.computeOutShape(h.map(y=>y.shape),1);let m=h[0].shape[0]===1,g=Ky(f,r,t[0].dtype,m),A=E.computeOutShape(a.map(y=>y.shape),s);o.shape=A;let x=n.dataIdMap.get(o.dataId);return x.stringBytes=E.fromStringArrayToUint8(g),h.forEach(y=>n.disposeData(y.dataId)),o}let l=v.sizeFromShape(a[0].shape.slice(0,s)),c=0,u=a.map(h=>{let f=v.sizeFromShape(h.shape.slice(s));return c+=f,f}),d=a.map(h=>n.typedArrayFromHeap(h)),p=n.typedArrayFromHeap(o);for(let h=0;h`cumsum does not support ${r.dtype} tensors in the WASM backend`);let c=E.getAxesPermutation([a],l),u=r;c!==null&&(u=Ic({inputs:{x:r},attrs:{perm:c},backend:n}));let d=E.getInnerMostAxes(1,l)[0];E.assertAxesAreInnerMostDims("cumsum",[d],l);let p=n.makeOutput(u.shape,u.dtype),h=u.shape[d],f=n.dataIdMap.get(u.dataId).id,m=n.dataIdMap.get(p.dataId).id;x6(f,o?1:0,i?1:0,h,m,Jt[r.dtype]);let g=p;if(c!==null){let A=E.getUndoAxesPermutation(c);g=Ic({inputs:{x:p},attrs:{perm:A},backend:n}),n.disposeData(u.dataId),n.disposeData(p.dataId)}return g}var Yfe={kernelName:Ai,backendName:"wasm",setupFunc:Kfe,kernelFunc:Zfe},b6;function Jfe(e){b6=e.wasm.cwrap(xi,null,["number","number","number","array","number","array","array","number","number"])}function Qfe(e){let{backend:t,inputs:n,attrs:s}=e,{x:r}=n,{blockSize:a,dataFormat:o}=s,i=r.shape[0],l=o==="NHWC"?r.shape[1]:r.shape[2],c=o==="NHWC"?r.shape[2]:r.shape[3],u=o==="NHWC"?r.shape[3]:r.shape[1],d=l*a,p=c*a,h=u/(a*a),f=o==="NHWC"?[i,d,p,h]:[i,h,d,p],m=t.makeOutput(f,"float32"),A=t.dataIdMap.get(r.dataId).id,x=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),y=new Uint8Array(new Int32Array(f).buffer),b=new Uint8Array(new Int32Array(v.computeStrides(f)).buffer),w=t.dataIdMap.get(m.dataId).id;return b6(A,a,o==="NHWC"?1:0,x,r.shape.length-1,y,b,f.length,w),m}var eme={kernelName:xi,backendName:"wasm",setupFunc:Jfe,kernelFunc:Qfe},v6;function tme(e){v6=e.wasm.cwrap(Ba,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function nme(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a}=t,o=s.dataIdMap.get(r.dataId).id,i=s.dataIdMap.get(a.dataId).id,{strides:l,dilations:c,pad:u,dimRoundingMode:d}=n,p=c==null?[1,1]:c,h=E.computeConv2DInfo(r.shape,a.shape,l,p,u,d,!0),f=h.filterHeight,m=h.filterWidth,g=h.padInfo.top,A=h.padInfo.right,x=h.padInfo.bottom,y=h.padInfo.left,b=h.dilationHeight,w=h.dilationWidth,k=h.strideHeight,I=h.strideWidth,N=h.inChannels,R=h.outChannels,O=h.padInfo.type==="SAME"?1:0;if(h.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${h.dataFormat}'. Please use 'channelsLast'.`);let $=s.makeOutput(h.outShape,"float32"),P=s.dataIdMap.get($.dataId).id;return v6(o,r.shape[0],r.shape[1],r.shape[2],i,f,m,g,A,x,y,O,b,w,k,I,N,R,P),$}var sme={kernelName:Ba,backendName:"wasm",setupFunc:tme,kernelFunc:nme},rme=En(Va),ame=!1,ome=Kn(bi,ame,"bool"),ime=En(Ua,"float32");function Vx(e){let{inputs:t,attrs:n,backend:s}=e,{input:r}=t,{dim:a}=n,o=r.shape.length,i=r.shape.slice(),l=a;return a<0&&(v.assert(-(o+1)<=a,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+a+1),i.splice(l,0,1),cs({inputs:{x:r},backend:s,attrs:{shape:i}})}var lme={kernelName:vi,backendName:"wasm",kernelFunc:Vx};function w6(e){let{attrs:{shape:t,value:n,dtype:s},backend:r}=e,a=r.makeOutput(t,s);return r.typedArrayFromHeap(a).fill(n),a}var ume={kernelName:yu,backendName:"wasm",kernelFunc:w6},k6;function cme(e){k6=e.wasm.cwrap(ki,null,["number","number","number","number","number","number"])}function dme(e){let{inputs:t,backend:n}=e,{image:s}=t,r=n.makeOutput(s.shape,s.dtype),a=n.dataIdMap.get(s.dataId).id,o=n.dataIdMap.get(r.dataId).id,[i,l,c,u]=s.shape;return k6(a,i,l,c,u,o),r}var pme={kernelName:ki,backendName:"wasm",kernelFunc:dme,setupFunc:cme},hme=En(Ga),fme=!1,mme=Kn(Ha,fme),S6;function gme(e){S6=e.wasm.cwrap(ja,null,["number","number","number","number","number","number","number"])}function Ame(e){let{backend:t,inputs:n,attrs:s}=e,{varianceEpsilon:r}=s,{x:a,mean:o,variance:i,offset:l,scale:c}=n,u=t.dataIdMap.get(a.dataId).id,d=t.dataIdMap.get(o.dataId).id,p=t.dataIdMap.get(i.dataId).id,h=l!=null?t.dataIdMap.get(l.dataId).id:0,f=c!=null?t.dataIdMap.get(c.dataId).id:0,m=t.makeOutput(a.shape,a.dtype);if(v.sizeFromShape(a.shape)===0)return m;let g=t.dataIdMap.get(m.dataId).id;return S6(u,d,p,h,f,r,g),m}var yme={kernelName:ja,backendName:"wasm",setupFunc:gme,kernelFunc:Ame},I6;function xme(e){I6=e.wasm.cwrap(ko,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function bme(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dilations:u,dataFormat:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=n,m=E.computeConv2DInfo(r.shape,a.shape,l,u,c,p),g=Np[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedConv2D in the wasm backend.`);let A=s.dataIdMap.get(r.dataId).id,x=s.dataIdMap.get(a.dataId).id,y=m.outChannels,b=0;if(o!=null){let G=s.dataIdMap.get(o.dataId);if(G.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${G.shape.length}.`);if(G.shape[0]!==y)throw new Error(`FusedConv2D bias shape (${G.shape}) does not match the number of output channels (${y})`);b=G.id}let w=m.filterHeight,k=m.filterWidth,I=m.padInfo.top,N=m.padInfo.right,R=m.padInfo.bottom,O=m.padInfo.left,$=m.dilationHeight,P=m.dilationWidth,T=m.strideHeight,F=m.strideWidth,U=m.inChannels,q=m.padInfo.type==="SAME"?1:0,z=m.batchSize,K=m.inHeight,J=m.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);let Q=s.makeOutput(m.outShape,"float32"),ne=s.dataIdMap.get(Q.dataId).id,re=i==null?0:s.dataIdMap.get(i.dataId).id;return I6(A,z,K,J,x,w,k,b,I,N,R,O,q,$,P,T,F,U,y,g,re,f||0,ne),Q}var vme={kernelName:ko,backendName:"wasm",setupFunc:xme,kernelFunc:bme},C6;function wme(e){C6=e.wasm.cwrap(So,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function kme(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:c,dilations:u,dataFormat:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=n,m=E.computeConv2DInfo(r.shape,a.shape,l,u,c,p,!0),g=Np[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let A=s.dataIdMap.get(r.dataId).id,x=s.dataIdMap.get(a.dataId).id,y=m.outChannels,b=0;if(o!=null){let G=s.dataIdMap.get(o.dataId);if(G.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${G.shape.length}.`);if(G.shape[0]!==y)throw new Error(`FusedDepthwiseConv2D bias shape (${G.shape}) does not match the number of output channels (${y})`);b=G.id}let w=m.filterHeight,k=m.filterWidth,I=m.padInfo.top,N=m.padInfo.right,R=m.padInfo.bottom,O=m.padInfo.left,$=m.dilationHeight,P=m.dilationWidth,T=m.strideHeight,F=m.strideWidth,U=m.inChannels,q=m.padInfo.type==="SAME"?1:0,z=m.batchSize,K=m.inHeight,J=m.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);let Q=s.makeOutput(m.outShape,"float32"),ne=s.dataIdMap.get(Q.dataId).id,re=i==null?0:s.dataIdMap.get(i.dataId).id;return C6(A,z,K,J,x,w,k,b,I,N,R,O,q,$,P,T,F,U,y,g,re,f||0,ne),Q}var Sme={kernelName:So,backendName:"wasm",setupFunc:wme,kernelFunc:kme},T6;function Ime(e){T6=e.wasm.cwrap(Ii,null,["number","number","number","number","number","number","array","number"])}function Cme(e){let{backend:t,inputs:n}=e,{params:s,indices:r}=n,[a,o,i,l]=G2.prepareAndValidate(s,r),c=t.makeOutput(a,s.dtype);if(o===0)return c;let u=r.shape,d=u[u.length-1],h=t.dataIdMap.get(s.dataId).id,m=t.dataIdMap.get(r.dataId).id,g=new Uint8Array(new Int32Array(l).buffer),A=t.dataIdMap.get(c.dataId).id;return T6(h,Jt[s.dtype],m,o,d,i,g,A),c}var Tme={kernelName:Ii,backendName:"wasm",setupFunc:Ime,kernelFunc:Cme},N6;function Nme(e){N6=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function Eme(e){let{backend:t,inputs:n,attrs:s}=e,{x:r,indices:a}=n,{axis:o,batchDims:i}=s,l=v.parseAxisParam(o,r.shape)[0],c=t.readSync(a.dataId),u=r.shape[l];for(let R=0;R=0,()=>`GatherV2: the index value ${O} is not in [0, ${u-1}]`)}let d=E.segment_util.collectGatherOpShapeInfo(r,a,l,i),p=cs({inputs:{x:r},attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]},backend:t}),h=v.sizeFromShape(a.shape),f=cs({inputs:{x:a},attrs:{shape:[d.batchSize,h/d.batchSize]},backend:t}),m=[d.batchSize,d.outerSize,h/d.batchSize,d.sliceSize],g=t.makeOutput(m,r.dtype);if(v.sizeFromShape(r.shape)===0)return g;let A=p.shape.length-1,y=t.dataIdMap.get(p.dataId).id,w=t.dataIdMap.get(f.dataId).id,k=t.dataIdMap.get(g.dataId).id,I=new Uint8Array(new Int32Array(v.computeStrides(p.shape)).buffer),N=new Uint8Array(new Int32Array(v.computeStrides(m)).buffer);return N6(y,Jt[r.dtype],I,A,w,d.batchSize,N,k),t.disposeData(p.dataId),t.disposeData(f.dataId),g.shape=d.outputShape,g}var Rme={kernelName:Si,backendName:"wasm",setupFunc:Nme,kernelFunc:Eme},$me=!1,_me=Kn(Ci,$me,"bool"),Dme=!1,Pme=Kn(qa,Dme,"bool"),E6;function Fme(e){E6=e.wasm.cwrap(Ti,null,["number","number","number","number"])}function Ome(e){let{inputs:{x:t},attrs:{alpha:n},backend:s}=e,r=s.dataIdMap.get(t.dataId).id,a=s.makeOutput(t.shape,"float32");if(v.sizeFromShape(t.shape)!==0){let o=s.dataIdMap.get(a.dataId).id;E6(r,Jt[t.dtype],n,o)}return a}var Mme={kernelName:Ti,backendName:"wasm",setupFunc:Fme,kernelFunc:Ome},zme=!1,Lme=Kn(Ni,zme,"bool"),Bme=!1,Wme=Kn(Ei,Bme,"bool"),Vme=En(Ka),Ume=!1,Gme=Kn(Ri,Ume,"bool"),R6;function Hme(e){R6=e.wasm.cwrap(Za,null,["number","number","number","number"])}function jme(e){let{backend:t,inputs:n,attrs:s}=e,{reductionIndices:r,keepDims:a}=s,{x:o}=n,l=t.dataIdMap.get(o.dataId).id,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=Ko(o,r,t);if(h){let y=t.dataIdMap.get(u.dataId).id;c=u,l=y}let f=c.shape.length;E.assertAxesAreInnerMostDims("max",d,f);let[m,g]=E.computeOutAndReduceShapes(c.shape,d),A=v.sizeFromShape(g),x=t.makeOutput(m,o.dtype);if(v.sizeFromShape(c.shape)!==0){let y=t.dataIdMap.get(x.dataId).id;R6(l,Jt[o.dtype],A,y)}if(h&&t.disposeData(u.dataId),a){let y=E.expandShapeToKeepDim(x.shape,p);x.shape=y}return x}var qme={kernelName:Za,backendName:"wasm",setupFunc:Hme,kernelFunc:jme},Xme=!1,Kme=Kn(Ya,Xme),$6;function Zme(e){$6=e.wasm.cwrap(Ja,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Yme(e){let{inputs:t,attrs:n,backend:s}=e,r=t.x,a=s.dataIdMap.get(r.dataId).id;v.assert(r.dtype==="float32",()=>`Error in MaxPool: only float32 input is supported. Got ${r.dtype}.`);let{filterSize:o,strides:i,pad:l,dimRoundingMode:c}=n,u=E.computePool2DInfo(r.shape,o,i,1,l,c),d=u.filterHeight,p=u.filterWidth,h=u.padInfo.top,f=u.padInfo.right,m=u.padInfo.bottom,g=u.padInfo.left,A=u.dilationHeight,x=u.dilationWidth,y=u.strideHeight,b=u.strideWidth,w=u.inChannels,k=u.outChannels;if(u.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${u.dataFormat}'. Please use 'channelsLast'.`);let I=s.makeOutput(u.outShape,"float32"),N=s.dataIdMap.get(I.dataId).id;return $6(a,r.shape[0],r.shape[1],r.shape[2],d,p,h,f,m,g,A,x,y,b,w,k,N),I}var Jme={kernelName:Ja,backendName:"wasm",setupFunc:Zme,kernelFunc:Yme},_6;function Qme(e){_6=e.wasm.cwrap(Qa,null,["number, number, number"])}function e0e(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=Ko(o,r,t),f=d;if(h){let b=t.dataIdMap.get(u.dataId).id;b!==i&&(c=u,l=b,f=E.getInnerMostAxes(f.length,c.shape.length))}E.assertAxesAreInnerMostDims("mean",f,c.shape.length);let[m,g]=E.computeOutAndReduceShapes(c.shape,f),A=v.sizeFromShape(g),x=c;c.dtype!=="float32"&&(x=Rp({backend:t,inputs:{x:c},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(x.dataId).id);let y=t.makeOutput(m,"float32");if(v.sizeFromShape(c.shape)!==0){let b=t.dataIdMap.get(y.dataId).id;_6(l,A,b)}if(h&&t.disposeData(u.dataId),a){let b=E.expandShapeToKeepDim(y.shape,p);y.shape=b}return c.dtype!=="float32"&&t.disposeData(x.dataId),y}var t0e={kernelName:Qa,backendName:"wasm",setupFunc:Qme,kernelFunc:e0e},D6;function n0e(e){D6=e.wasm.cwrap(eo,null,["number","number","number","number"])}function s0e(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=Ko(o,r,t);if(h){let y=t.dataIdMap.get(u.dataId).id;y!==i&&(c=u,l=y)}let f=c.shape.length;E.assertAxesAreInnerMostDims("min",d,f);let[m,g]=E.computeOutAndReduceShapes(c.shape,d),A=v.sizeFromShape(g),x=t.makeOutput(m,c.dtype);if(v.sizeFromShape(c.shape)!==0){let y=t.dataIdMap.get(x.dataId).id;D6(l,Jt[o.dtype],A,y)}if(h&&t.disposeData(u.dataId),a){let y=E.expandShapeToKeepDim(x.shape,p);x.shape=y}return x}var r0e={kernelName:eo,backendName:"wasm",setupFunc:n0e,kernelFunc:s0e},a0e=!1,o0e=Kn(to,a0e),Ux;(function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"})(Ux||(Ux={}));var P6;function i0e(e){P6=e.wasm.cwrap(no,null,["number","array","number","number","array","array","number","number"])}function l0e(e){let{inputs:{x:t},backend:n,attrs:{paddings:s,mode:r}}=e,a=s.map((f,m)=>f[0]+t.shape[m]+f[1]),o=n.dataIdMap.get(t.dataId).id,i=n.makeOutput(a,t.dtype),l=n.dataIdMap.get(i.dataId).id,c=new Uint8Array(new Int32Array(t.shape).buffer),u=s.map(f=>f[0]),d=s.map(f=>f[1]),p=new Uint8Array(new Int32Array(u).buffer),h=new Uint8Array(new Int32Array(d).buffer);return P6(o,c,t.shape.length,Jt[t.dtype],p,h,Ux[r],l),i}var u0e={kernelName:no,backendName:"wasm",kernelFunc:l0e,setupFunc:i0e},c0e=!0,d0e=Kn(so,c0e),p0e=En($i);function Gx(e,t){let n=new Int32Array(e.wasm.HEAPU8.buffer,t,4),s=n[0],r=n[1],a=n[2],o=n[3];return e.wasm._free(t),{pSelectedIndices:s,selectedSize:r,pSelectedScores:a,pValidOutputs:o}}var F6;function h0e(e){F6=e.wasm.cwrap(Di,"number",["number","number","number","number","number"])}function f0e(e){let{backend:t,inputs:n,attrs:s}=e,{iouThreshold:r,maxOutputSize:a,scoreThreshold:o}=s,{boxes:i,scores:l}=n,c=t.dataIdMap.get(i.dataId).id,u=t.dataIdMap.get(l.dataId).id,d=F6(c,u,a,r,o),{pSelectedIndices:p,selectedSize:h,pSelectedScores:f,pValidOutputs:m}=Gx(t,d);return t.wasm._free(f),t.wasm._free(m),t.makeOutput([h],"int32",p)}var m0e={kernelName:Di,backendName:"wasm",setupFunc:h0e,kernelFunc:f0e},O6;function g0e(e){O6=e.wasm.cwrap(Iu,"number",["number","number","number","number","number","bool"])}function A0e(e){let{backend:t,inputs:n,attrs:s}=e,{iouThreshold:r,maxOutputSize:a,scoreThreshold:o,padToMaxOutputSize:i}=s,{boxes:l,scores:c}=n,u=t.dataIdMap.get(l.dataId).id,d=t.dataIdMap.get(c.dataId).id,p=O6(u,d,a,r,o,i),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=Gx(t,p);t.wasm._free(m);let A=t.makeOutput([f],"int32",h),x=t.makeOutput([],"int32",g);return[A,x]}var y0e={kernelName:Iu,backendName:"wasm",setupFunc:g0e,kernelFunc:A0e},M6;function x0e(e){M6=e.wasm.cwrap(Pi,"number",["number","number","number","number","number","number"])}function b0e(e){let{backend:t,inputs:n,attrs:s}=e,{iouThreshold:r,maxOutputSize:a,scoreThreshold:o,softNmsSigma:i}=s,{boxes:l,scores:c}=n,u=t.dataIdMap.get(l.dataId).id,d=t.dataIdMap.get(c.dataId).id,p=M6(u,d,a,r,o,i),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=Gx(t,p);t.wasm._free(g);let A=t.makeOutput([f],"int32",h),x=t.makeOutput([f],"float32",m);return[A,x]}var v0e={kernelName:Pi,backendName:"wasm",setupFunc:x0e,kernelFunc:b0e},w0e=!1,k0e=Kn(_i,w0e,"bool"),z6;function S0e(e){z6=e.wasm.cwrap(Oi,null,["number","number","number","number","number"])}function I0e(e){let{inputs:t,backend:n,attrs:s}=e,{indices:r}=t,{depth:a,onValue:o,offValue:i}=s,l=n.makeOutput([...r.shape,a],"int32"),c=n.dataIdMap.get(l.dataId).id,d=n.dataIdMap.get(r.dataId).id;return z6(d,a,o,i,c),l}var C0e={kernelName:Oi,backendName:"wasm",setupFunc:S0e,kernelFunc:I0e};function T0e(e){let{inputs:{x:t},backend:n}=e,s=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(s).fill(1),s}var N0e={kernelName:Fi,backendName:"wasm",kernelFunc:T0e};function E0e(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(t.length===1)return Vx({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let a=t[0].shape,o=t[0].dtype;t.forEach(u=>{v.assertShapesMatch(a,u.shape,"All tensors passed to stack must have matching shapes"),v.assert(o===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(u=>{let d=Vx({inputs:{input:u},backend:n,attrs:{dim:r}});return i.push(d),d}),c=m6({inputs:l,backend:n,attrs:{axis:r}});return i.forEach(u=>n.disposeData(u.dataId)),c}var R0e={kernelName:Mi,backendName:"wasm",kernelFunc:E0e},L6;function $0e(e){L6=e.wasm.cwrap(ro,null,["number","array","number","number","array","array","number","number"])}function _0e(e){let{inputs:{x:t},backend:n,attrs:{paddings:s,constantValue:r}}=e,a=s.map((m,g)=>m[0]+t.shape[g]+m[1]);if(v.sizeFromShape(t.shape)===0)return w6({backend:n,attrs:{shape:a,value:r,dtype:t.dtype}});let o=n.dataIdMap.get(t.dataId).id,i=n.makeOutput(a,t.dtype),c=n.dataIdMap.get(i.dataId).id,u=new Uint8Array(new Int32Array(t.shape).buffer),d=s.map(m=>m[0]),p=s.map(m=>m[1]),h=new Uint8Array(new Int32Array(d).buffer),f=new Uint8Array(new Int32Array(p).buffer);return L6(o,u,t.shape.length,Jt[t.dtype],h,f,r,c),i}var B6={kernelName:ro,backendName:"wasm",kernelFunc:_0e,setupFunc:$0e},D0e=!1,P0e=Kn(ao,D0e),W6;function F0e(e){W6=e.wasm.cwrap(oo,null,["number","number","number"])}function O0e(e){let{inputs:t,backend:n}=e,{x:s,alpha:r}=t,a=n.dataIdMap.get(s.dataId).id,o=n.dataIdMap.get(r.dataId).id,i=a,l=s,c=l;l.dtype!=="float32"&&(c=Rp({backend:n,inputs:{x:s},attrs:{dtype:"float32"}}),i=n.dataIdMap.get(c.dataId).id);let u=n.makeOutput(s.shape,"float32"),d=n.dataIdMap.get(u.dataId).id;return W6(i,o,d),l.dtype!=="float32"&&n.disposeData(c.dataId),u}var M0e={kernelName:oo,backendName:"wasm",setupFunc:F0e,kernelFunc:O0e},V6;function z0e(e){V6=e.wasm.cwrap(zi,null,["number","number","number","number"])}function L0e(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=Ko(o,r,t),f=d;if(h){let y=t.dataIdMap.get(u.dataId).id;y!==i&&(c=u,l=y,f=E.getInnerMostAxes(f.length,c.shape.length))}E.assertAxesAreInnerMostDims("prod",f,c.shape.length);let[m,g]=E.computeOutAndReduceShapes(c.shape,f),A=v.sizeFromShape(g),x=t.makeOutput(m,c.dtype);if(v.sizeFromShape(c.shape)!==0){let y=t.dataIdMap.get(x.dataId).id;V6(l,A,Jt[x.dtype],y)}if(h&&t.disposeData(u.dataId),a){let y=E.expandShapeToKeepDim(x.shape,p);x.shape=y}return x}var B0e={kernelName:zi,backendName:"wasm",setupFunc:z0e,kernelFunc:L0e},W0e=e=>{let{backend:t,attrs:n}=e,{start:s,stop:r,step:a,dtype:o}=n,i=Jy(s,r,a,o),l=t.makeOutput([i.length],o);return t.typedArrayFromHeap(l).set(i),l},V0e={kernelName:Cu,backendName:"wasm",kernelFunc:W0e},U0e=!0,G0e=Kn(Wa,U0e),H0e=En(io),j0e=En(uo),U6;function q0e(e){U6=e.wasm.cwrap(lo,null,["number","number","number","number","number","number","number","number","number","number"])}function X0e(e){let{backend:t,inputs:n,attrs:s}=e,{images:r}=n,{alignCorners:a,halfPixelCenters:o,size:i}=s,[l,c]=i,[u,d,p,h]=r.shape,f=[u,l,c,h],m=t.dataIdMap.get(r.dataId),g;m.dtype!=="float32"&&(g=Rp({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(g.dataId));let A=m.id,x=t.makeOutput(f,"float32");if(v.sizeFromShape(r.shape)===0)return x;let y=t.dataIdMap.get(x.dataId).id;return U6(A,u,d,p,h,l,c,a?1:0,o?1:0,y),g!=null&&t.disposeData(g.dataId),x}var K0e={kernelName:lo,backendName:"wasm",setupFunc:q0e,kernelFunc:X0e},G6;function Z0e(e){G6=e.wasm.cwrap(Bi,null,["number","array","number","array","number","number"])}function Y0e(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s,o=v.parseAxisParam(a,r.shape);if(r.shape.length===0)return i0({inputs:{x:r},backend:n});let i=n.makeOutput(r.shape,r.dtype),l=n.dataIdMap.get(r.dataId).id,c=n.dataIdMap.get(i.dataId).id,u=new Uint8Array(new Int32Array(o).buffer),d=new Uint8Array(new Int32Array(r.shape).buffer);G6(l,u,o.length,d,r.shape.length,c);let p=cs({inputs:{x:i},attrs:{shape:r.shape},backend:n});return n.disposeData(i.dataId),p}var J0e={kernelName:Bi,backendName:"wasm",kernelFunc:Y0e,setupFunc:Z0e},H6;function Q0e(e){H6=e.wasm.cwrap(el,null,["number","number","number","number","number","number","number","number","array","number","number"])}function ege(e){let{inputs:t,backend:n,attrs:s}=e,{image:r}=t,{radians:a,fillValue:o,center:i}=s,l=n.makeOutput(r.shape,r.dtype),c=n.dataIdMap.get(r.dataId).id,u=n.dataIdMap.get(l.dataId).id,[d,p,h,f]=r.shape,[m,g]=E.getImageCenter(i,p,h),A=o===0,x=255,y=typeof o=="number"?[o,o,o,A?0:x]:[...o,x],b=new Uint8Array(new Int32Array(y).buffer);return H6(c,d,p,h,f,a,m,g,b,y.length,u),l}var tge={kernelName:el,backendName:"wasm",kernelFunc:ege,setupFunc:Q0e},nge=En(Wi),sge=En(co),j6;function rge(e){j6=e.wasm.cwrap(Vi,null,["number","number","number","number","number","number","array","number","number"])}function age(e){let{backend:t,inputs:n,attrs:s}=e,{indices:r,updates:a}=n,{shape:o}=s,i=t.makeOutput(o,a.dtype);if(v.sizeFromShape(o)===0)return i;let{sliceRank:l,numUpdates:c,sliceSize:u,strides:d,outputSize:p}=H2.calculateShapes(a,r,o),f=t.dataIdMap.get(r.dataId).id,g=t.dataIdMap.get(a.dataId).id,A=new Uint8Array(new Int32Array(d).buffer),x=t.dataIdMap.get(i.dataId).id;return j6(f,g,Jt[a.dtype],l,c,u,A,p,x),i}var oge={kernelName:Vi,backendName:"wasm",setupFunc:rge,kernelFunc:age},q6;function ige(e){q6=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function lge(e){let{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t,o=n.dataIdMap.get(s.dataId).id,i=n.dataIdMap.get(r.dataId).id,l=n.dataIdMap.get(a.dataId).id,c=n.makeOutput(r.shape,r.dtype),u=n.dataIdMap.get(c.dataId).id,d=s.shape.length,p=r.shape.length,h=d===0||d>1||p===1?1:v.sizeFromShape(r.shape.slice(1));return q6(o,i,l,h,u),c}var uge={kernelName:Ui,backendName:"wasm",kernelFunc:lge,setupFunc:ige},X6;function cge(e){X6=e.wasm.cwrap(ho,null,["number","number"])}function dge(e){let{backend:t,inputs:{x:n}}=e,s=t.dataIdMap.get(n.dataId).id,r=t.makeOutput(n.shape,n.dtype),a=t.dataIdMap.get(r.dataId).id;return v.sizeFromShape(r.shape)===0||X6(s,a),r}var pge={kernelName:"Sigmoid",backendName:"wasm",setupFunc:cge,kernelFunc:dge},hge=En(po),K6;function fge(e){K6=e.wasm.cwrap(go,null,["number","number","number","number"])}function mge(e){let{backend:t,inputs:{logits:n},attrs:{dim:s}}=e,r=t.dataIdMap.get(n.dataId).id,a=t.makeOutput(n.shape,n.dtype),o=t.dataIdMap.get(a.dataId).id,i=n.shape[s],l=v.sizeFromShape(n.shape)/i;return v.sizeFromShape(a.shape)===0||K6(r,o,i,l),a}var gge={kernelName:go,backendName:"wasm",setupFunc:fge,kernelFunc:mge};function Age(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:o}=s,i=v.sizeFromShape(a),l=[[0,0]];l.push(...o);for(let k=1+a.length;k{let p=[...u];p[i]=d;let h=Ep({inputs:{x:r},attrs:{begin:c,size:p},backend:s});return c[i]+=d,h})}var bge={kernelName:qi,backendName:"wasm",kernelFunc:xge},vge=En(fo),wge=En(_u),kge=!0,Sge=Kn(Ao,kge),Z6;function Ige(e){Z6=e.wasm.cwrap(vo,null,["number","number","number","number"])}function Cge(e){let{backend:t,inputs:n,attrs:s}=e,{alpha:r}=s,{x:a}=n,o=t.dataIdMap.get(a.dataId).id,i=t.makeOutput(a.shape,a.dtype),l=t.dataIdMap.get(i.dataId).id;return Z6(o,r,Jt[a.dtype],l),i}var Tge={kernelName:vo,backendName:"wasm",setupFunc:Ige,kernelFunc:Cge},Y6;function Nge(e){Y6=e.wasm.cwrap(Xi,null,["number","array","number","array","array","array","array","array","number","number"])}function Ege(e){let{backend:t,inputs:n,attrs:s}=e,{x:r}=n,{begin:a,end:o,strides:i,beginMask:l,endMask:c,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:p}=s,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:A,begin:x,end:y,strides:b}=Ft.sliceInfo(r.shape,a,o,i,l,c,u,d,p),w;if(m)w=cs({inputs:{x:r},backend:t,attrs:{shape:f}});else if(g||A){v.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let k=Ft.computeOutShape(x,y,b),I=Ep({inputs:{x:r},backend:t,attrs:{begin:x,size:k}});w=cs({inputs:{x:I},backend:t,attrs:{shape:f}}),t.disposeData(I.dataId)}else{let k=t.makeOutput(h,"float32"),I=t.dataIdMap.get(r.dataId).id,N=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),R=new Uint8Array(new Int32Array(x).buffer),O=new Uint8Array(new Int32Array(y).buffer),$=new Uint8Array(new Int32Array(b).buffer),P=new Uint8Array(new Int32Array(h).buffer),T=new Uint8Array(new Int32Array(v.computeStrides(h)).buffer),F=t.dataIdMap.get(k.dataId).id;Y6(I,N,r.shape.length,R,O,$,P,T,h.length,F),w=cs({inputs:{x:k},backend:t,attrs:{shape:f}}),t.disposeData(k.dataId)}return w}var Rge={kernelName:Xi,backendName:"wasm",setupFunc:Nge,kernelFunc:Ege},$ge=!0,_ge=Kn(yo,$ge),J6;function Dge(e){J6=e.wasm.cwrap(mo,null,["number","number","number","number"])}function Pge(e){let{backend:t,inputs:n,attrs:s}=e,{axis:r,keepDims:a}=s,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,c=o,{transposed:u,axes:d,originalAxes:p,inputWasTransposed:h}=Ko(o,r,t),f=d;if(h){let y=t.dataIdMap.get(u.dataId).id;y!==i&&(c=u,l=y,f=E.getInnerMostAxes(f.length,c.shape.length))}E.assertAxesAreInnerMostDims("sum",f,c.shape.length);let[m,g]=E.computeOutAndReduceShapes(c.shape,f),A=v.sizeFromShape(g),x=t.makeOutput(m,c.dtype);if(v.sizeFromShape(c.shape)!==0){let y=t.dataIdMap.get(x.dataId).id;J6(l,A,Jt[x.dtype],y)}if(h&&t.disposeData(u.dataId),a){let y=E.expandShapeToKeepDim(x.shape,p);x.shape=y}return x}var Fge={kernelName:mo,backendName:"wasm",setupFunc:Dge,kernelFunc:Pge},Oge=En(Ki),Mge=En(xo),Q6;function zge(e){Q6=e.wasm.cwrap(Yr,null,["number","array","number","array","number","number"])}function Lge(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,a=n.dataIdMap.get(r.dataId).id,{reps:o}=s,i=new Array(r.shape.length);for(let p=0;p{let{x:s}=e,{k:r,sorted:a}=n,o=t.dataIdMap.get(s.dataId).id,i=new Uint8Array(new Int32Array(s.shape).buffer),l=s.shape.slice();l[l.length-1]=r;let c=t.makeOutput(l,s.dtype),u=t.dataIdMap.get(c.dataId).id,d=t.makeOutput(l,"int32"),p=t.dataIdMap.get(d.dataId).id;return e8(o,i,s.shape.length,Jt[s.dtype],r,a,u,p),[c,d]},Uge={kernelName:Zi,backendName:"wasm",setupFunc:Wge,kernelFunc:Vge},t8;function Gge(e){t8=e.wasm.cwrap(Yi,null,["number","number","bool","number","number","number","number","number","number","array","number","number","number","number","number"])}function Hge(e){let{backend:t,inputs:n,attrs:s}=e,{image:r,transforms:a}=n,{interpolation:o,fillMode:i,fillValue:l,outputShape:c}=s,[u,d,p,h]=r.shape,[f,m]=c!=null?c:[d,p],g=[u,f,m,h],A=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),x=t.makeOutput(g,r.dtype),y=t.dataIdMap.get(x.dataId).id,w=t.dataIdMap.get(r.dataId).id,I=t.dataIdMap.get(a.dataId).id,N=o==="nearest"?1:2,R;switch(i){case"constant":R=1;break;case"reflect":R=2;break;case"wrap":R=3;break;case"nearest":R=4;break;default:R=1;break}return t8(w,I,a.shape[0]>1,u,f,m,h,p,d,A,r.shape.length-1,N,R,l,y),x}var jge={kernelName:Yi,backendName:"wasm",setupFunc:Gge,kernelFunc:Hge};function qge(e){let{inputs:t,backend:n,attrs:s}=e,{value:r}=t,{axis:a}=s;a<0&&(a+=r.shape.length);let o=r.shape[a],i=r.shape.length,l=new Array(i-1),c=0;for(let h=0;h({dataId:h,dtype:f,shape:l}))}var Xge={kernelName:Ji,backendName:"wasm",kernelFunc:qge};function Kge(e){let{inputs:{x:t},backend:n}=e,s=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(s).fill(0),s}var Zge={kernelName:Qi,backendName:"wasm",kernelFunc:Kge},Yge=[Qhe,tfe,rfe,pfe,mfe,yfe,vfe,Ife,$fe,_fe,Dfe,Ofe,Mfe,Bfe,Ufe,Gfe,Hfe,Xfe,Yfe,eme,sme,rme,ome,ime,lme,ume,pme,hme,mme,Jhe,yme,vme,Sme,Tme,Rme,_me,Pme,afe,Mme,Lme,Wme,Vme,Gme,qme,Kme,Jme,t0e,r0e,o0e,u0e,d0e,p0e,m0e,y0e,v0e,k0e,C0e,N0e,R0e,B6,P0e,M0e,B0e,V0e,G0e,H0e,j0e,wfe,K0e,J0e,tge,sge,nge,oge,uge,pge,hge,Efe,gge,yge,bge,vge,wge,Sge,Tge,Rge,_ge,Fge,Oge,Mge,Bge,Uge,jge,ufe,Xge,Zge];for(let e of Yge)cr(e);var Hx=Y();Hx.registerFlag("WASM_HAS_SIMD_SUPPORT",async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,9,1,7,0,65,0,253,15,26,11])));Hx.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(Hx.get("IS_NODE"))return!1;try{return new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch(e){return!1}});var n8=di(jE()),Jge='var Module={};function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;this.alert=threadAlert;Module["instantiateWasm"]=function(info,receiveInstance){var instance=new WebAssembly.Instance(Module["wasmModule"],info);Module["wasmModule"]=null;receiveInstance(instance);return instance.exports};function moduleLoaded(){}this.onmessage=function(e){try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob==="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["_emscripten_tls_init"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].setThreadStatus(Module["_pthread_self"](),1);try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(!Module["getNoExitRuntime"]())Module["PThread"].threadExit(result)}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["getNoExitRuntime"]()){}else{Module["PThread"].threadExit(ex.status)}}else{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}};if(typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string"){self={location:{href:__filename}};var onmessage=this.onmessage;var nodeWorkerThreads=require("worker_threads");global.Worker=nodeWorkerThreads.Worker;var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",function(data){onmessage({data:data})});var nodeFS=require("fs");var nodeRead=function(filename){return nodeFS.readFileSync(filename,"utf8")};function globalEval(x){global.require=require;global.Module=Module;eval.call(null,x)}importScripts=function(f){globalEval(nodeRead(f))};postMessage=function(msg){parentPort.postMessage(msg)};if(typeof performance==="undefined"){performance={now:function(){return Date.now()}}}}',Qge=di(qE()),s8=class extends ru{constructor(e){super();this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(o8),qx=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new sd(this,as())}write(e,t,n){let s={id:this.dataIdNextNumber++};return this.move(s,e,t,n,1),s}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=v.now();return e(),{kernelMs:v.now()-t}}move(e,t,n,s,r){let a=this.dataIdNextNumber++;if(s==="string"){let c=t;this.dataIdMap.set(e,{id:a,stringBytes:c,shape:n,dtype:s,memoryOffset:null,refCount:r});return}let o=v.sizeFromShape(n),i=o*v.bytesPerElement(s),l=this.wasm._malloc(i);this.dataIdMap.set(e,{id:a,memoryOffset:l,shape:n,dtype:s,refCount:r}),this.wasm.tfjs.registerTensor(a,o,l),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,i),l)}async read(e){return this.readSync(e)}readSync(e){let{memoryOffset:t,dtype:n,shape:s,stringBytes:r}=this.dataIdMap.get(e);if(n==="string")return r;let a=this.wasm.HEAPU8.slice(t,t+v.sizeFromShape(s)*v.bytesPerElement(n));return n2e(a.buffer,n)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){let n=this.dataIdMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;this.wasm._free(n.memoryOffset),this.wasm.tfjs.disposeData(n.id),this.dataIdMap.delete(e)}return!0}refCount(e){return this.dataIdMap.has(e)?this.dataIdMap.get(e).refCount:0}incRef(e){let t=this.dataIdMap.get(e);t!=null&&t.refCount++}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose(),"PThread"in this.wasm&&this.wasm.PThread.terminateAllThreads(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(e,t,n){let s;if(n==null)s=this.write(null,e,t);else{let r=this.dataIdNextNumber++;s={id:r},this.dataIdMap.set(s,{id:r,memoryOffset:n,shape:e,dtype:t,refCount:1});let a=v.sizeFromShape(e);this.wasm.tfjs.registerTensor(r,a,n)}return{dataId:s,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:n}){let s=this.wasm.HEAPU8.buffer,{memoryOffset:r}=this.dataIdMap.get(n),a=v.sizeFromShape(e);switch(t){case"float32":return new Float32Array(s,r,a);case"int32":return new Int32Array(s,r,a);case"bool":return new Uint8Array(s,r,a);default:throw new Error(`Unknown dtype ${t}`)}}};function e2e(e){return(t,n)=>(v.fetch(e,{credentials:"same-origin"}).then(s=>{s.ok||t.env.a(`failed to load wasm binary file at '${e}'`),s.arrayBuffer().then(r=>{WebAssembly.instantiate(r,t).then(a=>{n(a.instance,a.module)})})}),{})}function r8(e,t,n){if(l0!=null)return l0;let s="tfjs-backend-wasm.wasm";return e&&t?s="tfjs-backend-wasm-threaded-simd.wasm":e&&(s="tfjs-backend-wasm-simd.wasm"),_p!=null&&_p[s]!=null?_p[s]:n+s}async function t2e(){let[e,t]=await Promise.all([Y().getAsync("WASM_HAS_SIMD_SUPPORT"),Y().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((n,s)=>{let r={};r.locateFile=(i,l)=>{if(i.endsWith(".worker.js")){let c=Jge,u=new Blob([c],{type:"application/javascript"});return URL.createObjectURL(u)}return i.endsWith(".wasm")?r8(e,t,$p!=null?$p:l):l+i},jx&&(r.instantiateWasm=e2e(r8(e,t,$p!=null?$p:"")));let a=!1;r.onAbort=()=>{if(a||Dp)return;Dp=!0,s({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"})};let o;t&&e&&l0==null?(r.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+n8.default.toString()],{type:"text/javascript"}),o=(0,n8.default)(r)):o=(0,Qge.default)(r),o.then(i=>{a=!0,Dp=!1;let l=null;i.tfjs={init:i.cwrap("init",null,[]),initWithThreadsCount:i.cwrap("init_with_threads_count",null,["number"]),getThreadsCount:i.cwrap("get_threads_count","number",[]),registerTensor:i.cwrap("register_tensor",null,["number","number","number"]),disposeData:i.cwrap("dispose_data",l,["number"]),dispose:i.cwrap("dispose",l,[])},n({wasm:i})})})}function n2e(e,t){switch(t){case"float32":return new Float32Array(e);case"int32":return new Int32Array(e);case"bool":return new Uint8Array(e);default:throw new Error(`Unknown dtype ${t}`)}}var s2e=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],l0=null,$p=null,_p={},Dp=!1,jx=!1;function r2e(e,t=!1){if(J2("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),Dp)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");l0=e,jx=t}function a8(e,t=!1){if(Dp)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPaths()` before you call `tf.setBackend()` or `tf.ready()`");if(typeof e=="string")$p=e;else{_p=e;let n=s2e.filter(s=>_p[s]==null);if(n.length>0)throw new Error(`There were no entries found for the following binaries: ${n.join(",")}. Please either call setWasmPaths with a map providing a path for each binary, or with a string indicating the directory where all the binaries can be found.`)}jx=t}var o8=-1,qx=-1;function a2e(e){o8=e}function o2e(){if(qx===-1)throw new Error("WASM backend not initialized.");return qx}var i2e="0.0.0",l2e=2;ul("wasm",async()=>{let{wasm:e}=await t2e();return new s8(e)},l2e);var Zo="3.11.0-20211110",i8={tfjs:Zo,"tfjs-core":Zo,"tfjs-data":Zo,"tfjs-layers":Zo,"tfjs-converter":Zo,"tfjs-backend-cpu":Zo,"tfjs-backend-webgl":Zo,"tfjs-backend-wasm":Zo},Pp=i8["tfjs-core"];var l8=` precision highp float; attribute vec2 pos; attribute vec2 uv; varying vec2 vUv; uniform float flipY; void main(void) { vUv = uv; gl_Position = vec4(pos.x, pos.y*flipY, 0.0, 1.); } `;var u8=` precision highp float; varying vec2 vUv; uniform sampler2D texture; uniform float m[20]; void main(void) { vec4 c = texture2D(texture, vUv); gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[3] * c.a + m[4]; gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[8] * c.a + m[9]; gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[13] * c.a + m[14]; gl_FragColor.a = m[15] * c.r + m[16] * c.g + m[17] * c.b + m[18] * c.a + m[19]; } `,c8=` precision highp float; varying vec2 vUv; uniform sampler2D texture; uniform float m[20]; void main(void) { vec4 c = texture2D(texture, vUv); gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[4]; gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[9]; gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[14]; gl_FragColor.a = c.a; } `,d8=` precision highp float; varying vec2 vUv; uniform vec2 size; uniform sampler2D texture; vec2 pixelate(vec2 coord, vec2 size) { return floor( coord / size ) * size; } void main(void) { gl_FragColor = vec4(0.0); vec2 coord = pixelate(vUv, size); gl_FragColor += texture2D(texture, coord); } `,p8=` precision highp float; varying vec2 vUv; uniform sampler2D texture; uniform vec2 px; void main(void) { gl_FragColor = vec4(0.0); gl_FragColor += texture2D(texture, vUv + vec2(-7.0*px.x, -7.0*px.y))*0.0044299121055113265; gl_FragColor += texture2D(texture, vUv + vec2(-6.0*px.x, -6.0*px.y))*0.00895781211794; gl_FragColor += texture2D(texture, vUv + vec2(-5.0*px.x, -5.0*px.y))*0.0215963866053; gl_FragColor += texture2D(texture, vUv + vec2(-4.0*px.x, -4.0*px.y))*0.0443683338718; gl_FragColor += texture2D(texture, vUv + vec2(-3.0*px.x, -3.0*px.y))*0.0776744219933; gl_FragColor += texture2D(texture, vUv + vec2(-2.0*px.x, -2.0*px.y))*0.115876621105; gl_FragColor += texture2D(texture, vUv + vec2(-1.0*px.x, -1.0*px.y))*0.147308056121; gl_FragColor += texture2D(texture, vUv )*0.159576912161; gl_FragColor += texture2D(texture, vUv + vec2( 1.0*px.x, 1.0*px.y))*0.147308056121; gl_FragColor += texture2D(texture, vUv + vec2( 2.0*px.x, 2.0*px.y))*0.115876621105; gl_FragColor += texture2D(texture, vUv + vec2( 3.0*px.x, 3.0*px.y))*0.0776744219933; gl_FragColor += texture2D(texture, vUv + vec2( 4.0*px.x, 4.0*px.y))*0.0443683338718; gl_FragColor += texture2D(texture, vUv + vec2( 5.0*px.x, 5.0*px.y))*0.0215963866053; gl_FragColor += texture2D(texture, vUv + vec2( 6.0*px.x, 6.0*px.y))*0.00895781211794; gl_FragColor += texture2D(texture, vUv + vec2( 7.0*px.x, 7.0*px.y))*0.0044299121055113265; } `,h8=` precision highp float; varying vec2 vUv; uniform sampler2D texture; uniform vec2 px; uniform float m[9]; void main(void) { vec4 c11 = texture2D(texture, vUv - px); // top left vec4 c12 = texture2D(texture, vec2(vUv.x, vUv.y - px.y)); // top center vec4 c13 = texture2D(texture, vec2(vUv.x + px.x, vUv.y - px.y)); // top right vec4 c21 = texture2D(texture, vec2(vUv.x - px.x, vUv.y) ); // mid left vec4 c22 = texture2D(texture, vUv); // mid center vec4 c23 = texture2D(texture, vec2(vUv.x + px.x, vUv.y) ); // mid right vec4 c31 = texture2D(texture, vec2(vUv.x - px.x, vUv.y + px.y) ); // bottom left vec4 c32 = texture2D(texture, vec2(vUv.x, vUv.y + px.y) ); // bottom center vec4 c33 = texture2D(texture, vUv + px ); // bottom right gl_FragColor = c11 * m[0] + c12 * m[1] + c22 * m[2] + c21 * m[3] + c22 * m[4] + c23 * m[5] + c31 * m[6] + c32 * m[7] + c33 * m[8]; gl_FragColor.a = c22.a; } `;var Xx=(e,t,n)=>{let s=new RegExp("\\b"+t+" \\w+ (\\w+)","ig");e.replace(s,(r,a)=>(n[a]=0,r))},f8=class{constructor(t,n,s){he(this,"uniform",{});he(this,"attribute",{});he(this,"gl");he(this,"id");he(this,"compile",(t,n)=>{let s=this.gl.createShader(n);return s?(this.gl.shaderSource(s,t),this.gl.compileShader(s),this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS)?s:(Z(`filter: gl compile failed: ${this.gl.getShaderInfoLog(s)}`),null)):(Z("filter: could not create shader"),null)});this.gl=t;let r=this.compile(n,this.gl.VERTEX_SHADER),a=this.compile(s,this.gl.FRAGMENT_SHADER);if(this.id=this.gl.createProgram(),!(!r||!a)){if(!this.id){Z("filter: could not create webgl program");return}if(this.gl.attachShader(this.id,r),this.gl.attachShader(this.id,a),this.gl.linkProgram(this.id),!this.gl.getProgramParameter(this.id,this.gl.LINK_STATUS)){Z(`filter: gl link failed: ${this.gl.getProgramInfoLog(this.id)}`);return}this.gl.useProgram(this.id),Xx(n,"attribute",this.attribute);for(let o in this.attribute)this.attribute[o]=this.gl.getAttribLocation(this.id,o);Xx(n,"uniform",this.uniform),Xx(s,"uniform",this.uniform);for(let o in this.uniform)this.uniform[o]=this.gl.getUniformLocation(this.id,o)}}};function m8(){let e=0,t=null,n=!1,s=-1,r=[null,null],a=[],o=null,i=null,l=Zn(100,100),c={},u={INTERMEDIATE:1},d=l.getContext("webgl");if(this.gl=d,!d){Z("filter: cannot get webgl context");return}function p(x,y){if(!(x===l.width&&y===l.height)){if(l.width=x,l.height=y,!o){let b=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,-1,1,0,0,1,-1,1,1,1,1,1,0]);o=d.createBuffer(),d.bindBuffer(d.ARRAY_BUFFER,o),d.bufferData(d.ARRAY_BUFFER,b,d.STATIC_DRAW),d.pixelStorei(d.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0)}d.viewport(0,0,l.width,l.height),r=[null,null]}}function h(x,y){let b=d.createFramebuffer();d.bindFramebuffer(d.FRAMEBUFFER,b);let w=d.createRenderbuffer();d.bindRenderbuffer(d.RENDERBUFFER,w);let k=d.createTexture();return d.bindTexture(d.TEXTURE_2D,k),d.texImage2D(d.TEXTURE_2D,0,d.RGBA,x,y,0,d.RGBA,d.UNSIGNED_BYTE,null),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MAG_FILTER,d.LINEAR),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MIN_FILTER,d.LINEAR),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_2D,k,0),d.bindTexture(d.TEXTURE_2D,null),d.bindFramebuffer(d.FRAMEBUFFER,null),{fbo:b,texture:k}}function f(x){return r[x]=r[x]||h(l.width,l.height),r[x]}function m(x=0){if(!i)return;let y=null,b=null,w=!1;e===0?y=t:y=f(s).texture||null,e++,n&&!(x&u.INTERMEDIATE)?(b=null,w=e%2==0):(s=(s+1)%2,b=f(s).fbo||null),d.bindTexture(d.TEXTURE_2D,y),d.bindFramebuffer(d.FRAMEBUFFER,b),d.uniform1f(i.uniform.flipY,w?-1:1),d.drawArrays(d.TRIANGLES,0,6)}function g(x){if(c[x])return i=c[x],d.useProgram((i?i.id:null)||null),i;if(i=new f8(d,l8,x),!i)return Z("filter: could not get webgl program"),null;let y=Float32Array.BYTES_PER_ELEMENT,b=4*y;return d.enableVertexAttribArray(i.attribute.pos),d.vertexAttribPointer(i.attribute.pos,2,d.FLOAT,!1,b,0*y),d.enableVertexAttribArray(i.attribute.uv),d.vertexAttribPointer(i.attribute.uv,2,d.FLOAT,!1,b,2*y),c[x]=i,i}let A={colorMatrix:x=>{let y=new Float32Array(x);y[4]/=255,y[9]/=255,y[14]/=255,y[19]/=255;let b=y[18]===1&&y[3]===0&&y[8]===0&&y[13]===0&&y[15]===0&&y[16]===0&&y[17]===0&&y[19]===0?c8:u8,w=g(b);!w||(d.uniform1fv(w.uniform.m,y),m())},brightness:x=>{let y=(x||0)+1;A.colorMatrix([y,0,0,0,0,0,y,0,0,0,0,0,y,0,0,0,0,0,1,0])},saturation:x=>{let y=(x||0)*2/3+1,b=(y-1)*-.5;A.colorMatrix([y,b,b,0,0,b,y,b,0,0,b,b,y,0,0,0,0,0,1,0])},desaturate:()=>{A.saturation(-1)},contrast:x=>{let y=(x||0)+1,b=-128*(y-1);A.colorMatrix([y,0,0,0,b,0,y,0,0,b,0,0,y,0,b,0,0,0,1,0])},negative:()=>{A.contrast(-2)},hue:x=>{x=(x||0)/180*Math.PI;let y=Math.cos(x),b=Math.sin(x),w=.213,k=.715,I=.072;A.colorMatrix([w+y*(1-w)+b*-w,k+y*-k+b*-k,I+y*-I+b*(1-I),0,0,w+y*-w+b*.143,k+y*(1-k)+b*.14,I+y*-I+b*-.283,0,0,w+y*-w+b*-(1-w),k+y*-k+b*k,I+y*(1-I)+b*I,0,0,0,0,0,1,0])},desaturateLuminance:()=>{A.colorMatrix([.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,0,0,0,1,0])},sepia:()=>{A.colorMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0])},brownie:()=>{A.colorMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0])},vintagePinhole:()=>{A.colorMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0])},kodachrome:()=>{A.colorMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0])},technicolor:()=>{A.colorMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0])},polaroid:()=>{A.colorMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0])},shiftToBGR:()=>{A.colorMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0])},convolution:x=>{let y=new Float32Array(x),b=1/l.width,w=1/l.height,k=g(h8);!k||(d.uniform1fv(k.uniform.m,y),d.uniform2f(k.uniform.px,b,w),m())},detectEdges:()=>{A.convolution.call(this,[0,1,0,1,-4,1,0,1,0])},sobelX:()=>{A.convolution.call(this,[-1,0,1,-2,0,2,-1,0,1])},sobelY:()=>{A.convolution.call(this,[-1,-2,-1,0,0,0,1,2,1])},sharpen:x=>{let y=x||1;A.convolution.call(this,[0,-1*y,0,-1*y,1+4*y,-1*y,0,-1*y,0])},emboss:x=>{let y=x||1;A.convolution.call(this,[-2*y,-1*y,0,-1*y,1,1*y,0,1*y,2*y])},blur:x=>{let y=x/7/l.width,b=x/7/l.height,w=g(p8);!w||(d.uniform2f(w.uniform.px,0,b),m(u.INTERMEDIATE),d.uniform2f(w.uniform.px,y,0),m())},pixelate:x=>{let y=x/l.width,b=x/l.height,w=g(d8);!w||(d.uniform2f(w.uniform.size,y,b),m())}};this.add=function(x){let y=Array.prototype.slice.call(arguments,1),b=A[x];a.push({func:b,args:y})},this.reset=function(){a=[]},this.get=function(){return a},this.apply=function(x){p(x.width,x.height),e=0,t||(t=d.createTexture()),d.bindTexture(d.TEXTURE_2D,t),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MIN_FILTER,d.NEAREST),d.texParameteri(d.TEXTURE_2D,d.TEXTURE_MAG_FILTER,d.NEAREST),d.texImage2D(d.TEXTURE_2D,0,d.RGBA,d.RGBA,d.UNSIGNED_BYTE,x);for(let y=0;yh.data())),o=.99*Math.max(a[0][0],a[1][0],a[2][0]),i=[fe(n[0],s[0]),fe(n[1],s[1]),fe(n[2],s[2])],l=[fe(r[0],s[0]),fe(r[1],s[1]),fe(r[2],s[2])],c=[ge(o,l[0]),ge(o,l[1]),ge(o,l[2])],u=[L(i[0],c[0]),L(i[1],c[1]),L(i[2],c[2])],d=yn([u[0],u[1],u[2]],2),p=H(d,[1,t.shape[0],t.shape[1],3]);return te([...n,...s,...r,...i,...l,...c,...u,d,t]),p}var c0=2048,it=null,ln=null,Cc=null,It,da={inputSum:0,cacheDiff:1,sumMethod:0,inputTensor:void 0};function Zn(e,t){let n;if(de.browser)if(de.worker){if(typeof OffscreenCanvas=="undefined")throw new Error("canvas error: attempted to run in web worker but OffscreenCanvas is not supported");n=new OffscreenCanvas(e,t)}else{if(typeof document=="undefined")throw new Error("canvas error: attempted to run in browser but DOM is not defined");n=document.createElement("canvas"),n.width=e,n.height=t}else typeof de.Canvas!="undefined"?n=new de.Canvas(e,t):typeof globalThis.Canvas!="undefined"&&(n=new globalThis.Canvas(e,t));return n}function Kx(e,t){let n=t||Zn(e.width,e.height);return n.getContext("2d").drawImage(e,0,0),n}async function Tc(e,t,n=!0){if(!e)return t.debug&&Z("input error: input is missing"),{tensor:null,canvas:null};if(!(e instanceof Je)&&!(typeof Image!="undefined"&&e instanceof Image)&&!(typeof de.Canvas!="undefined"&&e instanceof de.Canvas)&&!(typeof globalThis.Canvas!="undefined"&&e instanceof globalThis.Canvas)&&!(typeof ImageData!="undefined"&&e instanceof ImageData)&&!(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)&&!(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)&&!(typeof HTMLMediaElement!="undefined"&&e instanceof HTMLMediaElement)&&!(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)&&!(typeof HTMLCanvasElement!="undefined"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas!="undefined"&&e instanceof OffscreenCanvas))throw new Error("input error: type is not recognized");if(e instanceof Je){let s=null;if(e.isDisposedInternal)throw new Error("input error: attempted to use tensor but it is disposed");if(!e.shape)throw new Error("input error: attempted to use tensor without a shape");if(e.shape.length===3){if(e.shape[2]===3)s=Kt(e,0);else if(e.shape[2]===4){let r=fl(e,[0,0,0],[-1,-1,3]);s=Kt(r,0),te(r)}}else e.shape.length===4&&(e.shape[3]===3?s=Wn(e):e.shape[3]===4&&(s=ml(e,[0,0,0,0],[-1,-1,-1,3])));if(s==null||s.shape.length!==4||s.shape[0]!==1||s.shape[3]!==3)throw new Error(`input error: attempted to use tensor with unrecognized shape: ${e.shape}`);if(s.dtype==="int32"){let r=me(s,"float32");te(s),s=r}return{tensor:s,canvas:t.filter.return?ln:null}}else{if(typeof e.readyState!="undefined"&&e.readyState<=2)return t.debug&&Z("input stream is not ready"),{tensor:null,canvas:it};let s=e.naturalWidth||e.videoWidth||e.width||e.shape&&e.shape[1]>0,r=e.naturalHeight||e.videoHeight||e.height||e.shape&&e.shape[2]>0;if(!s||!r)return t.debug&&Z("cannot determine input dimensions"),{tensor:null,canvas:it};let a=s,o=r;if(a>c0&&(a=c0,o=Math.trunc(a*r/s)),o>c0&&(o=c0,a=Math.trunc(o*s/r)),(t.filter.width||0)>0?a=t.filter.width:(t.filter.height||0)>0&&(a=s*((t.filter.height||0)/r)),(t.filter.height||0)>0?o=t.filter.height:(t.filter.width||0)>0&&(o=r*((t.filter.width||0)/s)),!a||!o)throw new Error("input error: cannot determine dimension");(!it||(it==null?void 0:it.width)!==a||(it==null?void 0:it.height)!==o)&&(it=Zn(a,o));let i=it.getContext("2d");if(typeof ImageData!="undefined"&&e instanceof ImageData?i.putImageData(e,0,0):t.filter.flip&&typeof i.translate!="undefined"?(i.translate(s,0),i.scale(-1,1),i.drawImage(e,0,0,s,r,0,0,it==null?void 0:it.width,it==null?void 0:it.height),i.setTransform(1,0,0,1,0,0)):i.drawImage(e,0,0,s,r,0,0,it==null?void 0:it.width,it==null?void 0:it.height),(!ln||it.width!==ln.width||(it==null?void 0:it.height)!==(ln==null?void 0:ln.height))&&(ln=Zn(it.width,it.height)),t.filter.enabled&&de.webgl.supported){if(It||(It=de.browser?new m8:null),de.filter=!!It,!It||!It.add)return t.debug&&Z("input process error: cannot initialize filters"),{tensor:null,canvas:it};It.reset(),t.filter.brightness!==0&&It.add("brightness",t.filter.brightness),t.filter.contrast!==0&&It.add("contrast",t.filter.contrast),t.filter.sharpness!==0&&It.add("sharpen",t.filter.sharpness),t.filter.blur!==0&&It.add("blur",t.filter.blur),t.filter.saturation!==0&&It.add("saturation",t.filter.saturation),t.filter.hue!==0&&It.add("hue",t.filter.hue),t.filter.negative&&It.add("negative"),t.filter.sepia&&It.add("sepia"),t.filter.vintage&&It.add("brownie"),t.filter.sepia&&It.add("sepia"),t.filter.kodachrome&&It.add("kodachrome"),t.filter.technicolor&&It.add("technicolor"),t.filter.polaroid&&It.add("polaroid"),t.filter.pixelate!==0&&It.add("pixelate",t.filter.pixelate),It.get()>0?ln=It.apply(it):ln=It.draw(it)}else Kx(it,ln),It&&(It=null),de.filter=!!It;if(!n)return{tensor:null,canvas:ln};if(!ln)throw new Error("canvas error: cannot create output");let l,c=3;if(typeof ImageData!="undefined"&&e instanceof ImageData||e.data&&e.width&&e.height)if(de.browser&&Ks)l=Ks?Ks.fromPixels(e):null;else{c=e.data.length/e.height/e.width;let p=new Uint8Array(e.data.buffer);l=ut(p,[e.height,e.width,c],"int32")}else if((!Cc||ln.width!==Cc.width||ln.height!==Cc.height)&&(Cc=Zn(ln.width,ln.height)),Ks&&de.browser)t.backend==="webgl"||t.backend==="humangl"||t.backend==="webgpu"?l=Ks.fromPixels(ln):(Cc=Kx(ln),l=Ks.fromPixels(Cc));else{let f=Kx(ln).getContext("2d").getImageData(0,0,a,o);c=f.data.length/a/o;let m=new Uint8Array(f.data.buffer);l=ut(m,[a,o,c])}if(c===4){let p=fl(l,[0,0,0],[-1,-1,3]);te(l),l=p}if(!l)throw new Error("input error: cannot create tensor");let u=me(l,"float32"),d=t.filter.equalization?await u0(u):Kt(u,0);return te([l,u]),{tensor:d,canvas:t.filter.return?ln:null}}}async function g8(e,t){let n=!1;if(e.cacheSensitivity===0||!t.shape||t.shape.length!==4||t.shape[1]>2048||t.shape[2]>2048)return n;if(!da.inputTensor)da.inputTensor=Wn(t);else if(da.inputTensor.shape[1]!==t.shape[1]||da.inputTensor.shape[2]!==t.shape[2])te(da.inputTensor),da.inputTensor=Wn(t);else{let s={};s.diff=fe(t,da.inputTensor),s.squared=L(s.diff,s.diff),s.sum=ke(s.squared);let a=(await s.sum.data())[0]/(t.shape[1]||1)/(t.shape[2]||1)/255/3;te([da.inputTensor,s.diff,s.squared,s.sum]),da.inputTensor=Wn(t),n=a<=e.cacheSensitivity}return n}async function A8(e,t,n){let s={};if(!t||!n||t.shape.length!==4||t.shape.length!==n.shape.length)return e.debug||Z("invalid input tensor or tensor shapes do not match:",t.shape,n.shape),0;if(t.shape[0]!==1||n.shape[0]!==1||t.shape[3]!==3||n.shape[3]!==3)return e.debug||Z("input tensors must be of shape [1, height, width, 3]:",t.shape,n.shape),0;s.input1=Wn(t),s.input2=t.shape[1]!==n.shape[1]||t.shape[2]!==n.shape[2]?Ce.resizeBilinear(n,[t.shape[1],t.shape[2]]):Wn(n),s.diff=fe(s.input1,s.input2),s.squared=L(s.diff,s.diff),s.sum=ke(s.squared);let a=(await s.sum.data())[0]/(t.shape[1]||1)/(t.shape[2]||1)/255/3;return te([s.input1,s.input2,s.diff,s.squared,s.sum]),a}var y8=class{constructor(){he(this,"browser");he(this,"node");he(this,"worker");he(this,"platform","");he(this,"agent","");he(this,"backends",[]);he(this,"initial");he(this,"filter");he(this,"tfjs");he(this,"offscreen");he(this,"perfadd",!1);he(this,"wasm",{supported:void 0,backend:void 0,simd:void 0,multithread:void 0});he(this,"webgl",{supported:void 0,backend:void 0,version:void 0,renderer:void 0});he(this,"webgpu",{supported:void 0,backend:void 0,adapter:void 0});he(this,"cpu",{model:void 0,flags:[]});he(this,"kernels",[]);he(this,"Canvas");he(this,"Image");he(this,"ImageData");if(this.browser=typeof navigator!="undefined",this.node=typeof process!="undefined",this.tfjs={version:Pp},this.offscreen=typeof OffscreenCanvas!="undefined",this.initial=!0,this.worker=this.browser&&this.offscreen?typeof WorkerGlobalScope!="undefined":void 0,typeof navigator!="undefined"){let t=navigator.userAgent.match(/\(([^()]+)\)/g);if(t&&t[0]){let n=t[0].match(/\(([^()]+)\)/g);this.platform=n&&n[0]?n[0].replace(/\(|\)/g,""):"",this.agent=navigator.userAgent.replace(t[0],""),this.platform[1]&&(this.agent=this.agent.replace(t[1],"")),this.agent=this.agent.replace(/ /g," ")}}else typeof process!="undefined"&&(this.platform=`${process.platform} ${process.arch}`,this.agent=`NodeJS ${process.version}`)}async updateBackend(){this.backends=Object.keys(as().registryFactory),this.wasm.supported=typeof WebAssembly!="undefined",this.wasm.backend=this.backends.includes("wasm"),this.wasm.supported&&this.wasm.backend&&Rs()==="wasm"&&(this.wasm.simd=await Y().getAsync("WASM_HAS_SIMD_SUPPORT"),this.wasm.multithread=await Y().getAsync("WASM_HAS_MULTITHREAD_SUPPORT"));let t=Zn(100,100),n=t?t.getContext("webgl2"):void 0;if(this.webgl.supported=typeof n!="undefined",this.webgl.backend=this.backends.includes("webgl"),this.webgl.supported&&this.webgl.backend&&(Rs()==="webgl"||Rs()==="humangl")){let s=Dr().gpgpu!=="undefined"?await Dr().getGPGPUContext().gl:null;s&&(this.webgl.version=s.getParameter(s.VERSION),this.webgl.renderer=s.getParameter(s.RENDERER))}this.webgpu.supported=this.browser&&typeof navigator.gpu!="undefined",this.webgpu.backend=this.backends.includes("webgpu");try{this.webgpu.supported&&(this.webgpu.adapter=(await navigator.gpu.requestAdapter()).name),this.kernels=Jr(Rs()).map(s=>s.kernelName.toLowerCase())}catch(s){this.webgpu.supported=!1}}async updateCPU(){let t={model:"",flags:[]};if(this.node&&this.platform.startsWith("linux")){let n=Ia("fs");try{let s=n.readFileSync("/proc/cpuinfo").toString();for(let r of s.split(` `))r.startsWith("model name")&&(t.model=r.match(/:(.*)/g)[0].replace(":","").trim()),r.startsWith("flags")&&(t.flags=r.match(/:(.*)/g)[0].replace(":","").trim().split(" ").sort())}catch(s){}}this.cpu?this.cpu=t:Object.defineProperty(this,"cpu",{value:t})}},de=new y8;var Zx="2.5.2";var ds,Yx=[],c2e=["white","black","asian","indian","other"],d2e=[15,23,28,35.5,45.5,55.5,65],x8=0,b8=0,Jx=Number.MAX_SAFE_INTEGER;async function v8(e){return de.initial&&(ds=null),ds?e.debug&&Z("cached model:",ds.modelUrl):(ds=await Be(We(e.modelBasePath,e.face.gear.modelPath)),!ds||!ds.modelUrl?Z("load model failed:",e.face.gear.modelPath):e.debug&&Z("load model:",ds.modelUrl)),ds}async function Qx(e,t,n,s){var o,i;if(!ds)return{age:0,gender:"unknown",genderScore:0,race:[]};let r=Jx<(((o=t.face.gear)==null?void 0:o.skipFrames)||0),a=(((i=t.face.gear)==null?void 0:i.skipTime)||0)>ie()-b8;return t.skipAllowed&&a&&r&&x8===s&&Yx[n]?(Jx++,Yx[n]):(Jx=0,new Promise(async l=>{var A,x;if(!(ds==null?void 0:ds.inputs[0].shape))return;let c={},u=[[0,.1,.9,.9]];c.resize=Ce.cropAndResize(e,u,[0],[ds.inputs[0].shape[2],ds.inputs[0].shape[1]]);let d={age:0,gender:"unknown",genderScore:0,race:[]};((A=t.face.gear)==null?void 0:A.enabled)&&([c.age,c.gender,c.race]=ds.execute(c.resize,["age_output","gender_output","race_output"]));let p=await c.gender.data();d.gender=p[0]>p[1]?"male":"female",d.genderScore=Math.round(100*(p[0]>p[1]?p[0]:p[1]))/100;let h=await c.race.data();for(let y=0;y(((x=t.face.gear)==null?void 0:x.minConfidence)||.2)&&d.race.push({score:Math.round(100*h[y])/100,race:c2e[y]});d.race.sort((y,b)=>b.score-y.score);let m=Array.from(await c.age.data()).map((y,b)=>[d2e[b],y]).sort((y,b)=>b[1]-y[1]),g=m[0][0];for(let y=1;yte(c[y])),Yx[n]=d,x8=s,b8=ie(),l(d)}))}var Yn=Ie(255,"float32"),d0=Ie(1,"float32"),Nc=Ie(2,"float32"),Ec=Ie(.5,"float32"),p0=Ie(127.5,"float32"),w8=Vt([.2989,.587,.114],"float32");var Pn,h0=[],k8=0,S8=0,eb=Number.MAX_SAFE_INTEGER;async function I8(e){return de.initial&&(Pn=null),Pn?e.debug&&Z("cached model:",Pn.modelUrl):(Pn=await Be(We(e.modelBasePath,e.face.ssrnet.modelPathAge)),!Pn||!Pn.modelUrl?Z("load model failed:",e.face.ssrnet.modelPathAge):e.debug&&Z("load model:",Pn.modelUrl)),Pn}async function tb(e,t,n,s){var o,i,l,c;if(!Pn)return{age:0};let r=eb<(((o=t.face.ssrnet)==null?void 0:o.skipFrames)||0),a=(((i=t.face.ssrnet)==null?void 0:i.skipTime)||0)>ie()-S8;return t.skipAllowed&&r&&a&&k8===s&&((l=h0[n])==null?void 0:l.age)&&((c=h0[n])==null?void 0:c.age)>0?(eb++,h0[n]):(eb=0,new Promise(async u=>{if(!(Pn==null?void 0:Pn.inputs)||!Pn.inputs[0]||!Pn.inputs[0].shape)return;let d={};d.resize=Ce.resizeBilinear(e,[Pn.inputs[0].shape[2],Pn.inputs[0].shape[1]],!1),d.enhance=L(d.resize,Yn);let p={age:0};if(t.face.ssrnet.enabled&&(d.age=Pn.execute(d.enhance)),d.age){let h=await d.age.data();p.age=Math.trunc(10*h[0])/10}Object.keys(d).forEach(h=>te(d[h])),h0[n]=p,k8=s,S8=ie(),u(p)}))}var ps,f0=[],C8=0,T8=0,nb=Number.MAX_SAFE_INTEGER,sb=[.2989,.587,.114];async function N8(e){return de.initial&&(ps=null),ps?e.debug&&Z("cached model:",ps.modelUrl):(ps=await Be(We(e.modelBasePath,e.face.ssrnet.modelPathGender)),!ps||!ps.modelUrl?Z("load model failed:",e.face.ssrnet.modelPathGender):e.debug&&Z("load model:",ps.modelUrl)),ps}async function rb(e,t,n,s){var o,i,l,c;if(!ps)return{gender:"unknown",genderScore:0};let r=nb<(((o=t.face.ssrnet)==null?void 0:o.skipFrames)||0),a=(((i=t.face.ssrnet)==null?void 0:i.skipTime)||0)>ie()-T8;return t.skipAllowed&&r&&a&&C8===s&&((l=f0[n])==null?void 0:l.gender)&&((c=f0[n])==null?void 0:c.genderScore)>0?(nb++,f0[n]):(nb=0,new Promise(async u=>{if(!(ps==null?void 0:ps.inputs[0].shape))return;let d={};d.resize=Ce.resizeBilinear(e,[ps.inputs[0].shape[2],ps.inputs[0].shape[1]],!1),d.enhance=X(()=>{let[f,m,g]=sn(d.resize,3,3),A=L(f,sb[0]),x=L(m,sb[1]),y=L(g,sb[2]),b=hf([A,x,y]);return L(fe(b,Ec),2)});let p={gender:"",genderScore:0};t.face.ssrnet.enabled&&(d.gender=ps.execute(d.enhance));let h=await d.gender.data();p.gender=h[0]>h[1]?"female":"male",p.genderScore=h[0]>h[1]?Math.trunc(100*h[0])/100:Math.trunc(100*h[1])/100,Object.keys(d).forEach(f=>te(d[f])),f0[n]=p,C8=s,T8=ie(),u(p)}))}var un,m0=[],ab=Number.MAX_SAFE_INTEGER,E8=0,R8=0;async function $8(e){var t,n;return de.initial&&(un=null),un?e.debug&&Z("cached model:",un.modelUrl):(un=await Be(We(e.modelBasePath,((t=e.face.antispoof)==null?void 0:t.modelPath)||"")),!un||!un.modelUrl?Z("load model failed:",(n=e.face.antispoof)==null?void 0:n.modelPath):e.debug&&Z("load model:",un.modelUrl)),un}async function ob(e,t,n,s){var o,i;if(!un)return 0;let r=(((o=t.face.antispoof)==null?void 0:o.skipTime)||0)>ie()-R8,a=ab<(((i=t.face.antispoof)==null?void 0:i.skipFrames)||0);return t.skipAllowed&&r&&a&&E8===s&&m0[n]?(ab++,m0[n]):(ab=0,new Promise(async l=>{let c=Ce.resizeBilinear(e,[(un==null?void 0:un.inputs[0].shape)?un.inputs[0].shape[2]:0,(un==null?void 0:un.inputs[0].shape)?un.inputs[0].shape[1]:0],!1),u=un==null?void 0:un.execute(c),d=(await u.data())[0];m0[n]=Math.round(100*d)/100,E8=s,R8=ie(),te([c,u]),l(m0[n])}))}var rr={silhouette:[10,338,297,332,284,251,389,356,454,323,361,288,397,365,379,378,400,377,152,148,176,149,150,136,172,58,132,93,234,127,162,21,54,103,67,109],lipsUpperOuter:[61,185,40,39,37,0,267,269,270,409,291],lipsLowerOuter:[146,91,181,84,17,314,405,321,375,291],lipsUpperInner:[78,191,80,81,82,13,312,311,310,415,308],lipsLowerInner:[78,95,88,178,87,14,317,402,318,324,308],rightEyeUpper0:[246,161,160,159,158,157,173],rightEyeLower0:[33,7,163,144,145,153,154,155,133],rightEyeUpper1:[247,30,29,27,28,56,190],rightEyeLower1:[130,25,110,24,23,22,26,112,243],rightEyeUpper2:[113,225,224,223,222,221,189],rightEyeLower2:[226,31,228,229,230,231,232,233,244],rightEyeLower3:[143,111,117,118,119,120,121,128,245],rightEyebrowUpper:[156,70,63,105,66,107,55,193],rightEyebrowLower:[35,124,46,53,52,65],rightEyeIris:[473,474,475,476,477],leftEyeUpper0:[466,388,387,386,385,384,398],leftEyeLower0:[263,249,390,373,374,380,381,382,362],leftEyeUpper1:[467,260,259,257,258,286,414],leftEyeLower1:[359,255,339,254,253,252,256,341,463],leftEyeUpper2:[342,445,444,443,442,441,413],leftEyeLower2:[446,261,448,449,450,451,452,453,464],leftEyeLower3:[372,340,346,347,348,349,350,357,465],leftEyebrowUpper:[383,300,293,334,296,336,285,417],leftEyebrowLower:[265,353,276,283,282,295],leftEyeIris:[468,469,470,471,472],midwayBetweenEyes:[168],noseTip:[1],noseBottom:[2],noseRightCorner:[98],noseLeftCorner:[327],rightCheek:[205],leftCheek:[425]},ib={count:468,mouth:13,symmetryLine:[13,rr.midwayBetweenEyes[0]]},Fp={leftEye:0,rightEye:1,nose:2,mouth:3,leftEar:4,rightEar:5,symmetryLine:[3,2]},lb=[{key:"EyeUpper0",indices:[9,10,11,12,13,14,15]},{key:"EyeUpper1",indices:[25,26,27,28,29,30,31]},{key:"EyeUpper2",indices:[41,42,43,44,45,46,47]},{key:"EyeLower0",indices:[0,1,2,3,4,5,6,7,8]},{key:"EyeLower1",indices:[16,17,18,19,20,21,22,23,24]},{key:"EyeLower2",indices:[32,33,34,35,36,37,38,39,40]},{key:"EyeLower3",indices:[54,55,56,57,58,59,60,61,62]}],Op=[[.499976992607117,.652534008026123],[.500025987625122,.547487020492554],[.499974012374878,.602371990680695],[.482113003730774,.471979022026062],[.500150978565216,.527155995368958],[.499909996986389,.498252987861633],[.499523013830185,.40106201171875],[.289712011814117,.380764007568359],[.499954998493195,.312398016452789],[.499987006187439,.269918978214264],[.500023007392883,.107050001621246],[.500023007392883,.666234016418457],[.5000159740448,.679224014282227],[.500023007392883,.692348003387451],[.499976992607117,.695277988910675],[.499976992607117,.70593398809433],[.499976992607117,.719385027885437],[.499976992607117,.737019002437592],[.499967992305756,.781370997428894],[.499816000461578,.562981009483337],[.473773002624512,.573909997940063],[.104906998574734,.254140973091125],[.365929991006851,.409575998783112],[.338757991790771,.41302502155304],[.311120003461838,.409460008144379],[.274657994508743,.389131009578705],[.393361985683441,.403706014156342],[.345234006643295,.344011008739471],[.370094001293182,.346076011657715],[.319321990013123,.347265005111694],[.297903001308441,.353591024875641],[.24779200553894,.410809993743896],[.396889001131058,.842755019664764],[.280097991228104,.375599980354309],[.106310002505779,.399955987930298],[.2099249958992,.391353011131287],[.355807989835739,.534406006336212],[.471751004457474,.65040397644043],[.474155008792877,.680191993713379],[.439785003662109,.657229006290436],[.414617002010345,.66654098033905],[.450374007225037,.680860996246338],[.428770989179611,.682690978050232],[.374971002340317,.727805018424988],[.486716985702515,.547628998756409],[.485300987958908,.527395009994507],[.257764995098114,.314490020275116],[.401223003864288,.455172002315521],[.429818987846375,.548614978790283],[.421351999044418,.533740997314453],[.276895999908447,.532056987285614],[.483370006084442,.499586999416351],[.33721199631691,.282882988452911],[.296391993761063,.293242990970612],[.169294998049736,.193813979625702],[.447580009698868,.302609980106354],[.392390012741089,.353887975215912],[.354490011930466,.696784019470215],[.067304998636246,.730105042457581],[.442739009857178,.572826027870178],[.457098007202148,.584792017936707],[.381974011659622,.694710969924927],[.392388999462128,.694203019142151],[.277076005935669,.271932005882263],[.422551989555359,.563233017921448],[.385919004678726,.281364023685455],[.383103013038635,.255840003490448],[.331431001424789,.119714021682739],[.229923993349075,.232002973556519],[.364500999450684,.189113974571228],[.229622006416321,.299540996551514],[.173287004232407,.278747975826263],[.472878992557526,.666198015213013],[.446828007698059,.668527007102966],[.422762006521225,.673889994621277],[.445307999849319,.580065965652466],[.388103008270264,.693961024284363],[.403039008378983,.706539988517761],[.403629004955292,.693953037261963],[.460041999816895,.557139039039612],[.431158006191254,.692366003990173],[.452181994915009,.692366003990173],[.475387006998062,.692366003990173],[.465828001499176,.779190003871918],[.472328990697861,.736225962638855],[.473087012767792,.717857003211975],[.473122000694275,.704625964164734],[.473033010959625,.695277988910675],[.427942007780075,.695277988910675],[.426479011774063,.703539967536926],[.423162013292313,.711845993995667],[.4183090031147,.720062971115112],[.390094995498657,.639572978019714],[.013953999616206,.560034036636353],[.499913990497589,.58014702796936],[.413199990987778,.69539999961853],[.409626007080078,.701822996139526],[.468080013990402,.601534962654114],[.422728985548019,.585985004901886],[.463079988956451,.593783974647522],[.37211999297142,.47341400384903],[.334562003612518,.496073007583618],[.411671012639999,.546965003013611],[.242175996303558,.14767599105835],[.290776997804642,.201445996761322],[.327338010072708,.256527006626129],[.399509996175766,.748921036720276],[.441727995872498,.261676013469696],[.429764986038208,.187834024429321],[.412198007106781,.108901023864746],[.288955003023148,.398952007293701],[.218936994671822,.435410976409912],[.41278201341629,.398970007896423],[.257135003805161,.355440020561218],[.427684992551804,.437960982322693],[.448339998722076,.536936044692993],[.178560003638268,.45755398273468],[.247308000922203,.457193970680237],[.286267012357712,.467674970626831],[.332827985286713,.460712015628815],[.368755996227264,.447206974029541],[.398963987827301,.432654976844788],[.476410001516342,.405806005001068],[.189241006970406,.523923993110657],[.228962004184723,.348950982093811],[.490725994110107,.562400996685028],[.404670000076294,.485132992267609],[.019469000399113,.401564002037048],[.426243007183075,.420431017875671],[.396993011236191,.548797011375427],[.266469985246658,.376977026462555],[.439121007919312,.51895797252655],[.032313998788595,.644356966018677],[.419054001569748,.387154996395111],[.462783008813858,.505746960639954],[.238978996872902,.779744982719421],[.198220998048782,.831938028335571],[.107550002634525,.540755033493042],[.183610007166862,.740257024765015],[.134409993886948,.333683013916016],[.385764002799988,.883153975009918],[.490967005491257,.579378008842468],[.382384985685349,.508572995662689],[.174399003386497,.397670984268188],[.318785011768341,.39623498916626],[.343364000320435,.400596976280212],[.396100014448166,.710216999053955],[.187885001301765,.588537991046906],[.430987000465393,.944064974784851],[.318993002176285,.898285031318665],[.266247987747192,.869701027870178],[.500023007392883,.190576016902924],[.499976992607117,.954452991485596],[.366169989109039,.398822009563446],[.393207013607025,.39553701877594],[.410373002290726,.391080021858215],[.194993004202843,.342101991176605],[.388664990663528,.362284004688263],[.365961998701096,.355970978736877],[.343364000320435,.355356991291046],[.318785011768341,.35834002494812],[.301414996385574,.363156020641327],[.058132998645306,.319076001644135],[.301414996385574,.387449026107788],[.499987989664078,.618434011936188],[.415838003158569,.624195992946625],[.445681989192963,.566076993942261],[.465844005346298,.620640993118286],[.49992299079895,.351523995399475],[.288718998432159,.819945991039276],[.335278987884521,.852819979190826],[.440512001514435,.902418971061707],[.128294005990028,.791940987110138],[.408771991729736,.373893976211548],[.455606997013092,.451801002025604],[.499877005815506,.908990025520325],[.375436991453171,.924192011356354],[.11421000212431,.615022003650665],[.448662012815475,.695277988910675],[.4480200111866,.704632043838501],[.447111994028091,.715808033943176],[.444831997156143,.730794012546539],[.430011987686157,.766808986663818],[.406787008047104,.685672998428345],[.400738000869751,.681069016456604],[.392399996519089,.677703022956848],[.367855995893478,.663918972015381],[.247923001646996,.601333022117615],[.452769994735718,.420849978923798],[.43639200925827,.359887003898621],[.416164010763168,.368713974952698],[.413385987281799,.692366003990173],[.228018000721931,.683571994304657],[.468268007040024,.352671027183533],[.411361992359161,.804327011108398],[.499989002943039,.469825029373169],[.479153990745544,.442654013633728],[.499974012374878,.439637005329132],[.432112008333206,.493588984012604],[.499886006116867,.866917014122009],[.49991300702095,.821729004383087],[.456548988819122,.819200992584229],[.344549000263214,.745438992977142],[.37890899181366,.574010014533997],[.374292999505997,.780184984207153],[.319687992334366,.570737957954407],[.357154995203018,.604269981384277],[.295284003019333,.621580958366394],[.447750002145767,.862477004528046],[.410986006259918,.508723020553589],[.31395098567009,.775308012962341],[.354128003120422,.812552988529205],[.324548006057739,.703992962837219],[.189096003770828,.646299958229065],[.279776990413666,.71465802192688],[.1338230073452,.682700991630554],[.336768001317978,.644733011722565],[.429883986711502,.466521978378296],[.455527991056442,.548622965812683],[.437114000320435,.558896005153656],[.467287987470627,.529924988746643],[.414712011814117,.335219979286194],[.37704598903656,.322777986526489],[.344107985496521,.320150971412659],[.312875986099243,.32233202457428],[.283526003360748,.333190023899078],[.241245999932289,.382785975933075],[.102986000478268,.468762993812561],[.267612010240555,.424560010433197],[.297879010438919,.433175981044769],[.333433985710144,.433878004550934],[.366427004337311,.426115989685059],[.396012008190155,.416696012020111],[.420121014118195,.41022801399231],[.007561000064015,.480777025222778],[.432949006557465,.569517970085144],[.458638995885849,.479089021682739],[.473466008901596,.545744001865387],[.476087987422943,.563830018043518],[.468472003936768,.555056989192963],[.433990985155106,.582361996173859],[.483518004417419,.562983989715576],[.482482999563217,.57784903049469],[.42645001411438,.389798998832703],[.438998997211456,.39649498462677],[.450067013502121,.400434017181396],[.289712011814117,.368252992630005],[.276670008897781,.363372981548309],[.517862021923065,.471948027610779],[.710287988185883,.380764007568359],[.526226997375488,.573909997940063],[.895093023777008,.254140973091125],[.634069979190826,.409575998783112],[.661242008209229,.41302502155304],[.688880026340485,.409460008144379],[.725341975688934,.389131009578705],[.606630027294159,.40370500087738],[.654766023159027,.344011008739471],[.629905998706818,.346076011657715],[.680678009986877,.347265005111694],[.702096998691559,.353591024875641],[.75221198797226,.410804986953735],[.602918028831482,.842862963676453],[.719901978969574,.375599980354309],[.893692970275879,.399959981441498],[.790081977844238,.391354024410248],[.643998026847839,.534487962722778],[.528249025344849,.65040397644043],[.525849997997284,.680191040039062],[.560214996337891,.657229006290436],[.585384011268616,.66654098033905],[.549625992774963,.680860996246338],[.57122802734375,.682691991329193],[.624852001667023,.72809898853302],[.513050019741058,.547281980514526],[.51509702205658,.527251958847046],[.742246985435486,.314507007598877],[.598631024360657,.454979002475739],[.570338010787964,.548575043678284],[.578631997108459,.533622980117798],[.723087012767792,.532054007053375],[.516445994377136,.499638974666595],[.662801027297974,.282917976379395],[.70362401008606,.293271005153656],[.830704987049103,.193813979625702],[.552385985851288,.302568018436432],[.607609987258911,.353887975215912],[.645429015159607,.696707010269165],[.932694971561432,.730105042457581],[.557260990142822,.572826027870178],[.542901992797852,.584792017936707],[.6180260181427,.694710969924927],[.607590973377228,.694203019142151],[.722943007946014,.271963000297546],[.577413976192474,.563166975975037],[.614082992076874,.281386971473694],[.616907000541687,.255886018276215],[.668509006500244,.119913995265961],[.770092010498047,.232020974159241],[.635536015033722,.189248979091644],[.77039098739624,.299556016921997],[.826722025871277,.278755009174347],[.527121007442474,.666198015213013],[.553171992301941,.668527007102966],[.577238023281097,.673889994621277],[.554691970348358,.580065965652466],[.611896991729736,.693961024284363],[.59696102142334,.706539988517761],[.596370995044708,.693953037261963],[.539958000183105,.557139039039612],[.568841993808746,.692366003990173],[.547818005084991,.692366003990173],[.52461302280426,.692366003990173],[.534089982509613,.779141008853912],[.527670979499817,.736225962638855],[.526912987232208,.717857003211975],[.526877999305725,.704625964164734],[.526966989040375,.695277988910675],[.572058022022247,.695277988910675],[.573521018028259,.703539967536926],[.57683801651001,.711845993995667],[.581691026687622,.720062971115112],[.609944999217987,.639909982681274],[.986046016216278,.560034036636353],[.5867999792099,.69539999961853],[.590372025966644,.701822996139526],[.531915009021759,.601536989212036],[.577268004417419,.585934996604919],[.536915004253387,.593786001205444],[.627542972564697,.473352015018463],[.665585994720459,.495950996875763],[.588353991508484,.546862006187439],[.757824003696442,.14767599105835],[.709249973297119,.201507985591888],[.672684013843536,.256581008434296],[.600408971309662,.74900496006012],[.55826598405838,.261672019958496],[.570303976535797,.187870979309082],[.588165998458862,.109044015407562],[.711045026779175,.398952007293701],[.781069993972778,.435405015945435],[.587247014045715,.398931980133057],[.742869973182678,.355445981025696],[.572156012058258,.437651991844177],[.55186802148819,.536570012569427],[.821442008018494,.457556009292603],[.752701997756958,.457181990146637],[.71375697851181,.467626988887787],[.66711300611496,.460672974586487],[.631101012229919,.447153985500336],[.6008620262146,.432473003864288],[.523481011390686,.405627012252808],[.810747981071472,.523926019668579],[.771045982837677,.348959028720856],[.509127020835876,.562718033790588],[.595292985439301,.485023975372314],[.980530977249146,.401564002037048],[.573499977588654,.420000016689301],[.602994978427887,.548687994480133],[.733529984951019,.376977026462555],[.560611009597778,.519016981124878],[.967685997486115,.644356966018677],[.580985009670258,.387160003185272],[.537728011608124,.505385041236877],[.760966002941132,.779752969741821],[.801778972148895,.831938028335571],[.892440974712372,.54076099395752],[.816350996494293,.740260004997253],[.865594983100891,.333687007427216],[.614073991775513,.883246004581451],[.508952975273132,.579437971115112],[.617941975593567,.508316040039062],[.825608015060425,.397674977779388],[.681214988231659,.39623498916626],[.656635999679565,.400596976280212],[.603900015354156,.710216999053955],[.81208598613739,.588539004325867],[.56801301240921,.944564998149872],[.681007981300354,.898285031318665],[.733752012252808,.869701027870178],[.633830010890961,.398822009563446],[.606792986392975,.39553701877594],[.589659988880157,.391062021255493],[.805015981197357,.342108011245728],[.611334979534149,.362284004688263],[.634037971496582,.355970978736877],[.656635999679565,.355356991291046],[.681214988231659,.35834002494812],[.698584973812103,.363156020641327],[.941866993904114,.319076001644135],[.698584973812103,.387449026107788],[.584177017211914,.624107003211975],[.554318010807037,.566076993942261],[.534153997898102,.62064003944397],[.711217999458313,.819975018501282],[.664629995822906,.852871000766754],[.559099972248077,.902631998062134],[.871706008911133,.791940987110138],[.591234028339386,.373893976211548],[.544341027736664,.451583981513977],[.624562978744507,.924192011356354],[.88577002286911,.615028977394104],[.551338016986847,.695277988910675],[.551980018615723,.704632043838501],[.552887976169586,.715808033943176],[.555167973041534,.730794012546539],[.569944024085999,.767035007476807],[.593203008174896,.685675978660583],[.599261999130249,.681069016456604],[.607599973678589,.677703022956848],[.631937980651855,.663500010967255],[.752032995223999,.601315021514893],[.547226011753082,.420395016670227],[.563543975353241,.359827995300293],[.583841025829315,.368713974952698],[.586614012718201,.692366003990173],[.771915018558502,.683578014373779],[.531597018241882,.352482974529266],[.588370978832245,.804440975189209],[.52079701423645,.442565023899078],[.567984998226166,.493479013442993],[.543282985687256,.819254994392395],[.655317008495331,.745514988899231],[.621008992195129,.574018001556396],[.625559985637665,.78031200170517],[.680198013782501,.570719003677368],[.64276397228241,.604337990283966],[.704662978649139,.621529996395111],[.552012026309967,.862591981887817],[.589071989059448,.508637011051178],[.685944974422455,.775357007980347],[.645735025405884,.812640011310577],[.675342977046967,.703978002071381],[.810858011245728,.646304965019226],[.72012197971344,.714666962623596],[.866151988506317,.682704985141754],[.663187026977539,.644596993923187],[.570082008838654,.466325998306274],[.544561982154846,.548375964164734],[.562758982181549,.558784961700439],[.531987011432648,.530140042304993],[.585271000862122,.335177004337311],[.622952997684479,.32277899980545],[.655896008014679,.320163011550903],[.687132000923157,.322345972061157],[.716481983661652,.333200991153717],[.758756995201111,.382786989212036],[.897013008594513,.468769013881683],[.732392013072968,.424547016620636],[.70211398601532,.433162987232208],[.66652500629425,.433866024017334],[.633504986763,.426087975502014],[.603875994682312,.416586995124817],[.579657971858978,.409945011138916],[.992439985275269,.480777025222778],[.567192018032074,.569419980049133],[.54136598110199,.478899002075195],[.526564002037048,.546118021011353],[.523913025856018,.563830018043518],[.531529009342194,.555056989192963],[.566035985946655,.582329034805298],[.51631098985672,.563053965568542],[.5174720287323,.577877044677734],[.573594987392426,.389806985855103],[.560697972774506,.395331978797913],[.549755990505219,.399751007556915],[.710287988185883,.368252992630005],[.723330020904541,.363372981548309]],zl=[127,34,139,11,0,37,232,231,120,72,37,39,128,121,47,232,121,128,104,69,67,175,171,148,157,154,155,118,50,101,73,39,40,9,151,108,48,115,131,194,204,211,74,40,185,80,42,183,40,92,186,230,229,118,202,212,214,83,18,17,76,61,146,160,29,30,56,157,173,106,204,194,135,214,192,203,165,98,21,71,68,51,45,4,144,24,23,77,146,91,205,50,187,201,200,18,91,106,182,90,91,181,85,84,17,206,203,36,148,171,140,92,40,39,193,189,244,159,158,28,247,246,161,236,3,196,54,68,104,193,168,8,117,228,31,189,193,55,98,97,99,126,47,100,166,79,218,155,154,26,209,49,131,135,136,150,47,126,217,223,52,53,45,51,134,211,170,140,67,69,108,43,106,91,230,119,120,226,130,247,63,53,52,238,20,242,46,70,156,78,62,96,46,53,63,143,34,227,173,155,133,123,117,111,44,125,19,236,134,51,216,206,205,154,153,22,39,37,167,200,201,208,36,142,100,57,212,202,20,60,99,28,158,157,35,226,113,160,159,27,204,202,210,113,225,46,43,202,204,62,76,77,137,123,116,41,38,72,203,129,142,64,98,240,49,102,64,41,73,74,212,216,207,42,74,184,169,170,211,170,149,176,105,66,69,122,6,168,123,147,187,96,77,90,65,55,107,89,90,180,101,100,120,63,105,104,93,137,227,15,86,85,129,102,49,14,87,86,55,8,9,100,47,121,145,23,22,88,89,179,6,122,196,88,95,96,138,172,136,215,58,172,115,48,219,42,80,81,195,3,51,43,146,61,171,175,199,81,82,38,53,46,225,144,163,110,246,33,7,52,65,66,229,228,117,34,127,234,107,108,69,109,108,151,48,64,235,62,78,191,129,209,126,111,35,143,163,161,246,117,123,50,222,65,52,19,125,141,221,55,65,3,195,197,25,7,33,220,237,44,70,71,139,122,193,245,247,130,33,71,21,162,153,158,159,170,169,150,188,174,196,216,186,92,144,160,161,2,97,167,141,125,241,164,167,37,72,38,12,145,159,160,38,82,13,63,68,71,226,35,111,158,153,154,101,50,205,206,92,165,209,198,217,165,167,97,220,115,218,133,112,243,239,238,241,214,135,169,190,173,133,171,208,32,125,44,237,86,87,178,85,86,179,84,85,180,83,84,181,201,83,182,137,93,132,76,62,183,61,76,184,57,61,185,212,57,186,214,207,187,34,143,156,79,239,237,123,137,177,44,1,4,201,194,32,64,102,129,213,215,138,59,166,219,242,99,97,2,94,141,75,59,235,24,110,228,25,130,226,23,24,229,22,23,230,26,22,231,112,26,232,189,190,243,221,56,190,28,56,221,27,28,222,29,27,223,30,29,224,247,30,225,238,79,20,166,59,75,60,75,240,147,177,215,20,79,166,187,147,213,112,233,244,233,128,245,128,114,188,114,217,174,131,115,220,217,198,236,198,131,134,177,132,58,143,35,124,110,163,7,228,110,25,356,389,368,11,302,267,452,350,349,302,303,269,357,343,277,452,453,357,333,332,297,175,152,377,384,398,382,347,348,330,303,304,270,9,336,337,278,279,360,418,262,431,304,408,409,310,415,407,270,409,410,450,348,347,422,430,434,313,314,17,306,307,375,387,388,260,286,414,398,335,406,418,364,367,416,423,358,327,251,284,298,281,5,4,373,374,253,307,320,321,425,427,411,421,313,18,321,405,406,320,404,405,315,16,17,426,425,266,377,400,369,322,391,269,417,465,464,386,257,258,466,260,388,456,399,419,284,332,333,417,285,8,346,340,261,413,441,285,327,460,328,355,371,329,392,439,438,382,341,256,429,420,360,364,394,379,277,343,437,443,444,283,275,440,363,431,262,369,297,338,337,273,375,321,450,451,349,446,342,467,293,334,282,458,461,462,276,353,383,308,324,325,276,300,293,372,345,447,382,398,362,352,345,340,274,1,19,456,248,281,436,427,425,381,256,252,269,391,393,200,199,428,266,330,329,287,273,422,250,462,328,258,286,384,265,353,342,387,259,257,424,431,430,342,353,276,273,335,424,292,325,307,366,447,345,271,303,302,423,266,371,294,455,460,279,278,294,271,272,304,432,434,427,272,407,408,394,430,431,395,369,400,334,333,299,351,417,168,352,280,411,325,319,320,295,296,336,319,403,404,330,348,349,293,298,333,323,454,447,15,16,315,358,429,279,14,15,316,285,336,9,329,349,350,374,380,252,318,402,403,6,197,419,318,319,325,367,364,365,435,367,397,344,438,439,272,271,311,195,5,281,273,287,291,396,428,199,311,271,268,283,444,445,373,254,339,263,466,249,282,334,296,449,347,346,264,447,454,336,296,299,338,10,151,278,439,455,292,407,415,358,371,355,340,345,372,390,249,466,346,347,280,442,443,282,19,94,370,441,442,295,248,419,197,263,255,359,440,275,274,300,383,368,351,412,465,263,467,466,301,368,389,380,374,386,395,378,379,412,351,419,436,426,322,373,390,388,2,164,393,370,462,461,164,0,267,302,11,12,374,373,387,268,12,13,293,300,301,446,261,340,385,384,381,330,266,425,426,423,391,429,355,437,391,327,326,440,457,438,341,382,362,459,457,461,434,430,394,414,463,362,396,369,262,354,461,457,316,403,402,315,404,403,314,405,404,313,406,405,421,418,406,366,401,361,306,408,407,291,409,408,287,410,409,432,436,410,434,416,411,264,368,383,309,438,457,352,376,401,274,275,4,421,428,262,294,327,358,433,416,367,289,455,439,462,370,326,2,326,370,305,460,455,254,449,448,255,261,446,253,450,449,252,451,450,256,452,451,341,453,452,413,464,463,441,413,414,258,442,441,257,443,442,259,444,443,260,445,444,467,342,445,459,458,250,289,392,290,290,328,460,376,433,435,250,290,392,411,416,433,341,463,464,453,464,465,357,465,412,343,412,399,360,363,440,437,399,456,420,456,363,401,435,288,372,383,353,339,255,249,448,261,255,133,243,190,133,155,112,33,246,247,33,130,25,398,384,286,362,398,414,362,463,341,263,359,467,263,249,255,466,467,260,75,60,166,238,239,79,162,127,139,72,11,37,121,232,120,73,72,39,114,128,47,233,232,128,103,104,67,152,175,148,173,157,155,119,118,101,74,73,40,107,9,108,49,48,131,32,194,211,184,74,185,191,80,183,185,40,186,119,230,118,210,202,214,84,83,17,77,76,146,161,160,30,190,56,173,182,106,194,138,135,192,129,203,98,54,21,68,5,51,4,145,144,23,90,77,91,207,205,187,83,201,18,181,91,182,180,90,181,16,85,17,205,206,36,176,148,140,165,92,39,245,193,244,27,159,28,30,247,161,174,236,196,103,54,104,55,193,8,111,117,31,221,189,55,240,98,99,142,126,100,219,166,218,112,155,26,198,209,131,169,135,150,114,47,217,224,223,53,220,45,134,32,211,140,109,67,108,146,43,91,231,230,120,113,226,247,105,63,52,241,238,242,124,46,156,95,78,96,70,46,63,116,143,227,116,123,111,1,44,19,3,236,51,207,216,205,26,154,22,165,39,167,199,200,208,101,36,100,43,57,202,242,20,99,56,28,157,124,35,113,29,160,27,211,204,210,124,113,46,106,43,204,96,62,77,227,137,116,73,41,72,36,203,142,235,64,240,48,49,64,42,41,74,214,212,207,183,42,184,210,169,211,140,170,176,104,105,69,193,122,168,50,123,187,89,96,90,66,65,107,179,89,180,119,101,120,68,63,104,234,93,227,16,15,85,209,129,49,15,14,86,107,55,9,120,100,121,153,145,22,178,88,179,197,6,196,89,88,96,135,138,136,138,215,172,218,115,219,41,42,81,5,195,51,57,43,61,208,171,199,41,81,38,224,53,225,24,144,110,105,52,66,118,229,117,227,34,234,66,107,69,10,109,151,219,48,235,183,62,191,142,129,126,116,111,143,7,163,246,118,117,50,223,222,52,94,19,141,222,221,65,196,3,197,45,220,44,156,70,139,188,122,245,139,71,162,145,153,159,149,170,150,122,188,196,206,216,92,163,144,161,164,2,167,242,141,241,0,164,37,11,72,12,144,145,160,12,38,13,70,63,71,31,226,111,157,158,154,36,101,205,203,206,165,126,209,217,98,165,97,237,220,218,237,239,241,210,214,169,140,171,32,241,125,237,179,86,178,180,85,179,181,84,180,182,83,181,194,201,182,177,137,132,184,76,183,185,61,184,186,57,185,216,212,186,192,214,187,139,34,156,218,79,237,147,123,177,45,44,4,208,201,32,98,64,129,192,213,138,235,59,219,141,242,97,97,2,141,240,75,235,229,24,228,31,25,226,230,23,229,231,22,230,232,26,231,233,112,232,244,189,243,189,221,190,222,28,221,223,27,222,224,29,223,225,30,224,113,247,225,99,60,240,213,147,215,60,20,166,192,187,213,243,112,244,244,233,245,245,128,188,188,114,174,134,131,220,174,217,236,236,198,134,215,177,58,156,143,124,25,110,7,31,228,25,264,356,368,0,11,267,451,452,349,267,302,269,350,357,277,350,452,357,299,333,297,396,175,377,381,384,382,280,347,330,269,303,270,151,9,337,344,278,360,424,418,431,270,304,409,272,310,407,322,270,410,449,450,347,432,422,434,18,313,17,291,306,375,259,387,260,424,335,418,434,364,416,391,423,327,301,251,298,275,281,4,254,373,253,375,307,321,280,425,411,200,421,18,335,321,406,321,320,405,314,315,17,423,426,266,396,377,369,270,322,269,413,417,464,385,386,258,248,456,419,298,284,333,168,417,8,448,346,261,417,413,285,326,327,328,277,355,329,309,392,438,381,382,256,279,429,360,365,364,379,355,277,437,282,443,283,281,275,363,395,431,369,299,297,337,335,273,321,348,450,349,359,446,467,283,293,282,250,458,462,300,276,383,292,308,325,283,276,293,264,372,447,346,352,340,354,274,19,363,456,281,426,436,425,380,381,252,267,269,393,421,200,428,371,266,329,432,287,422,290,250,328,385,258,384,446,265,342,386,387,257,422,424,430,445,342,276,422,273,424,306,292,307,352,366,345,268,271,302,358,423,371,327,294,460,331,279,294,303,271,304,436,432,427,304,272,408,395,394,431,378,395,400,296,334,299,6,351,168,376,352,411,307,325,320,285,295,336,320,319,404,329,330,349,334,293,333,366,323,447,316,15,315,331,358,279,317,14,316,8,285,9,277,329,350,253,374,252,319,318,403,351,6,419,324,318,325,397,367,365,288,435,397,278,344,439,310,272,311,248,195,281,375,273,291,175,396,199,312,311,268,276,283,445,390,373,339,295,282,296,448,449,346,356,264,454,337,336,299,337,338,151,294,278,455,308,292,415,429,358,355,265,340,372,388,390,466,352,346,280,295,442,282,354,19,370,285,441,295,195,248,197,457,440,274,301,300,368,417,351,465,251,301,389,385,380,386,394,395,379,399,412,419,410,436,322,387,373,388,326,2,393,354,370,461,393,164,267,268,302,12,386,374,387,312,268,13,298,293,301,265,446,340,380,385,381,280,330,425,322,426,391,420,429,437,393,391,326,344,440,438,458,459,461,364,434,394,428,396,262,274,354,457,317,316,402,316,315,403,315,314,404,314,313,405,313,421,406,323,366,361,292,306,407,306,291,408,291,287,409,287,432,410,427,434,411,372,264,383,459,309,457,366,352,401,1,274,4,418,421,262,331,294,358,435,433,367,392,289,439,328,462,326,94,2,370,289,305,455,339,254,448,359,255,446,254,253,449,253,252,450,252,256,451,256,341,452,414,413,463,286,441,414,286,258,441,258,257,442,257,259,443,259,260,444,260,467,445,309,459,250,305,289,290,305,290,460,401,376,435,309,250,392,376,411,433,453,341,464,357,453,465,343,357,412,437,343,399,344,360,440,420,437,456,360,420,363,361,401,288,265,372,353,390,339,249,339,448,255];var p2e=[127,234,132,58,172,150,149,148,152,377,378,379,397,288,361,454,356,70,63,105,66,107,336,296,334,293,300,168,6,195,4,98,97,2,326,327,33,160,158,133,153,144,362,385,387,263,373,380,57,40,37,0,267,270,287,321,314,17,84,91,78,81,13,311,308,402,14,178],h2e=[33,133,362,263,1,62,308,159,145,386,374,6,102,331,2,13,14,70,105,107,336,334,300,54,10,284,50,280,234,454,58,288,152],f2e=[33,133,362,263,1,78,308],tAe=p2e.map(e=>Op[e]),nAe=h2e.map(e=>Op[e]),sAe=f2e.map(e=>Op[e]);var Mp=e=>[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])],g0=e=>[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2],ub=(e,t)=>e?[Math.trunc(Math.max(0,e.startPoint[0])),Math.trunc(Math.max(0,e.startPoint[1])),Math.trunc(Math.min(t.shape[2]||0,e.endPoint[0])-Math.max(0,e.startPoint[0])),Math.trunc(Math.min(t.shape[1]||0,e.endPoint[1])-Math.max(0,e.startPoint[1]))]:[0,0,0,0],cb=(e,t)=>e?[e.startPoint[0]/(t.shape[2]||0),e.startPoint[1]/(t.shape[1]||0),(e.endPoint[0]-e.startPoint[0])/(t.shape[2]||0),(e.endPoint[1]-e.startPoint[1])/(t.shape[1]||0)]:[0,0,0,0],_8=(e,t)=>{let n=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],s=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]];return{startPoint:n,endPoint:s,landmarks:e.landmarks,confidence:e.confidence}},db=(e,t,n)=>{let s=t.shape[1],r=t.shape[2],a=Ce.cropAndResize(t,[[e.startPoint[1]/s,e.startPoint[0]/r,e.endPoint[1]/s,e.endPoint[0]/r]],[0],n),o=ge(a,Yn);return te(a),o},zp=(e,t)=>{let n=g0(e),s=Mp(e),r=[t*s[0]/2,t*s[1]/2];return{startPoint:[n[0]-r[0],n[1]-r[1]],endPoint:[n[0]+r[0],n[1]+r[1]],landmarks:e.landmarks,confidence:e.confidence}},Lp=e=>{let t=g0(e),n=Mp(e),s=Math.max(...n)/2;return{startPoint:[Math.round(t[0]-s),Math.round(t[1]-s)],endPoint:[Math.round(t[0]+s),Math.round(t[1]+s)],landmarks:e.landmarks,confidence:e.confidence}},A0=e=>{let t=e.map(s=>s[0]),n=e.map(s=>s[1]);return{startPoint:[Math.min(...t),Math.min(...n)],endPoint:[Math.max(...t),Math.max(...n)],landmarks:e}},pb=[[1,0,0],[0,1,0],[0,0,1]],m2e=e=>e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI)),g2e=(e,t)=>m2e(Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]));var D8=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]],Ll=(e,t)=>{let n=0;for(let s=0;s{let n=[];for(let s=0;s{let n=[],s=e.length;for(let r=0;r{let n=Math.cos(e),s=Math.sin(e),r=[[n,-s,0],[s,n,0],[0,0,1]],a=D8(t[0],t[1]),o=P8(a,r),i=D8(-t[0],-t[1]);return P8(o,i)},y2e=e=>{let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],n=[e[0][2],e[1][2]],s=[-Ll(t[0],n),-Ll(t[1],n)];return[t[0].concat(s[0]),t[1].concat(s[1]),[0,0,1]]},x2e=(e,t)=>[Ll(e,t[0]),Ll(e,t[1])];function O8(e){let t={strides:[e/16,e/8],anchors:[2,6]},n=[];for(let s=0;s[a[0]/r*(p[0]-r/2),a[1]/r*(p[1]-r/2),p[2]||0]),i=n&&n!==0&&Math.abs(n)>.2,l=i?F8(n,[0,0]):pb,c=i?o.map(p=>[...x2e(p,l),p[2]]):o,u=i?y2e(s):pb,d=[...g0({startPoint:t.startPoint,endPoint:t.endPoint}),1];return c.map(p=>[Math.round(p[0]+Ll(d,u[0])),Math.round(p[1]+Ll(d,u[1])),Math.round(p[2]||0)])}function hb(e,t,n,s){let r=t.landmarks.length>=ib.count?ib.symmetryLine:Fp.symmetryLine,a=0,o=pb,i;if(e&&de.kernels.includes("rotatewithoffset"))if(a=g2e(t.landmarks[r[0]],t.landmarks[r[1]]),a&&a!==0&&Math.abs(a)>.2){let c=g0({startPoint:t.startPoint,endPoint:t.endPoint}),u=[c[0]/n.shape[2],c[1]/n.shape[1]],d=Ce.rotateWithOffset(n,a,0,u);o=F8(-a,c),i=db(t,d,[s,s]),te(d)}else i=db(t,n,[s,s]);else i=db(t,n,[s,s]);return[a,o,i]}var z8=6,Ws,L8=null,Yo=0,Bp=null,y0=()=>Yo;async function B8(e){var t,n;return de.initial&&(Ws=null),Ws?e.debug&&Z("cached model:",Ws.modelUrl):(Ws=await Be(We(e.modelBasePath,((t=e.face.detector)==null?void 0:t.modelPath)||"")),!Ws||!Ws.modelUrl?Z("load model failed:",(n=e.face.detector)==null?void 0:n.modelPath):e.debug&&Z("load model:",Ws.modelUrl)),Yo=Ws.inputs[0].shape?Ws.inputs[0].shape[2]:0,Bp=Ie(Yo,"int32"),L8=fr(O8(Yo)),Ws}function b2e(e){let t={};t.boxStarts=Pe(e,[0,1],[-1,2]),t.centers=ue(t.boxStarts,L8),t.boxSizes=Pe(e,[0,3],[-1,2]),t.boxSizesNormalized=ge(t.boxSizes,Bp),t.centersNormalized=ge(t.centers,Bp),t.halfBoxSize=ge(t.boxSizesNormalized,Nc),t.starts=fe(t.centersNormalized,t.halfBoxSize),t.ends=ue(t.centersNormalized,t.halfBoxSize),t.startNormalized=L(t.starts,Bp),t.endNormalized=L(t.ends,Bp);let n=Wu([t.startNormalized,t.endNormalized],1);return Object.keys(t).forEach(s=>te(t[s])),n}async function W8(e,t){var i,l,c,u;if(!e||e.isDisposedInternal||e.shape.length!==4||e.shape[1]<1||e.shape[2]<1)return{boxes:[]};let n={};n.resized=Ce.resizeBilinear(e,[Yo,Yo]),n.div=ge(n.resized,p0),n.normalized=fe(n.div,Ec);let s=Ws==null?void 0:Ws.execute(n.normalized);if(Array.isArray(s)){let d=s.sort((p,h)=>p.size-h.size);n.concat384=wt([d[0],d[2]],2),n.concat512=wt([d[1],d[3]],2),n.concat=wt([n.concat512,n.concat384],1),n.batch=ot(n.concat,0)}else n.batch=ot(s);te(s),n.boxes=b2e(n.batch),n.logits=Pe(n.batch,[0,0],[-1,1]),n.sigmoid=ms(n.logits),n.scores=ot(n.sigmoid),n.nms=await Ce.nonMaxSuppressionAsync(n.boxes,n.scores,((i=t.face.detector)==null?void 0:i.maxDetected)||0,((l=t.face.detector)==null?void 0:l.iouThreshold)||0,((c=t.face.detector)==null?void 0:c.minConfidence)||0);let r=await n.nms.array(),a=[],o=await n.scores.data();for(let d=0;d(((u=t.face.detector)==null?void 0:u.minConfidence)||0)){let h={};h.bbox=Pe(n.boxes,[r[d],0],[1,-1]),h.slice=Pe(n.batch,[r[d],z8-1],[1,-1]),h.squeeze=ot(h.slice),h.landmarks=H(h.squeeze,[z8,-1]);let f=await h.bbox.data();a.push({box:{startPoint:[f[0],f[1]],endPoint:[f[2],f[3]]},landmarks:await h.landmarks.array(),confidence:p}),Object.keys(h).forEach(m=>te(h[m]))}}return Object.keys(n).forEach(d=>te(n[d])),{boxes:a,scaleFactor:[e.shape[2]/Yo,e.shape[1]/Yo]}}var gb={};Qc(gb,{connected:()=>mb,kpt:()=>fb});var fb=["nose","leftEyeInside","leftEye","leftEyeOutside","rightEyeInside","rightEye","rightEyeOutside","leftEar","rightEar","leftMouth","rightMouth","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftPalm","rightPalm","leftIndex","rightIndex","leftPinky","rightPinky","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle","leftHeel","rightHeel","leftFoot","rightFoot","bodyCenter","bodyTop","leftThumb","leftHand","rightThumb","rightHand"],mb={leftLeg:["leftHip","leftKnee","leftAnkle","leftHeel","leftFoot"],rightLeg:["rightHip","rightKnee","rightAnkle","rightHeel","rightFoot"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist","leftPalm"],rightArm:["rightShoulder","rightElbow","rightWrist","rightPalm"],leftHand:[],rightHand:[],head:[]};var V8={initial:!0},cn=[null,null],Jo=[[0,0],[0,0]],Ab=Number.MAX_SAFE_INTEGER,yb,x0=null,Qo=[[0,0],[0,0],[0,0],[0,0]],U8=0;async function G8(e){var t,n,s;if(V8.initial&&(cn[0]=null),!cn[0]&&((t=e.body.detector)==null?void 0:t.modelPath)){cn[0]=await Be(We(e.modelBasePath,((n=e.body.detector)==null?void 0:n.modelPath)||""));let r=Object.values(cn[0].modelSignature.inputs);Jo[0][0]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[1].size):0,Jo[0][1]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[2].size):0,!cn[0]||!cn[0].modelUrl?Z("load model failed:",(s=e.body.detector)==null?void 0:s.modelPath):e.debug&&Z("load model:",cn[0].modelUrl)}else e.debug&&cn[0]&&Z("cached model:",cn[0].modelUrl);return cn[0]}async function H8(e){var t;if(V8.initial&&(cn[1]=null),cn[1])e.debug&&Z("cached model:",cn[1].modelUrl);else{cn[1]=await Be(We(e.modelBasePath,e.body.modelPath||""));let n=Object.values(cn[1].modelSignature.inputs);Jo[1][0]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[1].size):0,Jo[1][1]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[2].size):0,((t=e.body.modelPath)==null?void 0:t.includes("lite"))?yb=["ld_3d","output_segmentation","output_heatmap","world_3d","output_poseflag"]:yb=["Identity","Identity_2","Identity_3","Identity_4","Identity_1"],!cn[1]||!cn[1].modelUrl?Z("load model failed:",e.body.modelPath):e.debug&&Z("load model:",cn[1].modelUrl)}return cn[1]}function v2e(e,t){let n=e.map(o=>o.position[0]),s=e.map(o=>o.position[1]),r=[Math.min(...n),Math.min(...s),Math.max(...n)-Math.min(...n),Math.max(...s)-Math.min(...s)],a=[r[0]/t[0],r[1]/t[1],r[2]/t[0],r[3]/t[1]];return{keypointsBox:r,keypointsBoxRaw:a}}async function w2e(e){let t={};if(!e.shape||!e.shape[1]||!e.shape[2])return e;Qo=[[0,0],[e.shape[2]>e.shape[1]?Math.trunc((e.shape[2]-e.shape[1])/2):0,e.shape[2]>e.shape[1]?Math.trunc((e.shape[2]-e.shape[1])/2):0],[e.shape[1]>e.shape[2]?Math.trunc((e.shape[1]-e.shape[2])/2):0,e.shape[1]>e.shape[2]?Math.trunc((e.shape[1]-e.shape[2])/2):0],[0,0]],t.pad=Js(e,Qo),t.resize=Ce.resizeBilinear(t.pad,[Jo[1][0],Jo[1][1]]);let n=ge(t.resize,Yn);return Object.keys(t).forEach(s=>te(t[s])),n}function k2e(e,t){for(let n of e)n.position=[n.position[0]*(t[0]+Qo[2][0]+Qo[2][1])/t[0]-Qo[2][0],n.position[1]*(t[1]+Qo[1][0]+Qo[1][1])/t[1]-Qo[1][0],n.position[2]],n.positionRaw=[n.position[0]/t[0],n.position[1]/t[1],n.position[2]];return e}var j8=e=>1-1/(1+Math.exp(e));async function S2e(e,t,n){var h;let s={};s.input=await w2e(e),[s.ld,s.segmentation,s.heatmap,s.world,s.poseflag]=(h=cn[1])==null?void 0:h.execute(s.input,yb);let r=(await s.poseflag.data())[0],a=Math.max(0,(r-.8)/(1-.8)),o=await s.ld.data(),i=[],l=5;for(let f=0;fte(s[f]));let d={};for(let[f,m]of Object.entries(mb)){let g=[];for(let A=0;Ab.part===m[A]),y=c.find(b=>b.part===m[A+1]);x&&y&&x.score>(t.body.minConfidence||0)&&y.score>(t.body.minConfidence||0)&&g.push([x.position,y.position])}d[f]=g}return{id:0,score:Math.trunc(100*a)/100,box:u.keypointsBox,boxRaw:u.keypointsBoxRaw,keypoints:c,annotations:d}}async function xb(e,t){let n=[e.shape[2]||0,e.shape[1]||0],s=(t.body.skipTime||0)>ie()-U8,r=Ab<(t.body.skipFrames||0);return t.skipAllowed&&s&&r&&x0!==null?Ab++:(x0=await S2e(e,t,n),U8=ie(),Ab=0),x0?[x0]:[]}var Rc=[{class:1,label:"person"},{class:2,label:"bicycle"},{class:3,label:"car"},{class:4,label:"motorcycle"},{class:5,label:"airplane"},{class:6,label:"bus"},{class:7,label:"train"},{class:8,label:"truck"},{class:9,label:"boat"},{class:10,label:"traffic light"},{class:11,label:"fire hydrant"},{class:12,label:"stop sign"},{class:13,label:"parking meter"},{class:14,label:"bench"},{class:15,label:"bird"},{class:16,label:"cat"},{class:17,label:"dog"},{class:18,label:"horse"},{class:19,label:"sheep"},{class:20,label:"cow"},{class:21,label:"elephant"},{class:22,label:"bear"},{class:23,label:"zebra"},{class:24,label:"giraffe"},{class:25,label:"backpack"},{class:26,label:"umbrella"},{class:27,label:"handbag"},{class:28,label:"tie"},{class:29,label:"suitcase"},{class:30,label:"frisbee"},{class:31,label:"skis"},{class:32,label:"snowboard"},{class:33,label:"sports ball"},{class:34,label:"kite"},{class:35,label:"baseball bat"},{class:36,label:"baseball glove"},{class:37,label:"skateboard"},{class:38,label:"surfboard"},{class:39,label:"tennis racket"},{class:40,label:"bottle"},{class:41,label:"wine glass"},{class:42,label:"cup"},{class:43,label:"fork"},{class:44,label:"knife"},{class:45,label:"spoon"},{class:46,label:"bowl"},{class:47,label:"banana"},{class:48,label:"apple"},{class:49,label:"sandwich"},{class:50,label:"orange"},{class:51,label:"broccoli"},{class:52,label:"carrot"},{class:53,label:"hot dog"},{class:54,label:"pizza"},{class:55,label:"donut"},{class:56,label:"cake"},{class:57,label:"chair"},{class:58,label:"couch"},{class:59,label:"potted plant"},{class:60,label:"bed"},{class:61,label:"dining table"},{class:62,label:"toilet"},{class:63,label:"tv"},{class:64,label:"laptop"},{class:65,label:"mouse"},{class:66,label:"remote"},{class:67,label:"keyboard"},{class:68,label:"cell phone"},{class:69,label:"microwave"},{class:70,label:"oven"},{class:71,label:"toaster"},{class:72,label:"sink"},{class:73,label:"refrigerator"},{class:74,label:"book"},{class:75,label:"clock"},{class:76,label:"vase"},{class:77,label:"scissors"},{class:78,label:"teddy bear"},{class:79,label:"hair drier"},{class:80,label:"toothbrush"}];var ar,Bl=0,bb=[],q8=0,vb=Number.MAX_SAFE_INTEGER;async function X8(e){if(de.initial&&(ar=null),ar)e.debug&&Z("cached model:",ar.modelUrl);else{ar=await Be(We(e.modelBasePath,e.object.modelPath||""));let t=Object.values(ar.modelSignature.inputs);Bl=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0,!ar||!ar.modelUrl?Z("load model failed:",e.object.modelPath):e.debug&&Z("load model:",ar.modelUrl)}return ar}async function I2e(e,t,n){if(!e)return[];let s=[],r=await e.array(),a=ot(e);te(e);let o=sn(a,6,1);te(a);let i=yn([o[1],o[0],o[3],o[2]],1),l=ot(i);te(i);let c=ot(o[4]),u=ot(o[5]);o.forEach(f=>te(f));let d=await Ce.nonMaxSuppressionAsync(l,c,n.object.maxDetected,n.object.iouThreshold,n.object.minConfidence);te(l),te(c),te(u);let p=await d.data();te(d);let h=0;for(let f of p){let m=Math.trunc(100*r[0][f][4])/100,g=r[0][f][5],A=Rc[g].label,[x,y]=[r[0][f][0]/Bl,r[0][f][1]/Bl],b=[x,y,r[0][f][2]/Bl-x,r[0][f][3]/Bl-y],w=[Math.trunc(b[0]*t[0]),Math.trunc(b[1]*t[1]),Math.trunc(b[2]*t[0]),Math.trunc(b[3]*t[1])];s.push({id:h++,score:m,class:g,label:A,box:w,boxRaw:b})}return s}async function wb(e,t){let n=(t.object.skipTime||0)>ie()-q8,s=vb<(t.object.skipFrames||0);return t.skipAllowed&&n&&s&&bb.length>0?(vb++,bb):(vb=0,new Promise(async r=>{let a=[e.shape[2],e.shape[1]],o=Ce.resizeBilinear(e,[Bl,Bl]),i=t.object.enabled?ar==null?void 0:ar.execute(o,["tower_0/detections"]):null;q8=ie(),te(o);let l=await I2e(i,a,t);bb=l,r(l)}))}var Ib={};Qc(Ib,{connected:()=>Sb,kpt:()=>kb});var kb=["head","neck","rightShoulder","rightElbow","rightWrist","chest","leftShoulder","leftElbow","leftWrist","bodyCenter","rightHip","rightKnee","rightAnkle","leftHip","leftKnee","leftAnkle"],Sb={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var dn,K8=0,Jn={id:0,keypoints:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,annotations:{}},Cb=Number.MAX_SAFE_INTEGER;async function Z8(e){return de.initial&&(dn=null),dn?e.debug&&Z("cached model:",dn.modelUrl):(dn=await Be(We(e.modelBasePath,e.body.modelPath||"")),!dn||!dn.modelUrl?Z("load model failed:",e.body.modelPath):e.debug&&Z("load model:",dn.modelUrl)),dn}async function C2e(e,t){let[n,s]=e.shape,r=H(e,[s*n]),a=An(r,0),o=(await a.data())[0];if(te([r,a]),o>t){let i=Zs(r,0),l=Ld(i,n),c=(await l.data())[0],u=ge(i,Ie(n,"int32")),d=(await u.data())[0];return te([l,u]),[c,d,o]}return[0,0,o]}async function Tb(e,t){let n=(t.body.skipTime||0)>ie()-K8,s=Cb<(t.body.skipFrames||0);return t.skipAllowed&&n&&s&&Object.keys(Jn.keypoints).length>0?(Cb++,[Jn]):(Cb=0,new Promise(async r=>{var d;let a=X(()=>{if(!(dn==null?void 0:dn.inputs[0].shape))return null;let p=Ce.resizeBilinear(e,[dn.inputs[0].shape[2],dn.inputs[0].shape[1]],!1),h=L(p,Nc);return fe(h,d0)}),o;if(t.body.enabled&&(o=dn==null?void 0:dn.execute(a)),K8=ie(),te(a),o){Jn.keypoints.length=0;let p=o.squeeze();te(o);let h=p.unstack(2);te(p);for(let f=0;f(((d=t.body)==null?void 0:d.minConfidence)||0)&&Jn.keypoints.push({score:Math.round(100*A)/100,part:kb[f],positionRaw:[m/dn.inputs[0].shape[2],g/dn.inputs[0].shape[1]],position:[Math.round(e.shape[2]*m/dn.inputs[0].shape[2]),Math.round(e.shape[1]*g/dn.inputs[0].shape[1])]})}h.forEach(f=>te(f))}Jn.score=Jn.keypoints.reduce((p,h)=>h.score>p?h.score:p,0);let i=Jn.keypoints.map(p=>p.position[0]),l=Jn.keypoints.map(p=>p.position[1]);Jn.box=[Math.min(...i),Math.min(...l),Math.max(...i)-Math.min(...i),Math.max(...l)-Math.min(...l)];let c=Jn.keypoints.map(p=>p.positionRaw[0]),u=Jn.keypoints.map(p=>p.positionRaw[1]);Jn.boxRaw=[Math.min(...c),Math.min(...u),Math.max(...c)-Math.min(...c),Math.max(...u)-Math.min(...u)];for(let[p,h]of Object.entries(Sb)){let f=[];for(let m=0;mx.part===h[m]),A=Jn.keypoints.find(x=>x.part===h[m+1]);g&&A&&g.score>(t.body.minConfidence||0)&&A.score>(t.body.minConfidence||0)&&f.push([g.position,A.position])}Jn.annotations[p]=f}r([Jn])}))}var T2e=["angry","disgust","fear","happy","sad","surprise","neutral"],Qn,b0=[],Y8=0,J8=0,Nb=Number.MAX_SAFE_INTEGER;async function Q8(e){var t,n;return de.initial&&(Qn=null),Qn?e.debug&&Z("cached model:",Qn.modelUrl):(Qn=await Be(We(e.modelBasePath,((t=e.face.emotion)==null?void 0:t.modelPath)||"")),!Qn||!Qn.modelUrl?Z("load model failed:",(n=e.face.emotion)==null?void 0:n.modelPath):e.debug&&Z("load model:",Qn.modelUrl)),Qn}async function Eb(e,t,n,s){var o,i;if(!Qn)return[];let r=Nb<(((o=t.face.emotion)==null?void 0:o.skipFrames)||0),a=(((i=t.face.emotion)==null?void 0:i.skipTime)||0)>ie()-J8;return t.skipAllowed&&a&&r&&Y8===s&&b0[n]&&b0[n].length>0?(Nb++,b0[n]):(Nb=0,new Promise(async l=>{var u,d;let c=[];if((u=t.face.emotion)==null?void 0:u.enabled){let p={},h=(Qn==null?void 0:Qn.inputs[0].shape)?Qn.inputs[0].shape[2]:0;p.resize=Ce.resizeBilinear(e,[h,h],!1),p.channels=L(p.resize,w8),p.grayscale=ke(p.channels,3,!0),p.grayscaleSub=fe(p.grayscale,Ec),p.grayscaleMul=L(p.grayscaleSub,Nc),p.emotion=Qn==null?void 0:Qn.execute(p.grayscaleMul),J8=ie();let f=await p.emotion.data();for(let m=0;m(((d=t.face.emotion)==null?void 0:d.minConfidence)||0)&&c.push({score:Math.min(.99,Math.trunc(100*f[m])/100),emotion:T2e[m]});c.sort((m,g)=>g.score-m.score),Object.keys(p).forEach(m=>te(p[m]))}b0[n]=c,Y8=s,l(c)}))}var ks,Rb=[],eT=0,tT=0,nT=Number.MAX_SAFE_INTEGER;async function sT(e){let t=We(e.modelBasePath,e.face.mobilefacenet.modelPath);return de.initial&&(ks=null),ks?e.debug&&Z("cached model:",t):(ks=await Be(t),ks?e.debug&&Z("load model:",t):Z("load model failed:",e.face.mobilefacenet.modelPath)),ks}async function $b(e,t,n,s){var o,i;if(!ks)return[];let r=nT<(((o=t.face.embedding)==null?void 0:o.skipFrames)||0),a=(((i=t.face.embedding)==null?void 0:i.skipTime)||0)>ie()-tT;return t.skipAllowed&&a&&r&&eT===s&&Rb[n]?(nT++,Rb[n]):new Promise(async l=>{var u;let c=[];if(((u=t.face.embedding)==null?void 0:u.enabled)&&(ks==null?void 0:ks.inputs[0].shape)){let d={};d.crop=Ce.resizeBilinear(e,[ks.inputs[0].shape[2],ks.inputs[0].shape[1]],!1),d.data=ks==null?void 0:ks.execute(d.crop);let p=await d.data.data();c=Array.from(p)}Rb[n]=c,eT=s,tT=ie(),l(c)})}var or,ei=0,N2e=2.3,_b=rr.leftEyeLower0,Db=rr.rightEyeLower0,$c={leftBounds:[_b[0],_b[_b.length-1]],rightBounds:[Db[0],Db[Db.length-1]]},_c={upperCenter:3,lowerCenter:4,index:71,numCoordinates:76};async function rT(e){var t,n;return de.initial&&(or=null),or?e.debug&&Z("cached model:",or.modelUrl):(or=await Be(We(e.modelBasePath,((t=e.face.iris)==null?void 0:t.modelPath)||"")),!or||!or.modelUrl?Z("load model failed:",(n=e.face.iris)==null?void 0:n.modelPath):e.debug&&Z("load model:",or.modelUrl)),ei=or.inputs[0].shape?or.inputs[0].shape[2]:0,ei===-1&&(ei=64),or}function v0(e,t,n,s){for(let r=0;r{let t=e[$c.leftBounds[0]][2],n=e[$c.rightBounds[0]][2];return t-n},aT=(e,t,n,s,r,a=!1)=>{let o=Lp(zp(A0([e[n],e[s]]),N2e)),i=Mp(o),l=Ce.cropAndResize(t,[[o.startPoint[1]/r,o.startPoint[0]/r,o.endPoint[1]/r,o.endPoint[0]/r]],[0],[ei,ei]);if(a&&de.kernels.includes("flipleftright")){let c=Ce.flipLeftRight(l);te(l),l=c}return{box:o,boxSize:i,crop:l}},oT=(e,t,n,s=!1)=>{let r=[];for(let a=0;a<_c.numCoordinates;a++){let o=e[a*3],i=e[a*3+1],l=e[a*3+2];r.push([(s?1-o/ei:o/ei)*n[0]+t.startPoint[0],i/ei*n[1]+t.startPoint[1],l])}return{rawCoords:r,iris:r.slice(_c.index)}},iT=(e,t,n)=>{let s=e[rr[`${n}EyeUpper0`][_c.upperCenter]][2],r=e[rr[`${n}EyeLower0`][_c.lowerCenter]][2],a=(s+r)/2;return t.map((o,i)=>{let l=a;return i===2?l=s:i===4&&(l=r),[o[0],o[1],l]})};async function lT(e,t,n,s){if(!or)return n.debug&&Z("face mesh iris detection requested, but model is not loaded"),e;let{box:r,boxSize:a,crop:o}=aT(e,t,$c.leftBounds[0],$c.leftBounds[1],s,!0),{box:i,boxSize:l,crop:c}=aT(e,t,$c.rightBounds[0],$c.rightBounds[1],s,!0),u=wt([o,c]);te(o),te(c);let d=or.execute(u);te(u);let p=await d.data();te(d);let h=p.slice(0,_c.numCoordinates*3),{rawCoords:f,iris:m}=oT(h,r,a,!0),g=p.slice(_c.numCoordinates*3),{rawCoords:A,iris:x}=oT(g,i,l),y=E2e(e);Math.abs(y)<30?(v0(e,f,"left",null),v0(e,A,"right",null)):y<1?v0(e,f,"left",["EyeUpper0","EyeLower0"]):v0(e,A,"right",["EyeUpper0","EyeLower0"]);let b=iT(e,m,"left"),w=iT(e,x,"right");return e.concat(b).concat(w)}var Dc=[],ir=null,Wl=0,Pb=Number.MAX_SAFE_INTEGER,uT=0;async function cT(e,t){var i,l,c,u,d,p,h,f,m,g,A;let n=(((i=t.face.detector)==null?void 0:i.skipTime)||0)>ie()-uT,s=Pb<(((l=t.face.detector)==null?void 0:l.skipFrames)||0);if(!t.skipAllowed||!n||!s||Dc.length===0){let x=await W8(e,t);uT=ie(),Dc=[];for(let y of x.boxes){let b={startPoint:y.box.startPoint,endPoint:y.box.endPoint,landmarks:y.landmarks,confidence:y.confidence},w=_8(b,x.scaleFactor),k=zp(w,Math.sqrt(((c=t.face.detector)==null?void 0:c.cropFactor)||1.6)),I=Lp(k);Dc.push(I)}Pb=0}else Pb++;let r=[],a=[],o=0;for(let x=0;x[T[0]/(e.shape[2]||0),T[1]/(e.shape[1]||0),(T[2]||0)/Wl]);for(let T of Object.keys(rr))k.annotations[T]=rr[T].map(F=>k.mesh[F]);y=Lp({...zp(A0(k.mesh),((g=t.face.detector)==null?void 0:g.cropFactor)||1.6),confidence:y.confidence}),k.box=ub(y,e),k.boxRaw=cb(y,e),k.score=k.faceScore,a.push(y),te(k.tensor),[b,w,k.tensor]=hb((A=t.face.detector)==null?void 0:A.rotation,y,e,Wl)}}else{k.box=ub(y,e),k.boxRaw=cb(y,e),k.score=k.boxScore,k.mesh=y.landmarks.map(I=>[(y.startPoint[0]+y.endPoint[0])/2+(y.endPoint[0]+y.startPoint[0])*I[0]/y0(),(y.startPoint[1]+y.endPoint[1])/2+(y.endPoint[1]+y.startPoint[1])*I[1]/y0()]),k.meshRaw=k.mesh.map(I=>[I[0]/(e.shape[2]||0),I[1]/(e.shape[1]||0),(I[2]||0)/Wl]);for(let I of Object.keys(Fp))k.annotations[I]=[k.mesh[Fp[I]]]}r.push(k)}return Dc=[...a],r}async function dT(e){var t,n;return de.initial&&(ir=null),ir?e.debug&&Z("cached model:",ir.modelUrl):(ir=await Be(We(e.modelBasePath,((t=e.face.mesh)==null?void 0:t.modelPath)||"")),!ir||!ir.modelUrl?Z("load model failed:",(n=e.face.mesh)==null?void 0:n.modelPath):e.debug&&Z("load model:",ir.modelUrl)),Wl=ir.inputs[0].shape?ir.inputs[0].shape[2]:0,ir}var pT=zl,hT=Op;var Ss,w0=[],fT=0,mT=0,Fb=Number.MAX_SAFE_INTEGER;async function gT(e){var n,s;let t=We(e.modelBasePath,((n=e.face.description)==null?void 0:n.modelPath)||"");return de.initial&&(Ss=null),Ss?e.debug&&Z("cached model:",t):(Ss=await Be(t),Ss?e.debug&&Z("load model:",t):Z("load model failed:",((s=e.face.description)==null?void 0:s.modelPath)||"")),Ss}function Ob(e){let t=e.image||e.tensor||e;if(!(Ss==null?void 0:Ss.inputs[0].shape))return t;let n=Ce.resizeBilinear(t,[Ss.inputs[0].shape[2],Ss.inputs[0].shape[1]],!1),s=L(n,Yn);return te(n),s}async function Mb(e,t,n,s){var o,i,l,c;if(!Ss)return{age:0,gender:"unknown",genderScore:0,descriptor:[]};let r=Fb<(((o=t.face.description)==null?void 0:o.skipFrames)||0),a=(((i=t.face.description)==null?void 0:i.skipTime)||0)>ie()-fT;return t.skipAllowed&&r&&a&&mT===s&&((l=w0[n])==null?void 0:l.age)&&((c=w0[n])==null?void 0:c.age)>0?(Fb++,w0[n]):(Fb=0,new Promise(async u=>{var p,h;let d={age:0,gender:"unknown",genderScore:0,descriptor:[]};if((p=t.face.description)==null?void 0:p.enabled){let f=Ob(e),m=Ss==null?void 0:Ss.execute(f);fT=ie(),te(f);let A=await(await m.find(R=>R.shape[1]===1)).data(),x=Math.trunc(200*Math.abs(A[0]-.5))/100;x>(((h=t.face.description)==null?void 0:h.minConfidence)||0)&&(d.gender=A[0]<=.5?"female":"male",d.genderScore=Math.min(.99,x));let y=Zs(m.find(R=>R.shape[1]===100),1),b=(await y.data())[0];te(y);let k=await m.find(R=>R.shape[1]===100).data();d.age=Math.round(k[b-1]>k[b+1]?10*b-100*k[b-1]:10*b+100*k[b+1])/10;let I=m.find(R=>R.shape[1]===1024),N=I?await I.data():[];d.descriptor=Array.from(N),m.forEach(R=>te(R))}w0[n]=d,mT=s,u(d)}))}function k0(e){return[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])]}function Wp(e){return[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2]}function AT(e,t,n){let s=t.shape[1],r=t.shape[2],a=[[e.startPoint[1]/s,e.startPoint[0]/r,e.endPoint[1]/s,e.endPoint[0]/r]];return Ce.cropAndResize(t,a,[0],n)}function yT(e,t){let n=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],s=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]],r=e.palmLandmarks.map(a=>[a[0]*t[0],a[1]*t[1]]);return{startPoint:n,endPoint:s,palmLandmarks:r,confidence:e.confidence}}function S0(e,t=1.5){let n=Wp(e),s=k0(e),r=[t*s[0]/2,t*s[1]/2],a=[n[0]-r[0],n[1]-r[1]],o=[n[0]+r[0],n[1]+r[1]];return{startPoint:a,endPoint:o,palmLandmarks:e.palmLandmarks}}function I0(e){let t=Wp(e),n=k0(e),r=Math.max(...n)/2,a=[t[0]-r,t[1]-r],o=[t[0]+r,t[1]+r];return{startPoint:a,endPoint:o,palmLandmarks:e.palmLandmarks}}function R2e(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function xT(e,t){let n=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]);return R2e(n)}var bT=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]];function ti(e,t){let n=0;for(let s=0;s[n.x,n.y]),this.anchorsTensor=fr(this.anchors),this.inputSize=this.model&&this.model.inputs&&this.model.inputs[0].shape?this.model.inputs[0].shape[2]:0,this.inputSizeTensor=Vt([this.inputSize,this.inputSize]),this.doubleInputSizeTensor=Vt([this.inputSize*2,this.inputSize*2])}normalizeBoxes(t){let n={};n.boxOffsets=Pe(t,[0,0],[-1,2]),n.boxSizes=Pe(t,[0,2],[-1,2]),n.div=ge(n.boxOffsets,this.inputSizeTensor),n.boxCenterPoints=ue(n.div,this.anchorsTensor),n.halfBoxSizes=ge(n.boxSizes,this.doubleInputSizeTensor),n.sub=fe(n.boxCenterPoints,n.halfBoxSizes),n.startPoints=L(n.sub,this.inputSizeTensor),n.add=ue(n.boxCenterPoints,n.halfBoxSizes),n.endPoints=L(n.add,this.inputSizeTensor);let s=Wu([n.startPoints,n.endPoints],1);return Object.keys(n).forEach(r=>te(n[r])),s}normalizeLandmarks(t,n){let s={};s.reshape=H(t,[-1,7,2]),s.div=ge(s.reshape,this.inputSizeTensor),s.landmarks=ue(s.div,this.anchors[n]);let r=L(s.landmarks,this.inputSizeTensor);return Object.keys(s).forEach(a=>te(s[a])),r}async predict(t,n){let s={};s.resize=Ce.resizeBilinear(t,[this.inputSize,this.inputSize]),s.div=ge(s.resize,p0),s.image=fe(s.div,d0),s.batched=this.model.execute(s.image),s.predictions=ot(s.batched),s.slice=Pe(s.predictions,[0,0],[-1,1]),s.sigmoid=ms(s.slice),s.scores=ot(s.sigmoid);let r=await s.scores.data();s.boxes=Pe(s.predictions,[0,1],[-1,4]),s.norm=this.normalizeBoxes(s.boxes),s.nms=await Ce.nonMaxSuppressionAsync(s.norm,s.scores,3*n.hand.maxDetected,n.hand.iouThreshold,n.hand.minConfidence);let a=await s.nms.array(),o=[];for(let i of a){let l={};l.box=Pe(s.norm,[i,0],[1,-1]),l.slice=Pe(s.predictions,[i,5],[1,14]),l.norm=this.normalizeLandmarks(l.slice,i),l.palmLandmarks=H(l.norm,[-1,2]);let c=await l.box.data(),u=c.slice(0,2),d=c.slice(2,4),p=await l.palmLandmarks.array(),h={startPoint:u,endPoint:d,palmLandmarks:p,confidence:r[i]},f=yT(h,[t.shape[2]/this.inputSize,t.shape[1]/this.inputSize]);o.push(f),Object.keys(l).forEach(m=>te(l[m]))}return Object.keys(s).forEach(i=>te(s[i])),o}};var _2e=5,ST=1.65,IT=[0,5,9,13,17,1,2],D2e=0,P2e=2,CT=0,Wb=class{constructor(t,n){he(this,"handDetector");he(this,"handPoseModel");he(this,"inputSize");he(this,"storedBoxes");he(this,"skipped");he(this,"detectedHands");this.handDetector=t,this.handPoseModel=n,this.inputSize=this.handPoseModel&&this.handPoseModel.inputs[0].shape?this.handPoseModel.inputs[0].shape[2]:0,this.storedBoxes=[],this.skipped=Number.MAX_SAFE_INTEGER,this.detectedHands=0}calculateLandmarksBoundingBox(t){let n=t.map(o=>o[0]),s=t.map(o=>o[1]),r=[Math.min(...n),Math.min(...s)],a=[Math.max(...n),Math.max(...s)];return{startPoint:r,endPoint:a}}getBoxForPalmLandmarks(t,n){let s=t.map(a=>Lb([...a,1],n)),r=this.calculateLandmarksBoundingBox(s);return S0(I0(r),_2e)}getBoxForHandLandmarks(t){let n=this.calculateLandmarksBoundingBox(t),s=S0(I0(n),ST);s.palmLandmarks=[];for(let r=0;r[o[0]*(h[0]-this.inputSize/2),o[1]*(h[1]-this.inputSize/2),o[2]*h[2]]),l=zb(s,[0,0]),c=i.map(h=>[...Lb(h,l),h[2]]),u=wT(r),d=[...Wp(n),1],p=[ti(d,u[0]),ti(d,u[1])];return c.map(h=>[Math.trunc(h[0]+p[0]),Math.trunc(h[1]+p[1]),Math.trunc(h[2])])}async estimateHands(t,n){let s=!1,r,a=(n.hand.skipTime||0)>ie()-CT,o=this.skipped<(n.hand.skipFrames||0);n.skipAllowed&&a&&o&&(r=await this.handDetector.predict(t,n),this.skipped=0),n.skipAllowed&&this.skipped++,r&&r.length>0&&(r.length!==this.detectedHands&&this.detectedHands!==n.hand.maxDetected||!n.hand.landmarks)&&(this.detectedHands=0,this.storedBoxes=[...r],this.storedBoxes.length>0&&(s=!0));let i=[];for(let l=0;l=n.hand.minConfidence/4){let w=H(y,[-1,3]),k=await w.array();te(y),te(w);let I=this.transformRawCoords(k,m,u,f),N=this.getBoxForHandLandmarks(I);this.storedBoxes[l]={...N,confidence:b};let R={landmarks:I,confidence:b,boxConfidence:c.confidence,fingerConfidence:b,box:{topLeft:N.startPoint,bottomRight:N.endPoint}};i.push(R)}else this.storedBoxes[l]=null;te(y)}else{let u=S0(I0(c),ST),d={confidence:c.confidence,boxConfidence:c.confidence,fingerConfidence:0,box:{topLeft:u.startPoint,bottomRight:u.endPoint},landmarks:[]};i.push(d)}}return this.storedBoxes=this.storedBoxes.filter(l=>l!==null),this.detectedHands=i.length,i.length>n.hand.maxDetected&&(i.length=n.hand.maxDetected),i}};var es={thumb:0,index:1,middle:2,ring:3,pinky:4,all:[0,1,2,3,4],nameMapping:{0:"thumb",1:"index",2:"middle",3:"ring",4:"pinky"},pointsMapping:{0:[[0,1],[1,2],[2,3],[3,4]],1:[[0,5],[5,6],[6,7],[7,8]],2:[[0,9],[9,10],[10,11],[11,12]],3:[[0,13],[13,14],[14,15],[15,16]],4:[[0,17],[17,18],[18,19],[19,20]]},getName:e=>es.nameMapping[e],getPoints:e=>es.pointsMapping[e]},ni={none:0,half:1,full:2,nameMapping:{0:"none",1:"half",2:"full"},getName:e=>ni.nameMapping[e]},zt={verticalUp:0,verticalDown:1,horizontalLeft:2,horizontalRight:3,diagonalUpRight:4,diagonalUpLeft:5,diagonalDownRight:6,diagonalDownLeft:7,nameMapping:{0:"verticalUp",1:"verticalDown",2:"horizontalLeft",3:"horizontalRight",4:"diagonalUpRight",5:"diagonalUpLeft",6:"diagonalDownRight",7:"diagonalDownLeft"},getName:e=>zt.nameMapping[e]},Vl=class{constructor(t){he(this,"name");he(this,"curls");he(this,"directions");he(this,"weights");he(this,"weightsRelative");this.name=t,this.curls={},this.directions={},this.weights=[1,1,1,1,1],this.weightsRelative=[1,1,1,1,1]}curl(t,n,s){typeof this.curls[t]=="undefined"&&(this.curls[t]=[]),this.curls[t].push([n,s])}direction(t,n,s){this.directions[t]||(this.directions[t]=[]),this.directions[t].push([n,s])}weight(t,n){this.weights[t]=n;let s=this.weights.reduce((r,a)=>r+a,0);this.weightsRelative=this.weights.map(r=>r*5/s)}matchAgainst(t,n){let s=0;for(let r in t){let a=t[r],o=this.curls[r];if(typeof o=="undefined"){s+=this.weightsRelative[r];continue}for(let[i,l]of o)if(a===i){s+=l*this.weightsRelative[r];break}}for(let r in n){let a=n[r],o=this.directions[r];if(typeof o=="undefined"){s+=this.weightsRelative[r];continue}for(let[i,l]of o)if(a===i){s+=l*this.weightsRelative[r];break}}return s/10}};var{thumb:Sr,index:pa,middle:ha,ring:Ul,pinky:Gl}=es,{none:Ir,half:F2e,full:Cr}=ni,{verticalUp:Pc,verticalDown:Sye,horizontalLeft:Vb,horizontalRight:O2e,diagonalUpRight:M2e,diagonalUpLeft:Fc,diagonalDownRight:Iye,diagonalDownLeft:Cye}=zt,si=new Vl("thumbs up");si.curl(Sr,Ir,1);si.direction(Sr,Pc,1);si.direction(Sr,Fc,.25);si.direction(Sr,M2e,.25);for(let e of[es.index,es.middle,es.ring,es.pinky])si.curl(e,Cr,1),si.direction(e,Vb,1),si.direction(e,O2e,1);var Qt=new Vl("victory");Qt.curl(Sr,F2e,.5);Qt.curl(Sr,Ir,.5);Qt.direction(Sr,Pc,1);Qt.direction(Sr,Fc,1);Qt.curl(pa,Ir,1);Qt.direction(pa,Pc,.75);Qt.direction(pa,Fc,1);Qt.curl(ha,Ir,1);Qt.direction(ha,Pc,1);Qt.direction(ha,Fc,.75);Qt.curl(Ul,Cr,1);Qt.direction(Ul,Pc,.2);Qt.direction(Ul,Fc,1);Qt.direction(Ul,Vb,.2);Qt.curl(Gl,Cr,1);Qt.direction(Gl,Pc,.2);Qt.direction(Gl,Fc,1);Qt.direction(Gl,Vb,.2);Qt.weight(pa,2);Qt.weight(ha,2);var ri=new Vl("point");ri.curl(Sr,Cr,1);ri.curl(pa,Ir,.5);ri.curl(ha,Cr,.5);ri.curl(Ul,Cr,.5);ri.curl(Gl,Cr,.5);ri.weight(pa,2);ri.weight(ha,2);var ai=new Vl("middle finger");ai.curl(Sr,Ir,1);ai.curl(pa,Cr,.5);ai.curl(ha,Cr,.5);ai.curl(Ul,Cr,.5);ai.curl(Gl,Cr,.5);ai.weight(pa,2);ai.weight(ha,2);var Oc=new Vl("open palm");Oc.curl(Sr,Ir,.75);Oc.curl(pa,Ir,.75);Oc.curl(ha,Ir,.75);Oc.curl(Ul,Ir,.75);Oc.curl(Gl,Ir,.75);var TT=[si,Qt,ri,ai,Oc];var z2e=.7,Hl={HALF_CURL_START_LIMIT:60,NO_CURL_START_LIMIT:130,DISTANCE_VOTE_POWER:1.1,SINGLE_ANGLE_VOTE_POWER:.9,TOTAL_ANGLE_VOTE_POWER:1.6};function NT(e,t,n,s){let r=(t-s)/(e-n),a=Math.atan(r)*180/Math.PI;return a<=0?a=-a:a>0&&(a=180-a),a}function ET(e,t){if(!e||!t)return[0,0];let n=NT(e[0],e[1],t[0],t[1]);if(e.length===2)return n;let s=NT(e[1],e[2],t[1],t[2]);return[n,s]}function RT(e,t=1){let n=0,s=0,r=0;return e>=75&&e<=105?n=1*t:e>=25&&e<=155?s=1*t:r=1*t,[n,s,r]}function L2e(e,t,n){let s=e[0]-t[0],r=e[0]-n[0],a=t[0]-n[0],o=e[1]-t[1],i=e[1]-n[1],l=t[1]-n[1],c=e[2]-t[2],u=e[2]-n[2],d=t[2]-n[2],p=Math.sqrt(s*s+o*o+c*c),h=Math.sqrt(r*r+i*i+u*u),f=Math.sqrt(a*a+l*l+d*d),m=(f*f+p*p-h*h)/(2*f*p);m>1?m=1:m<-1&&(m=-1);let g=Math.acos(m);g=57.2958*g%180;let A;return g>Hl.NO_CURL_START_LIMIT?A=ni.none:g>Hl.HALF_CURL_START_LIMIT?A=ni.half:A=ni.full,A}function $T(e,t,n,s){let r;return s===Math.abs(e)?e>0?r=zt.horizontalLeft:r=zt.horizontalRight:s===Math.abs(t)?t>0?r=zt.horizontalLeft:r=zt.horizontalRight:n>0?r=zt.horizontalLeft:r=zt.horizontalRight,r}function _T(e,t,n,s){let r;return s===Math.abs(e)?e<0?r=zt.verticalDown:r=zt.verticalUp:s===Math.abs(t)?t<0?r=zt.verticalDown:r=zt.verticalUp:n<0?r=zt.verticalDown:r=zt.verticalUp,r}function B2e(e,t,n,s,r,a,o,i){let l,c=_T(e,t,n,s),u=$T(r,a,o,i);return c===zt.verticalUp?u===zt.horizontalLeft?l=zt.diagonalUpLeft:l=zt.diagonalUpRight:u===zt.horizontalLeft?l=zt.diagonalDownLeft:l=zt.diagonalDownRight,l}function W2e(e,t,n,s){let r=e[0]-t[0],a=e[0]-n[0],o=t[0]-n[0],i=e[1]-t[1],l=e[1]-n[1],c=t[1]-n[1],u=Math.max(Math.abs(r),Math.abs(a),Math.abs(o)),d=Math.max(Math.abs(i),Math.abs(l),Math.abs(c)),p=0,h=0,f=0,m=d/(u+1e-5);m>1.5?p+=Hl.DISTANCE_VOTE_POWER:m>.66?h+=Hl.DISTANCE_VOTE_POWER:f+=Hl.DISTANCE_VOTE_POWER;let g=Math.sqrt(r*r+i*i),A=Math.sqrt(a*a+l*l),x=Math.sqrt(o*o+c*c),y=Math.max(g,A,x),b=e[0],w=e[1],k=n[0],I=n[1];y===g?(k=n[0],I=n[1]):y===x&&(b=t[0],w=t[1]);let O=ET([b,w],[k,I]),$=RT(O,Hl.TOTAL_ANGLE_VOTE_POWER);p+=$[0],h+=$[1],f+=$[2];for(let T of s){let F=RT(T,Hl.SINGLE_ANGLE_VOTE_POWER);p+=F[0],h+=F[1],f+=F[2]}let P;return p===Math.max(p,h,f)?P=_T(l,i,c,d):f===Math.max(h,f)?P=$T(a,r,o,u):P=B2e(l,i,c,d,a,r,o,u),P}function DT(e){let t=[],n=[],s=[],r=[];if(!e)return{curls:s,directions:r};for(let a of es.all){let o=es.getPoints(a),i=[],l=[];for(let c of o){let u=e[c[0]],d=e[c[1]],p=ET(u,d),h=p[0],f=p[1];i.push(h),l.push(f)}t.push(i),n.push(l)}for(let a of es.all){let o=a===es.thumb?1:0,i=es.getPoints(a),l=e[i[o][0]],c=e[i[o+1][1]],u=e[i[3][1]],d=L2e(l,c,u),p=W2e(l,c,u,t[a].slice(o));s[a]=d,r[a]=p}return{curls:s,directions:r}}function C0(e){if(!e||e.length===0)return null;let t=DT(e),n={};for(let s of es.all)n[es.getName(s)]={curl:ni.getName(t.curls[s]),direction:zt.getName(t.directions[s])};return n}function PT(e){let t=[];if(!e||e.length===0)return t;let n=DT(e);for(let s of TT){let r=s.matchAgainst(n.curls,n.directions);r>=z2e&&t.push({name:s.name,confidence:r})}return t}var FT={thumb:[1,2,3,4],index:[5,6,7,8],middle:[9,10,11,12],ring:[13,14,15,16],pinky:[17,18,19,20],palm:[0]},fa,ma,OT;async function Ub(e,t){let n=await OT.estimateHands(e,t);if(!n)return[];let s=[];for(let r=0;rn[r].landmarks[d]);let o=n[r].landmarks,i=[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,0,0],l=[0,0,0,0];if(o&&o.length>0){for(let u of o)u[0]i[2]&&(i[2]=u[0]),u[1]>i[3]&&(i[3]=u[1]);i[2]-=i[0],i[3]-=i[1],l=[i[0]/(e.shape[2]||0),i[1]/(e.shape[1]||0),i[2]/(e.shape[2]||0),i[3]/(e.shape[1]||0)]}else i=n[r].box?[Math.trunc(Math.max(0,n[r].box.topLeft[0])),Math.trunc(Math.max(0,n[r].box.topLeft[1])),Math.trunc(Math.min(e.shape[2]||0,n[r].box.bottomRight[0])-Math.max(0,n[r].box.topLeft[0])),Math.trunc(Math.min(e.shape[1]||0,n[r].box.bottomRight[1])-Math.max(0,n[r].box.topLeft[1]))]:[0,0,0,0],l=[n[r].box.topLeft[0]/(e.shape[2]||0),n[r].box.topLeft[1]/(e.shape[1]||0),(n[r].box.bottomRight[0]-n[r].box.topLeft[0])/(e.shape[2]||0),(n[r].box.bottomRight[1]-n[r].box.topLeft[1])/(e.shape[1]||0)];let c=C0(o);s.push({id:r,score:Math.round(100*n[r].confidence)/100,boxScore:Math.round(100*n[r].boxConfidence)/100,fingerScore:Math.round(100*n[r].fingerConfidence)/100,label:"hand",box:i,boxRaw:l,keypoints:o,annotations:a,landmarks:c})}return s}async function Gb(e){var n,s,r,a,o,i;de.initial&&(fa=null,ma=null),!fa||!ma?([fa,ma]=await Promise.all([e.hand.enabled?Be(We(e.modelBasePath,((n=e.hand.detector)==null?void 0:n.modelPath)||""),{fromTFHub:(((s=e.hand.detector)==null?void 0:s.modelPath)||"").includes("tfhub.dev")}):null,e.hand.landmarks?Be(We(e.modelBasePath,((r=e.hand.skeleton)==null?void 0:r.modelPath)||""),{fromTFHub:(((a=e.hand.skeleton)==null?void 0:a.modelPath)||"").includes("tfhub.dev")}):null]),e.hand.enabled&&(!fa||!fa.modelUrl?Z("load model failed:",((o=e.hand.detector)==null?void 0:o.modelPath)||""):e.debug&&Z("load model:",fa.modelUrl),!ma||!ma.modelUrl?Z("load model failed:",((i=e.hand.skeleton)==null?void 0:i.modelPath)||""):e.debug&&Z("load model:",ma.modelUrl))):(e.debug&&Z("cached model:",fa.modelUrl),e.debug&&Z("cached model:",ma.modelUrl));let t=new Bb(fa);return OT=new Wb(t,ma),[fa,ma]}function jl(e,t=[1,1]){let n=[e.map(i=>i[0]),e.map(i=>i[1])],s=[Math.min(...n[0]),Math.min(...n[1])],r=[Math.max(...n[0]),Math.max(...n[1])],a=[s[0],s[1],r[0]-s[0],r[1]-s[1]],o=[a[0]/t[0],a[1]/t[1],a[2]/t[0],a[3]/t[1]];return{box:a,boxRaw:o}}function MT(e,t=[1,1]){let n=[e.map(c=>c[0]),e.map(c=>c[1])],s=[Math.min(...n[0]),Math.min(...n[1])],r=[Math.max(...n[0]),Math.max(...n[1])],a=[(s[0]+r[0])/2,(s[1]+r[1])/2],o=Math.max(a[0]-s[0],a[1]-s[1],-a[0]+r[0],-a[1]+r[1]),i=[Math.trunc(a[0]-o),Math.trunc(a[1]-o),Math.trunc(2*o),Math.trunc(2*o)],l=[i[0]/t[0],i[1]/t[1],i[2]/t[0],i[3]/t[1]];return{box:i,boxRaw:l}}function T0(e,t){let n=[e[2]*t,e[3]*t];return[e[0]-(n[0]-e[2])/2,e[1]-(n[1]-e[3])/2,n[0],n[1]]}function Hb(e){return[Math.max(0,e[1]),Math.max(0,e[0]),Math.min(1,e[3]+e[1]),Math.min(1,e[2]+e[0])]}var Ct=[null,null],V2e=["StatefulPartitionedCall/Postprocessor/Slice","StatefulPartitionedCall/Postprocessor/ExpandDims_1"],oi=[[0,0],[0,0]],U2e=["hand","fist","pinch","point","face","tip","pinchtip"],zT=4,LT=1.6,G2e=512,H2e=1.4,N0=Number.MAX_SAFE_INTEGER,jb=0,ga=[0,0],qt={boxes:[],hands:[]},BT={thumb:[1,2,3,4],index:[5,6,7,8],middle:[9,10,11,12],ring:[13,14,15,16],pinky:[17,18,19,20],palm:[0]};async function WT(e){var t,n;if(de.initial&&(Ct[0]=null),Ct[0])e.debug&&Z("cached model:",Ct[0].modelUrl);else{E0(["tensorlistreserve","enter","tensorlistfromtensor","merge","loopcond","switch","exit","tensorliststack","nextiteration","tensorlistsetitem","tensorlistgetitem","reciprocal","shape","split","where"],e),Ct[0]=await Be(We(e.modelBasePath,((t=e.hand.detector)==null?void 0:t.modelPath)||""));let s=Object.values(Ct[0].modelSignature.inputs);oi[0][0]=Array.isArray(s)?parseInt(s[0].tensorShape.dim[1].size):0,oi[0][1]=Array.isArray(s)?parseInt(s[0].tensorShape.dim[2].size):0,!Ct[0]||!Ct[0].modelUrl?Z("load model failed:",(n=e.hand.detector)==null?void 0:n.modelPath):e.debug&&Z("load model:",Ct[0].modelUrl)}return Ct[0]}async function VT(e){var t,n;if(de.initial&&(Ct[1]=null),Ct[1])e.debug&&Z("cached model:",Ct[1].modelUrl);else{Ct[1]=await Be(We(e.modelBasePath,((t=e.hand.skeleton)==null?void 0:t.modelPath)||""));let s=Object.values(Ct[1].modelSignature.inputs);oi[1][0]=Array.isArray(s)?parseInt(s[0].tensorShape.dim[1].size):0,oi[1][1]=Array.isArray(s)?parseInt(s[0].tensorShape.dim[2].size):0,!Ct[1]||!Ct[1].modelUrl?Z("load model failed:",(n=e.hand.skeleton)==null?void 0:n.modelPath):e.debug&&Z("load model:",Ct[1].modelUrl)}return Ct[1]}async function j2e(e,t){let n=[];if(!e||!Ct[0])return n;let s={},r=(e.shape[2]||1)/(e.shape[1]||1),a=Math.min(Math.round((e.shape[1]||0)/8)*8,G2e),o=Math.round(a*r/8)*8;s.resize=Ce.resizeBilinear(e,[a,o]),s.cast=me(s.resize,"int32"),[s.rawScores,s.rawBoxes]=await Ct[0].executeAsync(s.cast,V2e),s.boxes=ot(s.rawBoxes,[0,2]),s.scores=ot(s.rawScores,[0]);let i=os(s.scores,1);te(i[zT]),i.splice(zT,1),s.filtered=yn(i,1),te(i),s.max=An(s.filtered,1),s.argmax=Zs(s.filtered,1);let l=0;s.nms=await Ce.nonMaxSuppressionAsync(s.boxes,s.max,t.hand.maxDetected,t.hand.iouThreshold,t.hand.minConfidence);let c=await s.nms.data(),u=await s.max.data(),d=await s.argmax.data();for(let p of Array.from(c)){let h=Pe(s.boxes,p,1),f=await h.data();te(h);let m=[f[1],f[0],f[3]-f[1],f[2]-f[0]],g=T0(m,H2e),A=Hb(g),x=[Math.trunc(m[0]*ga[0]),Math.trunc(m[1]*ga[1]),Math.trunc(m[2]*ga[0]),Math.trunc(m[3]*ga[1])],y=u[p],b=U2e[d[p]],w={id:l++,score:y,box:x,boxRaw:g,boxCrop:A,label:b};n.push(w)}return Object.keys(s).forEach(p=>te(s[p])),n.sort((p,h)=>h.score-p.score),n.length>(t.hand.maxDetected||1)&&(n.length=t.hand.maxDetected||1),n}async function qb(e,t,n){let s={id:t.id,score:Math.round(100*t.score)/100,boxScore:Math.round(100*t.score)/100,fingerScore:0,box:t.box,boxRaw:t.boxRaw,label:t.label,keypoints:[],landmarks:{},annotations:{}};if(e&&Ct[1]&&n.hand.landmarks&&t.score>(n.hand.minConfidence||0)){let r={};r.crop=Ce.cropAndResize(e,[t.boxCrop],[0],[oi[1][0],oi[1][1]],"bilinear"),r.div=ge(r.crop,Yn),[r.score,r.keypoints]=Ct[1].execute(r.div,["Identity_1","Identity"]);let a=(await r.score.data())[0],o=(100-Math.trunc(100/(1+Math.exp(a))))/100;if(o>=(n.hand.minConfidence||0)){s.fingerScore=o,r.reshaped=H(r.keypoints,[-1,3]);let c=(await r.reshaped.array()).map(u=>[u[0]/oi[1][1],u[1]/oi[1][0],u[2]||0]).map(u=>[u[0]*t.boxRaw[2],u[1]*t.boxRaw[3],u[2]||0]);s.keypoints=c.map(u=>[ga[0]*(u[0]+t.boxRaw[0]),ga[1]*(u[1]+t.boxRaw[1]),u[2]||0]),s.landmarks=C0(s.keypoints);for(let u of Object.keys(BT))s.annotations[u]=BT[u].map(d=>s.landmarks&&s.keypoints[d]?s.keypoints[d]:null)}Object.keys(r).forEach(i=>te(r[i]))}return s}async function Xb(e,t){var r,a;if(!Ct[0]||!Ct[1]||!((r=Ct[0])==null?void 0:r.inputs[0].shape)||!((a=Ct[1])==null?void 0:a.inputs[0].shape))return[];ga=[e.shape[2]||0,e.shape[1]||0],N0++;let n=(t.hand.skipTime||0)>ie()-jb,s=N0<(t.hand.skipFrames||0);return t.skipAllowed&&n&&s?qt.hands:new Promise(async o=>{let i=3*(t.hand.skipTime||0)>ie()-jb,l=N0<3*(t.hand.skipFrames||0);t.skipAllowed&&qt.hands.length===t.hand.maxDetected?qt.hands=await Promise.all(qt.boxes.map(u=>qb(e,u,t))):t.skipAllowed&&i&&l&&qt.hands.length>0?qt.hands=await Promise.all(qt.boxes.map(u=>qb(e,u,t))):(qt.boxes=await j2e(e,t),jb=ie(),qt.hands=await Promise.all(qt.boxes.map(u=>qb(e,u,t))),N0=0);let c=[...qt.boxes];if(qt.boxes.length=0,t.cacheSensitivity>0)for(let u=0;u.05&&d.box[3]/(e.shape[1]||1)>.05&&qt.hands[u].fingerScore&&qt.hands[u].fingerScore>(t.hand.minConfidence||0)){let p=T0(d.box,LT),h=T0(d.boxRaw,LT),f=Hb(h);qt.boxes.push({...c[u],box:p,boxRaw:h,boxCrop:f})}}for(let u=0;uie()-GT,a=Kb<(((i=t.face.liveness)==null?void 0:i.skipFrames)||0);return t.skipAllowed&&r&&a&&UT===s&&R0[n]?(Kb++,R0[n]):(Kb=0,new Promise(async l=>{let c=Ce.resizeBilinear(e,[(pn==null?void 0:pn.inputs[0].shape)?pn.inputs[0].shape[2]:0,(pn==null?void 0:pn.inputs[0].shape)?pn.inputs[0].shape[1]:0],!1),u=pn==null?void 0:pn.execute(c),d=(await u.data())[0];R0[n]=Math.round(100*d)/100,UT=s,GT=ie(),te([c,u]),l(R0[n])}))}var e5={};Qc(e5,{connected:()=>_0,horizontal:()=>Yb,kpt:()=>$0,relative:()=>Qb,vertical:()=>Jb});var $0=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],Yb=[["leftEye","rightEye"],["leftEar","rightEar"],["leftShoulder","rightShoulder"],["leftElbow","rightElbow"],["leftWrist","rightWrist"],["leftHip","rightHip"],["leftKnee","rightKnee"],["leftAnkle","rightAnkle"]],Jb=[["leftKnee","leftShoulder"],["rightKnee","rightShoulder"],["leftAnkle","leftKnee"],["rightAnkle","rightKnee"]],Qb=[[["leftHip","rightHip"],["leftShoulder","rightShoulder"]],[["leftElbow","rightElbow"],["leftShoulder","rightShoulder"]]],_0={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var jT=.005,Is={keypoints:[],padding:[[0,0],[0,0],[0,0],[0,0]]};function t5(e){for(let t of Yb){let n=e.keypoints.findIndex(r=>r.part===t[0]),s=e.keypoints.findIndex(r=>r.part===t[1]);if(e.keypoints[n]&&e.keypoints[s]&&e.keypoints[n].position[0]r&&r.part===t[0]),s=e.keypoints.findIndex(r=>r&&r.part===t[1]);e.keypoints[n]&&e.keypoints[s]&&e.keypoints[n].position[1]c&&c.part===t[0]),r=e.keypoints.findIndex(c=>c&&c.part===t[1]),a=e.keypoints.findIndex(c=>c&&c.part===n[0]),o=e.keypoints.findIndex(c=>c&&c.part===n[1]);if(!e.keypoints[a]||!e.keypoints[o])continue;let i=e.keypoints[s]?[Math.abs(e.keypoints[a].position[0]-e.keypoints[s].position[0]),Math.abs(e.keypoints[o].position[0]-e.keypoints[s].position[0])]:[0,0],l=e.keypoints[r]?[Math.abs(e.keypoints[o].position[0]-e.keypoints[r].position[0]),Math.abs(e.keypoints[a].position[0]-e.keypoints[r].position[0])]:[0,0];if(i[0]>i[1]||l[0]>l[1]){let c=e.keypoints[s];e.keypoints[s]=e.keypoints[r],e.keypoints[r]=c}}}function qT(e){for(let t=0;te.shape[1]?Math.trunc((e.shape[2]-e.shape[1])/2):0,e.shape[2]>e.shape[1]?Math.trunc((e.shape[2]-e.shape[1])/2):0],[e.shape[1]>e.shape[2]?Math.trunc((e.shape[1]-e.shape[2])/2):0,e.shape[1]>e.shape[2]?Math.trunc((e.shape[1]-e.shape[2])/2):0],[0,0]],n.pad=Js(e,Is.padding),n.resize=Ce.resizeBilinear(n.pad,[t,t]);let s=me(n.resize,"int32");return Object.keys(n).forEach(r=>te(n[r])),s}function KT(e,t){e.keypoints=e.keypoints.filter(s=>s&&s.position);for(let s of e.keypoints)s.position=[s.position[0]*(t[0]+Is.padding[2][0]+Is.padding[2][1])/t[0]-Is.padding[2][0],s.position[1]*(t[1]+Is.padding[1][0]+Is.padding[1][1])/t[1]-Is.padding[1][0]],s.positionRaw=[s.position[0]/t[0],s.position[1]/t[1]];let n=jl(e.keypoints.map(s=>s.position),t);return e.box=n.box,e.boxRaw=n.boxRaw,e}var Fn,ZT=0,n5=Number.MAX_SAFE_INTEGER,ql={boxes:[],bodies:[],last:0};async function YT(e){return de.initial&&(Fn=null),Fn?e.debug&&Z("cached model:",Fn.modelUrl):(E0(["size"],e),Fn=await Be(We(e.modelBasePath,e.body.modelPath||"")),!Fn||!Fn.modelUrl?Z("load model failed:",e.body.modelPath):e.debug&&Z("load model:",Fn.modelUrl)),ZT=Fn.inputs[0].shape?Fn.inputs[0].shape[2]:0,Fn}async function q2e(e,t,n){let s=e[0][0],r=[],a=0;for(let u=0;ut.body.minConfidence){let d=[s[u][1],s[u][0]];r.push({score:Math.round(100*a)/100,part:$0[u],positionRaw:d,position:[Math.round((n.shape[2]||0)*d[0]),Math.round((n.shape[1]||0)*d[1])]})}a=r.reduce((u,d)=>d.score>u?d.score:u,0);let o=[],i=jl(r.map(u=>u.position),[n.shape[2],n.shape[1]]),l={};for(let[u,d]of Object.entries(_0)){let p=[];for(let h=0;hg.part===d[h]),m=r.find(g=>g.part===d[h+1]);f&&m&&f.score>(t.body.minConfidence||0)&&m.score>(t.body.minConfidence||0)&&p.push([f.position,m.position])}l[u]=p}let c={id:0,score:a,box:i.box,boxRaw:i.boxRaw,keypoints:r,annotations:l};return t5(c),o.push(c),o}async function X2e(e,t,n){let s=[];for(let r=0;rt.body.minConfidence){let i=[];for(let d=0;d<17;d++){let p=a[3*d+2];if(p>t.body.minConfidence){let h=[a[3*d+1],a[3*d+0]];i.push({part:$0[d],score:Math.round(100*p)/100,positionRaw:h,position:[Math.round((n.shape[2]||0)*h[0]),Math.round((n.shape[1]||0)*h[1])]})}}let l=jl(i.map(d=>d.position),[n.shape[2],n.shape[1]]),c={};for(let[d,p]of Object.entries(_0)){let h=[];for(let f=0;fA.part===p[f]),g=i.find(A=>A.part===p[f+1]);m&&g&&m.score>(t.body.minConfidence||0)&&g.score>(t.body.minConfidence||0)&&h.push([m.position,g.position])}c[d]=h}let u={id:r,score:o,box:l.box,boxRaw:l.boxRaw,keypoints:[...i],annotations:c};t5(u),s.push(u)}}return s.sort((r,a)=>a.score-r.score),s.length>t.body.maxDetected&&(s.length=t.body.maxDetected),s}async function s5(e,t){if(!Fn||!(Fn==null?void 0:Fn.inputs[0].shape))return[];t.skipAllowed||(ql.boxes.length=0),n5++;let n=(t.body.skipTime||0)>ie()-ql.last,s=n5<(t.body.skipFrames||0);return t.skipAllowed&&n&&s?ql.bodies:new Promise(async r=>{let a={};n5=0,a.input=XT(e,ZT),a.res=Fn==null?void 0:Fn.execute(a.input),ql.last=ie();let o=await a.res.array();ql.bodies=a.res.shape[2]===17?await q2e(o,t,e):await X2e(o,t,e);for(let i of ql.bodies)KT(i,[e.shape[2]||1,e.shape[1]||1]),qT(i.keypoints);Object.keys(a).forEach(i=>te(a[i])),r(ql.bodies)})}var Vs,D0=[],JT=0,r5=Number.MAX_SAFE_INTEGER,P0=2.5;async function QT(e){if(!Vs||de.initial){Vs=await Be(We(e.modelBasePath,e.object.modelPath||""));let t=Object.values(Vs.modelSignature.inputs);Vs.inputSize=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):null,!Vs||!Vs.modelUrl?Z("load model failed:",e.object.modelPath):e.debug&&Z("load model:",Vs.modelUrl)}else e.debug&&Z("cached model:",Vs.modelUrl);return Vs}async function K2e(e,t,n,s){let r=0,a=[];for(let c of[1,2,4])X(async()=>{var g,A;let u=c*13,d=(g=e.find(x=>x.shape[1]===u**2&&x.shape[2]===Rc.length))==null?void 0:g.squeeze(),p=(A=e.find(x=>x.shape[1]===u**2&&x.shape[2]s.object.minConfidence&&y!==61){let w=(.5+Math.trunc(x%u))/u,k=(.5+Math.trunc(x/u))/u,I=f[x].map(U=>U*(u/c/t)),[N,R]=[w-P0/c*I[0],k-P0/c*I[1]],[O,$]=[w+P0/c*I[2]-N,k+P0/c*I[3]-R],P=[N,R,O,$];P=P.map(U=>Math.max(0,Math.min(U,1)));let T=[P[0]*n[0],P[1]*n[1],P[2]*n[0],P[3]*n[1]],F={id:r++,score:Math.round(100*b)/100,class:y+1,label:Rc[y].label,box:T.map(U=>Math.trunc(U)),boxRaw:P};a.push(F)}}});e.forEach(c=>te(c));let o=a.map(c=>[c.boxRaw[1],c.boxRaw[0],c.boxRaw[3],c.boxRaw[2]]),i=a.map(c=>c.score),l=[];if(o&&o.length>0){let c=await Ce.nonMaxSuppressionAsync(o,i,s.object.maxDetected,s.object.iouThreshold,s.object.minConfidence);l=await c.data(),te(c)}return a=a.filter((c,u)=>l.includes(u)).sort((c,u)=>u.score-c.score),a}async function a5(e,t){let n=(t.object.skipTime||0)>ie()-JT,s=r5<(t.object.skipFrames||0);return t.skipAllowed&&n&&s&&D0.length>0?(r5++,D0):(r5=0,!de.kernels.includes("mod")||!de.kernels.includes("sparsetodense")?D0:new Promise(async r=>{let a=[e.shape[2],e.shape[1]],o=Ce.resizeBilinear(e,[Vs.inputSize,Vs.inputSize],!1),i=ge(o,Yn),l=i.transpose([0,3,1,2]);te(i),te(o);let c;t.object.enabled&&(c=Vs.execute(l)),JT=ie(),te(l);let u=await K2e(c,Vs.inputSize,a,t);D0=u,r(u)}))}var Vp=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],Z2e=Vp.length,Up=Vp.reduce((e,t,n)=>(e[t]=n,e),{}),Y2e=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]],mxe=Y2e.map(([e,t])=>[Up[e],Up[t]]),eN=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]];function tN(e){let t=e.reduce(({maxX:n,maxY:s,minX:r,minY:a},{position:{x:o,y:i}})=>({maxX:Math.max(n,o),maxY:Math.max(s,i),minX:Math.min(r,o),minY:Math.min(a,i)}),{maxX:Number.NEGATIVE_INFINITY,maxY:Number.NEGATIVE_INFINITY,minX:Number.POSITIVE_INFINITY,minY:Number.POSITIVE_INFINITY});return[t.minX,t.minY,t.maxX-t.minX,t.maxY-t.minY]}function nN(e,[t,n],[s,r]){let a=t/s,o=n/r,i=(c,u)=>({id:u,score:c.score,boxRaw:[c.box[0]/r,c.box[1]/s,c.box[2]/r,c.box[3]/s],box:[Math.trunc(c.box[0]*o),Math.trunc(c.box[1]*a),Math.trunc(c.box[2]*o),Math.trunc(c.box[3]*a)],keypoints:c.keypoints.map(({score:d,part:p,position:h})=>({score:d,part:p,position:[Math.trunc(h.x*o),Math.trunc(h.y*a)],positionRaw:[h.x/s,h.y/s]}))});return e.map((c,u)=>i(c,u))}var o5=class{constructor(t,n){he(this,"priorityQueue");he(this,"numberOfElements");he(this,"getElementValue");this.priorityQueue=new Array(t),this.numberOfElements=-1,this.getElementValue=n}enqueue(t){this.priorityQueue[++this.numberOfElements]=t,this.swim(this.numberOfElements)}dequeue(){let t=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,t}empty(){return this.numberOfElements===-1}size(){return this.numberOfElements+1}all(){return this.priorityQueue.slice(0,this.numberOfElements+1)}max(){return this.priorityQueue[0]}swim(t){for(;t>0&&this.less(Math.floor(t/2),t);)this.exchange(t,Math.floor(t/2)),t=Math.floor(t/2)}sink(t){for(;2*t<=this.numberOfElements;){let n=2*t;if(nn?n:e}function sN(e,t,n,s){let r=n-e,a=s-t;return r*r+a*a}function c5(e,t){return{x:e.x+t.x,y:e.y+t.y}}var Cs,J2e=["MobilenetV1/offset_2/BiasAdd","MobilenetV1/heatmap_2/BiasAdd","MobilenetV1/displacement_fwd_2/BiasAdd","MobilenetV1/displacement_bwd_2/BiasAdd"],F0=1,Mc=16,Q2e=50**2;function rN(e,t,n,s,r,a,o=2){let i=A=>({y:a.get(A.y,A.x,e),x:a.get(A.y,A.x,a.shape[2]/2+e)}),l=(A,x,y)=>({y:u5(Math.round(A.y/Mc),0,x-1),x:u5(Math.round(A.x/Mc),0,y-1)}),[c,u]=s.shape,d=l(t.position,c,u),p=i(d),f=c5(t.position,p);for(let A=0;A[Up[p],Up[h]]),o=a.map(([,p])=>p),i=a.map(([p])=>p),l=t.shape[2],c=o.length,u=new Array(l),d=l5(e.part,Mc,n);u[e.part.id]={score:e.score,part:Vp[e.part.id],position:d};for(let p=c-1;p>=0;--p){let h=o[p],f=i[p];u[h]&&!u[f]&&(u[f]=rN(p,u[h],f,t,n,r))}for(let p=0;pt){i=!1;break}if(!i)break}return i}function n1e(e,t){let[n,s,r]=t.shape,a=new o5(n*s*r,({score:o})=>o);for(let o=0;o{var o;let a=(o=r[s])==null?void 0:o.position;return a?sN(n,t,a.y,a.x)<=Q2e:!1})}function s1e(e,t){return t.reduce((s,{position:r,score:a},o)=>(aN(e,r,o)||(s+=a),s),0)/t.length}function r1e(e,t,n,s,r,a){let o=[],i=n1e(a,t);for(;o.lengthh.score>a);let d=s1e(o,u),p=tN(u);d>a&&o.push({keypoints:u,box:p,score:Math.round(100*d)/100})}return o}async function d5(e,t){let n=X(()=>{if(!Cs.inputs[0].shape)return[];let o=Ce.resizeBilinear(e,[Cs.inputs[0].shape[2],Cs.inputs[0].shape[1]]),i=fe(ge(me(o,"float32"),127.5),1),c=Cs.execute(i,J2e).map(u=>ot(u,[0]));return c[1]=c[1].sigmoid(),c}),s=await Promise.all(n.map(o=>o.buffer()));for(let o of n)te(o);let r=await r1e(s[0],s[1],s[2],s[3],t.body.maxDetected,t.body.minConfidence);return Cs.inputs[0].shape?nN(r,[e.shape[1],e.shape[2]],[Cs.inputs[0].shape[2],Cs.inputs[0].shape[1]]):[]}async function oN(e){return!Cs||de.initial?(Cs=await Be(We(e.modelBasePath,e.body.modelPath||"")),!Cs||!Cs.modelUrl?Z("load model failed:",e.body.modelPath):e.debug&&Z("load model:",Cs.modelUrl)):e.debug&&Z("cached model:",Cs.modelUrl),Cs}var Us,p5=!1;async function h5(e){return!Us||de.initial?(Us=await Be(We(e.modelBasePath,e.segmentation.modelPath||"")),!Us||!Us.modelUrl?Z("load model failed:",e.segmentation.modelPath):e.debug&&Z("load model:",Us.modelUrl)):e.debug&&Z("cached model:",Us.modelUrl),Us}async function iN(e,t,n){var m,g;if(p5)return{data:[],canvas:null,alpha:null};p5=!0,Us||await h5(n);let s=await Tc(e,n),r=((m=s.tensor)==null?void 0:m.shape[2])||0,a=((g=s.tensor)==null?void 0:g.shape[1])||0;if(!s.tensor)return{data:[],canvas:null,alpha:null};let o={};o.resize=Ce.resizeBilinear(s.tensor,[Us.inputs[0].shape?Us.inputs[0].shape[1]:0,Us.inputs[0].shape?Us.inputs[0].shape[2]:0],!1),te(s.tensor),o.norm=ge(o.resize,Yn),o.res=Us.execute(o.norm),o.squeeze=ot(o.res,0),o.squeeze.shape[2]===2?(o.softmax=Xu(o.squeeze),[o.bg,o.fg]=os(o.softmax,2),o.expand=Kt(o.fg,2),o.pad=Kt(o.expand,0),o.crop=Ce.cropAndResize(o.pad,[[0,0,.5,.5]],[0],[r,a]),o.data=ot(o.crop,0)):o.data=Ce.resizeBilinear(o.squeeze,[a,r]);let i=Array.from(await o.data.data());if(de.node&&!de.Canvas&&typeof ImageData=="undefined")return n.debug&&Z("canvas support missing"),Object.keys(o).forEach(A=>te(o[A])),{data:i,canvas:null,alpha:null};let l=Zn(r,a);await Ks.toPixels(o.data,l);let c=l.getContext("2d");n.segmentation.blur&&n.segmentation.blur>0&&(c.filter=`blur(${n.segmentation.blur}px)`);let u=c.getImageData(0,0,r,a),d=Zn(r,a),p=d.getContext("2d");s.canvas&&p.drawImage(s.canvas,0,0),p.globalCompositeOperation="darken",n.segmentation.blur&&n.segmentation.blur>0&&(p.filter=`blur(${n.segmentation.blur}px)`),p.drawImage(l,0,0),p.globalCompositeOperation="source-over",p.filter="none";let h=p.getImageData(0,0,r,a);for(let A=0;Ate(o[A])),p5=!1,{data:i,canvas:d,alpha:l}}var f5=class{constructor(){he(this,"ssrnetage",null);he(this,"gear",null);he(this,"blazeposedetect",null);he(this,"blazepose",null);he(this,"centernet",null);he(this,"efficientpose",null);he(this,"mobilefacenet",null);he(this,"emotion",null);he(this,"facedetect",null);he(this,"faceiris",null);he(this,"facemesh",null);he(this,"faceres",null);he(this,"ssrnetgender",null);he(this,"handpose",null);he(this,"handskeleton",null);he(this,"handtrack",null);he(this,"liveness",null);he(this,"movenet",null);he(this,"nanodet",null);he(this,"posenet",null);he(this,"segmentation",null);he(this,"antispoof",null)}};function m5(e){for(let t of Object.keys(e.models))e.models[t]=null}async function lN(e){var t,n,s,r,a,o,i,l,c,u,d,p,h,f,m,g,A,x,y,b,w,k,I,N,R,O,$,P,T,F,U,q,z;de.initial&&m5(e),e.config.hand.enabled&&(!e.models.handpose&&((n=(t=e.config.hand.detector)==null?void 0:t.modelPath)==null?void 0:n.includes("handdetect"))&&([e.models.handpose,e.models.handskeleton]=await Gb(e.config)),!e.models.handskeleton&&e.config.hand.landmarks&&((r=(s=e.config.hand.detector)==null?void 0:s.modelPath)==null?void 0:r.includes("handdetect"))&&([e.models.handpose,e.models.handskeleton]=await Gb(e.config))),e.config.body.enabled&&!e.models.blazepose&&((o=(a=e.config.body)==null?void 0:a.modelPath)==null?void 0:o.includes("blazepose"))&&(e.models.blazepose=H8(e.config)),e.config.body.enabled&&!e.models.blazeposedetect&&((i=e.config.body.detector)==null?void 0:i.modelPath)&&((c=(l=e.config.body)==null?void 0:l.modelPath)==null?void 0:c.includes("blazepose"))&&(e.models.blazeposedetect=G8(e.config)),e.config.body.enabled&&!e.models.efficientpose&&((d=(u=e.config.body)==null?void 0:u.modelPath)==null?void 0:d.includes("efficientpose"))&&(e.models.efficientpose=Z8(e.config)),e.config.body.enabled&&!e.models.movenet&&((h=(p=e.config.body)==null?void 0:p.modelPath)==null?void 0:h.includes("movenet"))&&(e.models.movenet=YT(e.config)),e.config.body.enabled&&!e.models.posenet&&((m=(f=e.config.body)==null?void 0:f.modelPath)==null?void 0:m.includes("posenet"))&&(e.models.posenet=oN(e.config)),e.config.face.enabled&&!e.models.facedetect&&(e.models.facedetect=B8(e.config)),e.config.face.enabled&&((g=e.config.face.antispoof)==null?void 0:g.enabled)&&!e.models.antispoof&&(e.models.antispoof=$8(e.config)),e.config.face.enabled&&((A=e.config.face.liveness)==null?void 0:A.enabled)&&!e.models.liveness&&(e.models.liveness=HT(e.config)),e.config.face.enabled&&((x=e.config.face.description)==null?void 0:x.enabled)&&!e.models.faceres&&(e.models.faceres=gT(e.config)),e.config.face.enabled&&((y=e.config.face.emotion)==null?void 0:y.enabled)&&!e.models.emotion&&(e.models.emotion=Q8(e.config)),e.config.face.enabled&&((b=e.config.face.iris)==null?void 0:b.enabled)&&!e.models.faceiris&&(e.models.faceiris=rT(e.config)),e.config.face.enabled&&((w=e.config.face.mesh)==null?void 0:w.enabled)&&!e.models.facemesh&&(e.models.facemesh=dT(e.config)),e.config.face.enabled&&((k=e.config.face.gear)==null?void 0:k.enabled)&&!e.models.gear&&(e.models.gear=v8(e.config)),e.config.face.enabled&&((I=e.config.face.ssrnet)==null?void 0:I.enabled)&&!e.models.ssrnetage&&(e.models.ssrnetage=I8(e.config)),e.config.face.enabled&&((N=e.config.face.ssrnet)==null?void 0:N.enabled)&&!e.models.ssrnetgender&&(e.models.ssrnetgender=N8(e.config)),e.config.face.enabled&&((R=e.config.face.mobilefacenet)==null?void 0:R.enabled)&&!e.models.mobilefacenet&&(e.models.mobilefacenet=sT(e.config)),e.config.hand.enabled&&!e.models.handtrack&&(($=(O=e.config.hand.detector)==null?void 0:O.modelPath)==null?void 0:$.includes("handtrack"))&&(e.models.handtrack=WT(e.config)),e.config.hand.enabled&&e.config.hand.landmarks&&!e.models.handskeleton&&((T=(P=e.config.hand.detector)==null?void 0:P.modelPath)==null?void 0:T.includes("handtrack"))&&(e.models.handskeleton=VT(e.config)),e.config.object.enabled&&!e.models.centernet&&((U=(F=e.config.object)==null?void 0:F.modelPath)==null?void 0:U.includes("centernet"))&&(e.models.centernet=X8(e.config)),e.config.object.enabled&&!e.models.nanodet&&((z=(q=e.config.object)==null?void 0:q.modelPath)==null?void 0:z.includes("nanodet"))&&(e.models.nanodet=QT(e.config)),e.config.segmentation.enabled&&!e.models.segmentation&&(e.models.segmentation=h5(e.config));for await(let K of Object.keys(e.models))e.models[K]&&typeof e.models[K]!="undefined"&&(e.models[K]=await e.models[K])}async function uN(e){let t=["const","placeholder","noop","pad","squeeze","add","sub","mul","div"];for(let n of Object.keys(e.models))if(e.models[n]){let s=[];Array.isArray(e.models[n])?s=e.models[n].filter(r=>r!==null).map(r=>r&&r.executor?r:r.model):s=[e.models[n]];for(let r of s){if(!r){e.config.debug&&Z("model marked as loaded but not defined:",n);continue}let a=[],o=r==null?void 0:r.executor;if(o&&o.graph.nodes)for(let l of Object.values(o.graph.nodes)){let c=l.op.toLowerCase();a.includes(c)||a.push(c)}else!o&&e.config.debug&&Z("model signature not determined:",n);let i=[];for(let l of a)!t.includes(l)&&!e.env.kernels.includes(l)&&!e.env.kernels.includes(l.replace("_",""))&&!e.env.kernels.includes(l.replace("native",""))&&!e.env.kernels.includes(l.replace("v2",""))&&i.push(l);i.length>0&&e.config.debug&&Z("model validation:",n,i)}}}var Tt={name:"humangl",priority:999,canvas:null,gl:null,extensions:[],webGLattr:{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!1,desynchronized:!0}};function a1e(){let e=Tt.gl;!e||(Tt.extensions=e.getSupportedExtensions())}async function cN(e){var t;if(e.config.backend==="humangl"&&(Tt.name in as().registry&&(!Tt.gl||!Tt.gl.getParameter(Tt.gl.VERSION))&&(Z("error: humangl backend invalid context"),m5(e)),!Q2(Tt.name))){try{Tt.canvas=await Zn(100,100)}catch(s){Z("error: cannot create canvas:",s);return}try{if(Tt.gl=(t=Tt.canvas)==null?void 0:t.getContext("webgl2",Tt.webGLattr),!Tt.gl.getParameter(Tt.gl.VERSION).includes("2.0")){Z("override: using fallback webgl backend as webgl 2.0 is not detected"),e.config.backend="webgl";return}Tt.canvas&&(Tt.canvas.addEventListener("webglcontextlost",async r=>{throw Z("error: humangl:",r.type),Z("possible browser memory leak using webgl or conflict with multiple backend registrations"),e.emit("error"),new Error("backend error: webgl context lost")}),Tt.canvas.addEventListener("webglcontextrestored",r=>{Z("error: humangl context restored:",r)}),Tt.canvas.addEventListener("webglcontextcreationerror",r=>{Z("error: humangl context create:",r)}))}catch(s){Z("error: cannot get WebGL context:",s);return}try{Fm(2,Tt.gl)}catch(s){Z("error: cannot set WebGL context:",s);return}try{let s=new Gm(Tt.gl);ul(Tt.name,()=>new bp(s),Tt.priority)}catch(s){Z("error: cannot register WebGL backend:",s);return}try{Jr("webgl").forEach(r=>{let a={...r,backendName:Tt.name};cr(a)})}catch(s){Z("error: cannot update WebGL backend registration:",s);return}let n=Dr().getGPGPUContext?Dr().getGPGPUContext().gl:null;if(n)Z(`humangl webgl version:${n.getParameter(n.VERSION)} renderer:${n.getParameter(n.RENDERER)}`);else{Z("error: no current gl context:",n,Tt.gl);return}try{Rr.set("WEBGL_VERSION",2)}catch(s){Z("error: cannot set WebGL backend flags:",s);return}a1e(),Z("backend registered:",Tt.name)}}function o1e(){if(!de.kernels.includes("mod")){let e={kernelName:"Mod",backendName:Rs(),kernelFunc:t=>X(()=>fe(t.inputs.a,L(ge(t.inputs.a,t.inputs.b),t.inputs.b)))};cr(e),de.kernels.push("mod")}if(!de.kernels.includes("floormod")){let e={kernelName:"FloorMod",backendName:Rs(),kernelFunc:t=>X(()=>pf(t.inputs.a/t.inputs.b)*t.inputs.b+Ld(t.inputs.a,t.inputs.b))};cr(e),de.kernels.push("floormod")}}async function O0(e,t=!1){if(e.state="backend",t||de.initial||e.config.backend&&e.config.backend.length>0&&Rs()!==e.config.backend){let n=ie();if(e.config.backend&&e.config.backend.length>0){if(typeof window=="undefined"&&typeof WorkerGlobalScope!="undefined"&&e.config.debug&&e.config.debug&&Z("running inside web worker"),de.browser&&e.config.backend==="tensorflow"&&(e.config.debug&&Z("override: backend set to tensorflow while running in browser"),e.config.backend="humangl"),de.node&&(e.config.backend==="webgl"||e.config.backend==="humangl")&&(e.config.debug&&Z(`override: backend set to ${e.config.backend} while running in nodejs`),e.config.backend="tensorflow"),de.browser&&e.config.backend==="webgpu")if(typeof navigator=="undefined"||typeof navigator.gpu=="undefined")Z("override: backend set to webgpu but browser does not support webgpu"),e.config.backend="humangl";else{let r=await navigator.gpu.requestAdapter();e.config.debug&&Z("enumerated webgpu adapter:",r)}e.config.backend==="humangl"&&await cN(e);let s=Object.keys(as().registryFactory);if(e.config.debug&&Z("available backends:",s),s.includes(e.config.backend)||(Z(`error: backend ${e.config.backend} not found in registry`),e.config.backend=de.node?"tensorflow":"webgl",e.config.debug&&Z(`override: setting backend ${e.config.backend}`)),e.config.debug&&Z("setting backend:",e.config.backend),e.config.backend==="wasm"){if(e.config.debug&&Z("wasm path:",e.config.wasmPath),typeof(Ml==null?void 0:Ml.setWasmPaths)!="undefined")await a8(e.config.wasmPath);else throw new Error("backend error: attempting to use wasm backend but wasm path is not set");let r=await Y().getAsync("WASM_HAS_SIMD_SUPPORT"),a=await Y().getAsync("WASM_HAS_MULTITHREAD_SUPPORT");e.config.debug&&Z(`wasm execution: ${r?"SIMD":"no SIMD"} ${a?"multithreaded":"singlethreaded"}`),e.config.debug&&!r&&Z("warning: wasm simd support is not enabled")}try{await nv(e.config.backend),await df()}catch(r){return Z("error: cannot set backend:",e.config.backend,r),!1}}if(Rs()==="humangl"&&(Rr.set("CHECK_COMPUTATION_FOR_ERRORS",!1),Rr.set("WEBGL_CPU_FORWARD",!0),Rr.set("WEBGL_USE_SHAPES_UNIFORMS",!0),Rr.set("CPU_HANDOFF_SIZE_THRESHOLD",256),typeof e.config.deallocate!="undefined"&&e.config.deallocate&&(Z("changing webgl: WEBGL_DELETE_TEXTURE_THRESHOLD:",!0),Rr.set("WEBGL_DELETE_TEXTURE_THRESHOLD",0)),Dr().getGPGPUContext)){let s=await Dr().getGPGPUContext().gl;e.config.debug&&Z(`gl version:${s.getParameter(s.VERSION)} renderer:${s.getParameter(s.RENDERER)}`)}Rs()==="webgpu",tv(),await df(),e.performance.initBackend=Math.trunc(ie()-n),e.config.backend=Rs(),await de.updateBackend(),o1e()}return!0}function E0(e,t){for(let n of e){let s={kernelName:n,backendName:t.backend,kernelFunc:()=>{t.debug&&Z("kernelFunc",n,t.backend)}};cr(s)}de.kernels=Jr(Rs()).map(n=>n.kernelName.toLowerCase())}var Aa={color:"rgba(173, 216, 230, 0.6)",labelColor:"rgba(173, 216, 230, 1)",shadowColor:"black",font:'small-caps 16px "Segoe UI"',lineHeight:18,lineWidth:4,pointSize:2,roundRect:8,drawPoints:!1,drawLabels:!0,drawBoxes:!0,drawGestures:!0,drawPolygons:!0,drawGaze:!0,fillPolygons:!1,useDepth:!0,useCurves:!1},g5=0,Xl=e=>{if(!e)Z("draw error: invalid canvas");else if(!e.getContext)Z("draw error: canvas context not defined");else{let t=e.getContext("2d");if(!t)Z("draw error: cannot get canvas context");else return t}return null},zc=e=>Math.round(e*180/Math.PI);function A5(e,t,n,s,r){s=s||0,e.fillStyle=r.useDepth&&s?`rgba(${127.5+2*s}, ${127.5-2*s}, 255, 0.3)`:r.color,e.beginPath(),e.arc(t,n,r.pointSize,0,2*Math.PI),e.fill()}function Gp(e,t,n,s,r,a){if(e.beginPath(),a.useCurves){let o=(t+t+s)/2,i=(n+n+r)/2;e.ellipse(o,i,s/2,r/2,0,0,2*Math.PI)}else e.lineWidth=a.lineWidth,e.moveTo(t+a.roundRect,n),e.lineTo(t+s-a.roundRect,n),e.quadraticCurveTo(t+s,n,t+s,n+a.roundRect),e.lineTo(t+s,n+r-a.roundRect),e.quadraticCurveTo(t+s,n+r,t+s-a.roundRect,n+r),e.lineTo(t+a.roundRect,n+r),e.quadraticCurveTo(t,n+r,t,n+r-a.roundRect),e.lineTo(t,n+a.roundRect),e.quadraticCurveTo(t,n,t+a.roundRect,n),e.closePath();e.stroke()}function dN(e,t,n){if(!(t.length<2)){e.beginPath(),e.moveTo(t[0][0],t[0][1]);for(let s of t){let r=s[2]||0;e.strokeStyle=n.useDepth&&r!==0?`rgba(${127.5+2*r}, ${127.5-2*r}, 255, 0.3)`:n.color,e.fillStyle=n.useDepth&&r!==0?`rgba(${127.5+2*r}, ${127.5-2*r}, 255, 0.3)`:n.color,e.lineTo(s[0],Math.round(s[1]))}e.stroke(),n.fillPolygons&&(e.closePath(),e.fill())}}function i1e(e,t,n){if(!(t.length<2)){if(!n.useCurves||t.length<=2){dN(e,t,n);return}e.moveTo(t[0][0],t[0][1]);for(let s=0;s1&&l[1].length>0){let c=i[1]>0?`#${i[1]}`:"",u=`${i[0]} ${c}: ${l[1]}`;s.shadowColor&&s.shadowColor!==""&&(r.fillStyle=s.shadowColor,r.fillText(u,8,2+a*s.lineHeight)),r.fillStyle=s.labelColor,r.fillText(u,6,0+a*s.lineHeight),a+=1}}}}async function x5(e,t,n){var a,o,i,l,c;let s=$n(Aa,n);if(!t||!e)return;let r=Xl(e);if(!!r)for(let u of t){if(r.font=s.font,r.strokeStyle=s.color,r.fillStyle=s.color,s.drawBoxes&&Gp(r,u.box[0],u.box[1],u.box[2],u.box[3],s),s.drawLabels){let d=[];if(d.push(`face: ${Math.trunc(100*u.score)}%`),u.genderScore&&d.push(`${u.gender||""} ${Math.trunc(100*u.genderScore)}%`),u.age&&d.push(`age: ${u.age||""}`),u.iris&&d.push(`distance: ${u.iris}`),u.real&&d.push(`real: ${Math.trunc(100*u.real)}%`),u.live&&d.push(`live: ${Math.trunc(100*u.live)}%`),u.emotion&&u.emotion.length>0){let p=u.emotion.map(h=>`${Math.trunc(100*h.score)}% ${h.emotion}`);p.length>3&&(p.length=3),d.push(p.join(" "))}u.rotation&&u.rotation.angle&&u.rotation.gaze&&(u.rotation.angle.roll&&d.push(`roll: ${zc(u.rotation.angle.roll)}\xB0 yaw:${zc(u.rotation.angle.yaw)}\xB0 pitch:${zc(u.rotation.angle.pitch)}\xB0`),u.rotation.gaze.bearing&&d.push(`gaze: ${zc(u.rotation.gaze.bearing)}\xB0`)),d.length===0&&d.push("face"),r.fillStyle=s.color;for(let p=d.length-1;p>=0;p--){let h=Math.max(u.box[0],0),f=p*s.lineHeight+u.box[1];s.shadowColor&&s.shadowColor!==""&&(r.fillStyle=s.shadowColor,r.fillText(d[p],h+5,f+16)),r.fillStyle=s.labelColor,r.fillText(d[p],h+4,f+15)}}if(r.lineWidth=1,u.mesh&&u.mesh.length>0){if(s.drawPoints)for(let d of u.mesh)A5(r,d[0],d[1],d[2],s);if(s.drawPolygons){if(r.lineWidth=1,u.mesh.length>450)for(let d=0;du.mesh[h]);dN(r,p,s)}if(u.annotations&&u.annotations.leftEyeIris&&u.annotations.leftEyeIris[0]){r.strokeStyle=s.useDepth?"rgba(255, 200, 255, 0.3)":s.color,r.beginPath();let d=Math.abs(u.annotations.leftEyeIris[3][0]-u.annotations.leftEyeIris[1][0])/2,p=Math.abs(u.annotations.leftEyeIris[4][1]-u.annotations.leftEyeIris[2][1])/2;r.ellipse(u.annotations.leftEyeIris[0][0],u.annotations.leftEyeIris[0][1],d,p,0,0,2*Math.PI),r.stroke(),s.fillPolygons&&(r.fillStyle=s.useDepth?"rgba(255, 255, 200, 0.3)":s.color,r.fill())}if(u.annotations&&u.annotations.rightEyeIris&&u.annotations.rightEyeIris[0]){r.strokeStyle=s.useDepth?"rgba(255, 200, 255, 0.3)":s.color,r.beginPath();let d=Math.abs(u.annotations.rightEyeIris[3][0]-u.annotations.rightEyeIris[1][0])/2,p=Math.abs(u.annotations.rightEyeIris[4][1]-u.annotations.rightEyeIris[2][1])/2;r.ellipse(u.annotations.rightEyeIris[0][0],u.annotations.rightEyeIris[0][1],d,p,0,0,2*Math.PI),r.stroke(),s.fillPolygons&&(r.fillStyle=s.useDepth?"rgba(255, 255, 200, 0.3)":s.color,r.fill())}if(s.drawGaze&&((a=u.rotation)==null?void 0:a.angle)&&typeof Path2D!="undefined"){r.strokeStyle="pink";let d=u.box[0]+u.box[2]/2-u.box[3]*zc(u.rotation.angle.yaw)/90,p=u.box[1]+u.box[3]/2+u.box[2]*zc(u.rotation.angle.pitch)/90,h=new Path2D(` M ${u.box[0]+u.box[2]/2} ${u.box[1]} C ${d} ${u.box[1]}, ${d} ${u.box[1]+u.box[3]}, ${u.box[0]+u.box[2]/2} ${u.box[1]+u.box[3]} `),f=new Path2D(` M ${u.box[0]} ${u.box[1]+u.box[3]/2} C ${u.box[0]} ${p}, ${u.box[0]+u.box[2]} ${p}, ${u.box[0]+u.box[2]} ${u.box[1]+u.box[3]/2} `);r.stroke(f),r.stroke(h)}if(s.drawGaze&&((i=(o=u.rotation)==null?void 0:o.gaze)==null?void 0:i.strength)&&((c=(l=u.rotation)==null?void 0:l.gaze)==null?void 0:c.bearing)&&u.annotations.leftEyeIris&&u.annotations.rightEyeIris&&u.annotations.leftEyeIris[0]&&u.annotations.rightEyeIris[0]){r.strokeStyle="pink",r.fillStyle="pink";let d=[u.annotations.leftEyeIris[0][0]+Math.sin(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[3],u.annotations.leftEyeIris[0][1]+Math.cos(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[2]];pN(r,[u.annotations.leftEyeIris[0][0],u.annotations.leftEyeIris[0][1]],[d[0],d[1]],4);let p=[u.annotations.rightEyeIris[0][0]+Math.sin(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[3],u.annotations.rightEyeIris[0][1]+Math.cos(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[2]];pN(r,[u.annotations.rightEyeIris[0][0],u.annotations.rightEyeIris[0][1]],[p[0],p[1]],4)}}}}}async function b5(e,t,n){var a;let s=$n(Aa,n);if(!t||!e)return;let r=Xl(e);if(!!r){r.lineJoin="round";for(let o=0;o0)for(let o of a.keypoints)r.fillStyle=s.useDepth?`rgba(${127.5+2*(o[2]||0)}, ${127.5-2*(o[2]||0)}, 255, 0.5)`:s.color,A5(r,o[0],o[1],0,s);if(s.drawLabels&&a.annotations){let o=(i,l)=>{!i||i.length===0||!i[0]||(r.fillStyle=s.useDepth?`rgba(${127.5+2*i[i.length-1][2]}, ${127.5-2*i[i.length-1][2]}, 255, 0.5)`:s.color,r.fillText(l,i[i.length-1][0]+4,i[i.length-1][1]+4))};r.font=s.font,o(a.annotations.index,"index"),o(a.annotations.middle,"middle"),o(a.annotations.ring,"ring"),o(a.annotations.pinky,"pinky"),o(a.annotations.thumb,"thumb"),o(a.annotations.palm,"palm")}if(s.drawPolygons&&a.annotations){let o=i=>{if(!(!i||i.length===0||!i[0]))for(let l=0;l0?l-1:0][0],i[l>0?l-1:0][1]),r.lineTo(i[l][0],i[l][1]),r.stroke()};r.lineWidth=s.lineWidth,o(a.annotations.index),o(a.annotations.middle),o(a.annotations.ring),o(a.annotations.pinky),o(a.annotations.thumb)}}}}async function w5(e,t,n){let s=$n(Aa,n);if(!t||!e)return;let r=Xl(e);if(!!r){r.lineJoin="round",r.font=s.font;for(let a of t)if(s.drawBoxes){if(r.strokeStyle=s.color,r.fillStyle=s.color,Gp(r,a.box[0],a.box[1],a.box[2],a.box[3],s),s.drawLabels){let o=`${a.label} ${Math.round(100*a.score)}%`;s.shadowColor&&s.shadowColor!==""&&(r.fillStyle=s.shadowColor,r.fillText(o,a.box[0]+3,1+a.box[1]+s.lineHeight,a.box[2])),r.fillStyle=s.labelColor,r.fillText(o,a.box[0]+2,0+a.box[1]+s.lineHeight,a.box[2])}r.stroke()}}}async function hN(e,t,n){let s=$n(Aa,n);if(!t||!e)return;let r=Xl(e);if(!!r){r.lineJoin="round",r.font=s.font;for(let a=0;at!=n[r].y>t&&e<(n[r].x-n[a].x)*(t-n[a].y)/(n[r].y-n[a].y)+n[a].x&&(s=!s);return s}async function gN(e){if(!e.tensor||!e.mesh||e.mesh.length<100)return e.tensor;let t=e.tensor.shape[2]||0,n=e.tensor.shape[1]||0,s=await e.tensor.buffer(),r=[];for(let o of rr.silhouette)r.push({x:(e.mesh[o][0]-e.box[0])/e.box[2],y:(e.mesh[o][1]-e.box[1])/e.box[3]});Lc&&Lc>0&&(r=r.map(o=>({x:o.x>.5?o.x+Lc:o.x-Lc,y:o.y>.5?o.y+Lc:o.y-Lc})));for(let o=0;o{let t=(d,p)=>Math.atan2(d[1]-p[1],d[0]-p[0]);if(!e.annotations.rightEyeIris||!e.annotations.leftEyeIris)return{bearing:0,strength:0};let n=[0,-.1],s=1,r=e.mesh[33][2]>e.mesh[263][2],a=r?e.mesh[473]:e.mesh[468],o=r?[(e.mesh[133][0]+e.mesh[33][0])/2,(e.mesh[133][1]+e.mesh[33][1])/2]:[(e.mesh[263][0]+e.mesh[362][0])/2,(e.mesh[263][1]+e.mesh[362][1])/2],i=r?[e.mesh[133][0]-e.mesh[33][0],e.mesh[23][1]-e.mesh[27][1]]:[e.mesh[263][0]-e.mesh[362][0],e.mesh[253][1]-e.mesh[257][1]],l=[(o[0]-a[0])/i[0]-n[0],s*(a[1]-o[1])/i[1]-n[1]],c=Math.sqrt(l[0]**2+l[1]**2);return c=Math.min(c,e.boxRaw[2]/2,e.boxRaw[3]/2),{bearing:(t([0,0],l)+Math.PI/2)%Math.PI,strength:c}},AN=(e,t)=>{let n=g=>{let A=Math.sqrt(g[0]*g[0]+g[1]*g[1]+g[2]*g[2]);return g[0]/=A,g[1]/=A,g[2]/=A,g},s=(g,A)=>{let x=g[0]-A[0],y=g[1]-A[1],b=g[2]-A[2];return[x,y,b]},r=(g,A)=>{let x=g[1]*A[2]-g[2]*A[1],y=g[2]*A[0]-g[0]*A[2],b=g[0]*A[1]-g[1]*A[0];return[x,y,b]},a=g=>{let[A,x,y,b,w,k,I,N,R]=g,O,$,P;return b<1?b>-1?(P=Math.asin(b),$=Math.atan2(-I,A),O=Math.atan2(-k,w)):(P=-Math.PI/2,$=-Math.atan2(N,R),O=0):(P=Math.PI/2,$=Math.atan2(N,R),O=0),isNaN(O)&&(O=0),isNaN($)&&($=0),isNaN(P)&&(P=0),{pitch:2*-O,yaw:2*-$,roll:2*-P}},o=g=>{let A=(y,b,w,k)=>Math.atan2(k-b,w-y);return{pitch:A(g[10][1],g[10][2],g[152][1],g[152][2]),yaw:A(g[33][0],g[33][2],g[263][0],g[263][2]),roll:A(g[33][0],g[33][1],g[263][0],g[263][1])}},i=e.meshRaw;if(!i||i.length<300)return{angle:{pitch:0,yaw:0,roll:0},matrix:[1,0,0,0,1,0,0,0,1],gaze:{bearing:0,strength:0}};let l=Math.max(e.boxRaw[2]*t[0],e.boxRaw[3]*t[1])/1.5,c=[i[10],i[152],i[234],i[454]].map(g=>[g[0]*t[0]/l,g[1]*t[1]/l,g[2]]),u=n(s(c[1],c[0])),d=n(s(c[3],c[2])),p=n(r(d,u));d=r(u,p);let h=[d[0],d[1],d[2],u[0],u[1],u[2],p[0],p[1],p[2]],f=a(h),m=i.length===478?u1e(e):{bearing:0,strength:0};return{angle:f,matrix:h,gaze:m}};var S5=async(e,t)=>{var h,f,m,g,A,x,y,b,w,k,I,N,R,O,$,P,T,F,U,q,z,K,J,Q,ne,re;let n,s,r,a,o,i,l,c,u,d=[];e.state="run:face",n=ie();let p=await cT(t,e.config);if(e.performance.face=de.perfadd?(e.performance.face||0)+Math.trunc(ie()-n):Math.trunc(ie()-n),!t.shape||t.shape.length!==4)return[];if(!p)return[];for(let G=0;G200?AN(p[G],[t.shape[2],t.shape[1]]):null;e.analyze("Start Emotion:"),e.config.async?o=((f=e.config.face.emotion)==null?void 0:f.enabled)?Eb(p[G].tensor||ut([]),e.config,G,p.length):null:(e.state="run:emotion",n=ie(),o=((m=e.config.face.emotion)==null?void 0:m.enabled)?await Eb(p[G].tensor||ut([]),e.config,G,p.length):null,e.performance.emotion=de.perfadd?(e.performance.emotion||0)+Math.trunc(ie()-n):Math.trunc(ie()-n)),e.analyze("End Emotion:"),e.analyze("Start AntiSpoof:"),e.config.async?l=((g=e.config.face.antispoof)==null?void 0:g.enabled)?ob(p[G].tensor||ut([]),e.config,G,p.length):null:(e.state="run:antispoof",n=ie(),l=((A=e.config.face.antispoof)==null?void 0:A.enabled)?await ob(p[G].tensor||ut([]),e.config,G,p.length):null,e.performance.antispoof=de.perfadd?(e.performance.antispoof||0)+Math.trunc(ie()-n):Math.trunc(ie()-n)),e.analyze("End AntiSpoof:"),e.analyze("Start Liveness:"),e.config.async?c=((x=e.config.face.liveness)==null?void 0:x.enabled)?Zb(p[G].tensor||ut([]),e.config,G,p.length):null:(e.state="run:liveness",n=ie(),c=((y=e.config.face.liveness)==null?void 0:y.enabled)?await Zb(p[G].tensor||ut([]),e.config,G,p.length):null,e.performance.liveness=de.perfadd?(e.performance.antispoof||0)+Math.trunc(ie()-n):Math.trunc(ie()-n)),e.analyze("End Liveness:"),e.analyze("Start GEAR:"),e.config.async?r=((b=e.config.face.gear)==null?void 0:b.enabled)?Qx(p[G].tensor||ut([]),e.config,G,p.length):{}:(e.state="run:gear",n=ie(),r=((w=e.config.face.gear)==null?void 0:w.enabled)?await Qx(p[G].tensor||ut([]),e.config,G,p.length):{},e.performance.gear=Math.trunc(ie()-n)),e.analyze("End GEAR:"),e.analyze("Start SSRNet:"),e.config.async?(s=((k=e.config.face.ssrnet)==null?void 0:k.enabled)?tb(p[G].tensor||ut([]),e.config,G,p.length):{},a=((I=e.config.face.ssrnet)==null?void 0:I.enabled)?rb(p[G].tensor||ut([]),e.config,G,p.length):{}):(e.state="run:ssrnet",n=ie(),s=((N=e.config.face.ssrnet)==null?void 0:N.enabled)?await tb(p[G].tensor||ut([]),e.config,G,p.length):{},a=((R=e.config.face.ssrnet)==null?void 0:R.enabled)?await rb(p[G].tensor||ut([]),e.config,G,p.length):{},e.performance.ssrnet=Math.trunc(ie()-n)),e.analyze("End SSRNet:"),e.analyze("Start MobileFaceNet:"),e.config.async?i=((O=e.config.face.mobilefacenet)==null?void 0:O.enabled)?$b(p[G].tensor||ut([]),e.config,G,p.length):{}:(e.state="run:mobilefacenet",n=ie(),i=(($=e.config.face.mobilefacenet)==null?void 0:$.enabled)?await $b(p[G].tensor||ut([]),e.config,G,p.length):{},e.performance.mobilefacenet=Math.trunc(ie()-n)),e.analyze("End MobileFaceNet:"),e.analyze("Start Description:"),e.config.async?u=((P=e.config.face.description)==null?void 0:P.enabled)?Mb(p[G].tensor||ut([]),e.config,G,p.length):null:(e.state="run:description",n=ie(),u=((T=e.config.face.description)==null?void 0:T.enabled)?await Mb(p[G].tensor||ut([]),e.config,G,p.length):null,e.performance.description=de.perfadd?(e.performance.description||0)+Math.trunc(ie()-n):Math.trunc(ie()-n)),e.analyze("End Description:"),e.config.async&&([s,a,o,i,u,r,l,c]=await Promise.all([s,a,o,i,u,r,l,c])),e.analyze("Finish Face:"),((F=e.config.face.ssrnet)==null?void 0:F.enabled)&&s&&a&&(u={age:s.age,gender:a.gender,genderScore:a.genderScore}),((U=e.config.face.gear)==null?void 0:U.enabled)&&r&&(u={age:r.age,gender:r.gender,genderScore:r.genderScore,race:r.race}),((q=e.config.face.mobilefacenet)==null?void 0:q.enabled)&&i&&(u.descriptor=i),!((z=e.config.face.iris)==null?void 0:z.enabled)&&((J=(K=p[G])==null?void 0:K.annotations)==null?void 0:J.leftEyeIris)&&((ne=(Q=p[G])==null?void 0:Q.annotations)==null?void 0:ne.rightEyeIris)&&(delete p[G].annotations.leftEyeIris,delete p[G].annotations.rightEyeIris);let oe=p[G].annotations&&p[G].annotations.leftEyeIris&&p[G].annotations.leftEyeIris[0]&&p[G].annotations.rightEyeIris&&p[G].annotations.rightEyeIris[0]&&p[G].annotations.leftEyeIris.length>0&&p[G].annotations.rightEyeIris.length>0&&p[G].annotations.leftEyeIris[0]!==null&&p[G].annotations.rightEyeIris[0]!==null?Math.max(Math.abs(p[G].annotations.leftEyeIris[3][0]-p[G].annotations.leftEyeIris[1][0]),Math.abs(p[G].annotations.rightEyeIris[4][1]-p[G].annotations.rightEyeIris[2][1]))/t.shape[2]:0,pe=((re=e.config.face.detector)==null?void 0:re.return)?ot(p[G].tensor):null;te(p[G].tensor),p[G].tensor&&delete p[G].tensor;let ye={...p[G],id:G};(u==null?void 0:u.age)&&(ye.age=u.age),(u==null?void 0:u.gender)&&(ye.gender=u.gender),(u==null?void 0:u.genderScore)&&(ye.genderScore=u==null?void 0:u.genderScore),(u==null?void 0:u.descriptor)&&(ye.embedding=u==null?void 0:u.descriptor),(u==null?void 0:u.race)&&(ye.race=u==null?void 0:u.race),o&&(ye.emotion=o),l&&(ye.real=l),c&&(ye.live=c),oe&&oe!==0&&(ye.iris=Math.trunc(500/oe/11.7)/100),se&&(ye.rotation=se),pe&&(ye.tensor=pe),d.push(ye),e.analyze("End Face")}return e.analyze("End FaceMesh:"),e.config.async&&(e.performance.face&&delete e.performance.face,e.performance.age&&delete e.performance.age,e.performance.gender&&delete e.performance.gender,e.performance.emotion&&delete e.performance.emotion),d};var yN=e=>{if(!e)return[];let t=[];for(let n=0;nl.part==="leftWrist"),r=e[n].keypoints.find(l=>l.part==="rightWrist"),a=e[n].keypoints.find(l=>l.part==="nose");a&&s&&r&&s.position[1]l.part==="leftShoulder"),i=e[n].keypoints.find(l=>l.part==="rightShoulder");o&&i&&Math.abs(o.positionRaw[1]-i.positionRaw[1])>.1&&t.push({body:n,gesture:`leaning ${o.position[1]>i.position[1]?"left":"right"}`})}return t},xN=e=>{if(!e)return[];let t=[];for(let n=0;n450){let s=e[n].mesh[33][2]-e[n].mesh[263][2],r=e[n].mesh[33][0]-e[n].mesh[263][0];Math.abs(s/r)<=.15?t.push({face:n,gesture:"facing center"}):t.push({face:n,gesture:`facing ${s<0?"left":"right"}`}),Math.abs(e[n].mesh[374][1]-e[n].mesh[386][1])/Math.abs(e[n].mesh[443][1]-e[n].mesh[450][1])<.2&&t.push({face:n,gesture:"blink left eye"}),Math.abs(e[n].mesh[145][1]-e[n].mesh[159][1])/Math.abs(e[n].mesh[223][1]-e[n].mesh[230][1])<.2&&t.push({face:n,gesture:"blink right eye"});let i=Math.min(100,500*Math.abs(e[n].mesh[13][1]-e[n].mesh[14][1])/Math.abs(e[n].mesh[10][1]-e[n].mesh[152][1]));i>10&&t.push({face:n,gesture:`mouth ${Math.trunc(i)}% open`});let l=e[n].mesh[152][2];Math.abs(l)>10&&t.push({face:n,gesture:`head ${l<0?"up":"down"}`})}return t},bN=e=>{if(!e)return[];let t=[];for(let n=0;n.06||p>.06)&&(c=!1),d>p?d>.05&&t.push({iris:n,gesture:"looking right"}):p>.05&&t.push({iris:n,gesture:"looking left"});let h=Math.abs(e[n].mesh[145][1]-e[n].annotations.rightEyeIris[0][1])/e[n].box[3],f=Math.abs(e[n].mesh[374][1]-e[n].annotations.leftEyeIris[0][1])/e[n].box[3];(f<.01||h<.01||f>.022||h>.022)&&(c=!1),(f<.01||h<.01)&&t.push({iris:n,gesture:"looking down"}),(f>.022||h>.022)&&t.push({iris:n,gesture:"looking up"}),c&&t.push({iris:n,gesture:"looking center"})}return t},vN=e=>{if(!e)return[];let t=[];for(let n=0;n0){let r=s.reduce((o,i)=>o.position[2]o.position[1]((r-1)*De.body[z].box[se]+G)/r),J=e.body[z].boxRaw.map((G,se)=>((r-1)*De.body[z].boxRaw[se]+G)/r),Q=e.body[z].keypoints.map((G,se)=>({score:G.score,part:G.part,position:[De.body[z].keypoints[se]?((r-1)*De.body[z].keypoints[se].position[0]+G.position[0])/r:G.position[0],De.body[z].keypoints[se]?((r-1)*De.body[z].keypoints[se].position[1]+G.position[1])/r:G.position[1]],positionRaw:[De.body[z].keypoints[se]?((r-1)*De.body[z].keypoints[se].positionRaw[0]+G.positionRaw[0])/r:G.position[0],De.body[z].keypoints[se]?((r-1)*De.body[z].keypoints[se].positionRaw[1]+G.positionRaw[1])/r:G.position[1]]})),ne={},re={connected:{}};((i=(o=t.body)==null?void 0:o.modelPath)==null?void 0:i.includes("efficientpose"))?re=Ib:((c=(l=t.body)==null?void 0:l.modelPath)==null?void 0:c.includes("blazepose"))?re=gb:((d=(u=t.body)==null?void 0:u.modelPath)==null?void 0:d.includes("movenet"))&&(re=e5);for(let[G,se]of Object.entries(re.connected)){let oe=[];for(let pe=0;peNe.part===se[pe]),we=Q.find(Ne=>Ne.part===se[pe+1]);ye&&we&&ye.score>(t.body.minConfidence||0)&&we.score>(t.body.minConfidence||0)&&oe.push([ye.position,we.position])}ne[G]=oe}De.body[z]={...e.body[z],box:K,boxRaw:J,keypoints:Q,annotations:ne}}if(!De.hand||e.hand.length!==De.hand.length)De.hand=JSON.parse(JSON.stringify(e.hand));else for(let z=0;z((r-1)*De.hand[z].box[G]+re)/r),J=e.hand[z].boxRaw.map((re,G)=>((r-1)*De.hand[z].boxRaw[G]+re)/r);De.hand[z].keypoints.length!==e.hand[z].keypoints.length&&(De.hand[z].keypoints=e.hand[z].keypoints);let Q=e.hand[z].keypoints&&e.hand[z].keypoints.length>0?e.hand[z].keypoints.map((re,G)=>re.map((se,oe)=>((r-1)*(De.hand[z].keypoints[G][oe]||1)+(se||0))/r)):[],ne={};if(Object.keys(De.hand[z].annotations).length!==Object.keys(e.hand[z].annotations).length)De.hand[z].annotations=e.hand[z].annotations,ne=De.hand[z].annotations;else if(e.hand[z].annotations)for(let re of Object.keys(e.hand[z].annotations))ne[re]=e.hand[z].annotations[re]&&e.hand[z].annotations[re][0]?e.hand[z].annotations[re].map((G,se)=>G.map((oe,pe)=>((r-1)*De.hand[z].annotations[re][se][pe]+oe)/r)):null;De.hand[z]={...e.hand[z],box:K,boxRaw:J,keypoints:Q,annotations:ne}}if(!De.face||e.face.length!==De.face.length)De.face=JSON.parse(JSON.stringify(e.face));else for(let z=0;z((r-1)*De.face[z].box[ne]+Q)/r),J=e.face[z].boxRaw.map((Q,ne)=>((r-1)*De.face[z].boxRaw[ne]+Q)/r);if(e.face[z].rotation){let Q={matrix:[0,0,0,0,0,0,0,0,0],angle:{roll:0,yaw:0,pitch:0},gaze:{bearing:0,strength:0}};Q.matrix=(p=e.face[z].rotation)==null?void 0:p.matrix,Q.angle={roll:((r-1)*(((f=(h=De.face[z].rotation)==null?void 0:h.angle)==null?void 0:f.roll)||0)+(((g=(m=e.face[z].rotation)==null?void 0:m.angle)==null?void 0:g.roll)||0))/r,yaw:((r-1)*(((x=(A=De.face[z].rotation)==null?void 0:A.angle)==null?void 0:x.yaw)||0)+(((b=(y=e.face[z].rotation)==null?void 0:y.angle)==null?void 0:b.yaw)||0))/r,pitch:((r-1)*(((k=(w=De.face[z].rotation)==null?void 0:w.angle)==null?void 0:k.pitch)||0)+(((N=(I=e.face[z].rotation)==null?void 0:I.angle)==null?void 0:N.pitch)||0))/r},Q.gaze={bearing:((r-1)*(((O=(R=De.face[z].rotation)==null?void 0:R.gaze)==null?void 0:O.bearing)||0)+(((P=($=e.face[z].rotation)==null?void 0:$.gaze)==null?void 0:P.bearing)||0))/r,strength:((r-1)*(((F=(T=De.face[z].rotation)==null?void 0:T.gaze)==null?void 0:F.strength)||0)+(((q=(U=e.face[z].rotation)==null?void 0:U.gaze)==null?void 0:q.strength)||0))/r},De.face[z]={...e.face[z],rotation:Q,box:K,boxRaw:J}}De.face[z]={...e.face[z],box:K,boxRaw:J}}if(!De.object||e.object.length!==De.object.length)De.object=JSON.parse(JSON.stringify(e.object));else for(let z=0;z((r-1)*De.object[z].box[ne]+Q)/r),J=e.object[z].boxRaw.map((Q,ne)=>((r-1)*De.object[z].boxRaw[ne]+Q)/r);De.object[z]={...e.object[z],box:K,boxRaw:J}}if(e.persons){let z=e.persons;if(!De.persons||z.length!==De.persons.length)De.persons=JSON.parse(JSON.stringify(z));else for(let K=0;K((r-1)*De.persons[K].box[Q]+J)/r)}e.gesture&&(De.gesture=e.gesture);let a=ie();return I5=de.perfadd?I5+Math.round(a-n):Math.round(a-n),e.performance&&(De.performance={...e.performance,interpolate:I5}),De}function M0(e,t,n={order:2,multiplier:25}){let s=0;for(let r=0;r{if(e===0)return 1;let r=t===2?Math.sqrt(e):e**(1/t),a=(1-r/100-n)/(s-n);return Math.max(Math.min(a,1),0)};function SN(e,t,n={order:2,multiplier:25,min:.2,max:.8}){let s=M0(e,t,n);return kN(s,n.order||2,n.min||0,n.max||1)}function IN(e,t,n={order:2,multiplier:25,threshold:0,min:.2,max:.8}){if(!Array.isArray(e)||!Array.isArray(t)||e.length<64||t.length===0||e.length!==t[0].length)return{index:-1,distance:Number.POSITIVE_INFINITY,similarity:0};let s=Number.MAX_SAFE_INTEGER,r=-1;for(let o=0;oF.box[0]&&I.box[0]F.box[1]&&I.box[1]+I.box[3]N.body.box[0]&&F.box[0]+F.box[2]N.body.box[1]&&F.box[1]+F.box[3]N.body.box[0]&&F.box[1]+F.box[3]>N.body.box[1]&&F.box[1]+F.box[3]{F&&F.length===4&&(R.push(F[0],F[0]+F[2]),O.push(F[1],F[1]+F[3]))};$((A=N.face)==null?void 0:A.box),$((x=N.body)==null?void 0:x.box),$((b=(y=N.hands)==null?void 0:y.left)==null?void 0:b.box),$((k=(w=N.hands)==null?void 0:w.right)==null?void 0:k.box);let P=Math.min(...R),T=Math.min(...O);N.box=[P,T,Math.max(...R)-P,Math.max(...O)-T],r&&r[1]&&r[2]&&(N.boxRaw=[N.box[0]/r[2],N.box[1]/r[1],N.box[2]/r[2],N.box[3]/r[1]]),o.push(N)}return o}var z0=` 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`,L0=` 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 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAa2p1UYo5adbz+xbxMlvqJ1OqjDHLXree0ejmzNrWm953tPmTPWbWneZ7yoy5YhjrXXTjH8s75N mtkyxt0VZM2/m175N1V03yTKubMLXVXybeYLLX2VXy7eam+b0bOg4VquJW+rry4/O9uyZOq3UjVm 9r25axMzPaIdvhns1kzbZddM0p5Y47z8/R2+HcF03Doi1a8+Xzvbv+TotJnjDXkt+K8ODHp8cY8N IpSO0RCwF2YAAAAAAAAACvUZYw6fJkntWN3k8dfHz2vLucdz8mkjFE9bz1+UOZosX1UzPm0nqI/W MYo9FlcPNklfFGeH/NshLGun+Cz6PtHZtVZWlRLS+jxPkRpIn7rdoupHTdA5s6SI+7H6Mfo+32Y2 +To3neSIiZ7A0IjPXpXLePlMotGW3272t85datKzHZjbTVnsDj+FG/2Y/RlGP4R+jo20u7H6N1Ql o+H8I/REY957R+jpfReiK6eOYHLtj2tttH6KrY/6Y/R2c+kjeJiFVtLG24hxpw7/AHY/RRkw9O37 O99Hrt1YX0tfOBLjcGp4XF8c+u8fs9c4dcVcGemSI61nd3IneN1orQAAAAAAAAAAAAABFqxes1tE TE9JiUgPKcX4RbRXnNgiZwWnrH4XPi28PdXpW9JraImsxtMS8pxXhF9DecuGJtgmf+1TWW2N/la1 L7N7T5e3Vy6W3hsYcvLbqzbO9jvvCzvDR0+XeO7crO6FmGSvRThy/RtVXJ92elvk2rRvDUzU7pl4 izsd2J3jeBpcNz+Lg5LT7+Pp+Xk3W7js5eAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADs0NTrN96Yp6edkW8Wzm6+LNTq4pvTHO9vOfRoWtt 1mes95YWvs1s2fZldddOczLPLn2ju0MmebT3YZc2/mpm3qqllN1drsbZIhr3yzvtHf4AsvlYYseb V5Yx4KTe0+UQ6nDvZ3UazbJqd8OKeu33peq0eh0+hxcmnxxWPOfOfm0mP+steT/ji8N9mKY9suum L37+HHaPm9DSlaVitKxWsdohI0Y22gAgAAAAAAAAAABXnyRhw3yT92Nwef4xm8bVzET0rPJH5d12 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 AOZE/OsPS29nuH27YrV+VpeV9pdPXhOtw49NG9Mld55+vXcTPd42I47qo7xSfyWV9oM8d8VJ/VxM d8l46xWF9cV7en6o/qLfxp2I9ob+eCv/AHMo9op89P8A/wBORGmyT5R+qfo2X8P7n9Q/jTsx7RR5 6ef+4/8AuHftg/8A6cWcOSO9J/WEbWr3pY7Efzp2Lcfv5YK/9zWy8d1E/ZpSv5Oba1/+Hb9lc+LP bFt87I7E/wAabWbiurvEx4nL/pjZzc2bJkn372t85ZXx55/BX85lucC0vPxnTxlnnjm32mOiZqUu LJ2p4TwnVavNWaYbRTfre0bQ99pcH0bT0xb78vmtiIiNojaErMwAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAHnfarF7umzRHaZrLjYrdIen9ocPi8JyTt1xzF4eUw23rCm3R4r6bMy wt6kdTaWLdjswmNoZontsCm0K5XWjopnuDC0dGpqG5bs08/daKV672MjbSaif6oh6Z5f2LtvptRX 0tEvUN3Jfo8f7cYve0eX4zV7B5z20xc/C8eSPuZIRficfXlcPaG7ino08HWIbePpLF2NuiyOyrHK 3fZFSwuovHVfaVF4QK5YWTM9UT0EKry6Ps1Tn4zjn8NZn9nOtLseydObiWW34cf918fWfk+PYANn KAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAq1WKM+ly4p+/WYeBxTNd6zG0xO0 vobw3FcP0bi2em20Tbmj5Srr418V9sa2Z7qKyzi07MXUylhaU7yjqhLCeiq3ddaFNxFYW7NLNG8t zya+WO6Va9J7FW66mvwidnrXiPY3Ny8RyUn71Jj9Ht3RPjk19HK9pMHj8D1ER3rHN+jqqtTjjNps uOe16zAifXzfTz7kNyndpYazS9qT0mszDdoxrsi6m8LazMq6zDOsq1ZEyrt1WWlXaUCqyq0rbKbi Fdp6PReyFd8uqv8ACsfy83aXrPZHHto89/xX2/SP/dpj6y8vx6EBq5gAAAAAAAAAAAAAAAAAAAAA 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 NO67NbkhzNVnmInqzaOZrL93JyZeV0M1++7S02jvxDWxhxx033tPpC8Z6rrezWjmZyazJG2/u03h 2vFibTHoqvamiwVwY+nLGzV0+SZ1Mx8G0/45tOhzJ5lXMc3UVXRdlF1HP+iYsDPLPPy49/tz1+Te pSIr0ho6ak5Ms5J8o2q6NImOrHV7XX488ypzTtHXo0s9t6zG7c1G1qz6ubeZiZ3UatXJG3yauSO7 cvMTEx5tPLb3prPRMVr0HB8vicNxf0+7+kt+LOJwTJyY/Bnz3tH93X36N58cWvq6LSyiyndMSlC7 mZcymLJiwLosmJVRLKLAtiU7q4lMSCzc3YxJuDMRuAlKAEgAAAlAkAAAAAABKAEgAAAAAJAAAAAA AAAAAAAEgAAAAAAAAAAAAAkAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAhIAAACAAAASgAAAAAAEAAAA hGzJAImGMwzQDDZjNVuyNgUTVhNGxysZqDVmiu1G5NN2M4waM0+DCaN2cbGcQNGaMZq3JxMJxA1J qx2bU4kU09slorWNwa20z02RXHbJbl26QvtFovbHWkxEdJt5y2MOHlr2U1W3jx+1hiw8vSO63lmI XRTaEWmtY6snRHO1VpmJ+DjavpSZl2s8b7y4HFcnh0n0gha5ebJN55KRM2mdoiPN6fh+kpwXh0Wy RHj5Otp/s5Ps1p62y31+em9aTMYt/OfVfxTiPjZ52naI7fBrI5t66xz5+a1rW7yx0eSL6iZjtEOX qNbSletom3lENjh2fbHzbbWt3iVozruc+5ztWubf4M4ybpQ2Oboyrva0Vjza8WdDR4OkXt3n9ldX kaePP9VtYqctYhdvt5oivTeCZ2YOxXk6ubqMfV0b9mrljfqlFcq88k7z2U5axeItDa1OPessuC8P ya7XRWYnwqdbT/ZMilvIu4dpslNdixXja8Y5tt85djZdbDWnGOesRtXFtuw6T27No5Kx2OrKYQlC ExKJgBnEpiyvdlEgsizKLKollFgWxLKJVRLKJBbEp3VxLKJBnuMWQJEbpBIAAAJAAAABIAAAAAAA lAJAAAAAAAAAAAAAASAAAAAAAAAAAAAJAAAABAJABAlAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAA AAABAJQAAAAgAABAAI2EoBGyJhkgGPKxmqxAKpownHC+YRMdN5BrTj67R3bOn01o7p01Iv71u89o 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 2Q==`;async function c1e(e){let t=(r,a="application/octet-stream")=>fetch(`data:${a};base64,${r}`).then(o=>o.blob()),n,s;switch(e.config.warmup){case"face":n=await t(z0);break;case"body":case"full":n=await t(L0);break;default:n=null}if(n){let r=await createImageBitmap(n);s=await e.detect(r,e.config),r.close()}return s}async function d1e(e){return new Promise(t=>{let n;switch(e.config.warmup){case"face":n="data:image/jpeg;base64,"+z0;break;case"full":case"body":n="data:image/jpeg;base64,"+L0;break;default:n=null}let s;typeof Image!="undefined"?s=new Image:de.Image&&(s=new de.Image),s.onload=async()=>{let r=Zn(s.naturalWidth,s.naturalHeight);if(!r)Z("Warmup: Canvas not found"),t({});else{let a=r.getContext("2d");a&&a.drawImage(s,0,0);let o=await e.image(r),i=await e.detect(o.tensor,e.config);t(i)}},n?s.src=n:t(null)})}async function p1e(e){let t=r=>Buffer.from(r,"base64"),n;if(e.config.warmup==="face"&&(n=t(z0)),(e.config.warmup==="body"||e.config.warmup==="full")&&(n=t(L0)),!n)return null;let s;if(typeof void 0!="undefined"){let r=(void 0).decodeJpeg(n),a=r.expandDims(0);e.tf.dispose(r),s=await e.detect(a,e.config),e.tf.dispose(a)}else e.config.debug&&Z("Warmup tfjs-node not loaded");return s}async function TN(e,t){let n=ie();if(e.state="warmup",t&&(e.config=$n(e.config,t)),!e.config.warmup||e.config.warmup.length===0||e.config.warmup==="none")return{error:"null"};let s;return new Promise(async r=>{typeof createImageBitmap=="function"?s=await c1e(e):typeof Image!="undefined"||de.Canvas!==void 0?s=await d1e(e):s=await p1e(e);let a=ie();e.config.debug&&Z("Warmup",e.config.warmup,Math.round(a-n),"ms"),e.emit("warmup"),r(s)})}var Bc,Hp,jp,B0,EN=class{constructor(t){he(this,"version");he(this,"config");he(this,"result");he(this,"state");he(this,"process");he(this,"tf");he(this,"env");he(this,"draw");he(this,"models");he(this,"events");he(this,"faceTriangulation");he(this,"faceUVMap");he(this,"performance");td(this,Bc,void 0);td(this,Hp,void 0);td(this,jp,void 0);he(this,"gl");he(this,"analyze",(...t)=>{if(!ed(this,Hp))return;let n=this.tf.engine().state.numTensors,s=ed(this,Bc);nd(this,Bc,n);let r=n-s;r!==0&&Z(...t,r)});td(this,B0,t=>{if(!ed(this,jp))return null;if(!t)return"input is not defined";if(this.env.node&&!(t instanceof Je))return"input must be a tensor";try{this.tf.getBackend()}catch(n){return"backend not loaded"}return null});he(this,"similarity",SN);he(this,"distance",M0);he(this,"match",IN);he(this,"emit",t=>{var n;this.events&&this.events.dispatchEvent&&((n=this.events)==null||n.dispatchEvent(new Event(t)))});this.env=de,Ca.wasmPath=Pp.includes("-")?"https://vladmandic.github.io/tfjs/dist/":`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${Pp}/dist/`,Ca.modelBasePath=de.browser?"../models/":"file://models/",Ca.backend=de.browser?"humangl":"tensorflow",this.version=Zx,Object.defineProperty(this,"version",{value:Zx}),this.config=JSON.parse(JSON.stringify(Ca)),Object.seal(this.config),t&&(this.config=$n(this.config,t)),this.tf=Ml,this.state="idle",nd(this,Bc,0),nd(this,Hp,!1),nd(this,jp,!1),this.performance={},this.events=typeof EventTarget!="undefined"?new EventTarget:void 0,this.models=new f5,this.draw={options:Aa,canvas:(n,s)=>fN(n,s),face:(n,s,r)=>x5(n,s,r),body:(n,s,r)=>b5(n,s,r),hand:(n,s,r)=>v5(n,s,r),gesture:(n,s,r)=>y5(n,s,r),object:(n,s,r)=>w5(n,s,r),person:(n,s,r)=>hN(n,s,r),all:(n,s,r)=>mN(n,s,r)},this.result={face:[],body:[],hand:[],gesture:[],object:[],performance:{},timestamp:0,persons:[],error:null},this.process={tensor:null,canvas:null},this.faceTriangulation=pT,this.faceUVMap=hT,this.gl=Tt,this.emit("create")}reset(){let t=this.config.backend;this.config=JSON.parse(JSON.stringify(Ca)),this.config.backend=t}validate(t){return c2(Ca,t||this.config)}now(){return ie()}image(t,n=!0){return Tc(t,this.config,n)}async segmentation(t,n){return iN(t,n,this.config)}enhance(t){return Ob(t)}compare(t,n){return A8(this.config,t,n)}async init(){await O0(this,!0),await this.tf.ready()}async load(t){this.state="load";let n=ie(),s=Object.values(this.models).filter(o=>o).length;t&&(this.config=$n(this.config,t)),this.env.initial&&(this.config.debug&&Z(`version: ${this.version}`),this.config.debug&&Z(`tfjs version: ${this.tf.version_core}`),await O0(this)||Z("error: backend check failed"),await df(),this.env.browser&&(this.config.debug&&Z("configuration:",this.config),this.config.debug&&Z("environment:",this.env),this.config.debug&&Z("tf flags:",this.tf.ENV.flags))),await lN(this),this.env.initial&&this.config.debug&&Z("tf engine state:",this.tf.engine().state.numBytes,"bytes",this.tf.engine().state.numTensors,"tensors"),this.env.initial=!1,Object.values(this.models).filter(o=>o).length!==s&&(await uN(this),this.emit("load"));let a=Math.trunc(ie()-n);a>(this.performance.loadModels||0)&&(this.performance.loadModels=this.env.perfadd?(this.performance.loadModels||0)+a:a)}next(t=this.result){return wN(t,this.config)}async warmup(t){let n=ie(),s=await TN(this,t),r=ie();return this.performance.warmup=Math.trunc(r-n),s}async profile(t,n){let s=await this.tf.profile(()=>this.detect(t,n)),r={};for(let i of s.kernels)r[i.name]?r[i.name]+=i.kernelTimeMs:r[i.name]=i.kernelTimeMs;let a=[];Object.entries(r).forEach(i=>a.push({name:i[0],ms:i[1]})),a.sort((i,l)=>l.ms-i.ms),a.length=20;let o={};for(let i of a)o[i.name]=i.ms;return o}async detect(t,n){return this.state="detect",new Promise(async s=>{var g,A,x,y,b,w,k,I,N,R,O,$,P,T,F,U,q,z,K,J,Q,ne;this.state="config";let r;this.config=$n(this.config,n),this.state="check";let a=ed(this,B0).call(this,t);a&&(Z(a,t),this.emit("error"),s({face:[],body:[],hand:[],gesture:[],object:[],performance:this.performance,timestamp:ie(),persons:[],error:a}));let o=ie();await O0(this),await this.load(),r=ie(),this.state="image";let i=await Tc(t,this.config);if(this.process=i,this.performance.inputProcess=this.env.perfadd?(this.performance.inputProcess||0)+Math.trunc(ie()-r):Math.trunc(ie()-r),this.analyze("Get Image:"),!i.tensor){this.config.debug&&Z("could not convert input to tensor"),this.emit("error"),s({face:[],body:[],hand:[],gesture:[],object:[],performance:this.performance,timestamp:ie(),persons:[],error:"could not convert input to tensor"});return}this.emit("image"),r=ie(),this.config.skipAllowed=await g8(this.config,i.tensor),this.performance.totalFrames||(this.performance.totalFrames=0),this.performance.cachedFrames||(this.performance.cachedFrames=0),this.performance.totalFrames++,this.config.skipAllowed&&this.performance.cachedFrames++,this.performance.cacheCheck=this.env.perfadd?(this.performance.cacheCheck||0)+Math.trunc(ie()-r):Math.trunc(ie()-r),this.analyze("Check Changed:");let l=[],c=[],u=[],d=[];this.state="detect:face",this.config.async?(l=this.config.face.enabled?S5(this,i.tensor):[],this.performance.face&&delete this.performance.face):(r=ie(),l=this.config.face.enabled?await S5(this,i.tensor):[],this.performance.face=this.env.perfadd?(this.performance.face||0)+Math.trunc(ie()-r):Math.trunc(ie()-r)),this.config.async&&(this.config.body.maxDetected===-1||this.config.hand.maxDetected===-1)&&(l=await l),this.analyze("Start Body:"),this.state="detect:body";let p=this.config.body.maxDetected===-1?$n(this.config,{body:{maxDetected:this.config.face.enabled?1*l.length:1}}):this.config;this.config.async?(((g=this.config.body.modelPath)==null?void 0:g.includes("posenet"))?c=this.config.body.enabled?d5(i.tensor,p):[]:((A=this.config.body.modelPath)==null?void 0:A.includes("blazepose"))?c=this.config.body.enabled?xb(i.tensor,p):[]:((x=this.config.body.modelPath)==null?void 0:x.includes("efficientpose"))?c=this.config.body.enabled?Tb(i.tensor,p):[]:((y=this.config.body.modelPath)==null?void 0:y.includes("movenet"))&&(c=this.config.body.enabled?s5(i.tensor,p):[]),this.performance.body&&delete this.performance.body):(r=ie(),((b=this.config.body.modelPath)==null?void 0:b.includes("posenet"))?c=this.config.body.enabled?await d5(i.tensor,p):[]:((w=this.config.body.modelPath)==null?void 0:w.includes("blazepose"))?c=this.config.body.enabled?await xb(i.tensor,p):[]:((k=this.config.body.modelPath)==null?void 0:k.includes("efficientpose"))?c=this.config.body.enabled?await Tb(i.tensor,p):[]:((I=this.config.body.modelPath)==null?void 0:I.includes("movenet"))&&(c=this.config.body.enabled?await s5(i.tensor,p):[]),this.performance.body=this.env.perfadd?(this.performance.body||0)+Math.trunc(ie()-r):Math.trunc(ie()-r)),this.analyze("End Body:"),this.analyze("Start Hand:"),this.state="detect:hand";let h=this.config.hand.maxDetected===-1?$n(this.config,{hand:{maxDetected:this.config.face.enabled?2*l.length:1}}):this.config;this.config.async?(((R=(N=this.config.hand.detector)==null?void 0:N.modelPath)==null?void 0:R.includes("handdetect"))?u=this.config.hand.enabled?Ub(i.tensor,h):[]:(($=(O=this.config.hand.detector)==null?void 0:O.modelPath)==null?void 0:$.includes("handtrack"))&&(u=this.config.hand.enabled?Xb(i.tensor,h):[]),this.performance.hand&&delete this.performance.hand):(r=ie(),((T=(P=this.config.hand.detector)==null?void 0:P.modelPath)==null?void 0:T.includes("handdetect"))?u=this.config.hand.enabled?await Ub(i.tensor,h):[]:((U=(F=this.config.hand.detector)==null?void 0:F.modelPath)==null?void 0:U.includes("handtrack"))&&(u=this.config.hand.enabled?await Xb(i.tensor,h):[]),this.performance.hand=this.env.perfadd?(this.performance.hand||0)+Math.trunc(ie()-r):Math.trunc(ie()-r)),this.analyze("End Hand:"),this.analyze("Start Object:"),this.state="detect:object",this.config.async?(((q=this.config.object.modelPath)==null?void 0:q.includes("nanodet"))?d=this.config.object.enabled?a5(i.tensor,this.config):[]:((z=this.config.object.modelPath)==null?void 0:z.includes("centernet"))&&(d=this.config.object.enabled?wb(i.tensor,this.config):[]),this.performance.object&&delete this.performance.object):(r=ie(),((K=this.config.object.modelPath)==null?void 0:K.includes("nanodet"))?d=this.config.object.enabled?await a5(i.tensor,this.config):[]:((J=this.config.object.modelPath)==null?void 0:J.includes("centernet"))&&(d=this.config.object.enabled?await wb(i.tensor,this.config):[]),this.performance.object=this.env.perfadd?(this.performance.object||0)+Math.trunc(ie()-r):Math.trunc(ie()-r)),this.analyze("End Object:"),this.state="detect:await",this.config.async&&([l,c,u,d]=await Promise.all([l,c,u,d])),this.state="detect:gesture";let f=[];this.config.gesture.enabled&&(r=ie(),f=[...xN(l),...yN(c),...vN(u),...bN(l)],this.config.async?this.performance.gesture&&delete this.performance.gesture:this.performance.gesture=this.env.perfadd?(this.performance.gesture||0)+Math.trunc(ie()-r):Math.trunc(ie()-r)),this.performance.total=this.env.perfadd?(this.performance.total||0)+Math.trunc(ie()-o):Math.trunc(ie()-o);let m=((ne=(Q=this.process)==null?void 0:Q.tensor)==null?void 0:ne.shape)||[];this.result={face:l,body:c,hand:u,gesture:f,object:d,performance:this.performance,canvas:this.process.canvas,timestamp:Date.now(),error:null,get persons(){return CN(l,c,u,f,m)}},te(i.tensor),this.emit("detect"),this.state="idle",s(this.result)})}};Bc=new WeakMap,Hp=new WeakMap,jp=new WeakMap,B0=new WeakMap;return h1e;})(); /** * @license * Copyright 2017 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2018 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. * ============================================================================= */ /** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */ /** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2019 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. * ============================================================================= */ /** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */ /** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2020 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2020 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. * ============================================================================= */ /** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use backend file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * Human main module * @default Human Library * @summary * @author * @copyright * @license MIT */ /** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** @license See the LICENSE file. */