/* Human homepage: author: ' */ "use strict";var Human=(()=>{var Cf=Object.defineProperty;var e_=Object.getOwnPropertyDescriptor;var t_=Object.getOwnPropertyNames;var n_=Object.prototype.hasOwnProperty;var s_=(e,t,n)=>t in e?Cf(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Pi=(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 fa=(e,t)=>{for(var n in t)Cf(e,n,{get:t[n],enumerable:!0})},r_=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of t_(t))!n_.call(e,r)&&r!==n&&Cf(e,r,{get:()=>t[r],enumerable:!(s=e_(t,r))||s.enumerable});return e};var a_=e=>r_(Cf({},"__esModule",{value:!0}),e);var de=(e,t,n)=>(s_(e,typeof t!="symbol"?t+"":t,n),n),lv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var jr=(e,t,n)=>(lv(e,t,"read from private field"),n?n.call(e):t.get(e)),Mu=(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)},Bd=(e,t,n,s)=>(lv(e,t,"write to private field"),s?s.call(e,n):t.set(e,n),n);var Fbe={};fa(Fbe,{Env:()=>zh,Human:()=>G4,default:()=>G4,defaults:()=>Ha,draw:()=>M4,env:()=>pe,match:()=>U4,models:()=>kd});function ee(...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 uv(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 Kg(e,t,n="config",s=[]){for(let r of Object.keys(t))if(typeof t[r]=="object")Kg(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&&ee("invalid configuration",s),s}function Bt(...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]=Bt(a,o):n[r]=o}),n),{})}var Ha={backend:"",modelBasePath:"",cacheModels:!0,validateModels:!0,wasmPath:"",wasmPlatformFetch:!1,debug:!1,async:!0,warmup:"full",cacheSensitivity:.7,skipAllowed:!1,deallocate:!1,flags:{},softwareKernels:!1,filter:{enabled:!0,equalization:!1,width:0,height:0,flip:!1,return:!0,brightness:0,contrast:0,sharpness:0,blur:0,saturation:0,hue:0,negative:!1,sepia:!1,vintage:!1,kodachrome:!1,technicolor:!1,polaroid:!1,pixelate:0},gesture:{enabled:!0},face:{enabled:!0,detector:{modelPath:"blazeface.json",rotation:!0,maxDetected:1,skipFrames:99,skipTime:2500,minConfidence:.2,iouThreshold:.1,mask:!1,return:!1},mesh:{enabled:!0,modelPath:"facemesh.json",keepInvalid:!1},attention:{enabled:!1,modelPath:"facemesh-attention.json"},iris:{enabled:!0,modelPath:"iris.json"},emotion:{enabled:!0,minConfidence:.1,skipFrames:99,skipTime:1500,modelPath:"emotion.json"},description:{enabled:!0,modelPath:"faceres.json",skipFrames:99,skipTime:3e3,minConfidence:.1},antispoof:{enabled:!1,skipFrames:99,skipTime:4e3,modelPath:"antispoof.json"},liveness:{enabled:!1,skipFrames:99,skipTime:4e3,modelPath:"liveness.json"}},body:{enabled:!0,modelPath:"movenet-lightning.json",maxDetected:-1,minConfidence:.3,skipFrames:1,skipTime:200},hand:{enabled:!0,rotation:!0,skipFrames:99,skipTime:1e3,minConfidence:.5,iouThreshold:.2,maxDetected:-1,landmarks:!0,detector:{modelPath:"handtrack.json"},skeleton:{modelPath:"handlandmark-full.json"}},object:{enabled:!1,modelPath:"mb3-centernet.json",minConfidence:.2,iouThreshold:.4,maxDetected:10,skipFrames:99,skipTime:2e3},segmentation:{enabled:!1,modelPath:"rvm.json",ratio:.5,mode:"default"}};var Ye={};fa(Ye,{Abs:()=>dl,Acos:()=>gc,Acosh:()=>yc,AdadeltaOptimizer:()=>O0,AdagradOptimizer:()=>M0,AdamOptimizer:()=>z0,AdamaxOptimizer:()=>L0,Add:()=>Ta,AddN:()=>go,All:()=>Ac,Any:()=>xc,ArgMax:()=>yo,ArgMin:()=>bc,Asin:()=>vc,Asinh:()=>wc,Atan:()=>kc,Atan2:()=>pl,Atanh:()=>Sc,AvgPool:()=>Ao,AvgPool3D:()=>Np,AvgPool3DGrad:()=>$m,AvgPoolGrad:()=>Dm,BackendWasm:()=>QC,BatchMatMul:()=>xo,BatchToSpaceND:()=>hl,Bincount:()=>Pm,BroadcastArgs:()=>Fm,BroadcastTo:()=>mw,Callback:()=>D8,CallbackList:()=>Ok,Cast:()=>bo,Ceil:()=>vo,ClipByValue:()=>Na,Complex:()=>Ep,ComplexAbs:()=>Rp,Concat:()=>fl,Conv2D:()=>wo,Conv2DBackpropFilter:()=>Om,Conv2DBackpropInput:()=>ko,Conv3D:()=>_p,Conv3DBackpropFilterV2:()=>Mm,Conv3DBackpropInputV2:()=>zm,Cos:()=>So,Cosh:()=>Io,CropAndResize:()=>gl,Cumprod:()=>ml,Cumsum:()=>Co,CustomCallback:()=>zk,DataStorage:()=>Tp,DenseBincount:()=>Lm,DepthToSpace:()=>yl,DepthwiseConv2dNative:()=>To,DepthwiseConv2dNativeBackpropFilter:()=>Bm,DepthwiseConv2dNativeBackpropInput:()=>Wm,Diag:()=>Vm,Dilation2D:()=>Dp,Dilation2DBackpropFilter:()=>nm,Dilation2DBackpropInput:()=>tm,ENV:()=>by,EarlyStopping:()=>$8,Einsum:()=>$p,Elu:()=>Eo,EluGrad:()=>Um,Environment:()=>hw,Equal:()=>Al,Erf:()=>Ic,Exp:()=>Ro,ExpandDims:()=>xl,Expm1:()=>bl,FFT:()=>Gm,Fill:()=>Cc,FlipLeftRight:()=>vl,Floor:()=>_o,FloorDiv:()=>Do,FromPixels:()=>lp,FusedBatchNorm:()=>$o,FusedConv2D:()=>so,FusedDepthwiseConv2D:()=>ro,GPGPUContext:()=>Zu,GatherNd:()=>kl,GatherV2:()=>wl,GraphModel:()=>Ch,Greater:()=>Sl,GreaterEqual:()=>Po,History:()=>Mk,IFFT:()=>Hm,Identity:()=>Fo,Imag:()=>Pp,InputSpec:()=>an,IsFinite:()=>Tc,IsInf:()=>Nc,IsNan:()=>Il,KernelBackend:()=>fc,LRN:()=>Fp,LRNGrad:()=>qm,LayerVariable:()=>Ek,LayersModel:()=>ba,LeakyRelu:()=>Oo,Less:()=>Cl,LessEqual:()=>Tl,LinSpace:()=>jm,Log:()=>Mo,Log1p:()=>Ec,LogSoftmax:()=>yw,LogicalAnd:()=>Nl,LogicalNot:()=>El,LogicalOr:()=>Rc,LogicalXor:()=>gw,LowerBound:()=>Z_,MathBackendWebGL:()=>od,Max:()=>zo,MaxPool:()=>Bo,MaxPool3D:()=>Op,MaxPool3DGrad:()=>Km,MaxPoolGrad:()=>Xm,MaxPoolWithArgmax:()=>Zm,Maximum:()=>Lo,Mean:()=>Wo,Min:()=>Vo,Minimum:()=>Uo,MirrorPad:()=>Go,Mod:()=>_c,MomentumOptimizer:()=>B0,Multinomial:()=>Ym,Multiply:()=>Ho,Neg:()=>Rl,NonMaxSuppressionV3:()=>Dl,NonMaxSuppressionV4:()=>Dc,NonMaxSuppressionV5:()=>$l,NotEqual:()=>_l,OP_SCOPE_SUFFIX:()=>Sy,OneHot:()=>Fl,OnesLike:()=>Pl,Optimizer:()=>_a,OptimizerConstructors:()=>ja,Pack:()=>Ol,PadV2:()=>jo,Pool:()=>Y_,Pow:()=>qo,Prelu:()=>Xo,Prod:()=>Ko,RMSPropOptimizer:()=>W0,RNN:()=>ia,RaggedGather:()=>Jm,RaggedTensorToTensor:()=>Qm,Range:()=>$c,Rank:()=>f3,Real:()=>Mp,RealDiv:()=>No,Reciprocal:()=>Ml,Reduction:()=>rs,Relu:()=>Zo,Relu6:()=>Qo,Reshape:()=>zl,ResizeBilinear:()=>Jo,ResizeBilinearGrad:()=>t0,ResizeNearestNeighbor:()=>Yo,ResizeNearestNeighborGrad:()=>e0,Reverse:()=>Ll,RotateWithOffset:()=>Ql,Round:()=>Bl,Rsqrt:()=>ei,SGDOptimizer:()=>hh,ScatterNd:()=>Wl,SearchSorted:()=>n0,Select:()=>Vl,Selu:()=>Pc,Sequential:()=>ic,Sigmoid:()=>ni,Sign:()=>Fc,Sin:()=>ti,Sinh:()=>Gl,Slice:()=>Ul,Softmax:()=>ai,Softplus:()=>Oc,SpaceToBatchND:()=>Hl,SparseFillEmptyRows:()=>zp,SparseReshape:()=>Mc,SparseSegmentMean:()=>Lp,SparseSegmentSum:()=>Bp,SparseToDense:()=>Wp,SplitV:()=>jl,Sqrt:()=>si,Square:()=>zc,SquaredDifference:()=>oi,Step:()=>ui,StridedSlice:()=>ql,StringNGrams:()=>Lc,StringSplit:()=>Vp,StringToHashBucketFast:()=>Up,Sub:()=>ii,Sum:()=>ri,SymbolicTensor:()=>_r,Tan:()=>Xl,Tanh:()=>li,Tensor:()=>st,TensorBuffer:()=>gn,Tile:()=>Ea,TopK:()=>Kl,Transform:()=>Zl,Transpose:()=>Jr,Unique:()=>s0,Unpack:()=>Yl,UnsortedSegmentSum:()=>Gp,UpperBound:()=>J_,Variable:()=>dp,WebGPUBackend:()=>m2,ZerosLike:()=>Jl,_FusedMatMul:()=>no,abs:()=>rn,acos:()=>Vy,acosh:()=>Uy,add:()=>le,addN:()=>a0,all:()=>o0,any:()=>fp,argMax:()=>Ps,argMin:()=>Gy,asin:()=>Hy,asinh:()=>jy,atan:()=>qy,atan2:()=>Xy,atanh:()=>Ky,avgPool:()=>eh,avgPool3d:()=>Yy,backend:()=>Bs,backend_util:()=>T,basicLSTMCell:()=>c6,batchNorm:()=>Wc,batchNorm2d:()=>Jy,batchNorm3d:()=>Qy,batchNorm4d:()=>eA,batchToSpaceND:()=>th,bincount:()=>tA,booleanMaskAsync:()=>q6,broadcastArgs:()=>d6,broadcastTo:()=>Xi,broadcast_util:()=>tu,browser:()=>ra,buffer:()=>ze,callbacks:()=>dj,cast:()=>me,ceil:()=>nA,clipByValue:()=>bs,clone:()=>Hn,complex:()=>wa,concat:()=>ut,concat1d:()=>sA,concat2d:()=>nu,concat3d:()=>rA,concat4d:()=>aA,constraints:()=>Dk,conv1d:()=>i0,conv2d:()=>ka,conv2dTranspose:()=>l0,conv3d:()=>iA,conv3dTranspose:()=>lA,copyRegisteredKernels:()=>nD,cos:()=>nh,cosh:()=>u0,cosineWindow:()=>_0,cumprod:()=>mp,cumsum:()=>c0,customGrad:()=>na,data:()=>sS,denseBincount:()=>h6,deprecationWarn:()=>Dy,depthToSpace:()=>uA,depthwiseConv2d:()=>Vc,deregisterOp:()=>fj,device_util:()=>Xp,diag:()=>f6,dilation2d:()=>cA,disableDeprecationWarnings:()=>E$,dispose:()=>Y,disposeVariables:()=>R$,div:()=>ge,divNoNan:()=>dA,dot:()=>pA,dropout:()=>zA,einsum:()=>m6,elu:()=>Uc,enableDebugMode:()=>N$,enableProdMode:()=>_y,enclosingPowerOfTwo:()=>LA,engine:()=>Jt,env:()=>U,equal:()=>Fs,erf:()=>hA,euclideanNorm:()=>gA,exp:()=>Os,expandDims:()=>Ft,expm1:()=>yA,eye:()=>d0,fft:()=>dh,fill:()=>zr,findBackend:()=>$y,findBackendFactory:()=>P$,floor:()=>Hc,floorDiv:()=>Bc,forceHalfFloat:()=>x9,fused:()=>rc,gather:()=>jc,gatherND:()=>Y6,gather_util:()=>Fy,getBackend:()=>cn,getGradient:()=>p3,getKernel:()=>sm,getKernelsForBackend:()=>ea,getThreadsCount:()=>e0e,gpgpu_util:()=>YI,grad:()=>sO,grads:()=>rO,greater:()=>ks,greaterEqual:()=>pi,ifft:()=>sc,imag:()=>Jp,image:()=>ke,inTopKAsync:()=>J6,initializers:()=>$k,input:()=>Jk,io:()=>On,irfft:()=>T0,isFinite:()=>AA,isInf:()=>xA,isNaN:()=>bA,keep:()=>Cn,kernel_impls:()=>Ar,layers:()=>Pk,leakyRelu:()=>sh,less:()=>p0,lessEqual:()=>hi,linalg:()=>VA,linspace:()=>b6,loadGraphModel:()=>xx,loadGraphModelSync:()=>yq,loadLayersModel:()=>bG,localResponseNormalization:()=>vA,log:()=>Ms,log1p:()=>rh,logSigmoid:()=>wA,logSoftmax:()=>f0,logSumExp:()=>m0,logicalAnd:()=>gr,logicalNot:()=>ah,logicalOr:()=>g0,logicalXor:()=>kA,losses:()=>ck,lowerBound:()=>w6,matMul:()=>et,math:()=>Uw,max:()=>yn,maxPool:()=>oh,maxPool3d:()=>SA,maxPoolWithArgmax:()=>k6,maximum:()=>oa,mean:()=>Wt,memory:()=>om,meshgrid:()=>S6,metrics:()=>E8,min:()=>Sa,minimum:()=>qc,mirrorPad:()=>IA,mod:()=>ru,model:()=>AG,models:()=>R8,moments:()=>ih,movingAverage:()=>X6,mul:()=>M,multiRNNCell:()=>I6,multinomial:()=>C6,neg:()=>Dt,nextFrame:()=>UA,norm:()=>Gc,notEqual:()=>sl,oneHot:()=>ec,ones:()=>Ds,onesLike:()=>zs,op:()=>B,outerProduct:()=>T6,pad:()=>tr,pad1d:()=>N6,pad2d:()=>E6,pad3d:()=>R6,pad4d:()=>_6,pool:()=>CA,pow:()=>Ia,prelu:()=>uh,print:()=>Ny,prod:()=>TA,profile:()=>_$,raggedGather:()=>D6,raggedTensorToTensor:()=>$6,rand:()=>P6,randomGamma:()=>F6,randomNormal:()=>A0,randomStandardNormal:()=>O6,randomUniform:()=>Xc,range:()=>nc,ready:()=>Yp,real:()=>tc,reciprocal:()=>RA,registerBackend:()=>eu,registerCallbackConstructor:()=>vG,registerGradient:()=>Aw,registerKernel:()=>er,registerOp:()=>hj,regularizers:()=>_8,relu:()=>Lr,relu6:()=>x0,removeBackend:()=>$$,reshape:()=>W,reverse:()=>Js,reverse1d:()=>M6,reverse2d:()=>z6,reverse3d:()=>L6,reverse4d:()=>B6,rfft:()=>ph,round:()=>b0,rsqrt:()=>v0,scalar:()=>Ce,scatterND:()=>K6,scatter_util:()=>Oy,searchSorted:()=>y0,selu:()=>w0,separableConv2d:()=>k0,sequential:()=>xG,serialization:()=>ce,setBackend:()=>Zp,setPlatform:()=>F$,setThreadsCount:()=>Qme,setWasmPath:()=>Jme,setWasmPaths:()=>f2,setWebGLContext:()=>l2,setdiff1dAsync:()=>W6,sigmoid:()=>Mn,sign:()=>_A,signal:()=>uk,sin:()=>S0,sinh:()=>I0,slice:()=>Oe,slice1d:()=>ch,slice2d:()=>C0,slice3d:()=>fi,slice4d:()=>oo,slice_util:()=>Gt,softmax:()=>au,softplus:()=>su,spaceToBatchND:()=>lh,sparse:()=>dk,sparseToDense:()=>Z6,spectral:()=>lk,split:()=>Ht,sqrt:()=>Ln,square:()=>bt,squaredDifference:()=>N0,squeeze:()=>Ge,stack:()=>ln,step:()=>ou,stridedSlice:()=>DA,string:()=>pk,sub:()=>ye,sum:()=>ve,sumOutType:()=>qp,tan:()=>$A,tanh:()=>tl,tensor:()=>Ue,tensor1d:()=>Ot,tensor2d:()=>mr,tensor3d:()=>Py,tensor4d:()=>V6,tensor5d:()=>U6,tensor6d:()=>G6,tensor_util:()=>Dr,test_util:()=>r6,tidy:()=>X,tile:()=>As,time:()=>D$,topk:()=>PA,train:()=>zi,transpose:()=>tt,truncatedNormal:()=>E0,unique:()=>FA,unregisterGradient:()=>tD,unregisterKernel:()=>eD,unsortedSegmentSum:()=>R0,unstack:()=>bn,upcastType:()=>jn,upperBound:()=>H6,util:()=>v,valueAndGrad:()=>aO,valueAndGrads:()=>oO,variable:()=>OA,variableGrads:()=>v6,version:()=>Mh,version_converter:()=>xq,version_core:()=>Wy,version_layers:()=>d5,version_wasm:()=>t0e,version_webgl:()=>qne,webgl:()=>Xne,webgl_util:()=>vI,webgpu_util:()=>nT,where:()=>qn,whereAsync:()=>MA,zeros:()=>Vt,zerosLike:()=>ct});var o_=Object.create,my=Object.defineProperty,i_=Object.getOwnPropertyDescriptor,ew=Object.getOwnPropertyNames,l_=Object.getPrototypeOf,u_=Object.prototype.hasOwnProperty,tw=(e=>typeof Pi!="undefined"?Pi:typeof Proxy!="undefined"?new Proxy(e,{get:(t,n)=>(typeof Pi!="undefined"?Pi:t)[n]}):e)(function(e){if(typeof Pi!="undefined")return Pi.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')}),un=(e,t)=>function(){return t||(0,e[ew(e)[0]])((t={exports:{}}).exports,t),t.exports},We=(e,t)=>{for(var n in t)my(e,n,{get:t[n],enumerable:!0})},c_=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ew(t))!u_.call(e,r)&&r!==n&&my(e,r,{get:()=>t[r],enumerable:!(s=i_(t,r))||s.enumerable});return e},fo=(e,t,n)=>(n=e!=null?o_(l_(e)):{},c_(t||!e||!e.__esModule?my(n,"default",{value:e,enumerable:!0}):n,e)),d_=un({"node_modules/.pnpm/long@4.0.0/node_modules/long/src/long.js"(e,t){t.exports=s;var n=null;try{n=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch($){}function s($,S,F){this.low=$|0,this.high=S|0,this.unsigned=!!F}s.prototype.__isLong__,Object.defineProperty(s.prototype,"__isLong__",{value:!0});function r($){return($&&$.__isLong__)===!0}s.isLong=r;var a={},o={};function i($,S){var F,z,V;return S?($>>>=0,(V=0<=$&&$<256)&&(z=o[$],z)?z:(F=u($,($|0)<0?-1:0,!0),V&&(o[$]=F),F)):($|=0,(V=-128<=$&&$<128)&&(z=a[$],z)?z:(F=u($,$<0?-1:0,!1),V&&(a[$]=F),F))}s.fromInt=i;function l($,S){if(isNaN($))return S?b:A;if(S){if($<0)return b;if($>=g)return R}else{if($<=-y)return D;if($+1>=y)return N}return $<0?l(-$,S).neg():u($%m|0,$/m|0,S)}s.fromNumber=l;function u($,S,F){return new s($,S,F)}s.fromBits=u;var c=Math.pow;function p($,S,F){if($.length===0)throw Error("empty string");if($==="NaN"||$==="Infinity"||$==="+Infinity"||$==="-Infinity")return A;if(typeof S=="number"?(F=S,S=!1):S=!!S,F=F||10,F<2||360)throw Error("interior hyphen");if(z===0)return p($.substring(1),S,F).neg();for(var V=l(c(F,8)),j=A,G=0;G<$.length;G+=8){var q=Math.min(8,$.length-G),K=parseInt($.substring(G,G+q),F);if(q<8){var ne=l(c(F,q));j=j.mul(ne).add(l(K))}else j=j.mul(V),j=j.add(l(K))}return j.unsigned=S,j}s.fromString=p;function d($,S){return typeof $=="number"?l($,S):typeof $=="string"?p($,S):u($.low,$.high,typeof S=="boolean"?S:$.unsigned)}s.fromValue=d;var h=1<<16,f=1<<24,m=h*h,g=m*m,y=g/2,x=i(f),A=i(0);s.ZERO=A;var b=i(0,!0);s.UZERO=b;var w=i(1);s.ONE=w;var k=i(1,!0);s.UONE=k;var C=i(-1);s.NEG_ONE=C;var N=u(-1,2147483647,!1);s.MAX_VALUE=N;var R=u(-1,-1,!0);s.MAX_UNSIGNED_VALUE=R;var D=u(0,-2147483648,!1);s.MIN_VALUE=D;var E=s.prototype;E.toInt=function(){return this.unsigned?this.low>>>0:this.low},E.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},E.toString=function(S){if(S=S||10,S<2||36>>0,ae=ne.toString(S);if(G=K,G.isZero())return ae+q;for(;ae.length<6;)ae="0"+ae;q=""+ae+q}},E.getHighBits=function(){return this.high},E.getHighBitsUnsigned=function(){return this.high>>>0},E.getLowBits=function(){return this.low},E.getLowBitsUnsigned=function(){return this.low>>>0},E.getNumBitsAbs=function(){if(this.isNegative())return this.eq(D)?64:this.neg().getNumBitsAbs();for(var S=this.high!=0?this.high:this.low,F=31;F>0&&(S&1<=0},E.isOdd=function(){return(this.low&1)===1},E.isEven=function(){return(this.low&1)===0},E.equals=function(S){return r(S)||(S=d(S)),this.unsigned!==S.unsigned&&this.high>>>31===1&&S.high>>>31===1?!1:this.high===S.high&&this.low===S.low},E.eq=E.equals,E.notEquals=function(S){return!this.eq(S)},E.neq=E.notEquals,E.ne=E.notEquals,E.lessThan=function(S){return this.comp(S)<0},E.lt=E.lessThan,E.lessThanOrEqual=function(S){return this.comp(S)<=0},E.lte=E.lessThanOrEqual,E.le=E.lessThanOrEqual,E.greaterThan=function(S){return this.comp(S)>0},E.gt=E.greaterThan,E.greaterThanOrEqual=function(S){return this.comp(S)>=0},E.gte=E.greaterThanOrEqual,E.ge=E.greaterThanOrEqual,E.compare=function(S){if(r(S)||(S=d(S)),this.eq(S))return 0;var F=this.isNegative(),z=S.isNegative();return F&&!z?-1:!F&&z?1:this.unsigned?S.high>>>0>this.high>>>0||S.high===this.high&&S.low>>>0>this.low>>>0?-1:1:this.sub(S).isNegative()?-1:1},E.comp=E.compare,E.negate=function(){return!this.unsigned&&this.eq(D)?D:this.not().add(w)},E.neg=E.negate,E.add=function(S){r(S)||(S=d(S));var F=this.high>>>16,z=this.high&65535,V=this.low>>>16,j=this.low&65535,G=S.high>>>16,q=S.high&65535,K=S.low>>>16,ne=S.low&65535,ae=0,re=0,ue=0,oe=0;return oe+=j+ne,ue+=oe>>>16,oe&=65535,ue+=V+K,re+=ue>>>16,ue&=65535,re+=z+q,ae+=re>>>16,re&=65535,ae+=F+G,ae&=65535,u(ue<<16|oe,ae<<16|re,this.unsigned)},E.subtract=function(S){return r(S)||(S=d(S)),this.add(S.neg())},E.sub=E.subtract,E.multiply=function(S){if(this.isZero())return A;if(r(S)||(S=d(S)),n){var F=n.mul(this.low,this.high,S.low,S.high);return u(F,n.get_high(),this.unsigned)}if(S.isZero())return A;if(this.eq(D))return S.isOdd()?D:A;if(S.eq(D))return this.isOdd()?D:A;if(this.isNegative())return S.isNegative()?this.neg().mul(S.neg()):this.neg().mul(S).neg();if(S.isNegative())return this.mul(S.neg()).neg();if(this.lt(x)&&S.lt(x))return l(this.toNumber()*S.toNumber(),this.unsigned);var z=this.high>>>16,V=this.high&65535,j=this.low>>>16,G=this.low&65535,q=S.high>>>16,K=S.high&65535,ne=S.low>>>16,ae=S.low&65535,re=0,ue=0,oe=0,Ae=0;return Ae+=G*ae,oe+=Ae>>>16,Ae&=65535,oe+=j*ae,ue+=oe>>>16,oe&=65535,oe+=G*ne,ue+=oe>>>16,oe&=65535,ue+=V*ae,re+=ue>>>16,ue&=65535,ue+=j*ne,re+=ue>>>16,ue&=65535,ue+=G*K,re+=ue>>>16,ue&=65535,re+=z*ae+V*ne+j*K+G*q,re&=65535,u(oe<<16|Ae,re<<16|ue,this.unsigned)},E.mul=E.multiply,E.divide=function(S){if(r(S)||(S=d(S)),S.isZero())throw Error("division by zero");if(n){if(!this.unsigned&&this.high===-2147483648&&S.low===-1&&S.high===-1)return this;var F=(this.unsigned?n.div_u:n.div_s)(this.low,this.high,S.low,S.high);return u(F,n.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?b:A;var z,V,j;if(this.unsigned){if(S.unsigned||(S=S.toUnsigned()),S.gt(this))return b;if(S.gt(this.shru(1)))return k;j=b}else{if(this.eq(D)){if(S.eq(w)||S.eq(C))return D;if(S.eq(D))return w;var G=this.shr(1);return z=G.div(S).shl(1),z.eq(A)?S.isNegative()?w:C:(V=this.sub(S.mul(z)),j=z.add(V.div(S)),j)}else if(S.eq(D))return this.unsigned?b:A;if(this.isNegative())return S.isNegative()?this.neg().div(S.neg()):this.neg().div(S).neg();if(S.isNegative())return this.div(S.neg()).neg();j=A}for(V=this;V.gte(S);){z=Math.max(1,Math.floor(V.toNumber()/S.toNumber()));for(var q=Math.ceil(Math.log(z)/Math.LN2),K=q<=48?1:c(2,q-48),ne=l(z),ae=ne.mul(S);ae.isNegative()||ae.gt(V);)z-=K,ne=l(z,this.unsigned),ae=ne.mul(S);ne.isZero()&&(ne=w),j=j.add(ne),V=V.sub(ae)}return j},E.div=E.divide,E.modulo=function(S){if(r(S)||(S=d(S)),n){var F=(this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,S.low,S.high);return u(F,n.get_high(),this.unsigned)}return this.sub(this.div(S).mul(S))},E.mod=E.modulo,E.rem=E.modulo,E.not=function(){return u(~this.low,~this.high,this.unsigned)},E.and=function(S){return r(S)||(S=d(S)),u(this.low&S.low,this.high&S.high,this.unsigned)},E.or=function(S){return r(S)||(S=d(S)),u(this.low|S.low,this.high|S.high,this.unsigned)},E.xor=function(S){return r(S)||(S=d(S)),u(this.low^S.low,this.high^S.high,this.unsigned)},E.shiftLeft=function(S){return r(S)&&(S=S.toInt()),(S&=63)===0?this:S<32?u(this.low<>>32-S,this.unsigned):u(0,this.low<>>S|this.high<<32-S,this.high>>S,this.unsigned):u(this.high>>S-32,this.high>=0?0:-1,this.unsigned)},E.shr=E.shiftRight,E.shiftRightUnsigned=function(S){if(r(S)&&(S=S.toInt()),S&=63,S===0)return this;var F=this.high;if(S<32){var z=this.low;return u(z>>>S|F<<32-S,F>>>S,this.unsigned)}else return S===32?u(F,0,this.unsigned):u(F>>>S-32,0,this.unsigned)},E.shru=E.shiftRightUnsigned,E.shr_u=E.shiftRightUnsigned,E.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},E.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},E.toBytes=function(S){return S?this.toBytesLE():this.toBytesBE()},E.toBytesLE=function(){var S=this.high,F=this.low;return[F&255,F>>>8&255,F>>>16&255,F>>>24,S&255,S>>>8&255,S>>>16&255,S>>>24]},E.toBytesBE=function(){var S=this.high,F=this.low;return[S>>>24,S>>>16&255,S>>>8&255,S&255,F>>>24,F>>>16&255,F>>>8&255,F&255]},s.fromBytes=function(S,F,z){return z?s.fromBytesLE(S,F):s.fromBytesBE(S,F)},s.fromBytesLE=function(S,F){return new s(S[0]|S[1]<<8|S[2]<<16|S[3]<<24,S[4]|S[5]<<8|S[6]<<16|S[7]<<24,F)},s.fromBytesBE=function(S,F){return new s(S[4]<<24|S[5]<<16|S[6]<<8|S[7],S[0]<<24|S[1]<<16|S[2]<<8|S[3],F)}}}),p_=un({"(disabled):node_modules/.pnpm/node-fetch@2.6.7/node_modules/node-fetch/browser.js"(){}}),h_=un({"(disabled):util"(){}}),f_=un({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js"(e,t){(function(n,s,r){function a(u){var c=this,p=l();c.next=function(){var d=2091639*c.s0+c.c*23283064365386963e-26;return c.s0=c.s1,c.s1=c.s2,c.s2=d-(c.c=d|0)},c.c=1,c.s0=p(" "),c.s1=p(" "),c.s2=p(" "),c.s0-=p(u),c.s0<0&&(c.s0+=1),c.s1-=p(u),c.s1<0&&(c.s1+=1),c.s2-=p(u),c.s2<0&&(c.s2+=1),p=null}function o(u,c){return c.c=u.c,c.s0=u.s0,c.s1=u.s1,c.s2=u.s2,c}function i(u,c){var p=new a(u),d=c&&c.state,h=p.next;return h.int32=function(){return p.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,d&&(typeof d=="object"&&o(d,p),h.state=function(){return o(p,{})}),h}function l(){var u=4022871197,c=function(p){p=String(p);for(var d=0;d>>0,h-=u,h*=u,u=h>>>0,h-=u,u+=h*4294967296}return(u>>>0)*23283064365386963e-26};return c}s&&s.exports?s.exports=i:r&&r.amd?r(function(){return i}):this.alea=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),m_=un({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js"(e,t){(function(n,s,r){function a(l){var u=this,c="";u.x=0,u.y=0,u.z=0,u.w=0,u.next=function(){var d=u.x^u.x<<11;return u.x=u.y,u.y=u.z,u.z=u.w,u.w^=u.w>>>19^d^d>>>8},l===(l|0)?u.x=l:c+=l;for(var p=0;p>>0)/4294967296};return d.double=function(){do var h=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},d.int32=c.next,d.quick=d,p&&(typeof p=="object"&&o(p,c),d.state=function(){return o(c,{})}),d}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)}}),g_=un({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js"(e,t){(function(n,s,r){function a(l){var u=this,c="";u.next=function(){var d=u.x^u.x>>>2;return u.x=u.y,u.y=u.z,u.z=u.w,u.w=u.v,(u.d=u.d+362437|0)+(u.v=u.v^u.v<<4^(d^d<<1))|0},u.x=0,u.y=0,u.z=0,u.w=0,u.v=0,l===(l|0)?u.x=l:c+=l;for(var p=0;p>>4),u.next()}function o(l,u){return u.x=l.x,u.y=l.y,u.z=l.z,u.w=l.w,u.v=l.v,u.d=l.d,u}function i(l,u){var c=new a(l),p=u&&u.state,d=function(){return(c.next()>>>0)/4294967296};return d.double=function(){do var h=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},d.int32=c.next,d.quick=d,p&&(typeof p=="object"&&o(p,c),d.state=function(){return o(c,{})}),d}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)}}),y_=un({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js"(e,t){(function(n,s,r){function a(l){var u=this;u.next=function(){var p=u.x,d=u.i,h,f,m;return h=p[d],h^=h>>>7,f=h^h<<24,h=p[d+1&7],f^=h^h>>>10,h=p[d+3&7],f^=h^h>>>3,h=p[d+4&7],f^=h^h<<7,h=p[d+7&7],h=h^h<<13,f^=h^h<<9,p[d]=f,u.i=d+1&7,f};function c(p,d){var h,f,m=[];if(d===(d|0))f=m[0]=d;else for(d=""+d,h=0;h0;--h)p.next()}c(u,l)}function o(l,u){return u.x=l.x.slice(),u.i=l.i,u}function i(l,u){l==null&&(l=+new Date);var c=new a(l),p=u&&u.state,d=function(){return(c.next()>>>0)/4294967296};return d.double=function(){do var h=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},d.int32=c.next,d.quick=d,p&&(p.x&&o(p,c),d.state=function(){return o(c,{})}),d}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)}}),A_=un({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js"(e,t){(function(n,s,r){function a(l){var u=this;u.next=function(){var p=u.w,d=u.X,h=u.i,f,m;return u.w=p=p+1640531527|0,m=d[h+34&127],f=d[h=h+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,m=d[h]=m^f,u.i=h,m+(p^p>>>16)|0};function c(p,d){var h,f,m,g,y,x=[],A=128;for(d===(d|0)?(f=d,d=null):(d=d+"\0",f=0,A=Math.max(A,d.length)),m=0,g=-32;g>>15,f^=f<<4,f^=f>>>13,g>=0&&(y=y+1640531527|0,h=x[g&127]^=f+y,m=h==0?m+1:0);for(m>=128&&(x[(d&&d.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;p.w=y,p.X=x,p.i=m}c(u,l)}function o(l,u){return u.i=l.i,u.w=l.w,u.X=l.X.slice(),u}function i(l,u){l==null&&(l=+new Date);var c=new a(l),p=u&&u.state,d=function(){return(c.next()>>>0)/4294967296};return d.double=function(){do var h=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},d.int32=c.next,d.quick=d,p&&(p.X&&o(p,c),d.state=function(){return o(c,{})}),d}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)}}),x_=un({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js"(e,t){(function(n,s,r){function a(l){var u=this,c="";u.next=function(){var d=u.b,h=u.c,f=u.d,m=u.a;return d=d<<25^d>>>7^h,h=h-f|0,f=f<<24^f>>>8^m,m=m-d|0,u.b=d=d<<20^d>>>12^h,u.c=h=h-f|0,u.d=f<<16^h>>>16^m,u.a=m-d|0},u.a=0,u.b=0,u.c=-1640531527,u.d=1367130551,l===Math.floor(l)?(u.a=l/4294967296|0,u.b=l|0):c+=l;for(var p=0;p>>0)/4294967296};return d.double=function(){do var h=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},d.int32=c.next,d.quick=d,p&&(typeof p=="object"&&o(p,c),d.state=function(){return o(c,{})}),d}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)}}),b_=un({"(disabled):crypto"(){}}),v_=un({"node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js"(e,t){(function(n,s,r){var a=256,o=6,i=52,l="random",u=r.pow(a,o),c=r.pow(2,i),p=c*2,d=a-1,h;function f(w,k,C){var N=[];k=k==!0?{entropy:!0}:k||{};var R=x(y(k.entropy?[w,b(s)]:w==null?A():w,3),N),D=new m(N),E=function(){for(var $=D.g(o),S=u,F=0;$=p;)$/=2,S/=2,F>>>=1;return($+F)/S};return E.int32=function(){return D.g(4)|0},E.quick=function(){return D.g(4)/4294967296},E.double=E,x(b(D.S),s),(k.pass||C||function($,S,F,z){return z&&(z.S&&g(z,D),$.state=function(){return g(D,{})}),F?(r[l]=$,S):$})(E,R,"global"in k?k.global:this==r,k.state)}function m(w){var k,C=w.length,N=this,R=0,D=N.i=N.j=0,E=N.S=[];for(C||(w=[C++]);R{var s=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(s=s||__filename),function(r){r=r||{};function a(){return Q.buffer!=Qe&&Rt(Q.buffer),kt}function o(){return Q.buffer!=Qe&&Rt(Q.buffer),Cs}function i(){return Q.buffer!=Qe&&Rt(Q.buffer),Kt}function l(){return Q.buffer!=Qe&&Rt(Q.buffer),Pn}function u(){return Q.buffer!=Qe&&Rt(Q.buffer),ir}function c(){return Q.buffer!=Qe&&Rt(Q.buffer),es}function p(){return Q.buffer!=Qe&&Rt(Q.buffer),Ts}var d=typeof r!="undefined"?r:{},h,f;d.ready=new Promise(function(O,Z){h=O,f=Z});var m;typeof process!="undefined"&&process.listeners&&(m={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var g=Object.assign({},d),y=[],x="./this.program",A=(O,Z)=>{throw Z},b=typeof window=="object",w=typeof importScripts=="function",k=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",C=d.ENVIRONMENT_IS_PTHREAD||!1,N="";function R(O){return d.locateFile?d.locateFile(O,N):N+O}var D,E,$,S;function F(O){if(O instanceof Di)return;K("exiting due to exception: "+O)}if(k){w?N=Jf().dirname(N)+"/":N=__dirname+"/";var z,V;typeof tw=="function"&&(z=gy(),V=Jf()),D=(Z,fe)=>(Z=V.normalize(Z),z.readFileSync(Z,fe?void 0:"utf8")),$=Z=>{var fe=D(Z,!0);return fe.buffer||(fe=new Uint8Array(fe)),fe},E=(Z,fe,xe)=>{Z=V.normalize(Z),z.readFile(Z,function(Pe,lt){Pe?xe(Pe):fe(lt.buffer)})},process.argv.length>1&&(x=process.argv[1].replace(/\\/g,"/")),y=process.argv.slice(2),process.on("uncaughtException",function(Z){if(!(Z instanceof Di))throw Z}),process.on("unhandledRejection",function(Z){throw Z}),A=(Z,fe)=>{if(ur())throw process.exitCode=Z,fe;F(fe),process.exit(Z)},d.inspect=function(){return"[Emscripten Module object]"};let O;try{O=w_()}catch(Z){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),Z}global.Worker=O.Worker}else(b||w)&&(w?N=self.location.href:typeof document!="undefined"&&document.currentScript&&(N=document.currentScript.src),typeof s!="undefined"&&s&&(N=s),N.indexOf("blob:")!==0?N=N.substr(0,N.replace(/[?#].*/,"").lastIndexOf("/")+1):N="",k||(D=O=>{var Z=new XMLHttpRequest;return Z.open("GET",O,!1),Z.send(null),Z.responseText},w&&($=O=>{var Z=new XMLHttpRequest;return Z.open("GET",O,!1),Z.responseType="arraybuffer",Z.send(null),new Uint8Array(Z.response)}),E=(O,Z,fe)=>{var xe=new XMLHttpRequest;xe.open("GET",O,!0),xe.responseType="arraybuffer",xe.onload=()=>{if(xe.status==200||xe.status==0&&xe.response){Z(xe.response);return}fe()},xe.onerror=fe,xe.send(null)}),S=O=>document.title=O);k&&typeof performance=="undefined"&&(global.performance=k_().performance);var j=console.log.bind(console),G=console.warn.bind(console);k&&(j=O=>z.writeSync(1,O+` `),G=O=>z.writeSync(2,O+` `));var q=d.print||j,K=d.printErr||G;Object.assign(d,g),g=null,d.arguments&&(y=d.arguments),d.thisProgram&&(x=d.thisProgram),d.quit&&(A=d.quit);var ne=4,ae=Atomics.load,re=Atomics.store,ue=Atomics.compareExchange,oe;d.wasmBinary&&(oe=d.wasmBinary);var Ae=d.noExitRuntime||!0;typeof WebAssembly!="object"&&Ru("no native wasm support detected");var Q,Ie,Se=!1,Fe;function $e(O,Z){O||Ru(Z)}var rt=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function mt(O,Z,fe){for(var xe=Z+fe,Pe=Z;O[Pe]&&!(Pe>=xe);)++Pe;if(Pe-Z>16&&O.buffer&&rt)return rt.decode(O.buffer instanceof SharedArrayBuffer?O.slice(Z,Pe):O.subarray(Z,Pe));for(var lt="";Z>10,56320|Xs&1023)}}return lt}function gt(O,Z){return O?mt(o(),O,Z):""}function yt(O,Z,fe,xe){if(!(xe>0))return 0;for(var Pe=fe,lt=fe+xe-1,Ve=0;Ve=55296&&qe<=57343){var sn=O.charCodeAt(++Ve);qe=65536+((qe&1023)<<10)|sn&1023}if(qe<=127){if(fe>=lt)break;Z[fe++]=qe}else if(qe<=2047){if(fe+1>=lt)break;Z[fe++]=192|qe>>6,Z[fe++]=128|qe&63}else if(qe<=65535){if(fe+2>=lt)break;Z[fe++]=224|qe>>12,Z[fe++]=128|qe>>6&63,Z[fe++]=128|qe&63}else{if(fe+3>=lt)break;Z[fe++]=240|qe>>18,Z[fe++]=128|qe>>12&63,Z[fe++]=128|qe>>6&63,Z[fe++]=128|qe&63}}return Z[fe]=0,fe-Pe}function ht(O,Z,fe){return yt(O,o(),Z,fe)}var Qe,kt,Cs,Kt,or,Pn,ir,es,Ts;C&&(Qe=d.buffer);function Rt(O){Qe=O,d.HEAP8=kt=new Int8Array(O),d.HEAP16=Kt=new Int16Array(O),d.HEAP32=Pn=new Int32Array(O),d.HEAPU8=Cs=new Uint8Array(O),d.HEAPU16=or=new Uint16Array(O),d.HEAPU32=ir=new Uint32Array(O),d.HEAPF32=es=new Float32Array(O),d.HEAPF64=Ts=new Float64Array(O)}var ms=d.INITIAL_MEMORY||16777216;if(C)Q=d.wasmMemory,Qe=d.buffer;else if(d.wasmMemory)Q=d.wasmMemory;else if(Q=new WebAssembly.Memory({initial:ms/65536,maximum:32768,shared:!0}),!(Q.buffer instanceof SharedArrayBuffer))throw K("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"),k&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");Q&&(Qe=Q.buffer),ms=Qe.byteLength,Rt(Qe);var Un,Hr=[],Wa=[],lr=[],_d=!1;function ur(){return Ae}function Nu(){if(d.preRun)for(typeof d.preRun=="function"&&(d.preRun=[d.preRun]);d.preRun.length;)c1(d.preRun.shift());Fd(Hr)}function Sn(){_d=!0,!C&&Fd(Wa)}function Qh(){if(!C){if(d.postRun)for(typeof d.postRun=="function"&&(d.postRun=[d.postRun]);d.postRun.length;)H4(d.postRun.shift());Fd(lr)}}function c1(O){Hr.unshift(O)}function d1(O){Wa.unshift(O)}function H4(O){lr.unshift(O)}var Va=0,Eu=null,da=null;function j4(O){Va++,d.monitorRunDependencies&&d.monitorRunDependencies(Va)}function q4(O){if(Va--,d.monitorRunDependencies&&d.monitorRunDependencies(Va),Va==0&&(Eu!==null&&(clearInterval(Eu),Eu=null),da)){var Z=da;da=null,Z()}}function Ru(O){C?postMessage({cmd:"onAbort",arg:O}):d.onAbort&&d.onAbort(O),O="Aborted("+O+")",K(O),Se=!0,Fe=1,O+=". Build with -sASSERTIONS for more info.";var Z=new WebAssembly.RuntimeError(O);throw f(Z),Z}var p1="data:application/octet-stream;base64,";function ef(O){return O.startsWith(p1)}function Dd(O){return O.startsWith("file://")}var ts;ts="tfjs-backend-wasm-threaded-simd.wasm",ef(ts)||(ts=R(ts));function tf(O){try{if(O==ts&&oe)return new Uint8Array(oe);if($)return $(O);throw"both async and sync fetching of the wasm failed"}catch(Z){Ru(Z)}}function h1(){if(!oe&&(b||w)){if(typeof fetch=="function"&&!Dd(ts))return fetch(ts,{credentials:"same-origin"}).then(function(O){if(!O.ok)throw"failed to load wasm binary file at '"+ts+"'";return O.arrayBuffer()}).catch(function(){return tf(ts)});if(E)return new Promise(function(O,Z){E(ts,function(fe){O(new Uint8Array(fe))},Z)})}return Promise.resolve().then(function(){return tf(ts)})}function f1(){var O={env:ff,wasi_snapshot_preview1:ff};function Z(Ve,qe){var sn=Ve.exports;if(d.asm=sn,S1(d.asm._emscripten_tls_init),Un=d.asm.__indirect_function_table,d1(d.asm.__wasm_call_ctors),Ie=qe,!C){var Xs=je.unusedWorkers.length;je.unusedWorkers.forEach(function(ha){je.loadWasmModuleToWorker(ha,function(){--Xs||q4("wasm-instantiate")})})}}C||j4("wasm-instantiate");function fe(Ve){Z(Ve.instance,Ve.module)}function xe(Ve){return h1().then(function(qe){return WebAssembly.instantiate(qe,O)}).then(function(qe){return qe}).then(Ve,function(qe){K("failed to asynchronously prepare wasm: "+qe),Ru(qe)})}function Pe(){return!oe&&typeof WebAssembly.instantiateStreaming=="function"&&!ef(ts)&&!Dd(ts)&&!k&&typeof fetch=="function"?fetch(ts,{credentials:"same-origin"}).then(function(Ve){var qe=WebAssembly.instantiateStreaming(Ve,O);return qe.then(fe,function(sn){return K("wasm streaming compile failed: "+sn),K("falling back to ArrayBuffer instantiation"),xe(fe)})}):xe(fe)}if(d.instantiateWasm)try{var lt=d.instantiateWasm(O,Z);return lt}catch(Ve){K("Module.instantiateWasm callback failed with error: "+Ve),f(Ve)}return Pe().catch(f),{}}var m1,X4,g1={};function Di(O){this.name="ExitStatus",this.message="Program terminated with exit("+O+")",this.status=O}function y1(O){var Z=je.pthreads[O];delete je.pthreads[O],Z.terminate(),jg(O),je.runningWorkers.splice(je.runningWorkers.indexOf(Z),1),Z.pthread_ptr=0}function A1(O){var Z=je.pthreads[O];Z.postMessage({cmd:"cancel"})}function $d(O){var Z=je.pthreads[O];$e(Z),je.returnWorkerToPool(Z)}function nf(O){var Z=je.getNewWorker();if(!Z)return 6;je.runningWorkers.push(Z),je.pthreads[O.pthread_ptr]=Z,Z.pthread_ptr=O.pthread_ptr;var fe={cmd:"run",start_routine:O.startRoutine,arg:O.arg,pthread_ptr:O.pthread_ptr};return Z.runPthread=()=>{fe.time=performance.now(),Z.postMessage(fe,O.transferList)},Z.loaded&&(Z.runPthread(),delete Z.runPthread),0}var sf={varargs:void 0,get:function(){sf.varargs+=4;var O=l()[sf.varargs-4>>2];return O},getStr:function(O){var Z=gt(O);return Z}};function Pd(O){if(C)return Ua(1,1,O);Fe=O,ur()||(je.terminateAllThreads(),d.onExit&&d.onExit(O),Se=!0),A(O,new Di(O))}function K4(O,Z){if(Fe=O,!Z&&C)throw af(O),"unwind";Pd(O)}var rf=K4;function x1(O){if(O instanceof Di||O=="unwind")return Fe;A(1,O)}var je={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init:function(){C?je.initWorker():je.initMainThread()},initMainThread:function(){for(var O=8;O--;)je.allocateUnusedWorker()},initWorker:function(){Ae=!1},setExitStatus:function(O){Fe=O},terminateAllThreads:function(){for(var O of Object.values(je.pthreads))je.returnWorkerToPool(O);for(var O of je.unusedWorkers)O.terminate();je.unusedWorkers=[]},returnWorkerToPool:function(O){var Z=O.pthread_ptr;delete je.pthreads[Z],je.unusedWorkers.push(O),je.runningWorkers.splice(je.runningWorkers.indexOf(O),1),O.pthread_ptr=0,jg(Z)},receiveObjectTransfer:function(O){},threadInitTLS:function(){je.tlsInitFunctions.forEach(O=>O())},loadWasmModuleToWorker:function(O,Z){O.onmessage=fe=>{var xe=fe.data,Pe=xe.cmd;if(O.pthread_ptr&&(je.currentProxiedOperationCallerThread=O.pthread_ptr),xe.targetThread&&xe.targetThread!=bf()){var lt=je.pthreads[xe.targetThread];lt?lt.postMessage(xe,xe.transferList):K('Internal error! Worker sent a message "'+Pe+'" to target pthread '+xe.targetThread+", but that thread no longer exists!"),je.currentProxiedOperationCallerThread=void 0;return}Pe==="processProxyingQueue"?Od(xe.queue):Pe==="spawnThread"?nf(xe):Pe==="cleanupThread"?$d(xe.thread):Pe==="killThread"?y1(xe.thread):Pe==="cancelThread"?A1(xe.thread):Pe==="loaded"?(O.loaded=!0,Z&&Z(O),O.runPthread&&(O.runPthread(),delete O.runPthread)):Pe==="print"?q("Thread "+xe.threadId+": "+xe.text):Pe==="printErr"?K("Thread "+xe.threadId+": "+xe.text):Pe==="alert"?alert("Thread "+xe.threadId+": "+xe.text):xe.target==="setimmediate"?O.postMessage(xe):Pe==="onAbort"?d.onAbort&&d.onAbort(xe.arg):Pe&&K("worker sent an unknown command "+Pe),je.currentProxiedOperationCallerThread=void 0},O.onerror=fe=>{var xe="worker sent an error!";throw K(xe+" "+fe.filename+":"+fe.lineno+": "+fe.message),fe},k&&(O.on("message",function(fe){O.onmessage({data:fe})}),O.on("error",function(fe){O.onerror(fe)}),O.on("detachedExit",function(){})),O.postMessage({cmd:"load",urlOrBlob:d.mainScriptUrlOrBlob||s,wasmMemory:Q,wasmModule:Ie})},allocateUnusedWorker:function(){var O=R("tfjs-backend-wasm-threaded-simd.worker.js");je.unusedWorkers.push(new Worker(O))},getNewWorker:function(){return je.unusedWorkers.length==0&&(je.allocateUnusedWorker(),je.loadWasmModuleToWorker(je.unusedWorkers[0])),je.unusedWorkers.pop()}};d.PThread=je;function Fd(O){for(;O.length>0;)O.shift()(d)}function b1(O){var Z=qg(),fe=O();return vf(Z),fe}function Z4(O){return O}function Y4(O){var Z=/\b_Z[\w\d_]+/g;return O.replace(Z,function(fe){var xe=fe;return fe===xe?fe:xe+" ["+fe+"]"})}function v1(){var O=bf(),Z=l()[O+44>>2],fe=l()[O+48>>2],xe=Z-fe;rv(Z,xe),vf(Z)}d.establishStackSpace=v1;function af(O){if(C)return Ua(2,0,O);try{rf(O)}catch(Z){x1(Z)}}var _u=[];function w1(O){var Z=_u[O];return Z||(O>=_u.length&&(_u.length=O+1),_u[O]=Z=Un.get(O)),Z}function k1(O,Z){var fe=w1(O)(Z);ur()?je.setExitStatus(fe):sv(fe)}d.invokeEntryPoint=k1;function J4(){var O=new Error;if(!O.stack){try{throw new Error}catch(Z){O=Z}if(!O.stack)return"(no stack trace available)"}return O.stack.toString()}function S1(O){je.tlsInitFunctions.push(O)}function I1(O,Z){a().set(O,Z)}function C1(O){ev(O,!w,1,!b),je.threadInitTLS()}function T1(O){C?postMessage({cmd:"cleanupThread",thread:O}):$d(O)}function of(O,Z,fe,xe){return C?Ua(3,1,O,Z,fe,xe):lf(O,Z,fe,xe)}function lf(O,Z,fe,xe){if(typeof SharedArrayBuffer=="undefined")return K("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var Pe=[],lt=0;if(C&&(Pe.length===0||lt))return of(O,Z,fe,xe);if(lt)return lt;var Ve={startRoutine:fe,pthread_ptr:O,arg:xe,transferList:Pe};return C?(Ve.cmd="spawnThread",postMessage(Ve,Pe),0):nf(Ve)}function N1(){return 2097152}var E1=!0;function R1(){return E1}function Od(O){Atomics.store(l(),O>>2,1),bf()&&nv(O),Atomics.compareExchange(l(),O>>2,1,0)}d.executeNotifiedProxyingQueue=Od;function _1(O,Z,fe,xe){if(O==Z)setTimeout(()=>Od(xe));else if(C)postMessage({targetThread:O,cmd:"processProxyingQueue",queue:xe});else{var Pe=je.pthreads[O];if(!Pe)return;Pe.postMessage({cmd:"processProxyingQueue",queue:xe})}return 1}function D1(O,Z,fe){return-1}function $1(){Ru("")}function $i(O){$i.shown||($i.shown={}),$i.shown[O]||($i.shown[O]=1,k&&(O="warning: "+O),K(O))}function P1(){k||w||$i("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function F1(){return Date.now()}function uf(){return 2147483648}function O1(){return uf()}var Du;k?Du=()=>{var O=process.hrtime();return O[0]*1e3+O[1]/1e6}:C?Du=()=>performance.now()-d.__performance_now_clock_drift:Du=()=>performance.now();function M1(O,Z,fe){o().copyWithin(O,Z,Z+fe)}function z1(){return k?S_().cpus().length:navigator.hardwareConcurrency}function Ua(O,Z){var fe=arguments.length-2,xe=arguments;return b1(()=>{for(var Pe=fe,lt=wf(Pe*8),Ve=lt>>3,qe=0;qe>3,Pe=0;Pe>>16),Rt(Q.buffer),1}catch(Z){}}function W1(O){var Z=o().length;if(O=O>>>0,O<=Z)return!1;var fe=uf();if(O>fe)return!1;let xe=(sn,Xs)=>sn+(Xs-sn%Xs)%Xs;for(var Pe=1;Pe<=4;Pe*=2){var lt=Z*(1+.2/Pe);lt=Math.min(lt,O+100663296);var Ve=Math.min(fe,xe(Math.max(O,lt),65536)),qe=B1(Ve);if(qe)return!0}return!1}function V1(){throw"unwind"}function cf(O){return C?Ua(4,1,O):52}function df(O,Z,fe,xe,Pe){return C?Ua(5,1,O,Z,fe,xe,Pe):70}var U1=[null,[],[]];function G1(O,Z){var fe=U1[O];Z===0||Z===10?((O===1?q:K)(mt(fe,0)),fe.length=0):fe.push(Z)}function pf(O,Z,fe,xe){if(C)return Ua(6,1,O,Z,fe,xe);for(var Pe=0,lt=0;lt>2],qe=u()[Z+4>>2];Z+=8;for(var sn=0;sn>2]=Pe,0}function hf(O){var Z=d["_"+O];return Z}function H1(O,Z,fe,xe,Pe){var lt={string:Ns=>{var Ou=0;if(Ns!=null&&Ns!==0){var iv=(Ns.length<<2)+1;Ou=wf(iv),ht(Ns,Ou,iv)}return Ou},array:Ns=>{var Ou=wf(Ns.length);return I1(Ns,Ou),Ou}};function Ve(Ns){return Z==="string"?gt(Ns):Z==="boolean"?Boolean(Ns):Ns}var qe=hf(O),sn=[],Xs=0;if(xe)for(var ha=0;haVe==="number"||Ve==="boolean"),lt=Z!=="string";return lt&&Pe&&!xe?hf(O):function(){return H1(O,Z,fe,arguments,xe)}}je.init();var q1=[null,Pd,af,of,cf,df,pf],ff={__emscripten_init_main_thread_js:C1,__emscripten_thread_cleanup:T1,__pthread_create_js:lf,_emscripten_default_pthread_stack_size:N1,_emscripten_get_now_is_monotonic:R1,_emscripten_notify_task_queue:_1,_emscripten_set_offscreencanvas_size:D1,abort:$1,emscripten_check_blocking_allowed:P1,emscripten_date_now:F1,emscripten_get_heap_max:O1,emscripten_get_now:Du,emscripten_memcpy_big:M1,emscripten_num_logical_cores:z1,emscripten_receive_on_main_thread_js:L1,emscripten_resize_heap:W1,emscripten_unwind_to_js_event_loop:V1,exit:rf,fd_close:cf,fd_seek:df,fd_write:pf,memory:Q||d.wasmMemory},Q4=f1(),X1=d.___wasm_call_ctors=function(){return(X1=d.___wasm_call_ctors=d.asm.__wasm_call_ctors).apply(null,arguments)},K1=d._init=function(){return(K1=d._init=d.asm.init).apply(null,arguments)},Z1=d._init_with_threads_count=function(){return(Z1=d._init_with_threads_count=d.asm.init_with_threads_count).apply(null,arguments)},Y1=d._get_threads_count=function(){return(Y1=d._get_threads_count=d.asm.get_threads_count).apply(null,arguments)},J1=d._register_tensor=function(){return(J1=d._register_tensor=d.asm.register_tensor).apply(null,arguments)},Q1=d._dispose_data=function(){return(Q1=d._dispose_data=d.asm.dispose_data).apply(null,arguments)},eg=d._dispose=function(){return(eg=d._dispose=d.asm.dispose).apply(null,arguments)},tg=d._Abs=function(){return(tg=d._Abs=d.asm.Abs).apply(null,arguments)},ng=d._Add=function(){return(ng=d._Add=d.asm.Add).apply(null,arguments)},sg=d._AddN=function(){return(sg=d._AddN=d.asm.AddN).apply(null,arguments)},rg=d._All=function(){return(rg=d._All=d.asm.All).apply(null,arguments)},ag=d._Any=function(){return(ag=d._Any=d.asm.Any).apply(null,arguments)},og=d._ArgMax=function(){return(og=d._ArgMax=d.asm.ArgMax).apply(null,arguments)},ig=d._AvgPool=function(){return(ig=d._AvgPool=d.asm.AvgPool).apply(null,arguments)},lg=d._BatchMatMul=function(){return(lg=d._BatchMatMul=d.asm.BatchMatMul).apply(null,arguments)},ug=d._Ceil=function(){return(ug=d._Ceil=d.asm.Ceil).apply(null,arguments)},cg=d._ClipByValue=function(){return(cg=d._ClipByValue=d.asm.ClipByValue).apply(null,arguments)},dg=d._Conv2D=function(){return(dg=d._Conv2D=d.asm.Conv2D).apply(null,arguments)},pg=d._Conv2DBackpropInput=function(){return(pg=d._Conv2DBackpropInput=d.asm.Conv2DBackpropInput).apply(null,arguments)},hg=d._Cos=function(){return(hg=d._Cos=d.asm.Cos).apply(null,arguments)},fg=d._Cosh=function(){return(fg=d._Cosh=d.asm.Cosh).apply(null,arguments)},mg=d._CropAndResize=function(){return(mg=d._CropAndResize=d.asm.CropAndResize).apply(null,arguments)},gg=d._Cumprod=function(){return(gg=d._Cumprod=d.asm.Cumprod).apply(null,arguments)},yg=d._Cumsum=function(){return(yg=d._Cumsum=d.asm.Cumsum).apply(null,arguments)},Ag=d._DepthToSpace=function(){return(Ag=d._DepthToSpace=d.asm.DepthToSpace).apply(null,arguments)},xg=d._DepthwiseConv2dNative=function(){return(xg=d._DepthwiseConv2dNative=d.asm.DepthwiseConv2dNative).apply(null,arguments)},bg=d._Elu=function(){return(bg=d._Elu=d.asm.Elu).apply(null,arguments)},vg=d._Equal=function(){return(vg=d._Equal=d.asm.Equal).apply(null,arguments)},wg=d._Exp=function(){return(wg=d._Exp=d.asm.Exp).apply(null,arguments)},kg=d._FlipLeftRight=function(){return(kg=d._FlipLeftRight=d.asm.FlipLeftRight).apply(null,arguments)},Sg=d._Floor=function(){return(Sg=d._Floor=d.asm.Floor).apply(null,arguments)},Ig=d._FloorDiv=function(){return(Ig=d._FloorDiv=d.asm.FloorDiv).apply(null,arguments)},Cg=d._FusedBatchNorm=function(){return(Cg=d._FusedBatchNorm=d.asm.FusedBatchNorm).apply(null,arguments)},Tg=d._FusedConv2D=function(){return(Tg=d._FusedConv2D=d.asm.FusedConv2D).apply(null,arguments)},Ng=d._FusedDepthwiseConv2D=function(){return(Ng=d._FusedDepthwiseConv2D=d.asm.FusedDepthwiseConv2D).apply(null,arguments)},Eg=d._Gather=function(){return(Eg=d._Gather=d.asm.Gather).apply(null,arguments)},Rg=d._GatherNd=function(){return(Rg=d._GatherNd=d.asm.GatherNd).apply(null,arguments)},_g=d._Greater=function(){return(_g=d._Greater=d.asm.Greater).apply(null,arguments)},Dg=d._GreaterEqual=function(){return(Dg=d._GreaterEqual=d.asm.GreaterEqual).apply(null,arguments)},$g=d._LeakyRelu=function(){return($g=d._LeakyRelu=d.asm.LeakyRelu).apply(null,arguments)},Pg=d._Less=function(){return(Pg=d._Less=d.asm.Less).apply(null,arguments)},Fg=d._LessEqual=function(){return(Fg=d._LessEqual=d.asm.LessEqual).apply(null,arguments)},Og=d._Log=function(){return(Og=d._Log=d.asm.Log).apply(null,arguments)},Mg=d._LogicalAnd=function(){return(Mg=d._LogicalAnd=d.asm.LogicalAnd).apply(null,arguments)},zg=d._LogicalNot=function(){return(zg=d._LogicalNot=d.asm.LogicalNot).apply(null,arguments)},Lg=d._LogicalOr=function(){return(Lg=d._LogicalOr=d.asm.LogicalOr).apply(null,arguments)},Bg=d._LogicalXor=function(){return(Bg=d._LogicalXor=d.asm.LogicalXor).apply(null,arguments)},Wg=d._Max=function(){return(Wg=d._Max=d.asm.Max).apply(null,arguments)},mf=d._MaxPool=function(){return(mf=d._MaxPool=d.asm.MaxPool).apply(null,arguments)},gf=d._Maximum=function(){return(gf=d._Maximum=d.asm.Maximum).apply(null,arguments)},zd=d._Mean=function(){return(zd=d._Mean=d.asm.Mean).apply(null,arguments)},Vg=d._Min=function(){return(Vg=d._Min=d.asm.Min).apply(null,arguments)},Ug=d._Minimum=function(){return(Ug=d._Minimum=d.asm.Minimum).apply(null,arguments)},$u=d._MirrorPad=function(){return($u=d._MirrorPad=d.asm.MirrorPad).apply(null,arguments)},yf=d._Multiply=function(){return(yf=d._Multiply=d.asm.Multiply).apply(null,arguments)},Pu=d._Neg=function(){return(Pu=d._Neg=d.asm.Neg).apply(null,arguments)},Fu=d._NonMaxSuppressionV3=function(){return(Fu=d._NonMaxSuppressionV3=d.asm.NonMaxSuppressionV3).apply(null,arguments)},Gg=d._NonMaxSuppressionV4=function(){return(Gg=d._NonMaxSuppressionV4=d.asm.NonMaxSuppressionV4).apply(null,arguments)},te=d._NonMaxSuppressionV5=function(){return(te=d._NonMaxSuppressionV5=d.asm.NonMaxSuppressionV5).apply(null,arguments)},he=d._NotEqual=function(){return(he=d._NotEqual=d.asm.NotEqual).apply(null,arguments)},Re=d._OneHot=function(){return(Re=d._OneHot=d.asm.OneHot).apply(null,arguments)},ot=d._PadV2=function(){return(ot=d._PadV2=d.asm.PadV2).apply(null,arguments)},$t=d._Pow=function(){return($t=d._Pow=d.asm.Pow).apply(null,arguments)},Pt=d._Prelu=function(){return(Pt=d._Prelu=d.asm.Prelu).apply(null,arguments)},at=d._Prod=function(){return(at=d._Prod=d.asm.Prod).apply(null,arguments)},nt=d._RealDiv=function(){return(nt=d._RealDiv=d.asm.RealDiv).apply(null,arguments)},nn=d._Relu=function(){return(nn=d._Relu=d.asm.Relu).apply(null,arguments)},qs=d._Relu6=function(){return(qs=d._Relu6=d.asm.Relu6).apply(null,arguments)},pa=d._ResizeBilinear=function(){return(pa=d._ResizeBilinear=d.asm.ResizeBilinear).apply(null,arguments)},Af=d._ResizeNearestNeighbor=function(){return(Af=d._ResizeNearestNeighbor=d.asm.ResizeNearestNeighbor).apply(null,arguments)},Ld=d._Reverse=function(){return(Ld=d._Reverse=d.asm.Reverse).apply(null,arguments)},Hg=d._RotateWithOffset=function(){return(Hg=d._RotateWithOffset=d.asm.RotateWithOffset).apply(null,arguments)},ns=d._Round=function(){return(ns=d._Round=d.asm.Round).apply(null,arguments)},Ga=d._Rsqrt=function(){return(Ga=d._Rsqrt=d.asm.Rsqrt).apply(null,arguments)},xf=d._ScatterNd=function(){return(xf=d._ScatterNd=d.asm.ScatterNd).apply(null,arguments)},vR=d._SelectV2=function(){return(vR=d._SelectV2=d.asm.SelectV2).apply(null,arguments)},wR=d._Sigmoid=function(){return(wR=d._Sigmoid=d.asm.Sigmoid).apply(null,arguments)},kR=d._Sin=function(){return(kR=d._Sin=d.asm.Sin).apply(null,arguments)},SR=d._Softmax=function(){return(SR=d._Softmax=d.asm.Softmax).apply(null,arguments)},IR=d._SparseFillEmptyRows=function(){return(IR=d._SparseFillEmptyRows=d.asm.SparseFillEmptyRows).apply(null,arguments)},CR=d._SparseReshape=function(){return(CR=d._SparseReshape=d.asm.SparseReshape).apply(null,arguments)},TR=d._SparseSegmentReduction=function(){return(TR=d._SparseSegmentReduction=d.asm.SparseSegmentReduction).apply(null,arguments)},NR=d._Sqrt=function(){return(NR=d._Sqrt=d.asm.Sqrt).apply(null,arguments)},ER=d._Square=function(){return(ER=d._Square=d.asm.Square).apply(null,arguments)},RR=d._SquaredDifference=function(){return(RR=d._SquaredDifference=d.asm.SquaredDifference).apply(null,arguments)},_R=d._Step=function(){return(_R=d._Step=d.asm.Step).apply(null,arguments)},DR=d._StridedSlice=function(){return(DR=d._StridedSlice=d.asm.StridedSlice).apply(null,arguments)},$R=d._Sub=function(){return($R=d._Sub=d.asm.Sub).apply(null,arguments)},PR=d._Sum=function(){return(PR=d._Sum=d.asm.Sum).apply(null,arguments)},FR=d._Tan=function(){return(FR=d._Tan=d.asm.Tan).apply(null,arguments)},OR=d._Tanh=function(){return(OR=d._Tanh=d.asm.Tanh).apply(null,arguments)},MR=d._Tile=function(){return(MR=d._Tile=d.asm.Tile).apply(null,arguments)},zR=d._TopK=function(){return(zR=d._TopK=d.asm.TopK).apply(null,arguments)},LR=d._Transform=function(){return(LR=d._Transform=d.asm.Transform).apply(null,arguments)},BR=d._Transpose=function(){return(BR=d._Transpose=d.asm.Transpose).apply(null,arguments)},WR=d.__FusedMatMul=function(){return(WR=d.__FusedMatMul=d.asm._FusedMatMul).apply(null,arguments)},VR=d._malloc=function(){return(VR=d._malloc=d.asm.malloc).apply(null,arguments)},UR=d._free=function(){return(UR=d._free=d.asm.free).apply(null,arguments)},GR=d.__emscripten_tls_init=function(){return(GR=d.__emscripten_tls_init=d.asm._emscripten_tls_init).apply(null,arguments)},bf=d._pthread_self=function(){return(bf=d._pthread_self=d.asm.pthread_self).apply(null,arguments)},HR=d.___errno_location=function(){return(HR=d.___errno_location=d.asm.__errno_location).apply(null,arguments)},ev=d.__emscripten_thread_init=function(){return(ev=d.__emscripten_thread_init=d.asm._emscripten_thread_init).apply(null,arguments)},jR=d.__emscripten_thread_crashed=function(){return(jR=d.__emscripten_thread_crashed=d.asm._emscripten_thread_crashed).apply(null,arguments)},qR=d._emscripten_main_thread_process_queued_calls=function(){return(qR=d._emscripten_main_thread_process_queued_calls=d.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},XR=d._emscripten_main_browser_thread_id=function(){return(XR=d._emscripten_main_browser_thread_id=d.asm.emscripten_main_browser_thread_id).apply(null,arguments)},tv=d._emscripten_run_in_main_runtime_thread_js=function(){return(tv=d._emscripten_run_in_main_runtime_thread_js=d.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)},KR=d._emscripten_dispatch_to_thread_=function(){return(KR=d._emscripten_dispatch_to_thread_=d.asm.emscripten_dispatch_to_thread_).apply(null,arguments)},nv=d.__emscripten_proxy_execute_task_queue=function(){return(nv=d.__emscripten_proxy_execute_task_queue=d.asm._emscripten_proxy_execute_task_queue).apply(null,arguments)},jg=d.__emscripten_thread_free_data=function(){return(jg=d.__emscripten_thread_free_data=d.asm._emscripten_thread_free_data).apply(null,arguments)},sv=d.__emscripten_thread_exit=function(){return(sv=d.__emscripten_thread_exit=d.asm._emscripten_thread_exit).apply(null,arguments)},rv=d._emscripten_stack_set_limits=function(){return(rv=d._emscripten_stack_set_limits=d.asm.emscripten_stack_set_limits).apply(null,arguments)},qg=d.stackSave=function(){return(qg=d.stackSave=d.asm.stackSave).apply(null,arguments)},vf=d.stackRestore=function(){return(vf=d.stackRestore=d.asm.stackRestore).apply(null,arguments)},wf=d.stackAlloc=function(){return(wf=d.stackAlloc=d.asm.stackAlloc).apply(null,arguments)},ZR=d.dynCall_iijjiiii=function(){return(ZR=d.dynCall_iijjiiii=d.asm.dynCall_iijjiiii).apply(null,arguments)},YR=d.dynCall_jiji=function(){return(YR=d.dynCall_jiji=d.asm.dynCall_jiji).apply(null,arguments)};d.keepRuntimeAlive=ur,d.wasmMemory=Q,d.cwrap=j1,d.ExitStatus=Di,d.PThread=je;var kf;da=function O(){kf||av(),kf||(da=O)};function av(O){if(O=O||y,Va>0)return;if(C){h(d),Sn(),postMessage({cmd:"loaded"});return}if(Nu(),Va>0)return;function Z(){kf||(kf=!0,d.calledRun=!0,!Se&&(Sn(),h(d),d.onRuntimeInitialized&&d.onRuntimeInitialized(),Qh()))}d.setStatus?(d.setStatus("Running..."),setTimeout(function(){setTimeout(function(){d.setStatus("")},1),Z()},1)):Z()}if(d.preInit)for(typeof d.preInit=="function"&&(d.preInit=[d.preInit]);d.preInit.length>0;)d.preInit.pop()();av();var Sf;m&&(Sf={uncaughtException:process.listeners("uncaughtException").filter(function(O){return!m.uncaughtException.indexOf(O)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(O){return!m.unhandledRejection.indexOf(O)>-1})});var If;if(typeof WasmBackendModule!="undefined")If=WasmBackendModule;else if(typeof r!="undefined")If=r;else throw new Error("Could not find wasm module in post.js");if(Sf){var JR=If._dispose;If._dispose=function(){JR(),Sf.uncaughtException.forEach(function(O){process.removeListener("uncaughtException",O)}),Sf.unhandledRejection.forEach(function(O){process.removeListener("unhandledRejection",O)})}}return 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)}}),C_=un({"node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.21.0_aipmo6igpprgzt4umpaa3m6sn4/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm-threaded-simd.worker.js"(e,t){t.exports.wasmWorkerContents=`"use strict";var Module={};var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads");var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",data=>onmessage({data:data}));var fs=require("fs");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,"utf8"))},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}var initializedJS=false;var pendingNotifiedProxyingQueues=[];function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+" ");return}console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=(info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports};self.onunhandledrejection=e=>{throw e.reason??e};self.onmessage=e=>{try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob=="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module).then(function(instance){Module=instance})}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.pthread_ptr,0,0,1);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInitTLS();if(!initializedJS){pendingNotifiedProxyingQueues.forEach(queue=>{Module["executeNotifiedProxyingQueue"](queue)});pendingNotifiedProxyingQueues=[];initializedJS=true}try{Module["invokeEntryPoint"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["__emscripten_thread_exit"](ex.status)}}else{throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["__emscripten_thread_exit"](-1)}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processProxyingQueue"){if(initializedJS){Module["executeNotifiedProxyingQueue"](e.data.queue)}else{pendingNotifiedProxyingQueues.push(e.data.queue)}}else if(e.data.cmd){err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){if(Module["__emscripten_thread_crashed"]){Module["__emscripten_thread_crashed"]()}throw ex}};`}}),T_=un({"node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.21.0_aipmo6igpprgzt4umpaa3m6sn4/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js"(e,t){var n=(()=>{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(te,he){o=te,i=he});var l;typeof process!="undefined"&&process.listeners&&(l={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var u=Object.assign({},a),c=[],p="./this.program",d=(te,he)=>{throw he},h=typeof window=="object",f=typeof importScripts=="function",m=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="";function y(te){return a.locateFile?a.locateFile(te,g):g+te}var x,A,b,w;function k(te){if(te instanceof Eu)return;D("exiting due to exception: "+te)}if(m){f?g=Jf().dirname(g)+"/":g=__dirname+"/";var C,N;typeof tw=="function"&&(C=gy(),N=Jf()),x=(te,he)=>(te=N.normalize(te),C.readFileSync(te,he?void 0:"utf8")),b=te=>{var he=x(te,!0);return he.buffer||(he=new Uint8Array(he)),he},A=(te,he,Re)=>{te=N.normalize(te),C.readFile(te,function(ot,$t){ot?Re(ot):he($t.buffer)})},process.argv.length>1&&(p=process.argv[1].replace(/\\/g,"/")),c=process.argv.slice(2),process.on("uncaughtException",function(te){if(!(te instanceof Eu))throw te}),process.on("unhandledRejection",function(te){throw te}),d=(te,he)=>{if(Cs())throw process.exitCode=te,he;k(he),process.exit(te)},a.inspect=function(){return"[Emscripten Module object]"}}else(h||f)&&(f?g=self.location.href:typeof document!="undefined"&&document.currentScript&&(g=document.currentScript.src),s&&(g=s),g.indexOf("blob:")!==0?g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1):g="",x=te=>{var he=new XMLHttpRequest;return he.open("GET",te,!1),he.send(null),he.responseText},f&&(b=te=>{var he=new XMLHttpRequest;return he.open("GET",te,!1),he.responseType="arraybuffer",he.send(null),new Uint8Array(he.response)}),A=(te,he,Re)=>{var ot=new XMLHttpRequest;ot.open("GET",te,!0),ot.responseType="arraybuffer",ot.onload=()=>{if(ot.status==200||ot.status==0&&ot.response){he(ot.response);return}Re()},ot.onerror=Re,ot.send(null)},w=te=>document.title=te);var R=a.print||console.log.bind(console),D=a.printErr||console.warn.bind(console);Object.assign(a,u),u=null,a.arguments&&(c=a.arguments),a.thisProgram&&(p=a.thisProgram),a.quit&&(d=a.quit);var E=4,$;a.wasmBinary&&($=a.wasmBinary);var S=a.noExitRuntime||!0;typeof WebAssembly!="object"&&lr("no native wasm support detected");var F,z=!1,V;function j(te,he){te||lr(he)}var G=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function q(te,he,Re){for(var ot=he+Re,$t=he;te[$t]&&!($t>=ot);)++$t;if($t-he>16&&te.buffer&&G)return G.decode(te.subarray(he,$t));for(var Pt="";he<$t;){var at=te[he++];if(!(at&128)){Pt+=String.fromCharCode(at);continue}var nt=te[he++]&63;if((at&224)==192){Pt+=String.fromCharCode((at&31)<<6|nt);continue}var nn=te[he++]&63;if((at&240)==224?at=(at&15)<<12|nt<<6|nn:at=(at&7)<<18|nt<<12|nn<<6|te[he++]&63,at<65536)Pt+=String.fromCharCode(at);else{var qs=at-65536;Pt+=String.fromCharCode(55296|qs>>10,56320|qs&1023)}}return Pt}function K(te,he){return te?q(oe,te,he):""}function ne(te,he,Re,ot){if(!(ot>0))return 0;for(var $t=Re,Pt=Re+ot-1,at=0;at=55296&&nt<=57343){var nn=te.charCodeAt(++at);nt=65536+((nt&1023)<<10)|nn&1023}if(nt<=127){if(Re>=Pt)break;he[Re++]=nt}else if(nt<=2047){if(Re+1>=Pt)break;he[Re++]=192|nt>>6,he[Re++]=128|nt&63}else if(nt<=65535){if(Re+2>=Pt)break;he[Re++]=224|nt>>12,he[Re++]=128|nt>>6&63,he[Re++]=128|nt&63}else{if(Re+3>=Pt)break;he[Re++]=240|nt>>18,he[Re++]=128|nt>>12&63,he[Re++]=128|nt>>6&63,he[Re++]=128|nt&63}}return he[Re]=0,Re-$t}function ae(te,he,Re){return ne(te,oe,he,Re)}var re,ue,oe,Ae,Q,Ie,Se,Fe,$e;function rt(te){re=te,a.HEAP8=ue=new Int8Array(te),a.HEAP16=Ae=new Int16Array(te),a.HEAP32=Ie=new Int32Array(te),a.HEAPU8=oe=new Uint8Array(te),a.HEAPU16=Q=new Uint16Array(te),a.HEAPU32=Se=new Uint32Array(te),a.HEAPF32=Fe=new Float32Array(te),a.HEAPF64=$e=new Float64Array(te)}var mt=a.INITIAL_MEMORY||16777216,gt,yt=[],ht=[],Qe=[],kt=!1;function Cs(){return S}function Kt(){if(a.preRun)for(typeof a.preRun=="function"&&(a.preRun=[a.preRun]);a.preRun.length;)ir(a.preRun.shift());da(yt)}function or(){kt=!0,da(ht)}function Pn(){if(a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;)Ts(a.postRun.shift());da(Qe)}function ir(te){yt.unshift(te)}function es(te){ht.unshift(te)}function Ts(te){Qe.unshift(te)}var Rt=0,ms=null,Un=null;function Hr(te){Rt++,a.monitorRunDependencies&&a.monitorRunDependencies(Rt)}function Wa(te){if(Rt--,a.monitorRunDependencies&&a.monitorRunDependencies(Rt),Rt==0&&(ms!==null&&(clearInterval(ms),ms=null),Un)){var he=Un;Un=null,he()}}function lr(te){a.onAbort&&a.onAbort(te),te="Aborted("+te+")",D(te),z=!0,V=1,te+=". Build with -sASSERTIONS for more info.";var he=new WebAssembly.RuntimeError(te);throw i(he),he}var _d="data:application/octet-stream;base64,";function ur(te){return te.startsWith(_d)}function Nu(te){return te.startsWith("file://")}var Sn;Sn="tfjs-backend-wasm.wasm",ur(Sn)||(Sn=y(Sn));function Qh(te){try{if(te==Sn&&$)return new Uint8Array($);if(b)return b(te);throw"both async and sync fetching of the wasm failed"}catch(he){lr(he)}}function c1(){if(!$&&(h||f)){if(typeof fetch=="function"&&!Nu(Sn))return fetch(Sn,{credentials:"same-origin"}).then(function(te){if(!te.ok)throw"failed to load wasm binary file at '"+Sn+"'";return te.arrayBuffer()}).catch(function(){return Qh(Sn)});if(A)return new Promise(function(te,he){A(Sn,function(Re){te(new Uint8Array(Re))},he)})}return Promise.resolve().then(function(){return Qh(Sn)})}function d1(){var te={env:Pd,wasi_snapshot_preview1:Pd};function he(at,nt){var nn=at.exports;a.asm=nn,F=a.asm.memory,rt(F.buffer),gt=a.asm.__indirect_function_table,es(a.asm.__wasm_call_ctors),Wa("wasm-instantiate")}Hr("wasm-instantiate");function Re(at){he(at.instance)}function ot(at){return c1().then(function(nt){return WebAssembly.instantiate(nt,te)}).then(function(nt){return nt}).then(at,function(nt){D("failed to asynchronously prepare wasm: "+nt),lr(nt)})}function $t(){return!$&&typeof WebAssembly.instantiateStreaming=="function"&&!ur(Sn)&&!Nu(Sn)&&!m&&typeof fetch=="function"?fetch(Sn,{credentials:"same-origin"}).then(function(at){var nt=WebAssembly.instantiateStreaming(at,te);return nt.then(Re,function(nn){return D("wasm streaming compile failed: "+nn),D("falling back to ArrayBuffer instantiation"),ot(Re)})}):ot(Re)}if(a.instantiateWasm)try{var Pt=a.instantiateWasm(te,he);return Pt}catch(at){D("Module.instantiateWasm callback failed with error: "+at),i(at)}return $t().catch(i),{}}var H4,Va;function Eu(te){this.name="ExitStatus",this.message="Program terminated with exit("+te+")",this.status=te}function da(te){for(;te.length>0;)te.shift()(a)}function j4(te){return te}function q4(te){var he=/\b_Z[\w\d_]+/g;return te.replace(he,function(Re){var ot=Re;return Re===ot?Re:ot+" ["+Re+"]"})}function Ru(){var te=new Error;if(!te.stack){try{throw new Error}catch(he){te=he}if(!te.stack)return"(no stack trace available)"}return te.stack.toString()}function p1(te,he){ue.set(te,he)}function ef(){lr("")}function Dd(){return 2147483648}function ts(){return Dd()}function tf(te,he,Re){oe.copyWithin(te,he,he+Re)}function h1(te){try{return F.grow(te-re.byteLength+65535>>>16),rt(F.buffer),1}catch(he){}}function f1(te){var he=oe.length;te=te>>>0;var Re=Dd();if(te>Re)return!1;let ot=(nn,qs)=>nn+(qs-nn%qs)%qs;for(var $t=1;$t<=4;$t*=2){var Pt=he*(1+.2/$t);Pt=Math.min(Pt,te+100663296);var at=Math.min(Re,ot(Math.max(te,Pt),65536)),nt=h1(at);if(nt)return!0}return!1}var m1={varargs:void 0,get:function(){m1.varargs+=4;var te=Ie[m1.varargs-4>>2];return te},getStr:function(te){var he=K(te);return he}};function X4(te){return 52}function g1(te,he,Re,ot,$t){return 70}var Di=[null,[],[]];function y1(te,he){var Re=Di[te];he===0||he===10?((te===1?R:D)(q(Re,0)),Re.length=0):Re.push(he)}function A1(te,he,Re,ot){for(var $t=0,Pt=0;Pt>2],nt=Se[he+4>>2];he+=8;for(var nn=0;nn>2]=$t,0}function $d(te){var he=a["_"+te];return he}function nf(te,he,Re,ot,$t){var Pt={string:ns=>{var Ga=0;if(ns!=null&&ns!==0){var xf=(ns.length<<2)+1;Ga=zd(xf),ae(ns,Ga,xf)}return Ga},array:ns=>{var Ga=zd(ns.length);return p1(ns,Ga),Ga}};function at(ns){return he==="string"?K(ns):he==="boolean"?Boolean(ns):ns}var nt=$d(te),nn=[],qs=0;if(ot)for(var pa=0;paat==="number"||at==="boolean"),Pt=he!=="string";return Pt&&$t&&!ot?$d(te):function(){return nf(te,he,Re,arguments,ot)}}var Pd={abort:ef,emscripten_get_heap_max:ts,emscripten_memcpy_big:tf,emscripten_resize_heap:f1,fd_close:X4,fd_seek:g1,fd_write:A1},K4=d1(),rf=a.___wasm_call_ctors=function(){return(rf=a.___wasm_call_ctors=a.asm.__wasm_call_ctors).apply(null,arguments)},x1=a._init=function(){return(x1=a._init=a.asm.init).apply(null,arguments)},je=a._init_with_threads_count=function(){return(je=a._init_with_threads_count=a.asm.init_with_threads_count).apply(null,arguments)},Fd=a._get_threads_count=function(){return(Fd=a._get_threads_count=a.asm.get_threads_count).apply(null,arguments)},b1=a._register_tensor=function(){return(b1=a._register_tensor=a.asm.register_tensor).apply(null,arguments)},Z4=a._dispose_data=function(){return(Z4=a._dispose_data=a.asm.dispose_data).apply(null,arguments)},Y4=a._dispose=function(){return(Y4=a._dispose=a.asm.dispose).apply(null,arguments)},v1=a._Abs=function(){return(v1=a._Abs=a.asm.Abs).apply(null,arguments)},af=a._Add=function(){return(af=a._Add=a.asm.Add).apply(null,arguments)},_u=a._AddN=function(){return(_u=a._AddN=a.asm.AddN).apply(null,arguments)},w1=a._All=function(){return(w1=a._All=a.asm.All).apply(null,arguments)},k1=a._Any=function(){return(k1=a._Any=a.asm.Any).apply(null,arguments)},J4=a._ArgMax=function(){return(J4=a._ArgMax=a.asm.ArgMax).apply(null,arguments)},S1=a._AvgPool=function(){return(S1=a._AvgPool=a.asm.AvgPool).apply(null,arguments)},I1=a._BatchMatMul=function(){return(I1=a._BatchMatMul=a.asm.BatchMatMul).apply(null,arguments)},C1=a._Ceil=function(){return(C1=a._Ceil=a.asm.Ceil).apply(null,arguments)},T1=a._ClipByValue=function(){return(T1=a._ClipByValue=a.asm.ClipByValue).apply(null,arguments)},of=a._Conv2D=function(){return(of=a._Conv2D=a.asm.Conv2D).apply(null,arguments)},lf=a._Conv2DBackpropInput=function(){return(lf=a._Conv2DBackpropInput=a.asm.Conv2DBackpropInput).apply(null,arguments)},N1=a._Cos=function(){return(N1=a._Cos=a.asm.Cos).apply(null,arguments)},E1=a._Cosh=function(){return(E1=a._Cosh=a.asm.Cosh).apply(null,arguments)},R1=a._CropAndResize=function(){return(R1=a._CropAndResize=a.asm.CropAndResize).apply(null,arguments)},Od=a._Cumprod=function(){return(Od=a._Cumprod=a.asm.Cumprod).apply(null,arguments)},_1=a._Cumsum=function(){return(_1=a._Cumsum=a.asm.Cumsum).apply(null,arguments)},D1=a._DepthToSpace=function(){return(D1=a._DepthToSpace=a.asm.DepthToSpace).apply(null,arguments)},$1=a._DepthwiseConv2dNative=function(){return($1=a._DepthwiseConv2dNative=a.asm.DepthwiseConv2dNative).apply(null,arguments)},$i=a._Elu=function(){return($i=a._Elu=a.asm.Elu).apply(null,arguments)},P1=a._Equal=function(){return(P1=a._Equal=a.asm.Equal).apply(null,arguments)},F1=a._Exp=function(){return(F1=a._Exp=a.asm.Exp).apply(null,arguments)},uf=a._FlipLeftRight=function(){return(uf=a._FlipLeftRight=a.asm.FlipLeftRight).apply(null,arguments)},O1=a._Floor=function(){return(O1=a._Floor=a.asm.Floor).apply(null,arguments)},Du=a._FloorDiv=function(){return(Du=a._FloorDiv=a.asm.FloorDiv).apply(null,arguments)},M1=a._FusedBatchNorm=function(){return(M1=a._FusedBatchNorm=a.asm.FusedBatchNorm).apply(null,arguments)},z1=a._FusedConv2D=function(){return(z1=a._FusedConv2D=a.asm.FusedConv2D).apply(null,arguments)},Ua=a._FusedDepthwiseConv2D=function(){return(Ua=a._FusedDepthwiseConv2D=a.asm.FusedDepthwiseConv2D).apply(null,arguments)},Md=a._Gather=function(){return(Md=a._Gather=a.asm.Gather).apply(null,arguments)},L1=a._GatherNd=function(){return(L1=a._GatherNd=a.asm.GatherNd).apply(null,arguments)},B1=a._Greater=function(){return(B1=a._Greater=a.asm.Greater).apply(null,arguments)},W1=a._GreaterEqual=function(){return(W1=a._GreaterEqual=a.asm.GreaterEqual).apply(null,arguments)},V1=a._LeakyRelu=function(){return(V1=a._LeakyRelu=a.asm.LeakyRelu).apply(null,arguments)},cf=a._Less=function(){return(cf=a._Less=a.asm.Less).apply(null,arguments)},df=a._LessEqual=function(){return(df=a._LessEqual=a.asm.LessEqual).apply(null,arguments)},U1=a._Log=function(){return(U1=a._Log=a.asm.Log).apply(null,arguments)},G1=a._LogicalAnd=function(){return(G1=a._LogicalAnd=a.asm.LogicalAnd).apply(null,arguments)},pf=a._LogicalNot=function(){return(pf=a._LogicalNot=a.asm.LogicalNot).apply(null,arguments)},hf=a._LogicalOr=function(){return(hf=a._LogicalOr=a.asm.LogicalOr).apply(null,arguments)},H1=a._LogicalXor=function(){return(H1=a._LogicalXor=a.asm.LogicalXor).apply(null,arguments)},j1=a._Max=function(){return(j1=a._Max=a.asm.Max).apply(null,arguments)},q1=a._MaxPool=function(){return(q1=a._MaxPool=a.asm.MaxPool).apply(null,arguments)},ff=a._Maximum=function(){return(ff=a._Maximum=a.asm.Maximum).apply(null,arguments)},Q4=a._Mean=function(){return(Q4=a._Mean=a.asm.Mean).apply(null,arguments)},X1=a._Min=function(){return(X1=a._Min=a.asm.Min).apply(null,arguments)},K1=a._Minimum=function(){return(K1=a._Minimum=a.asm.Minimum).apply(null,arguments)},Z1=a._MirrorPad=function(){return(Z1=a._MirrorPad=a.asm.MirrorPad).apply(null,arguments)},Y1=a._Multiply=function(){return(Y1=a._Multiply=a.asm.Multiply).apply(null,arguments)},J1=a._Neg=function(){return(J1=a._Neg=a.asm.Neg).apply(null,arguments)},Q1=a._NonMaxSuppressionV3=function(){return(Q1=a._NonMaxSuppressionV3=a.asm.NonMaxSuppressionV3).apply(null,arguments)},eg=a._NonMaxSuppressionV4=function(){return(eg=a._NonMaxSuppressionV4=a.asm.NonMaxSuppressionV4).apply(null,arguments)},tg=a._NonMaxSuppressionV5=function(){return(tg=a._NonMaxSuppressionV5=a.asm.NonMaxSuppressionV5).apply(null,arguments)},ng=a._NotEqual=function(){return(ng=a._NotEqual=a.asm.NotEqual).apply(null,arguments)},sg=a._OneHot=function(){return(sg=a._OneHot=a.asm.OneHot).apply(null,arguments)},rg=a._PadV2=function(){return(rg=a._PadV2=a.asm.PadV2).apply(null,arguments)},ag=a._Pow=function(){return(ag=a._Pow=a.asm.Pow).apply(null,arguments)},og=a._Prelu=function(){return(og=a._Prelu=a.asm.Prelu).apply(null,arguments)},ig=a._Prod=function(){return(ig=a._Prod=a.asm.Prod).apply(null,arguments)},lg=a._RealDiv=function(){return(lg=a._RealDiv=a.asm.RealDiv).apply(null,arguments)},ug=a._Relu=function(){return(ug=a._Relu=a.asm.Relu).apply(null,arguments)},cg=a._Relu6=function(){return(cg=a._Relu6=a.asm.Relu6).apply(null,arguments)},dg=a._ResizeBilinear=function(){return(dg=a._ResizeBilinear=a.asm.ResizeBilinear).apply(null,arguments)},pg=a._ResizeNearestNeighbor=function(){return(pg=a._ResizeNearestNeighbor=a.asm.ResizeNearestNeighbor).apply(null,arguments)},hg=a._Reverse=function(){return(hg=a._Reverse=a.asm.Reverse).apply(null,arguments)},fg=a._RotateWithOffset=function(){return(fg=a._RotateWithOffset=a.asm.RotateWithOffset).apply(null,arguments)},mg=a._Round=function(){return(mg=a._Round=a.asm.Round).apply(null,arguments)},gg=a._Rsqrt=function(){return(gg=a._Rsqrt=a.asm.Rsqrt).apply(null,arguments)},yg=a._ScatterNd=function(){return(yg=a._ScatterNd=a.asm.ScatterNd).apply(null,arguments)},Ag=a._SelectV2=function(){return(Ag=a._SelectV2=a.asm.SelectV2).apply(null,arguments)},xg=a._Sigmoid=function(){return(xg=a._Sigmoid=a.asm.Sigmoid).apply(null,arguments)},bg=a._Sin=function(){return(bg=a._Sin=a.asm.Sin).apply(null,arguments)},vg=a._Softmax=function(){return(vg=a._Softmax=a.asm.Softmax).apply(null,arguments)},wg=a._SparseFillEmptyRows=function(){return(wg=a._SparseFillEmptyRows=a.asm.SparseFillEmptyRows).apply(null,arguments)},kg=a._SparseReshape=function(){return(kg=a._SparseReshape=a.asm.SparseReshape).apply(null,arguments)},Sg=a._SparseSegmentReduction=function(){return(Sg=a._SparseSegmentReduction=a.asm.SparseSegmentReduction).apply(null,arguments)},Ig=a._Sqrt=function(){return(Ig=a._Sqrt=a.asm.Sqrt).apply(null,arguments)},Cg=a._Square=function(){return(Cg=a._Square=a.asm.Square).apply(null,arguments)},Tg=a._SquaredDifference=function(){return(Tg=a._SquaredDifference=a.asm.SquaredDifference).apply(null,arguments)},Ng=a._Step=function(){return(Ng=a._Step=a.asm.Step).apply(null,arguments)},Eg=a._StridedSlice=function(){return(Eg=a._StridedSlice=a.asm.StridedSlice).apply(null,arguments)},Rg=a._Sub=function(){return(Rg=a._Sub=a.asm.Sub).apply(null,arguments)},_g=a._Sum=function(){return(_g=a._Sum=a.asm.Sum).apply(null,arguments)},Dg=a._Tan=function(){return(Dg=a._Tan=a.asm.Tan).apply(null,arguments)},$g=a._Tanh=function(){return($g=a._Tanh=a.asm.Tanh).apply(null,arguments)},Pg=a._Tile=function(){return(Pg=a._Tile=a.asm.Tile).apply(null,arguments)},Fg=a._TopK=function(){return(Fg=a._TopK=a.asm.TopK).apply(null,arguments)},Og=a._Transform=function(){return(Og=a._Transform=a.asm.Transform).apply(null,arguments)},Mg=a._Transpose=function(){return(Mg=a._Transpose=a.asm.Transpose).apply(null,arguments)},zg=a.__FusedMatMul=function(){return(zg=a.__FusedMatMul=a.asm._FusedMatMul).apply(null,arguments)},Lg=a._malloc=function(){return(Lg=a._malloc=a.asm.malloc).apply(null,arguments)},Bg=a._free=function(){return(Bg=a._free=a.asm.free).apply(null,arguments)},Wg=a.___errno_location=function(){return(Wg=a.___errno_location=a.asm.__errno_location).apply(null,arguments)},mf=a.stackSave=function(){return(mf=a.stackSave=a.asm.stackSave).apply(null,arguments)},gf=a.stackRestore=function(){return(gf=a.stackRestore=a.asm.stackRestore).apply(null,arguments)},zd=a.stackAlloc=function(){return(zd=a.stackAlloc=a.asm.stackAlloc).apply(null,arguments)},Vg=a.dynCall_iijjiiii=function(){return(Vg=a.dynCall_iijjiiii=a.asm.dynCall_iijjiiii).apply(null,arguments)},Ug=a.dynCall_jiji=function(){return(Ug=a.dynCall_jiji=a.asm.dynCall_jiji).apply(null,arguments)};a.cwrap=sf;var $u;Un=function te(){$u||yf(),$u||(Un=te)};function yf(te){if(te=te||c,Rt>0||(Kt(),Rt>0))return;function he(){$u||($u=!0,a.calledRun=!0,!z&&(or(),o(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),Pn()))}a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),he()},1)):he()}if(a.preInit)for(typeof a.preInit=="function"&&(a.preInit=[a.preInit]);a.preInit.length>0;)a.preInit.pop()();yf();var Pu;l&&(Pu={uncaughtException:process.listeners("uncaughtException").filter(function(te){return!l.uncaughtException.indexOf(te)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(te){return!l.unhandledRejection.indexOf(te)>-1})});var Fu;if(typeof r!="undefined")Fu=r;else if(typeof WasmBackendModuleThreadedSimd!="undefined")Fu=WasmBackendModuleThreadedSimd;else throw new Error("Could not find wasm module in post.js");if(Pu){var Gg=Fu._dispose;Fu._dispose=function(){Gg(),Pu.uncaughtException.forEach(function(te){process.removeListener("uncaughtException",te)}),Pu.unhandledRejection.forEach(function(te){process.removeListener("unhandledRejection",te)})}}return 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)}}),N_=1e-7,E_=1e-4,Tp=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}},fc=class{refCount(e){return Ks("refCount")}incRef(e){return Ks("incRef")}timerAvailable(){return!0}time(e){return Ks("time")}read(e){return Ks("read")}readSync(e){return Ks("readSync")}readToGPU(e,t){return Ks("readToGPU")}numDataIds(){return Ks("numDataIds")}disposeData(e,t){return Ks("disposeData")}write(e,t,n){return Ks("write")}move(e,t,n,s,r){return Ks("move")}memory(){return Ks("memory")}floatPrecision(){return Ks("floatPrecision")}epsilon(){return this.floatPrecision()===32?N_:E_}dispose(){return Ks("dispose")}};function Ks(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 sw(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,Qf(e,t,n)}function R_(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--,Qf(e,n,s),Qf(t,n,s)}function ip(e,t,n){return Math.max(e,Math.min(t,n))}function __(e){return e%2===0?e:e+1}function Qf(e,t,n){let s=e[t];e[t]=e[n],e[n]=s}function D_(e){let t=0;for(let n=0;nn+` Shapes ${e} and ${t} must match`)}function cl(e){P(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Ji(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||Gn(e)&&!n)for(let s=0;s0,n,s=setTimeout){return new Promise((r,a)=>{let o=0,i=()=>{if(e()){r();return}o++;let l=t(o);if(n!=null&&o>=n){a();return}s(i,l)};i()})}function B_(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 yr(e,t){let n=t.length;return e=e==null?t.map((s,r)=>r):[].concat(e),P(e.every(s=>s>=-n&&s`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),P(e.every(s=>Yu(s)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(s=>s<0?n+s:s)}function rw(e,t){let n=[],s=[],r=t!=null&&Array.isArray(t)&&t.length===0,a=t==null||r?null:yr(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 aw(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 ow(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 iw(e,t){for(let n=0;nt+=n.length),t}function Ka(e){return typeof e=="string"||e instanceof String}function cw(e){return typeof e=="boolean"}function dw(e){return typeof e=="number"}function Rm(e){return Array.isArray(e)?Rm(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":dw(e)?"float32":Ka(e)?"string":cw(e)?"bool":"float32"}function to(e){return!!(e&&e.constructor&&e.call&&e.apply)}function em(e,t){for(let n=t;n=0;--s)n[s]=n[s+1]*e[s+1];return n}function pw(e,t,n,s=!1){let r=new Array;if(t.length===1){let a=t[0]*(s?2:1);for(let o=0;ol*u)*(s?2:1);for(let l=0;lr*a)*(n?2:1);if(s===0)return[];if(s!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return pw(0,e,t,n)}function yy(e,t){let n=_m(e,t);for(let s=0;ss*r,1);if(t==null||t==="float32")return ju(e,new Float32Array(n));if(t==="int32")return ju(e,new Int32Array(n));if(t==="bool")return ju(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function Ay(e){e.forEach(t=>{P(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function U_(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]=q_(s,r)})}};function H_(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...s)=>(j_(t,s[0],s[1]),s.join("="))),t}function j_(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function q_(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 U(){return by}var by=null;function X_(e){by=e}var Zg;function fw(){if(Zg==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");Zg=e}return Zg}function K_(){let e=fw();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function vy(e,t){let n=K_();if(n.has(e))return n.get(e);{let s=t();return n.set(e,s),n.get(e)}}var dl="Abs",gc="Acos",yc="Acosh",Ta="Add",go="AddN",Ac="All",xc="Any",yo="ArgMax",bc="ArgMin",vc="Asin",wc="Asinh",kc="Atan",Sc="Atanh",pl="Atan2",Ao="AvgPool",Dm="AvgPoolGrad",Np="AvgPool3D",$m="AvgPool3DGrad",xo="BatchMatMul",hl="BatchToSpaceND",Pm="Bincount",mw="BroadcastTo",Fm="BroadcastArgs",bo="Cast",vo="Ceil",Na="ClipByValue",Ep="Complex",Rp="ComplexAbs",fl="Concat",wo="Conv2D",Om="Conv2DBackpropFilter",ko="Conv2DBackpropInput",_p="Conv3D",Mm="Conv3DBackpropFilterV2",zm="Conv3DBackpropInputV2",So="Cos",Io="Cosh",ml="Cumprod",Co="Cumsum",gl="CropAndResize",Lm="DenseBincount",yl="DepthToSpace",To="DepthwiseConv2dNative",Bm="DepthwiseConv2dNativeBackpropFilter",Wm="DepthwiseConv2dNativeBackpropInput",Vm="Diag",Dp="Dilation2D",tm="Dilation2DBackpropInput",nm="Dilation2DBackpropFilter",No="RealDiv",$p="Einsum",Eo="Elu",Um="EluGrad",Ic="Erf",Al="Equal",Ro="Exp",xl="ExpandDims",bl="Expm1",Gm="FFT",Cc="Fill",vl="FlipLeftRight",_o="Floor",Do="FloorDiv",$o="FusedBatchNorm",wl="GatherV2",kl="GatherNd",Sl="Greater",Po="GreaterEqual",Fo="Identity",Hm="IFFT",Pp="Imag",Tc="IsFinite",Nc="IsInf",Il="IsNan",Oo="LeakyRelu",Cl="Less",Tl="LessEqual",jm="LinSpace",Mo="Log",Ec="Log1p",Nl="LogicalAnd",El="LogicalNot",Rc="LogicalOr",gw="LogicalXor",yw="LogSoftmax",Z_="LowerBound",Fp="LRN",qm="LRNGrad",zo="Max",Lo="Maximum",Bo="MaxPool",Xm="MaxPoolGrad",Op="MaxPool3D",Km="MaxPool3DGrad",Zm="MaxPoolWithArgmax",Wo="Mean",Vo="Min",Uo="Minimum",Go="MirrorPad",_c="Mod",Ym="Multinomial",Ho="Multiply",Rl="Neg",_l="NotEqual",Dl="NonMaxSuppressionV3",Dc="NonMaxSuppressionV4",$l="NonMaxSuppressionV5",Pl="OnesLike",Fl="OneHot",Ol="Pack",jo="PadV2",Y_="Pool",qo="Pow",Xo="Prelu",Ko="Prod",Jm="RaggedGather",Qm="RaggedTensorToTensor",$c="Range",Mp="Real",Ml="Reciprocal",Zo="Relu",zl="Reshape",Yo="ResizeNearestNeighbor",e0="ResizeNearestNeighborGrad",Jo="ResizeBilinear",t0="ResizeBilinearGrad",Qo="Relu6",Ll="Reverse",Bl="Round",ei="Rsqrt",Wl="ScatterNd",n0="SearchSorted",Vl="Select",Pc="Selu",Ul="Slice",ti="Sin",Gl="Sinh",Fc="Sign",ni="Sigmoid",Oc="Softplus",si="Sqrt",ri="Sum",Hl="SpaceToBatchND",jl="SplitV",ai="Softmax",zp="SparseFillEmptyRows",Mc="SparseReshape",Lp="SparseSegmentMean",Bp="SparseSegmentSum",Wp="SparseToDense",oi="SquaredDifference",zc="Square",ql="StridedSlice",Lc="StringNGrams",Vp="StringSplit",Up="StringToHashBucketFast",ii="Sub",Xl="Tan",li="Tanh",Ea="Tile",Kl="TopK",Zl="Transform",Jr="Transpose",s0="Unique",Yl="Unpack",Gp="UnsortedSegmentSum",J_="UpperBound",Jl="ZerosLike",ui="Step",lp="FromPixels",Ql="RotateWithOffset",no="_FusedMatMul",so="FusedConv2D",ro="FusedDepthwiseConv2D";function Xa(...e){U().getBool("IS_TEST")||U().getBool("PROD")||console.warn(...e)}function Q_(...e){U().getBool("IS_TEST")||U().getBool("PROD")||console.log(...e)}var Ju=vy("kernelRegistry",()=>new Map),up=vy("gradRegistry",()=>new Map);function sm(e,t){let n=wy(e,t);return Ju.get(n)}function p3(e){return up.get(e)}function ea(e){let t=Ju.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 er(e){let{kernelName:t,backendName:n}=e,s=wy(t,n);Ju.has(s)&&Xa(`The kernel '${t}' for backend '${n}' is already registered`),Ju.set(s,e)}function Aw(e){let{kernelName:t}=e;up.has(t)&&U().getBool("DEBUG")&&Xa(`Overriding the gradient for '${t}'`),up.set(t,e)}function eD(e,t){let n=wy(e,t);if(!Ju.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);Ju.delete(n)}function tD(e){if(!up.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);up.delete(e)}function nD(e,t){ea(e).forEach(s=>{let r=Object.assign({},s,{backendName:t});er(r)})}function wy(e,t){return`${t}_${e}`}var v={};We(v,{arraysEqual:()=>mo,assert:()=>P,assertNonNegativeIntegerDimensions:()=>Ay,assertNonNull:()=>cl,assertShapesMatch:()=>ls,bytesFromStringArray:()=>uw,bytesPerElement:()=>d3,checkConversionForErrors:()=>iw,clamp:()=>ip,computeStrides:()=>mc,createScalarValue:()=>lD,createShuffledIndices:()=>z_,decodeString:()=>rm,distSquared:()=>P_,encodeString:()=>jp,fetch:()=>cD,fingerPrint64:()=>iD,flatten:()=>Ji,getArrayFromDType:()=>ow,getTypedArrayFromDType:()=>aw,hasEncodingLoss:()=>W_,hexToLong:()=>Hp,indexToLoc:()=>G_,inferDtype:()=>Rm,inferFromImplicitShape:()=>B_,isBoolean:()=>cw,isFunction:()=>to,isInt:()=>Yu,isNumber:()=>dw,isPromise:()=>xy,isScalarShape:()=>F_,isString:()=>Ka,isTypedArray:()=>Gn,isValidDtype:()=>lw,locToIndex:()=>U_,makeOnesTypedArray:()=>yy,makeZerosNestedTypedArray:()=>V_,makeZerosTypedArray:()=>_m,nearestDivisor:()=>em,nearestLargerEven:()=>__,now:()=>cp,parseAxisParam:()=>yr,randUniform:()=>$_,repeatedTry:()=>L_,rightPad:()=>np,shuffle:()=>sw,shuffleCombo:()=>R_,sizeFromShape:()=>It,sizeToSquarishShape:()=>M_,squeezeShape:()=>rw,sum:()=>D_,swap:()=>Qf,tanh:()=>O_,toNestedArray:()=>ju,toTypedArray:()=>r0});var dv=fo(d_()),Bi=dv.default||dv;function Hp(e){return Bi.fromString(e,!0,16)}var xw=Hp("c3a5c85c97cb3127"),Mi=Hp("b492b66fbe98f273"),ss=Hp("9ae16a3b2f90404f");function h3(e){return e.xor(e.shru(47))}function bw(e,t,n){let s=e.slice(t,t+n);return Bi.fromBytes(Array.from(s),!0,!0)}function St(e,t){return bw(e,t,8)}function pv(e,t){return bw(e,t,4)}function In(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function Ja(e,t,n=Hp("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 sD(e,t,n,s,r,a){r=r.add(e),a=In(a.add(r).add(s),21);let o=r;return r=r.add(t),r=r.add(n),a=a.add(In(r,44)),[r.add(s),a.add(o)]}function Tf(e,t,n,s){return sD(St(e,t),St(e,t+8),St(e,t+16),St(e,t+24),n,s)}function rD(e,t=e.length){if(t>=8){let n=ss.add(t*2),s=St(e,0).add(ss),r=St(e,t-8),a=In(r,37).mul(n).add(s),o=In(s,25).add(r).mul(n);return Ja(a,o,n)}if(t>=4){let n=ss.add(t*2),s=pv(e,0);return Ja(s.shl(3).add(t),pv(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 h3(ss.mul(a).xor(xw.mul(o))).mul(ss)}return ss}function aD(e,t=e.length){let n=ss.add(t*2),s=St(e,0).mul(Mi),r=St(e,8),a=St(e,t-8).mul(n),o=St(e,t-16).mul(ss);return Ja(In(s.add(r),43).add(In(a,30)).add(o),s.add(In(r.add(ss),18)).add(a),n)}function oD(e,t=e.length){let n=ss.add(t*2),s=St(e,0).mul(ss),r=St(e,8),a=St(e,t-8).mul(n),o=St(e,t-16).mul(ss),i=In(s.add(r),43).add(In(a,30)).add(o),l=Ja(i,s.add(In(r.add(ss),18)).add(a),n),u=St(e,16).mul(n),c=St(e,24),p=i.add(St(e,t-32)).mul(n),d=l.add(St(e,t-24)).mul(n);return Ja(In(u.add(c),43).add(In(p,30)).add(d),u.add(In(c.add(s),18)).add(p),n)}function iD(e,t=e.length){let n=Bi.fromNumber(81,!0);if(t<=32)return t<=16?rD(e,t):aD(e,t);if(t<=64)return oD(e,t);let s=n,r=n.mul(Mi).add(113),a=h3(r.mul(ss).add(113)).mul(ss),o=[Bi.UZERO,Bi.UZERO],i=[Bi.UZERO,Bi.UZERO];s=s.mul(ss).add(St(e,0));let l=0,u=(t-1>>6)*64,c=u+(t-1&63)-63;do s=In(s.add(r).add(o[0]).add(St(e,l+8)),37).mul(Mi),r=In(r.add(o[1]).add(St(e,l+48)),42).mul(Mi),s=s.xor(i[1]),r=r.add(o[0]).add(St(e,l+40)),a=In(a.add(i[0]),33).mul(Mi),o=Tf(e,l,o[1].mul(Mi),s.add(i[0])),i=Tf(e,l+32,a.add(i[1]),r.add(St(e,l+16))),[a,s]=[s,a],l+=64;while(l!==u);let p=Mi.add(a.and(255).shl(1));return l=c,i[0]=i[0].add(t-1&63),o[0]=o[0].add(i[0]),i[0]=i[0].add(o[0]),s=In(s.add(r).add(o[0]).add(St(e,l+8)),37).mul(p),r=In(r.add(o[1]).add(St(e,l+48)),42).mul(p),s=s.xor(i[1].mul(9)),r=r.add(o[0].mul(9).add(St(e,l+40))),a=In(a.add(i[0]),33).mul(p),o=Tf(e,l,o[1].mul(p),s.add(i[0])),i=Tf(e,l+32,a.add(i[1]),r.add(St(e,l+16))),[a,s]=[s,a],Ja(Ja(o[0],i[0],p).add(h3(r).mul(xw)).add(a),Ja(o[1],i[1],p).add(s),p)}function lD(e,t){return t==="string"?jp(e):r0([e],t)}function uD(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function r0(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Ji(e)),U().getBool("DEBUG")&&iw(e,t),uD(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=cp();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(r);else{r();for(let l of s)l.dataSync();a=Promise.resolve({kernelMs:cp()-o})}if(U().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let l=0;l{pD(c,u.dtype,e)})}return{kernelName:e,outputs:s,inputs:t,timeMs:a.then(l=>l.kernelMs),extraInfo:a.then(l=>l.getExtraProfileInfo!=null?l.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:s,inputs:r,extraInfo:a}=e;n.forEach(o=>{Promise.all([o.data(),s,a]).then(i=>{this.logger.logKernelProfile(t,o,i[0],i[1],r,i[2])})})}};function pD(e,t,n){if(t!=="float32")return!1;for(let s=0;s0?f:""} `}}console.log(`%c${i} %c${o} %c${l}D ${c} %c${u} %c${p} %c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function fD(e,t,n){let s={},r={};for(let l=0;ls[m.id]=!0),h=!0,r[u.id]=!0;break}if(h)break}}let a={};a[n.id]=!0;let o={};for(let l=e.length-1;l>=0;l--){let u=e[l],c=u.inputs;for(let p=0;p=0;r--){let a=t[r],o=[];if(a.outputs.forEach(l=>{let u=e[l.id];u!=null?o.push(u):o.push(null)}),a.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);let i=a.gradient(o);for(let l in a.inputs){if(!(l in i))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(i)}.`);let u=n(()=>i[l]());if(u.dtype!=="float32")throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);let c=a.inputs[l];if(!mo(u.shape,c.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${c.shape}'`);if(e[c.id]==null)e[c.id]=u;else{let p=e[c.id];e[c.id]=s(p,u),p.dispose()}}}}var hv=20,Wd=3,Yg=7;function gD(e,t,n,s){let r=mc(t),a=yD(e,t,n,r),o=t.length,i=Vf(e,t,n,r,a),l=["Tensor"];return s&&(l.push(` dtype: ${n}`),l.push(` rank: ${o}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(i.map(u=>" "+u).join(` `)),l.join(` `)}function yD(e,t,n,s){let r=It(t),a=s[s.length-1],o=new Array(a).fill(0),i=t.length,l=n==="complex64"?jd(e):e;if(i>1)for(let u=0;uhv){let g=Wd*o,y=Array.from(e.slice(0,g)),x=Array.from(e.slice((i-Wd)*o,i*o));return n==="complex64"&&(y=jd(y),x=jd(x)),["["+y.map((A,b)=>Hd(A,r[b],n)).join(", ")+", ..., "+x.map((A,b)=>Hd(A,r[i-Wd+b],n)).join(", ")+"]"]}let m=n==="complex64"?jd(e):Array.from(e);return["["+m.map((g,y)=>Hd(g,r[y],n)).join(", ")+"]"]}let u=t.slice(1),c=s.slice(1),p=s[0]*o,d=[];if(i>hv){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||ow(t,this.size),this.strides=mc(e)}set(e,...t){t.length===0&&(t=[0]),P(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let 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;srm(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}dataToGPU(e){return this.throwIfDisposed(),Nr().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();let e=Nr().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>rm(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 Nr().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Nr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Uu.print(this,e)}clone(){return this.throwIfDisposed(),Uu.clone(this)}toString(e=!1){let t=this.dataSync();return gD(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Uu.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Nr().makeVariable(this,e,t,n)}};Object.defineProperty(st,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function se(){return vy("Tensor",()=>st)}se();var dp=class extends st{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(!mo(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Nr().disposeTensor(this),this.dataId=e.dataId,Nr().incRef(this,null)}dispose(){Nr().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(dp,Symbol.hasInstance,{value:e=>e instanceof st&&e.assign!=null&&e.assign instanceof Function});var Dr={};We(Dr,{assertTypesMatch:()=>ww,getTensorsInContainer:()=>ky,isTensorInList:()=>kD,makeTypesMatch:()=>jt});var f3;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(f3||(f3={}));var m3;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(m3||(m3={}));var g3;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(g3||(g3={}));var y3;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(y3||(y3={}));var A3;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(A3||(A3={}));var wD={float32:y3,int32:m3,bool:g3,complex64:A3};function jn(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return wD[e][t]}function qp(e){return jn(e,"int32")}function jt(e,t){if(e.dtype===t.dtype)return[e,t];let n=jn(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function ww(e,t){P(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function kD(e,t){return t.some(n=>n.id===e.id)}function ky(e){let t=[];return kw(e,t,new Set),t}function kw(e,t,n){if(e==null)return;if(e instanceof st){t.push(e);return}if(!SD(e))return;let s=e;for(let r in s){let a=s[r];n.has(a)||(n.add(a),kw(a,t,n))}}function SD(e){return Array.isArray(e)||typeof e=="object"}function Jg(e){return e.kernelName!=null}var fv=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()}},pp=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new fv}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){ea(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 fc)&&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 pp.nextTensorId++}nextVariableId(){return pp.nextVariableId++}clone(e){let t=L.runKernel(Fo,{x:e}),n={x:e},s=a=>({x:()=>{let o="float32",i={x:a},l={dtype:o};return L.runKernel(bo,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,!(sm(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=Jg(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(Jg(e)){let{kernelName:h,inputs:f,attrs:m}=e;this.backendName==null&&this.backend;let g=sm(h,this.backendName);P(g!=null,()=>`Cannot find registered kernel '${h}' for backend '${this.backendName}'`),o=()=>{let y=this.backend.numDataIds();i=g.kernelFunc({inputs:f,attrs:m,backend:this.backend});let x=Array.isArray(i)?i:[i];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(h,y,x);let A=x.map(b=>b.rank!=null?b:this.makeTensorFromTensorInfo(b));if(s){let b=this.getTensorsForGradient(h,f,A);n=this.saveTensorsForBackwardMode(b)}return A}}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:u,attrs:c}=e,p=Jg(e)?null:e.backwardsFunc,d;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=o():(d=this.profiler.profileKernel(l,u,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(d),t=d.outputs)}),s&&this.addTapeNode(l,u,t,p,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map(h=>u[h]!=null?u[h].shape:null),outputShapes:t.map(h=>h.shape),kernelTimeMs:d.timeMs,extraInfo:d.extraInfo}),Array.isArray(i)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(n=>this.keep(this.clone(n)))}getTensorsForGradient(e,t,n){let s=p3(e);if(s!=null){let r=s.inputsToSave||[],a=s.outputsToSave||[],o;s.saveAllInputs?(P(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),o=Object.keys(t).map(l=>t[l])):o=r.map(l=>t[l]);let i=n.filter((l,u)=>a[u]);return o.concat(i)}return[]}makeTensor(e,t,n,s){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",s=s||this.backend;let r=e;n==="string"&&Ka(e[0])&&(r=e.map(i=>jp(i)));let a=s.write(r,t,n),o=new st(t,n,a,this.nextTensorId());if(this.trackTensor(o,s),n==="string"){let i=this.state.tensorInfo.get(a),l=uw(r);this.state.numBytes+=l-i.bytes,i.bytes=l}return o}makeTensorFromDataId(e,t,n,s){n=n||"float32";let r={dataId:e,shape:t,dtype:n};return this.makeTensorFromTensorInfo(r,s)}makeTensorFromTensorInfo(e,t){let{dataId:n,shape:s,dtype:r}=e,a=new st(s,r,n,this.nextTensorId());return this.trackTensor(a,t),a}makeVariable(e,t=!0,n,s){n=n||this.nextVariableId().toString(),s!=null&&s!==e.dtype&&(e=e.cast(s));let r=new dp(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*d3(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 dp||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*d3(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=p3(e);i!=null&&(s=i.gradFunc),s!=null&&(o.gradient=l=>(l=l.map((u,c)=>{if(u==null){let p=n[c],d=_m(p.size,p.dtype);return this.makeTensor(d,p.shape,p.dtype)}return u}),s(l.length>1?l:l[0],r,a))),this.state.activeTape.push(o)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=ky(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(P(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));P(r instanceof st,()=>"The result y returned by f() must be a tensor.");let a=fD(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?ID(r.shape):n,mD(o,a,l=>this.tidy(l),CD);let i=t.map(l=>o[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let u of l.saved)u.dispose()}),this.state.activeTape=null),{value:r,grads:i}})}customGrad(e){return P(to(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{P(t.every(o=>o instanceof st),()=>"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),P(n.value instanceof st,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),P(to(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),a=(o,i)=>{let l=n.gradFunc(o,i),u=Array.isArray(l)?l:[l];P(u.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),P(u.every(p=>p instanceof st),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let c={};return u.forEach((p,d)=>{c[d]=()=>p}),c};return this.runKernelFunc({forwardFunc:r,backwardsFunc:a,inputs:s})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){let t=cp(),n=await this.backend.time(e);return n.wallMs=cp()-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 fv;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}};pp.nextTensorId=0;pp.nextVariableId=0;function ID(e){let t=yy(It(e),"float32");return L.makeTensor(t,e,"float32")}function Sw(){let e=fw();if(e._tfengine==null){let t=new hw(e);e._tfengine=new pp(t)}return X_(e._tfengine.ENV),xD(()=>e._tfengine),e._tfengine}var L=Sw();function CD(e,t){let n={a:e,b:t};return L.runKernel(Ta,n)}var Xp={};We(Xp,{isBrowser:()=>Iw,isMobile:()=>ED,mockIsMobile:()=>ND});function TD(){return typeof navigator!="undefined"&&navigator!=null}var x3;function ND(e){x3=e}function ED(e){if(x3!==void 0)return x3;if(e||TD()){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 Iw(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var $s=U();$s.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.")});$s.registerFlag("IS_BROWSER",()=>Iw());$s.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");$s.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));$s.registerFlag("PROD",()=>!1);$s.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>$s.getBool("DEBUG"));$s.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);$s.registerFlag("IS_TEST",()=>!1);$s.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);$s.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);$s.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);$s.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1);$s.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);function ta(e,t){let n=e;if(Gn(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let s=[];for(;Array.isArray(n)||Gn(n)&&t!=="string";)s.push(n.length),n=n[0];return Array.isArray(e)&&U().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Cw(e,s,[]),s}function Cw(e,t,n){if(n=n||[],!Array.isArray(e)&&!Gn(e)){P(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}P(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),P(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),mv(s,r,t,n),e==null||!Gn(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=ta(e,r);!Gn(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?r0(e,r):Ji(e,[],!0);return L.makeTensor(i,a,r)}function hp(e,t,n,s="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((a,o)=>_(a,`${t}[${o}]`,n,s))}var Sy="__op";function B(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+Sy;let r=(...a)=>{L.startScope(n);try{let o=s(...a);return xy(o)&&console.error("Cannot return a Promise inside of tidy."),L.endScope(o),o}catch(o){throw L.endScope(null),o}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}function RD(e,t){let n=_(e,"real","complex"),s=_(t,"imag","complex");ls(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 L.runKernel(Ep,r)}var wa=B({complex_:RD});function ci(e,t,n,s){if(s==null&&(s=Rm(e)),s==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Gn(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){Ay(t);let r=It(t),a=It(n);P(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!Gn(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=s!=="string"?r0(e,s):Ji(e,[],!0),L.makeTensor(e,t,s)}function Ue(e,t,n){let s=ta(e,n);return ci(e,t,s,n)}var b3={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},am=4;async function _D(e,t){let n=[],s=[],r=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);for(let o=0;o{let d=await l.bytes(),h=d.reduce((g,y)=>g+y.length,0)+am*d.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 Iy=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function gv(e){return Iy?Buffer.byteLength(e):new Blob([e]).size}function $D(e){if(Iy)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 yv(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 Nw(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}function Ew(e,t,n){let s={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(e.trainingConfig!=null&&(s.trainingConfig=e.trainingConfig),e.weightsManifest!=null){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!n)throw new Error("modelJSON has weightsManifest but weightData is null");s.weightSpecs=t,s.weightData=n}return e.signature!=null&&(s.signature=e.signature),e.userDefinedMetadata!=null&&(s.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(s.modelInitializer=e.modelInitializer),s}async function Ty(e,t){let n,s;return e.weightsManifest!=null&&([n,s]=await t(e.weightsManifest)),Ew(e,n,s)}function Kp(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:gv(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:gv(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function Rw(e){let t=[];for(let n of e)t.push(...n.weights);return t}function FD(){let e=n=>{let s=n<<13,r=0;for(;(s&8388608)===0;)r-=8388608,s<<=1;return s&=-8388609,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 OD(){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 MD(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function zD(){let e=FD(),t=OD(),n=MD();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 Zt=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Zt.instance==null&&(Zt.instance=new Zt),Zt.instance}static registerSaveRouter(e){Zt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Zt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Zt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Zt.getHandlers(e,"load",t)}static getHandlers(e,t,n){let s=[];return(t==="load"?Zt.getInstance().loadRouters:Zt.getInstance().saveRouters).forEach(a=>{let o=a(e,n);o!==null&&s.push(o)}),s}},LD=e=>Zt.registerSaveRouter(e),BD=e=>Zt.registerLoadRouter(e),WD=e=>Zt.getSaveHandlers(e),VD=(e,t)=>Zt.getLoadHandlers(e,t),v3="tensorflowjs",w3=1,Gi="models_store",Za="model_info_store";function _w(){if(!U().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 k3(e){let t=e.result;t.createObjectStore(Gi,{keyPath:"modelPath"}),t.createObjectStore(Za,{keyPath:"modelPath"})}var Qi=class{constructor(e){if(this.indexedDB=_w(),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(v3,w3);r.onupgradeneeded=()=>k3(r),r.onsuccess=()=>{let a=r.result;if(t==null){let o=a.transaction(Gi,"readonly"),l=o.objectStore(Gi).get(this.modelPath);l.onsuccess=()=>{if(l.result==null)return a.close(),s(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(l.result.modelArtifacts)},l.onerror=u=>(a.close(),s(l.error)),o.oncomplete=()=>a.close()}else{let o=Kp(t),i=a.transaction(Za,"readwrite"),l=i.objectStore(Za),u=l.put({modelPath:this.modelPath,modelArtifactsInfo:o}),c;u.onsuccess=()=>{c=a.transaction(Gi,"readwrite");let d=c.objectStore(Gi).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:o});d.onsuccess=()=>n({modelArtifactsInfo:o}),d.onerror=h=>{l=i.objectStore(Za);let f=l.delete(this.modelPath);f.onsuccess=()=>(a.close(),s(d.error)),f.onerror=m=>(a.close(),s(d.error))}},u.onerror=p=>(a.close(),s(u.error)),i.oncomplete=()=>{c==null?a.close():c.oncomplete=()=>a.close()}}},r.onerror=a=>s(r.error)})}};Qi.URL_SCHEME="indexeddb://";var Dw=e=>U().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Qi.URL_SCHEME)?UD(e.slice(Qi.URL_SCHEME.length)):null;Zt.registerSaveRouter(Dw);Zt.registerLoadRouter(Dw);function UD(e){return new Qi(e)}function GD(e){return e.startsWith(Qi.URL_SCHEME)?e.slice(Qi.URL_SCHEME.length):e}var HD=class{constructor(){this.indexedDB=_w()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(v3,w3);n.onupgradeneeded=()=>k3(n),n.onsuccess=()=>{let s=n.result,r=s.transaction(Za,"readonly"),o=r.objectStore(Za).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=GD(e),new Promise((t,n)=>{let s=this.indexedDB.open(v3,w3);s.onupgradeneeded=()=>k3(s),s.onsuccess=()=>{let r=s.result,a=r.transaction(Za,"readwrite"),o=a.objectStore(Za),i=o.get(e),l;i.onsuccess=()=>{if(i.result==null)return r.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let u=o.delete(e),c=()=>{l=r.transaction(Gi,"readwrite");let d=l.objectStore(Gi).delete(e);d.onsuccess=()=>t(i.result.modelArtifactsInfo),d.onerror=h=>n(i.error)};u.onsuccess=c,u.onerror=p=>(c(),r.close(),n(i.error))}},i.onerror=u=>(r.close(),n(i.error)),a.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},s.onerror=r=>n(s.error)})}},Aa="/",Gu="tensorflowjs_models",$w="info",jD="model_topology",qD="weight_specs",XD="weight_data",KD="model_metadata";function Pw(e){return{info:[Gu,e,$w].join(Aa),topology:[Gu,e,jD].join(Aa),weightSpecs:[Gu,e,qD].join(Aa),weightData:[Gu,e,XD].join(Aa),modelMetadata:[Gu,e,KD].join(Aa)}}function Fw(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function ZD(e){let t=e.split(Aa);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Aa)}function YD(e){return e.startsWith(el.URL_SCHEME)?e.slice(el.URL_SCHEME.length):e}var el=class{constructor(e){if(!U().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=Pw(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=Kp(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,$D(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 Fw(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=PD(a),t}};el.URL_SCHEME="localstorage://";var Ow=e=>U().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(el.URL_SCHEME)?JD(e.slice(el.URL_SCHEME.length)):null;Zt.registerSaveRouter(Ow);Zt.registerLoadRouter(Ow);function JD(e){return new el(e)}var QD=class{constructor(){P(U().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),P(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Gu+Aa,n=Aa+$w;for(let s=0;s"scheme must not be undefined or null."),e.endsWith(qu)&&(e=e.slice(0,e.indexOf(qu))),P(e.length>0,()=>"scheme must not be an empty string.");let n=gs.getInstance();P(n.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){let t=gs.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(gs.getInstance().managers)}};function Uf(e){if(e.indexOf(qu)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${gs.getSchemes().join(",")}`);return{scheme:e.split(qu)[0],path:e.split(qu)[1]}}async function Mw(e,t,n=!1){P(e!==t,()=>`Old path and new path are the same: '${e}'`);let s=Zt.getLoadHandlers(e);P(s.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),P(s.length<2,()=>`Copying failed because more than one (${s.length}) load handlers for source URL ${e}.`);let r=s[0],a=Zt.getSaveHandlers(t);P(a.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),P(a.length<2,()=>`Copying failed because more than one (${s.length}) save handlers for destination URL ${t}.`);let o=a[0],i=Uf(e).scheme,l=Uf(e).path,u=i===Uf(e).scheme,c=await r.load();n&&u&&await gs.getManager(i).removeModel(l);let p=await o.save(c);return n&&!u&&await gs.getManager(i).removeModel(l),p.modelArtifactsInfo}async function e$(){let e=gs.getSchemes(),t={};for(let n of e){let s=await gs.getManager(n).listModels();for(let r in s){let a=n+qu+r;t[a]=s[r]}}return t}async function t$(e){let t=Uf(e);return gs.getManager(t.scheme).removeModel(t.path)}async function n$(e,t){return Mw(e,t,!1)}async function s$(e,t){return Mw(e,t,!0)}var r$=class{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}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)}setTimeoutCustom(e,t){if(!window||!U().getBool("USE_SETTIMEOUTCUSTOM")){setTimeout(e,t);return}this.functionRefs.push(e),setTimeout(()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")},t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",n=>{if(n.source===window&&n.data.name===this.messageName){n.stopPropagation();let s=this.functionRefs[n.data.index];s(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}},!0))}};if(U().get("IS_BROWSER")){U().setPlatform("browser",new r$);try{gs.registerManager(el.URL_SCHEME,new QD)}catch(e){}try{gs.registerManager(Qi.URL_SCHEME,new HD)}catch(e){}}var a$={importFetch:()=>p_()},Qg,o$=class{constructor(){this.util=h_(),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return U().global.fetch!=null?U().global.fetch(e,t):(Qg==null&&(Qg=a$.importFetch()),Qg(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)}};U().get("IS_NODE")&&!U().get("IS_BROWSER")&&U().setPlatform("node",new o$);function ze(e,t="float32",n){return t=t||"float32",Ay(e),new gn(e,t,n)}function i$(e,t){let n=_(e,"x","cast");if(!lw(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 L.runKernel(bo,s,r)}var me=B({cast_:i$});function l$(e){let n={x:_(e,"x","clone","string_or_numeric")};return L.runKernel(Fo,n)}var Hn=B({clone_:l$});function Ny(e,t=!1){console.log(e.toString(t))}Sw();var u$={buffer:ze,cast:me,clone:Hn,print:Ny};bD(u$);var On={};We(On,{browserFiles:()=>g$,browserHTTPRequest:()=>v$,concatenateArrayBuffers:()=>Cy,copyModel:()=>n$,decodeWeights:()=>Tw,encodeWeights:()=>_D,fromMemory:()=>k$,fromMemorySync:()=>Vw,getLoadHandlers:()=>VD,getModelArtifactsForJSON:()=>Ty,getModelArtifactsForJSONSync:()=>Ew,getModelArtifactsInfoForJSON:()=>Kp,getSaveHandlers:()=>WD,getWeightSpecs:()=>Rw,http:()=>Ry,isHTTPScheme:()=>S3,listModels:()=>e$,loadWeights:()=>y$,moveModel:()=>s$,registerLoadRouter:()=>BD,registerSaveRouter:()=>LD,removeModel:()=>t$,weightsLoaderFactory:()=>Lw,withSaveHandler:()=>S$,withSaveHandlerSync:()=>I$});var c$="model",d$=".json",p$=".weights.bin";function Av(e){return new Promise(t=>setTimeout(t)).then(e)}var Qu=class{constructor(e){if(!U().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Qu.URL_SCHEME)&&(e=e.slice(Qu.URL_SCHEME.length)),(e==null||e.length===0)&&(e=c$),this.modelJsonFileName=e+d$,this.weightDataFileName=e+p$}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=Nw(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 Av(()=>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 Av(()=>o.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Kp(e)}}}};Qu.URL_SCHEME="downloads://";var h$=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=Ty(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,Cy(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=>yv(r.name)),s={};for(let r of e)r.paths.forEach(a=>{let o=yv(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}},f$=e=>U().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Qu.URL_SCHEME)?m$(e.slice(Qu.URL_SCHEME.length)):null;Zt.registerSaveRouter(f$);function m$(e="model"){return new Qu(e)}function g$(e){return new h$(e)}function xv(e,t,n,s){o(e),n=n==null?0:n,s=s==null?1:s,i(n,s);let r=0,a=l=>(l.then(u=>{let c=n+ ++r/e.length*(s-n);return t(c),u}),l);function o(l){P(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function i(l,u){P(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),P(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),P(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(e.map(a))}async function zw(e,t){t==null&&(t={});let n=t.fetchFunc==null?U().platform.fetch:t.fetchFunc,s=e.map(p=>n(p,t.requestInit,{isBinary:!0})),r=0,a=.5,i=(t.onProgress==null?await Promise.all(s):await xv(s,t.onProgress,r,a)).map(p=>p.arrayBuffer()),l=.5,u=1;return t.onProgress==null?await Promise.all(i):await xv(i,t.onProgress,l,u)}async function y$(e,t="",n,s){return Lw(o=>zw(o,{requestInit:s}))(e,t,n)}function Lw(e){return async(t,n="",s)=>{let r=t.map(()=>!1),a={},o=s!=null?s.map(()=>!1):[],i=[];if(t.forEach((h,f)=>{let m=0;h.weights.forEach(g=>{let y="quantization"in g?g.quantization.dtype:g.dtype,x=b3[y]*It(g.shape),A=()=>{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&&(A(),o[w]=!0)}):A(),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),[]),u=[];l.forEach(h=>{t[h].paths.forEach(f=>{let m=n+(n.endsWith("/")?"":"/")+f;u.push(m)})});let c=await e(u),p={},d=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=Tw(w,[b.manifestEntry]);for(let C in k)p[C]=k[C]}),d+=f}),p}}var A$="application/octet-stream",x$="application/json",Ey=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(P(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=U().platform.fetch,P(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&P(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],s=Nw(e,n);t.body.append("model.json",new Blob([JSON.stringify(s)],{type:x$}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:A$}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:Kp(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 Ty(t,r=>this.loadWeights(r))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=b$(t),r=this.weightPathPrefix||n,a=Rw(e),o=[],i=[];for(let u of e)for(let c of u.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(c)):o.push(r+c+s);this.weightUrlConverter&&o.push(...await Promise.all(i));let l=await zw(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,Cy(l)]}};Ey.URL_SCHEME_REGEX=/^https?:\/\//;function b$(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),s=e.substring(0,t),r=n>t?e.substring(n):"";return[s+"/",r]}function S3(e){return e.match(Ey.URL_SCHEME_REGEX)!=null}var Bw=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(s=>S3(s)):n=S3(e),n)return Ry(e,t)}return null};Zt.registerSaveRouter(Bw);Zt.registerLoadRouter(Bw);function Ry(e,t){return new Ey(e,t)}function v$(e,t){return Ry(e,t)}var e3=class{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}},Ww=class{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}},w$=class{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}};function k$(e,t,n,s){let r=arguments;return new w$(Vw(...r))}function Vw(e,t,n,s){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new e3(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 e3({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 e3({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:s}))}function S$(e){return new Ww(e)}function I$(e){return new Ww(e)}var Uw={};We(Uw,{confusionMatrix:()=>W$});function C$(e,t,n=!1,s=!1){let r=_(e,"a","matMul"),a=_(t,"b","matMul");[r,a]=jt(r,a);let o={a:r,b:a},i={transposeA:n,transposeB:s};return L.runKernel(xo,o,i)}var et=B({matMul_:C$});function T$(e,t,n=1,s=0,r="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let o={indices:_(e,"indices","oneHot","int32")},i={dtype:r,depth:t,onValue:n,offValue:s};return L.runKernel(Fl,o,i)}var ec=B({oneHot_:T$});function _y(){U().set("PROD",!0)}function N$(){U().set("DEBUG",!0)}function E$(){U().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Dy(e){U().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}vD(Dy);function R$(){L.disposeVariables()}function Jt(){return L}function om(){return L.memory()}function _$(e){return L.profile(e)}function X(e,t){return L.tidy(e,t)}function Y(e){ky(e).forEach(n=>n.dispose())}function Cn(e){return L.keep(e)}function D$(e){return L.time(e)}function Zp(e){return L.setBackend(e)}function Yp(){return L.ready()}function cn(){return L.backendName}function $$(e){L.removeBackend(e)}function $y(e){return L.findBackend(e)}function P$(e){return L.findBackendFactory(e)}function eu(e,t,n=1){return L.registerBackend(e,t,n)}function Bs(){return L.backend}function F$(e,t){U().setPlatform(e,t)}function O$(e){let n={input:_(e,"input","imag")};return L.runKernel(Pp,n)}var Jp=B({imag_:O$});function M$(e){let n={x:_(e,"x","neg")};return L.runKernel(Rl,n)}var Dt=B({neg_:M$});function z$(e){let n={input:_(e,"input","real")};return L.runKernel(Mp,n)}var tc=B({real_:z$});function L$(e,t,n){let s=_(e,"x","transpose");if(t==null&&(t=s.shape.map((o,i)=>i).reverse()),P(s.rank===t.length,()=>`Error in transpose: rank of input ${s.rank} must match length of perm ${t}.`),t.forEach(o=>{P(o>=0&&o`All entries in 'perm' must be between 0 and ${s.rank-1} but got ${t}`)}),s.rank<=1)return s.clone();let r={x:s},a={perm:t};return s.dtype==="complex64"?X(()=>{let o=tc(s),i=Jp(s);return o=L.runKernel(Jr,{x:o},a),i=L.runKernel(Jr,{x:i},a),n&&(i=Dt(i)),wa(o,i)}):L.runKernel(Jr,r,a)}var tt=B({transpose_:L$});function B$(e,t,n){let s=_(e,"labels","confusionMatrix"),r=_(t,"predictions","confusionMatrix");P(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),P(s.rank===1,()=>`Expected the rank of labels to be 1, but got ${s.rank}`),P(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),P(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.`),P(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);let a=ec(me(s,"int32"),n),o=ec(me(r,"int32"),n),i=tt(a),l=et(i,o);return me(l,"int32")}var W$=B({confusionMatrix_:B$}),tu={};We(tu,{assertAndGetBroadcastShape:()=>vt,getBroadcastDims:()=>Gw,getReductionAxes:()=>on});function Gw(e,t){let n=e.length,s=[];for(let r=0;r1&&o===1&&s.unshift(a)}return s}function on(e,t){let n=[];for(let s=0;s1)&&n.unshift(a)}return n}function vt(e,t){let n=[],s=Math.max(e.length,t.length);for(let r=0;rX$,fromPixelsAsync:()=>j$,toPixels:()=>q$});function Py(e,t,n){if(cl(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let s=ta(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 ci(e,t,s,n)}var Fi;function Hw(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(sm(lp,L.backendName)!=null){let f={pixels:e},m={numChannels:t};return L.runKernel(lp,f,m)}let[u,c]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height],p;if(o)p=e.getContext("2d").getImageData(0,0,u,c).data;else if(s||n)p=e.data;else if(a||r||i){if(Fi==null)if(typeof document=="undefined")if(typeof OffscreenCanvas!="undefined"&&typeof OffscreenCanvasRenderingContext2D!="undefined")Fi=new OffscreenCanvas(1,1).getContext("2d");else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");else Fi=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Fi.canvas.width=u,Fi.canvas.height=c,Fi.drawImage(e,0,0,u,c),p=Fi.getImageData(0,0,u,c).data}let d;if(t===4)d=new Int32Array(p);else{let f=u*c;d=new Int32Array(f*t);for(let m=0;m4||a===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${a}`);if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);let o=await n.data(),i=n.dtype==="float32"?255:1,l=new Uint8ClampedArray(r*s*4);for(let u=0;u1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${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?(c[0]=h*i,c[1]=h*i,c[2]=h*i):c[d]=h*i}let p=u*4;l[p+0]=Math.round(c[0]),l[p+1]=Math.round(c[1]),l[p+2]=Math.round(c[2]),l[p+3]=Math.round(c[3])}if(t!=null){t.width=r,t.height=s;let u=t.getContext("2d"),c=new ImageData(l,r,s);u.putImageData(c,0,0)}return n!==e&&n.dispose(),l}var X$=B({fromPixels_:Hw}),Fy={};We(Fy,{prepareAndValidate:()=>jw});function jw(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(It(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 p=0;pp/u),1].slice(0,a);return[l,o,u,c]}var Oy={};We(Oy,{calculateShapes:()=>qw,validateInput:()=>zy,validateUpdateShape:()=>My});function My(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 p=r;pZ$,computeFlatOffset:()=>tP,computeOutShape:()=>J$,getNormalizedAxes:()=>Q$,isSliceContinous:()=>eP,maskToAxes:()=>Y$,parseSliceParams:()=>n6,sliceInfo:()=>nP,startForAxis:()=>e6,startIndicesWithElidedDims:()=>Yw,stopForAxis:()=>t6,stopIndicesWithElidedDims:()=>Jw,stridesForAxis:()=>Qw,stridesWithElidedDims:()=>Xw});var I3=-2,K$=-1;function Z$(e,t,n){let s=e.shape.length;P(s===t.length,()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`),P(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 Y$(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function J$(e,t,n){let s=[];for(let r=0;r0){let h=t[0],f=n+1;c=Yw(o,h,f,s,e),p=Jw(i,h,f,r,e),d=Xw(a,h,f,e)}else for(let h=0;h-1)a[i]=0;else{let l=Kw(t,n,i),u=s[l];e&1<-1)a[i]=Number.MAX_SAFE_INTEGER;else{let l=Kw(t,n,i),u=s[l];e&1<0?o=Number.MIN_SAFE_INTEGER:o=Number.MAX_SAFE_INTEGER);let l=s[r];return o<0&&(o+=l),o=ip(0,o,l-1),o}function t6(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=ip(0,o,l):o=ip(-1,o,l-1),o}function eP(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 tP(e,t){let n=e.length>0?e[e.length-1]:1;for(let s=0;s{P(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:(P(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 nP(e,t,n,s,r,a,o,i,l){let u;if(s==null?(u=new Array(t.length),u.fill(1)):u=s,o!=null&&(o&o-1)!==0)throw new Error("Multiple ellipses in slice is not allowed.");let c=!1,p={dims:u.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:u.slice(),beginMask:r,endMask:a,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:l};for(let A=0;A0?0:-1,d.strides[A]>0?w:w-1];if(b&&d.strides[A]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&d.strides[A]===1;let N=!!(d.beginMask&1<=w)throw Error(`slice index ${d.begin[A]} of dimension ${A} out of bounds.`)}else d.begin[A]=bv(d.begin[A],0,d.strides[A],w,k,C),d.end[A]=bv(d.end[A],1,d.strides[A],w,k,C);let E=d.strides[A]===1&&d.begin[A]===0&&d.end[A]===w;h=h&&E,f=f&&(A===0&&d.strides[A]===1||E)}else h=h&&d.strides[A]===1&&N,f=f&&(A===0&&d.strides[A]===1||N);let R,D=!1;if(d.beginValid&&d.endValid?(R=d.end[A]-d.begin[A],D=!0):b?(R=1,D=!0):N&&w>=0&&(d.strides[A]<0?R=-w:R=w,D=!0),D){let E;R===0||R<0!=d.strides[A]<0?E=0:E=Math.trunc(R/d.strides[A])+(R%d.strides[A]!==0?1:0),g.push(E)}else g.push(-1)}for(let A=0;A=0?y.push(g[b]):b===I3&&y.push(1)}return{finalShapeSparse:y.filter((A,b)=>d.finalShapeGatherIndices[b]!==I3),finalShape:y,isIdentity:h,sliceDim0:f,isSimpleSlice:m,begin:d.begin,end:d.end,strides:d.strides}}function sP(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={};We(ce,{Serializable:()=>s6,SerializationMap:()=>Wi,registerClass:()=>di});var s6=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},Wi=class{constructor(){this.classNameMap={}}static getMap(){return Wi.instance==null&&(Wi.instance=new Wi),Wi.instance}static register(e){Wi.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function di(e){P(e.className!=null,()=>"Class being registered does not have the static className property defined."),P(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),P(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Wi.register(e)}var r6={};We(r6,{TEST_EPSILON_FLOAT16:()=>a6,createVideoElement:()=>dP,encodeStrings:()=>o6,expectArrayBuffersEqual:()=>cP,expectArraysClose:()=>aP,expectArraysEqual:()=>iP,expectNumbersClose:()=>lP,expectPromiseToFail:()=>oP,expectValuesInRange:()=>uP,play:()=>pP,testEpsilon:()=>Ly});var rP=.001,a6=.1;function aP(e,t,n){return n==null&&(n=Ly()),C3(e,t,(s,r)=>By(s,r,n))}function Ly(){return L.backend.floatPrecision()===32?rP:a6}function C3(e,t,n){let s=!0;if((Gn(e)||Gn(t))&&(s=!1),Gn(e)&&Gn(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=ta(e),i=ta(t);if(!mo(o,i))throw new Error(`Arrays have different shapes. Actual: [${o}]. Expected: [${i}]`)}let r=Gn(e)?e:Ji(e),a=Gn(t)?t:Ji(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()),typeof expect!="undefined"&&expect().nothing()}function iP(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Ka(e)||Ka(e[0])||Ka(t)||Ka(t[0])?C3(e,n,(s,r)=>s==r):C3(e,t,(s,r)=>By(s,r,0))}function lP(e,t,n){if(n==null&&(n=Ly()),!By(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`);typeof expect!="undefined"&&expect().nothing()}function By(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function uP(e,t,n){for(let s=0;sn)throw new Error(`Value out of range:${e[s]} low: ${t}, high: ${n}`)}function cP(e,t){let n=new Float32Array(e),s=new Float32Array(t);if(n.length!==s.length)throw new Error(`Expected ArrayBuffer to be of length ${s.length}, but it was ${n.length}`);for(let r=0;r{t.addEventListener("loadeddata",s=>n(t)),t.load()})}async function pP(e){await e.play(),"requestVideoFrameCallback"in e&&await new Promise(t=>{e.requestVideoFrameCallback(t)})}var Wy="3.21.0";function hP(e,t){let n=_(e,"a","add"),s=_(t,"b","add");[n,s]=jt(n,s);let r={a:n,b:s};return L.runKernel(Ta,r)}var le=B({add_:hP});function fP(e,t){let n=_(e,"a","floorDiv"),s=_(t,"b","floorDiv");[n,s]=jt(n,s);let r={a:n,b:s};return L.runKernel(Do,r)}var Bc=B({floorDiv_:fP});function mP(e,t){let n=_(e,"a","div"),s=_(t,"b","div");if([n,s]=jt(n,s),n.dtype==="int32"&&s.dtype==="int32")return Bc(n,s);let r={a:n,b:s},a={};return L.runKernel(No,r,a)}var ge=B({div_:mP});function gP(e,t){let n=_(e,"a","mul"),s=_(t,"b","mul");[n,s]=jt(n,s);let r={a:n,b:s};return L.runKernel(Ho,r)}var M=B({mul_:gP});function yP(e){let t=_(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return L.runKernel(Rp,n)}else{let n={x:t};return L.runKernel(dl,n)}}var rn=B({abs_:yP});function AP(e){let n={x:_(e,"x","acos")};return L.runKernel(gc,n)}var Vy=B({acos_:AP});function xP(e){let n={x:_(e,"x","acosh")};return L.runKernel(yc,n)}var Uy=B({acosh_:xP});function bP(e){P(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),P(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((r,a)=>_(r,`tensors${a}`,"addN")),n=t[0];t.forEach(r=>{if(r.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!mo(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let s=t;return L.runKernel(go,s)}var a0=B({addN_:bP});function vP(e,t=null,n=!1){let r={x:_(e,"x","all","bool")},a={axis:t,keepDims:n};return L.runKernel(Ac,r,a)}var o0=B({all_:vP});function wP(e,t=null,n=!1){let r={x:_(e,"x","any","bool")},a={axis:t,keepDims:n};return L.runKernel(xc,r,a)}var fp=B({any_:wP});function kP(e,t=0){let s={x:_(e,"x","argMax")},r={axis:t};return L.runKernel(yo,s,r)}var Ps=B({argMax_:kP});function SP(e,t=0){let s={x:_(e,"x","argMin")},r={axis:t};return L.runKernel(bc,s,r)}var Gy=B({argMin_:SP});function IP(e){let n={x:_(e,"x","asin")};return L.runKernel(vc,n)}var Hy=B({asin_:IP});function CP(e){let n={x:_(e,"x","asinh")};return L.runKernel(wc,n)}var jy=B({asinh_:CP});function TP(e){let n={x:_(e,"x","atan")};return L.runKernel(kc,n)}var qy=B({atan_:TP});function NP(e,t){let n=_(e,"a","atan2"),s=_(t,"b","atan2");[n,s]=jt(n,s);let r={a:n,b:s};return L.runKernel(pl,r)}var Xy=B({atan2_:NP});function EP(e){let n={x:_(e,"x","atanh")};return L.runKernel(Sc,n)}var Ky=B({atanh_:EP});function RP(e,t,n,s,r="NHWC",a){let o=e[3],i=[...t,o],l=u6(r);return Qp(e,i,n,a,s,null,null,l)}function i6(e,t,n,s,r,a,o="channelsLast"){let[i,l]=im(t),u;if(o==="channelsLast")u=[i,l,e[3],e[3]];else if(o==="channelsFirst")u=[i,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return Qp(e,u,n,s,r,a,!1,o)}function _P(e,t,n,s,r,a,o="NDHWC"){let[i,l,u]=T3(t),c,p;if(o==="NDHWC")p="channelsLast",c=[i,l,u,e[4],e[4]];else if(o==="NCDHW")p="channelsFirst",c=[i,l,u,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return l6(e,c,n,s,r,!1,p,a)}function Qp(e,t,n,s,r,a,o=!1,i="channelsLast"){let[l,u,c,p]=[-1,-1,-1,-1];if(i==="channelsLast")[l,u,c,p]=e;else if(i==="channelsFirst")[l,p,u,c]=e;else throw new Error(`Unknown dataFormat ${i}`);let[d,h,,f]=t,[m,g]=im(n),[y,x]=im(s),A=Xu(d,y),b=Xu(h,x),{padInfo:w,outHeight:k,outWidth:C}=PP(r,u,c,m,g,A,b,a,i),N=o?f*p:f,R;return i==="channelsFirst"?R=[l,N,k,C]:i==="channelsLast"&&(R=[l,k,C,N]),{batchSize:l,dataFormat:i,inHeight:u,inWidth:c,inChannels:p,outHeight:k,outWidth:C,outChannels:N,padInfo:w,strideHeight:m,strideWidth:g,filterHeight:d,filterWidth:h,effectiveFilterHeight:A,effectiveFilterWidth:b,dilationHeight:y,dilationWidth:x,inShape:e,outShape:R,filterShape:t}}function l6(e,t,n,s,r,a=!1,o="channelsLast",i){let[l,u,c,p,d]=[-1,-1,-1,-1,-1];if(o==="channelsLast")[l,u,c,p,d]=e;else if(o==="channelsFirst")[l,d,u,c,p]=e;else throw new Error(`Unknown dataFormat ${o}`);let[h,f,m,,g]=t,[y,x,A]=T3(n),[b,w,k]=T3(s),C=Xu(h,b),N=Xu(f,w),R=Xu(m,k),{padInfo:D,outDepth:E,outHeight:$,outWidth:S}=FP(r,u,c,p,y,x,A,C,N,R,i),F=a?g*d:g,z;return o==="channelsFirst"?z=[l,F,E,$,S]:o==="channelsLast"&&(z=[l,E,$,S,F]),{batchSize:l,dataFormat:o,inDepth:u,inHeight:c,inWidth:p,inChannels:d,outDepth:E,outHeight:$,outWidth:S,outChannels:F,padInfo:D,strideDepth:y,strideHeight:x,strideWidth:A,filterDepth:h,filterHeight:f,filterWidth:m,effectiveFilterDepth:C,effectiveFilterHeight:N,effectiveFilterWidth:R,dilationDepth:b,dilationHeight:w,dilationWidth:k,inShape:e,outShape:z,filterShape:t}}function DP(e,t,n,s,r){s==null&&(s=Zy(e,t,n));let a=e[0],o=e[1],i=qi((a-t+2*s)/n+1,r),l=qi((o-t+2*s)/n+1,r);return[i,l]}function $P(e,t,n,s,r,a){r==null&&(r=Zy(e,t,s));let o=e[0],i=e[1],l=e[2],u=qi((o-t+2*r)/s+1,a),c=qi((i-t+2*r)/s+1,a),p=qi((l-t+2*r)/s+1,a);return[u,c,p,n]}function Zy(e,t,n,s=1){let r=Xu(t,s);return Math.floor((e[0]*(n-1)-n+r)/2)}function im(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function T3(e){return typeof e=="number"?[e,e,e]:e}function Xu(e,t){return t<=1?e:e+(e-1)*(t-1)}function PP(e,t,n,s,r,a,o,i,l){let u,c,p;if(typeof e=="number"){u={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let h=DP([t,n],a,s,e,i);c=h[0],p=h[1]}else if(e==="same"){c=Math.ceil(t/s),p=Math.ceil(n/r);let d=Math.max(0,(c-1)*s+a-t),h=Math.max(0,(p-1)*r+o-n),f=Math.floor(d/2),m=d-f,g=Math.floor(h/2),y=h-g;u={top:f,bottom:m,left:g,right:y,type:"SAME"}}else if(e==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-a+1)/s),p=Math.ceil((n-o+1)/r);else if(typeof e=="object"){let d=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];u={top:d,bottom:h,left:f,right:m,type:d===0&&h===0&&f===0&&m===0?"VALID":"EXPLICIT"},c=qi((t-a+d+h)/s+1,i),p=qi((n-o+f+m)/r+1,i)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outHeight:c,outWidth:p}}function FP(e,t,n,s,r,a,o,i,l,u,c){let p,d,h,f;if(typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let g=$P([t,n,s,1],i,1,r,e,c);d=g[0],h=g[1],f=g[2]}else if(e==="same"){d=Math.ceil(t/r),h=Math.ceil(n/a),f=Math.ceil(s/o);let m=(d-1)*r+i-t,g=(h-1)*a+l-n,y=(f-1)*o+u-s,x=Math.floor(m/2),A=m-x,b=Math.floor(g/2),w=g-b,k=Math.floor(y/2),C=y-k;p={top:b,bottom:w,left:k,right:C,front:x,back:A,type:"SAME"}}else if(e==="valid")p={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},d=Math.ceil((t-i+1)/r),h=Math.ceil((n-l+1)/a),f=Math.ceil((s-u+1)/o);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:d,outHeight:h,outWidth:f}}function qi(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 ao(e){let[t,n,s]=im(e);return t===1&&n===1&&s===1}function aa(e,t){return ao(e)||ao(t)}function u6(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function us(e,t,n){if(n!=null){if(typeof t=="string")throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if(typeof t=="number")P(Yu(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);else if(typeof t=="object")t.forEach(s=>{s.forEach(r=>{P(Yu(r),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${r}.`)})});else throw Error(`Error in ${e}: Unknown padding parameter: ${t}`)}}function OP(e,t){let s={x:_(e,"x","reshape","string_or_numeric")},r={shape:t};return L.runKernel(zl,s,r)}var W=B({reshape_:OP});function MP(e,t,n,s,r){let a=_(e,"x","avgPool","float32"),o=1;P(aa(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=W(a,[1,a.shape[0],a.shape[1],a.shape[2]])),P(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),us("avgPool",s,r);let u={x:i},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r},p=L.runKernel(Ao,u,c);return p=me(p,a.dtype),l?W(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var eh=B({avgPool_:MP});function zP(e,t,n,s,r,a="NDHWC"){let o=_(e,"x","avgPool3d","float32"),i=o,l=!1;o.rank===4&&(l=!0,i=W(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),P(i.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`),P(a==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),us("avgPool3d",s,r);let u={x:i},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},p=L.runKernel(Np,u,c);return p=me(p,i.dtype),l?W(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var Yy=B({avgPool3d_:zP});function LP(e,t=0){P(e.length>=1,()=>"Pass at least one tensor to concat");let n=hp(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 Hn(n[0]);let s=n,r={axis:t};return L.runKernel(fl,s,r)}var ut=B({concat_:LP});function BP(e){let n={x:_(e,"x","sigmoid","float32")};return L.runKernel(ni,n)}var Mn=B({sigmoid_:BP});function WP(e,t,n){let s=_(e,"x","slice","string_or_numeric");if(s.rank===0)throw new Error("Slicing scalar is not possible");let r={x:s},a={begin:t,size:n};return L.runKernel(Ul,r,a)}var Oe=B({slice_:WP});function VP(e){let n={x:_(e,"x","tanh","float32")};return L.runKernel(li,n)}var tl=B({tanh_:VP});function UP(e,t,n,s,r,a){let o=_(e,"forgetBias","basicLSTMCell"),i=_(t,"lstmKernel","basicLSTMCell"),l=_(n,"lstmBias","basicLSTMCell"),u=_(s,"data","basicLSTMCell"),c=_(r,"c","basicLSTMCell"),p=_(a,"h","basicLSTMCell"),d=ut([u,p],1),h=et(d,i),f=le(h,l),m=f.shape[0],g=f.shape[1]/4,y=[m,g],x=Oe(f,[0,0],y),A=Oe(f,[0,g],y),b=Oe(f,[0,g*2],y),w=Oe(f,[0,g*3],y),k=le(M(Mn(x),tl(A)),M(c,Mn(le(o,b)))),C=M(tl(k),Mn(w));return[k,C]}var c6=B({basicLSTMCell_:UP});function GP(e,t,n){let s=_(e,"x","batchToSpaceND"),r=t.reduce((i,l)=>i*l);P(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),P(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),P(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 L.runKernel(hl,a,o)}var th=B({batchToSpaceND_:GP});function HP(e){let t;return e.rank===0||e.rank===1?t=W(e,[1,1,1,e.size]):e.rank===2?t=W(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=W(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function jP(e,t,n,s,r,a){a==null&&(a=.001);let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),u;r!=null&&(u=_(r,"scale","batchNorm"));let c;s!=null&&(c=_(s,"offset","batchNorm")),P(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),P(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),P(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let d={x:HP(o),scale:u,offset:c,mean:i,variance:l},h={varianceEpsilon:a},f=L.runKernel($o,d,h);return W(f,o.shape)}var Wc=B({batchNorm_:jP});function qP(e,t,n,s,r,a){let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),u;r!=null&&(u=_(r,"scale","batchNorm"));let c;return s!=null&&(c=_(s,"offset","batchNorm")),P(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),P(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),P(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),c!=null&&P(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`),Wc(o,i,l,c,u,a)}var Jy=B({batchNorm2d_:qP});function XP(e,t,n,s,r,a){let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),u;r!=null&&(u=_(r,"scale","batchNorm"));let c;return s!=null&&(c=_(s,"offset","batchNorm")),P(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),P(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),P(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),c!=null&&P(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`),Wc(o,i,l,c,u,a)}var Qy=B({batchNorm3d_:XP});function KP(e,t,n,s,r,a){let o=_(e,"x","batchNorm"),i=_(t,"mean","batchNorm"),l=_(n,"variance","batchNorm"),u;r!=null&&(u=_(r,"scale","batchNorm"));let c;return s!=null&&(c=_(s,"offset","batchNorm")),P(o.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),P(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),P(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),c!=null&&P(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`),Wc(o,i,l,c,u,a)}var eA=B({batchNorm4d_:KP});function ZP(e,t,n){let s=_(e,"x","bincount"),r=_(t,"weights","bincount");P(s.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`),P(n>=0,()=>`size must be non-negative, but got ${n}.`),P(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 L.runKernel(Pm,a,o)}var tA=B({bincount_:ZP});function YP(e,t){let n=_(e,"s0","broadcastArgs","int32"),s=_(t,"s1","broadcastArgs","int32");if(n.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(s.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${s.rank}`);let r={s0:n,s1:s};return L.runKernel(Fm,r)}var d6=B({broadcastArgs_:YP});function JP(e,t){let n=_(e,"broadcastTo","x"),s=n.shape;if(t.some(u=>!(u>0)||u%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.lengthn.rank){let u=n.shape.slice();for(;u.length=0;u--)if(r[u]===t[u])a[u]=1;else if(n.shape[u]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);if(a.map((u,c)=>u>1?c:-1).filter(u=>u>=0).length===0)return Hn(n);let i={x:n},l={reps:a};return L.runKernel(Ea,i,l)}var Xi=B({broadcastTo_:JP});function QP(e){let n={x:_(e,"x","ceil","float32")};return L.runKernel(vo,n)}var nA=B({ceil_:QP});function zr(e,t,n){let s={shape:e,value:t,dtype:n};return L.runKernel(Cc,{},s)}function eF(e,t,n){let s=_(e,"x","clipByValue");if(P(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`),t===n)return zr(s.shape,t,s.dtype);let r={x:s},a={clipValueMin:t,clipValueMax:n};return L.runKernel(Na,r,a)}var bs=B({clipByValue_:eF});function tF(e){return ut(e,0)}var sA=B({concat1d_:tF});function nF(e,t){return ut(e,t)}var nu=B({concat2d_:nF});function sF(e,t){return ut(e,t)}var rA=B({concat3d_:sF});function rF(e,t){return ut(e,t)}var aA=B({concat4d_:rF});function aF(e,t,n,s,r="NHWC",a=[1,1],o){let i=_(e,"x","conv2d","float32"),l=_(t,"filter","conv2d","float32"),u=i,c=!1;i.rank===3&&(c=!0,u=W(i,[1,i.shape[0],i.shape[1],i.shape[2]])),P(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),P(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),us("conv2d",s,o);let p=r==="NHWC"?u.shape[3]:u.shape[1];P(p===l.shape[2],()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${l.shape[2]}.`),P(aa(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let d={x:u,filter:l},h={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},f=L.runKernel(wo,d,h);return c?W(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var ka=B({conv2d_:aF});function oF(e,t,n,s,r="NWC",a=1,o){let i=_(e,"x","conv1d"),l=_(t,"filter","conv1d"),u=i,c=!1;i.rank===2&&(c=!0,u=W(i,[1,i.shape[0],i.shape[1]])),P(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),P(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),us("conv1d",s,o),P(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),P(aa(n,a),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`),P(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);let p=W(l,[1,l.shape[0],l.shape[1],l.shape[2]]),d=W(u,[u.shape[0],1,u.shape[1],u.shape[2]]),g=ka(d,p,[1,n],s,"NHWC",[1,a],o);return c?W(g,[g.shape[2],g.shape[3]]):W(g,[g.shape[0],g.shape[2],g.shape[3]])}var i0=B({conv1d_:oF});function iF(e,t,n,s,r,a="NHWC",o){P(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let i=e,l=t,u=!1;t.rank===3&&(u=!0,l=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]),i=[1,e[0],e[1],e[2]]),P(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),P(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),P(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);let c=a==="NHWC"?i[3]:i[1],p=a==="NHWC"?l.shape[3]:l.shape[1];P(c===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[2]}.`),P(p===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[3]}.`),us("conv2dDerInput",r,o);let d={dy:l,filter:n},h={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,inputShape:i},f=L.runKernel(ko,d,h);return u?W(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var oA=B({conv2DBackpropInput_:iF});function lF(e,t,n,s,r,a){let o=_(e,"x","conv2dTranspose"),i=_(t,"filter","conv2dTranspose");return oA(n,o,i,s,r,"NHWC",a)}var l0=B({conv2dTranspose_:lF});function uF(e,t,n,s,r="NDHWC",a=[1,1,1]){let o=_(e,"x","conv3d"),i=_(t,"filter","conv3d"),l=o,u=!1;o.rank===4&&(u=!0,l=W(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),P(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),P(i.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`),P(l.shape[4]===i.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${i.shape[3]}.`),P(aa(n,a),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),P(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`);let c={x:l,filter:i},p={strides:n,pad:s,dataFormat:r,dilations:a},d=L.runKernel(_p,c,p);return u?W(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var iA=B({conv3d_:uF});function cF(e,t,n,s,r){P(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=W(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),a=[1,e[0],e[1],e[2],e[3]]);let l=a[4],u=o.shape[4];P(a.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`),P(o.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),P(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),P(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),P(u===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${n.shape[4]}.`);let c={dy:o,filter:n},p={pad:r,strides:s,inputShape:a},d=L.runKernel(zm,c,p);return i?W(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var p6=B({conv3DBackpropInput_:cF});function dF(e,t,n,s,r){let a=_(e,"x","conv3dTranspose"),o=_(t,"filter","conv3dTranspose");return p6(n,a,o,s,r)}var lA=B({conv3dTranspose_:dF});function pF(e){let n={x:_(e,"x","cos","float32")};return L.runKernel(So,n)}var nh=B({cos_:pF});function hF(e){let n={x:_(e,"x","cosh","float32")};return L.runKernel(Io,n)}var u0=B({cosh_:hF});function fF(e,t=0,n=!1,s=!1){let a={x:_(e,"x","cumprod")},o={axis:t,exclusive:n,reverse:s};return L.runKernel(ml,a,o)}var mp=B({cumprod_:fF});function mF(e,t=0,n=!1,s=!1){let a={x:_(e,"x","cumsum")},o={axis:t,exclusive:n,reverse:s};return L.runKernel(Co,a,o)}var c0=B({cumsum_:mF});function gF(e,t,n,s=!1){let r=_(e,"x","denseBincount"),a=_(t,"weights","denseBincount");P(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),P(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),P(n>=0,()=>`size must be non-negative, but got ${n}.`),P(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 L.runKernel(Lm,o,i)}var h6=B({denseBincount_:gF});function yF(e,t,n="NHWC"){let s=_(e,"x","depthToSpace","float32"),r=n==="NHWC"?s.shape[1]:s.shape[2],a=n==="NHWC"?s.shape[2]:s.shape[3],o=n==="NHWC"?s.shape[3]:s.shape[1];P(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),P(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying ${r} and ${t} for depthToSpace with input shape ${s.shape}`),P(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying ${a} and ${t} for depthToSpace with input shape ${s.shape}`),P(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 L.runKernel(yl,i,l)}var uA=B({depthToSpace_:yF});function AF(e,t,n,s,r="NHWC",a=[1,1],o){let i=_(e,"x","depthwiseConv2d","float32"),l=_(t,"filter","depthwiseConv2d","float32"),u=i,c=!1;i.rank===3&&(c=!0,u=W(i,[1,i.shape[0],i.shape[1],i.shape[2]])),P(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),P(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`);let p=r==="NHWC"?u.shape[3]:u.shape[1];P(p===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${p}) must match the inChannels dimension in filter ${l.shape[2]}.`),us("depthwiseConv2d",s,o);let d={x:u,filter:l},h={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o},f=L.runKernel(To,d,h);return c?W(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Vc=B({depthwiseConv2d_:AF});function xF(e){let n={x:_(e,"x","diag")};return L.runKernel(Vm,n)}var f6=B({diag_:xF});function bF(e,t,n,s,r=[1,1],a="NHWC"){let o=_(e,"x","dilation2d"),i=_(t,"filter","dilation2d");P(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),P(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),P(a==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);let l=o,u=!1;o.rank===3&&(l=W(o,[1,o.shape[0],o.shape[1],o.shape[2]]),u=!0);let c={x:l,filter:i},p={strides:n,pad:s,dilations:r},d=L.runKernel(Dp,c,p);return u?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var cA=B({dilation2d_:bF});function vF(e,t){let n=_(e,"a","equal","string_or_numeric"),s=_(t,"b","equal","string_or_numeric");[n,s]=jt(n,s),vt(n.shape,s.shape);let r={a:n,b:s};return L.runKernel(Al,r)}var Fs=B({equal_:vF});function wF(e,t,n){let s=_(t,"a","where"),r=_(n,"b","where"),a=_(e,"condition","where","bool"),o=vt(vt(a.shape,s.shape),r.shape),i=Xi(a,o),l=Xi(s,o),u=Xi(r,o),c={condition:i,t:l,e:u};return L.runKernel(Vl,c)}var qn=B({where_:wF});function kF(e){let n={x:_(e,"x","zerosLike")};return L.runKernel(Jl,n)}var ct=B({zerosLike_:kF});function SF(e,t){let n=_(e,"a","div"),s=_(t,"b","div");[n,s]=jt(n,s);let r=ge(n,s),a=ct(r),o=Fs(s,a);return qn(o,a,r)}var dA=B({divNoNan_:SF});function IF(e,t){let n=_(e,"t1","dot"),s=_(t,"t2","dot");P((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(P(r===a,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${a}.`),n.rank===1&&s.rank===1){let o=W(n,[1,-1]),i=W(s,[-1,1]),l=et(o,i);return W(l,[])}else if(n.rank===1&&s.rank===2){let o=W(n,[1,-1]),i=W(s,[s.shape[0],s.shape[1]]),l=et(o,i);return W(l,[l.size])}else if(n.rank===2&&s.rank===1){let o=W(s,[-1,1]),i=et(n,o);return W(i,[i.size])}else{let o=W(s,[s.shape[0],s.shape[1]]);return et(n,o)}}var pA=B({dot_:IF});function CF(e,...t){let n=t.map((r,a)=>_(r,`tensors${a}`,"einsum")),s={equation:e};return L.runKernel($p,n,s)}var m6=B({einsum_:CF});function TF(e){let n={x:_(e,"x","elu","float32")};return L.runKernel(Eo,n)}var Uc=B({elu_:TF});function NF(e){let t=_(e,"x","erf");P(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=me(t,"float32"));let n={x:t};return L.runKernel(Ic,n)}var hA=B({erf_:NF});function fA(e,t){for(let n=0;ne[a]);return[n,r]}function nl(e,t){let n=t.map(s=>1);return g6(e,n,t)}function EF(e,t,n){P(fA(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function A6(e,t){if(fA(e,t))return null;let n=[];for(let s=0;sn.push(s)),n}function mA(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function RF(e,t){let n=[];for(let s=t-e;s"Axis must be <= rank of the tensor");let s={input:n},r={dim:t};return L.runKernel(xl,s,r)}var Ft=B({expandDims_:BF});function WF(e){let n={x:_(e,"x","expm1")};return L.runKernel(bl,n)}var yA=B({expm1_:WF});function VF(e,t){let n=_(e,"x","tile","string_or_numeric");P(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 L.runKernel(Ea,s,r)}var As=B({tile_:VF});function UF(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}.`),P(Yu(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=a,i=!1;a.rank===3&&(i=!0,o=W(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let l={x:o},u={depthRadius:t,bias:n,alpha:s,beta:r},c=L.runKernel(Fp,l,u);return i?W(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var vA=B({localResponseNormalization_:eO});function tO(e){let n={x:_(e,"x","log","float32")};return L.runKernel(Mo,n)}var Ms=B({log_:tO});function nO(e){let n={x:_(e,"x","log1p")};return L.runKernel(Ec,n)}var rh=B({log1p_:nO});function sO(e){return P(to(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let s=_(t,"x","tf.grad","string_or_numeric"),r=n!=null?_(n,"dy","tf.grad"):null;return L.tidy(()=>{let{value:a,grads:o}=L.gradients(()=>e(s),[s],r);return r!=null&&ls(a.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),h0(o),o[0]})}}function rO(e){return P(to(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{P(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let s=hp(t,"args","tf.grads","string_or_numeric"),r=n!=null?_(n,"dy","tf.grads"):null;return L.tidy(()=>{let{value:a,grads:o}=L.gradients(()=>e(...s),s,r);return r!=null&&ls(a.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),h0(o),o})}}function aO(e){return P(to(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{P(t instanceof st,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),P(n==null||n instanceof st,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:s,value:r}=L.gradients(()=>e(t),[t],n);return h0(s),{grad:s[0],value:r}}}function oO(e){return P(to(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{P(Array.isArray(t)&&t.every(r=>r instanceof st),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),P(n==null||n instanceof st,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let s=L.gradients(()=>e(...t),t,n);return n!=null&&ls(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),h0(s.grads),s}}function v6(e,t){P(to(e),()=>"The f passed in variableGrads(f) must be a function"),P(t==null||Array.isArray(t)&&t.every(u=>u instanceof dp),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let u in L.registeredVariables)t.push(L.registeredVariables[u])}let s=n?t.filter(u=>!u.trainable):null,r=t.length;t=t.filter(u=>u.trainable),P(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);let a=!0,{value:o,grads:i}=L.gradients(e,t,null,a);P(i.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),P(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);let l={};return t.forEach((u,c)=>{i[c]!=null&&(l[u.name]=i[c])}),s!=null&&s.forEach(u=>l[u.name]=null),{value:o,grads:l}}function na(e){return L.customGrad(e)}function h0(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 iO(e){let n={x:_(e,"x","softplus")};return L.runKernel(Oc,n)}var su=B({softplus_:iO});function lO(e){let t=_(e,"x","logSigmoid");return na(s=>({value:Dt(su(Dt(s))),gradFunc:o=>M(o,Mn(Dt(s)))}))(t)}var wA=B({logSigmoid_:lO});function uO(e,t){let n=_(e,"a","sub"),s=_(t,"b","sub");[n,s]=jt(n,s);let r={a:n,b:s};return L.runKernel(ii,r)}var ye=B({sub_:uO});function cO(e,t=-1){let n=_(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return na((r,a)=>{let i=yn(r,t,!0),l=ye(r,i),u=ye(me(l,"float32"),Ms(ve(Os(l),t,!0)));return a([u]),{value:u,gradFunc:(p,d)=>{let[h]=d,f=!0,m=Os(h);return ye(p,M(ve(p,t,f),m))}}})(n)}var f0=B({logSoftmax_:cO});function dO(e,t=null,n=!1){let s=_(e,"x","logSumExp"),r=yr(t,s.shape),a=yn(s,r,!0),o=ye(s,a),i=Os(o),l=ve(i,r),u=Ms(l),c=le(W(a,u.shape),u);if(n){let p=nl(c.shape,r);return W(c,p)}return c}var m0=B({logSumExp_:dO});function pO(e,t){let n=_(e,"a","logicalAnd","bool"),s=_(t,"b","logicalAnd","bool");vt(n.shape,s.shape);let r={a:n,b:s};return L.runKernel(Nl,r)}var gr=B({logicalAnd_:pO});function hO(e){let n={x:_(e,"x","logicalNot","bool")};return L.runKernel(El,n)}var ah=B({logicalNot_:hO});function fO(e,t){let n=_(e,"a","logicalOr","bool"),s=_(t,"b","logicalOr","bool");vt(n.shape,s.shape);let r={a:n,b:s};return L.runKernel(Rc,r)}var g0=B({logicalOr_:fO});function mO(e,t){let n=_(e,"a","logicalXor","bool"),s=_(t,"b","logicalXor","bool");return vt(n.shape,s.shape),gr(g0(e,t),ah(gr(e,t)))}var kA=B({logicalXor_:mO}),Nf=2147483648;function gO(e,t,n="left"){let s=_(e,"sortedSequence","searchSorted"),r=_(t,"values","searchSorted"),a=s.shape[s.shape.length-1],o=r.shape[r.shape.length-1],i=W(s,[-1,a]),l=W(r,[-1,o]);if(i.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(i.shape[0]!==l.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(It(l.shape)>=Nf)throw new Error(`values tensor size must less than ${Nf}`);if(i.shape[1]>=Nf)throw new Error(`trailing dim_size must less than ${Nf} for int32 output type, was ${i.shape[1]}`);let u={sortedSequence:i,values:l},c={side:n};return L.runKernel(n0,u,c)}var y0=B({searchSorted_:gO});function w6(e,t){return y0(e,t,"left")}function yO(e,t,n,s,r){let a=_(e,"x","maxPool"),o=1,i=a,l=!1;a.rank===3&&(l=!0,i=W(a,[1,a.shape[0],a.shape[1],a.shape[2]])),P(i.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),P(aa(n,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),us("maxPool",s,r);let u={x:i},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r},p=L.runKernel(Bo,u,c);return l?W(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var oh=B({maxPool_:yO});function AO(e,t=[1,1,1],n,s,r,a="NDHWC"){let o=_(e,"x","maxPool3d"),i=o,l=!1;o.rank===4&&(l=!0,i=W(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),P(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),P(a==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),us("maxPool3d",s,r);let u={x:i},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},p=L.runKernel(Op,u,c);return l?W(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var SA=B({maxPool3d_:AO});function xO(e,t,n,s,r=!1){let o={x:_(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:s,includeBatchInIndex:r},l=L.runKernel(Zm,o,i);return{result:l[0],indexes:l[1]}}var k6=B({maxPoolWithArgmax_:xO});function bO(e,t){let n=_(e,"a","maximum"),s=_(t,"b","maximum");[n,s]=jt(n,s),n.dtype==="bool"&&(n=me(n,"int32"),s=me(s,"int32")),vt(n.shape,s.shape);let r={a:n,b:s};return L.runKernel(Lo,r)}var oa=B({maximum_:bO});function vO(e,t=null,n=!1){let r={x:_(e,"x","mean")},a={axis:t,keepDims:n};return L.runKernel(Wo,r,a)}var Wt=B({mean_:vO});function Vt(e,t="float32"){if(t==="complex64"){let s=Vt(e,"float32"),r=Vt(e,"float32");return wa(s,r)}let n=_m(It(e),t);return L.makeTensor(n,e,t)}function Ds(e,t="float32"){if(t==="complex64"){let s=Ds(e,"float32"),r=Vt(e,"float32");return wa(s,r)}let n=yy(It(e),t);return L.makeTensor(n,e,t)}function S6(e,t,{indexing:n="xy"}={}){if(n!=="xy"&&n!=="ij")throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(e===void 0)return[];let s=_(e,"x","meshgrid",e instanceof st?e.dtype:"float32");if(t===void 0)return[s];let r=_(t,"y","meshgrid",t instanceof st?t.dtype:"float32"),a=It(s.shape),o=It(r.shape);return n==="xy"?(s=W(s,[1,-1]),r=W(r,[-1,1]),[et(Ds([o,1],s.dtype),s),et(r,Ds([1,a],r.dtype))]):(s=W(s,[-1,1]),r=W(r,[1,-1]),[et(s,Ds([1,o],s.dtype)),et(Ds([a,1],r.dtype),r)])}function wO(e,t){let n=_(e,"a","minimum"),s=_(t,"b","minimum");[n,s]=jt(n,s),n.dtype==="bool"&&(n=me(n,"int32"),s=me(s,"int32")),vt(n.shape,s.shape);let r={a:n,b:s};return L.runKernel(Uo,r)}var qc=B({minimum_:wO});function kO(e,t,n){P(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let s=_(e,"x","mirrorPad");if(s.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");P(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."),P(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 L.runKernel(Go,o,a)}var IA=B({mirrorPad_:kO});function SO(e,t){let n=_(e,"a","mod"),s=_(t,"b","mod");[n,s]=jt(n,s);let r={a:n,b:s};return L.runKernel(_c,r)}var ru=B({mod_:SO});function IO(e,t=null,n=!1){e=_(e,"x","moments");let s=yr(t,e.shape),r=Wt(e,s,n),a=r.shape;n||(a=nl(r.shape,s));let o=bt(ye(me(e,"float32"),W(r,a))),i=Wt(o,s,n);return{mean:r,variance:i}}var ih=B({moments_:IO});function CO(e,t,n,s){let r=_(t,"data","multiRNNCell"),a=hp(n,"c","multiRNNCell"),o=hp(s,"h","multiRNNCell"),i=r,l=[];for(let p=0;p2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);n=n||Math.random();let l={logits:o===1?W(r,[1,-1]):r},u={numSamples:t,seed:n,normalized:s},c=L.runKernel(Ym,l,u);return o===1?W(c,[c.size]):c}var C6=B({multinomial_:TO});function NO(e,t){let n=_(e,"a","notEqual","string_or_numeric"),s=_(t,"b","notEqual","string_or_numeric");[n,s]=jt(n,s),vt(n.shape,s.shape);let r={a:n,b:s};return L.runKernel(_l,r)}var sl=B({notEqual_:NO});function EO(e){let n={x:_(e,"x","onesLike")};return L.runKernel(Pl,n)}var zs=B({onesLike_:EO});function RO(e,t){let n=_(e,"v1","outerProduct"),s=_(t,"v2","outerProduct");P(n.rank===1&&s.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${s.rank}.`);let r=W(n,[-1,1]),a=W(s,[1,-1]);return et(r,a)}var T6=B({outerProduct_:RO});function _O(e,t,n=0){let s=_(e,"x","pad");if(s.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let r={paddings:t,constantValue:n},a={x:s};return L.runKernel(jo,a,r)}var tr=B({pad_:_O});function DO(e,t,n=0){return P(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),tr(e,[t],n)}var N6=B({pad1d_:DO});function $O(e,t,n=0){return P(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),tr(e,t,n)}var E6=B({pad2d_:$O});function PO(e,t,n=0){return P(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),tr(e,t,n)}var R6=B({pad3d_:PO});function FO(e,t,n=0){return P(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),tr(e,t,n)}var _6=B({pad4d_:FO});function OO(e,t,n){let s=_(e,"x","spaceToBatchND");P(s.rank>=1+t.length,()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`),P(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),P(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 L.runKernel(Hl,r,a)}var lh=B({spaceToBatchND_:OO});function MO(e,t,n,s,r,a,o){r==null&&(r=[1,1]),a==null&&(a=1),s===0&&(s="valid");let i=_(e,"x","maxPool"),l=i,u=!1;i.rank===3&&(u=!0,l=W(i,[1,i.shape[0],i.shape[1],i.shape[2]])),P(aa(a,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${r}'`);let c=i6(l.shape,t,a,r,s),p=[c.dilationHeight,c.dilationWidth],d;s==="same"?d=LO([c.filterHeight,c.filterWidth],p):d=[[0,0],[0,0]];let h=p[0]===1&&p[1]===1,[f,m]=zO([c.inHeight,c.inWidth],p,d),g=h?s:"valid",y=h?l:lh(l,p,f),A=(n==="avg"?()=>eh(y,t,a,g,o):()=>oh(y,t,a,g,o))(),b=h?A:th(A,p,m);return u?W(b,[b.shape[1],b.shape[2],b.shape[3]]):b}function zO(e,t,n){let s=n.map(c=>c[0]),r=n.map(c=>c[1]),a=e.concat(s,r),o=t.map((c,p)=>(c-a[p]%c)%c),i=r.map((c,p)=>c+o[p]),l=t.map((c,p)=>[s[p],i[p]]),u=t.map((c,p)=>[0,o[p]]);return[l,u]}function LO(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 CA=B({pool_:MO});function BO(e,t){let n=_(e,"x","prelu"),s=_(t,"alpha","prelu"),r={x:n,alpha:s};return L.runKernel(Xo,r)}var uh=B({prelu_:BO});function WO(e,t=null,n=!1){let s=_(e,"x","prod");s.dtype==="bool"&&(s=me(s,"int32"));let r={x:s},a={axis:t,keepDims:n};return L.runKernel(Ko,r,a)}var TA=B({prod_:WO});function VO(e,t,n,s){let r=e.map((c,p)=>_(c,`tensors${p}`,"raggedGather","int32")),a=_(t,"paramsDenseValues","raggedGather"),o=_(n,"indices","raggedGather","int32"),i={paramsNestedSplits:r,paramsDenseValues:a,indices:o},l={outputRaggedRank:s},u=L.runKernel(Jm,i,l);return{outputNestedSplits:u.slice(0,u.length-1),outputDenseValues:u[u.length-1]}}var D6=B({raggedGather_:VO});function UO(e,t,n,s,r){let a=_(e,"shape","raggedTensorToTensor","int32"),o=_(t,"values","raggedTensorToTensor"),i=_(n,"defaultValue","raggedTensorToTensor",o.dtype),l=s.map((p,d)=>_(p,`tensors${d}`,"raggedTensorToTensor","int32")),u={shape:a,values:o,defaultValue:i,rowPartitionTensors:l},c={rowPartitionTypes:r};return L.runKernel(Qm,u,c)}var $6=B({raggedTensorToTensor_:UO});function GO(e,t,n){let s=It(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}},HO=class{constructor(e,t,n,s){this.alpha=e,this.beta=1/t,this.dtype=n;let r=s||Math.random();this.randu=NA.alea(r.toString()),this.randn=new EA(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=NA.alea(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function qO(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 HO(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}.`),Js(t,0)}var M6=B({reverse1d_:tM});function nM(e,t){let n=_(e,"x","reverse");return P(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),Js(n,t)}var z6=B({reverse2d_:nM});function sM(e,t){let n=_(e,"x","reverse");return P(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),Js(n,t)}var L6=B({reverse3d_:sM});function rM(e,t){let n=_(e,"x","reverse");return P(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),Js(n,t)}var B6=B({reverse4d_:rM});function aM(e){let n={x:_(e,"x","round")};return L.runKernel(Bl,n)}var b0=B({round_:aM});function oM(e){let n={x:_(e,"x","rsqrt","float32")};return L.runKernel(ei,n)}var v0=B({rsqrt_:oM});function iM(e){let n={x:_(e,"x","selu")};return L.runKernel(Pc,n)}var w0=B({selu_:iM});function lM(e,t,n,s,r,a=[1,1],o="NHWC"){let i=_(e,"x","separableConv2d"),l=_(t,"depthwiseFilter","separableConv2d"),u=_(n,"pointwiseFilter","separableConv2d"),c=i,p=!1;if(i.rank===3&&(p=!0,c=W(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");P(c.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`),P(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),P(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),P(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),P(u.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);let d=l.shape[2],h=l.shape[3];P(u.shape[2]===d*h,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${d*h}, but got ${u.shape[2]}.`);let f=Vc(c,l,s,r,o,a),g=ka(f,u,1,"valid",o);return p?W(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var k0=B({separableConv2d_:lM});async function uM(e,t){let n=_(e,"x","setdiff1d"),s=_(t,"y","setdiff1d");P(n.dtype===s.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`),P(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),P(s.rank===1,()=>`y should be 1D tensor, but got y (${s.shape}).`);let r=await n.data(),a=await s.data(),o=new Set(a),i=0;for(let c=0;c`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),Oe(s,[t],[n])}var ch=B({slice1d_:hM});function fM(e,t,n){let s=_(e,"x","slice2d");return P(s.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),Oe(s,t,n)}var C0=B({slice2d_:fM});function mM(e,t,n){let s=_(e,"x","slice3d");return P(s.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),Oe(s,t,n)}var fi=B({slice3d_:mM});function gM(e,t,n){let s=_(e,"x","slice4d");return P(s.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),Oe(s,t,n)}var oo=B({slice4d_:gM});function yM(e,t=-1){let n=_(e,"logits","softmax","float32");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);let s={logits:n},r={dim:t};return L.runKernel(ai,s,r)}var au=B({softmax_:yM});function AM(e){P(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return L.runKernel(Gm,t)}var dh=B({fft_:AM});function xM(e){P(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return L.runKernel(Hm,t)}var sc=B({ifft_:xM});function bM(e){let t=e.shape[e.shape.length-1],n=e.size/t,s;if(t<=2){let r=W(e,[n,t]);s=sc(r)}else{let r=[n,2*(t-1)],a=W(tc(e),[n,t]),o=W(Jp(e),[n,t]),i=Js(Oe(a,[0,1],[n,t-2]),1),l=M(Js(Oe(o,[0,1],[n,t-2]),1),Ce(-1)),u=ut([a,i],1),c=ut([o,l],1),p=W(wa(u,c),[r[0],r[1]]);s=sc(p)}if(s=tc(s),e.rank===3&&e.shape[0]!==0){let r=s,a=e.shape[0];s=W(s,[a,s.shape[0]/a,s.shape[1]]),r.dispose()}return s}var T0=B({irfft_:bM});function vM(e,t,n=0){let r={x:_(e,"x","split")},a={numOrSizeSplits:t,axis:n};return L.runKernel(jl,r,a)}var Ht=B({split_:vM});function wM(e,t){P(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=Oe(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=ut([e,Vt(f)],e.shape.length-1),n=t}else r=e;let a=ct(r),o=W(wa(r,a),[s,n]),i=dh(o),l=Math.floor(n/2)+1,u=tc(i),c=Jp(i),p=Ht(u,[l,n-l],u.shape.length-1),d=Ht(c,[l,n-l],c.shape.length-1),h=r.shape.slice();return h[r.shape.length-1]=l,W(wa(p[0],d[0]),h)}var ph=B({rfft_:wM});function kM(e,t){let n=_(e,"a","squaredDifference"),s=_(t,"b","squaredDifference");[n,s]=jt(n,s),vt(n.shape,s.shape);let r={a:n,b:s},a={};return L.runKernel(oi,r,a)}var N0=B({squaredDifference_:kM});function SM(e,t){let n=_(e,"x","squeeze","string_or_numeric");return W(n,rw(n.shape,t).newShape)}var Ge=B({squeeze_:SM});function IM(e,t=0){let n=hp(e,"tensors","stack","string_or_numeric");P(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&P(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let s=n,r={axis:t};return L.runKernel(Ol,s,r)}var ln=B({stack_:IM});function CM(e,t=0){let s={x:_(e,"x","step")},r={alpha:t};return L.runKernel(ui,s,r)}var ou=B({step_:CM});function TM(e,t,n,s,r=0,a=0,o=0,i=0,l=0){let c={x:_(e,"x","stridedSlice","string_or_numeric")},p={begin:t,end:n,strides:s,beginMask:r,endMask:a,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:l};return L.runKernel(ql,c,p)}var DA=B({stridedSlice_:TM});function NM(e){let n={x:_(e,"x","tan","float32")};return L.runKernel(Xl,n)}var $A=B({tan_:NM});function Ot(e,t){cl(e);let n=ta(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return ci(e,null,n,t)}function mr(e,t,n){if(cl(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let s=ta(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 ci(e,t,s,n)}function V6(e,t,n){if(cl(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let s=ta(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 ci(e,t,s,n)}function U6(e,t,n){if(cl(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let s=ta(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 ci(e,t,s,n)}function G6(e,t,n){if(cl(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let s=ta(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,ci(e,t,s,n)}function EM(e,t=1,n=!0){let s=_(e,"x","topk");if(s.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let r=s.shape[s.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);let a={x:s},o={k:t,sorted:n},[i,l]=L.runKernel(Kl,a,o);return{values:i,indices:l}}var PA=B({topk_:EM});function RM(e,t=0,n=1,s,r){if(s!=null&&s==="bool")throw new Error("Unsupported data type $ { dtype }");let a=new EA(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]=L.runKernel(s0,s,r);return{values:a,indices:o}}var FA=B({unique_:_M});function DM(e,t,n){let s=_(e,"x","unsortedSegmentSum"),r=_(t,"segmentIds","unsortedSegmentSum","int32");P(Yu(n),()=>"numSegments must be of dtype int");let a={x:s,segmentIds:r},o={numSegments:n};return L.runKernel(Gp,a,o)}var R0=B({unsortedSegmentSum_:DM});function $M(e,t=0){let n=_(e,"x","unstack","string_or_numeric");P(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);let s={value:n},r={axis:t};return L.runKernel(Yl,s,r)}var bn=B({unstack_:$M});function H6(e,t){return y0(e,t,"right")}function OA(e,t=!0,n,s){return L.makeVariable(e,t,n,s)}function j6(e,t){let n=[];for(let a=0;a0,()=>"mask cannot be scalar"),ls(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=Ce(1),u=ye(l,i),c=M(ye(o,a),u);if(r){P(s!=null,()=>"When using zeroDebias: true, step is required.");let p=_(s,"step","movingAverage");c=ge(c,ye(l,Ia(i,p)))}return le(a,c)}var X6=B({movingAverage_:OM});function MM(e,t,n){let s=_(e,"indices","scatterND","int32"),r=_(t,"updates","scatterND");zy(r,s,n);let a={indices:s,updates:r},o={shape:n};return L.runKernel(Wl,a,o)}var K6=B({scatterND_:MM});function zM(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 LM(e,t,n,s=0){let r=_(e,"sparseIndices","sparseToDense","int32"),a=_(t,"sparseValues","sparseToDense","string_or_numeric"),o=_(s,"defaultValue","sparseToDense",a.dtype);zM(r,a,n,o);let i={sparseIndices:r,sparseValues:a,defaultValue:o},l={outputShape:n};return L.runKernel(Wp,i,l)}var Z6=B({sparseToDense_:LM});function BM(e,t){let n=_(t,"indices","gatherND","int32"),r={params:_(e,"x","gatherND","string_or_numeric"),indices:n};return L.runKernel(kl,r)}var Y6=B({gatherND_:BM});function WM(e,t){if(t==null)return e.shape.slice();if(mo(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.`),P(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof st?r.clone():r;let a=WM(r,n),o=1-t,i=ge(Hc(le(Xc(a,0,1,"float32",s),o)),o);return M(r,i)}var zA=B({dropout_:VM});function LA(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function _0(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}`),P(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}`),ls(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];P(n>0&&n<=a,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`);let o=await s.data(),i=await r.data(),[l,u]=[o.length/a,a],c=aw("bool",l);for(let p=0;pg.value-m.value),c[p]=0;for(let m=0;mjM,depthwiseConv2d:()=>ZM,matMul:()=>JM});function GM(e,t,n,s,r,a="NHWC",o){let i=e;e.rank===3&&(i=W(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=W(t,[1,t.shape[0],t.shape[1],t.shape[2]])),P(i.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),P(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),P(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);let u=a==="NHWC"?i.shape[3]:i.shape[1],c=a==="NHWC"?l.shape[3]:l.shape[1];P(u===n[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${n[2]}.`),P(c===n[3],()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${n[3]}).`),us("conv2dDerFilter",r,o);let p={x:i,dy:l},d={strides:s,pad:r,dataFormat:a,dimRoundingMode:o,filterShape:n};return L.runKernel(Om,p,d)}var BA=B({conv2DBackpropFilter_:GM});function D0(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return M(e,ou(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function $0(e,t){let n=t,s=on(e.shape,t.shape);return s.length>0&&(n=ve(n,s)),W(n,e.shape)}function P0(e,t,n,s){if(t==="linear")return e;if(t==="relu")return Lr(e);if(t==="elu")return Uc(e);if(t==="relu6")return x0(e);if(t==="prelu")return uh(e,n);if(t==="leakyrelu")return sh(e,s);if(t==="sigmoid")return Mn(e);throw new Error(`Unknown fused activation ${t}.`)}var F0=(e,t)=>!(e>0)||t==="linear";function HM({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(l=l||"linear",F0(L.state.gradientDepth,l)===!1){P(r==="NHWC",()=>`Error in fused conv2d: got dataFormat of ${r} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);let k=ka(e,t,n,s,r,a,o);return i!=null&&(k=le(k,i)),P0(k,l,u,c)}let p=_(e,"x","conv2d","float32"),d=_(t,"filter","conv2d","float32"),h=p,f=!1;p.rank===3&&(f=!0,h=W(p,[1,p.shape[0],p.shape[1],p.shape[2]])),P(h.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`),P(d.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${d.rank}.`),us("fused conv2d",s,o);let m=r==="NHWC"?h.shape[3]:h.shape[1];P(d.shape[2]===m,()=>`Error in conv2d: depth of input (${m}) must match input depth for filter ${d.shape[2]}.`),P(aa(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let g=Qp(h.shape,d.shape,n,a,s,o),y;i!=null&&(y=_(i,"bias","fused conv2d"),[y]=jt(y,p),r==="NHWC"?vt(g.outShape,y.shape):(P(y.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${y.shape.length}.`),P(y.shape.length===0||y.shape[0]===g.outChannels||y.shape[0]===1,()=>`Error in fused conv2d: bias shape (${y.shape}) is not compatible with the number of output channels (${g.outChannels})`)));let x;if(u!=null){let k=u.shape;if(P(k.length<=1||k.length===3,()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${k.length}.`),k.length===1)P(k[0]===1||k[0]===g.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${k}) is not compatible with the number of output channels (${g.outChannels}).`);else if(k.length===3)try{vt(k,g.outShape)}catch(C){let N=`Error in fused conv2d: PReLU activation weights (${k}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(N)}x=_(u,"prelu weights","fused conv2d")}let A=(k,C)=>{P(r==="NHWC",()=>`Error in gradient of fused conv2D: got dataFormat of ${r} but only NHWC is currently supported.`);let[N,R,D,E]=C,$=D0(k,D,l);P(ao(a),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);let S=oA(R.shape,$,N,n,s),F=BA(R,$,N.shape,n,s),z=[S,F];if(E!=null){let V=$0(E,$);z.push(V)}return z},b={x:h,filter:d,bias:y,preluActivationWeights:x},w={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:c};return i==null?na((C,N,R)=>{let D=L.runKernel(so,b,w);return R([N,C,D]),f&&(D=W(D,[D.shape[1],D.shape[2],D.shape[3]])),{value:D,gradFunc:A}})(h,d):na((C,N,R,D)=>{let E=L.runKernel(so,b,w);return D([N,C,E,R]),f&&(E=W(E,[E.shape[1],E.shape[2],E.shape[3]])),{value:E,gradFunc:A}})(h,d,y)}var jM=B({fusedConv2d_:HM});function qM(e,t,n,s,r,a=[1,1],o){let i=e;e.rank===3&&(i=W(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={x:i,dy:l},c={strides:s,pad:r,dimRoundingMode:o,dilations:a,filterShape:n};return L.runKernel(Bm,u,c)}var Q6=B({depthwiseConv2dNativeBackpropFilter_:qM});function XM(e,t,n,s,r,a=[1,1],o){let i=t,l=!1;t.rank===3&&(l=!0,i=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={dy:i,filter:n},c={strides:s,pad:r,dimRoundingMode:o,dilations:a,inputShape:e},p=L.runKernel(Wm,u,c);return l?W(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var ek=B({depthwiseConv2dNativeBackpropInput_:XM});function KM({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(F0(L.state.gradientDepth,l)===!1){let w=Vc(e,t,n,s,r,a,o);return i!=null&&(w=le(w,i)),P0(w,l,u,c)}let p=_(e,"x","depthwiseConv2d","float32"),d=_(t,"filter","depthwiseConv2d","float32"),h=p,f=!1;p.rank===3&&(f=!0,h=W(p,[1,p.shape[0],p.shape[1],p.shape[2]])),P(h.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`),P(d.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${d.rank}.`),P(h.shape[3]===d.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${d.shape[2]}.`),a==null&&(a=[1,1]),P(aa(n,a),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),us("fused depthwiseConv2d",s,o);let m=Qp(h.shape,d.shape,n,a,s,o,!0),g;i!=null&&(g=_(i,"bias","fused conv2d"),[g]=jt(g,p),vt(m.outShape,g.shape));let y;u!=null&&(y=_(u,"prelu weights","fused depthwiseConv2d"));let x=(w,k)=>{P(ao(a),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);let[C,N,R,D]=k,E=D0(w,R,l),$=ek(N.shape,E,C,n,s,a,o),S=Q6(N,E,C.shape,n,s,a,o);if(D!=null){let F=$0(g,E);return[$,S,F]}return[$,S]},A={x:h,filter:d,bias:g,preluActivationWeights:y},b={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:c};return i==null?na((k,C,N)=>{let R=L.runKernel(ro,A,b);return N([C,k,R]),f&&(R=W(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:x}})(h,d):na((k,C,N,R)=>{let D=L.runKernel(ro,A,b);return R([C,k,D,N]),f&&(D=W(D,[D.shape[1],D.shape[2],D.shape[3]])),{value:D,gradFunc:x}})(h,d,g)}var ZM=B({fusedDepthwiseConv2d_:KM});function YM({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:r,activation:a="linear",preluActivationWeights:o,leakyreluAlpha:i=.2}){if(F0(L.state.gradientDepth,a)===!1){let E=et(e,t,n,s);return r!=null&&(E=le(E,r)),P0(E,a,o,i)}let l=_(e,"a","fused matMul"),u=_(t,"b","fused matMul");[l,u]=jt(l,u);let c=n?l.shape[l.rank-2]:l.shape[l.rank-1],p=s?u.shape[u.rank-1]:u.shape[u.rank-2],d=n?l.shape[l.rank-1]:l.shape[l.rank-2],h=s?u.shape[u.rank-2]:u.shape[u.rank-1],f=l.shape.slice(0,-2),m=u.shape.slice(0,-2),g=It(f),y=It(m);P(c===p,()=>`Error in fused matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${n} and transposeB=${s} must match.`);let A=vt(l.shape.slice(0,-2),u.shape.slice(0,-2)).concat([d,h]),b=n?W(l,[g,c,d]):W(l,[g,d,c]),w=s?W(u,[y,h,p]):W(u,[y,p,h]),k;r!=null&&(k=_(r,"bias","fused matMul"),[k]=jt(k,l),vt(A,k.shape));let C;o!=null&&(C=_(o,"prelu weights","fused matMul"));let N=(E,$)=>{let[S,F,z,V]=$,j=D0(W(E,z.shape),z,a),G,q;if(!n&&!s?(G=et(j,F,!1,!0),q=et(S,j,!0,!1)):!n&&s?(G=et(j,F,!1,!1),q=et(j,S,!0,!1)):n&&!s?(G=et(F,j,!1,!0),q=et(S,j,!1,!1)):(G=et(F,j,!0,!0),q=et(j,S,!0,!0)),r!=null){let K=$0(V,j);return[G,q,K]}else return[G,q]},R={a:b,b:w,bias:k,preluActivationWeights:C},D={transposeA:n,transposeB:s,activation:a,leakyreluAlpha:i};return r==null?na(($,S,F)=>{let z=L.runKernel(no,R,D);return F([$,S,z]),{value:W(z,A),gradFunc:N}})(b,w):na(($,S,F,z)=>{let V=L.runKernel(no,R,D);return z([$,S,V,F]),{value:W(V,A),gradFunc:N}})(b,w,k)}var JM=B({fusedMatMul_:YM});function QM(e){return _0(e,.54,.46)}var ez=B({hammingWindow_:QM});function tz(e){return _0(e,.5,.5)}var tk=B({hannWindow_:tz});function nz(e,t,n,s=!1,r=0){let a=0,o=[];for(;a+t<=e.size;)o.push(Oe(e,a,t)),a+=n;if(s)for(;a`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),P(i.rank===2&&i.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${i.shape}.`),P(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${i.shape}.`),P(s.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),P(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),P(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);let c={image:o,boxes:i,boxInd:l},p={method:r,extrapolationValue:a,cropSize:s};return L.runKernel(gl,c,p)}var oz=B({cropAndResize_:az});function iz(e){let t=_(e,"image","flipLeftRight","float32");P(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return L.runKernel(vl,n,{})}var lz=B({flipLeftRight_:iz});function uz(e){let t=_(e,"image","grayscaleToRGB"),n=t.rank-1,s=t.shape[n];P(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),P(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,As(t,r)}var cz=B({grayscaleToRGB_:uz});function dz(e,t,n=0,s=.5){let r=_(e,"image","rotateWithOffset","float32");P(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 L.runKernel(Ql,a,o)}var pz=B({rotateWithOffset_:dz});function Kc(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),P(0<=s&&s<=1,()=>`iouThreshold must be in [0, 1], but was '${s}'`),P(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),P(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),P(t.rank===1,()=>"scores must be a 1D tensor"),P(t.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`),P(0<=a&&a<=1,()=>`softNmsSigma must be in [0, 1], but was '${a}'`),{maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a}}function hz(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=_(e,"boxes","nonMaxSuppression","float32"),o=_(t,"scores","nonMaxSuppression","float32"),i=Kc(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l={maxOutputSize:n,iouThreshold:s,scoreThreshold:r};return L.runKernel(Dl,{boxes:a,scores:o},l)}var fz=B({nonMaxSuppression_:hz});function mz(e,t,n){let s=gz(e,t,n),r=s<0?-(s+1):s;e.splice(r,0,t)}function gz(e,t,n){return Az(e,t,n||yz)}function yz(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 sk(e,t,n,s,r){return WA(e,t,n,s,r,0)}function rk(e,t,n,s,r,a){return WA(e,t,n,s,r,0,!1,a,!0)}function ak(e,t,n,s,r,a){return WA(e,t,n,s,r,a,!0)}function WA(e,t,n,s,r,a,o=!1,i=!1,l=!1){let u=[];for(let g=0;gr&&u.push({score:t[g],boxIndex:g,suppressBeginIndex:0});u.sort(vv);let c=a>0?-.5/a:0,p=[],d=[];for(;p.length0;){let g=u.pop(),{score:y,boxIndex:x,suppressBeginIndex:A}=g;if(y=A;--w){let k=xz(e,x,p[w]);if(k>=s){b=!0;break}if(g.score=g.score*bz(s,c,k),g.score<=r)break}g.suppressBeginIndex=p.length,b||(g.score===y?(p.push(x),d.push(g.score)):g.score>r&&mz(u,g,vv))}let h=p.length,f=n-h;i&&f>0&&(p.push(...new Array(f).fill(0)),d.push(...new Array(f).fill(0)));let m={selectedIndices:p};return o&&(m.selectedScores=d),l&&(m.validOutputs=h),m}function xz(e,t,n){let s=e.subarray(t*4,t*4+4),r=e.subarray(n*4,n*4+4),a=Math.min(s[0],s[2]),o=Math.min(s[1],s[3]),i=Math.max(s[0],s[2]),l=Math.max(s[1],s[3]),u=Math.min(r[0],r[2]),c=Math.min(r[1],r[3]),p=Math.max(r[0],r[2]),d=Math.max(r[1],r[3]),h=(i-a)*(l-o),f=(p-u)*(d-c);if(h<=0||f<=0)return 0;let m=Math.max(a,u),g=Math.max(o,c),y=Math.min(i,p),x=Math.min(l,d),A=Math.max(y-m,0)*Math.max(x-g,0);return A/(h+f-A)}function bz(e,t,n){let s=Math.exp(t*n*n);return n<=e?s:0}function vv(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function vz(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){let a=_(e,"boxes","nonMaxSuppressionAsync"),o=_(t,"scores","nonMaxSuppressionAsync"),i=Kc(a,o,n,s,r);n=i.maxOutputSize,s=i.iouThreshold,r=i.scoreThreshold;let l=await Promise.all([a.data(),o.data()]),u=l[0],c=l[1],{selectedIndices:p}=sk(u,c,n,s,r);return a!==e&&a.dispose(),o!==t&&o.dispose(),Ot(p,"int32")}var wz=vz;function kz(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=_(e,"boxes","nonMaxSuppression"),i=_(t,"scores","nonMaxSuppression"),l=Kc(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let u={boxes:o,scores:i},c={maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a},p=L.runKernel($l,u,c);return{selectedIndices:p[0],selectedScores:p[1]}}var Sz=B({nonMaxSuppressionWithScore_:kz});async function Iz(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){let o=_(e,"boxes","nonMaxSuppressionAsync"),i=_(t,"scores","nonMaxSuppressionAsync"),l=Kc(o,i,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;let u=await Promise.all([o.data(),i.data()]),c=u[0],p=u[1],{selectedIndices:d,selectedScores:h}=ak(c,p,n,s,r,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Ot(d,"int32"),selectedScores:Ot(h)}}var Cz=Iz;function Tz(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=_(e,"boxes","nonMaxSuppression"),i=_(t,"scores","nonMaxSuppression"),l=Kc(o,i,n,s,r,null),u=l.maxOutputSize,c=l.iouThreshold,p=l.scoreThreshold,d={boxes:o,scores:i},h={maxOutputSize:u,iouThreshold:c,scoreThreshold:p,padToMaxOutputSize:a},f=L.runKernel(Dc,d,h);return{selectedIndices:f[0],validOutputs:f[1]}}var Nz=B({nonMaxSuppressionPadded_:Tz});async function Ez(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){let o=_(e,"boxes","nonMaxSuppressionAsync"),i=_(t,"scores","nonMaxSuppressionAsync"),l=Kc(o,i,n,s,r,null),u=l.maxOutputSize,c=l.iouThreshold,p=l.scoreThreshold,[d,h]=await Promise.all([o.data(),i.data()]),{selectedIndices:f,validOutputs:m}=rk(d,h,u,c,p,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Ot(f,"int32"),validOutputs:Ce(m,"int32")}}var Rz=Ez;function _z(e,t,n=!1,s=!1){let r=_(e,"images","resizeBilinear");P(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),P(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),P(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=W(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},u=L.runKernel(Jo,i,l);return o?W(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var ok=B({resizeBilinear_:_z});function Dz(e,t,n=!1,s=!1){let r=_(e,"images","resizeNearestNeighbor");P(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),P(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),P(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),P(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=W(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},u=L.runKernel(Yo,i,l);return o?W(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var ik=B({resizeNearestNeighbor_:Dz});function $z(e,t="binary",n=!1,s=.5){let r=_(e,"image","threshold"),a=.2989,o=.587,i=.114,l=r.shape[0]*r.shape[1],u=M(Ot([s]),255),c,p,d,h;if(P(r.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`),P(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]}.`),P(r.dtype==="int32"||r.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`),P(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),r.shape[2]===3){[c,p,d]=Ht(r,[1,1,1],-1);let g=M(c,a),y=M(p,o),x=M(d,i);h=le(le(g,y),x)}else h=e;if(t==="otsu"){let g=tA(me(b0(h),"int32"),Ue([]),256);u=Pz(g,l)}let f=n?hi(h,u):ks(h,u);return me(M(f,255),"int32")}function Pz(e,t){let n=Ot([-1]),s=Ot([0]),r=Ot([0]),a,o,i,l,u,c;for(let p=0;p`Error in transform: image must be rank 4,but got rank ${o.rank}.`),P(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"),P(a==null||a.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`);let l={image:o,transforms:i},u={interpolation:n,fillMode:s,fillValue:r,outputShape:a};return L.runKernel(Zl,l,u)}var Mz=B({transform_:Oz});function zz(e,t,n){P(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),P(n%1===0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);let s=_(e,"a","bandPart");P(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=W(nc(0,a,1,"int32"),[-1,1]),l=nc(0,o,1,"int32"),u=ye(i,l),c=gr(hi(u,Ce(+t,"int32")),pi(u,Ce(-n,"int32"))),p=Vt([a,o],s.dtype);return W(ln(bn(W(s,[-1,a,o])).map(d=>qn(c,d,p))),r)}var Lz=B({bandPart_:zz});function Bz(e){let t;if(Array.isArray(e)){t=!1,P(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let 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=Ht(e,e.shape[0],0).map(r=>Ge(r,[0]));P(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 wv(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,u)=>l*u),s=bn(W(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],a=[];s.forEach(l=>{let[u,c]=wv(l,t);r.push(u),a.push(c)});let o=W(ln(r,0),e.shape),i=W(ln(a,0),e.shape);return[o,i]}}function wv(e,t=!1){return L.tidy(()=>{P(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=d0(n),a=Hn(e),o=mr([[1]],[1,1]),i=Hn(o),l=n>=s?s:n;for(let u=0;u{let h=Oe(a,[u,u],[n-u,1]),f=Gc(h),m=Oe(a,[u,u],[1,1]),g=qn(ks(m,0),mr([[-1]]),mr([[1]])),y=ye(m,M(g,f)),x=ge(h,y);x.shape[0]===1?i=Hn(o):i=ut([o,Oe(x,[1,0],[x.shape[0]-1,x.shape[1]])],0);let A=Dt(ge(et(g,y),f)),b=Oe(a,[u,0],[n-u,s]),w=M(A,i),k=tt(i);if(u===0)a=ye(b,et(w,et(k,b)));else{let R=ye(b,et(w,et(k,b)));a=ut([Oe(a,[0,0],[u,s]),R],0)}let C=tt(w),N=Oe(r,[0,u],[n,r.shape[1]-u]);if(u===0)r=ye(N,et(et(N,i),C));else{let R=ye(N,et(et(N,i),C));r=ut([Oe(r,[0,0],[n,u]),R],1)}return[i,a,r]}),Y([c,p,d])}return!t&&n>s&&(r=Oe(r,[0,0],[n,s]),a=Oe(a,[0,0],[s,s])),[r,a]})}var Uz=B({qr_:Vz}),rs;(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"})(rs||(rs={}));function Gz(e,t,n=rs.SUM_BY_NONZERO_WEIGHTS){let s=_(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=_(t,"weights","computeWeightedLoss"));let a=r==null?s:M(s,r);if(n===rs.NONE)return a;if(n===rs.SUM)return ve(a);if(n===rs.MEAN){if(r==null)return Wt(a);{let o=s.size/r.size,i=ge(ve(a),ve(r));return o>1?ge(i,Ce(o)):i}}if(n===rs.SUM_BY_NONZERO_WEIGHTS){if(r==null)return ge(ve(a),Ce(s.size));{let o=M(r,Ds(s.shape)),i=me(ve(sl(o,Ce(0))),"float32");return ge(ve(a),i)}}throw Error(`Unknown reduction: ${n}`)}var Ra=B({computeWeightedLoss_:Gz});function Hz(e,t,n,s=rs.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","absoluteDifference"),a=_(t,"predictions","absoluteDifference"),o=null;n!=null&&(o=_(n,"weights","absoluteDifference")),ls(r.shape,a.shape,"Error in absoluteDifference: ");let i=rn(ye(r,a));return Ra(i,o,s)}var jz=B({absoluteDifference_:Hz});function qz(e,t,n,s,r=rs.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"labels","cosineDistance"),o=_(t,"predictions","cosineDistance"),i=null;s!=null&&(i=_(s,"weights","cosineDistance")),ls(a.shape,o.shape,"Error in cosineDistance: ");let l=Ce(1),u=ye(l,ve(M(a,o),n,!0));return Ra(u,i,r)}var Xz=B({cosineDistance_:qz});function Kz(e,t,n,s=rs.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","hingeLoss"),a=_(t,"predictions","hingeLoss"),o=null;n!=null&&(o=_(n,"weights","hingeLoss")),ls(r.shape,a.shape,"Error in hingeLoss: ");let i=Ce(1);r=ye(M(Ce(2),r),i);let l=Lr(ye(i,M(r,a)));return Ra(l,o,s)}var Zz=B({hingeLoss_:Kz});function Yz(e,t,n,s=1,r=rs.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"labels","huberLoss"),o=_(t,"predictions","huberLoss"),i=null;n!=null&&(i=_(n,"weights","huberLoss")),ls(a.shape,o.shape,"Error in huberLoss: ");let l=Ce(s),u=rn(ye(o,a)),c=qc(u,l),p=ye(u,c),d=le(M(Ce(.5),bt(c)),M(l,p));return Ra(d,i,r)}var Jz=B({huberLoss_:Yz});function Qz(e,t,n,s=1e-7,r=rs.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"labels","logLoss"),o=_(t,"predictions","logLoss"),i=null;n!=null&&(i=_(n,"weights","logLoss")),ls(a.shape,o.shape,"Error in logLoss: ");let l=Ce(1),u=Ce(s),c=Dt(M(a,Ms(le(o,u)))),p=M(ye(l,a),Ms(le(ye(l,o),u))),d=ye(c,p);return Ra(d,i,r)}var eL=B({logLoss_:Qz});function tL(e,t,n,s=rs.SUM_BY_NONZERO_WEIGHTS){let r=_(e,"labels","meanSquaredError"),a=_(t,"predictions","meanSquaredError"),o=null;n!=null&&(o=_(n,"weights","meanSquaredError")),ls(r.shape,a.shape,"Error in meanSquaredError: ");let i=N0(r,a);return Ra(i,o,s)}var nL=B({meanSquaredError_:tL});function sL(e,t){let n=_(e,"labels","sigmoidCrossEntropyWithLogits"),s=_(t,"logits","sigmoidCrossEntropyWithLogits");ls(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=Lr(s),a=M(s,n),o=rh(Os(Dt(rn(s))));return le(ye(r,a),o)}function rL(e,t,n,s=0,r=rs.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"multiClassLabels","sigmoidCrossEntropy"),o=_(t,"logits","sigmoidCrossEntropy"),i=null;if(n!=null&&(i=_(n,"weights","sigmoidCrossEntropy")),ls(a.shape,o.shape,"Error in sigmoidCrossEntropy: "),s>0){let u=Ce(s),c=Ce(1),p=Ce(.5);a=le(M(a,ye(c,u)),M(p,u))}let l=sL(a,o);return Ra(l,i,r)}var aL=B({sigmoidCrossEntropy_:rL});function oL(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 na((r,a,o)=>{let l=m0(a,[n],!0),u=ye(me(a,"float32"),l);o([r,u]);let c=Dt(M(u,r));return{value:ve(c,[n]),gradFunc:(h,f)=>{let[m,g]=f,y=nl(h.shape,[n]);return[M(W(h,y),ye(me(m,"float32"),Os(g))),M(W(h,y),ye(Os(g),me(m,"float32")))]}}})(e,t)}function iL(e,t,n,s=0,r=rs.SUM_BY_NONZERO_WEIGHTS){let a=_(e,"onehotLabels","softmaxCrossEntropy"),o=_(t,"logits","softmaxCrossEntropy"),i=null;if(n!=null&&(i=_(n,"weights","softmaxCrossEntropy")),ls(a.shape,o.shape,"Error in softmaxCrossEntropy: "),s>0){let u=Ce(s),c=Ce(1),p=Ce(a.shape[1]);a=le(M(a,ye(c,u)),ge(u,p))}let l=oL(a,o);return Ra(l,i,r)}var lL=B({softmaxCrossEntropy_:iL});function uL(e,t,n,s){let r=_(e,"indices","sparseFillEmptyRows","int32"),a=_(t,"values","sparseFillEmptyRows"),o=_(n,"denseShape","sparseFillEmptyRows","int32"),i=_(s,"defaultValue","sparseFillEmptyRows",a.dtype);if(r.rank!==2)throw new Error(`Indices should be Tensor2D but received shape ${r.shape}`);if(a.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(o.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(i.rank!==0)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);let l={indices:r,values:a,denseShape:o,defaultValue:i},u=L.runKernel(zp,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var cL=B({sparseFillEmptyRows_:uL});function dL(e,t,n){let s=_(e,"inputIndices","sparseReshape","int32"),r=_(t,"inputShape","sparseReshape","int32"),a=_(n,"newShape","sparseReshape","int32");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=L.runKernel(Mc,o);return{outputIndices:i[0],outputShape:i[1]}}var pL=B({sparseReshape_:dL});function hL(e,t,n){let s=_(e,"data","sparseSegmentMean"),r=_(t,"indices","sparseSegmentMean","int32"),a=_(n,"segmentIds","sparseSegmentMean","int32");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 L.runKernel(Lp,o)}var fL=B({sparseSegmentMean_:hL});function mL(e,t,n){let s=_(e,"data","sparseSegmentSum"),r=_(t,"indices","sparseSegmentSum","int32"),a=_(n,"segmentIds","sparseSegmentSum","int32");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 L.runKernel(Bp,o)}var gL=B({sparseSegmentSum_:mL});function yL(e,t,n,s,r,a,o,i){let l=_(e,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);let u=_(t,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let c={separator:n,nGramWidths:s,leftPad:r,rightPad:a,padWidth:o,preserveShortSequences:i},p={data:l,dataSplits:u},d=L.runKernel(Lc,p,c);return{nGrams:d[0],nGramsSplits:d[1]}}var AL=B({stringNGrams_:yL});function xL(e,t,n=!0){let s=_(e,"input","stringSplit","string"),r=_(t,"delimiter","stringSplit","string");if(s.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${s.shape}`);if(r.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);let a={skipEmpty:n},o={input:s,delimiter:r},i=L.runKernel(Vp,o,a);return{indices:i[0],values:i[1],shape:i[2]}}var bL=B({stringSplit_:xL});function vL(e,t){let n=_(e,"input","stringToHashBucketFast","string"),s={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let r={input:n};return L.runKernel(Up,r,s)}var wL=B({stringToHashBucketFast_:vL}),lk={fft:dh,ifft:sc,rfft:ph,irfft:T0},uk={hammingWindow:ez,hannWindow:tk,frame:nk,stft:rz},ke={flipLeftRight:lz,grayscaleToRGB:cz,resizeNearestNeighbor:ik,resizeBilinear:ok,rotateWithOffset:pz,cropAndResize:oz,nonMaxSuppression:fz,nonMaxSuppressionAsync:wz,nonMaxSuppressionWithScore:Sz,nonMaxSuppressionWithScoreAsync:Cz,nonMaxSuppressionPadded:Nz,nonMaxSuppressionPaddedAsync:Rz,threshold:Fz,transform:Mz},VA={bandPart:Lz,gramSchmidt:Wz,qr:Uz},ck={absoluteDifference:jz,computeWeightedLoss:Ra,cosineDistance:Xz,hingeLoss:Zz,huberLoss:Jz,logLoss:eL,meanSquaredError:nL,sigmoidCrossEntropy:aL,softmaxCrossEntropy:lL},dk={sparseFillEmptyRows:cL,sparseReshape:pL,sparseSegmentMean:fL,sparseSegmentSum:gL},pk={stringNGrams:AL,stringSplit:bL,stringToHashBucketFast:wL},_a=class extends s6{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 Y(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 v6(e,t)}dispose(){this.iterations_!=null&&Y(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Ce(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(_a,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var O0=class extends _a{constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=L.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=L.registeredVariables[n],a=!1;this.accumulatedGrads[s]==null&&(this.accumulatedGrads[s]={originalName:`${n}/accum_grad`,variable:X(()=>ct(r).variable(a))}),this.accumulatedUpdates[s]==null&&(this.accumulatedUpdates[s]={originalName:`${n}/accum_var`,variable:X(()=>ct(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 u=le(M(i,this.rho),M(bt(o),1-this.rho)),c=M(ge(Ln(le(l,this.epsilon)),Ln(le(i,this.epsilon))),o),p=le(M(l,this.rho),M(bt(c),1-this.rho));i.assign(u),l.assign(p);let d=le(M(c,-this.learningRate),r);r.assign(d)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Y(this.accumulatedGrads.map(e=>e.variable)),Y(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)}};O0.className="Adadelta";di(O0);var M0=class extends _a{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=L.registeredVariables[n];this.accumulatedGrads[s]==null&&(this.accumulatedGrads[s]={originalName:`${n}/accumulator`,variable:X(()=>zr(r.shape,this.initialAccumulatorValue).variable(!1))});let a=Array.isArray(e)?e[s].tensor:e[n];if(a==null)return;let o=this.accumulatedGrads[s].variable;X(()=>{let i=le(o,bt(a));o.assign(i);let l=le(M(ge(a,Ln(le(i,L.backend.epsilon()))),-this.learningRate),r);r.assign(l)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Y(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)}};M0.className="Adagrad";di(M0);var z0=class extends _a{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=Ce(t).variable(),this.accBeta2=Ce(n).variable()}),s==null&&(this.epsilon=L.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);X(()=>{let n=ye(1,this.accBeta1),s=ye(1,this.accBeta2);t.forEach((r,a)=>{let o=L.registeredVariables[r],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${r}/m`,variable:X(()=>ct(o).variable(i))}),this.accumulatedSecondMoment[a]==null&&(this.accumulatedSecondMoment[a]={originalName:`${r}/v`,variable:X(()=>ct(o).variable(i))});let l=Array.isArray(e)?e[a].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[a].variable,c=this.accumulatedSecondMoment[a].variable,p=le(M(u,this.beta1),M(l,1-this.beta1)),d=le(M(c,this.beta2),M(bt(l),1-this.beta2)),h=ge(p,n),f=ge(d,s);u.assign(p),c.assign(d);let m=le(M(ge(h,le(Ln(f),this.epsilon)),-this.learningRate),o);o.assign(m)}),this.accBeta1.assign(M(this.accBeta1,this.beta1)),this.accBeta2.assign(M(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Y(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Y(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(Ia(this.beta1,this.iterations_+1)),this.accBeta2.assign(Ia(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)}};z0.className="Adam";di(z0);var L0=class extends _a{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=Ce(0).variable(),this.accBeta1=Ce(t).variable()}),s==null&&(this.epsilon=L.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);X(()=>{let n=ye(1,this.accBeta1),s=ge(-this.learningRate,le(M(this.iteration,this.decay),1));t.forEach((r,a)=>{let o=L.registeredVariables[r],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${r}/m`,variable:ct(o).variable(i)}),this.accumulatedWeightedInfNorm[a]==null&&(this.accumulatedWeightedInfNorm[a]={originalName:`${r}/v`,variable:ct(o).variable(i)});let l=Array.isArray(e)?e[a].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[a].variable,c=this.accumulatedWeightedInfNorm[a].variable,p=le(M(u,this.beta1),M(l,1-this.beta1)),d=M(c,this.beta2),h=rn(l),f=oa(d,h);u.assign(p),c.assign(f);let m=le(M(ge(s,n),ge(p,le(f,this.epsilon))),o);o.assign(m)}),this.iteration.assign(le(this.iteration,1)),this.accBeta1.assign(M(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Y(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Y(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)}};L0.className="Adamax";di(L0);var hh=class extends _a{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=L.registeredVariables[n];X(()=>{let o=le(M(this.c,r),a);a.assign(o)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=Cn(Ce(-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)}};hh.className="SGD";di(hh);var B0=class extends hh{constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ce(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,s)=>{let r=L.registeredVariables[n];this.accumulations[s]==null&&(this.accumulations[s]={originalName:`${n}/momentum`,variable:X(()=>ct(r).variable(!1))});let a=this.accumulations[s].variable,o=Array.isArray(e)?e[s].tensor:e[n];o!=null&&X(()=>{let i,l=le(M(this.m,a),o);this.useNesterov?i=le(M(this.c,le(o,M(l,this.m))),r):i=le(M(this.c,l),r),a.assign(l),r.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Y(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)}};B0.className="Momentum";di(B0);var W0=class extends _a{constructor(e,t=.9,n=0,s=null,r=!1){if(super(),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=L.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=L.registeredVariables[n],a=!1;this.accumulatedMeanSquares[s]==null&&(this.accumulatedMeanSquares[s]={originalName:`${n}/rms`,variable:X(()=>ct(r).variable(a))}),this.accumulatedMoments[s]==null&&(this.accumulatedMoments[s]={originalName:`${n}/momentum`,variable:X(()=>ct(r).variable(a))}),this.accumulatedMeanGrads[s]==null&&this.centered&&(this.accumulatedMeanGrads[s]={originalName:`${n}/mg`,variable:X(()=>ct(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 u=le(M(i,this.decay),M(bt(o),1-this.decay));if(this.centered){let c=this.accumulatedMeanGrads[s].variable,p=le(M(c,this.decay),M(o,1-this.decay)),d=ge(M(o,this.learningRate),Ln(ye(u,le(bt(p),this.epsilon)))),h=le(M(l,this.momentum),d);i.assign(u),c.assign(p),l.assign(h);let f=ye(r,h);r.assign(f)}else{let c=le(M(i,this.decay),M(bt(o),1-this.decay)),p=le(M(l,this.momentum),ge(M(o,this.learningRate),Ln(le(c,this.epsilon))));i.assign(c),l.assign(p);let d=ye(r,p);r.assign(d)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Y(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Y(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Y(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)}};W0.className="RMSProp";di(W0);var ja=class{static sgd(e){return new hh(e)}static momentum(e,t,n=!1){return new B0(e,t,n)}static rmsprop(e,t=.9,n=0,s=null,r=!1){return new W0(e,t,n,s,r)}static adam(e=.001,t=.9,n=.999,s=null){return new z0(e,t,n,s)}static adadelta(e=.001,t=.95,n=null){return new O0(e,t,n)}static adamax(e=.002,t=.9,n=.999,s=null,r=0){return new L0(e,t,n,s,r)}static adagrad(e,t=.1){return new M0(e,t)}},zi={sgd:ja.sgd,momentum:ja.momentum,adadelta:ja.adadelta,adagrad:ja.adagrad,rmsprop:ja.rmsprop,adamax:ja.adamax,adam:ja.adam},kL=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function UA(){return new Promise(e=>kL(()=>e()))}var T={};We(T,{ERF_A1:()=>zL,ERF_A2:()=>LL,ERF_A3:()=>BL,ERF_A4:()=>WL,ERF_A5:()=>VL,ERF_P:()=>ML,PARALLELIZE_THRESHOLD:()=>GA,RowPartitionType:()=>Xr,SELU_SCALE:()=>fk,SELU_SCALEALPHA:()=>hk,applyActivation:()=>P0,assertAndGetBroadcastShape:()=>vt,assertAxesAreInnerMostDims:()=>EF,assertParamsConsistent:()=>SL,assignToTypedArray:()=>XL,axesAreInnerMostDims:()=>fA,calculateShapes:()=>qw,checkEinsumDimSizes:()=>eB,checkPadOnDimRoundingMode:()=>us,combineLocations:()=>g6,combineRaggedTensorToTensorShapes:()=>CL,complexWithEvenIndex:()=>HL,complexWithOddIndex:()=>jL,computeConv2DInfo:()=>Qp,computeConv3DInfo:()=>l6,computeDefaultPad:()=>Zy,computeDilation2DInfo:()=>RP,computeOptimalWindowSize:()=>RL,computeOutAndReduceShapes:()=>y6,computeOutShape:()=>IL,computePool2DInfo:()=>i6,computePool3DInfo:()=>_P,convertConv2DDataFormat:()=>u6,decodeEinsumEquation:()=>JL,eitherStridesOrDilationsAreOne:()=>aa,expandShapeToKeepDim:()=>nl,exponent:()=>ZL,exponents:()=>KL,fromStringArrayToUint8:()=>vB,fromUint8ToStringArray:()=>bB,getAxesPermutation:()=>A6,getBroadcastDims:()=>Gw,getComplexWithIndex:()=>qL,getEinsumComputePath:()=>tB,getEinsumPermutation:()=>QL,getFusedBiasGradient:()=>$0,getFusedDyActivation:()=>D0,getImageCenter:()=>_L,getInnerMostAxes:()=>RF,getPermuted:()=>$L,getRaggedRank:()=>NL,getReductionAxes:()=>on,getReshaped:()=>DL,getReshapedPermuted:()=>PL,getRowPartitionTypesHelper:()=>TL,getSliceBeginCoords:()=>FL,getSliceSize:()=>OL,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>aB,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>oB,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>iB,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>cB,getSparseReshapeInputOutputMismatchErrorMessage:()=>pB,getSparseReshapeInputOutputMultipleErrorMessage:()=>dB,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>lB,getSparseReshapeNegativeOutputDimErrorMessage:()=>uB,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>gB,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>hB,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>fB,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>mB,getUndoAxesPermutation:()=>mA,isIdentityPermutation:()=>nB,log:()=>Q_,mergeRealAndImagArrays:()=>UL,prepareAndValidate:()=>jw,prepareSplitSize:()=>rB,segment_util:()=>mk,shouldFuse:()=>F0,slice_util:()=>Gt,splitRealAndImagArrays:()=>GL,tupleValuesAreOne:()=>ao,upcastType:()=>jn,validateDefaultValueShape:()=>EL,validateInput:()=>zy,validateUpdateShape:()=>My,warn:()=>Xa});function SL(e,t){let n=e[0].length;e.forEach((r,a)=>{P(r.length===n,()=>`Error in concat${n}D: rank of tensors[${a}] must be the same as the rank of the rest (${n})`)}),P(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 IL(e,t){let n=e[0].slice();for(let s=1;s=0)if(i>=0){if(i!==a)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${r+e}] = ${a} but shape[${r+e}] = ${i}`)}else s[o]=a}return s}function TL(e){let t={FIRST_DIM_SIZE:Xr.FIRST_DIM_SIZE,VALUE_ROWIDS:Xr.VALUE_ROWIDS,ROW_LENGTHS:Xr.ROW_LENGTHS,ROW_SPLITS:Xr.ROW_SPLITS,ROW_LIMITS:Xr.ROW_LIMITS,ROW_STARTS:Xr.ROW_STARTS},n=[];for(let s of e)if(s in t)n.push(t[s]);else break;return n}function NL(e){return e.length===0?0:e[0]===Xr.FIRST_DIM_SIZE?e.length-1:e.length}function EL(e,t){if(e==null||t==null)return;let n=e.length,s=t.length;if(n>=s)throw new Error(`defaultValue.shape=${e} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${n} must be less than ragged tensor input flatValues.rank = ${s})`);for(let r=0;r=0&&o>=0&&a!==1&&a!==o)throw new Error(`defaultValue.shape=${e}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${r-e.length}] = ${a} but ragged tensor input.flatValues.shape[${r-e.length}] = ${o}`)}}var GA=30;function RL(e){return e<=GA?e:em(e,Math.floor(Math.sqrt(e)))}function _L(e,t,n){let s=n*(typeof e=="number"?e:e[0]),r=t*(typeof e=="number"?e:e[1]);return[s,r]}function DL(e,t,n,s=!0){let r=[];if(s)r=r.concat(t.slice(0)),r.push(e[0]/n),r=r.concat(e.slice(1));else{r=r.concat(e[0]);let a=t.length;for(let o=0;o=t*2+1||o%2===1?a.push(o):r.push(o);s.push(...r),s.push(0),s.push(...a)}return s}function PL(e,t,n,s=!0){let r=[];s?r.push(e[0]/n):r.push(e[0]*n);for(let a=1;a/g,kv=",",Sv="...";function JL(e,t){e=e.replace(/\s/g,"");let n=(e.length-e.replace(YL,"").length)/t3.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 ("${t3}").`);let[s,r]=e.split(t3);P(s.indexOf(Sv)===-1,()=>`The ellipsis notation ("${Sv}") is not supported yet.`);let a=s.split(kv),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 d=0;df.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 d=0;dr!==-1),{permutationIndices:n,expandDims:s}}function eB(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 tB(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 sB(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);P(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}P(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}function aB(e){return`Received SparseTensor with denseShape[0] = 0 but indices.shape[0] = ${e}`}function oB(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function iB(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function lB(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function uB(e,t){return`size ${e} must be non-negative, not ${t}`}function cB(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function dB(e,t){let n=It(e),s=It(t);return`Input to reshape is a SparseTensor with ${n} dense values, but the requested shape requires a multiple of ${s}. inputShape=${e} outputShape= ${t}`}function pB(e,t){let n=It(e),s=It(t);return`Input to reshape is a tensor with ${n} dense values, but the requested shape has ${s}. inputShape=${e} outputShape=${t}`}function hB(){return"segment ids must be >= 0"}function fB(){return"segment ids are not increasing"}function mB(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function gB(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}var mk={};We(mk,{collectGatherOpShapeInfo:()=>xB,computeOutShape:()=>AB,segOpComputeOptimalWindowSize:()=>yB});function yB(e,t){let n=!1,s;for(e<=GA?(s=e,n=!0):s=em(e,Math.floor(Math.sqrt(e)));!n;)s>t||s===e?n=!0:s=em(e,s+1);return s}function AB(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(nrm(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function vB(e){return e.map(t=>jp(t))}var Ar={};We(Ar,{nonMaxSuppressionV3Impl:()=>sk,nonMaxSuppressionV4Impl:()=>rk,nonMaxSuppressionV5Impl:()=>ak,whereImpl:()=>j6});var gk={kernelName:dl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>M(e,ou(me(n,"float32"),-1))}}},wB={kernelName:gc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=bt(me(n,"float32")),r=Ln(ye(Ce(1),s));return Dt(ge(e,r))}}}},kB={kernelName:yc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=Ln(ye(bt(me(n,"float32")),1));return ge(e,s)}}}},SB={kernelName:Ta,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=vt(n.shape,s.shape);return{a:()=>{let i=e,l=on(n.shape,r);return l.length>0&&(i=ve(i,l)),W(i,n.shape)},b:()=>{let i=e,l=on(s.shape,r);return l.length>0&&(i=ve(i,l)),W(i,s.shape)}}}},IB={kernelName:go,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((s,r)=>{n[r]=()=>e.clone()}),n}},CB={kernelName:yo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ct(n)}}},TB={kernelName:bc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ct(n)}}},NB={kernelName:vc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,Ln(ye(Ce(1),bt(me(n,"float32")))))}}},EB={kernelName:wc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=Ln(le(Ce(1),bt(me(n,"float32"))));return ge(e,s)}}}},RB={kernelName:pl,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=vt(n.shape,s.shape);return{a:()=>{let i=le(bt(n),bt(s)),l=M(e,ge(s,i)),u=on(n.shape,r);return u.length>0&&(l=ve(l,u)),W(l,n.shape)},b:()=>{let i=le(bt(n),bt(s)),l=Dt(M(e,ge(n,i))),u=on(s.shape,r);return u.length>0&&(l=ve(l,u)),W(l,s.shape)}}}},_B={kernelName:kc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,le(bt(me(n,"float32")),1))}}},DB={kernelName:Sc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,ye(Ce(1),bt(me(n,"float32"))))}}};function $B(e,t,n,s,r,a){let o=_(e,"dy","avgPool3dGrad"),i=_(t,"input","avgPool3dGrad"),l=o,u=i,c=!1;i.rank===4&&(c=!0,l=W(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),u=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),P(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),P(u.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),us("avgPool3dGrad",r,a);let p={dy:l,input:u},d={filterSize:n,strides:s,pad:r,dimRoundingMode:a},h=L.runKernel($m,p,d);return c?W(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var PB=B({avgPool3dGrad_:$B}),FB={kernelName:Np,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{filterSize:r,strides:a,pad:o,dimRoundingMode:i}=n;return{x:()=>PB(e,s,r,a,o,i)}}};function OB(e,t,n,s,r){let a=_(e,"dy","avgPoolGrad"),o=_(t,"input","avgPoolGrad");P(o.rank===a.rank,()=>`Rank of input (${o.rank}) does not match rank of dy (${a.rank})`);let i=o,l=a,u=!1;o.rank===3&&(u=!0,i=W(o,[1,o.shape[0],o.shape[1],o.shape[2]]),l=W(a,[1,a.shape[0],a.shape[1],a.shape[2]])),P(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),P(i.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${i.rank}.`);let c={dy:l,input:i},p={filterSize:n,strides:s,pad:r},d=L.runKernel(Dm,c,p);return u?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var MB=B({avgPoolGrad_:OB}),zB={kernelName:Ao,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{filterSize:r,strides:a,pad:o}=n;return{x:()=>MB(e,s,r,a,o)}}},LB={kernelName:xo,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{let[s,r]=t,{transposeA:a,transposeB:o}=n;return!a&&!o?{a:()=>et(e,r,!1,!0),b:()=>et(s,e,!0,!1)}:!a&&o?{a:()=>et(e,r,!1,!1),b:()=>et(e,s,!0,!1)}:a&&!o?{a:()=>et(r,e,!1,!0),b:()=>et(s,e,!1,!1)}:{a:()=>et(r,e,!0,!0),b:()=>et(e,s,!0,!0)}}},BB={kernelName:hl,gradFunc:(e,t,n)=>{let{blockShape:s,crops:r}=n;return{x:()=>lh(e,s,r)}}},WB={kernelName:mw,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:()=>ve(e,i,!0)}}},VB={kernelName:bo,gradFunc:e=>({x:()=>e.clone()})},UB={kernelName:vo,gradFunc:e=>({x:()=>ct(e)})},GB={kernelName:Na,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{clipValueMin:r,clipValueMax:a}=n;return{x:()=>qn(gr(pi(s,r),hi(s,a)),e,ct(e))}}},HB={kernelName:Rp,inputsToSave:["x"],gradFunc:gk.gradFunc},jB={kernelName:fl,saveAllInputs:!0,gradFunc:(e,t,n)=>{let s=t.map(l=>l.shape),{axis:r}=n,a=yr(r,t[0].shape)[0],o=s.map(l=>l[a]);return Ht(e,o,a).map(l=>()=>l)}},qB={kernelName:wo,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[s,r]=t,{dilations:a,strides:o,pad:i,dataFormat:l}=n;return P(ao(a),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`),{x:()=>oA(s.shape,e,r,o,i,l),filter:()=>BA(s,e,r.shape,o,i,l)}}},XB={kernelName:ko,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{let[s,r]=t,{strides:a,pad:o,dataFormat:i,dimRoundingMode:l}=n;return{dy:()=>ka(e,r,a,o,i,1,l),filter:()=>BA(e,s,r.shape,a,o,i,l)}}};function KB(e,t,n,s,r){let a=e;e.rank===4&&(a=W(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let o=t;o.rank===4&&(o=W(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),P(a.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${a.shape}.`),P(o.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${o.shape}.`),P(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),P(a.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${a.shape[4]}) must match input depth in filter (${n[3]}.`),P(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 L.runKernel(Mm,i,l)}var ZB=B({conv3DBackpropFilter_:KB}),YB={kernelName:_p,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:s,strides:r,pad:a}=n;P(ao(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:()=>p6(o.shape,e,i,r,a),filter:()=>ZB(o,e,i.shape,r,a)}}},JB={kernelName:So,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>M(Dt(S0(me(n,"float32"))),e)}}},QB={kernelName:Io,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>M(I0(me(n,"float32")),e)}}},eW={kernelName:Co,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{axis:r,exclusive:a,reverse:o}=n;return{x:()=>{let i=A6([r],s.rank),l=c0(e,r,a,!o);return i!=null&&(l=tt(l,i)),l}}}},tW={kernelName:To,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:s,strides:r,pad:a,dimRoundingMode:o}=n,i=s==null?[1,1]:s;P(ao(i),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);let[l,u]=t;return P(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),P(u.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`),P(l.shape[3]===u.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),P(aa(r,i),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'.`),us("depthwiseConv2d",a,o),{x:()=>ek(l.shape,e,u,r,a,i,o),filter:()=>Q6(l,e,u.shape,r,a,i,o)}}},nW={kernelName:Dp,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:()=>L.runKernel(tm,a,n),filter:()=>L.runKernel(nm,o,n)}}},sW={kernelName:Eo,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t,s={dy:e,y:n};return{x:()=>L.runKernel(Um,s)}}},rW={kernelName:Ic,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,s=M(Os(Dt(bt(n))),2/Math.sqrt(Math.PI));return{x:()=>M(e,s)}}},aW={kernelName:Ro,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>M(e,n)}}},oW={kernelName:xl,inputsToSave:["input"],gradFunc:(e,t)=>{let[n]=t;return{input:()=>W(e,n.shape)}}},iW={kernelName:bl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>M(e,Os(n))}}},lW={kernelName:_o,gradFunc:e=>({x:()=>ct(e)})},uW={kernelName:Do,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=vt(n.shape,s.shape);return{a:()=>{let i=ge(e,me(s,"float32")),l=on(n.shape,r);return l.length>0?W(ve(i,l),n.shape):i},b:()=>{let i=M(e,me(n,"float32")),l=on(s.shape,r);l.length>0&&(i=W(ve(i,l),s.shape));let u=bt(s);return Dt(ge(i,me(u,"float32")))}}}},cW={kernelName:$o,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{let{varianceEpsilon:s}=n,[r,a,o,i]=t,l=i==null?Ce(1):i,u=on(a.shape,r.shape),c=[];if(a.rank===1){for(let b=0;ba.rank===1?W(M(M(e,As(W(h,[1,1,1,a.shape[0]]),c)),l),r.shape):W(M(M(e,h),l),r.shape),mean:()=>{let b=M(M(h,Ce(-1)),d);return a.rank===1&&(b=ve(b,u)),W(b,a.shape)},variance:()=>{let b=M(M(f,p),d);return a.rank===1&&(b=ve(b,u)),W(b,a.shape)},scale:()=>{let b=M(p,h),w=M(e,b);return a.rank===1&&(w=ve(w,u)),W(w,a.shape)},offset:()=>{let b=e;return a.rank===1&&(b=ve(b,u)),W(b,a.shape)}}}},dW={kernelName:wl,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{let[s,r]=t,{axis:a}=n,o=yr(a,s.shape)[0];return{x:()=>{let l=s.shape,u=r.size,c=l.slice(0,o),p=c.length,d=l.slice(a,l.length).slice(1),h=d.length,f=Iv(0,p),m=Iv(p+1,p+1+h),g=Cv([c,[u],d]),y=W(e,g),x=W(r,[u]),A=Cv([[p],f,m]),b=tt(y,A),w=R0(b,x,s.shape[o]),k=mA(A);return w=tt(w,k),w},indices:()=>r}}};function Iv(e,t){let n=[];for(let s=e;s{let[n,s]=t;return{a:()=>ct(n),b:()=>ct(s)}}},hW={kernelName:Fo,gradFunc:e=>({x:()=>me(e,"float32")})},fW={kernelName:Tc,gradFunc:e=>({x:()=>ct(e)})},mW={kernelName:Nc,gradFunc:e=>({x:()=>ct(e)})},gW={kernelName:Il,gradFunc:e=>({x:()=>ct(e)})},yW={kernelName:Oo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{alpha:r}=n,a=ks(s,0);return{x:()=>qn(a,e,M(e,r))}}},AW={kernelName:Ec,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,le(n,1))}}},xW={kernelName:Mo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,me(n,"float32"))}}},bW={kernelName:yw,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s]=t,{axis:r}=n;return{logits:()=>{let o=Os(s);return ye(e,M(ve(e,r,!0),o))}}}};function vW(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 L.runKernel(qm,i,l)}var wW=B({localResponseNormalizationBackprop_:vW}),kW={kernelName:Fp,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{depthRadius:a,bias:o,alpha:i,beta:l}=n;return{x:()=>wW(s,r,e,a,o,i,l)}}};function yk(e,t,n,s){return t.rankM(e,me(Fs(n,t),e.dtype))}}var Tv={kernelName:zo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let s=n,{reductionIndices:r}=s,a=t[0],o=t[1],i=yr(r,a.shape),l=yk(e,o,a,i);return{x:()=>l.x()}}},SW={kernelName:Lo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t;return{a:()=>M(e,me(pi(n,s),"float32")),b:()=>M(e,me(p0(n,s),"float32"))}}};function IW(e,t,n,s,r,a,o){let i=_(e,"dy","maxPool3dGrad"),l=_(t,"input","maxPool3dGrad"),u=_(n,"output","maxPool3dGrad"),c=i,p=l,d=u,h=!1;l.rank===4&&(h=!0,c=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),p=W(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),d=W(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),P(c.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),P(p.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${p.rank}.`),P(d.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${d.rank}.`),us("maxPool3dGrad",a,o);let f={dy:c,input:p,output:d},m={filterSize:s,strides:r,pad:a,dimRoundingMode:o},g=L.runKernel(Km,f,m);return h?W(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var CW=B({maxPool3dGrad_:IW}),TW={kernelName:Op,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=n;return{x:()=>CW(e,s,r,a,o,i,l)}}};function NW(e,t,n,s,r,a,o){let i=_(e,"dy","maxPoolGrad"),l=_(t,"input","maxPoolGrad"),u=_(n,"output","maxPoolGrad");P(l.rank===i.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${i.rank})`),P(i.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${i.rank}.`),P(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),us("maxPoolGrad",a,o);let c={dy:i,input:l,output:u},p={filterSize:s,strides:r,pad:a,dimRoundingMode:o};return L.runKernel(Xm,c,p)}var EW=B({maxPoolGrad_:NW}),RW={kernelName:Bo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s,r]=t,{filterSize:a,strides:o,pad:i}=n;return{x:()=>EW(e,s,r,a,o,i)}}},_W={kernelName:Wo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{axis:r}=n,a=yr(r,s.shape),i=y6(s.shape,a)[1],l=It(i);return{x:()=>{let c=s.shape.slice();a.forEach(h=>{c[h]=1});let p=W(e,c);return ge(M(p,Ds(s.shape,"float32")),l)}}}},DW={kernelName:Vo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let s=n,{axis:r}=s,[a,o]=t,i=yr(r,a.shape),l=yk(e,o,a,i);return{x:()=>l.x()}}},$W={kernelName:Uo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t;return{a:()=>M(e,me(hi(n,s),"float32")),b:()=>M(e,me(ks(n,s),"float32"))}}},PW={kernelName:Go,inputsToSave:["x"],gradFunc:(e,t,n)=>{let s=t[0],{paddings:r}=n,a=r.map(o=>o[0]);return{x:()=>Oe(e,a,s.shape)}}},FW={kernelName:_c,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=vt(n.shape,s.shape);return{a:()=>{let i=on(n.shape,r);return i.length>0?W(ve(e,i),n.shape):e},b:()=>{let i=M(e,Dt(Hc(ge(n,s)))),l=on(s.shape,r);return l.length>0?W(ve(i,l),s.shape):i}}}},OW={kernelName:Ho,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=vt(n.shape,s.shape);return{a:()=>{let i=M(e,me(s,"float32")),l=on(n.shape,r);return l.length>0?W(ve(i,l),n.shape):i},b:()=>{let i=M(e,me(n,"float32")),l=on(s.shape,r);return l.length>0?W(ve(i,l),s.shape):i}}}},MW={kernelName:Rl,gradFunc:e=>({x:()=>Dt(e)})},zW={kernelName:Fl,inputsToSave:["indices"],gradFunc:(e,t)=>{let n=t[0];return{indices:()=>Vt(n.shape,"float32")}}},LW={kernelName:Pl,gradFunc:e=>({x:()=>ct(e)})},BW={kernelName:Ol,saveAllInputs:!0,gradFunc:(e,t,n)=>{let{axis:s}=n;return bn(e,s).map(a=>()=>a)}},Nv={kernelName:jo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let s=t[0],{paddings:r}=n,a=r.map(o=>o[0]);return{x:()=>Oe(e,a,s.shape)}}},WW={kernelName:qo,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[n,s,r]=t,a=n,o=s,i=vt(a.shape,o.shape);return{a:()=>{let c=me(o,"float32"),p=M(e,M(c,Ia(a,ye(c,Ce(1))))),d=on(a.shape,i);return d.length>0&&(p=ve(p,d)),W(p,a.shape)},b:()=>{let c=ks(a,0),p=qn(c,Ms(a),ct(a)),d=M(e,M(r,p)),h=on(o.shape,i);return h.length>0&&(d=ve(d,h)),W(d,o.shape)}}}},VW={kernelName:Xo,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[n,s]=t,r=ks(n,0);return{x:()=>qn(r,e,M(e,s)),alpha:()=>{let a=qn(r,ct(e),M(e,n)),o=on(s.shape,e.shape);return o.length>0&&(a=ve(a,o)),W(a,s.shape)}}}};function UW(e,t,n){let s=e.shape.slice();s[n]=1;let r=W(t,s),a=mp(e,n,!0,!1),o=mp(e,n,!0,!0),i=M(a,o);return M(r,i)}function GW(e,t,n){let s=e.shape.length,r=s-n.length,a=T.getAxesPermutation(n,s),o=e;a!=null&&(o=tt(e,a));let i=o.shape.slice(),u=i.splice(s-n.length,n.length).reduce((d,h)=>d*h,1);i.push(u);let c=o.reshape(i),p=UW(c,t,r);if(p=p.reshape(o.shape),a!=null){let d=T.getUndoAxesPermutation(a);p=tt(p,d)}return p}var HW={kernelName:Ko,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{axis:r}=n,a=[];return r==null?a=s.shape.map((o,i)=>i):typeof r=="number"?a=[r]:a=r,{x:()=>GW(s,e,a)}}},jW={kernelName:No,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=vt(n.shape,s.shape);return{a:()=>{let i=ge(e,me(s,"float32")),l=on(n.shape,r);return l.length>0?W(ve(i,l),n.shape):i},b:()=>{let i=M(e,me(n,"float32")),l=on(s.shape,r);l.length>0&&(i=W(ve(i,l),s.shape));let u=bt(s);return Dt(ge(i,me(u,"float32")))}}}},qW={kernelName:Ml,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,Dt(bt(n)))}}},XW={kernelName:Qo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,s=M(hi(n,6),ou(n));return{x:()=>M(e,me(s,"float32"))}}},KW={kernelName:Zo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>M(e,me(ou(n),"float32"))}}},ZW={kernelName:zl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>W(e,n.shape)}}},YW={kernelName:Jo,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[s]=t,r={dy:e,images:s};return{images:()=>L.runKernel(t0,r,n)}}},JW={kernelName:Yo,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[s]=t,r={dy:e,images:s};return{images:()=>L.runKernel(e0,r,n)}}},QW={kernelName:Ll,gradFunc:(e,t,n)=>{let{dims:s}=n,r=yr(s,e.shape);return{x:()=>Js(e,r)}}},eV={kernelName:Bl,gradFunc:e=>({x:()=>ct(e)})},tV={kernelName:ei,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Dt(ge(e,M(Ia(n,1.5),2)))}}},nV={kernelName:Vl,inputsToSave:["condition"],gradFunc:(e,t)=>{let[n]=t;return{condition:()=>me(ct(n),"float32"),t:()=>M(e,me(n,e.dtype)),e:()=>M(e,me(ah(n),e.dtype))}}},sV={kernelName:Pc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let s=ks(n,Ce(0)),r=Ce(hk),a=Ce(fk),o=M(e,a),i=M(M(e,r),Os(me(n,"float32")));return qn(s,o,i)}}}},rV={kernelName:ni,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>M(e,M(n,ye(Ce(1),n)))}}},aV={kernelName:Fc,gradFunc:e=>({x:()=>ct(e)})},oV={kernelName:ti,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>M(nh(me(n,"float32")),e)}}},iV={kernelName:Gl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>M(u0(me(n,"float32")),e)}}},lV={kernelName:Ul,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{begin:r,size:a}=n,o=s.shape,[i,l]=n6(s,r,a),u=[];for(let c=0;ctr(e,u)}}},uV={kernelName:ai,outputsToSave:[!0],gradFunc:(e,t,n)=>{let[s]=t,{dim:r}=n,a=!0,o=M(e,s);return{logits:()=>ye(o,M(ve(o,[r],a),s))}}},cV={kernelName:Oc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>M(e,Mn(n))}}},Ev={kernelName:Hl,gradFunc:(e,t,n)=>{let{blockShape:s,paddings:r}=n;return{x:()=>th(e,s,r)}}},Rv={kernelName:jl,gradFunc:(e,t,n)=>{let{axis:s}=n;return{x:()=>ut(e,s)}}},dV={kernelName:si,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,M(Ln(me(n,"float32")),2))}}},pV={kernelName:zc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>M(e,M(me(n,"float32"),2))}}},hV={kernelName:oi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=Ce(2);return{a:()=>M(e,M(r,ye(n,s))),b:()=>M(e,M(r,ye(s,n)))}}},fV={kernelName:ui,gradFunc:e=>({x:()=>ct(e)})},mV={kernelName:ii,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,s]=t,r=vt(n.shape,s.shape);return{a:()=>{let i=e,l=on(n.shape,r);return l.length>0&&(i=ve(i,l)),W(i,n.shape)},b:()=>{let i=e,l=on(s.shape,r);return l.length>0&&(i=ve(i,l)),W(Dt(i),s.shape)}}}},gV={kernelName:ri,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,r=s.shape.slice(),{axis:a}=n;yr(a,s.shape).forEach(u=>{r[u]=1});let i=W(e,r),l=M(i,Ds(s.shape,"float32"));return{x:()=>l}}},yV={kernelName:Xl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>ge(e,bt(nh(n)))}}},AV={kernelName:li,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>M(ye(Ce(1),bt(n)),e)}}},xV={kernelName:Ea,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[s]=t,{reps:r}=n;return{x:()=>{let o=ct(s);if(s.rank===1)for(let i=0;i{let s=n,{perm:r}=s,a=mA(r);return{x:()=>tt(e,a)}}},vV={kernelName:Yl,gradFunc:(e,t,n)=>{let s=n,{axis:r}=s;return{value:()=>ln(e,r)}}},wV={kernelName:Gp,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>kV(e,n)}}};function kV(e,t){let n=oa(t,ct(t)),s=jc(e,n),r=pi(t,Ce(0,"int32")),a=s.rank-r.rank;for(let i=0;i({x:()=>ct(e)})},IV=[gk,wB,kB,SB,IB,CB,TB,NB,EB,RB,_B,DB,FB,zB,LB,BB,WB,VB,UB,GB,HB,jB,XB,qB,YB,JB,QB,eW,tW,nW,jW,sW,rW,aW,oW,iW,uW,lW,cW,dW,pW,hW,fW,mW,gW,yW,AW,xW,bW,kW,Tv,Tv,SW,TW,RW,_W,DW,$W,PW,FW,OW,MW,zW,LW,BW,Nv,Nv,WW,VW,HW,qW,XW,KW,ZW,YW,JW,QW,eV,tV,nV,sV,rV,aV,oV,iV,lV,uV,cV,Ev,Ev,Rv,Rv,dV,hV,pV,fV,mV,gV,yV,AV,xV,bV,vV,wV,SV];for(let e of IV)Aw(e);se().prototype.abs=function(){return this.throwIfDisposed(),rn(this)};se().prototype.acos=function(){return this.throwIfDisposed(),Vy(this)};se().prototype.acosh=function(){return this.throwIfDisposed(),Uy(this)};se().prototype.add=function(e){return this.throwIfDisposed(),le(this,e)};se().prototype.all=function(e,t){return this.throwIfDisposed(),o0(this,e,t)};se().prototype.any=function(e,t){return this.throwIfDisposed(),fp(this,e,t)};se().prototype.argMax=function(e){return this.throwIfDisposed(),Ps(this,e)};se().prototype.argMin=function(e){return this.throwIfDisposed(),Gy(this,e)};se().prototype.asScalar=function(){return this.throwIfDisposed(),P(this.size===1,()=>"The array must have only 1 element."),W(this,[])};se().prototype.asType=function(e){return this.throwIfDisposed(),me(this,e)};se().prototype.as1D=function(){return this.throwIfDisposed(),W(this,[this.size])};se().prototype.as2D=function(e,t){return this.throwIfDisposed(),W(this,[e,t])};se().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),W(this,[e,t,n])};se().prototype.as4D=function(e,t,n,s){return this.throwIfDisposed(),W(this,[e,t,n,s])};se().prototype.as5D=function(e,t,n,s,r){return this.throwIfDisposed(),W(this,[e,t,n,s,r])};se().prototype.asin=function(){return this.throwIfDisposed(),Hy(this)};se().prototype.asinh=function(){return this.throwIfDisposed(),jy(this)};se().prototype.atan=function(){return this.throwIfDisposed(),qy(this)};se().prototype.atan2=function(e){return this.throwIfDisposed(),Xy(this,e)};se().prototype.atanh=function(){return this.throwIfDisposed(),Ky(this)};se().prototype.avgPool=function(e,t,n,s){return this.throwIfDisposed(),eh(this,e,t,n,s)};se().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),th(this,e,t)};se().prototype.batchNorm=function(e,t,n,s,r){return this.throwIfDisposed(),Wc(this,e,t,n,s,r)};se().prototype.broadcastTo=function(e){return this.throwIfDisposed(),Xi(this,e)};se().prototype.cast=function(e){return this.throwIfDisposed(),me(this,e)};se().prototype.ceil=function(){return this.throwIfDisposed(),nA(this)};se().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),bs(this,e,t)};se().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof st&&(e=[e]),ut([this,...e],t)};se().prototype.conv1d=function(e,t,n,s,r,a){return this.throwIfDisposed(),i0(this,e,t,n,s,r,a)};se().prototype.conv2dTranspose=function(e,t,n,s,r){return this.throwIfDisposed(),l0(this,e,t,n,s,r)};se().prototype.conv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),ka(this,e,t,n,s,r,a)};se().prototype.cos=function(){return this.throwIfDisposed(),nh(this)};se().prototype.cosh=function(){return this.throwIfDisposed(),u0(this)};se().prototype.cumprod=function(e,t,n){return this.throwIfDisposed(),mp(this,e,t,n)};se().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),c0(this,e,t,n)};se().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),uA(this,e,t)};se().prototype.depthwiseConv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),Vc(this,e,t,n,s,r,a)};se().prototype.dilation2d=function(e,t,n,s,r){return this.throwIfDisposed(),cA(this,e,t,n,s,r)};se().prototype.divNoNan=function(e){return this.throwIfDisposed(),dA(this,e)};se().prototype.div=function(e){return this.throwIfDisposed(),ge(this,e)};se().prototype.dot=function(e){return this.throwIfDisposed(),pA(this,e)};se().prototype.elu=function(){return this.throwIfDisposed(),Uc(this)};se().prototype.equal=function(e){return this.throwIfDisposed(),Fs(this,e)};se().prototype.erf=function(){return this.throwIfDisposed(),hA(this)};se().prototype.euclideanNorm=function(e,t){return this.throwIfDisposed(),gA(this,e,t)};se().prototype.exp=function(){return this.throwIfDisposed(),Os(this)};se().prototype.expandDims=function(e){return this.throwIfDisposed(),Ft(this,e)};se().prototype.expm1=function(){return this.throwIfDisposed(),yA(this)};se().prototype.fft=function(){return this.throwIfDisposed(),dh(this)};se().prototype.flatten=function(){return this.throwIfDisposed(),W(this,[this.size])};se().prototype.floor=function(){return this.throwIfDisposed(),Hc(this)};se().prototype.floorDiv=function(e){return this.throwIfDisposed(),Bc(this,e)};se().prototype.gather=function(e,t){return this.throwIfDisposed(),jc(this,e,t)};se().prototype.greaterEqual=function(e){return this.throwIfDisposed(),pi(this,e)};se().prototype.greater=function(e){return this.throwIfDisposed(),ks(this,e)};se().prototype.ifft=function(){return this.throwIfDisposed(),sc(this)};se().prototype.irfft=function(){return this.throwIfDisposed(),T0(this)};se().prototype.isFinite=function(){return this.throwIfDisposed(),AA(this)};se().prototype.isInf=function(){return this.throwIfDisposed(),xA(this)};se().prototype.isNaN=function(){return this.throwIfDisposed(),bA(this)};se().prototype.leakyRelu=function(e){return this.throwIfDisposed(),sh(this,e)};se().prototype.lessEqual=function(e){return this.throwIfDisposed(),hi(this,e)};se().prototype.less=function(e){return this.throwIfDisposed(),p0(this,e)};se().prototype.localResponseNormalization=function(e,t,n,s){return this.throwIfDisposed(),vA(this,e,t,n,s)};se().prototype.logSigmoid=function(){return this.throwIfDisposed(),wA(this)};se().prototype.logSoftmax=function(e){return this.throwIfDisposed(),f0(this,e)};se().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),m0(this,e,t)};se().prototype.log=function(){return this.throwIfDisposed(),Ms(this)};se().prototype.log1p=function(){return this.throwIfDisposed(),rh(this)};se().prototype.logicalAnd=function(e){return this.throwIfDisposed(),gr(this,e)};se().prototype.logicalNot=function(){return this.throwIfDisposed(),ah(this)};se().prototype.logicalOr=function(e){return this.throwIfDisposed(),g0(this,e)};se().prototype.logicalXor=function(e){return this.throwIfDisposed(),kA(this,e)};se().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),et(this,e,t,n)};se().prototype.maxPool=function(e,t,n,s){return this.throwIfDisposed(),oh(this,e,t,n,s)};se().prototype.max=function(e,t){return this.throwIfDisposed(),yn(this,e,t)};se().prototype.maximum=function(e){return this.throwIfDisposed(),oa(this,e)};se().prototype.mean=function(e,t){return this.throwIfDisposed(),Wt(this,e,t)};se().prototype.min=function(e,t){return this.throwIfDisposed(),Sa(this,e,t)};se().prototype.minimum=function(e){return this.throwIfDisposed(),qc(this,e)};se().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),IA(this,e,t)};se().prototype.mod=function(e){return this.throwIfDisposed(),ru(this,e)};se().prototype.mul=function(e){return this.throwIfDisposed(),M(this,e)};se().prototype.neg=function(){return this.throwIfDisposed(),Dt(this)};se().prototype.norm=function(e,t,n){return this.throwIfDisposed(),Gc(this,e,t,n)};se().prototype.notEqual=function(e){return this.throwIfDisposed(),sl(this,e)};se().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),ec(this,e,t,n)};se().prototype.onesLike=function(){return this.throwIfDisposed(),zs(this)};se().prototype.pad=function(e,t){return this.throwIfDisposed(),tr(this,e,t)};se().prototype.pool=function(e,t,n,s,r,a){return this.throwIfDisposed(),CA(this,e,t,n,s,r,a)};se().prototype.pow=function(e){return this.throwIfDisposed(),Ia(this,e)};se().prototype.prelu=function(e){return this.throwIfDisposed(),uh(this,e)};se().prototype.prod=function(e,t){return this.throwIfDisposed(),TA(this,e,t)};se().prototype.reciprocal=function(){return this.throwIfDisposed(),RA(this)};se().prototype.relu=function(){return this.throwIfDisposed(),Lr(this)};se().prototype.relu6=function(){return this.throwIfDisposed(),x0(this)};se().prototype.reshapeAs=function(e){return this.throwIfDisposed(),W(this,e.shape)};se().prototype.reshape=function(e){return this.throwIfDisposed(),W(this,e)};se().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),ok(this,e,t,n)};se().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),ik(this,e,t,n)};se().prototype.reverse=function(e){return this.throwIfDisposed(),Js(this,e)};se().prototype.rfft=function(){return this.throwIfDisposed(),ph(this)};se().prototype.round=function(){return this.throwIfDisposed(),b0(this)};se().prototype.rsqrt=function(){return this.throwIfDisposed(),v0(this)};se().prototype.selu=function(){return this.throwIfDisposed(),w0(this)};se().prototype.separableConv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),k0(this,e,t,n,s,r,a)};se().prototype.sigmoid=function(){return this.throwIfDisposed(),Mn(this)};se().prototype.sign=function(){return this.throwIfDisposed(),_A(this)};se().prototype.sin=function(){return this.throwIfDisposed(),S0(this)};se().prototype.sinh=function(){return this.throwIfDisposed(),I0(this)};se().prototype.slice=function(e,t){return this.throwIfDisposed(),Oe(this,e,t)};se().prototype.softmax=function(e){return this.throwIfDisposed(),au(this,e)};se().prototype.softplus=function(){return this.throwIfDisposed(),su(this)};se().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),lh(this,e,t)};se().prototype.split=function(e,t){return this.throwIfDisposed(),Ht(this,e,t)};se().prototype.sqrt=function(){return this.throwIfDisposed(),Ln(this)};se().prototype.square=function(){return this.throwIfDisposed(),bt(this)};se().prototype.squaredDifference=function(e){return this.throwIfDisposed(),N0(this,e)};se().prototype.squeeze=function(e){return this.throwIfDisposed(),Ge(this,e)};se().prototype.stack=function(e,t){this.throwIfDisposed();let n=e instanceof st?[this,e]:[this,...e];return ln(n,t)};se().prototype.step=function(e){return this.throwIfDisposed(),ou(this,e)};se().prototype.stridedSlice=function(e,t,n,s,r,a,o,i){return this.throwIfDisposed(),DA(this,e,t,n,s,r,a,o,i)};se().prototype.sub=function(e){return this.throwIfDisposed(),ye(this,e)};se().prototype.sum=function(e,t){return this.throwIfDisposed(),ve(this,e,t)};se().prototype.tan=function(){return this.throwIfDisposed(),$A(this)};se().prototype.tanh=function(){return this.throwIfDisposed(),tl(this)};se().prototype.tile=function(e){return this.throwIfDisposed(),As(this,e)};se().prototype.toBool=function(){return this.throwIfDisposed(),me(this,"bool")};se().prototype.toFloat=function(){return this.throwIfDisposed(),me(this,"float32")};se().prototype.toInt=function(){return this.throwIfDisposed(),me(this,"int32")};se().prototype.topk=function(e,t){return this.throwIfDisposed(),PA(this,e,t)};se().prototype.transpose=function(e){return this.throwIfDisposed(),tt(this,e)};se().prototype.unique=function(e){return this.throwIfDisposed(),FA(this,e)};se().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),R0(this,e,t)};se().prototype.unstack=function(e){return this.throwIfDisposed(),bn(this,e)};se().prototype.where=function(e,t){return this.throwIfDisposed(),qn(e,this,t)};se().prototype.zerosLike=function(){return this.throwIfDisposed(),ct(this)};var ma=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,ma.prototype)}},Rr=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Rr.prototype)}},H=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,H.prototype)}},Ke=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Ke.prototype)}},Ak=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Ak.prototype)}},xk=class{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){let n=this.cache.keys().next().value;this.cache.delete(n)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;tn.toUpperCase())}var cr={};function HA(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function N3(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>N3(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:N3(s))}}}function fh(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 cr)o=cr[a];else if(o=t[a],o==null)throw new H(`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 H(`${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 cr?[i,l]=cr.className:o in t&&([i,l]=t[o]),i==null)throw new H(`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 u={};for(let h of Object.keys(cr))u[h]=cr[h];for(let h of Object.keys(n))u[h]=n[h];let c=a.config;c.customObjects=u;let p=Object.assign({},cr);for(let h of Object.keys(n))cr[h]=n[h];N3(a.config);let d=l(i,a.config,n,r);return cr=Object.assign({},p),d}else{let u=Object.assign({},cr);for(let p of Object.keys(n))cr[p]=n[p];let c=new i(a.config);return cr=Object.assign({},u),c}}}function CV(e,t){return et?1:0}function Ef(e,t){return-1*CV(e,t)}function Qa(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function TV(e){if(e==null)throw new H(`Invalid value in obj: ${JSON.stringify(e)}`);for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function iu(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new H(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function jA(e,t,n=0,s=1/0){return Kr(n>=0),Kr(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every(r=>typeof r===t)}function Tn(e,t){Array.isArray(e)?(v.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,s)=>Tn(n,`element ${s+1} of ${t}`))):v.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${bk(e)}.`)}function bk(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>bk(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function NV(e,t,n){let s=n!=null?n():v.now(),r;return(...o)=>{let i=n!=null?n():v.now();return i-s0){let n=`${e}_${t}`;return zu.set(n,1),n}else return e}var MV=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Ck(e){return!!e.match(MV)}function zV(e){return e===parseInt(e.toString(),10)}function eo(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 Fr(e,t){if(t{if(e.shape.length!==2)throw new H(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let n=gh(e,1);return E3(n,[1,t,1])})}function BV(e){let t=[eo(e.shape)];return W(e,t)}function WV(e){if(e.rank<=1)throw new H(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);let t=[e.shape[0],eo(e.shape,1)];return W(e,t)}function Zi(e,t,n){return X(()=>{switch(e.rank){case 1:return ch(e,t,n);case 2:return C0(e,[t,0],[n,e.shape[1]]);case 3:return fi(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return oo(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return Oe(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return Oe(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 H(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function s3(e,t,n){return X(()=>{switch(e.rank){case 1:return ch(e,t,n);case 2:return C0(e,[0,t],[e.shape[0],n]);case 3:return fi(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return oo(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new H(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function _f(e,t,n,s){return X(()=>{switch(e.rank){case 1:return ch(e,t,n);case 2:switch(s){case 1:return Zi(e,t,n);case 2:return s3(e,t,n);default:throw new H(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return Zi(e,t,n);case 2:return fi(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return s3(e,t,n);default:throw new H(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return Zi(e,t,n);case 2:return oo(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return oo(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return s3(e,t,n);default:throw new H(`The axis is not within the rank of the tensor ${s}`)}default:throw new H(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function qA(e,t=-1){let n;return t<0&&(n=e[0].rank,n!==0?t=n:t=0),t===e[0].rank&&(t=-1),ut(e,t)}function $v(e,t){switch(e.rank){case 1:return sA([e,t]);case 2:return nu([e,t],0);case 3:return rA([e,t],0);case 4:return aA([e,t],0);default:throw new H(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function E3(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new H(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return As(e,t)}function U0(e,t=0,n=1,s,r){return A0(e,t,n,s,r)}function Qr(e,t,n,s){if(e.rank<2||t.rank<2)throw new Ke(`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 Ke(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and y shape = ${t.shape}`)}if(e.rank===2&&t.rank===2)return rc.matMul({a:e,b:t,transposeA:!1,transposeB:!1,bias:s?R3(e.rank,s,Or()):null,activation:n});{let r=e.shape.slice(),a=r.pop();e=W(e,[-1,a]);let o=t.shape.slice(),i=o.pop(),l=o.pop(),u=[...o,i],c=Array.from({length:t.rank},(f,m)=>m===0?t.rank-2:m<=t.rank-2?m-1:m);t=W(tt(t,c),[l,-1]);let p=[...r,...u],d=!1,h=!1;return W(rc.matMul({a:e,b:t,transposeA:d,transposeB:h,bias:s?R3(e.rank,s,Or()):null,activation:n}),p)}}function Tk(e,t,n){return X(()=>(Array.isArray(t)?t=Ot(t,"int32"):t=me(t,"int32"),jc(e,t,n)))}function yh(e){return M(e,e)}function R3(e,t,n){let s=t.shape;if(t.rank!==1&&t.rank!==e)throw new H(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(n==="channelsFirst")return s.length===1?W(t,[1,s[0],1,1,1]):W(t,[1,s[3],s[0],s[1],s[2]]);if(n==="channelsLast")return s.length===1?W(t,[1,1,1,1,s[0]]):W(t,[1].concat(s))}else if(e===4){if(n==="channelsFirst")return s.length===1?W(t,[1,s[0],1,1]):W(t,[1,s[2],s[0],s[1]]);if(n==="channelsLast")return s.length===1?W(t,[1,1,1,s[0]]):W(t,[1].concat(s))}else if(e===3){if(n==="channelsFirst")return s.length===1?W(t,[1,s[0],1]):W(t,[1,s[1],s[0]]);if(n==="channelsLast")return s.length===1?W(t,[1,1,s[0]]):W(t,[1].concat(s))}else if(e<3)return t;throw new H(`Unsupported input rank by biasAdd: ${t.rank}`)}function Br(e,t,n){return X(()=>(n==null&&(n=Or()),Qt(n),le(e,R3(e.rank,t,n))))}function VV(e,t=1){if(t!==1)throw new Ke(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Uc(e)}function UV(e){return X(()=>ge(e,le(rn(e),1)))}function Nk(e,t,n,s){return X(()=>zA(e,t,n,s))}function GV(e){return X(()=>{let t=le(.5,M(.2,e));return bs(t,0,1)})}function Ah(e,t,n=!1){return n?e():t()}var HV=["fanIn","fanOut","fanAvg"],jV=["normal","uniform","truncatedNormal"];function qV(e){iu(HV,"FanMode",e)}function XV(e){iu(jV,"Distribution",e)}var xr=class extends ce.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},XA=class extends xr{apply(e,t){return Vt(e,t)}};XA.className="Zeros";ce.registerClass(XA);var G0=class extends xr{apply(e,t){return Ds(e,t)}};G0.className="Ones";ce.registerClass(G0);var KA=class extends xr{constructor(e){if(super(),typeof e!="object")throw new H(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new H(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return X(()=>M(Ce(this.value),Ds(e,t)))}getConfig(){return{value:this.value}}};KA.className="Constant";ce.registerClass(KA);var ZA=class extends xr{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 Xc(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};ZA.className="RandomUniform";ce.registerClass(ZA);var YA=class extends xr{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 Ke(`randomNormal does not support dType ${t}.`);return U0(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};YA.className="RandomNormal";ce.registerClass(YA);var JA=class extends xr{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 Ke(`truncatedNormal does not support dType ${t}.`);return E0(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};JA.className="TruncatedNormal";ce.registerClass(JA);var QA=class extends xr{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 H("Identity matrix initializer can only be used for 2D square matrices.");return M(this.gain,d0(e[0]))})}getConfig(){return{gain:this.gain}}};QA.className="Identity";ce.registerClass(QA);function KV(e,t="channelsLast"){let n,s;if(Qt(t),e.length===2)n=e[0],s=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let r=eo(e,2);n=e[1]*r,s=e[0]*r}else if(t==="channelsLast"){let r=eo(e,0,e.length-2);n=e[e.length-2]*r,s=e[e.length-1]*r}}else{let r=eo(e);n=Math.sqrt(r),s=Math.sqrt(r)}return[n,s]}var vs=class extends xr{constructor(e){if(super(),e.scale<0)throw new H(`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,qV(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,XV(this.distribution),this.seed=e.seed}apply(e,t){let n=KV(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 Ke(`${this.getClassName()} does not support dType ${t}.`);return E0(e,0,o,t,this.seed)}else{let o=Math.sqrt(3*a);return Xc(e,-o,o,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};vs.className="VarianceScaling";ce.registerClass(vs);var H0=class extends vs{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return vs.className}};H0.className="GlorotUniform";ce.registerClass(H0);var j0=class extends vs{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return vs.className}};j0.className="GlorotNormal";ce.registerClass(j0);var q0=class extends vs{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return vs.className}};q0.className="HeNormal";ce.registerClass(q0);var X0=class extends vs{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return vs.className}};X0.className="HeUniform";ce.registerClass(X0);var K0=class extends vs{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return vs.className}};K0.className="LeCunNormal";ce.registerClass(K0);var Z0=class extends vs{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return vs.className}};Z0.className="LeCunNormal";ce.registerClass(Z0);var e5=class extends xr{constructor(e){if(super(),this.DEFAULT_GAIN=1,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,this.seed!=null)throw new Ke("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return X(()=>{if(e.length<2)throw new Ke("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=U0(n,0,1,"float32"),r=VA.gramSchmidt(s);return e[0]>e[1]&&(r=tt(r)),M(this.gain,r)})}getConfig(){return{gain:this.gain,seed:this.seed}}};e5.className="Orthogonal";ce.registerClass(e5);var Pv={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 Fv(e,t={}){return fh(e,ce.SerializationMap.getMap().classNameMap,t,"initializer")}function Ut(e){return HA(e)}function Mt(e){if(typeof e=="string"){let t=e in Pv?Pv[e]:e;if(t==="GlorotNormal")return new j0;if(t==="GlorotUniform")return new H0;if(t==="HeNormal")return new q0;if(t==="HeUniform")return new X0;if(t==="LeCunNormal")return new K0;if(t==="LeCunUniform")return new Z0;{let n={};return n.className=t,n.config={},Fv(n)}}else return e instanceof xr?e:Fv(e)}function _3(e){return Array.isArray(e)&&Array.isArray(e[0])}function lm(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Ze(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new H(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function At(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new H(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function um(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 Ov="Variable",Ek=class{constructor(e,t="float32",n=Ov,s=!0,r=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=wk(),n=n==null?Ov:n,this.originalName=Sk(n),this.name=Ik(this.originalName),this.trainable_=s,this.constraint=r,this.val=OA(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),ZV(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 ZV(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function D3(e){return e.map(t=>t.read())}function t5(e){e.forEach(t=>{t[0].write(t[1])})}var an=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||{}}},_r=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=wk(),a!=null&&(this.originalName=Sk(a),this.name=Ik(this.originalName)),this.rank=t.length}},YV=0,Y0=class{constructor(e,t){this.callArgs=t,this.id=YV++,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}}},JV=0,dt=class extends ce.Serializable{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=JV++,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=ga(n)+"_"+V0(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 Rr(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new H(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return ys(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return ys(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new ma(`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 ma(`Layer ${this.name} is not connected, no input to return.`);return ys(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new ma(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new ma(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return ys(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=_t(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=_t(this.inputSpec);if(e.length!==t.length)throw new H(`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 H(`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(u!=null&&[u,null].indexOf(c)===-1)throw new H(`Input ${n} is incompatible with layer ${this.name}: expected axis ${l} of input shape to have value ${u} 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 _t(e))a.push(o.shape);this.build(ys(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=_t(a),i=[];for(let l of o)n.indexOf(l)!==-1&&(l=l.clone()),i.push(l);if(a=ys(i),this.activityRegularizer!=null)throw new Ke("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}else{let a=QV(e),o=this.computeOutputShape(a),i,l=eU(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?a[0]:a),o!=null&&o.length>0&&Array.isArray(o[0])?i=o.map((u,c)=>new _r(l,u,this,_t(e),t,this.name,c)):i=new _r(l,o,this,_t(e),t,this.name),this.addInboundNode(e,i,null,null,a,o,t),this._refCount++,this.activityRegularizer!=null)throw new Ke("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 ma(`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 ma(`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 Rr(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return um(this.weights)}build(e){this.built=!0}getWeights(e=!1){return D3(e?this.trainableWeights:this.weights)}setWeights(e){X(()=>{let t=this.weights;if(t.length!==e.length)throw new H(`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=D3(t);for(let r=0;rr.apply(u.read())),a==null&&(a=!0),a?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=_t(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=_t(e);t=_t(t),n=_t(n),s=_t(s),r=lm(r),a=lm(a);let l=[],u=[],c=[];for(let p of i)l.push(p.sourceLayer),u.push(p.nodeIndex),c.push(p.tensorIndex);new Y0({outboundLayer:this,inboundLayers:l,nodeIndices:u,tensorIndices:c,inputTensors:i,outputTensors:t,inputMasks:n,outputMasks:s,inputShapes:r,outputShapes:a},o);for(let p=0;pe.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 QV(e){e=_t(e);let t=[];for(let n of e)t.push(n.shape);return ys(t)}function eU(e){return"float32"}function Rk(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;af.name),l=[],u=t.names();for(let f of i)u.indexOf(f)!==-1?l.push(t.getValue(f)):l.push(null);s!=null&&(s.maxNumTensors=-1/0,s.minNumTensors=1/0);let c=i.join(",")+"|"+t.names().sort().join(","),p=cm.get(c),d;if(p==null){let f=sU(o,t);p=f.sorted,d=f.recipientCounts,cm.put(c,p),dm.put(c,d)}d={},r||Object.assign(d,dm.get(c));let h=new Hi(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=Mv(e[0],t);n=r.sorted,s=r.recipientMap}else{let r=new Set;for(let a of e){let{sorted:o,recipientMap:i}=Mv(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(u=>s[l].add(u))}}return{sorted:n,recipientCounts:rU(s)}}function rU(e){let t={};for(let n in e)t[n]=e[n].size;return t}function Mv(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 u of i.inputs)r[u.name]==null&&(r[u.name]=new Set),r[u.name].add(i.name),!n.has(u.name)&&a.push(u)}}return{sorted:s,recipientMap:r}}function aU(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let n=null;for(let s=0;s100,nU);var Dk={};We(Dk,{maxNorm:()=>iU,minMaxNorm:()=>cU,nonNeg:()=>uU,unitNorm:()=>lU});function n5(e,t){return X(()=>Ln(ve(M(e,e),t,!0)))}var xh=class extends ce.Serializable{getConfig(){return{}}},s5=class extends xh{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=n5(e,this.axis),n=bs(t,0,this.maxValue);return M(e,ge(n,le(mn(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};s5.className="MaxNorm";ce.registerClass(s5);var r5=class extends xh{constructor(e){super(),this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return X(()=>ge(e,le(mn(),n5(e,this.axis))))}getConfig(){return{axis:this.axis}}};r5.className="UnitNorm";ce.registerClass(r5);var a5=class extends xh{apply(e){return Lr(e)}};a5.className="NonNeg";ce.registerClass(a5);var o5=class extends xh{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=n5(e,this.axis),n=le(M(this.rate,bs(t,this.minValue,this.maxValue)),M(1-this.rate,t));return M(e,ge(n,le(mn(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};o5.className="MinMaxNorm";ce.registerClass(o5);var zv={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function An(e){return HA(e)}function Lv(e,t={}){return fh(e,ce.SerializationMap.getMap().classNameMap,t,"constraint")}function xn(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in zv?zv[e]:e,config:{}};return Lv(n)}else return e instanceof xh?e:Lv(e)}function iU(e){return new s5(e)}function lU(e){return new r5(e)}function uU(){return new a5}function cU(e){return new o5(e)}var $k={};We($k,{constant:()=>hU,glorotNormal:()=>bU,glorotUniform:()=>xU,heNormal:()=>vU,heUniform:()=>wU,identity:()=>yU,leCunNormal:()=>kU,leCunUniform:()=>SU,ones:()=>pU,orthogonal:()=>IU,randomNormal:()=>mU,randomUniform:()=>fU,truncatedNormal:()=>gU,varianceScaling:()=>AU,zeros:()=>dU});function dU(){return new XA}function pU(){return new G0}function hU(e){return new KA(e)}function fU(e){return new ZA(e)}function mU(e){return new YA(e)}function gU(e){return new JA(e)}function yU(e){return new QA(e)}function AU(e){return new vs(e)}function xU(e){return new H0(e)}function bU(e){return new j0(e)}function vU(e){return new q0(e)}function wU(e){return new X0(e)}function kU(e){return new K0(e)}function SU(e){return new Z0(e)}function IU(e){return new e5(e)}var Pk={};We(Pk,{Layer:()=>dt,RNN:()=>ia,RNNCell:()=>Sh,activation:()=>YG,add:()=>oH,alphaDropout:()=>UH,average:()=>iH,averagePooling1d:()=>fx,averagePooling2d:()=>mx,averagePooling3d:()=>gx,avgPool1d:()=>gH,avgPool2d:()=>AH,avgPool3d:()=>bH,avgPooling1d:()=>yH,avgPooling2d:()=>xH,avgPooling3d:()=>vH,batchNormalization:()=>hH,bidirectional:()=>FH,concatenate:()=>lH,conv1d:()=>VG,conv2d:()=>UG,conv2dTranspose:()=>GG,conv3d:()=>HG,conv3dTranspose:()=>jG,convLstm2d:()=>_H,convLstm2dCell:()=>DH,cropping2D:()=>XG,dense:()=>JG,depthwiseConv2d:()=>ZG,dot:()=>pH,dropout:()=>QG,elu:()=>OG,embedding:()=>aH,flatten:()=>tH,gaussianDropout:()=>VH,gaussianNoise:()=>WH,globalAveragePooling1d:()=>wH,globalAveragePooling2d:()=>kH,globalMaxPool1d:()=>MH,globalMaxPool2d:()=>zH,globalMaxPooling1d:()=>I8,globalMaxPooling2d:()=>C8,gru:()=>IH,gruCell:()=>CH,input:()=>Jk,inputLayer:()=>FG,layerNormalization:()=>fH,leakyReLU:()=>zG,lstm:()=>TH,lstmCell:()=>NH,masking:()=>GH,maxPool1d:()=>LH,maxPool2d:()=>BH,maxPooling1d:()=>T8,maxPooling2d:()=>N8,maxPooling3d:()=>SH,maximum:()=>uH,minimum:()=>cH,multiply:()=>dH,permute:()=>rH,prelu:()=>LG,reLU:()=>MG,repeatVector:()=>nH,rescaling:()=>HH,reshape:()=>sH,rnn:()=>$H,separableConv2d:()=>qG,simpleRNN:()=>EH,simpleRNNCell:()=>RH,softmax:()=>BG,spatialDropout1d:()=>eH,stackedRNNCells:()=>PH,thresholdedReLU:()=>WG,timeDistributed:()=>OH,upSampling2d:()=>KG,zeroPadding2d:()=>mH});async function qa(e){if(e==null)return;let t=[],n=[],s=[];for(let r in e){let a=e[r];if(typeof a!="number"){let o=a;t.push(o.data()),n.push(r),s.push(o)}}if(t.length>0){let r=await Promise.all(t);for(let a=0;ale(this.totals[s],M(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=M(ge(1,this.seen),this.totals[n]);t[n]=s,this.totals[n].dispose(),Cn(t[n])}))}},Mk=class extends oc{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 zk(s,t))}var hr=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}`),hr.checkForDuplicate(t),hr.constructors[e]==null&&(hr.constructors[e]=[]),hr.constructors[e].push(t)}static checkForDuplicate(e){for(let t in hr.constructors)hr.constructors[+t].forEach(s=>{if(s===e)throw new H("Duplicate callback constructor.")})}static clear(){hr.constructors={}}static createCallbacks(e){let t=[];for(let n in hr.constructors){let s=+n;e>=s&&t.push(...hr.constructors[s])}return t.map(n=>new n)}};hr.constructors={};function Bk(e,t,n,s,r,a,o,i,l){let u=new Mk,c=[new TU,...hr.createCallbacks(t)];e!=null&&c.push(...e),c.push(u);let p=new Ok(c);return p.setParams({epochs:n,initialEpoch:s,samples:r,steps:a,batchSize:o,verbose:t,doValidation:i,metrics:l}),{callbackList:p,history:u}}function $r(e,t={},n=!1){return fh(e,ce.SerializationMap.getMap().classNameMap,t,"layer",n)}function pm(e,t){return X(()=>{e.dtype!=="float32"&&(e=me(e,"float32"));let n=ve(yh(e),t,!0),s=zr(n.shape,mn()),r=Ln(oa(n,s));return ge(e,r)})}function lu(e,t){return X(()=>Wt(yh(ye(t,e)),-1))}function J0(e,t){return X(()=>Wt(rn(ye(t,e)),-1))}function Yc(e,t){return X(()=>{let n=ye(e,t),s=bs(rn(e),mn(),Number.MAX_VALUE),r=rn(ge(n,s));return M(100,Wt(r,-1))})}function NU(e,t){return X(()=>{let n=bs(t,mn(),Number.MAX_VALUE),s=Ms(le(1,n)),r=bs(e,mn(),Number.MAX_VALUE),a=Ms(le(1,r));return Wt(yh(ye(s,a)),-1)})}function EU(e,t){return X(()=>{let n=oa(0,ye(1,M(e,t)));return Wt(yh(n),-1)})}function RU(e,t){return X(()=>{let n=oa(0,ye(1,M(e,t)));return Wt(n,-1)})}function _U(e,t){return X(()=>{let n=ve(M(e,t),-1),s=yn(M(ye(1,e),t),-1);return oa(0,le(1,ye(s,n)))})}function DU(e,t){return X(()=>{let n=Math.log(2),s=ye(t,e),r=ye(le(s,su(M(-2,s))),n);return Wt(r,-1)})}function gp(e,t,n=!1){return X(()=>{if(n)t=au(t);else{let s=ve(t,t.shape.length-1,!0);t=ge(t,s)}return t=bs(t,mn(),1-mn()),Dt(ve(M(me(e,"float32"),Ms(t)),t.shape.length-1))})}function hm(e,t,n=!1){return X(()=>{let s=me(Hc(BV(e)),"int32");t=bs(t,mn(),1-mn());let r=t.shape,a=W(ec(s,r[r.length-1]),r);return gp(a,t,n)})}function $U(e,t){if(!v.arraysEqual(e.shape,t.shape))throw new H(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return X(()=>{let n=Lr(t),s=Dt(rn(t));return le(ye(n,M(t,e)),rh(Os(s)))})}function Q0(e,t){return X(()=>{let n;return n=bs(t,mn(),1-mn()),n=Ms(ge(n,ye(1,n))),Wt($U(e,n),-1)})}function PU(e,t){return X(()=>{let n=bs(e,mn(),1),s=bs(t,mn(),1);return ve(M(e,Ms(ge(n,s))),-1)})}function FU(e,t){return X(()=>{let n=Ms(le(mn(),t));return Wt(ye(t,M(e,n)),-1)})}function i5(e,t){return X(()=>{let n=pm(e,-1),s=pm(t,-1),r=M(n,s);return Dt(ve(r,-1))})}var fm={meanSquaredError:lu,meanAbsoluteError:J0,meanAbsolutePercentageError:Yc,meanSquaredLogarithmicError:NU,squaredHinge:EU,hinge:RU,categoricalHinge:_U,logcosh:DU,categoricalCrossentropy:gp,sparseCategoricalCrossentropy:hm,binaryCrossentropy:Q0,kullbackLeiblerDivergence:PU,poisson:FU,cosineProximity:i5};function r3(e){if(typeof e=="string"){if(e in fm)return fm[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 H(t)}else return e}function l5(e,t){return X(()=>{let n=M(.5,zs(t)),s=mh(ks(t,n),e.dtype);return Wt(Fs(e,s),-1)})}function u5(e,t){return X(()=>mh(Fs(Ps(e,-1),Ps(t,-1)),"float32"))}function Wk(e,t){return X(()=>me(ve(gr(Fs(e,1),Fs(t,1))),"float32"))}function OU(e,t){return X(()=>me(ve(gr(Fs(e,1),Fs(t,0))),"float32"))}function MU(e,t){return X(()=>me(ve(gr(Fs(e,0),Fs(t,1))),"float32"))}function Vk(e,t){return X(()=>{let n=Wk(e,t),s=MU(e,t),r=le(n,s);return me(qn(ks(r,0),ge(n,r),0),"float32")})}function zU(e,t){return X(()=>{let n=Wk(e,t),s=OU(e,t),r=le(n,s);return me(qn(ks(r,0),ge(n,r),0),"float32")})}function Uk(e,t){return Q0(e,t)}function Gk(e,t){return e.rank===t.rank&&(e=Ge(e,[e.rank-1])),t=Ps(t,-1),t.dtype!==e.dtype&&(t=me(t,e.dtype)),me(Fs(e,t),"float32")}var LU=lu,BU=lu,WU=J0,VU=J0,UU=Yc,GU=Yc,c5=gp,HU=i5,Hk=hm,mm={binaryAccuracy:l5,categoricalAccuracy:u5,precision:Vk,categoricalCrossentropy:c5,sparseCategoricalCrossentropy:Hk,mse:LU,MSE:BU,mae:WU,MAE:VU,mape:UU,MAPE:GU,cosine:HU};function jU(e){if(typeof e=="string"&&e in mm)return mm[e];if(typeof e!="string"&&e!=null)return e;throw new H(`Unknown metric ${e}`)}function Df(e){if(Kr(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let n of Object.keys(fm))if(fm[n]===e){t=n;break}if(t!==void 0)return t;for(let n of Object.keys(mm))if(mm[n]===e){t=n;break}return t!==void 0?t:e.name}}function qU(e){let t={Adagrad:()=>zi.adagrad(.01),Adadelta:()=>zi.adadelta(1,.95,mn()),Adam:()=>zi.adam(.001,.9,.999,mn()),Adamax:()=>zi.adamax(.002,.9,.999,mn(),0),RMSProp:()=>zi.rmsprop(.001,.9,0,mn()),SGD:()=>zi.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 H(`Unknown Optimizer ${e}`)}var Wv=1*1024*1024;function Vv(e,t,n=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!$3(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>Wv&&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 <= ${Wv}.`)}}function $3(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"||!$3(e[n]))return!1;return!0}else if(Array.isArray(e)){for(let t of e)if(!$3(t))return!1;return!0}else return!1;else{let t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function XU(e,t,n,s=console.log){let r=ZU(e),a=["Layer (type)","Input Shape","Output shape","Param #"];r?(t=t||90,n=n||[.32,.61,.89,1]):(t=t||115,n=n||[.24,.48,.7,.8,1]),n[n.length-1]<=1&&(n=n.map(c=>Math.floor(t*c)));let o;if(!r){a.push("Receives inputs"),o=[];for(let c in e.nodesByDepth)o.push(...e.nodesByDepth[c])}s("_".repeat(t)),gm(a,n,s),s("=".repeat(t));let i=e.layers;for(let c=0;c1||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 gm(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 YU(e,t,n){let s,r;try{r=e.inboundNodes.map(l=>JSON.stringify(l.inputShapes)).join(",")}catch(l){r="multiple"}try{s=JSON.stringify(e.outputShape)}catch(l){s="multiple"}let a=e.name,o=e.getClassName(),i=[`${a} (${o})`,r,s,e.countParams().toString()];gm(i,t,n)}function JU(e,t,n,s){let r,a;try{a=e.inboundNodes.map(p=>JSON.stringify(p.inputShapes)).join(",")}catch(p){a="multiple"}try{r=JSON.stringify(e.outputShape)}catch(p){r="multiple"}let o=[];for(let p of e.inboundNodes)if(!(n!=null&&n.length>0&&n.indexOf(p)===-1))for(let d=0;dy.name)}`);Qa(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(y=>y.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(let y of this.outputs){let x=y.sourceLayer,A=y.nodeIndex,b=y.tensorIndex;this.outputLayers.push(x),this.outputLayersNodeIndices.push(A),this.outputLayersTensorIndices.push(b)}for(let y of this.inputs){let x=y.sourceLayer,A=y.nodeIndex,b=y.tensorIndex;Kr(A===0,"input layer has >1 nodes"),Kr(b===0,"input layer has >1 tensors"),this.inputLayers.push(x),this.inputLayersNodeIndices.push(A),this.inputLayersTensorIndices.push(b)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let y=0;yy.shape),this.internalOutputShapes=this.outputs.map(y=>y.shape);let t={},n={},s={},r={},a={},o=[],i=(y,x,A,b,w,k)=>{(b==null||w==null||k==null)&&(b=y.sourceLayer,w=y.nodeIndex,k=y.tensorIndex);let C=b.inboundNodes[w];if(A.indexOf(C)!==-1)throw new Rr(`The tensor ${y.name} at layer "${b.name}" is part of a cycle.`);if(x.indexOf(C)!==-1)return;this.containerNodes.add(qr.nodeKey(b,w)),b.id in a||(a[b.id]=Object.keys(a).length),A.indexOf(C)===-1&&A.push(C);let N=C.inboundLayers.length;for(let R=0;R=0;)A.splice(A.indexOf(C),1);o.push(C)},l=[],u=[];for(let y of this.outputs)i(y,l,u);let c=o.slice().reverse();for(let y of c){n[y.id]=y,y.id in t||(t[y.id]=0);let x=t[y.id],A=s[y.outboundLayer.id]==null?0:s[y.outboundLayer.id];x=Math.max(x,A),s[y.outboundLayer.id]=x,r[y.outboundLayer.id]=y.outboundLayer,t[y.id]=x;for(let b=0;bparseInt(y,10)).sort(Ef);this.layers=[];for(let y of h){let x=d[y];x.sort((A,b)=>{let w=a[A.id],k=a[b.id];return wk?1:0});for(let A of x)A instanceof qr&&this.internalContainerRefs.push(A),this.layers.push(A)}this.layersByDepth=d,h=Object.keys(p).map(y=>parseInt(y,10)).sort(Ef);let f=this.inputs.slice(),m=[];for(let y of h)for(let x of p[y]){let A=x.outboundLayer;if(A!=null){for(let b of x.inputTensors)if(f.indexOf(b)===-1)throw new Rr(`Graph disconnected: cannot obtain value for tensor ${b} at layer "${A.name}". The following previous layers were accessed without issue: ${m}`);for(let b of x.outputTensors)f.push(b);m.push(A.name)}}this.nodesByDepth=p;let g=this.layers.map(y=>y.name);for(let y of g){let x=g.filter(A=>A===y).length;if(x!==1)throw new Rr(`The name "${y}" is used ${x} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new Y0({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(y=>null),outputMasks:this.outputs.map(y=>null),inputShapes:this.inputs.map(y=>y.shape),outputShapes:this.outputs.map(y=>y.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();let e={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount===0){for(let t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(let t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach(t=>{t._trainableWeights.forEach(n=>n.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new H("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 H(`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 H(`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 H(`${a.length} of ${s} weights are not set: ${a}`)}t5(r)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${d5}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let n=P3(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return X(()=>{e=_t(e);let n=new Hi;for(let s=0;s{e=_t(e);let n;return t==null?n=rl(null,e.length):n=_t(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){let t=lm(e);if(t.length!==this.inputLayers.length)throw new H(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let n={};for(let o=0;oparseInt(o,10)).sort(Ef);if(s.length>1)for(let o of s){let i=this.nodesByDepth[o];for(let l of i){let u=l.outboundLayer;if(this.inputLayers.map(f=>f.id).indexOf(u.id)!==-1)continue;let c=[];for(let f=0;fparseInt(i,10)).sort(Ef);for(let i of s){let l=this.nodesByDepth[i];for(let u of l){let c=u.outboundLayer,p=u.inputTensors,d=u.outputTensors,h=new Array;for(let f of p)f.id in n&&h.push(n[f.id]);if(h.length===p.length){let f={},m,g,y,x;if(u.callArgs!=null&&(f=u.callArgs),h.length===1){let[A,b]=h[0];f.mask==null&&(f.mask=b),y=_t(c.call(A,f)),x=_t(c.computeMask(A,b)),m=[A],g=[b]}else m=h.map(A=>A[0]),g=h.map(A=>A[1]),f.mask==null&&(f.mask=g),y=_t(c.call(m,f)),x=_t(c.computeMask(m,g));if(c.activityRegularizer)throw new Ke("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let A=0;A{let e=[];for(let t of this.layers)for(let n=0;n0){let f=[];for(let m=0;m0&&m.apply(ys(y),x)}function l(m){let g=m.name,y=$r(m,t.customObjects!=null?t.customObjects:{});y.setFastWeightInitDuringBuild(s),r[g]=y,m.inboundNodes.forEach(A=>{if(!(A instanceof Array))throw new H(`Corrupted configuration, expected array for nodeData: ${A}`);o(y,A)})}let u=t.name,c=t.layers;for(let m of c)l(m);for(;!TV(a);)for(let m of c){let g=r[m.name];if(g.name in a){let y=a[g.name];delete a[g.name];for(let x of y)i(g,x)}}let p=[],d=[],h=t.inputLayers;for(let m of h){let g=m[0],y=m[1],x=m[2];Kr(g in r);let b=r[g].inboundNodes[y].outputTensors;p.push(b[x])}let f=t.outputLayers;for(let m of f){let g=m[0],y=m[1],x=m[2];Kr(g in r);let b=r[g].inboundNodes[y].outputTensors;d.push(b[x])}return new e({inputs:p,outputs:d,name:u})}get stateful(){if(this._stateful)throw new H("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 QU(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 qk(e,t){return QU(e,t,"classWeight")}async function Xk(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 Hn(e);if(e.shape.length===2){if(e.shape[1]>1)return Ps(e,1);if(e.shape[1]===1)return W(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());Y(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])}),Ot(o,"float32")}else return null}function eG(e,t){return M(e,t)}var tG=32;function Kk(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=Uv("input",e.inputNames,n),o=Uv("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 Uv(e,t,n){if(n instanceof st)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 H(`The feature data generated by the dataset lacks the required ${e} key '${r}'.`);s.push(n[r])}return s}}function nG(e){if(e.length===3)throw new Ke("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function sG(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(Gv(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=nG(n.validationData);a=g.xs,o=g.ys}let i=e.makeTrainFunction(),l=e.getDedupedMetricsNames(),u;r?u=l.slice().concat(l.map(g=>"val_"+g)):u=l.slice();let c=Lk(n.callbacks,n.yieldEvery),p=n.verbose==null?1:n.verbose,{callbackList:d,history:h}=Bk(c,p,n.epochs,null,null,rG(t,n),null,r,u);d.setModel(e),e.history=h,await d.onTrainBegin(),e.stopTraining_=!1;let f=n.initialEpoch==null?0:n.initialEpoch,m=await t.iterator();for(;f=n.batchesPerEpoch:A.done){if(r){let b;Gv(n.validationData)?b=_t(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):b=_t(e.evaluate(a,o,{batchSize:n.validationBatchSize==null?tG:n.validationBatchSize,verbose:0}));for(let w=0;w0)throw new Ke("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=aG(t)?t:await t.iterator(),i=0,l=0;for(;!s||l{if(u.value){let{xs:c,ys:p}=Kk(e,u.value),d=c.concat(p),h=X(()=>r(d));if(Y(d),l===0)for(let m=0;mle(a[m],M(f,g))),l>0&&Y(y)}Y(h),i+=f,++l}return a}),u.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 u=0;u0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function Xd(e,t,n){return e==null?[null]:Array.isArray(e)?e.map(s=>Zi(s,t,n-t)):Zi(e,t,n-t)}function p5(e,t){return X(()=>e==null?null:Array.isArray(e)?e.map(n=>p5(n,t)):Tk(e,t.dtype==="int32"?t:me(t,"int32")))}function O3(e,t){let n=[],s=0,r=null;for(;s=e&&(r=e),n.push([s,r]),s=r;return n}async function iG(e,t,n,s,r,a,o,i,l,u,c,p,d,h,f){r==null&&(r=32),a==null&&(a=1),c==null&&(c=!0),d==null&&(d=0);let m=!1;if(l!=null&&u!=null&&(m=!0),f!=null&&(m=!0,h==null))throw new H("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let g=e.checkNumSamples(n,r,h,"steps_per_epoch"),y;g!=null&&(y=Fr(0,g)),o==null&&(o=1);let{callbackList:x,history:A}=Bk(i,o,a,d,g,h,r,m,p);x.setModel(e),e.history=A,await x.onTrainBegin(),e.stopTraining_=!1;for(let b=d;b{let D=C[N][0],E=C[N][1],$=Zi(k,D,E-D);R.batch=N,R.size=E-D;let S=p5(n,$),F=t(S);for(let z=0;z0){if(g=!0,s.validationData.length===2)l=s.validationData[0],u=s.validationData[1];else throw s.validationData.length===3?new Ke("validationData including sample weights is not supported yet."):new H(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${s.validationData} is invalid.`);let R=!0,D=await e.standardizeUserData(l,u,null,null,R,h);c=D[0],p=D[1],y=c.concat(p)}else if(s.validationSplit!=null&&s.validationSplit>0&&s.validationSplit<1){g=!0;let R=Math.floor(r[0].shape[0]*(1-s.validationSplit)),D=r[0].shape[0];c=Xd(r,R,D),o=r,r=Xd(r,0,R),p=Xd(a,R,D),i=a,a=Xd(a,0,R),y=c.concat(p)}else s.validationSteps!=null&&(g=!0);let x=r.concat(a).concat(d);e.checkTrainableWeightsConsistency();let A=e.makeTrainFunction(),b=e.getDedupedMetricsNames(),w,k;g?(e.makeTestFunction(),w=e.testFunction,k=b.slice().concat(b.map(R=>"val_"+R))):(w=null,y=[],k=b.slice());let C=Lk(s.callbacks,s.yieldEvery);return await iG(e,A,x,b,h,s.epochs,s.verbose,C,w,y,s.shuffle,k,s.initialEpoch,null,null)}finally{e.isTraining=!1,Er(r,t),Er(a,n),Er(o,t),Er(i,n),Er(c,l),Er(p,u),d!=null&&Y(d)}}function Zk(e){let t=[];e instanceof st&&(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 st)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 uG(e){return e instanceof st}function M3(e){return Array.isArray(e)}function Hv(e){return!uG(e)&&!M3(e)}function jv(e,t,n,s=!0,r=""){if(t==null||t.length===0){if(e!=null){let o=!1;if(M3(e)&&e.length>0)o=!0;else if(Hv(e)){for(let i in e)if(e.hasOwnProperty(i)){o=!0;break}}else o=!0;if(o)throw new H(`Error when checking model ${r} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(o=>null);let a;if(Hv(e)){e=e,a=[];for(let o of t){if(e[o]==null)throw new H(`No data provided for "${o}". Need data for each key in: ${t}`);a.push(e[o])}}else if(M3(e)){if(e=e,e.length!==t.length)throw new H(`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 H(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);a=[e]}if(a=Zk(a),n!=null)for(let o=0;o=0&&u!==c)throw new H(`${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 cG(e,t,n){let s=Qa(e.map(a=>a.shape[0]));s.sort();let r=Qa(t.map(a=>a.shape[0]));if(r.sort(),s.length>1)throw new H(`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 H(`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 H(`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 dG(e,t,n){let s=[lu,Q0,gp];for(let r=0;r1)throw new H(`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 hG="layers-model",ba=class extends qr{constructor(e){super(e),this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new H("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).");XU(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=qU(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof _a))throw new H("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 H(`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(r3(e.loss[a]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new H(`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=>r3(o))}else{let a=r3(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=pG(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])};Ki("metric",()=>{for(let a=0;a{let u="",c,p,d;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]===Q0?["accuracy","acc"].indexOf(h)!==-1?p=l5:["crossentropy","ce"].indexOf(h)!==-1&&(p=Uk):this.lossFunctions[a]===hm?["accuracy","acc"].indexOf(h)!==-1?p=Gk:["crossentropy","ce"].indexOf(h)!==-1&&(p=Hk):["accuracy","acc"].indexOf(h)!==-1?p=u5:["crossentropy","ce"].indexOf(h)!==-1&&(p=c5);let g;["accuracy","acc"].indexOf(h)!==-1?g="acc":["crossentropy","ce"].indexOf(h)!==-1&&(g="ce"),d=p,c=u+g}else d=jU(h),c=u+Df(h);let f;Ki(c,()=>{f=d}),r(a,c,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;F3(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 ys(l)}finally{Er(a[0],e),Er(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),oG(this,e,t)}checkNumSamples(e,t,n,s="steps"){let r;if(n!=null){if(r=null,t!=null)throw new H(`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 H(`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 H("`outputs` is an empty Array, which is not allowed.");let n=Array.isArray(t),s=n?t:[t],r=this.retrieveSymbolicTensors(s),a=new Hi;if(e instanceof st&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new H(`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 H(`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 Ke("Verbose predictLoop() is not implemented yet.");let r=O3(s,t),a=this.outputs.map(o=>[]);for(let o=0;o{let l=r[o][0],u=r[o][1],c=Xd(e,l,u),p=[];if(Array.isArray(c))for(let h=0;ha[u].push(l));return ys(a.map(o=>ut(o,0)))})}predict(e,t={}){let n=Zk(e);qv(n,this.inputNames,this.feedInputShapes,!1);try{let s=t.batchSize==null?32:t.batchSize;return F3(s),this.predictLoop(n,s)}finally{Er(n,e)}}predictOnBatch(e){qv(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 Rr("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 H(`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 u=qk(s,this.outputNames);l=[];for(let c=0;c{let a=this.checkNumSamples(t,n,r,"steps"),o=[];if(s>0)throw new Ke("Verbose mode is not implemented yet.");if(r!=null)throw new Ke("steps mode in testLoop() is not implemented yet");{let i=O3(a,n),l=Ot(Fr(0,a));for(let u=0;u1&&(r+=`_${_v(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 c=[];for(let f=0;f1&&f{h=le(h,f)}),h},i=this.collectedTrainableWeights.map(c=>c.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;lga(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]=ga(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[ga(Df(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>ga(Df(e)));{let e={};for(let t in this.metrics)e[t]=ga(Df(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=yp(e.optimizer_config),n=$r(t),s;if(typeof e.loss=="string")s=Vi(e.loss);else if(Array.isArray(e.loss))s=e.loss.map(a=>Vi(a));else if(e.loss!=null){s={};for(let a in e.loss)s[a]=Vi(e.loss[a])}let r;if(Array.isArray(e.metrics))r=e.metrics.map(a=>Vi(a));else if(e.metrics!=null){r={};for(let a in e.metrics)r[a]=Vi(e.metrics[a])}this.compile({loss:s,metrics:r,optimizer:n})}async save(e,t){if(typeof e=="string"){let l=On.getSaveHandlers(e);if(l.length===0)throw new H(`Cannot find any save handlers for URL '${e}'`);if(l.length>1)throw new H(`Found more than one (${l.length}) save handlers for URL '${e}'`);e=l[0]}if(e.save==null)throw new H("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let n=await On.encodeWeights(this.getNamedWeights(t)),s=!1,r=null,o={modelTopology:this.toJSON(r,s),format:hG,generatedBy:`TensorFlow.js tfjs-layers v${d5}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){o.trainingConfig=this.getTrainingConfig();let l="optimizer",{data:u,specs:c}=await On.encodeWeights(await this.optimizer.getWeights(),l);n.specs.push(...c),n.data=On.concatenateArrayBuffers([n.data,u])}return this.userDefinedMetadata!=null&&(Vv(this.userDefinedMetadata,this.name,!0),o.userDefinedMetadata=this.userDefinedMetadata),o.weightData=n.data,o.weightSpecs=n.specs,e.save(o)}setUserDefinedMetadata(e){Vv(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};ba.className="Model";ce.registerClass(ba);var Yk=class extends ba{};Yk.className="Functional";ce.registerClass(Yk);async function fG(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);let s=yp(n),r=$r(s,t);if(e.weightsManifest!=null){let a=await On.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),Y(a)}return r}async function mG(e,t){if(t==null&&(t={}),typeof e=="string"){let n=On.getLoadHandlers(e,t);if(n.length===0)n.push(On.browserHTTPRequest(e,t));else if(n.length>1)throw new H(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return gG(e,void 0,t)}async function gG(e,t,n){if(n==null&&(n={}),e.load==null)throw new H("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=$r(yp(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 H("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:u,optimizerWeights:c}=yG(s.weightData,s.weightSpecs);i.loadWeights(u,a),i.optimizer!=null&&c.length>0&&await i.optimizer.setWeights(c),Y(u),Y(c.map(p=>p.tensor))}return i}function yG(e,t){let n=On.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 ic=class extends ba{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:V0("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 H(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof ic||e instanceof ba,n;if(t){if(n=e,n.outputs.length!==1)throw new H("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 H("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 H("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let s=_k({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 H(`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 H("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=Rk(this.outputs[0])}this.inboundNodes=[],new Y0({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:rl(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(s=>s.shape),outputShapes:this.outputs[0].shape})}else{let s=e.apply(this.outputs[0]);if(Array.isArray(s))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[s],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{let e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return this.model==null&&this.build(),this.model.call(e,t)}build(e){if(At(e),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new ba({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 Rr("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 Rr("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 Rr("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 Rr("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 H("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 ic))throw new Ke(`Sequential.fromConfig called on non-Sequential input: ${o}`);for(let i of r){let u=$r(i,void 0,s);s&&u.setFastWeightInitDuringBuild(!0),o.add(u)}return o}set stopTraining(e){if(this.model==null)throw new H("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 H("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}}};ic.className="Sequential";ce.registerClass(ic);function AG(e){return new ba(e)}function xG(e){return new ic(e)}function bG(e,t){return t==null&&(t={}),mG(e,t)}function Jk(e){return _k(e)}function vG(e,t){hr.registerCallbackConstructor(e,t)}var Ss=class extends ce.Serializable{getConfig(){return{}}},Qk=class extends Ss{apply(e,t=1){return VV(e,t)}};Qk.className="elu";ce.registerClass(Qk);var e8=class extends Ss{apply(e){return w0(e)}};e8.className="selu";ce.registerClass(e8);var t8=class extends Ss{apply(e){return Lr(e)}};t8.className="relu";ce.registerClass(t8);var n8=class extends Ss{apply(e){return X(()=>qc(6,Lr(e)))}};n8.className="relu6";ce.registerClass(n8);var s8=class extends Ss{apply(e){return e}};s8.className="linear";ce.registerClass(s8);var r8=class extends Ss{apply(e){return Mn(e)}};r8.className="sigmoid";ce.registerClass(r8);var a8=class extends Ss{apply(e){return GV(e)}};a8.className="hardSigmoid";ce.registerClass(a8);var o8=class extends Ss{apply(e){return su(e)}};o8.className="softplus";ce.registerClass(o8);var i8=class extends Ss{apply(e){return UV(e)}};i8.className="softsign";ce.registerClass(i8);var l8=class extends Ss{apply(e){return tl(e)}};l8.className="tanh";ce.registerClass(l8);var h5=class extends Ss{apply(e,t=-1){return au(e,t)}};h5.className="softmax";ce.registerClass(h5);var u8=class extends Ss{apply(e,t=-1){return f0(e,t)}};u8.className="logSoftmax";ce.registerClass(u8);var c8=class extends Ss{apply(e,t=1){return X(()=>M(Mn(M(e,t)),e))}};c8.className="swish";ce.registerClass(c8);var d8=class extends Ss{apply(e){return X(()=>M(e,tl(su(e))))}};d8.className="mish";ce.registerClass(d8);function lo(e){return e.getClassName()}function a3(e,t={}){return fh(e,ce.SerializationMap.getMap().classNameMap,t,"activation")}function uo(e){if(e==null){let t={};return t.className="linear",t.config={},a3(t)}if(typeof e=="string"){let t={};return t.className=e,t.config={},a3(t)}else return e instanceof Ss?e:a3(e)}function f5(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 p8=class extends ce.Serializable{},bh=class extends p8{constructor(e){super(),f5(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=Vt([1]);return this.hasL1&&(t=le(t,ve(M(this.l1,rn(e))))),this.hasL2&&(t=le(t,ve(M(this.l2,yh(e))))),W(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};bh.className="L1L2";ce.registerClass(bh);function wG(e){return f5(e),new bh({l1:e!=null?e.l1:null,l2:0})}function kG(e){return f5(e),new bh({l2:e!=null?e.l2:null,l1:0})}var Xv={l1l2:"L1L2"};function wt(e){return HA(e)}function Kv(e,t={}){return fh(e,ce.SerializationMap.getMap().classNameMap,t,"regularizer")}function zt(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in Xv?Xv[e]:e,config:{}};return Kv(n)}else return e instanceof p8?e:Kv(e)}var m5=class extends dt{constructor(e){super(e==null?{}:e),this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Ze(e);let n=Lr(e);return this.maxValue!=null&&(n=bs(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};m5.className="ReLU";ce.registerClass(m5);var g5=class extends dt{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=Ze(e);return sh(n,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};g5.className="LeakyReLU";ce.registerClass(g5);var y5=class extends dt{constructor(e){if(super(e==null?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Mt(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=zt(e.alphaRegularizer),this.alphaConstraint=xn(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 H(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=At(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let s of this.sharedAxes)t[s-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let n={};if(this.sharedAxes!=null)for(let s=1;s(Qt(t),t==="channelsFirst"?tt(e,[0,2,3,1]):e))}function h8(e,t){return X(()=>(Qt(t),t==="channelsFirst"?tt(e,[0,2,3,4,1]):e))}function SG(e,t,n,s=1,r="valid",a,o=1){return X(()=>{if(a==null&&(a=Or()),Qt(a),e.shape.length!==3)throw new H(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new H(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new H(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(a==="channelsFirst"&&(e=tt(e,[0,2,1])),r==="causal")throw new Ke("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let i=i0(e,t,s,r==="same"?"same":"valid","NWC",o);return n!=null&&(i=Br(i,n)),i})}function Zv(e,t,n,s=[1,1],r="valid",a,o,i=null){return X(()=>{if(a==null&&(a=Or()),Qt(a),e.rank!==3&&e.rank!==4)throw new H(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new H(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=v5(e,a);if(r==="causal")throw new Ke("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=rc.conv2d({x:l,filter:t,strides:s,pad:r==="same"?"same":"valid",dilations:o,dataFormat:"NHWC",bias:n,activation:i}),a==="channelsFirst"&&(l=tt(l,[0,3,1,2])),l})}function IG(e,t,n,s=[1,1,1],r="valid",a,o){return X(()=>{if(a==null&&(a=Or()),Qt(a),e.rank!==4&&e.rank!==5)throw new H(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new H(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let i=h8(e,a);if(r==="causal")throw new Ke("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return i=iA(i,t,s,r==="same"?"same":"valid","NDHWC",o),n!=null&&(i=Br(i,n)),a==="channelsFirst"&&(i=tt(i,[0,4,1,2,3])),i})}var w5=class extends dt{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",w5.verifyArgs(t),this.rank=e,Tn(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Ke(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Ku(t.kernelSize,e,"kernelSize"),this.strides=Ku(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,nr(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Qt(this.dataFormat),this.activation=uo(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=Mt(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=xn(t.biasConstraint),this.biasRegularizer=zt(t.biasRegularizer),this.activityRegularizer=zt(t.activityRegularizer),this.dilationRate=Ku(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new H(`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 H(`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 H(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(Kr("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!jA(e.kernelSize,"number",1,3))throw new H(`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:lo(this.activation),useBias:this.useBias,biasInitializer:Ut(this.biasInitializer),biasRegularizer:wt(this.biasRegularizer),activityRegularizer:wt(this.activityRegularizer),biasConstraint:An(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},vh=class extends w5{constructor(e,t){super(e,t),this.kernel=null,vh.verifyArgs(t),this.filters=t.filters,Tn(this.filters,"filters"),this.kernelInitializer=Mt(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=xn(t.kernelConstraint),this.kernelRegularizer=zt(t.kernelRegularizer)}build(e){e=At(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new H(`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=Ze(e);let n,s=this.bias==null?null:this.bias.read(),r=vk(this.activation.getClassName());if(r!=null&&this.rank===2)n=Zv(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(this.rank===1)n=SG(e,this.kernel.read(),s,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=Zv(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=IG(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Ke("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(e){e=At(e);let t=[],n=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let r=0;r 0 but got ${JSON.stringify(e.filters)}`)}},wh=class extends vh{constructor(e){super(2,e),wh.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!jA(e.kernelSize,"number",1,2))throw new H(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}};wh.className="Conv2D";ce.registerClass(wh);var kh=class extends vh{constructor(e){super(3,e),kh.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 H(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}};kh.className="Conv3D";ce.registerClass(kh);var k5=class extends wh{constructor(e){if(super(e),this.inputSpec=[new an({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new H(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=At(e),e.length!==4)throw new H("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 H("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 an({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return X(()=>{let n=Ze(e);if(n.shape.length!==4)throw new H(`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],u=this.kernelSize[0],c=this.kernelSize[1],p=this.strides[0],d=this.strides[1],h=Zr(i,p,u,this.padding),f=Zr(l,d,c,this.padding),m=[r,h,f,this.filters];this.dataFormat!=="channelsLast"&&(n=tt(n,[0,2,3,1]));let g=l0(n,this.kernel.read(),m,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=tt(g,[0,3,1,2])),this.bias!=null&&(g=Br(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=At(e);let t=e.slice(),n,s,r;this.dataFormat==="channelsFirst"?(n=1,s=2,r=3):(n=3,s=1,r=2);let a=this.kernelSize[0],o=this.kernelSize[1],i=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[s]=Zr(t[s],i,a,this.padding),t[r]=Zr(t[r],l,o,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};k5.className="Conv2DTranspose";ce.registerClass(k5);var S5=class extends kh{constructor(e){if(super(e),this.inputSpec=[new an({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new H(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=At(e),e.length!==5)throw new H("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 H("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 an({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return X(()=>{let n=Ze(e);if(n.shape.length!==5)throw new H(`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],u=s[a],c=s[o],p=this.kernelSize[0],d=this.kernelSize[1],h=this.kernelSize[2],f=this.strides[0],m=this.strides[1],g=this.strides[2],y=Zr(l,f,p,this.padding),x=Zr(u,m,d,this.padding),A=Zr(c,g,h,this.padding),b=[r,y,x,A,this.filters];this.dataFormat!=="channelsLast"&&(n=tt(n,[0,2,3,4,1]));let w=lA(n,this.kernel.read(),b,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(w=tt(w,[0,4,1,2,3])),this.bias!==null&&(w=Br(w,this.bias.read(),this.dataFormat)),this.activation!==null&&(w=this.activation.apply(w)),w})}computeOutputShape(e){e=At(e);let t=e.slice(),n,s,r,a;this.dataFormat==="channelsFirst"?(n=1,s=2,r=3,a=4):(n=4,s=1,r=2,a=3);let o=this.kernelSize[0],i=this.kernelSize[1],l=this.kernelSize[2],u=this.strides[0],c=this.strides[1],p=this.strides[2];return t[n]=this.filters,t[s]=Zr(t[s],u,o,this.padding),t[r]=Zr(t[r],c,i,this.padding),t[a]=Zr(t[a],p,l,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};S5.className="Conv3DTranspose";ce.registerClass(S5);var f8=class extends vh{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new H("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new H("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 H(`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=Mt(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=zt(t.depthwiseRegularizer),this.depthwiseConstraint=xn(t.depthwiseConstraint),this.pointwiseInitializer=Mt(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=zt(t.pointwiseRegularizer),this.pointwiseConstraint=xn(t.pointwiseConstraint)}build(e){if(e=At(e),e.length{e=Ze(e);let n;if(this.rank===1)throw new Ke("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=tt(e,[0,2,3,1])),n=k0(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=Br(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=tt(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=Ut(this.depthwiseInitializer),e.pointwiseInitializer=Ut(this.pointwiseInitializer),e.depthwiseRegularizer=wt(this.depthwiseRegularizer),e.pointwiseRegularizer=wt(this.pointwiseRegularizer),e.depthwiseConstraint=An(this.depthwiseConstraint),e.pointwiseConstraint=An(this.pointwiseConstraint),e}};f8.className="SeparableConv";var I5=class extends f8{constructor(e){super(2,e)}};I5.className="SeparableConv2D";ce.registerClass(I5);var e2=class extends vh{constructor(e){super(1,e),e2.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"&&!jA(e.kernelSize,"number",1,1))throw new H(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}};e2.className="Conv1D";ce.registerClass(e2);var C5=class extends dt{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=Ze(e),this.dataFormat==="channelsLast"){let n=_f(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return _f(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let n=_f(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return _f(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}};C5.className="Cropping2D";ce.registerClass(C5);var T5=class extends dt{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,Qt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,FV(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=Ze(e),s=n.shape;if(this.dataFormat==="channelsFirst"){n=tt(n,[0,2,3,1]);let r=this.size[0]*s[2],a=this.size[1]*s[3],o=this.interpolation==="nearest"?ke.resizeNearestNeighbor(n,[r,a]):ke.resizeBilinear(n,[r,a]);return tt(o,[0,3,1,2])}else{let r=this.size[0]*s[1],a=this.size[1]*s[2];return this.interpolation==="nearest"?ke.resizeNearestNeighbor(n,[r,a]):ke.resizeBilinear(n,[r,a])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}};T5.className="UpSampling2D";ce.registerClass(T5);function CG(e,t,n=[1,1],s="valid",r,a){return X(()=>{r==null&&(r=Or()),Qt(r);let o=v5(e,r);if(e.rank!==4)throw new H(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new H(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return o=Vc(o,t,n,s==="same"?"same":"valid","NHWC",a),r==="channelsFirst"&&(o=tt(o,[0,3,1,2])),o})}var N5=class extends w5{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=Mt(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=xn(e.depthwiseConstraint),this.depthwiseRegularizer=zt(e.depthwiseRegularizer)}build(e){if(e=At(e),e.length<4)throw new H(`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 H(`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=Ze(e);let n=CG(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=Br(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=At(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],s=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,r=Pr(t,this.kernelSize[0],this.padding,this.strides[0]),a=Pr(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=Ut(this.depthwiseInitializer),e.depthwiseRegularizer=wt(this.depthwiseRegularizer),e.depthwiseConstraint=An(this.depthwiseRegularizer),e}};N5.className="DepthwiseConv2D";ce.registerClass(N5);function m8(e,t,n,s){if(Array.isArray(e)){if(t!=null||n!=null)throw new H("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 g8(e,t,n,s=!1,r,a,o=!1,i=!1){return X(()=>{let l=t.shape.length;if(l<3)throw new H(`Input should be at least 3D, but is ${l}D.`);let u=[1,0].concat(Fr(2,l));if(t=tt(t,u),a!=null)throw new Ke("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=Ft(r,-1)),r=tt(r,u)),s&&(t=Js(t,0),r!=null&&(r=Js(r,0)));let c=[],p,d=n,h=t.shape[0],f=bn(t),m;r!=null&&(m=bn(r));for(let y=0;ye(x,d));if(r==null)p=A[0],d=A[1];else{let b=X(()=>{let w=m[y],k=ye(zs(w),w),C=le(M(A[0],w),M(d[0],k)),N=d.map((R,D)=>le(M(A[1][D],w),M(R,k)));return{output:C,newStates:N}});p=b.output,d=b.newStates}i&&c.push(p)}let g;return i&&(g=ln(c,1)),[p,g,d]})}var ia=class extends dt{constructor(e){super(e);let t;if(e.cell==null)throw new H("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new s2({cells:e.cell}):t=e.cell,t.stateSize==null)throw new H("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 an({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return Fr(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){_3(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 H(`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 an({shape:[null,o]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){X(()=>{if(!this.stateful)throw new ma("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape[0];if(n==null)throw new H("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=>Vt([n,s])):this.states_=[Vt([n,this.cell.stateSize])];else if(e==null)Y(this.states_),this.keptStates!=null&&(Y(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(s=>Vt([n,s])):this.states_[0]=Vt([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new H(`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()):Y(this.states_);for(let s=0;sCn(s.clone()))})}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});let r=m8(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 an({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 _r){let l=[e].concat(a),u=this.inputSpec.concat(o),c=this.inputSpec;this.inputSpec=u;let p=super.apply(l,t);return this.inputSpec=c,p}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=Ze(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 H(`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=g8((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),u=l[0],c=l[1],p=l[2];this.stateful&&this.resetStates(p,s);let d=this.returnSequences?c:u;return this.returnState?[d].concat(p):d})}getInitialState(e){return X(()=>{let t=Vt(e.shape);return t=ve(t,[1,2]),t=gh(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?E3(t,[1,n]):t):this.cell.stateSize>1?[E3(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()===ia.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign({},n,e,t)}static fromConfig(e,t,n={}){let s=t.cell,r=$r(s,n);return new e(Object.assign(t,{cell:r}))}};ia.className="RNN";ce.registerClass(ia);var Sh=class extends dt{},t2=class extends Sh{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,Tn(this.units,"units"),this.activation=uo(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Mt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Mt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Mt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=zt(e.kernelRegularizer),this.recurrentRegularizer=zt(e.recurrentRegularizer),this.biasRegularizer=zt(e.biasRegularizer),this.kernelConstraint=xn(e.kernelConstraint),this.recurrentConstraint=xn(e.recurrentConstraint),this.biasConstraint=xn(e.biasConstraint),this.dropout=ac([1,io([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=ac([1,io([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=At(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return X(()=>{if(e=e,e.length!==2)throw new H(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];let s=t.training==null?!1:t.training;0zs(e),rate:this.dropout,training:s,dropoutFunc:this.dropoutFunc})),0zs(n),rate:this.recurrentDropout,training:s,dropoutFunc:this.dropoutFunc}));let r,a=this.dropoutMask,o=this.recurrentDropoutMask;a!=null?r=Qr(M(e,a),this.kernel.read()):r=Qr(e,this.kernel.read()),this.bias!=null&&(r=Br(r,this.bias.read())),o!=null&&(n=M(n,o));let i=le(r,Qr(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:lo(this.activation),useBias:this.useBias,kernelInitializer:Ut(this.kernelInitializer),recurrentInitializer:Ut(this.recurrentInitializer),biasInitializer:Ut(this.biasInitializer),kernelRegularizer:wt(this.kernelRegularizer),recurrentRegularizer:wt(this.recurrentRegularizer),biasRegularizer:wt(this.biasRegularizer),activityRegularizer:wt(this.activityRegularizer),kernelConstraint:An(this.kernelConstraint),recurrentConstraint:An(this.recurrentConstraint),biasConstraint:An(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}};t2.className="SimpleRNNCell";ce.registerClass(t2);var E5=class extends ia{constructor(e){e.cell=new t2(e),super(e)}call(e,t){return X(()=>{this.cell.dropoutMask!=null&&(Y(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Y(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)}};E5.className="SimpleRNN";ce.registerClass(E5);var n2=class extends Sh{constructor(e){if(super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new H("GRUCell does not support reset_after parameter set to true.");this.units=e.units,Tn(this.units,"units"),this.activation=uo(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=uo(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Mt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Mt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Mt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=zt(e.kernelRegularizer),this.recurrentRegularizer=zt(e.recurrentRegularizer),this.biasRegularizer=zt(e.biasRegularizer),this.kernelConstraint=xn(e.kernelConstraint),this.recurrentConstraint=xn(e.recurrentConstraint),this.biasConstraint=xn(e.biasConstraint),this.dropout=ac([1,io([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=ac([1,io([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=At(e);let t=e[e.length-1];this.kernel=this.addWeight("kernel",[t,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return X(()=>{if(e=e,e.length!==2)throw new H(`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],0zs(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0zs(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&&(Y(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Y(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)}};R5.className="GRU";ce.registerClass(R5);var Ih=class extends Sh{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,Tn(this.units,"units"),this.activation=uo(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=uo(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Mt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Mt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Mt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=zt(e.kernelRegularizer),this.recurrentRegularizer=zt(e.recurrentRegularizer),this.biasRegularizer=zt(e.biasRegularizer),this.kernelConstraint=xn(e.kernelConstraint),this.recurrentConstraint=xn(e.recurrentConstraint),this.biasConstraint=xn(e.biasConstraint),this.dropout=ac([1,io([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=ac([1,io([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=At(e);let n=e[e.length-1];this.kernel=this.addWeight("kernel",[n,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let s;if(this.useBias){if(this.unitForgetBias){let r=this.biasInitializer,a=this.units;s=new(t=class extends xr{apply(i,l){let u=r.apply([a]),c=new G0().apply([a]),p=r.apply([a*2]);return $v($v(u,c),p)}},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 H(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let s=e[1],r=e[2];e=e[0],0zs(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0zs(s),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));let a=this.dropoutMask,o=this.recurrentDropoutMask,i,l,u,c;0{this.cell.dropoutMask!=null&&(Y(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Y(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)}};_5.className="LSTM";ce.registerClass(_5);var s2=class extends Sh{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{Ki(`RNNCell_${s}`,()=>{n.build(e),Array.isArray(n.stateSize)?t=n.stateSize[0]:t=n.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){let e=super.getConfig(),t=r=>({className:r.getClassName(),config:r.getConfig()}),s={cells:this.cells.map(t)};return Object.assign({},e,s)}static fromConfig(e,t,n={}){let s=[];for(let r of t.cells)s.push($r(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 D3(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):Nk(t(),n),i=()=>Ah(o,t,s);return!r||r<=1?Cn(i().clone()):Array(r).fill(void 0).map(i).map(u=>Cn(u.clone()))}var TG=function(e,t){var n={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(e);r{if(this.cell.dropoutMask!=null&&(Y(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Y(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new H("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=Vt(r);return Array.isArray(t)?Array(t.length).fill(a):[a]})}resetStates(e,t=!1){X(()=>{if(!this.stateful)throw new ma("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 H("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(()=>Vt(r)):this.states_=[Vt(r)];else if(e==null)Y(this.states_),this.keptStates!=null&&(Y(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Vt(r)):this.states_[0]=Vt(r);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new H(`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()):Y(this.states_);for(let o=0;oCn(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],u=e[i?4:3],c=Pr(l,s[0],r,a[0],o[0]),p=Pr(u,s[1],r,a[1],o[1]);return[...e.slice(0,2),...i?[n,c,p]:[c,p,n]]}};y8.className="ConvRNN2D";var r2=class extends Ih{constructor(e){let{filters:t,kernelSize:n,strides:s,padding:r,dataFormat:a,dilationRate:o}=e;super(Object.assign({},e,{units:t})),this.filters=t,Tn(this.filters,"filters"),this.kernelSize=Ku(n,2,"kernelSize"),this.kernelSize.forEach(i=>Tn(i,"kernelSize")),this.strides=Ku(s||1,2,"strides"),this.strides.forEach(i=>Tn(i,"strides")),this.padding=r||"valid",nr(this.padding),this.dataFormat=a||"channelsLast",Qt(this.dataFormat),this.dilationRate=Ku(o||1,2,"dilationRate"),this.dilationRate.forEach(i=>Tn(i,"dilationRate"))}build(e){var t;e=At(e);let n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new H(`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,u=this.filters;i=new(t=class extends xr{apply(p,d){let h=l.apply([u]),f=Ds([u]),m=l.apply([u*2]);return qA([h,f,m])}},t.className="CustomInit",t)}else i=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*r],null,i,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return X(()=>{if(e.length!==3)throw new H(`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;0zs(s),rate:this.dropout,training:n,count:o,dropoutFunc:this.dropoutFunc}));let i=this.dropoutMask,l=(q,K,ne)=>!K||!K[ne]?q:M(K[ne],q),u=l(s,i,0),c=l(s,i,1),p=l(s,i,2),d=l(s,i,3);0zs(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),y=l(r,h,3),x=3,[A,b,w,k]=Ht(this.kernel.read(),o,x),[C,N,R,D]=this.useBias?Ht(this.bias.read(),o):[null,null,null,null];u=this.inputConv(u,A,C,this.padding),c=this.inputConv(c,b,N,this.padding),p=this.inputConv(p,w,R,this.padding),d=this.inputConv(d,k,D,this.padding);let[E,$,S,F]=Ht(this.recurrentKernel.read(),o,x);f=this.recurrentConv(f,E),m=this.recurrentConv(m,$),g=this.recurrentConv(g,S),y=this.recurrentConv(y,F);let z=this.recurrentActivation.apply(le(u,f)),V=this.recurrentActivation.apply(le(c,m)),j=le(M(V,a),M(z,this.activation.apply(le(p,g)))),G=M(this.recurrentActivation.apply(le(d,y)),this.activation.apply(j));return[G,G,j]})}getConfig(){let e=super.getConfig(),{units:t}=e,n=TG(e,["units"]),s={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign({},n,s)}inputConv(e,t,n,s){let r=ka(e,t,this.strides,s||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?Br(r,n,this.dataFormat):r}recurrentConv(e,t){return ka(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};r2.className="ConvLSTM2DCell";ce.registerClass(r2);var D5=class extends y8{constructor(e){let t=new r2(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}};D5.className="ConvLSTM2D";ce.registerClass(D5);var a2=class extends dt{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=Ze(e);if(0Nk(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()}};a2.className="Dropout";ce.registerClass(a2);var $5=class extends a2{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};$5.className="SpatialDropout1D";ce.registerClass($5);var P5=class extends dt{constructor(e){if(super(e),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,Tn(this.units,"units"),this.activation=uo(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=Mt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Mt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=xn(e.kernelConstraint),this.biasConstraint=xn(e.biasConstraint),this.kernelRegularizer=zt(e.kernelRegularizer),this.biasRegularizer=zt(e.biasRegularizer),this.activityRegularizer=zt(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=At(e);let t=e[e.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){e=At(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return X(()=>{this.invokeCallHook(e,t);let n=Ze(e),s=vk(this.activation.getClassName()),r;return s!=null?r=Qr(n,this.kernel.read(),s,this.bias?this.bias.read():null):(r=Qr(n,this.kernel.read()),this.bias!=null&&(r=Br(r,this.bias.read())),this.activation!=null&&(r=this.activation.apply(r))),r})}getConfig(){let e={units:this.units,activation:lo(this.activation),useBias:this.useBias,kernelInitializer:Ut(this.kernelInitializer),biasInitializer:Ut(this.biasInitializer),kernelRegularizer:wt(this.kernelRegularizer),biasRegularizer:wt(this.biasRegularizer),activityRegularizer:wt(this.activityRegularizer),kernelConstraint:An(this.kernelConstraint),biasConstraint:An(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};P5.className="Dense";ce.registerClass(P5);var F5=class extends dt{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=At(e);for(let t of e.slice(1))if(t==null)throw new H(`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],eo(e,1)]}call(e,t){return X(()=>{this.invokeCallHook(e,t);let n=Ze(e);if(this.dataFormat==="channelsFirst"&&n.rank>1){let s=[0];for(let r=2;r{this.invokeCallHook(e,t);let n=Ze(e);return this.activation.apply(n)})}getConfig(){let e={activation:lo(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};O5.className="Activation";ce.registerClass(O5);var M5=class extends dt{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=Ze(e),LV(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};M5.className="RepeatVector";ce.registerClass(M5);var z5=class extends dt{constructor(e){super(e),this.targetShape=e.targetShape;for(let t=0;t{this.invokeCallHook(e,t);let n=Ze(e),s=n.shape,r=s.slice(0,1).concat(this.fixUnknownDimension(s.slice(1),this.targetShape));return W(n,r)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};z5.className="Reshape";ce.registerClass(z5);var L5=class extends dt{constructor(e){if(super(e),e.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);let t=Fr(1,e.dims.length+1);if(!v.arraysEqual(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new an({ndim:this.dims.length+1})]}computeOutputShape(e){e=At(e);let t=e.slice();return this.dims.forEach((n,s)=>{t[s+1]=e[n]}),t}call(e,t){return tt(Ze(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};L5.className="Permute";ce.registerClass(L5);var B5=class extends dt{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=Ze(e),s=-1;return fp(sl(n,this.maskValue),s)}call(e,t){return X(()=>{this.invokeCallHook(e,t);let n=Ze(e),s=-1,r=!0,a=fp(sl(n,this.maskValue),s,r);return M(n,me(a,n.dtype))})}};B5.className="Masking";ce.registerClass(B5);var W5=class extends dt{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(_t(e.inputLength))}this.inputDim=e.inputDim,Tn(this.inputDim,"inputDim"),this.outputDim=e.outputDim,Tn(this.outputDim,"outputDim"),this.embeddingsInitializer=Mt(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=zt(e.embeddingsRegularizer),this.activityRegularizer=zt(e.activityRegularizer),this.embeddingsConstraint=xn(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=Ze(e),sl(e,ct(e))):null)}computeOutputShape(e){if(e=At(e),this.inputLength==null)return[...e,this.outputDim];let t=_t(this.inputLength);if(t.length!==e.length-1)throw new H(`"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=Ze(e);n.dtype!=="int32"&&(n=mh(n,"int32"));let s=Tk(this.embeddings.read(),W(n,[n.size]));return W(s,At(this.computeOutputShape(n.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Ut(this.embeddingsInitializer),embeddingsRegularizer:wt(this.embeddingsRegularizer),activityRegularizer:wt(this.activityRegularizer),embeddingsConstraint:An(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};W5.className="Embedding";ce.registerClass(W5);var uu=class extends dt{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new Ke}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length1)throw new H(`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&&Qa(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=io(s);for(let a of e){let o=a.rank;for(let i=0;i1){let u=Fr(1,l).concat([0]);n.push(tt(i,u)),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,u=i[l-1],c=[u].concat(i.slice(0,i.length-1));a=W(tt(W(a,[-1,u]),[1,0]),c)}else if(o>1){let i=[o-1].concat(Fr(0,o-1));a=tt(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 H("`mask` should be an Array");if(!Array.isArray(e))throw new H("`inputs` should be an Array");if(t.length!==e.length)throw new H(`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:Ft(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 H("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return X(()=>qA(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new H("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 H("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new H("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new H(`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 Ke("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 Ke("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 u=0;us){o=r-s;let l=[];for(let u=0;u0){let l;s>r?l=s+r-3:l=s-1;let u=[];for(let c=l;c"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 Ke("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 H(`Dimension incompatibility: ${t[s[0]]} !== ${n[s[1]]}`)}mergeFunction(e){if(e.length!==2)throw new H(`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)=>Vd(r,e[a].shape.length)):s=[Vd(this.axes,t.shape.length),Vd(this.axes,n.shape.length)],this.normalize&&(t=pm(t,s[0]),n=pm(n,s[1])),NG(t,n,s)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[Vd(this.axes,e.length),Vd(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 Ke("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}};X5.className="Dot";ce.registerClass(X5);var K5=class extends dt{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=Ze(e);return Ah(()=>le(U0(n.shape,0,this.stddev),n),()=>n,t.training||!1)})}};K5.className="GaussianNoise";ce.registerClass(K5);var Z5=class extends dt{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=Ze(e);return this.rate>0&&this.rate<1?Ah(()=>{let r=Math.sqrt(this.rate/(1-this.rate));return M(n,U0(n.shape,1,r))},()=>n,t.training||!1):n})}};Z5.className="GaussianDropout";ce.registerClass(Z5);var Y5=class extends dt{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Ze(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 Ah(()=>{let r=Ze(e),a=1.6732632423543772,o=1.0507009873554805,i=-a*o,l=pi(Xc(n),this.rate);l=mh(l,"float32");let u=((1-this.rate)*(1+this.rate*i**2))**-.5,c=-u*i*this.rate,p=le(M(r,l),M(le(l,-1),i));return le(M(p,u),c)},()=>Ze(e),t.training||!1)}return e})}};Y5.className="AlphaDropout";ce.registerClass(Y5);function Ap(e,t,n,s,r,a=.001){let o;if(e.rank===2)o=Jy(e,t,n,s,r,a);else if(e.rank===3)o=Qy(e,t,n,s,r,a);else if(e.rank===4)o=eA(e,t,n,s,r,a);else throw new Ke(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return o}function EG(e,t,n,s,r=.001){return X(()=>{let a=ih(e,s),o=a.mean,i=a.variance;return[Ap(e,o,i,n,t,r),o,i]})}function RG(e,t,n,s,r=.001){return X(()=>{let a=ih(e,s),o=a.mean,i=a.variance,l=[];for(let f of Fr(0,e.rank))s.indexOf(f)!==-1?l.push(1):l.push(e.shape[f]);let u=W(o,l),c=W(i,l),p=t==null?null:W(t,l),d=n==null?null:W(n,l);return[Ap(e,u,c,d,p,r),o,i]})}function _G(e,t,n,s,r=.001){return v.arraysEqual(s.slice().sort(),Fr(0,e.rank-1))?EG(e,t,n,s,r):RG(e,t,n,s,r)}var J5=class extends dt{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=Mt(e.betaInitializer||"zeros"),this.gammaInitializer=Mt(e.gammaInitializer||"ones"),this.movingMeanInitializer=Mt(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Mt(e.movingVarianceInitializer||"ones"),this.betaConstraint=xn(e.betaConstraint),this.gammaConstraint=xn(e.gammaConstraint),this.betaRegularizer=zt(e.betaRegularizer),this.gammaRegularizer=zt(e.gammaRegularizer)}build(e){e=At(e);let t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new H(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new an({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=Ze(e),r=s.shape,a=r.length,o=Fr(0,a),i=this.axis>=0?this.axis:this.axis+a;o.splice(i,1);let l=rl(1,a);l[i]=r[i];let u=o.slice();u.sort();let c=!v.arraysEqual(u,Fr(0,a).slice(0,a-1)),p=()=>{if(c){let y=W(this.movingMean.read(),l),x=W(this.movingVariance.read(),l),A=this.center?W(this.beta.read(),l):null,b=this.scale?W(this.gamma.read(),l):null;return Ap(s,y,x,A,b,this.epsilon)}else return Ap(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 p();let[d,h,f]=_G(s,this.gamma.read(),this.beta.read(),o,this.epsilon),m=(y,x,A)=>{X(()=>{let b=1-A,w=y.read(),k=M(ye(w,x),b);y.write(ye(w,k))})};return(()=>{m(this.movingMean,h,this.momentum),m(this.movingVariance,f,this.momentum)})(),d})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Ut(this.betaInitializer),gammaInitializer:Ut(this.gammaInitializer),movingMeanInitializer:Ut(this.movingMeanInitializer),movingVarianceInitializer:Ut(this.movingVarianceInitializer),betaRegularizer:wt(this.betaRegularizer),gammaRegularizer:wt(this.gammaRegularizer),betaConstraint:An(this.betaConstraint),gammaConstraint:An(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};J5.className="BatchNormalization";ce.registerClass(J5);var Q5=class extends dt{constructor(e){if(e==null&&(e={}),super(e),this.axis=e.axis==null?-1:e.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(let t of this.axis)if(!Number.isInteger(t))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=Mt(e.betaInitializer||"zeros"),this.gammaInitializer=Mt(e.gammaInitializer||"ones"),this.betaRegularizer=zt(e.betaRegularizer),this.gammaRegularizer=zt(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=At(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let r=0;r=t)throw new Error(`Invalid axis: ${r}`);if(this.axis.length!==Qa(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=Ze(e),s=n.shape,r=s.length;return X(()=>{let{mean:o,variance:i}=ih(n,this.axis,!0),l=rl(1,r);for(let f of this.axis)l[f]=s[f];let u=f=>f!=null&&f.shape.length!==r?W(f,l):f,c=this.scale?u(this.gamma.read()):null,p=this.center?u(this.beta.read()):null,d=[],h=[];for(let f=0;f{if(e.rank!==4)throw new H(`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 H("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=Or()),n!=="channelsLast"&&n!=="channelsFirst")throw new H(`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]],tr(e,s)})}var ex=class extends dt{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?Or():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 H(`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 H(`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 H(`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 an({ndim:4})]}computeOutputShape(e){e=At(e);let t,n;return this.dataFormat==="channelsFirst"?(e[2]!=null&&e[2]>=0?t=e[2]+this.padding[0][0]+this.padding[0][1]:t=null,e[3]!=null&&e[3]>=0?n=e[3]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],e[1],t,n]):(e[1]!=null&&e[1]>=0?t=e[1]+this.padding[0][0]+this.padding[0][1]:t=null,e[2]!=null&&e[2]>=0?n=e[2]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],t,n,e[3]])}call(e,t){return X(()=>DG(Ze(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};ex.className="ZeroPadding2D";ce.registerClass(ex);function o2(e,t,n,s,r,a){return X(()=>{Qt(r),kk(a),nr(s),n==null&&(n=[1,1]),s==null&&(s="valid"),r==null&&(r=Or()),a==null&&(a="max"),e=v5(e,r);let o,i=s==="same"?"same":"valid";return a==="max"?o=oh(e,t,n,i):o=eh(e,t,n,i),r==="channelsFirst"&&(o=tt(o,[0,3,1,2])),o})}function A8(e,t,n,s,r,a){return X(()=>{Qt(r),kk(a),nr(s),n==null&&(n=[1,1,1]),s==null&&(s="valid"),r==null&&(r=Or()),a==null&&(a="max"),e=h8(e,r);let o,i=s==="same"?"same":"valid";return a==="max"?o=SA(e,t,n,i):o=Yy(e,t,n,i),r==="channelsFirst"&&(o=tt(o,[0,4,1,2,3])),o})}var x8=class extends dt{constructor(e){if(e.poolSize==null&&(e.poolSize=2),super(e),typeof e.poolSize=="number")this.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")this.poolSize=e.poolSize;else throw new H(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(Tn(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 H(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);Tn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,nr(this.padding),this.inputSpec=[new an({ndim:3})]}computeOutputShape(e){e=At(e);let t=Pr(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=gh(Ze(e),2);let n=this.poolingFunction(Ze(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Ge(n,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},tx=class extends x8{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return Qt(r),nr(s),o2(e,t,n,s,r,"max")}};tx.className="MaxPooling1D";ce.registerClass(tx);var nx=class extends x8{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return Qt(r),nr(s),o2(e,t,n,s,r,"avg")}};nx.className="AveragePooling1D";ce.registerClass(nx);var b8=class extends dt{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new H(`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];Tn(this.poolSize,"poolSize"),Tn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Qt(this.dataFormat),nr(this.padding),this.inputSpec=[new an({ndim:4})]}computeOutputShape(e){e=At(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=Pr(t,this.poolSize[0],this.padding,this.strides[0]),n=Pr(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(Ze(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}},sx=class extends b8{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return Qt(r),nr(s),o2(e,t,n,s,r,"max")}};sx.className="MaxPooling2D";ce.registerClass(sx);var rx=class extends b8{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return Qt(r),nr(s),o2(e,t,n,s,r,"avg")}};rx.className="AveragePooling2D";ce.registerClass(rx);var v8=class extends dt{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new H(`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];Tn(this.poolSize,"poolSize"),Tn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Qt(this.dataFormat),nr(this.padding),this.inputSpec=[new an({ndim:5})]}computeOutputShape(e){e=At(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],s=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=Pr(t,this.poolSize[0],this.padding,this.strides[0]),n=Pr(n,this.poolSize[1],this.padding,this.strides[1]),s=Pr(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(Ze(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}},ax=class extends v8{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return Qt(r),nr(s),A8(e,t,n,s,r,"max")}};ax.className="MaxPooling3D";ce.registerClass(ax);var ox=class extends v8{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return Qt(r),nr(s),A8(e,t,n,s,r,"avg")}};ox.className="AveragePooling3D";ce.registerClass(ox);var w8=class extends dt{constructor(e){super(e),this.inputSpec=[new an({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Ke}},ix=class extends w8{constructor(e){super(e||{})}call(e,t){return X(()=>{let n=Ze(e);return Wt(n,1)})}};ix.className="GlobalAveragePooling1D";ce.registerClass(ix);var lx=class extends w8{constructor(e){super(e||{})}call(e,t){return X(()=>{let n=Ze(e);return yn(n,1)})}};lx.className="GlobalMaxPooling1D";ce.registerClass(lx);var k8=class extends dt{constructor(e){super(e),this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Qt(this.dataFormat),this.inputSpec=[new an({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Ke}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},ux=class extends k8{call(e,t){return X(()=>{let n=Ze(e);return this.dataFormat==="channelsLast"?Wt(n,[1,2]):Wt(n,[2,3])})}};ux.className="GlobalAveragePooling2D";ce.registerClass(ux);var cx=class extends k8{call(e,t){return X(()=>{let n=Ze(e);return this.dataFormat==="channelsLast"?yn(n,[1,2]):yn(n,[2,3])})}};cx.className="GlobalMaxPooling2D";ce.registerClass(cx);var S8=class extends dt{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=$r(s,n);delete t.layer;let a={layer:r};return Object.assign(a,t),new e(a)}},dx=class extends S8{constructor(e){super(e),this.supportsMasking=!0}build(e){if(e=At(e),e.length<3)throw new H(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];let t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=At(e);let t=[e[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),s=e[1];return[n[0],s].concat(n.slice(1))}call(e,t){return X(()=>(e=Ze(e),g8((a,o)=>[Ze(this.layer.call(a,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};dx.className="TimeDistributed";ce.registerClass(dx);function $G(e){iu(PV,"BidirectionalMergeMode",e)}var PG="concat",px=class extends S8{constructor(e){super(e);let t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=$r(n),t.goBackwards=t.goBackwards!==!0;let s={};if(s.className=e.layer.getClassName(),s.config=t,this.backwardLayer=$r(s),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?PG:e.mergeMode,$G(this.mergeMode),e.weights)throw new Ke("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()):ys(s)}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});let r=m8(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 H("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 u=n.map(c=>new an({shape:c.shape}));this.forwardLayer.stateSpec=u.slice(0,l/2),this.backwardLayer.stateSpec=u.slice(l/2),o.push(...u)}if(s!=null)throw new Ke("Support for constants in Bidirectional layers is not implemented yet.");let i=a[0]instanceof _r;for(let l of a)if(l instanceof _r!==i)throw new H("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),u=this.inputSpec.concat(o),c=this.inputSpec;this.inputSpec=u;let p=super.apply(l,t);return this.inputSpec=c,p}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=Js(r,1));let o;return this.mergeMode==="concat"?o=qA([s,r]):this.mergeMode==="sum"?o=le(s,r):this.mergeMode==="ave"?o=M(.5,le(s,r)):this.mergeMode==="mul"?o=M(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){Ki(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),Ki(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=$r(t.layer);if(delete t.layer,t.numConstants!=null)throw new Ke("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let s=t;return s.layer=n,new e(s)}};px.className="Bidirectional";ce.registerClass(px);var hx=class extends dt{constructor(e){super(e),this.scale=e.scale,e.offset?this.offset=e.offset:this.offset=0}getConfig(){let e={scale:this.scale,offset:this.offset},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return X(()=>(e=Ze(e),e.dtype!=="float32"&&(e=mh(e,"float32")),le(M(e,this.scale),this.offset)))}};hx.className="Rescaling";ce.registerClass(hx);function FG(e){return new Zc(e)}function OG(e){return new A5(e)}function MG(e){return new m5(e)}function zG(e){return new g5(e)}function LG(e){return new y5(e)}function BG(e){return new b5(e)}function WG(e){return new x5(e)}function VG(e){return new e2(e)}function UG(e){return new wh(e)}function GG(e){return new k5(e)}function HG(e){return new kh(e)}function jG(e){return new S5(e)}function qG(e){return new I5(e)}function XG(e){return new C5(e)}function KG(e){return new T5(e)}function ZG(e){return new N5(e)}function YG(e){return new O5(e)}function JG(e){return new P5(e)}function QG(e){return new a2(e)}function eH(e){return new $5(e)}function tH(e){return new F5(e)}function nH(e){return new M5(e)}function sH(e){return new z5(e)}function rH(e){return new L5(e)}function aH(e){return new W5(e)}function oH(e){return new V5(e)}function iH(e){return new G5(e)}function lH(e){return new q5(e)}function uH(e){return new H5(e)}function cH(e){return new j5(e)}function dH(e){return new U5(e)}function pH(e){return new X5(e)}function hH(e){return new J5(e)}function fH(e){return new Q5(e)}function mH(e){return new ex(e)}function fx(e){return new nx(e)}function gH(e){return fx(e)}function yH(e){return fx(e)}function mx(e){return new rx(e)}function AH(e){return mx(e)}function xH(e){return mx(e)}function gx(e){return new ox(e)}function bH(e){return gx(e)}function vH(e){return gx(e)}function wH(e){return new ix(e)}function kH(e){return new ux(e)}function I8(e){return new lx(e)}function C8(e){return new cx(e)}function T8(e){return new tx(e)}function N8(e){return new sx(e)}function SH(e){return new ax(e)}function IH(e){return new R5(e)}function CH(e){return new n2(e)}function TH(e){return new _5(e)}function NH(e){return new Ih(e)}function EH(e){return new E5(e)}function RH(e){return new t2(e)}function _H(e){return new D5(e)}function DH(e){return new r2(e)}function $H(e){return new ia(e)}function PH(e){return new s2(e)}function FH(e){return new px(e)}function OH(e){return new dx(e)}var MH=I8,zH=C8,LH=T8,BH=N8;function WH(e){return new K5(e)}function VH(e){return new Z5(e)}function UH(e){return new Y5(e)}function GH(e){return new B5(e)}function HH(e){return new hx(e)}var E8={};We(E8,{MAPE:()=>nj,MSE:()=>aj,binaryAccuracy:()=>jH,binaryCrossentropy:()=>qH,categoricalAccuracy:()=>KH,categoricalCrossentropy:()=>ZH,cosineProximity:()=>QH,mape:()=>sj,meanAbsoluteError:()=>ej,meanAbsolutePercentageError:()=>tj,meanSquaredError:()=>rj,mse:()=>oj,precision:()=>YH,recall:()=>JH,sparseCategoricalAccuracy:()=>XH});function jH(e,t){return l5(e,t)}function qH(e,t){return Uk(e,t)}function XH(e,t){return Gk(e,t)}function KH(e,t){return u5(e,t)}function ZH(e,t){return c5(e,t)}function YH(e,t){return Vk(e,t)}function JH(e,t){return zU(e,t)}function QH(e,t){return i5(e,t)}function ej(e,t){return J0(e,t)}function tj(e,t){return Yc(e,t)}function nj(e,t){return Yc(e,t)}function sj(e,t){return Yc(e,t)}function rj(e,t){return lu(e,t)}function aj(e,t){return lu(e,t)}function oj(e,t){return lu(e,t)}var R8={};We(R8,{modelFromJSON:()=>fG});var _8={};We(_8,{l1:()=>lj,l1l2:()=>ij,l2:()=>uj});function ij(e){return new bh(e)}function lj(e){return wG(e)}function uj(e){return kG(e)}var D8=class extends oc{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof ba))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function $f(e,t){return et}var $8=class extends D8{constructor(e){if(super(),e==null&&(e={}),e.restoreBestWeights)throw new Ke("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=$f:this.mode==="max"?this.monitorFunc=Yv:this.monitor.indexOf("acc")!==-1?this.monitorFunc=Yv:this.monitorFunc=$f,this.monitorFunc===$f&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===$f?1/0:-1/0}async onEpochEnd(e,t){await qa(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 cj(e){return new $8(e)}var dj={earlyStopping:cj},pj=U();pj.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 pr;(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_QINT16=15]="DT_QINT16",e[e.DT_QUINT16=16]="DT_QUINT16",e[e.DT_UINT16=17]="DT_UINT16",e[e.DT_COMPLEX128=18]="DT_COMPLEX128",e[e.DT_HALF=19]="DT_HALF",e[e.DT_RESOURCE=20]="DT_RESOURCE",e[e.DT_VARIANT=21]="DT_VARIANT",e[e.DT_UINT32=22]="DT_UINT32",e[e.DT_UINT64=23]="DT_UINT64",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",e[e.DT_QINT16_REF=115]="DT_QINT16_REF",e[e.DT_QUINT16_REF=116]="DT_QUINT16_REF",e[e.DT_UINT16_REF=117]="DT_UINT16_REF",e[e.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",e[e.DT_HALF_REF=119]="DT_HALF_REF",e[e.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",e[e.DT_VARIANT_REF=121]="DT_VARIANT_REF",e[e.DT_UINT32_REF=122]="DT_UINT32_REF",e[e.DT_UINT64_REF=123]="DT_UINT64_REF"})(pr||(pr={}));var Jv;(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={}))})(Jv||(Jv={}));var yx={};function hj(e,t){let n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};yx[e]=n}function P8(e){return yx[e]}function fj(e){delete yx[e]}function I(e,t,n,s,r){let a=t.inputParams[e];if(a&&a.inputIndexStart!==void 0){let i=a.inputIndexStart,l=a.inputIndexEnd===0?void 0:a.inputIndexEnd===void 0?i+1:a.inputIndexEnd;if(a.type==="tensor")return as(t.inputNames[a.inputIndexStart],n,s,r);if(a.type==="tensors")return t.inputNames.slice(i,l).map(d=>as(d,n,s,r));let u=as(t.inputNames.slice(i)[0],n,s,r),c=u.dataSync();return a.type==="number"?c[0]:v.toNestedArray(u.shape,c)}let o=t.attrParams[e];return o&&o.value}function as(e,t,n,s){let[r,a]=Rs(e);if(s!=null){let i=s.getHashTableHandleByName(r);if(i!=null)return i}let o=n.currentContextIds.find(i=>!!t[ym(r,i)]);return o!==void 0?t[ym(r,o)][a]:void 0}function mj(e,t,n){return t[ym(e,n.currentContextId)]}function Yr(e,t){let[n,s,r]=Rs(e);return[ym(n,t&&t.currentContextId),s,r]}function ym(e,t){return t?`${e}-${t}`:e}function Rs(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 Gf(e,t,n){let s=I("pad",e,t,n);if(s==="explicit"){s=I("explicitPaddings",e,t,n);let r=[[0,0],[0,0],[0,0],[0,0]];for(let a=0;a<4;a++)r[a][0]=s[a*2],r[a][1]=s[a*2+1];return r}return s}function ya(e){return e.kept?e:Hn(e)}var F8={};We(F8,{json:()=>gj});var gj=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],O8={};We(O8,{json:()=>yj});var yj=[{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}]}],M8={};We(M8,{json:()=>Aj});var Aj=[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcatV2",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}],z8={};We(z8,{json:()=>xj});var xj=[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}],L8={};We(L8,{json:()=>bj});var bj=[{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"}]},{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:"RandomStandardNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"seed",name:"seed",type:"number",defaultValue:0},{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:"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"}]}],B8={};We(B8,{json:()=>vj});var vj=[{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}]}],W8={};We(W8,{json:()=>wj});var wj=[{tfOpName:"LowerBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"UpperBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}],V8={};We(V8,{json:()=>kj});var kj=[{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"}]}],U8={};We(U8,{json:()=>Sj});var Sj=[{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"}]}],G8={};We(G8,{json:()=>Ij});var Ij=[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}],H8={};We(H8,{json:()=>Cj});var Cj=[{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}]}],j8={};We(j8,{json:()=>Tj});var Tj=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]}],q8={};We(q8,{json:()=>Nj});var Nj=[{tfOpName:"EuclideanNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",defaultValue:!1}]},{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}],X8={};We(X8,{json:()=>Ej});var Ej=[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Cumprod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}],K8={};We(K8,{json:()=>Rj});var Rj=[{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}]}],Z8={};We(Z8,{json:()=>_j});var _j=[{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"}]}],Y8={};We(Y8,{json:()=>Dj});var Dj=[{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}]}],J8={};We(J8,{json:()=>$j});var $j=[{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"}]}],Q8={};We(Q8,{json:()=>Pj});var Pj=[{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:[]}],Qv=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[F8,O8,M8,z8,L8,B8,W8,V8,U8,G8,H8,j8,q8,X8,K8,Z8,Y8,J8,Q8],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=[],u={},c={};t!=null&&(u=this.mapSignatureEntries(t.inputs),c=this.mapSignatureEntries(t.outputs));let p=Object.keys(o);p.forEach(f=>{let m=o[f];m.inputNames.forEach((g,y)=>{let[x,,A]=Yr(g),b=o[x];if(b.outputs!=null){let w=b.outputs.indexOf(A);if(w!==-1){let k=`${x}:${w}`;m.inputNames[y]=k}}m.inputs.push(b),b.children.push(m)})}),Object.keys(c).length===0?p.forEach(f=>{let m=o[f];m.children.length===0&&l.push(m)}):Object.keys(c).forEach(f=>{let[m]=Yr(f),g=o[m];g!=null&&(g.signatureKey=c[f],l.push(g))}),Object.keys(u).length>0?Object.keys(u).forEach(f=>{let[m]=Yr(f),g=o[m];g&&(g.signatureKey=u[f],i.push(g))}):i=s;let d={};e.library!=null&&e.library.function!=null&&(d=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:d};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=P8(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.slice(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=z3(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=z3(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"string[]":o=H3(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=H3(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number":o=B3(e.attr,r.tfName,r.defaultValue||0),o===void 0&&!!r.tfDeprecatedName&&(o=B3(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number[]":o=G3(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=G3(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool":o=L3(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=L3(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool[]":o=q3(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=q3(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape":o=U3(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=U3(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape[]":o=j3(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=j3(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype":o=W3(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=W3(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype[]":o=V3(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=V3(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"func":o=e7(e.attr,r.tfName,r.defaultValue),o===void 0&&!!r.tfDeprecatedName&&(o=e7(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((c,p)=>(c[p.name]=this.mapNode(p),p.op==="Const"&&s.push(c[p.name]),c),{}));let a=[],o=[];e.signature.inputArg.forEach(c=>{let[p]=Yr(c.name),d={name:p,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Ax(c.type),type:"dtype"}},children:[]};d.signatureKey=c.name,a.push(d),r[p]=d}),Object.keys(r).forEach(c=>{let p=r[c];p.inputNames.forEach((d,h)=>{let[f,,m]=Yr(d),g=r[f];if(g.outputs!=null){let y=g.outputs.indexOf(m);if(y!==-1){let x=`${f}:${y}`;p.inputNames[h]=x}}p.inputs.push(g),g.children.push(p)})});let l=e.ret;e.signature.outputArg.forEach(c=>{let[p,d]=Yr(l[c.name]),h=r[p];h!=null&&(h.defaultOutput=d,o.push(h))});let u=this.mapArgsToSignature(e);return{nodes:r,inputs:a,outputs:o,weights:s,placeholders:n,signature:u}}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 Fj(e){let t=U().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 eS(e,t){let n=Array.isArray(e)?String.fromCharCode.apply(null,e):Fj(e);return t?n:n.toLowerCase()}function z3(e,t,n,s=!1){let r=e[t];return r!=null?eS(r.s,s):n}function L3(e,t,n){let s=e[t];return s?s.b:n}function B3(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 Ax(e){switch(typeof e=="string"&&(e=pr[e]),e){case pr.DT_FLOAT:case pr.DT_HALF:return"float32";case pr.DT_INT32:case pr.DT_INT64:case pr.DT_INT8:case pr.DT_UINT8:return"int32";case pr.DT_BOOL:return"bool";case pr.DT_DOUBLE:return"float32";case pr.DT_STRING:return"string";default:return null}}function e7(e,t,n){let s=e[t];return s&&s.func?s.func.name:n}function W3(e,t,n){let s=e[t];return s&&s.type?Ax(s.type):n}function V3(e,t,n){let s=e[t];return s&&s.list&&s.list.type?s.list.type.map(r=>Ax(r)):n}function tS(e){if(!e.unknownRank)return e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function U3(e,t,n){let s=e[t];return s&&s.shape?tS(s.shape):n}function G3(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 H3(e,t,n,s=!1){let r=e[t];return r&&r.list&&r.list.s?r.list.s.map(a=>eS(a,s)):n}function j3(e,t,n){let s=e[t];return s&&s.list&&s.list.shape?s.list.shape.map(r=>tS(r)):n}function q3(e,t,n){let s=e[t];return s&&s.list&&s.list.b?s.list.b:n}var Oj=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 as(e,this.tensorMap,this.context)}getAttr(e,t){let n=this.node.rawAttrs[e];if(n.tensor!=null)return as(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return B3(this.node.rawAttrs,e,t);if(n.s!=null)return z3(this.node.rawAttrs,e,t);if(n.b!=null)return L3(this.node.rawAttrs,e,t);if(n.shape!=null)return U3(this.node.rawAttrs,e,t);if(n.type!=null)return W3(this.node.rawAttrs,e,t);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return G3(this.node.rawAttrs,e,t);if(n.list.s!=null)return H3(this.node.rawAttrs,e,t);if(n.list.shape!=null)return j3(this.node.rawAttrs,e,t);if(n.list.b!=null)return q3(this.node.rawAttrs,e,t);if(n.list.type!=null)return V3(this.node.rawAttrs,e,t)}return t}},Bn={};We(Bn,{OP_SCOPE_SUFFIX:()=>Sy,abs:()=>rn,acos:()=>Vy,acosh:()=>Uy,add:()=>le,addN:()=>a0,all:()=>o0,any:()=>fp,argMax:()=>Ps,argMin:()=>Gy,asin:()=>Hy,asinh:()=>jy,atan:()=>qy,atan2:()=>Xy,atanh:()=>Ky,avgPool:()=>eh,avgPool3d:()=>Yy,basicLSTMCell:()=>c6,batchNorm:()=>Wc,batchNorm2d:()=>Jy,batchNorm3d:()=>Qy,batchNorm4d:()=>eA,batchToSpaceND:()=>th,bincount:()=>tA,booleanMaskAsync:()=>q6,broadcastArgs:()=>d6,broadcastTo:()=>Xi,buffer:()=>ze,cast:()=>me,ceil:()=>nA,clipByValue:()=>bs,clone:()=>Hn,complex:()=>wa,concat:()=>ut,concat1d:()=>sA,concat2d:()=>nu,concat3d:()=>rA,concat4d:()=>aA,conv1d:()=>i0,conv2d:()=>ka,conv2dTranspose:()=>l0,conv3d:()=>iA,conv3dTranspose:()=>lA,cos:()=>nh,cosh:()=>u0,cosineWindow:()=>_0,cumprod:()=>mp,cumsum:()=>c0,denseBincount:()=>h6,depthToSpace:()=>uA,depthwiseConv2d:()=>Vc,diag:()=>f6,dilation2d:()=>cA,div:()=>ge,divNoNan:()=>dA,dot:()=>pA,dropout:()=>zA,einsum:()=>m6,elu:()=>Uc,enclosingPowerOfTwo:()=>LA,equal:()=>Fs,erf:()=>hA,euclideanNorm:()=>gA,exp:()=>Os,expandDims:()=>Ft,expm1:()=>yA,eye:()=>d0,fft:()=>dh,fill:()=>zr,floor:()=>Hc,floorDiv:()=>Bc,fused:()=>rc,gather:()=>jc,gatherND:()=>Y6,greater:()=>ks,greaterEqual:()=>pi,ifft:()=>sc,imag:()=>Jp,image:()=>ke,inTopKAsync:()=>J6,irfft:()=>T0,isFinite:()=>AA,isInf:()=>xA,isNaN:()=>bA,leakyRelu:()=>sh,less:()=>p0,lessEqual:()=>hi,linalg:()=>VA,linspace:()=>b6,localResponseNormalization:()=>vA,log:()=>Ms,log1p:()=>rh,logSigmoid:()=>wA,logSoftmax:()=>f0,logSumExp:()=>m0,logicalAnd:()=>gr,logicalNot:()=>ah,logicalOr:()=>g0,logicalXor:()=>kA,losses:()=>ck,lowerBound:()=>w6,matMul:()=>et,max:()=>yn,maxPool:()=>oh,maxPool3d:()=>SA,maxPoolWithArgmax:()=>k6,maximum:()=>oa,mean:()=>Wt,meshgrid:()=>S6,min:()=>Sa,minimum:()=>qc,mirrorPad:()=>IA,mod:()=>ru,moments:()=>ih,movingAverage:()=>X6,mul:()=>M,multiRNNCell:()=>I6,multinomial:()=>C6,neg:()=>Dt,norm:()=>Gc,notEqual:()=>sl,oneHot:()=>ec,ones:()=>Ds,onesLike:()=>zs,op:()=>B,outerProduct:()=>T6,pad:()=>tr,pad1d:()=>N6,pad2d:()=>E6,pad3d:()=>R6,pad4d:()=>_6,pool:()=>CA,pow:()=>Ia,prelu:()=>uh,print:()=>Ny,prod:()=>TA,raggedGather:()=>D6,raggedTensorToTensor:()=>$6,rand:()=>P6,randomGamma:()=>F6,randomNormal:()=>A0,randomStandardNormal:()=>O6,randomUniform:()=>Xc,range:()=>nc,real:()=>tc,reciprocal:()=>RA,relu:()=>Lr,relu6:()=>x0,reshape:()=>W,reverse:()=>Js,reverse1d:()=>M6,reverse2d:()=>z6,reverse3d:()=>L6,reverse4d:()=>B6,rfft:()=>ph,round:()=>b0,rsqrt:()=>v0,scalar:()=>Ce,scatterND:()=>K6,searchSorted:()=>y0,selu:()=>w0,separableConv2d:()=>k0,setdiff1dAsync:()=>W6,sigmoid:()=>Mn,sign:()=>_A,signal:()=>uk,sin:()=>S0,sinh:()=>I0,slice:()=>Oe,slice1d:()=>ch,slice2d:()=>C0,slice3d:()=>fi,slice4d:()=>oo,softmax:()=>au,softplus:()=>su,spaceToBatchND:()=>lh,sparse:()=>dk,sparseToDense:()=>Z6,spectral:()=>lk,split:()=>Ht,sqrt:()=>Ln,square:()=>bt,squaredDifference:()=>N0,squeeze:()=>Ge,stack:()=>ln,step:()=>ou,stridedSlice:()=>DA,string:()=>pk,sub:()=>ye,sum:()=>ve,tan:()=>$A,tanh:()=>tl,tensor:()=>Ue,tensor1d:()=>Ot,tensor2d:()=>mr,tensor3d:()=>Py,tensor4d:()=>V6,tensor5d:()=>U6,tensor6d:()=>G6,tile:()=>As,topk:()=>PA,transpose:()=>tt,truncatedNormal:()=>E0,unique:()=>FA,unsortedSegmentSum:()=>R0,unstack:()=>bn,upperBound:()=>H6,variable:()=>OA,where:()=>qn,whereAsync:()=>MA,zeros:()=>Vt,zerosLike:()=>ct});var Mj=(e,t,n,s=Bn)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[s.add(I("a",e,t,n),I("b",e,t,n))];case"AddN":return[s.addN(I("tensors",e,t,n))];case"FloorMod":case"Mod":return[s.mod(I("a",e,t,n),I("b",e,t,n))];case"Mul":return[s.mul(I("a",e,t,n),I("b",e,t,n))];case"RealDiv":case"Div":return[s.div(I("a",e,t,n),I("b",e,t,n))];case"DivNoNan":return[s.divNoNan(I("a",e,t,n),I("b",e,t,n))];case"FloorDiv":return[s.floorDiv(I("a",e,t,n),I("b",e,t,n))];case"Sub":return[s.sub(I("a",e,t,n),I("b",e,t,n))];case"Minimum":return[s.minimum(I("a",e,t,n),I("b",e,t,n))];case"Maximum":return[s.maximum(I("a",e,t,n),I("b",e,t,n))];case"Pow":return[s.pow(I("a",e,t,n),I("b",e,t,n))];case"SquaredDifference":return[s.squaredDifference(I("a",e,t,n),I("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},zj=(e,t,n,s=Bn)=>{switch(e.op){case"Abs":case"ComplexAbs":return[s.abs(I("x",e,t,n))];case"Acos":return[s.acos(I("x",e,t,n))];case"Acosh":return[s.acosh(I("x",e,t,n))];case"Asin":return[s.asin(I("x",e,t,n))];case"Asinh":return[s.asinh(I("x",e,t,n))];case"Atan":return[s.atan(I("x",e,t,n))];case"Atan2":return[s.atan2(I("x",e,t,n),I("y",e,t,n))];case"Atanh":return[s.atanh(I("x",e,t,n))];case"Ceil":return[s.ceil(I("x",e,t,n))];case"Complex":return[s.complex(I("real",e,t,n),I("imag",e,t,n))];case"Cos":return[s.cos(I("x",e,t,n))];case"Cosh":return[s.cosh(I("x",e,t,n))];case"Elu":return[s.elu(I("x",e,t,n))];case"Erf":return[s.erf(I("x",e,t,n))];case"Exp":return[s.exp(I("x",e,t,n))];case"Expm1":return[s.expm1(I("x",e,t,n))];case"Floor":return[s.floor(I("x",e,t,n))];case"Log":return[s.log(I("x",e,t,n))];case"Log1p":return[s.log1p(I("x",e,t,n))];case"Imag":return[s.imag(I("x",e,t,n))];case"Neg":return[s.neg(I("x",e,t,n))];case"Reciprocal":return[s.reciprocal(I("x",e,t,n))];case"Real":return[s.real(I("x",e,t,n))];case"Relu":return[s.relu(I("x",e,t,n))];case"Round":return[s.round(I("x",e,t,n))];case"Selu":return[s.selu(I("x",e,t,n))];case"Sigmoid":return[s.sigmoid(I("x",e,t,n))];case"Sin":return[s.sin(I("x",e,t,n))];case"Sign":return[s.sign(I("x",e,t,n))];case"Sinh":return[s.sinh(I("x",e,t,n))];case"Softplus":return[s.softplus(I("x",e,t,n))];case"Sqrt":return[s.sqrt(I("x",e,t,n))];case"Square":return[s.square(I("x",e,t,n))];case"Tanh":return[s.tanh(I("x",e,t,n))];case"Tan":return[s.tan(I("x",e,t,n))];case"ClipByValue":return[s.clipByValue(I("x",e,t,n),I("clipValueMin",e,t,n),I("clipValueMax",e,t,n))];case"Relu6":return[s.relu6(I("x",e,t,n))];case"Rsqrt":return[s.rsqrt(as(e.inputNames[0],t,n))];case"Prod":return[s.prod(I("x",e,t,n),I("axes",e,t,n))];case"LeakyRelu":return[s.leakyRelu(I("x",e,t,n),I("alpha",e,t,n))];case"Prelu":return[s.prelu(I("x",e,t,n),I("alpha",e,t,n))];case"IsNan":return[s.isNaN(as(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function fr(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 t7(e){return!(typeof e=="number"||e.some(t=>t<0))}function Ud(e,t,n){let s=X3(e,n),r=!t7(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=X3(a.shape,s)}),!t7(s))throw new Error(`Non-fully-defined elementShape: ${s}`);return s}function X3(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 Lj=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=Ce(0),Cn(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),fr(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,Cn(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,bn(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=W(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}`);fr(t,r.shape,"TensorList shape mismatch: "),Cn(r)}),this.idTensor=Ce(0),this.maxNumElements=s,Cn(this.idTensor)}get id(){return this.idTensor.id}copy(){return new lc([...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.`);fr(e,this.elementShape,"TensorList shape mismatch: ");let s=Ud(this.elementShape,this.tensors,e);return X(()=>{let r=this.tensors.map(a=>W(a,s));return ln(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=Ud(this.elementShape,this.tensors,e),s=this.tensors.pop();return s.kept=!1,fr(s.shape,e,"TensorList shape mismatch: "),W(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(fr(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Cn(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);let t=new lc([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let n=0;nthis.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.`);fr(this.tensors[e].shape,t,"TensorList shape mismatch: ");let s=Ud(this.elementShape,this.tensors,t);return W(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.`);fr(this.elementShape,t.shape,"TensorList shape mismatch: "),Cn(t),this.tensors[e]!=null&&(this.tensors[e].kept=!1),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}`);fr(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let s=Ud(this.elementShape,this.tensors,n);return e.length===0?Ue([],[0].concat(s)):X(()=>{let r=e.map(a=>W(this.tensors[a],s));return ln(r,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);fr(this.elementShape,t,"TensorList shape mismatch: ");let n=Ud(this.elementShape,this.tensors,t);return this.size()===0?Ue([],[0].concat(n)):X(()=>{let s=this.tensors.map(r=>W(r,n));return ut(s,0)})}};function Bj(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);fr(r,t,"TensorList shape mismatch: ");let a=bn(e);return new lc(a,t,s)}function Wj(e,t,n,s){return new lc([],e,t,s)}function Vj(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 lc([],n,e.dtype,s),o=bn(e,0);return t.forEach((i,l)=>{a.setItem(i,o[l])}),a}function Uj(e,t,n){let s=0,r=t.map(c=>(s+=c,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=X3(a,n),i=s===0?0:e.size/s,l=X(()=>{let c=[];e=W(e,[1,s,i]);for(let p=0;p{switch(e.op){case"If":case"StatelessIf":{let s=I("thenBranch",e,t,n),r=I("elseBranch",e,t,n),a=I("cond",e,t,n),o=I("args",e,t,n);return(await a.data())[0]?n.functionMap[s].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap):n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{let s=I("body",e,t,n),r=I("cond",e,t,n),a=I("args",e,t,n),o=await n.functionMap[r].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),i=a.map(c=>c.id),l=await o[0].data();o.forEach(c=>{!c.kept&&i.indexOf(c.id)===-1&&c.dispose()});let u=a;for(;l[0];){let c=u;u=await n.functionMap[s].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);let p=u.map(h=>h.id);c.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&p.indexOf(h.id)===-1&&h.dispose()});let d=await n.functionMap[r].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);l=await d[0].data(),d.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&p.indexOf(h.id)===-1&&h.dispose()})}return u}case"LoopCond":{let s=I("pred",e,t,n);return[ya(s)]}case"Switch":{let s=I("pred",e,t,n),r=I("data",e,t,n);return r.kept||(r=ya(r)),(await s.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{let s=e.inputNames.find(r=>as(r,t,n)!==void 0);if(s){let r=as(s,t,n);return[ya(r)]}return}case"Enter":{let s=I("frameName",e,t,n),r=I("tensor",e,t,n);return n.enterFrame(s),[ya(r)]}case"Exit":{let s=I("tensor",e,t,n);return n.exitFrame(),[ya(s)]}case"NextIteration":{let s=I("tensor",e,t,n);return n.nextIteration(),[ya(s)]}case"TensorArrayV3":{let s=I("size",e,t,n),r=I("dtype",e,t,n),a=I("elementShape",e,t,n),o=I("dynamicSize",e,t,n),i=I("clearAfterRead",e,t,n),l=I("identicalElementShapes",e,t,n),u=I("name",e,t,n),c=new Lj(u,r,s,a,l,o,i);return n.addTensorArray(c),[c.idTensor,Ce(1)]}case"TensorArrayWriteV3":{let s=I("tensorArrayId",e,t,n),r=I("index",e,t,n),a=I("tensor",e,t,n),o=n.getTensorArray(s.id);return o.write(r,a),[o.idTensor]}case"TensorArrayReadV3":{let s=I("tensorArrayId",e,t,n),r=I("index",e,t,n);return[n.getTensorArray(s.id).read(r)]}case"TensorArrayGatherV3":{let s=I("tensorArrayId",e,t,n),r=I("indices",e,t,n),a=I("dtype",e,t,n);return[n.getTensorArray(s.id).gather(r,a)]}case"TensorArrayScatterV3":{let s=I("tensorArrayId",e,t,n),r=I("indices",e,t,n),a=I("tensor",e,t,n),o=n.getTensorArray(s.id);return o.scatter(r,a),[o.idTensor]}case"TensorArrayConcatV3":{let s=I("tensorArrayId",e,t,n),r=n.getTensorArray(s.id),a=I("dtype",e,t,n);return[r.concat(a)]}case"TensorArraySplitV3":{let s=I("tensorArrayId",e,t,n),r=I("tensor",e,t,n),a=I("lengths",e,t,n),o=n.getTensorArray(s.id);return o.split(a,r),[o.idTensor]}case"TensorArraySizeV3":{let s=I("tensorArrayId",e,t,n),r=n.getTensorArray(s.id);return[Ce(r.size(),"int32")]}case"TensorArrayCloseV3":{let s=I("tensorArrayId",e,t,n),r=n.getTensorArray(s.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{let s=I("tensorListId",e,t,n),r=I("index",e,t,n),a=I("tensor",e,t,n),o=n.getTensorList(s.id);return o.setItem(r,a),[o.idTensor]}case"TensorListGetItem":{let s=I("tensorListId",e,t,n),r=I("index",e,t,n),a=I("elementShape",e,t,n),o=I("elementDType",e,t,n);return[n.getTensorList(s.id).getItem(r,a,o)]}case"TensorListScatterV2":case"TensorListScatter":{let s=I("indices",e,t,n),r=I("tensor",e,t,n),a=I("elementShape",e,t,n),o=I("numElements",e,t,n),i=Vj(r,s,a,o);return n.addTensorList(i),[i.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let s=I("elementShape",e,t,n),r=I("elementDType",e,t,n),a;e.op==="TensorListReserve"?a="numElements":a="maxNumElements";let o=I(a,e,t,n),i=e.op==="TensorListReserve"?-1:o,l=Wj(s,r,o,i);return n.addTensorList(l),[l.idTensor]}case"TensorListGather":{let s=I("tensorListId",e,t,n),r=I("indices",e,t,n),a=I("elementShape",e,t,n),o=I("elementDType",e,t,n);return[n.getTensorList(s.id).gather(r,o,a)]}case"TensorListStack":{let s=I("tensorListId",e,t,n),r=I("elementShape",e,t,n),a=I("elementDType",e,t,n),o=I("numElements",e,t,n);return[n.getTensorList(s.id).stack(r,a,o)]}case"TensorListFromTensor":{let s=I("tensor",e,t,n),r=I("elementShape",e,t,n),a=I("elementDType",e,t,n),o=Bj(s,r,a);return n.addTensorList(o),[o.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{let s=I("tensorListId",e,t,n),r=n.getTensorList(s.id),a=I("dtype",e,t,n),o=I("elementShape",e,t,n);return[r.concat(a,o)]}case"TensorListPushBack":{let s=I("tensorListId",e,t,n),r=I("tensor",e,t,n),a=n.getTensorList(s.id);return a.pushBack(r),[a.idTensor]}case"TensorListPopBack":{let s=I("tensorListId",e,t,n),r=I("elementShape",e,t,n),a=I("elementDType",e,t,n);return[n.getTensorList(s.id).popBack(r,a)]}case"TensorListSplit":{let s=I("tensor",e,t,n),r=I("elementShape",e,t,n),a=I("lengths",e,t,n),o=Uj(s,a,r);return n.addTensorList(o),[o.idTensor]}case"TensorListLength":{let s=I("tensorListId",e,t,n),r=n.getTensorList(s.id);return[Ce(r.size(),"int32")]}case"TensorListResize":{let s=I("tensorListId",e,t,n),r=I("size",e,t,n),o=n.getTensorList(s.id).resize(r);return n.addTensorList(o),[o.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function n7(e,t,n){let[s,r]=I("fusedOps",e,t,n),a=s==="biasadd",o=!a,i=r==="prelu",l=s==="fusedbatchnorm",u=I("numArgs",e,t,n);if(a){if(i&&u!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&a&&u!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");let c=I("strides",e,t,n),p=Gf(e,t,n),d=I("dataFormat",e,t,n).toUpperCase(),h=I("dilations",e,t,n),[f,m]=I("args",e,t,n);o&&(m=f,f=void 0);let g=I("leakyreluAlpha",e,t,n);return{stride:c,pad:p,dataFormat:d,dilations:h,biasArg:f,preluArg:m,activationFunc:r,leakyreluAlpha:g}}var Hj=(e,t,n,s=Bn)=>{switch(e.op){case"Conv1D":{let r=I("stride",e,t,n),a=I("pad",e,t,n),o=I("dataFormat",e,t,n).toUpperCase(),i=I("dilation",e,t,n);return[s.conv1d(I("x",e,t,n),I("filter",e,t,n),r,a,o,i)]}case"Conv2D":{let r=I("strides",e,t,n),a=Gf(e,t,n),o=I("dataFormat",e,t,n).toUpperCase(),i=I("dilations",e,t,n);return[s.conv2d(I("x",e,t,n),I("filter",e,t,n),[r[1],r[2]],a,o,[i[1],i[2]])]}case"_FusedConv2D":{let{stride:r,pad:a,dataFormat:o,dilations:i,biasArg:l,preluArg:u,activationFunc:c,leakyreluAlpha:p}=n7(e,t,n);return[s.fused.conv2d({x:I("x",e,t,n),filter:I("filter",e,t,n),strides:[r[1],r[2]],pad:a,dataFormat:o,dilations:[i[1],i[2]],bias:l,activation:c,preluActivationWeights:u,leakyreluAlpha:p})]}case"FusedDepthwiseConv2dNative":{let{stride:r,pad:a,dataFormat:o,dilations:i,biasArg:l,preluArg:u,activationFunc:c,leakyreluAlpha:p}=n7(e,t,n);return[s.fused.depthwiseConv2d({x:I("x",e,t,n),filter:I("filter",e,t,n),strides:[r[1],r[2]],pad:a,dataFormat:o,dilations:[i[1],i[2]],bias:l,activation:c,preluActivationWeights:u,leakyreluAlpha:p})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let r=I("outputShape",e,t,n),a=I("strides",e,t,n),o=Gf(e,t,n);return[s.conv2dTranspose(I("x",e,t,n),I("filter",e,t,n),r,[a[1],a[2]],o)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let r=I("strides",e,t,n),a=Gf(e,t,n),o=I("dilations",e,t,n),i=I("dataFormat",e,t,n).toUpperCase();return[s.depthwiseConv2d(I("input",e,t,n),I("filter",e,t,n),[r[1],r[2]],a,i,[o[1],o[2]])]}case"Conv3D":{let r=I("strides",e,t,n),a=I("pad",e,t,n),o=I("dataFormat",e,t,n).toUpperCase(),i=I("dilations",e,t,n);return[s.conv3d(I("x",e,t,n),I("filter",e,t,n),[r[1],r[2],r[3]],a,o,[i[1],i[2],i[3]])]}case"AvgPool":{let r=I("strides",e,t,n),a=I("pad",e,t,n),o=I("kernelSize",e,t,n);return[s.avgPool(I("x",e,t,n),[o[1],o[2]],[r[1],r[2]],a)]}case"MaxPool":{let r=I("strides",e,t,n),a=I("pad",e,t,n),o=I("kernelSize",e,t,n);return[s.maxPool(I("x",e,t,n),[o[1],o[2]],[r[1],r[2]],a)]}case"MaxPoolWithArgmax":{let r=I("strides",e,t,n),a=I("pad",e,t,n),o=I("kernelSize",e,t,n),i=I("includeBatchInIndex",e,t,n),{result:l,indexes:u}=s.maxPoolWithArgmax(I("x",e,t,n),[o[1],o[2]],[r[1],r[2]],a,i);return[l,u]}case"AvgPool3D":{let r=I("strides",e,t,n),a=I("pad",e,t,n),o=I("kernelSize",e,t,n);return[s.avgPool3d(I("x",e,t,n),[o[1],o[2],o[3]],[r[1],r[2],r[3]],a)]}case"MaxPool3D":{let r=I("strides",e,t,n),a=I("pad",e,t,n),o=I("kernelSize",e,t,n);return[s.maxPool3d(I("x",e,t,n),[o[1],o[2],o[3]],[r[1],r[2],r[3]],a)]}case"Dilation2D":{let r=I("strides",e,t,n),a=I("pad",e,t,n),o=I("dilations",e,t,n),i=r[1],l=r[2],u=o[1],c=o[2];return[s.dilation2d(I("x",e,t,n),I("filter",e,t,n),[i,l],a,[u,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},jj=(e,t,n,s=Bn)=>{switch(e.op){case"Fill":{let r=I("shape",e,t,n),a=I("dtype",e,t,n),o=I("value",e,t,n);return[s.fill(r,o,a)]}case"LinSpace":{let r=I("start",e,t,n),a=I("stop",e,t,n),o=I("num",e,t,n);return[s.linspace(r,a,o)]}case"Multinomial":{let r=I("logits",e,t,n),a=I("numSamples",e,t,n),o=I("seed",e,t,n);return[s.multinomial(r,a,o)]}case"OneHot":{let r=I("indices",e,t,n),a=I("depth",e,t,n),o=I("onValue",e,t,n),i=I("offValue",e,t,n),l=I("dtype",e,t,n);return[s.oneHot(r,a,o,i,l)]}case"Ones":return[s.ones(I("shape",e,t,n),I("dtype",e,t,n))];case"OnesLike":return[s.onesLike(I("x",e,t,n))];case"RandomStandardNormal":return[s.randomStandardNormal(I("shape",e,t,n),I("dtype",e,t,n),I("seed",e,t,n))];case"RandomUniform":return[s.randomUniform(I("shape",e,t,n),I("minval",e,t,n),I("maxval",e,t,n),I("dtype",e,t,n))];case"Range":{let r=I("start",e,t,n),a=I("stop",e,t,n),o=I("step",e,t,n);return[s.range(r,a,o,I("dtype",e,t,n))]}case"TruncatedNormal":{let r=I("shape",e,t,n),a=I("mean",e,t,n),o=I("stdDev",e,t,n),i=I("seed",e,t,n);return[s.truncatedNormal(r,a,o,I("dtype",e,t,n),i)]}case"Zeros":return[s.zeros(I("shape",e,t,n),I("dtype",e,t,n))];case"ZerosLike":return[s.zerosLike(I("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function o3(e,t,n){let s=I("boxes",e,t,n),r=I("scores",e,t,n),a=I("maxOutputSize",e,t,n),o=I("iouThreshold",e,t,n),i=I("scoreThreshold",e,t,n),l=I("softNmsSigma",e,t,n);return{boxes:s,scores:r,maxOutputSize:a,iouThreshold:o,scoreThreshold:i,softNmsSigma:l}}var qj=async(e,t,n,s,r=Bn)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:a,scores:o,maxOutputSize:i,iouThreshold:l,scoreThreshold:u,softNmsSigma:c}=o3(e,t,n),p=await r.image.nonMaxSuppressionWithScoreAsync(a,o,i,l,u,c);return[p.selectedIndices,p.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:a,scores:o,maxOutputSize:i,iouThreshold:l,scoreThreshold:u}=o3(e,t,n),c=I("padToMaxOutputSize",e,t,n),p=await r.image.nonMaxSuppressionPaddedAsync(a,o,i,l,u,c);return[p.selectedIndices,p.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:a,scores:o,maxOutputSize:i,iouThreshold:l,scoreThreshold:u}=o3(e,t,n);return[await r.image.nonMaxSuppressionAsync(a,o,i,l,u)]}case"Where":{let a=r.cast(I("condition",e,t,n),"bool"),o=[await r.whereAsync(a)];return a.dispose(),o}case"ListDiff":return r.setdiff1dAsync(I("x",e,t,n),I("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}},Xj=(e,t,n,s=Bn)=>{switch(e.op){case"LowerBound":{let r=I("sortedSequence",e,t,n),a=I("values",e,t,n);return[s.lowerBound(r,a)]}case"TopKV2":{let r=I("x",e,t,n),a=I("k",e,t,n),o=I("sorted",e,t,n),i=s.topk(r,a,o);return[i.values,i.indices]}case"UpperBound":{let r=I("sortedSequence",e,t,n),a=I("values",e,t,n);return[s.upperBound(r,a)]}case"Unique":{let r=I("x",e,t,n),a=s.unique(r);return[a.values,a.indices]}case"UniqueV2":{let r=I("x",e,t,n),a=I("axis",e,t,n),o=s.unique(r,a);return[o.values,o.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Kj=(e,t,n,s=Bn)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let r=I("default",e,t,n);return[as(e.name,t,n)||r];case"Placeholder":return[as(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let c=I("x",e,t,n);return[ya(c)]}case"IdentityN":return I("x",e,t,n).map(c=>ya(c));case"Snapshot":let a=I("x",e,t,n);return[ya(a)];case"Shape":return[s.tensor1d(I("x",e,t,n).shape,"int32")];case"ShapeN":return I("x",e,t,n).map(c=>s.tensor1d(c.shape));case"Size":return[s.scalar(I("x",e,t,n).size,"int32")];case"Rank":return[s.scalar(I("x",e,t,n).rank,"int32")];case"NoOp":return[s.scalar(1)];case"Print":let o=I("x",e,t,n),i=I("data",e,t,n),l=I("message",e,t,n),u=I("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(l);for(let c=0;ce.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Ce(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=bn(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=I("keyDType",e,t,n),a=I("valueDType",e,t,n),o=new Zj(r,a);return s.addHashTable(e.name,o),[o.handle]}case"LookupTableImport":case"LookupTableImportV2":{let r=I("tableHandle",e,t,n,s),a=I("keys",e,t,n),o=I("values",e,t,n);return[await s.getHashTableById(r.id).import(a,o)]}case"LookupTableFind":case"LookupTableFindV2":{let r=I("tableHandle",e,t,n,s),a=I("keys",e,t,n),o=I("defaultValue",e,t,n);return[await s.getHashTableById(r.id).find(a,o)]}case"LookupTableSize":case"LookupTableSizeV2":{let r=I("tableHandle",e,t,n,s);return[s.getHashTableById(r.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Jj=(e,t,n,s=Bn)=>{switch(e.op){case"ResizeBilinear":{let r=I("images",e,t,n),a=I("size",e,t,n),o=I("alignCorners",e,t,n),i=I("halfPixelCenters",e,t,n);return[s.image.resizeBilinear(r,[a[0],a[1]],o,i)]}case"ResizeNearestNeighbor":{let r=I("images",e,t,n),a=I("size",e,t,n),o=I("alignCorners",e,t,n),i=I("halfPixelCenters",e,t,n);return[s.image.resizeNearestNeighbor(r,[a[0],a[1]],o,i)]}case"CropAndResize":{let r=I("image",e,t,n),a=I("boxes",e,t,n),o=I("boxInd",e,t,n),i=I("cropSize",e,t,n),l=I("method",e,t,n),u=I("extrapolationValue",e,t,n);return[s.image.cropAndResize(r,a,o,i,l,u)]}case"ImageProjectiveTransformV3":{let r=I("images",e,t,n),a=I("transforms",e,t,n),o=I("outputShape",e,t,n),i=I("fillValue",e,t,n),l=I("interpolation",e,t,n),u=I("fillMode",e,t,n);return[s.image.transform(r,a,l.toLowerCase(),u.toLowerCase(),i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Qj=(e,t,n,s=Bn)=>{switch(e.op){case"Equal":return[s.equal(I("a",e,t,n),I("b",e,t,n))];case"NotEqual":return[s.notEqual(I("a",e,t,n),I("b",e,t,n))];case"Greater":return[s.greater(I("a",e,t,n),I("b",e,t,n))];case"GreaterEqual":return[s.greaterEqual(I("a",e,t,n),I("b",e,t,n))];case"Less":return[s.less(I("a",e,t,n),I("b",e,t,n))];case"LessEqual":return[s.lessEqual(I("a",e,t,n),I("b",e,t,n))];case"LogicalAnd":return[s.logicalAnd(I("a",e,t,n),I("b",e,t,n))];case"LogicalNot":return[s.logicalNot(I("a",e,t,n))];case"LogicalOr":return[s.logicalOr(I("a",e,t,n),I("b",e,t,n))];case"Select":case"SelectV2":return[s.where(I("condition",e,t,n),I("a",e,t,n),I("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},eq=(e,t,n,s=Bn)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[s.matMul(I("a",e,t,n),I("b",e,t,n),I("transposeA",e,t,n),I("transposeB",e,t,n))];case"Einsum":return[s.einsum(I("equation",e,t,n),...I("tensors",e,t,n))];case"Transpose":return[s.transpose(I("x",e,t,n),I("perm",e,t,n))];case"_FusedMatMul":let[r,a]=I("fusedOps",e,t,n),o=r==="biasadd",i=a==="prelu",l=I("numArgs",e,t,n),u=I("leakyreluAlpha",e,t,n);if(o){if(i&&l!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&l!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[c,p]=I("args",e,t,n);return[s.fused.matMul({a:I("a",e,t,n),b:I("b",e,t,n),transposeA:I("transposeA",e,t,n),transposeB:I("transposeB",e,t,n),bias:c,activation:a,preluActivationWeights:p,leakyreluAlpha:u})];default:throw TypeError(`Node type ${e.op} is not implemented`)}},tq=(e,t,n,s=Bn)=>{switch(e.op){case"EuclideanNorm":return[s.euclideanNorm(I("x",e,t,n),I("axis",e,t,n),I("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":return[s.batchNorm(I("x",e,t,n),I("mean",e,t,n),I("variance",e,t,n),I("offset",e,t,n),I("scale",e,t,n),I("epsilon",e,t,n))];case"FusedBatchNormV3":return[s.batchNorm(I("x",e,t,n),I("mean",e,t,n),I("variance",e,t,n),I("offset",e,t,n),I("scale",e,t,n),I("epsilon",e,t,n))];case"LRN":return[s.localResponseNormalization(I("x",e,t,n),I("radius",e,t,n),I("bias",e,t,n),I("alpha",e,t,n),I("beta",e,t,n))];case"Softmax":return[s.softmax(I("x",e,t,n))];case"LogSoftmax":return[s.logSoftmax(I("x",e,t,n))];case"SparseToDense":return[s.sparseToDense(I("sparseIndices",e,t,n),I("outputShape",e,t,n),I("sparseValues",e,t,n),I("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},nq=(e,t,n,s=Bn)=>{switch(e.op){case"Max":{let i=I("axis",e,t,n),l=I("keepDims",e,t,n);return[s.max(I("x",e,t,n),i,l)]}case"Mean":{let i=I("axis",e,t,n),l=I("keepDims",e,t,n);return[s.mean(I("x",e,t,n),i,l)]}case"Min":{let i=I("axis",e,t,n),l=I("keepDims",e,t,n);return[s.min(I("x",e,t,n),i,l)]}case"Sum":{let i=I("axis",e,t,n),l=I("keepDims",e,t,n);return[s.sum(I("x",e,t,n),i,l)]}case"All":{let i=I("axis",e,t,n),l=I("keepDims",e,t,n);return[s.all(I("x",e,t,n),i,l)]}case"Any":{let i=I("axis",e,t,n),l=I("keepDims",e,t,n);return[s.any(I("x",e,t,n),i,l)]}case"ArgMax":{let i=I("axis",e,t,n);return[s.argMax(I("x",e,t,n),i)]}case"ArgMin":{let i=I("axis",e,t,n);return[s.argMin(I("x",e,t,n),i)]}case"Prod":{let i=I("axis",e,t,n),l=I("keepDims",e,t,n);return[s.prod(I("x",e,t,n),i,l)]}case"Cumprod":{let i=I("axis",e,t,n),l=I("exclusive",e,t,n),u=I("reverse",e,t,n);return[s.cumprod(I("x",e,t,n),i,l,u)]}case"Cumsum":{let i=I("axis",e,t,n),l=I("exclusive",e,t,n),u=I("reverse",e,t,n);return[s.cumsum(I("x",e,t,n),i,l,u)]}case"Bincount":let r=I("x",e,t,n),a=I("weights",e,t,n),o=I("size",e,t,n);return[s.bincount(r,a,o)];case"DenseBincount":{let i=I("x",e,t,n),l=I("weights",e,t,n),u=I("size",e,t,n),c=I("binaryOutput",e,t,n);return[s.denseBincount(i,l,u,c)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},sq=(e,t,n,s=Bn)=>{switch(e.op){case"ConcatV2":case"Concat":{let r=I("n",e,t,n),a=I("axis",e,t,n),o=I("tensors",e,t,n);return o=o.slice(0,r),[s.concat(o,a)]}case"Gather":{let r=I("x",e,t,n),a=I("indices",e,t,n);return[s.gather(r,s.cast(a,"int32"),0)]}case"GatherV2":{let r=I("axis",e,t,n),a=I("batchDims",e,t,n),o=I("x",e,t,n),i=I("indices",e,t,n);return[s.gather(o,s.cast(i,"int32"),r,a)]}case"Reverse":{let r=I("dims",e,t,n),a=[];for(let i=0;i{let r=I("axis",e,t,n),a=I("tensors",e,t,n),o=a[0].shape,i=s.squeeze(a[0]).shape,l=a.map(u=>{let c=v.arraysEqual(u.shape,o);if(!c&&!v.arraysEqual(s.squeeze(u).shape,i))throw new Error("the input tensors shape does not match");return c?u:s.reshape(u,o)});return[s.stack(l,r)]});case"Unpack":{let r=I("axis",e,t,n),a=I("tensor",e,t,n);return s.unstack(a,r)}case"Tile":{let r=I("reps",e,t,n);return[s.tile(I("x",e,t,n),r)]}case"Split":case"SplitV":{let r=I("axis",e,t,n),a=I("numOrSizeSplits",e,t,n),o=I("x",e,t,n);return s.split(o,a,r)}case"ScatterNd":{let r=I("indices",e,t,n),a=I("values",e,t,n),o=I("shape",e,t,n);return[s.scatterND(r,a,o)]}case"GatherNd":{let r=I("x",e,t,n),a=I("indices",e,t,n);return[s.gatherND(r,a)]}case"SparseToDense":{let r=I("sparseIndices",e,t,n),a=I("outputShape",e,t,n),o=I("sparseValues",e,t,n),i=I("defaultValue",e,t,n);return[s.sparseToDense(r,o,a,o.dtype===i.dtype?i:s.cast(i,o.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},rq=(e,t,n,s=Bn)=>{switch(e.op){case"SparseFillEmptyRows":{let{outputIndices:r,outputValues:a,emptyRowIndicator:o,reverseIndexMap:i}=s.sparse.sparseFillEmptyRows(I("indices",e,t,n),I("values",e,t,n),I("denseShape",e,t,n),I("defaultValue",e,t,n));return[r,a,o,i]}case"SparseReshape":{let{outputIndices:r,outputShape:a}=s.sparse.sparseReshape(I("inputIndices",e,t,n),I("inputShape",e,t,n),I("newShape",e,t,n));return[r,a]}case"SparseSegmentMean":return[s.sparse.sparseSegmentMean(I("data",e,t,n),I("indices",e,t,n),I("segmentIds",e,t,n))];case"SparseSegmentSum":return[s.sparse.sparseSegmentSum(I("data",e,t,n),I("indices",e,t,n),I("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},aq=(e,t,n,s=Bn)=>{switch(e.op){case"FFT":return[s.fft(I("x",e,t,n))];case"IFFT":return[s.ifft(I("x",e,t,n))];case"RFFT":return[s.rfft(I("x",e,t,n))];case"IRFFT":return[s.irfft(I("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},oq=(e,t,n,s=Bn)=>{switch(e.op){case"StringNGrams":{let{nGrams:r,nGramsSplits:a}=s.string.stringNGrams(I("data",e,t,n),I("dataSplits",e,t,n),I("separator",e,t,n),I("nGramWidths",e,t,n),I("leftPad",e,t,n),I("rightPad",e,t,n),I("padWidth",e,t,n),I("preserveShortSequences",e,t,n));return[r,a]}case"StringSplit":{let{indices:r,values:a,shape:o}=s.string.stringSplit(I("input",e,t,n),I("delimiter",e,t,n),I("skipEmpty",e,t,n));return[r,a,o]}case"StringToHashBucketFast":return[s.string.stringToHashBucketFast(I("input",e,t,n),I("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},iq=(e,t,n,s=Bn)=>{switch(e.op){case"Cast":return[s.cast(I("x",e,t,n),I("dtype",e,t,n))];case"ExpandDims":{let r=I("axis",e,t,n);return[s.expandDims(I("x",e,t,n),r)]}case"Squeeze":{let r=I("axis",e,t,n);return[s.squeeze(I("x",e,t,n),r)]}case"Reshape":return[s.reshape(I("x",e,t,n),I("shape",e,t,n))];case"MirrorPad":return[s.mirrorPad(I("x",e,t,n),I("padding",e,t,n),I("mode",e,t,n))];case"PadV2":case"Pad":return[s.pad(I("x",e,t,n),I("padding",e,t,n),I("constantValue",e,t,n))];case"SpaceToBatchND":{let r=I("blockShape",e,t,n),a=I("paddings",e,t,n);return[s.spaceToBatchND(I("x",e,t,n),r,a)]}case"BatchToSpaceND":{let r=I("blockShape",e,t,n),a=I("crops",e,t,n);return[s.batchToSpaceND(I("x",e,t,n),r,a)]}case"DepthToSpace":{let r=I("blockSize",e,t,n),a=I("dataFormat",e,t,n).toUpperCase();return[s.depthToSpace(I("x",e,t,n),r,a)]}case"BroadcastTo":return[s.broadcastTo(I("x",e,t,n),I("shape",e,t,n))];case"BroadcastArgs":return[s.broadcastArgs(I("s0",e,t,n),I("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function s7(e,t,n,s,r=X){let a=((o,i,l)=>{switch(o.category){case"arithmetic":return r(()=>Mj(o,i,l));case"basic_math":return r(()=>zj(o,i,l));case"control":return Gj(o,i,l);case"convolution":return r(()=>Hj(o,i,l));case"creation":return r(()=>jj(o,i,l));case"dynamic":return qj(o,i,l);case"evaluation":return r(()=>Xj(o,i,l));case"image":return r(()=>Jj(o,i,l));case"graph":return r(()=>Kj(o,i,l));case"logical":return r(()=>Qj(o,i,l));case"matrices":return r(()=>eq(o,i,l));case"normalization":return r(()=>tq(o,i,l));case"reduction":return r(()=>nq(o,i,l));case"slice_join":return r(()=>sq(o,i,l));case"sparse":return r(()=>rq(o,i,l));case"spectral":return r(()=>aq(o,i,l));case"string":return r(()=>oq(o,i,l));case"transformation":return r(()=>iq(o,i,l));case"hash_table":return Yj(o,i,l,s);case"custom":let u=P8(o.op);if(u&&u.customExecutor)return u.customExecutor(new Oj(o,i,l));throw TypeError(`Custom op ${o.op} is not registered.`);default:throw TypeError(`Unknown op '${o.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(a)?a.then(o=>[].concat(o)):[].concat(a)}var r7=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 a7(e,t,n,s){let r=new Set,a=[],o=null,i=null,l=new Set,u=Object.keys(e).map(d=>Rs(d)[0]),c=[];s!=null&&(c=s.map(d=>Rs(d.name)[0]));let p=[...t];for(;p.length>0;){let d=p.pop();if((nS(d)||pq(d)||hq(d))&&o==null&&(o=d,i=o.children.map(h=>h.name).filter(h=>r.has(h))),r.add(d.name),n[d.name]==null&&u.indexOf(d.name)===-1&&c.indexOf(d.name)===-1){if(d.inputs.length===0){a.push(d.name);continue}d.inputs.forEach(h=>{l.has(h.name)||(l.add(h.name),p.push(h))})}}return{inputs:e,outputs:t,usedNodes:r,missingInputs:a,dynamicNode:o,syncInputs:i}}function lq(e,t,n){let{usedNodes:s,inputs:r}=n,a=[],o=Object.keys(r).map(c=>Rs(c)[0]).map(c=>e.nodes[c]),i=e.initNodes;o.forEach(c=>{s.has(c.name)&&a.push(c)}),e.weights.forEach(c=>{s.has(c.name)&&a.push(c)}),i!=null&&i.forEach(c=>{s.has(c.name)&&a.push(c)});let l=new Set,u=[];for(;a.length>0;){let c=a.pop();l.add(c.name),t[c.name]||u.push(c),c.children.forEach(p=>{!l.has(p.name)&&s.has(p.name)&&p.inputs.every(d=>l.has(d.name))&&a.push(p)})}return u}var uq=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],cq=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],dq=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function nS(e){return uq.indexOf(e.op)>=0}function pq(e){return cq.indexOf(e.op)>=0}function hq(e){return dq.indexOf(e.op)>=0}var K3=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 K3(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=a7(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 lq(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(c=>this.graph.nodes[Rs(c)[0]]),r=t.map(c=>Rs(c)[0]),a=r.map(c=>this.graph.nodes[c]);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={},u={};return X(()=>{let c=new r7(this.weightMap,l,u,this.functionExecutorMap),p=Object.assign({},this.weightMap);Object.keys(e).forEach(f=>{let[m,g]=Rs(f),y=[];y[g]=e[f],p[m]=y});let d=this.getFrozenTensorIds(p),h={};for(let f=0;fas(f,p,c))})}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=mj(i.name,n,s);l!=null&&l.forEach(u=>{if(u&&!u.kept&&!r.has(u.id)){let c=o[u.id];if(c===1){if(!this.keepTensorForDebug)u.dispose();else{let[p,d]=Yr(t.name,s);this.intermediateTensors[p]?this.intermediateTensors[p][d]=u:(this.intermediateTensors[p]=[],this.intermediateTensors[p][d]=u)}delete o[u.id]}else c!=null&&o[u.id]--}})}}))}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){!this.intermediateTensors||(Object.keys(this.intermediateTensors).forEach(e=>this.intermediateTensors[e].forEach(t=>t.dispose())),this.disposeTensorsMap())}disposeTensorsMap(){!this.tensorsMap||Object.keys(this.tensorsMap).forEach(e=>{this.tensorsMap[e].forEach(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=U().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(u){console.warn(u.message)}this.resetIntermediateTensors();let a=new r7(this.weightMap,s,r,this.functionExecutorMap);this.tensorsMap=await this.executeWithControlFlow(e,a,t,n);let o=t.map(u=>as(u,this.tensorsMap,a)),i=o.map(u=>u.id),l=Object.keys(e).map(u=>e[u].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[Rs(x)[0]]),o=n.map(x=>Rs(x)[0]),i=o.map(x=>this.graph.nodes[x]);i.length===0&&(i=this._outputs);let{usedNodes:l,missingInputs:u,dynamicNode:c,syncInputs:p}=a7(e,i,this.weightMap,this._initNodes),d=[...a,...this.graph.weights,...this._initNodes||[]].map(x=>({node:x,contexts:t.currentContext})),h=Object.assign({},this.weightMap);Object.keys(e).forEach(x=>{let[A,b]=Rs(x),w=[];w[b]=e[x],h[A]=w});let f={},m=this.getFrozenTensorIds(h),g={};for(;d.length>0;){let x=this.processStack(a,d,t,h,g,m,o,f,l);await Promise.all(x)}c==null&&!s&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let y=i.filter(x=>!nS(x)&&!as(x.name,h,t)).map(x=>x.name);if(y.length>0){let x="";throw c!=null&&(x=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${p}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${r}]. Consider providing the following inputs: [${u}]. ${x}`)}return h}processStack(e,t,n,s,r,a,o,i,l){let u=[];for(;t.length>0;){let c=t.pop();n.currentContext=c.contexts;let p="";if(c.node.op==="Enter"&&I("isConstant",c.node,s,n)&&([p]=Yr(c.node.name,n)),s[c.node.name]==null){let d=s7(c.node,s,n,this._resourceManager);p||([p]=Yr(c.node.name,n));let h=n.currentContext;v.isPromise(d)?u.push(d.then(f=>(s[p]=f,n.currentContext=h,this.checkTensorForDisposal(p,c.node,s,n,a,o,i),this.processChildNodes(c.node,t,n,s,r,l),f))):(s[p]=d,this.checkTensorForDisposal(p,c.node,s,n,a,o,i),this.processChildNodes(c.node,t,n,s,r,l))}else this.processChildNodes(c.node,t,n,s,r,l)}return u}processChildNodes(e,t,n,s,r,a){e.children.forEach(o=>{let[i]=Yr(o.name,n);r[i]||!a.has(o.name)||(o.op==="Merge"?o.inputNames.some(l=>!!as(l,s,n))&&(r[i]=!0,t.push({contexts:n.currentContext,node:o})):o.inputNames.every(l=>!!as(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]=Rs(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]=Rs(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]=Rs(t);if(!this.graph.nodes[n])throw new Error(`The output '${t}' is not found in the graph`)})}},fq=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]}},mq="?tfjs-format=file",gq="model.json",Ch=class{constructor(e,t={},n=On){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=n,t==null&&(this.loadOptions={}),this.resourceManager=new fq}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}get modelStructuredOutputKeys(){return this.structuredOutputKeys}findIOHandler(){let e=this.modelUrl;if(e.load!=null)this.handler=e;else if(this.loadOptions.requestInit!=null)this.handler=this.io.browserHTTPRequest(e,this.loadOptions);else{let t=this.io.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(this.io.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}load(){if(this.findIOHandler(),this.handler.load==null)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let e=this.handler.load();return v.isPromise(e)?e.then(t=>this.loadSync(t)):this.loadSync(e)}loadSync(e){this.artifacts=e;let t=this.artifacts.modelTopology,n=this.artifacts.signature;if(this.artifacts.userDefinedMetadata!=null){let r=this.artifacts.userDefinedMetadata;r.signature!=null&&(n=r.signature),r.structuredOutputKeys!=null&&(this.structuredOutputKeys=r.structuredOutputKeys)}this.signature=n,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;let s=this.io.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new K3(Qv.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=Qv.Instance.transformGraph(e.modelInitializer);this.initializer=new K3(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=this.io.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){let n=this.execute(e,this.outputNodes);if(this.structuredOutputKeys){let s=n instanceof st?[n]:n,r={};return s.forEach((a,o)=>r[this.structuredOutputKeys[o]]=a),r}return n}normalizeInputs(e){if(!(e instanceof st)&&!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 xx(e,t={},n=On){if(e==null)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");t==null&&(t={}),t.fromTFHub&&typeof e=="string"&&(e=Aq(e));let s=new Ch(e,t,n);return await s.load(),s}function yq(e){if(e==null)throw new Error("modelUrl in loadGraphModelSync() cannot be null. Please provide model artifacts or an IOHandler that loads the model");let t;if(e instanceof Array){let[s,r]=e;if(!s)throw new Error("modelJSON must be the first element of the array");if(!r||!(r instanceof ArrayBuffer))throw new Error("An ArrayBuffer of weights must be the second element of the array");if(!("modelTopology"in s))throw new Error("Model JSON is missing 'modelTopology'");if(!("weightsManifest"in s))throw new Error("Model JSON is missing 'weightsManifest'");let a=On.getWeightSpecs(s.weightsManifest),o=On.getModelArtifactsForJSONSync(s,a,r);t=On.fromMemorySync(o)}else if("load"in e)t=e;else if("modelTopology"in e&&"weightSpecs"in e&&"weightData"in e)t=On.fromMemorySync(e);else throw new Error("Unknown model format");let n=new Ch(t);return n.load(),n}function Aq(e){return e.endsWith("/")||(e=e+"/"),`${e}${gq}${mq}`}var xq="3.21.0",sS={};We(sS,{CSVDataset:()=>pS,Dataset:()=>Jc,FileDataSource:()=>xS,TextLineDataset:()=>dS,URLDataSource:()=>bS,array:()=>Vq,csv:()=>Qq,func:()=>eX,generator:()=>tX,microphone:()=>sX,version_data:()=>rX,webcam:()=>nX,zip:()=>Uq});var bq=fo(Em()),vq=fo(Em());function wq(e,t){return Am(e,t)}function Am(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(uc(e)){let a=Array.isArray(e)?[]:{};s.add(e);for(let o in e){let i=e[o],l=Am(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 kq(e,t=aS){return rS(e,t)}function rS(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(uc(s)){let a=Array.isArray(s)?[]:{};n.add(s);for(let o in s){let i=e.map(u=>u[o]),l=rS(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 aS(e){return e===null?null:uc(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function oS(e,t){let n=new Map;Am(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 Am(e,t,n)}function uc(e){let t=!1;if(U().get("IS_BROWSER"))t=e instanceof TextDecoder;else{let{StringDecoder:n}=nw();t=e instanceof n}return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof st)&&!(e instanceof Promise)&&!t)}function Sq(e){return e==null||Iq(e)||Array.isArray(e)||typeof e=="object"&&e instanceof st||v.isTypedArray(e)}function Iq(e){return e===null||typeof e!="object"&&typeof e!="function"}function Cq(e){return wq(e,Tq)}function Tq(e){return e instanceof st?{value:e.clone(),recurse:!1}:uc(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}var iS=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}},bx=class extends iS{constructor(){super(bx.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 Fq(this,e,t)}columnMajorBatch(e,t=!0,n=aS){return this.rowMajorBatch(e,t).map(r=>kq(r,n))}concatenate(e,t){return new uS(lS([this,e]),t)}take(e){return e<0||e==null?this:new Pq(this,e)}skip(e){return e<0||e==null?this:new $q(this,e)}prefetch(e){return new cS(this,e)}shuffle(e,t){return new Wq(this,e,t)}serial(){return new Dq(this)}},Rq=class extends Nn{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:Cq(e),done:!1}}},_q=class extends Nn{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}}},Dq=class extends Nn{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()}},$q=class extends Nn{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()}},Fq=class extends Nn{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}}},Oq=class extends Nn{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;Y(e.value)}}},Mq=class extends Nn{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}}},zq=class extends Nn{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}}}},o7=class extends Nn{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}}},wx=class extends Nn{constructor(){super(),this.outputQueue=new bx,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}}},Lq=class extends wx{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}},uS=class extends Nn{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}},Ya;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(Ya||(Ya={}));var Bq=class extends Nn{constructor(e,t=Ya.FAIL){super(),this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){return"{TODO: fill in upstream of zip summaries} -> Zip"}async nextState(e){await e;let t=0,n=0;function s(a){return a instanceof Nn?{value:a.next().then(i=>(t++,i.done&&n++,i.value)),recurse:!1}:{value:null,recurse:!0}}let r=await oS(this.iterators,s);if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case Ya.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case Ya.SHORTEST:return{value:null,done:!0};case Ya.LONGEST:default:}return this.count++,{value:r,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},cS=class extends Nn{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new iS(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()}},Wq=class extends cS{constructor(e,t,n){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=vq.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}}},Jc=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),Es(async()=>(await n.iterator()).columnMajorBatch(e,t,Gq),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,Es(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,Es(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 Es(async()=>(await t.iterator()).map(n=>X(()=>e(n))),this.size)}mapAsync(e){let t=this;return Es(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 Es(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,Es(async()=>{let s=vx(async()=>({value:await t.iterator(),done:!1}));return Nq(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=bq.alea(t||v.now().toString());return Es(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,Es(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()}};Jc.MAX_BUFFER_SIZE=1e4;function Es(e,t=null){return new class extends Jc{constructor(){super(...arguments),this.size=t}async iterator(){return e()}}}function Vq(e){return Es(async()=>lS(e),e.length)}function Uq(e){if(!uc(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 oS(e,s=>{if(s instanceof Jc)return{value:s.iterator(),recurse:!1};if(uc(s))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return Eq(n,Ya.SHORTEST)},t)}function Gq(e){if(e===null)return null;let t=e[0];return Sq(t)?{value:Hq(e),recurse:!1}:{value:null,recurse:!0}}function Hq(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof st?ln(e):Ue(e)}var dS=class extends Jc{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))}},Pf='"',Gd=Symbol("out"),i7=Symbol("field"),Ff=Symbol("quote"),i3=Symbol("quoteafterquote"),l7=Symbol("quoteinquote"),pS=class extends Jc{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 dS(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(!U().get("IS_BROWSER"))throw new Error("microphone API is only supported in browser environment.");let t=new hS(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),Ue(n,t)}},fS=class extends Nn{constructor(e,t){if(super(),this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=Ot([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=mr([a,r,i,o],[1,4])}else this.cropBox=mr([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(!U().get("IS_BROWSER"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}let n=new fS(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=ra.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=Ft(me(e,"float32"),0),n;n=ke.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let s=n.shape;return W(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.")}},mS=class{},gS=class extends Nn{split(e){return new jq(this,e)}},jq=class extends gS{constructor(e,t){super(),this.upstream=e,this.impl=new qq(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},qq=class extends wx{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}},Xq=class extends Nn{decodeUTF8(){return new Kq(this)}},Kq=class extends gS{constructor(e){super(),this.upstream=e,this.impl=new Zq(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},Zq=class extends wx{constructor(e){if(super(),this.upstream=e,U().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=nw();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 U().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}},yS=class extends Xq{constructor(e,t={}){super(),this.file=e,this.options=t,v.assert(e instanceof Uint8Array||(U().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 Yq(e,t={},n){let s,r;typeof e=="string"?s=e:(s=e.url,r=Jq(e));let a=await(n||v.fetch)(s,r);if(a.ok){let o=new Uint8Array(await a.arrayBuffer());return new yS(o,t)}else throw new Error(a.statusText)}var Jq=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 AS(e){return typeof e=="string"&&e.slice(0,7)==="file://"}var xS=class extends mS{constructor(e,t={}){super(),this.input=e,this.options=t}async iterator(){if(AS(this.input)&&U().get("IS_NODE")){let e=gy();this.input=e.readFileSync(this.input.slice(7))}return new yS(this.input,this.options)}},bS=class extends mS{constructor(e,t={}){super(),this.url=e,this.fileOptions=t}async iterator(){return AS(this.url)?new xS(this.url,this.fileOptions).iterator():Yq(this.url,this.fileOptions)}};function Qq(e,t={}){return new pS(new bS(e),t)}function eX(e){let t=vx(e);return Es(async()=>t)}function tX(e){return Es(async()=>{let t=await e();return vx(()=>t.next())})}async function nX(e,t){return fS.create(e,t)}async function sX(e){return hS.create(e)}var rX="3.21.0";function Te(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 aX=Ar.whereImpl,kx=class extends fc{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new Tp(this,Jt())}nextDataId(){return kx.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,U().get("IS_NODE")&&T.warn(` ============================ Hi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details. ============================`));let 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 T.mergeRealAndImagArrays(s,r)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId);if(e.dtype==="string")try{let n=t.map(s=>v.decodeString(s));return ze(e.shape,e.dtype,n)}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return ze(e.shape,e.dtype,t)}makeOutput(e,t,n){return Jt().makeTensorFromTensorInfo(this.makeTensorInfo(t,n,e),this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos: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){Te([e],"where");let t=this.readSync(e.dataId);return aX(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};kx.nextDataId=0;var Sx={};We(Sx,{addImpl:()=>kS,bincountImpl:()=>Cx,bincountReduceImpl:()=>SS,castImpl:()=>wS,ceilImpl:()=>IS,concatImpl:()=>Tx,equalImpl:()=>CS,expImpl:()=>NS,expm1Impl:()=>RS,floorImpl:()=>_S,gatherNdImpl:()=>DS,gatherV2Impl:()=>$S,greaterEqualImpl:()=>FS,greaterImpl:()=>PS,lessEqualImpl:()=>MS,lessImpl:()=>OS,linSpaceImpl:()=>zS,logImpl:()=>LS,maxImpl:()=>BS,maximumImpl:()=>WS,minimumImpl:()=>VS,multiplyImpl:()=>Nx,negImpl:()=>US,notEqualImpl:()=>GS,prodImpl:()=>HS,raggedGatherImpl:()=>jS,raggedTensorToTensorImpl:()=>qS,rangeImpl:()=>Rx,rsqrtImpl:()=>XS,scatterImpl:()=>Hu,sigmoidImpl:()=>QX,simpleAbsImpl:()=>vS,sliceImpl:()=>bm,sparseFillEmptyRowsImpl:()=>ZS,sparseReshapeImpl:()=>YS,sparseSegmentReductionImpl:()=>_x,sqrtImpl:()=>nK,squaredDifferenceImpl:()=>JS,stridedSliceImpl:()=>QS,stringNGramsImpl:()=>Dx,stringSplitImpl:()=>$x,stringToHashBucketFastImpl:()=>Px,subImpl:()=>eI,tileImpl:()=>tI,topKImpl:()=>sI,transposeImpl:()=>Ex,uniqueImpl:()=>rI});function vS(e){let t=new Float32Array(e.length);for(let n=0;n{let{x:t}=e.inputs,n=e.backend;Te(t,"abs");let s=new Float32Array(v.sizeFromShape(t.shape)),r=n.data.get(t.dataId).values;return s=vS(r),n.makeOutput(s,t.shape,t.dtype)},iX={kernelName:dl,backendName:"cpu",kernelFunc:oX};function dn(e){return(t,n,s,r,a)=>{let o=T.assertAndGetBroadcastShape(t,n),i=o.length,l=v.computeStrides(o),u=v.sizeFromShape(o),c=v.getTypedArrayFromDType(a,u),p=t.length,d=n.length,h=v.computeStrides(t),f=v.computeStrides(n),m=T.getBroadcastDims(t,o),g=T.getBroadcastDims(n,o);if(m.length+g.length===0)for(let y=0;yA[C]=0);let b=v.locToIndex(A,p,h),w=x.slice(-d);g.forEach(C=>w[C]=0);let k=v.locToIndex(w,d,f);c[y]=e(s[b],r[k])}return[c,o]}}function _s(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 lX={kernelName:Ep,backendName:"cpu",kernelFunc:_s};function xm(e,t,n="float32"){if(n==="complex64"){let r=xm(e,t,"float32"),a=xm(e,t,"float32");return _s({inputs:{real:r,imag:a},backend:e})}let s=v.makeZerosTypedArray(v.sizeFromShape(t),n);return e.makeTensorInfo(t,n,s)}function sa(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 uX={kernelName:Fo,backendName:"cpu",kernelFunc:sa};function al(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 cX={kernelName:Mp,backendName:"cpu",kernelFunc:al};function wS(e,t,n,s){if(s==="int32"){let r=Int32Array.from(e);return[t,"int32",r]}if(s==="bool"){let r=v.toTypedArray([0],n),[a,o]=dn((i,l)=>i!==l?1:0)(t,[],e,r,"bool");return[o,"bool",a]}throw new Error(`Error in Cast: failed to cast ${n} to ${s}`)}function po(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dtype:a}=s;if(a==="complex64"){if(r.dtype==="complex64")return sa({inputs:{x:r},backend:n});let c=xm(n,r.shape,r.dtype),p=po({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),d=_s({inputs:{real:p,imag:c},backend:n});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(p),d}if(r.dtype==="complex64"){let c=al({inputs:{input:r},backend:n}),p=po({inputs:{x:c},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(c),p}if(!v.hasEncodingLoss(r.dtype,a)){let c=sa({inputs:{x:r},backend:n});return{dataId:c.dataId,shape:c.shape,dtype:a}}let o=n.data.get(r.dataId).values,[i,l,u]=wS(o,r.shape,r.dtype,a);return n.makeTensorInfo(i,l,u)}var dX={kernelName:bo,backendName:"cpu",kernelFunc:po};function En(e,t,n,s){return n==null?({inputs:r,backend:a})=>{let{a:o,b:i}=r,l=a;Te([o,i],e);let u=l.data.get(o.dataId).values,c=l.data.get(i.dataId).values,p=o.dtype==="string"?T.fromUint8ToStringArray(u):u,d=o.dtype==="string"?T.fromUint8ToStringArray(c):c,h=s||o.dtype,[f,m]=t(o.shape,i.shape,p,d,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 u=po({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),c=l.data.get(u.dataId),p=c.complexTensorInfos.real,d=c.complexTensorInfos.imag,h=l.data.get(p.dataId).values,f=l.data.get(d.dataId).values,m=po({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(m.dataId),y=g.complexTensorInfos.real,x=g.complexTensorInfos.imag,A=l.data.get(y.dataId).values,b=l.data.get(x.dataId).values,[w,k,C]=n(o.shape,i.shape,h,f,A,b),N=l.makeTensorInfo(C,"float32",w),R=l.makeTensorInfo(C,"float32",k),D=_s({inputs:{real:N,imag:R},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(m),l.disposeIntermediateTensorInfo(N),l.disposeIntermediateTensorInfo(R),D}else{let u=l.data.get(o.dataId).values,c=l.data.get(i.dataId).values,p=s||o.dtype,[d,h]=t(o.shape,i.shape,u,c,p);return l.makeTensorInfo(h,p,d)}}}function Ix(e){return(t,n,s,r,a,o)=>{let i=T.assertAndGetBroadcastShape(t,n),l=v.sizeFromShape(i),u=i.length,c=v.computeStrides(i),p=v.getTypedArrayFromDType("float32",l),d=v.getTypedArrayFromDType("float32",l),h=T.getBroadcastDims(t,i),f=T.getBroadcastDims(n,i),m=T.mergeRealAndImagArrays(s,r),g=T.mergeRealAndImagArrays(a,o),y=t.length,x=v.computeStrides(t),A=n.length,b=v.computeStrides(n);if(h.length+f.length===0)for(let w=0;wC[$]=0);let N=v.locToIndex(C,y,x),R=k.slice(-A);f.forEach($=>R[$]=0);let D=v.locToIndex(R,A,b),E=e(m[N*2],m[N*2+1],g[D*2],g[D*2+1]);p[w]=E.real,d[w]=E.imag}return[p,d,i]}}var kS=dn((e,t)=>e+t),pX=Ix((e,t,n,s)=>({real:e+n,imag:t+s})),cc=En(Ta,kS,pX),hX={kernelName:Ta,backendName:"cpu",kernelFunc:cc};function Cx(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 SS(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,u):t.size>0?o.set(o.get(i,u)+t.get(i,l),i,u):o.set(o.get(i,u)+1,i,u))}return o}function mi(e){return(t,n,s)=>{let r=v.getTypedArrayFromDType(n,t.length);for(let a=0;a{let{x:o}=s;if(Te(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,u=v.sizeFromShape(o.shape),c=n||o.dtype,p=v.getArrayFromDType(c,u);for(let d=0;d{let{x:o}=s;if(Te(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,u=n||o.dtype,c=t(l,u,r);return i.makeTensorInfo(o.shape,u,c)}}var IS=mi(e=>Math.ceil(e)),fX=Qc(vo,IS),mX={kernelName:vo,backendName:"cpu",kernelFunc:fX};function Tx(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"?T.fromUint8ToStringArray(o.vals):o.vals,l=0;for(let u=0;ue===t?1:0),TS=En(Al,CS,null,"bool"),gX={kernelName:Al,backendName:"cpu",kernelFunc:TS},NS=mi(e=>Math.exp(e)),ES=Qc(Ro,NS,"float32"),yX={kernelName:Ro,backendName:"cpu",kernelFunc:ES},RS=mi(e=>Math.expm1(e)),AX=Qc(bl,RS),xX={kernelName:bl,backendName:"cpu",kernelFunc:AX},_S=mi(e=>Math.floor(e)),bX=Qc(_o,_S),vX={kernelName:_o,backendName:"cpu",kernelFunc:bX};function DS(e,t,n,s,r,a,o,i,l){let u=ze([s,a],n);for(let c=0;c=l/a)throw new Error(`Invalid indices: ${p} does not index into ${i}`);for(let h=0;he>t?1:0),wX=En(Sl,PS,null,"bool"),kX={kernelName:Sl,backendName:"cpu",kernelFunc:wX},FS=dn((e,t)=>e>=t?1:0),SX=En(Po,FS,null,"bool"),IX={kernelName:Po,backendName:"cpu",kernelFunc:SX},OS=dn((e,t)=>ee<=t?1:0),NX=En(Tl,MS,null,"bool"),EX={kernelName:Tl,backendName:"cpu",kernelFunc:NX};function zS(e,t,n){let s=(t-e)/(n-1),r=v.makeZerosTypedArray(n,"float32");r[0]=e;for(let a=1;aMath.log(e)),RX=Qc(Mo,LS),_X={kernelName:Mo,backendName:"cpu",kernelFunc:RX};function BS(e,t,n,s){let r=v.getTypedArrayFromDType(s,v.sizeFromShape(n));for(let a=0;ai)&&(i=u)}r[a]=i}return r}var WS=dn((e,t)=>Math.max(e,t)),DX=En(Lo,WS),$X={kernelName:Lo,backendName:"cpu",kernelFunc:DX},VS=dn((e,t)=>Math.min(e,t)),PX=En(Uo,VS),FX={kernelName:Uo,backendName:"cpu",kernelFunc:PX},Nx=dn((e,t)=>e*t),OX=Ix((e,t,n,s)=>({real:e*n-t*s,imag:e*s+t*n})),i2=En(Ho,Nx,OX),MX={kernelName:Ho,backendName:"cpu",kernelFunc:i2};function US(e,t,n){let s=v.createScalarValue(-1,n);return Nx([],t,s,e,n)}function zX(e){let{inputs:t,backend:n}=e,{x:s}=t;Te(s,"neg");let r=n.data.get(s.dataId).values,[a,o]=US(r,s.shape,s.dtype);return n.makeTensorInfo(o,s.dtype,a)}var LX={kernelName:Rl,backendName:"cpu",kernelFunc:zX},GS=dn((e,t)=>e!==t?1:0),BX=En(_l,GS,null,"bool"),WX={kernelName:_l,backendName:"cpu",kernelFunc:BX};function Ex(e,t,n,s,r){let a=t.length,o=v.sizeFromShape(t),i=v.computeStrides(t),l=v.computeStrides(r),u=v.getTypedArrayFromDType(n,v.sizeFromShape(r));for(let c=0;cn.disposeIntermediateTensorInfo(x)),n.makeTensorInfo(y,g,f)}var GX={kernelName:Ko,backendName:"cpu",kernelFunc:UX};function HX(e,t,n){e.forEach((s,r)=>{if(s<0||s>=n){let a=v.indexToLoc(r,t.length,v.computeStrides(t)).join(",");throw new Error(`indices[${a}] = ${s} is not in [0, ${n})`)}})}function jX(e,t){for(let n=0;nr)throw new Error("Ragged splits must not point past values");for(let a=1;as[a])throw new Error("Ragged splits must be sorted in ascending order")}}function qX(e,t,n,s){let r=[],a=0,o=t.length-1+n.length,i=new Array(o).fill(null).map(()=>[0]);jX(n,s);let l=1;for(let u=0;u=0){let m=i[f],g=m[m.length-1]-h[c];for(let y=c;yr[o]=a)}return t}function u7(e,t){let n=e.slice(0,t);for(;n.lengthn&&(n=r)}return n}static getMaxWidthValueRowID(e){let t=e.length;if(t===0)return 0;let n=0,s=e[0],r=0;for(let a=1;a"Final length of result must be equal to firstDimension."),r}calculateOutputIndexRowSplit(e,t,n,s){let r=e.length,a=[];for(let o=0;o0&&a.length!==e[r-1])throw new Error("Invalid row split size.");return a}calculateOutputIndexValueRowID(e,t,n,s){let r=e.length,a=[];if(r===0)return[];let o=0,i=e[0];if(i>=t.length)throw new Error(`Got currentValueRowId=${i}, which is not less than ${t.length}`);let l=t[i];a.push(l);for(let u=1;u=0&&(++o,o=t.length)throw new Error(`Got nextValueRowId=${c} which is not less than ${t.length}`);l=t[c]}a.push(l)}if(a.length!==e.length)throw new Error("Invalid row ids.");return a}calculateOutputIndex(e,t,n,s){let r=this.getRowPartitionTensor(e),a=this.getRowPartitionTypeByDimension(e);switch(a){case dr.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(r,t,n,s);case dr.ROW_SPLITS:if(r.length-1>t.length)throw new Error(`Row partition size is greater than output size: ${r.length-1} > ${t.length}`);return this.calculateOutputIndexRowSplit(r,t,n,s);default:throw new Error(`Unsupported partition type: ${dr[a]}`)}}getFirstDimensionSize(){let e=this.rowPartitionValues[0];if(this.rowPartitionTypes.length===0)throw new Error("No row_partition_types given.");let t=this.rowPartitionTypes[0];switch(t){case dr.FIRST_DIM_SIZE:return e[0];case dr.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case dr.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${dr[t]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");let t=this.getFirstDimensionSize(),n=this.calculateOutputSize(t),s=new Array(this.raggedRank+1);s[s.length-1]=1;for(let i=s.length-2;i>=0;--i)s[i]=s[i+1]*n[i+1];let r=d7(n,!1),a=v.getArrayFromDType(this.valuesDType,v.sizeFromShape(r));if(s[0]*n[0]>0){let i=this.calculateFirstParentOutputIndex(t,s[0],n[0]);for(let l=1;l<=this.raggedRank;++l)i=this.calculateOutputIndex(l-1,i,s[l],n[l]);this.setOutput(this.raggedRank,i,a,r)}return[r,a]}setOutput(e,t,n,s){if(n.length===0)return;let r=this.values,a=n,o=s.slice();o=o.slice(e+1);let i=v.sizeFromShape(o),l=t.length,u=this.defaultValue;if(u.length!==i&&u.length!==1){let h=this.defaultValueShape;X(()=>{let f=W(u,h);u=Xi(f,o).dataSync()})}let c=0,p=0,d=0;for(let h=0;h<=l;++h){let f=h=l){let m=n.length;f=Math.floor(m/i)}if(f>d)if(this.defaultValue.length===1)a.subarray(d*i,f*i).fill(this.defaultValue[0]),d=f;else for(;f>d;){let m=a.slice(d*i);c7(m,u,i),++d}f<0?(c=h+1,p=d):(c=h,p=d,d=p+1)}}};function c7(e,t,n){for(let s=0;s= 0`);if(s<-1)throw new Error(`Dimension ${s} must be >= -1`);s=-1}n.push(s)}return n}function qS(e,t,n,s,r,a,o,i,l,u){return new Z3(e,t,n,s,r,a,o,i,l,u).compute()}function Rx(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)),YX=Qc(ei,XS),JX={kernelName:ei,backendName:"cpu",kernelFunc:YX};function Hu(e,t,n,s,r,a,o,i,l,u){let c=[s/r,r],p=e.values,d=t.values;if(s===0)return ze(n,t.dtype);let h=ze(c,t.dtype);typeof l=="string"||typeof l=="number"?h.values.fill(l):typeof l=="boolean"&&h.values.fill(+l);for(let f=0;f=s/r)throw new Error(`Invalid indices: ${m} does not index into ${n}`);for(let y=0;y1/(1+Math.exp(-e))),KS=xt(ni,e=>1/(1+Math.exp(-e))),eK={kernelName:ni,backendName:"cpu",kernelFunc:KS};function bm(e,t,n,s,r){let a=Gt.isSliceContinous(s,t,n),o=v.sizeFromShape(n),i=v.computeStrides(s);if(a){let p=Gt.computeFlatOffset(t,i);return r==="string"?e.slice(p,p+o):e.subarray(p,p+o)}let l=r==="string"?T.fromUint8ToStringArray(e):e,u=ze(s,r,l),c=ze(n,r);for(let p=0;pf+t[m]);c.set(u.get(...h),...d)}return r==="string"?T.fromStringArrayToUint8(c.values):c.values}function ol(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:o}=s;Te(r,"slice");let[i,l]=Gt.parseSliceParams(r,a,o);Gt.assertParamsValid(r,i,l);let u=n.data.get(r.dataId).values,c=bm(u,i,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,c)}var tK={kernelName:Ul,backendName:"cpu",kernelFunc:ol};function ZS(e,t,n,s,r,a,o){let i=t[0],l=a[0],u=new Array(l),c=new Array(i),p=t[1];if(l===0){if(i!==0)throw new Error(T.getSparseFillEmptyRowsIndicesDenseShapeMismatch(i));let g=v.getArrayFromDType(n,0),y=v.getArrayFromDType(r,0);return[g,[0,p],y,u,c]}let d=!0,h=0,f=new Array(l).fill(0);for(let g=0;g=l)throw new Error(T.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(g,y,l));++f[y],d=d&&y>=h,h=y}let m=!0;for(let g=0;g0&&(f[g]+=f[g-1])}if(m&&d){let g=e,y=s;for(let x=0;x0){h[d-1]=1;for(let g=d-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(p<0)throw new Error(T.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let d=t.slice();d[0]=p;let h=d.reduce((A,b)=>A*b,1),f=v.getArrayFromDType(n,h);if(i===0)return p>0&&f.fill(o),[f,d];if(p<=0)throw new Error(T.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let m=0,g=1,y=0,x=r[m];for(;;){let A=0;if(g=A)throw new Error(T.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage())}if(x<0||x>=p)throw new Error(T.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(x,p));x>y&&f.fill(o,y*u,x*u);for(let b=m;b=l[0])throw new Error(T.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(b,s[b],l[0]));for(let k=0;ki)break}return yMath.sqrt(e)),sK=xt(si,e=>Math.sqrt(e)),rK={kernelName:si,backendName:"cpu",kernelFunc:sK},JS=dn((e,t)=>{let n=e-t;return n*n}),aK=En(oi,JS),oK={kernelName:oi,backendName:"cpu",kernelFunc:aK};function QS(e,t,n,s){let r=ze(e,t.dtype);for(let a=0;a0?0:o-i),d=0;d+=l*this.leftPad.length;for(let y=0;yy.forEach(x=>f[m++]=x);for(let y=0;y0){g(e[p+c-1]);for(let y=0;y0){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(u=u&&t[l]<=n,!u)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],u=0;this.nGramWidths.forEach(c=>{u+=this.getNumNGrams(l,c)}),this.preserveShort&&l>0&&u===0&&(u=1),a[i]=a[i-1]+u}let o=new Array(a[r]);for(let i=0;i{let p=t[i+1]-t[i],d=this.getNumNGrams(p,c);this.createNGrams(e,l,o,u,d,c),u+=d}),this.preserveShort&&u===a[i]){let c=t[i+1]-t[i];if(c===0)continue;let p=c+2*this.padWidth,d=1;this.createNGrams(e,l,o,u,d,p)}}return[o,a]}};function Dx(e,t,n,s,r,a,o,i){return new iK(n,s,r,a,o,i).compute(e,t)}function lK(e,t,n,s){if(!e.length)return;if(t.length===0){for(let a=0;ae-t),uK=Ix((e,t,n,s)=>({real:e-n,imag:t-s})),Fx=En(ii,eI,uK),cK={kernelName:ii,backendName:"cpu",kernelFunc:Fx};function tI(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 nI(e,t,n=0,s=e.length-1){for(;s>n;){if(s-n>600){let i=s-n+1,l=t-n+1,u=Math.log(i),c=.5*Math.exp(2*u/3),p=.5*Math.sqrt(u*c*(i-c)/i)*Math.sign(l-i/2),d=Math.max(n,Math.floor(t-l*c/i+p)),h=Math.min(s,Math.floor(t+(i-l)*c/i+p));nI(e,t,d,h)}let r=e[t],a=n,o=s;for(v.swap(e,n,t),Kd(e[s],r)>0&&v.swap(e,n,s);a0;)o=o-1}Kd(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 sI(e,t,n,s,r){let a=t[t.length-1],[o,i]=[e.length/a,a],l=v.getTypedArrayFromDType(n,o*s),u=v.getTypedArrayFromDType("int32",o*s);for(let p=0;pf[A]={value:x,index:A}),s{for(let g=0;gnew kx,1);var aI=xt(Eo,e=>e>=0?e:Math.exp(e)-1),dK={kernelName:Eo,backendName:"cpu",kernelFunc:aI};function oI(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{alpha:a}=s;Te([r],"leakyRelu");let o=v.sizeFromShape(r.shape),i=n.data.get(r.dataId).values,l=v.getTypedArrayFromDType("float32",o);for(let u=0;ue<0?t*e:e);function iI(e){let{inputs:t,backend:n}=e,{x:s,alpha:r}=t;Te([s,r],"prelu");let a=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,[i,l]=hK(s.shape,r.shape,a,o,"float32");return n.makeTensorInfo(l,"float32",i)}var fK={kernelName:Xo,backendName:"cpu",kernelFunc:iI},lI=xt(Zo,e=>Math.max(0,e)),mK={kernelName:Zo,backendName:"cpu",kernelFunc:lI},uI=xt(Qo,e=>Math.min(Math.max(0,e),6)),gK={kernelName:Qo,backendName:"cpu",kernelFunc:uI};function vm(e,t,n,s,r){if(n==="linear")return sa({inputs:{x:t},backend:e});if(n==="relu")return lI({inputs:{x:t},backend:e});if(n==="elu")return aI({inputs:{x:t},backend:e});if(n==="relu6")return uI({inputs:{x:t},backend:e});if(n==="prelu")return iI({inputs:{x:t,alpha:s},backend:e});if(n==="leakyrelu")return oI({inputs:{x:t},backend:e,attrs:{alpha:r}});if(n==="sigmoid")return KS({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function Ct(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 u=n.data.get(r.dataId);if(u.complexTensorInfos!=null){let c=u.complexTensorInfos.real,p=u.complexTensorInfos.imag;c.shape=i,p.shape=i}return{dataId:r.dataId,shape:i,dtype:r.dtype}}var yK={kernelName:zl,backendName:"cpu",kernelFunc:Ct};function cI(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:o,transposeB:i}=s;Te([r,a],"matMul");let l=r.shape.length,u=a.shape.length,c=o?r.shape[l-2]:r.shape[l-1],p=i?a.shape[u-1]:a.shape[u-2],d=o?r.shape[l-1]:r.shape[l-2],h=i?a.shape[u-2]:a.shape[u-1],f=r.shape.slice(0,-2),m=a.shape.slice(0,-2),g=v.sizeFromShape(f),y=v.sizeFromShape(m),A=tu.assertAndGetBroadcastShape(r.shape.slice(0,-2),a.shape.slice(0,-2)).concat([d,h]);v.assert(c===p,()=>`Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${r.shape} and ${a.shape} and transposeA=${o} and transposeB=${i} must match.`);let b=o?[g,c,d]:[g,d,c],w=i?[y,h,p]:[y,p,h],k=Ct({inputs:{x:r},backend:n,attrs:{shape:b}}),C=Ct({inputs:{x:a},backend:n,attrs:{shape:w}}),N=o?k.shape[1]:k.shape[2],R=o?k.shape[2]:k.shape[1],D=i?C.shape[1]:C.shape[2],E=Math.max(g,y),$=n.data.get(k.dataId).values,S=n.data.get(C.dataId).values,F=v.computeStrides(k.shape),z=v.computeStrides(C.shape),[V,j,G]=o?[F[0],1,F[1]]:[F[0],F[1],1],[q,K,ne]=i?[1,z[1],z[0]]:[z[1],1,z[0]],ae=R*D,re=ze([E,R,D],k.dtype),ue=re.values,oe=n.blockSize;for(let Ae=0;AeMath.acos(e)),wK={kernelName:gc,backendName:"cpu",kernelFunc:vK},kK=xt(yc,e=>Math.acosh(e)),SK={kernelName:yc,backendName:"cpu",kernelFunc:kK};function IK(e){let{inputs:t,backend:n}=e,s=t;Te(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,A=b)}h[g]=A}return u.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(c,"int32",h)}var DK={kernelName:yo,backendName:"cpu",kernelFunc:_K};function $K(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;Te(r,"argMin");let o=v.parseAxisParam(a,r.shape),i=T.getAxesPermutation(o,r.shape.length),l=r,u=[];i!=null&&(l=ws({inputs:{x:r},backend:n,attrs:{perm:i}}),u.push(l),o=T.getInnerMostAxes(o.length,l.shape.length)),o=[o[0]],T.assertAxesAreInnerMostDims("argMin",o,l.shape.length);let[c,p]=T.computeOutAndReduceShapes(l.shape,o),d=v.sizeFromShape(c),h=v.makeZerosTypedArray(d,"int32"),f=v.sizeFromShape(p),m=n.data.get(l.dataId).values;for(let g=0;gn.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(c,"int32",h)}var PK={kernelName:bc,backendName:"cpu",kernelFunc:$K},FK=xt(vc,e=>Math.asin(e)),OK={kernelName:vc,backendName:"cpu",kernelFunc:FK},MK=xt(wc,e=>Math.asinh(e)),zK={kernelName:wc,backendName:"cpu",kernelFunc:MK},LK=xt(kc,e=>Math.atan(e)),BK={kernelName:kc,backendName:"cpu",kernelFunc:LK},WK=dn((e,t)=>Math.atan2(e,t)),VK=En(pl,WK),UK={kernelName:pl,backendName:"cpu",kernelFunc:VK},GK=xt(Sc,e=>Math.atanh(e)),HK={kernelName:Sc,backendName:"cpu",kernelFunc:GK};function Ox(e,t,n,s,r,a){let o=r.strideHeight,i=r.strideWidth,l=r.dilationHeight,u=r.dilationWidth,c=r.effectiveFilterHeight,p=r.effectiveFilterWidth,d=r.padInfo.top,h=r.padInfo.left,f=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=ze(r.outShape,n),g=m.values,y=r.outShape[1]*r.outShape[2]*r.outShape[3],x=r.outShape[2]*r.outShape[3],A=r.outShape[3];for(let b=0;bj?j=oe:a==="avg"&&(G+=oe,q++)}if(isNaN(j))break}let K=$+S*A+C;g[K]=a==="avg"?G/q:j}}}return m}function dI(e,t,n,s,r=!1,a=!1){let o=ze(s.outShape,"int32"),i=s.strideHeight,l=s.strideWidth,u=s.dilationHeight,c=s.dilationWidth,p=s.effectiveFilterHeight,d=s.effectiveFilterWidth,h=s.padInfo.top,f=s.padInfo.left,m=ze(t,n,e);for(let g=0;gD&&(D=V,r?E=a?((g*s.inHeight+$)*s.inWidth+F)*s.inChannels+y:($*s.inWidth+F)*s.inChannels+y:E=S*d+z)}}o.set(E,g,x,k,y)}}return o}function pI(e,t,n,s,r,a){let o=r.strideDepth,i=r.strideHeight,l=r.strideWidth,u=r.dilationDepth,c=r.dilationHeight,p=r.dilationWidth,d=r.effectiveFilterDepth,h=r.effectiveFilterHeight,f=r.effectiveFilterWidth,m=r.padInfo.front,g=r.padInfo.top,y=r.padInfo.left,x=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,A=ze(r.outShape,n),b=A.values,w=r.outShape[1]*r.outShape[2]*r.outShape[3]*r.outShape[4],k=r.outShape[2]*r.outShape[3]*r.outShape[4],C=r.outShape[3]*r.outShape[4],N=r.outShape[4];for(let R=0;RIe?Ie=kt:a==="avg"&&(Se+=kt,Fe++),isNaN(Ie))break}if(isNaN(Ie))break}if(isNaN(Ie))break}let $e=Q+$;b[$e]=a==="avg"?Se/Fe:Ie}}}}return A}function jK(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,u=t.effectiveFilterDepth,c=t.effectiveFilterHeight,p=t.effectiveFilterWidth,d=t.padInfo.front,h=t.padInfo.top,f=t.padInfo.left;for(let m=0;m=S&&(S=ne,F=V*c*p+G*c+K)}}}n.set(F,m,y,w,R,g)}}}return n}function qK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t;Te(r,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,u=1;v.assert(T.eitherStridesOrDilationsAreOne(o,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);let c=T.computePool2DInfo(r.shape,a,o,u,i,l),p;if(c.filterWidth===1&&c.filterHeight===1&&v.arraysEqual(c.inShape,c.outShape))p=sa({inputs:{x:r},backend:n});else{let d=n.data.get(r.dataId).values,h=v.computeStrides(r.shape),f=Ox(d,r.shape,r.dtype,h,c,"avg");p=n.makeTensorInfo(c.outShape,r.dtype,f.values)}return p}var XK={kernelName:Ao,backendName:"cpu",kernelFunc:qK};function KK(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l,dataFormat:u}=s;Te(r,"avgPool3d");let c=T.computePool3DInfo(r.shape,a,o,1,i,l,u),p=n.data.get(r.dataId).values,d=pI(p,r.shape,r.dtype,v.computeStrides(r.shape),c,"avg");return n.makeTensorInfo(d.shape,"float32",d.values)}var ZK={kernelName:Np,backendName:"cpu",kernelFunc:KK};function YK(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,{filterSize:o,strides:i,pad:l,dimRoundingMode:u}=s;Te([r,a],"avgPool3DGrad");let c=T.computePool3DInfo(a.shape,o,i,1,l,u),p=c.strideDepth,d=c.strideHeight,h=c.strideWidth,f=c.filterDepth,m=c.filterHeight,g=c.filterWidth,y=c.dilationDepth,x=c.dilationHeight,A=c.dilationWidth,b=c.effectiveFilterDepth,w=c.effectiveFilterHeight,k=c.effectiveFilterWidth,C=b-1-c.padInfo.front,N=k-1-c.padInfo.left,R=w-1-c.padInfo.top,D=ze(a.shape,"float32"),E=1/(f*m*g),$=n.bufferSync(r);for(let S=0;S=c.outDepth||Math.floor(re)!==re))for(let ue=0;ue=c.outHeight||Math.floor(oe)!==oe))for(let Ae=0;Ae=c.outWidth||Math.floor(Q)!==Q)continue;ne+=$.get(S,re,oe,Q,F)}}}D.set(ne*E,S,z,V,j,F)}return n.makeTensorInfo(D.shape,D.dtype,D.values)}var JK={kernelName:$m,backendName:"cpu",kernelFunc:YK};function QK(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,o=a;Te([r,a],"avgPoolGrad");let{filterSize:i,strides:l,pad:u}=s,c=T.computePool2DInfo(o.shape,i,l,1,u),p=c.strideHeight,d=c.strideWidth,h=c.filterHeight,f=c.filterWidth,m=c.dilationHeight,g=c.dilationWidth,y=c.effectiveFilterHeight,x=c.effectiveFilterWidth,A=x-1-c.padInfo.left,b=y-1-c.padInfo.top,w=ze(o.shape,"float32"),k=1/(h*f),C=n.data.get(r.dataId).values,N=ze(r.shape,"float32",C);for(let R=0;R=c.outHeight||Math.floor(j)!==j))for(let G=0;G=c.outWidth||Math.floor(q)!==q)continue;z+=N.get(R,j,q,D)}}w.set(z*k,R,E,$,D)}return n.makeTensorInfo(w.shape,w.dtype,w.values)}var eZ={kernelName:Dm,backendName:"cpu",kernelFunc:QK};function tZ(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."),Te([r,i,l,a,o],"batchNorm");let{varianceEpsilon:u}=s;u==null&&(u=.001);let c=n.data.get(r.dataId).values,p=n.data.get(i.dataId).values,d=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(c.length),g=f.length,y=h.length,x=d.length,A=p.length,b=0,w=0,k=0,C=0;for(let N=0;N=g&&(b=0),w>=A&&(w=0),k>=y&&(k=0),C>=x&&(C=0);return n.makeTensorInfo(r.shape,r.dtype,m)}var nZ={kernelName:$o,backendName:"cpu",kernelFunc:tZ};function sZ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:o}=s;Te([r],"batchToSpaceND");let i=a.reduce((y,x)=>y*x),l=T.getReshaped(r.shape,a,i),u=T.getPermuted(l.length,a.length),c=T.getReshapedPermuted(r.shape,a,i),p=T.getSliceBeginCoords(o,a.length),d=T.getSliceSize(c,o,a.length),h=Ct({inputs:{x:r},backend:n,attrs:{shape:l}}),f=ws({inputs:{x:h},backend:n,attrs:{perm:u}}),m=Ct({inputs:{x:f},backend:n,attrs:{shape:c}}),g=ol({inputs:{x:m},backend:n,attrs:{begin:p,size:d}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}var rZ={kernelName:hl,backendName:"cpu",kernelFunc:sZ};function aZ(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,u=Cx(i,l,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,u)}var oZ={kernelName:Pm,backendName:"cpu",kernelFunc:aZ};function iZ(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=T.assertAndGetBroadcastShape(Array.from(a),Array.from(o));return n.makeTensorInfo([i.length],"int32",Int32Array.from(i))}var lZ={kernelName:Fm,backendName:"cpu",kernelFunc:iZ},uZ=xt(Na,(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 u=0;um.shape);T.assertParamsConsistent(o,a);let i=T.computeOutShape(t.map(m=>m.shape),a);if(v.sizeFromShape(i)===0)return n.makeTensorInfo(i,t[0].dtype,[]);let l=t.filter(m=>v.sizeFromShape(m.shape)>0);if(l.length===1)return sa({inputs:{x:l[0]},backend:n});if(l[0].dtype==="complex64"){let m=l.map(b=>al({inputs:{input:b},backend:n})),g=l.map(b=>dc({inputs:{input:b},backend:n})),y=pc({inputs:m,backend:n,attrs:{axis:a}}),x=pc({inputs:g,backend:n,attrs:{axis:a}}),A=_s({inputs:{real:y,imag:x},backend:n});return m.forEach(b=>n.disposeIntermediateTensorInfo(b)),g.forEach(b=>n.disposeIntermediateTensorInfo(b)),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(x),A}let u=l.map(m=>{let g=v.sizeFromShape(m.shape.slice(a));return Ct({inputs:{x:m},backend:n,attrs:{shape:[-1,g]}})}),c=u.map(m=>({vals:n.data.get(m.dataId).values,shape:m.shape}));i=T.computeOutShape(u.map(m=>m.shape),1);let p=u[0].shape[0]===1,d=Tx(c,i,t[0].dtype,p),h=T.computeOutShape(l.map(m=>m.shape),a),f=n.makeTensorInfo(h,t[0].dtype,d);return u.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}var fZ={kernelName:fl,backendName:"cpu",kernelFunc:pc};function hI(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dataFormat:l,dilations:u,dimRoundingMode:c}=s;Te([r,a],"conv2d");let p=T.convertConv2DDataFormat(l),d=T.computeConv2DInfo(r.shape,a.shape,o,u,i,c,!1,p),h=d.filterHeight,f=d.filterWidth,m=d.dilationHeight,g=d.dilationWidth,y=d.padInfo.left,x=d.padInfo.top,A=d.dataFormat==="channelsLast",b=new gn(d.outShape,r.dtype),w=v.computeStrides(r.shape),k=v.computeStrides(a.shape),C=w[0],N=A?w[1]:w[2],R=A?w[2]:1,D=A?1:w[1],E=b.strides[0],$=A?b.strides[1]:b.strides[2],S=A?b.strides[2]:1,F=A?1:b.strides[1],z=n.data.get(r.dataId).values,V=n.data.get(a.dataId).values,j=b.values;for(let G=0;G=d.inHeight)continue;let Ae=ue*k[0],Q=q+oe*N;for(let Ie=0;Ie=d.inWidth)continue;let mt=Ae+$e*k[1],gt=Q+rt*R,yt=mt;for(let ht=0;ht=u.inDepth)continue;let G=V*R[0],q=E+j*N[1];for(let K=0;K=u.inHeight)continue;let oe=G+re*R[1],Ae=q+ue*N[2];for(let Q=0;Q=u.inWidth)continue;let rt=oe+Fe*R[2],mt=Ae+$e*u.inChannels,gt=rt;for(let yt=0;ytMath.cos(e)),TZ={kernelName:So,backendName:"cpu",kernelFunc:CZ},NZ=xt(Io,e=>Math.cosh(e)),EZ={kernelName:Io,backendName:"cpu",kernelFunc:NZ};function RZ(e){let{inputs:t,backend:n,attrs:s}=e,{image:r,boxes:a,boxInd:o}=t,{cropSize:i,method:l,extrapolationValue:u}=s,[c,p,d,h]=r.shape,f=a.shape[0],[m,g]=i,y=ze([f,m,g,h],"float32"),x=n.data.get(a.dataId).values,A=n.data.get(o.dataId).values,b=n.data.get(r.dataId).values,w=v.computeStrides(r.shape),k=v.computeStrides(y.shape);for(let C=0;C=c)continue;let F=m>1?(E-R)*(p-1)/(m-1):0,z=g>1?($-D)*(d-1)/(g-1):0;for(let V=0;V1?R*(p-1)+V*F:.5*(R+E)*(p-1);if(j<0||j>p-1){for(let G=0;G1?D*(d-1)+ne*z:.5*(D+$)*(d-1);if(ae<0||ae>d-1){for(let Ae=0;Ae1?D*(d-1)+G*z:.5*(D+$)*(d-1);if(q<0||q>d-1){for(let ae=0;aey+f-x-1:(y,x)=>y+x;for(let y=0;yy+f-x-1:(y,x)=>y+x;for(let y=0;y`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${o}`);let i=r.shape[0],l=r.shape[1],u=r.shape[2],c=r.shape[3],p=l*a,d=u*a,h=c/(a*a),f=n.data.get(r.dataId).values,m=new Float32Array(i*p*d*h),g=0;for(let y=0;y`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${d}'`);let h=T.computeConv2DInfo(r.shape,a.shape,o,d,i,u,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:y,padInfo:x}=h,A=x.left,b=x.top,w=h.outChannels/h.inChannels,k=new gn(h.outShape,r.dtype),C=n.data.get(r.dataId).values,N=n.data.get(a.dataId).values,R=k.values;for(let D=0;D=h.inHeight)continue;let G=V*p[0],q=E+j*c[1];for(let K=0;K=h.inWidth)continue;let oe=G+re*p[1],Ae=q+ue*h.inChannels,Q=ne,Ie=oe;for(let Se=0;Se{let{x:s,filter:r}=e,{strides:a,pad:o,dilations:i}=n,l=t,u=l.data.get(s.dataId).values,c=s.shape.length,p=l.data.get(r.dataId).values,d=r.shape.length,{batchSize:h,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:x,padInfo:A,strideHeight:b,strideWidth:w,filterHeight:k,filterWidth:C,dilationHeight:N,dilationWidth:R,outShape:D}=T.computeDilation2DInfo(s.shape,r.shape,a,o,"NHWC",i),E=v.sizeFromShape(D),$=D.length,S=v.getArrayFromDType(s.dtype,E);for(let z=0;z=0&&ue=0&&Aene&&(ne=Se)}}}let ae=v.locToIndex([z,V,G,K],$,v.computeStrides(D));S[ae]=ne}}}return{dataId:l.write(v.toTypedArray(S,s.dtype),D,s.dtype),shape:D,dtype:s.dtype}}},XZ={kernelName:nm,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:s,filter:r,dy:a}=e,{strides:o,pad:i,dilations:l}=n,u=t,c=v.toNestedArray(s.shape,u.data.get(s.dataId).values),p=v.toNestedArray(r.shape,u.data.get(r.dataId).values),{batchSize:d,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:x,strideHeight:A,strideWidth:b,filterHeight:w,filterWidth:k,dilationHeight:C,dilationWidth:N,outShape:R}=T.computeDilation2DInfo(s.shape,r.shape,o,i,"NHWC",l);v.assert(a.rank===R.length,()=>`Error in ${nm}, dy must have the same rank as output ${R.length}, but got ${a.rank}`);let D=v.toNestedArray(R,u.data.get(a.dataId).values),E=v.makeZerosNestedTypedArray(r.shape,r.dtype);for(let S=0;S=0&&re=0&&oeq&&(q=Ae,K=ae,ne=ue)}}}E[K][ne][G]+=D[S][F][V][G]}}}return{dataId:u.write(v.toTypedArray(E,s.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},KZ={kernelName:tm,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:s,filter:r,dy:a}=e,{strides:o,pad:i,dilations:l}=n,u=t,c=v.toNestedArray(s.shape,u.data.get(s.dataId).values),p=v.toNestedArray(r.shape,u.data.get(r.dataId).values),{batchSize:d,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:x,strideHeight:A,strideWidth:b,filterHeight:w,filterWidth:k,dilationHeight:C,dilationWidth:N,outShape:R}=T.computeDilation2DInfo(s.shape,r.shape,o,i,"NHWC",l);v.assert(a.rank===R.length,()=>`Error in ${tm}, dy must have the same rank as output ${R.length}, but got ${a.rank}`);let D=v.toNestedArray(R,u.data.get(a.dataId).values),E=v.makeZerosNestedTypedArray(s.shape,s.dtype);for(let S=0;S=0&&re=0&&oeq&&(q=Ae,K=re,ne=oe)}}}E[S][K][ne][G]+=D[S][F][V][G]}}}return{dataId:u.write(v.toTypedArray(E,s.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}};function Th(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;Te(r,"sum");let i;r.dtype==="bool"?i=po({inputs:{x:r},backend:n,attrs:{dtype:"int32"}}):i=sa({inputs:{x:r},backend:n});let l=i.shape.length,u=v.parseAxisParam(a,i.shape),c=T.getAxesPermutation(u,l),p=u,d=i;c!=null&&(d=ws({inputs:{x:i},backend:n,attrs:{perm:c}}),p=T.getInnerMostAxes(p.length,l)),T.assertAxesAreInnerMostDims("sum",p,d.shape.length);let[h,f]=T.computeOutAndReduceShapes(d.shape,p),m=T.upcastType(d.dtype,"int32"),g=xm(n,h,m),y=v.sizeFromShape(f),x=n.data.get(g.dataId).values,A=n.data.get(d.dataId).values;for(let b=0;b=0&&(d=Th({inputs:{x:d},backend:n,attrs:{axis:u[m]-(o.length-h),keepDims:!1}}),f.push(d)),h--)}for(let m of f)m!==d&&n.disposeIntermediateTensorInfo(m);return d}var JZ={kernelName:$p,backendName:"cpu",kernelFunc:YZ};function QZ(e){let{inputs:t,backend:n}=e,{dy:s,y:r}=t;Te([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]*(u+1)}return n.makeTensorInfo(r.shape,"float32",a)}var eY={kernelName:Um,backendName:"cpu",kernelFunc:QZ},tY=T.ERF_P,nY=T.ERF_A1,sY=T.ERF_A2,rY=T.ERF_A3,aY=T.ERF_A4,oY=T.ERF_A5,iY=xt(Ic,e=>{let t=Math.sign(e),n=Math.abs(e),s=1/(1+tY*n);return t*(1-((((oY*s+aY)*s+rY)*s+sY)*s+nY)*s*Math.exp(-n*n))}),lY={kernelName:Ic,backendName:"cpu",kernelFunc:iY};function wm(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),Ct({inputs:{x:r},backend:n,attrs:{shape:i}})}var uY={kernelName:xl,backendName:"cpu",kernelFunc:wm},cY=dn((e,t)=>e/t),Mx=En(No,cY),Y3={kernelName:No,backendName:"cpu",kernelFunc:Mx};function mI(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,u=[r,a],c=v.sizeFromShape(u),p=v.getTypedArrayFromDType("float32",c),d=v.getTypedArrayFromDType("float32",c);for(let g=0;g{let{image:s}=e,r=n,a=v.getTypedArrayFromDType(s.dtype,v.sizeFromShape(s.shape)),[o,i,l,u]=s.shape,c=r.data.get(s.dataId).values;for(let d=0;d=0&&AMath.floor(e/t)),bY=En(Do,xY,null,"int32"),vY={kernelName:Do,backendName:"cpu",kernelFunc:bY};function wY(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=s,m=hI({inputs:{x:r,filter:a},backend:n,attrs:{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:d}});if(o){let g=m;if(c==="NCHW"&&o.shape.length===1&&o.shape[0]!==1){let y=Ct({inputs:{x:o},backend:n,attrs:{shape:[o.shape[0],1,1]}});m=cc({inputs:{a:m,b:y},backend:n}),n.disposeIntermediateTensorInfo(y)}else m=cc({inputs:{a:m,b:o},backend:n});n.disposeIntermediateTensorInfo(g)}if(h){let g=m;if(c==="NCHW"&&h==="prelu"&&i.shape.length===1&&i.shape[0]!==1){let y=Ct({inputs:{x:i},backend:n,attrs:{shape:[i.shape[0],1,1]}});m=vm(n,m,h,y,f),n.disposeIntermediateTensorInfo(y)}else m=vm(n,m,h,i,f);n.disposeIntermediateTensorInfo(g)}return m}var kY={kernelName:so,backendName:"cpu",kernelFunc:wY};function SY(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=s,m=fI({inputs:{x:r,filter:a},backend:n,attrs:{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:d}});if(o){let g=m;m=cc({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=m;m=vm(n,m,h,i,f),n.disposeIntermediateTensorInfo(g)}return m}var IY={kernelName:ro,backendName:"cpu",kernelFunc:SY};function CY(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,u,c,p]=T.prepareAndValidate(s,r);if(u===0)return n.makeTensorInfo(l,s.dtype,[]);let d=n.data.get(r.dataId).values,h=n.bufferSync(s),f=DS(d,h,s.dtype,u,i,c,p,s.shape,a);return n.makeTensorInfo(l,s.dtype,f.values)}var TY={kernelName:kl,backendName:"cpu",kernelFunc:CY};function NY(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,indices:a}=t,{axis:o,batchDims:i}=s;Te([r,a],"gatherV2");let l=v.parseAxisParam(o,r.shape)[0],u=n.data.get(a.dataId).values,c=r.shape[l];for(let b=0;b=0,()=>`GatherV2: the index value ${w} is not in [0, ${c-1}]`)}let p=i;i==null&&(p=0);let d=v.sizeFromShape(a.shape),h=T.segment_util.collectGatherOpShapeInfo(r,a,l,p),f=Ct({inputs:{x:r},backend:n,attrs:{shape:[h.batchSize,h.outerSize,h.dimSize,h.sliceSize]}}),m=Ct({inputs:{x:a},backend:n,attrs:{shape:[h.batchSize,d/h.batchSize]}}),g=[h.batchSize,h.outerSize,d/h.batchSize,h.sliceSize],y=n.bufferSync(m),x=n.bufferSync(f),A=$S(x,y,g);return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.makeTensorInfo(h.outputShape,A.dtype,A.values)}var EY={kernelName:wl,backendName:"cpu",kernelFunc:NY};function RY(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=Ct({inputs:{x:s},backend:n,attrs:{shape:[o,a]}}),l=mI(i,!0,n),u=Ct({inputs:{x:l},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),u}var _Y={kernelName:Hm,backendName:"cpu",kernelFunc:RY},DY=xt(Tc,e=>Number.isFinite(e)?1:0,"bool"),$Y={kernelName:Tc,backendName:"cpu",kernelFunc:DY},PY=xt(Nc,e=>Math.abs(e)===1/0?1:0,"bool"),FY={kernelName:Nc,backendName:"cpu",kernelFunc:PY},OY=xt(Il,e=>Number.isNaN(e)?1:0,"bool"),MY={kernelName:Il,backendName:"cpu",kernelFunc:OY};function zY(e){let{backend:t,attrs:n}=e,{start:s,stop:r,num:a}=n,o=zS(s,r,a);return t.makeTensorInfo([o.length],"float32",o)}var LY={kernelName:jm,backendName:"cpu",kernelFunc:zY},BY=xt(Ec,e=>Math.log1p(e)),WY={kernelName:Ec,backendName:"cpu",kernelFunc:BY},VY=dn((e,t)=>e&&t),UY=En(Nl,VY,null,"bool"),GY={kernelName:Nl,backendName:"cpu",kernelFunc:UY},HY=xt(El,e=>e?0:1,"bool"),jY={kernelName:El,backendName:"cpu",kernelFunc:HY},qY=dn((e,t)=>e||t),XY=En(Rc,qY,null,"bool"),KY={kernelName:Rc,backendName:"cpu",kernelFunc:XY};function ZY(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{depthRadius:a,bias:o,alpha:i,beta:l}=s;Te(r,"LRN");let u=r.shape[3],c=u-1,p=n.data.get(r.dataId).values,d=v.sizeFromShape(r.shape),h=new Float32Array(d);function f(m){let g=m%u,y=m-g+Math.max(0,g-a),x=m-g+Math.min(g+a,c),A=0;for(;y<=x;y++){let b=p[y];A+=b*b}return A}for(let m=0;m`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);let c=T.computePool2DInfo(r.shape,a,o,u,i,l),p;if(c.filterWidth===1&&c.filterHeight===1&&v.arraysEqual(c.inShape,c.outShape))p=sa({inputs:{x:r},backend:n});else{let d=n.data.get(r.dataId).values,h=v.computeStrides(r.shape),f=Ox(d,r.shape,r.dtype,h,c,"max");p=n.makeTensorInfo(c.outShape,r.dtype,f.values)}return p}var nJ={kernelName:Bo,backendName:"cpu",kernelFunc:tJ};function sJ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l,dataFormat:u}=s;Te(r,"maxPool3d");let c=T.computePool3DInfo(r.shape,a,o,1,i,l,u),p=n.data.get(r.dataId).values,d=pI(p,r.shape,r.dtype,v.computeStrides(r.shape),c,"max");return n.makeTensorInfo(d.shape,"float32",d.values)}var rJ={kernelName:Op,backendName:"cpu",kernelFunc:sJ};function aJ(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,{filterSize:o,strides:i,pad:l,dimRoundingMode:u}=s;Te([r,a],"maxPool3DGrad");let c=T.computePool3DInfo(a.shape,o,i,1,l,u),p=n.bufferSync(a),d=jK(p,c),h=c.strideDepth,f=c.strideHeight,m=c.strideWidth,g=c.dilationDepth,y=c.dilationHeight,x=c.dilationWidth,A=c.effectiveFilterDepth,b=c.effectiveFilterHeight,w=c.effectiveFilterWidth,k=A-1-c.padInfo.front,C=w-1-c.padInfo.left,N=b-1-c.padInfo.top,R=ze(a.shape,"float32"),D=n.bufferSync(r);for(let E=0;E=c.outDepth||Math.floor(ne)!==ne))for(let ae=0;ae=c.outHeight||Math.floor(re)!==re))for(let ue=0;ue=c.outWidth||Math.floor(oe)!==oe)continue;let Ae=A*b*w-1-d.get(E,ne,re,oe,$),Q=K*b*w+ae*w+ue,Ie=Ae===Q?1:0;if(Ie===0)continue;q+=D.get(E,ne,re,oe,$)*Ie}}}R.set(q,E,S,F,z,$)}return n.makeTensorInfo(R.shape,R.dtype,R.values)}var oJ={kernelName:Km,backendName:"cpu",kernelFunc:aJ};function iJ(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a,output:o}=t,i=a;Te([a,o],"maxPoolGrad");let{filterSize:l,strides:u,pad:c,dimRoundingMode:p}=s,d=T.computePool2DInfo(i.shape,l,u,1,c,p),h=n.data.get(i.dataId).values,f=ze(d.outShape,i.dtype,dI(h,i.shape,i.dtype,d).values),m=d.strideHeight,g=d.strideWidth,y=d.dilationHeight,x=d.dilationWidth,A=d.effectiveFilterHeight,b=d.effectiveFilterWidth,w=b-1-d.padInfo.left,k=A-1-d.padInfo.top,C=ze(i.shape,"float32"),N=n.data.get(r.dataId).values,R=ze(r.shape,"float32",N);for(let D=0;D=d.outHeight||Math.floor(G)!==G))for(let q=0;q=d.outWidth||Math.floor(K)!==K)continue;let ne=A*b-1-f.get(D,G,K,E),ae=j*b+q,re=ne===ae?1:0;if(re===0)continue;V+=R.get(D,G,K,E)*re}}C.set(V,D,$,S,E)}return n.makeTensorInfo(C.shape,C.dtype,C.values)}var lJ={kernelName:Xm,backendName:"cpu",kernelFunc:iJ};function uJ(e,t,n,s,r){let a=v.computeStrides(t),o=Ox(e,t,n,a,r,"max"),i=dI(e,t,n,r,!0,s);return[o.values,i.values]}var cJ={kernelName:Zm,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:s}=e,{filterSize:r,strides:a,pad:o,includeBatchInIndex:i}=t,l=n;Te(s,"MaxPoolWithArgmax");let u=l.data.get(s.dataId).values,c=T.computePool2DInfo(s.shape,r,a,[1,1],o),[p,d]=uJ(u,s.shape,s.dtype,i,c),h=l.write(p,c.outShape,s.dtype),f=l.write(d,c.outShape,s.dtype);return[{dataId:h,shape:c.outShape,dtype:s.dtype},{dataId:f,shape:c.outShape,dtype:"int32"}]}};function dJ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s,i=v.parseAxisParam(a,r.shape),u=T.computeOutAndReduceShapes(r.shape,i)[1],c=v.sizeFromShape(u),p=[],d=n.makeTensorInfo([],"float32",new Float32Array([c]));p.push(d);let h=po({inputs:{x:r},backend:n,attrs:{dtype:"float32"}});p.push(h);let f=Mx({inputs:{a:h,b:d},backend:n});p.push(f);let m=Th({inputs:{x:f},backend:n,attrs:{axis:a,keepDims:o}});return p.forEach(g=>n.disposeIntermediateTensorInfo(g)),m}var pJ={kernelName:Wo,backendName:"cpu",kernelFunc:dJ};function hJ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;Te(r,"min");let i=v.parseAxisParam(a,r.shape),l=i,u=T.getAxesPermutation(l,r.shape.length),c=r;u!=null&&(c=ws({inputs:{x:r},backend:n,attrs:{perm:u}}),l=T.getInnerMostAxes(l.length,r.shape.length)),T.assertAxesAreInnerMostDims("min",l,c.shape.length);let[p,d]=T.computeOutAndReduceShapes(c.shape,l),h=v.sizeFromShape(d),f=v.makeZerosTypedArray(v.sizeFromShape(p),c.dtype),m=n.data.get(c.dataId).values;for(let y=0;yA[0]+r.shape[b]+A[1]),l=a.map(A=>A[0]),u=a.map((A,b)=>A[0]+r.shape[b]),c=o==="reflect"?0:1,p=n.data.get(r.dataId).values,d=r.shape.length,h=v.computeStrides(r.shape),f=v.sizeFromShape(i),m=i.length,g=v.computeStrides(i),y=v.getTypedArrayFromDType(r.dtype,f);for(let A=0;A=u[k]&&(b[k]=(u[k]-1)*2-b[k]+c);b=b.map((k,C)=>k-l[C]);let w=v.locToIndex(b,d,h);y[A]=p[w]}return{dataId:n.write(y,i,r.dtype),shape:i,dtype:r.dtype}}var gJ={kernelName:Go,backendName:"cpu",kernelFunc:mJ},yJ=dn((e,t)=>{let n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}),AJ=En(_c,yJ),xJ={kernelName:_c,backendName:"cpu",kernelFunc:AJ},bJ=fo(Em());function yI(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),u=gI({inputs:{x:r},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),c=T.expandShapeToKeepDim(u.shape,l),p=Ct({inputs:{x:u},backend:n,attrs:{shape:c}}),d=Fx({inputs:{a:r,b:p},backend:n}),h=ES({inputs:{x:d},backend:n}),f=Th({inputs:{x:h},backend:n,attrs:{axis:l,keepDims:!1}}),m=Ct({inputs:{x:f},backend:n,attrs:{shape:c}}),g=Mx({inputs:{a:h,b:m},backend:n});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}var vJ={kernelName:ai,backendName:"cpu",kernelFunc:yI};function wJ(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{numSamples:a,seed:o,normalized:i}=s;Te(r,"multinomial");let l=i?r:yI({inputs:{logits:r},backend:n,attrs:{dim:-1}}),u=l.shape[0],c=l.shape[1],p=n.data.get(l.dataId).values,d=[u,a],h=v.makeZerosTypedArray(v.sizeFromShape(d),"int32");for(let f=0;f=0&&p[d]{v.assertShapesMatch(a,c.shape,"All tensors passed to stack must have matching shapes"),v.assert(o===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(c=>{let p=wm({inputs:{input:c},backend:n,attrs:{dim:r}});return i.push(p),p}),u=pc({inputs:l,backend:n,attrs:{axis:r}});return i.forEach(c=>n.disposeIntermediateTensorInfo(c)),u}var MJ={kernelName:Ol,backendName:"cpu",kernelFunc:xI};function zJ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,constantValue:o}=s;Te(r,"pad");let i=a.map((x,A)=>x[0]+r.shape[A]+x[1]),l=a.map(x=>x[0]),u=n.data.get(r.dataId).values,c=v.sizeFromShape(r.shape),p=r.shape.length,d=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[C]),w=v.locToIndex(b,f,m);g[w]=u[x]}return{dataId:n.write(g,i,r.dtype),shape:i,dtype:r.dtype}}var bI={kernelName:jo,backendName:"cpu",kernelFunc:zJ},LJ=dn((e,t)=>Math.pow(e,t)),BJ=En(qo,LJ),WJ={kernelName:qo,backendName:"cpu",kernelFunc:BJ};function VJ(e){let{inputs:t,backend:n,attrs:s}=e,{paramsNestedSplits:r,paramsDenseValues:a,indices:o}=t,{outputRaggedRank:i}=s,l=r.map(y=>n.data.get(y.dataId).values),u=r.map(y=>y.shape),c=n.data.get(a.dataId).values,p=n.data.get(o.dataId).values,[d,h,f]=jS(l,u,c,a.shape,a.dtype,p,o.shape,i),m=d.map(y=>n.makeTensorInfo([y.length],"int32",y)),g=n.makeTensorInfo(f,a.dtype,h);return m.concat([g])}var UJ={kernelName:Jm,backendName:"cpu",kernelFunc:VJ};function GJ(e){let{inputs:t,backend:n,attrs:s}=e,{shape:r,values:a,defaultValue:o,rowPartitionTensors:i}=t,{rowPartitionTypes:l}=s,u=n.data.get(r.dataId).values,c=n.data.get(a.dataId).values,p=n.data.get(o.dataId).values,d=i.map(g=>n.data.get(g.dataId).values),h=i.map(g=>g.shape),[f,m]=qS(u,r.shape,c,a.shape,a.dtype,p,o.shape,d,h,l);return n.makeTensorInfo(f,a.dtype,m)}var HJ={kernelName:Qm,backendName:"cpu",kernelFunc:GJ};function jJ(e){let{backend:t,attrs:n}=e,{start:s,stop:r,dtype:a,step:o}=n,i=Rx(s,r,o,a);return t.makeTensorInfo([i.length],a,i)}var qJ={kernelName:$c,backendName:"cpu",kernelFunc:jJ},XJ=xt(Ml,e=>1/e),KJ={kernelName:Ml,backendName:"cpu",kernelFunc:XJ};function ZJ(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:o,size:i}=s;Te(r,"resizeBilinear");let l=v.computeStrides(r.shape),[u,c]=i,[p,d,h,f]=r.shape,m=n.data.get(r.dataId).values,g=new Float32Array(v.sizeFromShape([p,u,c,f])),y=[a&&u>1?d-1:d,a&&c>1?h-1:h],x=[a&&u>1?u-1:u,a&&c>1?c-1:c],A=0,b=y[0]/x[0],w=y[1]/x[1];for(let k=0;k1?u-1:u,o&&h>1?c-1:c],g=[o&&d>1?d-1:d,o&&h>1?h-1:h],y=m[0]/g[0],x=m[1]/g[1],A=n.data.get(a.dataId).values,b=0;for(let w=0;w1?d-1:d,a&&c>1?h-1:h],x=[a&&u>1?u-1:u,a&&c>1?c-1:c],A=y[0]/x[0],b=y[1]/x[1],w=0;for(let k=0;k1?c-1:c,o&&f>1?p-1:p],x=[o&&h>1?h-1:h,o&&f>1?f-1:f],A=y[0]/x[0],b=y[1]/x[1],w=1/A,k=1/b,C=Math.ceil(w)*2+2,N=Math.ceil(k)*2+2;for(let R=0;R=h)continue;let re=D+ae*l[1],ue=ae*A,oe=Math.min(c-1,o?Math.round(ue):Math.floor(ue));if(E===oe)for(let Ae=0;Ae=f)continue;let Ie=re+Q*l[2],Se=Q*b,Fe=Math.min(p-1,o?Math.round(Se):Math.floor(Se));z===Fe&&(K+=g[Ie+q])}}m[V+q]=K}}}}return n.makeTensorInfo(r.shape,r.dtype,m)}var sQ={kernelName:e0,backendName:"cpu",kernelFunc:nQ};function rQ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s;Te(r,"reverse");let o=r.shape.length,i=v.parseAxisParam(a,r.shape);if(o===0)return sa({inputs:{x:r},backend:n});let l=new gn(r.shape,r.dtype),u=n.bufferSync(r);for(let c=0;cd[h]=r.shape[h]-1-d[h]),l.set(u.get(...d),...p)}return n.makeTensorInfo(l.shape,l.dtype,l.values)}var aQ={kernelName:Ll,backendName:"cpu",kernelFunc:rQ},oQ={kernelName:Ql,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)),[u,c,p,d]=s.shape,[h,f]=T.getImageCenter(o,c,p),m=255,g=Math.sin(r),y=Math.cos(r),x=i.data.get(s.dataId).values;for(let b=0;b=0&&F=0&&z{let t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2===0?t:t+1}),lQ={kernelName:Bl,backendName:"cpu",kernelFunc:iQ};function uQ(e){let{inputs:t,backend:n,attrs:s}=e,{indices:r,updates:a}=t,{shape:o}=s,{sliceRank:i,numUpdates:l,sliceSize:u,strides:c,outputSize:p}=T.calculateShapes(a,r,o),d=!0,h=n.bufferSync(r),f=n.bufferSync(a),m=Hu(h,f,o,p,u,l,i,c,0,d);return n.makeTensorInfo(o,m.dtype,m.values)}var cQ={kernelName:Wl,backendName:"cpu",kernelFunc:uQ};function dQ(e,t){let n=0,s=e.length,r=0;for(;n1||r.shape.length===1?1:v.sizeFromShape(r.shape.slice(1));for(let f=0;fe>=0?xQ*e:AQ*(Math.exp(e)-1)),vQ={kernelName:Pc,backendName:"cpu",kernelFunc:bQ},wQ=xt(Fc,e=>e<0?-1:e>0?1:0),kQ={kernelName:Fc,backendName:"cpu",kernelFunc:wQ},SQ=xt(ti,e=>Math.sin(e)),IQ={kernelName:ti,backendName:"cpu",kernelFunc:SQ},CQ=xt(Gl,e=>Math.sinh(e)),TQ={kernelName:Gl,backendName:"cpu",kernelFunc:CQ},NQ=11920928955078125e-23,p7=Math.log(NQ)+2,EQ=xt(Oc,e=>{let t=e>-p7,n=eNumber(g)))),n.makeTensorInfo([m.length],s.dtype,new Int32Array(m))]}var PQ={kernelName:zp,backendName:"cpu",kernelFunc:$Q};function FQ(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),[u,c,p]=YS(i,s.shape,s.dtype,o,l);return[n.makeTensorInfo(c,s.dtype,u),n.makeTensorInfo([p.length],a.dtype,new Int32Array(p))]}var OQ={kernelName:Mc,backendName:"cpu",kernelFunc:FQ};function MQ(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}`);if(r.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");let o=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values,l=n.data.get(a.dataId).values,[u,c]=_x(o,s.shape,s.dtype,i,l,!0);return n.makeTensorInfo(c,s.dtype,u)}var zQ={kernelName:Lp,backendName:"cpu",kernelFunc:MQ};function LQ(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}`);if(r.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");let o=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values,l=n.data.get(a.dataId).values,[u,c]=_x(o,s.shape,s.dtype,i,l);return n.makeTensorInfo(c,s.dtype,u)}var BQ={kernelName:Bp,backendName:"cpu",kernelFunc:LQ};function WQ(e){let{inputs:t,backend:n,attrs:s}=e,{sparseIndices:r,sparseValues:a,defaultValue:o}=t,{outputShape:i}=s,{sliceRank:l,numUpdates:u,sliceSize:c,strides:p,outputSize:d}=T.calculateShapes(a,r,i),h=!1,f=n.bufferSync(r),m;switch(a.dtype){case"bool":{let g=n.bufferSync(a),y=Boolean(n.data.get(o.dataId).values[0]);m=Hu(f,g,i,d,c,u,l,p,y,h);break}case"float32":{let g=n.bufferSync(a),y=n.data.get(o.dataId).values[0];m=Hu(f,g,i,d,c,u,l,p,y,h);break}case"int32":{let g=n.bufferSync(a),y=n.data.get(o.dataId).values[0];m=Hu(f,g,i,d,c,u,l,p,y,h);break}case"string":{let g=n.bufferSync(a),y=v.decodeString(n.data.get(o.dataId).values[0]);m=Hu(f,g,i,d,c,u,l,p,y,h);break}default:throw new Error(`Unsupported type ${a.dtype}`)}return n.makeTensorInfo(i,m.dtype,m.values)}var VQ={kernelName:Wp,backendName:"cpu",kernelFunc:WQ};function UQ(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=T.prepareSplitSize(r,a,i),u=new Array(r.shape.length).fill(0),c=r.shape.slice();return l.map(p=>{let d=[...c];d[i]=p;let h=ol({inputs:{x:r},backend:n,attrs:{begin:u,size:d}});return u[i]+=p,h})}var GQ={kernelName:jl,backendName:"cpu",kernelFunc:UQ},HQ={kernelName:zc,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,s=t;Te(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}),qQ={kernelName:ui,backendName:"cpu",kernelFunc:jQ};function XQ(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:d}=s;Te(r,"stridedSlice");let{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:x,end:A,strides:b}=Gt.sliceInfo(r.shape,a,o,i,l,u,c,p,d),w;if(m)w=Ct({inputs:{x:r},backend:n,attrs:{shape:f}});else if(g||y){v.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let k=Gt.computeOutShape(x,A,b),C=ol({inputs:{x:r},backend:n,attrs:{begin:x,size:k}});w=Ct({inputs:{x:C},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(C)}else{let k=n.bufferSync(r),C=QS(h,k,b,x);w=n.makeTensorInfo(f,C.dtype,C.values)}return w}var KQ={kernelName:ql,backendName:"cpu",kernelFunc:XQ};function ZQ(e){let{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:u}=s,{data:c,dataSplits:p}=t,d=n.data.get(c.dataId).values,h=n.data.get(p.dataId).values,[f,m]=Dx(d,h,r,a,o,i,l,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(p.shape,"int32",m)]}var YQ={kernelName:Lc,backendName:"cpu",kernelFunc:ZQ};function JQ(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],[u,c,p]=$x(i,l,r),d=c.length;return[n.makeTensorInfo([d,2],"int32",u),n.makeTensorInfo([d],"string",c),n.makeTensorInfo([2],"int32",new Int32Array(p))]}var QQ={kernelName:Vp,backendName:"cpu",kernelFunc:JQ};function eee(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=Px(o,r);return n.makeTensorInfo(a.shape,"int32",i)}var tee={kernelName:Up,backendName:"cpu",kernelFunc:eee},nee=xt(Xl,e=>Math.tan(e)),see={kernelName:Xl,backendName:"cpu",kernelFunc:nee},ree=xt(li,e=>Math.tanh(e)),aee={kernelName:li,backendName:"cpu",kernelFunc:ree};function oee(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reps:a}=s;Te(r,"tile");let o=tI(n.bufferSync(r),a);return n.makeTensorInfo(o.shape,o.dtype,o.values)}var iee={kernelName:Ea,backendName:"cpu",kernelFunc:oee};function lee(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{k:a,sorted:o}=s;Te(r,"topk");let i=n.data.get(r.dataId).values,[l,u]=sI(i,r.shape,r.dtype,a,o);return[n.makeTensorInfo(l.shape,l.dtype,l.values),n.makeTensorInfo(u.shape,u.dtype,u.values)]}var uee={kernelName:Kl,backendName:"cpu",kernelFunc:lee};function cee(e){let{inputs:t,attrs:n,backend:s}=e,{image:r,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:l,outputShape:u}=n,[c,p,d,h]=r.shape,[f,m]=u!=null?u:[p,d],g=[c,f,m,h],y=v.computeStrides(r.shape),x=y[0],A=y[1],b=y[2],w=v.computeStrides(g),k=w[0],C=w[1],N=w[2],R=v.getTypedArrayFromDType(r.dtype,v.sizeFromShape(g));R.fill(l);let D=s.data.get(r.dataId).values,E=s.data.get(a.dataId).values;for(let S=0;St-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 hee(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 fee(e,t){return e}function mee(e,t){return v.clamp(0,e,t-1)}function Zd(e,t,n,s,r,a,o,i,l,u,c){let p=o*s+i*r+l*a+u;return 0<=i&&in.disposeIntermediateTensorInfo(f)),h}var kee={kernelName:Gp,backendName:"cpu",kernelFunc:wee},See=[bK,iX,wK,SK,hX,CK,NK,RK,DK,PK,OK,zK,BK,UK,HK,XK,ZK,JK,eZ,AK,nZ,rZ,oZ,lZ,dX,mX,cZ,lX,pZ,fZ,mZ,yZ,xZ,vZ,kZ,IZ,TZ,EZ,_Z,$Z,FZ,MZ,LZ,BZ,VZ,GZ,jZ,qZ,XZ,KZ,JZ,dK,eY,gX,lY,yX,uY,xX,mY,gY,AY,vX,vY,kY,IY,TY,EY,kX,IX,uX,_Y,hZ,$Y,FY,MY,pK,TX,EX,LY,_X,WY,GY,jY,KY,YY,QY,eJ,$X,nJ,rJ,oJ,lJ,cJ,pJ,fJ,FX,gJ,xJ,kJ,MX,LX,CJ,EJ,DJ,WX,PJ,OJ,MJ,bI,WJ,fK,GX,UJ,HJ,qJ,cX,Y3,KJ,mK,gK,yK,YJ,QJ,tQ,sQ,aQ,oQ,lQ,JX,cQ,mQ,yQ,vQ,eK,kQ,IQ,TQ,tK,vJ,RQ,DQ,PQ,OQ,zQ,BQ,VQ,GQ,rK,HQ,oK,qQ,KQ,YQ,QQ,tee,cK,ZZ,see,aee,iee,uee,dee,VX,xee,vee,kee,FJ];for(let e of See)er(e);var vI={};We(vI,{assertNotComplex:()=>td,bindCanvasToFramebuffer:()=>Fee,bindColorTextureToFramebuffer:()=>jf,bindTextureToProgramUniformSampler:()=>OI,bindTextureUnit:()=>$I,bindVertexBufferToProgramAttribute:()=>Q3,callAndCheck:()=>we,canBeRepresented:()=>wI,createFragmentShader:()=>II,createFramebuffer:()=>DI,createProgram:()=>CI,createStaticIndexBuffer:()=>EI,createStaticVertexBuffer:()=>NI,createTexture:()=>RI,createVertexShader:()=>SI,getBatchDim:()=>il,getExtensionOrThrow:()=>Yd,getFramebufferErrorMessage:()=>MI,getMaxTexturesInShader:()=>WI,getNumChannels:()=>$ee,getProgramUniformLocation:()=>FI,getProgramUniformLocationOrThrow:()=>PI,getRowsCols:()=>ll,getShapeAs3D:()=>qf,getTextureShapeFromLogicalShape:()=>LI,getWebGLDisjointQueryTimerVersion:()=>VI,getWebGLErrorMessage:()=>kI,getWebGLMaxTextureSize:()=>BI,hasExtension:()=>Ys,isCapableOfRenderingToFloatTexture:()=>UI,isDownloadFloatTextureEnabled:()=>GI,isReshapeFree:()=>bp,isWebGLFenceEnabled:()=>HI,isWebGLVersionEnabled:()=>ty,linkProgram:()=>TI,logShaderSourceAndInfoLog:()=>Bx,resetMaxTextureSize:()=>Oee,resetMaxTexturesInShader:()=>Mee,unbindColorTextureFromFramebuffer:()=>ey,unbindTextureUnit:()=>Pee,validateFramebuffer:()=>Jd,validateProgram:()=>Hf,validateTextureSize:()=>_I});var Ui={},Of={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function l2(e,t){Ui[e]=t}function Mr(e,t){if(!(e in Ui)||t!=null){let s=Cee(e,t);if(s!==null)Ui[e]=s;else return console.log("Could not get context for WebGL version",e),null}let n=Ui[e];return n==null||n.isContextLost()?(delete Ui[e],Mr(e)):(n.disable(n.DEPTH_TEST),n.disable(n.STENCIL_TEST),n.disable(n.BLEND),n.disable(n.DITHER),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SAMPLE_COVERAGE),n.enable(n.SCISSOR_TEST),n.enable(n.CULL_FACE),n.cullFace(n.BACK),Ui[e])}function Iee(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 Cee(e,t){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let n=t==null?Iee(e):t;return n.addEventListener("webglcontextlost",s=>{s.preventDefault(),delete Ui[e]},!1),U().getBool("SOFTWARE_WEBGL_ENABLED")&&(Of.failIfMajorPerformanceCaveat=!1),e===1?n.getContext("webgl",Of)||n.getContext("experimental-webgl",Of):n.getContext("webgl2",Of)}var xp;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(xp||(xp={}));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 Fn;(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"})(Fn||(Fn={}));function Nh(e,t){return[t,e]}function Tee(e,t){return e*t}function Mf(e){let t=v.sizeFromShape(e),n=Math.ceil(t/4);return v.sizeToSquarishShape(n)}function ed(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function Nee(e,t){let[n,s]=ed(e,t);return n*s*4}function Lx(e,t){let n=e,s,r,a,o,i,l,u,c,p,d;return U().getNumber("WEBGL_VERSION")===2?(s=n.R32F,r=n.R16F,a=n.RGBA16F,o=n.RGBA32F,i=n.RED,u=4,c=1,p=n.HALF_FLOAT,d=n.FLOAT,l=n.RGBA8):(s=e.RGBA,r=e.RGBA,a=e.RGBA,o=n.RGBA,i=e.RGBA,u=4,c=4,p=t!=null?t.HALF_FLOAT_OES:null,d=e.FLOAT,l=e.RGBA),{internalFormatFloat:s,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:o,textureFormatFloat:i,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:c,textureTypeHalfFloat:p,textureTypeFloat:d}}function we(e,t){let n=t();return U().getBool("DEBUG")&&Eee(e),n}function Eee(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+kI(e,t))}var Ree=596e-10,_ee=65504;function wI(e){return!!(U().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||Reee.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function SI(e,t){let n=Da(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(we(e,()=>e.shaderSource(n,t)),we(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 II(e,t){let n=Da(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(we(e,()=>e.shaderSource(n,t)),we(e,()=>e.compileShader(n)),U().get("ENGINE_COMPILE_ONLY"))return n;if(e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw Bx(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}var Dee=/ERROR: [0-9]+:([0-9]+):/g;function Bx(e,t){let n=Dee.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((p,d)=>v.rightPad((d+1).toString(),a)+p),i=0;for(let p=0;pe.createProgram(),"Unable to create WebGLProgram.")}function TI(e,t){if(we(e,()=>e.linkProgram(t)),!U().get("ENGINE_COMPILE_ONLY")&&e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function Hf(e,t){if(we(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function NI(e,t){let n=Da(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return we(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),we(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function EI(e,t){let n=Da(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return we(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),we(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function $ee(){return U().getNumber("WEBGL_VERSION")===2?1:4}function RI(e){return Da(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function _I(e,t){let n=U().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 DI(e){return Da(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function Q3(e,t,n,s,r,a,o){let i=e.getAttribLocation(t,n);return i===-1?!1:(we(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s)),we(e,()=>e.vertexAttribPointer(i,r,e.FLOAT,!1,a,o)),we(e,()=>e.enableVertexAttribArray(i)),!0)}function $I(e,t,n){zI(e,n),we(e,()=>e.activeTexture(e.TEXTURE0+n)),we(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function Pee(e,t){zI(e,t),we(e,()=>e.activeTexture(e.TEXTURE0+t)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function PI(e,t,n){return Da(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function FI(e,t,n){return e.getUniformLocation(t,n)}function OI(e,t,n,s){we(e,()=>$I(e,t,s)),we(e,()=>e.uniform1i(n,s))}function Fee(e){we(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),we(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),we(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function jf(e,t,n){we(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),we(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function ey(e,t){we(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),we(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Jd(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+MI(e,t))}function MI(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 Da(e,t,n){let s=we(e,()=>t());if(s==null)throw new Error(n);return s}function zI(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 il(e,t=2){return v.sizeFromShape(e.slice(0,e.length-t))}function ll(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 qf(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[il(e),...ll(e)]),t}function LI(e,t=!1){let n=U().getNumber("WEBGL_MAX_TEXTURE_SIZE"),s=U().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");s===1/0&&U().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(s=n/2),t&&(n=n*2,s=s*2,e=e.map((i,l)=>l>=e.length-2?v.nearestLargerEven(e[l]):e[l]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=v.squeezeShape(e).newShape);let r=v.sizeFromShape(e),a=null;e.length<=1&&r<=n?a=[1,r]:e.length===2&&e[0]<=n&&e[1]<=n?a=e:e.length===3&&e[0]*e[1]<=n&&e[2]<=n?a=[e[0]*e[1],e[2]]:e.length===3&&e[0]<=n&&e[1]*e[2]<=n?a=[e[0],e[1]*e[2]]:e.length===4&&e[0]*e[1]*e[2]<=n&&e[3]<=n?a=[e[0]*e[1]*e[2],e[3]]:e.length===4&&e[0]<=n&&e[1]*e[2]*e[3]<=n&&(a=[e[0],e[1]*e[2]*e[3]]);let o=a!=null&&Math.max(...a)>s&&Math.min(...a)<=(t?2:1)&&Math.min(...a)>0;if(a==null||o)if(t){let i=il(e),l=2,u=2;e.length&&([l,u]=ll(e)),r=i*(l/2)*(u/2),a=v.sizeToSquarishShape(r).map(c=>c*2)}else a=v.sizeToSquarishShape(r);return a}function zf(e){return e%2===0}function bp(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||zf(n)&&zf(s)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&zf(e[0])&&zf(t[0])}var Xf,Kf;function BI(e){if(Xf==null){let t=Mr(e);Xf=t.getParameter(t.MAX_TEXTURE_SIZE)}return Xf}function Oee(){Xf=null}function Mee(){Kf=null}function WI(e){if(Kf==null){let t=Mr(e);Kf=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Kf)}function VI(e){if(e===0)return 0;let t,n=Mr(e);return Ys(n,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:Ys(n,"EXT_disjoint_timer_query")?t=1:t=0,t}function Ys(e,t){return e.getExtension(t)!=null}function ty(e){try{if(Mr(e)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function UI(e){if(e===0)return!1;let t=Mr(e);if(e===1){if(!Ys(t,"OES_texture_float"))return!1}else if(!Ys(t,"EXT_color_buffer_float"))return!1;return ny(t)}function GI(e){if(e===0)return!1;let t=Mr(e);if(e===1){if(!Ys(t,"OES_texture_float")||!Ys(t,"WEBGL_color_buffer_float"))return!1}else{if(Ys(t,"EXT_color_buffer_float"))return ny(t);let s="EXT_color_buffer_half_float";if(Ys(t,s)){let r=t.getExtension(s);return zee(t,r)}return!1}return ny(t)}function ny(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 zee(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 HI(e){return e!==2?!1:Mr(e).fenceSync!=null}function td(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 Ee=U();Ee.registerFlag("HAS_WEBGL",()=>Ee.getNumber("WEBGL_VERSION")>0);Ee.registerFlag("WEBGL_VERSION",()=>ty(2)?2:ty(1)?1:0);Ee.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);Ee.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Ee.get("WEBGL_VERSION")===2);Ee.registerFlag("WEBGL_CPU_FORWARD",()=>!0);Ee.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);Ee.registerFlag("WEBGL_PACK",()=>Ee.getBool("HAS_WEBGL"));Ee.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_PACK_CLIP",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_PACK_REDUCE",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_LAZILY_UNPACK",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_CONV_IM2COL",()=>Ee.getBool("WEBGL_PACK"));Ee.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>BI(Ee.getNumber("WEBGL_VERSION")));Ee.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>WI(Ee.getNumber("WEBGL_VERSION")));Ee.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let e=Ee.getNumber("WEBGL_VERSION");return e===0?0:VI(e)});Ee.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Ee.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!Xp.isMobile());Ee.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>UI(Ee.getNumber("WEBGL_VERSION")));Ee.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>Ee.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Ee.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));Ee.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>GI(Ee.getNumber("WEBGL_VERSION")));Ee.registerFlag("WEBGL_FENCE_API_ENABLED",()=>HI(Ee.getNumber("WEBGL_VERSION")));Ee.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>Ee.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);Ee.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}.`)});Ee.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>Xp.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}.`)});Ee.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);Ee.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1);Ee.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5);Ee.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128);Ee.registerFlag("WEBGL_EXP_CONV",()=>!1);Ee.registerFlag("SOFTWARE_WEBGL_ENABLED",()=>Ee.getBool("IS_TEST"));Ee.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",()=>1/0);Ee.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",()=>!1);Ee.registerFlag("WEBGL2_ISNAN_CUSTOM",()=>!1);function cs(){let e,t,n,s,r,a,o,i,l,u;return U().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",n="out",s="in",r="texture",a="outputColor",o="out vec4 outputColor;",i=U().getBool("WEBGL2_ISNAN_CUSTOM")?` bool isnan_custom(float val) { uint floatToUint = floatBitsToUint(val); return (floatToUint & 0x7fffffffu) > 0x7f800000u; } bvec4 isnan_custom(vec4 val) { return bvec4(isnan_custom(val.x), isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w)); } #define isnan(value) isnan_custom(value) `:"",l="",u=` #define round(value) newRound(value) int newRound(float value) { return int(floor(value + 0.5)); } ivec4 newRound(vec4 value) { return ivec4(floor(value + vec4(0.5))); } `):(e="",t="attribute",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)); } `,u=` int round(float value) { return int(floor(value + 0.5)); } ivec4 round(vec4 value) { return ivec4(floor(value + vec4(0.5))); } `),{version:e,attribute:t,varyingVs:n,varyingFs:s,texture2D:r,output:a,defineOutput:o,defineSpecialNaN:i,defineSpecialInf:l,defineRound:u}}function cu(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 u2(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 Lee(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 Bee(e,t,n="index"){let s=e.map((a,o)=>o),r=Lee(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 Wx(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 Vx(){return` int getFlatIndex(ivec3 coords) { return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z; } `}var jI=` 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:qI}=T;function Wee(e,t,n){let s=[];if(e.forEach(h=>{let f=v.sizeFromShape(h.shapeInfo.logicalShape);if(h.shapeInfo.isUniform?s.push(`uniform float ${h.name}${f>1?`[${f}]`:""};`):(s.push(`uniform sampler2D ${h.name};`),s.push(`uniform int offset${h.name};`)),n.enableShapeUniforms){let{uniformShape:m}=Ux(n.packedInputs,h.shapeInfo.logicalShape,h.shapeInfo.texShape);switch(m.length){case 1:s.push(`uniform int ${h.name}Shape;`);break;case 2:s.push(`uniform ivec2 ${h.name}Shape;`);break;case 3:s.push(`uniform ivec3 ${h.name}Shape;`);break;case 4:s.push(`uniform ivec4 ${h.name}Shape;`);break;default:break}s.push(`uniform ivec2 ${h.name}TexShape;`)}}),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:s.push("uniform int outShape;");break;case 2:s.push("uniform ivec2 outShape;"),s.push("uniform int outShapeStrides;");break;case 3:s.push("uniform ivec3 outShape;"),s.push("uniform ivec2 outShapeStrides;");break;case 4:s.push("uniform ivec4 outShape;"),s.push("uniform ivec3 outShapeStrides;");break;default:break}s.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach(h=>{s.push(`uniform ${h.type} ${h.name}${h.arrayIndex?`[${h.arrayIndex}]`:""};`)});let r=s.join(` `),a=e.map(h=>Vee(h,t,n.packedInputs,n.enableShapeUniforms)).join(` `),o=t.texShape,i=cs(),l=Hee(i),u,c,p=Xee(i);return t.isPacked?(u=Uee(t.logicalShape,o,n.enableShapeUniforms),c=qee(i)):(u=Gee(t.logicalShape,o,n.enableShapeUniforms),c=jee(i)),n.packedInputs&&(p+=Jee),[p,l,c,r,u,a,n.userCode].join(` `)}function nd(e,t=!1){let n=e.shapeInfo.logicalShape;switch(n.length){case 0:return cte(e,t);case 1:return pte(e,t);case 2:return fte(e,t);case 3:return gte(e,t);case 4:return Ate(e,t);case 5:return xte(e);case 6:return bte(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function XI(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return ute(e);case 1:return dte(e,t);case 2:return hte(e,t);case 3:return mte(e,t);default:return yte(e,t)}}function Vee(e,t,n=!1,s){let r="";n?r+=XI(e,s):r+=nd(e,s);let a=e.shapeInfo.logicalShape,o=t.logicalShape;return a.length<=o.length&&(n?r+=vte(e,t):r+=wte(e,t)),r}function Uee(e,t,n){switch(e.length){case 0:return KI();case 1:return Qee(e,t,n);case 2:return ite(e,t,n);case 3:return tte(e,t,n);default:return ste(e,t,n)}}function Gee(e,t,n){switch(e.length){case 0:return KI();case 1:return ete(e,t,n);case 2:return lte(e,t,n);case 3:return nte(e,t,n);case 4:return rte(e,t,n);case 5:return ate(e,t);case 6:return ote(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function Hee(e){return` float sampleTexture(sampler2D textureSampler, vec2 uv) { return ${e.texture2D}(textureSampler, uv).r; } `}function jee(e){return` void setOutput(float val) { ${e.output} = vec4(val, 0, 0, 0); } `}function qee(e){return` void setOutput(vec4 val) { ${e.output} = val; } `}function Xee(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); } ${Kee} ${Zee} ${Yee} `}var Kee=` 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); } `,Zee=` vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR, int texNumC, int row, int col) { int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2); int texR = texelIndex / texNumC; int texC = texelIndex - texR * texNumC; return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); } `,Yee=` vec2 packedUVfrom3D(int texNumR, int texNumC, int texelsInBatch, int texelsInLogicalRow, int b, int row, int col) { int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2); int texR = index / texNumC; int texC = index - texR * texNumC; return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); } `,Jee=` 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 KI(){return` int getOutputCoords() { return 0; } `}function Qee(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 ete(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 tte(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 nte(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; ${u2(["r","c","d"],e)} return ivec3(r, c, d); } `;let s=cu(["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 ste(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 u=2;u=1?c="coords = 0;":c=i.map(x=>`coords.${p[x+u]} = 0;`).join(` `);let d="";o<2&&a>0?d="coords":d=e.shapeInfo.logicalShape.map((x,A)=>`coords.${p[A+u]}`).join(", ");let h="return outputValue;",m=v.sizeFromShape(e.shapeInfo.logicalShape)===1,y=v.sizeFromShape(t.logicalShape)===1;if(a===1&&!m&&!y)h=` return vec4(outputValue.xy, outputValue.xy); `;else if(m&&!y)o===1?h=` return vec4(outputValue.x, outputValue.x, 0., 0.); `:h=` return vec4(outputValue.x); `;else if(i.length){let x=a-2,A=a-1;i.indexOf(x)>-1&&i.indexOf(A)>-1?h="return vec4(outputValue.x);":i.indexOf(x)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(A)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return` vec4 ${r}() { ${l} coords = getOutputCoords(); ${c} vec4 outputValue = get${s}(${d}); ${h} } `}function wte(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 u=Tt(l),c=qI(e.shapeInfo.logicalShape,t.logicalShape),p=l-i,d,h=["x","y","z","w","u","v"];i===0?d="":l<2&&c.length>=1?d="coords = 0;":d=c.map(m=>`coords.${h[m+p]} = 0;`).join(` `);let f="";return l<2&&i>0?f="coords":f=e.shapeInfo.logicalShape.map((m,g)=>`coords.${h[g+p]}`).join(", "),` float ${r}() { ${u} coords = getOutputCoords(); ${d} return get${s}(${f}); } `}function Tt(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function Ux(e,t,n){let{newShape:s,keptDims:r}=v.squeezeShape(t),a=t.length,o=e&&a===3&&t[0]===1,i=o?t.slice(1):s,l=!e&&a>1&&!v.arraysEqual(t,n)&&s.lengthe[n]).join(", ")}function kte(e,t,n,s){let r=n.map((c,p)=>{let d={logicalShape:c.shape,texShape:c.isUniform?null:c.texData.texShape,isUniform:c.isUniform,isPacked:c.isUniform?!1:c.texData.isPacked,flatOffset:null};return c.texData!=null&&c.texData.slice!=null&&c.texData.slice.flatOffset>0&&(d.flatOffset=c.texData.slice.flatOffset),{name:t.variableNames[p],shapeInfo:d}}),a=r.map(c=>c.shapeInfo),o={logicalShape:s.shape,texShape:s.texData.texShape,isUniform:!1,isPacked:s.texData.isPacked,flatOffset:null},i=Wee(r,o,t),l=II(e.gl,i),u=e.createProgram(l);return U().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:l,source:i,webGLProgram:u,inShapeInfos:a,outShapeInfo:o,uniformLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,inShapesLocations:null,inTexShapesLocations:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:Object.assign({program:t,fragmentShader:l,source:i,webGLProgram:u,inShapeInfos:a,outShapeInfo:o},ZI(e,t,u))}function ZI(e,t,n){let s={},r={},a={},o=[],i,l,u,c=null,p=null;p=e.getUniformLocation(n,"NAN",!1),U().getNumber("WEBGL_VERSION")===1&&(c=e.getUniformLocation(n,"INFINITY",!1));let d=!1;for(let h=0;h{o[f]=e.getUniformLocation(n,h.name,d)}),{uniformLocations:s,customUniformLocations:o,infLoc:c,nanLoc:p,inShapesLocations:r,inTexShapesLocations:a,outShapeLocation:i,outShapeStridesLocation:u,outTexShapeLocation:l}}function f7(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 Ste(e,t,n,s,r){t.program.enableShapeUniforms||(f7(t.inShapeInfos,n),f7([t.outShapeInfo],[s]));let a=s.texData.texture,o=s.texData.texShape;s.texData.isPacked?e.setOutputPackedMatrixTexture(a.texture,o[0],o[1]):e.setOutputMatrixTexture(a.texture,o[0],o[1]),e.setProgram(t.webGLProgram),U().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,u)=>{let c=t.program.variableNames[u],p=t.uniformLocations[c],d=t.uniformLocations[`offset${c}`],h=t.inShapesLocations[`${c}Shape`],f=t.inTexShapesLocations[`${c}TexShape`];if(h){let{uniformShape:m}=Ux(t.program.packedInputs,l.shape,l.texData.texShape);switch(m.length){case 1:e.gl.uniform1iv(h,new Int32Array(m));break;case 2:e.gl.uniform2iv(h,new Int32Array(m));break;case 3:e.gl.uniform3iv(h,new Int32Array(m));break;case 4:e.gl.uniform4iv(h,new Int32Array(m));break;default:break}}if(f&&e.gl.uniform2i(f,l.texData.texShape[0],l.texData.texShape[1]),p!=null){if(l.isUniform){if(v.sizeFromShape(l.shape)<2)e.gl.uniform1f(p,l.uniformValues[0]);else{let m=l.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),e.gl.uniform1fv(p,m)}return}l.texData.slice!=null&&d!=null&&e.gl.uniform1i(d,l.texData.slice.flatOffset),e.setInputMatrixTexture(l.texData.texture.texture,p,u)}});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,u)=>{let c=t.customUniformLocations[u],p=r[u];if(l.type==="float")e.gl.uniform1fv(c,p);else if(l.type==="vec2")e.gl.uniform2fv(c,p);else if(l.type==="vec3")e.gl.uniform3fv(c,p);else if(l.type==="vec4")e.gl.uniform4fv(c,p);else if(l.type==="int")e.gl.uniform1iv(c,p);else if(l.type==="ivec2")e.gl.uniform2iv(c,p);else if(l.type==="ivec3")e.gl.uniform3iv(c,p);else if(l.type==="ivec4")e.gl.uniform4iv(c,p);else throw Error(`uniform type ${l.type} is not supported yet.`)}),e.executeProgram()}function Ite(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:u,uniformShape:c,keptDims:p}=Ux(e.packedInputs,o.shape,l),d="",h="",f="";if(c.length===1&&e.packedInputs){let w=[Math.ceil(l[0]/2),Math.ceil(l[1]/2)];d=`${w[0]>1}_${w[1]>1}`}else if(c.length===2&&!e.packedInputs)h=`${c[0]>1}_${c[1]>1}`;else if(c.length>2&&!e.packedInputs){let w=v.computeStrides(c);f=`${w[0]===l[1]}_${w[w.length-1]===l[1]}`}let m=o.shape.length,g=c.length===2&&v.arraysEqual(o.shape,l),y=v.sizeFromShape(o.shape)===1,x=T.getBroadcastDims(o.shape,n.shape),A=!e.packedInputs&&m===n.shape.length&&v.arraysEqual(l,n.texData.texShape),b=e.packedInputs||c.length>2?"":`${l[0]>1}_${l[1]>1}`;s+=`${m}_${A}_${u?p:""}_${c.length}_${y}_${x}_${g}_${d}_${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+`${U().getNumber("WEBGL_VERSION")}`,a}function ds(e){return U().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}var Cte=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=xp.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=cs();this.outputShape=e,this.enableShapeUniforms=ds(this.outputShape.length),this.userCode=` ivec3 outCoordsFromFlatIndex(int index) { ${this.enableShapeUniforms?u2(["r","c","d"],e):cu(["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; } `}},Tte=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=xp.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=cs();this.outputShape=e,this.enableShapeUniforms=ds(this.outputShape.length),this.userCode=` ivec3 outCoordsFromFlatIndex(int index) { ${this.enableShapeUniforms?u2(["r","c","d"],e):cu(["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; } `}},Nte=class{constructor(e){this.variableNames=["A"],this.outTexUsage=Zs.DOWNLOAD;let t=cs();this.outputShape=e,this.userCode=` ${jI} void main() { float x = getAAtOutCoords(); ${t.output} = encode_float(x); } `}},Ete=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Zs.DOWNLOAD;let t=cs();this.outputShape=e,this.userCode=` ${jI} void main() { ivec3 coords = getOutputCoords(); float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z)); ${t.output} = encode_float(x); } `}},Rte=class{constructor(e,t=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=cs();this.outputShape=e,this.enableShapeUniforms=ds(this.outputShape.length);let s="result";t&&(s="floor(result * 255. + 0.5)"),this.userCode=` ${this.enableShapeUniforms?Vx():Wx(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.); } `}},_te=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=cs();this.outputShape=e,this.enableShapeUniforms=ds(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?Vx():Wx(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}; } `}},YI={};We(YI,{bindVertexProgramAttributeStreams:()=>o9,createBufferFromOutputTexture:()=>u9,createFloat16MatrixTexture:()=>n9,createFloat16PackedMatrixTexture:()=>a9,createFloat32MatrixTexture:()=>t9,createIndexBuffer:()=>e9,createPackedMatrixTexture:()=>r9,createUnsignedBytesMatrixTexture:()=>s9,createVertexBuffer:()=>QI,createVertexShader:()=>JI,downloadByteEncodedFloatMatrixFromOutputTexture:()=>d9,downloadFloat32MatrixFromBuffer:()=>c9,downloadMatrixFromPackedOutputTexture:()=>h9,downloadPackedMatrixFromBuffer:()=>p9,getInternalFormatForFloat16MatrixTexture:()=>Hx,getInternalFormatForFloat16PackedMatrixTexture:()=>Xx,getInternalFormatForFloat32MatrixTexture:()=>Gx,getInternalFormatForPackedMatrixTexture:()=>qx,getInternalFormatForUnsignedBytesMatrixTexture:()=>jx,uploadDenseMatrixToTexture:()=>i9,uploadPixelDataToTexture:()=>l9});function JI(e){let t=cs(),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 SI(e,n)}function QI(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 NI(e,t)}function e9(e){let t=new Uint16Array([0,1,2,2,1,3]);return EI(e,t)}function Eh(e,t,n,s,r,a){_I(t,n);let o=RI(e),i=e.TEXTURE_2D;return we(e,()=>e.bindTexture(i,o)),we(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),we(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),we(e,()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST)),we(e,()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST)),U().getNumber("WEBGL_VERSION")===1?we(e,()=>e.texImage2D(i,0,s,t,n,0,r,a,null)):we(e,()=>e.texStorage2D(i,1,s,t,n)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null)),{texture:o,texShape:[n,t]}}function Gx(e){return e.internalFormatFloat}function t9(e,t,n,s){let[r,a]=Nh(t,n);return Eh(e,r,a,Gx(s),s.textureFormatFloat,e.FLOAT)}function Hx(e){return e.internalFormatHalfFloat}function n9(e,t,n,s){let[r,a]=Nh(t,n);return Eh(e,r,a,Hx(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function jx(e){return e.downloadTextureFormat}function s9(e,t,n,s){let[r,a]=Nh(t,n);return Eh(e,r,a,jx(s),e.RGBA,e.UNSIGNED_BYTE)}function qx(e){return e.internalFormatPackedFloat}function r9(e,t,n,s){let[r,a]=ed(t,n);return Eh(e,r,a,qx(s),e.RGBA,e.FLOAT)}function Xx(e){return e.internalFormatPackedHalfFloat}function a9(e,t,n,s){let[r,a]=ed(t,n);return Eh(e,r,a,Xx(s),e.RGBA,s.textureTypeHalfFloat)}function o9(e,t,n){return we(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Q3(e,t,"clipSpacePos",n,3,20,0)&&Q3(e,t,"uv",n,2,20,12)}function i9(e,t,n,s,r,a){we(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),U().getNumber("WEBGL_VERSION")===2?we(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,s,e.RGBA,i,o)):we(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,n,s,0,e.RGBA,i,o)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function l9(e,t,n){we(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?U().getNumber("WEBGL_VERSION")===2?we(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data)):we(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):U().getNumber("WEBGL_VERSION")===2?we(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n)):we(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function u9(e,t,n,s){let r=e.createBuffer();we(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,r));let i=4*4*t*n;return we(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,i,e.STREAM_READ)),we(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),we(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),r}function c9(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 d9(e,t,n,s){let[r,a]=Nh(t,n),o=4,i=new Uint8Array(Tee(t*n,o));return we(e,()=>e.readPixels(0,0,r,a,s.downloadTextureFormat,e.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function p9(e,t,n,s,r,a,o,i){let l=e,u=new Float32Array(Nee(a,o));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}function h9(e,t,n){let s=new Float32Array(t*n*4);return we(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,s)),s}var Zu=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=U().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,l2(t,e)):this.gl=Mr(t);let n="WEBGL_color_buffer_float",s="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),U().getNumber("WEBGL_VERSION")===1){let r="OES_texture_float",a="OES_texture_half_float";if(this.textureFloatExtension=Yd(this.gl,r),Ys(this.gl,a))this.textureHalfFloatExtension=Yd(this.gl,a);else if(U().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),Ys(this.gl,s))this.colorBufferHalfFloatExtension=Yd(this.gl,s);else if(U().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",Ys(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(Ys(this.gl,s))this.colorBufferHalfFloatExtension=this.gl.getExtension(s);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=QI(this.gl),this.indexBuffer=e9(this.gl),this.framebuffer=DI(this.gl),this.textureConfig=Lx(this.gl,this.textureHalfFloatExtension)}get debug(){return U().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");let e=this.gl;we(e,()=>e.finish()),we(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),we(e,()=>e.deleteFramebuffer(this.framebuffer)),we(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),we(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),we(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),t9(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),n9(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),s9(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),l9(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,s){this.throwIfDisposed(),i9(this.gl,e,t,n,s,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),a9(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),r9(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(ey(this.gl,this.framebuffer),this.outputTexture=null),we(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>d9(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,s,r,a){return p9(this.gl,e,t,n,s,r,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return c9(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);let s=u9(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(U().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 U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>h9(this.gl,t,n))}createProgram(e){this.throwIfDisposed();let t=this.gl;this.vertexShader==null&&(this.vertexShader=JI(t));let n=CI(t);return we(t,()=>t.attachShader(n,this.vertexShader)),we(t,()=>t.attachShader(n,e)),TI(t,n),this.debug&&Hf(t,n),this.vertexAttrsAreBound||(this.setProgram(n),this.vertexAttrsAreBound=o9(t,this.program,this.vertexBuffer)),n}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&we(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&Hf(this.gl,this.program),we(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?PI(this.gl,e,t):FI(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),we(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),OI(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();let[s,r]=ed(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&&Hf(this.gl,this.program),Jd(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;this.debug&&this.debugValidate(),we(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),we(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Yd(this.gl,U().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(U().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(U().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,U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,U().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=Dte(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){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;let n;"setTimeoutCustom"in U().platform&&(n=U().platform.setTimeoutCustom.bind(U().platform)),v.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0),()=>0,null,n)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),jf(this.gl,e,this.framebuffer),this.debug&&Jd(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(jf(this.gl,this.outputTexture,this.framebuffer),this.debug&&Jd(this.gl)):ey(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;jf(s,e,this.framebuffer),this.debug&&Jd(s),this.outputTexture=e,we(s,()=>s.viewport(0,0,t,n)),we(s,()=>s.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,s){this.throwIfDisposed(),we(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 Dte(e){let t=0;for(;t`${e}.${n}`)}function os(e,t){return t===1?[e]:y9(e,t)}function vne(e,t){if(e===1)return"rc";let n="";for(let s=0;s ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let n=this.rank-2;n= ${this.enableShapeUniforms?`outShape[${n}]`:this.outputShape[n]}`,n= ${n}; bool rEdge = rp1 >= ${s}; `}getOutput(e){let t=this.getSourceCoordsArr(e);return this.rank===1?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${t[0]}), cEdge ? 0. : getA(${t[1]}), rEdge ? 0. : getA(${t[2]}), rEdge || cEdge ? 0. : getA(${t[3]})`}},A9=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=ds(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=` ${kne(t,this.enableShapeUniforms)} ${this.enableShapeUniforms?Vx():Wx(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 kne(e,t){return` ivec3 inputCoordsFromReshapedOutCoords(int index) { ${t?Bee(["r","c","d"],"inputShape"):cu(["r","c","d"],e)} return ivec3(r, c, d); } `}var Sne=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=g7(t,n),r=y7(e,s,n);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);let a=m7(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===Fn.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===Fn.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===Fn.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===Fn.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===Fn.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=g7(n,s),a=y7(t,r,s);a in this.freeTextures||(this.freeTextures[a]=[]);let o=m7(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,s),i=U().get("WEBGL_DELETE_TEXTURE_THRESHOLD");i!==-1&&this._numBytesAllocated>i?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=o):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;let l=this.usedTextures[a],u=l.indexOf(e);if(u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(u,1),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);let t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function Ine(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;if(t===n.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}function m7(e,t,n,s,r){let a=Cne(t,s),o;if(r){let[l,u]=ed(e[0],e[1]);o=l*u}else{let[l,u]=Nh(e[0],e[1]);o=l*u}let i=Ine(n,a);return o*i}function Cne(e,t){switch(e){case Fn.PACKED_2X2_FLOAT32:return qx(t);case Fn.PACKED_2X2_FLOAT16:return Xx(t);case Fn.UNPACKED_FLOAT32:return Gx(t);case Fn.UNPACKED_FLOAT16:return Hx(t);case Fn.PACKED_4X1_UNSIGNED_BYTE:return jx(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function Tne(e){return U().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Fn.PACKED_2X2_FLOAT32:Fn.UNPACKED_FLOAT32:e?Fn.PACKED_2X2_FLOAT16:Fn.UNPACKED_FLOAT16}function g7(e,t){if(e===Zs.UPLOAD)return Fn.PACKED_2X2_FLOAT32;if(e===Zs.RENDER||e==null)return Tne(t);if(e===Zs.DOWNLOAD||e===Zs.PIXELS)return Fn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function y7(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}var xa=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=ds(this.outputShape.length),this.userCode=` float unaryOperation(float x) { ${t} } void main() { float x = getAAtOutCoords(); float y = unaryOperation(x); setOutput(y); } `}},br="if (isnan(x)) return x;",Nne="return x;",A7="return abs(x);",Ene="return (x >= 0.0) ? x : (exp(x) - 1.0);",Rne=br+` return (x < 0.0) ? 0.0 : x; `,_ne=br+` return (x < 0.0) ? 0.0 : min(6.0, x); `,Lu="return x;",Dne="return 1.0 / (1.0 + exp(-1.0 * x));",$ne="return x;",Pne=` 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; `,Fne=` 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; `,One=` 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; `,Mne="return 1.0 / (1.0 + exp(-1.0 * x));",ji=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=ds(this.outputShape.length),this.userCode=` vec4 unaryOperation(vec4 x) { ${t} } void main() { vec4 x = getAAtOutCoords(); vec4 y = unaryOperation(x); setOutput(y); } `}},zne=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=ds(this.outputShape.length);let t=e.length,n=os("rc",t),s=Tt(t),r=vne(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})); } `}},Lne=Ar.whereImpl,Bne=1e-7,Wne=1e-4,Lf={};function Vne(e){return e in Lf||(Lf[e]={}),Lf[e]}var Une=U().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),Gne=600;function Hne(){return U().global.screen==null?1024:U().global.screen.height*U().global.screen.width*window.devicePixelRatio*Gne/1024/1024}var od=class extends fc{constructor(e){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!U().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(e!=null){if(e instanceof Zu)t=e;else{let n=Mr(U().getNumber("WEBGL_VERSION"),e);t=new Zu(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{let n=Mr(U().getNumber("WEBGL_VERSION"));t=new Zu(n),this.binaryCache=Vne(U().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new Sne(this.gpgpu),this.numMBBeforeWarning=Hne(),this.texData=new Tp(this,Jt())}nextDataId(){return od.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}write(e,t,n){if((U().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||U().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(U().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 p;i?p=new ji(o,Lu):p=new xa(o,Lu);let d=this.runWebGLProgram(p,[{dataId:e,shape:o,dtype:s}],s),h=this.readSync(d.dataId);return this.disposeIntermediateTensorInfo(d),h}if(n!=null)return this.convertAndCacheOnCPU(e);if(s==="string")return n;let l=this.activeTimers!=null,u;l&&(u=v.now());let c;if(s==="complex64"){let p=this.readSync(r.real.dataId),d=this.readSync(r.imag.dataId);c=T.mergeRealAndImagArrays(p,d)}else c=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=v.now()-u),this.convertAndCacheOnCPU(e,c)}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 ji(s,Lu):h=new xa(s,Lu);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(U().getBool("DEBUG")&&!U().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&U().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l=null,u;if(a!=="complex64"&&U().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);let h=this.texData.get(u.dataId);l=this.gpgpu.createBufferFromTexture(h.texture.texture,...Mf(s))}this.pendingRead.set(e,[]),a!=="complex64"&&await this.gpgpu.createAndWaitForFence();let c;if(a==="complex64"){let h=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]),f=h[0],m=h[1];c=T.mergeRealAndImagArrays(f,m)}else if(l==null)c=this.getValuesFromTexture(e);else{let h=v.sizeFromShape(s);c=this.gpgpu.downloadFloat32MatrixFromBuffer(l,h)}if(u!=null&&this.disposeIntermediateTensorInfo(u),l!=null){let h=this.gpgpu.gl;we(h,()=>h.deleteBuffer(l))}let p=this.convertAndCacheOnCPU(e,c),d=this.pendingRead.get(e);return this.pendingRead.delete(e),d.forEach(h=>h(p)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&Jt().removeDataId(e,this),this.pendingDeletes--),p}readToGPU(e,t={}){let n=this.texData.get(e),{values:s,shape:r,slice:a,dtype:o,isPacked:i,texture:l}=n;if(o==="complex64")throw new Error("Does not support reading texture for complex64 dtype.");if(a!=null){let d;i?d=new ji(r,Lu):d=new xa(r,Lu);let h=this.runWebGLProgram(d,[{dataId:e,shape:r,dtype:o}],o),f=this.readToGPU(h,t);return this.disposeIntermediateTensorInfo(h),f}if(l==null)throw s!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");let u=this.decode(e,t.customTexShape),c=Jt().makeTensorFromTensorInfo(u),p=this.texData.get(u.dataId);return Object.assign({tensorRef:c},p.texture)}bufferSync(e){let t=this.readSync(e.dataId);if(e.dtype==="string")try{let n=t.map(s=>v.decodeString(s));return ze(e.shape,e.dtype,n)}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return ze(e.shape,e.dtype,t)}checkNumericalProblems(e){if(e!=null)for(let t=0;t0}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};return(async()=>{if(U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let i=await Promise.all(r);o.kernelMs=v.sum(i),o.getExtraProfileInfo=()=>i.map((l,u)=>({name:a[u],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 U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:v.now(),endMs:null}}endTimer(e){return U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=v.now(),e)}async getQueryTime(e){if(U().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 u=this.texData.get(e);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=Une){return U().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){return Jt().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,n),this)}unpackTensor(e){let t=new zne(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new wne(e.shape),n=!0;return this.runWebGLProgram(t,[e],e.dtype,null,n)}packedReshape(e,t){let n=[il(e.shape),...ll(e.shape)],s={dtype:e.dtype,shape:n,dataId:e.dataId},r=[il(t),...ll(t)],a=new A9(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,t){let n=this.texData.get(e),{isPacked:s,shape:r,dtype:a}=n;if(t!=null){let p=v.sizeFromShape(r),d=t[0]*t[1]*4;v.assert(p<=d,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.")}let o=qf(r),i;s?i=new Tte(o):i=new Cte(o);let l=!0,u=[t!=null?t:Mf(o)],c=this.runWebGLProgram(i,[{shape:o,dtype:a,dataId:e}],a,u,l,t);return{dtype:a,shape:r,dataId:c.dataId}}runWebGLProgram(e,t,n,s,r=!1,a){let o=this.makeTensorInfo(e.outputShape,n),i=this.texData.get(o.dataId);if(e.packedOutput&&(i.isPacked=!0),e.outPackingScheme===xp.DENSE){let g=a!=null?a:Mf(e.outputShape);i.texShape=g.map(y=>y*2)}if(e.outTexUsage!=null&&(i.usage=e.outTexUsage),v.sizeFromShape(o.shape)===0)return i.values=v.getTypedArrayFromDType(o.dtype,0),o;let l=[],u=t.map(g=>{if(g.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let y=this.texData.get(g.dataId);if(y.texture==null){if(!e.packedInputs&&v.sizeFromShape(g.shape)<=U().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:g.shape,texData:null,isUniform:!0,uniformValues:y.values};e.packedInputs&&(y.isPacked=!0,y.shape=g.shape)}if(this.uploadToGPU(g.dataId),!!y.isPacked!=!!e.packedInputs)g=y.isPacked?this.unpackTensor(g):this.packTensor(g),l.push(g),y=this.texData.get(g.dataId);else if(y.isPacked&&!bp(y.shape,g.shape)){let x=g,A=g.shape;g.shape=y.shape,g=this.packedReshape(g,A),l.push(g),y=this.texData.get(g.dataId),x.shape=A}return{shape:g.shape,texData:y,isUniform:!1}});this.uploadToGPU(o.dataId);let c={shape:o.shape,texData:i,isUniform:!1},p=Ite(e,u,c),d=this.getAndSaveBinary(p,()=>kte(this.gpgpu,e,u,c)),h=this.activeTimers!=null,f;h&&(f=this.startTimer()),U().get("ENGINE_COMPILE_ONLY")||Ste(this.gpgpu,d,u,c,s),l.forEach(g=>this.disposeIntermediateTensorInfo(g)),h&&(f=this.endTimer(f),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(f)}));let m=U().get("WEBGL_FLUSH_THRESHOLD");if(m>0){let g=v.now();g-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=g)}if(!U().getBool("WEBGL_LAZILY_UNPACK")&&i.isPacked&&r===!1){let g=this.unpackTensor(o);return this.disposeIntermediateTensorInfo(o),g}return o}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||(U().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(!U().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=U().getBool("DEBUG");U().set("DEBUG",!1);let t=this.abs(Ce(1e-8)).dataSync()[0];if(U().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?Bne:Wne}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,u;l&&(u=v.now());let c=t.texShape;if(c==null&&(c=LI(n,i),t.texShape=c),r!=null){let p=qf(n),d,h=c[1],f=c[0],m=r instanceof Uint8Array||r instanceof Uint8ClampedArray;(i||!m)&&([h,f]=ed(c[0],c[1])),i?d=new _te(p,m):d=new Rte(p,m);let g=m?[f,h]:c,y=this.makeTensorInfo(g,s),x=this.texData.get(y.dataId);m?x.usage=Zs.PIXELS:x.usage=Zs.UPLOAD,x.texShape=g,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(y.dataId),h,f,r);let A=[[f,h]],b=!0,w=this.runWebGLProgram(d,[y],s,A,b),k=this.texData.get(w.dataId);t.texShape=k.texShape,t.isPacked=k.isPacked,t.usage=k.usage,U().get("ENGINE_COMPILE_ONLY")?this.disposeData(w.dataId):(t.texture=k.texture,t.values=null,this.texData.delete(w.dataId)),this.disposeIntermediateTensorInfo(y),l&&(this.uploadWaitMs+=v.now()-u)}else{let p=this.acquireTexture(c,o,s,i);t.texture=p}}convertAndCacheOnCPU(e,t){let n=this.texData.get(e),{dtype:s}=n;return this.releaseGPUData(e),t!=null&&(n.values=jne(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)}checkCompileCompletion(){for(let[,e]of Object.entries(this.binaryCache))this.checkCompletion_(e)}async checkCompileCompletionAsync(){let e=[];if(this.gpgpu.parallelCompilationExtension){for(let[,t]of Object.entries(this.binaryCache))e.push(this.checkCompletionAsync_(t));return Promise.all(e)}else{for(let[,t]of Object.entries(this.binaryCache)){let n=new Promise(s=>{try{this.checkCompletion_(t),s(!0)}catch(r){throw r}});e.push(n)}return Promise.all(e)}}async checkCompletionAsync_(e){return this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(e):(await UA(),this.checkCompletionAsync_(e))}checkCompletion_(e){if(this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS)===!1)throw console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)),this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS)===!1?(Bx(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)),new Error("Failed to compile fragment shader.")):new Error("Failed to link vertex and fragment shaders.");return!0}getUniformLocations(){for(let[,e]of Object.entries(this.binaryCache)){let{uniformLocations:t,customUniformLocations:n,infLoc:s,nanLoc:r,inShapesLocations:a,inTexShapesLocations:o,outShapeLocation:i,outShapeStridesLocation:l,outTexShapeLocation:u}=ZI(this.gpgpu,e.program,e.webGLProgram);e.uniformLocations=t,e.customUniformLocations=n,e.infLoc=s,e.nanLoc=r,e.inShapesLocations=a,e.inTexShapesLocations=o,e.outShapeLocation=i,e.outShapeStridesLocation=l,e.outTexShapeLocation=u}}};od.nextDataId=0;function jne(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 od,2);var Xne={forceHalfFloat:x9},Zx=` if (isnan(a)) return a; if (isnan(b)) return b; `,hc=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=T.assertAndGetBroadcastShape(t,n),this.enableShapeUniforms=ds(this.outputShape.length),this.userCode=` float binaryOperation(float a, float b) { ${e} } void main() { float a = getAAtOutCoords(); float b = getBAtOutCoords(); setOutput(binaryOperation(a, b)); } `}},Rh=` result.r = isNaN.r ? NAN : result.r; result.g = isNaN.g ? NAN : result.g; result.b = isNaN.b ? NAN : result.b; result.a = isNaN.a ? NAN : result.a; `,_h=class{constructor(e,t,n,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=T.assertAndGetBroadcastShape(t,n);let r=this.outputShape.length;this.enableShapeUniforms=ds(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=` ${Tt(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=os("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 Ls(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 Kne={kernelName:Fo,backendName:"webgl",kernelFunc:Ls};function gi(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=Ls({inputs:{x:s},backend:n}),l=Ls({inputs:{x:r},backend:n});return o.complexTensorInfos={real:i,imag:l},a}var Zne={kernelName:Ep,backendName:"webgl",kernelFunc:gi},b9="return (a < 0.) ? b * a : a;",v9=` vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); `;function Yne(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{alpha:a}=s,o=n.makeTensorInfo([],"float32",v.createScalarValue(a,"float32")),i=U().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new _h(v9,r.shape,o.shape):new hc(b9,r.shape,o.shape),l=n.runWebGLProgram(i,[r,o],"float32");return n.disposeIntermediateTensorInfo(o),l}var Jne={kernelName:Oo,backendName:"webgl",kernelFunc:Yne},w9="return (a < 0.) ? b * a : a;",k9=` vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); `;function Qne(e){let{inputs:t,backend:n}=e,{x:s,alpha:r}=t,a=U().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new _h(k9,s.shape,r.shape):new hc(w9,s.shape,r.shape);return n.runWebGLProgram(a,[s,r],"float32")}var ese={kernelName:Xo,backendName:"webgl",kernelFunc:Qne},id="if (isnan(x)) return x;";function pt({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 p=i.texData.get(o.dataId),d=n(p.values,l);return i.makeTensorInfo(o.shape,l,d)}let u=U().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,c;return u?c=new ji(o.shape,t):c=new xa(o.shape,e),i.runWebGLProgram(c,[o],l)}}function Wn({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:s=!1,cpuKernelImpl:r,dtype:a}){return({inputs:o,backend:i})=>{let{a:l,b:u}=o,c=i;if(s&&l.dtype==="complex64"){let f=c.texData.get(l.dataId),m=c.texData.get(u.dataId),[g,y]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(A=>{let[b,w]=A,k={dataId:b.dataId,dtype:b.dtype,shape:l.shape},C={dataId:w.dataId,dtype:w.dtype,shape:u.shape},N=new hc(e,l.shape,u.shape);return c.runWebGLProgram(N,[k,C],jn(b.dtype,w.dtype))}),x=gi({inputs:{real:g,imag:y},backend:c});return c.disposeIntermediateTensorInfo(g),c.disposeIntermediateTensorInfo(y),x}let p=a||jn(l.dtype,u.dtype);if((l.dtype==="string"||u.dtype==="string"||c.shouldExecuteOnCPU([l,u]))&&r!=null){let f=c.texData.get(l.dataId).values,m=c.texData.get(u.dataId).values,g=l.dtype==="string"?T.fromUint8ToStringArray(f):f,y=l.dtype==="string"?T.fromUint8ToStringArray(m):m,[x,A]=r(l.shape,u.shape,g,y,p),b=c.makeTensorInfo(A,p),w=c.texData.get(b.dataId);return w.values=x,b}let d=U().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return d?h=new _h(t,l.shape,u.shape,n):h=new hc(e,l.shape,u.shape),c.runWebGLProgram(h,[l,u],p)}}function vp(e,t=!1){if(e==="linear")return t?$ne:Nne;if(e==="relu")return t?Fne:Rne;if(e==="elu")return t?Pne:Ene;if(e==="relu6")return t?One:_ne;if(e==="prelu")return t?k9:w9;if(e==="leakyrelu")return t?v9:b9;if(e==="sigmoid")return t?Mne:Dne;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var S9=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=ds(this.outputShape.length);let u=s?e[1]:e[2],c=Math.ceil(u/2),p=s?"i * 2, rc.y":"rc.y, i * 2",d=r?"rc.z, i * 2":"i * 2, rc.z",h=s?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],m="",g="";o&&(i?m=`vec4 activation(vec4 a) { vec4 b = getPreluActivationWeightsAtOutCoords(); ${o} }`:l?m=`vec4 activation(vec4 a) { vec4 b = getLeakyreluAlphaAtOutCoords(); ${o} }`:m=`vec4 activation(vec4 x) { ${o} }`,g="result = activation(result);");let y=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let x="rc.x",A="rc.x";e[0]`The new shape (${l}) has ${u} elements and the old shape (${r.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);let c=o.texData.get(r.dataId);return c.isPacked&&!bp(r.shape,l)&&!(c.texture!==null&&bp(c.shape,l))?nse(r,l,o):(o.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype})}var sse={kernelName:zl,backendName:"webgl",kernelFunc:be},w7=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 c=1/t;l=`sumValue += dot(values * ${v.isInt(c)?c.toPrecision(2):c}, ones);`}let u="";r%n>0&&(u=` 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) { ${u} 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); } `}},rse=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 u=Math.floor(n/4)*4,c=n%4,p=` 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); } } } `,d="vec4";t==="all"?(o="1.0",p=` bool reducedAllValue = all(values); float floatedReducedAllValue = float(reducedAllValue); allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0); `,d="bvec4"):t==="any"&&(o="0.0",p=` bool reducedAnyValue = any(values); float floatedReducedAnyValue = float(reducedAnyValue); anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0); `,d="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 < ${u}; i += 4) { int inIdx = inOffset + i; ${d} values = ${d}( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), getValue(batch, inIdx + 3) ); ${p} } int inIdx = inOffset + ${u}; if (${c===1}) { ${d} values = ${d}( getValue(batch, inIdx), initializationValue, initializationValue, initializationValue ); ${p} } else if (${c===2}) { ${d} values = ${d}( getValue(batch, inIdx), getValue(batch, inIdx + 1), initializationValue, initializationValue ); ${p} } else if (${c===3}) { ${d} values = ${d}( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), initializationValue ); ${p} } setOutput(${l}); } `}};function ase(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=T.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:s,outSize:Math.ceil(n/s)})}return t}function pu(e,t,n,s){let r=ase(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=Tt(this.rank),r=y9("rc",this.rank),a=new Array(this.rank);for(let u=0;u`Error in matMul: inner shapes (${p}) and (${d}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${s} must match.`);let w=n?[y,p,h]:[y,h,p],k=s?[x,f,d]:[x,d,f],C=be({inputs:{x:e},backend:r,attrs:{shape:w}}),N=be({inputs:{x:t},backend:r,attrs:{shape:k}}),R=[C,N],D=Math.max(y,x),E=n?C.shape[1]:C.shape[2],$=a!=null,S=o!=null,F=l==="leakyrelu",z=l!=null?vp(l,!0):null,V=$||S||F||z!=null,j;if((h===1||f===1)&&E>I9&&V===!1){let q=C,K=N;n&&(q=is({inputs:{x:C},backend:r,attrs:{perm:[0,2,1]}}),R.push(q)),s&&(K=is({inputs:{x:N},backend:r,attrs:{perm:[0,2,1]}}),R.push(K));let ne=f!==1,ae=f===1,re=q;ne&&(re=be({inputs:{x:q},backend:r,attrs:{shape:[D,E,1]}}),R.push(re));let ue=f===1?2:1,oe=K;ae&&(oe=be({inputs:{x:K},backend:r,attrs:{shape:[D,1,E]}}),R.push(oe));let Ae=Yx({inputs:{a:re,b:oe},backend:r});j=d2({inputs:{x:Ae},backend:r,attrs:{axis:ue,keepDims:!0}}),R.push(Ae)}else{let q=jn(e.dtype,t.dtype),K=new S9(w,k,[D,h,f],n,s,$,z,S,F),ne=[C,N];if(a!=null&&ne.push(a),S&&ne.push(o),F){let ae=r.makeTensorInfo([],"float32",v.createScalarValue(i,"float32"));ne.push(ae),R.push(ae)}j=r.runWebGLProgram(K,ne,q)}let G=be({inputs:{x:j},backend:r,attrs:{shape:b}});R.push(j);for(let q of R)r.disposeIntermediateTensorInfo(q);return G}function pse(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:p}=s;return Sm({a:r,b:a,transposeA:l,transposeB:u,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:p,activation:c})}var hse={kernelName:no,backendName:"webgl",kernelFunc:pse},k7="return abs(x);";function fse(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=m9(a.values);return n.makeTensorInfo(s.shape,s.dtype,o)}let r;return U().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new ji(s.shape,k7):r=new xa(s.shape,k7),n.runWebGLProgram(r,[s],s.dtype)}var mse={kernelName:dl,backendName:"webgl",kernelFunc:fse},gse=br+` if (abs(x) > 1.) { return NAN; } return acos(x); `,yse=pt({opSnippet:gse}),Ase={kernelName:gc,backendName:"webgl",kernelFunc:yse},xse=br+` if (x < 1.0) return NAN; return log(x + sqrt(x * x - 1.0));`,bse=pt({opSnippet:xse}),vse={kernelName:yc,backendName:"webgl",kernelFunc:bse},S7="return a + b;",wse=Wn({opSnippet:S7,packedOpSnippet:S7,supportsComplex:!0,cpuKernelImpl:$te}),kse={kernelName:Ta,backendName:"webgl",kernelFunc:wse},Sse=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); } `}},Ise=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 Zf(e){let{inputs:t,backend:n}=e,s=t;if(s.length===1)return Ls({inputs:{x:s[0]},backend:n});if(s.length>U().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let l=Math.floor(s.length/2),u=Zf({inputs:s.slice(0,l),backend:n}),c=Zf({inputs:s.slice(l),backend:n});return Zf({inputs:[u,c],backend:n})}let r=s.map(l=>l.dtype).reduce((l,u)=>jn(l,u)),a=s.map(l=>l.shape),i=U().getBool("WEBGL_PACK")?new Ise(s[0].shape,a):new Sse(s[0].shape,a);return n.runWebGLProgram(i,s,r)}var Cse={kernelName:go,backendName:"webgl",kernelFunc:Zf};function Tse(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),u=l,c=T.getAxesPermutation(u,i),p=r;c!=null&&(p=is({inputs:{x:r},backend:n,attrs:{perm:c}}),u=T.getInnerMostAxes(u.length,i)),T.assertAxesAreInnerMostDims("all",u,i);let[d,h]=T.computeOutAndReduceShapes(p.shape,u),f=v.sizeFromShape(h),m=be({inputs:{x:p},backend:n,attrs:{shape:[-1,f]}}),g=pu(m,m.dtype,"all",n),y;if(o){let x=T.expandShapeToKeepDim(d,l);y=be({inputs:{x:g},backend:n,attrs:{shape:x}})}else y=be({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),c!=null&&n.disposeIntermediateTensorInfo(p),y}var Nse={kernelName:Ac,backendName:"webgl",kernelFunc:Tse};function Ese(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),u=l,c=T.getAxesPermutation(u,i),p=r;c!=null&&(p=is({inputs:{x:r},backend:n,attrs:{perm:c}}),u=T.getInnerMostAxes(u.length,i)),T.assertAxesAreInnerMostDims("any",u,i);let[d,h]=T.computeOutAndReduceShapes(p.shape,u),f=v.sizeFromShape(h),m=be({inputs:{x:p},backend:n,attrs:{shape:[-1,f]}}),g=pu(m,m.dtype,"any",n),y;if(o){let x=T.expandShapeToKeepDim(d,l);y=be({inputs:{x:g},backend:n,attrs:{shape:x}})}else y=be({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),c!=null&&n.disposeIntermediateTensorInfo(p),y}var Rse={kernelName:xc,backendName:"webgl",kernelFunc:Ese},_se=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)); } `}},Dse=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=Tt(i),u=os("coords",i),c,p;if(a===1){p=i+1;let C=Tt(p);c=` ${C} sourceLocR = ${C}(${u.join()}, 0); ++${u[i-1]}; ${C} sourceLocG = ${C}(${u.join()}, 0); ++${u[i-2]}; ${C} sourceLocA = ${C}(${u.join()}, 0); --${u[i-1]}; ${C} sourceLocB = ${C}(${u.join()}, 0); --${u[i-2]};`}else p=i,c=` ${l} sourceLocR = coords; ++${u[i-1]}; ${l} sourceLocG = coords; ++${u[i-2]}; ${l} sourceLocA = coords; --${u[i-1]}; ${l} sourceLocB = coords; --${u[i-2]};`;let d=["x","y","z","w","u","v"].slice(0,p),h="."+d[p-1],f=d.map(C=>"int "+C),m=os("sourceLocR",p-1).concat("inIdx.r"),g=os("sourceLocG",p-1).concat("inIdx.g"),y=os("sourceLocB",p-1).concat("inIdx.b"),x=os("sourceLocA",p-1).concat("inIdx.a"),A=n==="max"?"greaterThan":"lessThan",b=s?"":` inIdx = round(vec4(getBestIndicesAChannel(${m.join()}), getBestIndicesAChannel(${g.join()}), getBestIndicesAChannel(${y.join()}), getBestIndicesAChannel(${x.join()})));`,w=`vec4( getAChannel(${m.join()}), hasNextCol ? getAChannel(${g.join()}) : 0., hasNextRow ? getAChannel(${y.join()}) : 0., hasNextRow && hasNextCol ? getAChannel(${x.join()}) : 0.)`,k=s?"":` float getBestIndicesAChannel(${f.join()}) { return getChannel(getBestIndicesA(${d.join()}), vec2(${d.slice(-2).join()})); }`;this.userCode=` float getAChannel(${f.join()}) { return getChannel(getA(${d.join()}), vec2(${d.slice(-2).join()})); } ${k} void main() { ${l} coords = getOutputCoords(); bool hasNextCol = ${u[i-1]} < ${o[i-1]-1}; bool hasNextRow = ${u[i-2]} < ${o[i-2]-1}; ${c} 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(${A}(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 C9(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=T.computeOptimalWindowSize(a),i={windowSize:o,inSize:a,batchSize:r,outSize:Math.ceil(a/o)},l=new _se(i,n,s==null),u=[t];s!=null&&u.push(s);let c=e.runWebGLProgram(l,u,"int32");if(c.shape[1]===1)return c;let p=C9(e,t,n,c);return e.disposeIntermediateTensorInfo(c),p}function T9(e,t,n,s=null){let r=s!=null?s.shape:t.shape,a=r[r.length-1],o=T.computeOptimalWindowSize(a),i=new Dse(r,o,n,s==null),l=s==null?[t]:[t,s],u=e.runWebGLProgram(i,l,"int32");if(u.shape.length===t.shape.length){let c=T9(e,t,n,u);return e.disposeIntermediateTensorInfo(u),c}return u}function N9(e,t,n,s){let r=[n];if(T.assertAxesAreInnerMostDims("arg"+s.charAt(0).toUpperCase()+s.slice(1),r,t.shape.length),!U().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[u,c]=T.computeOutAndReduceShapes(l.shape,r),p=v.sizeFromShape(c),d=be({inputs:{x:l},backend:e,attrs:{shape:[-1,p]}});a.push(d);let h=C9(e,d,s);a.push(h);let f=be({inputs:{x:h},backend:e,attrs:{shape:u}});return a.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}return T9(e,t,s)}function $se(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s,o=v.parseAxisParam(a,r.shape),i=T.getAxesPermutation(o,r.shape.length),l=r,u=[];i!=null&&(l=is({inputs:{x:r},backend:n,attrs:{perm:i}}),u.push(l),o=T.getInnerMostAxes(o.length,l.shape.length)),T.assertAxesAreInnerMostDims("argMax",[o[0]],l.shape.length);let c=N9(n,l,o[0],"max");return u.forEach(p=>n.disposeIntermediateTensorInfo(p)),c}var Pse={kernelName:yo,backendName:"webgl",kernelFunc:$se};function Fse(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s,o=v.parseAxisParam(a,r.shape),i=T.getAxesPermutation(o,r.shape.length),l=r,u=[];i!=null&&(l=is({inputs:{x:r},backend:n,attrs:{perm:i}}),u.push(l),o=T.getInnerMostAxes(o.length,l.shape.length)),T.assertAxesAreInnerMostDims("argMin",[o[0]],l.shape.length);let c=N9(n,l,o[0],"min");return u.forEach(p=>n.disposeIntermediateTensorInfo(p)),c}var Ose={kernelName:bc,backendName:"webgl",kernelFunc:Fse},Mse=br+` if (abs(x) > 1.) { return NAN; } return asin(x); `,zse=pt({opSnippet:Mse}),Lse={kernelName:vc,backendName:"webgl",kernelFunc:zse},Bse=br+"return log(x + sqrt(x * x + 1.0));",Wse=pt({opSnippet:Bse}),Vse={kernelName:wc,backendName:"webgl",kernelFunc:Wse},Use=br+` return atan(x); `,Gse=pt({opSnippet:Use}),Hse={kernelName:kc,backendName:"webgl",kernelFunc:Gse},jse=Zx+` return atan(a, b); `,qse=` vec4 result = atan(a, b); bvec4 isNaNA = isnan(a); bvec4 isNaNB = isnan(b); bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w); `+Rh+` return result; `,Xse=Wn({opSnippet:jse,packedOpSnippet:qse}),Kse={kernelName:pl,backendName:"webgl",kernelFunc:Xse},Zse=br+` if ((x < -1.0) || (x > 1.0)) return NAN; return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,Yse=pt({opSnippet:Zse}),Jse={kernelName:Sc,backendName:"webgl",kernelFunc:Yse},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,u=e.dilationWidth,c=e.effectiveFilterHeight,p=e.effectiveFilterWidth,d=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;let f=t==="avg",m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,y="0.0";if(f||(y="-1.0 / 1e-20"),n){let C=">=";this.userCode=` const ivec2 strides = ivec2(${o}, ${i}); const ivec2 pads = ivec2(${d}, ${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 < ${c}; wR += ${l}) { int xR = xRCorner + wR; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${p}; wC += ${u}) { int xC = xCCorner + wC; if (xC < 0 || xC >= ${e.inWidth}) { continue; } float value = getX(batch, xR, xC, d); // If a min / max value has already been found, use it. If not, // use the current value. float currMinMaxValue = mix( value, minMaxValue, minMaxValueFound); if (value ${C} currMinMaxValue) { minMaxValue = value; minMaxValueFound = 1.0; minMaxPosition = ${s?r?m:g:`wR * ${p} + wC`}; } } } setOutput(float(minMaxPosition)); } `;return}let x="max",A=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(A="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(${d}, ${h}); const float initializationValue = ${y}; const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); float count = 0.0; float getValue(int batch, int xR, int xC, int d) { if (xC < 0 || xC >= ${e.inWidth}) { return initializationValue; } count += 1.0; return getX(batch, xR, xC, d); } void main() { ivec4 coords = getOutputCoords(); int batch = coords[0]; int d = coords[3]; ivec2 xRCCorner = coords.yz * strides - pads; int xRCorner = xRCCorner.x; int xCCorner = xRCCorner.y; // max/min x(?, ?, d) to get y(yR, yC, d). // ? = to be determined vec4 minMaxValue = vec4(${y}); float avgValue = 0.0; count = 0.0; for (int wR = 0; wR < ${c}; wR += ${l}) { int xR = xRCorner + wR; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${b}; wC += 4) { int xC = xCCorner + wC * ${u}; vec4 values = vec4( getValue(batch, xR, xC, d), getValue(batch, xR, xC + ${u}, d), getValue(batch, xR, xC + 2 * ${u}, d), getValue(batch, xR, xC + 3 * ${u}, d) ); ${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 + ${u}, d), initializationValue, initializationValue ); ${k} } else if (${w===3}) { vec4 values = vec4( getValue(batch, xR, xC, d), getValue(batch, xR, xC + ${u}, d), getValue(batch, xR, xC + 2 * ${u}, d), initializationValue ); ${k} } } setOutput(${A}); } `}},Jx=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,u=e.dilationDepth,c=e.dilationHeight,p=e.dilationWidth,d=e.effectiveFilterDepth,h=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;let x=t==="avg",A="0.0";if(x||(A="-1.0 / 1e-20"),n){let R=">=";this.userCode=` const ivec3 strides = ivec3(${o}, ${i}, ${l}); const ivec3 pads = ivec3(${m}, ${g}, ${y}); void main() { ivec5 coords = getOutputCoords(); int batch = coords.x; int ch = coords.u; ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; int xDCorner = xCorner.x; int xRCorner = xCorner.y; int xCCorner = xCorner.z; // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch). // ? = to be determined float minMaxValue = 0.0; float minMaxValueFound = 0.0; int minMaxPosition = 0; for (int wD = 0; wD < ${d}; wD += ${u}) { int xD = xDCorner + wD; if (xD < 0 || xD >= ${e.inDepth}) { continue; } for (int wR = 0; wR < ${h}; wR += ${c}) { int xR = xRCorner + wR; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${f}; wC += ${p}) { 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,C=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}, ${y}); 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 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(${A}); float avgValue = 0.0; count = 0.0; for (int wD = 0; wD < ${d}; wD += ${u}) { int xD = xDCorner + wD; if (xD < 0 || xD >= ${e.inDepth}) { continue; } for (int wR = 0; wR < ${h}; wR += ${c}) { int xR = xRCorner + wR; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${k}; wC += 4) { int xC = xCCorner + wC * ${p}; vec4 values = vec4( getValue(batch, xD, xR, xC, ch), getValue(batch, xD, xR, xC + ${p}, ch), getValue(batch, xD, xR, xC + 2 * ${p}, ch), getValue(batch, xD, xR, xC + 3 * ${p}, ch) ); ${N} } int xC = xCCorner + ${k}; if (${C===1}) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), initializationValue, initializationValue, initializationValue ); ${N} } else if (${C===2}) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), getValue(batch, xD, xR, xC + ${p}, ch), initializationValue, initializationValue ); ${N} } else if (${C===3}) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), getValue(batch, xD, xR, xC + ${p}, ch), getValue(batch, xD, xR, xC + 2 * ${p}, ch), initializationValue ); ${N} } } setOutput(${w}); } } `}};function Qse(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t;td(r,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,u=1;v.assert(T.eitherStridesOrDilationsAreOne(o,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);let c=T.computePool2DInfo(r.shape,a,o,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&v.arraysEqual(c.inShape,c.outShape))return Ls({inputs:{x:r},backend:n});let p=new wp(c,"avg",!1);return n.runWebGLProgram(p,[r],"float32")}var ere={kernelName:Ao,backendName:"webgl",kernelFunc:Qse};function tre(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l,dataFormat:u}=s,c=[1,1,1],p=T.computePool3DInfo(r.shape,a,o,c,i,l,u),d=new Jx(p,"avg",!1);return n.runWebGLProgram(d,[r],"float32")}var nre={kernelName:Np,backendName:"webgl",kernelFunc:tre},sre=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,u=i-1-e.padInfo.top,c=l-1-e.padInfo.left,p=1/(t*n);this.userCode=` const ivec2 pads = ivec2(${u}, ${c}); const float avgMultiplier = float(${p}); 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); } `}},rre=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,u=e.dilationWidth,c=e.effectiveFilterDepth,p=e.effectiveFilterHeight,d=e.effectiveFilterWidth,h=c-1-e.padInfo.front,f=p-1-e.padInfo.top,m=d-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 < ${c}; 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 < ${p}; 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 < ${d}; wC += ${u}) { 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 are(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,o=a,{filterSize:i,strides:l,pad:u,dimRoundingMode:c}=s,p=[1,1,1],d=T.computePool3DInfo(o.shape,i,l,p,u,c),h=new rre(d);return n.runWebGLProgram(h,[r],o.dtype)}var ore={kernelName:$m,backendName:"webgl",kernelFunc:are};function ire(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,o=a;td([r,a],"avgPoolGrad");let{filterSize:i,strides:l,pad:u}=s,c=T.computePool2DInfo(o.shape,i,l,1,u),p=new sre(c);return n.runWebGLProgram(p,[r],o.dtype)}var lre={kernelName:Dm,backendName:"webgl",kernelFunc:ire};function ure(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:o,transposeB:i}=s;return Sm({a:r,b:a,transposeA:o,transposeB:i,backend:n})}var cre={kernelName:xo,backendName:"webgl",kernelFunc:ure},dre=class{constructor(e,t,n,s,r,a){this.outputShape=[],this.variableNames=["x","mean","variance"],T.assertAndGetBroadcastShape(e,t),T.assertAndGetBroadcastShape(e,n);let o="0.0";s!=null&&(T.assertAndGetBroadcastShape(e,s),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="1.0";r!=null&&(T.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))); } `}},pre=class{constructor(e,t,n,s,r,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],T.assertAndGetBroadcastShape(e,t),T.assertAndGetBroadcastShape(e,n);let o="vec4(0.0)";s!=null&&(T.assertAndGetBroadcastShape(e,s),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="vec4(1.0)";r!=null&&(T.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); } `}},hre=({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 u=[s,r,a],c=null;o!=null&&(c=o.shape,u.push(o));let p=null;i!=null&&(p=i.shape,u.push(i));let d=U().getBool("WEBGL_PACK_NORMALIZATION")?new pre(s.shape,r.shape,a.shape,c,p,l):new dre(s.shape,r.shape,a.shape,c,p,l);return t.runWebGLProgram(d,u,u[0].dtype)},fre={kernelName:$o,backendName:"webgl",kernelFunc:hre},mre=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=Tt(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let n=gre(this.rank),s,r=e.map((a,o)=>`sourceLoc.${sy[o]} = start[${o}] + coords.${sy[o]};`);s=` ${t} sourceLoc; ${t} coords = getOutputCoords(); ${r.join(` `)} `,this.userCode=` void main() { ${s} setOutput(getSource(${n})); } `}},sy=["x","y","z","w","u","v"];function gre(e){if(e===1)return"sourceLoc";if(e<=6)return sy.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var yre=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=Tt(this.rank),n=os("coords",this.rank),s=os("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((u,c)=>`start[${c}]`).join()});`:e.map((u,c)=>`${s[c]} = ${n[c]} + start[${c}];`).join(` `);this.userCode=` void main() { ${t} coords = getOutputCoords(); ${t} sourceLoc; ${l} vec4 result = vec4(0.); ${o} ${i} setOutput(result); } `}};function Are(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=Gt.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 ld(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:o}=s,[i,l]=Gt.parseSliceParams(r,a,o);if(Gt.assertParamsValid(r,i,l),v.sizeFromShape(l)===0)return n.makeTensorInfo(l,r.dtype,[]);if(n.shouldExecuteOnCPU([r])||r.dtype==="string"){let p=n.texData.get(r.dataId),d=une(p.values,i,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,d)}let{isPacked:u}=n.texData.get(r.dataId),c=Gt.isSliceContinous(r.shape,i,l);if(u||!c){let p=U().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new yre(l):new mre(l),d=[i];return n.runWebGLProgram(p,[r],r.dtype,d)}return n.uploadToGPU(r.dataId),Are(r,i,l,n)}var xre={kernelName:Ul,backendName:"webgl",kernelFunc:ld},bre=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,A)=>x*A),l=T.getReshaped(r.shape,a,i),u=T.getPermuted(l.length,a.length),c=T.getReshapedPermuted(r.shape,a,i),p=T.getSliceBeginCoords(o,a.length),d=T.getSliceSize(c,o,a.length),h=[],f=be({inputs:{x:r},backend:n,attrs:{shape:l}}),m=is({inputs:{x:f},backend:n,attrs:{perm:u}}),g=be({inputs:{x:m},backend:n,attrs:{shape:c}}),y=ld({inputs:{x:g},backend:n,attrs:{begin:p,size:d}});return h.push(f),h.push(m),h.push(g),h.forEach(x=>n.disposeIntermediateTensorInfo(x)),y},vre={kernelName:hl,backendName:"webgl",kernelFunc:bre};function wre(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),u=f9(i,l,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,u)}var kre={kernelName:Pm,backendName:"webgl",kernelFunc:wre};function Sre(e){let{inputs:t,backend:n}=e,{s0:s,s1:r}=t,a=n.readSync(s.dataId),o=n.readSync(r.dataId),i=T.assertAndGetBroadcastShape(Array.from(a),Array.from(o));return n.makeTensorInfo([i.length],"int32",Int32Array.from(i))}var Ire={kernelName:Fm,backendName:"webgl",kernelFunc:Sre},Cre="return float(a != b);",E9=Wn({opSnippet:Cre,cpuKernelImpl:tne,dtype:"bool"}),Tre={kernelName:_l,backendName:"webgl",kernelFunc:E9};function Dh(e){let{inputs:t,backend:n}=e,{input:s}=t,r=n.texData.get(s.dataId);return Ls({inputs:{x:r.complexTensorInfos.real},backend:n})}var Nre={kernelName:Mp,backendName:"webgl",kernelFunc:Dh},Ere="return float(int(x));";function Rre(e,t){let n=new xa(e.shape,Ere),s=t.runWebGLProgram(n,[e],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}function ry(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dtype:a}=s;if(a==="complex64"){if(r.dtype==="complex64")return Ls({inputs:{x:r},backend:n});let o=Vt(r.shape),i=ry({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=gi({inputs:{real:i,imag:o},backend:n});return o.dispose(),n.disposeIntermediateTensorInfo(i),l}if(r.dtype==="complex64"){let o=Dh({inputs:{input:r},backend:n}),i=ry({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(o),i}if(!v.hasEncodingLoss(r.dtype,a)){let o=Ls({inputs:{x:r},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(n.shouldExecuteOnCPU([r])){let o=n.texData.get(r.dataId).values,[i,l,u]=Fte(o,r.shape,r.dtype,a);return n.makeTensorInfo(i,l,u)}if(a==="int32")return Rre(r,n);if(a==="bool"){let o=n.makeTensorInfo([],"bool",v.getTypedArrayFromDType("bool",1)),l=E9({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 _re={kernelName:bo,backendName:"webgl",kernelFunc:ry},I7="return ceil(x);",Dre=pt({opSnippet:I7,packedOpSnippet:I7,cpuKernelImpl:Ote}),$re={kernelName:vo,backendName:"webgl",kernelFunc:Dre},Pre=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)); } `}},Fre=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 Ore(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{clipValueMin:a,clipValueMax:o}=s,i;U().getBool("WEBGL_PACK_CLIP")?i=new Fre(r.shape):i=new Pre(r.shape);let l=[[a],[o]];return n.runWebGLProgram(i,[r],r.dtype,l)}var Mre={kernelName:Na,backendName:"webgl",kernelFunc:Ore},zre=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 C7(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function Lre(e){let{inputs:t,backend:n}=e,{x:s}=t,r=n.texData.get(s.dataId),a=new zre(s.shape),o=[C7(s,r.complexTensorInfos.real),C7(s,r.complexTensorInfos.imag)];return n.runWebGLProgram(a,o,o[0].dtype)}var Bre={kernelName:Rp,backendName:"webgl",kernelFunc:Lre},Wre=class{constructor(e){this.outputShape=[],this.outputShape=T.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}(${Bf(o,l,m)}), vec2(${Bf(u,l,m)})); }`}let d=i.length,h=i[i.length-1];p+=` return getChannel( getT${d}(${Bf(o,l,h)}), vec2(${Bf(u,l,h)}));`,this.userCode=` float getValue(${o.map(f=>"int "+f)}) { ${p} } 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 Bf(e,t,n){let s=e.indexOf(t);return e.map((a,o)=>o===s?`${a} - ${n}`:a).join()}function p2(e){let{inputs:t,backend:n}=e,{input:s}=t,r=n.texData.get(s.dataId);return Ls({inputs:{x:r.complexTensorInfos.imag},backend:n})}var Ure={kernelName:Pp,backendName:"webgl",kernelFunc:p2};function Qd(e,t,n){let s=e[0].dtype;if(s==="complex64"){let p=e.map(g=>Dh({inputs:{input:g},backend:n})),d=e.map(g=>p2({inputs:{input:g},backend:n})),h=Qd(p,t,n),f=Qd(d,t,n),m=gi({inputs:{real:h,imag:f},backend:n});return p.forEach(g=>n.disposeIntermediateTensorInfo(g)),d.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),m}let r=n.shouldExecuteOnCPU(e);if(s==="string"&&(r=!0),r){let p=e.map(x=>{let A=v.sizeFromShape(x.shape.slice(t));return be({inputs:{x},backend:n,attrs:{shape:[-1,A]}})}),d=p.map(x=>({vals:n.readSync(x.dataId),shape:x.shape})),h=T.computeOutShape(p.map(x=>x.shape),1),f=p[0].shape[0]===1,m=Mte(d,h,s,f),g=T.computeOutShape(e.map(x=>x.shape),t),y=n.makeTensorInfo(g,s,m);return p.forEach(x=>n.disposeIntermediateTensorInfo(x)),y}let a=U().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(e.length>a){let p=[];for(let h=0;h1){let p=new Vre(e.map(d=>d.shape),t);return n.runWebGLProgram(p,e,s)}let{tensors2D:o,outShape:i}=Gre(e,t,n),l=new Wre(o.map(p=>p.shape)),u=n.runWebGLProgram(l,o,s);o.forEach(p=>n.disposeIntermediateTensorInfo(p));let c=be({inputs:{x:u},attrs:{shape:i},backend:n});return n.disposeIntermediateTensorInfo(u),c}function Gre(e,t,n){let s=T.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>be({inputs:{x:a},attrs:{shape:[-1,v.sizeFromShape(a.shape.slice(t))]},backend:n})),outShape:s}}function R9(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s,a=v.parseAxisParam(r,t[0].shape)[0],o=t.map(u=>u.shape);T.assertParamsConsistent(o,a);let i=T.computeOutShape(t.map(u=>u.shape),a);if(v.sizeFromShape(i)===0)return n.makeTensorInfo(i,t[0].dtype,[]);let l=t.filter(u=>v.sizeFromShape(u.shape)>0);return l.length===1?Ls({inputs:{x:l[0]},backend:n}):Qd(l,a,n)}var Hre={kernelName:fl,backendName:"webgl",kernelFunc:R9},_9=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,u=e.dilationHeight,c=e.dilationWidth,p=e.filterHeight,d=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4,m=e.dataFormat==="channelsLast",g=m?1:2,y=m?2:3,x=m?3:1,A="",b="";n&&(s?A=`float activation(float a) { float b = getPreluActivationWeightsAtOutCoords(); ${n} }`:r?A=`float activation(float a) { float b = getLeakyreluAlphaAtOutCoords(); ${n} }`:A=` 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=` ${A} 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[${y}]) * strides - pads; int xRCorner = xRCCorner.x; int xCCorner = xRCCorner.y; // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; for (int wR = 0; wR < ${p}; wR++) { int xR = xRCorner + wR * ${u}; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${d}; wC++) { int xC = xCCorner + wC * ${c}; 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); } `}},jre=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,u=e.dilationWidth,c=e.filterDepth,p=e.filterHeight,d=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 < ${c}; wF++) { int xF = xFCorner + wF * ${i}; if (xF < 0 || xF >= ${e.inDepth}) { continue; } for (int wR = 0; wR < ${p}; wR++) { int xR = xRCorner + wR * ${l}; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${d}; wC++) { int xC = xCCorner + wC * ${u}; 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); } `}},D9=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=ds(this.outputShape.length);let a=e.padInfo.left,o=e.strideWidth,i=e.dilationWidth,l=e.filterHeight,u=e.filterWidth,c=u,p=` int xR; int xC; int xCOffset; vec4 wTexel; vec4 previous; vec4 final;`;for(let m=0;m=0 && xR < inDims[0]) { `;for(let m=0;m<(c+1)/2;m++){let g=m*2;if(p+=` xC = xCCorner + ${g*i}; `,o===1){if(g= 0 && xCOffset < inDims[1] && xTexelC${g}Ready == 0) { xTexelC${g} = 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${g}.zw = vec2(0.0); } xTexelC${g}Ready = 1; } `,i===1&&g>0?p+=` xC${g} = vec4(xTexelC${g-2}.zw, xTexelC${g}.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${g} = vec4(previous.zw, xTexelC${g}.xy); } else { xC${g} = vec4(0.0, 0.0, xTexelC${g}.xy); } `):p+=` if (xC >= 0 && xC < inDims[1] && xTexelC${g}Ready == 0) { xTexelC${g} = getX(batch, xR, xC, d1); if (xC + 1 >= inDims[1]) { xTexelC${g}.zw = vec2(0.0); } xTexelC${g}Ready = 1; } xC${g} = xTexelC${g}; `,g+1= 0 && xCOffset < inDims[1] && xTexelC${g+1}Ready == 0) { xTexelC${g+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${g+1}.zw = vec2(0.0); } xTexelC${g+1}Ready = 1; } `,i>1?p+=` xCOffset -= 2; if (xCOffset >= 0 && xCOffset < inDims[1]) { previous = getX(batch, xR, xCOffset, d1); xC${g+1} = vec4(previous.zw, xTexelC${g+1}.xy); } else { xC${g+1} = vec4(0.0, 0.0, xTexelC${g+1}.xy); } `:p+=` xC${g+1} = vec4(xTexelC${g}.zw, xTexelC${g+1}.xy); `):y===1?p+=` xC${g+1} = xTexelC${g}; `:p+=` xCOffset = xC + ${y}; if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g+1}Ready == 0) { xTexelC${g+1} = getX(batch, xR, xCOffset, d1); if (xCOffset + 1 >= inDims[1]) { xTexelC${g+1}.zw = vec2(0.0); } xTexelC${g+1}Ready = 1; } xC${g+1} = xTexelC${g+1}; `}}else g= 0 && xCOffset < inDims[1] && xTexelC${g}Ready == 0) { xTexelC${g} = 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${g}.zw = vec2(0.0); } xTexelC${g}Ready = 1; } if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${g+1}Ready == 0) { xTexelC${g+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${g+1}.zw = vec2(0.0); } xTexelC${g+1}Ready = 1; } xC${g} = vec4(xTexelC${g}.zw, xTexelC${g+1}.zw); `,g+1= 0 && xCOffset < inDims[1]) { final = getX(batch, xR, xCOffset, d1); } xC${g+1} = vec4(xTexelC${g+1}.xy, final.xy); `)):(p+=` if(xC >= 0 && xC < inDims[1] && xTexelC${g}Ready == 0) { xTexelC${g} = getX(batch, xR, xC, d1); if (xC + 1 >= inDims[1]) { xTexelC${g}.zw = vec2(0.0); } xTexelC${g}Ready = 1; } xCOffset = xC + strides[1]; if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g+1}Ready == 0) { xTexelC${g+1} = getX(batch, xR, xCOffset, d1); if (xCOffset + 1 >= inDims[1]) { xTexelC${g+1}.zw = vec2(0.); } xTexelC${g+1}Ready = 1; } xC${g} = vec4( xTexelC${g}.xy, xTexelC${g+1}.xy); `,g+1= 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[${u*2+c}] = getChannel( getA(rc.x, d0, int(innerDims.x), int(innerDims.y)), innerDims); } else { innerDims = vec2(d0, d1); result[${u*2+c}] = getChannel( getA(rc.x, ch, int(innerDims.x), int(innerDims.y)), innerDims); } } } } `;this.userCode=` void main() { ivec3 rc = getOutputCoords(); vec4 result = vec4(0); int blockIndex, pos, offsetY, d0, offsetX, d1, ch; vec2 innerDims; ${l} ${s.output} = result; } `}};function Im(e,t){let n=e.length;return n>=3?t?[...e.slice(0,-3),e[n-3]*e[n-2],e[n-1]]:[...e.slice(0,-3),e[n-3],e[n-2]*e[n-1]]:!t&&n===1&&e[0]>1?[e[0],1]:null}function $9({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let l=e.shape,u=s.texData.get(e.dataId),c=n.inChannels,p=l[0]*l[1]*l[2],d=n.outChannels,h=n.dataFormat==="channelsLast",f=!1,m=!1,g,y=[];if(a!=null){let b=Im(a.shape,h);b!=null&&(a=be({inputs:{x:a},backend:s,attrs:{shape:b}}),y.push(a))}if(r!=null){let b=Im(r.shape,h);b!=null&&(r=be({inputs:{x:r},backend:s,attrs:{shape:b}}),y.push(r))}if(!((p===1||d===1)&&c>I9)&&u.isPacked&&h&&u.texture!=null&&l[2]%2!==0&&v.arraysEqual(u.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=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,v.assert(bp(u.shape,w.shape),()=>`packed reshape ${u.shape} to ${w.shape} isn't free`);let C=be({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}});y.push(C);let N=Sm({a:w,b:C,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"),u.shape=k,R.shape=n.outShape,g=Ls({inputs:{x:N},backend:s}),g.shape=n.outShape,y.push(N)}else{let b=n.outHeight*n.outWidth,w=be({inputs:{x:e},backend:s,attrs:{shape:h?[n.batchSize,b,n.inChannels]:[n.batchSize,n.inChannels,b]}}),k=be({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}}),C=Sm({a:h?w:k,b:h?k:w,transposeA:!h,transposeB:m,backend:s,bias:r,activation:i,preluActivationWeights:a,leakyreluAlpha:o});g=be({inputs:{x:C},backend:s,attrs:{shape:n.outShape}}),y.push(w),y.push(k),y.push(C)}for(let b of y)s.disposeIntermediateTensorInfo(b);return g}function P9({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:l,filterHeight:u,inChannels:c,outWidth:p,outHeight:d,dataFormat:h}=n,f=h==="channelsLast",m=l*u*c,g=d*p,y=[n.batchSize,m,g],x=!0,A=!1,b=[];if(a!=null){let G=Im(a.shape,f);G!=null&&(a=be({inputs:{x:a},backend:s,attrs:{shape:G}}),b.push(a))}if(r!=null){let G=Im(r.shape,f);G!=null&&(r=be({inputs:{x:r},backend:s,attrs:{shape:G}}),b.push(r))}let w=be({inputs:{x:t},backend:s,attrs:{shape:[1,m,v.sizeFromShape(t.shape)/m]}});b.push(w);let k=new qre(y,n),C=[e.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],N=s.runWebGLProgram(k,[e],"float32",C),R=be({inputs:{x:N},backend:s,attrs:{shape:y}});b.push(N),b.push(R);let D=r!=null,E=a!=null,$=i==="leakyrelu",S=i?vp(i,!0):null,F=new S9(f?R.shape:w.shape,f?w.shape:R.shape,f?[n.batchSize,g,n.outChannels]:[n.batchSize,n.outChannels,g],x,A,D,S,E,$),z=f?[R,w]:[w,R];if(r&&z.push(r),E&&z.push(a),$){let G=s.makeTensorInfo([],"float32",v.createScalarValue(o,"float32"));z.push(G),b.push(G)}let V=s.runWebGLProgram(F,z,"float32"),j=be({inputs:{x:V},backend:s,attrs:{shape:n.outShape}});b.push(V);for(let G of b)s.disposeIntermediateTensorInfo(G);return j}function Xre(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dataFormat:l,dilations:u,dimRoundingMode:c}=s,p=T.convertConv2DDataFormat(l),d=T.computeConv2DInfo(r.shape,a.shape,o,u,i,c,!1,p),h;if(d.filterHeight===1&&d.filterWidth===1&&d.dilationHeight===1&&d.dilationWidth===1&&d.strideHeight===1&&d.strideWidth===1&&(d.padInfo.type==="SAME"||d.padInfo.type==="VALID"))h=$9({x:r,filter:a,convInfo:d,backend:n});else if(d.strideWidth<=2&&p==="channelsLast"&&U().getBool("WEBGL_EXP_CONV")){let m=new D9(d),g=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];h=n.runWebGLProgram(m,[r,a],"float32",g)}else if(U().getBool("WEBGL_CONV_IM2COL"))h=P9({x:r,filter:a,convInfo:d,backend:n});else{let m=new _9(d);h=n.runWebGLProgram(m,[r,a],"float32")}let f=be({inputs:{x:h},backend:n,attrs:{shape:d.outShape}});return n.disposeIntermediateTensorInfo(h),f}var Kre={kernelName:wo,backendName:"webgl",kernelFunc:Xre},Zre=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); } `}},Yre=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,u=a?2:3,c=a?3:1;this.userCode=` const ivec2 pads = ivec2(${o}, ${i}); void main() { ivec4 coords = getOutputCoords(); int batch = coords[0]; int d1 = coords[${c}]; ivec2 dyCorner = ivec2(coords[${l}], coords[${u}]) - pads; int dyRCorner = dyCorner.x; int dyCCorner = dyCorner.y; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; for (int wR = 0; wR < ${t}; wR++) { float dyR = float(dyRCorner + wR) / ${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); } `}},Jre=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); } `}},Qre=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,u=s-1-e.padInfo.left;this.userCode=` const ivec3 pads = ivec3(${i}, ${l}, ${u}); void main() { ivec5 coords = getOutputCoords(); int batch = coords.x; int d1 = coords.u; ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; int dyFCorner = dyCorner.x; int dyRCorner = dyCorner.y; int dyCCorner = dyCorner.z; float dotProd = 0.0; for (int wF = 0; wF < ${t}; wF++) { float dyF = float(dyFCorner + wF) / ${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 eae(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:o,pad:i,dataFormat:l,dimRoundingMode:u,filterShape:c}=s,p=T.convertConv2DDataFormat(l),d=T.computeConv2DInfo(r.shape,c,o,1,i,u,!1,p),h=new Zre(d);return n.runWebGLProgram(h,[r,a],"float32")}var tae={kernelName:Om,backendName:"webgl",kernelFunc:eae};function nae(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{inputShape:o,strides:i,pad:l,dataFormat:u,dimRoundingMode:c}=s,p=T.convertConv2DDataFormat(u),d=T.computeConv2DInfo(o,a.shape,i,1,l,c,!1,p),h=new Yre(d);return n.runWebGLProgram(h,[r,a],"float32")}var sae={kernelName:ko,backendName:"webgl",kernelFunc:nae};function rae(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dilations:l}=s,u=T.computeConv3DInfo(r.shape,a.shape,o,l,i),c=new jre(u);return n.runWebGLProgram(c,[r,a],"float32")}var aae={kernelName:_p,backendName:"webgl",kernelFunc:rae};function oae(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:o,pad:i,filterShape:l}=s,u=T.computeConv3DInfo(r.shape,l,o,1,i),c=new Jre(u);return n.runWebGLProgram(c,[r,a],"float32")}var iae={kernelName:Mm,backendName:"webgl",kernelFunc:oae};function lae(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{pad:o,strides:i,inputShape:l}=s,u=T.computeConv3DInfo(l,a.shape,i,1,o),c=new Qre(u);return n.runWebGLProgram(c,[r,a],"float32")}var uae={kernelName:zm,backendName:"webgl",kernelFunc:lae},cae=id+` return cos(x); `,dae=pt({opSnippet:cae}),pae={kernelName:So,backendName:"webgl",kernelFunc:dae},hae=` float e2x = exp(-x); return (e2x + 1.0 / e2x) / 2.0; `,fae=pt({opSnippet:hae}),mae={kernelName:Io,backendName:"webgl",kernelFunc:fae},gae=class{constructor(e,t,n,s,r){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[a,o,i,l]=e,[u]=t,[c,p]=n;this.outputShape=[u,c,p,l];let d=s==="bilinear"?1:0,[h,f]=[`${o-1}.0`,`${i-1}.0`],[m,g,y]=c>1?[`${(o-1)/(c-1)}`,"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${h}`],[x,A,b]=p>1?[`${(i-1)/(p-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 = ${A}; float in_y = ${y}; if( in_y < 0.0 || in_y > ${h} ) { setOutput(float(${r})); return; } float in_x = ${b}; if( in_x < 0.0 || in_x > ${f} ) { setOutput(float(${r})); return; } vec2 sourceFracIndexCR = vec2(in_x,in_y); if(${d} == 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); } } `}},yae=e=>{let{inputs:t,backend:n,attrs:s}=e,{image:r,boxes:a,boxInd:o}=t,{cropSize:i,method:l,extrapolationValue:u}=s,c=new gae(r.shape,a.shape,i,l,u);return n.runWebGLProgram(c,[r,a,o],"float32")},Aae={kernelName:gl,backendName:"webgl",kernelFunc:yae},kp;(function(e){e.Prod="*",e.Sum="+"})(kp||(kp={}));var T7=class{constructor(e,t,n,s){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];let r=this.outputShape.length,a=this.op===kp.Prod?"1.0":"0.0",o=n?a:`getX(${N7(r,"coords",this.op)})`,i=this.outputShape[this.outputShape.length-1],l="",u="";n?(l=s?`end != ${i-1}`:"end != 0",u=s?"end + 1":"end - 1"):(l=s?`end + pow2 < ${i}`:"end >= pow2",u=s?"end + pow2":"end - pow2"),this.userCode=` void main() { ${Tt(r)} coords = getOutputCoords(); int end = ${E7(r,"coords",this.op)}; float val = ${o}; int pow2 = int(pow(2.0, index)); if (${l}) { int idx = ${u}; ${E7(r,"coords",this.op)} = idx; val ${this.op}= getX(${N7(r,"coords",this.op)}); } setOutput(val); } `}};function N7(e,t,n){if(e===1)return`${t}`;if(e===2)return`${t}.x, ${t}.y`;if(e===3)return`${t}.x, ${t}.y, ${t}.z`;if(e===4)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function E7(e,t,n){if(e===1)return`${t}`;if(e===2)return`${t}.y`;if(e===3)return`${t}.z`;if(e===4)return`${t}.w`;throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function F9(e,t,n,s,r,a){let o=t.shape.length,i=T.getAxesPermutation([s],o),l=t;i!=null&&(l=is({inputs:{x:t},backend:n,attrs:{perm:i}}));let u=T.getInnerMostAxes(1,o)[0];if(u!==o-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${s}`);let c=l.shape[u],p=Ls({inputs:{x:l},backend:n});for(let d=0;d<=Math.ceil(Math.log2(c))-1;d++){let h=new T7(e,l.shape,!1,a),f=[[d]],m=p;p=n.runWebGLProgram(h,[p],p.dtype,f),n.disposeIntermediateTensorInfo(m)}if(r){let d=new T7(e,l.shape,r,a),h=p;p=n.runWebGLProgram(d,[p],p.dtype),n.disposeIntermediateTensorInfo(h)}if(i!=null){let d=T.getUndoAxesPermutation(i),h=is({inputs:{x:p},backend:n,attrs:{perm:d}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(l),h}return p}function xae(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:o,reverse:i}=s;return F9(kp.Prod,r,n,a,o,i)}var bae={kernelName:ml,backendName:"webgl",kernelFunc:xae};function vae(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:o,reverse:i}=s;return F9(kp.Sum,r,n,a,o,i)}var wae={kernelName:Co,backendName:"webgl",kernelFunc:vae};function kae(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),u=n.readSync(a.dataId),c=f9(l,u,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,c)}else if(r.shape.length===2){let l=n.bufferSync(r),u=n.bufferSync(a),c=Pte(l,u,o,i);return n.makeTensorInfo(c.shape,a.dtype,c.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}var Sae={kernelName:Lm,backendName:"webgl",kernelFunc:kae},Iae=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 Cae(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],u=o==="NHWC"?r.shape[2]:r.shape[3],c=o==="NHWC"?r.shape[3]:r.shape[1],p=l*a,d=u*a,h=c/(a*a),f=o==="NHWC"?[i,p,d,h]:[i,h,p,d],m=new Iae(f,a,o);return n.runWebGLProgram(m,[r],r.dtype)}var Tae={kernelName:yl,backendName:"webgl",kernelFunc:Cae},O9=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=ds(this.outputShape.length);let a=e.filterHeight,o=e.filterWidth,i=e.outChannels/e.inChannels,l="",u="";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} } `,u="result = activation(result);");let c=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; ${c} ${u} setOutput(result); } `}},M9=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=ds(this.outputShape.length);let a=e.outChannels/e.inChannels,o=e.padInfo.left,i=e.strideWidth,l=e.dilationWidth,u=e.filterHeight,c=e.filterWidth,p=c,d=` 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<(p+1)/2;g++){let y=g*2;if(d+=` xC = xCCorner + ${y*l}; `,i===1){if(y= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) { xTexelC${y} = getX(batch, xR, xCOffset, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if (xCOffset + 1 >= inDims[1]) { xTexelC${y}.zw = vec2(0.0); } xTexelC${y}Ready = 1; } `,l===1&&y>0?d+=` xC${y} = vec4(xTexelC${y-2}.zw, xTexelC${y}.xy); `:d+=` xCOffset = xC + 1 - 2; if (xCOffset >= 0 && xCOffset < inDims[1]) { previous = getX(batch, xR, xCOffset, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if (xCOffset + 1 >= inDims[1]) { previous.zw = vec2(0.0); } xC${y} = vec4(previous.zw, xTexelC${y}.xy); } else { xC${y} = vec4(0.0, 0.0, xTexelC${y}.xy); } `):d+=` if (xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) { xTexelC${y} = getX(batch, xR, xC, d1); if (xC + 1 >= inDims[1]) { xTexelC${y}.zw = vec2(0.0); } xTexelC${y}Ready = 1; } xC${y} = xTexelC${y}; `,y+1= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) { xTexelC${y+1} = getX(batch, xR, xCOffset, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if (xCOffset + 1 >= inDims[1]) { xTexelC${y+1}.zw = vec2(0.0); } xTexelC${y+1}Ready = 1; } `,l>1?d+=` xCOffset -= 2; if (xCOffset >= 0 && xCOffset < inDims[1]) { previous = getX(batch, xR, xCOffset, d1); xC${y+1} = vec4(previous.zw, xTexelC${y+1}.xy); } else { xC${y+1} = vec4(0.0, 0.0, xTexelC${y+1}.xy); } `:d+=` xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.xy); `):x===1?d+=` xC${y+1} = xTexelC${y}; `:d+=` xCOffset = xC + ${x}; if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) { xTexelC${y+1} = getX(batch, xR, xCOffset, d1); if (xCOffset + 1 >= inDims[1]) { xTexelC${y+1}.zw = vec2(0.0); } xTexelC${y+1}Ready = 1; } xC${y+1} = xTexelC${y+1}; `}}else y= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) { xTexelC${y} = getX(batch, xR, xCOffset, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if (xCOffset + 1 >= inDims[1]) { xTexelC${y}.zw = vec2(0.0); } xTexelC${y}Ready = 1; } if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${y+1}Ready == 0) { xTexelC${y+1} = getX(batch, xR, xC + 1, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if (xC + 2 >= inDims[1]) { xTexelC${y+1}.zw = vec2(0.0); } xTexelC${y+1}Ready = 1; } xC${y} = vec4(xTexelC${y}.zw, xTexelC${y+1}.zw); `,y+1= 0 && xCOffset < inDims[1]) { final = getX(batch, xR, xCOffset, d1); } xC${y+1} = vec4(xTexelC${y+1}.xy, final.xy); `)):(d+=` if(xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) { xTexelC${y} = getX(batch, xR, xC, d1); if (xC + 1 >= inDims[1]) { xTexelC${y}.zw = vec2(0.0); } xTexelC${y}Ready = 1; } xCOffset = xC + strides[1]; if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) { xTexelC${y+1} = getX(batch, xR, xCOffset, d1); if (xCOffset + 1 >= inDims[1]) { xTexelC${y+1}.zw = vec2(0.); } xTexelC${y+1}Ready = 1; } xC${y} = vec4( xTexelC${y}.xy, xTexelC${y+1}.xy); `,y+1`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);let p=T.computeConv2DInfo(r.shape,a.shape,o,c,i,u,!0),d;U().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels===1?d=new M9(p):d=new O9(p);let h=[[p.padInfo.top,p.padInfo.left],[p.strideHeight,p.strideWidth],[p.dilationHeight,p.dilationWidth],[p.inHeight,p.inWidth]];return n.runWebGLProgram(d,[r,a],"float32",h)}var Eae={kernelName:To,backendName:"webgl",kernelFunc:Nae},Rae=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); } `}},_ae=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 Dae(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:o,dilations:i,pad:l,dimRoundingMode:u,filterShape:c}=s,p=T.computeConv2DInfo(r.shape,c,o,i,l,u,!0),d=new Rae(p);return n.runWebGLProgram(d,[r,a],"float32")}var $ae={kernelName:Bm,backendName:"webgl",kernelFunc:Dae};function Pae(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{strides:o,dilations:i,pad:l,dimRoundingMode:u,inputShape:c}=s,p=T.computeConv2DInfo(c,a.shape,o,i,l,u,!0),d=new _ae(p);return n.runWebGLProgram(d,[r,a],"float32")}var Fae={kernelName:Wm,backendName:"webgl",kernelFunc:Pae},Oae=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 Mae(e){let{inputs:t,backend:n}=e,{x:s}=t,r=[...s.shape,...s.shape],a=v.sizeFromShape(s.shape),o=be({inputs:{x:s},backend:n,attrs:{shape:[a]}}),i=new Oae(a),l=n.runWebGLProgram(i,[o],o.dtype),u=be({inputs:{x:l},backend:n,attrs:{shape:r}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),u}var zae={kernelName:Vm,backendName:"webgl",kernelFunc:Mae},Lae=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:u}=e,{top:c,left:p}=s;this.userCode=` const ivec2 strides = ivec2(${r}, ${a}); const ivec2 pads = ivec2(${c}, ${p}); 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 * ${u}; 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 Bae(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dilations:l}=s,u=T.computeDilation2DInfo(r.shape,a.shape,o,i,"NHWC",l),c,p=new Lae(u);c=n.runWebGLProgram(p,[r,a],"float32");let d=be({inputs:{x:c},backend:n,attrs:{shape:u.outShape}});return n.disposeIntermediateTensorInfo(c),d}var Wae={kernelName:Dp,backendName:"webgl",kernelFunc:Bae};function Vae(e){let{inputs:t,backend:n,attrs:s}=e,{equation:r}=s,a=t,{allDims:o,summedDims:i,idDims:l}=T.decodeEinsumEquation(r,a.length);T.checkEinsumDimSizes(o.length,l,a);let{path:u,steps:c}=T.getEinsumComputePath(i,l),p=c.length,d=null,h=o.length,f=[];for(let m=0;m=0&&(d=d2({inputs:{x:d},backend:n,attrs:{axis:u[m]-(o.length-h),keepDims:!1}}),f.push(d)),h--)}for(let m of f)m!==d&&n.disposeIntermediateTensorInfo(m);return d}var Uae={kernelName:$p,backendName:"webgl",kernelFunc:Vae},Gae="return (x >= 0.0) ? x : (exp(x) - 1.0);",Hae=` 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; `,jae=pt({opSnippet:Gae,packedOpSnippet:Hae}),qae={kernelName:Eo,backendName:"webgl",kernelFunc:jae},Xae="return (b >= 1.0) ? a : a * (b + 1.0);",Kae=` vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.))); return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0)))); `,Zae=e=>{let{inputs:t,backend:n}=e,{dy:s,y:r}=t,a=U().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new _h(Kae,s.shape,r.shape):new hc(Xae,s.shape,r.shape);return n.runWebGLProgram(a,[s,r],s.dtype)},Yae={kernelName:Um,backendName:"webgl",kernelFunc:Zae},Jae=` return vec4(equal(a, b)); `,Qae="return float(a == b);",eoe=Wn({opSnippet:Qae,packedOpSnippet:Jae,dtype:"bool",cpuKernelImpl:zte}),toe={kernelName:Al,backendName:"webgl",kernelFunc:eoe},noe=` // Error function is calculated approximately with elementary function. // See "Handbook of Mathematical Functions with Formulas, // Graphs, and Mathematical Tables", Abramowitz and Stegun. float p = ${T.ERF_P}; float a1 = ${T.ERF_A1}; float a2 = ${T.ERF_A2}; float a3 = ${T.ERF_A3}; float a4 = ${T.ERF_A4}; float a5 = ${T.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)); `,soe=pt({opSnippet:noe}),roe={kernelName:Ic,backendName:"webgl",kernelFunc:soe},aoe=id+` return exp(x); `,ooe=` vec4 result = exp(x); bvec4 isNaN = isnan(x); result.r = isNaN.r ? x.r : result.r; result.g = isNaN.g ? x.g : result.g; result.b = isNaN.b ? x.b : result.b; result.a = isNaN.a ? x.a : result.a; return result; `,z9=pt({opSnippet:aoe,packedOpSnippet:ooe,cpuKernelImpl:Lte,dtype:"float32"}),ioe={kernelName:Ro,backendName:"webgl",kernelFunc:z9};function ay(e){let{inputs:t,attrs:n,backend:s}=e,{dim:r}=n,{input:a}=t,o=a.shape.length,i=a.shape.slice(),l=r;return r<0&&(v.assert(-(o+1)<=r,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+r+1),i.splice(l,0,1),be({inputs:{x:a},backend:s,attrs:{shape:i}})}var loe={kernelName:xl,backendName:"webgl",kernelFunc:ay},R7="return exp(x) - 1.0;",uoe=pt({opSnippet:R7,packedOpSnippet:R7,cpuKernelImpl:Bte}),coe={kernelName:bl,backendName:"webgl",kernelFunc:uoe},_7=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 L9(e,t,n){let s=n.texData.get(e.dataId),r=v.sizeFromShape(e.shape),a=e.shape[e.shape.length-1],o=r/a,i=be({inputs:{x:e},backend:n,attrs:{shape:[o,a]}}),l=i.shape,u=new _7("real",l,t),c=new _7("imag",l,t),p=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:l},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:l}],d=n.runWebGLProgram(u,p,"float32"),h=n.runWebGLProgram(c,p,"float32"),f=gi({inputs:{real:d,imag:h},backend:n});n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h);let m=be({inputs:{x:f},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(f),m}function doe(e){let{inputs:t,backend:n}=e,{input:s}=t;return L9(s,!1,n)}var poe={kernelName:Gm,backendName:"webgl",kernelFunc:doe},hoe=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 $h(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 hoe(s,r),i=[[r]];return t.runWebGLProgram(o,[],a,i)}}var foe={kernelName:Cc,backendName:"webgl",kernelFunc:$h},moe=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); } `}},goe={kernelName:vl,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,s=t,r=new moe(n.shape);return s.runWebGLProgram(r,[n],n.dtype)}},D7="return floor(x);",yoe=pt({opSnippet:D7,packedOpSnippet:D7,cpuKernelImpl:Wte}),Aoe={kernelName:_o,backendName:"webgl",kernelFunc:yoe},xoe=` 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; } `,boe=` 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); `,voe=Wn({opSnippet:xoe,packedOpSnippet:boe,dtype:"int32"}),woe={kernelName:Do,backendName:"webgl",kernelFunc:voe},koe=class{constructor(e){this.variableNames=["A"];let t=cs(),[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)); } `}},Soe=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=cs(),[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; } `}},Ioe={kernelName:lp,backendName:"webgl",kernelFunc:Coe},Bu,l3=U().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function Coe(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,u]=o?[r.videoWidth,r.videoHeight]:[r.width,r.height],c=[u,l],p=[u,l,a];if(i||o){let m=U().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(Bu==null||m!==l3)&&(l3=m,Bu=document.createElement("canvas").getContext("2d",{willReadFrequently:l3})),Bu.canvas.width=l,Bu.canvas.height=u,Bu.drawImage(r,0,0,l,u),r=Bu.canvas}let d=n.makeTensorInfo(c,"int32");n.texData.get(d.dataId).usage=Zs.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(d.dataId),r);let h=U().getBool("WEBGL_PACK")?new Soe(p):new koe(p),f=n.runWebGLProgram(h,[d],"int32");return n.disposeData(d.dataId),f}function Toe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=s,m=T.convertConv2DDataFormat(c),g=T.computeConv2DInfo(r.shape,a.shape,l,p,u,d,!1,m),y,x=[],A=o!=null,b=i!=null,w=h==="leakyrelu",k=()=>{let N=[r,a],R=(D,E)=>{if(E==="NCHW"&&D.shape.length===1&&D.shape[0]!==1){let $=be({inputs:{x:D},backend:n,attrs:{shape:[D.shape[0],1,1]}});return x.push($),$}return D};if(A&&N.push(R(o,c)),b&&N.push(R(i,c)),w){let D=n.makeTensorInfo([],"float32",v.createScalarValue(f,"float32"));N.push(D),x.push(D)}return N};if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))y=$9({x:r,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else if(g.strideWidth<=2&&m==="channelsLast"&&U().getBool("WEBGL_EXP_CONV")){let N=h?vp(h,!0):null,R=new D9(g,A,N,b,w),D=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],E=k();y=n.runWebGLProgram(R,E,"float32",D)}else if(U().getBool("WEBGL_CONV_IM2COL"))y=P9({x:r,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else{let N=h?vp(h,!1):null,R=new _9(g,A,N,b,w),D=k();y=n.runWebGLProgram(R,D,"float32")}let C=be({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return x.push(y),x.forEach(N=>n.disposeIntermediateTensorInfo(N)),C}var Noe={kernelName:so,backendName:"webgl",kernelFunc:Toe};function Eoe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:u,dilations:c,dimRoundingMode:p,activation:d,leakyreluAlpha:h}=s,f=[],m=c;m==null&&(m=[1,1]),v.assert(T.eitherStridesOrDilationsAreOne(l,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`);let g=T.computeConv2DInfo(r.shape,a.shape,l,m,u,p,!0),y=U().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,x=d?vp(d,y):null,A=[r,a],b=o!=null,w=i!=null,k=d==="leakyrelu";if(b&&A.push(o),w&&A.push(i),k){let D=n.makeTensorInfo([],"float32",v.createScalarValue(h,"float32"));A.push(D),f.push(D)}let C;y?C=new M9(g,b,x,w,k):C=new O9(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(C,A,"float32",N);return f.forEach(D=>n.disposeIntermediateTensorInfo(D)),R}var Roe={kernelName:ro,backendName:"webgl",kernelFunc:Eoe},_oe=class{constructor(e,t,n,s){this.sliceDim=e,this.strides=t,this.paramsShape=s,this.variableNames=["x","indices"],this.outputShape=n;let r=Tt(n.length),a=` int index;`;for(let o=0;o= ${this.paramsShape[o]}; flattenIndex += index * ${this.strides[o]};`;this.userCode=` void main() { ${r} coords = getOutputCoords(); int flattenIndex = 0; bool out_of_bounds = false; ${a} setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1])); } `}};function Doe(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,u,c,p]=T.prepareAndValidate(s,r),d=be({inputs:{x:r},backend:n,attrs:{shape:[u,o]}}),h=be({inputs:{x:s},backend:n,attrs:{shape:[v.sizeFromShape(s.shape)/c,c]}});if(n.shouldExecuteOnCPU([s,r])||s.dtype==="string"){let y=n.readSync(r.dataId),x=n.bufferSync(s),A=Vte(y,x,s.dtype,u,o,c,p,s.shape,i);return n.makeTensorInfo(l,s.dtype,A.values)}let f=new _oe(o,p,[u,c],s.shape),m=n.runWebGLProgram(f,[h,d],h.dtype),g=be({inputs:{x:m},backend:n,attrs:{shape:l}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),g}var $oe={kernelName:kl,backendName:"webgl",kernelFunc:Doe},Poe=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=Tt(this.rank),s=Foe(e,2);this.userCode=` void main() { ${n} resRC = getOutputCoords(); int index = int(getIndices(resRC.x, resRC.z)); float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0; setOutput(inBounds * getA(${s})); } `}};function Foe(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, ${A-1}]`)}}let u=T.segment_util.collectGatherOpShapeInfo(r,a,l,i),c=v.sizeFromShape(a.shape),p=[],d=be({inputs:{x:r},backend:n,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),h=be({inputs:{x:a},backend:n,attrs:{shape:[u.batchSize,c/u.batchSize]}});p.push(d),p.push(h);let f=[u.batchSize,u.outerSize,c/u.batchSize,u.sliceSize];if(n.shouldExecuteOnCPU([r,a])||r.dtype==="string"){let x=n.bufferSync(h),A=n.bufferSync(d),b=Ute(A,x,f);return p.forEach(w=>n.disposeIntermediateTensorInfo(w)),n.makeTensorInfo(u.outputShape,b.dtype,b.values)}let m=new Poe(d.shape,f),g=n.runWebGLProgram(m,[d,h],d.dtype);p.push(g);let y=be({inputs:{x:g},backend:n,attrs:{shape:u.outputShape}});return p.forEach(x=>n.disposeIntermediateTensorInfo(x)),y}var Ooe={kernelName:wl,backendName:"webgl",kernelFunc:B9},Moe="return float(a > b);",zoe=` return vec4(greaterThan(a, b)); `,Loe=Wn({opSnippet:Moe,packedOpSnippet:zoe,cpuKernelImpl:Gte,dtype:"bool"}),Boe={kernelName:Sl,backendName:"webgl",kernelFunc:Loe},Woe="return float(a >= b);",Voe=` return vec4(greaterThanEqual(a, b)); `,Uoe=Wn({opSnippet:Woe,packedOpSnippet:Voe,dtype:"bool",cpuKernelImpl:Hte}),Goe={kernelName:Po,backendName:"webgl",kernelFunc:Uoe};function Hoe(e){let{inputs:t,backend:n}=e,{input:s}=t;return L9(s,!0,n)}var joe={kernelName:Hm,backendName:"webgl",kernelFunc:Hoe},qoe="return float(!isnan(x) && !isinf(x));",Xoe=pt({opSnippet:qoe,dtype:"bool"}),Koe={kernelName:Tc,backendName:"webgl",kernelFunc:Xoe},Zoe="return float(isinf(x));",Yoe=pt({opSnippet:Zoe,dtype:"bool"}),Joe={kernelName:Nc,backendName:"webgl",kernelFunc:Yoe},Qoe="return float(isnan(x));",eie=pt({opSnippet:Qoe,dtype:"bool"}),tie={kernelName:Il,backendName:"webgl",kernelFunc:eie},nie="return float(a < b);",sie=` return vec4(lessThan(a, b)); `,rie=Wn({opSnippet:nie,packedOpSnippet:sie,cpuKernelImpl:jte,dtype:"bool"}),aie={kernelName:Cl,backendName:"webgl",kernelFunc:rie},oie="return float(a <= b);",iie=` return vec4(lessThanEqual(a, b)); `,lie=Wn({opSnippet:oie,packedOpSnippet:iie,cpuKernelImpl:qte,dtype:"bool"}),uie={kernelName:Tl,backendName:"webgl",kernelFunc:lie};function cie(e){let{backend:t,attrs:n}=e,{start:s,stop:r,num:a}=n,o=Xte(s,r,a);return t.makeTensorInfo([o.length],"float32",o)}var die={kernelName:jm,backendName:"webgl",kernelFunc:cie},pie=id+` return x < 0.0 ? 0./0. : log(x); `,hie=` vec4 result = log(x); bvec4 isNaN = isnan(x); result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r); result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g); result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b); result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a); return result; `,fie=pt({opSnippet:pie,packedOpSnippet:hie,cpuKernelImpl:Kte}),mie={kernelName:Mo,backendName:"webgl",kernelFunc:fie},gie=id+` return log(1.0 + x); `,yie=pt({opSnippet:gie}),Aie={kernelName:Ec,backendName:"webgl",kernelFunc:yie},xie="return float(a >= 1.0 && b >= 1.0);",bie=` return vec4( vec4(greaterThanEqual(a, vec4(1.0))) * vec4(greaterThanEqual(b, vec4(1.0)))); `,vie=Wn({opSnippet:xie,packedOpSnippet:bie,dtype:"bool"}),wie={kernelName:Nl,backendName:"webgl",kernelFunc:vie},kie="return float(!(x >= 1.0));",Sie=pt({opSnippet:kie}),Iie={kernelName:El,backendName:"webgl",kernelFunc:Sie},Cie="return float(a >= 1.0 || b >= 1.0);",Tie=` return min( vec4(greaterThanEqual(a, vec4(1.0))) + vec4(greaterThanEqual(b, vec4(1.0))), vec4(1.0)); `,Nie=Wn({opSnippet:Cie,packedOpSnippet:Tie,dtype:"bool"}),Eie={kernelName:Rc,backendName:"webgl",kernelFunc:Nie},Rie=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); } `}},_ie=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); } `}},Die=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{depthRadius:a,bias:o,alpha:i,beta:l}=s,u=U().getBool("WEBGL_PACK_NORMALIZATION")?new _ie(r.shape,a,o,i,l):new Rie(r.shape,a,o,i,l);return n.runWebGLProgram(u,[r],r.dtype)},$ie={kernelName:Fp,backendName:"webgl",kernelFunc:Die},Pie=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); } `}},Fie=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r,y:a,dy:o}=t,{depthRadius:i,bias:l,alpha:u,beta:c}=s,p=new Pie(r.shape,i,l,u,c);return n.runWebGLProgram(p,[r,a,o],r.dtype)},Oie={kernelName:qm,backendName:"webgl",kernelFunc:Fie};function Mie(e,t,n,s){let r=v.sizeFromShape(t),o=v.sizeFromShape(e.shape)/r,i=be({inputs:{x:e},attrs:{shape:[o,r]},backend:s}),l=pu(i,e.dtype,"max",s),u=be({inputs:{x:l},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(i),s.disposeIntermediateTensorInfo(l),u}function W9(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),u=l,c=T.getAxesPermutation(u,i),p=c!=null,d=n.shouldExecuteOnCPU([r]),h=r;if(p){if(d){let A=n.texData.get(h.dataId).values,b=new Array(i);for(let C=0;C`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);let c=T.computePool2DInfo(r.shape,a,o,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&v.arraysEqual(c.inShape,c.outShape))return Ls({inputs:{x:r},backend:n});let p=new wp(c,"max",!1);return n.runWebGLProgram(p,[r],r.dtype)}var Gie={kernelName:Bo,backendName:"webgl",kernelFunc:Uie};function Hie(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dataFormat:l,dimRoundingMode:u}=s,c=[1,1,1],p=T.computePool3DInfo(r.shape,a,o,c,i,u,l),d=new Jx(p,"max",!1);return n.runWebGLProgram(d,[r],r.dtype)}var jie={kernelName:Op,backendName:"webgl",kernelFunc:Hie},qie=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); } `}},Xie=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,u=e.effectiveFilterWidth,c=i-1-e.padInfo.front,p=l-1-e.padInfo.top,d=u-1-e.padInfo.left,h=i*l*u-1;this.userCode=` const ivec3 pads = ivec3(${c}, ${p}, ${d}); 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 < ${u}; 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} * ${u} + wR * ${u} + wC; float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); dotProd += dyValue * mask; } } } setOutput(dotProd); } `}};function Kie(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,o=a,{filterSize:i,strides:l,pad:u,dimRoundingMode:c}=s,p=[1,1,1],d=T.computePool3DInfo(o.shape,i,l,p,u,c),h=new Jx(d,"max",!0),f=n.runWebGLProgram(h,[o],o.dtype),m=new Xie(d),g=n.runWebGLProgram(m,[r,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}var Zie={kernelName:Km,backendName:"webgl",kernelFunc:Kie};function Yie(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a,output:o}=t,i=a;td([a,o],"maxPoolGrad");let{filterSize:l,strides:u,pad:c,dimRoundingMode:p}=s,d=T.computePool2DInfo(i.shape,l,u,1,c,p),h=!0,f=new wp(d,"max",h),m=n.runWebGLProgram(f,[i],i.dtype),g=new qie(d),y=n.runWebGLProgram(g,[r,m],i.dtype);return n.disposeIntermediateTensorInfo(m),y}var Jie={kernelName:Xm,backendName:"webgl",kernelFunc:Yie};function Qie(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 ele={kernelName:Zm,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 u=[1,1];v.assert(T.eitherStridesOrDilationsAreOne(a,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=T.computePool2DInfo(s.shape,r,a,u,o),[p,d]=Qie(s,i,c,l);return[p,d]}};function tle(e,t,n,s){let r=v.sizeFromShape(t),o=v.sizeFromShape(e.shape)/r,i=be({inputs:{x:e},attrs:{shape:[o,r]},backend:s}),l=pu(i,"float32","mean",s),u=be({inputs:{x:l},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(i),s.disposeIntermediateTensorInfo(l),u}var nle={kernelName:Wo,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),u=l,c=T.getAxesPermutation(u,i),p=c!=null,d=o.shouldExecuteOnCPU([s]),h=[],f=s;if(p){if(d){let b=o.texData.get(f.dataId).values,w=new Array(i);for(let N=0;Nu[0]+e[c]+u[1]);let s=e.length,r=Tt(s),a=t.map(u=>u[0]).join(","),o=t.map((u,c)=>u[0]+e[c]).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})); } `}},cle=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=Tt(s),a=t.map(h=>h[0]).join(","),o=t.map((h,f)=>h[0]+e[f]).join(","),i=os("rc",s),l=os("source",s),u=`${i[s-1]} < ${this.outputShape[s-1]}`,c=s===1?"source":`vec2(${l.slice(-2).join()})`,p=n==="reflect"?0:1,d="";if(s===1){let h=` ${r} source = rc; if (source < start) { source = start * 2 - source - ${p}; } else if (source >= end) { source = (end - 1) * 2 - source + ${p}; } source -= start; `;d=` ${r} rc = outputLoc; ${h} result[0] = getChannel(getX(${l.join()}), ${c}); ${i[s-1]} += 1; if(${u}) { ${h} result[1] = getChannel(getX(${l.join()}), ${c}); } `}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 - ${p}) + gte * ((end - 1) * 2 - source + ${p}); source -= start; `;d=` ${r} rc = outputLoc; ${h} result[0] = getChannel(getX(${l.join()}), ${c}); ${i[s-1]} += 1; if(${u}) { ${h} result[1] = getChannel(getX(${l.join()}), ${c}); } rc = outputLoc; ${i[s-2]} += 1; if(${i[s-2]} < ${this.outputShape[s-2]}) { ${h} result[2] = getChannel(getX(${l.join()}), ${c}); ${i[s-1]} += 1; if(${u}) { ${h} result[3] = getChannel(getX(${l.join()}), ${c}); } } `}this.userCode=` const ${r} start = ${r}(${a}); const ${r} end = ${r}(${o}); void main() { ${r} outputLoc = getOutputCoords(); vec4 result = vec4(0.); ${d} setOutput(result); } `}},dle=({inputs:e,backend:t,attrs:n})=>{let{x:s}=e,{paddings:r,mode:a}=n,o=U().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new cle(s.shape,r,a):new ule(s.shape,r,a);return t.runWebGLProgram(o,[s],s.dtype)},ple={kernelName:Go,backendName:"webgl",kernelFunc:dle},hle=`if (b == 0.0) return NAN; return mod(a, b);`,fle=` vec4 result = mod(a, b); bvec4 isNaN = equal(b, vec4(0.0)); `+Rh+` return result; `,mle=Wn({opSnippet:hle,packedOpSnippet:fle}),gle={kernelName:_c,backendName:"webgl",kernelFunc:mle},yle=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})); } `}},Ale=` if (a == b) { return 1.0; }; return a / b;`,xle=` // 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; `,V9=Wn({opSnippet:Ale,packedOpSnippet:xle,checkOutOfBounds:!0}),ble={kernelName:No,backendName:"webgl",kernelFunc:V9},$7="return a - b;",U9=Wn({opSnippet:$7,packedOpSnippet:$7,supportsComplex:!0,cpuKernelImpl:yne}),vle={kernelName:ii,backendName:"webgl",kernelFunc:U9};function G9(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{dim:a}=s,o=v.parseAxisParam([a],r.shape),i=W9({inputs:{x:r},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),l=T.expandShapeToKeepDim(i.shape,o),u=be({inputs:{x:i},backend:n,attrs:{shape:l}}),c=U9({inputs:{a:r,b:u},backend:n}),p=z9({inputs:{x:c},backend:n}),d=d2({inputs:{x:p},backend:n,attrs:{axis:o,keepDims:!1}}),h=be({inputs:{x:d},backend:n,attrs:{shape:l}}),f=V9({inputs:{a:p,b:h},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),f}var wle={kernelName:ai,backendName:"webgl",kernelFunc:G9};function kle(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{numSamples:a,seed:o,normalized:i}=s,l=i?r:G9({inputs:{logits:r},backend:n,attrs:{dim:r.shape.length-1}}),u=l.shape[0],c=l.shape[1],p=new yle(u,c,a),d=[[o]],h=n.runWebGLProgram(p,[l],"int32",d);return i||n.disposeIntermediateTensorInfo(l),h}var Sle={kernelName:Ym,backendName:"webgl",kernelFunc:kle},Ile=br+` return -x; `,Cle=` vec4 result = -x; bvec4 isNaN = isnan(x); result.r = isNaN.r ? x.r : result.r; result.g = isNaN.g ? x.g : result.g; result.b = isNaN.b ? x.b : result.b; result.a = isNaN.a ? x.a : result.a; return result; `;function Tle(e){let{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])){let a=n.texData.get(s.dataId),[o,i]=ene(a.values,s.shape,s.dtype);return n.makeTensorInfo(i,s.dtype,o)}let r;return U().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new ji(s.shape,Cle):r=new xa(s.shape,Ile),n.runWebGLProgram(r,[s],s.dtype)}var Nle={kernelName:Rl,backendName:"webgl",kernelFunc:Tle},Ele=Ar.nonMaxSuppressionV3Impl;function Rle(e){T.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,u=n.readSync(r.dataId),c=n.readSync(a.dataId),{selectedIndices:p}=Ele(u,c,o,i,l);return n.makeTensorInfo([p.length],"int32",new Int32Array(p))}var _le={kernelName:Dl,backendName:"webgl",kernelFunc:Rle},Dle=Ar.nonMaxSuppressionV4Impl;function $le(e){T.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:u}=s,c=n.readSync(r.dataId),p=n.readSync(a.dataId),{selectedIndices:d,validOutputs:h}=Dle(c,p,o,i,l,u);return[n.makeTensorInfo([d.length],"int32",new Int32Array(d)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var Ple={kernelName:Dc,backendName:"webgl",kernelFunc:$le},Fle=Ar.nonMaxSuppressionV5Impl;function Ole(e){T.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:u}=s,c=n.readSync(r.dataId),p=n.readSync(a.dataId),d=o,h=i,f=l,m=u,{selectedIndices:g,selectedScores:y}=Fle(c,p,d,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var Mle={kernelName:$l,backendName:"webgl",kernelFunc:Ole},zle=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))); } `}},Lle=e=>{let{inputs:t,backend:n,attrs:s}=e,{indices:r}=t,{dtype:a,depth:o,onValue:i,offValue:l}=s,u=v.sizeFromShape(r.shape),c=new zle(u,o,i,l),p=be({inputs:{x:r},backend:n,attrs:{shape:[u]}}),d=n.runWebGLProgram(c,[p],a);n.disposeIntermediateTensorInfo(p);let h=[...r.shape,o],f=be({inputs:{x:d},backend:n,attrs:{shape:h}});return n.disposeIntermediateTensorInfo(d),f},Ble={kernelName:Fl,backendName:"webgl",kernelFunc:Lle};function Cm(e){let{inputs:t,backend:n}=e,{x:s}=t;if(s.dtype==="complex64"){let r=Dh({inputs:{input:s},backend:n}),a=Cm({inputs:{x:r},backend:n}),o=p2({inputs:{input:s},backend:n}),i=Cm({inputs:{x:o},backend:n}),l=gi({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),l}else return $h({attrs:{shape:s.shape,dtype:s.dtype,value:s.dtype==="string"?"":0},backend:n})}var Wle={kernelName:Jl,backendName:"webgl",kernelFunc:Cm};function H9(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=Dh({inputs:{input:s},backend:n}),a=H9({inputs:{x:r},backend:n}),o=p2({inputs:{input:s},backend:n}),i=Cm({inputs:{x:o},backend:n}),l=gi({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),l}else return $h({attrs:{shape:s.shape,dtype:s.dtype,value:1},backend:n})}var Vle={kernelName:Pl,backendName:"webgl",kernelFunc:H9};function Ule(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(t.length===1)return ay({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let a=t[0].shape,o=t[0].dtype;t.forEach(c=>{v.assertShapesMatch(a,c.shape,"All tensors passed to stack must have matching shapes"),v.assert(o===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(c=>{let p=ay({inputs:{input:c},backend:n,attrs:{dim:r}});return i.push(p),p}),u=R9({inputs:l,backend:n,attrs:{axis:r}});return i.forEach(c=>n.disposeIntermediateTensorInfo(c)),u}var Gle={kernelName:Ol,backendName:"webgl",kernelFunc:Ule},Hle=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((l,u)=>l[0]+e[u]+l[1]);let s=e.length,r=Tt(s),a=t.map(l=>l[0]).join(","),o=t.map((l,u)=>l[0]+e[u]).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})); } } `}},jle=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=Tt(s),a=t.map(f=>f[0]).join(","),o=t.map((f,m)=>f[0]+e[m]).join(","),i=os("rc",s),l=os("source",s),u=`${i[s-1]} < ${this.outputShape[s-1]}`,c=s===1?"source":`vec2(${l.slice(-2).join()})`,p=[`${r} rc = outputLoc;`,`${i[s-1]} += 1; if(${u}) { `,s===1?"":`} rc = outputLoc; ${i[s-2]} += 1; if(${i[s-2]} < ${this.outputShape[s-2]}) {`,s===1?"":` ${i[s-1]} += 1; if(${u}) {`],d=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 u=a.map((c,p)=>c[0]+r.shape[p]+c[1]);return $h({backend:n,attrs:{shape:u,value:o,dtype:r.dtype}})}let i=U().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new jle(r.shape,a,o):new Hle(r.shape,a,o),l=[[o]];return n.runWebGLProgram(i,[r],r.dtype,l)},qle={kernelName:jo,backendName:"webgl",kernelFunc:j9},Xle=` 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); `,Kle=` // 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; bvec4 isNaN1 = lessThan(a, vec4(0.0)); bvec4 isNaN2 = lessThan(floor(b), b); bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w); `+Rh+` return result; `,Zle=Wn({opSnippet:Xle,packedOpSnippet:Kle}),Yle={kernelName:qo,backendName:"webgl",kernelFunc:Zle};function Jle(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s,i=r.shape.length,l=[],u=v.parseAxisParam(a,r.shape),c=u,p=T.getAxesPermutation(c,i),d=r;p!=null&&(d=is({inputs:{x:r},backend:n,attrs:{perm:p}}),c=T.getInnerMostAxes(c.length,i),l.push(d)),T.assertAxesAreInnerMostDims("prod",c,i);let h;if(n.shouldExecuteOnCPU([d])){let f=n.texData.get(d.dataId).values,{outVals:m,outShape:g,outDtype:y}=nne(d.shape,d.dtype,f,c);h=n.makeTensorInfo(g,y,m)}else{let[f,m]=T.computeOutAndReduceShapes(d.shape,c),g=v.sizeFromShape(m),y=be({inputs:{x:d},backend:n,attrs:{shape:[-1,g]}}),x=qp(r.dtype),A=pu(y,x,"prod",n);h=be({inputs:{x:A},backend:n,attrs:{shape:f}}),l.push(y),l.push(A)}if(o){l.push(h);let f=T.expandShapeToKeepDim(h.shape,u);h=be({inputs:{x:h},backend:n,attrs:{shape:f}})}return l.forEach(f=>n.disposeIntermediateTensorInfo(f)),h}var Qle={kernelName:Ko,backendName:"webgl",kernelFunc:Jle};function eue(e){let{inputs:t,backend:n,attrs:s}=e,{paramsNestedSplits:r,paramsDenseValues:a,indices:o}=t,{outputRaggedRank:i}=s,l=r.map(y=>n.readSync(y.dataId)),u=r.map(y=>y.shape),c=n.readSync(a.dataId),p=n.readSync(o.dataId),[d,h,f]=sne(l,u,c,a.shape,a.dtype,p,o.shape,i),m=d.map(y=>n.makeTensorInfo([y.length],"int32",y)),g=n.makeTensorInfo(f,a.dtype,h);return m.concat([g])}var tue={kernelName:Jm,backendName:"webgl",kernelFunc:eue};function nue(e){let{inputs:t,backend:n,attrs:s}=e,{shape:r,values:a,defaultValue:o,rowPartitionTensors:i}=t,{rowPartitionTypes:l}=s,u=n.readSync(r.dataId),c=n.readSync(a.dataId),p=n.readSync(o.dataId),d=i.map(g=>n.readSync(g.dataId)),h=i.map(g=>g.shape),[f,m]=rne(u,r.shape,c,a.shape,a.dtype,p,o.shape,d,h,l);return n.makeTensorInfo(f,a.dtype,m)}var sue={kernelName:Qm,backendName:"webgl",kernelFunc:nue},q9=e=>{let{backend:t,attrs:n}=e,{start:s,stop:r,step:a,dtype:o}=n,i=ane(s,r,a,o);return t.makeTensorInfo([i.length],o,i)},rue={kernelName:$c,backendName:"webgl",kernelFunc:q9},aue="return 1.0 / x;",oue=pt({opSnippet:aue}),iue={kernelName:Ml,backendName:"webgl",kernelFunc:oue},lue=br+` return (x < 0.0) ? 0.0 : x; `,uue=` 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; `,cue=pt({opSnippet:lue,packedOpSnippet:uue}),due={kernelName:Zo,backendName:"webgl",kernelFunc:cue},pue=br+` return (x < 0.0) ? 0.0 : min(6.0, x); `,hue=` 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; `,fue=pt({opSnippet:pue,packedOpSnippet:hue}),mue={kernelName:Qo,backendName:"webgl",kernelFunc:fue},gue=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 u=[s&&t>1?o-1:o,s&&n>1?i-1:i],c=[s&&t>1?t-1:t,s&&n>1?n-1:n],p;r?p="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` const vec2 effectiveInputOverOutputRatioRC = vec2( ${u[0]/c[0]}, ${u[1]/c[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 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); } `}},yue=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 u=[s&&t>1?o-1:o,s&&n>1?i-1:i],c=[s&&t>1?t-1:t,s&&n>1?n-1:n],p;r?p="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` const vec3 effectiveInputOverOutputRatioRC = vec3( ${u[0]/c[0]}, ${u[1]/c[1]}, ${u[1]/c[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 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 Aue(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:o,size:i}=s,[l,u]=i,c=U().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new yue(r.shape,l,u,a,o):new gue(r.shape,l,u,a,o);return n.runWebGLProgram(c,[r],"float32")}var xue={kernelName:Jo,backendName:"webgl",kernelFunc:Aue},bue=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],u=i[0]/l[0],c=i[1]/l[1],p=1/u,d=1/c,h=Math.ceil(p)*2+2,f=Math.ceil(d)*2+2;this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; int r = coords[1]; int c = coords[2]; float accumulator = 0.0; const float heightScale = float(${u}); const float widthScale = float(${c}); const float invHeightScale = float(${p}); const float invWidthScale = float(${d}); 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 vue(e){let{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:o}=s,i=new bue(a.shape,r.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var wue={kernelName:t0,backendName:"webgl",kernelFunc:vue},kue=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 u=[s&&t>1?o-1:o,s&&n>1?i-1:i],c=[s&&t>1?t-1:t,s&&n>1?n-1:n],p=s?"0.5":"0.0",d;r?d="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` const vec2 effectiveInputOverOutputRatioRC = vec2( ${u[0]/c[0]}, ${u[1]/c[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 coordinators of nearest neighbor point. ivec2 sourceNearestRC = ivec2( min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${p}))); float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d); setOutput(newValue); } `}},Sue=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 u=[s&&t>1?o-1:o,s&&n>1?i-1:i],c=[s&&t>1?t-1:t,s&&n>1?n-1:n],p=s?"0.5":"0.0",d;r?d="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` const vec3 effectiveInputOverOutputRatioRC = vec3( ${u[0]/c[0]}, ${u[1]/c[1]}, ${u[1]/c[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 coordinators of nearest neighbor point. ivec3 sourceNearestRC = ivec3( min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${p}))); // 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 Iue(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:o,size:i}=s,[l,u]=i,c=U().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Sue(r.shape,l,u,a,o):new kue(r.shape,l,u,a,o);return n.runWebGLProgram(c,[r],r.dtype)}var Cue={kernelName:Yo,backendName:"webgl",kernelFunc:Iue},Tue=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],u=i[0]/l[0],c=i[1]/l[1],p=1/u,d=1/c,h=Math.ceil(p)*2+2,f=Math.ceil(d)*2+2;this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; int r = coords[1]; int c = coords[2]; float accumulator = 0.0; const float heightScale = float(${u}); const float widthScale = float(${c}); const float invHeightScale = float(${p}); const float invWidthScale = float(${d}); 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 Nue(e){let{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:o}=s,i=new Tue(a.shape,r.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var Eue={kernelName:e0,backendName:"webgl",kernelFunc:Nue},Rue=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=Tt(n);this.userCode=` void main() { ${a} coords = getOutputCoords(); setOutput(getX(${r})); } `}},_ue=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=os("rc",n),r=`${s[n-1]} + 1 < ${this.outputShape[n-1]}`,a=`${s[n-2]} + 1 < ${this.outputShape[n-2]}`,o=Tt(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 = ${u(s.slice())}; if(${r}) { result.a = ${c(s.slice())}; } } setOutput(result); } `;function i(h){return p(h)}function l(h){return h[n-1]="("+h[n-1]+" + 1)",p(h)}function u(h){return h[n-2]="("+h[n-2]+" + 1)",p(h)}function c(h){return h[n-1]="("+h[n-1]+" + 1)",h[n-2]="("+h[n-2]+" + 1)",p(h)}function p(h){let f=e.map((y,x)=>d(x,h)),m=f.join(","),g=f.slice(-2).join(",");return`getChannel(getX(${m}), vec2(${g}))`}function d(h,f){return t.indexOf(h)!==-1&&e[h]!==1?`${e[h]} - ${f[h]} - 1`:`${f[h]}`}}};function Due(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 Ls({inputs:{x:r},backend:n});let l=U().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new _ue(r.shape,i):new Rue(r.shape,i);return n.runWebGLProgram(l,[r],r.dtype)}var $ue={kernelName:Ll,backendName:"webgl",kernelFunc:Due},Pue=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); } `}},Fue={kernelName:Ql,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:s}=e,{radians:r,fillValue:a,center:o}=t,i=n,l=new Pue(s.shape,a),[u,c]=T.getImageCenter(o,s.shape[1],s.shape[2]),p=[[u,c,Math.sin(r),Math.cos(r)]];return i.runWebGLProgram(l,[s],s.dtype,p)}},Oue=` // 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; } } `,Mue=pt({opSnippet:Oue}),zue={kernelName:Bl,backendName:"webgl",kernelFunc:Mue},Lue="return inversesqrt(x);",Bue=pt({opSnippet:Lue,cpuKernelImpl:one}),Wue={kernelName:ei,backendName:"webgl",kernelFunc:Bue},X9=class{constructor(e,t,n,s,r,a,o=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;let i=Tt(r.length),l=Tt(a.length),u="";n===1?u="i":n===2&&(u="i, j");let c=`getIndices(${u})`,p="";s===1?p="i":s===2&&(p="i, coords[1]");let d=`getUpdates(${p})`,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(${c}); flattenedIndex += index * ${h}; } if (flattenedIndex == coords[0]) { sum += ${d}; found = true; } } setOutput(mix(getDefaultValue(), sum, float(found))); } `}};function Vue(e){let{inputs:t,backend:n,attrs:s}=e,{indices:r,updates:a}=t,{shape:o}=s,{sliceRank:i,numUpdates:l,sliceSize:u,strides:c,outputSize:p}=T.calculateShapes(a,r,o),d=[p/u,u];if(p===0)return n.makeTensorInfo(o,r.dtype);let h=be({inputs:{x:r},backend:n,attrs:{shape:[l,i]}}),f=be({inputs:{x:a},backend:n,attrs:{shape:[l,u]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new X9(l,i,h.shape.length,f.shape.length,c,d),y=n.runWebGLProgram(g,[f,h,m],f.dtype),x=be({inputs:{x:y},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(m),x}var Uue={kernelName:Wl,backendName:"webgl",kernelFunc:Vue},Gue=class{constructor(e,t,n,s){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,n];let r="while (left < right) {",a=`for (int i = 0; i < ${Math.ceil(Math.log2(t+1))}; ++i) { if (left >= right) break;`,o=U().getNumber("WEBGL_VERSION")===2?r:a,i=s==="left"?"<":"<=";this.userCode=` int findBound(int batch, float value) { int left = 0; int right = numInputs; int mid; ${o} mid = (left + right) / 2; if (getSortedSequence(batch, mid) ${i} value) { left = mid + 1; } else { right = mid; } } return right; } void main() { ivec2 coords = getOutputCoords(); int batch = coords[0]; int valueIndex = coords[1]; float value = getValues(batch, valueIndex); setOutput(float(findBound(batch, value))); } `}};function Hue(e){let{inputs:t,backend:n,attrs:s}=e,{sortedSequence:r,values:a}=t,{side:o}=s,i=new Gue(r.shape[0],r.shape[1],a.shape[1],o),l=[[r.shape[1]]];return n.runWebGLProgram(i,[r,a],"int32",l)}var jue={kernelName:n0,backendName:"webgl",kernelFunc:Hue},que=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 u=0;u= 1.0) { setOutput(getA(${r})); } else { setOutput(getB(${r})); } } `}};function Xue(e){let{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t,o=new que(s.shape.length,r.shape,r.shape.length);return n.runWebGLProgram(o,[s,r,a],jn(r.dtype,a.dtype))}var Kue={kernelName:Vl,backendName:"webgl",kernelFunc:Xue},Zue=` // Stable and Attracting Fixed Point (0, 1) for Normalized Weights. // see: https://arxiv.org/abs/1706.02515 float scaleAlpha = ${T.SELU_SCALEALPHA}; float scale = ${T.SELU_SCALE}; return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0); `,Yue=pt({opSnippet:Zue}),Jue={kernelName:Pc,backendName:"webgl",kernelFunc:Yue},Que=id+` return 1.0 / (1.0 + exp(-1.0 * x)); `,ece=` vec4 result = 1.0 / (1.0 + exp(-1.0 * x)); bvec4 isNaN = isnan(x); result.r = isNaN.r ? x.r : result.r; result.g = isNaN.g ? x.g : result.g; result.b = isNaN.b ? x.b : result.b; result.a = isNaN.a ? x.a : result.a; return result; `,tce=pt({opSnippet:Que,packedOpSnippet:ece,cpuKernelImpl:lne}),nce={kernelName:ni,backendName:"webgl",kernelFunc:tce},sce=` if (isnan(x)) { return 0.0; } return sign(x); `,rce=pt({opSnippet:sce}),ace={kernelName:Fc,backendName:"webgl",kernelFunc:rce},oce=id+` return sin(x); `,ice=pt({opSnippet:oce}),lce={kernelName:ti,backendName:"webgl",kernelFunc:ice},uce=` float e2x = exp(x); return (e2x - 1.0 / e2x) / 2.0; `,cce=pt({opSnippet:uce}),dce={kernelName:Gl,backendName:"webgl",kernelFunc:cce},pce=` 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; `,hce=pt({opSnippet:pce}),fce={kernelName:Oc,backendName:"webgl",kernelFunc:hce},mce=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:o}=s;v.assert(r.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((y,x)=>y*x),l=[[0,0]];l.push(...o);for(let y=1+a.length;yn.disposeIntermediateTensorInfo(y)),g},gce={kernelName:Hl,backendName:"webgl",kernelFunc:mce};function yce(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),u=n.readSync(a.dataId),c=n.readSync(o.dataId)[0],[p,d,h,f,m]=cne(i,s.shape,s.dtype,l,r.dtype,u,c);return[n.makeTensorInfo(d,s.dtype,p),n.makeTensorInfo([d[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 Ace={kernelName:zp,backendName:"webgl",kernelFunc:yce};function xce(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)),[u,c,p]=dne(i,s.shape,s.dtype,o,l);return[n.makeTensorInfo(c,s.dtype,u),n.makeTensorInfo([p.length],a.dtype,new Int32Array(p))]}var bce={kernelName:Mc,backendName:"webgl",kernelFunc:xce};function vce(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),[u,c]=g9(o,s.shape,s.dtype,i,l,!0);return n.makeTensorInfo(c,s.dtype,u)}var wce={kernelName:Lp,backendName:"webgl",kernelFunc:vce};function kce(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),[u,c]=g9(o,s.shape,s.dtype,i,l);return n.makeTensorInfo(c,s.dtype,u)}var Sce={kernelName:Bp,backendName:"webgl",kernelFunc:kce};function Ice(e){let{inputs:t,backend:n,attrs:s}=e,{sparseIndices:r,sparseValues:a,defaultValue:o}=t,{outputShape:i}=s,{sliceRank:l,numUpdates:u,sliceSize:c,strides:p,outputSize:d}=T.calculateShapes(a,r,i),h=!1;if(a.dtype==="string"){let y=n.bufferSync(r),x=n.bufferSync(a),A=v.decodeString(n.readSync(o.dataId)[0]),b=ine(y,x,i,d,c,u,l,p,A,h);return n.makeTensorInfo(i,b.dtype,b.values)}let f=new X9(u,l,r.shape.length,a.shape.length,p,[d,1],h),m=n.runWebGLProgram(f,[a,r,o],a.dtype),g=be({inputs:{x:m},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(m),g}var Cce={kernelName:Wp,backendName:"webgl",kernelFunc:Ice};function Tce(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=T.prepareSplitSize(r,a,i),u=r.shape.length,c=new Array(u).fill(0),p=r.shape.slice();return l.map(d=>{let h=[...p];h[i]=d;let f=ld({inputs:{x:r},backend:n,attrs:{begin:c,size:h}});return c[i]+=d,f})}var Nce={kernelName:jl,backendName:"webgl",kernelFunc:Tce},P7="return sqrt(x);",Ece=pt({opSnippet:P7,packedOpSnippet:P7,cpuKernelImpl:pne}),Rce={kernelName:si,backendName:"webgl",kernelFunc:Ece},_ce="return x * x;",Dce=pt({opSnippet:_ce}),$ce={kernelName:zc,backendName:"webgl",kernelFunc:Dce},F7="return (a - b) * (a - b);",Pce=Wn({opSnippet:F7,packedOpSnippet:F7}),Fce={kernelName:oi,backendName:"webgl",kernelFunc:Pce};function Oce({inputs:e,attrs:t,backend:n}){let{x:s}=e,r=br+` return x > 0.0 ? 1.0 : float(${t.alpha}); `,a=new xa(s.shape,r);return n.runWebGLProgram(a,[s],s.dtype)}var Mce={kernelName:ui,backendName:"webgl",kernelFunc:Oce},zce=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let s=n.length,r=Tt(n.length),a=Tt(n.length),o="";if(s===1)o="coords * strides + begin";else{let i=0;o=n.map((l,u)=>(i++,n.length===1?`coords * strides[${u}] + begin[${u}]`:`coords[${i-1}] * strides[${u}] + begin[${u}]`)).join(",")}this.userCode=` ${r} begin = ${r}(${e}); ${r} strides = ${r}(${t}); void main() { ${a} coords = getOutputCoords(); setOutput(getX(${o})); } `}};function Lce(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:d}=s,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:x,end:A,strides:b}=Gt.sliceInfo(r.shape,a,o,i,l,u,c,p,d),w;if(m)w=be({inputs:{x:r},backend:n,attrs:{shape:f}});else if(g||y){v.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let C=Gt.computeOutShape(x,A,b),N=ld({inputs:{x:r},backend:n,attrs:{begin:x,size:C}});w=be({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),D=hne(h,R,b,x);w=n.makeTensorInfo(f,r.dtype,D.values)}else{let N=new zce(x,b,h);w=n.runWebGLProgram(N,[r],r.dtype)}let k=be({inputs:{x:w},backend:n,attrs:{shape:f}});return n.disposeIntermediateTensorInfo(w),k}var Bce={kernelName:ql,backendName:"webgl",kernelFunc:Lce};function Wce(e){let{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:u}=s,{data:c,dataSplits:p}=t,d=n.readSync(c.dataId),h=n.readSync(p.dataId),[f,m]=fne(d,h,r,a,o,i,l,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(p.shape,"int32",m)]}var Vce={kernelName:Lc,backendName:"webgl",kernelFunc:Wce};function Uce(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],[u,c,p]=mne(i,l,r),d=c.length;return[n.makeTensorInfo([d,2],"int32",u),n.makeTensorInfo([d],"string",c),n.makeTensorInfo([2],"int32",new Int32Array(p))]}var Gce={kernelName:Vp,backendName:"webgl",kernelFunc:Uce};function Hce(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=gne(o,r);return n.makeTensorInfo(a.shape,"int32",i)}var jce={kernelName:Up,backendName:"webgl",kernelFunc:Hce},qce="return tan(x);",Xce=pt({opSnippet:qce}),Kce={kernelName:Xl,backendName:"webgl",kernelFunc:Xce},Zce=` float e2x = exp(-2.0 * abs(x)); return sign(x) * (1.0 - e2x) / (1.0 + e2x); `,Yce=pt({opSnippet:Zce}),Jce={kernelName:li,backendName:"webgl",kernelFunc:Yce},Qce=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),u=r.dtype==="string"?l.map(d=>v.decodeString(d)):l,c=ze(r.shape,r.dtype,u),p=Ane(c,a);return n.makeTensorInfo(p.shape,p.dtype,p.values)}let o=new Qce(r.shape,a);return n.runWebGLProgram(o,[r],r.dtype)}var tde={kernelName:Ea,backendName:"webgl",kernelFunc:K9},nde=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)); } } `}},sde=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 Oi(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function O7(e){let t=1;for(;tl){let D=n.readSync(r.dataId),[E,$]=xne(D,u,r.dtype,a,o);return[n.makeTensorInfo(E.shape,E.dtype,E.values),n.makeTensorInfo($.shape,$.dtype,$.values)]}if(a===0)return u[u.length-1]=0,[n.makeTensorInfo(u,r.dtype,[]),n.makeTensorInfo(u,"int32",[])];if(c===1)return[r,$h({attrs:{shape:u,dtype:"int32",value:0},backend:n})];let p=n.texData.get(r.dataId),d=p!==null&&p.isPacked,h=d?n.unpackTensor(r):r,m=v.sizeFromShape(u)/c,g=be({inputs:{x:h},attrs:{shape:[m,c]},backend:n});d&&Oi(n,h);let y=O7(a),x=O7(c),A=null,b=()=>A===null?[g,g]:[g,A],w=(D,E,$)=>{let S=b(),F=new nde($),V=[[c],[A===null?1:0],[Number.NEGATIVE_INFINITY],[D],[E]],j=A;A=n.runWebGLProgram(F,S,"int32",V),Oi(n,j)};for(let D=1;D=1;$/=2)w(E,$,[m,x])}for(let D=x;D>y;D/=2){let E=b(),$=new sde([m,D/2]),F=[[c],[A===null?1:0],[y]],z=A;A=n.runWebGLProgram($,E,"int32",F),Oi(n,z);let V=y/2,j=V*2;for(let G=V;G>=1;G/=2)w(j,G,A.shape)}let k=A;A=ld({inputs:{x:A},backend:n,attrs:{begin:0,size:[m,a]}}),Oi(n,k);let C=B9({inputs:{x:g,indices:A},backend:n,attrs:{axis:1,batchDims:1}});Oi(n,g);let N=u.slice(0,-1);N.push(a),k=A,A=be({inputs:{x:A},attrs:{shape:N},backend:n}),Oi(n,k);let R=C;return C=be({inputs:{x:C},attrs:{shape:N},backend:n}),Oi(n,R),[C,A]}var ade={kernelName:Kl,backendName:"webgl",kernelFunc:rde},ode=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 ide(e){let{inputs:t,backend:n,attrs:s}=e,{image:r,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:l,outputShape:u}=s,[c,p,d,h]=r.shape,[f,m]=u!=null?u:[p,d],g=[c,f,m,h],y=new ode(p,d,o,i,l,g);return n.runWebGLProgram(y,[r,a],"float32")}var lde={kernelName:Zl,backendName:"webgl",kernelFunc:ide};function ude(e){let{inputs:t,attrs:n,backend:s}=e,{axis:r}=n,{x:a}=t;td(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:u}=bne(o,r,a.shape,a.dtype);return[s.makeTensorInfo(l,a.dtype,i),s.makeTensorInfo([u.length],"int32",u)]}var cde={kernelName:s0,backendName:"webgl",kernelFunc:ude};function dde(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],u=new Array(i-1),c=0;for(let m=0;mn.disposeIntermediateTensorInfo(m)),f}var pde={kernelName:Yl,backendName:"webgl",kernelFunc:dde},hde=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",u=Math.floor(n/4)*4,c=n%4,p=` sumValue += dot(values, segFilter); `,d="";r%n>0&&(d=` 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) { ${d} 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 < ${u}; i += 4) { int inIdx = inOffset + i; vec4 values = vec4( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), getValue(batch, inIdx + 3) ); vec4 segFilter = vec4( int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0, int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0 ); ${p} } int inIdx = inOffset + ${u}; if (${c===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 ); ${p} } else if (${c===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 ); ${p} } else if (${c===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 ); ${p} } setOutput(${l}); } `}};function fde(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,segmentIds:a}=t,{numSegments:o}=s,i=r.shape.length,l=[],u=0,c=T.getAxesPermutation([u],i),p=r;c!=null&&(p=is({inputs:{x:r},backend:n,attrs:{perm:c}}),l.push(p),u=T.getInnerMostAxes(1,i)[0]);let d=T.segment_util.computeOutShape(p.shape,u,o),h=v.sizeFromShape([p.shape[u]]),f=be({inputs:{x:p},backend:n,attrs:{shape:[-1,h]}});l.push(f);let m=qp(r.dtype),g=(b,w,k,C,N)=>{let R=b.shape[0],D=b.shape[1],E=T.segment_util.segOpComputeOptimalWindowSize(D,N),$={windowSize:E,inSize:D,batchSize:R,numSegments:N},S=new hde($,w),F=n.compileAndRun(S,[b,k],C);if(l.push(F),F.shape[1]===N)return F;let z=q9({backend:n,attrs:{start:0,stop:N,step:1,dtype:"float32"}}),V=K9({inputs:{x:z},backend:n,attrs:{reps:[D/E]}});return l.push(z),l.push(V),g(F,w,V,C,N)},y=g(f,"unsortedSegmentSum",a,m,o),x=be({inputs:{x:y},backend:n,attrs:{shape:d}}),A=x;if(c!=null){l.push(x);let b=T.getUndoAxesPermutation(c);A=is({inputs:{x:A},backend:n,attrs:{perm:b}})}return l.forEach(b=>n.disposeIntermediateTensorInfo(b)),A}var mde={kernelName:Gp,backendName:"webgl",kernelFunc:fde},gde=[hse,mse,Ase,vse,kse,Cse,Nse,Rse,Pse,Ose,Lse,Vse,Hse,Kse,Jse,ere,nre,ore,lre,cre,fre,vre,kre,Ire,_re,$re,Mre,Zne,Bre,Hre,Kre,tae,sae,aae,iae,uae,pae,mae,Aae,bae,wae,Sae,Tae,Eae,$ae,Fae,zae,Wae,Uae,qae,Yae,toe,roe,ioe,loe,coe,poe,foe,goe,Aoe,woe,Ioe,Noe,Roe,$oe,Ooe,Boe,Goe,Kne,joe,Ure,Koe,Joe,tie,Jne,aie,uie,die,mie,Aie,wie,Iie,Eie,$ie,Oie,zie,Vie,Gie,jie,Zie,Jie,ele,nle,rle,lle,ple,gle,Sle,tse,Nle,_le,Ple,Mle,Tre,Ble,Vle,Gle,qle,Yle,ese,Qle,tue,sue,rue,Nre,ble,iue,due,mue,sse,xue,wue,Cue,Eue,$ue,Fue,zue,Wue,Uue,jue,Kue,Jue,nce,ace,lce,dce,xre,wle,fce,gce,Ace,bce,wce,Sce,Cce,Nce,Rce,$ce,Fce,Mce,Bce,Vce,Gce,jce,vle,cse,Kce,Jce,tde,ade,lde,dse,cde,pde,mde,Wle];for(let e of gde)er(e);var qt;(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"})(qt||(qt={}));var Sp;(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"})(Sp||(Sp={}));var Z9;function yde(e){Z9=e.wasm.cwrap(no,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function Ade(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:u,activation:c,leakyreluAlpha:p}=s,d=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=Sp[c];if(g==null)throw new Error(`${c} activation not yet supported for FusedConv2D in the wasm backend.`);let y=l?r.shape[2]:r.shape[1],x=u?a.shape[1]:a.shape[2],A=tu.assertAndGetBroadcastShape(r.shape.slice(0,-2),a.shape.slice(0,-2)),b=n.makeOutput([...A,y,x],r.dtype),w=n.dataIdMap.get(b.dataId).id,k=new Uint8Array(new Int32Array(r.shape).buffer),C=new Uint8Array(new Int32Array(a.shape).buffer);return Z9(d,k,r.shape.length,h,C,a.shape.length,l,u,g,f,m,p||0,w),b}var xde={kernelName:no,backendName:"wasm",setupFunc:yde,kernelFunc:Ade};function Rn(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,u=o.makeOutput(i.shape,t||i.dtype),c=o.dataIdMap.get(u.dataId).id;return v.sizeFromShape(u.shape)===0||n(l,qt[i.dtype],c),u}return{kernelName:e,backendName:"wasm",setupFunc:s,kernelFunc:r}}var bde=Rn(dl);function Vn(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:u,b:c}=l,p=i.dataIdMap.get(u.dataId).id,d=i.dataIdMap.get(c.dataId).id,h=n!=null?n:u.dtype,f=T.assertAndGetBroadcastShape(u.shape,c.shape),m=i.makeOutput(f,h);if(v.sizeFromShape(f)===0)return m;let g=new Uint8Array(new Int32Array(u.shape).buffer),y=new Uint8Array(new Int32Array(c.shape).buffer),x=i.dataIdMap.get(m.dataId).id;return(()=>s(p,g,u.shape.length,d,y,c.shape.length,qt[u.dtype],x))(),m}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:a}}var vde=!0,wde=Vn(Ta,vde),Y9;function kde(e){Y9=e.wasm.cwrap(go,null,["array","number","number","number"])}function Sde(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 Y9(a,r.length,qt[s.dtype],o),s}var Ide={kernelName:go,backendName:"wasm",setupFunc:kde,kernelFunc:Sde};function h2(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 Cde={kernelName:Fo,backendName:"wasm",kernelFunc:h2},J9;function Tde(e){J9=e.wasm.cwrap(Jr,null,["number","array","number","number","number","array","number"])}function ho(e){let{inputs:t,backend:n,attrs:s}=e,[r,a]=Ede(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 Rde={kernelName:Jr,backendName:"wasm",kernelFunc:ho,setupFunc:Tde};function yi(e,t,n){let s=e.shape,r=e.shape.length,a=v.parseAxisParam(t,s),o=a,i=T.getAxesPermutation(o,r),l=null,u=!1;if(i!=null){let c=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 Ude={kernelName:zl,backendName:"wasm",kernelFunc:xs},sC;function Gde(e){sC=e.wasm.cwrap(xo,null,["number","array","number","number","array","number","number","number","number"])}function Hde(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,u=a.shape.length,c=o?r.shape[l-2]:r.shape[l-1],p=i?a.shape[u-1]:a.shape[u-2],d=o?r.shape[l-1]:r.shape[l-2],h=i?a.shape[u-2]:a.shape[u-1],f=r.shape.slice(0,-2),m=a.shape.slice(0,-2),g=v.sizeFromShape(f),y=v.sizeFromShape(m),A=tu.assertAndGetBroadcastShape(r.shape.slice(0,-2),a.shape.slice(0,-2)).concat([d,h]);v.assert(c===p,()=>`Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${r.shape} and ${a.shape} and transposeA=${o} and transposeB=${i} must match.`);let b=o?[g,c,d]:[g,d,c],w=i?[y,h,p]:[y,p,h],k=xs({inputs:{x:r},backend:n,attrs:{shape:b}}),C=xs({inputs:{x:a},backend:n,attrs:{shape:w}}),N=n.dataIdMap.get(k.dataId).id,R=n.dataIdMap.get(C.dataId).id,D=o?k.shape[2]:k.shape[1],E=i?C.shape[1]:C.shape[2],$=Math.max(g,y),S=n.makeOutput([$,D,E],k.dtype),F=n.dataIdMap.get(S.dataId).id,z=new Uint8Array(new Int32Array(k.shape).buffer),V=new Uint8Array(new Int32Array(C.shape).buffer);return sC(N,z,k.shape.length,R,V,C.shape.length,o,i,F),n.disposeData(k.dataId),n.disposeData(C.dataId),S.shape=A,S}var jde={kernelName:xo,backendName:"wasm",setupFunc:Gde,kernelFunc:Hde};function ul(e){let{inputs:{x:t},attrs:{begin:n,size:s},backend:r}=e,[a,o]=Gt.parseSliceParams(t,n,s),i=Gt.isSliceContinous(t.shape,a,o),l=r.readSync(t.dataId),u=r.makeOutput(o,t.dtype),c=v.computeStrides(t.shape),p=r.dataIdMap.get(u.dataId);if(i){let f=Gt.computeFlatOffset(a,c);return t.dtype==="string"?p.stringBytes=l.slice(f,f+v.sizeFromShape(o)):r.typedArrayFromHeap(u).set(l.subarray(f,f+v.sizeFromShape(o))),u}if(t.dtype==="string"){let f=bm(l,a,o,t.shape,t.dtype);return p.stringBytes=f,u}let d=r.typedArrayFromHeap(u),h=t.shape.length;if(h===2)qde(l,c[0],d,a,o);else if(h===3)Xde(l,c[0],c[1],d,a,o);else if(h===4)Kde(l,c[0],c[1],c[2],d,a,o);else{let f=bm(l,a,o,t.shape,t.dtype);d.set(f)}return u}function qde(e,t,n,s,r){let a=0,o=s[0],i=s[1],l=o+r[0];for(let u=o;uy*x),l=T.getReshaped(r.shape,a,i),u=T.getPermuted(l.length,a.length),c=T.getReshapedPermuted(r.shape,a,i),p=T.getSliceBeginCoords(o,a.length),d=T.getSliceSize(c,o,a.length),h=xs({inputs:{x:r},backend:n,attrs:{shape:l}}),f=ho({inputs:{x:h},backend:n,attrs:{perm:u}}),m=xs({inputs:{x:f},backend:n,attrs:{shape:c}}),g=ul({inputs:{x:m},backend:n,attrs:{begin:p,size:d}});return n.disposeData(h.dataId),n.disposeData(f.dataId),n.disposeData(h.dataId),g}var Jde={kernelName:hl,backendName:"wasm",kernelFunc:Yde};function ud(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 Qde={kernelName:bo,backendName:"wasm",kernelFunc:ud},epe=Rn(vo),rC;function tpe(e){rC=e.wasm.cwrap(Na,null,["number","number","number","number"])}function npe(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),u=n.dataIdMap.get(l.dataId).id;return rC(i,a,o,u),l}var spe={kernelName:Na,backendName:"wasm",setupFunc:tpe,kernelFunc:npe};function aC(e){let{inputs:t,backend:n}=e,s=v.parseAxisParam(e.attrs.axis,t[0].shape)[0],r=t.map(h=>h.shape);T.assertParamsConsistent(r,s);let a=T.computeOutShape(t.map(h=>h.shape),s),o=t.filter(h=>v.sizeFromShape(h.shape)>0);if(o.length===1)return h2({inputs:{x:o[0]},backend:n});let i=n.makeOutput(a,t[0].dtype);if(v.sizeFromShape(a)===0)return i;if(o[0].dtype==="string"){let h=o.map(A=>{let b=v.sizeFromShape(A.shape.slice(s));return xs({inputs:{x:A},backend:n,attrs:{shape:[-1,b]}})}),f=h.map(A=>({vals:n.readSync(A.dataId),shape:A.shape}));a=T.computeOutShape(h.map(A=>A.shape),1);let m=h[0].shape[0]===1,g=Tx(f,a,t[0].dtype,m),y=T.computeOutShape(o.map(A=>A.shape),s);i.shape=y;let x=n.dataIdMap.get(i.dataId);return x.stringBytes=T.fromStringArrayToUint8(g),h.forEach(A=>n.disposeData(A.dataId)),i}let l=v.sizeFromShape(o[0].shape.slice(0,s)),u=0,c=o.map(h=>{let f=v.sizeFromShape(h.shape.slice(s));return u+=f,f}),p=o.map(h=>n.typedArrayFromHeap(h)),d=n.typedArrayFromHeap(i);for(let h=0;h`cumprod does not support ${r.dtype} tensors in the WASM backend`);let u=T.getAxesPermutation([a],l),c=r;u!==null&&(c=ho({inputs:{x:r},attrs:{perm:u},backend:n}));let p=T.getInnerMostAxes(1,l)[0];T.assertAxesAreInnerMostDims("cumprod",[p],l);let d=n.makeOutput(c.shape,c.dtype),h=c.shape[p],f=n.dataIdMap.get(c.dataId).id,m=n.dataIdMap.get(d.dataId).id;uC(f,o?1:0,i?1:0,h,m,qt[r.dtype]);let g=d;if(u!==null){let y=T.getUndoAxesPermutation(u);g=ho({inputs:{x:d},attrs:{perm:y},backend:n}),n.disposeData(c.dataId),n.disposeData(d.dataId)}return g}var Ape={kernelName:ml,backendName:"wasm",setupFunc:gpe,kernelFunc:ype},cC;function xpe(e){cC=e.wasm.cwrap(Co,null,["number","number","number","number","number","number"])}function bpe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:o,reverse:i}=s,l=r.shape.length;v.assert(r.dtype==="float32"||r.dtype==="int32",()=>`cumsum does not support ${r.dtype} tensors in the WASM backend`);let u=T.getAxesPermutation([a],l),c=r;u!==null&&(c=ho({inputs:{x:r},attrs:{perm:u},backend:n}));let p=T.getInnerMostAxes(1,l)[0];T.assertAxesAreInnerMostDims("cumsum",[p],l);let d=n.makeOutput(c.shape,c.dtype),h=c.shape[p],f=n.dataIdMap.get(c.dataId).id,m=n.dataIdMap.get(d.dataId).id;cC(f,o?1:0,i?1:0,h,m,qt[r.dtype]);let g=d;if(u!==null){let y=T.getUndoAxesPermutation(u);g=ho({inputs:{x:d},attrs:{perm:y},backend:n}),n.disposeData(c.dataId),n.disposeData(d.dataId)}return g}var vpe={kernelName:Co,backendName:"wasm",setupFunc:xpe,kernelFunc:bpe},dC;function wpe(e){dC=e.wasm.cwrap(yl,null,["number","number","number","array","number","array","array","number","number"])}function kpe(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],u=o==="NHWC"?r.shape[2]:r.shape[3],c=o==="NHWC"?r.shape[3]:r.shape[1],p=l*a,d=u*a,h=c/(a*a),f=o==="NHWC"?[i,p,d,h]:[i,h,p,d],m=t.makeOutput(f,"float32"),y=t.dataIdMap.get(r.dataId).id,x=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),A=new Uint8Array(new Int32Array(f).buffer),b=new Uint8Array(new Int32Array(v.computeStrides(f)).buffer),w=t.dataIdMap.get(m.dataId).id;return dC(y,a,o==="NHWC"?1:0,x,r.shape.length-1,A,b,f.length,w),m}var Spe={kernelName:yl,backendName:"wasm",setupFunc:wpe,kernelFunc:kpe},pC;function Ipe(e){pC=e.wasm.cwrap(To,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Cpe(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:u,pad:c,dimRoundingMode:p}=n,d=u==null?[1,1]:u,h=T.computeConv2DInfo(r.shape,a.shape,l,d,c,p,!0),f=h.filterHeight,m=h.filterWidth,g=h.padInfo.top,y=h.padInfo.right,x=h.padInfo.bottom,A=h.padInfo.left,b=h.dilationHeight,w=h.dilationWidth,k=h.strideHeight,C=h.strideWidth,N=h.inChannels,R=h.outChannels,D=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 E=s.makeOutput(h.outShape,"float32"),$=s.dataIdMap.get(E.dataId).id;return pC(o,r.shape[0],r.shape[1],r.shape[2],i,f,m,g,y,x,A,D,b,w,k,C,N,R,$),E}var Tpe={kernelName:To,backendName:"wasm",setupFunc:Ipe,kernelFunc:Cpe},Npe=Rn(Eo),Epe=!1,Rpe=Vn(Al,Epe,"bool"),_pe=Rn(Ro,"float32");function iy(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),xs({inputs:{x:r},backend:s,attrs:{shape:i}})}var Dpe={kernelName:xl,backendName:"wasm",kernelFunc:iy};function hC(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 $pe={kernelName:Cc,backendName:"wasm",kernelFunc:hC},fC;function Ppe(e){fC=e.wasm.cwrap(vl,null,["number","number","number","number","number","number"])}function Fpe(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,u,c]=s.shape;return fC(a,i,l,u,c,o),r}var Ope={kernelName:vl,backendName:"wasm",kernelFunc:Fpe,setupFunc:Ppe},Mpe=Rn(_o),zpe=!1,Lpe=Vn(Do,zpe),mC;function Bpe(e){mC=e.wasm.cwrap($o,null,["number","number","number","number","number","number","number"])}function Wpe(e){let{backend:t,inputs:n,attrs:s}=e,{varianceEpsilon:r}=s,{x:a,mean:o,variance:i,offset:l,scale:u}=n,c=t.dataIdMap.get(a.dataId).id,p=t.dataIdMap.get(o.dataId).id,d=t.dataIdMap.get(i.dataId).id,h=l!=null?t.dataIdMap.get(l.dataId).id:0,f=u!=null?t.dataIdMap.get(u.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 mC(c,p,d,h,f,r,g),m}var Vpe={kernelName:$o,backendName:"wasm",setupFunc:Bpe,kernelFunc:Wpe},gC;function Upe(e){gC=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 Gpe(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:u,dilations:c,dataFormat:p,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=n,m=T.computeConv2DInfo(r.shape,a.shape,l,c,u,d),g=Sp[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedConv2D in the wasm backend.`);let y=s.dataIdMap.get(r.dataId).id,x=s.dataIdMap.get(a.dataId).id,A=m.outChannels,b=0;if(o!=null){let re=s.dataIdMap.get(o.dataId);if(re.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${re.shape.length}.`);if(re.shape[0]!==A)throw new Error(`FusedConv2D bias shape (${re.shape}) does not match the number of output channels (${A})`);b=re.id}let w=m.filterHeight,k=m.filterWidth,C=m.padInfo.top,N=m.padInfo.right,R=m.padInfo.bottom,D=m.padInfo.left,E=m.dilationHeight,$=m.dilationWidth,S=m.strideHeight,F=m.strideWidth,z=m.inChannels,V=m.padInfo.type==="SAME"?1:0,j=m.batchSize,G=m.inHeight,q=m.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let K=s.makeOutput(m.outShape,"float32"),ne=s.dataIdMap.get(K.dataId).id,ae=i==null?0:s.dataIdMap.get(i.dataId).id;return gC(y,j,G,q,x,w,k,b,C,N,R,D,V,E,$,S,F,z,A,g,ae,f||0,ne),K}var Hpe={kernelName:so,backendName:"wasm",setupFunc:Upe,kernelFunc:Gpe},yC;function jpe(e){yC=e.wasm.cwrap(ro,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 qpe(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:u,dilations:c,dataFormat:p,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=n,m=T.computeConv2DInfo(r.shape,a.shape,l,c,u,d,!0),g=Sp[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let y=s.dataIdMap.get(r.dataId).id,x=s.dataIdMap.get(a.dataId).id,A=m.outChannels,b=0;if(o!=null){let re=s.dataIdMap.get(o.dataId);if(re.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${re.shape.length}.`);if(re.shape[0]!==A)throw new Error(`FusedDepthwiseConv2D bias shape (${re.shape}) does not match the number of output channels (${A})`);b=re.id}let w=m.filterHeight,k=m.filterWidth,C=m.padInfo.top,N=m.padInfo.right,R=m.padInfo.bottom,D=m.padInfo.left,E=m.dilationHeight,$=m.dilationWidth,S=m.strideHeight,F=m.strideWidth,z=m.inChannels,V=m.padInfo.type==="SAME"?1:0,j=m.batchSize,G=m.inHeight,q=m.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let K=s.makeOutput(m.outShape,"float32"),ne=s.dataIdMap.get(K.dataId).id,ae=i==null?0:s.dataIdMap.get(i.dataId).id;return yC(y,j,G,q,x,w,k,b,C,N,R,D,V,E,$,S,F,z,A,g,ae,f||0,ne),K}var Xpe={kernelName:ro,backendName:"wasm",setupFunc:jpe,kernelFunc:qpe},AC;function Kpe(e){AC=e.wasm.cwrap(kl,null,["number","number","number","number","number","number","array","number"])}function Zpe(e){let{backend:t,inputs:n}=e,{params:s,indices:r}=n,[a,o,i,l]=Fy.prepareAndValidate(s,r),u=t.makeOutput(a,s.dtype);if(o===0)return u;let c=r.shape,p=c[c.length-1],h=t.dataIdMap.get(s.dataId).id,m=t.dataIdMap.get(r.dataId).id,g=new Uint8Array(new Int32Array(l).buffer),y=t.dataIdMap.get(u.dataId).id;return AC(h,qt[s.dtype],m,o,p,i,g,y),u}var Ype={kernelName:kl,backendName:"wasm",setupFunc:Kpe,kernelFunc:Zpe},xC;function Jpe(e){xC=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function Qpe(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],u=t.readSync(a.dataId),c=r.shape[l];for(let R=0;R=0,()=>`GatherV2: the index value ${D} is not in [0, ${c-1}]`)}let p=T.segment_util.collectGatherOpShapeInfo(r,a,l,i),d=xs({inputs:{x:r},attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]},backend:t}),h=v.sizeFromShape(a.shape),f=xs({inputs:{x:a},attrs:{shape:[p.batchSize,h/p.batchSize]},backend:t}),m=[p.batchSize,p.outerSize,h/p.batchSize,p.sliceSize],g=t.makeOutput(m,r.dtype);if(v.sizeFromShape(r.shape)===0)return g;let y=d.shape.length-1,A=t.dataIdMap.get(d.dataId).id,w=t.dataIdMap.get(f.dataId).id,k=t.dataIdMap.get(g.dataId).id,C=new Uint8Array(new Int32Array(v.computeStrides(d.shape)).buffer),N=new Uint8Array(new Int32Array(v.computeStrides(m)).buffer);return xC(A,qt[r.dtype],C,y,w,p.batchSize,N,k),t.disposeData(d.dataId),t.disposeData(f.dataId),g.shape=p.outputShape,g}var ehe={kernelName:wl,backendName:"wasm",setupFunc:Jpe,kernelFunc:Qpe},the=!1,nhe=Vn(Sl,the,"bool"),she=!1,rhe=Vn(Po,she,"bool"),bC;function ahe(e){bC=e.wasm.cwrap(Oo,null,["number","number","number","number"])}function ohe(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;bC(r,qt[t.dtype],n,o)}return a}var ihe={kernelName:Oo,backendName:"wasm",setupFunc:ahe,kernelFunc:ohe},lhe=!1,uhe=Vn(Cl,lhe,"bool"),che=!1,dhe=Vn(Tl,che,"bool"),phe=Rn(Mo),hhe=!1,fhe=Vn(Nl,hhe,"bool"),mhe=Rn(El),ghe=!1,yhe=Vn(Rc,ghe,"bool"),Ahe=!1,xhe=Vn(gw,Ahe,"bool"),vC;function bhe(e){vC=e.wasm.cwrap(zo,null,["number","number","number","number"])}function vhe(e){let{backend:t,inputs:n,attrs:s}=e,{reductionIndices:r,keepDims:a}=s,{x:o}=n,l=t.dataIdMap.get(o.dataId).id,u=o,{transposed:c,axes:p,originalAxes:d,inputWasTransposed:h}=yi(o,r,t);if(h){let A=t.dataIdMap.get(c.dataId).id;u=c,l=A}let f=u.shape.length;T.assertAxesAreInnerMostDims("max",p,f);let[m,g]=T.computeOutAndReduceShapes(u.shape,p),y=v.sizeFromShape(g),x=t.makeOutput(m,o.dtype);if(v.sizeFromShape(u.shape)!==0){let A=t.dataIdMap.get(x.dataId).id;vC(l,qt[o.dtype],y,A)}if(h&&t.disposeData(c.dataId),a){let A=T.expandShapeToKeepDim(x.shape,d);x.shape=A}return x}var whe={kernelName:zo,backendName:"wasm",setupFunc:bhe,kernelFunc:vhe},khe=!1,She=Vn(Lo,khe),wC;function Ihe(e){wC=e.wasm.cwrap(Bo,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Che(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:u}=n,c=T.computePool2DInfo(r.shape,o,i,1,l,u),p=c.filterHeight,d=c.filterWidth,h=c.padInfo.top,f=c.padInfo.right,m=c.padInfo.bottom,g=c.padInfo.left,y=c.dilationHeight,x=c.dilationWidth,A=c.strideHeight,b=c.strideWidth,w=c.inChannels,k=c.outChannels;if(c.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);let C=s.makeOutput(c.outShape,"float32"),N=s.dataIdMap.get(C.dataId).id;return wC(a,r.shape[0],r.shape[1],r.shape[2],p,d,h,f,m,g,y,x,A,b,w,k,N),C}var The={kernelName:Bo,backendName:"wasm",setupFunc:Ihe,kernelFunc:Che},kC;function Nhe(e){kC=e.wasm.cwrap(Wo,null,["number, number, number"])}function Ehe(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,u=o,{transposed:c,axes:p,originalAxes:d,inputWasTransposed:h}=yi(o,r,t),f=p;if(h){let b=t.dataIdMap.get(c.dataId).id;b!==i&&(u=c,l=b,f=T.getInnerMostAxes(f.length,u.shape.length))}T.assertAxesAreInnerMostDims("mean",f,u.shape.length);let[m,g]=T.computeOutAndReduceShapes(u.shape,f),y=v.sizeFromShape(g),x=u;u.dtype!=="float32"&&(x=ud({backend:t,inputs:{x:u},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(x.dataId).id);let A=t.makeOutput(m,"float32");if(v.sizeFromShape(u.shape)!==0){let b=t.dataIdMap.get(A.dataId).id;kC(l,y,b)}if(h&&t.disposeData(c.dataId),a){let b=T.expandShapeToKeepDim(A.shape,d);A.shape=b}return u.dtype!=="float32"&&t.disposeData(x.dataId),A}var Rhe={kernelName:Wo,backendName:"wasm",setupFunc:Nhe,kernelFunc:Ehe},SC;function _he(e){SC=e.wasm.cwrap(Vo,null,["number","number","number","number"])}function Dhe(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,u=o,{transposed:c,axes:p,originalAxes:d,inputWasTransposed:h}=yi(o,r,t);if(h){let A=t.dataIdMap.get(c.dataId).id;A!==i&&(u=c,l=A)}let f=u.shape.length;T.assertAxesAreInnerMostDims("min",p,f);let[m,g]=T.computeOutAndReduceShapes(u.shape,p),y=v.sizeFromShape(g),x=t.makeOutput(m,u.dtype);if(v.sizeFromShape(u.shape)!==0){let A=t.dataIdMap.get(x.dataId).id;SC(l,qt[o.dtype],y,A)}if(h&&t.disposeData(c.dataId),a){let A=T.expandShapeToKeepDim(x.shape,d);x.shape=A}return x}var $he={kernelName:Vo,backendName:"wasm",setupFunc:_he,kernelFunc:Dhe},Phe=!1,Fhe=Vn(Uo,Phe),ly;(function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"})(ly||(ly={}));var IC;function Ohe(e){IC=e.wasm.cwrap(Go,null,["number","array","number","number","array","array","number","number"])}function Mhe(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,u=new Uint8Array(new Int32Array(t.shape).buffer),c=s.map(f=>f[0]),p=s.map(f=>f[1]),d=new Uint8Array(new Int32Array(c).buffer),h=new Uint8Array(new Int32Array(p).buffer);return IC(o,u,t.shape.length,qt[t.dtype],d,h,ly[r],l),i}var zhe={kernelName:Go,backendName:"wasm",kernelFunc:Mhe,setupFunc:Ohe},Lhe=!0,Bhe=Vn(Ho,Lhe),Whe=Rn(Rl);function Qx(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 CC;function Vhe(e){CC=e.wasm.cwrap(Dl,"number",["number","number","number","number","number"])}function Uhe(e){let{backend:t,inputs:n,attrs:s}=e,{iouThreshold:r,maxOutputSize:a,scoreThreshold:o}=s,{boxes:i,scores:l}=n,u=t.dataIdMap.get(i.dataId).id,c=t.dataIdMap.get(l.dataId).id,p=CC(u,c,a,r,o),{pSelectedIndices:d,selectedSize:h,pSelectedScores:f,pValidOutputs:m}=Qx(t,p);return t.wasm._free(f),t.wasm._free(m),t.makeOutput([h],"int32",d)}var Ghe={kernelName:Dl,backendName:"wasm",setupFunc:Vhe,kernelFunc:Uhe},TC;function Hhe(e){TC=e.wasm.cwrap(Dc,"number",["number","number","number","number","number","bool"])}function jhe(e){let{backend:t,inputs:n,attrs:s}=e,{iouThreshold:r,maxOutputSize:a,scoreThreshold:o,padToMaxOutputSize:i}=s,{boxes:l,scores:u}=n,c=t.dataIdMap.get(l.dataId).id,p=t.dataIdMap.get(u.dataId).id,d=TC(c,p,a,r,o,i),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=Qx(t,d);t.wasm._free(m);let y=t.makeOutput([f],"int32",h),x=t.makeOutput([],"int32",g);return[y,x]}var qhe={kernelName:Dc,backendName:"wasm",setupFunc:Hhe,kernelFunc:jhe},NC;function Xhe(e){NC=e.wasm.cwrap($l,"number",["number","number","number","number","number","number"])}function Khe(e){let{backend:t,inputs:n,attrs:s}=e,{iouThreshold:r,maxOutputSize:a,scoreThreshold:o,softNmsSigma:i}=s,{boxes:l,scores:u}=n,c=t.dataIdMap.get(l.dataId).id,p=t.dataIdMap.get(u.dataId).id,d=NC(c,p,a,r,o,i),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=Qx(t,d);t.wasm._free(g);let y=t.makeOutput([f],"int32",h),x=t.makeOutput([f],"float32",m);return[y,x]}var Zhe={kernelName:$l,backendName:"wasm",setupFunc:Xhe,kernelFunc:Khe},Yhe=!1,Jhe=Vn(_l,Yhe,"bool"),EC;function Qhe(e){EC=e.wasm.cwrap(Fl,null,["number","number","number","number","number"])}function efe(e){let{inputs:t,backend:n,attrs:s}=e,{indices:r}=t,{dtype:a,depth:o,onValue:i,offValue:l}=s,u=n.makeOutput([...r.shape,o],a),c=n.dataIdMap.get(u.dataId).id,d=n.dataIdMap.get(r.dataId).id;return EC(d,o,i,l,c),u}var tfe={kernelName:Fl,backendName:"wasm",setupFunc:Qhe,kernelFunc:efe};function nfe(e){let{inputs:{x:t},backend:n}=e,s=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(s).fill(1),s}var sfe={kernelName:Pl,backendName:"wasm",kernelFunc:nfe};function rfe(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(t.length===1)return iy({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let a=t[0].shape,o=t[0].dtype;t.forEach(c=>{v.assertShapesMatch(a,c.shape,"All tensors passed to stack must have matching shapes"),v.assert(o===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(c=>{let p=iy({inputs:{input:c},backend:n,attrs:{dim:r}});return i.push(p),p}),u=aC({inputs:l,backend:n,attrs:{axis:r}});return i.forEach(c=>n.disposeData(c.dataId)),u}var afe={kernelName:Ol,backendName:"wasm",kernelFunc:rfe},RC;function ofe(e){RC=e.wasm.cwrap(jo,null,["number","array","number","number","array","array","number","number"])}function ife(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 hC({backend:n,attrs:{shape:a,value:r,dtype:t.dtype}});let o=n.dataIdMap.get(t.dataId).id,i=n.makeOutput(a,t.dtype),u=n.dataIdMap.get(i.dataId).id,c=new Uint8Array(new Int32Array(t.shape).buffer),p=s.map(m=>m[0]),d=s.map(m=>m[1]),h=new Uint8Array(new Int32Array(p).buffer),f=new Uint8Array(new Int32Array(d).buffer);return RC(o,c,t.shape.length,qt[t.dtype],h,f,r,u),i}var _C={kernelName:jo,backendName:"wasm",kernelFunc:ife,setupFunc:ofe},lfe=!1,ufe=Vn(qo,lfe),DC;function cfe(e){DC=e.wasm.cwrap(Xo,null,["number","number","number"])}function dfe(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,u=l;l.dtype!=="float32"&&(u=ud({backend:n,inputs:{x:s},attrs:{dtype:"float32"}}),i=n.dataIdMap.get(u.dataId).id);let c=n.makeOutput(s.shape,"float32"),p=n.dataIdMap.get(c.dataId).id;return DC(i,o,p),l.dtype!=="float32"&&n.disposeData(u.dataId),c}var pfe={kernelName:Xo,backendName:"wasm",setupFunc:cfe,kernelFunc:dfe},$C;function hfe(e){$C=e.wasm.cwrap(Ko,null,["number","number","number","number"])}function ffe(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,u=o,{transposed:c,axes:p,originalAxes:d,inputWasTransposed:h}=yi(o,r,t),f=p;if(h){let A=t.dataIdMap.get(c.dataId).id;A!==i&&(u=c,l=A,f=T.getInnerMostAxes(f.length,u.shape.length))}T.assertAxesAreInnerMostDims("prod",f,u.shape.length);let[m,g]=T.computeOutAndReduceShapes(u.shape,f),y=v.sizeFromShape(g),x=t.makeOutput(m,u.dtype);if(v.sizeFromShape(u.shape)!==0){let A=t.dataIdMap.get(x.dataId).id;$C(l,y,qt[x.dtype],A)}if(h&&t.disposeData(c.dataId),a){let A=T.expandShapeToKeepDim(x.shape,d);x.shape=A}return x}var mfe={kernelName:Ko,backendName:"wasm",setupFunc:hfe,kernelFunc:ffe},gfe=e=>{let{backend:t,attrs:n}=e,{start:s,stop:r,step:a,dtype:o}=n,i=Rx(s,r,a,o),l=t.makeOutput([i.length],o);return t.typedArrayFromHeap(l).set(i),l},yfe={kernelName:$c,backendName:"wasm",kernelFunc:gfe},Afe=!0,xfe=Vn(No,Afe),bfe=Rn(Zo),vfe=Rn(Qo),PC;function wfe(e){PC=e.wasm.cwrap(Jo,null,["number","number","number","number","number","number","number","number","number","number"])}function kfe(e){let{backend:t,inputs:n,attrs:s}=e,{images:r}=n,{alignCorners:a,halfPixelCenters:o,size:i}=s,[l,u]=i,[c,p,d,h]=r.shape,f=[c,l,u,h],m=t.dataIdMap.get(r.dataId),g;m.dtype!=="float32"&&(g=ud({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(g.dataId));let y=m.id,x=t.makeOutput(f,"float32");if(v.sizeFromShape(r.shape)===0)return x;let A=t.dataIdMap.get(x.dataId).id;return PC(y,c,p,d,h,l,u,a?1:0,o?1:0,A),g!=null&&t.disposeData(g.dataId),x}var Sfe={kernelName:Jo,backendName:"wasm",setupFunc:wfe,kernelFunc:kfe},FC;function Ife(e){FC=e.wasm.cwrap(Yo,null,["number","number","number","number","number","number","number","number","number","number"])}function Cfe(e){let{backend:t,inputs:n,attrs:s}=e,{images:r}=n,{alignCorners:a,halfPixelCenters:o,size:i}=s,[l,u]=i,[c,p,d,h]=r.shape,f=[c,l,u,h],m=t.makeOutput(f,"float32");if(v.sizeFromShape(r.shape)===0)return m;let g=t.dataIdMap.get(r.dataId),y;g.dtype!=="float32"&&(y=ud({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),g=t.dataIdMap.get(y.dataId));let x=g.id,A=t.dataIdMap.get(m.dataId).id;return FC(x,c,p,d,h,l,u,a?1:0,o?1:0,A),y!=null&&t.disposeData(y.dataId),m}var Tfe={kernelName:Yo,backendName:"wasm",setupFunc:Ife,kernelFunc:Cfe},OC;function Nfe(e){OC=e.wasm.cwrap(Ll,null,["number","array","number","array","number","number"])}function Efe(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 h2({inputs:{x:r},backend:n});let i=n.makeOutput(r.shape,r.dtype),l=n.dataIdMap.get(r.dataId).id,u=n.dataIdMap.get(i.dataId).id,c=new Uint8Array(new Int32Array(o).buffer),p=new Uint8Array(new Int32Array(r.shape).buffer);OC(l,c,o.length,p,r.shape.length,u);let d=xs({inputs:{x:i},attrs:{shape:r.shape},backend:n});return n.disposeData(i.dataId),d}var Rfe={kernelName:Ll,backendName:"wasm",kernelFunc:Efe,setupFunc:Nfe},MC;function _fe(e){MC=e.wasm.cwrap(Ql,null,["number","number","number","number","number","number","number","number","array","number","number"])}function Dfe(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),u=n.dataIdMap.get(r.dataId).id,c=n.dataIdMap.get(l.dataId).id,[p,d,h,f]=r.shape,[m,g]=T.getImageCenter(i,d,h),y=o===0,x=255,A=typeof o=="number"?[o,o,o,y?0:x]:[...o,x],b=new Uint8Array(new Int32Array(A).buffer);return MC(u,p,d,h,f,a,m,g,b,A.length,c),l}var $fe={kernelName:Ql,backendName:"wasm",kernelFunc:Dfe,setupFunc:_fe},Pfe=Rn(Bl),Ffe=Rn(ei),zC;function Ofe(e){zC=e.wasm.cwrap(Wl,null,["number","number","number","number","number","number","array","number","number"])}function Mfe(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:u,sliceSize:c,strides:p,outputSize:d}=Oy.calculateShapes(a,r,o),f=t.dataIdMap.get(r.dataId).id,g=t.dataIdMap.get(a.dataId).id,y=new Uint8Array(new Int32Array(p).buffer),x=t.dataIdMap.get(i.dataId).id;return zC(f,g,qt[a.dtype],l,u,c,y,d,x),i}var zfe={kernelName:Wl,backendName:"wasm",setupFunc:Ofe,kernelFunc:Mfe},LC;function Lfe(e){LC=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function Bfe(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,u=n.makeOutput(r.shape,r.dtype),c=n.dataIdMap.get(u.dataId).id,p=s.shape.length,d=r.shape.length,h=p===0||p>1||d===1?1:v.sizeFromShape(r.shape.slice(1));return LC(o,i,l,h,c),u}var Wfe={kernelName:Vl,backendName:"wasm",kernelFunc:Bfe,setupFunc:Lfe},BC;function Vfe(e){BC=e.wasm.cwrap(ni,null,["number","number"])}function Ufe(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||BC(s,a),r}var Gfe={kernelName:"Sigmoid",backendName:"wasm",setupFunc:Vfe,kernelFunc:Ufe},Hfe=Rn(ti),WC;function jfe(e){WC=e.wasm.cwrap(ai,null,["number","number","number","number"])}function qfe(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||WC(r,o,i,l),a}var Xfe={kernelName:ai,backendName:"wasm",setupFunc:jfe,kernelFunc:qfe};function Kfe(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;k0?l+1:0;if(c<0)throw new Error(T.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let p=r.shape.slice();p[0]=c;let d=n.dataIdMap.get(r.dataId).id,h=n.dataIdMap.get(a.dataId).id,f=n.dataIdMap.get(o.dataId).id,m=n.makeOutput(p,r.dtype),g=n.dataIdMap.get(m.dataId).id,y=n.makeOutput([4],"int32"),x=n.dataIdMap.get(y.dataId).id;GC(d,qt[r.dtype],r.shape[0],h,f,g,x,t,0);let A=n.readSync(y.dataId),b;switch(A[0]){case 0:{b=T.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break}case 1:{b=T.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break}case 2:b=T.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(A[1],A[2]);break;case 3:b=T.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(A[1],A[2],A[3]);break;default:b=""}if(n.disposeData(y.dataId),b)throw n.disposeData(m.dataId),new Error(b);return m}function sme(e){return jC(e,!0)}var rme={kernelName:Lp,backendName:"wasm",setupFunc:HC,kernelFunc:sme};function ame(e){return jC(e,!1)}var ome={kernelName:Bp,backendName:"wasm",setupFunc:HC,kernelFunc:ame};function ime(e){let{inputs:t,attrs:n,backend:s}=e,{x:r}=t,{numOrSizeSplits:a,axis:o}=n,i=v.parseAxisParam(o,r.shape)[0],l=T.prepareSplitSize(r,a,i),u=new Array(r.shape.length).fill(0),c=r.shape.slice();return l.map(p=>{let d=[...c];d[i]=p;let h=ul({inputs:{x:r},attrs:{begin:u,size:d},backend:s});return u[i]+=p,h})}var lme={kernelName:jl,backendName:"wasm",kernelFunc:ime},ume=Rn(si),cme=Rn(zc),dme=!0,pme=Vn(oi,dme),qC;function hme(e){qC=e.wasm.cwrap(ui,null,["number","number","number","number"])}function fme(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 qC(o,r,qt[a.dtype],l),i}var mme={kernelName:ui,backendName:"wasm",setupFunc:hme,kernelFunc:fme},XC;function gme(e){XC=e.wasm.cwrap(ql,null,["number","array","number","array","array","array","array","array","number","number"])}function yme(e){let{backend:t,inputs:n,attrs:s}=e,{x:r}=n,{begin:a,end:o,strides:i,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:d}=s,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:x,end:A,strides:b}=Gt.sliceInfo(r.shape,a,o,i,l,u,c,p,d),w;if(m)w=xs({inputs:{x:r},backend:t,attrs:{shape:f}});else if(g||y){v.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let k=Gt.computeOutShape(x,A,b),C=ul({inputs:{x:r},backend:t,attrs:{begin:x,size:k}});w=xs({inputs:{x:C},backend:t,attrs:{shape:f}}),t.disposeData(C.dataId)}else{let k=t.makeOutput(h,"float32"),C=t.dataIdMap.get(r.dataId).id,N=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),R=new Uint8Array(new Int32Array(x).buffer),D=new Uint8Array(new Int32Array(A).buffer),E=new Uint8Array(new Int32Array(b).buffer),$=new Uint8Array(new Int32Array(h).buffer),S=new Uint8Array(new Int32Array(v.computeStrides(h)).buffer),F=t.dataIdMap.get(k.dataId).id;XC(C,N,r.shape.length,R,D,E,$,S,h.length,F),w=xs({inputs:{x:k},backend:t,attrs:{shape:f}}),t.disposeData(k.dataId)}return w}var Ame={kernelName:ql,backendName:"wasm",setupFunc:gme,kernelFunc:yme};function xme(e){let{backend:t,inputs:n,attrs:s}=e,{data:r,dataSplits:a}=n,{separator:o,nGramWidths:i,leftPad:l,rightPad:u,padWidth:c,preserveShortSequences:p}=s,d=t.readSync(r.dataId),h=t.readSync(a.dataId),[f,m]=Dx(d,h,o,i,l,u,c,p),g=t.makeOutput([f.length],"string"),y=t.dataIdMap.get(g.dataId);y.stringBytes=f;let x=t.makeOutput(a.shape,"int32");return t.typedArrayFromHeap(x).set(m),[g,x]}var bme={kernelName:Lc,backendName:"wasm",kernelFunc:xme};function vme(e){let{backend:t,inputs:n,attrs:s}=e,{input:r,delimiter:a}=n,{skipEmpty:o}=s,i=t.readSync(r.dataId),l=t.readSync(a.dataId),[u,c,p]=$x(i,l[0],o),d=c.length,h=t.makeOutput([d,2],"int32");t.typedArrayFromHeap(h).set(u);let m=t.makeOutput([d],"string"),g=t.dataIdMap.get(m.dataId);g.stringBytes=c;let y=t.makeOutput([2],"int32");return t.typedArrayFromHeap(y).set(p),[h,m,y]}var wme={kernelName:Vp,backendName:"wasm",kernelFunc:vme};function kme(e){let{backend:t,inputs:n,attrs:s}=e,{input:r}=n,{numBuckets:a}=s,o=t.readSync(r.dataId),i=Px(o,a),l=t.makeOutput(r.shape,"int32");return t.typedArrayFromHeap(l).set(i),l}var Sme={kernelName:Up,backendName:"wasm",kernelFunc:kme},Ime=!0,Cme=Vn(ii,Ime),KC;function Tme(e){KC=e.wasm.cwrap(ri,null,["number","number","number","number"])}function Nme(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,u=o,{transposed:c,axes:p,originalAxes:d,inputWasTransposed:h}=yi(o,r,t),f=p;if(h){let A=t.dataIdMap.get(c.dataId).id;A!==i&&(u=c,l=A,f=T.getInnerMostAxes(f.length,u.shape.length))}T.assertAxesAreInnerMostDims("sum",f,u.shape.length);let[m,g]=T.computeOutAndReduceShapes(u.shape,f),y=v.sizeFromShape(g),x=t.makeOutput(m,u.dtype);if(v.sizeFromShape(u.shape)!==0){let A=t.dataIdMap.get(x.dataId).id;KC(l,y,qt[x.dtype],A)}if(h&&t.disposeData(c.dataId),a){let A=T.expandShapeToKeepDim(x.shape,d);x.shape=A}return x}var Eme={kernelName:ri,backendName:"wasm",setupFunc:Tme,kernelFunc:Nme},Rme=Rn(Xl),_me=Rn(li),ZC;function Dme(e){ZC=e.wasm.cwrap(Ea,null,["number","array","number","array","number","number"])}function $me(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 d=0;d{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 u=t.makeOutput(l,s.dtype),c=t.dataIdMap.get(u.dataId).id,p=t.makeOutput(l,"int32"),d=t.dataIdMap.get(p.dataId).id;return YC(o,i,s.shape.length,qt[s.dtype],r,a,c,d),[u,p]},Mme={kernelName:Kl,backendName:"wasm",setupFunc:Fme,kernelFunc:Ome},JC;function zme(e){JC=e.wasm.cwrap(Zl,null,["number","number","bool","number","number","number","number","number","number","array","number","array","number","number","number","number","number"])}function Lme(e){let{backend:t,inputs:n,attrs:s}=e,{image:r,transforms:a}=n,{interpolation:o,fillMode:i,fillValue:l,outputShape:u}=s,[c,p,d,h]=r.shape,[f,m]=u!=null?u:[p,d],g=[c,f,m,h],y=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),x=new Uint8Array(new Int32Array(v.computeStrides(g)).buffer),A=t.makeOutput(g,r.dtype),b=t.dataIdMap.get(A.dataId).id,k=t.dataIdMap.get(r.dataId).id,N=t.dataIdMap.get(a.dataId).id,R=o==="nearest"?1:2,D;switch(i){case"constant":D=1;break;case"reflect":D=2;break;case"wrap":D=3;break;case"nearest":D=4;break;default:D=1;break}return JC(k,N,a.shape[0]>1,c,f,m,h,d,p,y,r.shape.length-1,x,g.length-1,R,D,l,b),A}var Bme={kernelName:Zl,backendName:"wasm",setupFunc:zme,kernelFunc:Lme};function Wme(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),u=0;for(let h=0;h({dataId:h,dtype:f,shape:l}))}var Vme={kernelName:Yl,backendName:"wasm",kernelFunc:Wme};function Ume(e){let{inputs:{x:t},backend:n}=e,s=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(s).fill(0),s}var Gme={kernelName:Jl,backendName:"wasm",kernelFunc:Ume},Hme=[xde,bde,wde,Ide,$de,Ode,Lde,Vde,jde,Jde,Qde,epe,spe,rpe,ipe,cpe,dpe,ppe,mpe,Ape,vpe,Spe,Tpe,Npe,Rpe,_pe,Dpe,$pe,Ope,Mpe,Lpe,Vpe,Hpe,Xpe,Ype,ehe,nhe,rhe,Cde,ihe,uhe,dhe,phe,fhe,mhe,yhe,xhe,whe,She,The,Rhe,$he,Fhe,zhe,Bhe,Whe,Ghe,qhe,Zhe,Jhe,tfe,sfe,afe,_C,ufe,pfe,mfe,yfe,xfe,bfe,vfe,Ude,Sfe,Tfe,Rfe,$fe,Pfe,Ffe,zfe,Wfe,Gfe,Hfe,Zde,Xfe,Zfe,Qfe,nme,rme,ome,lme,ume,cme,pme,mme,Ame,bme,wme,Sme,Cme,Eme,Rme,_me,Pme,Mme,Bme,Rde,Vme,Gme];for(let e of Hme)er(e);var uy=U();uy.registerFlag("WASM_HAS_SIMD_SUPPORT",async()=>{try{return 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]))}catch(e){return!1}});uy.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(uy.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 M7=fo(I_()),jme=fo(C_()),z7=fo(T_()),L7=M7.default||M7,qme=z7.default||z7,QC=class extends fc{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(eT),cy=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new Tp(this,Jt())}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 u=t;this.dataIdMap.set(e,{id:a,stringBytes:u,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,t,n){let{memoryOffset:s,dtype:r,shape:a,stringBytes:o}=this.dataIdMap.get(e);if(r==="string")return(t==null||t===0)&&(n==null||n>=o.length)?o:o.slice(t,n);t=t||0,n=n||v.sizeFromShape(a);let i=v.bytesPerElement(r),l=this.wasm.HEAPU8.slice(s+t*i,s+n*i);return Zme(l.buffer,r)}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 Xme(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 B7(e,t,n){if(Tm!=null)return Tm;let s="tfjs-backend-wasm.wasm";return e&&t?s="tfjs-backend-wasm-threaded-simd.wasm":e&&(s="tfjs-backend-wasm-simd.wasm"),rp!=null&&rp[s]!=null?rp[s]:n+s}async function Kme(){let[e,t]=await Promise.all([U().getAsync("WASM_HAS_SIMD_SUPPORT"),U().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((n,s)=>{let r={};r.locateFile=(i,l)=>{if(i.endsWith(".worker.js")){let u=jme.wasmWorkerContents.replace(/\n/g,"\\n"),c=new Blob([u],{type:"application/javascript"});return URL.createObjectURL(c)}return i.endsWith(".wasm")?B7(e,t,ep!=null?ep:l):l+i},eb&&(r.instantiateWasm=Xme(B7(e,t,ep!=null?ep:"")));let a=!1;r.onAbort=()=>{if(a||ap)return;ap=!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&&Tm==null?(r.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+L7.toString()],{type:"text/javascript"}),o=L7(r)):o=qme(r),o.then(i=>{a=!0,ap=!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})}).catch(s)})}function Zme(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 Yme=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],Tm=null,ep=null,rp={},ap=!1,eb=!1;function Jme(e,t=!1){if(Dy("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),ap)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");Tm=e,eb=t}function f2(e,t=!1){if(ap)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")ep=e;else{rp=e;let n=Yme.filter(s=>rp[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.`)}eb=t}var eT=-1,cy=-1;function Qme(e){eT=e}function e0e(){if(cy===-1)throw new Error("WASM backend not initialized.");return cy}var t0e="3.21.0",n0e=2;eu("wasm",async()=>{let{wasm:e}=await Kme();return new QC(e)},n0e);var $a=U();$a.registerFlag("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE",()=>15);$a.registerFlag("WEBGPU_CPU_FORWARD",()=>!0);$a.registerFlag("WEBGPU_MATMUL_PROGRAM_TYPE",()=>-1);$a.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE",()=>!1);$a.registerFlag("WEBGPU_USE_LOW_POWER_GPU",()=>!1);$a.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e3);$a.registerFlag("WEBGPU_USE_PROFILE_TOOL",()=>!1);$a.registerFlag("WEBGPU_IMPORT_EXTERNAL_TEXTURE",()=>!0);$a.registerFlag("WEBGPU_USE_NAIVE_CONV2D_DEBUG",()=>!1);var s0e=class{constructor(e){e&&(this.vendor=e.vendor)}isIntel(){return this.vendor==="intel"}},r0e=class{constructor(e){this.device=e,this.numUsedBuffers=0,this.numFreeBuffers=0,this.freeBuffers=new Map,this.usedBuffers=new Map,this.numBytesUsed=0,this.numBytesAllocated=0}acquireUploadBuffer(e,t){return this.acquireBuffer(e,t,!0)}acquireBuffer(e,t,n=!1){let s=W7(e,t);if(this.freeBuffers.has(s)||this.freeBuffers.set(s,[]),this.usedBuffers.has(s)||this.usedBuffers.set(s,[]),this.numBytesUsed+=e,this.numUsedBuffers++,this.freeBuffers.get(s).length>0){this.numFreeBuffers--;let a=this.freeBuffers.get(s).shift();return this.usedBuffers.get(s).push(a),a}this.numBytesAllocated+=e;let r=this.device.createBuffer({size:e,usage:t,mappedAtCreation:n});return this.usedBuffers.get(s).push(r),r}releaseBuffer(e,t,n){if(this.freeBuffers.size===0)return;let s=W7(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}releaseUploadBuffer(e,t,n){e.mapAsync(GPUMapMode.WRITE).then(()=>{this.releaseBuffer(e,t,n)},s=>{})}getNumUsedBuffers(){return this.numUsedBuffers}getNumFreeBuffers(){return this.numFreeBuffers}dispose(){this.freeBuffers.forEach((e,t)=>{e.forEach(n=>{n.destroy()})}),this.usedBuffers.forEach((e,t)=>{e.forEach(n=>{n.destroy()})}),this.freeBuffers=new Map,this.usedBuffers=new Map,this.numUsedBuffers=0,this.numFreeBuffers=0,this.numBytesUsed=0,this.numBytesAllocated=0}};function W7(e,t){return`${e}_${t}`}var a0e=class{constructor(e){this.device=e,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures=new Map,this.usedTextures=new Map,this.numBytesUsed=0,this.numBytesAllocated=0}acquireTexture(e,t,n,s){let r=U7(n),a=e*t*r,o=V7(e,t,n,s);if(this.freeTextures.has(o)||this.freeTextures.set(o,[]),this.usedTextures.has(o)||this.usedTextures.set(o,[]),this.numBytesUsed+=a,this.numUsedTextures++,this.freeTextures.get(o).length>0){this.numFreeTextures--;let l=this.freeTextures.get(o).shift();return this.usedTextures.get(o).push(l),l}this.numBytesAllocated+=a;let i=this.device.createTexture({size:[e,t],format:n,usage:s});return this.usedTextures.get(o).push(i),i}releaseTexture(e,t,n,s,r){if(this.freeTextures.size===0)return;let a=V7(t,n,s,r);this.freeTextures.has(a)||this.freeTextures.set(a,[]),this.freeTextures.get(a).push(e),this.numFreeTextures++,this.numUsedTextures--;let o=this.usedTextures.get(a),i=o.indexOf(e);if(i<0)throw new Error("Cannot release a texture that was never provided by this texture manager");o.splice(i,1);let l=U7(s),u=t*n*l;this.numBytesUsed-=u}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){this.freeTextures.forEach((e,t)=>{e.forEach(n=>{n.destroy()})}),this.usedTextures.forEach((e,t)=>{e.forEach(n=>{n.destroy()})}),this.freeTextures=new Map,this.usedTextures=new Map,this.numUsedTextures=0,this.numFreeTextures=0,this.numBytesUsed=0,this.numBytesAllocated=0}};function V7(e,t,n,s){return`${e}_${t}_${n}_${s}`}function U7(e){if(e==="rgba8unorm")return 16;throw new Error(`${e} is not supported!`)}function o0e(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}var i0e=(e,t,n,s)=>{let r={dtype:s.dtype,shape:s.shape},a=l0e(n,r,t),o=e.createShaderModule({code:a,label:t.constructor.name});return e.createComputePipeline({compute:{module:o,entryPoint:"_start"},label:t.constructor.name,layout:"auto"})};function zn(e){if(e<=1)return"i32";if(e===2)return"vec2";if(e===3)return"vec3";if(e===4)return"vec4";if(e===5)return"vec5";if(e===6)return"vec6";throw Error(`GPU for rank ${e} is not yet supported`)}function va(e){if(e===0)return"x";if(e===1)return"y";if(e===2)return"z";if(e===3)return"w";if(e===4)return"u";if(e===5)return"v";throw Error(`Index ${e} is not yet supported`)}function Je(...e){let t;switch(e.length){case 0:t=` ${Ip()} fn _start(@builtin(local_invocation_id) LocalId : vec3, @builtin(global_invocation_id) GlobalId : vec3, @builtin(num_workgroups) NumWorkgroups : vec3) { localId = LocalId; globalId = GlobalId; numWorkgroups = NumWorkgroups; main(); } fn main() `;break;case 1:t=` ${Ip()} fn _start(@builtin(local_invocation_id) LocalId : vec3, @builtin(global_invocation_id) GlobalId : vec3, @builtin(num_workgroups) NumWorkgroups : vec3) { localId = LocalId; globalId = GlobalId; numWorkgroups = NumWorkgroups; main(getGlobalIndex()); } fn main(${e[0]} : i32) `;break;default:throw Error("Unreachable")}return t}function Ip(){return` @compute @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ) `}function l0e(e,t,n){let s=[];if(s.push(` const workGroupSizeX = ${n.workGroupSize[0]}u; const workGroupSizeY = ${n.workGroupSize[1]}u; const workGroupSizeZ = ${n.workGroupSize[2]}u; var localId: vec3; var globalId: vec3; var numWorkgroups: vec3; // Only used when the y/z dimension of workgroup size is 1. fn getGlobalIndex() -> i32 { ${tT(n)?" 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); `} } `),n.isFromPixels)return s.push(` struct Uniform { size : i32, numChannels : i32, outShapeStrides : vec2, }; @group(0) @binding(0) var result: array<${op(t.dtype,n.isVec4)}>; @group(0) @binding(2) var uniforms: Uniform; `),[G7,s.join(` `),H7(t.shape),n.getUserCode()].join(` `);let r="struct Uniforms { NAN : f32, ";n.variableNames.forEach((d,h)=>{let f=zn(e[h].shape.length);r+=`${d.charAt(0).toLowerCase()+d.slice(1)}Shape : ${f}, `}),r+=`outShape : ${zn(t.shape.length)}, `;let o=t.shape.length-1;r+=` outShapeStrides: ${zn(o)}, `,n.size&&(r+="size : i32, "),n.uniforms&&(r+=n.uniforms),r+="};",r=g0e(r),s.push(r),n.atomic?s.push(` @group(0) @binding(0) var result: array>; `):s.push(` @group(0) @binding(0) var result: array<${op(t.dtype,n.isVec4)}>; `),n.variableNames.forEach((d,h)=>{s.push(` @group(0) @binding(${1+h}) var ${d}: array<${n.variableTypes?n.variableTypes[h]:op(e[h].dtype,n.isVec4)}>; `)}),r!==""&&s.push(` @group(0) @binding(${1+n.variableNames.length}) var uniforms: Uniforms; `);let l=h0e(t.shape,n.dispatchLayout),u=[G7,s.join(` `),H7(t.shape),l,f0e(t.shape.length)];n.atomic||u.push(m0e(t.shape,t.dtype,n.isVec4));let c=e.map((d,h)=>p0e(d,t.shape,n.variableTypes?n.variableTypes[h]==="vec4":n.isVec4,n.dispatchLayout.x.length===t.shape.length)).join(` `);return u.push(c),u.push(n.getUserCode()),u.join(` `)}function u0e(e,t,n,s){let r=e.shaderKey;if(e.isFromPixels)return r;let a=n.map(c=>c.dtype).concat(s.dtype),o=n.map(c=>T.getBroadcastDims(c.shape,s.shape)),i=n.map(c=>v.arraysEqual(c.shape,s.shape)).join("_"),l=o.map(c=>c.join("_")).join(";"),u=tT(e)?"flatDispatch":"";return r+="_"+(e.workGroupSize?e.workGroupSize.join(","):"")+t.map(c=>c.length).join(",")+a.join(",")+e.variableNames.join(",")+l+i+u,r}var G7=` struct vec5 {x: i32, y: i32, z: i32, w: i32, u: i32}; struct vec6 {x: i32, y: i32, z: i32, w: i32, u: i32, v: i32}; // Checks whether coordinates lie within the bounds of the shape. fn coordsInBounds2D(coord : vec2, shape : vec2) -> bool { return all(coord >= vec2(0)) && all(coord < shape); } fn coordsInBounds3D(coord : vec3, shape : vec3) -> bool { return all(coord >= vec3(0)) && all(coord < shape); } fn coordsInBounds4D(coord : vec4, shape : vec4) -> bool { return all(coord >= vec4(0)) && all(coord < shape); } fn getIndexFromCoords1D(coord : i32, shape : i32) -> i32 { return coord; } fn getIndexFromCoords2D(coords : vec2, shape : vec2) -> i32 { return dot(coords, vec2(shape.y, 1)); } fn getIndexFromCoords3D(coords : vec3, shape : vec3) -> i32 { return dot(coords, vec3(shape.y * shape.z, shape.z, 1)); } fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 { return dot(coords, vec4( shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); } fn getIndexFromCoords5D(coords : vec5, shape : vec5) -> i32 { let shapeStrides: vec5 = vec5(shape.y * shape.z * shape.w * shape.u, shape.z * shape.w * shape.u, shape.w * shape.u, shape.u, 1); return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u; } fn getIndexFromCoords6D(coords : vec6, shape : vec6) -> i32 { let shapeStrides: vec6 = vec6(shape.y * shape.z * shape.w * shape.u * shape.v, shape.z * shape.w * shape.u * shape.v, shape.w * shape.u * shape.v, shape.u * shape.v, shape.v, 1); return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u + coords.v*shapeStrides.v; } fn idiv(a: i32, b: i32, sign: f32) -> i32 { var res: i32 = a / b; let modulo: i32 = a % b; if (sign < 0. && modulo != 0) { res = res - 1; } return res; } // NaN defination in IEEE 754-1985 is : // - sign = either 0 or 1. // - biased exponent = all 1 bits. // - fraction = anything except all 0 bits (since all 0 bits represents infinity). // https://en.wikipedia.org/wiki/IEEE_754-1985#Representation_of_non-numbers fn isnan(val: f32) -> bool { let floatToUint: u32 = bitcast(val); return (floatToUint & 0x7fffffffu) > 0x7f800000u; } fn isnanVec4(val : vec4) -> vec4 { return vec4(isnan(val[0]), isnan(val[1]), isnan(val[2]), isnan(val[3])); } `;function H7(e){let t=e.length;if(t<=1)return"fn getCoordsFromIndex(index : i32) -> i32 { return index; }";let n=v.computeStrides(e),s=zn(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;return a="var index2 = index;"+n.map((o,i)=>{let l=`let ${r[i]} = index2 / uniforms.outShapeStrides.${va(i)}`,u=i===n.length-1?`let ${r[i+1]} = index2 - ${r[i]} * uniforms.outShapeStrides.${va(i)}`:`index2 = index2 - ${r[i]} * uniforms.outShapeStrides.${va(i)}`;return`${l}; ${u};`}).join(""),` fn getCoordsFromIndex(index : i32) -> ${s} { ${a} return ${s}(${r.join(",")}); } `}function c0e(e,t){let n=e.name,s=e.shape.length,r=zn(s),a="get"+n.charAt(0).toUpperCase()+n.slice(1),o=["d0","d1","d2","d3","d4","d5"].slice(0,s),i=o.map(c=>`${c} : i32`).join(", ");if(s<1)return t?` fn ${a}() -> vec4 { return vec4(${n}[0]); } `:` fn ${a}() ->f32 { return f32(${n}[0]); } `;let l=`uniforms.${n.charAt(0).toLowerCase()+n.slice(1)}Shape`,u=`${s}D`;return s===0&&(u="1D"),t?` fn ${a}(${i}) -> vec4 { return vec4(${n}[getIndexFromCoords${u}(${r}(${o.join(",")}), ${l}) / 4]); } `:` fn ${a}(${i}) -> f32 { return f32(${n}[getIndexFromCoords${u}(${r}(${o.join(",")}), ${l})]); } `}function d0e(e,t,n,s){let r=e.name,a=r.charAt(0).toUpperCase()+r.slice(1),o="get"+a+"ByOutput",i=e.shape.length,l=t.length,u=zn(l);if(v.arraysEqual(e.shape,t)&&s)return n?` fn ${o}Index(globalIndex : i32) -> vec4 { return vec4(${r}[globalIndex]); } fn ${o}Coords(coords : ${u}) -> vec4 { return vec4(${r}[${l>1?"getOutputIndexFromCoords(coords)":"coords"} / 4]); } `:` fn ${o}Index(globalIndex : i32) -> f32 { return f32(${r}[globalIndex]); } fn ${o}Coords(coords : ${u}) -> f32 { return f32(${r}[${l>1?"getOutputIndexFromCoords(coords)":"coords"}]); } `;let c=T.getBroadcastDims(e.shape,t),p=l-i,d="";if(i===0)return n?` fn ${o}Index(globalIndex : i32) -> vec4 { return get${a}(); } fn ${o}Coords(coords : ${u}) -> vec4 { return get${a}(); } `:` fn ${o}Index(globalIndex : i32) -> f32{ return get${a}(); } fn ${o}Coords(coords : ${u}) -> f32{ return get${a}(); } `;l<2&&c.length>=1?d="coords = 0;":d=c.map(g=>`coords.${va(g+p)} = 0;`).join(` `);let h="";if(l<2&&i>0)h="coords";else if(l>1){let g=zn(i),y=e.shape.map((x,A)=>`coords.${va(A+p)}`).join(", ");h=`${g}(${y})`}else h="coords";let f=`uniforms.${r.charAt(0).toLowerCase()+r.slice(1)}Shape`,m=`${i}D`;return n?` fn ${o}Index(globalIndex : i32) -> vec4 { var coords = getCoordsFromIndex(globalIndex); ${d} return ${r}[getIndexFromCoords${m}(${h}, ${f}) / 4]; } fn ${o}Coords(coordsIn : ${u}) -> vec4 { var coords = coordsIn; ${d} return ${r}[getIndexFromCoords${m}(${h}, ${f}) / 4]; } `:` fn ${o}Index(globalIndex : i32) -> f32 { var coords = getCoordsFromIndex(globalIndex); ${d} return f32(${r}[getIndexFromCoords${m}(${h}, ${f})]); } fn ${o}Coords(coordsIn : ${u}) -> f32 { var coords = coordsIn; ${d} return f32(${r}[getIndexFromCoords${m}(${h}, ${f})]); } `}function p0e(e,t,n,s){let r=c0e(e,n);return e.shape.length<=t.length&&(r+=d0e(e,t,n,s)),r}function h0e(e,t){let{x:n,y:s=[],z:r=[]}=t,a=e.length,o=n.length+s.length+r.length;if(o!==a)return"";if(n.length===a)return`fn getOutputCoords() -> ${zn(a)}{ let globalIndex = getGlobalIndex(); return getCoordsFromIndex(globalIndex); } `;let i="",l=[n,s,r];for(let d=0;d ${c} { ${i} `;return u.length===0?p+=`return ${c}(0); }`:p+=`return ${c}(${u.join(",")}); }`,p}function f0e(e){let t="";switch(e){case 0:case 1:t+=` fn getOutputIndexFromCoords(coords : i32) -> i32 { return coords; } `;break;case 2:t+=` fn getOutputIndexFromCoords(coords : vec2) -> i32 { return dot(coords, vec2(uniforms.outShapeStrides, 1)); } `;break;case 3:t+=` fn getOutputIndexFromCoords(coords : vec3) -> i32 { return dot(coords, vec3(uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, 1)); } `;break;case 4:t+=` fn getOutputIndexFromCoords(coords : vec4) -> i32 { return dot(coords, vec4( uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, uniforms.outShapeStrides.z, 1)); } `;break;case 5:t+=` fn getOutputIndexFromCoords(coords : vec5) -> i32 { return coords.x * uniforms.outShapeStrides.x + coords.y * uniforms.outShapeStrides.y + coords.z * uniforms.outShapeStrides.z + coords.w * uniforms.outShapeStrides.w + coords.u; } `;break;case 6:t+=` fn getOutputIndexFromCoords(coords : vec6) -> i32 { return coords.x * uniforms.outShapeStrides.x + coords.y * uniforms.outShapeStrides.y + coords.z * uniforms.outShapeStrides.z + coords.w * uniforms.outShapeStrides.w + coords.u * uniforms.outShapeStrides.u + coords.v; } `;break;default:v.assert(!1,()=>`Unsupported ${e}D shape`);break}return t}function tT(e){return e.dispatch[1]===1&&e.dispatch[2]===1}function op(e,t){return e==="float32"?t?"vec4":"f32":e==="int32"||e==="bool"?t?"vec4":"i32":e}function m0e(e,t,n){let s=e.length,r=op(t,n),a;if(n?a=`fn setOutputAtIndex(flatIndex : i32, value : vec4) { result[flatIndex] = ${r}(value); } fn setOutputAtIndexI32(flatIndex : i32, value : vec4) { result[flatIndex] = ${r}(value); }`:a=`fn setOutputAtIndex(flatIndex : i32, value : f32) { result[flatIndex] = ${r}(value); } fn setOutputAtIndexI32(flatIndex : i32, value : i32) { result[flatIndex] = ${r}(value); }`,s>=2){let o=["d0","d1","d2","d3","d4","d5"].slice(0,s),i=zn(s);n?a+=` fn setOutputAtCoords(${o.map(l=>`${l} : i32`).join(", ")}, value : vec4) { let flatIndex = getOutputIndexFromCoords(${i}(${o.join(", ")})); setOutputAtIndex(flatIndex / 4, value); } fn setOutputAtCoordsI32(${o.map(l=>`${l} : i32`).join(", ")}, value : vec4) { let flatIndex = getOutputIndexFromCoords(${i}(${o.join(", ")})); setOutputAtIndexI32(flatIndex / 4, value); } `:a+=` fn setOutputAtCoords(${o.map(l=>`${l} : i32`).join(", ")}, value : f32) { let flatIndex = getOutputIndexFromCoords(${i}(${o.join(", ")})); setOutputAtIndex(flatIndex, value); } fn setOutputAtCoordsI32(${o.map(l=>`${l} : i32`).join(", ")}, value : i32) { let flatIndex = getOutputIndexFromCoords(${i}(${o.join(", ")})); setOutputAtIndexI32(flatIndex, value); } `}return a}function g0e(e){let t=/(\w+)\s*:\s*vec(5|6)/g;e=e.replace(t,s=>"@align(16) "+s);let n=/vec(5|6)\s*,\s*(\w+)/g;return e=e.replace(n,(s,r,a)=>`vec${r}, @align(16) ${a}`),e}var nT={};We(nT,{ArrayBufferToTypedArray:()=>aT,GPUBytesPerElement:()=>rT,MatMulProgramType:()=>Tr,computeDispatch:()=>Be,computeWorkGroupInfoForMatMul:()=>sT,computeWorkGroupSizeForConv2d:()=>tb,computeWorkPerThreadForConv2d:()=>nb,flatDispatchLayout:()=>it,isWebGPUSupported:()=>sb,tilesFitEvenlyIntoShape:()=>y0e});var Yi=e=>{let t=1;for(let n=0;nn%e[s]===0)}function Be(e,t,n=[1,1,1],s=[1,1,1]){let[r,a,o]=[Math.ceil(Yi(e.x.map(i=>t[i]))/(n[0]*s[0])),e.y?Math.ceil(Yi(e.y.map(i=>t[i]))/(n[1]*s[1])):1,e.z?Math.ceil(Yi(e.z.map(i=>t[i]))/(n[2]*s[2])):1];return[r,a,o]}function sT(e,t,n,s=!1){let r=[8,8,1],a=[4,4,1];return s||(e<=8&&(a[1]=1),t<=16&&n<=16&&(r[0]=4)),{workGroupSize:r,elementsPerThread:a}}function tb(e,t,n=!1){if(n)return[8,8,1];let s=Yi(e.x.map(a=>t[a])),r=Yi(e.y.map(a=>t[a]));return s<=4?[4,16,1]:r<=4?[16,4,1]:[16,16,1]}function nb(e,t,n=!1){if(n)return[4,4,1];let s=Yi(e.x.map(a=>t[a])),r=Yi(e.y.map(a=>t[a]));return s<=4?[1,2,1]:r<=4?[2,1,1]:[2,2,1]}function it(e){return{x:e.map((t,n)=>n)}}function rT(e){if(e==="float32"||e==="int32"||e==="bool"||e==="string")return 4;if(e==="complex64")return 8;throw new Error(`Unknown dtype ${e}`)}function aT(e,t){if(t==="float32")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"||t==="string")return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}function sb(){return(typeof window!="undefined"||typeof WorkerGlobalScope!="undefined")&&!!navigator.gpu}var Tr;(function(e){e[e.MatMulReduceProgram=0]="MatMulReduceProgram",e[e.MatMulSplitKProgram=1]="MatMulSplitKProgram",e[e.MatMulSmallOutputSizeProgram=2]="MatMulSmallOutputSizeProgram",e[e.MatMulPackedProgram=3]="MatMulPackedProgram",e[e.MatMulMax=4]="MatMulMax"})(Tr||(Tr={}));var A0e=U().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD"),x0e=(e,t)=>{let n=e.limits.maxComputeWorkgroupsPerDimension,s=t.dispatchLayout,r=t.dispatch;if(r.every(o=>o<=n))return r;v.assert(r[0]>n&&s.y===void 0&&s.z===void 0,()=>"Dispatch size exceeds WebGPU limits in Y or Z dimension.");let a=Math.ceil(Math.sqrt(r[0]));return a>n?(a=Math.ceil(Math.cbrt(r[0])),v.assert(a<=n,()=>"Total dispatch size exceeds WebGPU maximum."),[a,a,a]):[a,a,1]},m2=class extends fc{constructor(e,t){if(super(),this.commandQueueOwnedIds=new WeakSet,this.dispatchNumberInEncoder=0,this.disposed=!1,this.downloadWaitMs=0,this.tensorDataPendingDisposal=[],this.stagingPendingDisposal=[],this.uniformPendingDisposal=[],this.uploadWaitMs=0,!sb())throw new Error("WebGPU is not supported on this device");this.pipelineCache={},this.device=e,this.queue=e.queue,this.currentCommandEncoder=null,this.currentComputePass=null,this.supportTimeQuery=e.features.has("timestamp-query"),this.adapterInfo=new s0e(t),this.bufferManager=new r0e(this.device),this.textureManager=new a0e(this.device),this.tensorMap=new Tp(this,Jt()),this.supportTimeQuery&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:2})),U().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 m2.nextDataId++}floatPrecision(){return 32}defaultGpuBufferUsage(){return GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}disposeData(e,t=!1){if(this.tensorDataPendingDisposal.indexOf(e)>=0)return!1;if(!this.tensorMap.has(e))return!0;let n=this.tensorMap.get(e);if(this.decRef(e),!t&&n.refCount>0)return!1;if(this.commandQueueOwnedIds.has(e))return this.tensorDataPendingDisposal.push(e),!1;let{complexTensorInfos:s}=this.tensorMap.get(e);return s!=null&&(this.disposeData(s.real.dataId,t),this.disposeData(s.imag.dataId,t)),this.releaseResource(e),this.tensorMap.delete(e),!0}memory(){return{numBytesInGPU:this.bufferManager.numBytesUsed,numBytesAllocatedInGPU:this.bufferManager.numBytesAllocated,unreliable:!1}}releaseResource(e){let t=this.tensorMap.get(e);if(!(!t||!t.resourceInfo)){if("texture"in t.resourceInfo){let n=t.resourceInfo;n.texture instanceof GPUTexture&&this.textureManager.releaseTexture(n.texture,n.width,n.height,n.format,n.usage),n.texture=null}else{let n=t.resourceInfo;this.bufferManager.releaseBuffer(n.buffer,n.size,n.usage),n.buffer=null}t.resourceInfo=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()};return this.tensorMap.set(s,{dtype:n,shape:t,values:e,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).");this.tensorMap.set(e,{dtype:s,shape:n,values:t,refCount:r})}submitQueue(){this.ensureComputePassEnded(),this.queue.submit([this.currentCommandEncoder.finish()]),this.currentCommandEncoder=null,this.dispatchNumberInEncoder=0,this.commandQueueOwnedIds=new WeakSet,this.tensorDataPendingDisposal.forEach(e=>{this.releaseResource(e),this.tensorMap.delete(e)}),this.uniformPendingDisposal.forEach(e=>this.bufferManager.releaseBuffer(e.buffer,e.size,e.usage)),this.stagingPendingDisposal.forEach(e=>this.bufferManager.releaseUploadBuffer(e.buffer,e.size,e.usage)),this.tensorDataPendingDisposal=[],this.uniformPendingDisposal=[],this.stagingPendingDisposal=[]}ensureCommandEncoderReady(){this.currentCommandEncoder||(this.currentCommandEncoder=this.device.createCommandEncoder())}ensureComputePassEnded(){this.currentComputePass&&(this.currentComputePass.end(),this.currentComputePass=null)}getComputePass(){return this.currentComputePass||(this.currentComputePass=this.currentCommandEncoder.beginComputePass()),this.currentComputePass}async getBufferData(e,t){let n=this.bufferManager.acquireBuffer(t,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(e,0,n,0,t),this.submitQueue(),await n.mapAsync(GPUMapMode.READ);let s=n.getMappedRange().slice(0);return n.unmap(),n!=null&&this.bufferManager.releaseBuffer(n,t,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ),U().getBool("WEBGPU_USE_PROFILE_TOOL")&&(v.assert(this.dummyContext!==void 0,()=>"Fail to get context for profiling tool"),this.dummyContext.getCurrentTexture()),s}convertAndCacheOnCPU(e,t){let n=this.tensorMap.get(e);return this.releaseResource(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=T.mergeRealAndImagArrays(a,o)}else{let r=t.resourceInfo,a=await this.getBufferData(r.buffer,r.size);s=aT(a,t.dtype)}return this.convertAndCacheOnCPU(e,s),s}readToGPU(e){let t=this.tensorMap.get(e),{values:n,dtype:s,shape:r,resourceInfo:a}=t;if(s==="complex64")throw new Error("Does not support reading buffer for complex64 dtype.");if(a==null)throw n!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");let o=a.size,i=this.bufferManager.acquireBuffer(o,a.usage);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(a.buffer,0,i,0,o),this.submitQueue();let l=this.makeTensorInfo(r,s),u=Jt().makeTensorFromTensorInfo(l),c=this.tensorMap.get(l.dataId);return c.resourceInfo={size:o,usage:this.defaultGpuBufferUsage(),buffer:i},{tensorRef:u,buffer:i,bufSize:o}}bufferSync(e){let t=this.readSync(e.dataId);if(e.dtype==="string")try{let n=t.map(s=>v.decodeString(s));return ze(e.shape,e.dtype,n)}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return ze(e.shape,e.dtype,t)}async time(e){this.supportTimeQuery||console.warn("This device doesn't support timestamp-query extension. Start Chrome browser with flag --disable-dawn-features=disallow_unsafe_apis then try again. Otherwise, zero will be shown for the kernel time when profiling mode is enabled. Using performance.now is not workable for webgpu since it doesn't support synchronous data read from GPU.");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,u)=>({name:a[u],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", "),this.uploadWaitMs=0,this.downloadWaitMs=0,o}makeTensorInfo(e,t,n){return t==="string"&&n!=null&&n.length>0&&v.isString(n[0])&&(n=n.map(r=>v.encodeString(r))),{dataId:this.write(n,e,t),shape:e,dtype:t}}tensorToBinding(e){if(!e)return null;let t=this.tensorMap.get(e.dataId);if("texture"in t.resourceInfo){let s=t.resourceInfo;return s.texture instanceof GPUExternalTexture?s.texture:s.texture.createView()}let n=t.resourceInfo;return{offset:0,size:n.size,buffer:n.buffer}}async getQueryTime(e){return this.supportTimeQuery?this.getTimeFromQuerySet(e):0}uploadToGPU(e){let t=this.tensorMap.get(e);if(t.resourceInfo)return;let n=rT(t.dtype)*v.sizeFromShape(t.shape),s=this.bufferManager.acquireBuffer(n,this.defaultGpuBufferUsage());if(t.resourceInfo={size:n,usage:this.defaultGpuBufferUsage(),buffer:s},t.values){let r=this.bufferManager.acquireUploadBuffer(n,GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC),a=r.getMappedRange();t.dtype==="int32"||t.dtype==="bool"?new Int32Array(a).set(t.values):new Float32Array(a).set(t.values),r.unmap(),this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(r,0,s,0,n);let o={size:n,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC,buffer:r};this.stagingPendingDisposal.push(o)}}makeUniforms(e){let t=0,n=0,s=[];e.forEach(i=>{i.data.length===0&&(i.data=[1]);let l;switch(i.data.length){case 1:l=4;break;case 2:l=8;break;case 3:l=16;break;case 4:l=16;break;case 5:l=16;break;case 6:l=16;break;default:v.assert(!1,()=>`Unsupported ${i.data.length}D shape`)}(n===5||n===6)&&(l=16),t=Math.ceil(t/l)*l,n=i.data.length,s.push(t),t+=i.data.length*4});let r=new ArrayBuffer(t);e.forEach((i,l)=>{let u=s[l];i.type==="int32"?new Int32Array(r,u,i.data.length).set(i.data):i.type==="uint32"?new Uint32Array(r,u,i.data.length).set(i.data):new Float32Array(r,u,i.data.length).set(i.data)});let a=this.bufferManager.acquireBuffer(t,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.queue.writeBuffer(a,0,r,0,t);let o={size:t,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM,buffer:a};return this.uniformPendingDisposal.push(o),{offset:0,size:t,buffer:a}}runWebGPUProgram(e,t,n,s,r){if(r||(r=this.makeTensorInfo(e.outputShape,n)),v.sizeFromShape(r.shape)===0)return this.tensorMap.get(r.dataId).values=v.getTypedArrayFromDType(r.dtype,0),r;this.uploadToGPU(r.dataId),e.dispatch=x0e(this.device,e);let a=[],o=[];if(!e.isFromPixels){a.push({type:"float32",data:[NaN]}),o=t.concat(r).map(g=>g.shape);let f="int32";o.map(g=>{a.push({type:f,data:g})});let m=v.computeStrides(r.shape);if(a.push({type:f,data:m}),e.size){let g=v.sizeFromShape(e.outputShape);a.push({type:f,data:[e.isVec4?g/4:g]})}}let i=t.map((f,m)=>{if(f.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(f.dataId),{dtype:this.tensorMap.get(f.dataId).dtype,shape:f.shape,name:e.variableNames[m]}}),l=u0e(e,o,i,r),u;l in this.pipelineCache?u=this.pipelineCache[l]:(u=i0e(this.device,e,i,r),this.pipelineCache[l]=u),s&&(a=[...a,...s]);let c=[this.tensorToBinding(r),...t.map(f=>this.tensorToBinding(f)),this.makeUniforms(a)],p=this.device.createBindGroup({layout:u.getBindGroupLayout(0),entries:c.map((f,m)=>({binding:m,resource:f}))});this.ensureCommandEncoderReady();let d=this.getComputePass(),h=this.activeTimers!=null;return h&&this.supportTimeQuery&&d.writeTimestamp(this.querySet,0),d.setPipeline(u),d.setBindGroup(0,p),d.dispatchWorkgroups(e.dispatch[0],e.dispatch[1],e.dispatch[2]),h&&this.supportTimeQuery&&d.writeTimestamp(this.querySet,1),this.dispatchNumberInEncoder++,t.forEach(f=>{this.commandQueueOwnedIds.add(f.dataId)}),this.commandQueueOwnedIds.add(r.dataId),U().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE")<=this.dispatchNumberInEncoder&&this.submitQueue(),h&&this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(this.querySet)}),r}async getTimeFromQuerySet(e){let t=this.bufferManager.acquireBuffer(16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),n=this.bufferManager.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=A0e){return U().getBool("WEBGPU_CPU_FORWARD")&&e.every(n=>this.tensorMap.get(n.dataId).resourceInfo==null&&v.sizeFromShape(n.shape){U().set("CHECK_COMPUTATION_FOR_ERRORS",!1);let e={powerPreference:U().get("WEBGPU_USE_LOW_POWER_GPU")?"low-power":"high-performance"},t=await navigator.gpu.requestAdapter(e),n=t.limits,s={},r=t.features.has("timestamp-query");s.requiredLimits={maxComputeWorkgroupStorageSize:n.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:n.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:n.maxStorageBufferBindingSize},r&&(s.requiredFeatures=["timestamp-query"]);let a=await t.requestDevice(s),o=await t.requestAdapterInfo();return new m2(a,o)},3);var Xe;(function(e){e[e.MUL=0]="MUL",e[e.ADD=1]="ADD",e[e.ATAN2=2]="ATAN2",e[e.SUB=3]="SUB",e[e.DIV=4]="DIV",e[e.EQUAL=5]="EQUAL",e[e.GREATER=6]="GREATER",e[e.GREATER_EQUAL=7]="GREATER_EQUAL",e[e.LESS=8]="LESS",e[e.LESS_EQUAL=9]="LESS_EQUAL",e[e.LOGICAL_AND=10]="LOGICAL_AND",e[e.NOT_EQUAL=11]="NOT_EQUAL",e[e.SQUARED_DIFFERENCE=12]="SQUARED_DIFFERENCE",e[e.INT_DIV=13]="INT_DIV",e[e.POW=14]="POW",e[e.PRELU=15]="PRELU",e[e.MAX=16]="MAX",e[e.MIN=17]="MIN",e[e.COMPLEX_MULTIPLY_REAL=18]="COMPLEX_MULTIPLY_REAL",e[e.COMPLEX_MULTIPLY_IMAG=19]="COMPLEX_MULTIPLY_IMAG"})(Xe||(Xe={}));var b0e=` if (isnan(a)) { return a; } if (isnan(b)) { return b; } `,oT=` if (isNaN.r) { resultTemp.r = valueForNaN; } if (isNaN.g) { resultTemp.g = valueForNaN; } if (isNaN.b) { resultTemp.b = valueForNaN; } if (isNaN.a) { resultTemp.a = valueForNaN; } `,iT=` let isNaN = isnanVec4(a) | isnanVec4(b); ${oT} `,v0e="return a + b;",w0e="return areal * breal - aimag * bimag;",k0e="return areal * bimag + aimag * breal;",S0e="return a / b;",I0e="return a * b;",C0e="return (a - b) * (a - b);",T0e="return a - b;",N0e="return f32(a == b);",E0e="return vec4(a == b);",R0e="return f32(a > b);",_0e="return vec4(a > b);",D0e="return f32(a >= b);",$0e="return vec4(a >= b);",P0e="return f32(a < b);",F0e="return vec4(a < b);",O0e="return f32(a <= b);",M0e="return vec4(a <= b);",z0e="return f32(f32(a) >= 1.0 && f32(b) >= 1.0);",L0e=`return (vec4(a >= vec4(1.0)) * vec4(b >= vec4(1.0)));`,B0e=` let s = sign(a) * sign(b); let ia = i32(round(a)); let ib = i32(round(b)); return f32(idiv(ia, ib, s)); `,W0e=` 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); `,V0e=` if (isnan(a) || isnan(b)) { return 1.0; } return f32(a != b); `,U0e=` var resultTemp = vec4(a != b); let valueForNaN = 1.0; ${iT} return resultTemp; `,G0e=` 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); `,H0e=` 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 = (a < vec4(0.0)) & (floor(b) < b); let valueForNaN = uniforms.NAN; ${oT} return resultTemp; `,j0e="if (a < 0.0) { return b * a; } return a;",q0e=` let aLessThanZero = vec4(a < vec4(0.0)); return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); `;function u3(e,t,n="uniforms.NAN"){let s=t?iT:b0e;return t?` let valueForNaN = ${n}; var resultTemp = vec4(${e}(a, b)); `+s+` return resultTemp; `:s+` return ${e}(a, b); `}function rb(e,t){switch(e){case Xe.MUL:return I0e;case Xe.ADD:return v0e;case Xe.ATAN2:return u3("atan2",t);case Xe.SUB:return T0e;case Xe.DIV:return S0e;case Xe.EQUAL:return t?E0e:N0e;case Xe.GREATER:return t?_0e:R0e;case Xe.GREATER_EQUAL:return t?$0e:D0e;case Xe.LESS:return t?F0e:P0e;case Xe.LESS_EQUAL:return t?M0e:O0e;case Xe.LOGICAL_AND:return t?L0e:z0e;case Xe.NOT_EQUAL:return t?U0e:V0e;case Xe.SQUARED_DIFFERENCE:return C0e;case Xe.INT_DIV:return t?W0e:B0e;case Xe.PRELU:return t?q0e:j0e;case Xe.MAX:return u3("max",t);case Xe.MIN:return u3("min",t);case Xe.POW:return t?H0e:G0e;case Xe.COMPLEX_MULTIPLY_REAL:return w0e;case Xe.COMPLEX_MULTIPLY_IMAG:return k0e;default:throw new Error(`BinaryType ${e} is not implemented!`)}}var De;(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.IS_NAN=8]="IS_NAN",e[e.LINEAR=9]="LINEAR",e[e.LOG=10]="LOG",e[e.LOGICAL_NOT=11]="LOGICAL_NOT",e[e.NEG=12]="NEG",e[e.RELU=13]="RELU",e[e.RELU6=14]="RELU6",e[e.LEAKYRELU=15]="LEAKYRELU",e[e.RECIPROCAL=16]="RECIPROCAL",e[e.RSQRT=17]="RSQRT",e[e.SIN=18]="SIN",e[e.SINH=19]="SINH",e[e.SIGMOID=20]="SIGMOID",e[e.SQRT=21]="SQRT",e[e.SQUARE=22]="SQUARE",e[e.TANH=23]="TANH",e[e.TO_INT=24]="TO_INT"})(De||(De={}));var X0e="return abs(a);",K0e="return ceil(a);",Z0e="return cos(a);",Y0e=` let e2x = exp(-a); return (e2x + 1.0 / e2x) / 2.0; `,J0e="return exp(a) - 1.0;",Q0e="if (a >= 0.0) { return a; } return (exp(a) - 1.0);",e2e=` 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; `,t2e="return exp(a);",n2e="return floor(a);",s2e="return f32(isnan(a));",r2e="return a;",a2e=`if (a < 0.0) { return uniforms.NAN; } return log(a);`,o2e="return f32(!(a >= 1.0));",i2e="return -a;",l2e="if (a < 0.0) { return uniforms.alpha * a; } return a;",u2e=` let aLessThanZero = vec4(a < vec4(0.0)); return (aLessThanZero * (uniforms.alpha * a)) + ((vec4(1.0) - aLessThanZero) * a); `,c2e="return 1.0 / a;",d2e="return select(a, 0.0, a < 0.0);",p2e="return clamp(a, 0.0, 6.0);",h2e="return clamp(a, vec4(0.0, 0.0, 0.0, 0.0), vec4(6.0, 6.0, 6.0, 6.0));",f2e=` return select(a, vec4(0.0), a < vec4(0.0)); `,m2e="return 1.0/sqrt(a);",g2e="return 1.0 / (1.0 + exp(-1.0 * a));",y2e="return sin(a);",A2e=` let e2x = exp(a); return (e2x - 1.0 / e2x) / 2.0; `,x2e="return sqrt(a);",b2e="return a * a;",v2e=` let e2x = exp(-2.0 * abs(a)); return sign(a) * (1.0 - e2x) / (1.0 + e2x); `,w2e="return f32(i32((a)));";function Li(e,t){switch(e){case De.ABS:return X0e;case De.COS:return Z0e;case De.COSH:return Y0e;case De.CEIL:return K0e;case De.ELU:return t?e2e:Q0e;case De.EXP:return t2e;case De.EXPM1:return J0e;case De.FLOOR:return n2e;case De.IS_NAN:return s2e;case De.LINEAR:return r2e;case De.LOG:return a2e;case De.LOGICAL_NOT:return o2e;case De.NEG:return i2e;case De.LEAKYRELU:return t?u2e:l2e;case De.RECIPROCAL:return c2e;case De.RELU:return t?f2e:d2e;case De.RELU6:return t?h2e:p2e;case De.RSQRT:return m2e;case De.SIGMOID:return g2e;case De.SIN:return y2e;case De.SINH:return A2e;case De.SQRT:return x2e;case De.SQUARE:return b2e;case De.TANH:return v2e;case De.TO_INT:return w2e;default:throw new Error(`BinaryType ${e} is not implemented!`)}}var Yt=e=>{switch(e){case 1:return"f32";case 2:return"vec2";case 3:return"vec3";case 4:return"vec4";default:throw new Error(`${e}-component is not supported.`)}};function Pa(e,t=!1,n=!1,s=3){if(e===null)return"";let r="";if(e==="linear")r=Li(De.LINEAR);else if(e==="relu")r=Li(De.RELU,n);else if(e==="elu")r=Li(De.ELU,n);else if(e==="relu6")r=Li(De.RELU6,n);else if(e==="prelu")r=rb(Xe.PRELU,n);else if(e==="sigmoid")r=Li(De.SIGMOID,n);else if(e==="leakyrelu")r=Li(De.LEAKYRELU,n);else throw new Error(`Activation ${e} has not been implemented for the WebGPU backend.`);let o=Yt(n?4:1),i="";return t?i=` fn activation(a : ${o}, coords : vec${s}) -> ${o} { let b = getPreluActivationWeightsByOutputCoords(coords); ${r} }`:i=` fn activation(a : ${o}, coords : vec${s}) -> ${o} { ${r} }`,i}function hu(e,t){return` ${e?"value = value + getBiasByOutputCoords(coords);":""} ${t?"value = activation(value, coords);":""} `}function lT(e,t,n,s,r=!1,a=!1,o=!1,i=1){v.assert(n&&i===1||!n,()=>`transposeA ${n} is not compatible with component size ${i}`);let l=` let batch = ${e?"0":"batchIn"}; ${n?"value = getA(batch, col, row);":"value = getA(batch, row, col);"} `,u=s?"value = getB(batch, col, row);":"value = getB(batch, row, col);";return` fn mm_readA(batchIn: i32, row: i32, colIn: i32) -> ${Yt(i)} { var value = ${Yt(i)}(0.0); let col = colIn * ${i}; ${r&&o?l:` ${n?"if(row < uniforms.dimAOuter && col < uniforms.dimInner)":"if(row < uniforms.aShape[1] && col < uniforms.aShape[2])"} { ${l} } `} return value; } fn mm_readB(batchIn: i32, row: i32, colIn: i32) -> ${Yt(i)} { let col = colIn * ${i}; let batch = ${t?"0":"batchIn"}; var value = ${Yt(i)}(0.0); ${u} return value; } `}function ab(e,t,n,s,r,a,o=!1,i=!1,l=!1,u=1){return` ${lT(n,s,r,a,o,i,l,u)} fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Yt(u)}) { let col = colIn * ${u}; ${o&&i?"":"if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)"} { var value = valueIn; let coords = vec3(batch, row, col); ${hu(e,t)} setOutputAtCoords(coords[0], coords[1], coords[2], value); } } `}var k2e=e=>e?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart / InnerElementSize + inputCol); `:` mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRow + innerRow, kStart / InnerElementSize + inputCol); `,S2e=(e,t)=>e?` let ACached0 = mm_Asub[k * InnerElementSize][localRow]; let ACached1 = mm_Asub[k * InnerElementSize + 1][localRow]; let ACached2 = mm_Asub[k * InnerElementSize + 2][localRow]; ${t===3?"":"let ACached3 = mm_Asub[k * InnerElementSize + 3][localRow];"} for (var i = 0; i < RowPerThread; i = i + 1) { acc[i] = BCached0 * ACached0[i] + acc[i]; acc[i] = BCached1 * ACached1[i] + acc[i]; acc[i] = BCached2 * ACached2[i] + acc[i]; ${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} }`:` for (var i = 0; i < RowPerThread; i = i + 1) { let ACached = mm_Asub[tileRow + i][k]; acc[i] = BCached0 * ACached.x + acc[i]; acc[i] = BCached1 * ACached.y + acc[i]; acc[i] = BCached2 * ACached.z + acc[i]; ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} }`;function g2(e,t,n=!1,s=32,r=!1,a=32,o=!1){let i=t[1]*e[1],l=t[0]*e[0],u=n?i:s,c=n?s:i,p=u/t[0],d=s/t[1];return v.assert((n&&p===4&&e[1]===4||!n&&(p===3||p===4))&&u%t[0]===0&&s%t[1]===0&&e[0]===4,()=>`If transposeA ${n} is true, innerElementSize ${p} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${p} must be 3 or 4. tileAWidth ${u} must be divisible by workGroupSize[0]${t[0]}. tileInner ${s} must be divisible by workGroupSize[1] ${t[1]}. ColPerThread ${e[0]} must be 4.`),` var mm_Asub : array, ${u/p}>, ${c}>; var mm_Bsub : array, ${l/e[0]}>, ${s}>; const RowPerThread = ${e[1]}; const ColPerThread = ${e[0]}; const InnerElementSize = ${p}; const TileInner = ${s}; @compute @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ) fn _start(@builtin(local_invocation_id) LocalId : vec3, @builtin(global_invocation_id) GlobalId : vec3, @builtin(num_workgroups) NumWorkgroups: vec3, @builtin(workgroup_id) workgroupId: vec3) { localId = LocalId; globalId = GlobalId; numWorkgroups = NumWorkgroups; let localRow = i32(localId.y); let tileRow = ${o?"0":"localRow * RowPerThread"}; let tileCol = i32(localId.x); let globalRow = ${o?"0":"i32(globalId.y) * RowPerThread"}; let globalCol = i32(globalId.x); let batch = ${r?"0":"i32(globalId.z)"}; let globalRowStart = i32(workgroupId.y) * ${i}; let numTiles = ${r?`${Math.ceil(a/s)}`:"(uniforms.dimInner - 1) / TileInner + 1"}; var kStart = ${r?`i32(globalId.z) * ${a}`:"0"}; var acc: array, RowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${d}; 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; ${k2e(n)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${d}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol); } kStart = kStart + TileInner; workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < TileInner / InnerElementSize; k = k + 1) { let BCached0 = mm_Bsub[k * InnerElementSize][tileCol]; let BCached1 = mm_Bsub[k * InnerElementSize + 1][tileCol]; let BCached2 = mm_Bsub[k * InnerElementSize + 2][tileCol]; ${p===3?"":"let BCached3 = mm_Bsub[k * InnerElementSize + 3][tileCol];"} ${S2e(n,p)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`}var j7=e=>e?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart + inputCol); `:` mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRowStart + inputRow, kStart + inputCol); `,I2e=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];";function y2(e,t,n=!1,s=32,r=!1,a=32,o=!1){let i=e[1]*t[1],l=e[0]*t[0],u=n?i:s,c=n?s:i;v.assert(c%t[1]===0&&u%t[0]===0&&s%t[1]===0,()=>`tileAHight ${c} must be divisible by workGroupSize[1]${t[1]}, tileAWidth ${u} must be divisible by workGroupSize[0]${t[0]}, tileInner ${s} must be divisible by workGroupSize[1]${t[1]}`);let p=c/t[1],d=u/t[0],h=s/t[1],f=o?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${i}; let globalColStart = i32(workgroupId.x) * ${l}; // Loop over shared dimension. for (var t = 0; t < numTiles; t = t + 1) { // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${c}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${t[0]}) { ${j7(n)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${s}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${l}; inputCol = inputCol + ${t[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol); } } kStart = kStart + TileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array; for (var k = 0; k < TileInner; k = k + 1) { for (var inner = 0; inner < ColPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; } for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) { let ACached = ${n?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`} for (var innerCol = 0; innerCol < ColPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${t[1]}; for (var innerCol = 0; innerCol < ColPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${t[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } `:` let tileRow = i32(localId.y) * RowPerThread; let tileCol = i32(localId.x) * ColPerThread; let globalRow = i32(globalId.y) * RowPerThread; let globalCol = i32(globalId.x) * ColPerThread; let globalRowStart = i32(workgroupId.y) * ${i}; let tileRowA = i32(localId.y) * ${p}; let tileColA = i32(localId.x) * ${d}; let tileRowB = i32(localId.y) * ${h}; // 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 < ${p}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${d}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${j7(n)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${h}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ColPerThread; innerCol = innerCol + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol + innerCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol + innerCol); } } kStart = kStart + TileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array; for (var k = 0; k < TileInner; k = k + 1) { for (var inner = 0; inner < ColPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][tileCol + inner]; } for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) { ${I2e(n)} for (var innerCol = 0; innerCol < ColPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ColPerThread; innerCol = innerCol + 1) { mm_write(batch, globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol]); } } `;return` var mm_Asub : array, ${c}>; var mm_Bsub : array, ${s}>; const RowPerThread = ${e[1]}; const ColPerThread = ${e[0]}; const TileInner = ${s}; @compute @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ) fn _start(@builtin(local_invocation_id) LocalId : vec3, @builtin(global_invocation_id) GlobalId : vec3, @builtin(num_workgroups) NumWorkgroups: vec3, @builtin(workgroup_id) workgroupId: vec3) { localId = LocalId; globalId = GlobalId; numWorkgroups = NumWorkgroups; let batch = ${r?"0":"i32(globalId.z)"}; let numTiles = ${r?`${Math.ceil(a/s)}`:"(uniforms.dimInner - 1) / TileInner + 1"}; var kStart = ${r?`i32(globalId.z) * ${a}`:"0"}; var acc : array, RowPerThread>; // Without this initialization strange values show up in acc. for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ColPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = 0.0; } } ${f} } `}var C2e=e=>e?` mm_readA(batch, colA, globalRow), mm_readA(batch, colA + 1, globalRow), mm_readA(batch, colA + 2, globalRow), mm_readA(batch, colA + 3, globalRow) `:` mm_readA(batch, globalRow, colA), mm_readA(batch, globalRow, colA + 1), mm_readA(batch, globalRow, colA + 2), mm_readA(batch, globalRow, colA + 3) `;function T2e(e,t=!1){return v.assert(e[1]===1&&e[2]===1,()=>`A linear work group size is required. But got ${e}.`),` const TileSize = ${e[0]*4}; var mm_Asub : array, ${e[0]}>; ${Je()} { let tileCol = i32(localId.x); let globalCol = i32(globalId.x); let globalRow = i32(globalId.y); let numTiles = (uniforms.dimInner - 1) / TileSize + 1; let batch = i32(globalId.z); // 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(${C2e(t)}); workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < TileSize / 4; k = k + 1) { let rowB = t * TileSize + k * 4; let BCached = vec4(mm_readB(batch, rowB, globalCol), mm_readB(batch, rowB + 1, globalCol), mm_readB(batch, rowB + 2, globalCol), mm_readB(batch, rowB + 3, globalCol)); let ACached = mm_Asub[k]; acc = acc + dot(ACached, BCached); } workgroupBarrier(); } mm_write(batch, globalRow, globalCol, acc); } `}var N2e=class{constructor(e,t,n,s,r=!1,a=!1,o=null,i=null,l=null,u=!1){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.outputShape=t,this.dispatchLayout={x:[2],y:[1],z:[0]};let c=r?e[1]:e[2];if(this.isVec4=(c%4===0&&!r||t[1]%4===0&&r)&&t[2]%4===0&&!a,this.isVectorA=t[1]===1&&!r,!this.isVec4&&this.isVectorA)this.elementsPerThread=[1,1,1],this.workGroupSize=[32,1,1];else{let h=sT(t[1],c,t[2],r);this.workGroupSize=h.workGroupSize,this.elementsPerThread=h.elementsPerThread}this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread);let p=o!=null,d=l!=null;p&&this.variableNames.push("bias"),d&&this.variableNames.push("preluActivationWeights"),this.sequentialAccessByThreads=u,this.transposeA=r,this.transposeB=a,this.addBias=p,this.activation=i,this.hasPreluActivationWeights=d,this.batchAEqualOne=n,this.batchBEqualOne=s,[this.fitAOuter,this.fitBOuter,this.fitInner]=this.getShapeFit(t[1],t[2],c),this.shaderKey=`matMulPacked_${this.elementsPerThread}_${r}_${a}_${this.activation}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.isVec4}_${this.isVectorA}_${this.batchAEqualOne}_${this.batchBEqualOne}_${this.sequentialAccessByThreads}`}getShapeFit(e,t,n){let s=this.workGroupSize[1]*this.elementsPerThread[1],r=this.workGroupSize[0]*this.elementsPerThread[0];!this.isVec4&&this.isVectorA?this.tileInner=this.workGroupSize[0]*4:this.tileInner=r;let a=e%s===0,o=t%r===0,i=n%this.tileInner===0;return[a,o,i]}getUserCode(){return` ${Pa(this.activation,this.hasPreluActivationWeights,this.isVec4)} ${ab(this.addBias,this.activation,this.batchAEqualOne,this.batchBEqualOne,!1,this.transposeB,this.fitAOuter,this.fitBOuter,this.fitInner,this.isVec4?4:1)} ${this.isVec4?g2(this.elementsPerThread,this.workGroupSize,this.transposeA,this.tileInner,!1,null,this.isVectorA):this.isVectorA?T2e(this.workGroupSize,this.transposeA):y2(this.elementsPerThread,this.workGroupSize,this.transposeA,this.tileInner,!1,null,this.sequentialAccessByThreads)} `}};function E2e(){return` var sumValues : array; ${Je()} { let coords = getOutputCoords(); let batch = coords[0]; let row = coords[1]; let col = coords[2]; var sum = 0.0; let Length = uniforms.dimInner; for (var k = i32(localId.x); k < Length; k = k + i32(workGroupSizeX)) { let dataA = mm_readA(batch, row, k); let dataB = mm_readB(batch, k, col); sum = sum + dataA * dataB; } sumValues[localId.x] = sum; workgroupBarrier(); for(var currentSize = workGroupSizeX / 2u; currentSize > 1u; currentSize = currentSize / 2u) { if (localId.x < currentSize) { sumValues[localId.x] = sumValues[localId.x] + sumValues[localId.x + currentSize]; } workgroupBarrier(); } if (localId.x == 0u) { sum = sumValues[0] + sumValues[1]; mm_write(batch, row, col, sum); } } `}var R2e=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=[256,1,1],this.outputShape=e,this.dispatchLayout={x:[],y:[1,2],z:[0]},this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize);let l=a!=null,u=i!=null;l&&this.variableNames.push("bias"),u&&this.variableNames.push("preluActivationWeights"),this.transposeA=s,this.transposeB=r,this.addBias=l,this.activation=o,this.hasPreluActivationWeights=u,this.batchAEqualOne=t,this.batchBEqualOne=n,this.shaderKey=`matMulReduce_${this.activation}_${s}_${r}_${this.batchAEqualOne}_${this.batchBEqualOne}`}getUserCode(){return` ${Pa(this.activation,this.hasPreluActivationWeights)} ${ab(this.addBias,this.activation,this.batchAEqualOne,this.batchBEqualOne,this.transposeA,this.transposeB)} ${E2e()} `}};function _2e(e){let t=e[1],n=e[0],s=t>n?t:n;return` var mm_Asub : array, ${t}>; var mm_Bsub : 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. // Read data from global memory to registers firstly, then store them into // shared memory, so it is instruction-Level parallelism for arithmetic // operations and others handle IO operations between barrier api, makes ALU // and load/store units work simultaneously, could improves the performance. ${Je()} { let tileRow = i32(localId.y); let tileCol = i32(localId.x); let globalRow = i32(globalId.y); let globalCol = i32(globalId.x); let batch = i32(globalId.z); // uniforms.dimInner should be greater than 0. let numTiles = (uniforms.dimInner - 1) / ${s} + 1; var acc = 0.0; var globalColA = tileCol; var globalRowB = 0; var regA = mm_readA(batch, globalRow, globalColA); var regB0 = mm_readB(batch, globalRowB + 2 * tileRow, globalCol); var regB1 = mm_readB(batch, globalRowB + 2 * tileRow + 1, globalCol); globalColA = globalColA + ${s}; globalRowB = globalRowB + ${s}; for (var t = 0; t < numTiles; t = t + 1) { mm_Asub[tileRow][tileCol] = regA; mm_Bsub[2 * tileRow][tileCol] = regB0; mm_Bsub[2 * tileRow + 1][tileCol] = regB1; workgroupBarrier(); regA = mm_readA(batch, globalRow, globalColA); regB0 = mm_readB(batch, globalRowB + 2 * tileRow, globalCol); regB1 = mm_readB(batch, globalRowB + 2 * tileRow + 1, globalCol); globalColA = globalColA + ${s}; globalRowB = globalRowB + ${s}; for (var k = 0; k < ${s}; k = k + 1) { acc = acc + mm_Asub[tileRow][k] * mm_Bsub[k][tileCol]; } workgroupBarrier(); } mm_write(batch, globalRow, globalCol, acc); } `}var D2e=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,8,1],this.outputShape=n,this.dispatchLayout={x:[2],y:[1],z:[0]},this.dispatch=[Math.ceil(n[2]/this.workGroupSize[0]),Math.ceil(n[1]/this.workGroupSize[1]),n[0]];let l=a!=null;l&&this.variableNames.push("bias");let u=i!=null;u&&this.variableNames.push("preluActivationWeights"),this.transposeA=s,this.transposeB=r,this.addBias=l,this.activation=o,this.hasPreluActivationWeights=u,this.batchAEqualOne=e[0]===1,this.batchBEqualOne=t[0]===1,this.shaderKey=`matMulSmallOutputSize_${this.activation}_${s}_${r}_${this.batchAEqualOne}_${this.batchBEqualOne}`}getUserCode(){return` ${Pa(this.activation,this.hasPreluActivationWeights)} ${ab(this.addBias,this.activation,this.batchAEqualOne,this.batchBEqualOne,this.transposeA,this.transposeB)} ${_2e(this.workGroupSize)} `}},$2e=class{constructor(e,t,n,s,r=!1,a=!1){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workGroupSize=[8,8,1],this.atomic=!0,this.isVec4=!1,this.splitedDimInner=128,v.assert(e[0]===1,()=>"MatMulSplitKProgram only supports batch = 1."),this.outputShape=e,this.dispatchLayout={x:[2],y:[1],z:[0,3]},this.isVec4=(r&&this.outputShape[1]%4===0||!r&&t%4===0)&&this.outputShape[2]%4===0,this.elementsPerThread=[4,4,this.splitedDimInner],this.isVec4||(this.outputShape[1]<16&&(this.elementsPerThread[1]=1),this.outputShape[2]<16&&(this.elementsPerThread[0]=1)),this.dispatch=Be(this.dispatchLayout,[this.outputShape[0],this.outputShape[1],this.outputShape[2],t],this.workGroupSize,this.elementsPerThread),this.transposeA=r,this.transposeB=a,this.batchAEqualOne=n,this.batchBEqualOne=s,this.shaderKey=`matMulSplitK_${r}_${a}_${n}_${s}_${this.elementsPerThread}_${this.isVec4}`}getUserCode(){let e=s=>` for (var i = 0; i < ${s}; i = i + 1) { var oldValue = atomicLoad(&(result[flatIndex + i])); var exchanged = false; for (; !exchanged;) { let newValueF32 = bitcast(oldValue) + ${s>1?"value[i]":"value"}; let newValue = bitcast(newValueF32); let res = atomicCompareExchangeWeak(&(result[flatIndex + i]), oldValue, newValue); oldValue = res.old_value; exchanged = res.exchanged; } } `,t=this.isVec4?4:1;return` ${lT(this.batchAEqualOne,this.batchBEqualOne,!1,this.transposeB,!1,!1,!1,t)} fn mm_write(batch: i32, row : i32, colIn : i32, value : ${Yt(t)}) { let col = colIn * ${t}; if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) { let coords = vec3(batch, row, col); let flatIndex = getOutputIndexFromCoords(coords); // The problem is that we should initialize output to zero before using. // Otherwise, the original value will be added to the result. ${e(t)} } } ${this.isVec4?g2(this.elementsPerThread,this.workGroupSize,this.transposeA,32,!0,this.splitedDimInner):y2(this.elementsPerThread,this.workGroupSize,this.transposeA,32,!0,this.splitedDimInner)} `}},P2e=class{constructor(e,t=null,n=null,s=null){this.uniforms="",this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.addBias=t!=null,this.hasPreluActivationWeights=s!=null,this.activation=n,this.addBias&&this.variableNames.push("bias"),this.hasPreluActivationWeights&&this.variableNames.push("preluActivationWeights"),this.shaderKey=`biasActivation_${n}`}getUserCode(){return` ${Pa(this.activation,this.hasPreluActivationWeights)} ${Je("index")} { if (index < uniforms.size) { let coords = getCoordsFromIndex(index); var value = getXByOutputIndex(index); ${hu(this.addBias,this.activation)} setOutputAtIndex(index, value); } } `}},F2e=class{constructor(e){this.variableNames=[],this.outputShape=[],this.uniforms="value : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="fill"}getUserCode(){return` ${Je("index")} { if (index < uniforms.size) { setOutputAtIndex(index, uniforms.value); } } `}};function fu(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 F2e(s),i=[{type:"float32",data:[r]}];return t.runWebGPUProgram(o,[],a,i)}}var O2e={kernelName:Cc,backendName:"webgpu",kernelFunc:fu};function Le(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 M2e={kernelName:zl,backendName:"webgpu",kernelFunc:Le};function ob({a:e,b:t,transposeA:n,transposeB:s,backend:r,bias:a=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:l=null}){let u=e.shape.length,c=t.shape.length,p=n?e.shape[u-2]:e.shape[u-1],d=s?t.shape[c-1]:t.shape[c-2],h=n?e.shape[u-1]:e.shape[u-2],f=s?t.shape[c-2]:t.shape[c-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=v.sizeFromShape(m),x=v.sizeFromShape(g),b=tu.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([h,f]);v.assert(p===d,()=>`Error in matMul: inner shapes (${p}) and (${d}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${s} must match.`);let w=n?[y,p,h]:[y,h,p],k=s?[x,f,d]:[x,d,f],C=Le({inputs:{x:e},backend:r,attrs:{shape:w}}),N=Le({inputs:{x:t},backend:r,attrs:{shape:k}}),R=[C,N],D=Math.max(y,x),E=y===1,$=x===1,S=[C,N],F=[{type:"int32",data:[h]},{type:"int32",data:[f]},{type:"int32",data:[p]}],z,V,j=[D,h,f],G=U().get("WEBGPU_MATMUL_PROGRAM_TYPE");switch(G<0&&(h*f<=128?G=Tr.MatMulReduceProgram:D===1&&h<=128&&f<=48&&d>=2e3?G=Tr.MatMulSplitKProgram:h<=16&&(f<=512||d>=2*f)||f<=16&&(h<=512||p>=2*h)?G=Tr.MatMulSmallOutputSizeProgram:G=Tr.MatMulPackedProgram),G){case Tr.MatMulReduceProgram:z=new R2e(j,E,$,n,s,a,l,o);break;case Tr.MatMulSplitKProgram:{if(V=fu({backend:r,attrs:{shape:j,value:0,dtype:e.dtype}}),z=new $2e(j,d,E,$,n,s),a||l){V=r.runWebGPUProgram(z,S,e.dtype,F,V);let ne=new P2e(V.shape,a,l,o),ae=null,re=[V];a&&re.push(a),o&&re.push(o),l==="leakyrelu"&&(ae=[{type:"float32",data:[i]}],ne.uniforms+=" alpha : f32,");let ue=r.runWebGPUProgram(ne,re,V.dtype,ae);R.push(V);let oe=Le({inputs:{x:ue},backend:r,attrs:{shape:b}});R.push(ue);for(let Ae of R)r.disposeData(Ae.dataId);return oe}break}case Tr.MatMulSmallOutputSizeProgram:z=new D2e(w,k,j,n,s,a,l,o);break;case Tr.MatMulPackedProgram:let K=r.adapterInfo.isIntel();z=new N2e(w,j,E,$,n,s,a,l,o,K);break;default:throw new Error(`Unsupported MatMulProgramType ${G}.`)}a&&S.push(a),o&&S.push(o),l==="leakyrelu"&&(F.push({type:"float32",data:[i]}),z.uniforms+=" alpha : f32,"),V=r.runWebGPUProgram(z,S,e.dtype,F,V);let q=Le({inputs:{x:V},backend:r,attrs:{shape:b}});R.push(V);for(let K of R)r.disposeData(K.dataId);return q}function z2e(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:p}=s;return ob({a:r,b:a,transposeA:l,transposeB:u,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:p,activation:c})}var L2e={kernelName:no,backendName:"webgpu",kernelFunc:z2e},q7=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.workGroupSize=[128,1,1],this.size=!0,this.outputShape=T.assertAndGetBroadcastShape(t,n),this.dispatchLayout=it(this.outputShape),this.dispatch=Be(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 { ${rb(this.op,!1)} } ${Je("index")} { if(index < uniforms.size) { let areal = getARealByOutputIndex(index); let aimag = getAImagByOutputIndex(index); let breal = getBRealByOutputIndex(index); let bimag = getBImagByOutputIndex(index); setOutputAtIndex(index, binaryOpComplex(areal, aimag, breal, bimag)); } } `}},dy=class{constructor(e,t,n){this.size=!0,this.variableNames=["A","B"],this.outputShape=T.assertAndGetBroadcastShape(t,n),this.dispatchLayout=it(this.outputShape),this.op=e,this.useSharedMemoryWithA=t.length<=1&&n.length>1&&t[0]<128,this.useSharedMemoryWithB=n.length<=1&&t.length>1&&n[0]<128,this.useSharedMemoryWithA||this.useSharedMemoryWithB?(this.isVec4=!1,this.lastDimensionSize=this.useSharedMemoryWithB?n[0]:t[0],this.shaderKey=`binary_${this.type}_${e}_${this.lastDimensionSize}_${this.useSharedMemoryWithB}`,this.type="shared",this.workGroupSize=[256,1,1],this.workPerThread=1):(v.arraysEqual(t,n)&&v.sizeFromShape(t)%4===0?(this.isVec4=!0,this.type="vec4",this.workPerThread=4):(this.isVec4=!1,this.type="plain",this.workPerThread=1),this.shaderKey=`binary_${this.type}_${e}`,this.workGroupSize=[128,1,1]),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1])}getUserCode(){let e,t=this.isVec4?"vec4":"f32",n=` fn binaryOperation(a : ${t}, b : ${t}) -> ${t} { ${rb(this.op,this.isVec4)} }; `;if(this.type==="shared"){let s=this.lastDimensionSize>1?`coords[${this.outputShape.length-1}]`:"0",r=this.useSharedMemoryWithB?`let a = getAByOutputIndex(index); let b = sharedBuf[${s}];`:`let a = sharedBuf[${s}]; let b = getBByOutputIndex(index);`;e=` ${n} var sharedBuf : array; ${Je("index")} { // Fill in the shared memory buffer. let localIndex = i32(localId.x); if(localIndex < ${this.lastDimensionSize}) { sharedBuf[localIndex] = f32(${this.useSharedMemoryWithB?"B":"A"}[localIndex]); } workgroupBarrier(); if(index < uniforms.size) { let coords = getCoordsFromIndex(index); ${r} setOutputAtIndex(index, binaryOperation(a, b)); } } `}else e=` ${n} ${Je("index")} { if (index < uniforms.size) { let a = getAByOutputIndex(index); let b = getBByOutputIndex(index); setOutputAtIndex(index, binaryOperation(a, b)); } } `;return e}};function Qs(e){let{inputs:t}=e,{x:n}=t;return e.backend.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}var B2e={kernelName:Fo,backendName:"webgpu",kernelFunc:Qs};function cd(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=Qs({inputs:{x:s},backend:n}),l=Qs({inputs:{x:r},backend:n});return o.complexTensorInfos={real:i,imag:l},a}var W2e={kernelName:Ep,backendName:"webgpu",kernelFunc:cd},Ph=class{constructor(e,t){this.variableNames=["A"],this.size=!0;let n=128;this.workGroupSize=[n,1,1],this.outputShape=e,this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.op=t,this.shaderKey=`unary_${t}`}getUserCode(){return` fn unaryOperation(a : f32) -> f32 { ${Li(this.op,!1)} } ${Je("index")} { if (index < uniforms.size) { let a = getAByOutputIndex(index); setOutputAtIndex(index, unaryOperation(a)); } } `}};function vn({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 u=o.tensorMap.get(a.dataId),c=t(u.values,i);return o.makeTensorInfo(a.shape,i,c)}let l=new Ph(a.shape,e);return o.runWebGPUProgram(l,[a],i)}}function Xn({opType: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 p=l.tensorMap.get(o.dataId),d=l.tensorMap.get(i.dataId),h,f;if(e!==Xe.MUL)[h,f]=[[p.complexTensorInfos.real,d.complexTensorInfos.real],[p.complexTensorInfos.imag,d.complexTensorInfos.imag]].map(g=>{let[y,x]=g,A={dataId:y.dataId,dtype:y.dtype,shape:o.shape},b={dataId:x.dataId,dtype:x.dtype,shape:i.shape},w=new dy(e,o.shape,i.shape);return l.runWebGPUProgram(w,[A,b],jn(y.dtype,x.dtype))});else{let g=new q7(Xe.COMPLEX_MULTIPLY_REAL,o.shape,i.shape),y=new q7(Xe.COMPLEX_MULTIPLY_IMAG,o.shape,i.shape),x=[{dataId:p.complexTensorInfos.real.dataId,dtype:p.complexTensorInfos.real.dtype,shape:o.shape},{dataId:p.complexTensorInfos.imag.dataId,dtype:p.complexTensorInfos.imag.dtype,shape:o.shape},{dataId:d.complexTensorInfos.real.dataId,dtype:d.complexTensorInfos.real.dtype,shape:i.shape},{dataId:d.complexTensorInfos.imag.dataId,dtype:d.complexTensorInfos.imag.dtype,shape:i.shape}];h=l.runWebGPUProgram(g,x,"float32"),f=l.runWebGPUProgram(y,x,"float32")}let m=cd({inputs:{real:h,imag:f},backend:l});return l.disposeData(h.dataId),l.disposeData(f.dataId),m}let u=s||jn(o.dtype,i.dtype);if((o.dtype==="string"||i.dtype==="string"||l.shouldExecuteOnCPU([o,i]))&&t!=null){let p=l.tensorMap.get(o.dataId).values,d=l.tensorMap.get(i.dataId).values,h=o.dtype==="string"?T.fromUint8ToStringArray(p):p,f=o.dtype==="string"?T.fromUint8ToStringArray(d):d,[m,g]=t(o.shape,i.shape,h,f,u);return l.makeTensorInfo(g,u,m)}let c=new dy(e,o.shape,i.shape);return l.runWebGPUProgram(c,[o,i],u)}}var{addImpl:V2e,castImpl:U2e,ceilImpl:G2e,concatImpl:H2e,equalImpl:j2e,expImpl:q2e,expm1Impl:X2e,floorImpl:K2e,gatherNdImpl:Z2e,gatherV2Impl:Y2e,greaterEqualImpl:J2e,greaterImpl:Q2e,lessEqualImpl:e1e,lessImpl:t1e,logImpl:n1e,maxImpl:s1e,maximumImpl:r1e,minimumImpl:a1e,multiplyImpl:o1e,negImpl:i1e,notEqualImpl:l1e,prodImpl:u1e,rangeImpl:c1e,rsqrtImpl:d1e,scatterImpl:p1e,simpleAbsImpl:h1e,sliceImpl:f1e,stridedSliceImpl:m1e,stringNGramsImpl:g1e,subImpl:y1e,tileImpl:A1e,topKImpl:x1e,transposeImpl:b1e,uniqueImpl:Wbe}=Sx,v1e=vn({opType:De.ABS,cpuKernelImpl:h1e}),w1e={kernelName:dl,backendName:"webgpu",kernelFunc:v1e},k1e=Xn({opType:Xe.ADD,cpuKernelImpl:V2e,supportsComplex:!0}),S1e={kernelName:Ta,backendName:"webgpu",kernelFunc:k1e},I1e=class{constructor(e){this.workPerThread=1,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e[0],this.variableNames=e.map((t,n)=>`T${n}`),this.dispatchLayout=it(this.outputShape),this.dispatch=Be(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}ByOutputCoords(coords);`)});let t=this.variableNames.map(s=>`v${s}`).join(" + ");return` ${Je("index")} { for (var i = 0; i < ${this.workPerThread}; i = i + 1) { let flatIndex = index * ${this.workPerThread} + i; if (flatIndex < uniforms.size) { let coords = getCoordsFromIndex(flatIndex); ${e.join(` `)} setOutputAtIndex(flatIndex, ${t}); } } } `}};function C1e(e){let{inputs:t,backend:n}=e,s=t;if(s.length===1)return Qs({inputs:{x:s[0]},backend:n});let r=s.map(i=>i.dtype).reduce((i,l)=>jn(i,l)),a=s.map(i=>i.shape),o=new I1e(a);return n.runWebGPUProgram(o,s,r)}var T1e={kernelName:go,backendName:"webgpu",kernelFunc:C1e},uT=class{constructor(e,t,n){this.workGroupSize=[64,1,1],this.variableNames=["x"],this.uniforms="infinityValue : f32,",this.size=!0;let s=[t];this.op=n==="min"?"<":">";let[r,a]=T.computeOutAndReduceShapes(e,s);this.outputShape=r.length===0?[1]:r,this.dispatchLayout=it(this.outputShape),v.sizeFromShape(a)<32||v.sizeFromShape(r)>1e3?(this.type="plain",this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize)):(this.type="shared",this.dispatch=Be(this.dispatchLayout,this.outputShape,[1,1,1])),this.inputShape=e,this.shaderKey=`argMinMax_${this.op}_${this.type}`}getUserCode(){let e=()=>this.inputShape.length===1?"uniforms.xShape":`uniforms.xShape.${va(this.inputShape.length-1)}`,t=()=>{let n="";if(this.outputShape.length===1)this.inputShape.length!==1&&(n+="outputCoords,");else for(let s=0;s u32 { return ((a - 1u) / b + 1u); } ${` var xBestIndices : array; var xBestValues : array; `} ${Je("index")} { let outputIndex = index / i32(workGroupSizeX); let reduceLength = ${e()}; var bestIndex = i32(localId.x); var bestValue = uniforms.infinityValue; let outputCoords = getCoordsFromIndex(outputIndex); for (var k = i32(localId.x); k < reduceLength && outputIndex < uniforms.size; k = k + i32(workGroupSizeX)) { let candidate = getX(${t()} k); if (!isnan(candidate) && candidate ${this.op} bestValue) { bestValue = candidate; bestIndex = k; } } xBestValues[localId.x] = bestValue; xBestIndices[localId.x] = bestIndex; workgroupBarrier(); var reduceSize = min(u32(reduceLength), workGroupSizeX); for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) { let interval = DIV_CEIL(reduceSize, 2u); if (localId.x < currentSize) { let candidate = xBestValues[localId.x + interval]; if (candidate ${this.op} bestValue) { bestValue = candidate; xBestValues[localId.x] = bestValue; xBestIndices[localId.x] = xBestIndices[localId.x + interval]; } } reduceSize = interval; workgroupBarrier(); } if (localId.x == 0u && outputIndex < uniforms.size) { setOutputAtIndexI32(outputIndex, xBestIndices[localId.x]); } } `:` ${Je("index")} { if (index < uniforms.size) { let outputCoords = getCoordsFromIndex(index); var bestIndex = 0; var bestValue = getX(${t()} 0); let reduceLength = ${e()}; for (var i = 1; i < reduceLength; i++) { let candidate = getX(${t()} i); if (candidate ${this.op} bestValue) { bestValue = candidate; bestIndex = i; } } setOutputAtIndexI32(index, bestIndex); } } `}},N1e=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]}>; ${Ip()} fn _start(@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[y * width + x]; } workgroupBarrier(); x = i32(workgroupId.y) * TILE_DIM + i32(localId.x); y = i32(workgroupId.x) * TILE_DIM + i32(localId.y); if (x < height && y < width) { setOutputAtIndex((y * height + x), tile[localId.x] [localId.y]); } } `}},E1e=class{constructor(e,t){this.variableNames=["A"],this.workPerThread=1,this.workGroupSize=[64,1,1],this.size=!0;let n=new Array(e.length);for(let s=0;s6)throw Error(`Transpose for rank ${t} is not yet supported`);let n=new Array(t);for(let s=0;sn.disposeData(h.dataId)),d}var $1e={kernelName:yo,backendName:"webgpu",kernelFunc:D1e};function P1e(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s,o=v.parseAxisParam(a,r.shape),i=T.getAxesPermutation(o,r.shape.length),l=r,u=[];i!=null&&(l=Ca({inputs:{x:r},backend:n,attrs:{perm:i}}),u.push(l),o=T.getInnerMostAxes(o.length,l.shape.length)),T.assertAxesAreInnerMostDims("argMin",[o[0]],l.shape.length);let c=new uT(l.shape,o[0],"min"),p=[{type:"float32",data:[Number.POSITIVE_INFINITY]}],d=n.runWebGPUProgram(c,[l],"int32",p);return u.forEach(h=>n.disposeData(h.dataId)),d}var F1e={kernelName:bc,backendName:"webgpu",kernelFunc:P1e},O1e=Xn({opType:Xe.ATAN2}),M1e={kernelName:pl,backendName:"webgpu",kernelFunc:O1e},X7=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=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`pool2D_${t}`,this.poolType=t}getUserCode(){let e="resultValue = max(value, resultValue);";this.poolType==="avg"&&(e="resultValue = resultValue + value; count = count + 1.0;");let t="resultValue";return this.poolType==="avg"&&(t="resultValue / count"),` ${Je("index")} { if (index < uniforms.size) { let coords = getCoordsFromIndex(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} } } setOutputAtIndex(index, ${t}); } } `}},z1e=class{constructor(e){this.variableNames=["x"],this.uniforms="stride : vec2,",this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="poolWithFilterSizeEqualsOne"}getUserCode(){return` ${Je("index")} { if (index < uniforms.size) { let coords = getCoordsFromIndex(index); let batch = coords[0]; let d = coords[3]; let xRCCorner = coords.yz * uniforms.stride; let xRCorner = xRCCorner.x; let xCCorner = xRCCorner.y; let value = getX(batch, xRCorner, xCCorner, d); setOutputAtIndex(index, value); } } `}},L1e=class{constructor(e,t){this.workGroupSize=[64,1,1],this.variableNames=["x"],this.uniforms="reduceSize : i32,",this.size=!0,this.inputShape=[e.batchSize,e.inSize];let[n]=T.computeOutAndReduceShapes(this.inputShape,[1]);this.outputShape=n.length===0?[1]:n,this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,[1,1,1]),this.reduceType=t,this.shaderKey=`reduce_${t}`}getUserCode(){let e="",t="0.0";this.reduceType==="min"||this.reduceType==="max"?(e=` if (isnan(candidate)) { bestValue = uniforms.NAN; } else if (!isnan(bestValue) && candidate ${this.reduceType==="min"?"<":">"} bestValue) { bestValue = candidate; }`,t="f32(x[offset])"):this.reduceType==="sum"||this.reduceType==="mean"?e=" bestValue = bestValue + candidate; ":this.reduceType==="prod"&&(e=" bestValue = bestValue * candidate; ",t="1.0");let n=this.reduceType==="mean"?"setOutputAtIndex(outputIndex, bestValue / f32(uniforms.reduceSize));":"setOutputAtIndex(outputIndex, bestValue);";return` fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${` var xBestValues : array; `} fn getOffset(outputIndex : i32) -> i32 { let outputCoords = getCoordsFromIndex(outputIndex); let offset = ${this.outputShape.length===1?"outputCoords":"outputCoords[0]"} * uniforms.reduceSize; return offset; } ${Je("index")} { let outputIndex = index / i32(workGroupSizeX); let offset = getOffset(outputIndex); var bestValue = ${t}; let Length = uniforms.reduceSize; let WorkPerThread = DIV_CEIL(u32(Length), workGroupSizeX); for (var k = i32(localId.x); k < Length && outputIndex < uniforms.size; k = k + i32(workGroupSizeX)) { let candidate = f32(x[offset + k]); ${e} } xBestValues[localId.x] = bestValue; workgroupBarrier(); var reduceSize = min(u32(Length), workGroupSizeX); for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) { let interval = DIV_CEIL(reduceSize, 2u); if (localId.x < currentSize) { let candidate = xBestValues[localId.x + interval]; ${e} xBestValues[localId.x] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (localId.x == 0u && outputIndex < uniforms.size) { ${n} } } `}};function Fh(e,t,n,s,r){let a=e.shape.length,o=[],i=v.parseAxisParam(t,e.shape),l=i,u=T.getAxesPermutation(l,a),c=e;u!=null&&(c=Ca({inputs:{x:e},attrs:{perm:u},backend:r}),l=T.getInnerMostAxes(l.length,a),o.push(c)),T.assertAxesAreInnerMostDims(s,l,a);let[p,d]=T.computeOutAndReduceShapes(c.shape,l),h=p;n&&(h=T.expandShapeToKeepDim(p,i));let f;if((s==="max"||s==="prod")&&r.shouldExecuteOnCPU([c])){let m=r.tensorMap.get(c.dataId).values;switch(s){case"max":let g=s1e(m,v.sizeFromShape(d),h,e.dtype);f=r.makeTensorInfo(h,e.dtype,g);break;case"prod":let{outVals:y,outShape:x,outDtype:A}=u1e(c.shape,c.dtype,m,l);f=r.makeTensorInfo(x,A,y);break;default:throw new Error(`${s} CPU implementation is not yet supported.`)}}else{let m=v.sizeFromShape(d),y=v.sizeFromShape(c.shape)/m,x={windowSize:m,inSize:m,batchSize:y,outSize:1},A=s==="mean"?"float32":qp(e.dtype),b=[{type:"int32",data:[m]}],w=new L1e(x,s),k=r.runWebGPUProgram(w,[c],A,b);o.push(k),f=Le({inputs:{x:k},attrs:{shape:h},backend:r})}return o.forEach(m=>r.disposeData(m.dataId)),f}function ib(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reductionIndices:a,keepDims:o}=s;return Fh(r,a,o,"max",n)}var B1e={kernelName:zo,backendName:"webgpu",kernelFunc:ib};function cT(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{keepDims:a,axis:o}=s;return Fh(r,o,a,"mean",n)}var W1e={kernelName:Wo,backendName:"webgpu",kernelFunc:cT};function dT(e,t,n,s){if(t.filterWidth===1&&t.filterHeight===1&&v.arraysEqual(t.inShape,t.outShape))return Qs({inputs:{x:e},backend:s});if(t.filterWidth===t.inWidth&&t.filterHeight===t.inHeight&&t.batchSize===1&&t.padInfo.type==="VALID"){let o=e.shape.length,i=Le({inputs:{x:e},backend:s,attrs:{shape:[e.shape[o-3]*e.shape[o-2],e.shape[o-1]]}}),l;n==="avg"?l=cT({inputs:{x:i},backend:s,attrs:{axis:0,keepDims:!1}}):(v.assert(n==="max",()=>`Invalid pool type ${n}`),l=ib({inputs:{x:i},backend:s,attrs:{reductionIndices:0,keepDims:!1}}));let u=Le({inputs:{x:l},backend:s,attrs:{shape:t.outShape}});return s.disposeData(i.dataId),s.disposeData(l.dataId),u}let r,a=[{type:"int32",data:[t.strideHeight,t.strideWidth]}];return t.filterHeight===1&&t.filterWidth===1?r=new z1e(t):(n==="avg"?r=new X7(t,"avg"):(v.assert(n==="max",()=>`Invalid pool type ${n}`),r=new X7(t,"max")),a.push({type:"int32",data:[t.padInfo.top,t.padInfo.left]},{type:"int32",data:[t.dilationHeight,t.dilationWidth]},{type:"int32",data:[t.inHeight,t.inWidth]},{type:"int32",data:[t.effectiveFilterHeight,t.effectiveFilterWidth]})),s.runWebGPUProgram(r,[e],e.dtype,a)}function V1e(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,u=1,c=T.computePool2DInfo(r.shape,a,o,u,i,l);return dT(r,c,"avg",n)}var U1e={kernelName:Ao,backendName:"webgpu",kernelFunc:V1e};function G1e(e){let{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:o,transposeB:i}=s;return ob({a:r,b:a,transposeA:o,transposeB:i,backend:n})}var H1e={kernelName:xo,backendName:"webgpu",kernelFunc:G1e},j1e=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=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.start=e,this.uniforms=`start : ${zn(e.length)}, `,this.shaderKey="slice"}getUserCode(){let e=zn(this.rank),t=q1e(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.${py[a]} = uniforms.start.${va(a)} + coords.${py[a]};`),` ${Je("index")} { if (index < uniforms.size) { var sourceLoc : ${e}; let coords = getCoordsFromIndex(index); ${n.join(` `)} setOutputAtIndex(index, getSource(${t})); } } `}},py=["x","y","z","w","u","v"];function q1e(e){if(e===1)return"sourceLoc";if(e<=6)return py.slice(0,e).map(t=>`sourceLoc.${t}`).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}function dd(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:o}=s,[i,l]=Gt.parseSliceParams(r,a,o);if(Gt.assertParamsValid(r,i,l),n.shouldExecuteOnCPU([r])||r.dtype==="string"){let p=n.tensorMap.get(r.dataId),d=f1e(p.values,i,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,d)}if(v.sizeFromShape(l)===0)return n.makeTensorInfo(l,r.dtype,[]);let u=new j1e(i,l),c=[{type:"int32",data:i}];return n.runWebGPUProgram(u,[r],r.dtype,c)}var X1e={kernelName:Ul,backendName:"webgpu",kernelFunc:dd},K1e=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,A)=>x*A),l=T.getReshaped(r.shape,a,i),u=T.getPermuted(l.length,a.length),c=T.getReshapedPermuted(r.shape,a,i),p=T.getSliceBeginCoords(o,a.length),d=T.getSliceSize(c,o,a.length),h=[],f=Le({inputs:{x:r},backend:n,attrs:{shape:l}}),m=Ca({inputs:{x:f},backend:n,attrs:{perm:u}}),g=Le({inputs:{x:m},backend:n,attrs:{shape:c}}),y=dd({inputs:{x:g},backend:n,attrs:{begin:p,size:d}});return h.push(f),h.push(m),h.push(g),h.forEach(x=>n.disposeData(x.dataId)),y},Z1e={kernelName:hl,backendName:"webgpu",kernelFunc:K1e},pT=Xn({opType:Xe.NOT_EQUAL,dtype:"bool",cpuKernelImpl:l1e}),Y1e={kernelName:_l,backendName:"webgpu",kernelFunc:pT};function Oh(e){let{inputs:t,backend:n}=e,{input:s}=t,r=n.tensorMap.get(s.dataId);return Qs({inputs:{x:r.complexTensorInfos.real},backend:n})}var J1e={kernelName:Mp,backendName:"webgpu",kernelFunc:Oh};function Q1e(e,t){let n=new Ph(e.shape,De.TO_INT),s=t.runWebGPUProgram(n,[e],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}function hy(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dtype:a}=s;if(a==="complex64"){if(r.dtype==="complex64")return Qs({inputs:{x:r},backend:n});let o=Vt(r.shape),i=hy({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=cd({inputs:{real:i,imag:o},backend:n});return o.dispose(),n.disposeData(i.dataId),l}if(r.dtype==="complex64"){let o=Oh({inputs:{input:r},backend:n}),i=hy({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeData(o.dataId),i}if(!v.hasEncodingLoss(r.dtype,a)){let o=Qs({inputs:{x:r},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(n.shouldExecuteOnCPU([r])){let o=n.tensorMap.get(r.dataId).values,[i,l,u]=U2e(o,r.shape,r.dtype,a);return n.makeTensorInfo(i,l,u)}if(a==="int32")return Q1e(r,n);if(a==="bool"){let o=n.makeTensorInfo([],"bool",v.getTypedArrayFromDType("bool",1)),l=pT({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 ege={kernelName:bo,backendName:"webgpu",kernelFunc:hy},tge=vn({opType:De.CEIL,cpuKernelImpl:G2e}),nge={kernelName:vo,backendName:"webgpu",kernelFunc:tge},sge=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=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.shaderKey="clipVec4"}getUserCode(){return` ${Je("index")} { if(index < uniforms.size) { let value = getAByOutputIndex(index); var clampedValue : vec4; for (var i = 0; i < 4; i = i + 1) { if (isnan(value[i])) { clampedValue[i] = value[i]; } else { clampedValue[i] = clamp(value[i], uniforms.minVal, uniforms.maxVal); } } setOutputAtIndex(index, clampedValue); } } `}},rge=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=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="clip"}getUserCode(){return` ${Je("index")} { if(index < uniforms.size) { let value = getAByOutputIndex(index); if (isnan(value)) { setOutputAtIndex(index, value); return; } setOutputAtIndex(index, clamp(value, uniforms.minVal, uniforms.maxVal)); } } `}};function age(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 sge(r.shape):i=new rge(r.shape),n.runWebGPUProgram(i,[r],r.dtype,l)}var oge={kernelName:Na,backendName:"webgpu",kernelFunc:age},ige=class{constructor(e){this.uniforms="",this.workPerThread=1,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=T.computeOutShape(e,1),this.variableNames=e.map((t,n)=>`T${n}`),this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.offsetLength=e.length-1;for(let t=0;t0){e.push("if (yC < uniforms.offset0){ setOutputAtCoords(coords.x, coords.y, getT0(yR, yC)); }");for(let r=1;rOh({inputs:{input:A},backend:n})),m=e.map(A=>A2({inputs:{input:A},backend:n})),g=tp(f,t,n),y=tp(m,t,n),x=cd({inputs:{real:g,imag:y},backend:n});return f.forEach(A=>n.disposeData(A.dataId)),m.forEach(A=>n.disposeData(A.dataId)),n.disposeData(g.dataId),n.disposeData(y.dataId),x}let r=n.shouldExecuteOnCPU(e);if(s==="string"&&(r=!0),r){let f=e.map(w=>{let k=v.sizeFromShape(w.shape.slice(t));return Le({inputs:{x:w},backend:n,attrs:{shape:[-1,k]}})}),m=f.map(w=>({vals:n.readSync(w.dataId),shape:w.shape})),g=T.computeOutShape(f.map(w=>w.shape),1),y=f[0].shape[0]===1,x=H2e(m,g,s,y),A=T.computeOutShape(e.map(w=>w.shape),t),b=n.makeTensorInfo(A,s,x);return f.forEach(w=>n.disposeData(w.dataId)),b}let a=n.device.limits.maxStorageBuffersPerShaderStage-1;if(e.length>a){let f=[];for(let g=0;gf.shape),u=new ige(l),c=[],p=new Array(l.length-1);if(p.length>0){p[0]=l[0][1],c.push({type:"int32",data:[p[0]]});for(let f=1;fn.disposeData(f.dataId));let h=Le({inputs:{x:d},backend:n,attrs:{shape:i}});return n.disposeData(d.dataId),h}function uge(e,t,n){let s=T.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>Le({inputs:{x:a},backend:n,attrs:{shape:[v.sizeFromShape(a.shape.slice(0,t)),v.sizeFromShape(a.shape.slice(t))]}})),outShape:s}}function hT(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s,a=v.parseAxisParam(r,t[0].shape)[0],o=t.map(u=>u.shape);T.assertParamsConsistent(o,a);let i=T.computeOutShape(t.map(u=>u.shape),a);if(v.sizeFromShape(i)===0)return n.makeTensorInfo(i,t[0].dtype,[]);let l=t.filter(u=>v.sizeFromShape(u.shape)>0);return l.length===1?Qs({inputs:{x:l[0]},backend:n}):tp(l,a,n)}var cge={kernelName:fl,backendName:"webgpu",kernelFunc:hT};function dge(e,t,n,s,r=!1,a=null,o=!1,i=4,l=4,u=4){let c=R=>{switch(R){case 1:return"resData = x[xIndex];";case 3:return"resData = vec3(x[xIndex], x[xIndex + 1], x[xIndex + 2]);";case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${R} is not supported.`)}},p=R=>{switch(R){case 1:return"return W[row * uniforms.wShape[3] + colIn];";case 4:return"return W[row * uniforms.wShape[3] / 4 + colIn];";default:throw new Error(`innerElementSize ${R} is not supported.`)}},d=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,h=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,f=e?"uniforms.xShape[1]":"uniforms.xShape[2]",m=e?"uniforms.xShape[2]":"uniforms.xShape[3]",g=e?"row":"col",y=e?"col":"row",x=` let inChannels = uniforms.wShape[2]; let outWidth = ${e?"uniforms.outShape[2]":"uniforms.outShape[3]"}; let outRow = ${g} / outWidth; let outCol = ${g} % outWidth; let WRow = ${y} / (uniforms.filterDims[1] * inChannels); let WCol = ${y} / inChannels % uniforms.filterDims[1]; let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; let xCh = ${y} % inChannels; var resData = ${Yt(i)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${f} && xCol >= 0 && xCol < ${m}) { ${d} let xIndex = getIndexFromCoords4D(coord, uniforms.xShape); ${c(i)} } return resData;`,A=e?t&&s?` let col = colIn * ${i}; ${x}`:` let col = colIn * ${i}; if (row < uniforms.dimAOuter && col < uniforms.dimInner) { ${x} } return ${Yt(i)}(0.0);`:s&&n?` let col = colIn * ${i}; ${x}`:` let col = colIn * ${i}; if (row < uniforms.dimInner && col < uniforms.dimBOuter) { ${x} } return ${Yt(i)}(0.0);`,b=`${p(l)}`,w=Yt(u),k=Yt(e?i:l),C=Yt(e?l:i);return` ${Pa(a,o,u===4,4)} fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${k} { ${e?A:b} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${C} { ${e?b:A} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${w}) { let col = colIn * ${u}; if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) { var value = valueIn; let outWidth = ${e?"uniforms.outShape[2]":"uniforms.outShape[3]"}; ${h} ${hu(r,a)} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`}var pge=class{constructor(e,t,n,s,r=!1,a=null,o=!1,i=!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,this.isChannelsLast=e.dataFormat==="channelsLast",this.isVec4=((e.inChannels%4===0||e.inChannels%3===0)&&this.isChannelsLast||e.outWidth%4===0&&!this.isChannelsLast)&&e.outChannels%4===0,this.dispatchLayout=this.isChannelsLast?{x:[3],y:[1,2],z:[0]}:{x:[2,3],y:[1],z:[0]},this.workGroupSize=tb(this.dispatchLayout,this.outputShape,this.isVec4),this.elementsPerThread=nb(this.dispatchLayout,this.outputShape,this.isVec4),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread),this.isVec4?(this.isChannelsLast&&e.inChannels%4!==0?(this.innerElementSize=3,this.variableTypes=["f32","vec4"]):(this.innerElementSize=4,this.variableTypes=["vec4","vec4"]),r&&(this.variableNames.push("bias"),this.variableTypes.push("vec4")),o&&(this.variableNames.push("preluActivationWeights"),this.variableTypes.push("vec4"))):(this.innerElementSize=this.elementsPerThread[0],r&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights")),this.sequentialAccessByThreads=i,this.addBias=r,this.activation=a,this.hasPreluActivationWeights=o,this.tileAOuter=this.workGroupSize[1]*this.elementsPerThread[1],this.tileBOuter=this.workGroupSize[0]*this.elementsPerThread[0],this.tileInner=Math.max(this.workGroupSize[0]*this.innerElementSize,this.workGroupSize[1]),this.fitAOuter=t%this.tileAOuter===0,this.fitBOuter=n%this.tileBOuter===0,this.fitInner=s%this.tileInner===0,this.shaderKey=`conv2DMM_${this.elementsPerThread}_${this.activation}}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.isVec4}_${this.innerElementSize}_${this.isChannelsLast}_${this.sequentialAccessByThreads}`}getUserCode(){let e=this.isVec4?g2(this.elementsPerThread,this.workGroupSize,!this.isChannelsLast,this.tileInner):y2(this.elementsPerThread,this.workGroupSize,!this.isChannelsLast,this.tileInner,!1,null,this.sequentialAccessByThreads),t=this.isVec4?[this.innerElementSize,4,4]:[1,1,1];return` ${dge(this.isChannelsLast,this.fitAOuter,this.fitBOuter,this.fitInner,this.addBias,this.activation,this.hasPreluActivationWeights,t[0],t[1],t[2])} ${e} `}},hge=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=[4,4,8],this.outputShape=e.outShape,this.isChannelsLast=e.dataFormat==="channelsLast",this.dispatchLayout=this.isChannelsLast?{x:[2],y:[1],z:[0,3]}:{x:[3],y:[2],z:[0,1]},this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.addBias=t,this.activation=n,this.hasPreluActivationWeights=s,t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.shaderKey=`conv2dnaive_${this.activation}_${this.isChannelsLast}`}getUserCode(){return` ${Pa(this.activation,this.hasPreluActivationWeights,!1,4)} fn readInp(batch : i32, row : i32, col : i32, chan : i32) -> f32{ let coords = vec4(batch, row, col, chan); if (coordsInBounds4D(coords, uniforms.xShape)) { return getX(batch, row, col, chan); } else { return 0.0; } } fn readFilt(row : i32, col : i32, xChannel : i32, outChannel : i32) -> f32{ let coords = vec4(row, col, xChannel, outChannel); if(coordsInBounds4D(coords, uniforms.wShape)) { return getW(row, col, xChannel, outChannel); } else { return 0.0; } } fn writeResult(batch : i32, row : i32, col : i32, chan : i32, valueIn : f32) { let coords = ${this.isChannelsLast?"vec4(batch, row, col, chan);":"vec4(batch, chan, row, col);"} if (coordsInBounds4D(coords, uniforms.outShape)) { var value = valueIn; ${hu(this.addBias,this.activation)} setOutputAtCoords(coords.x, coords.y, coords.z, coords.w, value); } } ${Je("index")} { let coords = getOutputCoords(); let batch = coords[0]; let outChannel = ${this.isChannelsLast?"coords[3];":"coords[1];"} let outRow = ${this.isChannelsLast?"coords[1];":"coords[2];"} let outCol = ${this.isChannelsLast?"coords[2];":"coords[3];"} var acc : f32 = 0.0; for (var row = 0; row < uniforms.filterDims[0]; row = row + 1) { for (var col = 0; col < uniforms.filterDims[1]; col = col + 1) { let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * row - uniforms.pad[0]; let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * col - uniforms.pad[1]; for (var xChannel = 0; xChannel < ${this.isChannelsLast?"uniforms.xShape[3];":"uniforms.xShape[1];"} xChannel = xChannel + 1) { ${this.isChannelsLast?"let v = readInp(batch, xRow, xCol, xChannel);":"let v = readInp(batch, xChannel, xRow, xCol);"} let f = readFilt(row, col, xChannel, outChannel); acc = acc + v * f; } } } writeResult(batch, outRow, outCol, outChannel, acc); } `}};function K7(e,t){let n=e.length;return n>=3?t?[...e.slice(0,-3),e[n-3]*e[n-2],e[n-1]]:[...e.slice(0,-3),e[n-3],e[n-2]*e[n-1]]:!t&&n===1&&e[0]>1?[e[0],1]:null}function fge({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let l=n.dataFormat==="channelsLast",u=!l,c=!1,p=l&&n.filterHeight===n.inHeight&&n.filterWidth===n.inWidth&&n.padInfo.type==="VALID",d=[],h,f;if(p){let y=n.inHeight*n.inWidth*n.inChannels;h=Le({inputs:{x:e},backend:s,attrs:{shape:[1,n.batchSize,y]}}),f=Le({inputs:{x:t},backend:s,attrs:{shape:[1,y,n.outChannels]}})}else h=Le({inputs:{x:e},backend:s,attrs:{shape:l?[n.batchSize,n.inHeight*n.inWidth,n.inChannels]:[n.batchSize,n.inChannels,n.inHeight*n.inWidth]}}),f=Le({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}});if(d.push(h),d.push(f),a!=null){let y=K7(a.shape,l);y!=null&&(a=Le({inputs:{x:a},backend:s,attrs:{shape:y}}),d.push(a))}if(r!=null){let y=K7(r.shape,l);y!=null&&(r=Le({inputs:{x:r},backend:s,attrs:{shape:y}}),d.push(r))}let m=ob({a:l?h:f,b:l?f:h,transposeA:u,transposeB:c,backend:s,bias:r,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),g=Le({inputs:{x:m},backend:s,attrs:{shape:n.outShape}});d.push(m);for(let y of d)s.disposeData(y.dataId);return g}function fT({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let l=r!=null,u=a!=null,c=n.dataFormat==="channelsLast",p=c&&n.filterHeight===n.inHeight&&n.filterWidth===n.inWidth&&n.padInfo.type==="VALID",d=U().getBool("WEBGPU_USE_NAIVE_CONV2D_DEBUG");if(!d&&(p||n.filterHeight===1&&n.filterWidth===1&&n.dilationHeight===1&&n.dilationWidth===1&&n.strideHeight===1&&n.strideWidth===1&&(n.padInfo.type==="SAME"||n.padInfo.type==="VALID")))return fge({x:e,filter:t,convInfo:n,backend:s,bias:r,activation:i,preluActivationWeights:a,leakyreluAlpha:o});let h,f=[n.padInfo.top,n.padInfo.left],m=[{type:"int32",data:[n.filterHeight,n.filterWidth]},{type:"int32",data:[...f]},{type:"int32",data:[n.strideHeight,n.strideWidth]},{type:"int32",data:[n.dilationHeight,n.dilationWidth]}];if(d)h=new hge(n,l,i,u);else{let A=c?n.outHeight*n.outWidth:n.outChannels,b=c?n.outChannels:n.outHeight*n.outWidth,w=n.filterHeight*n.filterWidth*n.inChannels;m.push({type:"int32",data:[A]},{type:"int32",data:[b]},{type:"int32",data:[w]});let k=s.adapterInfo.isIntel();h=new pge(n,A,b,w,l,i,u,k)}let g=[],y=[e,t];l&&(!c&&r.shape.length===1&&(r=Le({inputs:{x:r},backend:s,attrs:{shape:[r.shape[0],1,1]}}),g.push(r)),y.push(r)),u&&(!c&&a.shape.length===1&&(a=Le({inputs:{x:a},backend:s,attrs:{shape:[a.shape[0],1,1]}}),g.push(a)),y.push(a)),i==="leakyrelu"&&(m.push({type:"float32",data:[o]}),h.uniforms+=" alpha : f32,");let x=s.runWebGPUProgram(h,y,e.dtype,m);for(let A of g)s.disposeData(A.dataId);return x}function mge(e){let{inputs:t,attrs:n,backend:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dataFormat:l,dilations:u,dimRoundingMode:c}=n,p=T.convertConv2DDataFormat(l),d=T.computeConv2DInfo(r.shape,a.shape,o,u,i,c,!1,p);return fT({x:r,filter:a,convInfo:d,backend:s})}var gge={kernelName:wo,backendName:"webgpu",kernelFunc:mge};function yge(e=4){let t=a=>{switch(a){case 1:return"return W[getIndexFromCoords4D(coord, uniforms.wShape)];";case 4:return` let coord1 = vec4(coordX, coordY, col + 1, rowInner); let coord2 = vec4(coordX, coordY, col + 2, rowInner); let coord3 = vec4(coordX, coordY, col + 3, rowInner); let v0 = W[getIndexFromCoords4D(coord, uniforms.wShape)]; let v1 = W[getIndexFromCoords4D(coord1, uniforms.wShape)]; let v2 = W[getIndexFromCoords4D(coord2, uniforms.wShape)]; let v3 = W[getIndexFromCoords4D(coord3, uniforms.wShape)]; return vec4(v0, v1, v2, v3); `;default:throw new Error(`innerElementSize ${a} is not supported.`)}},s=`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 ${Yt(e)}(0.0); } if (xC < 0.0 || xC >= f32(uniforms.outBackprop[2]) || fract(xC) > 0.0) { return ${Yt(e)}(0.0); } let coord = vec4( batch, i32(xR), i32(xC), col % uniforms.outBackprop[3]); return x[getIndexFromCoords4D(coord, uniforms.xShape)/${e}];`} } return ${Yt(e)}(0.0);`;return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Yt(e)} { let col = colIn * ${e}; ${s} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Yt(e)} { let col = colIn * ${e}; 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 rowInner = row % uniforms.outBackprop[3]; let coord = vec4(coordX, coordY, col, rowInner); ${t(e)} } return ${Yt(e)}(0.0); } fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${Yt(e)}) { let col = colIn * ${e}; if (row < uniforms.dimAOuter && (col + ${e-1}) < uniforms.dimBOuter) { var value = valueInput; let outCoord = vec4( batch, row / uniforms.outShape[2], row % uniforms.outShape[2], col); result[getIndexFromCoords4D(outCoord, uniforms.outShape)/${e}] = value; } }`}var Age=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.isVec4=e.inChannels%4===0&&e.outChannels%4===0,this.dispatchLayout={x:[3],y:[1,2],z:[0]},this.workGroupSize=tb(this.dispatchLayout,this.outputShape,this.isVec4),this.elementsPerThread=nb(this.dispatchLayout,this.outputShape,this.isVec4),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread),this.isVec4&&(this.variableTypes=["vec4","f32"]),this.shaderKey=`conv2DDerInputMM_${this.isVec4}_${this.elementsPerThread}`}getUserCode(){let e=this.isVec4?g2(this.elementsPerThread,this.workGroupSize):y2(this.elementsPerThread,this.workGroupSize);return` ${yge(this.isVec4?4:1)} ${e} `}},xge=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=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.isChannelsLast=e.dataFormat==="channelsLast",this.shaderKey=`conv2DDerInput_${this.isChannelsLast}`}getUserCode(){let e=this.isChannelsLast?1:2,t=this.isChannelsLast?2:3,n=this.isChannelsLast?3:1;return` ${Je("index")} { if(index < uniforms.size) { let coords = getCoordsFromIndex(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 = i32(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 = i32(dyC); for (var d2 = 0; d2 < uniforms.outBackprop[3]; d2 = d2 + 1) { if (${this.isChannelsLast}) { let xValue = getDy(batch, idyR, idyC, d2); let wValue = getW(wRPerm, wCPerm, d1, d2); dotProd = dotProd + xValue * wValue; } else { let xValue = getDy(batch, d2, idyR, idyC); let wValue = getW(wRPerm, wCPerm, d1, d2); dotProd = dotProd + xValue * wValue; } } } } setOutputAtIndex(index, dotProd); } } `}};function bge(e){let{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{inputShape:o,strides:i,pad:l,dataFormat:u,dimRoundingMode:c}=s,p=T.convertConv2DDataFormat(u),d=T.computeConv2DInfo(o,a.shape,i,1,l,c,!1,p),h=[{type:"int32",data:[d.filterHeight,d.filterWidth]},{type:"int32",data:[d.filterHeight-1-d.padInfo.top,d.filterWidth-1-d.padInfo.left]},{type:"int32",data:[d.strideHeight,d.strideWidth]},{type:"int32",data:[d.batchSize,d.outHeight,d.outWidth,d.outChannels]}],f;if(U().getBool("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE")||d.filterHeight<=2&&d.filterWidth<=2&&d.outChannels<=16&&d.inChannels===1)f=new xge(d);else{f=new Age(d);let m=d.inHeight*d.inWidth,g=d.inChannels,y=d.filterHeight*d.filterWidth*d.outChannels;h.push({type:"uint32",data:[m]},{type:"uint32",data:[g]},{type:"uint32",data:[y]})}return n.runWebGPUProgram(f,[r,a],"float32",h)}var vge={kernelName:ko,backendName:"webgpu",kernelFunc:bge},wge=vn({opType:De.COS}),kge={kernelName:So,backendName:"webgpu",kernelFunc:wge},Sge=vn({opType:De.COSH}),Ige={kernelName:Io,backendName:"webgpu",kernelFunc:Sge},Cge=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=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.methodId=s==="bilinear"?1:0,this.cropHeightBiggerThan1=this.outputShape[1]>1,this.cropWidthBiggerThan1=this.outputShape[2]>1,this.shaderKey=`cropAndResize_${this.methodId}_${this.cropHeightBiggerThan1}_${this.cropWidthBiggerThan1}`}getUserCode(){let[e,t]=["f32(uniforms.imageShape[1] - 1)","f32(uniforms.imageShape[2] - 1)"],[n,s,r]=this.cropHeightBiggerThan1?[`(${e} / f32(uniforms.outShape[1] - 1))`,"(y2-y1) * height_ratio",`y1*${e} + f32(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${e}`],[a,o,i]=this.cropWidthBiggerThan1?[`(${t} / f32(uniforms.outShape[2] - 1))`,"(x2-x1) * width_ratio",`x1*${t} + f32(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${t}`];return` ${Je("index")} { if (index < uniforms.size) { let coords = getCoordsFromIndex(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} ) { setOutputAtIndex(index, uniforms.extrapolationValue); return; } let in_x = ${i}; if( in_x < 0.0 || in_x > ${t} ) { setOutputAtIndex(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; setOutputAtIndex(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); setOutputAtIndex(index, newValue); } } } `}},Tge=e=>{let{inputs:t,backend:n,attrs:s}=e,{image:r,boxes:a,boxInd:o}=t,{cropSize:i,method:l,extrapolationValue:u}=s,c=new Cge(r.shape[3],a.shape,i,l),p=[{type:"float32",data:[u]}];return n.runWebGPUProgram(c,[r,a,o],"float32",p)},Nge={kernelName:gl,backendName:"webgpu",kernelFunc:Tge},Cp;(function(e){e.Prod="*",e.Sum="+"})(Cp||(Cp={}));var Z7=class{constructor(e,t,n,s){this.variableNames=["x"],this.uniforms="index : f32,",this.size=!0;let r=128;this.workGroupSize=[r,1,1],this.outputShape=t,this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.exclusive=n,this.reverse=s,this.op=e,this.shaderKey=`cum_${this.op}_${this.exclusive}_${this.reverse}`}getUserCode(){let e=this.outputShape.length,t=this.op===Cp.Prod?"1.0":"0.0",n=this.exclusive?t:`getX(${Y7(e,"coords",this.op)})`,s=this.outputShape[this.outputShape.length-1],r="",a="";return this.exclusive?(r=this.reverse?`end != ${s-1}`:"end != 0",a=this.reverse?"end + 1":"end - 1"):(r=this.reverse?`end + pow2 < ${s}`:"end >= pow2",a=this.reverse?"end + pow2":"end - pow2"),` ${Je("index")} { if (index < uniforms.size) { var coords = getCoordsFromIndex(index); let end = ${J7(e,"coords",this.op)}; var val = ${n}; let pow2 = i32(pow(2.0, uniforms.index)); if (${r}) { let idx = ${a}; ${J7(e,"coords",this.op)} = idx; val ${this.op}= getX(${Y7(e,"coords",this.op)}); } setOutputAtIndex(index, val); } } `}};function Y7(e,t,n){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 ${n} for rank ${e} is not yet supported`)}function J7(e,t,n){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 ${n} for rank ${e} is not yet supported`)}function mT(e,t,n,s,r,a){let o=t.shape.length,i=T.getAxesPermutation([s],o),l=t;i!=null&&(l=Ca({inputs:{x:t},backend:n,attrs:{perm:i}}));let u=T.getInnerMostAxes(1,o)[0];if(u!==o-1)throw new Error(`WebGPU cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${s}`);let c=l.shape[u],p=Qs({inputs:{x:l},backend:n});for(let d=0;d<=Math.ceil(Math.log2(c))-1;d++){let h=new Z7(e,l.shape,!1,a),f=p,m=[{type:"float32",data:[d]}];p=n.runWebGPUProgram(h,[p],p.dtype,m),n.disposeData(f.dataId)}if(r){let d=new Z7(e,l.shape,r,a),h=p,f=[{type:"float32",data:[0]}];p=n.runWebGPUProgram(d,[p],p.dtype,f),n.disposeData(h.dataId)}if(i!=null){let d=T.getUndoAxesPermutation(i),h=Ca({inputs:{x:p},backend:n,attrs:{perm:d}});return n.disposeData(p.dataId),n.disposeData(l.dataId),h}return p}function Ege(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:o,reverse:i}=s;return mT(Cp.Prod,r,n,a,o,i)}var Rge={kernelName:ml,backendName:"webgpu",kernelFunc:Ege};function _ge(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:o,reverse:i}=s;return mT(Cp.Sum,r,n,a,o,i)}var Dge={kernelName:Co,backendName:"webgpu",kernelFunc:_ge},$ge=class{constructor(e,t){this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.uniforms="blockSize : i32,",this.outputShape=e,this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`depthToSpace_${t}`,this.dataFormat=t}getUserCode(){return` ${Je("index")} { if (index < uniforms.size) { let coords = getCoordsFromIndex(index); let b = coords[0]; let h = ${this.getHeightCoordString()}; let w = ${this.getWidthCoordString()}; let d = ${this.getDepthCoordString()}; let in_h = h / uniforms.blockSize; let offset_h = h % uniforms.blockSize; let in_w = w / uniforms.blockSize; let offset_w = w % uniforms.blockSize; let offset_d = (offset_h * uniforms.blockSize + offset_w) * ${this.getOutputDepthSize()}; let in_d = d + offset_d; let rlt = ${this.getInputSamplingString()}; setOutputAtIndex(index, rlt); } }`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?"uniforms.outShape[3]":"uniforms.outShape[1]"}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}};function Pge(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],u=o==="NHWC"?r.shape[2]:r.shape[3],c=o==="NHWC"?r.shape[3]:r.shape[1],p=l*a,d=u*a,h=c/(a*a),f=o==="NHWC"?[i,p,d,h]:[i,h,p,d],m=[{type:"int32",data:[a]}],g=new $ge(f,o);return n.runWebGPUProgram(g,[r],r.dtype,m)}var Fge={kernelName:yl,backendName:"webgpu",kernelFunc:Pge},Oge=class{constructor(e,t,n,s=!1,r=null,a=!1){this.variableNames=["x","W"],this.uniforms="pad : vec2, inDims : vec2,",this.workGroupSize=[16,16,1],this.outputShape=e,this.dispatchLayout={x:[3],y:[2],z:[0,1]},this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),s&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),this.addBias=s,this.activation=r,this.hasPreluActivation=a,this.filterHeight=t,this.filterWidth=n,this.shaderKey=`depthwiseNCHW_${this.activation}_${this.filterHeight}_${this.filterWidth}`}getUserCode(){let e=this.filterWidth*this.filterHeight,t=this.workGroupSize[0]*this.workGroupSize[1]*this.workGroupSize[2],n=this.workGroupSize[1]+this.filterHeight-1,s=this.workGroupSize[0]+this.filterWidth-1;return` ${Pa(this.activation,this.hasPreluActivation,!1,4)} var mm_Asub : array, ${n}>; var mm_Bsub : array, ${this.filterHeight}>; fn readX(batch : i32, channel : i32, row : i32, col : i32) -> f32 { var value = 0.0; if (row >=0 && row < uniforms.inDims[0] && col >=0 && col < uniforms.inDims[1]) { value = getX(batch, channel, row, col); } return value; } ${Ip()} fn _start(@builtin(local_invocation_id) LocalId : vec3, @builtin(global_invocation_id) GlobalId : vec3, @builtin(local_invocation_index) LocalIndex: u32, @builtin(num_workgroups) NumWorkgroups: vec3) { localId = LocalId; globalId = GlobalId; let localIndex = i32(LocalIndex); numWorkgroups = NumWorkgroups; let coords = getOutputCoords(); let batch = coords[0]; let xRCCorner = vec2(coords.zw) - uniforms.pad; let channelMul = uniforms.wShape[3]; let d1 = coords[1] / channelMul; let q = coords[1] % channelMul; let inputRowStart = xRCCorner.x; let inputColStart = xRCCorner.y; let localRow = i32(localId.y); let localCol = i32(localId.x); // Load one tile of X into local memory. for (var inputRow = localRow; inputRow < ${n}; inputRow = inputRow + ${this.workGroupSize[1]}) { for (var inputCol = localCol; inputCol < ${s}; inputCol = inputCol + ${this.workGroupSize[0]}) { let rowOffset = inputRow - localRow; let colOffset = inputCol - localCol; mm_Asub[inputRow][inputCol] = readX(batch, d1, inputRowStart + rowOffset, inputColStart + colOffset); } } // Load one tile of W into local memory. var wIndex = localIndex; ${e, inDims : vec2,",this.workGroupSize=[4,4,4],this.workPerThread=4,this.isVec4=!0,this.outputShape=e.outShape,this.dispatchLayout={x:[3],y:[2],z:[0,1]},this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[4,this.workPerThread,1]),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=`depthwiseVec4_${n}_${this.convInfo.filterHeight}_${this.convInfo.filterWidth}_${this.convInfo.strideHeight}_${this.convInfo.strideWidth}_${this.workPerThread}`}getUserCode(){let e=(this.workPerThread-1)*this.convInfo.strideWidth+this.convInfo.filterWidth;return` ${Pa(this.activation,this.hasPreluActivation,!0,4)} fn readX(batch : i32, row : i32, col : i32, channel : i32) -> vec4 { var value = vec4(0.0); if (col >=0 && col < uniforms.inDims[1]) { value = getX(batch, row, col, channel); } return value; } const strideHeight = ${this.convInfo.strideHeight}; const strideWidth = ${this.convInfo.strideWidth}; ${Ip()} fn _start(@builtin(global_invocation_id) globalId: vec3) { let batch = i32(globalId.z) / uniforms.outShape[1]; let r = i32(globalId.z) % uniforms.outShape[1]; let c = i32(globalId.y) * ${this.workPerThread}; let d1 = i32(globalId.x) * 4; let xRCCorner = vec2(r, c) * vec2(strideHeight, strideWidth) - uniforms.pad; let xRCorner = xRCCorner.x; let xCCorner = xRCCorner.y; var xVals : array, ${e}>; var dotProd : array, ${this.workPerThread}>; for (var i = 0; i < ${this.workPerThread}; i++) { dotProd[i] = vec4(0.0); } // Use constant instead of uniform can give better performance. for (var wR = 0; wR < ${this.convInfo.filterHeight}; wR = wR + 1) { let xR = xRCorner + wR; if (xR >=0 && xR < uniforms.inDims[0]) { for (var i = 0; i < ${e}; i++) { xVals[i] = readX(batch, xR, xCCorner + i, d1); } for (var wC = 0; wC < ${this.convInfo.filterWidth}; wC = wC + 1) { let wValue = getW(wR, wC, d1, 0); for (var i = 0; i < ${this.workPerThread}; i++) { dotProd[i] = fma(xVals[i * strideWidth + wC], wValue, dotProd[i]); } } } } for (var i = 0; i < ${this.workPerThread}; i = i + 1) { let coords = vec4(batch, r, c + i, d1); if (coordsInBounds4D(coords, uniforms.outShape)) { var value = dotProd[i]; ${hu(this.addBias,this.activation)} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } } } `}},yT=class{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.uniforms=`pad : vec2, inDims : vec2, filterHeight : i32, filterWidth : i32, stride : vec2, dilation : vec2,`,this.workGroupSize=[256,1,1],this.outputShape=e.outShape,this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.isChannelsLast=e.dataFormat==="channelsLast",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.activation}_${this.isChannelsLast}`}getUserCode(){let e=this.isChannelsLast?"getX(batch, xR, xC, d1);":"getX(batch, d1, xR, xC);";return` ${Pa(this.activation,this.hasPreluActivation,!1,4)} ${Je()} { let coords = getOutputCoords(); let batch = coords[0]; let xRCCorner = vec2(coords.${this.isChannelsLast?"yz":"zw"}) * uniforms.stride - uniforms.pad; let d2 = coords[${this.isChannelsLast?3:1}]; let channelMul = uniforms.wShape[3]; let d1 = d2 / channelMul; let q = d2 % channelMul; let inputRowStart = xRCCorner.x; let inputColStart = xRCCorner.y; let inputRowEnd = inputRowStart + uniforms.filterHeight * uniforms.dilation[0]; let inputColEnd = inputColStart + uniforms.filterWidth * uniforms.dilation[1]; // Convolve x(?, ?, d1)|x(d1, ?, ?) with w(:, :, d1, q) to get // y(yR, yC, d2)|y(d2, yR, yC). ? = to be determined. : = across all // values in that axis. x(?, ?, d1) and y(yR, yC, d2) is for NHWC. // x(d1, ?, ?) and y(d2, yR, yC) is for NCHW. var value = 0.0; // Extract if checking out of for loop for performance. if (inputRowStart >= 0 && inputColStart >= 0 && inputRowEnd < uniforms.inDims[0] && inputColEnd < uniforms.inDims[1]) { for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) { let xR = inputRowStart + wR * uniforms.dilation[0]; for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) { let xC = inputColStart + wC * uniforms.dilation[1]; let xVal = ${e}; let wVal = getW(wR, wC, d1, q); value = value + xVal * wVal; } } } else { for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) { let xR = inputRowStart + wR * uniforms.dilation[0]; if (xR < 0 || xR >= uniforms.inDims[0]) { continue; } for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) { let xC = inputColStart + wC * uniforms.dilation[1]; if (xC < 0 || xC >= uniforms.inDims[1]) { continue; } let xVal = ${e}; let wVal = getW(wR, wC, d1, q); value = value + xVal * wVal; } } } ${hu(this.addBias,this.activation)} if (coordsInBounds4D(coords, uniforms.outShape)) { setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } } `}};function Mge(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:o,pad:i,dataFormat:l,dilations:u,dimRoundingMode:c}=s,p=T.convertConv2DDataFormat(l),d=u;d==null&&(d=[1,1]);let h=T.computeConv2DInfo(r.shape,a.shape,o,d,i,c,!0,p),f=[{type:"int32",data:[h.padInfo.top,h.padInfo.left]},{type:"int32",data:[h.inHeight,h.inWidth]}],m=h.dataFormat==="channelsLast",g;return!m&&h.inHeight>16&&h.inWidth>16&&h.strideHeight===1&&h.strideWidth===1&&h.dilationWidth===1&&h.dilationHeight===1&&h.inChannels===h.outChannels?g=new Oge(h.outShape,h.filterHeight,h.filterWidth):m&&h.inHeight>4&&h.inWidth>4&&h.strideWidth<=2&&h.inChannels===h.outChannels&&h.dilationHeight===1&&h.dilationWidth===1&&h.inChannels%4===0?g=new gT(h):(g=new yT(h),f.push({type:"int32",data:[h.filterHeight]},{type:"int32",data:[h.filterWidth]},{type:"int32",data:[h.strideHeight,h.strideWidth]},{type:"int32",data:[h.dilationHeight,h.dilationWidth]})),n.runWebGPUProgram(g,[r,a],r.dtype,f)}var zge={kernelName:To,backendName:"webgpu",kernelFunc:Mge},AT=Xn({opType:Xe.MUL,cpuKernelImpl:o1e,supportsComplex:!0}),Lge={kernelName:Ho,backendName:"webgpu",kernelFunc:AT};function lb(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;return Fh(r,a,o,"sum",n)}var Bge={kernelName:ri,backendName:"webgpu",kernelFunc:lb};function Wge(e){let{inputs:t,backend:n,attrs:s}=e,{equation:r}=s,a=t,{allDims:o,summedDims:i,idDims:l}=T.decodeEinsumEquation(r,a.length);T.checkEinsumDimSizes(o.length,l,a);let{path:u,steps:c}=T.getEinsumComputePath(i,l),p=c.length,d=null,h=o.length,f=[];for(let m=0;m=0&&(d=lb({inputs:{x:d},backend:n,attrs:{axis:u[m]-(o.length-h),keepDims:!1}}),f.push(d)),h--)}for(let m of f)m!==d&&n.disposeData(m.dataId);return d}var Vge={kernelName:$p,backendName:"webgpu",kernelFunc:Wge},Uge=vn({opType:De.ELU}),Gge={kernelName:Eo,backendName:"webgpu",kernelFunc:Uge},Hge=Xn({opType:Xe.EQUAL,dtype:"bool",cpuKernelImpl:j2e}),jge={kernelName:Al,backendName:"webgpu",kernelFunc:Hge},xT=vn({opType:De.EXP,cpuKernelImpl:q2e,dtype:"float32"}),qge={kernelName:Ro,backendName:"webgpu",kernelFunc:xT};function fy(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),Le({inputs:{x:a},backend:s,attrs:{shape:i}})}var Xge={kernelName:xl,backendName:"webgpu",kernelFunc:fy},Kge=vn({opType:De.EXPM1,cpuKernelImpl:X2e}),Zge={kernelName:bl,backendName:"webgpu",kernelFunc:Kge},Yge=class{constructor(e){this.outputShape=[],this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="flipLeftRight"}getUserCode(){return` ${Je("index")} { if (index < uniforms.size) { let coords = getCoordsFromIndex(index); let coordX = uniforms.xShape[2] - coords[2] - 1; let outputValue = getX(coords[0], coords[1], coordX, coords[3]); setOutputAtIndex(index, outputValue); } } `}},Jge={kernelName:vl,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,s=t,r=new Yge(n.shape);return s.runWebGPUProgram(r,[n],n.dtype)}},Qge=vn({opType:De.FLOOR,cpuKernelImpl:K2e}),e3e={kernelName:_o,backendName:"webgpu",kernelFunc:Qge},t3e=Xn({opType:Xe.INT_DIV,dtype:"int32"}),n3e={kernelName:Do,backendName:"webgpu",kernelFunc:t3e},s3e=class{constructor(e,t,n=!1){this.isFromPixels=!0,this.outputShape=[0],this.variableNames=[],this.workGroupSize=[256,1,1],this.outputShape=e,this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[t,1,1]),this.importVideo=n,this.shaderKey=`fromPixels_${this.importVideo}`}getUserCode(){let e=this.importVideo?"textureLoad(src, vec2(coords.yx));":"textureLoad(src, vec2(coords.yx), 0)";return` @binding(1) @group(0) var src: ${this.importVideo?"texture_external":"texture_2d"}; ${Je("index")} { let flatIndex = index * uniforms.numChannels; if (flatIndex < uniforms.size) { let coords = getCoordsFromIndex(flatIndex); let values = ${e}; for (var i = 0; i < uniforms.numChannels; i = i + 1) { result[flatIndex + i] = i32(floor(255.0 * values[i])); } } } `}},r3e={kernelName:lp,backendName:"webgpu",kernelFunc:a3e},Wu,c3=U().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU"),Wf=new Map;function a3e(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,u=typeof ImageBitmap!="undefined"&&r instanceof ImageBitmap,[c,p]=o?[r.videoWidth,r.videoHeight]:[r.width,r.height],d=[p,c,a],h=!1,f=o||i;if(u||l||f){let x;if(h){let D=r;if(!Wf.has(D)||Wf.get(D).expired){let E={source:D};Wf.set(D,n.device.importExternalTexture(E))}x={width:c,height:p,format:null,usage:null,texture:Wf.get(D)}}else{if(f){let S=U().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(Wu==null||S!==c3)&&(c3=S,Wu=document.createElement("canvas").getContext("2d",{willReadFrequently:c3})),Wu.canvas.width=c,Wu.canvas.height=p,Wu.drawImage(r,0,0,c,p),r=Wu.canvas}let D=GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,E="rgba8unorm",$=n.textureManager.acquireTexture(d[1],d[0],E,D);n.queue.copyExternalImageToTexture({source:r},{texture:$},[d[1],d[0]]),x={width:c,height:p,format:E,usage:D,texture:$}}let A=v.sizeFromShape(d),b=v.computeStrides(d),w=new s3e(d,a,h),k=[{type:"uint32",data:[A]},{type:"uint32",data:[a]},{type:"uint32",data:[...b]}],C=n.makeTensorInfo([p,c],"int32"),N=n.tensorMap.get(C.dataId);N.resourceInfo=x;let R=n.runWebGPUProgram(w,[C],"int32",k);return n.disposeData(C.dataId),R}let m=r.data,g=m;if(a!=null&&a!==4){g=new Uint8Array(r.width*r.height*a);let x=m.length,A=0;for(let b=0;b(xValue, -meanValue, offsetValue), vec3(inv, inv, 1.0))); } } `}},i3e={kernelName:$o,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:s,scale:r,offset:a,mean:o,variance:i}=e,{varianceEpsilon:l}=t,u=n,c=[s,o,i],p=null;a!=null&&(p=a.shape,c.push(a));let d=null;r!=null&&(d=r.shape,c.push(r));let h=new o3e(s.shape,o.shape,i.shape,p,d),f=[{type:"float32",data:[l]}];return u.runWebGPUProgram(h,c,s.dtype,f)}};function l3e(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=s,m=T.convertConv2DDataFormat(c),g=T.computeConv2DInfo(r.shape,a.shape,l,p,u,d,!1,m);return fT({x:r,filter:a,convInfo:g,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:f,activation:h})}var u3e={kernelName:so,backendName:"webgpu",kernelFunc:l3e};function c3e(e){let{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:u,dilations:c,dimRoundingMode:p,activation:d,leakyreluAlpha:h}=s,f=c;f==null&&(f=[1,1]),v.assert(T.eitherStridesOrDilationsAreOne(l,f),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${f}'`);let m=T.computeConv2DInfo(r.shape,a.shape,l,f,u,p,!0),g=[r,a],y=o!=null,x=i!=null;y&&g.push(o),x&&g.push(i);let A=[{type:"int32",data:[m.padInfo.top,m.padInfo.left]},{type:"int32",data:[m.inHeight,m.inWidth]}],b;return m.inHeight>4&&m.inWidth>4&&m.strideWidth<=2&&m.inChannels===m.outChannels&&m.dilationHeight===1&&m.dilationWidth===1&&m.inChannels%4===0?b=new gT(m,y,d,x):(b=new yT(m,y,d,x),A.push({type:"int32",data:[m.filterHeight]},{type:"int32",data:[m.filterWidth]},{type:"int32",data:[m.strideHeight,m.strideWidth]},{type:"int32",data:[m.dilationHeight,m.dilationWidth]})),d==="leakyrelu"&&(A.push({type:"float32",data:[h]}),b.uniforms+=" alpha : f32,"),n.runWebGPUProgram(b,g,"float32",A)}var d3e={kernelName:ro,backendName:"webgpu",kernelFunc:c3e},p3e=class{constructor(e,t){this.variableNames=["A","indices"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`gathernd_${e}`,this.sliceDim=e,this.uniforms=`sliceDim : i32, strides : ${zn(e)},`}getUserCode(){let e;return this.sliceDim>1?e="uniforms.strides[j]":e="uniforms.strides",` ${Je("index")} { if (index < uniforms.size) { let coords = getCoordsFromIndex(index); var flattenIndex = 0; for (var j = 0; j < uniforms.sliceDim; j = j + 1) { let indexTemp = i32(round(getIndices(coords[0], j))); let strideNum = ${e}; flattenIndex = flattenIndex + indexTemp * strideNum; } setOutputAtIndex(index, getA(flattenIndex, coords[1])); } } `}};function h3e(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,u,c,p]=T.prepareAndValidate(s,r),d=Le({inputs:{x:r},backend:n,attrs:{shape:[u,o]}}),h=Le({inputs:{x:s},backend:n,attrs:{shape:[v.sizeFromShape(s.shape)/c,c]}});if(n.shouldExecuteOnCPU([s,r])||s.dtype==="string"){let x=n.readSync(r.dataId),A=n.bufferSync(s),b=Z2e(x,A,s.dtype,u,o,c,p,s.shape,i);return n.makeTensorInfo(l,s.dtype,b.values)}let f=new p3e(o,[u,c]),m=[{type:"int32",data:[o]},{type:"int32",data:p}],g=n.runWebGPUProgram(f,[h,d],h.dtype,m),y=Le({inputs:{x:g},backend:n,attrs:{shape:l}});return n.disposeData(d.dataId),n.disposeData(h.dataId),n.disposeData(g.dataId),y}var f3e={kernelName:kl,backendName:"webgpu",kernelFunc:h3e},m3e=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=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="gather"}getUserCode(){let e=g3e(this.aShape);return` ${Je("index")} { if (index < uniforms.size) { let resRC = getCoordsFromIndex(index); let indexZ = i32(getIndices(resRC.x, resRC.z)); let inBounds = select(0.0, 1.0, indexZ >= 0 && indexZ < uniforms.aShape[2]); setOutputAtIndex(index, inBounds * getA(${e})); } } `}};function g3e(e){let t=["resRC.x","resRC.y","resRC.z","resRC.w"],n=[];for(let s=0;sn.disposeData(R.dataId)),n.makeTensorInfo(u.outputShape,N.dtype,N.values)}let m=new m3e(d.shape,f),g=n.runWebGPUProgram(m,[d,h],d.dtype);p.push(g);let y=Le({inputs:{x:g},backend:n,attrs:{shape:u.outputShape}});return p.forEach(x=>n.disposeData(x.dataId)),y}var y3e={kernelName:wl,backendName:"webgpu",kernelFunc:bT},A3e=Xn({opType:Xe.GREATER,cpuKernelImpl:Q2e,dtype:"bool"}),x3e={kernelName:Sl,backendName:"webgpu",kernelFunc:A3e},b3e=Xn({opType:Xe.GREATER_EQUAL,dtype:"bool",cpuKernelImpl:J2e}),v3e={kernelName:Po,backendName:"webgpu",kernelFunc:b3e},w3e=vn({opType:De.IS_NAN,dtype:"bool"}),k3e={kernelName:Il,backendName:"webgpu",kernelFunc:w3e};function S3e(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{alpha:a}=s,o=[{type:"float32",data:[a]}],i=new Ph(r.shape,De.LEAKYRELU);return i.uniforms="alpha : f32,",n.runWebGPUProgram(i,[r],"float32",o)}var I3e={kernelName:Oo,backendName:"webgpu",kernelFunc:S3e},C3e=Xn({opType:Xe.LESS,dtype:"bool",cpuKernelImpl:t1e}),T3e={kernelName:Cl,backendName:"webgpu",kernelFunc:C3e},N3e=Xn({opType:Xe.LESS_EQUAL,dtype:"bool",cpuKernelImpl:e1e}),E3e={kernelName:Tl,backendName:"webgpu",kernelFunc:N3e},R3e=vn({opType:De.LOG,cpuKernelImpl:n1e}),_3e={kernelName:Mo,backendName:"webgpu",kernelFunc:R3e},D3e=Xn({opType:Xe.LOGICAL_AND,dtype:"bool"}),$3e={kernelName:Nl,backendName:"webgpu",kernelFunc:D3e},P3e=vn({opType:De.LOGICAL_NOT}),F3e={kernelName:El,backendName:"webgpu",kernelFunc:P3e},O3e=Xn({opType:Xe.MAX,cpuKernelImpl:r1e}),M3e={kernelName:Lo,backendName:"webgpu",kernelFunc:O3e};function z3e(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=s,u=1,c=T.computePool2DInfo(r.shape,a,o,u,i,l);return dT(r,c,"max",n)}var L3e={kernelName:Bo,backendName:"webgpu",kernelFunc:z3e};function B3e(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;return Fh(r,a,o,"min",n)}var W3e={kernelName:Vo,backendName:"webgpu",kernelFunc:B3e},V3e=Xn({opType:Xe.MIN,cpuKernelImpl:a1e}),U3e={kernelName:Uo,backendName:"webgpu",kernelFunc:V3e},G3e=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=it(this.outputShape),this.dispatch=Be(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,u)=>`uniforms.pad${u}[0]`).join(","),n=this.xShape.map((l,u)=>`uniforms.pad${u}[0] + uniforms.xShape${e>1?`[${u}]`:""}`).join(","),s=e===1?"start":"start[i]",r=e===1?"end":"end[i]",a=e===1?"outC":"outC[i]",o=zn(e),i=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return` ${Je("index")} { if (index < uniforms.size) { let start = ${o}(${t}); let end = ${o}(${n}); var outC = getCoordsFromIndex(index); for (var i = 0; i < ${e}; i = i + 1) { if (${a} < ${s}) { ${a} = ${s} * 2 - ${a} - ${this.offset}; } else if(${a} >= ${r}) { ${a} = (${r} - 1) * 2 - ${a} + ${this.offset}; } } let coords = outC - start; setOutputAtIndex(index, getX(${i})); } } `}},H3e={kernelName:Go,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:s}=e,{paddings:r,mode:a}=t,o=n,i=r.map(c=>({type:"int32",data:[c[0],c[1]]})),l=new G3e(s.shape,r,a);return o.runWebGPUProgram(l,[s],s.dtype,i)}};function j3e(e){let{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])){let a=n.tensorMap.get(s.dataId),[o,i]=i1e(a.values,s.shape,s.dtype);return n.makeTensorInfo(i,s.dtype,o)}let r=new Ph(s.shape,De.NEG);return n.runWebGPUProgram(r,[s],s.dtype)}var q3e={kernelName:Rl,backendName:"webgpu",kernelFunc:j3e};function X3e(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,u=n.readSync(r.dataId),c=n.readSync(a.dataId),{selectedIndices:p}=Ar.nonMaxSuppressionV3Impl(u,c,o,i,l);return n.makeTensorInfo([p.length],"int32",new Int32Array(p))}var K3e={kernelName:Dl,backendName:"webgpu",kernelFunc:X3e};function Z3e(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:u}=s,c=n.readSync(r.dataId),p=n.readSync(a.dataId),d=o,h=i,f=l,m=u,{selectedIndices:g,selectedScores:y}=Ar.nonMaxSuppressionV5Impl(c,p,d,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var Y3e={kernelName:$l,backendName:"webgpu",kernelFunc:Z3e};function Nm(e){let{inputs:t,backend:n}=e,{x:s}=t;if(s.dtype==="complex64"){let r=Oh({inputs:{input:s},backend:n}),a=Nm({inputs:{x:r},backend:n}),o=A2({inputs:{input:s},backend:n}),i=Nm({inputs:{x:o},backend:n}),l=cd({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 fu({attrs:{shape:s.shape,dtype:s.dtype,value:s.dtype==="string"?"":0},backend:n})}var J3e={kernelName:Jl,backendName:"webgpu",kernelFunc:Nm};function vT(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=Oh({inputs:{input:s},backend:n}),a=vT({inputs:{x:r},backend:n}),o=A2({inputs:{input:s},backend:n}),i=Nm({inputs:{x:o},backend:n}),l=cd({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 fu({attrs:{shape:s.shape,dtype:s.dtype,value:1},backend:n})}var Q3e={kernelName:Pl,backendName:"webgpu",kernelFunc:vT};function eye(e){let{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(t.length===1)return fy({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let a=t[0].shape,o=t[0].dtype;t.forEach(c=>{v.assertShapesMatch(a,c.shape,"All tensors passed to stack must have matching shapes"),v.assert(o===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(c=>{let p=fy({inputs:{input:c},backend:n,attrs:{dim:r}});return i.push(p),p}),u=hT({inputs:l,backend:n,attrs:{axis:r}});return i.forEach(c=>n.disposeData(c.dataId)),u}var tye={kernelName:Ol,backendName:"webgpu",kernelFunc:eye},nye=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=it(this.outputShape),this.dispatch=Be(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=zn(e),n=this.xShape.map((c,p)=>`uniforms.pad${p}[0]`).join(","),s=this.xShape.map((c,p)=>`uniforms.pad${p}[0] + uniforms.xShape${e>1?`[${p}]`:""}`).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` ${Je("index")} { if (index < uniforms.size) { let start = ${r}; let end = ${a}; let outC = getCoordsFromIndex(index); if (${o} || ${i}) { setOutputAtIndex(index, uniforms.constantValue); } else { let coords = outC - start; setOutputAtIndex(index, getX(${l})); } } } `}},wT=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,constantValue:o}=s;if(a.every(u=>v.arraysEqual(u,[0,0])))return Qs({inputs:{x:r},backend:n});if(v.sizeFromShape(r.shape)===0){let u=a.map((c,p)=>c[0]+r.shape[p]+c[1]);return fu({backend:n,attrs:{shape:u,value:o,dtype:r.dtype}})}let i=[{type:"float32",data:[o]}];a.map(u=>i.push({type:"int32",data:[u[0],u[1]]}));let l=new nye(r.shape,a);return n.runWebGPUProgram(l,[r],r.dtype,i)},sye={kernelName:jo,backendName:"webgpu",kernelFunc:wT},rye=Xn({opType:Xe.POW}),aye={kernelName:qo,backendName:"webgpu",kernelFunc:rye};function oye(e){let{inputs:t,backend:n}=e,{x:s,alpha:r}=t,a=new dy(Xe.PRELU,s.shape,r.shape);return n.runWebGPUProgram(a,[s,r],"float32")}var iye={kernelName:Xo,backendName:"webgpu",kernelFunc:oye};function lye(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:o}=s;return Fh(r,a,o,"prod",n)}var uye={kernelName:Ko,backendName:"webgpu",kernelFunc:lye},cye=e=>{let{backend:t,attrs:n}=e,{start:s,stop:r,step:a,dtype:o}=n,i=c1e(s,r,a,o);return t.makeTensorInfo([i.length],o,i)},dye={kernelName:$c,backendName:"webgpu",kernelFunc:cye},kT=Xn({opType:Xe.DIV}),pye={kernelName:No,backendName:"webgpu",kernelFunc:kT},hye=vn({opType:De.RECIPROCAL}),fye={kernelName:Ml,backendName:"webgpu",kernelFunc:hye},mye=vn({opType:De.RELU}),gye={kernelName:Zo,backendName:"webgpu",kernelFunc:mye},yye=vn({opType:De.RELU6}),Aye={kernelName:Qo,backendName:"webgpu",kernelFunc:yye},xye=class{constructor(e,t,n){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2, halfPixelCenters : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,n,e[3]],this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="resizeBilinear"}getUserCode(){return` ${Je("index")} { if (index < uniforms.size) { let coords = getCoordsFromIndex(index); let b = coords[0]; let d = coords[3]; let rc = coords.yz; let effectiveInSize = vec2( f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0], f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]); let effectiveOutSize = vec2( f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0], f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]); let effectiveInputOverOutputRatioRC = effectiveInSize / effectiveOutSize; // Fractional source index let sourceFracIndexRC = (vec2(rc) + vec2(uniforms.halfPixelCenters)) * effectiveInputOverOutputRatioRC - vec2(uniforms.halfPixelCenters); // 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; setOutputAtIndex(index, newValue); } } `}};function bye(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,size:o,halfPixelCenters:i}=s,[l,u]=o,c=a&&l>1?1:0,p=a&&u>1?1:0,h=[{type:"float32",data:[c,p]},{type:"float32",data:[i?.5:0]}],f=new xye(r.shape,l,u);return n.runWebGPUProgram(f,[r],"float32",h)}var vye={kernelName:Jo,backendName:"webgpu",kernelFunc:bye},wye=class{constructor(e,t,n,s){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2, roundBase : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,n,e[3]],this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.halfPixelCenters=s,this.shaderKey=`resizeNearest_${s}`}getUserCode(){let e;return this.halfPixelCenters?e="max((vec2(rc) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":e="vec2(rc) * effectiveInputOverOutputRatioRC",` ${Je("index")} { if (index < uniforms.size) { let coords = getCoordsFromIndex(index); let b = coords[0]; let d = coords[3]; let rc = coords.yz; let effectiveInSize = vec2( f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0], f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]); let effectiveOutSize = vec2( f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0], f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]); let effectiveInputOverOutputRatioRC = effectiveInSize / effectiveOutSize; // Fractional source index let sourceFracIndexRC = ${e}; // Compute the coordinators of nearest neighbor point. let inputShapeRC = vec2(f32(uniforms.xShape.y), f32(uniforms.xShape.z)); let sourceNearestRC = vec2( min(inputShapeRC - 1.0, floor(sourceFracIndexRC + uniforms.roundBase))); let newValue = getX(b, sourceNearestRC.x, sourceNearestRC.y, d); setOutputAtIndex(index, newValue); } } `}};function kye(e){let{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:o,size:i}=s,[l,u]=i,c=a&&l>1?1:0,p=a&&u>1?1:0,h=[{type:"float32",data:[c,p]},{type:"float32",data:[a?.5:0]}],f=new wye(r.shape,l,u,o);return n.runWebGPUProgram(f,[r],r.dtype,h)}var Sye={kernelName:Yo,backendName:"webgpu",kernelFunc:kye},Iye=class{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms=`centerX : f32, centerY : f32, sinRadians : f32, cosRadians : f32,`,this.shaderKey="rotate",this.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` ${Je("index")} { if (index < uniforms.size) { let coords = getCoordsFromIndex(index); let coordXFloat = (f32(coords[2]) - uniforms.centerX) * uniforms.cosRadians - (f32(coords[1]) - uniforms.centerY) * uniforms.sinRadians; let coordYFloat = (f32(coords[2]) - uniforms.centerX) * uniforms.sinRadians + (f32(coords[1]) - uniforms.centerY) * uniforms.cosRadians; let coordX = i32(round(coordXFloat + uniforms.centerX)); let coordY = i32(round(coordYFloat + uniforms.centerY)); ${this.fillSnippet} if(coordX >= 0 && coordX < uniforms.xShape[2] && coordY >= 0 && coordY < uniforms.xShape[1]) { outputValue = getX(coords[0], coordY, coordX, coords[3]); } setOutputAtIndex(index, outputValue); } } `}},Cye={kernelName:Ql,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:s}=e,{radians:r,fillValue:a,center:o}=t,i=n,l=new Iye(s.shape,a),[u,c]=T.getImageCenter(o,s.shape[1],s.shape[2]),p=[{type:"float32",data:[u]},{type:"float32",data:[c]},{type:"float32",data:[Math.sin(r)]},{type:"float32",data:[Math.cos(r)]}];return typeof a=="number"?p.push({type:"float32",data:[Number.parseFloat(a.toFixed(2))]}):p.push({type:"float32",data:a}),i.runWebGPUProgram(l,[s],s.dtype,p)}},Tye=vn({opType:De.RSQRT,cpuKernelImpl:d1e}),Nye={kernelName:ei,backendName:"webgpu",kernelFunc:Tye},Yf=class{constructor(e,t,n,s,r,a,o,i=!0){this.variableNames=["updates","indices"],this.workGroupSize=[64,1,1],this.atomic=!0,this.outputShape=a,this.type=o,this.sumDupeIndices=i,this.dispatchLayout=it(e),this.dispatch=Be(this.dispatchLayout,e,this.workGroupSize),this.sliceDimGreaterThanOne=t>1,this.shaderKey=`scatter_${n}_${s}_${this.sliceDimGreaterThanOne}_${o}_${i}`;let l=zn(r.length);this.uniforms=`sliceDim : i32, strides: ${l}, 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="";this.dispatchLayout.x.length===1?(s="flattenedIndex",r=` fn getUpdatesCoordsFromFlatIndex(index : i32) -> i32 { return index; } `):this.dispatchLayout.x.length===2&&(s="vec2(flattenedIndex, coords[1])",r=` fn getUpdatesCoordsFromFlatIndex(index : i32) -> vec2 { // N.B. |updates| could be a scalar tensor, conceptually representing a // 2D tensor with all values equal to that. By design, its size must be // the same as |outShape[1]| in one dimension, and |indicesShape[0]| // gives the other. let sliceSize = uniforms.outShape[1]; let d0 = index / sliceSize; let d1 = index - d0 * sliceSize; return vec2(d0, d1); } `);let o=`getUpdates(${Array.from({length:this.updatesRank},(u,c)=>`coords[${c}]`).join(", ")})`,i=(u,c)=>{let p=`atomicAdd(${u}, bitcast(${c}))`;this.type==="float32"&&(p=` { var oldBits = 0; var newBits = bitcast(${c}); loop { let info = atomicCompareExchangeWeak(${u}, oldBits, newBits); if (info.exchanged) { break; } oldBits = info.old_value; let oldValue = bitcast(oldBits); let newValue = oldValue + (${c}); newBits = bitcast(newValue); } } `);let d=`atomicStore(${u}, bitcast(${c}));`;return this.sumDupeIndices?p:d};return` ${r} ${Je("index")} { 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 = ${op(this.type,!1)}(${o}); let flatIndex = getOutputIndexFromCoords(${s}); ${i("&result[flatIndex]","updateValue")}; } }`}};function Eye(e){let{inputs:t,backend:n,attrs:s}=e,{indices:r,updates:a}=t,{shape:o}=s,{sliceRank:i,numUpdates:l,sliceSize:u,strides:c,outputSize:p}=T.calculateShapes(a,r,o),d=[p/u,u];if(p===0)return n.makeTensorInfo(o,r.dtype);let h=Le({inputs:{x:r},backend:n,attrs:{shape:[l,i]}}),f=Le({inputs:{x:a},backend:n,attrs:{shape:[l,u]}}),m=f.dtype,g=fu({backend:n,attrs:{shape:d,value:0,dtype:m}}),y=v.sizeFromShape(f.shape),x=[{type:"int32",data:[i]},{type:"int32",data:c},{type:"int32",data:[y]}],A=new Yf(f.shape,i,h.shape.length,f.shape.length,c,d,m),b=n.runWebGPUProgram(A,[f,h],m,x,g),w=Le({inputs:{x:b},backend:n,attrs:{shape:o}});return n.disposeData(h.dataId),n.disposeData(f.dataId),n.disposeData(b.dataId),w}var Rye={kernelName:Wl,backendName:"webgpu",kernelFunc:Eye},_ye=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=it(this.outputShape),this.dispatch=Be(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) { setOutputAtIndex(index, getA(${t})); } else { setOutputAtIndex(index, getB(${t})); } } } `}};function Dye(e){let{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t,o=new _ye(s.shape.length,r.shape,r.shape.length);return n.runWebGPUProgram(o,[s,r,a],jn(r.dtype,a.dtype))}var $ye={kernelName:Vl,backendName:"webgpu",kernelFunc:Dye},Pye=vn({opType:De.SIGMOID}),Fye={kernelName:ni,backendName:"webgpu",kernelFunc:Pye},Oye=vn({opType:De.SIN}),Mye={kernelName:ti,backendName:"webgpu",kernelFunc:Oye},zye=vn({opType:De.SINH}),Lye={kernelName:Gl,backendName:"webgpu",kernelFunc:zye},ST=Xn({opType:Xe.SUB,cpuKernelImpl:y1e,supportsComplex:!0}),Bye={kernelName:ii,backendName:"webgpu",kernelFunc:ST};function Wye(e){let{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{dim:a}=s,o=v.parseAxisParam([a],r.shape),i=ib({inputs:{x:r},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),l=T.expandShapeToKeepDim(i.shape,o),u=Le({inputs:{x:i},backend:n,attrs:{shape:l}}),c=ST({inputs:{a:r,b:u},backend:n}),p=xT({inputs:{x:c},backend:n}),d=lb({inputs:{x:p},backend:n,attrs:{axis:o,keepDims:!1}}),h=Le({inputs:{x:d},backend:n,attrs:{shape:l}}),f=kT({inputs:{a:p,b:h},backend:n});return n.disposeData(i.dataId),n.disposeData(u.dataId),n.disposeData(c.dataId),n.disposeData(p.dataId),n.disposeData(d.dataId),n.disposeData(h.dataId),f}var Vye={kernelName:ai,backendName:"webgpu",kernelFunc:Wye},Uye=e=>{let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:o}=s;v.assert(r.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGPU backend not implemented yet");let i=a.reduce((y,x)=>y*x),l=[[0,0]];l.push(...o);for(let y=1+a.length;yn.disposeData(y.dataId)),g},Gye={kernelName:Hl,backendName:"webgpu",kernelFunc:Uye},Hye=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),u=r.dtype==="string"?l.map(d=>v.decodeString(d)):l,c=ze(r.shape,r.dtype,u),p=A1e(c,a);return n.makeTensorInfo(p.shape,p.dtype,p.values)}let o=new Hye(r.shape,a);return n.runWebGPUProgram(o,[r],r.dtype)}var qye={kernelName:Ea,backendName:"webgpu",kernelFunc:IT};function Xye(e){let{inputs:t,backend:n,attrs:s}=e,{sparseIndices:r,sparseValues:a,defaultValue:o}=t,{outputShape:i}=s,{sliceRank:l,numUpdates:u,sliceSize:c,strides:p,outputSize:d}=T.calculateShapes(a,r,i),h=!1;if(a.dtype==="string"){let N=n.bufferSync(r),R=n.bufferSync(a),D=v.decodeString(n.readSync(o.dataId)[0]),E=p1e(N,R,i,d,c,u,l,p,D,h);return n.makeTensorInfo(i,E.dtype,E.values)}let f=[d/c,c],m=Le({inputs:{x:r},backend:n,attrs:{shape:[u,l]}}),g=a.shape.length?Le({inputs:{x:a},backend:n,attrs:{shape:[u,c]}}):Qs({inputs:{x:a},backend:n}),y=g.dtype,x=n.makeTensorInfo([],y,v.makeZerosTypedArray(1,y)),A=Le({inputs:{x:o},backend:n,attrs:{shape:Array(f.length).fill(1)}}),b=IT({inputs:{x:A},backend:n,attrs:{reps:f}}),w=v.sizeFromShape([u,c]),k=[{type:"int32",data:[l]},{type:"int32",data:p},{type:"int32",data:[w]}];switch(u){case 0:break;case 1:{let N=new Yf([u,c],l,m.shape.length,g.shape.length,p,f,y,h);n.runWebGPUProgram(N,[g,m],y,k,b)}break;default:{let N=new Yf([u,c],l,m.shape.length,x.shape.length,p,f,y,h);n.runWebGPUProgram(N,[x,m],y,k,b)}{let N=new Yf([u,c],l,m.shape.length,g.shape.length,p,f,y);n.runWebGPUProgram(N,[g,m],y,k,b)}}let C=Le({inputs:{x:b},backend:n,attrs:{shape:i}});return n.disposeData(m.dataId),n.disposeData(g.dataId),n.disposeData(A.dataId),n.disposeData(x.dataId),n.disposeData(b.dataId),C}var Kye={kernelName:Wp,backendName:"webgpu",kernelFunc:Xye};function Zye(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=T.prepareSplitSize(r,a,i),u=r.shape.length,c=new Array(u).fill(0),p=r.shape.slice();return l.map(d=>{let h=[...p];h[i]=d;let f=dd({inputs:{x:r},backend:n,attrs:{begin:c,size:h}});return c[i]+=d,f})}var Yye={kernelName:jl,backendName:"webgpu",kernelFunc:Zye},Jye=vn({opType:De.SQRT}),Qye={kernelName:si,backendName:"webgpu",kernelFunc:Jye},eAe={kernelName:zc,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,s=t,r=new Ph(n.shape,De.SQUARE);return s.runWebGPUProgram(r,[n],n.dtype)}},tAe=Xn({opType:Xe.SQUARED_DIFFERENCE}),nAe={kernelName:oi,backendName:"webgpu",kernelFunc:tAe},sAe=class{constructor(e){this.variableNames=["x"],this.workPerThread=1,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]);let t=zn(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` ${Je("index")} { if (index < uniforms.size) { let coords = getCoordsFromIndex(index); setOutputAtIndex(index, getX(${t})); } } `}};function rAe(e){let{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:d}=s,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:x,end:A,strides:b}=Gt.sliceInfo(r.shape,a,o,i,l,u,c,p,d),w;if(m)w=Le({inputs:{x:r},backend:n,attrs:{shape:f}});else if(g||y){v.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let k=Gt.computeOutShape(x,A,b),C=dd({inputs:{x:r},backend:n,attrs:{begin:x,size:k}});w=Le({inputs:{x:C},backend:n,attrs:{shape:f}}),n.disposeData(C.dataId)}else if(n.shouldExecuteOnCPU([r])){let C=n.readSync(r.dataId),N=ze(r.shape,r.dtype,C),R=m1e(h,N,b,x);w=n.makeTensorInfo(f,r.dtype,R.values)}else{let C=new sAe(h),N=[{type:"int32",data:x},{type:"int32",data:b}],R=n.runWebGPUProgram(C,[r],r.dtype,N);w=Le({inputs:{x:R},backend:n,attrs:{shape:f}}),n.disposeData(R.dataId)}return w}var aAe={kernelName:ql,backendName:"webgpu",kernelFunc:rAe};function oAe(e){let{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:u}=s,{data:c,dataSplits:p}=t,d=n.readSync(c.dataId),h=n.readSync(p.dataId),[f,m]=g1e(d,h,r,a,o,i,l,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(p.shape,"int32",m)]}var iAe={kernelName:Lc,backendName:"webgpu",kernelFunc:oAe},lAe=vn({opType:De.TANH}),uAe={kernelName:li,backendName:"webgpu",kernelFunc:lAe},cAe=class{constructor(e){this.variableNames=["x","indices"],this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms=`inputSize : i32, firstPass : i32, negativeInf : f32, dir : i32, inc : i32,`,this.shaderKey="swap"}getUserCode(){return` ${Je("index")} { if (index < uniforms.size) { let outC = getCoordsFromIndex(index); let batch = outC[0]; let elemIdx = outC[1]; // We compare elements pair-wise within a group of size 2 * inc. // The comparing rule for each group alternates between ascending // and descending. Within each group, we compare each pair at // positions i and i+inc. To decide whether an element at position i // is x0 or x1, we mod it by 2 * inc, if the result is smaller than // inc, it is in the first half of the group, we denote it as x0, // otherwise we denote it as x1. // For example, as shown in the Bitonic top K paper referenced // above, Figure5(a) shows that element[1] is in the second half of // the group when group size is 2, but it is in the first half of // the group when group size is 4. let isFirstInPair = elemIdx % (2 * uniforms.inc) < uniforms.inc; var i = 0; if (isFirstInPair) { i = elemIdx; } else { i = elemIdx - uniforms.inc; } var i0 = 0; if (uniforms.firstPass == 1) { i0 = i; } else { i0 = i32(getIndices(batch, i)); } var i1 = 0; if (uniforms.firstPass == 1) { i1 = i + uniforms.inc; } else { i1 = i32(getIndices(batch, i + uniforms.inc)); } var x0 = f32(0.0); var x1 = f32(0.0); if (i0 < uniforms.inputSize) { x0 = getX(batch, i0); } else { x0 = uniforms.negativeInf; } if (i1 < uniforms.inputSize) { x1 = getX(batch, i1); } else { x1 = uniforms.negativeInf; } let reverse = elemIdx % (2 * uniforms.dir) >= uniforms.dir; let isGreater = x0 > x1 || (x0 == x1 && i1 > i0); if (reverse == isGreater) { // Elements in opposite order of direction let iTemp = i0; i0 = i1; i1 = iTemp; } if (isFirstInPair) { setOutputAtIndex(index, f32(i0)); } else { setOutputAtIndex(index, f32(i1)); } } } `}},dAe=class{constructor(e){this.variableNames=["x","indices"],this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms="inputSize : i32, firstPass : i32, k : i32,",this.shaderKey="merge"}getUserCode(){return` ${Je("index")} { if (index < uniforms.size) { let outC = getCoordsFromIndex(index); let batch = outC[0]; let elemIdx = outC[1]; // The output size is half of the previous size. // If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ // (k=4), we only need to output the indices at positions |, the // indices at positions _ can be thrown away, see Figure5(b) After // Phase 2 (Merge phase) in the Bitonic Top K paper referenced // above. // For example, the paper shows we only need to output the orange // bars. The output sequence should look like this | | | | | | | |. // Because the sequence is halved, to map the output index back to // the previous sequence to find the corresponding value, we need // to double the index. When we double the index, we basically // interpolate a position, so 2i looks like // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k // position of each 2k positions by - elemIdx % k. E.g. for output // at index 4,5,6,7, we want to get the corresponding element at // original index 8,9,10,11, for output at index 8,9,10,11, // we want to get the corresponding element at original index // 16,17,18,19, so on and so forth. var i = 0; if (elemIdx < uniforms.k) { i = elemIdx; } else { i = elemIdx * 2 - elemIdx % uniforms.k; } var i0 = 0; if (uniforms.firstPass == 1) { i0 = i; } else { i0 = i32(getIndices(batch, i)); } var i1 = 0; if (uniforms.firstPass == 1) { i1 = i + uniforms.k; } else { i1 = i32(getIndices(batch, i + uniforms.k)); } let x0 = getX(batch, i0); var x1 = f32(0.0); if (i1 < uniforms.inputSize) { x1 = getX(batch, i1); } else { x1 = x0; } if (x0 >= x1) { setOutputAtIndex(index, f32(i0)); } else { setOutputAtIndex(index, f32(i1)); } } } `}};function Vu(e,t){t!==null&&e.disposeData(t.dataId)}function Q7(e){let t=1;for(;tf===null?[p,p]:[p,f],g=(w,k,C)=>{let N=m(),R=new cAe(C),E=[{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]}],$=f;f=n.runWebGPUProgram(R,N,"int32",E),Vu(n,$)};for(let w=1;w=1;C/=2)g(k,C,[c,h])}for(let w=h;w>d;w/=2){let k=m(),C=new dAe([c,w/2]),R=[{type:"int32",data:[l]},{type:"int32",data:[f===null?1:0]},{type:"int32",data:[d]}],D=f;f=n.runWebGPUProgram(C,k,"int32",R),Vu(n,D);let E=d/2,$=E*2;for(let S=E;S>=1;S/=2)g($,S,f.shape)}let y=f;f=dd({inputs:{x:f},backend:n,attrs:{begin:0,size:[c,a]}}),Vu(n,y);let x=bT({inputs:{x:p,indices:f},backend:n,attrs:{axis:1,batchDims:1}});Vu(n,p);let A=i.slice(0,-1);A.push(a),y=f,f=Le({inputs:{x:f},attrs:{shape:A},backend:n}),Vu(n,y);let b=x;return x=Le({inputs:{x},attrs:{shape:A},backend:n}),Vu(n,b),[x,f]}var hAe={kernelName:Kl,backendName:"webgpu",kernelFunc:pAe},fAe=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=it(this.outputShape),this.dispatch=Be(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="transform"}getUserCode(){return` fn mapCoord(outCoord : f32, len : f32) -> f32{ var inCoord = outCoord; if(uniforms.fillModeId == 2) { if (inCoord < 0.0) { if (len <= 1.0) { inCoord = 0.0; } else { let sz2 = 2.0 * len; if (inCoord < sz2) { inCoord = sz2 * f32(i32(f32(-inCoord / sz2))) + inCoord; } if (inCoord < -len) { inCoord = inCoord + sz2; } else { inCoord = -inCoord - 1.0; } } } else if (inCoord > len - 1.0) { if (len <= 1.0) { inCoord = 0.0; } else { let sz2 = 2.0 * len; inCoord = inCoord - sz2 * f32(i32(f32(inCoord / sz2))); if (inCoord >= len) { inCoord = sz2 - inCoord - 1.0; } } } return clamp(inCoord, 0.0, len - 1.0); } else if (uniforms.fillModeId == 3) { if (inCoord < 0.0) { if (len <= 1.0) { inCoord = 0.0; } else { let sz = len - 1.0; inCoord = inCoord + len * (f32(i32(f32(-inCoord / sz))) + 1.0); } } else if (inCoord > len - 1.0) { if (len <= 1.0) { inCoord = 0.0; } else { let sz = len - 1.0; inCoord = inCoord - len * f32(i32(f32(inCoord / sz))); } } return clamp(inCoord, 0.0, len - 1.0); } else if (uniforms.fillModeId == 4) { return clamp(outCoord, 0.0, len - 1.0); } return outCoord; } fn readWithFillValue(batch : i32, coordY : i32, coordX : i32, channel : i32) -> f32 { var outputValue : f32; if (0 <= coordY && coordY < uniforms.imageShape[1] && 0 <= coordX && coordX < uniforms.imageShape[2]) { outputValue = getImage(batch, coordY, coordX, channel); } else { outputValue = uniforms.fillValue; } return outputValue; } ${Je("index")} { if (index < uniforms.size) { let coords = getCoordsFromIndex(index); var outputValue : f32; let batch = coords[0]; let x = coords[2]; let y = coords[1]; let channel = coords[3]; let xf = f32(x); let yf = f32(y); let a1 = getTransforms(batch, 0); let a2 = getTransforms(batch, 1); let a3 = getTransforms(batch, 2); let b1 = getTransforms(batch, 3); let b2 = getTransforms(batch, 4); let b3 = getTransforms(batch, 5); let c1 = getTransforms(batch, 6); let c2 = getTransforms(batch, 7); let projection = c1 * xf + c2 * yf + 1.0; if (projection == 0.0) { outputValue = uniforms.fillValue; } else { let inX = (a1 * xf + a2 * yf + a3) / projection; let inY = (b1 * xf + b2 * yf + b3) / projection; let mapX = mapCoord(inX, f32(uniforms.imageShape[2])); let mapY = mapCoord(inY, f32(uniforms.imageShape[1])); if (uniforms.interpolationModeId == 1) { let coordY = i32(round(mapY)); let coordX = i32(round(mapX)); outputValue = readWithFillValue(batch, coordY, coordX, channel); } else { let yFloor = floor(mapY); let xFloor = floor(mapX); let yCeil = yFloor + 1.0; let xCeil = xFloor + 1.0; let valueYFloor = (xCeil - mapX) * readWithFillValue(batch, i32(yFloor), i32(xFloor), channel) + (mapX - xFloor) * readWithFillValue(batch, i32(yFloor), i32(xCeil), channel); let valueYCeil = (xCeil - mapX) * readWithFillValue(batch, i32(yCeil), i32(xFloor), channel) + (mapX - xFloor) * readWithFillValue(batch, i32(yCeil), i32(xCeil), channel); outputValue = (yCeil - mapY) * valueYFloor + (mapY - yFloor) * valueYCeil; } } setOutputAtIndex(index, outputValue); } } `}};function mAe(e){let{inputs:t,backend:n,attrs:s}=e,{image:r,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:l,outputShape:u}=s,[c,p,d,h]=r.shape,[f,m]=u!=null?u:[p,d],g=[c,f,m,h],y=new fAe(g),x=o==="nearest"?1:2,A;switch(i){case"constant":A=1;break;case"reflect":A=2;break;case"wrap":A=3;break;case"nearest":A=4;break;default:A=1;break}let b=[{type:"int32",data:[x]},{type:"int32",data:[A]},{type:"float32",data:[l]}];return n.runWebGPUProgram(y,[r,a],"float32",b)}var gAe={kernelName:Zl,backendName:"webgpu",kernelFunc:mAe};function yAe(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],u=new Array(i-1),c=0;for(let m=0;mn.disposeData(m.dataId)),f}var AAe={kernelName:Yl,backendName:"webgpu",kernelFunc:yAe},xAe=[L2e,w1e,S1e,T1e,$1e,F1e,M1e,U1e,H1e,Z1e,ege,nge,oge,W2e,cge,gge,vge,kge,Ige,Nge,Rge,Dge,Fge,zge,Vge,Gge,jge,qge,Xge,Zge,O2e,Jge,r3e,e3e,n3e,i3e,u3e,d3e,f3e,y3e,x3e,v3e,B2e,lge,k3e,I3e,T3e,E3e,_3e,$3e,F3e,B1e,M3e,L3e,W1e,W3e,U3e,H3e,Lge,q3e,K3e,Y3e,Y1e,Q3e,tye,sye,aye,iye,uye,dye,J1e,pye,fye,gye,Aye,M2e,vye,Sye,Cye,Nye,Rye,$ye,Fye,Mye,Lye,X1e,aAe,iAe,Vye,Gye,Kye,Yye,Qye,eAe,nAe,Bye,Bge,uAe,qye,hAe,gAe,_1e,AAe,J3e];for(let e of xAe)er(e);var bAe="3.21.0",vAe="3.21.0",wAe="3.21.0",kAe="3.21.0",SAe="3.21.0",IAe="3.21.0",CAe="3.21.0",Mh={tfjs:bAe,"tfjs-core":vAe,"tfjs-data":wAe,"tfjs-layers":kAe,"tfjs-converter":SAe,"tfjs-backend-webgl":IAe,"tfjs-backend-wasm":CAe};var CT=` 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 TT=` 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]; } `,NT=` 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; } `,ET=` 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); } `,RT=` 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; } `,_T=` 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 ub=(e,t,n)=>{let s=new RegExp("\\b"+t+" \\w+ (\\w+)","ig");e.replace(s,(r,a)=>(n[a]=0,r))},cb=class{constructor(t,n,s){de(this,"uniform",{});de(this,"attribute",{});de(this,"gl");de(this,"id");de(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:(ee(`filter: gl compile failed: ${this.gl.getShaderInfoLog(s)||"unknown"}`),null)):(ee("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){ee("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)){ee(`filter: gl link failed: ${this.gl.getProgramInfoLog(this.id)||"unknown"}`);return}this.gl.useProgram(this.id),ub(n,"attribute",this.attribute);for(let o in this.attribute)this.attribute[o]=this.gl.getAttribLocation(this.id,o);ub(n,"uniform",this.uniform),ub(s,"uniform",this.uniform);for(let o in this.uniform)this.uniform[o]=this.gl.getUniformLocation(this.id,o)}}};function DT(){let e=0,t=null,n=!1,s=-1,r=[null,null],a=[],o=null,i=null,l=vr(100,100),u={},c={INTERMEDIATE:1},p=l.getContext("webgl");if(!p){ee("filter: cannot get webgl context");return}this.gl=p;function d(x,A){if(!(x===l.width&&A===l.height)){if(l.width=x,l.height=A,!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=p.createBuffer(),p.bindBuffer(p.ARRAY_BUFFER,o),p.bufferData(p.ARRAY_BUFFER,b,p.STATIC_DRAW),p.pixelStorei(p.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0)}p.viewport(0,0,l.width,l.height),r=[null,null]}}function h(x,A){let b=p.createFramebuffer();p.bindFramebuffer(p.FRAMEBUFFER,b);let w=p.createRenderbuffer();p.bindRenderbuffer(p.RENDERBUFFER,w);let k=p.createTexture();return p.bindTexture(p.TEXTURE_2D,k),p.texImage2D(p.TEXTURE_2D,0,p.RGBA,x,A,0,p.RGBA,p.UNSIGNED_BYTE,null),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.LINEAR),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.LINEAR),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE),p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_2D,k,0),p.bindTexture(p.TEXTURE_2D,null),p.bindFramebuffer(p.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 A=null,b=null,w=!1;e===0?A=t:A=f(s).texture||null,e++,n&&!(x&c.INTERMEDIATE)?(b=null,w=e%2===0):(s=(s+1)%2,b=f(s).fbo||null),p.bindTexture(p.TEXTURE_2D,A),p.bindFramebuffer(p.FRAMEBUFFER,b),p.uniform1f(i.uniform.flipY,w?-1:1),p.drawArrays(p.TRIANGLES,0,6)}function g(x){if(u[x])return i=u[x],p.useProgram((i?i.id:null)||null),i;if(i=new cb(p,CT,x),!i)return ee("filter: could not get webgl program"),null;let A=Float32Array.BYTES_PER_ELEMENT,b=4*A;return p.enableVertexAttribArray(i.attribute.pos),p.vertexAttribPointer(i.attribute.pos,2,p.FLOAT,!1,b,0*A),p.enableVertexAttribArray(i.attribute.uv),p.vertexAttribPointer(i.attribute.uv,2,p.FLOAT,!1,b,2*A),u[x]=i,i}let y={colorMatrix:x=>{let A=new Float32Array(x);A[4]/=255,A[9]/=255,A[14]/=255,A[19]/=255;let b=A[18]===1&&A[3]===0&&A[8]===0&&A[13]===0&&A[15]===0&&A[16]===0&&A[17]===0&&A[19]===0?NT:TT,w=g(b);!w||(p.uniform1fv(w.uniform.m,A),m())},brightness:x=>{let A=(x||0)+1;y.colorMatrix([A,0,0,0,0,0,A,0,0,0,0,0,A,0,0,0,0,0,1,0])},saturation:x=>{let A=(x||0)*2/3+1,b=(A-1)*-.5;y.colorMatrix([A,b,b,0,0,b,A,b,0,0,b,b,A,0,0,0,0,0,1,0])},desaturate:()=>{y.saturation(-1)},contrast:x=>{let A=(x||0)+1,b=-128*(A-1);y.colorMatrix([A,0,0,0,b,0,A,0,0,b,0,0,A,0,b,0,0,0,1,0])},negative:()=>{y.contrast(-2)},hue:x=>{x=(x||0)/180*Math.PI;let A=Math.cos(x),b=Math.sin(x),w=.213,k=.715,C=.072;y.colorMatrix([w+A*(1-w)+b*-w,k+A*-k+b*-k,C+A*-C+b*(1-C),0,0,w+A*-w+b*.143,k+A*(1-k)+b*.14,C+A*-C+b*-.283,0,0,w+A*-w+b*-(1-w),k+A*-k+b*k,C+A*(1-C)+b*C,0,0,0,0,0,1,0])},desaturateLuminance:()=>{y.colorMatrix([.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,0,0,0,1,0])},sepia:()=>{y.colorMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0])},brownie:()=>{y.colorMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0])},vintagePinhole:()=>{y.colorMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0])},kodachrome:()=>{y.colorMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0])},technicolor:()=>{y.colorMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0])},polaroid:()=>{y.colorMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0])},shiftToBGR:()=>{y.colorMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0])},convolution:x=>{let A=new Float32Array(x),b=1/l.width,w=1/l.height,k=g(_T);!k||(p.uniform1fv(k.uniform.m,A),p.uniform2f(k.uniform.px,b,w),m())},detectEdges:()=>{y.convolution.call(this,[0,1,0,1,-4,1,0,1,0])},sobelX:()=>{y.convolution.call(this,[-1,0,1,-2,0,2,-1,0,1])},sobelY:()=>{y.convolution.call(this,[-1,-2,-1,0,0,0,1,2,1])},sharpen:x=>{let A=x||1;y.convolution.call(this,[0,-1*A,0,-1*A,1+4*A,-1*A,0,-1*A,0])},emboss:x=>{let A=x||1;y.convolution.call(this,[-2*A,-1*A,0,-1*A,1,1*A,0,1*A,2*A])},blur:x=>{let A=x/7/l.width,b=x/7/l.height,w=g(RT);!w||(p.uniform2f(w.uniform.px,0,b),m(c.INTERMEDIATE),p.uniform2f(w.uniform.px,A,0),m())},pixelate:x=>{let A=x/l.width,b=x/l.height,w=g(ET);!w||(p.uniform2f(w.uniform.size,A,b),m())}};this.add=function(x){let A=Array.prototype.slice.call(arguments,1),b=y[x];a.push({func:b,args:A})},this.reset=function(){a=[]},this.get=function(){return a},this.apply=function(x){d(x.width,x.height),e=0,t||(t=p.createTexture()),p.bindTexture(p.TEXTURE_2D,t),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.NEAREST),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.NEAREST),p.texImage2D(p.TEXTURE_2D,0,p.RGBA,p.RGBA,p.UNSIGNED_BYTE,x);for(let A=0;Ah.data())),o=.99*Math.max(a[0][0],a[1][0],a[2][0]),i=[ye(n[0],s[0]),ye(n[1],s[1]),ye(n[2],s[2])],l=[ye(r[0],s[0]),ye(r[1],s[1]),ye(r[2],s[2])],u=[ge(o,l[0]),ge(o,l[1]),ge(o,l[2])],c=[M(i[0],u[0]),M(i[1],u[1]),M(i[2],u[2])],p=ln([c[0],c[1],c[2]],2),d=W(p,[1,t.shape[0],t.shape[1],3]);return Y([...n,...s,...r,...i,...l,...u,...c,p,t]),d}var b2=3840,_n=null,Dn=null,pd=null,Nt,sr={inputSum:0,cacheDiff:1,sumMethod:0,inputTensor:void 0};function db(){sr.inputSum=0,sr.cacheDiff=1,sr.sumMethod=0,sr.inputTensor=void 0}function vr(e,t){let n;if(pe.browser)if(pe.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 pe.Canvas!="undefined"?n=new pe.Canvas(e,t):typeof globalThis.Canvas!="undefined"&&(n=new globalThis.Canvas(e,t));return n}function v2(e,t){let n=t||vr(e.width,e.height);return n.getContext("2d").drawImage(e,0,0),n}async function w2(e,t,n=!0){var d,h;if(!e)return t.debug&&ee("input error: input is missing"),{tensor:null,canvas:null};if(!(e instanceof st)&&!(typeof Image!="undefined"&&e instanceof Image)&&!(typeof pe.Canvas!="undefined"&&e instanceof pe.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 st){let f=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)f=Ft(e,0);else if(e.shape[2]===4){let m=fi(e,[0,0,0],[-1,-1,3]);f=Ft(m,0),Y(m)}}else e.shape.length===4&&(e.shape[3]===3?f=Hn(e):e.shape[3]===4&&(f=oo(e,[0,0,0,0],[-1,-1,-1,3])));if(f==null||f.shape.length!==4||f.shape[0]!==1||f.shape[3]!==3)throw new Error(`input error: attempted to use tensor with unrecognized shape: ${e.shape.toString()}`);if(f.dtype==="int32"){let m=me(f,"float32");Y(f),f=m}return{tensor:f,canvas:t.filter.return?Dn:null}}if(typeof e.readyState!="undefined"&&e.readyState<=2)return t.debug&&ee("input stream is not ready"),{tensor:null,canvas:_n};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&&ee("cannot determine input dimensions"),{tensor:null,canvas:_n};let a=s,o=r;if(a>b2&&(a=b2,o=Math.trunc(a*r/s)),o>b2&&(o=b2,a=Math.trunc(o*s/r)),(((d=t.filter)==null?void 0:d.width)||0)>0?a=t.filter.width:(((h=t.filter)==null?void 0:h.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");(!_n||_n.width!==a||_n.height!==o)&&(_n=vr(a,o));let i=_n.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,_n.width,_n.height),i.setTransform(1,0,0,1,0,0)):i.drawImage(e,0,0,s,r,0,0,_n.width,_n.height),(!Dn||_n.width!==Dn.width||_n.height!==Dn.height)&&(Dn=vr(_n.width,_n.height)),t.filter.enabled&&pe.webgl.supported?(Nt||(Nt=pe.browser?new DT:null),pe.filter=!!Nt,Nt!=null&&Nt.add?(Nt.reset(),t.filter.brightness!==0&&Nt.add("brightness",t.filter.brightness),t.filter.contrast!==0&&Nt.add("contrast",t.filter.contrast),t.filter.sharpness!==0&&Nt.add("sharpen",t.filter.sharpness),t.filter.blur!==0&&Nt.add("blur",t.filter.blur),t.filter.saturation!==0&&Nt.add("saturation",t.filter.saturation),t.filter.hue!==0&&Nt.add("hue",t.filter.hue),t.filter.negative&&Nt.add("negative"),t.filter.sepia&&Nt.add("sepia"),t.filter.vintage&&Nt.add("brownie"),t.filter.sepia&&Nt.add("sepia"),t.filter.kodachrome&&Nt.add("kodachrome"),t.filter.technicolor&&Nt.add("technicolor"),t.filter.polaroid&&Nt.add("polaroid"),t.filter.pixelate!==0&&Nt.add("pixelate",t.filter.pixelate),Nt.get()>0?Dn=Nt.apply(_n):Dn=Nt.draw(_n)):(t.debug&&ee("input process error: cannot initialize filters"),pe.webgl.supported=!1,t.filter.enabled=!1,v2(_n,Dn))):(v2(_n,Dn),Nt&&(Nt=null),pe.filter=!!Nt),!n)return{tensor:null,canvas:Dn};if(!Dn)throw new Error("canvas error: cannot create output");let l,u=3;if(typeof ImageData!="undefined"&&e instanceof ImageData||e.data&&e.width&&e.height)if(pe.browser&&ra)l=ra?ra.fromPixels(e):null;else{u=e.data.length/e.height/e.width;let f=new Uint8Array(e.data.buffer);l=Ue(f,[e.height,e.width,u],"int32")}else if((!pd||Dn.width!==pd.width||Dn.height!==pd.height)&&(pd=vr(Dn.width,Dn.height)),ra&&pe.browser)t.backend==="webgl"||t.backend==="humangl"||t.backend==="webgpu"?l=ra.fromPixels(Dn):(pd=v2(Dn),l=ra.fromPixels(pd));else{let g=v2(Dn).getContext("2d").getImageData(0,0,a,o);u=g.data.length/a/o;let y=new Uint8Array(g.data.buffer);l=Ue(y,[a,o,u])}if(u===4){let f=fi(l,[0,0,0],[-1,-1,3]);Y(l),l=f}if(!l)throw new Error("input error: cannot create tensor");let c=me(l,"float32"),p=t.filter.equalization?await x2(c):Ft(c,0);return Y([l,c]),{tensor:p,canvas:t.filter.return?Dn:null}}async function $T(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(!sr.inputTensor)sr.inputTensor=Hn(t);else if(sr.inputTensor.shape[1]!==t.shape[1]||sr.inputTensor.shape[2]!==t.shape[2])Y(sr.inputTensor),sr.inputTensor=Hn(t);else{let s={};s.diff=ye(t,sr.inputTensor),s.squared=M(s.diff,s.diff),s.sum=ve(s.squared);let a=(await s.sum.data())[0]/(t.shape[1]||1)/(t.shape[2]||1)/255/3;Y([sr.inputTensor,s.diff,s.squared,s.sum]),sr.inputTensor=Hn(t),n=a<=(e.cacheSensitivity||0)}return n}async function PT(e,t,n){let s={};if(!t||!n||t.shape.length!==4||t.shape.length!==n.shape.length)return e.debug||ee("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||ee("input tensors must be of shape [1, height, width, 3]:",t.shape,n.shape),0;s.input1=Hn(t),s.input2=t.shape[1]!==n.shape[1]||t.shape[2]!==n.shape[2]?ke.resizeBilinear(n,[t.shape[1],t.shape[2]]):Hn(n),s.diff=ye(s.input1,s.input2),s.squared=M(s.diff,s.diff),s.sum=ve(s.squared);let a=(await s.sum.data())[0]/(t.shape[1]||1)/(t.shape[2]||1)/255/3;return Y([s.input1,s.input2,s.diff,s.squared,s.sum]),a}var zh=class{constructor(){de(this,"browser");de(this,"node");de(this,"worker");de(this,"platform","");de(this,"agent","");de(this,"backends",[]);de(this,"initial");de(this,"filter");de(this,"tfjs");de(this,"offscreen");de(this,"perfadd",!1);de(this,"tensorflow",{version:void 0,gpu:void 0});de(this,"wasm",{supported:void 0,backend:void 0,simd:void 0,multithread:void 0});de(this,"webgl",{supported:void 0,backend:void 0,version:void 0,renderer:void 0});de(this,"webgpu",{supported:void 0,backend:void 0,adapter:void 0});de(this,"cpu",{model:void 0,flags:[]});de(this,"kernels",[]);de(this,"Canvas");de(this,"Image");de(this,"ImageData");if(this.browser=typeof navigator!="undefined",this.node=typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined",this.tfjs={version:Mh["tfjs-core"]},this.offscreen=typeof OffscreenCanvas!="undefined",this.initial=!0,this.worker=this.browser&&this.offscreen?typeof WorkerGlobalScope!="undefined":void 0,typeof navigator!="undefined"){let t=navigator.userAgent.match(/\(([^()]+)\)/g);if(t!=null&&t[0]){let n=t[0].match(/\(([^()]+)\)/g);this.platform=n!=null&&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(Jt().registryFactory),this.tensorflow={version:Bs().binding?Bs().binding.TF_Version:void 0,gpu:Bs().binding?Bs().binding.isUsingGpuDevice():void 0},this.wasm.supported=typeof WebAssembly!="undefined",this.wasm.backend=this.backends.includes("wasm"),this.wasm.supported&&this.wasm.backend&&cn()==="wasm"&&(this.wasm.simd=U().get("WASM_HAS_SIMD_SUPPORT"),this.wasm.multithread=U().get("WASM_HAS_MULTITHREAD_SUPPORT"));let t=vr(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&&(cn()==="webgl"||cn()==="humangl")){let s=Bs().gpgpu!=="undefined"?await Bs().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{if(this.webgpu.supported){let s=await navigator.gpu.requestAdapter();this.webgpu.adapter=s?s.name:void 0}}catch(s){this.webgpu.supported=!1}try{this.kernels=ea(cn()).map(s=>s.kernelName.toLowerCase())}catch(s){}}updateCPU(){let t={model:"",flags:[]};this.node&&this.platform.startsWith("linux"),this.cpu?this.cpu=t:Object.defineProperty(this,"cpu",{value:t})}},pe=new zh;var S2=class{constructor(){de(this,"config");de(this,"element");de(this,"stream");de(this,"start",async t=>{if(t!=null&&t.debug&&(this.config.debug=t==null?void 0:t.debug),t!=null&&t.crop&&(this.config.crop=t==null?void 0:t.crop),t!=null&&t.mode&&(this.config.mode=t==null?void 0:t.mode),t!=null&&t.width&&(this.config.width=t==null?void 0:t.width),t!=null&&t.height&&(this.config.height=t==null?void 0:t.height),t!=null&&t.element)if(typeof t.element=="string"){let r=document.getElementById(t.element);if(r&&r instanceof HTMLVideoElement)this.element=r;else{this.config.debug&&ee("webcam","cannot get dom element",t.element);return}}else if(t.element instanceof HTMLVideoElement)this.element=t.element;else{this.config.debug&&ee("webcam","unknown dom element",t.element);return}else this.element=document.createElement("video");let n={audio:!1,video:{facingMode:this.config.mode==="front"?"user":"environment",resizeMode:this.config.crop?"crop-and-scale":"none",width:{ideal:this.config.width>0?this.config.width:window.innerWidth},height:{ideal:this.config.height>0?this.config.height:window.innerHeight}}};if(this.element.addEventListener("play",()=>{this.config.debug&&ee("webcam","play")}),this.element.addEventListener("pause",()=>{this.config.debug&&ee("webcam","pause")}),this.element.addEventListener("click",async()=>{!this.element||!this.stream||(this.element.paused?await this.element.play():this.element.pause())}),!(navigator!=null&&navigator.mediaDevices)){this.config.debug&&ee("webcam","no devices");return}try{this.stream=await navigator.mediaDevices.getUserMedia(n)}catch(r){ee("webcam",r);return}if(!this.stream){this.config.debug&&ee("webcam","no stream");return}this.element.srcObject=this.stream,await new Promise(r=>{this.element?this.element.onloadeddata=()=>r(!0):r(!1)}),await this.element.play(),this.config.debug&&ee("webcam",{width:this.width,height:this.height,label:this.label,stream:this.stream,track:this.track,settings:this.settings,constraints:this.constraints,capabilities:this.capabilities})});de(this,"pause",()=>{this.element&&this.element.pause()});de(this,"play",async()=>{this.element&&await this.element.play()});de(this,"stop",()=>{this.config.debug&&ee("webcam","stop"),this.track&&this.track.stop()});this.config={element:void 0,debug:!0,mode:"front",crop:!1,width:0,height:0}}get track(){if(!!this.stream)return this.stream.getVideoTracks()[0]}get capabilities(){if(!!this.track)return this.track.getCapabilities?this.track.getCapabilities():void 0}get constraints(){if(!!this.track)return this.track.getConstraints?this.track.getConstraints():void 0}get settings(){if(!this.stream)return;let t=this.stream.getVideoTracks()[0];return t.getSettings?t.getSettings():void 0}get label(){return this.track?this.track.label:""}get paused(){var t;return((t=this.element)==null?void 0:t.paused)||!1}get width(){var t;return((t=this.element)==null?void 0:t.videoWidth)||0}get height(){var t;return((t=this.element)==null?void 0:t.videoHeight)||0}};var pb={};fa(pb,{age:()=>VAe,"anti-spoofing":()=>v5e,antispoof:()=>RAe,blazeface:()=>_Ae,"blazeface-back":()=>UAe,"blazeface-front":()=>GAe,"blazepose-detect":()=>b5e,"blazepose-detector2d":()=>HAe,"blazepose-detector3d":()=>jAe,"blazepose-full":()=>qAe,"blazepose-heavy":()=>XAe,"blazepose-lite":()=>KAe,default:()=>P5e,efficientpose:()=>ZAe,"efficientpose-i-lite":()=>w5e,"efficientpose-ii-lite":()=>k5e,"efficientpose-iv":()=>S5e,emotion:()=>DAe,faceboxes:()=>YAe,facemesh:()=>$Ae,"facemesh-attention":()=>QAe,"facemesh-attention-alt":()=>JAe,"facemesh-detection-full":()=>e5e,"facemesh-detection-short":()=>t5e,"facemesh-orig":()=>n5e,faceres:()=>PAe,"faceres-deep":()=>s5e,gear:()=>r5e,gender:()=>o5e,"gender-ssrnet-imdb":()=>a5e,handdetect:()=>i5e,"handlandmark-full":()=>FAe,"handlandmark-lite":()=>l5e,"handlandmark-sparse":()=>u5e,handskeleton:()=>c5e,handtrack:()=>OAe,"insightface-efficientnet-b0":()=>I5e,"insightface-ghostnet-strides1":()=>C5e,"insightface-ghostnet-strides2":()=>T5e,"insightface-mobilenet-emore":()=>N5e,"insightface-mobilenet-swish":()=>E5e,iris:()=>MAe,liveness:()=>zAe,"mb3-centernet":()=>LAe,meet:()=>d5e,mobileface:()=>p5e,mobilefacenet:()=>h5e,models:()=>BAe,"movenet-lightning":()=>WAe,"movenet-multipose":()=>f5e,"movenet-thunder":()=>m5e,nanodet:()=>g5e,"nanodet-e":()=>R5e,"nanodet-g":()=>_5e,"nanodet-m":()=>D5e,"nanodet-t":()=>$5e,posenet:()=>y5e,rvm:()=>A5e,selfie:()=>x5e});var RAe=853098,_Ae=538928,DAe=820516,$Ae=1477958,PAe=6978814,FAe=5431368,OAe=2964837,MAe=2599092,zAe=592976,LAe=4030290,BAe=0,WAe=4650216,VAe=161240,UAe=538928,GAe=402048,HAe=7499400,jAe=5928856,qAe=6338290,XAe=27501554,KAe=2725490,ZAe=5651240,YAe=2013002,JAe=2387598,QAe=2382414,e5e=1026192,t5e=201268,n5e=2955780,s5e=13957620,r5e=1498916,a5e=161236,o5e=201808,i5e=3515612,l5e=2023432,u5e=5286322,c5e=5502280,d5e=372228,p5e=2183192,h5e=5171976,f5e=9448838,m5e=12477112,g5e=7574558,y5e=5032780,A5e=3739355,x5e=212886,b5e=5928804,v5e=853098,w5e=2269064,k5e=5651240,S5e=25643252,I5e=13013224,C5e=8093408,T5e=8049584,N5e=6938536,E5e=12168584,R5e=12319156,_5e=7574558,D5e=1887474,$5e=5294216,P5e={antispoof:RAe,blazeface:_Ae,emotion:DAe,facemesh:$Ae,faceres:PAe,"handlandmark-full":FAe,handtrack:OAe,iris:MAe,liveness:zAe,"mb3-centernet":LAe,models:BAe,"movenet-lightning":WAe,age:VAe,"blazeface-back":UAe,"blazeface-front":GAe,"blazepose-detector2d":HAe,"blazepose-detector3d":jAe,"blazepose-full":qAe,"blazepose-heavy":XAe,"blazepose-lite":KAe,efficientpose:ZAe,faceboxes:YAe,"facemesh-attention-alt":JAe,"facemesh-attention":QAe,"facemesh-detection-full":e5e,"facemesh-detection-short":t5e,"facemesh-orig":n5e,"faceres-deep":s5e,gear:r5e,"gender-ssrnet-imdb":a5e,gender:o5e,handdetect:i5e,"handlandmark-lite":l5e,"handlandmark-sparse":u5e,handskeleton:c5e,meet:d5e,mobileface:p5e,mobilefacenet:h5e,"movenet-multipose":f5e,"movenet-thunder":m5e,nanodet:g5e,posenet:y5e,rvm:A5e,selfie:x5e,"blazepose-detect":b5e,"anti-spoofing":v5e,"efficientpose-i-lite":w5e,"efficientpose-ii-lite":k5e,"efficientpose-iv":S5e,"insightface-efficientnet-b0":I5e,"insightface-ghostnet-strides1":C5e,"insightface-ghostnet-strides2":T5e,"insightface-mobilenet-emore":N5e,"insightface-mobilenet-swish":E5e,"nanodet-e":R5e,"nanodet-g":_5e,"nanodet-m":D5e,"nanodet-t":$5e};var ps={cacheModels:!0,cacheSupported:!0,verbose:!0,debug:!1,modelBasePath:""},wr={};async function F5e(e,t){return ps.debug&&ee("load model fetch:",e,t),fetch(e,t)}function FT(e){ps.cacheModels=e.cacheModels,ps.verbose=e.debug,ps.modelBasePath=e.modelBasePath}async function Me(e){var u,c,p,d;let t=uv(ps.modelBasePath,e||"");t.toLowerCase().endsWith(".json")||(t+=".json");let n=t.includes("/")?t.split("/"):t.split("\\"),s=n[n.length-1].replace(".json",""),r="indexeddb://"+s;wr[s]={name:s,sizeFromManifest:0,sizeLoadedWeights:0,sizeDesired:pb[s],inCache:!1},ps.cacheSupported=typeof indexedDB!="undefined";let a={};try{a=ps.cacheSupported&&ps.cacheModels?await On.listModels():{}}catch(h){ps.cacheSupported=!1}wr[s].inCache=ps.cacheSupported&&ps.cacheModels&&Object.keys(a).includes(r);let o=typeof fetch=="undefined"?{}:{fetchFunc:(h,f)=>F5e(h,f)},i=new Ch(wr[s].inCache?r:t,o),l=!1;try{i.findIOHandler(),ps.debug&&ee("model load handler:",i.handler)}catch(h){ee("error finding model i/o handler:",t,h)}try{let h=await((u=i.handler)==null?void 0:u.load())||null;wr[s].sizeFromManifest=((c=h==null?void 0:h.weightData)==null?void 0:c.byteLength)||0,h?i.loadSync(h):i=await xx(wr[s].inCache?r:t,o),wr[s].sizeLoadedWeights=((d=(p=i.artifacts)==null?void 0:p.weightData)==null?void 0:d.byteLength)||0,ps.verbose&&ee("load:",{model:s,url:i.modelUrl,bytes:wr[s].sizeLoadedWeights}),l=!0}catch(h){ee("error loading model:",t,h)}if(l&&ps.cacheModels&&ps.cacheSupported&&!wr[s].inCache)try{let h=await i.save(r);ps.debug&&ee("model saved:",r,h)}catch(h){ee("error saving model:",t,h)}return i}var hb="2.11.1";var kd={};fa(kd,{Models:()=>Xh,getModelStats:()=>E4,load:()=>R4,reset:()=>r1,validate:()=>o1,validateModel:()=>a1});var wn,I2=[],fb=Number.MAX_SAFE_INTEGER,OT=0,MT=0;async function zT(e){var t;return pe.initial&&(wn=null),wn?e.debug&&ee("cached model:",wn.modelUrl):wn=await Me((t=e.face.antispoof)==null?void 0:t.modelPath),wn}async function mb(e,t,n,s){var o,i;if(!wn||!(wn!=null&&wn.executor))return 0;let r=(((o=t.face.antispoof)==null?void 0:o.skipTime)||0)>ie()-MT,a=fb<(((i=t.face.antispoof)==null?void 0:i.skipFrames)||0);return t.skipAllowed&&r&&a&&OT===s&&I2[n]?(fb++,I2[n]):(fb=0,new Promise(async l=>{let u=ke.resizeBilinear(e,[wn!=null&&wn.inputs[0].shape?wn.inputs[0].shape[2]:0,wn!=null&&wn.inputs[0].shape?wn.inputs[0].shape[1]:0],!1),c=wn==null?void 0:wn.execute(u),p=(await c.data())[0];I2[n]=Math.round(100*p)/100,OT=s,MT=ie(),Y([u,c]),l(I2[n])}))}var kr={silhouette:[10,338,297,332,284,251,389,356,454,323,361,288,397,365,379,378,400,377,152,148,176,149,150,136,172,58,132,93,234,127,162,21,54,103,67,109],lipsUpperOuter:[185,40,39,37,0,267,269,270,409],lipsLowerOuter:[61,146,91,181,84,17,314,405,321,375,291],lipsUpperInner:[191,80,81,82,13,312,311,310,415],lipsLowerInner:[78,95,88,178,87,14,317,402,318,324,308],lipsLowerSemiOuter:[76,77,90,180,85,16,315,404,320,307,306],lipsUpperSemiOuter:[184,74,73,72,11,302,303,304,408],lipsLowerSemiInner:[62,96,89,179,86,15,316,403,319,325,292],lipsUpperSemiInner:[183,42,41,38,12,268,271,272,407],rightEyeUpper0:[246,161,160,159,158,157,173],rightEyeLower0:[33,7,163,144,145,153,154,155,133],rightEyeUpper1:[247,30,29,27,28,56,190],rightEyeLower1:[130,25,110,24,23,22,26,112,243],rightEyeUpper2:[113,225,224,223,222,221,189],rightEyeLower2:[226,31,228,229,230,231,232,233,244],rightEyeLower3:[143,111,117,118,119,120,121,128,245],rightEyebrowUpper:[156,70,63,105,66,107,55,193],rightEyebrowLower:[35,124,46,53,52,65],rightEyeIris:[473,474,475,476,477],leftEyeUpper0:[466,388,387,386,385,384,398],leftEyeLower0:[263,249,390,373,374,380,381,382,362],leftEyeUpper1:[467,260,259,257,258,286,414],leftEyeLower1:[359,255,339,254,253,252,256,341,463],leftEyeUpper2:[342,445,444,443,442,441,413],leftEyeLower2:[446,261,448,449,450,451,452,453,464],leftEyeLower3:[372,340,346,347,348,349,350,357,465],leftEyebrowUpper:[383,300,293,334,296,336,285,417],leftEyebrowLower:[265,353,276,283,282,295],leftEyeIris:[468,469,470,471,472],midwayBetweenEyes:[168],noseTip:[1],noseBottom:[2],noseRightCorner:[98],noseLeftCorner:[327],rightCheek:[205],leftCheek:[425]},gb={count:468,mouth:13,symmetryLine:[13,kr.midwayBetweenEyes[0]]},mu={leftEye:0,rightEye:1,nose:2,mouth:3,leftEar:4,rightEar:5,symmetryLine:[3,2]},yb=[{key:"EyeUpper0",indices:[9,10,11,12,13,14,15]},{key:"EyeUpper1",indices:[25,26,27,28,29,30,31]},{key:"EyeUpper2",indices:[41,42,43,44,45,46,47]},{key:"EyeLower0",indices:[0,1,2,3,4,5,6,7,8]},{key:"EyeLower1",indices:[16,17,18,19,20,21,22,23,24]},{key:"EyeLower2",indices:[32,33,34,35,36,37,38,39,40]},{key:"EyeLower3",indices:[54,55,56,57,58,59,60,61,62]},{key:"EyebrowUpper",indices:[63,64,65,66,67,68,69,70]},{key:"EyebrowLower",indices:[48,49,50,51,52,53]}],Lh=[[.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]],gu=[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 z5e=[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],L5e=[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],B5e=[33,133,362,263,1,78,308],H8e=z5e.map(e=>Lh[e]),j8e=L5e.map(e=>Lh[e]),q8e=B5e.map(e=>Lh[e]);function Ai(e){let t=e.map(n=>n[0]);return t.push(e[e.length-1][1]),t}var W5e=[[61,146],[146,91],[91,181],[181,84],[84,17],[17,314],[314,405],[405,321],[321,375],[375,291],[61,185],[185,40],[40,39],[39,37],[37,0],[0,267],[267,269],[269,270],[270,409],[409,291],[78,95],[95,88],[88,178],[178,87],[87,14],[14,317],[317,402],[402,318],[318,324],[324,308],[78,191],[191,80],[80,81],[81,82],[82,13],[13,312],[312,311],[311,310],[310,415],[415,308]],V5e=[[263,249],[249,390],[390,373],[373,374],[374,380],[380,381],[381,382],[382,362],[263,466],[466,388],[388,387],[387,386],[386,385],[385,384],[384,398],[398,362]],U5e=[[276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]],G5e=[[474,475],[475,476],[476,477],[477,474]],H5e=[[33,7],[7,163],[163,144],[144,145],[145,153],[153,154],[154,155],[155,133],[33,246],[246,161],[161,160],[160,159],[159,158],[158,157],[157,173],[173,133]],j5e=[[46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]],q5e=[[469,470],[470,471],[471,472],[472,469]],X5e=[[10,338],[338,297],[297,332],[332,284],[284,251],[251,389],[389,356],[356,454],[454,323],[323,361],[361,288],[288,397],[397,365],[365,379],[379,378],[378,400],[400,377],[377,152],[152,148],[148,176],[176,149],[149,150],[150,136],[136,172],[172,58],[58,132],[132,93],[93,234],[234,127],[127,162],[162,21],[21,54],[54,103],[103,67],[67,109],[109,10]],X8e={lips:Ai(W5e),leftEye:Ai(V5e),leftEyebrow:Ai(U5e),leftIris:Ai(G5e),rightEye:Ai(H5e),rightEyebrow:Ai(j5e),rightIris:Ai(q5e),faceOval:Ai(X5e)};var He={tf255:255,tf1:1,tf2:2,tf05:.5,tf127:127.5,rgb:[.2989,.587,.114]};function BT(){He.tf255=Ce(255,"float32"),He.tf1=Ce(1,"float32"),He.tf2=Ce(2,"float32"),He.tf05=Ce(.5,"float32"),He.tf127=Ce(127.5,"float32"),He.rgb=Ot([.2989,.587,.114],"float32")}var hd=e=>[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])],C2=e=>[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2,1],T2=(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],N2=(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],UT=(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}},xb=(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],o=ke.cropAndResize(t,[a],[0],n),i=ge(o,He.tf255);return Y(o),i},E2=(e,t)=>{let n=C2(e),s=hd(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}},R2=e=>{let t=C2(e),n=hd(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}},GT=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}},bb=[[1,0,0],[0,1,0],[0,0,1]],Z5e=e=>e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI)),Y5e=(e,t)=>Z5e(Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]));var WT=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]],yu=(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=WT(t[0],t[1]),o=VT(a,r),i=WT(-t[0],-t[1]);return VT(o,i)},Q5e=e=>{let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],n=[e[0][2],e[1][2]],s=[-yu(t[0],n),-yu(t[1],n)];return[t[0].concat(s[0]),t[1].concat(s[1]),[0,0,1]]},exe=(e,t)=>[yu(e,t[0]),yu(e,t[1])];function jT(e){let t=e===192?{strides:[4],anchors:[1]}:{strides:[e/16,e/8],anchors:[2,6]},n=[];for(let s=0;s[a[0]/r*(h[0]-r/2),a[1]/r*(h[1]-r/2),h[2]||0]),i=n&&n!==0&&Math.abs(n)>.2,l=i?HT(n,[0,0]):bb,u=i?o.map(h=>[...exe(h,l),h[2]]):o,c=i?Q5e(s):bb,p=C2(t),d=[yu(p,c[0]),yu(p,c[1])];return u.map(h=>[Math.trunc(h[0]+d[0]),Math.trunc(h[1]+d[1]),Math.trunc(h[2]||0)])}function XT(e,t,n,s){let r=t.landmarks.length>=gb.count?gb.symmetryLine:mu.symmetryLine,a=0,o=bb,i;if(e&&pe.kernels.includes("rotatewithoffset"))if(a=Y5e(t.landmarks[r[0]],t.landmarks[r[1]]),a&&a!==0&&Math.abs(a)>.2){let u=C2(t),c=[u[0]/n.shape[2],u[1]/n.shape[1]],p=ke.rotateWithOffset(n,a,0,c);o=HT(-a,u),i=xb(t,p,[s,s]),Y(p)}else i=xb(t,n,[s,s]);else i=xb(t,n,[s,s]);return[a,o,i]}var txe=e=>{let t=e.map(s=>s[0]),n=e.map(s=>s[1]);return[Math.min(...t)+(Math.max(...t)-Math.min(...t))/2,Math.min(...n)+(Math.max(...n)-Math.min(...n))/2]},KT=(e,t)=>{let n=txe(e),s=hd(t);return{startPoint:[n[0]-s[0]/2,n[1]-s[1]/2],endPoint:[n[0]+s[0]/2,n[1]+s[1]/2]}};var ZT=6,nxe=1.4,Wr,YT=null,xi=0,Bh=null,fd=()=>xi;async function JT(e){var t;return pe.initial&&(Wr=null),Wr?e.debug&&ee("cached model:",Wr.modelUrl):Wr=await Me((t=e.face.detector)==null?void 0:t.modelPath),xi=Wr.executor&&Wr.inputs[0].shape?Wr.inputs[0].shape[2]:256,Bh=Ce(xi,"int32"),YT=mr(jT(xi)),Wr}function sxe(e){let t={};t.boxStarts=Oe(e,[0,1],[-1,2]),t.centers=le(t.boxStarts,YT),t.boxSizes=Oe(e,[0,3],[-1,2]),t.boxSizesNormalized=ge(t.boxSizes,Bh),t.centersNormalized=ge(t.centers,Bh),t.halfBoxSize=ge(t.boxSizesNormalized,He.tf2),t.starts=ye(t.centersNormalized,t.halfBoxSize),t.ends=le(t.centersNormalized,t.halfBoxSize),t.startNormalized=M(t.starts,Bh),t.endNormalized=M(t.ends,Bh);let n=nu([t.startNormalized,t.endNormalized],1);return Object.keys(t).forEach(s=>Y(t[s])),n}async function QT(e,t){var i,l,u,c;if(!e||e.isDisposedInternal||e.shape.length!==4||e.shape[1]<1||e.shape[2]<1)return[];let n={};n.resized=ke.resizeBilinear(e,[xi,xi]),n.div=ge(n.resized,He.tf127),n.normalized=ye(n.div,He.tf05);let s=Wr==null?void 0:Wr.execute(n.normalized);if(Array.isArray(s)&&s.length>2){let p=s.sort((d,h)=>d.size-h.size);n.concat384=ut([p[0],p[2]],2),n.concat512=ut([p[1],p[3]],2),n.concat=ut([n.concat512,n.concat384],1),n.batch=Ge(n.concat,0)}else Array.isArray(s)?n.batch=Ge(s[0]):n.batch=Ge(s);Y(s),n.boxes=sxe(n.batch),n.logits=Oe(n.batch,[0,0],[-1,1]),n.sigmoid=Mn(n.logits),n.scores=Ge(n.sigmoid),n.nms=await ke.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,((u=t.face.detector)==null?void 0:u.minConfidence)||0);let r=await n.nms.array(),a=[],o=await n.scores.data();for(let p=0;p(((c=t.face.detector)==null?void 0:c.minConfidence)||0)){let h={};h.bbox=Oe(n.boxes,[r[p],0],[1,-1]),h.slice=Oe(n.batch,[r[p],ZT-1],[1,-1]),h.squeeze=Ge(h.slice),h.landmarks=W(h.squeeze,[ZT,-1]);let f=await h.bbox.data(),m={startPoint:[f[0],f[1]],endPoint:[f[2],f[3]],landmarks:await h.landmarks.array(),confidence:d},g=UT(m,[(e.shape[2]||0)/xi,(e.shape[1]||0)/xi]),y=E2(g,t.face.scale||nxe),x=R2(y);a.push(x),Object.keys(h).forEach(A=>Y(h[A]))}}return Object.keys(n).forEach(p=>Y(n[p])),a}var _2={};fa(_2,{connected:()=>kb,kpt:()=>wb});var wb=["nose","leftEyeInside","leftEye","leftEyeOutside","rightEyeInside","rightEye","rightEyeOutside","leftEar","rightEar","leftMouth","rightMouth","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftPinky","rightPinky","leftIndex","rightIndex","leftThumb","rightThumb","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle","leftHeel","rightHeel","leftFoot","rightFoot","bodyCenter","bodyTop","leftPalm","leftHand","rightPalm","rightHand"],kb={shoulders:["leftShoulder","rightShoulder"],hips:["rightHip","leftHip"],mouth:["leftMouth","rightMouth"],leftLegUpper:["leftHip","leftKnee"],leftLegLower:["leftKnee","leftAnkle"],leftFoot:["leftAnkle","leftHeel","leftFoot"],leftTorso:["leftShoulder","leftHip"],leftArmUpper:["leftShoulder","leftElbow"],leftArmLower:["leftElbow","leftWrist"],leftHand:["leftWrist","leftPalm"],leftHandPinky:["leftPalm","leftPinky"],leftHandIndex:["leftPalm","leftIndex"],leftHandThumb:["leftPalm","leftThumb"],leftEyeOutline:["leftEyeInside","leftEyeOutside"],rightLegUpper:["rightHip","rightKnee"],rightLegLower:["rightKnee","rightAnkle"],rightFoot:["rightAnkle","rightHeel","rightFoot"],rightTorso:["rightShoulder","rightHip"],rightArmUpper:["rightShoulder","rightElbow"],rightArmLower:["rightElbow","rightWrist"],rightHand:["rightWrist","rightPalm"],rightHandPinky:["rightPalm","rightPinky"],rightHandIndex:["rightPalm","rightIndex"],rightHandThumb:["rightPalm","rightThumb"],rightEyeOutline:["rightEyeInside","rightEyeOutside"]};var tN=224,rxe,axe=5,D2=[8,16,32,32,32];function nN(){let e=[],t=0;for(;tn.x)),y:Ot(e.map(n=>n.y))}}function Fa(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 sN(e,t=[1,1]){let n=[e.map(u=>u[0]),e.map(u=>u[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 $2(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]]}var oN={initial:!0},Kn={detector:null,landmarks:null},md={detector:[224,224],landmarks:[256,256]},Sb=Number.MAX_SAFE_INTEGER,ixe={landmarks:["ld_3d","activation_segmentation","activation_heatmap","world_3d","output_poseflag"],detector:[]},F2=null,Wh,bi=[[0,0],[0,0],[0,0],[0,0]],rN=0,aN=e=>1-1/(1+Math.exp(e));async function iN(e){var t;if(oN.initial&&(Kn.detector=null),!Kn.detector&&e.body.detector&&e.body.detector.modelPath){Kn.detector=await Me(e.body.detector.modelPath);let n=(t=Kn.detector)!=null&&t.executor?Object.values(Kn.detector.modelSignature.inputs):void 0;md.detector[0]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[1].size):0,md.detector[1]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[2].size):0}else e.debug&&Kn.detector&&ee("cached model:",Kn.detector.modelUrl);return nN(),Kn.detector}async function lN(e){var t;if(oN.initial&&(Kn.landmarks=null),Kn.landmarks)e.debug&&ee("cached model:",Kn.landmarks.modelUrl);else{Kn.landmarks=await Me(e.body.modelPath);let n=(t=Kn.landmarks)!=null&&t.executor?Object.values(Kn.landmarks.modelSignature.inputs):void 0;md.landmarks[0]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[1].size):0,md.landmarks[1]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[2].size):0}return Kn.landmarks}function lxe(e,t){var r,a;let n={};if(!((r=e==null?void 0:e.shape)!=null&&r[1])||!((a=e==null?void 0:e.shape)!=null&&a[2]))return e;let s;if(Wh&&(n.cropped=ke.cropAndResize(e,[Wh],[0],[e.shape[1],e.shape[2]])),e.shape[1]!==e.shape[2]){let o=[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],i=[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];bi=[[0,0],o,i,[0,0]],n.pad=tr(n.cropped||e,bi),n.resize=ke.resizeBilinear(n.pad,[t,t]),s=ge(n.resize,He.tf255)}else e.shape[1]!==t?(n.resize=ke.resizeBilinear(n.cropped||e,[t,t]),s=ge(n.resize,He.tf255)):s=ge(n.cropped||e,He.tf255);return Object.keys(n).forEach(o=>Y(n[o])),s}function uxe(e,t){for(let n of e)n.position=[Math.trunc(n.position[0]*(t[0]+bi[2][0]+bi[2][1])/t[0]-bi[2][0]),Math.trunc(n.position[1]*(t[1]+bi[1][0]+bi[1][1])/t[1]-bi[1][0]),n.position[2]],n.positionRaw=[n.position[0]/t[0],n.position[1]/t[1],2*n.position[2]/(t[0]+t[1])];if(Wh)for(let n of e)n.positionRaw=[n.positionRaw[0]+Wh[1],n.positionRaw[1]+Wh[0],n.positionRaw[2]],n.position=[Math.trunc(n.positionRaw[0]*t[0]),Math.trunc(n.positionRaw[1]*t[1]),n.positionRaw[2]];return e}function cxe(e){let t=e.find(i=>i.part==="leftPalm"),n=e.find(i=>i.part==="leftWrist"),s=e.find(i=>i.part==="leftIndex");t.position[2]=((n.position[2]||0)+(s.position[2]||0))/2;let r=e.find(i=>i.part==="rightPalm"),a=e.find(i=>i.part==="rightWrist"),o=e.find(i=>i.part==="rightIndex");r.position[2]=((a.position[2]||0)+(o.position[2]||0))/2}async function dxe(e,t,n){var f,m;if(!((f=Kn.landmarks)!=null&&f.executor))return null;let s={};[s.ld,s.segmentation,s.heatmap,s.world,s.poseflag]=(m=Kn.landmarks)==null?void 0:m.execute(e,ixe.landmarks);let r=(await s.poseflag.data())[0],a=await s.ld.data(),o=await s.world.data();Object.keys(s).forEach(g=>Y(s[g]));let i=[],l=5;for(let g=0;gg.position),p=Fa(c,[n[0],n[1]]),d={};for(let[g,y]of Object.entries(kb)){let x=[];for(let A=0;Ak.part===y[A]),w=u.find(k=>k.part===y[A+1]);b&&w&&x.push([b.position,w.position])}d[g]=x}return{id:0,score:Math.trunc(100*r)/100,box:p.box,boxRaw:p.boxRaw,keypoints:u,annotations:d}}async function Ib(e,t){let n=[e.shape[2]||0,e.shape[1]||0],s=(t.body.skipTime||0)>ie()-rN,r=Sb<(t.body.skipFrames||0);if(t.skipAllowed&&s&&r&&F2!==null)Sb++;else{let a={};a.landmarks=lxe(e,256),F2=await dxe(a.landmarks,t,n),Object.keys(a).forEach(o=>Y(a[o])),rN=ie(),Sb=0}return F2?[F2]:[]}var gd=[{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 Is,Au=0,Cb=[],cN=0,Tb=Number.MAX_SAFE_INTEGER;async function dN(e){if(pe.initial&&(Is=null),Is)e.debug&&ee("cached model:",Is.modelUrl);else{Is=await Me(e.object.modelPath);let t=Is!=null&&Is.executor?Object.values(Is.modelSignature.inputs):void 0;Au=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}return Is}async function pxe(e,t,n){if(!e)return[];let s={},r=[],a=await e.array();s.squeeze=Ge(e);let o=Ht(s.squeeze,6,1);s.stack=ln([o[1],o[0],o[3],o[2]],1),s.boxes=Ge(s.stack),s.scores=Ge(o[4]),s.classes=Ge(o[5]),Y([e,...o]),s.nms=await ke.nonMaxSuppressionAsync(s.boxes,s.scores,n.object.maxDetected,n.object.iouThreshold,n.object.minConfidence||0);let i=await s.nms.data(),l=0;for(let u of Array.from(i)){let c=Math.trunc(100*a[0][u][4])/100,p=a[0][u][5];if(Number.isNaN(p))continue;let d=gd[p].label,[h,f]=[a[0][u][0]/Au,a[0][u][1]/Au],m=[h,f,a[0][u][2]/Au-h,a[0][u][3]/Au-f],g=[Math.trunc(m[0]*t[0]),Math.trunc(m[1]*t[1]),Math.trunc(m[2]*t[0]),Math.trunc(m[3]*t[1])];r.push({id:l++,score:c,class:p,label:d,box:g,boxRaw:m})}return Object.keys(s).forEach(u=>Y(s[u])),r}async function Nb(e,t){if(!(Is!=null&&Is.executor))return[];let n=(t.object.skipTime||0)>ie()-cN,s=Tb<(t.object.skipFrames||0);return t.skipAllowed&&n&&s&&Cb.length>0?(Tb++,Cb):(Tb=0,new Promise(async r=>{let a=[e.shape[2]||0,e.shape[1]||0],o=ke.resizeBilinear(e,[Au,Au]),i=t.object.enabled?Is==null?void 0:Is.execute(o,["tower_0/detections"]):null;cN=ie(),Y(o);let l=await pxe(i,a,t);Cb=l,r(l)}))}var O2={};fa(O2,{connected:()=>Rb,kpt:()=>Eb});var Eb=["head","neck","rightShoulder","rightElbow","rightWrist","chest","leftShoulder","leftElbow","leftWrist","bodyCenter","rightHip","rightKnee","rightAnkle","leftHip","leftKnee","leftAnkle"],Rb={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var kn,hN=0,hs={id:0,keypoints:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,annotations:{}},_b=Number.MAX_SAFE_INTEGER;async function fN(e){return pe.initial&&(kn=null),kn?e.debug&&ee("cached model:",kn.modelUrl):kn=await Me(e.body.modelPath),kn}async function hxe(e,t){let[n,s]=e.shape,r=W(e,[s*n]),a=yn(r,0),o=(await a.data())[0];if(o>t){let i=Ps(r,0),l=ru(i,n),u=(await l.data())[0],c=ge(i,n),p=(await c.data())[0];return Y([r,a,i,l,c]),[u,p,o]}return Y([r,a]),[0,0,o]}async function Db(e,t){if(!(kn!=null&&kn.executor))return[];let n=(t.body.skipTime||0)>ie()-hN,s=_b<(t.body.skipFrames||0);return t.skipAllowed&&n&&s&&Object.keys(hs.keypoints).length>0?(_b++,[hs]):(_b=0,new Promise(async r=>{let a=X(()=>{if(!(kn!=null&&kn.inputs[0].shape))return null;let p=ke.resizeBilinear(e,[kn.inputs[0].shape[2],kn.inputs[0].shape[1]],!1),d=M(p,He.tf2);return ye(d,He.tf1)}),o;if(t.body.enabled&&(o=kn==null?void 0:kn.execute(a)),hN=ie(),Y(a),o){hs.keypoints.length=0;let p=Ge(o);Y(o);let d=bn(p,2);Y(p);for(let h=0;h(t.body.minConfidence||0)&&hs.keypoints.push({score:Math.round(100*g)/100,part:Eb[h],positionRaw:[f/kn.inputs[0].shape[2],m/kn.inputs[0].shape[1]],position:[Math.round(e.shape[2]*f/kn.inputs[0].shape[2]),Math.round(e.shape[1]*m/kn.inputs[0].shape[1])]})}d.forEach(h=>Y(h))}hs.score=hs.keypoints.reduce((p,d)=>d.score>p?d.score:p,0);let i=hs.keypoints.map(p=>p.position[0]),l=hs.keypoints.map(p=>p.position[1]);hs.box=[Math.min(...i),Math.min(...l),Math.max(...i)-Math.min(...i),Math.max(...l)-Math.min(...l)];let u=hs.keypoints.map(p=>p.positionRaw[0]),c=hs.keypoints.map(p=>p.positionRaw[1]);hs.boxRaw=[Math.min(...u),Math.min(...c),Math.max(...u)-Math.min(...u),Math.max(...c)-Math.min(...c)];for(let[p,d]of Object.entries(Rb)){let h=[];for(let f=0;fy.part===d[f]),g=hs.keypoints.find(y=>y.part===d[f+1]);m&&g&&m.score>(t.body.minConfidence||0)&&g.score>(t.body.minConfidence||0)&&h.push([m.position,g.position])}hs.annotations[p]=h}r([hs])}))}var fxe=["angry","disgust","fear","happy","sad","surprise","neutral"],rr,M2=[],gN=0,yN=0,$b=Number.MAX_SAFE_INTEGER;async function AN(e){var t;return pe.initial&&(rr=null),rr?e.debug&&ee("cached model:",rr.modelUrl):rr=await Me((t=e.face.emotion)==null?void 0:t.modelPath),rr}async function Pb(e,t,n,s){var o,i;if(!rr)return[];let r=$b<(((o=t.face.emotion)==null?void 0:o.skipFrames)||0),a=(((i=t.face.emotion)==null?void 0:i.skipTime)||0)>ie()-yN;return t.skipAllowed&&a&&r&&gN===s&&M2[n]&&M2[n].length>0?($b++,M2[n]):($b=0,new Promise(async l=>{var c;let u=[];if((c=t.face.emotion)!=null&&c.enabled){let p={},d=rr!=null&&rr.inputs[0].shape?rr.inputs[0].shape[2]:0;p.resize=ke.resizeBilinear(e,[d,d],!1),p.channels=M(p.resize,He.rgb),p.grayscale=ve(p.channels,3,!0),p.grayscaleSub=ye(p.grayscale,He.tf05),p.grayscaleMul=M(p.grayscaleSub,He.tf2),p.emotion=rr==null?void 0:rr.execute(p.grayscaleMul),yN=ie();let h=await p.emotion.data();for(let f=0;f(t.face.emotion.minConfidence||0)&&u.push({score:Math.min(.99,Math.trunc(100*h[f])/100),emotion:fxe[f]});u.sort((f,m)=>m.score-f.score),Object.keys(p).forEach(f=>Y(p[f]))}M2[n]=u,gN=s,l(u)}))}var Ws,vi=0,mxe=2.3,Fb=kr.leftEyeLower0,Ob=kr.rightEyeLower0,yd={leftBounds:[Fb[0],Fb[Fb.length-1]],rightBounds:[Ob[0],Ob[Ob.length-1]]},Ad={upperCenter:3,lowerCenter:4,index:71,numCoordinates:76};async function kN(e){var t,n;return pe.initial&&(Ws=null),Ws?e.debug&&ee("cached model:",Ws.modelUrl):Ws=await Me((t=e.face.iris)==null?void 0:t.modelPath),vi=(Ws==null?void 0:Ws.executor)&&((n=Ws.inputs)==null?void 0:n[0].shape)?Ws.inputs[0].shape[2]:0,vi===-1&&(vi=64),Ws}function z2(e,t,n,s){for(let r=0;r{let t=e[yd.leftBounds[0]][2],n=e[yd.rightBounds[0]][2];return t-n},bN=(e,t,n,s,r,a=!1)=>{let o=R2(E2(GT([e[n],e[s]]),mxe)),i=hd(o),l=ke.cropAndResize(t,[[o.startPoint[1]/r,o.startPoint[0]/r,o.endPoint[1]/r,o.endPoint[0]/r]],[0],[vi,vi]);if(a&&pe.kernels.includes("flipleftright")){let u=ke.flipLeftRight(l);Y(l),l=u}return{box:o,boxSize:i,crop:l}},vN=(e,t,n,s=!1)=>{let r=[];for(let a=0;a{let s=e[kr[`${n}EyeUpper0`][Ad.upperCenter]][2],r=e[kr[`${n}EyeLower0`][Ad.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 SN(e,t,n){if(!(Ws!=null&&Ws.executor))return e;let{box:s,boxSize:r,crop:a}=bN(e,t,yd.leftBounds[0],yd.leftBounds[1],n,!0),{box:o,boxSize:i,crop:l}=bN(e,t,yd.rightBounds[0],yd.rightBounds[1],n,!0),u=ut([a,l]);Y(a),Y(l);let c=Ws.execute(u);Y(u);let p=await c.data();Y(c);let d=p.slice(0,Ad.numCoordinates*3),{rawCoords:h,iris:f}=vN(d,s,r,!0),m=p.slice(Ad.numCoordinates*3),{rawCoords:g,iris:y}=vN(m,o,i,!1),x=gxe(e);Math.abs(x)<30?(z2(e,h,"left",null),z2(e,g,"right",null)):x<1?z2(e,h,"left",["EyeUpper0","EyeLower0"]):z2(e,g,"right",["EyeUpper0","EyeLower0"]);let A=wN(e,f,"left"),b=wN(e,y,"right");return e.concat(A).concat(b)}var yxe=[[61,146],[146,91],[91,181],[181,84],[84,17],[17,314],[314,405],[405,321],[321,375],[375,291],[61,185],[185,40],[40,39],[39,37],[37,0],[0,267],[267,269],[269,270],[270,409],[409,291],[78,95],[95,88],[88,178],[178,87],[87,14],[14,317],[317,402],[402,318],[318,324],[324,308],[78,191],[191,80],[80,81],[81,82],[82,13],[13,312],[312,311],[311,310],[310,415],[415,308]],Axe=[[263,249],[249,390],[390,373],[373,374],[374,380],[380,381],[381,382],[382,362],[263,466],[466,388],[388,387],[387,386],[386,385],[385,384],[384,398],[398,362]],xxe=[[276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]],bxe=[[474,475],[475,476],[476,477],[477,474]],vxe=[[33,7],[7,163],[163,144],[144,145],[145,153],[153,154],[154,155],[155,133],[33,246],[246,161],[161,160],[160,159],[159,158],[158,157],[157,173],[173,133]],wxe=[[46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]],kxe=[[469,470],[470,471],[471,472],[472,469]],Sxe=[[10,338],[338,297],[297,332],[332,284],[284,251],[251,389],[389,356],[356,454],[454,323],[323,361],[361,288],[288,397],[397,365],[365,379],[379,378],[378,400],[400,377],[377,152],[152,148],[148,176],[176,149],[149,150],[150,136],[136,172],[172,58],[58,132],[132,93],[93,234],[234,127],[127,162],[162,21],[21,54],[54,103],[103,67],[67,109],[109,10]];function wi(e){let t=e.map(n=>n[0]);return t.push(e[e.length-1][1]),t}var Ixe={lips:wi(yxe),leftEye:wi(Axe),leftEyebrow:wi(xxe),leftIris:wi(bxe),rightEye:wi(vxe),rightEyebrow:wi(wxe),rightIris:wi(kxe),faceOval:wi(Sxe)},Cxe=Object.entries(Ixe).map(([e,t])=>t.map(n=>[n,e])).flat(),bSe=new Map(Cxe),Vh=[61,146,91,181,84,17,314,405,321,375,291,185,40,39,37,0,267,269,270,409,78,95,88,178,87,14,317,402,318,324,308,191,80,81,82,13,312,311,310,415,76,77,90,180,85,16,315,404,320,307,306,184,74,73,72,11,302,303,304,408,62,96,89,179,86,15,316,403,319,325,292,183,42,41,38,12,268,271,272,407],xu=[33,7,163,144,145,153,154,155,133,246,161,160,159,158,157,173,130,25,110,24,23,22,26,112,243,247,30,29,27,28,56,190,226,31,228,229,230,231,232,233,244,113,225,224,223,222,221,189,35,124,46,53,52,65,143,111,117,118,119,120,121,128,245,156,70,63,105,66,107,55,193],bu=[263,249,390,373,374,380,381,382,362,466,388,387,386,385,384,398,359,255,339,254,253,252,256,341,463,467,260,259,257,258,286,414,446,261,448,449,450,451,452,453,464,342,445,444,443,442,441,413,265,353,276,283,282,295,372,340,346,347,348,349,350,357,465,383,300,293,334,296,336,285,417];async function TN(e,t){var a,o,i,l,u,c,p,d,h,f;let n={lips:await((o=(a=t.filter(m=>m.size===160))==null?void 0:a[0])==null?void 0:o.data()),irisL:await((l=(i=t.filter(m=>m.size===10))==null?void 0:i[0])==null?void 0:l.data()),eyeL:await((c=(u=t.filter(m=>m.size===142))==null?void 0:u[0])==null?void 0:c.data()),irisR:await((d=(p=t.filter(m=>m.size===10))==null?void 0:p[1])==null?void 0:d.data()),eyeR:await((f=(h=t.filter(m=>m.size===142))==null?void 0:h[1])==null?void 0:f.data())};for(let m of Object.values(n))if(!m)return e;let s=xu.reduce((m,g)=>m+=e[g][2],0)/xu.length;for(let m=0;mm+=e[g][2],0)/bu.length;for(let m=0;mie()-la.timestamp,s=la.skipped<(((u=t.face.detector)==null?void 0:u.skipFrames)||0);!t.skipAllowed||!n||!s||la.boxes.length===0?(la.boxes=await QT(e,t),la.timestamp=ie(),la.skipped=0):la.skipped++;let r=[],a=[],o=0,i=Uh;for(let x=0;xD.shape[D.shape.length-1]===1).data();if(k.faceScore=Math.round(100*R[0])/100,k.faceScore<(((f=t.face.detector)==null?void 0:f.minConfidence)||1)){if(A.confidence=k.faceScore,t.face.mesh.keepInvalid){k.box=T2(A,e),k.boxRaw=N2(A,e),k.score=k.boxScore,k.mesh=A.landmarks.map(D=>[(A.startPoint[0]+A.endPoint[0])/2+(A.endPoint[0]+A.startPoint[0])*D[0]/fd(),(A.startPoint[1]+A.endPoint[1])/2+(A.endPoint[1]+A.startPoint[1])*D[1]/fd()]),k.meshRaw=k.mesh.map(D=>[D[0]/(e.shape[2]||1),D[1]/(e.shape[1]||1),(D[2]||0)/i]);for(let D of Object.keys(mu))k.annotations[D]=[k.mesh[mu[D]]]}}else{let D=C.find(F=>F.shape[F.shape.length-1]===1404),E=W(D,[-1,3]),$=await E.array();Y(E),(m=t.face.attention)!=null&&m.enabled?$=await TN($,C):(g=t.face.iris)!=null&&g.enabled&&($=await SN($,k.tensor,Uh)),k.mesh=qT($,A,b,w,Uh),k.meshRaw=k.mesh.map(F=>[F[0]/(e.shape[2]||0),F[1]/(e.shape[1]||0),(F[2]||0)/i]);for(let F of Object.keys(kr))k.annotations[F]=kr[F].map(z=>k.mesh[z]);k.score=k.faceScore;let S={...KT(k.mesh,A),confidence:A.confidence,landmarks:A.landmarks};k.box=T2(S,e),k.boxRaw=N2(S,e),a.push(S)}Y(C)}else{k.box=T2(A,e),k.boxRaw=N2(A,e),k.score=k.boxScore,k.mesh=A.landmarks.map(C=>[(A.startPoint[0]+A.endPoint[0])/2+(A.endPoint[0]+A.startPoint[0])*C[0]/fd(),(A.startPoint[1]+A.endPoint[1])/2+(A.endPoint[1]+A.startPoint[1])*C[1]/fd()]),k.meshRaw=k.mesh.map(C=>[C[0]/(e.shape[2]||0),C[1]/(e.shape[1]||0),(C[2]||0)/i]);for(let C of Object.keys(mu))k.annotations[C]=[k.mesh[mu[C]]]}k.score>(((y=t.face.detector)==null?void 0:y.minConfidence)||1)?r.push(k):Y(k.tensor)}return la.boxes=a,r}async function EN(e){var t,n,s,r,a,o;return pe.initial&&(Lt=null),((t=e.face.attention)==null?void 0:t.enabled)&&(Lt==null?void 0:Lt.signature)&&Object.keys(((n=Lt==null?void 0:Lt.signature)==null?void 0:n.outputs)||{}).length<6&&(Lt=null),Lt?e.debug&&ee("cached model:",Lt.modelUrl):(s=e.face.attention)!=null&&s.enabled?Lt=await Me(e.face.attention.modelPath):Lt=await Me((r=e.face.mesh)==null?void 0:r.modelPath),Uh=Lt.executor&&((a=Lt==null?void 0:Lt.inputs)==null?void 0:a[0].shape)?(o=Lt==null?void 0:Lt.inputs)==null?void 0:o[0].shape[2]:256,Lt}var RN=gu,_N=Lh;var Zn,ki=[],DN=0,$N=0,zb=Number.MAX_SAFE_INTEGER;async function PN(e){var t;return pe.initial&&(Zn=null),Zn?e.debug&&ee("cached model:",Zn.modelUrl):Zn=await Me((t=e.face.description)==null?void 0:t.modelPath),Zn}function Lb(e){let t=e.image||e.tensor||e;if(!(Zn!=null&&Zn.inputs[0].shape))return t;let n=ke.resizeBilinear(t,[Zn.inputs[0].shape[2],Zn.inputs[0].shape[1]],!1),s=M(n,He.tf255);return Y(n),s}async function Bb(e,t,n,s){var i,l,u,c;let r={age:0,gender:"unknown",genderScore:0,descriptor:[]};if(!(Zn!=null&&Zn.executor))return r;let a=zb<(((i=t.face.description)==null?void 0:i.skipFrames)||0),o=(((l=t.face.description)==null?void 0:l.skipTime)||0)>ie()-DN;return t.skipAllowed&&a&&o&&$N===s&&((u=ki==null?void 0:ki[n])==null?void 0:u.age)>0&&((c=ki==null?void 0:ki[n])==null?void 0:c.genderScore)>0?(zb++,ki[n]):(zb=0,new Promise(async p=>{var d;if((d=t.face.description)!=null&&d.enabled){let h=Lb(e),f=Zn==null?void 0:Zn.execute(h);DN=ie(),Y(h);let g=await f.find(N=>N.shape[1]===1).data(),y=Math.trunc(200*Math.abs(g[0]-.5))/100;y>(t.face.description.minConfidence||0)&&(r.gender=g[0]<=.5?"female":"male",r.genderScore=Math.min(.99,y));let x=Ps(f.find(N=>N.shape[1]===100),1),A=(await x.data())[0];Y(x);let w=await f.find(N=>N.shape[1]===100).data();r.age=Math.round(w[A-1]>w[A+1]?10*A-100*w[A-1]:10*A+100*w[A+1])/10,(Number.isNaN(g[0])||Number.isNaN(w[0]))&&ee("faceres error:",{model:Zn,result:f});let k=f.find(N=>N.shape[1]===1024),C=k?await k.data():[];r.descriptor=Array.from(C),f.forEach(N=>Y(N))}ki[n]=r,$N=s,p(r)}))}var Sr,Vb=[],Nxe=["white","black","asian","indian","other"],Exe=[15,23,28,35.5,45.5,55.5,65],FN=0,ON=0,Ub=Number.MAX_SAFE_INTEGER;async function MN(e){var t;return pe.initial&&(Sr=null),Sr?e.debug&&ee("cached model:",Sr.modelUrl):Sr=await Me((t=e.face.gear)==null?void 0:t.modelPath),Sr}async function Gb(e,t,n,s){var o,i;if(!Sr)return{age:0,gender:"unknown",genderScore:0,race:[]};let r=Ub<(((o=t.face.gear)==null?void 0:o.skipFrames)||0),a=(((i=t.face.gear)==null?void 0:i.skipTime)||0)>ie()-ON;return t.skipAllowed&&a&&r&&FN===s&&Vb[n]?(Ub++,Vb[n]):(Ub=0,new Promise(async l=>{var y,x;if(!(Sr!=null&&Sr.inputs[0].shape))return;let u={},c=[[0,.1,.9,.9]];u.resize=ke.cropAndResize(e,c,[0],[Sr.inputs[0].shape[2],Sr.inputs[0].shape[1]]);let p={age:0,gender:"unknown",genderScore:0,race:[]};(y=t.face.gear)!=null&&y.enabled&&([u.age,u.gender,u.race]=Sr.execute(u.resize,["age_output","gender_output","race_output"]));let d=await u.gender.data();p.gender=d[0]>d[1]?"male":"female",p.genderScore=Math.round(100*(d[0]>d[1]?d[0]:d[1]))/100;let h=await u.race.data();for(let A=0;A(((x=t.face.gear)==null?void 0:x.minConfidence)||.2)&&p.race.push({score:Math.round(100*h[A])/100,race:Nxe[A]});p.race.sort((A,b)=>b.score-A.score);let m=Array.from(await u.age.data()).map((A,b)=>[Exe[b],A]).sort((A,b)=>b[1]-A[1]),g=m[0][0];for(let A=1;AY(u[A])),Vb[n]=p,FN=s,ON=ie(),l(p)}))}function L2(e){return[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])]}function Gh(e){return[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2]}function WN(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 ke.cropAndResize(t,a,[0],n)}function VN(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 B2(e,t=1.5){let n=Gh(e),s=L2(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 W2(e){let t=Gh(e),n=L2(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 Rxe(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function UN(e,t){let n=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]);return Rxe(n)}var LN=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]];function Si(e,t){let n=0;for(let s=0;s[o.x,o.y]),this.anchorsTensor=mr(this.anchors),this.inputSize=((a=(r=(s=(n=this==null?void 0:this.model)==null?void 0:n.inputs)==null?void 0:s[0])==null?void 0:r.shape)==null?void 0:a[2])||0,this.inputSizeTensor=Ot([this.inputSize,this.inputSize]),this.doubleInputSizeTensor=Ot([this.inputSize*2,this.inputSize*2])}normalizeBoxes(t){let n={};n.boxOffsets=Oe(t,[0,0],[-1,2]),n.boxSizes=Oe(t,[0,2],[-1,2]),n.div=ge(n.boxOffsets,this.inputSizeTensor),n.boxCenterPoints=le(n.div,this.anchorsTensor),n.halfBoxSizes=ge(n.boxSizes,this.doubleInputSizeTensor),n.sub=ye(n.boxCenterPoints,n.halfBoxSizes),n.startPoints=M(n.sub,this.inputSizeTensor),n.add=le(n.boxCenterPoints,n.halfBoxSizes),n.endPoints=M(n.add,this.inputSizeTensor);let s=nu([n.startPoints,n.endPoints],1);return Object.keys(n).forEach(r=>Y(n[r])),s}normalizeLandmarks(t,n){let s={};s.reshape=W(t,[-1,7,2]),s.div=ge(s.reshape,this.inputSizeTensor),s.landmarks=le(s.div,this.anchors[n]?this.anchors[n]:0);let r=M(s.landmarks,this.inputSizeTensor);return Object.keys(s).forEach(a=>Y(s[a])),r}async predict(t,n){var i;let s={};s.resize=ke.resizeBilinear(t,[this.inputSize,this.inputSize]),s.div=ge(s.resize,He.tf127),s.image=ye(s.div,He.tf1),s.batched=this.model.execute(s.image),s.predictions=Ge(s.batched),s.slice=Oe(s.predictions,[0,0],[-1,1]),s.sigmoid=Mn(s.slice),s.scores=Ge(s.sigmoid);let r=await s.scores.data();s.boxes=Oe(s.predictions,[0,1],[-1,4]),s.norm=this.normalizeBoxes(s.boxes),s.nms=await ke.nonMaxSuppressionAsync(s.norm,s.scores,3*(((i=n.hand)==null?void 0:i.maxDetected)||1),n.hand.iouThreshold,n.hand.minConfidence);let a=await s.nms.array(),o=[];for(let l of a){let u={};u.box=Oe(s.norm,[l,0],[1,-1]),u.slice=Oe(s.predictions,[l,5],[1,14]),u.norm=this.normalizeLandmarks(u.slice,l),u.palmLandmarks=W(u.norm,[-1,2]);let c=await u.box.data(),p=c.slice(0,2),d=c.slice(2,4),h=await u.palmLandmarks.array(),f={startPoint:p,endPoint:d,palmLandmarks:h,confidence:r[l]},m=VN(f,[(t.shape[2]||1)/this.inputSize,(t.shape[1]||0)/this.inputSize]);o.push(m),Object.keys(u).forEach(g=>Y(u[g]))}return Object.keys(s).forEach(l=>Y(s[l])),o}};var Pxe=5,qN=1.65,XN=[0,5,9,13,17,1,2],Fxe=0,Oxe=2,KN=0,U2=class{constructor(t,n){de(this,"handDetector");de(this,"handPoseModel");de(this,"inputSize");de(this,"storedBoxes");de(this,"skipped");de(this,"detectedHands");var s,r,a;this.handDetector=t,this.handPoseModel=n,this.inputSize=((a=(r=(s=this.handPoseModel)==null?void 0:s.inputs)==null?void 0:r[0].shape)==null?void 0:a[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=>jb([...a,1],n)),r=this.calculateLandmarksBoundingBox(s);return B2(W2(r),Pxe)}getBoxForHandLandmarks(t){let n=this.calculateLandmarksBoundingBox(t),s=B2(W2(n),qN);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=Hb(s,[0,0]),u=i.map(h=>[...jb(h,l),h[2]]),c=GN(r),p=[...Gh(n),1],d=[Si(p,c[0]),Si(p,c[1])];return u.map(h=>[Math.trunc(h[0]+d[0]),Math.trunc(h[1]+d[1]),Math.trunc(h[2])])}async estimateHands(t,n){let s=!1,r,a=(n.hand.skipTime||0)>ie()-KN,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=W(A,[-1,3]),k=await w.array();Y(A),Y(w);let C=this.transformRawCoords(k,m,c,f),N=this.getBoxForHandLandmarks(C);this.storedBoxes[l]={...N,confidence:b};let R={landmarks:C,confidence:b,boxConfidence:u.confidence,fingerConfidence:b,box:{topLeft:N.startPoint,bottomRight:N.endPoint}};i.push(R)}else this.storedBoxes[l]=null;Y(A)}else{let c=B2(W2(u),qN),p={confidence:u.confidence,boxConfidence:u.confidence,fingerConfidence:0,box:{topLeft:c.startPoint,bottomRight:c.endPoint},landmarks:[]};i.push(p)}}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 fs={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=>fs.nameMapping[e],getPoints:e=>fs.pointsMapping[e]},Ci={none:0,half:1,full:2,nameMapping:{0:"none",1:"half",2:"full"},getName:e=>Ci.nameMapping[e]},Xt={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=>Xt.nameMapping[e]},Ii=class{constructor(t){de(this,"name");de(this,"curls");de(this,"directions");de(this,"weights");de(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:Vr,index:Oa,middle:Ma,ring:vu,pinky:wu}=fs,{none:Ur,half:zxe,full:Gr}=Ci,{verticalUp:xd,verticalDown:WSe,horizontalLeft:qb,horizontalRight:Lxe,diagonalUpRight:Bxe,diagonalUpLeft:bd,diagonalDownRight:VSe,diagonalDownLeft:USe}=Xt,Ti=new Ii("thumbs up");Ti.curl(Vr,Ur,1);Ti.direction(Vr,xd,1);Ti.direction(Vr,bd,.25);Ti.direction(Vr,Bxe,.25);for(let e of[fs.index,fs.middle,fs.ring,fs.pinky])Ti.curl(e,Gr,1),Ti.direction(e,qb,1),Ti.direction(e,Lxe,1);var pn=new Ii("victory");pn.curl(Vr,zxe,.5);pn.curl(Vr,Ur,.5);pn.direction(Vr,xd,1);pn.direction(Vr,bd,1);pn.curl(Oa,Ur,1);pn.direction(Oa,xd,.75);pn.direction(Oa,bd,1);pn.curl(Ma,Ur,1);pn.direction(Ma,xd,1);pn.direction(Ma,bd,.75);pn.curl(vu,Gr,1);pn.direction(vu,xd,.2);pn.direction(vu,bd,1);pn.direction(vu,qb,.2);pn.curl(wu,Gr,1);pn.direction(wu,xd,.2);pn.direction(wu,bd,1);pn.direction(wu,qb,.2);pn.weight(Oa,2);pn.weight(Ma,2);var Ni=new Ii("point");Ni.curl(Vr,Gr,1);Ni.curl(Oa,Ur,.5);Ni.curl(Ma,Gr,.5);Ni.curl(vu,Gr,.5);Ni.curl(wu,Gr,.5);Ni.weight(Oa,2);Ni.weight(Ma,2);var Ei=new Ii("middle finger");Ei.curl(Vr,Ur,1);Ei.curl(Oa,Gr,.5);Ei.curl(Ma,Gr,.5);Ei.curl(vu,Gr,.5);Ei.curl(wu,Gr,.5);Ei.weight(Oa,2);Ei.weight(Ma,2);var vd=new Ii("open palm");vd.curl(Vr,Ur,.75);vd.curl(Oa,Ur,.75);vd.curl(Ma,Ur,.75);vd.curl(vu,Ur,.75);vd.curl(wu,Ur,.75);var ZN=[Ti,pn,Ni,Ei,vd];var Wxe=.7,ku={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 YN(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 QN(e,t){if(!e||!t)return[0,0];let n=YN(e[0],e[1],t[0],t[1]);if(e.length===2)return n;let s=YN(e[1],e[2],t[1],t[2]);return[n,s]}function JN(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 Vxe(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],u=e[2]-t[2],c=e[2]-n[2],p=t[2]-n[2],d=Math.sqrt(s*s+o*o+u*u),h=Math.sqrt(r*r+i*i+c*c),f=Math.sqrt(a*a+l*l+p*p),m=(f*f+d*d-h*h)/(2*f*d);m>1?m=1:m<-1&&(m=-1);let g=Math.acos(m);g=57.2958*g%180;let y;return g>ku.NO_CURL_START_LIMIT?y=Ci.none:g>ku.HALF_CURL_START_LIMIT?y=Ci.half:y=Ci.full,y}function eE(e,t,n,s){let r;return s===Math.abs(e)?e>0?r=Xt.horizontalLeft:r=Xt.horizontalRight:s===Math.abs(t)?t>0?r=Xt.horizontalLeft:r=Xt.horizontalRight:n>0?r=Xt.horizontalLeft:r=Xt.horizontalRight,r}function tE(e,t,n,s){let r;return s===Math.abs(e)?e<0?r=Xt.verticalDown:r=Xt.verticalUp:s===Math.abs(t)?t<0?r=Xt.verticalDown:r=Xt.verticalUp:n<0?r=Xt.verticalDown:r=Xt.verticalUp,r}function Uxe(e,t,n,s,r,a,o,i){let l,u=tE(e,t,n,s),c=eE(r,a,o,i);return u===Xt.verticalUp?c===Xt.horizontalLeft?l=Xt.diagonalUpLeft:l=Xt.diagonalUpRight:c===Xt.horizontalLeft?l=Xt.diagonalDownLeft:l=Xt.diagonalDownRight,l}function Gxe(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],u=t[1]-n[1],c=Math.max(Math.abs(r),Math.abs(a),Math.abs(o)),p=Math.max(Math.abs(i),Math.abs(l),Math.abs(u)),d=0,h=0,f=0,m=p/(c+1e-5);m>1.5?d+=ku.DISTANCE_VOTE_POWER:m>.66?h+=ku.DISTANCE_VOTE_POWER:f+=ku.DISTANCE_VOTE_POWER;let g=Math.sqrt(r*r+i*i),y=Math.sqrt(a*a+l*l),x=Math.sqrt(o*o+u*u),A=Math.max(g,y,x),b=e[0],w=e[1],k=n[0],C=n[1];A===g?(k=n[0],C=n[1]):A===x&&(b=t[0],w=t[1]);let D=QN([b,w],[k,C]),E=JN(D,ku.TOTAL_ANGLE_VOTE_POWER);d+=E[0],h+=E[1],f+=E[2];for(let S of s){let F=JN(S,ku.SINGLE_ANGLE_VOTE_POWER);d+=F[0],h+=F[1],f+=F[2]}let $;return d===Math.max(d,h,f)?$=tE(l,i,u,p):f===Math.max(h,f)?$=eE(a,r,o,c):$=Uxe(l,i,u,p,a,r,o,c),$}function nE(e){let t=[],n=[],s=[],r=[];if(!e)return{curls:s,directions:r};for(let a of fs.all){let o=fs.getPoints(a),i=[],l=[];for(let u of o){let c=e[u[0]],p=e[u[1]],d=QN(c,p),h=d[0],f=d[1];i.push(h),l.push(f)}t.push(i),n.push(l)}for(let a of fs.all){let o=a===fs.thumb?1:0,i=fs.getPoints(a),l=e[i[o][0]],u=e[i[o+1][1]],c=e[i[3][1]],p=Vxe(l,u,c),d=Gxe(l,u,c,t[a].slice(o));s[a]=p,r[a]=d}return{curls:s,directions:r}}function G2(e){if(!e||e.length===0)return null;let t=nE(e),n={};for(let s of fs.all)n[fs.getName(s)]={curl:Ci.getName(t.curls[s]),direction:Xt.getName(t.directions[s])};return n}function sE(e){let t=[];if(!e||e.length===0)return t;let n=nE(e);for(let s of ZN){let r=s.matchAgainst(n.curls,n.directions);r>=Wxe&&t.push({name:s.name,confidence:r})}return t}var rE={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]},Su,Iu,aE;async function Kb(e,t){let n=await aE.estimateHands(e,t);if(!n)return[];let s=[];for(let r=0;rn[r].landmarks[p]);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 c of o)c[0]i[2]&&(i[2]=c[0]),c[1]>i[3]&&(i[3]=c[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 u=G2(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:u})}return s}async function Zb(e){var n,s;pe.initial&&(Su=null,Iu=null),!Su||!Iu?[Su,Iu]=await Promise.all([e.hand.enabled?Me((n=e.hand.detector)==null?void 0:n.modelPath):null,e.hand.landmarks?Me((s=e.hand.skeleton)==null?void 0:s.modelPath):null]):(e.debug&&ee("cached model:",Su.modelUrl),e.debug&&ee("cached model:",Iu.modelUrl));let t=Su?new V2(Su):void 0;return t&&Iu&&(aE=new U2(t,Iu)),[Su,Iu]}var tn=[null,null],Hxe=["StatefulPartitionedCall/Postprocessor/Slice","StatefulPartitionedCall/Postprocessor/ExpandDims_1"],Ri=[[0,0],[0,0]],jxe=["hand","fist","pinch","point","face","tip","pinchtip"],iE=4,lE=1.6,qxe=512,Xxe=1.4,H2=Number.MAX_SAFE_INTEGER,Yb=0,za=[0,0],en={boxes:[],hands:[]},uE={thumb:[1,2,3,4],index:[5,6,7,8],middle:[9,10,11,12],ring:[13,14,15,16],pinky:[17,18,19,20],base:[0],palm:[0,17,13,9,5,1,0]};async function cE(e){var t;if(pe.initial&&(tn[0]=null),tn[0])e.debug&&ee("cached model:",tn[0].modelUrl);else{j2(["tensorlistreserve","enter","tensorlistfromtensor","merge","loopcond","switch","exit","tensorliststack","nextiteration","tensorlistsetitem","tensorlistgetitem","reciprocal","shape","split","where"],e),tn[0]=await Me((t=e.hand.detector)==null?void 0:t.modelPath);let n=tn[0].executor?Object.values(tn[0].modelSignature.inputs):void 0;Ri[0][0]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[1].size):0,Ri[0][1]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[2].size):0}return tn[0]}async function dE(e){var t;if(pe.initial&&(tn[1]=null),tn[1])e.debug&&ee("cached model:",tn[1].modelUrl);else{tn[1]=await Me((t=e.hand.skeleton)==null?void 0:t.modelPath);let n=tn[1].executor?Object.values(tn[1].modelSignature.inputs):void 0;Ri[1][0]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[1].size):0,Ri[1][1]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[2].size):0}return tn[1]}async function Kxe(e,t){let n=[];if(!e||!tn[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,qxe),o=Math.round(a*r/8)*8;s.resize=ke.resizeBilinear(e,[a,o]),s.cast=me(s.resize,"int32"),[s.rawScores,s.rawBoxes]=await tn[0].executeAsync(s.cast,Hxe),s.boxes=Ge(s.rawBoxes,[0,2]),s.scores=Ge(s.rawScores,[0]);let i=bn(s.scores,1);Y(i[iE]),i.splice(iE,1),s.filtered=ln(i,1),Y(i),s.max=yn(s.filtered,1),s.argmax=Ps(s.filtered,1);let l=0;s.nms=await ke.nonMaxSuppressionAsync(s.boxes,s.max,(t.hand.maxDetected||0)+1,t.hand.iouThreshold||0,t.hand.minConfidence||1);let u=await s.nms.data(),c=await s.max.data(),p=await s.argmax.data();for(let d of Array.from(u)){let h=Oe(s.boxes,d,1),f=await h.data();Y(h);let m=[f[1],f[0],f[3]-f[1],f[2]-f[0]],g=$2(m,Xxe),y=[Math.trunc(m[0]*za[0]),Math.trunc(m[1]*za[1]),Math.trunc(m[2]*za[0]),Math.trunc(m[3]*za[1])],x=c[d],A=jxe[p[d]],b={id:l++,score:x,box:y,boxRaw:g,label:A};n.push(b)}return Object.keys(s).forEach(d=>Y(s[d])),n.sort((d,h)=>h.score-d.score),n.length>(t.hand.maxDetected||1)&&(n.length=t.hand.maxDetected||1),n}async function Jb(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&&tn[1]&&n.hand.landmarks&&t.score>(n.hand.minConfidence||0)){let r={},a=[t.boxRaw[1],t.boxRaw[0],t.boxRaw[3]+t.boxRaw[1],t.boxRaw[2]+t.boxRaw[0]];r.crop=ke.cropAndResize(e,[a],[0],[Ri[1][0],Ri[1][1]],"bilinear"),r.div=ge(r.crop,He.tf255),[r.score,r.keypoints]=tn[1].execute(r.div,["Identity_1","Identity"]);let o=(await r.score.data())[0],i=(100-Math.trunc(100/(1+Math.exp(o))))/100;if(i>=(n.hand.minConfidence||0)){s.fingerScore=i,r.reshaped=W(r.keypoints,[-1,3]);let c=(await r.reshaped.array()).map(p=>[p[0]/Ri[1][1],p[1]/Ri[1][0],p[2]||0]).map(p=>[p[0]*t.boxRaw[2],p[1]*t.boxRaw[3],p[2]||0]);s.keypoints=c.map(p=>[za[0]*(p[0]+t.boxRaw[0]),za[1]*(p[1]+t.boxRaw[1]),p[2]||0]),s.landmarks=G2(s.keypoints);for(let p of Object.keys(uE))s.annotations[p]=uE[p].map(d=>s.landmarks&&s.keypoints[d]?s.keypoints[d]:null)}Object.keys(r).forEach(l=>Y(r[l]))}return s}async function Qb(e,t){var r,a;if(!((r=tn[0])!=null&&r.executor)||!((a=tn[1])!=null&&a.executor)||!tn[0].inputs[0].shape||!tn[1].inputs[0].shape)return[];za=[e.shape[2]||0,e.shape[1]||0],H2++;let n=(t.hand.skipTime||0)>ie()-Yb,s=H2<(t.hand.skipFrames||0);return t.skipAllowed&&n&&s?en.hands:new Promise(async o=>{let i=3*(t.hand.skipTime||0)>ie()-Yb,l=H2<3*(t.hand.skipFrames||0);t.skipAllowed&&en.hands.length===t.hand.maxDetected?en.hands=await Promise.all(en.boxes.map(c=>Jb(e,c,t))):t.skipAllowed&&i&&l&&en.hands.length>0?en.hands=await Promise.all(en.boxes.map(c=>Jb(e,c,t))):(en.boxes=await Kxe(e,t),Yb=ie(),en.hands=await Promise.all(en.boxes.map(c=>Jb(e,c,t))),H2=0);let u=[...en.boxes];if(en.boxes.length=0,t.cacheSensitivity>0)for(let c=0;c.05&&p.box[3]/(e.shape[1]||1)>.05&&en.hands[c].fingerScore&&en.hands[c].fingerScore>(t.hand.minConfidence||0)){let d=$2(p.box,lE),h=$2(p.boxRaw,lE);en.boxes.push({...u[c],box:d,boxRaw:h})}}for(let c=0;cie()-fE;return t.skipAllowed&&a&&r&&hE===s&&e4[n]?(mE++,e4[n]):new Promise(async l=>{var c;let u=[];if(((c=t.face.insightface)==null?void 0:c.enabled)&&(Vs==null?void 0:Vs.inputs[0].shape)){let p={};p.crop=ke.resizeBilinear(e,[Vs.inputs[0].shape[2],Vs.inputs[0].shape[1]],!1),p.data=Vs.execute(p.crop);let d=await p.data.data();u=Array.from(d),Object.keys(p).forEach(h=>Y(p[h]))}e4[n]=u,hE=s,fE=ie(),l(u)})}var $n,q2=[],n4=Number.MAX_SAFE_INTEGER,AE=0,xE=0;async function bE(e){var t;return pe.initial&&($n=null),$n?e.debug&&ee("cached model:",$n.modelUrl):$n=await Me((t=e.face.liveness)==null?void 0:t.modelPath),$n}async function s4(e,t,n,s){var o,i;if(!($n!=null&&$n.executor))return 0;let r=(((o=t.face.liveness)==null?void 0:o.skipTime)||0)>ie()-xE,a=n4<(((i=t.face.liveness)==null?void 0:i.skipFrames)||0);return t.skipAllowed&&r&&a&&AE===s&&q2[n]?(n4++,q2[n]):(n4=0,new Promise(async l=>{let u=ke.resizeBilinear(e,[$n!=null&&$n.inputs[0].shape?$n.inputs[0].shape[2]:0,$n!=null&&$n.inputs[0].shape?$n.inputs[0].shape[1]:0],!1),c=$n==null?void 0:$n.execute(u),p=(await c.data())[0];q2[n]=Math.round(100*p)/100,AE=s,xE=ie(),Y([u,c]),l(q2[n])}))}var Yn;async function r4(e){return!Yn||pe.initial?Yn=await Me(e.segmentation.modelPath):e.debug&&ee("cached model:",Yn.modelUrl),Yn}async function wE(e,t){var r;if(Yn||(Yn=await r4(t)),!(Yn!=null&&Yn.executor)||!((r=Yn==null?void 0:Yn.inputs)!=null&&r[0].shape))return null;let n={};n.resize=ke.resizeBilinear(e,[Yn.inputs[0].shape?Yn.inputs[0].shape[1]:0,Yn.inputs[0].shape?Yn.inputs[0].shape[2]:0],!1),n.norm=ge(n.resize,He.tf255),n.res=Yn.execute(n.norm),n.squeeze=Ge(n.res,0),[n.bgRaw,n.fgRaw]=bn(n.squeeze,2),n.fg=au(n.fgRaw),n.mul=M(n.fg,He.tf255),n.expand=Ft(n.mul,2),n.output=ke.resizeBilinear(n.expand,[e.shape[1],e.shape[2]]);let s;switch(t.segmentation.mode||"default"){case"default":n.input=Ge(e),n.concat=ut([n.input,n.output],-1),s=me(n.concat,"int32");break;case"alpha":s=me(n.output,"int32");break;default:s=Ue(0)}return Object.keys(n).forEach(a=>Y(n[a])),s}var Us,a4=[],SE=0,IE=0,CE=Number.MAX_SAFE_INTEGER;async function TE(e){var t;return pe.initial&&(Us=null),Us?e.debug&&ee("cached model:",Us.modelUrl):Us=await Me((t=e.face.mobilefacenet)==null?void 0:t.modelPath),Us}async function o4(e,t,n,s){var o,i;if(!(Us!=null&&Us.executor))return[];let r=CE<(((o=t.face.mobilefacenet)==null?void 0:o.skipFrames)||0),a=(((i=t.face.mobilefacenet)==null?void 0:i.skipTime)||0)>ie()-IE;return t.skipAllowed&&a&&r&&SE===s&&a4[n]?(CE++,a4[n]):new Promise(async l=>{var c;let u=[];if(((c=t.face.mobilefacenet)==null?void 0:c.enabled)&&(Us==null?void 0:Us.inputs[0].shape)){let p={};p.crop=ke.resizeBilinear(e,[Us.inputs[0].shape[2],Us.inputs[0].shape[1]],!1),p.data=Us.execute(p.crop);let d=await p.data.data();u=Array.from(d),Object.keys(p).forEach(h=>Y(p[h]))}a4[n]=u,SE=s,IE=ie(),l(u)})}var Hh={};fa(Hh,{connected:()=>K2,horizontal:()=>i4,kpt:()=>X2,relative:()=>u4,vertical:()=>l4});var X2=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],i4=[["leftEye","rightEye"],["leftEar","rightEar"],["leftShoulder","rightShoulder"],["leftElbow","rightElbow"],["leftWrist","rightWrist"],["leftHip","rightHip"],["leftKnee","rightKnee"],["leftAnkle","rightAnkle"]],l4=[["leftKnee","leftShoulder"],["rightKnee","rightShoulder"],["leftAnkle","leftKnee"],["rightAnkle","rightKnee"]],u4=[[["leftHip","rightHip"],["leftShoulder","rightShoulder"]],[["leftElbow","rightElbow"],["leftShoulder","rightShoulder"]]],K2={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var EE=.005,Gs={keypoints:[],padding:[[0,0],[0,0],[0,0],[0,0]]};function c4(e){for(let t of i4){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]u&&u.part===t[0]),r=e.keypoints.findIndex(u=>u&&u.part===t[1]),a=e.keypoints.findIndex(u=>u&&u.part===n[0]),o=e.keypoints.findIndex(u=>u&&u.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 u=e.keypoints[s];e.keypoints[s]=e.keypoints[r],e.keypoints[r]=u}}}function RE(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=tr(e,Gs.padding),n.resize=ke.resizeBilinear(n.pad,[t,t]);let s=me(n.resize,"int32");return Object.keys(n).forEach(o=>Y(n[o])),s}function DE(e,t){e.keypoints=e.keypoints.filter(s=>s==null?void 0:s.position);for(let s of e.keypoints)s.position=[s.position[0]*(t[0]+Gs.padding[2][0]+Gs.padding[2][1])/t[0]-Gs.padding[2][0],s.position[1]*(t[1]+Gs.padding[1][0]+Gs.padding[1][1])/t[1]-Gs.padding[1][0]],s.positionRaw=[s.position[0]/t[0],s.position[1]/t[1]];let n=Fa(e.keypoints.map(s=>s.position),t);return e.box=n.box,e.boxRaw=n.boxRaw,e}var hn,Z2=0,d4=Number.MAX_SAFE_INTEGER,Cu={boxes:[],bodies:[],last:0};async function $E(e){var t;return pe.initial&&(hn=null),hn?e.debug&&ee("cached model:",hn.modelUrl):(j2(["size"],e),hn=await Me(e.body.modelPath)),Z2=(hn==null?void 0:hn.executor)&&((t=hn==null?void 0:hn.inputs)==null?void 0:t[0].shape)?hn.inputs[0].shape[2]:0,Z2<64&&(Z2=256),hn}function Yxe(e,t,n){let s=e[0][0],r=[],a=0;for(let c=0;ct.body.minConfidence){let p=[s[c][1],s[c][0]];r.push({score:Math.round(100*a)/100,part:X2[c],positionRaw:p,position:[Math.round((n.shape[2]||0)*p[0]),Math.round((n.shape[1]||0)*p[1])]})}a=r.reduce((c,p)=>p.score>c?p.score:c,0);let o=[],i=Fa(r.map(c=>c.position),[n.shape[2],n.shape[1]]),l={};for(let[c,p]of Object.entries(K2)){let d=[];for(let h=0;hg.part===p[h]),m=r.find(g=>g.part===p[h+1]);f&&m&&f.score>(t.body.minConfidence||0)&&m.score>(t.body.minConfidence||0)&&d.push([f.position,m.position])}l[c]=d}let u={id:0,score:a,box:i.box,boxRaw:i.boxRaw,keypoints:r,annotations:l};return c4(u),o.push(u),o}function Jxe(e,t,n){let s=[];for(let r=0;rt.body.minConfidence){let i=[];for(let p=0;p<17;p++){let d=a[3*p+2];if(d>t.body.minConfidence){let h=[a[3*p+1],a[3*p+0]];i.push({part:X2[p],score:Math.round(100*d)/100,positionRaw:h,position:[Math.round((n.shape[2]||0)*h[0]),Math.round((n.shape[1]||0)*h[1])]})}}let l=Fa(i.map(p=>p.position),[n.shape[2],n.shape[1]]),u={};for(let[p,d]of Object.entries(K2)){let h=[];for(let f=0;fy.part===d[f]),g=i.find(y=>y.part===d[f+1]);m&&g&&m.score>(t.body.minConfidence||0)&&g.score>(t.body.minConfidence||0)&&h.push([m.position,g.position])}u[p]=h}let c={id:r,score:o,box:l.box,boxRaw:l.boxRaw,keypoints:[...i],annotations:u};c4(c),s.push(c)}}return s.sort((r,a)=>a.score-r.score),s.length>t.body.maxDetected&&(s.length=t.body.maxDetected),s}async function p4(e,t){var r;if(!(hn!=null&&hn.executor)||!((r=hn==null?void 0:hn.inputs)!=null&&r[0].shape))return[];t.skipAllowed||(Cu.boxes.length=0),d4++;let n=(t.body.skipTime||0)>ie()-Cu.last,s=d4<(t.body.skipFrames||0);return t.skipAllowed&&n&&s?Cu.bodies:new Promise(async a=>{let o={};d4=0,o.input=_E(e,Z2),o.res=hn==null?void 0:hn.execute(o.input),Cu.last=ie();let i=await o.res.array();Cu.bodies=o.res.shape[2]===17?Yxe(i,t,e):Jxe(i,t,e);for(let l of Cu.bodies)DE(l,[e.shape[2]||1,e.shape[1]||1]),RE(l.keypoints);Object.keys(o).forEach(l=>Y(o[l])),a(Cu.bodies)})}var Ir,Y2=[],FE=0,h4=Number.MAX_SAFE_INTEGER,Q2=0,J2=2.5;async function OE(e){if(!Ir||pe.initial){Ir=await Me(e.object.modelPath);let t=Ir!=null&&Ir.executor?Object.values(Ir.modelSignature.inputs):void 0;Q2=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):416}else e.debug&&ee("cached model:",Ir.modelUrl);return Ir}async function Qxe(e,t,n){let s=0,r=[],a=Q2;for(let u of[1,2,4]){let c=u*13,p=Ge(e.find(y=>y.shape[1]===c**2&&(y.shape[2]||0)===gd.length)),d=await p.array(),h=Ge(e.find(y=>y.shape[1]===c**2&&(y.shape[2]||0)(n.object.minConfidence||0)&&x!==61){let b=(.5+Math.trunc(y%c))/c,w=(.5+Math.trunc(y/c))/c,k=g[y].map(F=>F*(c/u/a)),[C,N]=[b-J2/u*k[0],w-J2/u*k[1]],[R,D]=[b+J2/u*k[2]-C,w+J2/u*k[3]-N],E=[C,N,R,D];E=E.map(F=>Math.max(0,Math.min(F,1)));let $=[E[0]*t[0],E[1]*t[1],E[2]*t[0],E[3]*t[1]],S={id:s++,score:Math.round(100*A)/100,class:x+1,label:gd[x].label,box:$.map(F=>Math.trunc(F)),boxRaw:E};r.push(S)}}Y([p,h,f,m])}let o=r.map(u=>[u.boxRaw[1],u.boxRaw[0],u.boxRaw[3],u.boxRaw[2]]),i=r.map(u=>u.score),l=[];if(o&&o.length>0){let u=await ke.nonMaxSuppressionAsync(o,i,n.object.maxDetected,n.object.iouThreshold,n.object.minConfidence);l=await u.data(),Y(u)}return r=r.filter((u,c)=>l.includes(c)).sort((u,c)=>c.score-u.score),r}async function f4(e,t){if(!(Ir!=null&&Ir.executor))return[];let n=(t.object.skipTime||0)>ie()-FE,s=h4<(t.object.skipFrames||0);return t.skipAllowed&&n&&s&&Y2.length>0?(h4++,Y2):(h4=0,!pe.kernels.includes("mod")||!pe.kernels.includes("sparsetodense")?Y2:new Promise(async r=>{let a=[e.shape[2]||0,e.shape[1]||0],o=ke.resizeBilinear(e,[Q2,Q2],!1),i=ge(o,He.tf255),l=tt(i,[0,3,1,2]),u;t.object.enabled&&(u=Ir.execute(l)),FE=ie();let c=await Qxe(u,a,t);Y2=c,Y([o,i,l,...u]),r(c)}))}var qh=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],ebe=qh.length,jh=qh.reduce((e,t,n)=>(e[t]=n,e),{}),tbe=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]],kIe=tbe.map(([e,t])=>[jh[e],jh[t]]),zE=[["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 LE(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 BE(e,[t,n],[s,r]){let a=t/s,o=n/r,i=(u,c)=>({id:c,score:u.score,boxRaw:[u.box[0]/r,u.box[1]/s,u.box[2]/r,u.box[3]/s],box:[Math.trunc(u.box[0]*o),Math.trunc(u.box[1]*a),Math.trunc(u.box[2]*o),Math.trunc(u.box[3]*a)],keypoints:u.keypoints.map(({score:p,part:d,position:h})=>({score:p,part:d,position:[Math.trunc(h.x*o),Math.trunc(h.y*a)],positionRaw:[h.x/s,h.y/s]})),annotations:{}});return e.map((u,c)=>i(u,c))}var e1=class{constructor(t,n){de(this,"priorityQueue");de(this,"numberOfElements");de(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 WE(e,t,n,s){let r=n-e,a=s-t;return r*r+a*a}function A4(e,t){return{x:e.x+t.x,y:e.y+t.y}}var Hs,sbe=["MobilenetV1/offset_2/BiasAdd","MobilenetV1/heatmap_2/BiasAdd","MobilenetV1/displacement_fwd_2/BiasAdd","MobilenetV1/displacement_bwd_2/BiasAdd"],t1=1,wd=16,rbe=50**2;function VE(e,t,n,s,r,a,o=2){let i=y=>({y:a.get(y.y,y.x,e),x:a.get(y.y,y.x,a.shape[2]/2+e)}),l=(y,x,A)=>({y:y4(Math.round(y.y/wd),0,x-1),x:y4(Math.round(y.x/wd),0,A-1)}),[u,c]=s.shape,p=l(t.position,u,c),d=i(p),f=A4(t.position,d);for(let y=0;y[jh[d],jh[h]]),o=a.map(([,d])=>d),i=a.map(([d])=>d),l=t.shape[2],u=o.length,c=new Array(l),p=g4(e.part,wd,n);c[e.part.id]={score:e.score,part:qh[e.part.id],position:p};for(let d=u-1;d>=0;--d){let h=o[d],f=i[d];c[h]&&!c[f]&&(c[f]=VE(d,c[h],f,t,n,r))}for(let d=0;dt){i=!1;break}if(!i)break}return i}function ibe(e,t){let[n,s,r]=t.shape,a=new e1(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?WE(n,t,a.y,a.x)<=rbe:!1})}function lbe(e,t){return t.reduce((s,{position:r,score:a},o)=>(UE(e,r,o)||(s+=a),s),0)/t.length}function ube(e,t,n,s,r,a){let o=[],i=ibe(a,t);for(;o.lengthh.score>a);let p=lbe(o,c),d=LE(c);p>a&&o.push({keypoints:c,box:d,score:Math.round(100*p)/100})}return o}async function x4(e,t){if(!(Hs!=null&&Hs.executor))return[];let n=X(()=>{if(!Hs.inputs[0].shape)return[];let o=ke.resizeBilinear(e,[Hs.inputs[0].shape[2],Hs.inputs[0].shape[1]]),i=ye(ge(me(o,"float32"),127.5),1),u=Hs.execute(i,sbe).map(c=>Ge(c,[0]));return u[1]=Mn(u[1]),u}),s=await Promise.all(n.map(o=>o.buffer()));for(let o of n)Y(o);let r=ube(s[0],s[1],s[2],s[3],t.body.maxDetected,t.body.minConfidence);return Hs.inputs[0].shape?BE(r,[e.shape[1],e.shape[2]],[Hs.inputs[0].shape[2],Hs.inputs[0].shape[1]]):[]}async function GE(e){return!Hs||pe.initial?Hs=await Me(e.body.modelPath):e.debug&&ee("cached model:",Hs.modelUrl),Hs}var ua,cbe=["fgr","pha","r1o","r2o","r3o","r4o"],fn={},v4=0;function qE(e){Y([fn.r1i,fn.r2i,fn.r3i,fn.r4i,fn.downsample_ratio]),fn.r1i=Ue(0),fn.r2i=Ue(0),fn.r3i=Ue(0),fn.r4i=Ue(0),v4=e.segmentation.ratio||.5,fn.downsample_ratio=Ue(v4)}async function w4(e){return!ua||pe.initial?ua=await Me(e.segmentation.modelPath):e.debug&&ee("cached model:",ua.modelUrl),qE(e),ua}var jE=e=>X(()=>{let t=Ge(e,[0]),n=M(t,He.tf255);return me(n,"int32")});function b4(e,t){let n=e?jE(e):zr([t.shape[1]||0,t.shape[2]||0,3],255,"int32"),s=t?jE(t):zr([e.shape[1]||0,e.shape[2]||0,1],255,"int32"),r=ut([n,s],-1);return Y([n,s]),r}function dbe(e){return X(()=>{let t={};return t.unstack=bn(e,-1),t.concat=ut(t.unstack,1),t.split=Ht(t.concat,4,1),t.stack=ut(t.split,2),t.squeeze=Ge(t.stack,[0]),t.expand=Ft(t.squeeze,-1),t.add=le(t.expand,1),t.mul=M(t.add,127.5),t.cast=me(t.mul,"int32"),t.tile=As(t.cast,[1,1,3]),t.alpha=zr([t.tile.shape[0]||0,t.tile.shape[1]||0,1],255,"int32"),ut([t.tile,t.alpha],-1)})}async function XE(e,t){if(ua||(ua=await w4(t)),!(ua!=null&&ua.executor))return null;fn.src=ge(e,255),v4!==t.segmentation.ratio&&qE(t);let[n,s,r,a,o,i]=await ua.executeAsync(fn,cbe),l;switch(t.segmentation.mode||"default"){case"default":l=b4(n,s);break;case"alpha":l=b4(null,s);break;case"foreground":l=b4(n,null);break;case"state":l=dbe(r);break;default:l=Ue(0)}return Y([fn.src,n,s,fn.r1i,fn.r2i,fn.r3i,fn.r4i]),[fn.r1i,fn.r2i,fn.r3i,fn.r4i]=[r,a,o,i],l}var Jn;async function k4(e){return!Jn||pe.initial?Jn=await Me(e.segmentation.modelPath):e.debug&&ee("cached model:",Jn.modelUrl),Jn}async function ZE(e,t){var r;if(Jn||(Jn=await k4(t)),!(Jn!=null&&Jn.executor)||!((r=Jn==null?void 0:Jn.inputs)!=null&&r[0].shape))return null;let n={};n.resize=ke.resizeBilinear(e,[Jn.inputs[0].shape?Jn.inputs[0].shape[1]:0,Jn.inputs[0].shape?Jn.inputs[0].shape[2]:0],!1),n.norm=ge(n.resize,He.tf255),n.res=Jn.execute(n.norm),n.squeeze=Ge(n.res,0),n.alpha=ke.resizeBilinear(n.squeeze,[e.shape[1],e.shape[2]]),n.mul=M(n.alpha,He.tf255);let s;switch(t.segmentation.mode||"default"){case"default":n.input=Ge(e),n.concat=ut([n.input,n.mul],-1),s=me(n.concat,"int32");break;case"alpha":s=me(n.mul,"int32");break;default:s=Ue(0)}return Object.keys(n).forEach(a=>Y(n[a])),s}var js,n1=[],JE=0,QE=0,S4=Number.MAX_SAFE_INTEGER;async function eR(e){return pe.initial&&(js=null),js?e.debug&&ee("cached model:",js.modelUrl):js=await Me(e.face.ssrnet.modelPathAge),js}async function I4(e,t,n,s){var o,i,l,u;if(!js)return{age:0};let r=S4<(((o=t.face.ssrnet)==null?void 0:o.skipFrames)||0),a=(((i=t.face.ssrnet)==null?void 0:i.skipTime)||0)>ie()-QE;return t.skipAllowed&&r&&a&&JE===s&&((l=n1[n])==null?void 0:l.age)&&((u=n1[n])==null?void 0:u.age)>0?(S4++,n1[n]):(S4=0,new Promise(async c=>{var h;if(!(js!=null&&js.inputs)||!js.inputs[0]||!js.inputs[0].shape)return;let p={};p.resize=ke.resizeBilinear(e,[js.inputs[0].shape[2],js.inputs[0].shape[1]],!1),p.enhance=M(p.resize,He.tf255);let d={age:0};if((h=t.face.ssrnet)!=null&&h.enabled&&(p.age=js.execute(p.enhance)),p.age){let f=await p.age.data();d.age=Math.trunc(10*f[0])/10}Object.keys(p).forEach(f=>Y(p[f])),n1[n]=d,JE=s,QE=ie(),c(d)}))}var Cr,s1=[],nR=0,sR=0,C4=Number.MAX_SAFE_INTEGER,T4=[.2989,.587,.114];async function rR(e){var t;return pe.initial&&(Cr=null),Cr?e.debug&&ee("cached model:",Cr.modelUrl):Cr=await Me((t=e.face.ssrnet)==null?void 0:t.modelPathGender),Cr}async function N4(e,t,n,s){var o,i,l,u;if(!Cr)return{gender:"unknown",genderScore:0};let r=C4<(((o=t.face.ssrnet)==null?void 0:o.skipFrames)||0),a=(((i=t.face.ssrnet)==null?void 0:i.skipTime)||0)>ie()-sR;return t.skipAllowed&&r&&a&&nR===s&&((l=s1[n])==null?void 0:l.gender)&&((u=s1[n])==null?void 0:u.genderScore)>0?(C4++,s1[n]):(C4=0,new Promise(async c=>{var f;if(!(Cr!=null&&Cr.inputs[0].shape))return;let p={};p.resize=ke.resizeBilinear(e,[Cr.inputs[0].shape[2],Cr.inputs[0].shape[1]],!1),p.enhance=X(()=>{let[m,g,y]=Ht(p.resize,3,3),x=M(m,T4[0]),A=M(g,T4[1]),b=M(y,T4[2]),w=a0([x,A,b]);return M(ye(w,He.tf05),2)});let d={gender:"unknown",genderScore:0};(f=t.face.ssrnet)!=null&&f.enabled&&(p.gender=Cr.execute(p.enhance));let h=await p.gender.data();d.gender=h[0]>h[1]?"female":"male",d.genderScore=h[0]>h[1]?Math.trunc(100*h[0])/100:Math.trunc(100*h[1])/100,Object.keys(p).forEach(m=>Y(p[m])),s1[n]=d,nR=s,sR=ie(),c(d)}))}var Xh=class{constructor(){de(this,"ssrnetage",null);de(this,"gear",null);de(this,"blazeposedetect",null);de(this,"blazepose",null);de(this,"centernet",null);de(this,"efficientpose",null);de(this,"mobilefacenet",null);de(this,"insightface",null);de(this,"emotion",null);de(this,"facedetect",null);de(this,"faceiris",null);de(this,"facemesh",null);de(this,"faceres",null);de(this,"ssrnetgender",null);de(this,"handpose",null);de(this,"handskeleton",null);de(this,"handtrack",null);de(this,"liveness",null);de(this,"meet",null);de(this,"movenet",null);de(this,"nanodet",null);de(this,"posenet",null);de(this,"selfie",null);de(this,"rvm",null);de(this,"antispoof",null)}},J,E4=e=>{e&&(J=e),J||ee("instance not registred");let t=0,n=0,s=0;for(let a of Object.values(wr))t+=a.sizeFromManifest,n+=a.sizeLoadedWeights,s+=a.sizeDesired;let r=s>0?n/s:0;return{numLoadedModels:Object.values(wr).length,numDefinedModels:Object.keys(J.models).length,percentageLoaded:r,totalSizeFromManifest:t,totalSizeWeights:n,totalSizeLoading:s,totalSizeEnabled:void 0,modelStats:Object.values(wr)}};function r1(e){e&&(J=e);for(let t of Object.keys(J.models))J.models[t]=null}async function R4(e){var t,n,s,r,a,o,i,l,u,c,p,d,h,f,m,g,y,x,A,b,w,k,C,N,R,D,E,$,S;e&&(J=e),J||ee("instance not registred"),pe.initial&&r1(J),J.config.hand.enabled&&(!J.models.handpose&&((n=(t=J.config.hand.detector)==null?void 0:t.modelPath)==null?void 0:n.includes("handdetect"))&&([J.models.handpose,J.models.handskeleton]=await Zb(J.config)),!J.models.handskeleton&&J.config.hand.landmarks&&((r=(s=J.config.hand.detector)==null?void 0:s.modelPath)==null?void 0:r.includes("handdetect"))&&([J.models.handpose,J.models.handskeleton]=await Zb(J.config))),J.config.body.enabled&&!J.models.blazepose&&((a=J.config.body.modelPath)==null?void 0:a.includes("blazepose"))&&(J.models.blazepose=lN(J.config)),J.config.body.enabled&&!J.models.blazeposedetect&&J.config.body.detector&&J.config.body.detector.modelPath&&(J.models.blazeposedetect=iN(J.config)),J.config.body.enabled&&!J.models.efficientpose&&((o=J.config.body.modelPath)==null?void 0:o.includes("efficientpose"))&&(J.models.efficientpose=fN(J.config)),J.config.body.enabled&&!J.models.movenet&&((i=J.config.body.modelPath)==null?void 0:i.includes("movenet"))&&(J.models.movenet=$E(J.config)),J.config.body.enabled&&!J.models.posenet&&((l=J.config.body.modelPath)==null?void 0:l.includes("posenet"))&&(J.models.posenet=GE(J.config)),J.config.face.enabled&&!J.models.facedetect&&(J.models.facedetect=JT(J.config)),J.config.face.enabled&&((u=J.config.face.antispoof)==null?void 0:u.enabled)&&!J.models.antispoof&&(J.models.antispoof=zT(J.config)),J.config.face.enabled&&((c=J.config.face.liveness)==null?void 0:c.enabled)&&!J.models.liveness&&(J.models.liveness=bE(J.config)),J.config.face.enabled&&((p=J.config.face.description)==null?void 0:p.enabled)&&!J.models.faceres&&(J.models.faceres=PN(J.config)),J.config.face.enabled&&((d=J.config.face.emotion)==null?void 0:d.enabled)&&!J.models.emotion&&(J.models.emotion=AN(J.config)),J.config.face.enabled&&((h=J.config.face.iris)==null?void 0:h.enabled)&&!((f=J.config.face.attention)!=null&&f.enabled)&&!J.models.faceiris&&(J.models.faceiris=kN(J.config)),J.config.face.enabled&&((m=J.config.face.mesh)==null?void 0:m.enabled)&&!J.models.facemesh&&(J.models.facemesh=EN(J.config)),J.config.face.enabled&&((g=J.config.face.gear)==null?void 0:g.enabled)&&!J.models.gear&&(J.models.gear=MN(J.config)),J.config.face.enabled&&((y=J.config.face.ssrnet)==null?void 0:y.enabled)&&!J.models.ssrnetage&&(J.models.ssrnetage=eR(J.config)),J.config.face.enabled&&((x=J.config.face.ssrnet)==null?void 0:x.enabled)&&!J.models.ssrnetgender&&(J.models.ssrnetgender=rR(J.config)),J.config.face.enabled&&((A=J.config.face.mobilefacenet)==null?void 0:A.enabled)&&!J.models.mobilefacenet&&(J.models.mobilefacenet=TE(J.config)),J.config.face.enabled&&((b=J.config.face.insightface)==null?void 0:b.enabled)&&!J.models.insightface&&(J.models.insightface=gE(J.config)),J.config.hand.enabled&&!J.models.handtrack&&((k=(w=J.config.hand.detector)==null?void 0:w.modelPath)==null?void 0:k.includes("handtrack"))&&(J.models.handtrack=cE(J.config)),J.config.hand.enabled&&J.config.hand.landmarks&&!J.models.handskeleton&&((N=(C=J.config.hand.detector)==null?void 0:C.modelPath)==null?void 0:N.includes("handtrack"))&&(J.models.handskeleton=dE(J.config)),J.config.object.enabled&&!J.models.centernet&&((R=J.config.object.modelPath)==null?void 0:R.includes("centernet"))&&(J.models.centernet=dN(J.config)),J.config.object.enabled&&!J.models.nanodet&&((D=J.config.object.modelPath)==null?void 0:D.includes("nanodet"))&&(J.models.nanodet=OE(J.config)),J.config.segmentation.enabled&&!J.models.selfie&&((E=J.config.segmentation.modelPath)==null?void 0:E.includes("selfie"))&&(J.models.selfie=k4(J.config)),J.config.segmentation.enabled&&!J.models.meet&&(($=J.config.segmentation.modelPath)==null?void 0:$.includes("meet"))&&(J.models.meet=r4(J.config)),J.config.segmentation.enabled&&!J.models.rvm&&((S=J.config.segmentation.modelPath)==null?void 0:S.includes("rvm"))&&(J.models.rvm=w4(J.config));for await(let F of Object.keys(J.models))J.models[F]&&typeof J.models[F]!="undefined"&&(J.models[F]=await J.models[F])}function a1(e,t,n){var u,c;if(!t||(e&&(J=e),J||ee("instance not registred"),!((u=J==null?void 0:J.config)!=null&&u.validateModels)))return null;let s=["const","placeholder","noop","pad","squeeze","add","sub","mul","div"],r=["biasadd","fusedbatchnormv3","matmul","switch","shape","merge","split","broadcastto"],a=[],o=[],i=t.modelUrl,l=t.executor;if((c=l==null?void 0:l.graph)!=null&&c.nodes)for(let p of Object.values(l.graph.nodes)){let d=p.op.toLowerCase();a.includes(d)||a.push(d)}else!l&&J.config.debug&&ee("model not loaded",n);for(let p of a)!s.includes(p)&&!r.includes(p)&&!J.env.kernels.includes(p)&&!J.env.kernels.includes(p.replace("_",""))&&!J.env.kernels.includes(p.replace("native",""))&&!J.env.kernels.includes(p.replace("v2",""))&&o.push(p);return J.config.debug&&o.length>0&&ee("model validation failed:",n,o),o.length>0?{name:n,missing:o,ops:a,url:i}:null}function o1(e){e&&(J=e),J||ee("instance not registred");let t=[];for(let n of Object.keys(e.models)){let s=e.models[n];if(!s)continue;let r=a1(e,s,n);r&&t.push(r)}return t}var Et={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 pbe(){let e=Et.gl;!e||(Et.extensions=e.getSupportedExtensions())}function oR(e){var t;if(e.config.backend==="humangl"&&(Et.name in Jt().registry&&!((t=Et==null?void 0:Et.gl)!=null&&t.getParameter(Et.gl.VERSION))&&(ee("humangl error: backend invalid context"),r1(e)),!$y(Et.name))){try{Et.canvas=vr(100,100)}catch(s){ee("humangl error: cannot create canvas:",s);return}try{if(Et.gl=Et.canvas.getContext("webgl2",Et.webGLattr),!Et.gl){ee("humangl error: cannot get webgl context");return}if(!Et.gl.getParameter(Et.gl.VERSION).includes("2.0")){ee("backend override: using fallback webgl backend as webgl 2.0 is not detected"),e.config.backend="webgl";return}Et.canvas&&(Et.canvas.addEventListener("webglcontextlost",r=>{throw ee("humangl error:",r.type),ee("possible browser memory leak using webgl or conflict with multiple backend registrations"),e.emit("error"),new Error("backend error: webgl context lost")}),Et.canvas.addEventListener("webglcontextrestored",r=>{ee("humangl error: context restored:",r)}),Et.canvas.addEventListener("webglcontextcreationerror",r=>{ee("humangl error: context create:",r)}))}catch(s){ee("humangl error: cannot get webgl context:",s);return}try{l2(2,Et.gl)}catch(s){ee("humangl error: cannot set webgl context:",s);return}try{let s=new Zu(Et.gl);eu(Et.name,()=>new od(s),Et.priority)}catch(s){ee("humangl error: cannot register webgl backend:",s);return}try{ea("webgl").forEach(r=>{let a={...r,backendName:Et.name};er(a)})}catch(s){ee("humangl error: cannot update webgl backend registration:",s);return}try{U().flagRegistry.WEBGL_VERSION&&U().set("WEBGL_VERSION",2)}catch(s){ee("humangl error: cannot set WebGL backend flags:",s);return}pbe();let n=Bs().getGPGPUContext?Bs().getGPGPUContext().gl:null;n?e.config.debug&&ee("humangl backend registered:",{webgl:n.getParameter(n.VERSION),renderer:n.getParameter(n.RENDERER)}):ee("humangl error: no current gl context:",n,Et.gl)}}function hbe(e){let t=[];if(!pe.kernels.includes("mod")){let n={kernelName:"Mod",backendName:cn(),kernelFunc:s=>X(()=>ye(s.inputs.a,M(ge(s.inputs.a,s.inputs.b),s.inputs.b)))};er(n),pe.kernels.push("mod"),t.push("mod")}if(!pe.kernels.includes("floormod")){let n={kernelName:"FloorMod",backendName:cn(),kernelFunc:s=>X(()=>le(M(Bc(s.inputs.a/s.inputs.b),s.inputs.b),ru(s.inputs.a,s.inputs.b)))};er(n),pe.kernels.push("floormod"),t.push("floormod")}if(!pe.kernels.includes("rotatewithoffset")&&e.softwareKernels){let n={kernelName:"RotateWithOffset",backendName:cn(),kernelFunc:s=>X(()=>{let r=cn();Zp("cpu");let a=ke.rotateWithOffset(s.inputs.image,s.attrs.radians,s.attrs.fillValue,s.attrs.center);return Zp(r),a})};er(n),pe.kernels.push("rotatewithoffset"),t.push("rotatewithoffset")}t.length>0&&e.debug&&ee("registered kernels:",t)}var lR={};async function Kh(e,t=!1){if(e.state="backend",t||pe.initial||e.config.backend&&e.config.backend.length>0&&cn()!==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&&ee("running inside web worker"),pe.browser&&e.config.backend==="tensorflow"&&(e.config.debug&&ee("override: backend set to tensorflow while running in browser"),e.config.backend="webgl"),pe.node&&(e.config.backend==="webgl"||e.config.backend==="humangl")&&(e.config.debug&&ee(`override: backend set to ${e.config.backend} while running in nodejs`),e.config.backend="tensorflow"),pe.browser&&e.config.backend==="webgpu")if(typeof navigator=="undefined"||typeof navigator.gpu=="undefined")ee("override: backend set to webgpu but browser does not support webgpu"),e.config.backend="webgl";else{let r=await navigator.gpu.requestAdapter();if(e.config.debug&&ee("enumerated webgpu adapter:",r),!r)ee("override: backend set to webgpu but browser reports no available gpu"),e.config.backend="webgl";else{let a="requestAdapterInfo"in r?await r.requestAdapterInfo():void 0;ee("webgpu adapter info:",a)}}let s=Object.keys(Jt().registryFactory);if(e.config.backend==="humangl"&&!s.includes("humangl")&&(oR(e),s=Object.keys(Jt().registryFactory)),e.config.debug&&ee("available backends:",s),s.includes(e.config.backend)||(ee(`error: backend ${e.config.backend} not found in registry`),e.config.backend=pe.node?"tensorflow":"webgl",e.config.debug&&ee(`override: setting backend ${e.config.backend}`)),e.config.debug&&ee("setting backend:",[e.config.backend]),e.config.backend==="wasm"){if(U().flagRegistry.CANVAS2D_WILL_READ_FREQUENTLY&&U().set("CANVAS2D_WILL_READ_FREQUENTLY",!0),e.config.debug&&ee("wasm path:",e.config.wasmPath),typeof f2!="undefined")f2(e.config.wasmPath,e.config.wasmPlatformFetch);else throw new Error("backend error: attempting to use wasm backend but wasm path is not set");let r=!1,a=!1;try{r=await U().getAsync("WASM_HAS_MULTITHREAD_SUPPORT"),a=await U().getAsync("WASM_HAS_SIMD_SUPPORT"),e.config.debug&&ee(`wasm execution: ${a?"simd":"no simd"} ${r?"multithreaded":"singlethreaded"}`),e.config.debug&&!a&&ee("warning: wasm simd support is not enabled")}catch(o){ee("wasm detection failed")}}try{await Zp(e.config.backend),await Yp()}catch(r){return ee("error: cannot set backend:",e.config.backend,r),!1}e.config.debug&&(lR=JSON.parse(JSON.stringify(U().flags)))}if((cn()==="humangl"||cn()==="webgl")&&(U().flagRegistry.WEBGL_USE_SHAPES_UNIFORMS&&U().set("WEBGL_USE_SHAPES_UNIFORMS",!0),U().flagRegistry.WEBGL_EXP_CONV&&U().set("WEBGL_EXP_CONV",!0),e.config.debug&&typeof e.config.deallocate!="undefined"&&e.config.deallocate&&(ee("changing webgl: WEBGL_DELETE_TEXTURE_THRESHOLD:",!0),U().set("WEBGL_DELETE_TEXTURE_THRESHOLD",0))),cn(),e.config.debug){let s=U().flags,r={};for(let a of Object.keys(s))lR[a]!==s[a]&&(r[a]=s[a]);e.config.debug&&Object.keys(r).length>0&&ee("backend:",cn(),"flags:",r)}if(e.config.flags&&Object.keys(e.config.flags).length>0){e.config.debug&&ee("flags:",e.config.flags);for(let[s,r]of Object.entries(e.config.flags))U().set(s,r)}_y(),BT(),e.performance.initBackend=Math.trunc(ie()-n),e.config.backend=cn(),await pe.updateBackend(),hbe(e.config),pe.initial=!1}return!0}function j2(e,t){for(let n of e){let s={kernelName:n,backendName:t.backend,kernelFunc:()=>{t.debug&&ee("kernelFunc",n,t.backend)}};er(s)}pe.kernels=ea(cn()).map(n=>n.kernelName.toLowerCase())}var M4={};fa(M4,{all:()=>O4,body:()=>Id,canvas:()=>F4,face:()=>Sd,gesture:()=>Nd,hand:()=>Cd,object:()=>Td,options:()=>Qn,person:()=>P4});var ar=e=>{if(!e)ee("draw error: invalid canvas");else if(!e.getContext)ee("draw error: canvas context not defined");else{let t=e.getContext("2d");if(!t)ee("draw error: cannot get canvas context");else return t}return null},Tu=e=>Math.round(e*180/Math.PI),La=(e,t)=>{if(!t.useDepth||typeof e=="undefined")return t.color;let n=Uint8ClampedArray.from([127+2*e,127-2*e,255]);return`rgba(${n[0]}, ${n[1]}, ${n[2]}, ${t.alpha})`};function Ba(e,t,n,s,r){e.fillStyle=La(s,r),e.beginPath(),e.arc(t,n,r.pointSize,0,2*Math.PI),e.fill()}function ca(e,t,n,s,r,a){if(e.beginPath(),e.lineWidth=a.lineWidth,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.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 _4(e,t,n){if(!(t.length<2)){e.beginPath(),e.moveTo(t[0][0],t[0][1]);for(let s of t)e.strokeStyle=La(s[2]||0,n),e.lineTo(Math.trunc(s[0]),Math.trunc(s[1]));e.stroke(),n.fillPolygons&&(e.closePath(),e.fill())}}function cR(e,t,n){if(!(t.length<2)){if(e.lineWidth=n.lineWidth,!n.useCurves||t.length<=2){_4(e,t,n);return}e.moveTo(t[0][0],t[0][1]);for(let s=0;s0){let a=e.emotion.map(o=>`${Math.trunc(100*o.score)}% ${o.emotion}`);a.length>3&&(a.length=3),r.push(a.join(" "))}((n=e.rotation)==null?void 0:n.angle)&&((s=e.rotation)==null?void 0:s.gaze)&&(e.rotation.angle.roll&&r.push(`roll: ${Tu(e.rotation.angle.roll)}\xB0 yaw:${Tu(e.rotation.angle.yaw)}\xB0 pitch:${Tu(e.rotation.angle.pitch)}\xB0`),e.rotation.gaze.bearing&&r.push(`gaze: ${Tu(e.rotation.gaze.bearing)}\xB0`)),r.length===0&&r.push("face"),t.fillStyle=ft.color;for(let a=r.length-1;a>=0;a--){let o=Math.max(e.box[0],0),i=a*ft.lineHeight+e.box[1];ft.shadowColor&&ft.shadowColor!==""&&(t.fillStyle=ft.shadowColor,t.fillText(r[a],o+5,i+16)),t.fillStyle=ft.labelColor,t.fillText(r[a],o+4,i+15)}}}function mbe(e,t){var n,s,r,a;if(((n=e.annotations)==null?void 0:n.leftEyeIris)&&((s=e.annotations)==null?void 0:s.leftEyeIris[0])){t.strokeStyle=ft.useDepth?"rgba(255, 200, 255, 0.3)":ft.color,t.beginPath();let o=Math.abs(e.annotations.leftEyeIris[3][0]-e.annotations.leftEyeIris[1][0])/2,i=Math.abs(e.annotations.leftEyeIris[4][1]-e.annotations.leftEyeIris[2][1])/2;t.ellipse(e.annotations.leftEyeIris[0][0],e.annotations.leftEyeIris[0][1],o,i,0,0,2*Math.PI),t.stroke(),ft.fillPolygons&&(t.fillStyle=ft.useDepth?"rgba(255, 255, 200, 0.3)":ft.color,t.fill())}if(((r=e.annotations)==null?void 0:r.rightEyeIris)&&((a=e.annotations)==null?void 0:a.rightEyeIris[0])){t.strokeStyle=ft.useDepth?"rgba(255, 200, 255, 0.3)":ft.color,t.beginPath();let o=Math.abs(e.annotations.rightEyeIris[3][0]-e.annotations.rightEyeIris[1][0])/2,i=Math.abs(e.annotations.rightEyeIris[4][1]-e.annotations.rightEyeIris[2][1])/2;t.ellipse(e.annotations.rightEyeIris[0][0],e.annotations.rightEyeIris[0][1],o,i,0,0,2*Math.PI),t.stroke(),ft.fillPolygons&&(t.fillStyle=ft.useDepth?"rgba(255, 255, 200, 0.3)":ft.color,t.fill())}}function gbe(e,t){var n;if(ft.drawGaze&&((n=e.rotation)==null?void 0:n.angle)&&typeof Path2D!="undefined"){t.strokeStyle="pink";let s=e.box[0]+e.box[2]/2-e.box[3]*Tu(e.rotation.angle.yaw)/90,r=e.box[1]+e.box[3]/2+e.box[2]*Tu(e.rotation.angle.pitch)/90,a=new Path2D(` M ${e.box[0]+e.box[2]/2} ${e.box[1]} C ${s} ${e.box[1]}, ${s} ${e.box[1]+e.box[3]}, ${e.box[0]+e.box[2]/2} ${e.box[1]+e.box[3]} `),o=new Path2D(` M ${e.box[0]} ${e.box[1]+e.box[3]/2} C ${e.box[0]} ${r}, ${e.box[0]+e.box[2]} ${r}, ${e.box[0]+e.box[2]} ${e.box[1]+e.box[3]/2} `);t.stroke(o),t.stroke(a)}}function ybe(e,t){var n;if(ft.drawGaze&&((n=e.rotation)==null?void 0:n.gaze.strength)&&e.rotation.gaze.bearing&&e.annotations.leftEyeIris&&e.annotations.rightEyeIris&&e.annotations.leftEyeIris[0]&&e.annotations.rightEyeIris[0]){t.strokeStyle="pink",t.fillStyle="pink";let s=[e.annotations.leftEyeIris[0][0]+Math.sin(e.rotation.gaze.bearing)*e.rotation.gaze.strength*e.box[3],e.annotations.leftEyeIris[0][1]+Math.cos(e.rotation.gaze.bearing)*e.rotation.gaze.strength*e.box[2]];D4(t,[e.annotations.leftEyeIris[0][0],e.annotations.leftEyeIris[0][1]],[s[0],s[1]],4);let r=[e.annotations.rightEyeIris[0][0]+Math.sin(e.rotation.gaze.bearing)*e.rotation.gaze.strength*e.box[3],e.annotations.rightEyeIris[0][1]+Math.cos(e.rotation.gaze.bearing)*e.rotation.gaze.strength*e.box[2]];D4(t,[e.annotations.rightEyeIris[0][0],e.annotations.rightEyeIris[0][1]],[r[0],r[1]],4)}}function Abe(e,t){if(ft.drawPolygons&&e.mesh.length>=468){t.lineWidth=1;for(let n=0;ne.mesh[r]);_4(t,s,ft)}mbe(e,t)}}function xbe(e,t){if(ft.drawPoints&&e.mesh.length>=468)for(let n=0;n0&&(xbe(r,s),Abe(r,s),gbe(r,s),ybe(r,s))}}function Id(e,t,n){let s=Bt(Qn,n);if(!t||!e)return;let r=ar(e);if(!!r){r.lineJoin="round";for(let a=0;a0)for(let o of a.keypoints)r.fillStyle=La(o[2],s),Ba(r,o[0],o[1],0,s);if(s.drawLabels&&a.annotations){let o=(i,l)=>{if(!i||i.length===0||!i[0])return;let u=i[i.length-1][2]||-256;r.fillStyle=La(u,s),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)}}}}function Td(e,t,n){let s=Bt(Qn,n);if(!t||!e)return;let r=ar(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,ca(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()}}}function Nd(e,t,n){let s=Bt(Qn,n);if(!(!t||!e)&&s.drawGestures){let r=ar(e);if(!r)return;r.font=s.font,r.fillStyle=s.color;let a=1;for(let o=0;o1&&l[1].length>0){let u=i[1]>0?`#${i[1]}`:"",c=`${i[0]} ${u}: ${l[1]}`;s.shadowColor&&s.shadowColor!==""&&(r.fillStyle=s.shadowColor,r.fillText(c,8,2+a*s.lineHeight)),r.fillStyle=s.labelColor,r.fillText(c,6,0+a*s.lineHeight),a+=1}}}}var $4=0;function P4(e,t,n){let s=Bt(Qn,n);if(!t||!e)return;let r=ar(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 dR(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 kr.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]});Ed&&Ed>0&&(r=r.map(o=>({x:o.x>.5?o.x+Ed:o.x-Ed,y:o.y>.5?o.y+Ed:o.y-Ed})));for(let o=0;o{let t=(p,d)=>Math.atan2(p[1]-d[1],p[0]-d[0]);if(!e.annotations.rightEyeIris||!e.annotations.leftEyeIris)return{bearing:0,strength:0};let n=[0,-.1],s=1,r=(e.mesh[33][2]||0)>(e.mesh[263][2]||0),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]],u=Math.sqrt(l[0]*l[0]+l[1]*l[1]);return u=Math.min(u,e.boxRaw[2]/2,e.boxRaw[3]/2),{bearing:(t([0,0],l)+Math.PI/2)%Math.PI,strength:u}},pR=(e,t)=>{let n=m=>{let g=Math.sqrt(m[0]*m[0]+m[1]*m[1]+m[2]*m[2]);return m[0]/=g,m[1]/=g,m[2]/=g,m},s=(m,g)=>{let y=m[0]-g[0],x=m[1]-g[1],A=m[2]-g[2];return[y,x,A]},r=(m,g)=>{let y=m[1]*g[2]-m[2]*g[1],x=m[2]*g[0]-m[0]*g[2],A=m[0]*g[1]-m[1]*g[0];return[y,x,A]},a=m=>{let[g,y,x,A,b,w,k,C,N]=m,R,D,E;return A<1?A>-1?(E=Math.asin(A),D=Math.atan2(-k,g),R=Math.atan2(-w,b)):(E=-Math.PI/2,D=-Math.atan2(C,N),R=0):(E=Math.PI/2,D=Math.atan2(C,N),R=0),Number.isNaN(R)&&(R=0),Number.isNaN(D)&&(D=0),Number.isNaN(E)&&(E=0),{pitch:2*-R,yaw:2*-D,roll:2*-E}},o=e.meshRaw;if(!o||o.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 i=Math.max(e.boxRaw[2]*t[0],e.boxRaw[3]*t[1])/1.5,l=[o[10],o[152],o[234],o[454]].map(m=>[m[0]*t[0]/i,m[1]*t[1]/i,m[2]]),u=n(s(l[1],l[0])),c=n(s(l[3],l[2])),p=n(r(c,u));c=r(u,p);let d=[c[0],c[1],c[2],u[0],u[1],u[2],p[0],p[1],p[2]],h=a(d),f=o.length===478?kbe(e):{bearing:0,strength:0};return{angle:h,matrix:d,gaze:f}};var L4=async(e,t)=>{var f,m,g,y,x,A,b,w,k,C,N,R,D,E,$,S,F,z,V,j,G,q,K,ne,ae,re,ue,oe,Ae;let n=ie(),s,r,a,o,i,l,u,c,p,d=[];e.state="run:face";let h=await NN(t,e.config);if(e.performance.face=pe.perfadd?(e.performance.face||0)+Math.trunc(ie()-n):Math.trunc(ie()-n),!t.shape||t.shape.length!==4)return[];if(!h)return[];for(let Q=0;Q200?pR(h[Q],[t.shape[2],t.shape[1]]):null;e.analyze("Start Emotion:"),e.config.async?o=(m=e.config.face.emotion)!=null&&m.enabled?Pb(h[Q].tensor||Ue([]),e.config,Q,h.length):[]:(e.state="run:emotion",n=ie(),o=(g=e.config.face.emotion)!=null&&g.enabled?await Pb(h[Q].tensor||Ue([]),e.config,Q,h.length):[],e.performance.emotion=pe.perfadd?(e.performance.emotion||0)+Math.trunc(ie()-n):Math.trunc(ie()-n)),e.analyze("End Emotion:"),e.analyze("Start AntiSpoof:"),e.config.async?u=(y=e.config.face.antispoof)!=null&&y.enabled?mb(h[Q].tensor||Ue([]),e.config,Q,h.length):0:(e.state="run:antispoof",n=ie(),u=(x=e.config.face.antispoof)!=null&&x.enabled?await mb(h[Q].tensor||Ue([]),e.config,Q,h.length):0,e.performance.antispoof=pe.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=(A=e.config.face.liveness)!=null&&A.enabled?s4(h[Q].tensor||Ue([]),e.config,Q,h.length):0:(e.state="run:liveness",n=ie(),c=(b=e.config.face.liveness)!=null&&b.enabled?await s4(h[Q].tensor||Ue([]),e.config,Q,h.length):0,e.performance.liveness=pe.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=(w=e.config.face.gear)!=null&&w.enabled?Gb(h[Q].tensor||Ue([]),e.config,Q,h.length):null:(e.state="run:gear",n=ie(),r=(k=e.config.face.gear)!=null&&k.enabled?await Gb(h[Q].tensor||Ue([]),e.config,Q,h.length):null,e.performance.gear=Math.trunc(ie()-n)),e.analyze("End GEAR:"),e.analyze("Start SSRNet:"),e.config.async?(s=(C=e.config.face.ssrnet)!=null&&C.enabled?I4(h[Q].tensor||Ue([]),e.config,Q,h.length):null,a=(N=e.config.face.ssrnet)!=null&&N.enabled?N4(h[Q].tensor||Ue([]),e.config,Q,h.length):null):(e.state="run:ssrnet",n=ie(),s=(R=e.config.face.ssrnet)!=null&&R.enabled?await I4(h[Q].tensor||Ue([]),e.config,Q,h.length):null,a=(D=e.config.face.ssrnet)!=null&&D.enabled?await N4(h[Q].tensor||Ue([]),e.config,Q,h.length):null,e.performance.ssrnet=Math.trunc(ie()-n)),e.analyze("End SSRNet:"),e.analyze("Start MobileFaceNet:"),e.config.async?i=(E=e.config.face.mobilefacenet)!=null&&E.enabled?o4(h[Q].tensor||Ue([]),e.config,Q,h.length):null:(e.state="run:mobilefacenet",n=ie(),i=($=e.config.face.mobilefacenet)!=null&&$.enabled?await o4(h[Q].tensor||Ue([]),e.config,Q,h.length):null,e.performance.mobilefacenet=Math.trunc(ie()-n)),e.analyze("End MobileFaceNet:"),e.analyze("Start InsightFace:"),e.config.async?l=(S=e.config.face.insightface)!=null&&S.enabled?t4(h[Q].tensor||Ue([]),e.config,Q,h.length):null:(e.state="run:mobilefacenet",n=ie(),l=(F=e.config.face.insightface)!=null&&F.enabled?await t4(h[Q].tensor||Ue([]),e.config,Q,h.length):null,e.performance.mobilefacenet=Math.trunc(ie()-n)),e.analyze("End InsightFace:"),e.analyze("Start Description:"),e.config.async?p=Bb(h[Q].tensor||Ue([]),e.config,Q,h.length):(e.state="run:description",n=ie(),p=await Bb(h[Q].tensor||Ue([]),e.config,Q,h.length),e.performance.description=pe.perfadd?(e.performance.description||0)+Math.trunc(ie()-n):Math.trunc(ie()-n)),e.analyze("End Description:"),e.config.async&&([s,a,o,i,l,p,r,u,c]=await Promise.all([s,a,o,i,l,p,r,u,c])),e.analyze("Finish Face:"),((z=e.config.face.ssrnet)==null?void 0:z.enabled)&&s&&a&&(p={...p,age:s.age,gender:a.gender,genderScore:a.genderScore}),((V=e.config.face.gear)==null?void 0:V.enabled)&&r&&(p={...p,age:r.age,gender:r.gender,genderScore:r.genderScore,race:r.race}),((j=e.config.face.mobilefacenet)==null?void 0:j.enabled)&&i&&(p.descriptor=i),((G=e.config.face.insightface)==null?void 0:G.enabled)&&l&&(p.descriptor=l),(q=e.config.face.iris)!=null&&q.enabled;let Se=((ae=(ne=(K=h[Q])==null?void 0:K.annotations)==null?void 0:ne.leftEyeIris)==null?void 0:ae[0])&&((oe=(ue=(re=h[Q])==null?void 0:re.annotations)==null?void 0:ue.rightEyeIris)==null?void 0:oe[0])&&h[Q].annotations.leftEyeIris.length>0&&h[Q].annotations.rightEyeIris.length>0&&h[Q].annotations.leftEyeIris[0]!==null&&h[Q].annotations.rightEyeIris[0]!==null?Math.max(Math.abs(h[Q].annotations.leftEyeIris[3][0]-h[Q].annotations.leftEyeIris[1][0]),Math.abs(h[Q].annotations.rightEyeIris[4][1]-h[Q].annotations.rightEyeIris[2][1]))/t.shape[2]:0,Fe=(Ae=e.config.face.detector)!=null&&Ae.return?Ge(h[Q].tensor):null;Y(h[Q].tensor),h[Q].tensor&&delete h[Q].tensor;let $e={...h[Q],id:Q};p.age&&($e.age=p.age),p.gender&&($e.gender=p.gender),p.genderScore&&($e.genderScore=p.genderScore),p.descriptor&&($e.embedding=p.descriptor),p.race&&($e.race=p.race),o&&($e.emotion=o),u&&($e.real=u),c&&($e.live=c),Se&&Se!==0&&($e.iris=Math.trunc(500/Se/11.7)/100),Ie&&($e.rotation=Ie),Fe&&($e.tensor=Fe),d.push($e),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 hR=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},fR=e=>{if(!e)return[];let t=[];for(let n=0;n450){let s=(e[n].mesh[33][2]||0)-(e[n].mesh[263][2]||0),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]||0;Math.abs(l)>10&&t.push({face:n,gesture:`head ${l<0?"up":"down"}`})}return t},mR=e=>{var n,s,r,a;if(!e)return[];let t=[];for(let o=0;o.06||g>.06)&&(h=!1),m>g?m>.05&&t.push({iris:o,gesture:"looking right"}):g>.05&&t.push({iris:o,gesture:"looking left"});let y=Math.abs(e[o].mesh[145][1]-e[o].annotations.rightEyeIris[0][1])/e[o].box[3],x=Math.abs(e[o].mesh[374][1]-e[o].annotations.leftEyeIris[0][1])/e[o].box[3];(x<.01||y<.01||x>.022||y>.022)&&(h=!1),(x<.01||y<.01)&&t.push({iris:o,gesture:"looking down"}),(x>.022||y>.022)&&t.push({iris:o,gesture:"looking up"}),h&&t.push({iris:o,gesture:"looking center"})}return t},gR=e=>{if(!e)return[];let t=[];for(let n=0;n0){let r=s.reduce((o,i)=>(o.position[2]||0)<(i.position[2]||0)?o:i);t.push({hand:n,gesture:`${r.name} forward`});let a=s.reduce((o,i)=>o.position[1]((r-1)*Ne.body[S].box[K]+q)/r),z=e.body[S].boxRaw.map((q,K)=>((r-1)*Ne.body[S].boxRaw[K]+q)/r),V=e.body[S].keypoints.map((q,K)=>{var ne,ae,re,ue,oe,Ae,Q,Ie,Se;return{score:q.score,part:q.part,position:[Ne.body[S].keypoints[K]?((r-1)*(Ne.body[S].keypoints[K].position[0]||0)+(q.position[0]||0))/r:q.position[0],Ne.body[S].keypoints[K]?((r-1)*(Ne.body[S].keypoints[K].position[1]||0)+(q.position[1]||0))/r:q.position[1],Ne.body[S].keypoints[K]?((r-1)*(Ne.body[S].keypoints[K].position[2]||0)+(q.position[2]||0))/r:q.position[2]],positionRaw:[Ne.body[S].keypoints[K]?((r-1)*(Ne.body[S].keypoints[K].positionRaw[0]||0)+(q.positionRaw[0]||0))/r:q.positionRaw[0],Ne.body[S].keypoints[K]?((r-1)*(Ne.body[S].keypoints[K].positionRaw[1]||0)+(q.positionRaw[1]||0))/r:q.positionRaw[1],Ne.body[S].keypoints[K]?((r-1)*(Ne.body[S].keypoints[K].positionRaw[2]||0)+(q.positionRaw[2]||0))/r:q.positionRaw[2]],distance:[Ne.body[S].keypoints[K]?((r-1)*(((ne=Ne.body[S].keypoints[K].distance)==null?void 0:ne[0])||0)+(((ae=q.distance)==null?void 0:ae[0])||0))/r:(re=q.distance)==null?void 0:re[0],Ne.body[S].keypoints[K]?((r-1)*(((ue=Ne.body[S].keypoints[K].distance)==null?void 0:ue[1])||0)+(((oe=q.distance)==null?void 0:oe[1])||0))/r:(Ae=q.distance)==null?void 0:Ae[1],Ne.body[S].keypoints[K]?((r-1)*(((Q=Ne.body[S].keypoints[K].distance)==null?void 0:Q[2])||0)+(((Ie=q.distance)==null?void 0:Ie[2])||0))/r:(Se=q.distance)==null?void 0:Se[2]]}}),j={},G={connected:{}};(o=t.body.modelPath)!=null&&o.includes("efficientpose")?G=O2:(i=t.body.modelPath)!=null&&i.includes("blazepose")?G=_2:(l=t.body.modelPath)!=null&&l.includes("movenet")&&(G=Hh);for(let[q,K]of Object.entries(G.connected)){let ne=[];for(let ae=0;aeoe.part===K[ae]),ue=V.find(oe=>oe.part===K[ae+1]);re&&ue&&ne.push([re.position,ue.position])}j[q]=ne}Ne.body[S]={...e.body[S],box:F,boxRaw:z,keypoints:V,annotations:j}}if(!Ne.hand||e.hand.length!==Ne.hand.length)Ne.hand=JSON.parse(JSON.stringify(e.hand));else for(let S=0;S((r-1)*Ne.hand[S].box[q]+G)/r),z=e.hand[S].boxRaw.map((G,q)=>((r-1)*Ne.hand[S].boxRaw[q]+G)/r);Ne.hand[S].keypoints.length!==e.hand[S].keypoints.length&&(Ne.hand[S].keypoints=e.hand[S].keypoints);let V=e.hand[S].keypoints&&e.hand[S].keypoints.length>0?e.hand[S].keypoints.map((G,q)=>G.map((K,ne)=>((r-1)*(Ne.hand[S].keypoints[q][ne]||1)+(K||0))/r)):[],j={};if(Object.keys(Ne.hand[S].annotations).length!==Object.keys(e.hand[S].annotations).length)Ne.hand[S].annotations=e.hand[S].annotations,j=Ne.hand[S].annotations;else if(e.hand[S].annotations)for(let G of Object.keys(e.hand[S].annotations))j[G]=(p=(c=(u=e.hand[S])==null?void 0:u.annotations)==null?void 0:c[G])!=null&&p[0]?e.hand[S].annotations[G].map((q,K)=>q.map((ne,ae)=>((r-1)*Ne.hand[S].annotations[G][K][ae]+ne)/r)):null;Ne.hand[S]={...e.hand[S],box:F,boxRaw:z,keypoints:V,annotations:j}}if(!Ne.face||e.face.length!==Ne.face.length)Ne.face=JSON.parse(JSON.stringify(e.face));else for(let S=0;S((r-1)*Ne.face[S].box[j]+V)/r),z=e.face[S].boxRaw.map((V,j)=>((r-1)*Ne.face[S].boxRaw[j]+V)/r);if(e.face[S].rotation){let V={matrix:[0,0,0,0,0,0,0,0,0],angle:{roll:0,yaw:0,pitch:0},gaze:{bearing:0,strength:0}};V.matrix=(d=e.face[S].rotation)==null?void 0:d.matrix,V.angle={roll:((r-1)*(((f=(h=Ne.face[S].rotation)==null?void 0:h.angle)==null?void 0:f.roll)||0)+(((g=(m=e.face[S].rotation)==null?void 0:m.angle)==null?void 0:g.roll)||0))/r,yaw:((r-1)*(((x=(y=Ne.face[S].rotation)==null?void 0:y.angle)==null?void 0:x.yaw)||0)+(((b=(A=e.face[S].rotation)==null?void 0:A.angle)==null?void 0:b.yaw)||0))/r,pitch:((r-1)*(((k=(w=Ne.face[S].rotation)==null?void 0:w.angle)==null?void 0:k.pitch)||0)+(((N=(C=e.face[S].rotation)==null?void 0:C.angle)==null?void 0:N.pitch)||0))/r},V.gaze={bearing:((r-1)*(((R=Ne.face[S].rotation)==null?void 0:R.gaze.bearing)||0)+(((D=e.face[S].rotation)==null?void 0:D.gaze.bearing)||0))/r,strength:((r-1)*(((E=Ne.face[S].rotation)==null?void 0:E.gaze.strength)||0)+((($=e.face[S].rotation)==null?void 0:$.gaze.strength)||0))/r},Ne.face[S]={...e.face[S],rotation:V,box:F,boxRaw:z}}else Ne.face[S]={...e.face[S],box:F,boxRaw:z}}if(!Ne.object||e.object.length!==Ne.object.length)Ne.object=JSON.parse(JSON.stringify(e.object));else for(let S=0;S((r-1)*Ne.object[S].box[j]+V)/r),z=e.object[S].boxRaw.map((V,j)=>((r-1)*Ne.object[S].boxRaw[j]+V)/r);Ne.object[S]={...e.object[S],box:F,boxRaw:z}}if(e.persons){let S=e.persons;if(!Ne.persons||S.length!==Ne.persons.length)Ne.persons=JSON.parse(JSON.stringify(S));else for(let F=0;F((r-1)*Ne.persons[F].box[V]+z)/r)}e.gesture&&(Ne.gesture=e.gesture);let a=ie();return B4=pe.perfadd?B4+Math.round(a-n):Math.round(a-n),e.performance&&(Ne.performance={...e.performance,interpolate:B4}),Ne}var U4={};fa(U4,{distance:()=>Zh,match:()=>V4,similarity:()=>W4});function Zh(e,t,n={order:2,multiplier:25}){if(!e||!e)return Number.MAX_SAFE_INTEGER;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 W4(e,t,n={order:2,multiplier:25,min:.2,max:.8}){let s=Zh(e,t,n);return AR(s,n.order||2,n.min||0,n.max||1)}function V4(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)return{index:-1,distance:Number.POSITIVE_INFINITY,similarity:0};let s=Number.MAX_SAFE_INTEGER,r=-1;for(let o=0;ob.box[0]&&h.box[0]b.box[1]&&h.box[1]+h.box[3]f.body.box[0]&&b.box[0]+b.box[2]f.body.box[1]&&b.box[1]+b.box[3]f.body.box[0]&&b.box[1]+b.box[3]>f.body.box[1]&&b.box[1]+b.box[3]{b&&b.length===4&&(m.push(b[0],b[0]+b[2]),g.push(b[1],b[1]+b[3]))};y(f.face.box),y((c=f.body)==null?void 0:c.box),y((p=f.hands.left)==null?void 0:p.box),y((d=f.hands.right)==null?void 0:d.box);let x=Math.min(...m),A=Math.min(...g);f.box=[x,A,Math.max(...m)-x,Math.max(...g)-A],(r==null?void 0:r[1])&&(r==null?void 0:r[2])&&(f.boxRaw=[f.box[0]/r[2],f.box[1]/r[1],f.box[2]/r[2],f.box[3]/r[1]]),o.push(f)}return o}var i1=` /9j/4AAQSkZJRgABAQEAYABgAAD/4QBoRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUA AAABAAAARgEoAAMAAAABAAIAAAExAAIAAAARAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQu bmV0IDQuMi4xMwAA/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoUDg8MEBcUGBgXFBYWGh0lHxob IxwWFiAsICMmJykqKRkfLTAtKDAlKCko/9sAQwEHBwcKCAoTCgoTKBoWGigoKCgoKCgoKCgoKCgo KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo/8AAEQgBAAEAAwEhAAIRAQMRAf/E AB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAE EQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZH SElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1 tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEB AQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXET IjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFla Y2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXG x8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAwDAQACEQMRAD8A+qaKACigApGOKAML Xp8xlF5A7V4X8RtYs7PzfNImnx8sa8Kp9z3q2tEgp6angWs62ZZ5CTGoJ6DArGNz5p+UrID6EUrF PUlW1EuN0XNW7PQ2L5j3JnoKXN0KijqNP0eYoqXBdgPuuo+ZPeupisWn2Jd4+0r924XgsQOCff3/ AJ1FzRKxDqGii6m3siiQ8F1XGfXI6YNWLfRbiRQMkcZI9fpTDluT2/h6Qy8gDPbtmtG38JeY480Z 5zSLUTZg8M28YwYxjAArXtdPt402qgHbpSaLWhma3o0Uqk7Nx9DWLaaVblgPs6qRyds2M/gRSQp9 zZOni2iWS2hlQ+kjYz9OMGrdjq89vIPPVhj+8M/lQyDq9P1WOYBlMZz1AOD+VdDaTiReOKulK0jO tHmi0WDTlr0TyxRVhT8tJjIX+9SUxHXUV553BRQAVBcPhSBTSuxPY86+IGti0s5I7dsORy9fM3i6 8e8mfDO5P90ZrWWiJicNPpZZtxV/xrW0jQt4DOv6Vk2dEEdTY6BHuB25rpbPSo0QARjP0qTRI17W wA/hFaMWmoQMgflQXYsDS142rU9tpqqenfNA7GgtihxkdKuRW6qMY/GkDZY8sY4Ap4hXbyB+VArk EtuH4wPyrk/EGkOm+a3jw3suRQLc5i38SX9hJ9nnY+XnBUdPyNdFY6pa3KkkAE9l6f8AfJ/pSJT6 GhDmI+Zb4ZRycdv6ium0nUhKFydrelTsNnS2829RnrVgV6NKXNG55lWPLIM81Op+WrZkRMfmNNzT A7GivPO4KKAEY4XNYWt3vkwPg4OK0giJdjw/xrqhm87Zs8tc7pX5A+leSajf6aHYJ50kn4AZpTep rBWRm2Vobm4BXfyehPFdnpmnBFUY5rI2SN63tlToK0YI+KZpFF+3QdavwoKTLtoW0Toaswpk5pCb LCxipAhoIuP2dKevHXoaYDylRyxhlwRQI4nxVoCXWZI1GfpXGtbSWjYPGP73+NIGupt6TqMsLruZ ih4xnP5V09mQ+JLd8gn0xSYJnVaVdkook69K34zuUGunDS3Rx4qOzHVIp4rrOMY3NJQI7GivPO8K KAILt9kZrz3xlebYiu8KCCWb0XvW0NFch6ysfO3jLVjfXLIn+pQkKorl7WxNxIPl71g2dUUdpo+l pBGvHPet23iC8ihFosrxirkHQUFo0IF4FXI1O726CpKLacCrMJoJLYHAPpTwucHpSRJJ5e4AZI9x UqpxzVpCuOC8cUpQUMRnXttuB4rjNdsYyeVwfXpmpGmcvcQyafMCFJjPY10eg34BUg4DcZP8jUO4 HaRq3lLNF+IHet7R7jz7c56rwa2wz9+xhiVeFy/T1PFegeaNPWigDsc0ZrzzvDNIaAM7VpNqdegr xL4l6kywyRhseZ19lrdfAZL4jxYg3Fw20d63tJsdrDI5rm3Z3R0R0Mce1eKnQYAplIkWrMJ45oZS NO3PHbNXIyfpSGWowSOasxLUiZdjFSqtNEMkUemKlAGKsRJjAppFAiORMjmsTVrNZEO4cfSoZSOD 1eJ7WXBUzQZ+7nkfSo7e2Ei+ZaMzxntjBX2NSU1Y6/wxqojiEFzkA8KTXYaUoWRyv3W5rSjpNHPX +BmpSg8V6J5gUUAdhRXnneFFAGHrTfu5PpXzj8S70/aZtxzztXFbv4DKHxHI+H4GZiz9zxXXW8G3 GBXMjvLRXAx0oPGPSmMVeOnWrMTYpFI0bcg1fh54xmgovRcD3qxETSIZcRvzp+/BpEkqsBUqsM9K q4Em4Gkxk0yRGXrVW6i8yFhkg+tJjRxGsWrxllkUMh9eK5uMz6bcebbnfG33kPcVkay2OntPKuo0 nhXI67c8qa7Lw3c+adjcEDGK1paSRhVV4s6A0or0jyRRQ1AHX0V553hRQBz+vNtt5z3xXzX8Qbdm uic5YnOMdK3l8JnTXvlbwpYl+WySOgrp5YfLOOB9O1c62O7qQkc+9RsKChFPWp4DluOlSykaNruH ArUgHShFNF2NT1qxGO3NBmyxGcE1N2560CFzjrUysO9JAPDDjFOVuKoQuSRTWouBkazbCa3cd8cV wF7IISQccHBzUSWpV9C3o1x5b5GAjdQD1rs9DjC3kckbEhqKfxIzn8LOupRXqnkPccBSkUAzraK8 87wooA5rxMSI3HqK8B8bQl9Q8sffY5b/AAraXwkUviNrw9pH2W1ViMMRTdRjw4HpWNtDti9TPc4P FQs2M5qdyyMHLcfjV63HTAoBGtap0wK0YxigpsuRDtVhVYd6GQydVwwIqdRnqKCR23I5pCMUW6gD YNKuetAEise9KTxQBWuFyhrznxNZkXjFeN3I+tTIZg2OqmzmxNF0PO3vXp/g2+hukVl4zyPanTXv JmVR+60dpThXpnlPceopWFAbnV0V553hSGgRynjC5FujOey14Ssp1HxNmTnc+a3kvcIpv37HoEYQ QmMdVHSsnVbYJF5jVk0dsNzlruVIsl2wKxbjWrVHILjg1CRbZJb+ILHPzyhfStODWLQgFJFYd+el UJM27HUIXxhga1Y5lLVLKLkMnoauxnPPrSEx7ShF+Y/n2qrc6xBbhizDAqkK1zJuvG9nbg8ZA681 ly/Ei052RO3uKAsZlx8QGd8xxvt9Aa1NH8dK7AXMcip64zigdkdrZX8F7EJLdwwNXMkrz1qRMRly CK4TxmpidWI49felPYSOMmi80NIoOV6qRzXYeA5SskYPfirpfEjGr8LPWVHyD6U4CvQPL3ZItOYc UDOoNFeed4Uhpks4H4iE/Z5MeleMeGULeLgjds10S+BGdL+Jc9OSBU2Huc5Nc74yvUtrcDBrJnZF 63PJdXvLy/lKWw46bvQVz82jXhkLO5Y+9ZlsYthcRnbIjY9R3q3awTRkEM3WmJI6C0ea3dGRsr1x XY6TqW9FLHnjrUs0izpLK5DDjofSta3ckH09KRUkZuuTvFGdvPauE1Y3U6Mqbssf/rUxHPTaJPK2 ZmJPbBqzY6DCZh5xJC9s9aBJHU6dpemJjfEmfetJtI0+VPkUr/unFOxdiextHs33W07YHQHk11mk Xb3KbZ1xIvcd6LEyWho4Nct41sTPYb16ipexCPPZN+wYGCvH1rrPAEJmvkPoc1VL4kZVvgZ6yFwK cBXoHkkqinFaVyzo80GuE7WJRQSziPiGdthK5HQV4x4J/wBI8WPIewNdEvgRNL42emO/yj1UHNef eNpRczbC+I17DvWT2OqJxc0sMK4TCisy41q0hfEkqj8aixdwTXNOlwvmqD9anS9tXH7uVG+hosO4 /wC0oOhrR0+6G4YNIEzsNEuCxAPNdjZruA4xxUmjINSjURksOlcbqFykbnjFA1sYGoassaknCqO5 rl7rxhGm7yBnBxuJq0rkSlYpw+NLlsfd5P8AerVsvHEqSBHwPVgcgVpyMyVXU3rXxcHYETAk+hru /DWti6ZSTyOKzZqndHaxvvUGq2rQ+dYyqR24qWI8dvbr7LqDxyDAzXpvw6FvIxePGSM06Xxoyr/A zviKFHNegeX1J41zUhXioGbuaSuM6wpCaBHG/EcA6HN/exxXjXw2jL67cv8A3Qa6H8CFR+NnoWpO I4XI44rxLxrqjQzSEsQM1gdSPM9U1uR1YbmWIdXHf2rmpIb67YS28UrRlsLI3c/jW0VZGUpO5pW1 jfLNOjahawzwReYI5cjzMkDavHJ5/SrVv9uhtPtVxCPLBwzxnlT9KGghLU3tKvvPjHzbl7EGuisJ GRxWLOg7nRXJEbDjmvSNK+aFSfSoZr0KutRkphc4NcRrdkVjL9aVio7Hk3iqS8ubhrWzUlsZY9kG cZNc5D4aee5MclzJIFTzHAO0MfatqSOWu7bFS1srDUZEis0vIZoUxPvfcC+4/dx2xjr712XiTwXb WmlQ6hol3cRhoFd4rlg3zY5wR0GelavQwjq7GD4etdVvSnk2wAB+9v8A8mvcfA2kXiRo0/UdcDis ZnTTulqeoWqbUAJqWUb42X1FZlnjfjSwlGrr5S/eNdD4RkvLAAQ4yRyaUZcruVKl7TQ9I0G+mnzH ckFwM8VuIK7ac3KF2eXiKapz5UWYxipNtMyNejNch0jSar3cjR27uoyQCRVRWom9DxTx54gu5fMi lbKdMVjfCZPNlv5v9rFbVHpYqjGzbOn8SzFI9o715L4u0r7arYzk+lYdTqSujy7U/C0u4vHk+WwO xuh9q3J9dgvbdVukMV1EwbDDgn04rZMwlHoZ+orZ6hfQ3RWVnQYCgZAq+8U0ln5NtBsV2yxYcfgK JtW0CnB31LlroVwJ1nQLGDjeP7w+lb0dsFxjrWB0tHS6NuWPJ6A16ToUm63T3Gallr4S7cxiTjrX PaxaF7dlVeSMUhxZ5jd+H7qCa4eF3DSE5x3zXN3Wk6jbyeaiFWUY6ZyPStYS5SalPmVipFbX0E4c W0alvmPHJrag0rVvEE6LdljGpG2NRtQD+tW5XMI0uU9M8NeFo9PiQhecDIIrtrOMIoG3H4VlJm9t C6CB06VPGM1IHLeItGS6uw+ORT7e3jsbQvj7gzUNam0JaWE+HN7NqOqX80n3FO1RXo8YzXdS+BHk 4z+KyzGPapcU2YIv7qQtiuaxvcaWqG4O6FwfSrS1JbPnrxoxkv7qIfejcitj4V2f2exumI+8+aKn xHTT+G5d8Txlm4rjLxMsQwzWT3OiK0Mm6sEkVsAcjFc1d+FEmlGwEDPQVopaEuOpr6f4ZWNAu3tW vHpAj5ZQcUFIWaDjGMVUMQ3cVDBmvbhY7QAV2nh+T/R1yeKhlrY31+b61FcQK6nIoJMi401WblRi qr6PCw5UYq9y+YgOgWzNkRrx3xWjp+nx2v3FQcelAbmko9anQ4GBUNisPHWr1qMrQhS2K11HvmYV hamcxSRZ5xRIqluS/DKAQQXZxyXrvo2FdlL4EeZjH+/ZbjNSZpswLNBrE1Gt7VE4ODVIlnh/j61F j4lmeTGyUbq6LwdEqWbeX0YbhSqfEddP4Bddj4JIrhL5d8h7VjI6oLQqKNzelWre3yc4/ClFjaL6 wqBxxUUxwCKu5BmXRA6c+9ZjP83FSBoQuPs4BrsNBlUW659KmRrDY6G1lyQtW3Hy0lqQ1qVJnAbm oy3b9KYJCqRj3o4zRctIlhjLHmpSuOBRbQOpLGpPFaES7UqkZzKN1KsEc87/AHUUmvPLTVGv72aQ k7WJwKmRrQ3ud74Ltilgz4++2a6iNDXdS0gjyMU71my7GpqTbxSbMki3SViajTTHqkSeR/GeyZmg nQHkEE1S+F+oPPavBL96I4/Cia1udVF+4dVrkW+Fq8+v4tjMDWUkdVJ6WM0cNV+F+MVmjUcZgqnP 1qpNNnkcVRLiZtxIS1UzzIF7mghlxUZpVQdq6nTVdAoAOKzkbQWhvwM6gMM1twOJYx3NOJE11Kt1 H1/pVVlwBkk+9NocXoOQ45FPj+fkUJFF2NSB700v/hTEty5ZpkjvVyUgcCq6GM9zC14/8Se6GcZQ 1574Xs5WkI2HBPHFQ1dm1KSSZ7Rotn9l0+KPHIHNacae1dy0Vjxaj5ptlhVp+2s2CJ9ppCKzuWNx zSFc1SYrHNeNdIGpaYw25ZeRXmvheyk0jVpEdcLJ0q3ZxNKTa0O3vQHg/DNcHrsJDmsmjspnNzNt fFIJ24GazOhC+azDmgZIOOKBsp3J2qSaZodubq58yQ4QAnmhGT3NO18pb7BORmu205LfYpyKVkWp Oxr5gKYWoIZWgfGfloFq1qTPLubnGO1RPtxg4P0oBAkY/hBz6VNDDkZ6AU0W2WSdqkdKr9ZOaGSj VtcLHmnOcgmmYvcz7mBLy3MbdD1q9ouiRK6bUAVeelOC1InPlidSsWMDFOCEdq3uefykqrinYqGy rFvApMVka2DAowKAsMkRXQqwyDXn/iWyitNQ3qPl6itIvRoF8RXinW4tQ6HI6GuW8SIVBPalc6qe 5x9x97r3qruwTjrWZ0ksZ9TUmcDNAmZ9/wAoao63rR0+w22MLPtAzt6mghmfofiB76LdJBJBIp5D d/oa7bSdWLIPnpDi9TM8TeKdas51XTbIyxd3J/pXS+E/EFxqNoFu7do5OmD60maHWrnZyDRkn/69 MlEyOR0xntVoNx+FUgYjPxg4FLCuWDZyKQr2RoRnP0qO+nEFpJITgAUzLqZnhu6+0rknOTXpOmwJ Fbrt5yMmnHYyr6Oxb2ijaKLnPYMClwKQWK3n0hn+lachHOJ9pNNN0apQFzsY10a4v4hXQh0xpieQ MA1XLZNjhK80cT8OdV+3Wl3A7ZZJCw+hrR1qLcjZ/CsbnfHRnFXseHJArOYYbrUs1uPhYbuatqFP ByfSkMq3UIINYkto+87Tx6GkSxfsDbflGD7CtTw/pk4nzITtPIFMFudsukh4Rxz71paTpKwP5jcn 0qTRy0NORMDgVCqewoJTJgAoxjntTiTu7fWmFxAcnn1q3EPl+X8KZMi4gKqB1Peob/Tv7Us5bfeU yOoq4R5nYxqT5I8xieH9J1DTbvyJELRg8ODwa9Ms5mSFV9BWiptbnNVrKdmif7Q1KLg96XIZc5Is pNL5pqeUrmMtZs0jzV08phchaY00zH1p2ZNxjS1g+LdJOt6U9ssmxjyGp2urDjLlaZzng/wUPDqz TSTmWeTrjpVjVk3Rvjr2rnqQ5dDvo1XUd2cTqSNk9OKxXGCeKxZ1DAxHTr2q5C/y8GokUhsz54qu uCxzSQjQ0+FZblR2ro4bZYiMVQ0dBb7Qi5x0qzuG5QOh71LYErDufpSeWrHnimIXbjkUjLkH1Hem gGxryc+tXI19KYmWegq9YLiLJ7mtqS945cS7QsWehqxA9dEjz4krPSxyZqbFFhGxUm6smjRM55Lk HvSvNxXTY57kLT+9MNwKdhXGm5FIbkU7Bca1wMEVhaiuQcVhXWiZ14R6tHGanGBI2OtYkqEHjgVy s9ErEeo6UBsHipKEZs5qpPdRxcbhx70NCSuybTNWihc5brW9Fq6vjMnFSdEIdDRi8RRKygZbHFbu m6nb3RA3gMegNJhOm0jbXGOoxTuCc1Rz3FyoGKawz9KaAVcZqeMgCmIkB4FaUTbYwB6V00Fuzixb 0SFMuDU8Mlbs4UPeXHeiOXkUrDuXYnyKk3cVk0ap6HMxxketSMhrcwRC0dMMZFMQ3yzSeVQAeUaz 9Vj8uPd271nVV4m+GdpnHX67pCeKyLtBtNcR6xlk9RVeWTb3qRnO6trgttyIfm71z7ai8j7/AJmN DNqUVa5Yi1AnjynHuBV+11YJhWWXcP8AZNSzqgmaEerSsf3NtIQP4mGKtRavdRgMIpVI9KjU0a7n R6T43uYQI7qN2Tpkqciu503VVuQGAYZHQjFVc4alPlZrpKGAznpTwxOc9+lWjIlUACnM4XApiLNk nmvnsK0NvpXZRVonmYqV52GsmanhXitTmFkSiJTSAvwrxUxXIrJ7miOfjf1pzNWxkRlqYWpgJupu 6gQbuahvIxPA6eo4pNXVioS5WmefakGhndH4INZs5DJXA10PaTurmLO21uKpSZqGMoXGnRzBiyjd 9Kx5rcQS428fSkjanLoaOliHGZFB56VswW+mtPufcBsGOAfmxz+tFkd8HpoaUx09FAtFY8DO71qb Sms/Nb7RbecG6AEjFLS5c78t+p0djpVs9wsyQiJAdyr1rW+zqjErzSe559Sbk9S3C+MA1bjbgE1S MSXzMVG0vNUI2tPKrAuCMnrVzNd0PhR49W/O2xrHmp4TxVMzQshpIzzQBehqesnuaI5VGzT2bitz FEbNTC1ADS1JupgG6l3UAc14s04yR/aYRll+8BXCtLncDXFWjys9TCz5oW7GddH5qqNzWDOgQnC8 VSuo1kHzAGkPYopEY2+RWxV23Vzj5G/Kg3jWaNazhZuqNXS6TaKhB2c0jR1nJWOlhOxRxU4YkCgx Y0OQatQyDbyaaFYe8uF4NY3iC9ltbVGj43NTIL3h7WzMihjzXVQXYYDdW9Cf2WcOJpfaRZ3g9KsQ mupnCLIabGeaAL0LcVY3cVmzRHIxtUhetzEjZqjLUAIWpN1ArhupwagAfDKQ3Q1594v0c2bm6tx+ 5Y8j+6ayrR5onThp8s7dzkZjuqAAmuBnqC7c0iwgtzSA0rWzjfGRW3ZadDu4AoNYo2rfS4v7orSh 05UA2r0pDbsTm29KRottBNyJ0wpJ9KhD7f6U0ikNWffIFBz60zVUW52ow4UcUN6EPcx44WsbgOmd ua7TT5Bd24KHnFKnLlZFSN4koluLdueRWvp14swweG9DXoxldHlTjYtzGoo25qzEvwtUxas2jRPQ 5CNqkLVsYoYzUzdQA3dSFqBBmnqaBhuqhriCXTpVIzxUz+Fl03aSPI9QTypW2/dz0qKNw3SvOPZR Mqin8VLKRcs3O4Cuk0w/MDjt1NBtHY6O2IIHY1pxgFaETIRwMkjtVSUEk4570MlFW5bap6dKzWm8 1tqH8aY+hp2FvGoGayNevVt7/ap4xzUvYjqTLtvLPcvJxSaVcyWsxTnFZlnT2t15xHmCtOBYwQy4 B9q7cPO+jPPxFO2qLEj5HWo42+aus4HpoX4W4FTF+KlotbHII9SFuK0MUNZqiLUDE3UbqBBupwag Bc1DefPbyD/ZND2KjujyPWlKzuPesRZjHJXms9lMuw3StjnmphKDSLTJ7OfE3JrpbO4GQc9qlnRA 3LO82k5NbFvdADkjBoCSHyXIIIzgVQvdRigT7wzjgUzO1jHknlvG7qnp61etYFQDIpCZoqVijzXn 3iC8EmsOuaCGb/heR/s0ijkVv6fbxy3QMg5xmsnuX0Ldzut3+UYTPWk+2GJSe+M1pFtamcldalmx 1eO4XaThhWnC+TXqR2PHqL3maUJ4qRjxSEjj42qXdxVmaGs1MJoATfSbqBAG5p6mgAzTJTmNvpQU tzzHXY83D/U1zF5FhjgV5r3Pa6FMsV5HWnLe7RhqBRdmTwagN2d2K2rPU1C5LAnPrUs6Iysbdrq6 f3gK0BrUKj/WClY05iM6xLOcQAj3NT29uznfKSzHuadzNu7NSBFjHNSm5VO9IRnajqoWMhTzXFtA bvUfMduSeg702Qz0rS7FbTToQFwzjJqaGTFyfK5PQViyzUuFmuIdgGABya5u/vTaN5cnUHFUmLoZ zyskwlgJweSK6zQdUEwVJeGr0aUrxPLxEfe0OrhPAqVjxWhznGRtUwatDK4jNxURbmkAm6jNABup 6tQAFqhupNtu59qUnZFwV5JHnWsHdIx96w5lz15rzT2uhRmt85xWbcxMnUGmZlB0bdxmrNvFIcfM 350mWjbs7YkDJY/jW5ZWW4jikWkdNp9mqYJFaJdEHHakUULu/VB1rLn1Ld/FgetMGYd/qWSQmSa0 /AemS32pfa7piLeLkg9z6UmQtz0W7uQ2cZx0A9BVzR7cAea6j2rPqX0L99KRat5A6Dk1wOoKZ52a YfMORTYRLujiGWEq6/NWza2yKQVHNdOHerRy4laJo6TTnbbtb8KuM3Fdh5z3OJjbmpt3FaMxAtUZ agBN1GaQBzTwaAAms3VbjERUGsa07RsdeFpuUuY4jUjljWTKK4j02RE4IpJYFk6imQkVl0xWarsO mAEcUi0bNnZBR0rWtoguMCkUi21wI161mXuocEKaYXMS4u+pY/hVCSWSY4HT0pEmlouiSahdpEBl mOceleiwWcNjClvHgJH97Hc1EmVFFi3Czy7mwIl/WtJbjP7uLgd/apQ2VNVvtsBhiPzdK5S4nAuR nqOCaTGi9pcytPlU+XpmumtWII44rah8ZjiNIXRuWeNvvViQ/LXpJWPJbu7nCRvVkNxVsxBmqJmo EPiXca0YLMuOlJsuKuPlsSi5IrNuG8s4HWs5VEkbwoOTKsk+FJY4rC1K53k1xTk5O7PSpwVNWRzt 4cms+WpKICtSLTETQj5q0YeBSGiys23pUguGxQMq3E59ayrm4x3yaAKiRtO2WPHcmhruKFxFajzZ ScA44qRHoXhuMaLpxaUg6hcDLMf4F9KlhuDeXGASIl+8azZslYma68y48m1+7nFW5rtbRNhb5z1p iMKbUg0zuW4A4rPgb7VdKXOMmpA7HRbMS7nUYiUda0lkQOBngVrS+JGdbWLRt2bAx5BqeQ/LXpnj PQ4GJ+ashuK0MhWaoWcA0AaOmASMK7jRNPWYBmHyiuepO2x10qfcv6vYxCzYqoGK4HVYVTJrmb5l c6oaM5TUJ8EgGsG4kLNUHT0M64OaqMMikSRsuKbnFMRLG3zVehOaGNE445NNlnVFpDMu6uie9Vo1 8z5mOAOST2pDK91cNN+5tsrH3PrW54a06KxT7fdrlh/q1Pc+tJ6IUdZGvHPLezMcnBOWbsPap5r3 ylFtbdT1xUWNWzU0/Zbwlgfmx8zGsHWtRHmMqE59aAMyNifvHPc1f0gtPdqkY5JosJHeNci2tktY euPnNY+oXWZEVJNrZ9aun8SIq/CzodHuriIokhDIR1ronbKZr0o6o8ipoz//2Q==`,l1=` /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAsICAoIBwsKCQoNDAsNERwSEQ8PESIZGhQcKSQrKigk JyctMkA3LTA9MCcnOEw5PUNFSElIKzZPVU5GVEBHSEX/2wBDAQwNDREPESESEiFFLicuRUVFRUVF RUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUX/wAARCASwBLADASIA AhEBAxEB/8QAGwABAAIDAQEAAAAAAAAAAAAAAAEDAgQFBgf/xABDEAEAAgECBAMECQIDBgUFAQAA AQIDBBEFEiExE0FRBiJhcRQjMkJSgZGhsWLBJDNyFSVTY3OSNEPR4fAHFjWCokT/xAAYAQEAAwEA AAAAAAAAAAAAAAAAAQIDBP/EACARAQEBAQADAQEBAQEBAAAAAAABAhEDITFBEjJRIhP/2gAMAwEA AhEDEQA/APqYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAKNTq8OkxzfNkisQC8eb1XtRNbzXT4q7eU2nu0MntRq/D8StMccvW29ZmdvgjsTyvZjxOLj +s8WLxn8TFPXs6Oj9oct7c14rkxz22nrB2I49KOdTjelmszfmpMeUxv/AA28OqwZ4icWWtt/SUi4 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmdo3nsPNe0Pt Fh09Z0+DNWL7+9O/7A3eJcZppsV5raI27esvH6jX5ddM25p79Ilo59VbUZOe2Tm/PeGvfPfT2iKR PLv1+DO678XmW/a97U6TtOyzTbTF538/T9WjTNecm9a7126tqk3rSYxY5ta1plRZqZNXGjyZcPXl mZmsx+qjBrsuO16xM7eXRt04JrdTltk5OWJnfaWf0a2lty5MdZnfzSn+WOHiOutFpjHa9e8bQ2fp +alYy462pk7zXbuxjPesbRS0f6ZZV1ET1tErzXFLHo+A+1ddZf6NrI8PJHa1vN6iJi0bxMTHwfOa zhzd61v1846utwniM6DUdb3nBaNrVmd9vjC/ZVePYirBqMWppz4rxaPgtEAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAItaK1m09ojcHnvarjM8P0vh49+a/eY8ng9D h1fGM1rxjtGPfvbzdbjuTJxHX48cTPNltM/KsS9Dw7S49Jp6UpHaGe2vjz1y9J7LYK13vHWe7bj2 ex1tvM80ekuxW3RnW3Vm6P5jRx8H0+OYmMcb+bapo8GKPdpC6bQwtdHU8JpWkdJ/JweL6e23iU67 d4dubSqyVi9Zi0bwIs68XGp36TtEq7ZJmZmevzdbifCKWtbJinkt6eTgZPFw32t+sRurbWVzxs1y Rv6T8V1NZNPtfq0seTm+Kevr+SZuxXjvaPiV8N4viycto9HseG6+uu08W6Rkj7UPmFck1tE1nlmP Ld3eA8V8HVVi1pjq6Ma/pnqce/ERMTETHaUrKgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAADW19+TQ5p/p2bLS4v04Zmt5VjeQeJ4bjnLqsupv+Ka1+ERLv4reTmcNxcuC vy3l0qdI2hlr66sT02ot0ZV7qqrInruzrVZLGSZ37JjqgYTG0K5lbaFVhDT1Ub456RPweY4hixWi eSdpjvD1eWejz3FNHWYtkpvFo9EIseb3tS3SerOms22rfpPqZKzvvHSYUz70TExG6Gdbs2rljeJ/ Mx5L0vEzPaelnOi98c9J2bFNTFpit47+a+PVUvx9T9nOIfT+GV5p3yY/ds67wvsXqpxau+G09Lx+ r3TqrEAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADV4ljnLw3U0jvO O0fs2lWqyUw6XLkyfYrWZkHldBEV09eveG3Fq1mI3jd4vPrOIaid8G9MP3Y38k6fNrt/rMk9Ou8s tfXXn49rGWInuy8SO/k5Gl1E3rG/fzbOe94wTy99mbRvTrMOOvNfJWsesywniukrG/jU6fF43WYN TmtEeJtEQ06aSmK2+bNtEd+qfSO17unF9Hmvy1y13XWyVmN4tExLxVK8PmNq5NrT58zawam+m/yc 0Xj8NpRYSvQZ7xEOdqI3rPozxayNRXe0ct/ON03jmrKB5nV4q1yTO20Obmv4c+cx8HoeI6WZpNoj q83niYmYscU0r8aJ6T1n49zeJ+Meqm1drb9J+Kd5p136StGVem9l9TbHxLDFp7W7+sS+q1nesT6w +PcAzVjiGHftzQ+v4f8AJpv6On8jH9ZgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAABp8VrW/C9TW0ztOO3b5Nxp8VmI4bn37TWYB8f1HFtTfUfR9FWJmsdZ9I7MtJxDX5s d8ta1y0xzteaR2277rcuhycP12SceLxMeWNpjttHwlu8I0mfQ1y+D7k5YmJmY36T36Ka43z/AF1t cI1ds+qxVj7/AEej19PCw9HJ4NoK4OIU5Y35YmZdzVTGebVZabx5jJS+Tmns81rNLm1Wrzc9rVw4 Yibbem72mXTTS0w0M3BvEta1bWrM95ie5EanY87wXgNOL6XPfxraXLhra/W28bR/dzYzarBqJxRe bzE7Rt5vWU9n8mPHOGmS0Ypnea1naJb+k9ncNLR7u2y/WcxXO4TOoyUrN6zD0FaW5Y3hu49FiwUi KxCvLMR0hlW0jn6ukWw3iXjOJzbDlneOj3GaN6zDzfFOH+LE7SRGo83XNSZ2lbG2/WfdlvaT2cy6 rNFInlrv1mfJ37cK4PwTTxOoidRm2+/2/KFuyMp47XB4LivXiunrH2b2iH2qn2K/J8x4fGDNxTSZ 9Nh8OviRvTyfT6xtWI+DeXs9MNZubypASqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAOZx6/LoOWPvWiHTcf2hiZ0e8fc2mf1E5+vP/AEeuSd7RC2uKtI6QjHfeINTfwtPf Jvty9WPfbt/lucP03gxfJf7d/wBoReYpm97zaNeLb4Ims9Nt94auDjem1Wo5PFi1onylS+1o7l8V bxvtupjDMdNkYtXS1+Stt+m63xImEJ4xjHER2ZxMUjeUTO3VRmydBbjLJqPi08mbeVOXJPq1sl5Q Vbkz9+rRy35rxHqzmZlVEe/Ez5LRlW5iyfR6zffaIjq1OSNZps2a21rZInafSPJhxGMl9LStLRWM lorM/A4dkrWbYfLZC2W/7K6eubX6b4RzT+W76K8b7G6X62cu3Sten59nsm3j+OXz3/0ANGIAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0OIYfpOHPijvNNo+fdvtXJO18k/ /OwPFYbz2ls3jx8VqW6xMdWPEdP9D4lkx/dt79flLLHbkxTPwY6nt2512ORTRzE2x4/dpE7cvkme E4IrW3hRMxO8THRtU1FKWtvtvK2upx22rzRCtXkqzh2jtF7ZbT122b01ndnpuWuP3Z3+Ky20qDVv fauzVy3mejZzNK8dVjqi87KLRLYtXruqvXzkQp7Qoid88R6rcl+WGlW0/Sa22mfhCZOq2x082ix6 jkm822pO8VrPdr4dNObVeDo8XW3uzMbzK+mvxT7szE27cvnu9j7PcNjSaXx8mOIzZevbrEeic5tN +SZnpt8J4fHD9HXHO3PPW0x/DeBtJxx29vaAJQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAKNRim9Z5e89Nl4DzXtVh5babURHrSf7f3ec1+qnDorWrvvt5Pccb0n0zhmWk Rvevv1+cPE2rGTFNZU26PFfxwa5dVkjelI2772nZnX6bbrEUq3o0d678u8wmuDL2ittvVjXdneeK cGv4jpJ6U56+kS7+j118+GLXpakzHaWlp9NNY3tv+bbiYiNoQy1y30uyZJlrWmZnuym6q1iIJnop yW2Te8bdWnnypQqzZOadokiIpSZntWN5lrxki19vNRxrUeBwnNNd+fJEY6/OejXLn3Xe/wDp9wyn E8uo4lqqxblv7lJ26T6vpD5X7G8QycKzeBMbzMRM1/FH/wA/h9QwZ6ajDXLitvWzRgsAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAeL45w+dDrZvWv1OWd4+E+j2jX 12jx67TWw5Y6T2nzifU+rZ1y9eHwzDYxxEy18+DJodXfT5o96vafWPVbjyxDn1OOzHudbM0rt2UW iI69mVtRXZq5tREb9VUoy2iIlRbJ0UX1VZ6btTLrI7V6yk62M2oisT1c7JmtkttVMUyZp6x0beDS RWOvdKijDimvWd3G9pNRMfRcNfvZOb9Hpb0itJeP47k/3hgjaZnbaP1XxWW3T0movbNS0W645nbf 0nrMPpXs3xamoxdJiLbe/X1n8Uf3fKsOTw4jbaXo+EarJhtGTHMxeJ6xH7Sti9Zaj6x3HM4NxXFx DS1mtoi8dJrv2l011QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AGjxLhODieOIye7kr9m8d4eM4to9RwjPXFa0ZIvG9bR0fQXmPbDFvTTZPOJmEWS/V8bs9R43NxLL G8eFbePg1bajU5/s0l1ceKLx1hbjwRE9mOpx0y2uRTSZsm3PMw2aaKtIjo6kYo9EXpET0hVLXxYK xC6MZvyx1lFs0RHfaPiCnU12pLyHGNDbUajBekWma2npWN3p8+opa20e9LSyZLxExTlpM+vdOdcZ a9tPS8MyUvFrzWlI6727u1pYxYrbVmb7x+TQx6au3Nqcl7/0rcmW9axGnwZJj1novmxnZXV0fFp4 ZxLBPgTGK8xzXr5fOH0bFlpmxVyY7Rato3iYfNuG2x56Wrqa8s2jz+7Lu8O12bS6jkwzN6THNNI6 tvrN68Y4rxlx1vHa0bskAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAA4XtTTm0OKfTJ/aXdcL2pyRGjwU362yb7fkJz9eTxxyZJjyltRXzUZK7TFtl9Lbwy06YzrHwa+ fJFd/wCVt8m0bQ0eS2qzcm+1K/an+zNZFL5M1pjFXeI72ky48eGnPkvNp27+TPU6nHpMfLXaIjpE erk5dRMxOfN1mPeisfshW1ne1a1577Y6x5R3U0zze31FOWI6ze0byU098kRlzbxM9qrMlPDpyRMR Md5Vt/Ihp5898mWZm1pjftE91uCt7fCI7dWeHDEW3t723l6rslqxWZnasR+SYhFbzhnfxJ2jyeq9 lcGXWZcmW0zWKxHLaI7794eJx5fpfEKabT8t8l5isddo3l9S4VjrwrRUwzSJt3tav3pdOL6Y6dXD j8HFWm+/KsU4NRXPvtWazHquWVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAa+fXYNP9u8b+kdZBsDkZOO135cWOZn4y5Wu4xqctbe9y19Kp4njt6vi+PDm8DFMWybbzPlV 5PiGtz67UxbNbeKTtWIjaIXYpnwuaftT5tXJT3vmi1pMsrU5qIrG1V1a+5DCa7b9GFbRr5J6Wnbt Cu+Wmk0m8956z8ZWZNorbfzcbX5rZslazPux3hUt41NTntktObJ13+zX1bek01r4/HzVm0bxPXy/ +bNfDgjVa2uOY92kdfg6ufJOKvLXtttVVSqbcta2vM7zXtHpLQy5ZtMd+vWd+7Zy3mdJHXra3f0c vUarw7zFY5rT2hH1Lavnrgx81p3U49Pk4nE5L35MO/StfNRXR5tXnrS8W67WvfyiPSPi7uLHFK1p jrtSsbR5Lc4RzsXBaYreP4l45esRD2HD9fnw6evvWvO3Tfr0aGk0U55ra0TFInv6uzgrXFXlx0i0 77RPlC83Yj+JW7oddqr6vHzTTw9/f6dod+L1t9m0T8pcbFSmPHER3892W0zPuz+jSbVvidkcqmfP Sel7bekrI4n4dZnPWIrHeYnZee2Wpy8dEaml4npNZblw5qzb8M9JbYgAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAABEzFYmZnaI7yCXL1XGa0jJXT0571nbee27DiXEprp8nhbxG20W8 5cbD0ikfnKO+urTPvjoZdXqctdsmTaPSvRpWmsdZ6yztfaGplvv3lWW1tyRlz1x0vkn7Vo5atTNe Y0+1o79V2KsZsvX7Ne5mwxnyTNvsx2iGneM/rCdRSuOsTasTt5kRFtpjqmOH4t4nk7estiMNa97R Hwhna0iuKTEdmGWa4672nZtRele1N59Zlq6vLOSsYorEc07qcW65euzRvtXvPZy52naZ7ujr6fXV rWdukREK8+njHgmZmPc67bq6ivVWhxxgxZLztNrT1mZ/SP4VZs0zaOvfp84WUtNsXLvtv3699+rU z7+Jtt5qURqMnPpctaR1rMSw4ZoK57eNk6xHaJRh97Ltt7lo5Z+L1HAPZvVauZ2nFTSzMTzeJEz8 to6xPfvsZntPZ9rXxabmxzefdrv0j1dXh/BcmstW1qxTHHasR3+b0GPhGl+kWmd64dNEVjf73T7X y8vy+Ddx6O3iRakxTH5RXrMw1/lX+3Itw2MFIraN48qRHdZi0cUjmmPen9noox1iO0fNzdXEYrTt stcmd9aX0bJ+HePmiKTitO8TMLZ1cVjrMfqpz6ys4pjfrPRWZ9rXXptUit6zO+23VyaRHEc05L1/ w9J9ys/en1ljqdVbwYw452tlnl3jyjzbmmiMeKtYjpEbLeTXPUU8ee/+qjJpsV5rbkrFqzE1tEbT DpYNbW21Mnu29fKWna0KbqTdjXXjld0cvQ63ltGHNPSfs2n+HUbS9c2s2UASqAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAOVxPWe99HpP8ArmP4b+r1EabT3yT3iOkesvMVtN7za07zad5l XV5GmM9vVfEstvDx0jtaVVMlq+UJ18b5cMRvPeSuK87bUt+i2Z3PtG7zXpjkzXt6R+TXyTMzvM7t ydHqZ+zhv1+Cv/ZuqvPTHMfOYaTMil1a1K2vHSLTELq2v+KWzThGo84rH5rq8JzedqR+ZeI7WnOS 34pYTafWXR/2Pln/AMyrKOCWnvmiPyR6O1y9585lhWJvl557Q6eo4T4dYiMvW3b3UanhldHpJtGX e09unmjsT7eb1l4trI2t0hsZfrdNO0bzy+nzU20/+NmkzO9esz+TZxWis9dttvPv+Tn21jjaW8zn 26bTG3mp1M/Wzv3t0jyWXiKZJmsTERaZhXXDbNl8WaztWenxZLstPp5pau8frDtVrNMM5cfTfpMf 3aunxxbes9d/R09Dp8ebJi09ptFr3jtt2WyrW9wy1Jx132mK+Xq9PotT0iIU19ntLtExa3T47T+q 6nBaYvsZstZ+cT/LeMnUi0TXffo1s2m8Ws2/OIMWk5Jib5L328rS2t94Sh5TV4ppklpW6PT6rh+P NbebTHyas8E081mZy5P2W6OFhjxNTE/hr/LoRO0Kvo9dPqctKzMxEx1la5t3tdnjnMs4noievcrO yZjeFF1OSnNV0OG62cn1GWffj7Mz5w05joovzY7xes7TE7w0xrjPeex6Ua+j1UarBFu1o6Wj0lsN 3JfQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACrU5o0+nvlt92P3BxuM6nxNRGCs+7Tv8 2hToxm1r3m9utrTvMsonqyt7XTmcja0u3O6FMfi5t/u0/lzdJM81p9O3zdvHTwsUR5+bfPqOfX1h dqV+3O7bs1+T31oqmI3TEM4rvCdkDGIIhlFd2daboS0NXG2bD6bufxXU1vlmu/u4us/N0+L1tTSx kr9qk7w89j1FNZMV3jxLzvaJ8mer+LSOZqK2xZotbvljfr/89U453rXt9lse081xZtNjx7TGKu0t DHlrevSevaN5Y6+tJ8c7VRNMt63n3ub+6/R54rERMztDYy4a5omclYmfxKcenrjtHLvtPrCnVmdb eFe3JXmjy6eS/DrMuLVYsta9Mdt++6qLxO+0dEc8UmInr18iUfReHcXrqccb9Z27Q61Lb13eJ9nc 1Z35rTvE9avY4bTkpG8xEfB05vYxqybc07R281naGMREdoT5JQqy9mply7Q3bV3iXG1eXw7TWSka c258t7+tpT5/BjT7MfHqndz12Z+M4lMMKyziUJJiN1WSu9fku23RaOgKNJqbaTU1t9yelo+D0cTE xEx1iXmM1Nt3W4PqvFweDaffx9vjDbGvxz+TP66QDRiAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAOJxzU73rp6z296zsZMkYsdr2naKxvLyObNOfNfJbvad1dXkaeOdpvsc2yuZVzfbfqybutwu s5s8R92J3dvJb3tnO4HSMegtmt3nfZvYp8SZl0z45NfSK7onH1bNcfRFqnUKJr0Y7dVtq7prjEsK 0XVpEM6028mW20IHK41aPo3J6zs4ODhdcvPnvExFevNXpMOrxi/PlrTee7PLX6Pwa09uaNlKtHg9 dM3z5d7ReOu02nu0JzZMfblrv5R5uvrcdImZ26T1mYhxs1Os7RH93PZ7axuafNfLitvbaYU3yZYt PXs9NwHhui1HBa5LVicsb81onrEuVqNNSuS8Y67dZ6xPZa59Il9uX41vEitImZme3q2Kxbxora0T Md/ROSa4Ztkj7c9OafL5LuGYubmyX3iu/TfbdSfVnpvZLT/XZK233+Mbbva1xRXyiPk8pwbH4N6T adq5a71n0tD1WDL4tPe6Xr0tDpz8YVnJHWEXYxbqlBedoef4tW0XraO09HdyztSZcbUz43C+ee9b SVMaeOfqq7+jGckQ1Yz7+7v2RN/WXPXZPjci2+2yyJaVMuy+uSJlA2d+pNoVRbeDcSxyTE+TDDlt pdRXLTynrHrDOyiyZeVFnY9TjvXJjres71tG8MnJ4Nqt4tp7T1jrV1nRL1x2cvABKAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAHJ49qfD09cNZ97JPX5PPw2uI6j6Vrsl/ux7tfk1mWr7dOM8iLdm vfebREefRsWldw7SxqNbWbR7lPesrn3Vteo7dYjDpMGCvfbeXQ0uLlxRLRxROfUc34p6fCHYrXlr EejqrjY8uzCYW7MZjdVKqK9VlaxCYrsnYExBMRMJRPZA8/xPHtmpP9W2xx76vhWOInvt/C7ike7N vwzE9kcapGfhlevTaFbFo8RqJ5vy8/RoW09ek0msxHfp3dzNoLzp4zUmZpMbT8HJyYJi20X2n0lh ZY1li/RaidBF4w2mK3jrHaFGp1lN+tptPp5IjBkid5mIp16TKu0abBPv33vPlM7z+iPdFNcWXU5I tkrNce/b1W5db1nTaf3ax9q0fxDW1ebNk2phty1mOu09VOm8W19orEz23j1TwfSeERFuEYMddptW d43dvBn21eKJ75KbW+cf/JcTgMxXTb3nbljz+TpcPmc2uyZO1KRtVtGVdi0bx07qJnllsRO6rNTe N4XVamsy8mnvPwc3R2jPwe8TPbdlxXNOPSZfhWWpwO85OFzv57qrODkzeHntSe8Sn6Rv0a3EZ218 8nXekfr1a0ZLVnqx19dWb6demXybOO7lYMvNMdW9S/VVLo0us7tPHdtUtEwJiZU3jq2Jhham8CVG PNODNTJXvWd3qcWSubFXJWd4tG8PK3pPd1OB6veLaa89Y61/u2xfxh5c/rsgNHOAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAANLimq+i6O0xPv392rdeZ4rq/pOqnlnelOkIt5F8Z7Wj27I2I6sb25YY V1ImY3dbQ08LRc23vZp2j5OJG+XJWle9p2h6HHtbJXFT7OOIpX+7TxT31j5rycdTh+Dpz+XaG/sw w18PHWseULN2trBE9UcrJKBhFU7JAQi0dEomegNDUYovM7x3jb5tO1ZvpbaTLtzRExWfWPJ08kbT Ex5NXWYYyV5omYtHWJieyeDzuizfRs19Jn6TM7Ru1uMcJxZqTkw+5f4ebqa7SV1MR4tdrx2vEfy1 axqsNOTLjnLXytVXi3Xj8+nmsxTLM16d5npPyUzpekTtSK+U7vS6vQ/SYmK1vWPS1HOn2dvvvvE/ tDO5XlcO+LbfHSd/W3o6/BdDOXPTnj3Kz38rS6Wm4FNrRyRzTH3p6RH/AKvR8L4dXSzE3jmtHn5I mbfqLV+m4dbLSsZInHjr3iI6zLpYaxS01rHuxHRHiT9mv6s67Vj1aqL6326MrWiYa+/Q54BxPaGe XRZpj8MquB4+Xg8zPnB7SX30to379GxpK1xcHiKz5IS8xr8PLPixH2bftLTy05o6dHYyVjLhy0t1 izjZa3pMVv3iO/qz1G2L+NbSajbNyW7xLsY8kTDz+fJXFqKZN4iZnafi6WHL0iYlStI7OO+7axW2 crFl7dW9jvE9ULN+J3ZbdFGOy+AYWpEqN7afNXLj+1Wd23KrJVMvCzseh0+auow1yU7WhY4fCdV4 OadPefcvPuz6S7jol649Tl4AJVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAV581NPhtkvO0R+4NPi2 r8DB4dJ9+/7Q83Po2NTqLanNbLfvPaPSFDHV66sZ5ET0hRknyW2lTtMyouz0c8usx2n7s7vScKwx zc1vu/y85p+maJh6Th+SOWeveXR4/wDLm8v+nX5mUWa9bbrInolmu5jdTNkxYFk2Isr3TuCzeGMz +THdEyDDJO9Ja823rt2XWnya946pGvktDXta0ztWu/ybvLE9dkcoOf4GbJPWK1j49VmLh9JtE33v Mevb9G7WsW8l1ccREISophiJ2jpDYpijbaOjOuOJ8ujOdqxsgVcsUjaETYvbaFFrgu5lVsm0yUtu ryg43H5m+GIj1XcJzePoL4pnrWGtxmfchr8JvfHS1622if3QljzTTLes+qrNjrkiYtCzPMxnm095 YZJ6boS5teB49Tqscza97VtvWvlv8V/FOF34RrIxTM2xXjelp/eHoeA6XnzReY3ivX/0dfivDcfE 9HbDbaLx1pb0lOs+jO7K8Lis3cN+0NKcd9PmthzV5clJ2mF9J9GHHVL108dm1SznYr/Ft0tuhLb8 mNohFbMhLWy0mJ3rPXvDvcO1karBG8/WV6Wj+7kWrvDDBlvpdRGSnbzj1hpjX4z8mOx6UYYstc2O uSk71tG7Ns5AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACZ2jeXneJ62dVl5KT9VTt8Z9W9xbWclPo+O fft9qfSHEU1pv48ftYST23ZTDC/p0YtlVuvVjMbM5+LCZjYGWGdrTPxiHY4ffaf3cjTxz1v6xMS6 Olty2iXVj/Dk8n+ndrkhnGRo1v8AFdW3RCrZ5uiYsqrboncSu508yjmZRYQt50TfowYTbYGVrKrT uTZjvukQnYhMIGVY2ZxPVWyrHVCWzXpVXkt3TE7Va+W4K7X3jv1auTNy3jdba0RZpamfroQN7Hk3 6wr1GTaN2OOJiu6Mu98NvgDi8Wy74d/yZ8PiPAiO2zU4nb6qIn1bugjfFE/ASp1ke9u15mbbRDZ1 Mb823kx0Ontn1OOkedoJCvT8I03gaKsz9q/WW+isRWsVjtHRKyrhe0XCfpWL6Vgr9fjjrEfeh5fF feH0V5Dj3DPoOo+k4a/U5J6xH3ZZ7z3228evytOk7NvFbo0cdols47bSybt7HbddHVqUs2aW3Qnq xVeu8LILR3SlZw3V/R8nhXn6u0/pLuPMXjeHT4Zruf6jLPvR9mZ8/g1xrvpz+TH7HUAaMAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAABRq9VXSYJyW79qx6yvmdo3l5viGs+maqYrO+OnSvx+KLeLZz2te1rZL2v ed7WneZYWnZl5K72YV1xEyxmeqJljzIEWlVkszvbZp5soN3h2SJz3pP3odCnuWmPRxuERfJrZmtZ mtY96fR28kbX3dXj/wAuTyf6bmK+9YX1s0cNtm3Sd4LFY2K23W1s16StiUJW7bp22RW3RluBuruz mWEgrmCGWyNkoExKE1QlPmsqRDKeyBjaejWy2W3ttDUyz1QKslvehVqKTNosyyTvELabXptIJpaP B39Ia2mz+JGpr51jdZefDx2hzuHZObNq58poJaGtjxJ2+LoaKP8ADRPo5+T3skx5OhpOmC0fBNQ0 5yTbn+bt8A0u9raiY6RHLVwY62mI6zMvaaHBGn0mPHt1iN5+aYVsACBXqMFNTgviyxvW0bSsAeE1 mkvw7V2w5Ote9besJx2er4rw2nEdNNekZa9aW9JeQjnxZLYskTW9Z2mJY7zz26fHrrdpbZsY7NGt mxjvso1b9NmUwpx33XRO4K7VUTE1nmrvEx1bVo2VWiJE/XY4frY1WPlt0y17x6/FuPM0m+HJGTHO 1qu9pNVXVYt46Xj7VfRtnXXL5MfzexsALsgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHM4jxOMFJphmJv529Dq ZLfjDjPEIx450+K3v2+1MeUOHSOWFc3nJkmZnf4yujpVlqunOeFpV2nctLCZUXRM7MJtsWlRkv3Q ky5NmpWt9RnrixVm17TtEQnJabXisRMzPSIew9n+CRoccajURvqLx5/chfOest642OGcIpoOG2w7 ROW9d72+LQvXevyejcPUU5M+SvpLeOataraw2a0dLbLqTtK1G3Es4lVWWUSoldFtmcXUbpidgXzK GEW3TuCUSncnsDFMMLSms9EC6J6FpVzbZE5ALy0809ZbFr9GtfrEoFMzuuwz0Ueey3HbaBLDXe7i tMOfwWnP9I+NZbuttvhs1uBRtXPb4SDm3iIvf57N7Dbl0VrS5+XrltEd+Z1Jx7cNms9N4TURRw3T +PrcO3WszEvZOD7P6aYiMlvu16S7y1QAIAABxOPcLnUY/pWCv1tI96I+9DtgmXl68Biy7/NtUu3+ O8HnFa2s0tfd75KR5fFyMWTdhrPHVnX9R0cd21S3Rzsdm1iuqs256wrmGcT0RYSx5d047X02SMmO esd49YRE9WcdSXhZ2O1p89NRji9J+cei1xMc3wXi+KZj1j1dTTaqmor06WjvWW+ddcu8XK8BZmAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAMMmWmKu952UZ9XFZmuP3revlDTtzWnmvO8q3XGmfHb9ZanV3yxtWeWn7y4es vPNtDqZJ6Ts5mppvdl/XXRMyfGvSNlu/RVvtOzLfoipLT1VTKbSpvfogRkvtDVyZOhkyvQcA4Dzz XV6yvTvTHMfvK+c9U3rkW+zvA/D21urr789cdZ8vi9KDb45rejl8Rry6iJ/FV1HP4vXbBTJEfYt1 +UpiHM295bXsqrO9l8QkZ0lZEqqLeyBZHZLGvZkhIndADKJ3TMoqWQMZ6pjsxll2jsCLSrmU2lFY 36gieyu0LJk3jbsga0wdqzK20QpyztQGprL/AFMrOE05NLkt6qdVWZxNrSe5o9vWBLiUjnzXn0vL q555dHt8HOwV928/1z/LpzXxbYccRvzTB+jucOwxh0dI22mY3ltIrHLWIjyjZKyoAAAAACJiJjaY 3iXleM8InR5J1GniZw2n3oj7s/8Ao9Wi9a3rNbRE1mNpifNFnVs65XhcWTdt47bnFuF24dm8TFEz p7T0/pn0a+HJux1OOrOux08d1ndqY7tillVkzExLOk7yd4YxGwluViJhE45raL0na0dtlWO0+bZr 1TKi+2zptZGTamT3b/tLacvJjiY3XaTWdYxZZ6/dtPm1zrv1z78fPcbwC7EAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABhkyV xUm152iAZWtFazNp2iGhm1Vss8uP3aevnKrNntqLdelI7VRHRnrX/HRjx/tZREVjZXeybW6KbWZt pCZ6S08tN7Nmbb7zCrJtyoS5145bSx5mWafelr3tsKmS/o08uXyhlly7RPV2+AcBnPNdZrK+53pS fP4ytnPVda4y4BwHxOXV6uvu96Unz+MvVxG0bQRG0bR2G0nHLb2gCUDX12LxtFmpHeazt82wT1gH mMN4tWs+rcr2aEV8DU5sM/cvO3yb+O0csLUTSdrLphRE8tlkZI7Atr2ZMazDJVKTYSCawi7Ksq7z 1QERvLK3ZGPrKbyCrbdnMcsbeaa18/RhvvM7oGEwTG0JmYYTIML22a2e28xELM19oURPNO4lOem+ n3ZY5+prVnMc2GYU4/L4A0a15cNf6rz/AC6fC6+NxCPOuOu/5tHJTbHj+F5/l1+BYumXJMd9o3/d MRXYASgAAAAAAABhlxUz4rY8lYtS0bTEvH8R4ffhmo6bzhtPu29Pg9mq1Gnx6rDbFmrzVsizq2df zXkMWTeIbNL7tbXaHLwzUctvexWn3bmPL8WFnHVL326VZ91MfFVjvvVlz79kLrcf2m7j7bNHH3bl J2SirLQoy4t1++7G0dBC/RanxI8PJPv18/WG241+alovSdrV6w6mDNGfFF4/OPSW2b1zeTPL1aAs zAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAVZ9RXBTe3WZ7R6iZOpzZq4ac1p+UermZMl89+a/byj0Ra9815ted59PQ32hlrXXRjH DpCLX6ML5NlNsm/ZRqstfdXzbsZt06sLZNvNB1Za8RDWyZdo7q8udq5Mu/mIMt4md2lmy7JzZuWJ dHgfBL8RvGo1MTXTxPSPx/8AstJ1XWpIs4BwSdbeNVqq/URPu0n73/s9hEREbRG0QUpWlYrWIisR tER5JbSccur2gCUAAAAPM8Sry8Uyz67fwuxbzVPGsE49XGbvF42V4M0TEL33ERnktsxpk3sumK2j admFdPFZ33VS2Mdui2J3UU6LYlFSsN2O5NkCyJ6K7T1TEsbAsxdpReerKkTFGMxvYEz0rsqtbbpC b2VT1QEzuwtbaGUxspuJU3neWdKoiu8rq12gCI92YatLcublnzbEz1aOptyZqTuDHLfxN6R0+t5X qdJhjBp6UiPLeXl9NSMnEKxHa1+bb8nrlvxUAAAAAAAAAAABTqtNj1eC2LLXeto/R43VabJw/VTh ydY+7b1h7ho8V4dXiGlmvbJXrS3xRZ1fGv5rzeHN02bEW3cys3xZJx5ImtqztMS3MeTeGFjqlb2O 8btql3NpbZtYsnSBLeiWfdTjtutid+ghherHS5p0+f3vsX6T8Fkw181d4lMvEWdnHaGnw/UeNh5L T7+PpPxbjdyWcvAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAo1Oprgr63ntAmTqdRqK4K9etp7Q5d7Wy2m953lNrWyWm953mVd77R0 Za1104xxlN9lV8qnJl2a9s3xUXX2ybsJyRDWtl3YWydEC+2VRkzeW6q+T4tbJm+KRdfK1cmWZnlr vNp7RC/R6HU8SycmCk7ed57Q9ZwvgOn4fEXtHi5/O9o7fJaZ6z1uRyOEezVstq6jiEbV71xevzer rWtKxWsRFY6REeSRrJxz22gCUAAAAAANbX6aNVpL0npMRvWfSXlKamsRMVvXm+EvZXjmpaPWHzfL oNRjzXicfWJ8phfPxFejx72x7xMzK+sXiNoiXlq+Pi6fWV/VfTNqfLJl/WTg9Pji8R70LqvMV1Gq j/zcv6yz+lanzzZP1lWpelTET6S81Gp1P/Gyf90s412rjtnyfqql6asREdWM9+jz9eJ6yP8Az7uh odZqMt458tpB1JvEViI3/RhzRt13/R1MNaziiZiJn5K9ZNceKZiIiQcu/WekT+iYrWI3lzdTrs+8 8uW0fJzcur1Np/zsn6g79phVaIeetqNR/wAXJ/3SwnUaj/i5P+6UD0ldonum161h5mNRqP8Ai5P1 lNtRqJjacuT9Qd22WN5aGeZyZd/KHJy59RHbLf8AVq31Gp/4uT9ZEvS8Lr/vSs2npzRtL1z53wK+ oza/HW2XJNd99pmX0Rb8VAAAAAAAAAAAAAAcHj/C5yV+l4I9+v24jzj1cLFk8nu5jeNpeW41wmdL knU6ev1Vp96sfdn/ANFdTrXG+eq1q5F2LLtbZoY8m8d11bbSydErsYsm+zZrO/zcnBm226uhiyRK EtrvCrJDOJTeu8A1MWX6Lqq5N/dnpb5O5ExMbx2cPNTeJb/DM/iYPDtPvY+nzhri/jDy5/W6AuwA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAa2p1UYo5adbz+xbxMlvqJ1OqjDHLXree0ejmzNrWm953tPmTPWbWneZ7yoy5YhjrXXTjH8s75N mtkyxt0VZM2/m175N1V03yTKubMLXVXybeYLLX2VXy7eam+b0bOg4VquJW+rry4/O9uyZOq3UjVm 9r25axMzPaIdvhns1kzbZddM0p5Y47z8/R2+HcF03Doi1a8+Xzvbv+TotJnjDXkt+K8ODHp8cY8N IpSO0RCwF2YAAAAAAAAACvUZYw6fJkntWN3k8dfHz2vLucdz8mkjFE9bz1+UOZosX1UzPm0nqI/W MYo9FlcPNklfFGeH/NshLGun+Cz6PtHZtVZWlRLS+jxPkRpIn7rdoupHTdA5s6SI+7H6Mfo+32Y2 +To3neSIiZ7A0IjPXpXLePlMotGW3272t85datKzHZjbTVnsDj+FG/2Y/RlGP4R+jo20u7H6N1Ql o+H8I/REY957R+jpfReiK6eOYHLtj2tttH6KrY/6Y/R2c+kjeJiFVtLG24hxpw7/AHY/RRkw9O37 O99Hrt1YX0tfOBLjcGp4XF8c+u8fs9c4dcVcGemSI61nd3IneN1orQAAAAAAAAAAAAABFqxes1tE TE9JiUgPKcX4RbRXnNgiZwWnrH4XPi28PdXpW9JraImsxtMS8pxXhF9DecuGJtgmf+1TWW2N/la1 L7N7T5e3Vy6W3hsYcvLbqzbO9jvvCzvDR0+XeO7crO6FmGSvRThy/RtVXJ92elvk2rRvDUzU7pl4 izsd2J3jeBpcNz+Lg5LT7+Pp+Xk3W7js5eAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADs0NTrN96Yp6edkW8Wzm6+LNTq4pvTHO9vOfRoWtt 1mes95YWvs1s2fZldddOczLPLn2ju0MmebT3YZc2/mpm3qqllN1drsbZIhr3yzvtHf4AsvlYYseb V5Yx4KTe0+UQ6nDvZ3UazbJqd8OKeu33peq0eh0+hxcmnxxWPOfOfm0mP+steT/ji8N9mKY9suum L37+HHaPm9DSlaVitKxWsdohI0Y22gAgAAAAAAAAAABXnyRhw3yT92Nwef4xm8bVzET0rPJH5d12 CvLhho3rN9RWs9Z23n5y6O21YhrVYbdGOCfrrLPJRpv863zVS6FS09SvZj3lVZZRdPSqmnSWdrIE ebOkK4ldTsgW1WKqd1oMZhEVZyRAImOjGI6rJ7IiATNd46qL02bHkiaxaoNGY2n4ImPgtyV2n0Vo Gvlx7x2beiyTk08RPevSVUxux00+Fn2n7N+n5rRFb4AAAAAAAAAAAAAAACLVres1tETWekxKQHlu L8InR2nPp43wz3j8P/s5dLveWrFqzW0bxPeJeV4xwmdFec+CJnDM9Y/CrY1xv8qvTZ+WYdbDk5oh 5zHk283U0eo3jaZZ2N5XYjrCnLSJhOK+8d1kxvCqzSwZvousrb7k9LfJ3nB1OLeJdLhufx9LEWn3 6e7LXN9Ofy5/W4AuxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAETaKxMzO0Qi9646Ta07RDmZ9VbPbaOlI7Qi3i+c3TPUaqcu9adKfy0722ZXvFa9 XO1OrjrESxt66ZJmcjPUanlidmhkzTZVfLN5VWvsC2b7R3U3yqrZZtO1esz2h2+F+zWTUcuXXTNM feKR3n5+iZLVbqRzNJo9TxHLyaekz62ntD1fDOA6fQbZL7Zc/wCKY6R8odLBgxabFGPDSKUjyiFj SZkYa3aALKAAAAAAAAAAAAAADQ4pl2pTFH3p3n5Q33E12Tn1eSfKscsLZ+orS00eJqbW+Lfnu1tF XaJnZsz3WpCfsyp00fWSvmPdVYOmSUDd8kR3InoQosy7JmUX7MdwZ17ro7KKT1XRPRAsrO0rYndr 79V1ZBaQiJ6JgCSIJASwrO07MpV2nqBlrv1a1o2bf2qtfLXaQUTO0sb05o3jv3ZXhjS20xEphW5h yeJjjf7UdJWNKLziyRePsz0lux1SgAQAAAAAAAAAAAAAADG9K5KTS8Rato2mJZAPIcU4ZbQZuekT OC3afT4NXFkmlntc2GmoxWx5K71tG0vHa/RX0GpmlutJ61t6wrY2xr8dXS5uesN+tt4ef0eaa223 2dnHk3juyreM81OaFGiy/RtZET9jJ7s/2bdutd2jqKeic3iNTsd8a2h1H0jTVtP2o6W+bZbOO+gA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABje9cdJt adohGTLXFTmvO0fy52bJfU23t0pHaqLeL5xdK9Rnvqb+cUjtCi94xxvK3JetKuHrdZvaa1ljb10y cnIs1Wt3naJc++TmVWvMz1YWybfMGdsm3eWek0mo4jm8PT0mfW3lDf4V7P5tdMZdRviwfvZ6/TaX DpMMYsFIpWPTzXmf+steT8jn8L4Dp+HxF77Zc/4pjpHydYGjC3oAAAAAAAAAAAAAAAAADG9opS1p 7RG7zszN6WtPe0zLua+3Joss/wBOzhzG2OsL5+IrY09dsSyYRijbHEMvOChb7KjF0yS2LQ169Mso S24noyrPVXWejNVKbTuw3T3REdQWU6LYlVvsyiUDPfqupPRr79VuOQX1lZEqoZxIMksd0gT2VT0l bPZVbuCaW8i8bwr32WxbcGnkjaZa9p2ndv5qbw5+aNugLItF6TEtvTX5sMb969HMpfazc0d9stqe vVZDdAQAAAAAAAAAAAAAAAADV1+iprtPOO/2u9bektoB4TJTJpNRbHkja1Z6uto8viVht+0HDvpG H6Tjj6zHHvbecONw7Ltfkmeqmo6Ma69DXbbZTkr1mGWO3RneOaGbZRoM30fVzSelMnT83aef1FZ7 x3h1tBqfpGnjmn369LNc3sc3kzy9bQCzIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAa+q1dNNXr7157VhGp1Xh70x+9f9ocy283m1p5rz3mVbrjXHjt91lz 5c9+fJ1nyjyhdM8lZlOOIiqrUXikd+kMreunnI5XEdX4dZiZcG+XmtNl/F83PeeWWHDOGanieSKY q+5H2rz2hMzWd1Iqx1yajJXHhrNrW6REeb1nCPZumn2z62Ivl7xTyr/6uhwzhGn4Zj2xxzZJ+1kn vLoNJnjHW7TbbsAszAAAAAAAAAAAAAAAAAAAAaPFrbaSK/itEOXt0rDf4xb/ACa/GZacRvaF58Q2 IjasQnzPIhCU92tMbZGzHmotG10C6nZkwpPRmipIllEbMIZIE7solgmJBnCyk9VMM6z1BtVllEqK z0WRILYlluriWcSDJVbusV27gwInaSWM9ECyZ3hqamnSWxFmOSOaqRx725bNnSZNs9J+OynVY+WZ YYr7TE+nVaIr0Ais81Yn1hKAAAAAAAAAAAAAAAAAABExvG09peU4nov9n66L0j6q/WPg9Y1OJaON ZpL0+9HWs/EWzeVz9PbmrEtnyc3h9reHy26TWdnSr2YX6657ijLXpLX0+onSamL/AHJ6W+Tbv2aW ekTv16JzeI1Ox6KJiYiY7Slz+E6jxdN4dp3vj6fl5Og2clnKACAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACZ2jeQRMxEbzO0Q08uqtkma4ulfO3r8lefUePMxWf cjy9WvlzVxV6T1Z61/x0Y8f7Wc7Ur1lqVy+LqOWJ2hp6rXddon5rOF1tfmz5OkT0qzb8dWbxjp1c biuuilJ5Z6r+IcQrixzEy8zl1E6rNt1tMztFY81sztU1eRucN4ffi2p5esRM72n0h7rS6XFo8FcO CkVpX082nwXh3+z9FWLxHi36328vg6TZyW9ABAAAAAAAAAAAAAAAAAAAAAADj8Unm1tK/hqppHvw y1k8/EMk+m0GOPeafiFpCZYwolnXspvHvLa9mF46gmnZmwozRUiUCBKYYsoBLOFbKAX0llEqqyzi QXRLOJVRLOOwLIljZMEgrlhKyYYTAK5nZPN0RZjugUanHzVlz6xtLq361c+9eXItPpXX0dubTU+E bL2lw2++O1fSW6m/VYAISAAAAAAAAAAAAAAAAAp1GbwcfTreelYEydcuMcRrM/L9nnlsV6wqpi2r tv133mfWVkRyRtEdGFva7MzkYZNoamWN4bV4mYa9qztKIujhVppxGI8r1mJegeZpknBqKZY+7L0t LRekWrO8TG8Ns/HJ5ZypAWZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAADS12fp4VJ6z9qVuq1HgUiI+3bpDl589cOKZmevqprXPTbx477rDJlrhr1nq4+s182tMRP RqaziXiZJrWekNG17ZbxWJ336M5LXRbI3dLTJrs07RMY6fan1dHLrowY+X7MVjt6N3R6Kul0EbWm s7bz8Z+LnabQX43r7Y53php/mXj+Dnv0f1JO1x/8ZxbUzj02O15mfLtD13AvZqnDds+pmMmo26el XX0Wh0/D8EYtNjilY7+s/NstpOOTW7QBKgAAAAAAAAAAAAAAAAAAAAAADG88tLW9I3BwJtz6nNf1 vK/DHVqYJ3pzT5y3MPZeojOWMQylEKpTVjZnDCwkqzYQyRRICATCITAJZQxhMAshnEq4ZQC2srKq qrIBZCWNZZgwswmFloVyCu0dFcx1WyrtCBhv5NTPHXds2U5o3hIz4ffbPt+KHUcTSW5c9Jme0u2v VYAKpAAAAAAAAAAAAAAAAYZctcVOa35R6tLrltN795/YvknNqrfhpPLH92V5isd9mWq6fHjk6rn0 ZxG8KK5Jm/wbVZiYZtqrmkqL023bkxvCiY3lJHNyRG81mHS4Rn5sNsNp64+3yaWaNrzOzHBl+i6q mT7s9J+S+ay8mex6EIneN47SNXKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAImYiJme0JafEs3h6fkidrZOn5eaLeJk7eOdm1Hi2vmtPTry/CHmOJcUvmvOPF1n09Pm 6HF9ZGm01qxO3R5vSY7XwzmzTy47zzTEd7en5Mfvt2/PURWdo3tvPrPlKymbktFqTtMTvHzbOLDG f63JXbFX7FdnoODcDprZpq9TjiMMTvSn4vj8l5fxnrk91saPSa7i2hpOfbTVt5x1m0fLydzR6PDo dPGHBXasd585n1lsRERG0dIF5OOe6tAEqgAAAAAAAAAAAAAAAAAAAAAAADX11+TRZrf0y2Gjxe22 gtH4piP3TPpXKwxtjhuYo9xq442iIblI2pC1RET2ILd9kxCqRjZmwlCSEohIJAQAAJZISDKGUd2M MoBnVbVVCyAWVWeSuqyOwIlXZZKue4MJV2WWYT2QKbKL9YlfdRdIo35b7/Hd3KTzUrPrDh27uxpb c2mpPwX/ABX9XAKpAAAAAAAAAAAAAACekTIp1eTwtJmv+GkyJn1oafeazbfpMzLR4jq/o8b823zX 6XNF8ERCvTcNpxLV5LauvPhx9Irv3lhztdtv8TtaWLicXrt03jzjzb2k1nid56ty3s/w+a7Uwzjn 1raejlarhmbhl/FpbxMO/fzj5p/ixSeXOvTtRfeI280ZI26tfDm3pWe63LaZx7qtGvniJ6tPLvOK fOa9WzbJvTbza02jl3n5SSljscK1MajSxWZ96nSW88xw/VfQ9XMT9nfa3yemid43jtLeXsce88qQ EqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADia3UTm1l4j7OP3Y/u 7Vp2rM+kPJW1PhYcmS0+9MzKm/jbwz31weMzbV8UppazPL9q0/BF4rk1GLDSNqxPWPhCnHmnNrtT qPKteWPm6U6OdHaZvO+SaRNvhv12Ub/q3FhtrNVj0uKOt56z6R5y9zix1w4qY6RtWsREOJ7L6OKa S2rvX6zNM7T6Vh3mmZyOfya7eACzIAAAAAAAAAAAAAAAAAAAAAAAAAAczjVvqMVfW/8AZ03I41bf Lp6/OVs/UVrY47NyOzUxd4bUJpEbb3Z7IiOrKIVSjZhMLJYyhKIgmGUQSDESIEbJEgQmCITEAmGU IiGUAyhZVhDOoM4Wx2VQtqBKuyyWEgqlhKyyuyBVaGtkbNmvk7A15l1eH2300R6TMORPSXT4ZO+O 8fFefEX63gEAAAAAAAAAAAAAAAq1WPxdLlp+Kkx+y1Fvsz8gjhaDauGK8sx07y3OE3m1tT6RaP4c vU6yMNKUx73zT0ilY3l2eF6a+m0kRl/zbzz3+Ez5M8z26fJruW6wzYq5sV8d43raNpZjRzPPaTmx 5b6bJ9rHO3zb2WJ8GWPEscY9bgzxH2t62n19GWW0eHOzHU5XbjXZ1x8WTnz2iZ7S2M1IjH2+LX0V KTqs8zO9ot0j8nUthi1J3UaOFMTfLFo6xMbS9BwHWTqdHOO8+/hnln5eTjYMFo1WTH5VnePzXcIm 2k4zlpPSmXy/hfF5eMfJns69OA2cgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAADG/2LfJ874rW845mubliY7bPoto5qzHrDz0+yePNF41OotaJ7RWNtpV1OtfHqZ715fhu j8adNpcVfeyzE2/vLuanhOu1nEctIxTTFa/+ZPbZ3eHcF0vDbTfFE2yzG03t32+DokynXl9+leDB TTYKYccbUpWIhYCzEAAAAAAAAAAAAAAAAAAAAAAAAAAAAcXjE/4zDH9M/wAu04XF5/3jj/0f3Wz9 RUYmzDWxS2I7FSyjuzY1ZKpRKEygEwiWUIkGIk2QJNhKQhMIhkCYZQxhlAMoZwwZwgWQshVCyATL CWc9ldpBhZXLOVdpQK7NfJPRdaWvknoDVvPvOnwuel4+TlXn3nS4VPvXj4QtEV0wAAAAAAAAAAAA AAAAAVV02CmTxK4qRf8AFFeq0AAAanEsfPpZmO9Ji0NDLfkwdOsulrumiyzHlVzJrz4Ovoy26vB8 cTBa9NffLtMY77Rv8Yegx5ImkKdJoY1HC81Y+3OSbVn0mGGkmbY45u6tnrrTOu2xGO0RxCd+nNVj qKxTV1vH2pjaGtnyzXXYdo96ZmGXEMk15b7/AGZiVerWPTYckZcNbx5wzc7hGbnxXxzPWk7x8pdF 0S9jh1OXgAlUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAcPjEf4/FP9H93ccXjMf4vDP9Mx+62fqKrx+S+GvibEFSsqyYwlVK ZYsmIMoRKYJQIPIEiQ2ATCUQygCGUIhMAyhnDCGUIFkLIV1ZxIMpVWWSrsCuyqyyyq09ECq8tfJK 66jJ2Bp5J6upwn7dv9Lk5J951uE/av8AJaIrqAAAAAAAAAAAAAAAAAAAAAAq1Mc2myxPnWf4cmtu XT9fR0tffk0WSe28bfq5Wbamm3326MtunwfK6PCv/AxPraZ/dz9PO97/AOqf5dHhdZrw7Dv3mOb9 XOxRFM+avpe38mvkPHf/AFWlrKba7Tzt99ZxKkfR7euyNXMTrtPHfa0z+zPiM/UR8Zj+Wbdu8HpN M2bfzrV13M4dO2pyR61dNvj44/J/oAWZgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADj8bj63BPzdhyeNx0wz8ZWz9RWri7Nmv VrYu0NmqaRZHZlDGGSiwxZSgCEkCBCQSCQBMJRCYgEsoYx3Z17AlMIhlCBnDOGEM4AlhZZKq4KrK 7LLKrIFN2vdfZReAaObu6/CO9vk5OePR1uEd7fJeIrqAIAAAAAAAAAAAAAAAAAAAAGtxCk5NFliI 3mI32+XVyNTyZOHTee946PQKPoeDffw4777eW/yVs60xv+ZxOnr4Okx1t05KRv8Ao41Z5q3yed5m XY1szXRZ5jvFJ/hxItP0aOSN9q7yrtr4f2tHFM5+KT16Yq/vK/iGSbXw4vO14UcPx5MGfNbPG18m 1oj4THRsTw7VanPXVYpi3gzMcnrvCnG11JOupwuN8+a3pEQ6jT4divjxWnJExa09pbjbM5HHu90A JUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAHM41H1GOf6nTc/jEf4Ws+lls/UX45uGekNujTwdm5RNIthKIZKLDFlsiQIShIC EgCUJ7AmGTGO7IDzZQhMSDJMMYZQgZwzhhDOATuqssmVdgVWVWWyqtCBTeVF19lF+wNLNG7q8I+9 8nLyupwnt+S8RXUAQAAAAAAAAAAAAAAAAAAAAAAItWL1mto3iY2lyrcLyUxzix2ia2nvPeK+jrCL OrTVnxpanhuPPemSs8l6RtE7dJj0ldpNP9GwRSZ3neZmV4cR/Vs4AJQAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANHi1d9H M+kt5ra+vPoskfDdOfqK4mn7Q3aNHBPZu0W0RdDOGFWcKLCJZeTGQQlCQSgASBsCYZQxhlAJTAmA TsmAgGcM4YQyjsgRLC3VnaVcgwsrt3Z2V2QK7tbJ1bN5a9waeWO7p8Knt8nNyebpcK8vkvlFdQBA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAK9RXmwZI+ErEWjesx6wQeZwejeo0cccuW8 elpblJaaRGxVnCuss4ZrMvJEgCAASISCQIBlCYYpieoM0wx8k7gzIRueYM4Z79FcSy3QEsLJmWFp BjaVVpZWlXMoGNmvkXXlr3kGtknu6XCf7OXkl1OEdl8orqgIAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAHmskcmtzV/rls0U62OXiWX4zErcc9GmkRfWVkSqqziWayxCPIANwBIhIJSxS CRG6dwZwlhEs4BluMdzfqgZxLLdXuy3AmVdpZTKuZBjaVVpWWV2QlhZRdfZRcGpl7urwfrzfJy8r rcH61vPyWitdMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHA4nHLxKZ9awnH2ZcY jbW459aq8fZpfiI2IZwrqzhmsz3Ebm4JN0AMhCQSIASndiAziWUSriWcAyRujc80DM3RCfIETLCW UsZEsJYSslXZAwlTddPZTkBp5e7r8Gj6rJPxhx8k9Xa4PG2C8/FaK10QAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAcfjcbZMFvnDWx9m5x2PqcNvS+zSxT7sNPxH62YZQwqzhRZO6UCB KUAJTux3SDIRuAncQAmJZRLBMSgZ7iIAZRKd2DICUSlAljLCYWMLIFVukNfI2bNbIDTyT7zu8Ijb Sz/qcG/2nf4T/wCE/wD2WnxWt4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHL9oL +Hw2cm28VvEuPptfgyVj6yIn0no7/FtJfW8NzYMe3PaPd39d3iMug1WktNc2C9dvPbeP1aZ9xF+v T471tHu2iflK2HkqWmvaZj5Surqc9Ps5bx+alTHqYHm68S1Vf/NmfnC2vGNTXvyT84Ql6A3cSvHM sfaxVn5Ssrxyv3sM/lKB1xza8bwT3pePyWV4tpZ+/MfOEjfGrXiGlt2zV/PotrqcN/s5aT/+wLRj FontMSlAlKEgndO6IAZQljDIEgeQljLCzOVdkCu/SGrkbF56NPNeKxMzMRHxENe0+89DwuNtHHzl 5PJr8NcnLW3Pbf7r1nCZm2gpae8zMrz4i/W6AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAETETG0xukB4HVaeMHEtRi26RedvkyjBSfX9W77QYvC4xz7dMlYlrU7M929dWJLFc6aPK0q 7YLxPS0S22FlP6q38Zac0yR92s/KVc3tHfFf8tpbcsLRvB/dR/8ALLVnU0r9uL1+dZI1mnmdvGpv 6TOy6ym+Oto2tWJ+cJ/tW+KLK5KW+zes/KU7tG+h01p64qx8Y6NXNo6Y+uPJlp8rLf0rfG7MXtHa 0x8pZxqs9e2a8f8A7Oj7HaTHn0+f6RWM23LETfr6vRW4PoL99NT8ui7F4+vEdXXtnt+fVbXjGsr/ AOZE/OsPS29nuH27YrV+VpeV9pdPXhOtw49NG9Mld55+vXcTPd42I47qo7xSfyWV9oM8d8VJ/VxM d8l46xWF9cV7en6o/qLfxp2I9ob+eCv/AHMo9op89P8A/wBORGmyT5R+qfo2X8P7n9Q/jTsx7RR5 6ef+4/8AuHftg/8A6cWcOSO9J/WEbWr3pY7Efzp2Lcfv5YK/9zWy8d1E/ZpSv5Oba1/+Hb9lc+LP bFt87I7E/wAabWbiurvEx4nL/pjZzc2bJkn372t85ZXx55/BX85lucC0vPxnTxlnnjm32mOiZqUu LJ2p4TwnVavNWaYbRTfre0bQ99pcH0bT0xb78vmtiIiNojaErMwAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAHnfarF7umzRHaZrLjYrdIen9ocPi8JyTt1xzF4eUw23rCm3R4r6bMy wt6kdTaWLdjswmNoZontsCm0K5XWjopnuDC0dGpqG5bs08/daKV672MjbSaif6oh6Z5f2LtvptRX 0tEvUN3Jfo8f7cYve0eX4zV7B5z20xc/C8eSPuZIRficfXlcPaG7ino08HWIbePpLF2NuiyOyrHK 3fZFSwuovHVfaVF4QK5YWTM9UT0EKry6Ps1Tn4zjn8NZn9nOtLseydObiWW34cf918fWfk+PYANn KAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAq1WKM+ly4p+/WYeBxTNd6zG0xO0 vobw3FcP0bi2em20Tbmj5Srr418V9sa2Z7qKyzi07MXUylhaU7yjqhLCeiq3ddaFNxFYW7NLNG8t zya+WO6Va9J7FW66mvwidnrXiPY3Ny8RyUn71Jj9Ht3RPjk19HK9pMHj8D1ER3rHN+jqqtTjjNps uOe16zAifXzfTz7kNyndpYazS9qT0mszDdoxrsi6m8LazMq6zDOsq1ZEyrt1WWlXaUCqyq0rbKbi Fdp6PReyFd8uqv8ACsfy83aXrPZHHto89/xX2/SP/dpj6y8vx6EBq5gAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAB5n2q03LfDqqx39y39npmlxbS/TOG5se29tuavzgWzeV4mtui2 O3RRSY2hdVhqO2MvI36iu9lUsrSrvDHn6spnmSiq5jooyV6tq1VV69RC32byTh43h8otMx+r6I+Z aK/g8TwX7bXh9Mid4iW+fjl8n1ICWb57xLBOm4zqse20Tbmj8+qKdnS9q8PhcTw5tumSm0/OHMxz 0Za+uzx3sX1t0Zxurr1ZxvspWiZYWZbsbT0QK7KLrZVZJFaqt5vbezNOTg9J/FaZeJns93wCvLwb T/GJn92uGHldIBowAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADuAPA67F9H4l qMW20VvO3yRWW97T4fC4rXJHSMtI/WGhVlue3b473K2KzMML4+62tujG9pnozXaOSOVFMnVbmq1t trJRW5E7wwvUxTvCyY6CHOt7moxz6Wh9PxTzYaT61h8x1MbZK/OH0zTf+Fxf6I/htj45vL9WgLMn mvbPFvocGWO9L7fq85p5maw9d7VYvE4JkmPu2if3eW0+PasdFNOnxfF1Y2hlykRsmY+LJ0MZjZXa eq2eyi8oQTO0KLdZWzPRjWu6VaqtHR73g0bcI0sf0Q8Nkq93wqNuFaWP+XDTDDytwBowAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAef9q8HNpcGaI60vtPyl56k9Iew49j8ThGe PwxFv0l4zH2U26fDfTYiyJljvsjf4sm6vJ1hrXjq2MkqLdZEVbgbMx0auGdmzNt6iHN1Ub5af6of TdPG2nxx6Vj+HzaaTm1+nx/iyVj930ysbViPRrj45vL9SAuyc7j1efguqj+jd4/T33rD3HEcPj8O 1GP8WOY/Z4TTT7sKadHhbcsZnaCJ3TPZk6VdrKbTutmP0U2nqgrGOsr8deiuI2X09EqKM1dt3uuG f/jdN/06/wAPE546S9rwud+Gaaf+XH8NMMPK2wGjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAABrcRp4nDtRWPPHP8PCYusPoWSvNjtX1iYfPuWaXtX8MzCuvjfw32siu8ptXoxi 0wy5t4YulReqmazu2skbquURWFInddM7VYRGyL291KFnCcfj8e0le/Lbmn8n0N4b2Ur4nHLWmPsY 5e5a5+OXyXugBZmiY3iY9Xz7NjnTa3Ph/BeYj5PoTxftFg8Hjk2iOmWkW/Psrr418V5WrWd2faFc V2jdnEMXWxntupmN7NiYU27iWML6dVMVnddjgVqMsdHr+CW5uE6f4Rt+7yuSsTDv+zWXn0WTHP3L /tK+GHl+O0A1c4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8Dn93W56/wDM t/L3z59qp24jn+OS38lnpr4r7ZxHQ2TEstt3PXUrt27K57rr1VT0BjKnJPRbMqMs7QlV2fYvHvrd VknyrEfu9m8f7FZI8fVU85iJewbT45NfQBKo817W4eulzxHaZrL0rje09ItwqbfhtBVs3leai8RD KLw1sduesL606dWFdsZT1jdhNeq6K9DlhCVUU6s4jZnt1YzAhnM71dH2bycmszY/K1d/0c6OzY4R fwuK4p8rTstn6z8k7HrwGzkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHz3 Vxvr80/8y38voTwGpj/F5/8AqT/JfjTx/WVeyY6FPspc9dZPVXaOq2WEwIUTVRmjo2rNfLHRI3vZ DJycXtX8dZh7t879nsnhcbwz23tt+r6I2nxyb+gCVBzuPY/E4PqI9K7ui19fTxNBnp60n+Aj5/pJ 3jZu1aOnnltMNussdfXbm+l3ZM9URHREdZVXTuT1Nk7boQiOkJw28PU47/htEp5eivJPLMTCZ9Vv x7mJ3iJ9UqNHk8XR4b+tIXuhxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD weqjbWZ4/wCZP8vePCaz/wDIaiP+Zb+UX408f0r9lOxWOifJhXWjfyYWllPRXYQxnrCrJHRd3YZI 6A1NJecHEsN/S0T+76bE7xE+r5dk93LW3pL6ZpMni6PDf8VIn9m2fjm8s9rgFmQxvHNS0esbMiew PnHLyai9fS0w2aNfUTtrs3+uf5bGPqy068fF227KtSsdFlKqNGMV6myyY6sbdIQI8tlOWOi6Jhhk j3RD0vA8nicMx9etZmHRcT2Zyb6XNT8N9/2dt0T449T2AJVAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAHhdfG3E9TH9cvdPEcXjk4zqI/q3L8aeP6xr2TsxpLOekMK6mFo6qpXSrm OqBixvHSVmzC4OfqK7S9/wAByeLwbTW9K7fo8Fqo6Paeyl+fglI/Da0NcMPK7QC7AAB8313TiOf/ AKk/y2MHWrX4jG3E9R/1Lfyv0/aFNOrHxuU7LI7MMayGTVlHWUXhNe6Z6wIUsb9d1m20q7dkDpez N9tRqKT5xEvRvKez9+Xis1/FSYerb5+OTyf6AFlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAB43j9eXjN/jWJ/Z7J5L2mry8Upb8VIF8f6aGOey2eynHvOy7bowrrYSxZSwQJ2YXZ 92N4BoanrEvVexmTm4blr+HJ/aHltRHSXofYm/1Wrp5RaJaYY+X49WA0c4AD51xONuKan/qW/lbp +0MOLRtxbU/9SU4J7KadWPjep2WQrr2WRPRk1TvsndXMpiRCb9FNu0rbTuqvKBscCjfi9PhWZeue V9n434rafTHL1TfPxy+T/QAszAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHmv avHtfTZfnV6VxPajHzcNrf8ABeJFs/XnMcr4no18c+6vr2YadkY2YM57sEDLyY37Mo7MMnYGlqO0 vQ+xNfqNVb1tEfs87qZ2rL0/sVX/AHdnt65P7Q0wx8vx6UBo5wAHz/jUbcX1PT78qtO2vaCnJxjP 8Zif2amnnspp04+OjWejKJ6MKdmcMmyJn4m5ZHzEVPMwtJv0VZLbQDqezcb8RzT6Y/7vUPM+ytZt n1OTyiIh6Ztn45N/6AFlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABocbxeLw nUR5xXm/Rvq8+OMuDJjntaswEeBxT0bNZ6NatZpNqz3rO0rqsdO3PxlaWEMpY+aqWXkryT0ZT2V3 7A0dVPuy9f7G124NM/iyT/Z4zWT7sw957MYfB4Fp4/FE2/WWmGHldcBowAAeM9qKcvFeb8VIly9P 0nq7ntbTbVYL+tJj93CwT76unR4/jo0nozhhTsy3Y1sWljM9Ce7HyQIm3RRlttVbaWrnt0Sh6n2U x8vD8mSfv3/h3XN4Bi8Lg2nj8Uc36y6TeOPXugCUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAPD8RxeBxXUU26Tbmj8+quro+02Lw+I4ssdslNvzhzazvDPbq8d7GW7Dfqz2VzG 0s2qd+iu/Zn5Ksk9BVztX1mI8930zh2LwOHabH+HHWP2fNYp4+vwYvxXiP3fUqxtWIjyjZtj45/L faQFmQADzftfj3w6fJ6WmHmsP23rvaqnNwqLfhvEvIYZ+sV038bo0noy36MK9oZQxrdMyrlnMbMZ QKrS1M07zEestq/RRjr4utwY/wAV4j91p9V18fQdJj8LR4ccfdpEfsuREbREJbuMAAAAAAAAAAAA BAJAAAAEAJEAJQAJQAJEAJQAJQAJEACUJAQlAJEAJQAJQJAAAEAJEAJBAAAJAABAJEJAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwvanDzaPFmjvjv8A tLztJ3h7HjGHx+FainnFeaPnHV4vFbeIU038VbHeGF+kso7Mb9mTdhKnLK3dRm7SIrHhGPxeP6Sv 9cT/AHfSnz72Zx+J7Q45/BWZ/Z9BbZ+OXyfQBZQABzeP4/E4NqI9Ii36S8Ng/wAx9C4jTxOH6ivr jn+Hz3B/mQi/GvjdCnWNlsdI2V07LIlg6USrt2ZzZXMoFV+zPhGLxeOaavpbm/RVltEN72Yx+Jxm b7dKUmf7L5+s9/HtRA2cqRACRACRACRACUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAACQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQCQQCRACRACRCQBCQBCQB ACRACRACRACRACL1i9LVntMbPATTwdRkxT3pea/u+gPE8Xx+DxrPHlaYt+qNfGvjvtXXsi0dOrKk dEXjZg6VMtbP2bMtXUdpEV0/Y2nNxbNf8OP+727xvsXH+N1U/wBEfy9k3nxyb+gCVQAGOWvNivX1 rMPnGGOXNNfOJ2fSZ6w+dZKeHxDPX8N7R+6L8a+L63KdoZ7q6zvEMpnowdKJ6ywmWUyqvIKM0vQ+ x+D6rU55+9aKx+TzWa36vbezmDwODYenW+95/Nphj5L6dQBo5wAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAEiAAAEoA AAAAAAAAAAAAAEAkEAkRuAkQbgkQAkQAkQAkQAl5T2nx8nEMOT8dNv0l6pwfarHvpcGWPu32/WCr YvK4mOem6b9mGKd4Z3idmFdka0y1c892zfpMtLPaNpEV6D2Kj/Eauf6YeweQ9ieuTVz8K/3evbT4 5NfQBKoAA8FxCvJxrUx/XMvevD8Zry8fz/Haf2RfjTx/6RSOnRMyypHu9kXjowrqVSrvPRnZVl6V kK0775MsUjvadn0nT4ow6bFijtSsVfPuFYvpPGtNTy54mfy6vorXDm8l9pEC7JIgBIgBIgBIgBIg BIgBIhIAgBIhIAgBIgBIIBIAAhIAhIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJAAAAAAAAAAAAAAA AAAAAAAAABAJQkAEAAAAAAAAAAjc3BIjdG4Mkbo5kcwMjdhzHMDPc3V8xzAs3N1fMjmBZubq+Y5g Wbm6vmOYFm5ur5jmBZubq+Y5gWbm6vmOYFm5ur5jmBZubq+Y5gWbm6vmTzAz3N2HMnmBlu5ftFTx OEZJ/DMW/d0t2rxKni8N1FPWkiZ9eS08e7Cy8dGGn6UhZaJljXZGnmc3UT3dPP2cnUT78xCIV6j2 H/8A9c/6f7vXPI+w8bU1U+vL/d63du5NfUiDcVSIAS8b7RV5eOb/AIqRL2TyXtNX/e2KfXH/AHlF +NPH/pr4+2xcxx0hFpY11K7R16KM32ZWz3UaidqSgrc9kcPicWyZJjfw6T+727y3sXh2xarN+K0V h6lvPjj3e0ASqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJQAAAAAkQAkQAkAAAAAAAAAAAAAAA EgAAAAAAAAAAAAAAAAAAAAAgAAABKDcAN0bgkY8xzAyRux5kcwM9zdXNkTcFm6OZXzMeYFvMibKu ZHMC2bo51U2RuC2bom6rc3BZzom6sBZzI52ADPnOdggFnMc6skFnMc6rc3BbznOp3RzAv50c6nml HMC/nOf4qOY5wX85zqOc5wbHOc7X5znBsc6edr85zg2ec52vzpi4NjmY5bROG+/bllVzsNTk5dLl n0pP8BHmMHWNmzt0aum8obm08vVjfrtnxztR0mXHzTvaZdjVRMTLkZo6yiFen9iZ2pqY/wBP93rN 3kPY+/LfPX1rE/u9XzN3HfqzdO6vmTuIZ7m7Hc3Bnu8t7TR/vHBP9E/y9Pu837SV31umn+if5Rfi /j/01MMb1hjkrtKzBG0bMsmOZY11tOYamr6Und0LUc7XT7u3rJPqL8er9lcPhcFpbzyWm39v7O00 +FYvA4Zpsc94xxu227jv1IAgAAAAAAAAABKAAAASgASgBIgBIgBIgBIhIAAAAAAAAAAAAAAAAAAC UACUJAAAAAAAAAAAABIAAAAAAAAAAAAAAAAAAAAg3AEbomQZbo3YzLGbAz3RNlc3YzcFs2YzdVN2 M2Bdzom6nmNwW86JurTAMuY3REJ2BB1ZRVMVBhsbSsiqeUFXLucq3lTygp5TlXcpygp5TlXcpygp 5TlXcqOUFXKjlXcrGYBXysdlswiYBVMdUTCyY6sZBWxlnMMZgGLGZZSwkDdHMiWO4MuY5mEyjcFn N1OdVzHMC3nTzqeY5gX85zqOZPMC+Lqdbk20eb/RKOZr8QybaK/XvtH7iZ9aGlp2luzT3fg19NHS OjbmPcYX67XH1XSZ9XIzRvMuzrK7zLkZYmYnciunb9lZ5dTk+OP+71cXeP8AZnJ/ip2nf3J/l6iL /Fu5L9bMWZczXi6YuIbEWTzKIuyiwLt3nuO25uI4a/hx7/rLuczg8TicvFLbfdpEK6+NPH/phhjo stLGkctUWnoxrrU3j1cnWTzZq1jzl1clo5Zcu8c+txR63iP3Tn6pv4+g4o5cVI9IiGe7CJ2iE7t3 GyN2O6dwSINwSISAlAAlACRAAlAAlACRACRCQAAAAAAAAAASgASISAAAAAAAAAAAAACQAAAAAAAA AAAAAASAAAAAAAAAAAAAAAAIAAAQCAJljuljsCJlhMs9mOwMJYys5TkBVsjZdyHICrZPKt5E8oK4 qmKrOVOwMIqyirPY2Bjyp2ZbAI2NmSARsbMgEbI2ZAMdjZICNkbMkSCNmOzJEgx2YyzljMAwlhKy WEwCuWErJhhMArlhLOWEgxljMpljIImWMyTKJA3N0IBO5vux3NwZbnMx3NwZczT4jf3MdPW27a3a fJOq1XNP2KdIRfi+J2trSYfcjeF+Wm1OicVeWIiN9kai8xjY12ORqultnI1Ecsujq79XP1FovWYI rTgeq+j8QrWZ+3Mx+r2UXeC0WG2Ti2kiN5mL807eUREvbzbaejefHJv62Iv8WUXa0WTFhVtRdlF2 rz9WUXBtc7jR9dqc2T1ttHyhvZMvJitb0jdq6XHNcNenWVN3028U99WRj6Kb02be3Tq18/SN2Lpc 3UdN9nOmZrqKX/DaJ/d0svvTLRzV3jomK6+Pd1vvWJj0ZczT0mXxNJht60hfFnQ4qu3N1cWTEgs3 Tur5k7gz3N2O5uDM3Y7m4MtxBuCQASIASIASAAAAAAACRCQAAAAAAAAEoSAAAAAAAAAAAlAAlCQA AAAAAAAAAAASAAAAAAAAAAAAIASgAAAEJAQJQCNkbMgGOyOVnsAw5TlZ7GwMOVPKy2NgY7GzIBGx skA2AAAAAAAAAAQkBAEghEskAxYzDPZGwK5hjMLJhjMAqmGEwumrCagomFcw2JqqtUFEsLLrV82F o7gqljKyYYTGwMZRKUSCAQAboJnaN5Bjkneu0d5W4ccViIiOzHFWbTzNumP1Zarr8eeRMbxDW1Mx NO67NbkhzNVnmInqzaOZrL93JyZeV0M1++7S02jvxDWxhxx033tPpC8Z6rrezWjmZyazJG2/u03h 2vFibTHoqvamiwVwY+nLGzV0+SZ1Mx8G0/45tOhzJ5lXMc3UVXRdlF1HP+iYsDPLPPy49/tz1+Te pSIr0ho6ak5Ms5J8o2q6NImOrHV7XX488ypzTtHXo0s9t6zG7c1G1qz6ubeZiZ3UatXJG3yauSO7 cvMTEx5tPLb3prPRMVr0HB8vicNxf0+7+kt+LOJwTJyY/Bnz3tH93X36N58cWvq6LSyiyndMSlC7 mZcymLJiwLosmJVRLKLAtiU7q4lMSCzc3YxJuDMRuAlKAEgAAAlAkAAAAAABKAEgAAAAAJAAAAAA AAAAAAAEgAAAAAAAAAAAAAkAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAhIAAACAAAASgAAAAAAEAAAA hGzJAImGMwzQDDZjNVuyNgUTVhNGxysZqDVmiu1G5NN2M4waM0+DCaN2cbGcQNGaMZq3JxMJxA1J qx2bU4kU09slorWNwa20z02RXHbJbl26QvtFovbHWkxEdJt5y2MOHlr2U1W3jx+1hiw8vSO63lmI XRTaEWmtY6snRHO1VpmJ+DjavpSZl2s8b7y4HFcnh0n0gha5ebJN55KRM2mdoiPN6fh+kpwXh0Wy RHj5Otp/s5Ps1p62y31+em9aTMYt/OfVfxTiPjZ52naI7fBrI5t66xz5+a1rW7yx0eSL6iZjtEOX qNbSletom3lENjh2fbHzbbWt3iVozruc+5ztWubf4M4ybpQ2Oboyrva0Vjza8WdDR4OkXt3n9ldX kaePP9VtYqctYhdvt5oivTeCZ2YOxXk6ubqMfV0b9mrljfqlFcq88k7z2U5axeItDa1OPessuC8P ya7XRWYnwqdbT/ZMilvIu4dpslNdixXja8Y5tt85djZdbDWnGOesRtXFtuw6T27No5Kx2OrKYQlC ExKJgBnEpiyvdlEgsizKLKollFgWxLKJVRLKJBbEp3VxLKJBnuMWQJEbpBIAAAJAAAABIAAAAAAA lAJAAAAAAAAAAAAAASAAAAAAAAAAAAAJAAAABAJABAlAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAA AAABAJQAAAAgAABAAI2EoBGyJhkgGPKxmqxAKpownHC+YRMdN5BrTj67R3bOn01o7p01Iv71u89o b9a7LfBTfS1vWI2jf12VfQPSW8KX2mas+NC2iv6xMNfJpMnLtEbuuxtMRCtzF55NR5rPps1N/ctP y6uHreE6nXZ4pak48X3rT06fB7fNeI33cbX6mI32R/MWu7XF116aDSRhxbRERs8f499bkyZeeKae kzE2mdon81/tfxDLGOunwbzlzbx08oaHBvZHJlx48mrvaa94pu04y617576rNGLRRM0397JEd/lu 9Dw/S3x4qxffo6mm4NjwUiKY4iI9Ib1dHFY6QIaNabbrYrLfrpJtaK1rMzPZb/s+05IpP59OyLeJ k7eNfRaOc1ue32I7fGXYpi5Y77M8OGMeOKxHSFsU3Y29deZMzirl6dlVvhLatCjJHeYQv1rXnps1 8k9/VsW6qLVmZIi1rzitlvFKRvaZ2h6TSaenC9FFY+3brM+sqeG8Prp4+kZ+lvuxPkr1mqm95nfp DXM459676a2q1dsV7XietvNno78+CJn1cjX6mOeIm0bR33dfRU5NJjidt9t5afjG/V6JZ7I2QMNh nyo2BhsMuVG3wAhMSbbQRAMolnE+iuGUSCyJZRKuGUSCyJZK4llEgyZMYTuCUsYSCQASISAAAlCQ AAAAAAEoASCASAAAAAAAAAAAAlACRACQAAAAAAAAAEgCEoASCAAAAAAAAAAAAAAAAAAAAAAABAAA AAAAAAAISAIAAAAAAQAAACASgAAAQJAQAAhIDHZhln3do7z0WS18mWsajHjmes7pg3dNi5aRMNqO yvDHTpPRaigHZhN4hHRlaVN59JY3zRENLUavaO+yq0iNVlitJ6vNcR1MVi0zO0era1/Ea0rPvbz5 PM5MWp45qvo2GZrhmfrsnpHpHzTCseEcM/2vrr8Q1Eb4qzy44nziPN63HpYiIiI7LNHoqabBTFii IpSNohuVxrKtWMEejPwY9G1FFmHB4mWJn7MdfnIM9JpIx15to5pbUaas/a6rqViI7MxPxqX0UT1r O3wVzpbR2hviP5i03Y5s6a879FNtHljydhExCv8AMTPJXBnRZbz0iG5ptFjwe/l96zctMVamTJtE yTMibu1VrdTzRMR0j0ed4lr64MVpm0RERvMz5NvX62uOJ69XhOKX1HH9bHDtFvNYnfJeOy0Z2ojX 6jjnEq6fRUmccTvN/J9H0eKcOnx45neaxEbubwHgOHg+milI3vP2resu3Wu0JQmITsmISDHZHKz2 JgFc1RMLJhGwK9iIZ7MZgEdgmAEwyiWCdwWRLKJVxKYsC2JTuriWUSDNlEsIlMAySx3SCRCQSIAS AAACRACQAAAAAAASIASAAAAAAAAAAAAAAACRACRACQASIAAAAAAAAAAAAAAAAAAAAAAAAQCUAAAA AAAAAAIAAAAAAAAQAAAAAACBICBICAAEJAQJQCJcLjuS2ny6fPG/LWdpd1o8T0X07SXx/e7wCdJx Wa0jmneHQpxPDMdZmJfNtZm49weZrh0/j4o7VtSZ2+Uw0/8A7o49k92vBLc/ntFohFW9PqGXimOI 6Tu1L8T3eCx6r2t1O3JwvHjifO99v7t/Bwf2l1PXU6rS6eJ8qUm8x+so5TsekzcSjbvs4mt4rzW5 K2mbT0itesy2cHsvbvqtbmyz5xERWP2jd1tJwrTaONsOKtZ8585+cnDrzmn4Rq+IZObUROHD32n7 Vv8A0ej0uhxaXFGPFSK1j0bkY4jyZRVZVXFGUVWbGwKsk8mObekNrSW3pWf1a2aYjHbm7bNnQ1id PW0TvuDdhJEbQABMsLW2R0ZTMQrvfbz2YWzVhpanUxEd0dWkW5c8R5uXxDX1w4pnfr5Q19XxKuOJ 2neXltVqtVxbV/RdJ715+1bypANfiOu1HENV9C0MTfNeesx2rD1PAeBYuE6aKx72W3W9/WVnBuB4 eF4dqRzZbdb5J72l160WVK02ZxCYhOwI23TsnY2BGxsnYBjsiYZsZBjMMZZSgGEolMsQDdG6NwZ7 piVe6YkFsSziVMWZRILolMSriWUSCyJTuwhMSDMRCQSI3SAlACRCQAAEoAEoASAAAAAAAAACUACR ACQAAAAAAAAAAAAASAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAABAAAAAAAAAAAAACBKAAAAAAAQ JQAAAhICEbJAYTWJ7wx8KvpC0BV4ceieWGewDHlNmWwCNjZICNhIDmcZredBecdpiY69FXCOLW+i UiZidukulmxxlx2paN4mNng+K4+I8Hy2yaTfl37TXetoCPfRxfp1qi3F48ofKMvtvxak8s6LDv61 rZji9rPaLUf5PC+bfttS0q8q3p9W/wBrRMdpUZuKdN99nzvFqPbTVz7nD8OKs+do2/mW3h4D7Xaq ZnPrtNpqz35aRaYOHY9Zk4pNt9rR+rl6zi+OnS+WN57Rv1lXp/YrNaYtruL6zNPnGO3hxP6O5w/2 f0HDuun09Yv55Le9afznqcOvO4tBreMTHu30unnva0bWt8on+70nDuE4OHYYx4Kbesz3tPrMuhGO IjpDOKrK9YVpsyiGUQnYGOyUgI2SlAIEmwMWMs9kTAMJYzDOYRMArmGErZhhMArlHmzmGMwDE3Ts bAbs4swj5pgFkSziVcM4BZEsolXDKAZwyhjCYBkACQhIAAAAAAAJAAAAAAAAAAAAAAAAAAAShIAA AAAAAAJAAAAAAAAAAAAAABAJEAAAAAAAAAAAAAAAIEoBKAAAAAAAAAAAAAAABAlAAAAAAAIAAAAA BAkBAkBAkBAlACEgMZjdjbFW8bWrEx8YWANb6Fp+bfwab+vLDKMFK9qxH5L0bAr8OPRPKz2AY7J2 SbAjYZAI2E7AIEgIEgIEgMdkSy2NgY7MdlmyNoBXsxmFuyNgVTVjNV3KjlBRNTlXTVHKCrlIqt5T lBhEMohlFerLlBjEMohMVTEARDKCITsAk2AEgAAAkAAAAAAAAAAAAAAAAAAAAAAAASAAAAAAAAD/ 2Q==`;async function Ebe(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(i1);break;case"body":case"full":n=await t(l1);break;default:n=null}if(n){let r=await createImageBitmap(n);s=await e.detect(r,e.config),r.close()}return s}async function Rbe(e){return new Promise(t=>{let n;switch(e.config.warmup){case"face":n="data:image/jpeg;base64,"+i1;break;case"full":case"body":n="data:image/jpeg;base64,"+l1;break;default:n=""}let s;if(typeof Image!="undefined")s=new Image;else if(pe.Image)s=new pe.Image;else return;s.onload=async()=>{let r=vr(s.naturalWidth,s.naturalHeight);if(!r)ee("Warmup: Canvas not found"),t(void 0);else{let a=r.getContext("2d");a&&a.drawImage(s,0,0);let o=await e.image(r),i=o.tensor?await e.detect(o.tensor,e.config):void 0;t(i)}},n?s.src=n:t(void 0)})}async function _be(e){let t=r=>Buffer.from(r,"base64"),n;e.config.warmup==="face"?n=t(i1):n=t(l1);let s;if("node"in Ye&&cn()==="tensorflow"){let r=(void 0).decodeJpeg(n),a=Ft(r,0);e.tf.dispose(r),s=await e.detect(a,e.config),e.tf.dispose(a)}else e.config.debug&&ee("Warmup tfjs-node not loaded");return s}async function Dbe(e){let t;return typeof createImageBitmap=="function"?t=await Ebe(e):typeof Image!="undefined"||pe.Canvas!==void 0?t=await Rbe(e):t=await _be(e),t}async function $be(e){var i,l,u,c;if(!U().flagRegistry.ENGINE_COMPILE_ONLY)return;let t=cn(),n=Bs();if(t!=="webgl"&&t!=="humangl"||!(n!=null&&n.checkCompileCompletion))return;U().set("ENGINE_COMPILE_ONLY",!0);let s=Jt().state.numTensors,r=[];for(let[p,d]of Object.entries(e.models).filter(([h,f])=>h!==null&&f!==null)){let h=(l=(i=d.inputs)==null?void 0:i[0])!=null&&l.shape?[...d.inputs[0].shape]:[1,64,64,3],f=(c=(u=d.inputs)==null?void 0:u[0])!=null&&c.dtype?d.inputs[0].dtype:"float32";for(let g=0;gY(y)):Y(g)}catch(g){e.config.debug&&ee("compile fail model:",p)}Y(m)}let a=await n.checkCompileCompletionAsync();n.getUniformLocations(),e.config.debug&&ee("compile pass:",{models:r,kernels:a.length}),U().set("ENGINE_COMPILE_ONLY",!1);let o=Jt().state.numTensors;o-s>0&&ee("tensor leak:",o-s)}async function bR(e,t){await Kh(e,!1);let n=ie();return e.state="warmup",t&&(e.config=Bt(e.config,t)),!e.config.warmup||e.config.warmup.length===0||e.config.warmup==="none"?{face:[],body:[],hand:[],gesture:[],object:[],performance:e.performance,timestamp:ie(),persons:[],error:null}:new Promise(async s=>{await kd.load(e),await $be(e);let r=await Dbe(e),a=ie();e.config.debug&&ee("warmup",e.config.warmup,Math.round(a-n),"ms"),e.emit("warmup"),s(r)})}var Rd,Yh,Jh,u1,_i,G4=class{constructor(t){de(this,"version");de(this,"config");de(this,"result");de(this,"state");de(this,"process");de(this,"tf");de(this,"env");de(this,"draw");de(this,"models");de(this,"events");de(this,"faceTriangulation");de(this,"faceUVMap");de(this,"performance");Mu(this,Rd,void 0);Mu(this,Yh,void 0);Mu(this,Jh,void 0);de(this,"gl");de(this,"analyze",(...t)=>{if(!jr(this,Yh))return;let n=this.tf.engine().state.numTensors,s=jr(this,Rd);Bd(this,Rd,n);let r=n-s;r!==0&&ee(...t,r)});Mu(this,u1,t=>{if(!jr(this,Jh))return null;if(!t)return"input is not defined";if(this.env.node&&!(t instanceof st))return"input must be a tensor";try{this.tf.getBackend()}catch(n){return"backend not loaded"}return null});de(this,"similarity",W4);de(this,"distance",Zh);de(this,"match",V4);de(this,"webcam",new S2);de(this,"emit",t=>{var n;(n=this.events)!=null&&n.dispatchEvent&&this.events.dispatchEvent(new Event(t))});Mu(this,_i,{});this.env=pe;let n=(Mh.tfjs||Wy).replace(/-(.*)/,"");Ha.wasmPath=`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${n}/dist/`,Ha.modelBasePath=pe.browser?"../models/":"file://models/",Ha.backend=pe.browser?"webgl":"tensorflow",this.version=hb,Object.defineProperty(this,"version",{value:hb}),this.config=JSON.parse(JSON.stringify(Ha)),Object.seal(this.config),this.config.cacheModels=typeof indexedDB!="undefined",t&&(this.config=Bt(this.config,t)),FT(this.config),this.tf=Ye,this.state="idle",Bd(this,Rd,0),Bd(this,Yh,!1),Bd(this,Jh,!1),this.performance={},this.events=typeof EventTarget!="undefined"?new EventTarget:void 0,this.models=new Xh,this.draw={options:Qn,canvas:(r,a)=>F4(r,a),face:(r,a,o)=>Sd(r,a,o),body:(r,a,o)=>Id(r,a,o),hand:(r,a,o)=>Cd(r,a,o),gesture:(r,a,o)=>Nd(r,a,o),object:(r,a,o)=>Td(r,a,o),person:(r,a,o)=>P4(r,a,o),all:(r,a,o)=>O4(r,a,o)},this.result={face:[],body:[],hand:[],gesture:[],object:[],performance:{},timestamp:0,persons:[],error:null},this.process={tensor:null,canvas:null},this.faceTriangulation=RN,this.faceUVMap=_N,this.gl=Et,a1(this,null,""),this.emit("create"),(this.config.debug||this.env.browser)&&ee(`version: ${this.version}`),this.config.debug&&ee(`tfjs version: ${this.tf.version["tfjs-core"]}`);let s=JSON.parse(JSON.stringify(this.env));delete s.kernels,delete s.initial,delete s.perfadd,this.config.debug&&ee("environment:",s)}reset(){let t=this.config.backend;this.config=JSON.parse(JSON.stringify(Ha)),this.config.backend=t,db(),pe.initial=!0}validate(t){let n=Kg(Ha,t||this.config);return n.length===0&&(this.config=Bt(this.config,t)),n}check(){return o1(this)}now(){return ie()}image(t,n=!0){return w2(t,this.config,n)}async segmentation(t,n){var a,o,i;if(n&&(this.config=Bt(this.config,n)),!this.config.segmentation.enabled)return null;let s=await w2(t,this.config);if(!s.tensor)return null;let r=null;return(a=this.config.segmentation.modelPath)!=null&&a.includes("rvm")&&(r=await XE(s.tensor,this.config)),(o=this.config.segmentation.modelPath)!=null&&o.includes("meet")&&(r=await wE(s.tensor,this.config)),(i=this.config.segmentation.modelPath)!=null&&i.includes("selfie")&&(r=await ZE(s.tensor,this.config)),Y(s.tensor),r}enhance(t){return Lb(t)}compare(t,n){return PT(this.config,t,n)}async init(){await Kh(this,!0),await this.tf.ready(),db()}async load(t){this.state="load";let n=ie(),s=Object.values(this.models).filter(o=>o).length;t&&(this.config=Bt(this.config,t)),this.env.initial&&(await Kh(this,!1)||ee("error: backend check failed"),await Yp(),this.env.browser&&(this.config.debug&&ee("configuration:",this.config),this.config.debug&&ee("tf flags:",this.tf.ENV.flags))),await R4(this),this.env.initial&&this.config.debug&&ee("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&&(o1(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 yR(t,this.config)}getModelStats(){return E4(this)}async warmup(t){let n=ie(),s=await bR(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={},a=0;for(let i of s.kernels)r[i.name]?r[i.name]+=i.kernelTimeMs:r[i.name]=i.kernelTimeMs,a+=i.kernelTimeMs;let o=[];Object.entries(r).forEach(i=>o.push({kernel:i[0],time:i[1],perc:0}));for(let i of o)i.perc=Math.round(1e3*i.time/a)/1e3,i.time=Math.round(1e3*i.time)/1e3;return o.sort((i,l)=>l.time-i.time),o.length=20,o}async detect(t,n){return this.state="detect",new Promise(async s=>{var g,y,x,A,b,w,k,C,N,R,D,E,$,S,F,z,V,j,G,q,K;this.state="config";let r;this.config=Bt(this.config,n),this.state="check";let a=jr(this,u1).call(this,t);a&&(ee(a,t),this.emit("error"),s({face:[],body:[],hand:[],gesture:[],object:[],performance:this.performance,timestamp:ie(),persons:[],error:a}));let o=ie();await this.load(),r=ie(),this.state="image";let i=await w2(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&&ee("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 $T(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=[],u=[],c=[],p=[];this.state="detect:face",this.config.async?(l=this.config.face.enabled?L4(this,i.tensor):[],this.performance.face&&delete this.performance.face):(r=ie(),l=this.config.face.enabled?await L4(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 d=this.config.body.maxDetected===-1?Bt(this.config,{body:{maxDetected:this.config.face.enabled?1*l.length:1}}):this.config;this.config.async?((g=this.config.body.modelPath)!=null&&g.includes("posenet")?u=this.config.body.enabled?x4(i.tensor,d):[]:(y=this.config.body.modelPath)!=null&&y.includes("blazepose")?u=this.config.body.enabled?Ib(i.tensor,d):[]:(x=this.config.body.modelPath)!=null&&x.includes("efficientpose")?u=this.config.body.enabled?Db(i.tensor,d):[]:(A=this.config.body.modelPath)!=null&&A.includes("movenet")&&(u=this.config.body.enabled?p4(i.tensor,d):[]),this.performance.body&&delete this.performance.body):(r=ie(),(b=this.config.body.modelPath)!=null&&b.includes("posenet")?u=this.config.body.enabled?await x4(i.tensor,d):[]:(w=this.config.body.modelPath)!=null&&w.includes("blazepose")?u=this.config.body.enabled?await Ib(i.tensor,d):[]:(k=this.config.body.modelPath)!=null&&k.includes("efficientpose")?u=this.config.body.enabled?await Db(i.tensor,d):[]:(C=this.config.body.modelPath)!=null&&C.includes("movenet")&&(u=this.config.body.enabled?await p4(i.tensor,d):[]),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?Bt(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&&R.includes("handdetect")?c=this.config.hand.enabled?Kb(i.tensor,h):[]:(E=(D=this.config.hand.detector)==null?void 0:D.modelPath)!=null&&E.includes("handtrack")&&(c=this.config.hand.enabled?Qb(i.tensor,h):[]),this.performance.hand&&delete this.performance.hand):(r=ie(),(S=($=this.config.hand.detector)==null?void 0:$.modelPath)!=null&&S.includes("handdetect")?c=this.config.hand.enabled?await Kb(i.tensor,h):[]:(z=(F=this.config.hand.detector)==null?void 0:F.modelPath)!=null&&z.includes("handtrack")&&(c=this.config.hand.enabled?await Qb(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?((V=this.config.object.modelPath)!=null&&V.includes("nanodet")?p=this.config.object.enabled?f4(i.tensor,this.config):[]:(j=this.config.object.modelPath)!=null&&j.includes("centernet")&&(p=this.config.object.enabled?Nb(i.tensor,this.config):[]),this.performance.object&&delete this.performance.object):(r=ie(),(G=this.config.object.modelPath)!=null&&G.includes("nanodet")?p=this.config.object.enabled?await f4(i.tensor,this.config):[]:(q=this.config.object.modelPath)!=null&&q.includes("centernet")&&(p=this.config.object.enabled?await Nb(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,u,c,p]=await Promise.all([l,u,c,p])),this.state="detect:gesture";let f=[];this.config.gesture.enabled&&(r=ie(),f=[...fR(l),...hR(u),...gR(c),...mR(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=((K=this.process.tensor)==null?void 0:K.shape)||[];this.result={face:l,body:u,hand:c,gesture:f,object:p,performance:this.performance,canvas:this.process.canvas,timestamp:Date.now(),error:null,get persons(){return xR(l,u,c,f,m)}},Y(i.tensor),this.emit("detect"),this.state="idle",s(this.result)})}async sleep(t){return new Promise(n=>{setTimeout(n,t)})}async video(t,n=!0,s=0){n?(jr(this,_i)[t.id]||(this.config.debug&&ee("video start",t.id),jr(this,_i)[t.id]=!0),!t.paused&&jr(this,_i)[t.id]&&t.readyState>=2&&await this.detect(t),s>0&&await this.sleep(s),jr(this,_i)[t.id]&&requestAnimationFrame(()=>this.video(t,n,s))):(this.config.debug&&ee("video stop",t.id),jr(this,_i)[t.id]=!1)}};Rd=new WeakMap,Yh=new WeakMap,Jh=new WeakMap,u1=new WeakMap,_i=new WeakMap;return a_(Fbe);})();