human/dist/human.js

8128 lines
1.4 MiB

/*
Human
homepage: <https://github.com/vladmandic/human>
author: <https://github.com/vladmandic>'
*/
"use strict";var Human=(()=>{var sc=Object.defineProperty;var MI=Object.getOwnPropertyDescriptor;var $I=Object.getOwnPropertyNames;var _I=Object.prototype.hasOwnProperty;var PI=(e,t,a)=>t in e?sc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a;var Cs=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(t,a)=>(typeof require!="undefined"?require:t)[a]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var hr=(e,t)=>{for(var a in t)sc(e,a,{get:t[a],enumerable:!0})},FI=(e,t,a,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of $I(t))!_I.call(e,r)&&r!==a&&sc(e,r,{get:()=>t[r],enumerable:!(n=MI(t,r))||n.enumerable});return e};var OI=e=>FI(sc({},"__esModule",{value:!0}),e);var ue=(e,t,a)=>(PI(e,typeof t!="symbol"?t+"":t,a),a),O5=(e,t,a)=>{if(!t.has(e))throw TypeError("Cannot "+a)};var Ga=(e,t,a)=>(O5(e,t,"read from private field"),a?a.call(e):t.get(e)),Gn=(e,t,a)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,a)},fr=(e,t,a,n)=>(O5(e,t,"write to private field"),n?n.call(e,a):t.set(e,a),a);var w0e={};hr(w0e,{Env:()=>Ap,Human:()=>A5,default:()=>A5,defaults:()=>Io,draw:()=>s0,empty:()=>or,env:()=>ne,match:()=>$0,models:()=>x5});var Ue={};hr(Ue,{Abs:()=>wl,Acos:()=>kl,Acosh:()=>Il,AdadeltaOptimizer:()=>Th,AdagradOptimizer:()=>Ch,AdamOptimizer:()=>Nh,AdamaxOptimizer:()=>Eh,Add:()=>ts,AddN:()=>Ks,All:()=>Zs,Any:()=>Ys,ArgMax:()=>Js,ArgMin:()=>kd,Asin:()=>Sl,Asinh:()=>Tl,Atan:()=>Cl,Atan2:()=>El,Atanh:()=>Nl,AvgPool:()=>Qs,AvgPool3D:()=>Hc,AvgPool3DGrad:()=>G1,AvgPoolGrad:()=>U1,BackendWasm:()=>I8,BatchMatMul:()=>ei,BatchToSpaceND:()=>Rl,Bincount:()=>Id,BroadcastArgs:()=>jc,BroadcastTo:()=>TS,Cast:()=>ti,Ceil:()=>ai,ClipByValue:()=>as,Complex:()=>Sd,ComplexAbs:()=>qc,Concat:()=>Ml,Conv2D:()=>ni,Conv2DBackpropFilter:()=>Xc,Conv2DBackpropInput:()=>ri,Conv3D:()=>Kc,Conv3DBackpropFilterV2:()=>H1,Conv3DBackpropInputV2:()=>Zc,Cos:()=>si,Cosh:()=>ii,CropAndResize:()=>ui,Cumprod:()=>oi,Cumsum:()=>li,DataStorage:()=>vd,DenseBincount:()=>Td,DepthToSpace:()=>di,DepthwiseConv2dNative:()=>pi,DepthwiseConv2dNativeBackpropFilter:()=>Yc,DepthwiseConv2dNativeBackpropInput:()=>Jc,Diag:()=>Qc,Dilation2D:()=>eh,Dilation2DBackpropFilter:()=>Gm,Dilation2DBackpropInput:()=>Um,ENV:()=>W1,Einsum:()=>Cd,Elu:()=>hi,EluGrad:()=>j1,Environment:()=>mA,Equal:()=>fi,Erf:()=>$l,Exp:()=>mi,ExpandDims:()=>_l,Expm1:()=>Pl,FFT:()=>Nd,Fill:()=>Fl,FlipLeftRight:()=>gi,Floor:()=>xi,FloorDiv:()=>Ai,FromPixels:()=>rd,FusedBatchNorm:()=>yi,FusedConv2D:()=>qr,FusedDepthwiseConv2D:()=>Xr,GPGPUContext:()=>il,GatherNd:()=>bi,GatherV2:()=>Ol,GraphModel:()=>op,Greater:()=>vi,GreaterEqual:()=>wi,IFFT:()=>Ed,Identity:()=>ki,Imag:()=>Rd,IsFinite:()=>Dl,IsInf:()=>zl,IsNan:()=>Ii,KernelBackend:()=>bl,LRN:()=>ah,LRNGrad:()=>q1,LeakyRelu:()=>Si,Less:()=>Ti,LessEqual:()=>Ci,LinSpace:()=>th,Log:()=>Ni,Log1p:()=>Ll,LogSoftmax:()=>CS,LogicalAnd:()=>Ei,LogicalNot:()=>Ri,LogicalOr:()=>Bl,LogicalXor:()=>xA,LowerBound:()=>NS,MathBackendCPU:()=>$h,MathBackendWebGL:()=>fu,Max:()=>Mi,MaxPool:()=>_i,MaxPool3D:()=>nh,MaxPool3DGrad:()=>K1,MaxPoolGrad:()=>X1,MaxPoolWithArgmax:()=>rh,Maximum:()=>$i,Mean:()=>Pi,Min:()=>Fi,Minimum:()=>Oi,MirrorPad:()=>Di,Mod:()=>Wl,MomentumOptimizer:()=>Rh,Multinomial:()=>sh,Multiply:()=>zi,Neg:()=>Vl,NonMaxSuppressionV3:()=>Bi,NonMaxSuppressionV4:()=>Ul,NonMaxSuppressionV5:()=>Wi,NotEqual:()=>Li,OP_SCOPE_SUFFIX:()=>e2,OneHot:()=>Vi,OnesLike:()=>Gl,Optimizer:()=>is,OptimizerConstructors:()=>Or,Pack:()=>Hl,PadV2:()=>Ui,Pool:()=>ES,Pow:()=>Gi,Prelu:()=>Hi,Prod:()=>ji,RMSPropOptimizer:()=>Mh,RaggedGather:()=>ih,RaggedRange:()=>oh,RaggedTensorToTensor:()=>lh,Range:()=>jl,Rank:()=>qm,Real:()=>Md,RealDiv:()=>ci,Reciprocal:()=>qi,Reduction:()=>ya,Relu:()=>Xi,Relu6:()=>Yi,Reshape:()=>ql,ResizeBilinear:()=>Zi,ResizeBilinearGrad:()=>Y1,ResizeNearestNeighbor:()=>Ki,ResizeNearestNeighborGrad:()=>Z1,Reverse:()=>Ji,RotateWithOffset:()=>mo,Round:()=>Xl,Rsqrt:()=>Qi,SGDOptimizer:()=>ip,ScatterNd:()=>eo,SearchSorted:()=>$d,Select:()=>Kl,Selu:()=>_d,Sigmoid:()=>ao,Sign:()=>Pd,Sin:()=>to,Sinh:()=>Yl,Slice:()=>Zl,Softmax:()=>so,Softplus:()=>Fd,SpaceToBatchND:()=>Jl,SparseFillEmptyRows:()=>Od,SparseReshape:()=>eu,SparseSegmentMean:()=>Dd,SparseSegmentSum:()=>zd,SparseToDense:()=>Ld,SplitV:()=>Ql,Sqrt:()=>no,Square:()=>Bd,SquaredDifference:()=>io,Step:()=>fo,StridedSlice:()=>oo,StringNGrams:()=>tu,StringSplit:()=>Wd,StringToHashBucketFast:()=>Vd,Sub:()=>lo,Sum:()=>ro,Tan:()=>uo,Tanh:()=>po,Tensor:()=>pt,TensorBuffer:()=>jt,Tile:()=>ns,TopK:()=>co,Transform:()=>ho,Transpose:()=>Ar,Unique:()=>uh,Unpack:()=>au,UnsortedSegmentSum:()=>dh,UpperBound:()=>RS,Variable:()=>od,WebGPUBackend:()=>Vh,ZerosLike:()=>nu,_FusedMatMul:()=>jr,abs:()=>qa,acos:()=>oy,acosh:()=>ly,add:()=>be,addN:()=>ch,all:()=>uy,any:()=>dy,argMax:()=>ar,argMin:()=>py,asin:()=>cy,asinh:()=>hy,atan:()=>fy,atan2:()=>my,atanh:()=>gy,avgPool:()=>b2,avgPool3d:()=>by,backend:()=>tr,backend_util:()=>T,basicLSTMCell:()=>vy,batchNorm:()=>Qd,batchNorm2d:()=>wy,batchNorm3d:()=>ky,batchNorm4d:()=>Iy,batchToSpaceND:()=>v2,bincount:()=>w2,booleanMaskAsync:()=>a4,broadcastArgs:()=>Sy,broadcastTo:()=>sl,broadcast_util:()=>xo,browser:()=>wr,buffer:()=>Me,cast:()=>He,ceil:()=>Ty,clipByValue:()=>Cy,clone:()=>wa,complex:()=>br,concat:()=>at,concat1d:()=>Ny,concat2d:()=>ru,concat3d:()=>Ey,concat4d:()=>Ry,conv1d:()=>My,conv2d:()=>ep,conv2dTranspose:()=>_y,conv3d:()=>Py,conv3dTranspose:()=>Fy,copyRegisteredKernels:()=>FS,cos:()=>Oy,cosh:()=>Dy,cosineWindow:()=>vh,cumprod:()=>zy,cumsum:()=>Ly,customGrad:()=>Qn,denseBincount:()=>By,deprecationWarn:()=>l2,depthToSpace:()=>Wy,depthwiseConv2d:()=>hh,deregisterOp:()=>yP,device_util:()=>jd,diag:()=>Vy,dilation2d:()=>Uy,disableDeprecationWarnings:()=>uC,dispose:()=>Y,disposeVariables:()=>dC,div:()=>me,divNoNan:()=>Gy,dot:()=>Hy,dropout:()=>o4,einsum:()=>jy,elu:()=>I2,enableDebugMode:()=>lC,enableProdMode:()=>o2,enclosingPowerOfTwo:()=>J2,engine:()=>kt,env:()=>W,equal:()=>k2,erf:()=>qy,euclideanNorm:()=>Zy,exp:()=>Zr,expandDims:()=>Gt,expm1:()=>Yy,eye:()=>T2,fft:()=>yh,fill:()=>nr,findBackend:()=>u2,findBackendFactory:()=>mC,floor:()=>C2,floorDiv:()=>Yd,forceHalfFloat:()=>G6,fused:()=>Q2,gather:()=>N2,gatherND:()=>i4,gather_util:()=>c2,getBackend:()=>ia,getGradient:()=>Hm,getKernel:()=>Sc,getKernelsForBackend:()=>Zn,getThreadsCount:()=>Ene,gpgpu_util:()=>w6,grad:()=>UE,grads:()=>GE,greater:()=>np,greaterEqual:()=>E2,ifft:()=>hd,imag:()=>Zd,image:()=>ge,inTopKAsync:()=>l4,io:()=>jn,irfft:()=>X2,isFinite:()=>Jy,isInf:()=>Qy,isNaN:()=>eb,keep:()=>On,kernel_impls:()=>Tn,leakyRelu:()=>R2,less:()=>tb,lessEqual:()=>fh,linalg:()=>g4,linspace:()=>ab,loadGraphModel:()=>r3,loadGraphModelSync:()=>kF,localResponseNormalization:()=>nb,log:()=>cl,log1p:()=>M2,logSigmoid:()=>sb,logSoftmax:()=>ib,logSumExp:()=>_2,logicalAnd:()=>pd,logicalNot:()=>P2,logicalOr:()=>F2,logicalXor:()=>ob,losses:()=>x4,lowerBound:()=>lb,matMul:()=>st,math:()=>UA,max:()=>pa,maxPool:()=>O2,maxPool3d:()=>ub,maxPoolWithArgmax:()=>db,maximum:()=>D2,mean:()=>cd,memory:()=>pC,meshgrid:()=>pb,min:()=>Kr,minimum:()=>z2,mirrorPad:()=>cb,mod:()=>su,moments:()=>hb,movingAverage:()=>n4,mul:()=>ae,multiRNNCell:()=>fb,multinomial:()=>mb,neg:()=>Xn,nextFrame:()=>b4,norm:()=>ap,notEqual:()=>L2,oneHot:()=>Nc,ones:()=>Wr,onesLike:()=>gb,op:()=>D,outerProduct:()=>xb,pad:()=>rr,pad1d:()=>Ab,pad2d:()=>yb,pad3d:()=>bb,pad4d:()=>vb,pool:()=>wb,pow:()=>pl,prelu:()=>W2,print:()=>r2,prod:()=>kb,profile:()=>cC,raggedGather:()=>Ib,raggedRange:()=>Sb,raggedTensorToTensor:()=>Tb,rand:()=>Cb,randomGamma:()=>Nb,randomNormal:()=>G2,randomStandardNormal:()=>Eb,randomUniform:()=>H2,range:()=>hl,ready:()=>Kd,real:()=>dl,reciprocal:()=>Rb,registerBackend:()=>go,registerGradient:()=>$S,registerKernel:()=>mn,registerOp:()=>AP,relu:()=>rp,relu6:()=>j2,removeBackend:()=>fC,reshape:()=>J,reverse:()=>Yr,reverse1d:()=>Mb,reverse2d:()=>$b,reverse3d:()=>_b,reverse4d:()=>Pb,rfft:()=>bh,round:()=>q2,rsqrt:()=>Fb,scalar:()=>Fe,scatterND:()=>r4,scatter_util:()=>h2,searchSorted:()=>gh,selu:()=>Ob,separableConv2d:()=>Db,serialization:()=>ay,setBackend:()=>Xd,setPlatform:()=>gC,setThreadsCount:()=>Nne,setWasmPath:()=>Cne,setWasmPaths:()=>Wh,setWebGLContext:()=>Fh,setdiff1dAsync:()=>zb,shared:()=>_h,sigmoid:()=>Da,sign:()=>Lb,signal:()=>m4,sin:()=>Bb,sinh:()=>Wb,slice:()=>Pe,slice1d:()=>Vb,slice2d:()=>Ub,slice3d:()=>sp,slice4d:()=>xh,slice_util:()=>It,softmax:()=>Ah,softplus:()=>$2,spaceToBatchND:()=>B2,sparse:()=>A4,sparseToDense:()=>s4,spectral:()=>f4,split:()=>ka,sqrt:()=>Jn,square:()=>In,squaredDifference:()=>K2,squeeze:()=>_e,stack:()=>sa,step:()=>Z2,stridedSlice:()=>Gb,string:()=>y4,sub:()=>fe,sum:()=>tt,sumOutType:()=>Hd,tan:()=>Hb,tanh:()=>Rc,tensor:()=>Be,tensor1d:()=>Ht,tensor2d:()=>Kn,tensor3d:()=>p2,tensor4d:()=>jb,tensor5d:()=>qb,tensor6d:()=>Xb,tensor_util:()=>vA,test_util:()=>ry,tidy:()=>$e,tile:()=>Gr,time:()=>hC,topk:()=>Kb,train:()=>m_,transpose:()=>Ws,truncatedNormal:()=>Zb,unique:()=>Yb,unregisterGradient:()=>PS,unregisterKernel:()=>_S,unsortedSegmentSum:()=>Jb,unstack:()=>Ta,upcastType:()=>ca,upperBound:()=>Qb,util:()=>v,valueAndGrad:()=>HE,valueAndGrads:()=>jE,variable:()=>e4,variableGrads:()=>rb,version:()=>xp,version_converter:()=>SF,version_core:()=>A2,version_cpu:()=>$O,version_wasm:()=>Rne,version_webgl:()=>AG,webgl:()=>yG,webgl_util:()=>j7,webgpu_util:()=>C8,where:()=>Vs,whereAsync:()=>Y2,zeros:()=>fn,zerosLike:()=>Ka});var DI=Object.create,z1=Object.defineProperty,zI=Object.getOwnPropertyDescriptor,LI=Object.getOwnPropertyNames,BI=Object.getPrototypeOf,WI=Object.prototype.hasOwnProperty,aA=(e=>typeof Cs!="undefined"?Cs:typeof Proxy!="undefined"?new Proxy(e,{get:(t,a)=>(typeof Cs!="undefined"?Cs:t)[a]}):e)(function(e){if(typeof Cs!="undefined")return Cs.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')}),qt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Xe=(e,t)=>{for(var a in t)z1(e,a,{get:t[a],enumerable:!0})},VI=(e,t,a,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of LI(t))!WI.call(e,r)&&r!==a&&z1(e,r,{get:()=>t[r],enumerable:!(n=zI(t,r))||n.enumerable});return e},yl=(e,t,a)=>(a=e!=null?DI(BI(e)):{},VI(t||!e||!e.__esModule?z1(a,"default",{value:e,enumerable:!0}):a,e)),UI=qt((e,t)=>{t.exports=n;var a=null;try{a=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(I){}function n(I,N,O){this.low=I|0,this.high=N|0,this.unsigned=!!O}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0});function r(I){return(I&&I.__isLong__)===!0}n.isLong=r;var s={},i={};function o(I,N){var O,L,B;return N?(I>>>=0,(B=0<=I&&I<256)&&(L=i[I],L)?L:(O=u(I,(I|0)<0?-1:0,!0),B&&(i[I]=O),O)):(I|=0,(B=-128<=I&&I<128)&&(L=s[I],L)?L:(O=u(I,I<0?-1:0,!1),B&&(s[I]=O),O))}n.fromInt=o;function l(I,N){if(isNaN(I))return N?b:y;if(N){if(I<0)return b;if(I>=g)return _}else{if(I<=-x)return $;if(I+1>=x)return E}return I<0?l(-I,N).neg():u(I%m|0,I/m|0,N)}n.fromNumber=l;function u(I,N,O){return new n(I,N,O)}n.fromBits=u;var p=Math.pow;function c(I,N,O){if(I.length===0)throw Error("empty string");if(I==="NaN"||I==="Infinity"||I==="+Infinity"||I==="-Infinity")return y;if(typeof N=="number"?(O=N,N=!1):N=!!N,O=O||10,O<2||36<O)throw RangeError("radix");var L;if((L=I.indexOf("-"))>0)throw Error("interior hyphen");if(L===0)return c(I.substring(1),N,O).neg();for(var B=l(p(O,8)),G=y,j=0;j<I.length;j+=8){var U=Math.min(8,I.length-j),H=parseInt(I.substring(j,j+U),O);if(U<8){var V=l(p(O,U));G=G.mul(V).add(l(H))}else G=G.mul(B),G=G.add(l(H))}return G.unsigned=N,G}n.fromString=c;function d(I,N){return typeof I=="number"?l(I,N):typeof I=="string"?c(I,N):u(I.low,I.high,typeof N=="boolean"?N:I.unsigned)}n.fromValue=d;var h=1<<16,f=1<<24,m=h*h,g=m*m,x=g/2,A=o(f),y=o(0);n.ZERO=y;var b=o(0,!0);n.UZERO=b;var w=o(1);n.ONE=w;var S=o(1,!0);n.UONE=S;var C=o(-1);n.NEG_ONE=C;var E=u(-1,2147483647,!1);n.MAX_VALUE=E;var _=u(-1,-1,!0);n.MAX_UNSIGNED_VALUE=_;var $=u(0,-2147483648,!1);n.MIN_VALUE=$;var M=n.prototype;M.toInt=function(){return this.unsigned?this.low>>>0:this.low},M.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},M.toString=function(I){if(I=I||10,I<2||36<I)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq($)){var N=l(I),O=this.div(N),L=O.mul(N).sub(this);return O.toString(I)+L.toInt().toString(I)}else return"-"+this.neg().toString(I);for(var B=l(p(I,6),this.unsigned),G=this,j="";;){var U=G.div(B),H=G.sub(U.mul(B)).toInt()>>>0,V=H.toString(I);if(G=U,G.isZero())return V+j;for(;V.length<6;)V="0"+V;j=""+V+j}},M.getHighBits=function(){return this.high},M.getHighBitsUnsigned=function(){return this.high>>>0},M.getLowBits=function(){return this.low},M.getLowBitsUnsigned=function(){return this.low>>>0},M.getNumBitsAbs=function(){if(this.isNegative())return this.eq($)?64:this.neg().getNumBitsAbs();for(var I=this.high!=0?this.high:this.low,N=31;N>0&&(I&1<<N)==0;N--);return this.high!=0?N+33:N+1},M.isZero=function(){return this.high===0&&this.low===0},M.eqz=M.isZero,M.isNegative=function(){return!this.unsigned&&this.high<0},M.isPositive=function(){return this.unsigned||this.high>=0},M.isOdd=function(){return(this.low&1)===1},M.isEven=function(){return(this.low&1)===0},M.equals=function(I){return r(I)||(I=d(I)),this.unsigned!==I.unsigned&&this.high>>>31===1&&I.high>>>31===1?!1:this.high===I.high&&this.low===I.low},M.eq=M.equals,M.notEquals=function(I){return!this.eq(I)},M.neq=M.notEquals,M.ne=M.notEquals,M.lessThan=function(I){return this.comp(I)<0},M.lt=M.lessThan,M.lessThanOrEqual=function(I){return this.comp(I)<=0},M.lte=M.lessThanOrEqual,M.le=M.lessThanOrEqual,M.greaterThan=function(I){return this.comp(I)>0},M.gt=M.greaterThan,M.greaterThanOrEqual=function(I){return this.comp(I)>=0},M.gte=M.greaterThanOrEqual,M.ge=M.greaterThanOrEqual,M.compare=function(I){if(r(I)||(I=d(I)),this.eq(I))return 0;var N=this.isNegative(),O=I.isNegative();return N&&!O?-1:!N&&O?1:this.unsigned?I.high>>>0>this.high>>>0||I.high===this.high&&I.low>>>0>this.low>>>0?-1:1:this.sub(I).isNegative()?-1:1},M.comp=M.compare,M.negate=function(){return!this.unsigned&&this.eq($)?$:this.not().add(w)},M.neg=M.negate,M.add=function(I){r(I)||(I=d(I));var N=this.high>>>16,O=this.high&65535,L=this.low>>>16,B=this.low&65535,G=I.high>>>16,j=I.high&65535,U=I.low>>>16,H=I.low&65535,V=0,Q=0,Z=0,re=0;return re+=B+H,Z+=re>>>16,re&=65535,Z+=L+U,Q+=Z>>>16,Z&=65535,Q+=O+j,V+=Q>>>16,Q&=65535,V+=N+G,V&=65535,u(Z<<16|re,V<<16|Q,this.unsigned)},M.subtract=function(I){return r(I)||(I=d(I)),this.add(I.neg())},M.sub=M.subtract,M.multiply=function(I){if(this.isZero())return y;if(r(I)||(I=d(I)),a){var N=a.mul(this.low,this.high,I.low,I.high);return u(N,a.get_high(),this.unsigned)}if(I.isZero())return y;if(this.eq($))return I.isOdd()?$:y;if(I.eq($))return this.isOdd()?$:y;if(this.isNegative())return I.isNegative()?this.neg().mul(I.neg()):this.neg().mul(I).neg();if(I.isNegative())return this.mul(I.neg()).neg();if(this.lt(A)&&I.lt(A))return l(this.toNumber()*I.toNumber(),this.unsigned);var O=this.high>>>16,L=this.high&65535,B=this.low>>>16,G=this.low&65535,j=I.high>>>16,U=I.high&65535,H=I.low>>>16,V=I.low&65535,Q=0,Z=0,re=0,ee=0;return ee+=G*V,re+=ee>>>16,ee&=65535,re+=B*V,Z+=re>>>16,re&=65535,re+=G*H,Z+=re>>>16,re&=65535,Z+=L*V,Q+=Z>>>16,Z&=65535,Z+=B*H,Q+=Z>>>16,Z&=65535,Z+=G*U,Q+=Z>>>16,Z&=65535,Q+=O*V+L*H+B*U+G*j,Q&=65535,u(re<<16|ee,Q<<16|Z,this.unsigned)},M.mul=M.multiply,M.divide=function(I){if(r(I)||(I=d(I)),I.isZero())throw Error("division by zero");if(a){if(!this.unsigned&&this.high===-2147483648&&I.low===-1&&I.high===-1)return this;var N=(this.unsigned?a.div_u:a.div_s)(this.low,this.high,I.low,I.high);return u(N,a.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?b:y;var O,L,B;if(this.unsigned){if(I.unsigned||(I=I.toUnsigned()),I.gt(this))return b;if(I.gt(this.shru(1)))return S;B=b}else{if(this.eq($)){if(I.eq(w)||I.eq(C))return $;if(I.eq($))return w;var G=this.shr(1);return O=G.div(I).shl(1),O.eq(y)?I.isNegative()?w:C:(L=this.sub(I.mul(O)),B=O.add(L.div(I)),B)}else if(I.eq($))return this.unsigned?b:y;if(this.isNegative())return I.isNegative()?this.neg().div(I.neg()):this.neg().div(I).neg();if(I.isNegative())return this.div(I.neg()).neg();B=y}for(L=this;L.gte(I);){O=Math.max(1,Math.floor(L.toNumber()/I.toNumber()));for(var j=Math.ceil(Math.log(O)/Math.LN2),U=j<=48?1:p(2,j-48),H=l(O),V=H.mul(I);V.isNegative()||V.gt(L);)O-=U,H=l(O,this.unsigned),V=H.mul(I);H.isZero()&&(H=w),B=B.add(H),L=L.sub(V)}return B},M.div=M.divide,M.modulo=function(I){if(r(I)||(I=d(I)),a){var N=(this.unsigned?a.rem_u:a.rem_s)(this.low,this.high,I.low,I.high);return u(N,a.get_high(),this.unsigned)}return this.sub(this.div(I).mul(I))},M.mod=M.modulo,M.rem=M.modulo,M.not=function(){return u(~this.low,~this.high,this.unsigned)},M.and=function(I){return r(I)||(I=d(I)),u(this.low&I.low,this.high&I.high,this.unsigned)},M.or=function(I){return r(I)||(I=d(I)),u(this.low|I.low,this.high|I.high,this.unsigned)},M.xor=function(I){return r(I)||(I=d(I)),u(this.low^I.low,this.high^I.high,this.unsigned)},M.shiftLeft=function(I){return r(I)&&(I=I.toInt()),(I&=63)===0?this:I<32?u(this.low<<I,this.high<<I|this.low>>>32-I,this.unsigned):u(0,this.low<<I-32,this.unsigned)},M.shl=M.shiftLeft,M.shiftRight=function(I){return r(I)&&(I=I.toInt()),(I&=63)===0?this:I<32?u(this.low>>>I|this.high<<32-I,this.high>>I,this.unsigned):u(this.high>>I-32,this.high>=0?0:-1,this.unsigned)},M.shr=M.shiftRight,M.shiftRightUnsigned=function(I){if(r(I)&&(I=I.toInt()),I&=63,I===0)return this;var N=this.high;if(I<32){var O=this.low;return u(O>>>I|N<<32-I,N>>>I,this.unsigned)}else return I===32?u(N,0,this.unsigned):u(N>>>I-32,0,this.unsigned)},M.shru=M.shiftRightUnsigned,M.shr_u=M.shiftRightUnsigned,M.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},M.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},M.toBytes=function(I){return I?this.toBytesLE():this.toBytesBE()},M.toBytesLE=function(){var I=this.high,N=this.low;return[N&255,N>>>8&255,N>>>16&255,N>>>24,I&255,I>>>8&255,I>>>16&255,I>>>24]},M.toBytesBE=function(){var I=this.high,N=this.low;return[I>>>24,I>>>16&255,I>>>8&255,I&255,N>>>24,N>>>16&255,N>>>8&255,N&255]},n.fromBytes=function(I,N,O){return O?n.fromBytesLE(I,N):n.fromBytesBE(I,N)},n.fromBytesLE=function(I,N){return new n(I[0]|I[1]<<8|I[2]<<16|I[3]<<24,I[4]|I[5]<<8|I[6]<<16|I[7]<<24,N)},n.fromBytesBE=function(I,N){return new n(I[4]<<24|I[5]<<16|I[6]<<8|I[7],I[0]<<24|I[1]<<16|I[2]<<8|I[3],N)}}),GI=qt(()=>{}),HI=qt(()=>{}),jI=qt((e,t)=>{(function(a,n,r){function s(u){var p=this,c=l();p.next=function(){var d=2091639*p.s0+p.c*23283064365386963e-26;return p.s0=p.s1,p.s1=p.s2,p.s2=d-(p.c=d|0)},p.c=1,p.s0=c(" "),p.s1=c(" "),p.s2=c(" "),p.s0-=c(u),p.s0<0&&(p.s0+=1),p.s1-=c(u),p.s1<0&&(p.s1+=1),p.s2-=c(u),p.s2<0&&(p.s2+=1),c=null}function i(u,p){return p.c=u.c,p.s0=u.s0,p.s1=u.s1,p.s2=u.s2,p}function o(u,p){var c=new s(u),d=p&&p.state,h=c.next;return h.int32=function(){return c.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,d&&(typeof d=="object"&&i(d,c),h.state=function(){return i(c,{})}),h}function l(){var u=4022871197,p=function(c){c=String(c);for(var d=0;d<c.length;d++){u+=c.charCodeAt(d);var h=.02519603282416938*u;u=h>>>0,h-=u,h*=u,u=h>>>0,h-=u,u+=h*4294967296}return(u>>>0)*23283064365386963e-26};return p}n&&n.exports?n.exports=o:r&&r.amd?r(function(){return o}):this.alea=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),qI=qt((e,t)=>{(function(a,n,r){function s(l){var u=this,p="";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:p+=l;for(var c=0;c<p.length+64;c++)u.x^=p.charCodeAt(c)|0,u.next()}function i(l,u){return u.x=l.x,u.y=l.y,u.z=l.z,u.w=l.w,u}function o(l,u){var p=new s(l),c=u&&u.state,d=function(){return(p.next()>>>0)/4294967296};return d.double=function(){do var h=p.next()>>>11,f=(p.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},d.int32=p.next,d.quick=d,c&&(typeof c=="object"&&i(c,p),d.state=function(){return i(p,{})}),d}n&&n.exports?n.exports=o:r&&r.amd?r(function(){return o}):this.xor128=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),XI=qt((e,t)=>{(function(a,n,r){function s(l){var u=this,p="";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:p+=l;for(var c=0;c<p.length+64;c++)u.x^=p.charCodeAt(c)|0,c==p.length&&(u.d=u.x<<10^u.x>>>4),u.next()}function i(l,u){return u.x=l.x,u.y=l.y,u.z=l.z,u.w=l.w,u.v=l.v,u.d=l.d,u}function o(l,u){var p=new s(l),c=u&&u.state,d=function(){return(p.next()>>>0)/4294967296};return d.double=function(){do var h=p.next()>>>11,f=(p.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},d.int32=p.next,d.quick=d,c&&(typeof c=="object"&&i(c,p),d.state=function(){return i(p,{})}),d}n&&n.exports?n.exports=o:r&&r.amd?r(function(){return o}):this.xorwow=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),KI=qt((e,t)=>{(function(a,n,r){function s(l){var u=this;u.next=function(){var c=u.x,d=u.i,h,f,m;return h=c[d],h^=h>>>7,f=h^h<<24,h=c[d+1&7],f^=h^h>>>10,h=c[d+3&7],f^=h^h>>>3,h=c[d+4&7],f^=h^h<<7,h=c[d+7&7],h=h^h<<13,f^=h^h<<9,c[d]=f,u.i=d+1&7,f};function p(c,d){var h,f,m=[];if(d===(d|0))f=m[0]=d;else for(d=""+d,h=0;h<d.length;++h)m[h&7]=m[h&7]<<15^d.charCodeAt(h)+m[h+1&7]<<13;for(;m.length<8;)m.push(0);for(h=0;h<8&&m[h]===0;++h);for(h==8?f=m[7]=-1:f=m[h],c.x=m,c.i=0,h=256;h>0;--h)c.next()}p(u,l)}function i(l,u){return u.x=l.x.slice(),u.i=l.i,u}function o(l,u){l==null&&(l=+new Date);var p=new s(l),c=u&&u.state,d=function(){return(p.next()>>>0)/4294967296};return d.double=function(){do var h=p.next()>>>11,f=(p.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},d.int32=p.next,d.quick=d,c&&(c.x&&i(c,p),d.state=function(){return i(p,{})}),d}n&&n.exports?n.exports=o:r&&r.amd?r(function(){return o}):this.xorshift7=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),ZI=qt((e,t)=>{(function(a,n,r){function s(l){var u=this;u.next=function(){var c=u.w,d=u.X,h=u.i,f,m;return u.w=c=c+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+(c^c>>>16)|0};function p(c,d){var h,f,m,g,x,A=[],y=128;for(d===(d|0)?(f=d,d=null):(d=d+"\0",f=0,y=Math.max(y,d.length)),m=0,g=-32;g<y;++g)d&&(f^=d.charCodeAt((g+32)%d.length)),g===0&&(x=f),f^=f<<10,f^=f>>>15,f^=f<<4,f^=f>>>13,g>=0&&(x=x+1640531527|0,h=A[g&127]^=f+x,m=h==0?m+1:0);for(m>=128&&(A[(d&&d.length||0)&127]=-1),m=127,g=4*128;g>0;--g)f=A[m+34&127],h=A[m=m+1&127],f^=f<<13,h^=h<<17,f^=f>>>15,h^=h>>>12,A[m]=f^h;c.w=x,c.X=A,c.i=m}p(u,l)}function i(l,u){return u.i=l.i,u.w=l.w,u.X=l.X.slice(),u}function o(l,u){l==null&&(l=+new Date);var p=new s(l),c=u&&u.state,d=function(){return(p.next()>>>0)/4294967296};return d.double=function(){do var h=p.next()>>>11,f=(p.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},d.int32=p.next,d.quick=d,c&&(c.X&&i(c,p),d.state=function(){return i(p,{})}),d}n&&n.exports?n.exports=o:r&&r.amd?r(function(){return o}):this.xor4096=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),YI=qt((e,t)=>{(function(a,n,r){function s(l){var u=this,p="";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):p+=l;for(var c=0;c<p.length+20;c++)u.b^=p.charCodeAt(c)|0,u.next()}function i(l,u){return u.a=l.a,u.b=l.b,u.c=l.c,u.d=l.d,u}function o(l,u){var p=new s(l),c=u&&u.state,d=function(){return(p.next()>>>0)/4294967296};return d.double=function(){do var h=p.next()>>>11,f=(p.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},d.int32=p.next,d.quick=d,c&&(typeof c=="object"&&i(c,p),d.state=function(){return i(p,{})}),d}n&&n.exports?n.exports=o:r&&r.amd?r(function(){return o}):this.tychei=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),JI=qt(()=>{}),QI=qt((e,t)=>{(function(a,n,r){var s=256,i=6,o=52,l="random",u=r.pow(s,i),p=r.pow(2,o),c=p*2,d=s-1,h;function f(w,S,C){var E=[];S=S==!0?{entropy:!0}:S||{};var _=A(x(S.entropy?[w,b(n)]:w==null?y():w,3),E),$=new m(E),M=function(){for(var I=$.g(i),N=u,O=0;I<p;)I=(I+O)*s,N*=s,O=$.g(1);for(;I>=c;)I/=2,N/=2,O>>>=1;return(I+O)/N};return M.int32=function(){return $.g(4)|0},M.quick=function(){return $.g(4)/4294967296},M.double=M,A(b($.S),n),(S.pass||C||function(I,N,O,L){return L&&(L.S&&g(L,$),I.state=function(){return g($,{})}),O?(r[l]=I,N):I})(M,_,"global"in S?S.global:this==r,S.state)}function m(w){var S,C=w.length,E=this,_=0,$=E.i=E.j=0,M=E.S=[];for(C||(w=[C++]);_<s;)M[_]=_++;for(_=0;_<s;_++)M[_]=M[$=d&$+w[_%C]+(S=M[_])],M[$]=S;(E.g=function(I){for(var N,O=0,L=E.i,B=E.j,G=E.S;I--;)N=G[L=d&L+1],O=O*s+G[d&(G[L]=G[B=d&B+N])+(G[B]=N)];return E.i=L,E.j=B,O})(s)}function g(w,S){return S.i=w.i,S.j=w.j,S.S=w.S.slice(),S}function x(w,S){var C=[],E=typeof w,_;if(S&&E=="object")for(_ in w)try{C.push(x(w[_],S-1))}catch($){}return C.length?C:E=="string"?w:w+"\0"}function A(w,S){for(var C=w+"",E,_=0;_<C.length;)S[d&_]=d&(E^=S[d&_]*19)+C.charCodeAt(_++);return b(S)}function y(){try{var w;return h&&(w=h.randomBytes)?w=w(s):(w=new Uint8Array(s),(a.crypto||a.msCrypto).getRandomValues(w)),b(w)}catch(E){var S=a.navigator,C=S&&S.plugins;return[+new Date,a,C,a.screen,b(n)]}}function b(w){return String.fromCharCode.apply(0,w)}if(A(r.random(),n),typeof t=="object"&&t.exports){t.exports=f;try{h=JI()}catch(w){}}else typeof define=="function"&&define.amd?define(function(){return f}):r["seed"+l]=f})(typeof self!="undefined"?self:e,[],Math)}),nA=qt((e,t)=>{var a=jI(),n=qI(),r=XI(),s=KI(),i=ZI(),o=YI(),l=QI();l.alea=a,l.xor128=n,l.xorwow=r,l.xorshift7=s,l.xor4096=i,l.tychei=o,t.exports=l}),wc=qt(()=>{}),rA=qt(()=>{}),eS=qt(()=>{}),tS=qt(()=>{}),aS=qt(()=>{}),nS=qt((e,t)=>{var a=(()=>{var n=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(n=n||__filename),function(r){r=r||{};function s(){return oe.buffer!=je&&dt(oe.buffer),ht}function i(){return oe.buffer!=je&&dt(oe.buffer),Va}function o(){return oe.buffer!=je&&dt(oe.buffer),Ft}function l(){return oe.buffer!=je&&dt(oe.buffer),aa}function u(){return oe.buffer!=je&&dt(oe.buffer),$a}function p(){return oe.buffer!=je&&dt(oe.buffer),on}function c(){return oe.buffer!=je&&dt(oe.buffer),_a}var d=typeof r!="undefined"?r:{},h,f;d.ready=new Promise(function(F,q){h=F,f=q});var m;typeof process!="undefined"&&process.listeners&&(m={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var g=Object.assign({},d),x=[],A="./this.program",y=(F,q)=>{throw q},b=typeof window=="object",w=typeof importScripts=="function",S=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",C=d.ENVIRONMENT_IS_PTHREAD||!1,E="";function _(F){return d.locateFile?d.locateFile(F,E):E+F}var $,M,I,N;function O(F){F instanceof Ss||H("exiting due to exception: "+F)}if(S){w?E=wc().dirname(E)+"/":E=__dirname+"/";var L,B;typeof aA=="function"&&(L=rA(),B=wc()),$=(q,se)=>(q=B.normalize(q),L.readFileSync(q,se?void 0:"utf8")),I=q=>{var se=$(q,!0);return se.buffer||(se=new Uint8Array(se)),se},M=(q,se,pe)=>{q=B.normalize(q),L.readFile(q,function(Te,Je){Te?pe(Te):se(Je.buffer)})},process.argv.length>1&&(A=process.argv[1].replace(/\\/g,"/")),x=process.argv.slice(2),process.on("uncaughtException",function(q){if(!(q instanceof Ss))throw q}),process.on("unhandledRejection",function(q){throw q}),y=(q,se)=>{if(bn())throw process.exitCode=q,se;O(se),process.exit(q)},d.inspect=function(){return"[Emscripten Module object]"};let F;try{F=eS()}catch(q){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),q}global.Worker=F.Worker}else(b||w)&&(w?E=self.location.href:typeof document!="undefined"&&document.currentScript&&(E=document.currentScript.src),typeof n!="undefined"&&n&&(E=n),E.indexOf("blob:")!==0?E=E.substr(0,E.replace(/[?#].*/,"").lastIndexOf("/")+1):E="",S||($=F=>{var q=new XMLHttpRequest;return q.open("GET",F,!1),q.send(null),q.responseText},w&&(I=F=>{var q=new XMLHttpRequest;return q.open("GET",F,!1),q.responseType="arraybuffer",q.send(null),new Uint8Array(q.response)}),M=(F,q,se)=>{var pe=new XMLHttpRequest;pe.open("GET",F,!0),pe.responseType="arraybuffer",pe.onload=()=>{if(pe.status==200||pe.status==0&&pe.response){q(pe.response);return}se()},pe.onerror=se,pe.send(null)}),N=F=>document.title=F);S&&typeof performance=="undefined"&&(global.performance=tS().performance);var G=console.log.bind(console),j=console.warn.bind(console);S&&(G=F=>L.writeSync(1,F+`
`),j=F=>L.writeSync(2,F+`
`));var U=d.print||G,H=d.printErr||j;Object.assign(d,g),g=null,d.arguments&&(x=d.arguments),d.thisProgram&&(A=d.thisProgram),d.quit&&(y=d.quit);var V=4,Q=Atomics.load,Z=Atomics.store,re=Atomics.compareExchange,ee;d.wasmBinary&&(ee=d.wasmBinary);var he=d.noExitRuntime||!0;typeof WebAssembly!="object"&&Uo("no native wasm support detected");var oe,Ae,we=!1,Re;function Ge(F,q){F||Uo(q)}var Ke=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function nt(F,q,se){for(var pe=q+se,Te=q;F[Te]&&!(Te>=pe);)++Te;if(Te-q>16&&F.buffer&&Ke)return Ke.decode(F.buffer instanceof SharedArrayBuffer?F.slice(q,Te):F.subarray(q,Te));for(var Je="";q<Te;){var Oe=F[q++];if(!(Oe&128)){Je+=String.fromCharCode(Oe);continue}var We=F[q++]&63;if((Oe&224)==192){Je+=String.fromCharCode((Oe&31)<<6|We);continue}var Dt=F[q++]&63;if((Oe&240)==224?Oe=(Oe&15)<<12|We<<6|Dt:Oe=(Oe&7)<<18|We<<12|Dt<<6|F[q++]&63,Oe<65536)Je+=String.fromCharCode(Oe);else{var un=Oe-65536;Je+=String.fromCharCode(55296|un>>10,56320|un&1023)}}return Je}function ut(F,q){return F?nt(i(),F,q):""}function et(F,q,se,pe){if(!(pe>0))return 0;for(var Te=se,Je=se+pe-1,Oe=0;Oe<F.length;++Oe){var We=F.charCodeAt(Oe);if(We>=55296&&We<=57343){var Dt=F.charCodeAt(++Oe);We=65536+((We&1023)<<10)|Dt&1023}if(We<=127){if(se>=Je)break;q[se++]=We}else if(We<=2047){if(se+1>=Je)break;q[se++]=192|We>>6,q[se++]=128|We&63}else if(We<=65535){if(se+2>=Je)break;q[se++]=224|We>>12,q[se++]=128|We>>6&63,q[se++]=128|We&63}else{if(se+3>=Je)break;q[se++]=240|We>>18,q[se++]=128|We>>12&63,q[se++]=128|We>>6&63,q[se++]=128|We&63}}return q[se]=0,se-Te}function rt(F,q,se){return et(F,i(),q,se)}var je,ht,Va,Ft,sn,aa,$a,on,_a;C&&(je=d.buffer);function dt(F){je=F,d.HEAP8=ht=new Int8Array(F),d.HEAP16=Ft=new Int16Array(F),d.HEAP32=aa=new Int32Array(F),d.HEAPU8=Va=new Uint8Array(F),d.HEAPU16=sn=new Uint16Array(F),d.HEAPU32=$a=new Uint32Array(F),d.HEAPF32=on=new Float32Array(F),d.HEAPF64=_a=new Float64Array(F)}var Pa=d.INITIAL_MEMORY||16777216;if(C)oe=d.wasmMemory,je=d.buffer;else if(d.wasmMemory)oe=d.wasmMemory;else if(oe=new WebAssembly.Memory({initial:Pa/65536,maximum:32768,shared:!0}),!(oe.buffer instanceof SharedArrayBuffer))throw H("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"),S&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");oe&&(je=oe.buffer),Pa=je.byteLength,dt(je);var Ua,ur=[],Bo=[],Un=[],$u=!1;function bn(){return he}function Wo(){if(d.preRun)for(typeof d.preRun=="function"&&(d.preRun=[d.preRun]);d.preRun.length;)U0(d.preRun.shift());Ou(ur)}function Xt(){$u=!0,!C&&Ou(Bo)}function _p(){if(!C){if(d.postRun)for(typeof d.postRun=="function"&&(d.postRun=[d.postRun]);d.postRun.length;)y5(d.postRun.shift());Ou(Un)}}function U0(F){ur.unshift(F)}function G0(F){Bo.unshift(F)}function y5(F){Un.unshift(F)}var _r=0,Vo=null,dr=null;function b5(F){_r++,d.monitorRunDependencies&&d.monitorRunDependencies(_r)}function v5(F){if(_r--,d.monitorRunDependencies&&d.monitorRunDependencies(_r),_r==0&&(Vo!==null&&(clearInterval(Vo),Vo=null),dr)){var q=dr;dr=null,q()}}function Uo(F){C?postMessage({cmd:"onAbort",arg:F}):d.onAbort&&d.onAbort(F),F="Aborted("+F+")",H(F),we=!0,Re=1,F+=". Build with -sASSERTIONS for more info.";var q=new WebAssembly.RuntimeError(F);throw f(q),q}var H0="data:application/octet-stream;base64,";function Pp(F){return F.startsWith(H0)}function _u(F){return F.startsWith("file://")}var xa;xa="tfjs-backend-wasm-threaded-simd.wasm",Pp(xa)||(xa=_(xa));function Fp(F){try{if(F==xa&&ee)return new Uint8Array(ee);if(I)return I(F);throw"both async and sync fetching of the wasm failed"}catch(q){Uo(q)}}function j0(){if(!ee&&(b||w)){if(typeof fetch=="function"&&!_u(xa))return fetch(xa,{credentials:"same-origin"}).then(function(F){if(!F.ok)throw"failed to load wasm binary file at '"+xa+"'";return F.arrayBuffer()}).catch(function(){return Fp(xa)});if(M)return new Promise(function(F,q){M(xa,function(se){F(new Uint8Array(se))},q)})}return Promise.resolve().then(function(){return Fp(xa)})}function q0(){var F={env:qp,wasi_snapshot_preview1:qp};function q(Oe,We){var Dt=Oe.exports;if(d.asm=Dt,nf(d.asm._emscripten_tls_init),Ua=d.asm.__indirect_function_table,G0(d.asm.__wasm_call_ctors),Ae=We,!C){var un=Le.unusedWorkers.length;Le.unusedWorkers.forEach(function(cr){Le.loadWasmModuleToWorker(cr,function(){--un||v5("wasm-instantiate")})})}}C||b5("wasm-instantiate");function se(Oe){q(Oe.instance,Oe.module)}function pe(Oe){return j0().then(function(We){return WebAssembly.instantiate(We,F)}).then(function(We){return We}).then(Oe,function(We){H("failed to asynchronously prepare wasm: "+We),Uo(We)})}function Te(){return!ee&&typeof WebAssembly.instantiateStreaming=="function"&&!Pp(xa)&&!_u(xa)&&!S&&typeof fetch=="function"?fetch(xa,{credentials:"same-origin"}).then(function(Oe){var We=WebAssembly.instantiateStreaming(Oe,F);return We.then(se,function(Dt){return H("wasm streaming compile failed: "+Dt),H("falling back to ArrayBuffer instantiation"),pe(se)})}):pe(se)}if(d.instantiateWasm)try{var Je=d.instantiateWasm(F,q);return Je}catch(Oe){H("Module.instantiateWasm callback failed with error: "+Oe),f(Oe)}return Te().catch(f),{}}var X0,w5,K0={};function Ss(F){this.name="ExitStatus",this.message="Program terminated with exit("+F+")",this.status=F}function Z0(F){var q=Le.pthreads[F];delete Le.pthreads[F],q.terminate(),Nm(F),Le.runningWorkers.splice(Le.runningWorkers.indexOf(q),1),q.pthread_ptr=0}function Y0(F){var q=Le.pthreads[F];q.postMessage({cmd:"cancel"})}function Pu(F){var q=Le.pthreads[F];Ge(q),Le.returnWorkerToPool(q)}function Op(F){var q=Le.getNewWorker();if(!q)return 6;Le.runningWorkers.push(q),Le.pthreads[F.pthread_ptr]=q,q.pthread_ptr=F.pthread_ptr;var se={cmd:"run",start_routine:F.startRoutine,arg:F.arg,pthread_ptr:F.pthread_ptr};return q.runPthread=()=>{se.time=performance.now(),q.postMessage(se,F.transferList)},q.loaded&&(q.runPthread(),delete q.runPthread),0}var Dp={varargs:void 0,get:function(){Dp.varargs+=4;var F=l()[Dp.varargs-4>>2];return F},getStr:function(F){var q=ut(F);return q}};function Fu(F){if(C)return Pr(1,1,F);Re=F,bn()||(Le.terminateAllThreads(),d.onExit&&d.onExit(F),we=!0),y(F,new Ss(F))}function k5(F,q){if(Re=F,!q&&C)throw Lp(F),"unwind";Fu(F)}var zp=k5;function J0(F){if(F instanceof Ss||F=="unwind")return Re;y(1,F)}var Le={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init:function(){C?Le.initWorker():Le.initMainThread()},initMainThread:function(){for(var F=8;F--;)Le.allocateUnusedWorker()},initWorker:function(){he=!1},setExitStatus:function(F){Re=F},terminateAllThreads:function(){for(var F of Object.values(Le.pthreads))Le.returnWorkerToPool(F);for(var F of Le.unusedWorkers)F.terminate();Le.unusedWorkers=[]},returnWorkerToPool:function(F){var q=F.pthread_ptr;delete Le.pthreads[q],Le.unusedWorkers.push(F),Le.runningWorkers.splice(Le.runningWorkers.indexOf(F),1),F.pthread_ptr=0,Nm(q)},receiveObjectTransfer:function(F){},threadInitTLS:function(){Le.tlsInitFunctions.forEach(F=>F())},loadWasmModuleToWorker:function(F,q){F.onmessage=se=>{var pe=se.data,Te=pe.cmd;if(F.pthread_ptr&&(Le.currentProxiedOperationCallerThread=F.pthread_ptr),pe.targetThread&&pe.targetThread!=Qp()){var Je=Le.pthreads[pe.targetThread];Je?Je.postMessage(pe,pe.transferList):H('Internal error! Worker sent a message "'+Te+'" to target pthread '+pe.targetThread+", but that thread no longer exists!"),Le.currentProxiedOperationCallerThread=void 0;return}Te==="processProxyingQueue"?Du(pe.queue):Te==="spawnThread"?Op(pe):Te==="cleanupThread"?Pu(pe.thread):Te==="killThread"?Z0(pe.thread):Te==="cancelThread"?Y0(pe.thread):Te==="loaded"?(F.loaded=!0,q&&q(F),F.runPthread&&(F.runPthread(),delete F.runPthread)):Te==="print"?U("Thread "+pe.threadId+": "+pe.text):Te==="printErr"?H("Thread "+pe.threadId+": "+pe.text):Te==="alert"?alert("Thread "+pe.threadId+": "+pe.text):pe.target==="setimmediate"?F.postMessage(pe):Te==="onAbort"?d.onAbort&&d.onAbort(pe.arg):Te&&H("worker sent an unknown command "+Te),Le.currentProxiedOperationCallerThread=void 0},F.onerror=se=>{var pe="worker sent an error!";throw H(pe+" "+se.filename+":"+se.lineno+": "+se.message),se},S&&(F.on("message",function(se){F.onmessage({data:se})}),F.on("error",function(se){F.onerror(se)}),F.on("detachedExit",function(){})),F.postMessage({cmd:"load",urlOrBlob:d.mainScriptUrlOrBlob||n,wasmMemory:oe,wasmModule:Ae})},allocateUnusedWorker:function(){var F=_("tfjs-backend-wasm-threaded-simd.worker.js");Le.unusedWorkers.push(new Worker(F))},getNewWorker:function(){return Le.unusedWorkers.length==0&&(Le.allocateUnusedWorker(),Le.loadWasmModuleToWorker(Le.unusedWorkers[0])),Le.unusedWorkers.pop()}};d.PThread=Le;function Ou(F){for(;F.length>0;)F.shift()(d)}function Q0(F){var q=Em(),se=F();return ec(q),se}function I5(F){return F}function S5(F){var q=/\b_Z[\w\d_]+/g;return F.replace(q,function(se){var pe=se;return se===pe?se:pe+" ["+se+"]"})}function ef(){var F=Qp(),q=l()[F+44>>2],se=l()[F+48>>2],pe=q-se;$5(q,pe),ec(q)}d.establishStackSpace=ef;function Lp(F){if(C)return Pr(2,0,F);try{zp(F)}catch(q){J0(q)}}var Go=[];function tf(F){var q=Go[F];return q||(F>=Go.length&&(Go.length=F+1),Go[F]=q=Ua.get(F)),q}function af(F,q){var se=tf(F)(q);bn()?Le.setExitStatus(se):M5(se)}d.invokeEntryPoint=af;function T5(){var F=new Error;if(!F.stack){try{throw new Error}catch(q){F=q}if(!F.stack)return"(no stack trace available)"}return F.stack.toString()}function nf(F){Le.tlsInitFunctions.push(F)}function rf(F,q){s().set(F,q)}function sf(F){N5(F,!w,1,!b),Le.threadInitTLS()}function of(F){C?postMessage({cmd:"cleanupThread",thread:F}):Pu(F)}function Bp(F,q,se,pe){return C?Pr(3,1,F,q,se,pe):Wp(F,q,se,pe)}function Wp(F,q,se,pe){if(typeof SharedArrayBuffer=="undefined")return H("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var Te=[],Je=0;if(C&&(Te.length===0||Je))return Bp(F,q,se,pe);if(Je)return Je;var Oe={startRoutine:se,pthread_ptr:F,arg:pe,transferList:Te};return C?(Oe.cmd="spawnThread",postMessage(Oe,Te),0):Op(Oe)}function lf(){return 2097152}var uf=!0;function df(){return uf}function Du(F){Atomics.store(l(),F>>2,1),Qp()&&R5(F),Atomics.compareExchange(l(),F>>2,1,0)}d.executeNotifiedProxyingQueue=Du;function pf(F,q,se,pe){if(F==q)setTimeout(()=>Du(pe));else if(C)postMessage({targetThread:F,cmd:"processProxyingQueue",queue:pe});else{var Te=Le.pthreads[F];if(!Te)return;Te.postMessage({cmd:"processProxyingQueue",queue:pe})}return 1}function cf(F,q,se){return-1}function hf(){Uo("")}function Ts(F){Ts.shown||(Ts.shown={}),Ts.shown[F]||(Ts.shown[F]=1,S&&(F="warning: "+F),H(F))}function ff(){S||w||Ts("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function mf(){return Date.now()}function Vp(){return 2147483648}function gf(){return Vp()}var Ho;S?Ho=()=>{var F=process.hrtime();return F[0]*1e3+F[1]/1e6}:C?Ho=()=>performance.now()-d.__performance_now_clock_drift:Ho=()=>performance.now();function xf(F,q,se){i().copyWithin(F,q,q+se)}function Af(){return S?aS().cpus().length:navigator.hardwareConcurrency}function Pr(F,q){var se=arguments.length-2,pe=arguments;return Q0(()=>{for(var Te=se,Je=tc(Te*8),Oe=Je>>3,We=0;We<se;We++){var Dt=pe[2+We];c()[Oe+We]=Dt}return E5(F,Te,Je,q)})}var zu=[];function yf(F,q,se){zu.length=q;for(var pe=se>>3,Te=0;Te<q;Te++)zu[Te]=c()[pe+Te];var Je=F<0,Oe=Je?K0[-F-1]:Cf[F];return Oe.apply(null,zu)}function bf(F){try{return oe.grow(F-je.byteLength+65535>>>16),dt(oe.buffer),1}catch(q){}}function vf(F){var q=i().length;if(F=F>>>0,F<=q)return!1;var se=Vp();if(F>se)return!1;let pe=(Dt,un)=>Dt+(un-Dt%un)%un;for(var Te=1;Te<=4;Te*=2){var Je=q*(1+.2/Te);Je=Math.min(Je,F+100663296);var Oe=Math.min(se,pe(Math.max(F,Je),65536)),We=bf(Oe);if(We)return!0}return!1}function wf(){throw"unwind"}function Up(F){return C?Pr(4,1,F):52}function Gp(F,q,se,pe,Te){return C?Pr(5,1,F,q,se,pe,Te):70}var kf=[null,[],[]];function If(F,q){var se=kf[F];q===0||q===10?((F===1?U:H)(nt(se,0)),se.length=0):se.push(q)}function Hp(F,q,se,pe){if(C)return Pr(6,1,F,q,se,pe);for(var Te=0,Je=0;Je<se;Je++){var Oe=u()[q>>2],We=u()[q+4>>2];q+=8;for(var Dt=0;Dt<We;Dt++)If(F,i()[Oe+Dt]);Te+=We}return u()[pe>>2]=Te,0}function jp(F){var q=d["_"+F];return q}function Sf(F,q,se,pe,Te){var Je={string:dn=>{var Ko=0;if(dn!=null&&dn!==0){var F5=(dn.length<<2)+1;Ko=tc(F5),rt(dn,Ko,F5)}return Ko},array:dn=>{var Ko=tc(dn.length);return rf(dn,Ko),Ko}};function Oe(dn){return q==="string"?ut(dn):q==="boolean"?Boolean(dn):dn}var We=jp(F),Dt=[],un=0;if(pe)for(var cr=0;cr<pe.length;cr++){var P5=Je[se[cr]];P5?(un===0&&(un=Em()),Dt[cr]=P5(pe[cr])):Dt[cr]=pe[cr]}var Rm=We.apply(null,Dt);function RI(dn){return un!==0&&ec(un),Oe(dn)}return Rm=RI(Rm),Rm}function Tf(F,q,se,pe){se=se||[];var Te=se.every(Oe=>Oe==="number"||Oe==="boolean"),Je=q!=="string";return Je&&Te&&!pe?jp(F):function(){return Sf(F,q,se,arguments,pe)}}Le.init();var Cf=[null,Fu,Lp,Bp,Up,Gp,Hp],qp={__emscripten_init_main_thread_js:sf,__emscripten_thread_cleanup:of,__pthread_create_js:Wp,_emscripten_default_pthread_stack_size:lf,_emscripten_get_now_is_monotonic:df,_emscripten_notify_task_queue:pf,_emscripten_set_offscreencanvas_size:cf,abort:hf,emscripten_check_blocking_allowed:ff,emscripten_date_now:mf,emscripten_get_heap_max:gf,emscripten_get_now:Ho,emscripten_memcpy_big:xf,emscripten_num_logical_cores:Af,emscripten_receive_on_main_thread_js:yf,emscripten_resize_heap:vf,emscripten_unwind_to_js_event_loop:wf,exit:zp,fd_close:Up,fd_seek:Gp,fd_write:Hp,memory:oe||d.wasmMemory},C5=q0(),Nf=d.___wasm_call_ctors=function(){return(Nf=d.___wasm_call_ctors=d.asm.__wasm_call_ctors).apply(null,arguments)},Ef=d._init=function(){return(Ef=d._init=d.asm.init).apply(null,arguments)},Rf=d._init_with_threads_count=function(){return(Rf=d._init_with_threads_count=d.asm.init_with_threads_count).apply(null,arguments)},Mf=d._get_threads_count=function(){return(Mf=d._get_threads_count=d.asm.get_threads_count).apply(null,arguments)},$f=d._register_tensor=function(){return($f=d._register_tensor=d.asm.register_tensor).apply(null,arguments)},_f=d._dispose_data=function(){return(_f=d._dispose_data=d.asm.dispose_data).apply(null,arguments)},Pf=d._dispose=function(){return(Pf=d._dispose=d.asm.dispose).apply(null,arguments)},Ff=d._Abs=function(){return(Ff=d._Abs=d.asm.Abs).apply(null,arguments)},Of=d._Add=function(){return(Of=d._Add=d.asm.Add).apply(null,arguments)},Df=d._AddN=function(){return(Df=d._AddN=d.asm.AddN).apply(null,arguments)},zf=d._All=function(){return(zf=d._All=d.asm.All).apply(null,arguments)},Lf=d._Any=function(){return(Lf=d._Any=d.asm.Any).apply(null,arguments)},Bf=d._ArgMax=function(){return(Bf=d._ArgMax=d.asm.ArgMax).apply(null,arguments)},Wf=d._AvgPool=function(){return(Wf=d._AvgPool=d.asm.AvgPool).apply(null,arguments)},Vf=d._BatchMatMul=function(){return(Vf=d._BatchMatMul=d.asm.BatchMatMul).apply(null,arguments)},Uf=d._Ceil=function(){return(Uf=d._Ceil=d.asm.Ceil).apply(null,arguments)},Gf=d._ClipByValue=function(){return(Gf=d._ClipByValue=d.asm.ClipByValue).apply(null,arguments)},Hf=d._Conv2D=function(){return(Hf=d._Conv2D=d.asm.Conv2D).apply(null,arguments)},jf=d._Conv2DBackpropInput=function(){return(jf=d._Conv2DBackpropInput=d.asm.Conv2DBackpropInput).apply(null,arguments)},qf=d._Cos=function(){return(qf=d._Cos=d.asm.Cos).apply(null,arguments)},Xf=d._Cosh=function(){return(Xf=d._Cosh=d.asm.Cosh).apply(null,arguments)},Kf=d._CropAndResize=function(){return(Kf=d._CropAndResize=d.asm.CropAndResize).apply(null,arguments)},Zf=d._Cumprod=function(){return(Zf=d._Cumprod=d.asm.Cumprod).apply(null,arguments)},Yf=d._Cumsum=function(){return(Yf=d._Cumsum=d.asm.Cumsum).apply(null,arguments)},Jf=d._DepthToSpace=function(){return(Jf=d._DepthToSpace=d.asm.DepthToSpace).apply(null,arguments)},Qf=d._DepthwiseConv2dNative=function(){return(Qf=d._DepthwiseConv2dNative=d.asm.DepthwiseConv2dNative).apply(null,arguments)},em=d._Elu=function(){return(em=d._Elu=d.asm.Elu).apply(null,arguments)},tm=d._Equal=function(){return(tm=d._Equal=d.asm.Equal).apply(null,arguments)},am=d._Exp=function(){return(am=d._Exp=d.asm.Exp).apply(null,arguments)},nm=d._FlipLeftRight=function(){return(nm=d._FlipLeftRight=d.asm.FlipLeftRight).apply(null,arguments)},rm=d._Floor=function(){return(rm=d._Floor=d.asm.Floor).apply(null,arguments)},sm=d._FloorDiv=function(){return(sm=d._FloorDiv=d.asm.FloorDiv).apply(null,arguments)},im=d._FusedBatchNorm=function(){return(im=d._FusedBatchNorm=d.asm.FusedBatchNorm).apply(null,arguments)},om=d._FusedConv2D=function(){return(om=d._FusedConv2D=d.asm.FusedConv2D).apply(null,arguments)},lm=d._FusedDepthwiseConv2D=function(){return(lm=d._FusedDepthwiseConv2D=d.asm.FusedDepthwiseConv2D).apply(null,arguments)},um=d._Gather=function(){return(um=d._Gather=d.asm.Gather).apply(null,arguments)},dm=d._GatherNd=function(){return(dm=d._GatherNd=d.asm.GatherNd).apply(null,arguments)},pm=d._Greater=function(){return(pm=d._Greater=d.asm.Greater).apply(null,arguments)},cm=d._GreaterEqual=function(){return(cm=d._GreaterEqual=d.asm.GreaterEqual).apply(null,arguments)},hm=d._IsNan=function(){return(hm=d._IsNan=d.asm.IsNan).apply(null,arguments)},fm=d._LeakyRelu=function(){return(fm=d._LeakyRelu=d.asm.LeakyRelu).apply(null,arguments)},mm=d._Less=function(){return(mm=d._Less=d.asm.Less).apply(null,arguments)},gm=d._LessEqual=function(){return(gm=d._LessEqual=d.asm.LessEqual).apply(null,arguments)},xm=d._Log=function(){return(xm=d._Log=d.asm.Log).apply(null,arguments)},Am=d._LogicalAnd=function(){return(Am=d._LogicalAnd=d.asm.LogicalAnd).apply(null,arguments)},ym=d._LogicalNot=function(){return(ym=d._LogicalNot=d.asm.LogicalNot).apply(null,arguments)},bm=d._LogicalOr=function(){return(bm=d._LogicalOr=d.asm.LogicalOr).apply(null,arguments)},vm=d._LogicalXor=function(){return(vm=d._LogicalXor=d.asm.LogicalXor).apply(null,arguments)},wm=d._Max=function(){return(wm=d._Max=d.asm.Max).apply(null,arguments)},km=d._MaxPool=function(){return(km=d._MaxPool=d.asm.MaxPool).apply(null,arguments)},Xp=d._Maximum=function(){return(Xp=d._Maximum=d.asm.Maximum).apply(null,arguments)},Kp=d._Mean=function(){return(Kp=d._Mean=d.asm.Mean).apply(null,arguments)},Lu=d._Min=function(){return(Lu=d._Min=d.asm.Min).apply(null,arguments)},Im=d._Minimum=function(){return(Im=d._Minimum=d.asm.Minimum).apply(null,arguments)},Sm=d._MirrorPad=function(){return(Sm=d._MirrorPad=d.asm.MirrorPad).apply(null,arguments)},jo=d._Multiply=function(){return(jo=d._Multiply=d.asm.Multiply).apply(null,arguments)},Zp=d._Neg=function(){return(Zp=d._Neg=d.asm.Neg).apply(null,arguments)},qo=d._NonMaxSuppressionV3=function(){return(qo=d._NonMaxSuppressionV3=d.asm.NonMaxSuppressionV3).apply(null,arguments)},Xo=d._NonMaxSuppressionV4=function(){return(Xo=d._NonMaxSuppressionV4=d.asm.NonMaxSuppressionV4).apply(null,arguments)},Tm=d._NonMaxSuppressionV5=function(){return(Tm=d._NonMaxSuppressionV5=d.asm.NonMaxSuppressionV5).apply(null,arguments)},X=d._NotEqual=function(){return(X=d._NotEqual=d.asm.NotEqual).apply(null,arguments)},ie=d._OneHot=function(){return(ie=d._OneHot=d.asm.OneHot).apply(null,arguments)},ke=d._PadV2=function(){return(ke=d._PadV2=d.asm.PadV2).apply(null,arguments)},Ye=d._Pow=function(){return(Ye=d._Pow=d.asm.Pow).apply(null,arguments)},yt=d._Prelu=function(){return(yt=d._Prelu=d.asm.Prelu).apply(null,arguments)},bt=d._Prod=function(){return(bt=d._Prod=d.asm.Prod).apply(null,arguments)},Ze=d._RealDiv=function(){return(Ze=d._RealDiv=d.asm.RealDiv).apply(null,arguments)},qe=d._Reciprocal=function(){return(qe=d._Reciprocal=d.asm.Reciprocal).apply(null,arguments)},Ot=d._Relu=function(){return(Ot=d._Relu=d.asm.Relu).apply(null,arguments)},ln=d._Relu6=function(){return(ln=d._Relu6=d.asm.Relu6).apply(null,arguments)},pr=d._ResizeBilinear=function(){return(pr=d._ResizeBilinear=d.asm.ResizeBilinear).apply(null,arguments)},Yp=d._ResizeNearestNeighbor=function(){return(Yp=d._ResizeNearestNeighbor=d.asm.ResizeNearestNeighbor).apply(null,arguments)},Bu=d._Reverse=function(){return(Bu=d._Reverse=d.asm.Reverse).apply(null,arguments)},Cm=d._RotateWithOffset=function(){return(Cm=d._RotateWithOffset=d.asm.RotateWithOffset).apply(null,arguments)},Fa=d._Round=function(){return(Fa=d._Round=d.asm.Round).apply(null,arguments)},Fr=d._Rsqrt=function(){return(Fr=d._Rsqrt=d.asm.Rsqrt).apply(null,arguments)},Jp=d._ScatterNd=function(){return(Jp=d._ScatterNd=d.asm.ScatterNd).apply(null,arguments)},Jk=d._SelectV2=function(){return(Jk=d._SelectV2=d.asm.SelectV2).apply(null,arguments)},Qk=d._Sigmoid=function(){return(Qk=d._Sigmoid=d.asm.Sigmoid).apply(null,arguments)},eI=d._Sin=function(){return(eI=d._Sin=d.asm.Sin).apply(null,arguments)},tI=d._Softmax=function(){return(tI=d._Softmax=d.asm.Softmax).apply(null,arguments)},aI=d._SparseFillEmptyRows=function(){return(aI=d._SparseFillEmptyRows=d.asm.SparseFillEmptyRows).apply(null,arguments)},nI=d._SparseReshape=function(){return(nI=d._SparseReshape=d.asm.SparseReshape).apply(null,arguments)},rI=d._SparseSegmentReduction=function(){return(rI=d._SparseSegmentReduction=d.asm.SparseSegmentReduction).apply(null,arguments)},sI=d._Sqrt=function(){return(sI=d._Sqrt=d.asm.Sqrt).apply(null,arguments)},iI=d._Square=function(){return(iI=d._Square=d.asm.Square).apply(null,arguments)},oI=d._SquaredDifference=function(){return(oI=d._SquaredDifference=d.asm.SquaredDifference).apply(null,arguments)},lI=d._Step=function(){return(lI=d._Step=d.asm.Step).apply(null,arguments)},uI=d._StridedSlice=function(){return(uI=d._StridedSlice=d.asm.StridedSlice).apply(null,arguments)},dI=d._Sub=function(){return(dI=d._Sub=d.asm.Sub).apply(null,arguments)},pI=d._Sum=function(){return(pI=d._Sum=d.asm.Sum).apply(null,arguments)},cI=d._Tan=function(){return(cI=d._Tan=d.asm.Tan).apply(null,arguments)},hI=d._Tanh=function(){return(hI=d._Tanh=d.asm.Tanh).apply(null,arguments)},fI=d._Tile=function(){return(fI=d._Tile=d.asm.Tile).apply(null,arguments)},mI=d._TopK=function(){return(mI=d._TopK=d.asm.TopK).apply(null,arguments)},gI=d._Transform=function(){return(gI=d._Transform=d.asm.Transform).apply(null,arguments)},xI=d._Transpose=function(){return(xI=d._Transpose=d.asm.Transpose).apply(null,arguments)},AI=d.__FusedMatMul=function(){return(AI=d.__FusedMatMul=d.asm._FusedMatMul).apply(null,arguments)},yI=d._malloc=function(){return(yI=d._malloc=d.asm.malloc).apply(null,arguments)},bI=d._free=function(){return(bI=d._free=d.asm.free).apply(null,arguments)},vI=d.__emscripten_tls_init=function(){return(vI=d.__emscripten_tls_init=d.asm._emscripten_tls_init).apply(null,arguments)},Qp=d._pthread_self=function(){return(Qp=d._pthread_self=d.asm.pthread_self).apply(null,arguments)},wI=d.___errno_location=function(){return(wI=d.___errno_location=d.asm.__errno_location).apply(null,arguments)},N5=d.__emscripten_thread_init=function(){return(N5=d.__emscripten_thread_init=d.asm._emscripten_thread_init).apply(null,arguments)},kI=d.__emscripten_thread_crashed=function(){return(kI=d.__emscripten_thread_crashed=d.asm._emscripten_thread_crashed).apply(null,arguments)},II=d._emscripten_main_thread_process_queued_calls=function(){return(II=d._emscripten_main_thread_process_queued_calls=d.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},SI=d._emscripten_main_browser_thread_id=function(){return(SI=d._emscripten_main_browser_thread_id=d.asm.emscripten_main_browser_thread_id).apply(null,arguments)},E5=d._emscripten_run_in_main_runtime_thread_js=function(){return(E5=d._emscripten_run_in_main_runtime_thread_js=d.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)},TI=d._emscripten_dispatch_to_thread_=function(){return(TI=d._emscripten_dispatch_to_thread_=d.asm.emscripten_dispatch_to_thread_).apply(null,arguments)},R5=d.__emscripten_proxy_execute_task_queue=function(){return(R5=d.__emscripten_proxy_execute_task_queue=d.asm._emscripten_proxy_execute_task_queue).apply(null,arguments)},Nm=d.__emscripten_thread_free_data=function(){return(Nm=d.__emscripten_thread_free_data=d.asm._emscripten_thread_free_data).apply(null,arguments)},M5=d.__emscripten_thread_exit=function(){return(M5=d.__emscripten_thread_exit=d.asm._emscripten_thread_exit).apply(null,arguments)},$5=d._emscripten_stack_set_limits=function(){return($5=d._emscripten_stack_set_limits=d.asm.emscripten_stack_set_limits).apply(null,arguments)},Em=d.stackSave=function(){return(Em=d.stackSave=d.asm.stackSave).apply(null,arguments)},ec=d.stackRestore=function(){return(ec=d.stackRestore=d.asm.stackRestore).apply(null,arguments)},tc=d.stackAlloc=function(){return(tc=d.stackAlloc=d.asm.stackAlloc).apply(null,arguments)},CI=d.dynCall_iijjiiii=function(){return(CI=d.dynCall_iijjiiii=d.asm.dynCall_iijjiiii).apply(null,arguments)},NI=d.dynCall_jiji=function(){return(NI=d.dynCall_jiji=d.asm.dynCall_jiji).apply(null,arguments)};d.keepRuntimeAlive=bn,d.wasmMemory=oe,d.cwrap=Tf,d.ExitStatus=Ss,d.PThread=Le;var ac;dr=function F(){ac||_5(),ac||(dr=F)};function _5(F){if(F=F||x,_r>0)return;if(C){h(d),Xt(),postMessage({cmd:"loaded"});return}if(Wo(),_r>0)return;function q(){ac||(ac=!0,d.calledRun=!0,!we&&(Xt(),h(d),d.onRuntimeInitialized&&d.onRuntimeInitialized(),_p()))}d.setStatus?(d.setStatus("Running..."),setTimeout(function(){setTimeout(function(){d.setStatus("")},1),q()},1)):q()}if(d.preInit)for(typeof d.preInit=="function"&&(d.preInit=[d.preInit]);d.preInit.length>0;)d.preInit.pop()();_5();var nc;m&&(nc={uncaughtException:process.listeners("uncaughtException").filter(function(F){return!m.uncaughtException.indexOf(F)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(F){return!m.unhandledRejection.indexOf(F)>-1})});var rc;if(typeof WasmBackendModule!="undefined")rc=WasmBackendModule;else if(typeof r!="undefined")rc=r;else throw new Error("Could not find wasm module in post.js");if(nc){var EI=rc._dispose;rc._dispose=function(){EI(),nc.uncaughtException.forEach(function(F){process.removeListener("uncaughtException",F)}),nc.unhandledRejection.forEach(function(F){process.removeListener("unhandledRejection",F)})}}return r.ready}})();typeof e=="object"&&typeof t=="object"?t.exports=a:typeof define=="function"&&define.amd?define([],function(){return a}):typeof e=="object"&&(e.WasmBackendModuleThreadedSimd=a)}),rS=qt((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}};`}),sS=qt((e,t)=>{var a=(()=>{var n=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(n=n||__filename),function(r){r=r||{};var s=typeof r!="undefined"?r:{},i,o;s.ready=new Promise(function(X,ie){i=X,o=ie});var l;typeof process!="undefined"&&process.listeners&&(l={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var u=Object.assign({},s),p=[],c="./this.program",d=(X,ie)=>{throw ie},h=typeof window=="object",f=typeof importScripts=="function",m=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="";function x(X){return s.locateFile?s.locateFile(X,g):g+X}var A,y,b,w;function S(X){X instanceof Vo||$("exiting due to exception: "+X)}if(m){f?g=wc().dirname(g)+"/":g=__dirname+"/";var C,E;typeof aA=="function"&&(C=rA(),E=wc()),A=(X,ie)=>(X=E.normalize(X),C.readFileSync(X,ie?void 0:"utf8")),b=X=>{var ie=A(X,!0);return ie.buffer||(ie=new Uint8Array(ie)),ie},y=(X,ie,ke)=>{X=E.normalize(X),C.readFile(X,function(Ye,yt){Ye?ke(Ye):ie(yt.buffer)})},process.argv.length>1&&(c=process.argv[1].replace(/\\/g,"/")),p=process.argv.slice(2),process.on("uncaughtException",function(X){if(!(X instanceof Vo))throw X}),process.on("unhandledRejection",function(X){throw X}),d=(X,ie)=>{if(Va())throw process.exitCode=X,ie;S(ie),process.exit(X)},s.inspect=function(){return"[Emscripten Module object]"}}else(h||f)&&(f?g=self.location.href:typeof document!="undefined"&&document.currentScript&&(g=document.currentScript.src),n&&(g=n),g.indexOf("blob:")!==0?g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1):g="",A=X=>{var ie=new XMLHttpRequest;return ie.open("GET",X,!1),ie.send(null),ie.responseText},f&&(b=X=>{var ie=new XMLHttpRequest;return ie.open("GET",X,!1),ie.responseType="arraybuffer",ie.send(null),new Uint8Array(ie.response)}),y=(X,ie,ke)=>{var Ye=new XMLHttpRequest;Ye.open("GET",X,!0),Ye.responseType="arraybuffer",Ye.onload=()=>{if(Ye.status==200||Ye.status==0&&Ye.response){ie(Ye.response);return}ke()},Ye.onerror=ke,Ye.send(null)},w=X=>document.title=X);var _=s.print||console.log.bind(console),$=s.printErr||console.warn.bind(console);Object.assign(s,u),u=null,s.arguments&&(p=s.arguments),s.thisProgram&&(c=s.thisProgram),s.quit&&(d=s.quit);var M=4,I;s.wasmBinary&&(I=s.wasmBinary);var N=s.noExitRuntime||!0;typeof WebAssembly!="object"&&Un("no native wasm support detected");var O,L=!1,B;function G(X,ie){X||Un(ie)}var j=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function U(X,ie,ke){for(var Ye=ie+ke,yt=ie;X[yt]&&!(yt>=Ye);)++yt;if(yt-ie>16&&X.buffer&&j)return j.decode(X.subarray(ie,yt));for(var bt="";ie<yt;){var Ze=X[ie++];if(!(Ze&128)){bt+=String.fromCharCode(Ze);continue}var qe=X[ie++]&63;if((Ze&224)==192){bt+=String.fromCharCode((Ze&31)<<6|qe);continue}var Ot=X[ie++]&63;if((Ze&240)==224?Ze=(Ze&15)<<12|qe<<6|Ot:Ze=(Ze&7)<<18|qe<<12|Ot<<6|X[ie++]&63,Ze<65536)bt+=String.fromCharCode(Ze);else{var ln=Ze-65536;bt+=String.fromCharCode(55296|ln>>10,56320|ln&1023)}}return bt}function H(X,ie){return X?U(ee,X,ie):""}function V(X,ie,ke,Ye){if(!(Ye>0))return 0;for(var yt=ke,bt=ke+Ye-1,Ze=0;Ze<X.length;++Ze){var qe=X.charCodeAt(Ze);if(qe>=55296&&qe<=57343){var Ot=X.charCodeAt(++Ze);qe=65536+((qe&1023)<<10)|Ot&1023}if(qe<=127){if(ke>=bt)break;ie[ke++]=qe}else if(qe<=2047){if(ke+1>=bt)break;ie[ke++]=192|qe>>6,ie[ke++]=128|qe&63}else if(qe<=65535){if(ke+2>=bt)break;ie[ke++]=224|qe>>12,ie[ke++]=128|qe>>6&63,ie[ke++]=128|qe&63}else{if(ke+3>=bt)break;ie[ke++]=240|qe>>18,ie[ke++]=128|qe>>12&63,ie[ke++]=128|qe>>6&63,ie[ke++]=128|qe&63}}return ie[ke]=0,ke-yt}function Q(X,ie,ke){return V(X,ee,ie,ke)}var Z,re,ee,he,oe,Ae,we,Re,Ge;function Ke(X){Z=X,s.HEAP8=re=new Int8Array(X),s.HEAP16=he=new Int16Array(X),s.HEAP32=Ae=new Int32Array(X),s.HEAPU8=ee=new Uint8Array(X),s.HEAPU16=oe=new Uint16Array(X),s.HEAPU32=we=new Uint32Array(X),s.HEAPF32=Re=new Float32Array(X),s.HEAPF64=Ge=new Float64Array(X)}var nt=s.INITIAL_MEMORY||16777216,ut,et=[],rt=[],je=[],ht=!1;function Va(){return N}function Ft(){if(s.preRun)for(typeof s.preRun=="function"&&(s.preRun=[s.preRun]);s.preRun.length;)$a(s.preRun.shift());dr(et)}function sn(){ht=!0,dr(rt)}function aa(){if(s.postRun)for(typeof s.postRun=="function"&&(s.postRun=[s.postRun]);s.postRun.length;)_a(s.postRun.shift());dr(je)}function $a(X){et.unshift(X)}function on(X){rt.unshift(X)}function _a(X){je.unshift(X)}var dt=0,Pa=null,Ua=null;function ur(X){dt++,s.monitorRunDependencies&&s.monitorRunDependencies(dt)}function Bo(X){if(dt--,s.monitorRunDependencies&&s.monitorRunDependencies(dt),dt==0&&(Pa!==null&&(clearInterval(Pa),Pa=null),Ua)){var ie=Ua;Ua=null,ie()}}function Un(X){s.onAbort&&s.onAbort(X),X="Aborted("+X+")",$(X),L=!0,B=1,X+=". Build with -sASSERTIONS for more info.";var ie=new WebAssembly.RuntimeError(X);throw o(ie),ie}var $u="data:application/octet-stream;base64,";function bn(X){return X.startsWith($u)}function Wo(X){return X.startsWith("file://")}var Xt;Xt="tfjs-backend-wasm.wasm",bn(Xt)||(Xt=x(Xt));function _p(X){try{if(X==Xt&&I)return new Uint8Array(I);if(b)return b(X);throw"both async and sync fetching of the wasm failed"}catch(ie){Un(ie)}}function U0(){if(!I&&(h||f)){if(typeof fetch=="function"&&!Wo(Xt))return fetch(Xt,{credentials:"same-origin"}).then(function(X){if(!X.ok)throw"failed to load wasm binary file at '"+Xt+"'";return X.arrayBuffer()}).catch(function(){return _p(Xt)});if(y)return new Promise(function(X,ie){y(Xt,function(ke){X(new Uint8Array(ke))},ie)})}return Promise.resolve().then(function(){return _p(Xt)})}function G0(){var X={env:Fu,wasi_snapshot_preview1:Fu};function ie(Ze,qe){var Ot=Ze.exports;s.asm=Ot,O=s.asm.memory,Ke(O.buffer),ut=s.asm.__indirect_function_table,on(s.asm.__wasm_call_ctors),Bo("wasm-instantiate")}ur("wasm-instantiate");function ke(Ze){ie(Ze.instance)}function Ye(Ze){return U0().then(function(qe){return WebAssembly.instantiate(qe,X)}).then(function(qe){return qe}).then(Ze,function(qe){$("failed to asynchronously prepare wasm: "+qe),Un(qe)})}function yt(){return!I&&typeof WebAssembly.instantiateStreaming=="function"&&!bn(Xt)&&!Wo(Xt)&&!m&&typeof fetch=="function"?fetch(Xt,{credentials:"same-origin"}).then(function(Ze){var qe=WebAssembly.instantiateStreaming(Ze,X);return qe.then(ke,function(Ot){return $("wasm streaming compile failed: "+Ot),$("falling back to ArrayBuffer instantiation"),Ye(ke)})}):Ye(ke)}if(s.instantiateWasm)try{var bt=s.instantiateWasm(X,ie);return bt}catch(Ze){$("Module.instantiateWasm callback failed with error: "+Ze),o(Ze)}return yt().catch(o),{}}var y5,_r;function Vo(X){this.name="ExitStatus",this.message="Program terminated with exit("+X+")",this.status=X}function dr(X){for(;X.length>0;)X.shift()(s)}function b5(X){return X}function v5(X){var ie=/\b_Z[\w\d_]+/g;return X.replace(ie,function(ke){var Ye=ke;return ke===Ye?ke:Ye+" ["+ke+"]"})}function Uo(){var X=new Error;if(!X.stack){try{throw new Error}catch(ie){X=ie}if(!X.stack)return"(no stack trace available)"}return X.stack.toString()}function H0(X,ie){re.set(X,ie)}function Pp(){Un("")}function _u(){return 2147483648}function xa(){return _u()}function Fp(X,ie,ke){ee.copyWithin(X,ie,ie+ke)}function j0(X){try{return O.grow(X-Z.byteLength+65535>>>16),Ke(O.buffer),1}catch(ie){}}function q0(X){var ie=ee.length;X=X>>>0;var ke=_u();if(X>ke)return!1;let Ye=(Ot,ln)=>Ot+(ln-Ot%ln)%ln;for(var yt=1;yt<=4;yt*=2){var bt=ie*(1+.2/yt);bt=Math.min(bt,X+100663296);var Ze=Math.min(ke,Ye(Math.max(X,bt),65536)),qe=j0(Ze);if(qe)return!0}return!1}var X0={varargs:void 0,get:function(){X0.varargs+=4;var X=Ae[X0.varargs-4>>2];return X},getStr:function(X){var ie=H(X);return ie}};function w5(X){return 52}function K0(X,ie,ke,Ye,yt){return 70}var Ss=[null,[],[]];function Z0(X,ie){var ke=Ss[X];ie===0||ie===10?((X===1?_:$)(U(ke,0)),ke.length=0):ke.push(ie)}function Y0(X,ie,ke,Ye){for(var yt=0,bt=0;bt<ke;bt++){var Ze=we[ie>>2],qe=we[ie+4>>2];ie+=8;for(var Ot=0;Ot<qe;Ot++)Z0(X,ee[Ze+Ot]);yt+=qe}return we[Ye>>2]=yt,0}function Pu(X){var ie=s["_"+X];return ie}function Op(X,ie,ke,Ye,yt){var bt={string:Fa=>{var Fr=0;if(Fa!=null&&Fa!==0){var Jp=(Fa.length<<2)+1;Fr=Lu(Jp),Q(Fa,Fr,Jp)}return Fr},array:Fa=>{var Fr=Lu(Fa.length);return H0(Fa,Fr),Fr}};function Ze(Fa){return ie==="string"?H(Fa):ie==="boolean"?Boolean(Fa):Fa}var qe=Pu(X),Ot=[],ln=0;if(Ye)for(var pr=0;pr<Ye.length;pr++){var Yp=bt[ke[pr]];Yp?(ln===0&&(ln=Xp()),Ot[pr]=Yp(Ye[pr])):Ot[pr]=Ye[pr]}var Bu=qe.apply(null,Ot);function Cm(Fa){return ln!==0&&Kp(ln),Ze(Fa)}return Bu=Cm(Bu),Bu}function Dp(X,ie,ke,Ye){ke=ke||[];var yt=ke.every(Ze=>Ze==="number"||Ze==="boolean"),bt=ie!=="string";return bt&&yt&&!Ye?Pu(X):function(){return Op(X,ie,ke,arguments,Ye)}}var Fu={abort:Pp,emscripten_get_heap_max:xa,emscripten_memcpy_big:Fp,emscripten_resize_heap:q0,fd_close:w5,fd_seek:K0,fd_write:Y0},k5=G0(),zp=s.___wasm_call_ctors=function(){return(zp=s.___wasm_call_ctors=s.asm.__wasm_call_ctors).apply(null,arguments)},J0=s._init=function(){return(J0=s._init=s.asm.init).apply(null,arguments)},Le=s._init_with_threads_count=function(){return(Le=s._init_with_threads_count=s.asm.init_with_threads_count).apply(null,arguments)},Ou=s._get_threads_count=function(){return(Ou=s._get_threads_count=s.asm.get_threads_count).apply(null,arguments)},Q0=s._register_tensor=function(){return(Q0=s._register_tensor=s.asm.register_tensor).apply(null,arguments)},I5=s._dispose_data=function(){return(I5=s._dispose_data=s.asm.dispose_data).apply(null,arguments)},S5=s._dispose=function(){return(S5=s._dispose=s.asm.dispose).apply(null,arguments)},ef=s._Abs=function(){return(ef=s._Abs=s.asm.Abs).apply(null,arguments)},Lp=s._Add=function(){return(Lp=s._Add=s.asm.Add).apply(null,arguments)},Go=s._AddN=function(){return(Go=s._AddN=s.asm.AddN).apply(null,arguments)},tf=s._All=function(){return(tf=s._All=s.asm.All).apply(null,arguments)},af=s._Any=function(){return(af=s._Any=s.asm.Any).apply(null,arguments)},T5=s._ArgMax=function(){return(T5=s._ArgMax=s.asm.ArgMax).apply(null,arguments)},nf=s._AvgPool=function(){return(nf=s._AvgPool=s.asm.AvgPool).apply(null,arguments)},rf=s._BatchMatMul=function(){return(rf=s._BatchMatMul=s.asm.BatchMatMul).apply(null,arguments)},sf=s._Ceil=function(){return(sf=s._Ceil=s.asm.Ceil).apply(null,arguments)},of=s._ClipByValue=function(){return(of=s._ClipByValue=s.asm.ClipByValue).apply(null,arguments)},Bp=s._Conv2D=function(){return(Bp=s._Conv2D=s.asm.Conv2D).apply(null,arguments)},Wp=s._Conv2DBackpropInput=function(){return(Wp=s._Conv2DBackpropInput=s.asm.Conv2DBackpropInput).apply(null,arguments)},lf=s._Cos=function(){return(lf=s._Cos=s.asm.Cos).apply(null,arguments)},uf=s._Cosh=function(){return(uf=s._Cosh=s.asm.Cosh).apply(null,arguments)},df=s._CropAndResize=function(){return(df=s._CropAndResize=s.asm.CropAndResize).apply(null,arguments)},Du=s._Cumprod=function(){return(Du=s._Cumprod=s.asm.Cumprod).apply(null,arguments)},pf=s._Cumsum=function(){return(pf=s._Cumsum=s.asm.Cumsum).apply(null,arguments)},cf=s._DepthToSpace=function(){return(cf=s._DepthToSpace=s.asm.DepthToSpace).apply(null,arguments)},hf=s._DepthwiseConv2dNative=function(){return(hf=s._DepthwiseConv2dNative=s.asm.DepthwiseConv2dNative).apply(null,arguments)},Ts=s._Elu=function(){return(Ts=s._Elu=s.asm.Elu).apply(null,arguments)},ff=s._Equal=function(){return(ff=s._Equal=s.asm.Equal).apply(null,arguments)},mf=s._Exp=function(){return(mf=s._Exp=s.asm.Exp).apply(null,arguments)},Vp=s._FlipLeftRight=function(){return(Vp=s._FlipLeftRight=s.asm.FlipLeftRight).apply(null,arguments)},gf=s._Floor=function(){return(gf=s._Floor=s.asm.Floor).apply(null,arguments)},Ho=s._FloorDiv=function(){return(Ho=s._FloorDiv=s.asm.FloorDiv).apply(null,arguments)},xf=s._FusedBatchNorm=function(){return(xf=s._FusedBatchNorm=s.asm.FusedBatchNorm).apply(null,arguments)},Af=s._FusedConv2D=function(){return(Af=s._FusedConv2D=s.asm.FusedConv2D).apply(null,arguments)},Pr=s._FusedDepthwiseConv2D=function(){return(Pr=s._FusedDepthwiseConv2D=s.asm.FusedDepthwiseConv2D).apply(null,arguments)},zu=s._Gather=function(){return(zu=s._Gather=s.asm.Gather).apply(null,arguments)},yf=s._GatherNd=function(){return(yf=s._GatherNd=s.asm.GatherNd).apply(null,arguments)},bf=s._Greater=function(){return(bf=s._Greater=s.asm.Greater).apply(null,arguments)},vf=s._GreaterEqual=function(){return(vf=s._GreaterEqual=s.asm.GreaterEqual).apply(null,arguments)},wf=s._IsNan=function(){return(wf=s._IsNan=s.asm.IsNan).apply(null,arguments)},Up=s._LeakyRelu=function(){return(Up=s._LeakyRelu=s.asm.LeakyRelu).apply(null,arguments)},Gp=s._Less=function(){return(Gp=s._Less=s.asm.Less).apply(null,arguments)},kf=s._LessEqual=function(){return(kf=s._LessEqual=s.asm.LessEqual).apply(null,arguments)},If=s._Log=function(){return(If=s._Log=s.asm.Log).apply(null,arguments)},Hp=s._LogicalAnd=function(){return(Hp=s._LogicalAnd=s.asm.LogicalAnd).apply(null,arguments)},jp=s._LogicalNot=function(){return(jp=s._LogicalNot=s.asm.LogicalNot).apply(null,arguments)},Sf=s._LogicalOr=function(){return(Sf=s._LogicalOr=s.asm.LogicalOr).apply(null,arguments)},Tf=s._LogicalXor=function(){return(Tf=s._LogicalXor=s.asm.LogicalXor).apply(null,arguments)},Cf=s._Max=function(){return(Cf=s._Max=s.asm.Max).apply(null,arguments)},qp=s._MaxPool=function(){return(qp=s._MaxPool=s.asm.MaxPool).apply(null,arguments)},C5=s._Maximum=function(){return(C5=s._Maximum=s.asm.Maximum).apply(null,arguments)},Nf=s._Mean=function(){return(Nf=s._Mean=s.asm.Mean).apply(null,arguments)},Ef=s._Min=function(){return(Ef=s._Min=s.asm.Min).apply(null,arguments)},Rf=s._Minimum=function(){return(Rf=s._Minimum=s.asm.Minimum).apply(null,arguments)},Mf=s._MirrorPad=function(){return(Mf=s._MirrorPad=s.asm.MirrorPad).apply(null,arguments)},$f=s._Multiply=function(){return($f=s._Multiply=s.asm.Multiply).apply(null,arguments)},_f=s._Neg=function(){return(_f=s._Neg=s.asm.Neg).apply(null,arguments)},Pf=s._NonMaxSuppressionV3=function(){return(Pf=s._NonMaxSuppressionV3=s.asm.NonMaxSuppressionV3).apply(null,arguments)},Ff=s._NonMaxSuppressionV4=function(){return(Ff=s._NonMaxSuppressionV4=s.asm.NonMaxSuppressionV4).apply(null,arguments)},Of=s._NonMaxSuppressionV5=function(){return(Of=s._NonMaxSuppressionV5=s.asm.NonMaxSuppressionV5).apply(null,arguments)},Df=s._NotEqual=function(){return(Df=s._NotEqual=s.asm.NotEqual).apply(null,arguments)},zf=s._OneHot=function(){return(zf=s._OneHot=s.asm.OneHot).apply(null,arguments)},Lf=s._PadV2=function(){return(Lf=s._PadV2=s.asm.PadV2).apply(null,arguments)},Bf=s._Pow=function(){return(Bf=s._Pow=s.asm.Pow).apply(null,arguments)},Wf=s._Prelu=function(){return(Wf=s._Prelu=s.asm.Prelu).apply(null,arguments)},Vf=s._Prod=function(){return(Vf=s._Prod=s.asm.Prod).apply(null,arguments)},Uf=s._RealDiv=function(){return(Uf=s._RealDiv=s.asm.RealDiv).apply(null,arguments)},Gf=s._Reciprocal=function(){return(Gf=s._Reciprocal=s.asm.Reciprocal).apply(null,arguments)},Hf=s._Relu=function(){return(Hf=s._Relu=s.asm.Relu).apply(null,arguments)},jf=s._Relu6=function(){return(jf=s._Relu6=s.asm.Relu6).apply(null,arguments)},qf=s._ResizeBilinear=function(){return(qf=s._ResizeBilinear=s.asm.ResizeBilinear).apply(null,arguments)},Xf=s._ResizeNearestNeighbor=function(){return(Xf=s._ResizeNearestNeighbor=s.asm.ResizeNearestNeighbor).apply(null,arguments)},Kf=s._Reverse=function(){return(Kf=s._Reverse=s.asm.Reverse).apply(null,arguments)},Zf=s._RotateWithOffset=function(){return(Zf=s._RotateWithOffset=s.asm.RotateWithOffset).apply(null,arguments)},Yf=s._Round=function(){return(Yf=s._Round=s.asm.Round).apply(null,arguments)},Jf=s._Rsqrt=function(){return(Jf=s._Rsqrt=s.asm.Rsqrt).apply(null,arguments)},Qf=s._ScatterNd=function(){return(Qf=s._ScatterNd=s.asm.ScatterNd).apply(null,arguments)},em=s._SelectV2=function(){return(em=s._SelectV2=s.asm.SelectV2).apply(null,arguments)},tm=s._Sigmoid=function(){return(tm=s._Sigmoid=s.asm.Sigmoid).apply(null,arguments)},am=s._Sin=function(){return(am=s._Sin=s.asm.Sin).apply(null,arguments)},nm=s._Softmax=function(){return(nm=s._Softmax=s.asm.Softmax).apply(null,arguments)},rm=s._SparseFillEmptyRows=function(){return(rm=s._SparseFillEmptyRows=s.asm.SparseFillEmptyRows).apply(null,arguments)},sm=s._SparseReshape=function(){return(sm=s._SparseReshape=s.asm.SparseReshape).apply(null,arguments)},im=s._SparseSegmentReduction=function(){return(im=s._SparseSegmentReduction=s.asm.SparseSegmentReduction).apply(null,arguments)},om=s._Sqrt=function(){return(om=s._Sqrt=s.asm.Sqrt).apply(null,arguments)},lm=s._Square=function(){return(lm=s._Square=s.asm.Square).apply(null,arguments)},um=s._SquaredDifference=function(){return(um=s._SquaredDifference=s.asm.SquaredDifference).apply(null,arguments)},dm=s._Step=function(){return(dm=s._Step=s.asm.Step).apply(null,arguments)},pm=s._StridedSlice=function(){return(pm=s._StridedSlice=s.asm.StridedSlice).apply(null,arguments)},cm=s._Sub=function(){return(cm=s._Sub=s.asm.Sub).apply(null,arguments)},hm=s._Sum=function(){return(hm=s._Sum=s.asm.Sum).apply(null,arguments)},fm=s._Tan=function(){return(fm=s._Tan=s.asm.Tan).apply(null,arguments)},mm=s._Tanh=function(){return(mm=s._Tanh=s.asm.Tanh).apply(null,arguments)},gm=s._Tile=function(){return(gm=s._Tile=s.asm.Tile).apply(null,arguments)},xm=s._TopK=function(){return(xm=s._TopK=s.asm.TopK).apply(null,arguments)},Am=s._Transform=function(){return(Am=s._Transform=s.asm.Transform).apply(null,arguments)},ym=s._Transpose=function(){return(ym=s._Transpose=s.asm.Transpose).apply(null,arguments)},bm=s.__FusedMatMul=function(){return(bm=s.__FusedMatMul=s.asm._FusedMatMul).apply(null,arguments)},vm=s._malloc=function(){return(vm=s._malloc=s.asm.malloc).apply(null,arguments)},wm=s._free=function(){return(wm=s._free=s.asm.free).apply(null,arguments)},km=s.___errno_location=function(){return(km=s.___errno_location=s.asm.__errno_location).apply(null,arguments)},Xp=s.stackSave=function(){return(Xp=s.stackSave=s.asm.stackSave).apply(null,arguments)},Kp=s.stackRestore=function(){return(Kp=s.stackRestore=s.asm.stackRestore).apply(null,arguments)},Lu=s.stackAlloc=function(){return(Lu=s.stackAlloc=s.asm.stackAlloc).apply(null,arguments)},Im=s.dynCall_iijjiiii=function(){return(Im=s.dynCall_iijjiiii=s.asm.dynCall_iijjiiii).apply(null,arguments)},Sm=s.dynCall_jiji=function(){return(Sm=s.dynCall_jiji=s.asm.dynCall_jiji).apply(null,arguments)};s.cwrap=Dp;var jo;Ua=function X(){jo||Zp(),jo||(Ua=X)};function Zp(X){if(X=X||p,dt>0||(Ft(),dt>0))return;function ie(){jo||(jo=!0,s.calledRun=!0,!L&&(sn(),i(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),aa()))}s.setStatus?(s.setStatus("Running..."),setTimeout(function(){setTimeout(function(){s.setStatus("")},1),ie()},1)):ie()}if(s.preInit)for(typeof s.preInit=="function"&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();Zp();var qo;l&&(qo={uncaughtException:process.listeners("uncaughtException").filter(function(X){return!l.uncaughtException.indexOf(X)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(X){return!l.unhandledRejection.indexOf(X)>-1})});var Xo;if(typeof r!="undefined")Xo=r;else if(typeof WasmBackendModuleThreadedSimd!="undefined")Xo=WasmBackendModuleThreadedSimd;else throw new Error("Could not find wasm module in post.js");if(qo){var Tm=Xo._dispose;Xo._dispose=function(){Tm(),qo.uncaughtException.forEach(function(X){process.removeListener("uncaughtException",X)}),qo.unhandledRejection.forEach(function(X){process.removeListener("unhandledRejection",X)})}}return r.ready}})();typeof e=="object"&&typeof t=="object"?t.exports=a:typeof define=="function"&&define.amd?define([],function(){return a}):typeof e=="object"&&(e.WasmBackendModule=a)}),vd=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}},bl=class{refCount(e){return Ha("refCount")}incRef(e){return Ha("incRef")}timerAvailable(){return!0}time(e){return Ha("time")}read(e){return Ha("read")}readSync(e){return Ha("readSync")}readToGPU(e,t){return Ha("readToGPU")}numDataIds(){return Ha("numDataIds")}disposeData(e,t){return Ha("disposeData")}write(e,t,a){return Ha("write")}move(e,t,a,n,r){return Ha("move")}createTensorFromTexture(e,t,a){return Ha("createTensorFromTexture")}memory(){return Ha("memory")}floatPrecision(){return Ha("floatPrecision")}epsilon(){return this.floatPrecision()===32?1e-7:1e-4}dispose(){return Ha("dispose")}};function Ha(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 sA(e){let t=e.length,a=0;for(;t>0;)a=Math.random()*t|0,t--,kc(e,t,a)}function iS(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let a=e.length,n=0;for(;a>0;)n=Math.random()*a|0,a--,kc(e,a,n),kc(t,a,n)}function nd(e,t,a){return Math.max(e,Math.min(t,a))}function oS(e){return e%2===0?e:e+1}function kc(e,t,a){let n=e[t];e[t]=e[a],e[a]=n}function lS(e){let t=0;for(let a=0;a<e.length;a++)t+=e[a];return t}function uS(e,t){let a=Math.random();return t*a+(1-a)*e}function dS(e,t){let a=0;for(let n=0;n<e.length;n++){let r=Number(e[n])-Number(t[n]);a+=r*r}return a}function P(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function Sa(e,t,a=""){P(es(e,t),()=>a+` Shapes ${e} and ${t} must match`)}function Xs(e){P(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function zs(e,t=[],a=!1){if(t==null&&(t=[]),Array.isArray(e)||da(e)&&!a)for(let n=0;n<e.length;++n)zs(e[n],t,a);else t.push(e);return t}function At(e){if(e.length===0)return 1;let t=e[0];for(let a=1;a<e.length;a++)t*=e[a];return t}function pS(e){return e.length===0}function es(e,t){if(e===t)return!0;if(e==null||t==null||e.length!==t.length)return!1;for(let a=0;a<e.length;a++)if(e[a]!==t[a])return!1;return!0}function ol(e){return e%1===0}function cS(e){if(Math.tanh!=null)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;{let t=Math.exp(2*e);return(t-1)/(t+1)}}function hS(e){let t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function fS(e){let t=new Uint32Array(e);for(let a=0;a<e;++a)t[a]=a;return sA(t),t}function Qu(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function mS(e,t=r=>0,a,n){return new Promise((r,s)=>{let i=0,o=()=>{if(e()){r();return}i++;let l=t(i);if(a!=null&&i>=a){s();return}n!=null?n(o,l):setTimeout(o,l)};o()})}function gS(e,t){let a=1,n=-1;for(let s=0;s<e.length;++s)if(e[s]>=0)a*=e[s];else if(e[s]===-1){if(n!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${n} and dim ${s}`);n=s}else if(e[s]<0)throw Error(`Shapes can not be < 0. Found ${e[s]} at dim ${s}`);if(n===-1){if(t>0&&t!==a)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(a===0)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%a!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${a}`);let r=e.slice();return r[n]=t/a,r}function wd(e,t){let a=t.length;return e=e==null?t.map((n,r)=>r):[].concat(e),P(e.every(n=>n>=-a&&n<a),()=>`All values in axis param must be in range [-${a}, ${a}) but got axis ${e}`),P(e.every(n=>ol(n)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(n=>n<0?a+n:n)}function iA(e,t){let a=[],n=[],r=t!=null&&Array.isArray(t)&&t.length===0,s=t==null||r?null:wd(t,e).sort(),i=0;for(let o=0;o<e.length;++o){if(s!=null){if(s[i]===o&&e[o]!==1)throw new Error(`Can't squeeze axis ${o} since its dim '${e[o]}' is not 1`);(s[i]==null||s[i]>o)&&e[o]===1&&(a.push(e[o]),n.push(o)),s[i]<=o&&i++}e[o]!==1&&(a.push(e[o]),n.push(o))}return{newShape:a,keptDims:n}}function oA(e,t){let a=null;if(e==null||e==="float32")a=new Float32Array(t);else if(e==="int32")a=new Int32Array(t);else if(e==="bool")a=new Uint8Array(t);else throw new Error(`Unknown data type ${e}`);return a}function lA(e,t){let a=null;if(e==null||e==="float32")a=new Float32Array(t);else if(e==="int32")a=new Int32Array(t);else if(e==="bool")a=new Uint8Array(t);else if(e==="string")a=new Array(t);else throw new Error(`Unknown data type ${e}`);return a}function uA(e,t){for(let a=0;a<e.length;a++){let n=e[a];if(isNaN(n)||!isFinite(n))throw Error(`A tensor of type ${t} being uploaded contains ${n}.`)}}function dA(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function xS(e,t){return!(t==="complex64"||t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64"||t==="bool"&&e==="bool")}function da(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}function Vm(e){if(e==="float32"||e==="int32")return 4;if(e==="complex64")return 8;if(e==="bool")return 1;throw new Error(`Unknown dtype ${e}`)}function pA(e){if(e==null)return 0;let t=0;return e.forEach(a=>t+=a.length),t}function Lr(e){return typeof e=="string"||e instanceof String}function cA(e){return typeof e=="boolean"}function hA(e){return typeof e=="number"}function Uc(e){return Array.isArray(e)?Uc(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":hA(e)?"float32":Lr(e)?"string":cA(e)?"bool":"float32"}function Hr(e){return!!(e&&e.constructor&&e.call&&e.apply)}function Ic(e,t){for(let a=t;a<e;++a)if(e%a===0)return a;return e}function vl(e){let t=e.length;if(t<2)return[];let a=new Array(t-1);a[t-2]=e[t-1];for(let n=t-3;n>=0;--n)a[n]=a[n+1]*e[n+1];return a}function fA(e,t,a,n=!1){let r=new Array;if(t.length===1){let s=t[0]*(n?2:1);for(let i=0;i<s;i++)r[i]=a[e+i]}else{let s=t[0],i=t.slice(1),o=i.reduce((l,u)=>l*u)*(n?2:1);for(let l=0;l<s;l++)r[l]=fA(e+l*o,i,a,n)}return r}function al(e,t,a=!1){if(e.length===0)return t[0];let n=e.reduce((r,s)=>r*s)*(a?2:1);if(n===0)return[];if(n!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${a?" for a complex tensor":""}.`);return fA(0,e,t,a)}function L1(e,t){let a=Gc(e,t);for(let n=0;n<a.length;n++)a[n]=1;return a}function Gc(e,t){if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool")return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function AS(e,t){let a=e.reduce((n,r)=>n*r,1);if(t==null||t==="float32")return al(e,new Float32Array(a));if(t==="int32")return al(e,new Int32Array(a));if(t==="bool")return al(e,new Uint8Array(a));throw new Error(`Unknown data type ${t}`)}function Ja(e){e.forEach(t=>{P(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function yS(e,t,a){if(t===0)return 0;if(t===1)return e[0];let n=e[e.length-1];for(let r=0;r<e.length-1;++r)n+=a[r]*e[r];return n}function bS(e,t,a){if(t===0)return[];if(t===1)return[e];let n=new Array(t);for(let r=0;r<n.length-1;++r)n[r]=Math.floor(e/a[r]),e-=n[r]*a[r];return n[n.length-1]=e,n}function B1(e){return e&&e.then&&typeof e.then=="function"}var D5="tfjsflags",mA=class{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=vS,this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&(W().getBool("IS_TEST")||W().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,a){if(this.flagRegistry[e]={evaluationFn:t,setHook:a},this.urlFlags[e]!=null){let n=this.urlFlags[e];W().getBool("IS_TEST")||W().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${n}.`),this.set(e,n)}}async getAsync(e){return e in this.flags?this.flags[e]:(this.flags[e]=await this.evaluateFlag(e),this.flags[e])}get(e){if(e in this.flags)return this.flags[e];let t=this.evaluateFlag(e);if(B1(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null)throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(this.flagRegistry[e]==null)throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;let e=this.getQueryParams(this.global.location.search);D5 in e&&e[D5].split(",").forEach(t=>{let[a,n]=t.split(":");this.urlFlags[a]=kS(a,n)})}};function vS(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(a,...n)=>(wS(t,n[0],n[1]),n.join("="))),t}function wS(e,t,a){e[decodeURIComponent(t)]=decodeURIComponent(a||"")}function kS(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 W(){return W1}var W1=null;function IS(e){W1=e}var Mm;function gA(){if(Mm==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");Mm=e}return Mm}function SS(){let e=gA();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function V1(e,t){let a=SS();if(a.has(e))return a.get(e);{let n=t();return a.set(e,n),a.get(e)}}var wl="Abs",kl="Acos",Il="Acosh",ts="Add",Ks="AddN",Zs="All",Ys="Any",Js="ArgMax",kd="ArgMin",Sl="Asin",Tl="Asinh",Cl="Atan",Nl="Atanh",El="Atan2",Qs="AvgPool",U1="AvgPoolGrad",Hc="AvgPool3D",G1="AvgPool3DGrad",ei="BatchMatMul",Rl="BatchToSpaceND",Id="Bincount",TS="BroadcastTo",jc="BroadcastArgs",ti="Cast",ai="Ceil",as="ClipByValue",Sd="Complex",qc="ComplexAbs",Ml="Concat",ni="Conv2D",Xc="Conv2DBackpropFilter",ri="Conv2DBackpropInput",Kc="Conv3D",H1="Conv3DBackpropFilterV2",Zc="Conv3DBackpropInputV2",si="Cos",ii="Cosh",oi="Cumprod",li="Cumsum",ui="CropAndResize",Td="DenseBincount",di="DepthToSpace",pi="DepthwiseConv2dNative",Yc="DepthwiseConv2dNativeBackpropFilter",Jc="DepthwiseConv2dNativeBackpropInput",Qc="Diag",eh="Dilation2D",Um="Dilation2DBackpropInput",Gm="Dilation2DBackpropFilter",ci="RealDiv",Cd="Einsum",hi="Elu",j1="EluGrad",$l="Erf",fi="Equal",mi="Exp",_l="ExpandDims",Pl="Expm1",Nd="FFT",Fl="Fill",gi="FlipLeftRight",xi="Floor",Ai="FloorDiv",yi="FusedBatchNorm",Ol="GatherV2",bi="GatherNd",vi="Greater",wi="GreaterEqual",ki="Identity",Ed="IFFT",Rd="Imag",Dl="IsFinite",zl="IsInf",Ii="IsNan",Si="LeakyRelu",Ti="Less",Ci="LessEqual",th="LinSpace",Ni="Log",Ll="Log1p",Ei="LogicalAnd",Ri="LogicalNot",Bl="LogicalOr",xA="LogicalXor",CS="LogSoftmax",NS="LowerBound",ah="LRN",q1="LRNGrad",Mi="Max",$i="Maximum",_i="MaxPool",X1="MaxPoolGrad",nh="MaxPool3D",K1="MaxPool3DGrad",rh="MaxPoolWithArgmax",Pi="Mean",Fi="Min",Oi="Minimum",Di="MirrorPad",Wl="Mod",sh="Multinomial",zi="Multiply",Vl="Neg",Li="NotEqual",Bi="NonMaxSuppressionV3",Ul="NonMaxSuppressionV4",Wi="NonMaxSuppressionV5",Gl="OnesLike",Vi="OneHot",Hl="Pack",Ui="PadV2",ES="Pool",Gi="Pow",Hi="Prelu",ji="Prod",ih="RaggedGather",oh="RaggedRange",lh="RaggedTensorToTensor",jl="Range",Md="Real",qi="Reciprocal",Xi="Relu",ql="Reshape",Ki="ResizeNearestNeighbor",Z1="ResizeNearestNeighborGrad",Zi="ResizeBilinear",Y1="ResizeBilinearGrad",Yi="Relu6",Ji="Reverse",Xl="Round",Qi="Rsqrt",eo="ScatterNd",$d="SearchSorted",Kl="Select",_d="Selu",Zl="Slice",to="Sin",Yl="Sinh",Pd="Sign",ao="Sigmoid",Fd="Softplus",no="Sqrt",ro="Sum",Jl="SpaceToBatchND",Ql="SplitV",so="Softmax",Od="SparseFillEmptyRows",eu="SparseReshape",Dd="SparseSegmentMean",zd="SparseSegmentSum",Ld="SparseToDense",io="SquaredDifference",Bd="Square",oo="StridedSlice",tu="StringNGrams",Wd="StringSplit",Vd="StringToHashBucketFast",lo="Sub",uo="Tan",po="Tanh",ns="Tile",co="TopK",ho="Transform",Ar="Transpose",uh="Unique",au="Unpack",dh="UnsortedSegmentSum",RS="UpperBound",nu="ZerosLike",fo="Step",rd="FromPixels",mo="RotateWithOffset",jr="_FusedMatMul",qr="FusedConv2D",Xr="FusedDepthwiseConv2D";function zr(...e){W().getBool("IS_TEST")||W().getBool("PROD")||console.warn(...e)}function MS(...e){W().getBool("IS_TEST")||W().getBool("PROD")||console.log(...e)}var ll=V1("kernelRegistry",()=>new Map),sd=V1("gradRegistry",()=>new Map);function Sc(e,t){let a=J1(e,t);return ll.get(a)}function Hm(e){return sd.get(e)}function Zn(e){let t=ll.entries(),a=[];for(;;){let{done:n,value:r}=t.next();if(n)break;let[s,i]=r,[o]=s.split("_");o===e&&a.push(i)}return a}function mn(e){let{kernelName:t,backendName:a}=e,n=J1(t,a);ll.has(n)&&zr(`The kernel '${t}' for backend '${a}' is already registered`),ll.set(n,e)}function $S(e){let{kernelName:t}=e;sd.has(t)&&W().getBool("DEBUG")&&zr(`Overriding the gradient for '${t}'`),sd.set(t,e)}function _S(e,t){let a=J1(e,t);if(!ll.has(a))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);ll.delete(a)}function PS(e){if(!sd.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);sd.delete(e)}function FS(e,t){Zn(e).forEach(a=>{let n=Object.assign({},a,{backendName:t});mn(n)})}function J1(e,t){return`${t}_${e}`}var v={};Xe(v,{arraysEqual:()=>es,assert:()=>P,assertNonNegativeIntegerDimensions:()=>Ja,assertNonNull:()=>Xs,assertShapesMatch:()=>Sa,bytesFromStringArray:()=>pA,bytesPerElement:()=>Vm,checkConversionForErrors:()=>uA,clamp:()=>nd,computeStrides:()=>vl,createScalarValue:()=>WS,createShuffledIndices:()=>fS,decodeString:()=>Tc,distSquared:()=>dS,encodeString:()=>Gd,fetch:()=>US,fingerPrint64:()=>BS,flatten:()=>zs,getArrayFromDType:()=>lA,getTypedArrayFromDType:()=>oA,hasEncodingLoss:()=>xS,hexToLong:()=>Ud,indexToLoc:()=>bS,inferDtype:()=>Uc,inferFromImplicitShape:()=>gS,isBoolean:()=>cA,isFunction:()=>Hr,isInt:()=>ol,isNumber:()=>hA,isPromise:()=>B1,isScalarShape:()=>pS,isString:()=>Lr,isTypedArray:()=>da,isValidDtype:()=>dA,locToIndex:()=>yS,makeOnesTypedArray:()=>L1,makeZerosNestedTypedArray:()=>AS,makeZerosTypedArray:()=>Gc,nearestDivisor:()=>Ic,nearestLargerEven:()=>oS,now:()=>id,parseAxisParam:()=>wd,randUniform:()=>uS,repeatedTry:()=>mS,rightPad:()=>Qu,shuffle:()=>sA,shuffleCombo:()=>iS,sizeFromShape:()=>At,sizeToSquarishShape:()=>hS,squeezeShape:()=>iA,sum:()=>lS,swap:()=>kc,tanh:()=>cS,toNestedArray:()=>al,toTypedArray:()=>ph});var z5=yl(UI()),$s=z5.default||z5;function Ud(e){return $s.fromString(e,!0,16)}var AA=Ud("c3a5c85c97cb3127"),Rs=Ud("b492b66fbe98f273"),Aa=Ud("9ae16a3b2f90404f");function jm(e){return e.xor(e.shru(47))}function yA(e,t,a){let n=e.slice(t,t+a);return $s.fromBytes(Array.from(n),!0,!0)}function ft(e,t){return yA(e,t,8)}function L5(e,t){return yA(e,t,4)}function Kt(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function Ur(e,t,a=Ud("9ddfea08eb382d69")){let n=e.xor(t).mul(a);n=n.xor(n.shru(47));let r=t.xor(n).mul(a);return r=r.xor(r.shru(47)),r=r.mul(a),r}function OS(e,t,a,n,r,s){r=r.add(e),s=Kt(s.add(r).add(n),21);let i=r;return r=r.add(t),r=r.add(a),s=s.add(Kt(r,44)),[r.add(n),s.add(i)]}function ic(e,t,a,n){return OS(ft(e,t),ft(e,t+8),ft(e,t+16),ft(e,t+24),a,n)}function DS(e,t=e.length){if(t>=8){let a=Aa.add(t*2),n=ft(e,0).add(Aa),r=ft(e,t-8),s=Kt(r,37).mul(a).add(n),i=Kt(n,25).add(r).mul(a);return Ur(s,i,a)}if(t>=4){let a=Aa.add(t*2),n=L5(e,0);return Ur(n.shl(3).add(t),L5(e,t-4),a)}if(t>0){let a=e[0],n=e[t>>1],r=e[t-1],s=a+(n<<8),i=t+(r<<2);return jm(Aa.mul(s).xor(AA.mul(i))).mul(Aa)}return Aa}function zS(e,t=e.length){let a=Aa.add(t*2),n=ft(e,0).mul(Rs),r=ft(e,8),s=ft(e,t-8).mul(a),i=ft(e,t-16).mul(Aa);return Ur(Kt(n.add(r),43).add(Kt(s,30)).add(i),n.add(Kt(r.add(Aa),18)).add(s),a)}function LS(e,t=e.length){let a=Aa.add(t*2),n=ft(e,0).mul(Aa),r=ft(e,8),s=ft(e,t-8).mul(a),i=ft(e,t-16).mul(Aa),o=Kt(n.add(r),43).add(Kt(s,30)).add(i),l=Ur(o,n.add(Kt(r.add(Aa),18)).add(s),a),u=ft(e,16).mul(a),p=ft(e,24),c=o.add(ft(e,t-32)).mul(a),d=l.add(ft(e,t-24)).mul(a);return Ur(Kt(u.add(p),43).add(Kt(c,30)).add(d),u.add(Kt(p.add(n),18)).add(c),a)}function BS(e,t=e.length){let a=$s.fromNumber(81,!0);if(t<=32)return t<=16?DS(e,t):zS(e,t);if(t<=64)return LS(e,t);let n=a,r=a.mul(Rs).add(113),s=jm(r.mul(Aa).add(113)).mul(Aa),i=[$s.UZERO,$s.UZERO],o=[$s.UZERO,$s.UZERO];n=n.mul(Aa).add(ft(e,0));let l=0,u=(t-1>>6)*64,p=u+(t-1&63)-63;do n=Kt(n.add(r).add(i[0]).add(ft(e,l+8)),37).mul(Rs),r=Kt(r.add(i[1]).add(ft(e,l+48)),42).mul(Rs),n=n.xor(o[1]),r=r.add(i[0]).add(ft(e,l+40)),s=Kt(s.add(o[0]),33).mul(Rs),i=ic(e,l,i[1].mul(Rs),n.add(o[0])),o=ic(e,l+32,s.add(o[1]),r.add(ft(e,l+16))),[s,n]=[n,s],l+=64;while(l!==u);let c=Rs.add(s.and(255).shl(1));return l=p,o[0]=o[0].add(t-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),n=Kt(n.add(r).add(i[0]).add(ft(e,l+8)),37).mul(c),r=Kt(r.add(i[1]).add(ft(e,l+48)),42).mul(c),n=n.xor(o[1].mul(9)),r=r.add(i[0].mul(9).add(ft(e,l+40))),s=Kt(s.add(o[0]),33).mul(c),i=ic(e,l,i[1].mul(c),n.add(o[0])),o=ic(e,l+32,s.add(o[1]),r.add(ft(e,l+16))),[s,n]=[n,s],Ur(Ur(i[0],o[0],c).add(jm(r).mul(AA)).add(s),Ur(i[1],o[1],c).add(n),c)}function WS(e,t){return t==="string"?Gd(e):ph([e],t)}function VS(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function ph(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=zs(e)),W().getBool("DEBUG")&&uA(e,t),VS(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 a=new Uint8Array(e.length);for(let n=0;n<a.length;++n)Math.round(e[n])!==0&&(a[n]=1);return a}else throw new Error(`Unknown data type ${t}`)}function id(){return W().platform.now()}function US(e,t){return W().platform.fetch(e,t)}function Gd(e,t="utf-8"){return t=t||"utf-8",W().platform.encode(e,t)}function Tc(e,t="utf-8"){return t=t||"utf-8",W().platform.decode(e,t)}var GS=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new jS)}profileKernel(e,t,a){let n,r=()=>{n=a()},s,i=id();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(r);else{r();for(let o of n)o.dataSync();s=Promise.resolve({kernelMs:id()-i})}if(W().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let o=0;o<n.length;o++){let l=n[o];l.data().then(u=>{HS(u,l.dtype,e)})}return{kernelName:e,outputs:n,inputs:t,timeMs:s.then(o=>o.kernelMs),extraInfo:s.then(o=>o.getExtraProfileInfo!=null?o.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:a,timeMs:n,inputs:r,extraInfo:s}=e;a.forEach(i=>{Promise.all([i.data(),n,s]).then(o=>{this.logger.logKernelProfile(t,i,o[0],o[1],r,o[2])})})}};function HS(e,t,a){if(t!=="float32")return!1;for(let n=0;n<e.length;n++){let r=e[n];if(isNaN(r)||!isFinite(r))return console.warn(`Found ${r} in the result of '${a}'`),!0}return!1}var jS=class{logKernelProfile(e,t,a,n,r,s){let i=typeof n=="number"?Qu(`${n}ms`,9):n.error,o=Qu(e,25),l=t.rank,u=t.size,p=Qu(t.shape.toString(),14),c="";for(let d in r){let h=r[d];if(h!=null){let f=h.shape||t.shape,m=f.length;c+=`${d}: ${m}D ${m>0?f:""} `}}console.log(`%c${o} %c${i} %c${l}D ${p} %c${u} %c${c} %c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function qS(e,t,a){let n={},r={};for(let l=0;l<t.length;l++)n[t[l].id]=!0;for(let l=0;l<e.length;l++){let u=e[l],p=u.inputs;for(let c in p){let d=p[c],h=!1;for(let f=0;f<t.length;f++)if(n[d.id]){u.outputs.forEach(m=>n[m.id]=!0),h=!0,r[u.id]=!0;break}if(h)break}}let s={};s[a.id]=!0;let i={};for(let l=e.length-1;l>=0;l--){let u=e[l],p=u.inputs;for(let c=0;c<u.outputs.length;c++)if(s[u.outputs[c].id]){for(let d in p)s[p[d].id]=!0,i[u.id]=!0;break}}let o=[];for(let l=0;l<e.length;l++){let u=e[l];if(r[u.id]&&i[u.id]){let p={};for(let d in u.inputs){let h=u.inputs[d];n[h.id]&&(p[d]=h)}let c=Object.assign({},u);c.inputs=p,c.outputs=u.outputs,o.push(c)}}return o}function XS(e,t,a,n){for(let r=t.length-1;r>=0;r--){let s=t[r],i=[];if(s.outputs.forEach(l=>{let u=e[l.id];u!=null?i.push(u):i.push(null)}),s.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);let o=s.gradient(i);for(let l in s.inputs){if(!(l in o))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(o)}.`);let u=a(()=>o[l]());if(u.dtype!=="float32")throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);let p=s.inputs[l];if(!es(u.shape,p.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${p.shape}'`);if(e[p.id]==null)e[p.id]=u;else{let c=e[p.id];e[p.id]=n(c,u),c.dispose()}}}}var B5=20,Wu=3,$m=7;function KS(e,t,a,n){let r=vl(t),s=ZS(e,t,a,r),i=t.length,o=hc(e,t,a,r,s),l=["Tensor"];return n&&(l.push(` dtype: ${a}`),l.push(` rank: ${i}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(o.map(u=>" "+u).join(`
`)),l.join(`
`)}function ZS(e,t,a,n){let r=At(t),s=n[n.length-1],i=new Array(s).fill(0),o=t.length,l=a==="complex64"?Gu(e):e;if(o>1)for(let u=0;u<r/s;u++){let p=u*s;for(let c=0;c<s;c++)i[c]=Math.max(i[c],Uu(l[p+c],0,a).length)}return i}function Uu(e,t,a){let n;return Array.isArray(e)?n=`${parseFloat(e[0].toFixed($m))} + ${parseFloat(e[1].toFixed($m))}j`:Lr(e)?n=`'${e}'`:a==="bool"?n=bA(e):n=parseFloat(e.toFixed($m)).toString(),Qu(n,t)}function bA(e){return e===0?"false":"true"}function hc(e,t,a,n,r,s=!0){let i=a==="complex64"?2:1,o=t[0],l=t.length;if(l===0){if(a==="complex64"){let m=Gu(e);return[Uu(m[0],0,a)]}return a==="bool"?[bA(e[0])]:[e[0].toString()]}if(l===1){if(o>B5){let m=Wu*i,g=Array.from(e.slice(0,m)),x=Array.from(e.slice((o-Wu)*i,o*i));return a==="complex64"&&(g=Gu(g),x=Gu(x)),["["+g.map((A,y)=>Uu(A,r[y],a)).join(", ")+", ..., "+x.map((A,y)=>Uu(A,r[o-Wu+y],a)).join(", ")+"]"]}return["["+(a==="complex64"?Gu(e):Array.from(e)).map((m,g)=>Uu(m,r[g],a)).join(", ")+"]"]}let u=t.slice(1),p=n.slice(1),c=n[0]*i,d=[];if(o>B5){for(let m=0;m<Wu;m++){let g=m*c,x=g+c;d.push(...hc(e.slice(g,x),u,a,p,r,!1))}d.push("...");for(let m=o-Wu;m<o;m++){let g=m*c,x=g+c;d.push(...hc(e.slice(g,x),u,a,p,r,m===o-1))}}else for(let m=0;m<o;m++){let g=m*c,x=g+c;d.push(...hc(e.slice(g,x),u,a,p,r,m===o-1))}let h=l===2?",":"";d[0]="["+d[0]+h;for(let m=1;m<d.length-1;m++)d[m]=" "+d[m]+h;let f=`,
`;for(let m=2;m<l;m++)f+=`
`;return d[d.length-1]=" "+d[d.length-1]+"]"+(s?"":f),d}function Gu(e){let t=[];for(let a=0;a<e.length;a+=2)t.push([e[a],e[a+1]]);return t}var jt=class{constructor(e,t,a){if(this.dtype=t,this.shape=e.slice(),this.size=At(e),a!=null){let n=a.length;P(n===this.size,()=>`Length of values '${n}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=a||lA(t,this.size),this.strides=vl(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 a=this.locToIndex(t);this.values[a]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let n of e){if(n<0||n>=this.shape[t]){let r=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(r)}t++}let a=e[e.length-1];for(let n=0;n<e.length-1;++n)a+=this.strides[n]*e[n];return this.values[a]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let a=0;a<e.length-1;++a)t+=this.strides[a]*e[a];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let a=0;a<t.length-1;++a)t[a]=Math.floor(e/this.strides[a]),e-=t[a]*this.strides[a];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Fn().makeTensor(this.values,this.shape,this.dtype)}},Fn=null,Qo=null,YS=null;function JS(e){Fn=e}function QS(e){Qo=e}function eT(e){YS=e}var pt=class{constructor(e,t,a,n){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=At(e),this.strides=vl(e),this.dataId=a,this.id=n,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return Qo.buffer(this.shape,this.dtype,e)}bufferSync(){return Qo.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return al(this.shape,e,this.dtype==="complex64")}arraySync(){return al(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=Fn().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(a=>Tc(a))}catch(a){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(),Fn().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();let e=Fn().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Tc(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 Fn().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Fn().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Qo.print(this,e)}clone(){return this.throwIfDisposed(),Qo.clone(this)}toString(e=!1){let t=this.dataSync();return KS(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Qo.cast(this,e)}variable(e=!0,t,a){return this.throwIfDisposed(),Fn().makeVariable(this,e,t,a)}};Object.defineProperty(pt,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function tT(){return V1("Tensor",()=>pt)}tT();var od=class extends pt{constructor(e,t,a,n){super(e.shape,e.dtype,e.dataId,n),this.trainable=t,this.name=a}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(!es(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Fn().disposeTensor(this),this.dataId=e.dataId,Fn().incRef(this,null)}dispose(){Fn().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(od,Symbol.hasInstance,{value:e=>e instanceof pt&&e.assign!=null&&e.assign instanceof Function});var vA={};Xe(vA,{assertTypesMatch:()=>wA,getTensorsInContainer:()=>Q1,isTensorInList:()=>nT,makeTypesMatch:()=>St});var qm;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(qm||(qm={}));var Xm;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(Xm||(Xm={}));var Km;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(Km||(Km={}));var Zm;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(Zm||(Zm={}));var Ym;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(Ym||(Ym={}));var aT={float32:Zm,int32:Xm,bool:Km,complex64:Ym};function ca(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return aT[e][t]}function Hd(e){return ca(e,"int32")}function St(e,t){if(e.dtype===t.dtype)return[e,t];let a=ca(e.dtype,t.dtype);return[e.cast(a),t.cast(a)]}function wA(e,t){P(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function nT(e,t){return t.some(a=>a.id===e.id)}function Q1(e){let t=[];return kA(e,t,new Set),t}function kA(e,t,a){if(e==null)return;if(e instanceof pt){t.push(e);return}if(!rT(e))return;let n=e;for(let r in n){let s=n[r];a.has(s)||(a.add(s),kA(s,t,a))}}function rT(e){return Array.isArray(e)||typeof e=="object"}function _m(e){return e.kernelName!=null}var W5=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()}},ld=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new W5}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let a=e[t];if(await this.initializeBackend(a).success){await this.setBackend(a);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){let{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry))if(e in this.registryFactory){let{asyncInit:t}=this.initializeBackend(e);if(t)return null}else return null;return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,a=1){return e in this.registryFactory?(zr(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:a},!0)}async setBackend(e){if(this.registryFactory[e]==null)throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,this.registry[e]==null){this.backendInstance=null;let{success:t,asyncInit:a}=this.initializeBackend(e);if(!(a?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new GS(this.backendInstance),!0}setupRegisteredKernels(){Zn(this.backendName).forEach(e=>{e.setupFunc!=null&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Zn(e).forEach(t=>{t.disposeFunc!=null&&t.disposeFunc(this.registry[e])})}initializeBackend(e){let t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{let a=t.factory();if(a&&!(a instanceof bl)&&typeof a.then=="function"){let n=++this.pendingBackendInitId,r=a.then(s=>n<this.pendingBackendInitId?!1:(this.registry[e]=s,this.pendingBackendInit=null,!0)).catch(s=>(n<this.pendingBackendInitId||(this.pendingBackendInit=null,zr(`Initialization of backend ${e} failed`),zr(s.stack||s.message)),!1));return this.pendingBackendInit=r,{success:r,asyncInit:!0}}else return this.registry[e]=a,{success:!0,asyncInit:!1}}catch(a){return zr(`Initialization of backend ${e} failed`),zr(a.stack||a.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let a=e[t],{success:n,asyncInit:r}=this.initializeBackend(a);if(r||n)return{name:a,asyncInit:r}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){let a=this.state.tensorInfo.get(t),n=a.backend,r=this.readSync(t),s=n.refCount(t);n.disposeData(t,!0),a.backend=e,e.move(t,r,a.shape,a.dtype,s),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let a=null;if(t==null){if(typeof e!="function")throw new Error("Please provide a function to tidy()");t=e}else{if(typeof e!="string"&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof t!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");a=e}let n;return this.scopedRun(()=>this.startScope(a),()=>this.endScope(n),()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n))}scopedRun(e,t,a){e();try{let n=a();return t(),n}catch(n){throw t(),n}}nextTensorId(){return ld.nextTensorId++}nextVariableId(){return ld.nextVariableId++}clone(e){let t=z.runKernel(ki,{x:e}),a={x:e},n=s=>({x:()=>{let i="float32",o={x:s},l={dtype:i};return z.runKernel(ti,o,l)}}),r=[];return this.addTapeNode(this.state.activeScope.name,a,[t],n,r,{}),t}runKernel(e,t,a){if(this.backendName==null&&this.backend,Sc(e,this.backendName)==null)throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:a})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,a){let n=this.backend.numDataIds(),r=0;a.forEach(o=>{r+=o.dtype==="complex64"?3:1});let s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=n-t-r-s;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,a=[],n=this.isTapeOn(),r=this.state.numBytes,s=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let i;this.backendName==null&&this.backend;let o,l=_m(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(_m(e)){let{kernelName:h,inputs:f,attrs:m}=e;this.backendName==null&&this.backend;let g=Sc(h,this.backendName);P(g!=null,()=>`Cannot find registered kernel '${h}' for backend '${this.backendName}'`),i=()=>{let x=this.backend.numDataIds();o=g.kernelFunc({inputs:f,attrs:m,backend:this.backend});let A=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(h,x,A);let y=A.map(b=>b.rank!=null?b:this.makeTensorFromTensorInfo(b));if(n){let b=this.getTensorsForGradient(h,f,y);a=this.saveTensorsForBackwardMode(b)}return y}}else{let{forwardFunc:h}=e,f=m=>{!n||(a=m.map(g=>this.keep(this.clone(g))))};i=()=>{let m=this.backend.numDataIds();o=this.tidy(()=>h(this.backend,f));let g=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,m,g),g}}let{inputs:u,attrs:p}=e,c=_m(e)?null:e.backwardsFunc,d;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=i():(d=this.profiler.profileKernel(l,u,()=>i()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(d),t=d.outputs)}),n&&this.addTapeNode(l,u,t,c,a,p),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,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(o)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(t=>this.keep(this.clone(t)))}getTensorsForGradient(e,t,a){let n=Hm(e);if(n!=null){let r=n.inputsToSave||[],s=n.outputsToSave||[],i;n.saveAllInputs?(P(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),i=Object.keys(t).map(l=>t[l])):i=r.map(l=>t[l]);let o=a.filter((l,u)=>s[u]);return i.concat(o)}return[]}makeTensor(e,t,a,n){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");a=a||"float32",n=n||this.backend;let r=e;a==="string"&&Lr(e[0])&&(r=e.map(o=>Gd(o)));let s=n.write(r,t,a),i=new pt(t,a,s,this.nextTensorId());if(this.trackTensor(i,n),a==="string"){let o=this.state.tensorInfo.get(s),l=pA(r);this.state.numBytes+=l-o.bytes,o.bytes=l}return i}makeTensorFromDataId(e,t,a,n){a=a||"float32";let r={dataId:e,shape:t,dtype:a};return this.makeTensorFromTensorInfo(r,n)}makeTensorFromTensorInfo(e,t){let{dataId:a,shape:n,dtype:r}=e,s=new pt(n,r,a,this.nextTensorId());return this.trackTensor(s,t),s}makeVariable(e,t=!0,a,n){a=a||this.nextVariableId().toString(),n!=null&&n!==e.dtype&&(e=e.cast(n));let r=new od(e,t,a,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 a=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(a=e.size*Vm(e.dtype)),this.state.numBytes+=a,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:a})),e instanceof od||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 a=e.size*Vm(e.dtype);this.state.numBytes-=a}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,a=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(n=>n.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-a;for(let n of this.state.activeProfile.kernels)n.kernelTimeMs=await n.kernelTimeMs,n.extraInfo=await n.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,a,n,r,s){let i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:a,saved:r},o=Hm(e);o!=null&&(n=o.gradFunc),n!=null&&(i.gradient=l=>(l=l.map((u,p)=>{if(u==null){let c=a[p],d=Gc(c.size,c.dtype);return this.makeTensor(d,c.shape,c.dtype)}return u}),n(l.length>1?l:l[0],r,s))),this.state.activeTape.push(i)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=Q1(e),a=new Set(t.map(r=>r.id));for(let r=0;r<this.state.activeScope.track.length;r++){let s=this.state.activeScope.track[r];!s.kept&&!a.has(s.id)&&s.dispose()}let n=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(r=>{!r.kept&&r.scopeId===n.id&&this.track(r)})}gradients(e,t,a,n=!1){if(P(t.length>0,()=>"gradients() received an empty list of xs."),a!=null&&a.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${a.dtype}'`);let r=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));P(r instanceof pt,()=>"The result y returned by f() must be a tensor.");let s=qS(this.state.activeTape,t,r);if(!n&&s.length===0&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{let i={};i[r.id]=a==null?sT(r.shape):a,XS(i,s,l=>this.tidy(l),iT);let o=t.map(l=>i[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let u of l.saved)u.dispose()}),this.state.activeTape=null),{value:r,grads:o}})}customGrad(e){return P(Hr(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{P(t.every(i=>i instanceof pt),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let a,n={};t.forEach((i,o)=>{n[o]=i});let r=(i,o)=>(a=e(...t,o),P(a.value instanceof pt,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),P(Hr(a.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),a.value),s=(i,o)=>{let l=a.gradFunc(i,o),u=Array.isArray(l)?l:[l];P(u.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),P(u.every(c=>c instanceof pt),()=>"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 p={};return u.forEach((c,d)=>{p[d]=()=>c}),p};return this.runKernelFunc({forwardFunc:r,backwardsFunc:s,inputs:n})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){let t=id(),a=await this.backend.time(e);return a.wallMs=id()-t,a}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 W5;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}};ld.nextTensorId=0;ld.nextVariableId=0;function sT(e){let t=L1(At(e),"float32");return z.makeTensor(t,e,"float32")}function IA(){let e=gA();if(e._tfengine==null){let t=new mA(e);e._tfengine=new ld(t)}return IS(e._tfengine.ENV),JS(()=>e._tfengine),e._tfengine}var z=IA();function iT(e,t){let a={a:e,b:t};return z.runKernel(ts,a)}var jd={};Xe(jd,{isBrowser:()=>SA,isMobile:()=>uT,mockIsMobile:()=>lT});function oT(){return typeof navigator!="undefined"&&navigator!=null}var Jm;function lT(e){Jm=e}function uT(e){if(Jm!==void 0)return Jm;if(e||oT()){if(e||(e=navigator),e.product==="ReactNative")return!0;let t=e.userAgent||e.vendor||(typeof window!="undefined"?window.opera:"");if(!t){let a=e;return a.userAgentData&&a.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 SA(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var hn=W();hn.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.")});hn.registerFlag("IS_BROWSER",()=>SA());hn.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");hn.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));hn.registerFlag("PROD",()=>!1);hn.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>hn.getBool("DEBUG"));hn.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);hn.registerFlag("IS_TEST",()=>!1);hn.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);hn.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);hn.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1);hn.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);function Yn(e,t){let a=e;if(da(e))return t==="string"?[]:[e.length];if(typeof e=="object"&&"texture"in e){let r=e.channels||"RGBA";return[e.height,e.width*r.length]}if(!Array.isArray(e))return[];let n=[];for(;Array.isArray(a)||da(a)&&t!=="string";)n.push(a.length),a=a[0];return Array.isArray(e)&&W().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&TA(e,n,[]),n}function TA(e,t,a){if(a=a||[],!Array.isArray(e)&&!da(e)){P(t.length===0,()=>`Element arr[${a.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}P(t.length>0,()=>`Element arr[${a.join("][")}] should be a primitive, but is an array of ${e.length} elements`),P(e.length===t[0],()=>`Element arr[${a.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let n=t.slice(1);for(let r=0;r<e.length;++r)TA(e[r],n,a.concat(r))}function V5(e,t,a,n){if(e!=="string_or_numeric"){if(e==null)throw new Error("Expected dtype cannot be null.");if(e!=="numeric"&&e!==t||e==="numeric"&&t==="string")throw new Error(`Argument '${a}' passed to '${n}' must be ${e} tensor, but got ${t} tensor`)}}function R(e,t,a,n="numeric"){if(e instanceof pt)return V5(n,e.dtype,t,a),e;let r=Uc(e);if(r!=="string"&&["bool","int32","float32"].indexOf(n)>=0&&(r=n),V5(n,r,t,a),e==null||!da(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){let o=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${a}' must be a Tensor or TensorLike, but got '${o}'`)}let s=Yn(e,r);!da(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?ph(e,r):zs(e,[],!0);return z.makeTensor(i,s,r)}function ud(e,t,a,n="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${a} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((r,s)=>R(r,`${t}[${s}]`,a,n))}var e2="__op";function D(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 a=t[0],n=e[a];a.endsWith("_")&&(a=a.substring(0,a.length-1)),a=a+e2;let r=(...s)=>{z.startScope(a);try{let i=n(...s);return B1(i)&&console.error("Cannot return a Promise inside of tidy."),z.endScope(i),i}catch(i){throw z.endScope(null),i}};return Object.defineProperty(r,"name",{value:a,configurable:!0}),r}function dT(e,t){let a=R(e,"real","complex"),n=R(t,"imag","complex");Sa(a.shape,n.shape,`real and imag shapes, ${a.shape} and ${n.shape}, must match in call to tf.complex().`);let r={real:a,imag:n};return z.runKernel(Sd,r)}var br=D({complex_:dT});function rs(e,t,a,n){if(n==null&&(n=Uc(e)),n==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(typeof e=="object"&&"texture"in e){if(n!=="float32"&&n!=="int32")throw new Error(`Creating tensor from texture only supports 'float32'|'int32' dtype, while the dtype is ${n}.`);return e.channels=e.channels||"RGBA",z.backend.createTensorFromTexture(e,t||a,n)}if(!da(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){Ja(t);let r=At(t),s=At(a);P(r===s,()=>`Based on the provided shape, [${t}], the tensor should have ${r} values but has ${s}`);for(let i=0;i<a.length;++i){let o=a[i],l=i===a.length-1?o!==At(t.slice(i)):!0;P(a[i]===t[i]||!l,()=>`Error creating a new Tensor. Inferred shape (${a}) does not match the provided shape (${t}). `)}}return!da(e)&&!Array.isArray(e)&&(e=[e]),t=t||a,e=n!=="string"?ph(e,n):zs(e,[],!0),z.makeTensor(e,t,n)}function Be(e,t,a){let n=Yn(e,a);return rs(e,t,n,a)}var Qm={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},Cc=4;async function pT(e,t){let a=[],n=[],r=Array.isArray(e)?e.map(i=>i.name):Object.keys(e);for(let i=0;i<r.length;++i){let o=r[i],l=Array.isArray(e)?e[i].tensor:e[o];if(l.dtype!=="float32"&&l.dtype!=="int32"&&l.dtype!=="bool"&&l.dtype!=="string"&&l.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${o}': ${l.dtype}`);let u={name:o,shape:l.shape,dtype:l.dtype};if(l.dtype==="string"){let p=new Promise(async c=>{let d=await l.bytes(),h=d.reduce((g,x)=>g+x.length,0)+Cc*d.length,f=new Uint8Array(h),m=0;for(let g=0;g<d.length;g++){let x=d[g],A=new Uint8Array(new Uint32Array([x.length]).buffer);f.set(A,m),m+=Cc,f.set(x,m),m+=x.length}c(f)});n.push(p)}else n.push(l.data());t!=null&&(u.group=t),a.push(u)}let s=await Promise.all(n);return{data:cT(s),specs:a}}function CA(e,t){let a={},n,r=0;for(let s of t){let i=s.name,o=s.dtype,l=s.shape,u=At(l),p;if("quantization"in s){let c=s.quantization;if(c.dtype==="uint8"||c.dtype==="uint16"){if(!("min"in c&&"scale"in c))throw new Error(`Weight ${s.name} with quantization ${c.dtype} doesn't have corresponding metadata min and scale.`)}else if(c.dtype==="float16"){if(o!=="float32")throw new Error(`Weight ${s.name} is quantized with ${c.dtype} which only supports weights of type float32 not ${o}.`)}else throw new Error(`Weight ${s.name} has unknown quantization dtype ${c.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let d=Qm[c.dtype],h=e.slice(r,r+u*d),f=c.dtype==="uint8"?new Uint8Array(h):new Uint16Array(h);if(o==="float32")if(c.dtype==="uint8"||c.dtype==="uint16"){p=new Float32Array(f.length);for(let m=0;m<f.length;m++){let g=f[m];p[m]=g*c.scale+c.min}}else if(c.dtype==="float16")n===void 0&&(n=AT()),p=n(f);else throw new Error(`Unsupported quantization type ${c.dtype} for weight type float32.`);else if(o==="int32"){if(c.dtype!=="uint8"&&c.dtype!=="uint16")throw new Error(`Unsupported quantization type ${c.dtype} for weight type int32.`);p=new Int32Array(f.length);for(let m=0;m<f.length;m++){let g=f[m];p[m]=Math.round(g*c.scale+c.min)}}else throw new Error(`Unsupported dtype in weight '${i}': ${o}`);r+=u*d}else if(o==="string"){let c=At(s.shape);p=[];for(let d=0;d<c;d++){let h=new Uint32Array(e.slice(r,r+Cc))[0];r+=Cc;let f=new Uint8Array(e.slice(r,r+h));p.push(f),r+=h}}else{let c=Qm[o],d=e.slice(r,r+u*c);if(o==="float32")p=new Float32Array(d);else if(o==="int32")p=new Int32Array(d);else if(o==="bool")p=new Uint8Array(d);else if(o==="complex64"){p=new Float32Array(d);let h=new Float32Array(p.length/2),f=new Float32Array(p.length/2);for(let x=0;x<h.length;x++)h[x]=p[x*2],f[x]=p[x*2+1];let m=Be(h,l,"float32"),g=Be(f,l,"float32");a[i]=br(m,g),m.dispose(),g.dispose()}else throw new Error(`Unsupported dtype in weight '${i}': ${o}`);r+=u*c}o!=="complex64"&&(a[i]=Be(p,l,o))}return a}function cT(e){if(e===null)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0,a=[];e.forEach(s=>{if(t+=s.byteLength,a.push(s.byteLength===s.buffer.byteLength?s:new s.constructor(s)),!(s instanceof Float32Array||s instanceof Int32Array||s instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${s.constructor.name}`)});let n=new Uint8Array(t),r=0;return a.forEach(s=>{n.set(new Uint8Array(s.buffer),r),r+=s.byteLength}),n.buffer}var t2=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function U5(e){return t2?Buffer.byteLength(e):new Blob([e]).size}function hT(e){if(t2)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),a="";for(let n=0,r=t.length;n<r;n++)a+=String.fromCharCode(t[n]);return btoa(a)}function fT(e){if(t2){let n=Buffer.from(e,"base64");return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}let t=atob(e),a=new Uint8Array(t.length);for(let n=0;n<t.length;++n)a.set([t.charCodeAt(n)],n);return a.buffer}function a2(e){if(e.length===1)return e[0];let t=0;e.forEach(r=>{t+=r.byteLength});let a=new Uint8Array(t),n=0;return e.forEach(r=>{a.set(new Uint8Array(r),n),n+=r.byteLength}),a.buffer}function G5(e){let t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);let a=e.split(t);return a[a.length-1]}function NA(e,t){let a={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return e.signature!=null&&(a.signature=e.signature),e.userDefinedMetadata!=null&&(a.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(a.modelInitializer=e.modelInitializer),e.initializerSignature!=null&&(a.initializerSignature=e.initializerSignature),e.trainingConfig!=null&&(a.trainingConfig=e.trainingConfig),a}function EA(e,t,a){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),e.weightsManifest!=null){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!a)throw new Error("modelJSON has weightsManifest but weightData is null");n.weightSpecs=t,n.weightData=a}return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),e.initializerSignature!=null&&(n.initializerSignature=e.initializerSignature),n}async function n2(e,t){let a,n;return e.weightsManifest!=null&&([a,n]=await t(e.weightsManifest)),EA(e,a,n)}function qd(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:U5(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:U5(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function RA(e){let t=[];for(let a of e)t.push(...a.weights);return t}function mT(){let e=a=>{let n=a<<13,r=0;for(;(n&8388608)===0;)r-=8388608,n<<=1;return n&=-8388609,r+=947912704,n|r},t=new Uint32Array(2048);t[0]=0;for(let a=1;a<1024;a++)t[a]=e(a);for(let a=1024;a<2048;a++)t[a]=939524096+(a-1024<<13);return t}function gT(){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 xT(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function AT(){let e=mT(),t=gT(),a=xT();return n=>{let r=new ArrayBuffer(4*n.length),s=new Uint32Array(r);for(let i=0;i<n.length;i++){let o=n[i],l=e[a[o>>10]+(o&1023)]+t[o>>10];s[i]=l}return new Float32Array(r)}}var Rt=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Rt.instance==null&&(Rt.instance=new Rt),Rt.instance}static registerSaveRouter(e){Rt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Rt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Rt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Rt.getHandlers(e,"load",t)}static getHandlers(e,t,a){let n=[];return(t==="load"?Rt.getInstance().loadRouters:Rt.getInstance().saveRouters).forEach(r=>{let s=r(e,a);s!==null&&n.push(s)}),n}},yT=e=>Rt.registerSaveRouter(e),bT=e=>Rt.registerLoadRouter(e),vT=e=>Rt.getSaveHandlers(e),wT=(e,t)=>Rt.getLoadHandlers(e,t),e1="tensorflowjs",t1=1,Fs="models_store",Br="model_info_store";function MA(){if(!W().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 a1(e){let t=e.result;t.createObjectStore(Fs,{keyPath:"modelPath"}),t.createObjectStore(Br,{keyPath:"modelPath"})}var Ls=class{constructor(e){if(this.indexedDB=MA(),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((a,n)=>{let r=this.indexedDB.open(e1,t1);r.onupgradeneeded=()=>a1(r),r.onsuccess=()=>{let s=r.result;if(t==null){let i=s.transaction(Fs,"readonly"),o=i.objectStore(Fs).get(this.modelPath);o.onsuccess=()=>{if(o.result==null)return s.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));a(o.result.modelArtifacts)},o.onerror=l=>(s.close(),n(o.error)),i.oncomplete=()=>s.close()}else{let i=qd(t),o=s.transaction(Br,"readwrite"),l=o.objectStore(Br),u=l.put({modelPath:this.modelPath,modelArtifactsInfo:i}),p;u.onsuccess=()=>{p=s.transaction(Fs,"readwrite");let c=p.objectStore(Fs).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i});c.onsuccess=()=>a({modelArtifactsInfo:i}),c.onerror=d=>{l=o.objectStore(Br);let h=l.delete(this.modelPath);h.onsuccess=()=>(s.close(),n(c.error)),h.onerror=f=>(s.close(),n(c.error))}},u.onerror=c=>(s.close(),n(u.error)),o.oncomplete=()=>{p==null?s.close():p.oncomplete=()=>s.close()}}},r.onerror=s=>n(r.error)})}};Ls.URL_SCHEME="indexeddb://";var $A=e=>W().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ls.URL_SCHEME)?kT(e.slice(Ls.URL_SCHEME.length)):null;Rt.registerSaveRouter($A);Rt.registerLoadRouter($A);function kT(e){return new Ls(e)}function IT(e){return e.startsWith(Ls.URL_SCHEME)?e.slice(Ls.URL_SCHEME.length):e}var ST=class{constructor(){this.indexedDB=MA()}async listModels(){return new Promise((e,t)=>{let a=this.indexedDB.open(e1,t1);a.onupgradeneeded=()=>a1(a),a.onsuccess=()=>{let n=a.result,r=n.transaction(Br,"readonly"),s=r.objectStore(Br).getAll();s.onsuccess=()=>{let i={};for(let o of s.result)i[o.modelPath]=o.modelArtifactsInfo;e(i)},s.onerror=i=>(n.close(),t(s.error)),r.oncomplete=()=>n.close()},a.onerror=n=>t(a.error)})}async removeModel(e){return e=IT(e),new Promise((t,a)=>{let n=this.indexedDB.open(e1,t1);n.onupgradeneeded=()=>a1(n),n.onsuccess=()=>{let r=n.result,s=r.transaction(Br,"readwrite"),i=s.objectStore(Br),o=i.get(e),l;o.onsuccess=()=>{if(o.result==null)return r.close(),a(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let u=i.delete(e),p=()=>{l=r.transaction(Fs,"readwrite");let c=l.objectStore(Fs).delete(e);c.onsuccess=()=>t(o.result.modelArtifactsInfo),c.onerror=d=>a(o.error)};u.onsuccess=p,u.onerror=c=>(p(),r.close(),a(o.error))}},o.onerror=u=>(r.close(),a(o.error)),s.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},n.onerror=r=>a(n.error)})}},xr="/",el="tensorflowjs_models",_A="info",TT="model_topology",CT="weight_specs",NT="weight_data",ET="model_metadata";function PA(e){return{info:[el,e,_A].join(xr),topology:[el,e,TT].join(xr),weightSpecs:[el,e,CT].join(xr),weightData:[el,e,NT].join(xr),modelMetadata:[el,e,ET].join(xr)}}function FA(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function RT(e){let t=e.split(xr);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(xr)}function MT(e){return e.startsWith(Bs.URL_SCHEME)?e.slice(Bs.URL_SCHEME.length):e}var Bs=class{constructor(e){if(!W().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=PA(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),a=JSON.stringify(e.weightSpecs),n=qd(e);try{this.LS.setItem(this.keys.info,JSON.stringify(n)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,a),this.LS.setItem(this.keys.weightData,hT(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,initializerSignature:e.initializerSignature!=null?e.initializerSignature:void 0,trainingConfig:e.trainingConfig!=null?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(r)),{modelArtifactsInfo:n}}catch(r){throw FA(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${n.modelTopologyBytes}, weightSpecsBytes=${n.weightSpecsBytes}, weightDataBytes=${n.weightDataBytes}.`)}}}async load(){let e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");let t={},a=JSON.parse(this.LS.getItem(this.keys.topology));if(a==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=a;let n=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(n==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=n;let r=this.LS.getItem(this.keys.modelMetadata);if(r!=null){let i=JSON.parse(r);t.format=i.format,t.generatedBy=i.generatedBy,t.convertedBy=i.convertedBy,i.signature!=null&&(t.signature=i.signature),i.userDefinedMetadata!=null&&(t.userDefinedMetadata=i.userDefinedMetadata),i.modelInitializer!=null&&(t.modelInitializer=i.modelInitializer),i.initializerSignature!=null&&(t.initializerSignature=i.initializerSignature),i.trainingConfig!=null&&(t.trainingConfig=i.trainingConfig)}let s=this.LS.getItem(this.keys.weightData);if(s==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=fT(s),t}};Bs.URL_SCHEME="localstorage://";var OA=e=>W().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Bs.URL_SCHEME)?$T(e.slice(Bs.URL_SCHEME.length)):null;Rt.registerSaveRouter(OA);Rt.registerLoadRouter(OA);function $T(e){return new Bs(e)}var _T=class{constructor(){P(W().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=el+xr,a=xr+_A;for(let n=0;n<this.LS.length;++n){let r=this.LS.key(n);if(r.startsWith(t)&&r.endsWith(a)){let s=RT(r);e[s]=JSON.parse(this.LS.getItem(r))}}return e}async removeModel(e){e=MT(e);let t=PA(e);if(this.LS.getItem(t.info)==null)throw new Error(`Cannot find model at path '${e}'`);let a=JSON.parse(this.LS.getItem(t.info));return FA(t),a}},nl="://",Oa=class{constructor(){this.managers={}}static getInstance(){return Oa.instance==null&&(Oa.instance=new Oa),Oa.instance}static registerManager(e,t){P(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(nl)&&(e=e.slice(0,e.indexOf(nl))),P(e.length>0,()=>"scheme must not be an empty string.");let a=Oa.getInstance();P(a.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),a.managers[e]=t}static getManager(e){let t=Oa.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(Oa.getInstance().managers)}};function fc(e){if(e.indexOf(nl)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Oa.getSchemes().join(",")}`);return{scheme:e.split(nl)[0],path:e.split(nl)[1]}}async function DA(e,t,a=!1){P(e!==t,()=>`Old path and new path are the same: '${e}'`);let n=Rt.getLoadHandlers(e);P(n.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),P(n.length<2,()=>`Copying failed because more than one (${n.length}) load handlers for source URL ${e}.`);let r=n[0],s=Rt.getSaveHandlers(t);P(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),P(s.length<2,()=>`Copying failed because more than one (${n.length}) save handlers for destination URL ${t}.`);let i=s[0],o=fc(e).scheme,l=fc(e).path,u=o===fc(e).scheme,p=await r.load();a&&u&&await Oa.getManager(o).removeModel(l);let c=await i.save(p);return a&&!u&&await Oa.getManager(o).removeModel(l),c.modelArtifactsInfo}async function PT(){let e=Oa.getSchemes(),t={};for(let a of e){let n=await Oa.getManager(a).listModels();for(let r in n){let s=a+nl+r;t[s]=n[r]}}return t}async function FT(e){let t=fc(e);return Oa.getManager(t.scheme).removeModel(t.path)}async function OT(e,t){return DA(e,t,!1)}async function DT(e,t){return DA(e,t,!0)}var zT=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(typeof window=="undefined"||!W().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",a=>{if(a.source===window&&a.data.name===this.messageName){a.stopPropagation();let n=this.functionRefs[a.data.index];n(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}},!0))}};if(W().get("IS_BROWSER")){W().setPlatform("browser",new zT);try{Oa.registerManager(Bs.URL_SCHEME,new _T)}catch(e){}try{Oa.registerManager(Ls.URL_SCHEME,new ST)}catch(e){}}var LT={importFetch:()=>GI()},Pm,BT=class{constructor(){this.util=HI(),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return W().global.fetch!=null?W().global.fetch(e,t):(Pm==null&&(Pm=LT.importFetch()),Pm(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)}};W().get("IS_NODE")&&!W().get("IS_BROWSER")&&W().setPlatform("node",new BT);function Me(e,t="float32",a){return t=t||"float32",Ja(e),new jt(e,t,a)}function WT(e,t){let a=R(e,"x","cast");if(!dA(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&a.dtype!=="string"||t!=="string"&&a.dtype==="string")throw new Error("Only strings can be casted to strings");let n={x:a},r={dtype:t};return z.runKernel(ti,n,r)}var He=D({cast_:WT});function VT(e){let t={x:R(e,"x","clone","string_or_numeric")};return z.runKernel(ki,t)}var wa=D({clone_:VT});function r2(e,t=!1){console.log(e.toString(t))}IA();var UT={buffer:Me,cast:He,clone:wa,print:r2};QS(UT);var jn={};Xe(jn,{browserFiles:()=>ZT,browserHTTPRequest:()=>tC,concatenateArrayBuffers:()=>a2,copyModel:()=>OT,decodeWeights:()=>CA,encodeWeights:()=>pT,fromMemory:()=>nC,fromMemorySync:()=>VA,getLoadHandlers:()=>wT,getModelArtifactsForJSON:()=>n2,getModelArtifactsForJSONSync:()=>EA,getModelArtifactsInfoForJSON:()=>qd,getSaveHandlers:()=>vT,getWeightSpecs:()=>RA,http:()=>i2,isHTTPScheme:()=>n1,listModels:()=>PT,loadWeights:()=>YT,moveModel:()=>DT,registerLoadRouter:()=>bT,registerSaveRouter:()=>yT,removeModel:()=>FT,weightsLoaderFactory:()=>LA,withSaveHandler:()=>rC,withSaveHandlerSync:()=>sC});var GT="model",HT=".json",jT=".weights.bin";function H5(e){return new Promise(t=>setTimeout(t)).then(e)}var ul=class{constructor(e){if(!W().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(ul.URL_SCHEME)&&(e=e.slice(ul.URL_SCHEME.length)),(e==null||e.length===0)&&(e=GT),this.modelJsonFileName=e+HT,this.weightDataFileName=e+jT}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 a=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],n=NA(e,a),r=window.URL.createObjectURL(new Blob([JSON.stringify(n)],{type:"application/json"})),s=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(s.download=this.modelJsonFileName,s.href=r,await H5(()=>s.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let i=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;i.download=this.weightDataFileName,i.href=t,await H5(()=>i.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:qd(e)}}}};ul.URL_SCHEME="downloads://";var qT=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 a=new FileReader;a.onload=n=>{let r=JSON.parse(n.target.result),s=r.modelTopology;if(s==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:s});return}let i=n2(r,o=>this.loadWeights(o));e(i)},a.onerror=n=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),a.readAsText(this.jsonFile)})}loadWeights(e){let t=[],a=[];for(let s of e)t.push(...s.weights),a.push(...s.paths);let n=this.checkManifestAndWeightFiles(e),r=a.map(s=>this.loadWeightsFile(s,n[s]));return Promise.all(r).then(s=>[t,a2(s)])}loadWeightsFile(e,t){return new Promise((a,n)=>{let r=new FileReader;r.onload=s=>{let i=s.target.result;a(i)},r.onerror=s=>n(`Failed to weights data from file of path '${e}'.`),r.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){let t=[],a=this.weightsFiles.map(r=>G5(r.name)),n={};for(let r of e)r.paths.forEach(s=>{let i=G5(s);if(t.indexOf(i)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${i}'`);if(t.push(i),a.indexOf(i)===-1)throw new Error(`Weight file with basename '${i}' is not provided.`);n[s]=this.weightsFiles[a.indexOf(i)]});if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return n}},XT=e=>W().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ul.URL_SCHEME)?KT(e.slice(ul.URL_SCHEME.length)):null;Rt.registerSaveRouter(XT);function KT(e="model"){return new ul(e)}function ZT(e){return new qT(e)}function j5(e,t,a,n){i(e),a=a==null?0:a,n=n==null?1:n,o(a,n);let r=0,s=l=>(l.then(u=>{let p=a+ ++r/e.length*(n-a);return t(p),u}),l);function i(l){P(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function o(l,u){P(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),P(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),P(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(e.map(s))}async function zA(e,t){t==null&&(t={});let a=t.fetchFunc==null?W().platform.fetch:t.fetchFunc,n=e.map(u=>a(u,t.requestInit,{isBinary:!0})),r=0,s=.5,i=(t.onProgress==null?await Promise.all(n):await j5(n,t.onProgress,r,s)).map(u=>u.arrayBuffer()),o=.5,l=1;return t.onProgress==null?await Promise.all(i):await j5(i,t.onProgress,o,l)}async function YT(e,t="",a,n){return LA(r=>zA(r,{requestInit:n}))(e,t,a)}function LA(e){return async(t,a="",n)=>{let r=t.map(()=>!1),s={},i=n!=null?n.map(()=>!1):[],o=[];if(t.forEach((h,f)=>{let m=0;h.weights.forEach(g=>{let x="quantization"in g?g.quantization.dtype:g.dtype,A=Qm[x]*At(g.shape),y=()=>{r[f]=!0,s[f]==null&&(s[f]=[]),s[f].push({manifestEntry:g,groupOffset:m,sizeBytes:A})};n!=null?n.forEach((b,w)=>{b===g.name&&(y(),i[w]=!0)}):y(),o.push(g.name),m+=A})}),!i.every(h=>h)){let h=n.filter((f,m)=>!i[m]);throw new Error(`Could not find weights in manifest with names: ${h.join(", ")}.
Manifest JSON has weights with names: ${o.join(", ")}.`)}let l=r.reduce((h,f,m)=>(f&&h.push(m),h),[]),u=[];l.forEach(h=>{t[h].paths.forEach(f=>{let m=a+(a.endsWith("/")?"":"/")+f;u.push(m)})});let p=await e(u),c={},d=0;return l.forEach(h=>{let f=t[h].paths.length,m=0;for(let y=0;y<f;y++)m+=p[d+y].byteLength;let g=new ArrayBuffer(m),x=new Uint8Array(g),A=0;for(let y=0;y<f;y++){let b=new Uint8Array(p[d+y]);x.set(b,A),A+=b.byteLength}s[h].forEach(y=>{let b=g.slice(y.groupOffset,y.groupOffset+y.sizeBytes),w=CA(b,[y.manifestEntry]);for(let S in w)c[S]=w[S]}),d+=f}),c}}var JT="application/octet-stream",QT="application/json",s2=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=W().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 a=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],n=NA(e,a);t.body.append("model.json",new Blob([JSON.stringify(n)],{type:QT}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:JT}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:qd(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 s=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?s+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":s+=" Please make sure the server is serving valid JSON for this request.",new Error(s)}let a=t.modelTopology,n=t.weightsManifest;if(a==null&&n==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return n2(t,r=>this.loadWeights(r))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[a,n]=eC(t),r=this.weightPathPrefix||a,s=RA(e),i=[],o=[];for(let u of e)for(let p of u.paths)this.weightUrlConverter!=null?o.push(this.weightUrlConverter(p)):i.push(r+p+n);this.weightUrlConverter&&i.push(...await Promise.all(o));let l=await zA(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[s,a2(l)]}};s2.URL_SCHEME_REGEX=/^https?:\/\//;function eC(e){let t=e.lastIndexOf("/"),a=e.lastIndexOf("?"),n=e.substring(0,t),r=a>t?e.substring(a):"";return[n+"/",r]}function n1(e){return e.match(s2.URL_SCHEME_REGEX)!=null}var BA=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let a=!0;if(Array.isArray(e)?a=e.every(n=>n1(n)):a=n1(e),a)return i2(e,t)}return null};Rt.registerSaveRouter(BA);Rt.registerLoadRouter(BA);function i2(e,t){return new s2(e,t)}function tC(e,t){return i2(e,t)}var Fm=class{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}},WA=class{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}},aC=class{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}};function nC(e,t,a,n){let r=arguments;return new aC(VA(...r))}function VA(e,t,a,n){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new Fm(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 Fm({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 Fm({modelTopology:e,weightSpecs:t,weightData:a,trainingConfig:n}))}function rC(e){return new WA(e)}function sC(e){return new WA(e)}var UA={};Xe(UA,{confusionMatrix:()=>wC});function iC(e,t,a=!1,n=!1){let r=R(e,"a","matMul"),s=R(t,"b","matMul");[r,s]=St(r,s);let i={a:r,b:s},o={transposeA:a,transposeB:n};return z.runKernel(ei,i,o)}var st=D({matMul_:iC});function oC(e,t,a=1,n=0,r="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let s={indices:R(e,"indices","oneHot","int32")},i={dtype:r,depth:t,onValue:a,offValue:n};return z.runKernel(Vi,s,i)}var Nc=D({oneHot_:oC});function o2(){W().set("PROD",!0)}function lC(){W().set("DEBUG",!0)}function uC(){W().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function l2(e){W().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}eT(l2);function dC(){z.disposeVariables()}function kt(){return z}function pC(){return z.memory()}function cC(e){return z.profile(e)}function $e(e,t){return z.tidy(e,t)}function Y(e){Q1(e).forEach(t=>t.dispose())}function On(e){return z.keep(e)}function hC(e){return z.time(e)}function Xd(e){return z.setBackend(e)}function Kd(){return z.ready()}function ia(){return z.backendName}function fC(e){z.removeBackend(e)}function u2(e){return z.findBackend(e)}function mC(e){return z.findBackendFactory(e)}function go(e,t,a=1){return z.registerBackend(e,t,a)}function tr(){return z.backend}function gC(e,t){W().setPlatform(e,t)}function xC(e){let t={input:R(e,"input","imag")};return z.runKernel(Rd,t)}var Zd=D({imag_:xC});function AC(e){let t={x:R(e,"x","neg")};return z.runKernel(Vl,t)}var Xn=D({neg_:AC});function yC(e){let t={input:R(e,"input","real")};return z.runKernel(Md,t)}var dl=D({real_:yC});function bC(e,t,a){let n=R(e,"x","transpose");if(t==null&&(t=n.shape.map((i,o)=>o).reverse()),P(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(i=>{P(i>=0&&i<n.rank,()=>`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();let r={x:n},s={perm:t};return n.dtype==="complex64"?$e(()=>{let i=dl(n),o=Zd(n);return i=z.runKernel(Ar,{x:i},s),o=z.runKernel(Ar,{x:o},s),a&&(o=Xn(o)),br(i,o)}):z.runKernel(Ar,r,s)}var Ws=D({transpose_:bC});function vC(e,t,a){let n=R(e,"labels","confusionMatrix"),r=R(t,"predictions","confusionMatrix");P(a==null||a>0&&Number.isInteger(a),()=>`If provided, numClasses must be a positive integer, but got ${a}`),P(n.rank===1,()=>`Expected the rank of labels to be 1, but got ${n.rank}`),P(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),P(n.shape[0]===r.shape[0],()=>`Mismatch in the number of examples: ${n.shape[0]} vs. ${r.shape[0]}. Labels and predictions should have the same number of elements.`),P(a>0&&Number.isInteger(a),()=>`numClasses is required to be a positive integer, but got ${a}`);let s=Nc(He(n,"int32"),a),i=Nc(He(r,"int32"),a),o=Ws(s),l=st(o,i);return He(l,"int32")}var wC=D({confusionMatrix_:vC}),xo={};Xe(xo,{assertAndGetBroadcastShape:()=>zt,getBroadcastDims:()=>GA,getReductionAxes:()=>d2});function GA(e,t){let a=e.length,n=[];for(let r=0;r<a;r++){let s=a-1-r,i=e[s]||1;(t[t.length-1-r]||1)>1&&i===1&&n.unshift(s)}return n}function d2(e,t){let a=[];for(let n=0;n<t.length;n++){let r=e[e.length-n-1],s=t.length-n-1,i=t[s];(r==null||r===1&&i>1)&&a.unshift(s)}return a}function zt(e,t){let a=[],n=Math.max(e.length,t.length);for(let r=0;r<n;r++){let s=e[e.length-r-1];s==null&&(s=1);let i=t[t.length-r-1];if(i==null&&(i=1),s===1)a.unshift(i);else if(i===1)a.unshift(s);else if(s!==i){let o=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(o)}else a.unshift(s)}return a}var wr={};Xe(wr,{fromPixels:()=>EC,fromPixelsAsync:()=>CC,toPixels:()=>NC});function p2(e,t,a){if(Xs(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let n=Yn(e,a);if(n.length!==3&&n.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return rs(e,t,n,a)}var Ns;function HA(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 a=!1,n=!1,r=!1,s=!1,i=!1,o=!1;if(e.data instanceof Uint8Array)a=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)n=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)r=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)s=!0;else if(e.getContext!=null)i=!0;else if(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)o=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);if(Sc(rd,z.backendName)!=null){let d={pixels:e},h={numChannels:t};return z.runKernel(rd,d,h)}let[l,u]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height],p;if(i)p=e.getContext("2d").getImageData(0,0,l,u).data;else if(n||a)p=e.data;else if(s||r||o){if(Ns==null)if(typeof document=="undefined")if(typeof OffscreenCanvas!="undefined"&&typeof OffscreenCanvasRenderingContext2D!="undefined")Ns=new OffscreenCanvas(1,1).getContext("2d");else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");else Ns=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Ns.canvas.width=l,Ns.canvas.height=u,Ns.drawImage(e,0,0,l,u),p=Ns.getImageData(0,0,l,u).data}let c;if(t===4)c=new Int32Array(p);else{let d=l*u;c=new Int32Array(d*t);for(let h=0;h<d;h++)for(let f=0;f<t;++f)c[h*t+f]=p[h*4+f]}return p2(c,[u,l,t],"int32")}function kC(e){return e!=null&&e.data instanceof Uint8Array}function IC(){return typeof window!="undefined"&&typeof ImageBitmap!="undefined"&&window.hasOwnProperty("createImageBitmap")}function SC(e){return e!=null&&e.width!==0&&e.height!==0}function TC(e){return IC()&&!(e instanceof ImageBitmap)&&SC(e)&&!kC(e)}async function CC(e,t=3){let a=null;if(W().getBool("WRAP_TO_IMAGEBITMAP")&&TC(e)){let n;try{n=await createImageBitmap(e,{premultiplyAlpha:"none"})}catch(r){n=null}n!=null&&n.width===e.width&&n.height===e.height?a=n:a=e}else a=e;return HA(a,t)}async function NC(e,t){let a=R(e,"img","toPixels");if(!(e instanceof pt)){let u=a;a=He(u,"int32"),u.dispose()}if(a.rank!==2&&a.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${a.rank}.`);let[n,r]=a.shape.slice(0,2),s=a.rank===2?1:a.shape[2];if(s>4||s===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${s}`);if(a.dtype!=="float32"&&a.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${a.dtype}. Please use float32 or int32 tensors.`);let i=await a.data(),o=a.dtype==="float32"?255:1,l=new Uint8ClampedArray(r*n*4);for(let u=0;u<n*r;++u){let p=[0,0,0,255];for(let d=0;d<s;d++){let h=i[u*s+d];if(a.dtype==="float32"){if(h<0||h>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${h}.`)}else if(a.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}.`);s===1?(p[0]=h*o,p[1]=h*o,p[2]=h*o):p[d]=h*o}let c=u*4;l[c+0]=Math.round(p[0]),l[c+1]=Math.round(p[1]),l[c+2]=Math.round(p[2]),l[c+3]=Math.round(p[3])}if(t!=null){t.width=r,t.height=n;let u=t.getContext("2d"),p=new ImageData(l,r,n);u.putImageData(p,0,0)}return a!==e&&a.dispose(),l}var EC=D({fromPixels_:HA}),c2={};Xe(c2,{prepareAndValidate:()=>jA});function jA(e,t){let a=e.shape.length,n=t.shape.length;if(a<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${a}.`);if(n<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${n}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[n-1]>a)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[n-1]} vs. ${a}`);if(At(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let r=t.shape,s=r[r.length-1],i=1;for(let c=0;c<r.length-1;++c)i*=r[c];let o=e.shape,l=r.slice();l.pop();let u=1;for(let c=s;c<a;++c)u*=o[c],l.push(o[c]);let p=[...vl(e.shape).map(c=>c/u),1].slice(0,s);return[l,i,u,p]}var h2={};Xe(h2,{calculateShapes:()=>qA,validateInput:()=>m2,validateUpdateShape:()=>f2});function f2(e,t,a){let n=t.rank>1?t.shape[t.rank-1]:1,r=t.rank>1?t.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${a.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${n}, and batchDim: ${r}.`;if(a.rank<r)throw new Error(s+` update.rank < ${r}. `);if(e.length<n+(a.rank-r))throw new Error(s+` Output shape length < ${n+(a.rank-r)}`);if(a.rank!==r+e.length-n)throw new Error(s+` update.rank != ${r+e.length-n}`);for(let i=0;i<r;++i)if(a.shape[i]!==t.shape[i])throw new Error(s+` updates.shape[${i}] (${a.shape[i]}) != indices.shape[${i}] (${t.shape[i]}).`);for(let i=0;i<a.rank-r;++i)if(a.shape[i+r]!==e[i+n])throw new Error(s+` updates.shape[${i+r}] (${a.shape[i+r]}) != shape[${i+r}] (${e[i+r]})`)}function m2(e,t,a){if(t.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if(t.dtype!=="int32")throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);if(a.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${a}`);if(a.length===0){if(t.size===0)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(e.size===0)throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}f2(a,t,e)}function qA(e,t,a){let n=t.shape.length,r=n>1?t.shape[n-1]:1,s=a.length,i=1;for(let c=r;c<s;++c)i*=a[c];let o=r<1?1:r,l=At(t.shape)/o,u=[...vl(a.slice(0,r)),1],p=At(a);return{sliceRank:r,numUpdates:l,sliceSize:i,strides:u,outputSize:p}}var It={};Xe(It,{assertParamsValid:()=>MC,computeFlatOffset:()=>OC,computeOutShape:()=>_C,getNormalizedAxes:()=>PC,isSliceContinous:()=>FC,maskToAxes:()=>$C,parseSliceParams:()=>DC,sliceInfo:()=>zC,startForAxis:()=>ey,startIndicesWithElidedDims:()=>YA,stopForAxis:()=>ty,stopIndicesWithElidedDims:()=>JA,stridesForAxis:()=>QA,stridesWithElidedDims:()=>XA});var r1=-2,RC=-1;function MC(e,t,a){let n=e.shape.length;P(n===t.length,()=>`Error in slice${n}D: Length of begin ${t} must match the rank of the array (${n}).`),P(n===a.length,()=>`Error in slice${n}D: Length of size ${a} must match the rank of the array (${n}).`);for(let r=0;r<n;++r)P(t[r]+a[r]<=e.shape[r],()=>`Error in slice${n}D: begin[${r}] + size[${r}] (${t[r]+a[r]}) would overflow input.shape[${r}] (${e.shape[r]})`)}function $C(e){let t=[],a=0;for(;e>0;)e&1&&t.push(a),e/=2,a++;return t}function _C(e,t,a){let n=[];for(let r=0;r<e.length;r++)n[r]=Math.ceil((t[r]-e[r])/a[r]);return n}function XA(e,t,a,n){let r=[...e];for(let s=r.length;s<n.length;s++)r.push(1);for(let s=0;s<a;s++)s===0?r[t]=1:(r.splice(t,0,1),r.pop());return r}function KA(e,t,a){return a<=e?a:a-(t-1)}function ZA(e,t){let a=[];for(let n=0;n<e;n++)a.push(t+n);return a}function PC(e,t,a,n,r,s,i,o,l){let u=e.length,p=new Array(u),c=new Array(u),d=new Array(u);if(t.length&&a>0){let h=t[0],f=a+1;p=YA(i,h,f,n,e),c=JA(o,h,f,r,e),d=XA(s,h,f,e)}else for(let h=0;h<u;h++)p[h]=ey(i,n,s,e,h,l),c[h]=ty(o,r,s,e,h,l),d[h]=QA(s,h,l);return{begin:p,end:c,strides:d}}function YA(e,t,a,n,r){let s=[...r],i=ZA(a,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=0;else{let l=KA(t,a,o),u=n[l];e&1<<l&&(u=0),s[o]=u}return s}function JA(e,t,a,n,r){let s=[...r],i=ZA(a,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=Number.MAX_SAFE_INTEGER;else{let l=KA(t,a,o),u=n[l];e&1<<l&&(u=Number.MAX_SAFE_INTEGER),s[o]=u}for(let o=0;o<s.length;o++){let l=r[o];s[o]<0&&(s[o]+=l),s[o]=nd(0,s[o],r[o])}return s}function QA(e,t,a){let n=e[t];return(a&1<<t||n==null)&&(n=1),n}function ey(e,t,a,n,r,s){let i=t[r],o=a[r]||1;(e&1<<r||s&1<<r||i==null)&&(o>0?i=Number.MIN_SAFE_INTEGER:i=Number.MAX_SAFE_INTEGER);let l=n[r];return i<0&&(i+=l),i=nd(0,i,l-1),i}function ty(e,t,a,n,r,s){let i=t[r],o=a[r]||1;(e&1<<r||s&1<<r||i==null)&&(o>0?i=Number.MAX_SAFE_INTEGER:i=Number.MIN_SAFE_INTEGER);let l=n[r];return i<0&&(i+=l),o>0?i=nd(0,i,l):i=nd(-1,i,l-1),i}function FC(e,t,a){let n=a.length;for(let r=0;r<a.length;r++)if(a[r]>1){n=r;break}for(let r=n+1;r<a.length;r++)if(t[r]>0||a[r]!==e[r])return!1;return!0}function OC(e,t){let a=e.length>0?e[e.length-1]:1;for(let n=0;n<e.length-1;n++)a+=e[n]*t[n];return a}function DC(e,t,a){let n,r=e.shape.length;typeof t=="number"?n=[t,...new Array(r-1).fill(0)]:t.length<r?n=t.concat(new Array(r-t.length).fill(0)):n=t.slice(),n.forEach(i=>{P(i!==-1,()=>"slice() does not support negative begin indexing.")});let s;return a==null?s=new Array(r).fill(-1):typeof a=="number"?s=[a,...new Array(r-1).fill(-1)]:a.length<r?s=a.concat(new Array(r-a.length).fill(-1)):s=a,s=s.map((i,o)=>i>=0?i:(P(i===-1,()=>`Negative size values should be exactly -1 but got ${i} for the slice() size at index ${o}.`),e.shape[o]-n[o])),[n,s]}function zC(e,t,a,n,r,s,i,o,l){let u;if(n==null?(u=new Array(t.length),u.fill(1)):u=n,i!=null&&(i&i-1)!==0)throw new Error("Multiple ellipses in slice is not allowed.");let p=!1,c={dims:u.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:a.slice(),strides:u.slice(),beginMask:r,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};for(let A=0;A<c.dims;A++)p&&(1<<A&o)!==0&&c.numAddAxisAfterEllipsis++,1<<A&i&&(p=!0);p||(c.ellipsisMask|=1<<c.dims,c.dims++);let d={dims:e.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};LC(c,d);let h=!0,f=!0,m=!0,g=[],x=[];for(let A=0;A<e.length;++A){if(d.strides[A]===0)throw Error(`strides[${A}] must be non-zero`);let y=!!(d.shrinkAxisMask&1<<A),b=e[A];if(b===-1){g.push(y?1:-1);continue}let w=[d.beginMask&1<<A,d.endMask&1<<A],S=[d.strides[A]>0?0:-1,d.strides[A]>0?b:b-1];if(y&&d.strides[A]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&d.strides[A]===1;let C=!!(d.beginMask&1<<A&&d.endMask&1<<A);if(d.beginValid&&d.endValid){if(y){let M=d.begin[A]<0?b+d.begin[A]:d.begin[A];if(d.begin[A]=M,d.end[A]=d.begin[A]+1,M<0||M>=b)throw Error(`slice index ${d.begin[A]} of dimension ${A} out of bounds.`)}else d.begin[A]=q5(d.begin[A],0,d.strides[A],b,w,S),d.end[A]=q5(d.end[A],1,d.strides[A],b,w,S);let $=d.strides[A]===1&&d.begin[A]===0&&d.end[A]===b;h=h&&$,f=f&&(A===0&&d.strides[A]===1||$)}else h=h&&d.strides[A]===1&&C,f=f&&(A===0&&d.strides[A]===1||C);let E,_=!1;if(d.beginValid&&d.endValid?(E=d.end[A]-d.begin[A],_=!0):y?(E=1,_=!0):C&&b>=0&&(d.strides[A]<0?E=-b:E=b,_=!0),_){let $;E===0||E<0!=d.strides[A]<0?$=0:$=Math.trunc(E/d.strides[A])+(E%d.strides[A]!==0?1:0),g.push($)}else g.push(-1)}for(let A=0;A<d.finalShapeGatherIndices.length;++A){let y=d.finalShapeGatherIndices[A];y>=0?x.push(g[y]):y===r1&&x.push(1)}return{finalShapeSparse:x.filter((A,y)=>d.finalShapeGatherIndices[y]!==r1),finalShape:x,isIdentity:h,sliceDim0:f,isSimpleSlice:m,begin:d.begin,end:d.end,strides:d.strides}}function LC(e,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let a=0;t.beginValid=e.begin!=null,t.endValid=e.end!=null,t.begin=new Array(t.dims),t.end=new Array(t.dims),t.strides=new Array(t.dims),t.finalShapeGatherIndices=[],t.finalShapeGatherIndicesSparse=[],t.inputShapeGatherIndicesSparse=new Array(t.dims);for(let n=0;n<e.dims;n++)if(1<<n&e.ellipsisMask){let r=Math.min(t.dims-(e.dims-n)+1+e.numAddAxisAfterEllipsis,t.dims);for(;a<r;a++)t.begin[a]=0,t.end[a]=0,t.strides[a]=1,t.beginMask|=1<<a,t.endMask|=1<<a,t.finalShapeGatherIndices.push(a),t.finalShapeGatherIndicesSparse.push(-1),t.inputShapeGatherIndicesSparse[a]=n}else if(1<<n&e.newAxisMask)t.finalShapeGatherIndices.push(r1),t.finalShapeGatherIndicesSparse.push(-1);else{if(a===t.begin.length)throw Error(`Index out of range using input dim ${a}; input has only ${t.dims} dims, ${t.begin.length}.`);e.begin!=null&&(t.begin[a]=e.begin[n]),e.end!=null&&(t.end[a]=e.end[n]),t.strides[a]=e.strides[n],e.beginMask&1<<n&&(t.beginMask|=1<<a),e.endMask&1<<n&&(t.endMask|=1<<a),e.shrinkAxisMask&1<<n?(t.finalShapeGatherIndices.push(RC),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<a):(t.finalShapeGatherIndices.push(a),t.finalShapeGatherIndicesSparse.push(n)),t.inputShapeGatherIndicesSparse[a]=n,a++}}function q5(e,t,a,n,r,s){if(r[t])return a>0?s[t]:s[t+1&1];{let i=e<0?n+e:e;return i<s[0]?s[0]:i>s[1]?s[1]:i}}var ay={};Xe(ay,{Serializable:()=>ny,SerializationMap:()=>_s,registerClass:()=>ss});var ny=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},_s=class{constructor(){this.classNameMap={}}static getMap(){return _s.instance==null&&(_s.instance=new _s),_s.instance}static register(e){_s.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function ss(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."),_s.register(e)}var ry={};Xe(ry,{TEST_EPSILON_FLOAT16:()=>sy,createVideoElement:()=>qC,encodeStrings:()=>iy,expectArrayBuffersEqual:()=>jC,expectArraysClose:()=>WC,expectArraysEqual:()=>UC,expectNumbersClose:()=>GC,expectPromiseToFail:()=>VC,expectValuesInRange:()=>HC,play:()=>XC,testEpsilon:()=>g2});var BC=.001,sy=.1;function WC(e,t,a){return a==null&&(a=g2()),s1(e,t,(n,r)=>x2(n,r,a))}function g2(){return z.backend.floatPrecision()===32?BC:sy}function s1(e,t,a){let n=!0;if((da(e)||da(t))&&(n=!1),da(e)&&da(t)&&(n=!0),n){let i=e.constructor.name,o=t.constructor.name;if(i!==o)throw new Error(`Arrays are of different type. Actual: ${i}. Expected: ${o}`)}if(Array.isArray(e)&&Array.isArray(t)){let i=Yn(e),o=Yn(t);if(!es(i,o))throw new Error(`Arrays have different shapes. Actual: [${i}]. Expected: [${o}]`)}let r=da(e)?e:zs(e),s=da(t)?t:zs(t);if(r.length!==s.length)throw new Error(`Arrays have different lengths actual: ${r.length} vs expected: ${s.length}.
Actual: ${r}.
Expected: ${s}.`);for(let i=0;i<s.length;++i){let o=r[i],l=s[i];if(!a(o,l))throw new Error(`Arrays differ: actual[${i}] = ${o}, expected[${i}] = ${l}.
Actual: ${r}.
Expected: ${s}.`)}typeof expect!="undefined"&&expect().nothing()}function VC(e,t){e().then(()=>t.fail(),()=>t()),typeof expect!="undefined"&&expect().nothing()}function UC(e,t){let a=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Lr(e)||Lr(e[0])||Lr(t)||Lr(t[0])?s1(e,a,(n,r)=>n==r):s1(e,t,(n,r)=>x2(n,r,0))}function GC(e,t,a){if(a==null&&(a=g2()),!x2(e,t,a))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`);typeof expect!="undefined"&&expect().nothing()}function x2(e,t,a){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>a)}function HC(e,t,a){for(let n=0;n<e.length;n++)if(e[n]<t||e[n]>a)throw new Error(`Value out of range:${e[n]} low: ${t}, high: ${a}`)}function jC(e,t){let a=new Float32Array(e),n=new Float32Array(t);if(a.length!==n.length)throw new Error(`Expected ArrayBuffer to be of length ${n.length}, but it was ${a.length}`);for(let r=0;r<n.length;r++)if(a[r]!==n[r])throw new Error(`Expected ArrayBuffer value at ${r} to be ${n[r]} but got ${a[r]} instead`)}function iy(e){for(let t=0;t<e.length;t++){let a=e[t];Array.isArray(a)?iy(a):e[t]=Gd(a)}return e}function qC(e){let t=document.createElement("video");return"playsInline"in t&&(t.playsInline=!0),t.muted=!0,t.loop=!0,t.style.position="fixed",t.style.left="0px",t.style.top="0px",t.preload="auto",t.appendChild(e),new Promise(a=>{t.addEventListener("loadeddata",n=>a(t)),t.load()})}async function XC(e){await e.play(),"requestVideoFrameCallback"in e&&await new Promise(t=>{e.requestVideoFrameCallback(t)})}var A2="4.1.0";function KC(e,t){let a=R(e,"a","add"),n=R(t,"b","add");[a,n]=St(a,n);let r={a,b:n};return z.runKernel(ts,r)}var be=D({add_:KC});function ZC(e,t){let a=R(e,"a","floorDiv"),n=R(t,"b","floorDiv");[a,n]=St(a,n);let r={a,b:n};return z.runKernel(Ai,r)}var Yd=D({floorDiv_:ZC});function YC(e,t){let a=R(e,"a","div"),n=R(t,"b","div");if([a,n]=St(a,n),a.dtype==="int32"&&n.dtype==="int32")return Yd(a,n);let r={a,b:n},s={};return z.runKernel(ci,r,s)}var me=D({div_:YC});function JC(e,t){let a=R(e,"a","mul"),n=R(t,"b","mul");[a,n]=St(a,n);let r={a,b:n};return z.runKernel(zi,r)}var ae=D({mul_:JC});function QC(e){let t=R(e,"x","abs");if(t.dtype==="complex64"){let a={x:t};return z.runKernel(qc,a)}else{let a={x:t};return z.runKernel(wl,a)}}var qa=D({abs_:QC});function eN(e){let t={x:R(e,"x","acos")};return z.runKernel(kl,t)}var oy=D({acos_:eN});function tN(e){let t={x:R(e,"x","acosh")};return z.runKernel(Il,t)}var ly=D({acosh_:tN});function aN(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,s)=>R(r,`tensors${s}`,"addN")),a=t[0];t.forEach(r=>{if(r.dtype!==a.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!es(r.shape,a.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let n=t;return z.runKernel(Ks,n)}var ch=D({addN_:aN});function nN(e,t=null,a=!1){let n={x:R(e,"x","all","bool")},r={axis:t,keepDims:a};return z.runKernel(Zs,n,r)}var uy=D({all_:nN});function rN(e,t=null,a=!1){let n={x:R(e,"x","any","bool")},r={axis:t,keepDims:a};return z.runKernel(Ys,n,r)}var dy=D({any_:rN});function sN(e,t=0){let a={x:R(e,"x","argMax")},n={axis:t};return z.runKernel(Js,a,n)}var ar=D({argMax_:sN});function iN(e,t=0){let a={x:R(e,"x","argMin")},n={axis:t};return z.runKernel(kd,a,n)}var py=D({argMin_:iN});function oN(e){let t={x:R(e,"x","asin")};return z.runKernel(Sl,t)}var cy=D({asin_:oN});function lN(e){let t={x:R(e,"x","asinh")};return z.runKernel(Tl,t)}var hy=D({asinh_:lN});function uN(e){let t={x:R(e,"x","atan")};return z.runKernel(Cl,t)}var fy=D({atan_:uN});function dN(e,t){let a=R(e,"a","atan2"),n=R(t,"b","atan2");[a,n]=St(a,n);let r={a,b:n};return z.runKernel(El,r)}var my=D({atan2_:dN});function pN(e){let t={x:R(e,"x","atanh")};return z.runKernel(Nl,t)}var gy=D({atanh_:pN});function cN(e,t,a,n,r="NHWC",s){let i=e[3],o=[...t,i],l=yy(r);return Jd(e,o,a,s,n,null,null,l)}function xy(e,t,a,n,r,s,i="channelsLast"){let[o,l]=Ec(t),u;if(i==="channelsLast")u=[o,l,e[3],e[3]];else if(i==="channelsFirst")u=[o,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return Jd(e,u,a,n,r,s,!1,i)}function hN(e,t,a,n,r,s,i="NDHWC"){let[o,l,u]=i1(t),p,c;if(i==="NDHWC")c="channelsLast",p=[o,l,u,e[4],e[4]];else if(i==="NCDHW")c="channelsFirst",p=[o,l,u,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return Ay(e,p,a,n,r,!1,c,s)}function Jd(e,t,a,n,r,s,i=!1,o="channelsLast"){let[l,u,p,c]=[-1,-1,-1,-1];if(o==="channelsLast")[l,u,p,c]=e;else if(o==="channelsFirst")[l,c,u,p]=e;else throw new Error(`Unknown dataFormat ${o}`);let[d,h,,f]=t,[m,g]=Ec(a),[x,A]=Ec(n),y=rl(d,x),b=rl(h,A),{padInfo:w,outHeight:S,outWidth:C}=gN(r,u,p,m,g,y,b,s,o),E=i?f*c:f,_;return o==="channelsFirst"?_=[l,E,S,C]:o==="channelsLast"&&(_=[l,S,C,E]),{batchSize:l,dataFormat:o,inHeight:u,inWidth:p,inChannels:c,outHeight:S,outWidth:C,outChannels:E,padInfo:w,strideHeight:m,strideWidth:g,filterHeight:d,filterWidth:h,effectiveFilterHeight:y,effectiveFilterWidth:b,dilationHeight:x,dilationWidth:A,inShape:e,outShape:_,filterShape:t}}function Ay(e,t,a,n,r,s=!1,i="channelsLast",o){let[l,u,p,c,d]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[l,u,p,c,d]=e;else if(i==="channelsFirst")[l,d,u,p,c]=e;else throw new Error(`Unknown dataFormat ${i}`);let[h,f,m,,g]=t,[x,A,y]=i1(a),[b,w,S]=i1(n),C=rl(h,b),E=rl(f,w),_=rl(m,S),{padInfo:$,outDepth:M,outHeight:I,outWidth:N}=xN(r,u,p,c,x,A,y,C,E,_,o),O=s?g*d:g,L;return i==="channelsFirst"?L=[l,O,M,I,N]:i==="channelsLast"&&(L=[l,M,I,N,O]),{batchSize:l,dataFormat:i,inDepth:u,inHeight:p,inWidth:c,inChannels:d,outDepth:M,outHeight:I,outWidth:N,outChannels:O,padInfo:$,strideDepth:x,strideHeight:A,strideWidth:y,filterDepth:h,filterHeight:f,filterWidth:m,effectiveFilterDepth:C,effectiveFilterHeight:E,effectiveFilterWidth:_,dilationDepth:b,dilationHeight:w,dilationWidth:S,inShape:e,outShape:L,filterShape:t}}function fN(e,t,a,n,r){n==null&&(n=y2(e,t,a));let s=e[0],i=e[1],o=Os((s-t+2*n)/a+1,r),l=Os((i-t+2*n)/a+1,r);return[o,l]}function mN(e,t,a,n,r,s){r==null&&(r=y2(e,t,n));let i=e[0],o=e[1],l=e[2],u=Os((i-t+2*r)/n+1,s),p=Os((o-t+2*r)/n+1,s),c=Os((l-t+2*r)/n+1,s);return[u,p,c,a]}function y2(e,t,a,n=1){let r=rl(t,n);return Math.floor((e[0]*(a-1)-a+r)/2)}function Ec(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function i1(e){return typeof e=="number"?[e,e,e]:e}function rl(e,t){return t<=1?e:e+(e-1)*(t-1)}function gN(e,t,a,n,r,s,i,o,l){let u,p,c;if(typeof e=="number"){u={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let d=fN([t,a],s,n,e,o);p=d[0],c=d[1]}else if(e==="same"){p=Math.ceil(t/n),c=Math.ceil(a/r);let d=Math.max(0,(p-1)*n+s-t),h=Math.max(0,(c-1)*r+i-a),f=Math.floor(d/2),m=d-f,g=Math.floor(h/2),x=h-g;u={top:f,bottom:m,left:g,right:x,type:"SAME"}}else if(e==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},p=Math.ceil((t-s+1)/n),c=Math.ceil((a-i+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"},p=Os((t-s+d+h)/n+1,o),c=Os((a-i+f+m)/r+1,o)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outHeight:p,outWidth:c}}function xN(e,t,a,n,r,s,i,o,l,u,p){let c,d,h,f;if(typeof e=="number"){c={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let m=mN([t,a,n,1],o,1,r,e,p);d=m[0],h=m[1],f=m[2]}else if(e==="same"){d=Math.ceil(t/r),h=Math.ceil(a/s),f=Math.ceil(n/i);let m=(d-1)*r+o-t,g=(h-1)*s+l-a,x=(f-1)*i+u-n,A=Math.floor(m/2),y=m-A,b=Math.floor(g/2),w=g-b,S=Math.floor(x/2),C=x-S;c={top:b,bottom:w,left:S,right:C,front:A,back:y,type:"SAME"}}else if(e==="valid")c={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},d=Math.ceil((t-o+1)/r),h=Math.ceil((a-l+1)/s),f=Math.ceil((n-u+1)/i);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:c,outDepth:d,outHeight:h,outWidth:f}}function Os(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 dd(e){let[t,a,n]=Ec(e);return t===1&&a===1&&n===1}function kr(e,t){return dd(e)||dd(t)}function yy(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Sn(e,t,a){if(a!=null){if(typeof t=="string")throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${a} but got pad ${t}.`);if(typeof t=="number")P(ol(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${a} but got pad ${t}.`);else if(typeof t=="object")t.forEach(n=>{n.forEach(r=>{P(ol(r),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${a} but got pad ${r}.`)})});else throw Error(`Error in ${e}: Unknown padding parameter: ${t}`)}}function AN(e,t){let a={x:R(e,"x","reshape","string_or_numeric")},n={shape:t};return z.runKernel(ql,a,n)}var J=D({reshape_:AN});function yN(e,t,a,n,r){let s=R(e,"x","avgPool","float32"),i=1;P(kr(a,i),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${i}'`);let o=s,l=!1;s.rank===3&&(l=!0,o=J(s,[1,s.shape[0],s.shape[1],s.shape[2]])),P(o.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${o.rank}.`),Sn("avgPool",n,r);let u={x:o},p={filterSize:t,strides:a,pad:n,dimRoundingMode:r},c=z.runKernel(Qs,u,p);return c=He(c,s.dtype),l?J(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var b2=D({avgPool_:yN});function bN(e,t,a,n,r,s="NDHWC"){let i=R(e,"x","avgPool3d","float32"),o=i,l=!1;i.rank===4&&(l=!0,o=J(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),P(o.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`),P(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),Sn("avgPool3d",n,r);let u={x:o},p={filterSize:t,strides:a,pad:n,dimRoundingMode:r,dataFormat:s},c=z.runKernel(Hc,u,p);return c=He(c,o.dtype),l?J(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var by=D({avgPool3d_:bN});function vN(e,t=0){P(e.length>=1,()=>"Pass at least one tensor to concat");let a=ud(e,"tensors","concat","string_or_numeric");if(a[0].dtype==="complex64"&&a.forEach(s=>{if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${s.dtype}. `)}),a.length===1)return wa(a[0]);let n=a,r={axis:t};return z.runKernel(Ml,n,r)}var at=D({concat_:vN});function wN(e){let t={x:R(e,"x","sigmoid","float32")};return z.runKernel(ao,t)}var Da=D({sigmoid_:wN});function kN(e,t,a){let n=R(e,"x","slice","string_or_numeric");if(n.rank===0)throw new Error("Slicing scalar is not possible");let r={x:n},s={begin:t,size:a};return z.runKernel(Zl,r,s)}var Pe=D({slice_:kN});function IN(e){let t={x:R(e,"x","tanh","float32")};return z.runKernel(po,t)}var Rc=D({tanh_:IN});function SN(e,t,a,n,r,s){let i=R(e,"forgetBias","basicLSTMCell"),o=R(t,"lstmKernel","basicLSTMCell"),l=R(a,"lstmBias","basicLSTMCell"),u=R(n,"data","basicLSTMCell"),p=R(r,"c","basicLSTMCell"),c=R(s,"h","basicLSTMCell"),d=at([u,c],1),h=st(d,o),f=be(h,l),m=f.shape[0],g=f.shape[1]/4,x=[m,g],A=Pe(f,[0,0],x),y=Pe(f,[0,g],x),b=Pe(f,[0,g*2],x),w=Pe(f,[0,g*3],x),S=be(ae(Da(A),Rc(y)),ae(p,Da(be(i,b)))),C=ae(Rc(S),Da(w));return[S,C]}var vy=D({basicLSTMCell_:SN});function TN(e,t,a){let n=R(e,"x","batchToSpaceND"),r=t.reduce((o,l)=>o*l);P(n.rank>=1+t.length,()=>`input rank is ${n.rank} but should be > than blockShape.length ${t.length}`),P(a.length===t.length,()=>`crops.length is ${a.length} but should be equal to blockShape.length ${t.length}`),P(n.shape[0]%r===0,()=>`input tensor batch is ${n.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`);let s={x:n},i={blockShape:t,crops:a};return z.runKernel(Rl,s,i)}var v2=D({batchToSpaceND_:TN});function CN(e){let t;return e.rank===0||e.rank===1?t=J(e,[1,1,1,e.size]):e.rank===2?t=J(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=J(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function NN(e,t,a,n,r,s){s==null&&(s=.001);let i=R(e,"x","batchNorm"),o=R(t,"mean","batchNorm"),l=R(a,"variance","batchNorm"),u;r!=null&&(u=R(r,"scale","batchNorm"));let p;n!=null&&(p=R(n,"offset","batchNorm")),P(o.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),P(p==null||o.rank===p.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),P(u==null||o.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let c={x:CN(i),scale:u,offset:p,mean:o,variance:l},d={varianceEpsilon:s},h=z.runKernel(yi,c,d);return J(h,i.shape)}var Qd=D({batchNorm_:NN});function EN(e,t,a,n,r,s){let i=R(e,"x","batchNorm"),o=R(t,"mean","batchNorm"),l=R(a,"variance","batchNorm"),u;r!=null&&(u=R(r,"scale","batchNorm"));let p;return n!=null&&(p=R(n,"offset","batchNorm")),P(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),P(o.rank===2||o.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`),P(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),p!=null&&P(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${p.rank}.`),Qd(i,o,l,p,u,s)}var wy=D({batchNorm2d_:EN});function RN(e,t,a,n,r,s){let i=R(e,"x","batchNorm"),o=R(t,"mean","batchNorm"),l=R(a,"variance","batchNorm"),u;r!=null&&(u=R(r,"scale","batchNorm"));let p;return n!=null&&(p=R(n,"offset","batchNorm")),P(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),P(o.rank===3||o.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`),P(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),p!=null&&P(p.rank===3||p.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${p.rank}.`),Qd(i,o,l,p,u,s)}var ky=D({batchNorm3d_:RN});function MN(e,t,a,n,r,s){let i=R(e,"x","batchNorm"),o=R(t,"mean","batchNorm"),l=R(a,"variance","batchNorm"),u;r!=null&&(u=R(r,"scale","batchNorm"));let p;return n!=null&&(p=R(n,"offset","batchNorm")),P(i.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`),P(o.rank===4||o.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`),P(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),p!=null&&P(p.rank===4||p.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${p.rank}.`),Qd(i,o,l,p,u,s)}var Iy=D({batchNorm4d_:MN});function $N(e,t,a){let n=R(e,"x","bincount"),r=R(t,"weights","bincount");P(n.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${n.dtype}`),P(a>=0,()=>`size must be non-negative, but got ${a}.`),P(r.size===n.size||r.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${n.shape}, weights shape: ${r.shape}.`);let s={x:n,weights:r},i={size:a};return z.runKernel(Id,s,i)}var w2=D({bincount_:$N});function _N(e,t){let a=R(e,"s0","broadcastArgs","int32"),n=R(t,"s1","broadcastArgs","int32");if(a.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${a.rank}`);if(n.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${n.rank}`);let r={s0:a,s1:n};return z.runKernel(jc,r)}var Sy=D({broadcastArgs_:_N});function PN(e,t){let a=R(e,"broadcastTo","x"),n=a.shape;if(Ja(t),t.length<a.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${a.rank}.`);if(t.length>a.rank){let l=a.shape.slice();for(;l.length<t.length;)l.unshift(1);a=J(a,l)}let r=a.shape,s=Array.from(t);for(let l=t.length-1;l>=0;l--)if(r[l]===t[l])s[l]=1;else if(a.shape[l]!==1)throw new Error(`broadcastTo(): [${n}] cannot be broadcast to [${t}].`);if(s.map((l,u)=>l>1?u:-1).filter(l=>l>=0).length===0)return wa(a);let i={x:a},o={reps:s};return z.runKernel(ns,i,o)}var sl=D({broadcastTo_:PN});function FN(e){let t={x:R(e,"x","ceil","float32")};return z.runKernel(ai,t)}var Ty=D({ceil_:FN});function nr(e,t,a){Ja(e);let n={shape:e,value:t,dtype:a};return z.runKernel(Fl,{},n)}function ON(e,t,a){let n=R(e,"x","clipByValue");if(P(t<=a,()=>`Error in clip: min (${t}) must be less than or equal to max (${a}).`),t===a)return nr(n.shape,t,n.dtype);let r={x:n},s={clipValueMin:t,clipValueMax:a};return z.runKernel(as,r,s)}var Cy=D({clipByValue_:ON});function DN(e){return at(e,0)}var Ny=D({concat1d_:DN});function zN(e,t){return at(e,t)}var ru=D({concat2d_:zN});function LN(e,t){return at(e,t)}var Ey=D({concat3d_:LN});function BN(e,t){return at(e,t)}var Ry=D({concat4d_:BN});function WN(e,t,a,n,r="NHWC",s=[1,1],i){let o=R(e,"x","conv2d","float32"),l=R(t,"filter","conv2d","float32"),u=o,p=!1;o.rank===3&&(p=!0,u=J(o,[1,o.shape[0],o.shape[1],o.shape[2]])),P(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),P(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),Sn("conv2d",n,i);let c=r==="NHWC"?u.shape[3]:u.shape[1];P(c===l.shape[2],()=>`Error in conv2d: depth of input (${c}) must match input depth for filter ${l.shape[2]}.`),P(kr(a,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${a} and dilations '${s}'`);let d={x:u,filter:l},h={strides:a,pad:n,dataFormat:r,dilations:s,dimRoundingMode:i},f=z.runKernel(ni,d,h);return p?J(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var ep=D({conv2d_:WN});function VN(e,t,a,n,r="NWC",s=1,i){let o=R(e,"x","conv1d"),l=R(t,"filter","conv1d"),u=o,p=!1;o.rank===2&&(p=!0,u=J(o,[1,o.shape[0],o.shape[1]])),P(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),P(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),Sn("conv1d",n,i),P(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),P(kr(a,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${a} and dilation '${s}'`),P(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);let c=J(l,[1,l.shape[0],l.shape[1],l.shape[2]]),d=J(u,[u.shape[0],1,u.shape[1],u.shape[2]]),h=ep(d,c,[1,a],n,"NHWC",[1,s],i);return p?J(h,[h.shape[2],h.shape[3]]):J(h,[h.shape[0],h.shape[2],h.shape[3]])}var My=D({conv1d_:VN});function UN(e,t,a,n,r,s="NHWC",i){P(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let o=e,l=t,u=!1;t.rank===3&&(u=!0,l=J(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),P(o.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`),P(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),P(a.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${a.rank}`);let p=s==="NHWC"?o[3]:o[1],c=s==="NHWC"?l.shape[3]:l.shape[1];P(p===a.shape[2],()=>`Error in conv2dDerInput: depth of input (${p}) must match input depth for filter ${a.shape[2]}.`),P(c===a.shape[3],()=>`Error in conv2dDerInput: depth of output (${c}) must match output depth for filter ${a.shape[3]}.`),Sn("conv2dDerInput",r,i);let d={dy:l,filter:a},h={strides:n,pad:r,dataFormat:s,dimRoundingMode:i,inputShape:o},f=z.runKernel(ri,d,h);return u?J(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var $y=D({conv2DBackpropInput_:UN});function GN(e,t,a,n,r,s){let i=R(e,"x","conv2dTranspose"),o=R(t,"filter","conv2dTranspose");return $y(a,i,o,n,r,"NHWC",s)}var _y=D({conv2dTranspose_:GN});function HN(e,t,a,n,r="NDHWC",s=[1,1,1]){let i=R(e,"x","conv3d"),o=R(t,"filter","conv3d"),l=i,u=!1;i.rank===4&&(u=!0,l=J(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),P(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),P(o.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`),P(l.shape[4]===o.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`),P(kr(a,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${a} and dilations '${s}'`),P(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`);let p={x:l,filter:o},c={strides:a,pad:n,dataFormat:r,dilations:s},d=z.runKernel(Kc,p,c);return u?J(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var Py=D({conv3d_:HN});function jN(e,t,a,n,r){P(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let s=e,i=t,o=!1;t.rank===4&&(o=!0,i=J(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),s=[1,e[0],e[1],e[2],e[3]]);let l=s[4],u=i.shape[4];P(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),P(i.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),P(a.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${a.rank}`),P(l===a.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${a.shape[3]}.`),P(u===a.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${a.shape[4]}.`);let p={dy:i,filter:a},c={pad:r,strides:n,inputShape:s},d=z.runKernel(Zc,p,c);return o?J(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var qN=D({conv3DBackpropInput_:jN});function XN(e,t,a,n,r){let s=R(e,"x","conv3dTranspose"),i=R(t,"filter","conv3dTranspose");return qN(a,s,i,n,r)}var Fy=D({conv3dTranspose_:XN});function KN(e){let t={x:R(e,"x","cos","float32")};return z.runKernel(si,t)}var Oy=D({cos_:KN});function ZN(e){let t={x:R(e,"x","cosh","float32")};return z.runKernel(ii,t)}var Dy=D({cosh_:ZN});function YN(e,t=0,a=!1,n=!1){let r={x:R(e,"x","cumprod")},s={axis:t,exclusive:a,reverse:n};return z.runKernel(oi,r,s)}var zy=D({cumprod_:YN});function JN(e,t=0,a=!1,n=!1){let r={x:R(e,"x","cumsum")},s={axis:t,exclusive:a,reverse:n};return z.runKernel(li,r,s)}var Ly=D({cumsum_:JN});function QN(e,t,a,n=!1){let r=R(e,"x","denseBincount"),s=R(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(a>=0,()=>`size must be non-negative, but got ${a}.`),P(s.size===r.size||s.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${s.shape}.`);let i={x:r,weights:s},o={size:a,binaryOutput:n};return z.runKernel(Td,i,o)}var By=D({denseBincount_:QN});function eE(e,t,a="NHWC"){let n=R(e,"x","depthToSpace","float32"),r=a==="NHWC"?n.shape[1]:n.shape[2],s=a==="NHWC"?n.shape[2]:n.shape[3],i=a==="NHWC"?n.shape[3]:n.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
${n.shape}`),P(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${s} and ${t} for depthToSpace with input shape
${n.shape}`),P(i%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${n.shape}`);let o={x:n},l={blockSize:t,dataFormat:a};return z.runKernel(di,o,l)}var Wy=D({depthToSpace_:eE});function tE(e,t,a,n,r="NHWC",s=[1,1],i){let o=R(e,"x","depthwiseConv2d","float32"),l=R(t,"filter","depthwiseConv2d","float32"),u=o,p=!1;o.rank===3&&(p=!0,u=J(o,[1,o.shape[0],o.shape[1],o.shape[2]])),P(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),P(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`);let c=r==="NHWC"?u.shape[3]:u.shape[1];P(c===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${c}) must match the inChannels dimension in filter ${l.shape[2]}.`),Sn("depthwiseConv2d",n,i);let d={x:u,filter:l},h={strides:a,pad:n,dataFormat:r,dilations:s,dimRoundingMode:i},f=z.runKernel(pi,d,h);return p?J(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var hh=D({depthwiseConv2d_:tE});function aE(e){let t={x:R(e,"x","diag")};return z.runKernel(Qc,t)}var Vy=D({diag_:aE});function nE(e,t,a,n,r=[1,1],s="NHWC"){let i=R(e,"x","dilation2d"),o=R(t,"filter","dilation2d");P(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),P(o.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`),P(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=i,u=!1;i.rank===3&&(l=J(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=!0);let p={x:l,filter:o},c={strides:a,pad:n,dilations:r},d=z.runKernel(eh,p,c);return u?J(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Uy=D({dilation2d_:nE});function rE(e,t){let a=R(e,"a","equal","string_or_numeric"),n=R(t,"b","equal","string_or_numeric");[a,n]=St(a,n),zt(a.shape,n.shape);let r={a,b:n};return z.runKernel(fi,r)}var k2=D({equal_:rE});function sE(e,t,a){let n=R(t,"a","where"),r=R(a,"b","where"),s=R(e,"condition","where","bool"),i=zt(zt(s.shape,n.shape),r.shape),o=sl(s,i),l=sl(n,i),u=sl(r,i),p={condition:o,t:l,e:u};return z.runKernel(Kl,p)}var Vs=D({where_:sE});function iE(e){let t={x:R(e,"x","zerosLike")};return z.runKernel(nu,t)}var Ka=D({zerosLike_:iE});function oE(e,t){let a=R(e,"a","div"),n=R(t,"b","div");[a,n]=St(a,n);let r=me(a,n),s=Ka(r),i=k2(n,s);return Vs(i,s,r)}var Gy=D({divNoNan_:oE});function lE(e,t){let a=R(e,"t1","dot"),n=R(t,"t2","dot");P((a.rank===1||a.rank===2)&&(n.rank===1||n.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${a.rank} and ${n.rank}.`);let r=a.rank===1?a.size:a.shape[1],s=n.rank===1?n.size:n.shape[0];if(P(r===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${s}.`),a.rank===1&&n.rank===1){let i=J(a,[1,-1]),o=J(n,[-1,1]),l=st(i,o);return J(l,[])}else if(a.rank===1&&n.rank===2){let i=J(a,[1,-1]),o=J(n,[n.shape[0],n.shape[1]]),l=st(i,o);return J(l,[l.size])}else if(a.rank===2&&n.rank===1){let i=J(n,[-1,1]),o=st(a,i);return J(o,[o.size])}else{let i=J(n,[n.shape[0],n.shape[1]]);return st(a,i)}}var Hy=D({dot_:lE});function uE(e,...t){let a=t.map((r,s)=>R(r,`tensors${s}`,"einsum")),n={equation:e};return z.runKernel(Cd,a,n)}var jy=D({einsum_:uE});function dE(e){let t={x:R(e,"x","elu","float32")};return z.runKernel(hi,t)}var I2=D({elu_:dE});function pE(e){let t=R(e,"x","erf");P(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=He(t,"float32"));let a={x:t};return z.runKernel($l,a)}var qy=D({erf_:pE});function S2(e,t){for(let a=0;a<e.length;++a)if(e[e.length-a-1]!==t-1-a)return!1;return!0}function Xy(e,t,a){let n=e.length+t.length,r=[],s=0,i=0;for(let o=0;o<n;o++)a.indexOf(o)===-1?r.push(e[s++]):r.push(t[i++]);return r}function cE(e,t){let a=[],n=e.length;for(let s=0;s<n;s++)t.indexOf(s)===-1&&a.push(e[s]);let r=t.map(s=>e[s]);return[a,r]}function tp(e,t){let a=t.map(n=>1);return Xy(e,a,t)}function hE(e,t,a){P(S2(t,a),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${a} input.`)}function fE(e,t){if(S2(e,t))return null;let a=[];for(let n=0;n<t;++n)e.indexOf(n)===-1&&a.push(n);return e.forEach(n=>a.push(n)),a}function mE(e){return e.map((t,a)=>[a,t]).sort((t,a)=>t[1]-a[1]).map(t=>t[0])}function gE(e,t){let a=[];for(let n=t-e;n<t;++n)a.push(n);return a}function xE(e,t=null,a=!1){let n={x:R(e,"x","max")},r={reductionIndices:t,keepDims:a};return z.runKernel(Mi,n,r)}var pa=D({max_:xE});function AE(e,t=null,a=!1){let n={x:R(e,"x","min")},r={axis:t,keepDims:a};return z.runKernel(Fi,n,r)}var Kr=D({min_:AE});function yE(e,t){let a=R(e,"base","pow"),n=R(t,"exp","pow");[a,n]=St(a,n);let r={a,b:n};return z.runKernel(Gi,r)}var pl=D({pow_:yE});function Fe(e,t){if((da(e)&&t!=="string"||Array.isArray(e))&&t!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(t==="string"&&da(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return rs(e,[],[],t)}function bE(e){let t={x:R(e,"x","sqrt","float32")};return z.runKernel(no,t)}var Jn=D({sqrt_:bE});function vE(e){let t=R(e,"x","square"),a={};return z.runKernel("Square",{x:t},a)}var In=D({square_:vE});function wE(e,t=null,a=!1){let n=R(e,"x","sum");n.dtype==="bool"&&(n=He(n,"int32"));let r={x:n},s={axis:t,keepDims:a};return z.runKernel(ro,r,s)}var tt=D({sum_:wE});function kE(e,t="euclidean",a=null,n=!1){e=R(e,"x","norm");let r=Ky(e,t,a),s=r.shape;if(n){let i=wd(a,e.shape);s=tp(r.shape,i)}return J(r,s)}function Ky(e,t,a=null){if(e.rank===0)return qa(e);if(e.rank!==1&&a===null)return Ky(J(e,[-1]),t,a);if(e.rank===1||typeof a=="number"||Array.isArray(a)&&a.length===1){if(t===1)return tt(qa(e),a);if(t===1/0)return pa(qa(e),a);if(t===-1/0)return Kr(qa(e),a);if(t==="euclidean"||t===2)return Jn(tt(pl(qa(e),Fe(2,"int32")),a));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(a)&&a.length===2){if(t===1)return pa(tt(qa(e),a[0]),a[1]-1);if(t===1/0)return pa(tt(qa(e),a[1]),a[0]);if(t===-1/0)return Kr(tt(qa(e),a[1]),a[0]);if(t==="fro"||t==="euclidean")return Jn(tt(In(e),a));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${a}`)}var ap=D({norm_:kE});function IE(e,t=null,a=!1){return ap(e,"euclidean",t,a)}var Zy=D({euclideanNorm_:IE});function SE(e){let t={x:R(e,"x","exp")};return z.runKernel(mi,t)}var Zr=D({exp_:SE});function TE(e,t=0){let a=R(e,"x","expandDims","string_or_numeric");P(t<=a.rank,()=>"Axis must be <= rank of the tensor");let n={input:a},r={dim:t};return z.runKernel(_l,n,r)}var Gt=D({expandDims_:TE});function CE(e){let t={x:R(e,"x","expm1")};return z.runKernel(Pl,t)}var Yy=D({expm1_:CE});function NE(e,t){let a=R(e,"x","tile","string_or_numeric");P(a.rank===t.length,()=>`Error in transpose: rank of input ${a.rank} must match length of reps ${t}.`);let n={x:a},r={reps:t};return z.runKernel(ns,n,r)}var Gr=D({tile_:NE});function EE(e,t,a,n="float32"){t==null&&(t=e);let r=Me([e,t],n),s=e<=t?e:t;for(let o=0;o<s;++o)r.set(1,o,o);let i=J(r.toTensor(),[e,t]);if(a==null)return i;if(a.length===1)return Gr(Gt(i,0),[a[0],1,1]);if(a.length===2)return Gr(Gt(Gt(i,0),0),[a[0],a[1],1,1]);if(a.length===3)return Gr(Gt(Gt(Gt(i,0),0),0),[a[0],a[1],a[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${a.length}D.`)}var T2=D({eye_:EE});function RE(e){let t={x:R(e,"x","floor","float32")};return z.runKernel(xi,t)}var C2=D({floor_:RE});function ME(e,t,a=0,n=0){let r=R(e,"x","gather"),s=R(t,"indices","gather","int32"),i={x:r,indices:s},o={axis:a,batchDims:n};return z.runKernel(Ol,i,o)}var N2=D({gather_:ME});function $E(e,t){let a=R(e,"a","greater","string_or_numeric"),n=R(t,"b","greater","string_or_numeric");[a,n]=St(a,n),zt(a.shape,n.shape);let r={a,b:n};return z.runKernel(vi,r)}var np=D({greater_:$E});function _E(e,t){let a=R(e,"a","greaterEqual","string_or_numeric"),n=R(t,"b","greaterEqual","string_or_numeric");[a,n]=St(a,n),zt(a.shape,n.shape);let r={a,b:n};return z.runKernel(wi,r)}var E2=D({greaterEqual_:_E});function PE(e){let t={x:R(e,"x","isFinite")};return z.runKernel(Dl,t)}var Jy=D({isFinite_:PE});function FE(e){let t={x:R(e,"x","isInf")};return z.runKernel(zl,t)}var Qy=D({isInf_:FE});function OE(e){let t={x:R(e,"x","isNaN")};return z.runKernel(Ii,t)}var eb=D({isNaN_:OE});function DE(e,t=.2){let a={x:R(e,"x","leakyRelu")},n={alpha:t};return z.runKernel(Si,a,n)}var R2=D({leakyRelu_:DE});function zE(e,t){let a=R(e,"a","less","string_or_numeric"),n=R(t,"b","less","string_or_numeric");[a,n]=St(a,n),zt(a.shape,n.shape);let r={a,b:n};return z.runKernel(Ti,r)}var tb=D({less_:zE});function LE(e,t){let a=R(e,"a","lessEqual","string_or_numeric"),n=R(t,"b","lessEqual","string_or_numeric");[a,n]=St(a,n),zt(a.shape,n.shape);let r={a,b:n};return z.runKernel(Ci,r)}var fh=D({lessEqual_:LE});function ab(e,t,a){if(a<=0)throw new Error("The number of values should be positive.");let n={start:e,stop:t,num:a};return z.runKernel(th,{},n)}function BE(e,t=5,a=1,n=1,r=.5){let s=R(e,"x","localResponseNormalization");P(s.rank===4||s.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
rank ${s.rank}.`),P(ol(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=s,o=!1;s.rank===3&&(o=!0,i=J(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:i},u={depthRadius:t,bias:a,alpha:n,beta:r},p=z.runKernel(ah,l,u);return o?J(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var nb=D({localResponseNormalization_:BE});function WE(e){let t={x:R(e,"x","log","float32")};return z.runKernel(Ni,t)}var cl=D({log_:WE});function VE(e){let t={x:R(e,"x","log1p")};return z.runKernel(Ll,t)}var M2=D({log1p_:VE});function UE(e){return P(Hr(e),()=>"The f passed in grad(f) must be a function"),(t,a)=>{let n=R(t,"x","tf.grad","string_or_numeric"),r=a!=null?R(a,"dy","tf.grad"):null;return z.tidy(()=>{let{value:s,grads:i}=z.gradients(()=>e(n),[n],r);return r!=null&&Sa(s.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),mh(i),i[0]})}}function GE(e){return P(Hr(e),()=>"The f passed in grads(f) must be a function"),(t,a)=>{P(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let n=ud(t,"args","tf.grads","string_or_numeric"),r=a!=null?R(a,"dy","tf.grads"):null;return z.tidy(()=>{let{value:s,grads:i}=z.gradients(()=>e(...n),n,r);return r!=null&&Sa(s.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),mh(i),i})}}function HE(e){return P(Hr(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,a)=>{P(t instanceof pt,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),P(a==null||a instanceof pt,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:n,value:r}=z.gradients(()=>e(t),[t],a);return mh(n),{grad:n[0],value:r}}}function jE(e){return P(Hr(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,a)=>{P(Array.isArray(t)&&t.every(r=>r instanceof pt),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),P(a==null||a instanceof pt,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let n=z.gradients(()=>e(...t),t,a);return a!=null&&Sa(n.value.shape,a.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),mh(n.grads),n}}function rb(e,t){P(Hr(e),()=>"The f passed in variableGrads(f) must be a function"),P(t==null||Array.isArray(t)&&t.every(u=>u instanceof od),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let a=t!=null;if(!a){t=[];for(let u in z.registeredVariables)t.push(z.registeredVariables[u])}let n=a?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 s=!0,{value:i,grads:o}=z.gradients(e,t,null,s);P(o.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),P(i.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`);let l={};return t.forEach((u,p)=>{o[p]!=null&&(l[u.name]=o[p])}),n!=null&&n.forEach(u=>l[u.name]=null),{value:i,grads:l}}function Qn(e){return z.customGrad(e)}function mh(e){if(e.filter(t=>t==null).length>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
the f you passed encloses all operations that lead from x to y.`)}function qE(e){let t={x:R(e,"x","softplus")};return z.runKernel(Fd,t)}var $2=D({softplus_:qE});function XE(e){let t=R(e,"x","logSigmoid");return Qn(a=>({value:Xn($2(Xn(a))),gradFunc:n=>ae(n,Da(Xn(a)))}))(t)}var sb=D({logSigmoid_:XE});function KE(e,t){let a=R(e,"a","sub"),n=R(t,"b","sub");[a,n]=St(a,n);let r={a,b:n};return z.runKernel(lo,r)}var fe=D({sub_:KE});function ZE(e,t=-1){let a=R(e,"logits","logSoftmax");if(t===-1&&(t=a.rank-1),t!==a.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${a.rank} and axis was ${t}`);return Qn((n,r)=>{let s=pa(n,t,!0),i=fe(n,s),o=fe(He(i,"float32"),cl(tt(Zr(i),t,!0)));return r([o]),{value:o,gradFunc:(l,u)=>{let[p]=u,c=!0,d=Zr(p);return fe(l,ae(tt(l,t,c),d))}}})(a)}var ib=D({logSoftmax_:ZE});function YE(e,t=null,a=!1){let n=R(e,"x","logSumExp"),r=wd(t,n.shape),s=pa(n,r,!0),i=fe(n,s),o=Zr(i),l=tt(o,r),u=cl(l),p=be(J(s,u.shape),u);if(a){let c=tp(p.shape,r);return J(p,c)}return p}var _2=D({logSumExp_:YE});function JE(e,t){let a=R(e,"a","logicalAnd","bool"),n=R(t,"b","logicalAnd","bool");zt(a.shape,n.shape);let r={a,b:n};return z.runKernel(Ei,r)}var pd=D({logicalAnd_:JE});function QE(e){let t={x:R(e,"x","logicalNot","bool")};return z.runKernel(Ri,t)}var P2=D({logicalNot_:QE});function eR(e,t){let a=R(e,"a","logicalOr","bool"),n=R(t,"b","logicalOr","bool");zt(a.shape,n.shape);let r={a,b:n};return z.runKernel(Bl,r)}var F2=D({logicalOr_:eR});function tR(e,t){let a=R(e,"a","logicalXor","bool"),n=R(t,"b","logicalXor","bool");return zt(a.shape,n.shape),pd(F2(e,t),P2(pd(e,t)))}var ob=D({logicalXor_:tR}),oc=2147483648;function aR(e,t,a="left"){let n=R(e,"sortedSequence","searchSorted"),r=R(t,"values","searchSorted"),s=n.shape[n.shape.length-1],i=r.shape[r.shape.length-1],o=J(n,[-1,s]),l=J(r,[-1,i]);if(o.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(o.shape[0]!==l.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(At(l.shape)>=oc)throw new Error(`values tensor size must less than ${oc}`);if(o.shape[1]>=oc)throw new Error(`trailing dim_size must less than ${oc} for int32 output type, was ${o.shape[1]}`);let u={sortedSequence:o,values:l},p={side:a};return z.runKernel($d,u,p)}var gh=D({searchSorted_:aR});function lb(e,t){return gh(e,t,"left")}function nR(e,t,a,n,r){let s=R(e,"x","maxPool"),i=1,o=s,l=!1;s.rank===3&&(l=!0,o=J(s,[1,s.shape[0],s.shape[1],s.shape[2]])),P(o.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`),P(kr(a,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${i}'`),Sn("maxPool",n,r);let u={x:o},p={filterSize:t,strides:a,pad:n,dimRoundingMode:r},c=z.runKernel(_i,u,p);return l?J(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var O2=D({maxPool_:nR});function rR(e,t=[1,1,1],a,n,r,s="NDHWC"){let i=R(e,"x","maxPool3d"),o=i,l=!1;i.rank===4&&(l=!0,o=J(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),P(o.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`),P(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),Sn("maxPool3d",n,r);let u={x:o},p={filterSize:t,strides:a,pad:n,dimRoundingMode:r,dataFormat:s},c=z.runKernel(nh,u,p);return l?J(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var ub=D({maxPool3d_:rR});function sR(e,t,a,n,r=!1){let s={x:R(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:a,pad:n,includeBatchInIndex:r},o=z.runKernel(rh,s,i);return{result:o[0],indexes:o[1]}}var db=D({maxPoolWithArgmax_:sR});function iR(e,t){let a=R(e,"a","maximum"),n=R(t,"b","maximum");[a,n]=St(a,n),a.dtype==="bool"&&(a=He(a,"int32"),n=He(n,"int32")),zt(a.shape,n.shape);let r={a,b:n};return z.runKernel($i,r)}var D2=D({maximum_:iR});function oR(e,t=null,a=!1){let n={x:R(e,"x","mean")},r={axis:t,keepDims:a};return z.runKernel(Pi,n,r)}var cd=D({mean_:oR});function fn(e,t="float32"){if(Ja(e),t==="complex64"){let n=fn(e,"float32"),r=fn(e,"float32");return br(n,r)}let a=Gc(At(e),t);return z.makeTensor(a,e,t)}function Wr(e,t="float32"){if(Ja(e),t==="complex64"){let n=Wr(e,"float32"),r=fn(e,"float32");return br(n,r)}let a=L1(At(e),t);return z.makeTensor(a,e,t)}function pb(e,t,{indexing:a="xy"}={}){if(a!=="xy"&&a!=="ij")throw new TypeError(`${a} is not a valid third argument to meshgrid`);if(e===void 0)return[];let n=R(e,"x","meshgrid",e instanceof pt?e.dtype:"float32");if(t===void 0)return[n];let r=R(t,"y","meshgrid",t instanceof pt?t.dtype:"float32"),s=At(n.shape),i=At(r.shape);return a==="xy"?(n=J(n,[1,-1]),r=J(r,[-1,1]),[st(Wr([i,1],n.dtype),n),st(r,Wr([1,s],r.dtype))]):(n=J(n,[-1,1]),r=J(r,[1,-1]),[st(n,Wr([1,i],n.dtype)),st(Wr([s,1],r.dtype),r)])}function lR(e,t){let a=R(e,"a","minimum"),n=R(t,"b","minimum");[a,n]=St(a,n),a.dtype==="bool"&&(a=He(a,"int32"),n=He(n,"int32")),zt(a.shape,n.shape);let r={a,b:n};return z.runKernel(Oi,r)}var z2=D({minimum_:lR});function uR(e,t,a){P(a==="reflect"||a==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${a}.`);let n=R(e,"x","mirrorPad");if(n.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");P(t.length===n.rank,()=>`Padding doesn't match input. Must be ${n.rank}. Got ${t.length}.`);let r=a==="reflect"?1:0;for(let o=0;o<n.rank;o++)P(t[o].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),P(t[o][0]>=0&&t[o][0]<=n.shape[o]-r&&t[o][1]>=0&&t[o][1]<=n.shape[o]-r,()=>`Padding in dimension ${o} cannot be greater than or equal to ${n.shape[o]-r} or less than 0 for input of shape ${n.shape}`);let s={paddings:t,mode:a},i={x:n};return z.runKernel(Di,i,s)}var cb=D({mirrorPad_:uR});function dR(e,t){let a=R(e,"a","mod"),n=R(t,"b","mod");[a,n]=St(a,n);let r={a,b:n};return z.runKernel(Wl,r)}var su=D({mod_:dR});function pR(e,t=null,a=!1){e=R(e,"x","moments");let n=wd(t,e.shape),r=cd(e,n,a),s=r.shape;a||(s=tp(r.shape,n));let i=In(fe(He(e,"float32"),J(r,s))),o=cd(i,n,a);return{mean:r,variance:o}}var hb=D({moments_:pR});function cR(e,t,a,n){let r=R(t,"data","multiRNNCell"),s=ud(a,"c","multiRNNCell"),i=ud(n,"h","multiRNNCell"),o=r,l=[];for(let c=0;c<e.length;c++){let d=e[c](o,s[c],i[c]);l.push(d[0]),l.push(d[1]),o=d[1]}let u=[],p=[];for(let c=0;c<l.length;c+=2)u.push(l[c]),p.push(l[c+1]);return[u,p]}var fb=D({multiRNNCell_:cR});function hR(e,t,a,n=!1){let r=R(e,"logits","multinomial"),s=r.size,i=r.rank;if(s<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${s}.`);if(i>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);a=a||Math.random();let o={logits:i===1?J(r,[1,-1]):r},l={numSamples:t,seed:a,normalized:n},u=z.runKernel(sh,o,l);return i===1?J(u,[u.size]):u}var mb=D({multinomial_:hR});function fR(e,t){let a=R(e,"a","notEqual","string_or_numeric"),n=R(t,"b","notEqual","string_or_numeric");[a,n]=St(a,n),zt(a.shape,n.shape);let r={a,b:n};return z.runKernel(Li,r)}var L2=D({notEqual_:fR});function mR(e){let t={x:R(e,"x","onesLike")};return z.runKernel(Gl,t)}var gb=D({onesLike_:mR});function gR(e,t){let a=R(e,"v1","outerProduct"),n=R(t,"v2","outerProduct");P(a.rank===1&&n.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${a.rank} and ${n.rank}.`);let r=J(a,[-1,1]),s=J(n,[1,-1]);return st(r,s)}var xb=D({outerProduct_:gR});function xR(e,t,a=0){let n=R(e,"x","pad");if(n.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let r={paddings:t,constantValue:a},s={x:n};return z.runKernel(Ui,s,r)}var rr=D({pad_:xR});function AR(e,t,a=0){return P(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),rr(e,[t],a)}var Ab=D({pad1d_:AR});function yR(e,t,a=0){return P(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),rr(e,t,a)}var yb=D({pad2d_:yR});function bR(e,t,a=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."),rr(e,t,a)}var bb=D({pad3d_:bR});function vR(e,t,a=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."),rr(e,t,a)}var vb=D({pad4d_:vR});function wR(e,t,a){let n=R(e,"x","spaceToBatchND");P(n.rank>=1+t.length,()=>`input rank ${n.rank} should be > than [blockShape] ${t.length}`),P(a.length===t.length,()=>`paddings.shape[0] ${a.length} must be equal to [blockShape] ${t.length}`),P(n.shape.reduce((i,o,l)=>l>0&&l<=t.length?i&&(o+a[l-1][0]+a[l-1][1])%t[l-1]===0:i,!0),()=>`input spatial dimensions ${n.shape.slice(1)} with paddings ${a.toString()} must be divisible by blockShapes ${t.toString()}`);let r={x:n},s={blockShape:t,paddings:a};return z.runKernel(Jl,r,s)}var B2=D({spaceToBatchND_:wR});function kR(e,t,a,n,r,s,i){r==null&&(r=[1,1]),s==null&&(s=1),n===0&&(n="valid");let o=R(e,"x","maxPool"),l=o,u=!1;o.rank===3&&(u=!0,l=J(o,[1,o.shape[0],o.shape[1],o.shape[2]])),P(kr(s,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`);let p=xy(l.shape,t,s,r,n),c=[p.dilationHeight,p.dilationWidth],d;n==="same"?d=SR([p.filterHeight,p.filterWidth],c):d=[[0,0],[0,0]];let h=c[0]===1&&c[1]===1,[f,m]=IR([p.inHeight,p.inWidth],c,d),g=h?n:"valid",x=h?l:B2(l,c,f),A=(a==="avg"?()=>b2(x,t,s,g,i):()=>O2(x,t,s,g,i))(),y=h?A:v2(A,c,m);return u?J(y,[y.shape[1],y.shape[2],y.shape[3]]):y}function IR(e,t,a){let n=a.map(p=>p[0]),r=a.map(p=>p[1]),s=e.concat(n,r),i=t.map((p,c)=>(p-s[c]%p)%p),o=r.map((p,c)=>p+i[c]),l=t.map((p,c)=>[n[c],o[c]]),u=t.map((p,c)=>[0,i[c]]);return[l,u]}function SR(e,t){let a=e.map((s,i)=>s+(s-1)*(t[i]-1)).map(s=>s-1),n=a.map(s=>Math.floor(s/2)),r=a.map((s,i)=>s-n[i]);return a.map((s,i)=>[n[i],r[i]])}var wb=D({pool_:kR});function TR(e,t){let a=R(e,"x","prelu"),n=R(t,"alpha","prelu"),r={x:a,alpha:n};return z.runKernel(Hi,r)}var W2=D({prelu_:TR});function CR(e,t=null,a=!1){let n=R(e,"x","prod");n.dtype==="bool"&&(n=He(n,"int32"));let r={x:n},s={axis:t,keepDims:a};return z.runKernel(ji,r,s)}var kb=D({prod_:CR});function NR(e,t,a,n){let r=e.map((p,c)=>R(p,`tensors${c}`,"raggedGather","int32")),s=R(t,"paramsDenseValues","raggedGather"),i=R(a,"indices","raggedGather","int32"),o={paramsNestedSplits:r,paramsDenseValues:s,indices:i},l={outputRaggedRank:n},u=z.runKernel(ih,o,l);return{outputNestedSplits:u.slice(0,u.length-1),outputDenseValues:u[u.length-1]}}var Ib=D({raggedGather_:NR});function ER(e,t,a){let n=R(e,"starts","raggedRange"),r=R(t,"limits","raggedRange",n.dtype),s=R(a,"deltas","raggedRange",n.dtype),i={starts:n,limits:r,deltas:s},o=z.runKernel(oh,i);return{rtNestedSplits:o[0],rtDenseValues:o[1]}}var Sb=D({raggedRange_:ER});function RR(e,t,a,n,r){let s=R(e,"shape","raggedTensorToTensor","int32"),i=R(t,"values","raggedTensorToTensor"),o=R(a,"defaultValue","raggedTensorToTensor",i.dtype),l=n.map((c,d)=>R(c,`tensors${d}`,"raggedTensorToTensor","int32")),u={shape:s,values:i,defaultValue:o,rowPartitionTensors:l},p={rowPartitionTypes:r};return z.runKernel(lh,u,p)}var Tb=D({raggedTensorToTensor_:RR});function MR(e,t,a){Ja(e);let n=At(e),r=null;if(a==null||a==="float32")r=new Float32Array(n);else if(a==="int32")r=new Int32Array(n);else if(a==="bool")r=new Uint8Array(n);else throw new Error(`Unknown data type ${a}`);for(let s=0;s<n;s++)r[s]=t();return z.makeTensor(r,e,a)}var Cb=D({rand_:MR}),V2=yl(nA()),U2=class{constructor(e,t,a,n,r){this.mean=e,this.stdDev=t,this.dtype=a,this.nextVal=NaN,this.truncated=n,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);let s=r||Math.random();this.random=V2.alea(s.toString())}nextValue(){if(!isNaN(this.nextVal)){let n=this.nextVal;return this.nextVal=NaN,n}let e,t,a=!1;for(;!a;){let n,r,s;do n=2*this.random()-1,r=2*this.random()-1,s=n*n+r*r;while(s>=1||s===0);let i=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*n*i,t=this.mean+this.stdDev*r*i,(!this.truncated||this.isValidTruncated(e))&&(a=!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}},$R=class{constructor(e,t,a,n){this.alpha=e,this.beta=1/t,this.dtype=a;let r=n||Math.random();this.randu=V2.alea(r.toString()),this.randn=new U2(0,1,a,!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,a,n,r,s;for(;;){do n=this.randn.nextValue(),s=1+this.c*n;while(s<=0);if(s*=s*s,e=n*n,t=1-.331*e*e,a=.5*e+this.d*(1-s+Math.log(s)),r=this.randu(),r<t||Math.log(r)<a)break}return s=1/this.beta*this.d*s,this.alpha<1&&(s*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(s)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}},_R=class{constructor(e=0,t=1,a,n){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=a,n==null&&(n=Math.random()),typeof n=="number"&&(n=n.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=V2.alea(n)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function PR(e,t,a=1,n="float32",r){if(Ja(e),a==null&&(a=1),n==null&&(n="float32"),n!=="float32"&&n!=="int32")throw new Error(`Unsupported data type ${n}`);let s=new $R(t,a,n,r),i=Me(e,n);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var Nb=D({randomGamma_:PR});function FR(e,t=0,a=1,n,r){if(Ja(e),n!=null&&n==="bool")throw new Error(`Unsupported data type ${n}`);let s=new U2(t,a,n,!1,r),i=Me(e,n);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var G2=D({randomNormal_:FR});function OR(e,t,a){if(t!=null&&t==="bool")throw new Error(`Unsupported data type ${t}`);return G2(e,0,1,t,a)}var Eb=D({randomStandardNormal_:OR});function DR(e,t=0,a=1,n="float32",r){Ja(e);let s=Me(e,n),i=new _R(t,a,null,r);for(let o=0;o<s.values.length;o++)s.values[o]=i.nextValue();return s.toTensor()}var H2=D({randomUniform_:DR});function hl(e,t,a=1,n="float32"){if(a===0)throw new Error("Cannot have a step of zero");let r={start:e,stop:t,step:a,dtype:n};return z.runKernel(jl,{},r)}function zR(e){let t={x:R(e,"x","reciprocal")};return z.runKernel(qi,t)}var Rb=D({reciprocal_:zR});function LR(e){let t={x:R(e,"x","relu")};return z.runKernel(Xi,t)}var rp=D({relu_:LR});function BR(e){let t={x:R(e,"x","relu6")};return z.runKernel(Yi,t)}var j2=D({relu6_:BR});function WR(e,t){let a={x:R(e,"x","reverse")},n={dims:t};return z.runKernel(Ji,a,n)}var Yr=D({reverse_:WR});function VR(e){let t=R(e,"x","reverse");return P(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Yr(t,0)}var Mb=D({reverse1d_:VR});function UR(e,t){let a=R(e,"x","reverse");return P(a.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${a.rank}.`),Yr(a,t)}var $b=D({reverse2d_:UR});function GR(e,t){let a=R(e,"x","reverse");return P(a.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${a.rank}.`),Yr(a,t)}var _b=D({reverse3d_:GR});function HR(e,t){let a=R(e,"x","reverse");return P(a.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${a.rank}.`),Yr(a,t)}var Pb=D({reverse4d_:HR});function jR(e){let t={x:R(e,"x","round")};return z.runKernel(Xl,t)}var q2=D({round_:jR});function qR(e){let t={x:R(e,"x","rsqrt","float32")};return z.runKernel(Qi,t)}var Fb=D({rsqrt_:qR});function XR(e){let t={x:R(e,"x","selu")};return z.runKernel(_d,t)}var Ob=D({selu_:XR});function KR(e,t,a,n,r,s=[1,1],i="NHWC"){let o=R(e,"x","separableConv2d"),l=R(t,"depthwiseFilter","separableConv2d"),u=R(a,"pointwiseFilter","separableConv2d"),p=o,c=!1;if(o.rank===3&&(c=!0,p=J(o,[1,o.shape[0],o.shape[1],o.shape[2]])),i==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");P(p.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${p.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=hh(p,l,n,r,i,s),m=ep(f,u,1,"valid",i);return c?J(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Db=D({separableConv2d_:KR});async function ZR(e,t){let a=R(e,"x","setdiff1d"),n=R(t,"y","setdiff1d");P(a.dtype===n.dtype,()=>`x and y should have the same dtype, but got x (${a.dtype}) and y (${n.dtype}).`),P(a.rank===1,()=>`x should be 1D tensor, but got x (${a.shape}).`),P(n.rank===1,()=>`y should be 1D tensor, but got y (${n.shape}).`);let r=await a.data(),s=await n.data(),i=new Set(s),o=0;for(let p=0;p<r.length;p++)i.has(r[p])||o++;let l=new jt([o],a.dtype),u=new jt([o],"int32");for(let p=0,c=0;p<r.length;p++)i.has(r[p])||(l.values[c]=r[p],u.values[c]=p,c++);return[l.toTensor(),u.toTensor()]}var zb=ZR;function YR(e){let t={x:R(e,"x","sign")};return z.runKernel(Pd,t)}var Lb=D({sign_:YR});function JR(e){let t={x:R(e,"x","sin","float32")};return z.runKernel(to,t)}var Bb=D({sin_:JR});function QR(e){let t={x:R(e,"x","sinh")};return z.runKernel(Yl,t)}var Wb=D({sinh_:QR});function eM(e,t,a){let n=R(e,"x","slice1d");return P(n.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${n.rank} tensor`),Pe(n,[t],[a])}var Vb=D({slice1d_:eM});function tM(e,t,a){let n=R(e,"x","slice2d");return P(n.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${n.rank} tensor`),Pe(n,t,a)}var Ub=D({slice2d_:tM});function aM(e,t,a){let n=R(e,"x","slice3d");return P(n.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${n.rank} tensor`),Pe(n,t,a)}var sp=D({slice3d_:aM});function nM(e,t,a){let n=R(e,"x","slice4d");return P(n.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${n.rank} tensor`),Pe(n,t,a)}var xh=D({slice4d_:nM});function rM(e,t=-1){let a=R(e,"logits","softmax","float32");if(t===-1&&(t=a.rank-1),t!==a.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${a.rank} and dim was ${t}`);let n={logits:a},r={dim:t};return z.runKernel(so,n,r)}var Ah=D({softmax_:rM});function sM(e){P(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return z.runKernel(Nd,t)}var yh=D({fft_:sM});function iM(e){P(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return z.runKernel(Ed,t)}var hd=D({ifft_:iM});function oM(e){let t=e.shape[e.shape.length-1],a=e.size/t,n;if(t<=2){let r=J(e,[a,t]);n=hd(r)}else{let r=[a,2*(t-1)],s=J(dl(e),[a,t]),i=J(Zd(e),[a,t]),o=Yr(Pe(s,[0,1],[a,t-2]),1),l=ae(Yr(Pe(i,[0,1],[a,t-2]),1),Fe(-1)),u=at([s,o],1),p=at([i,l],1),c=J(br(u,p),[r[0],r[1]]);n=hd(c)}if(n=dl(n),e.rank===3&&e.shape[0]!==0){let r=n,s=e.shape[0];n=J(n,[s,n.shape[0]/s,n.shape[1]]),r.dispose()}return n}var X2=D({irfft_:oM});function lM(e,t,a=0){let n={x:R(e,"x","split")},r={numOrSizeSplits:t,axis:a};return z.runKernel(Ql,n,r)}var ka=D({split_:lM});function uM(e,t){P(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let a=e.shape[e.shape.length-1],n=e.size/a,r;if(t!=null&&t<a){let f=e.shape.map(g=>0),m=e.shape.map(g=>g);m[e.shape.length-1]=t,r=Pe(e,f,m),a=t}else if(t!=null&&t>a){let f=e.shape.map(m=>m);f[e.shape.length-1]=t-a,r=at([e,fn(f)],e.shape.length-1),a=t}else r=e;let s=Ka(r),i=J(br(r,s),[n,a]),o=yh(i),l=Math.floor(a/2)+1,u=dl(o),p=Zd(o),c=ka(u,[l,a-l],u.shape.length-1),d=ka(p,[l,a-l],p.shape.length-1),h=r.shape.slice();return h[r.shape.length-1]=l,J(br(c[0],d[0]),h)}var bh=D({rfft_:uM});function dM(e,t){let a=R(e,"a","squaredDifference"),n=R(t,"b","squaredDifference");[a,n]=St(a,n),zt(a.shape,n.shape);let r={a,b:n},s={};return z.runKernel(io,r,s)}var K2=D({squaredDifference_:dM});function pM(e,t){let a=R(e,"x","squeeze","string_or_numeric");return J(a,iA(a.shape,t).newShape)}var _e=D({squeeze_:pM});function cM(e,t=0){let a=ud(e,"tensors","stack","string_or_numeric");P(a.length>=1,()=>"Pass at least one tensor to tf.stack"),a.length>0&&P(t<=a[0].rank,()=>"Axis must be <= rank of the tensor");let n=a,r={axis:t};return z.runKernel(Hl,n,r)}var sa=D({stack_:cM});function hM(e,t=0){let a={x:R(e,"x","step")},n={alpha:t};return z.runKernel(fo,a,n)}var Z2=D({step_:hM});function fM(e,t,a,n,r=0,s=0,i=0,o=0,l=0){let u={x:R(e,"x","stridedSlice","string_or_numeric")},p={begin:t,end:a,strides:n,beginMask:r,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return z.runKernel(oo,u,p)}var Gb=D({stridedSlice_:fM});function mM(e){let t={x:R(e,"x","tan","float32")};return z.runKernel(uo,t)}var Hb=D({tan_:mM});function Ht(e,t){Xs(e);let a=Yn(e,t);if(a.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return rs(e,null,a,t)}function Kn(e,t,a){if(Xs(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let n=Yn(e,a);if(n.length!==2&&n.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return rs(e,t,n,a)}function jb(e,t,a){if(Xs(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let n=Yn(e,a);if(n.length!==4&&n.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return rs(e,t,n,a)}function qb(e,t,a){if(Xs(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let n=Yn(e,a);if(n.length!==5&&n.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return rs(e,t,n,a)}function Xb(e,t,a){if(Xs(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let n=Yn(e,a);if(n.length!==6&&n.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||n,rs(e,t,n,a)}function gM(e,t=1,a=!0){let n=R(e,"x","topk");if(n.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let r=n.shape[n.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 s={x:n},i={k:t,sorted:a},[o,l]=z.runKernel(co,s,i);return{values:o,indices:l}}var Kb=D({topk_:gM});function xM(e,t=0,a=1,n,r){if(Ja(e),n!=null&&n==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new U2(t,a,n,!0,r),i=Me(e,n);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var Zb=D({truncatedNormal_:xM});function AM(e,t=0){let a=R(e,"x","unique","string_or_numeric");P(a.rank>0,()=>"The input tensor must be at least 1D");let n={x:a},r={axis:t},[s,i]=z.runKernel(uh,n,r);return{values:s,indices:i}}var Yb=D({unique_:AM});function yM(e,t,a){let n=R(e,"x","unsortedSegmentSum"),r=R(t,"segmentIds","unsortedSegmentSum","int32");P(ol(a),()=>"numSegments must be of dtype int");let s={x:n,segmentIds:r},i={numSegments:a};return z.runKernel(dh,s,i)}var Jb=D({unsortedSegmentSum_:yM});function bM(e,t=0){let a=R(e,"x","unstack","string_or_numeric");P(t>=-a.shape.length&&t<a.shape.length,()=>`Axis = ${t} is not in [-${a.shape.length}, ${a.shape.length})`);let n={value:a},r={axis:t};return z.runKernel(au,n,r)}var Ta=D({unstack_:bM});function Qb(e,t){return gh(e,t,"right")}function e4(e,t=!0,a,n){return z.makeVariable(e,t,a,n)}function t4(e,t){let a=[];for(let s=0;s<t.length;s++)t[s]&&a.push(s);let n=Me(e,"int32"),r=Me([a.length,e.length],"int32");for(let s=0;s<a.length;s++){let i=n.indexToLoc(a[s]),o=s*e.length;r.values.set(i,o)}return r.toTensor()}async function vM(e){let t=R(e,"condition","whereAsync","bool"),a=await t.data(),n=t4(t.shape,a);return e!==t&&t.dispose(),n}var Y2=vM;async function wM(e,t,a){let n=R(e,"tensor","boolMask"),r=R(t,"mask","boolMask","bool"),s=a==null?0:a,i=r.rank,o=n.shape;P(i>0,()=>"mask cannot be scalar"),Sa(o.slice(s,s+i),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let m=s;m<s+i;m++)l*=o[m];let u=o.slice(0,s).concat([l],o.slice(s+i)),p=J(n,u),c=J(r,[-1]),d=await Y2(c),h=_e(d,[1]),f=N2(p,h,s);return e!==n&&n.dispose(),t!==r&&r.dispose(),h.dispose(),p.dispose(),c.dispose(),d.dispose(),f}var a4=wM;function kM(e,t,a,n,r=!0){let s=R(e,"v","movingAverage"),i=R(t,"x","movingAverage"),o=R(a,"decay","movingAverage");wA(s,i),P(es(s.shape,i.shape),()=>"Shape mismatch in v and x");let l=Fe(1),u=fe(l,o),p=ae(fe(i,s),u);if(r){P(n!=null,()=>"When using zeroDebias: true, step is required.");let c=R(n,"step","movingAverage");p=me(p,fe(l,pl(o,c)))}return be(s,p)}var n4=D({movingAverage_:kM});function IM(e,t,a){Ja(a);let n=R(e,"indices","scatterND","int32"),r=R(t,"updates","scatterND");m2(r,n,a);let s={indices:n,updates:r},i={shape:a};return z.runKernel(eo,s,i)}var r4=D({scatterND_:IM});function SM(e,t,a,n){if(e.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);let r=e.rank>0?e.shape[0]:1,s=e.rank>1?e.shape[1]:1;if(a.length!==s)throw new Error(`outputShape has incorrect number of elements:, ${a.length}, should be: ${s}.`);let i=t.size;if(!(t.rank===0||t.rank===1&&i===r))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${r}]`);if(t.dtype!==n.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function TM(e,t,a,n=0){Ja(a);let r=R(e,"sparseIndices","sparseToDense","int32"),s=R(t,"sparseValues","sparseToDense","string_or_numeric"),i=R(n,"defaultValue","sparseToDense",s.dtype);SM(r,s,a,i);let o={sparseIndices:r,sparseValues:s,defaultValue:i},l={outputShape:a};return z.runKernel(Ld,o,l)}var s4=D({sparseToDense_:TM});function CM(e,t){let a=R(t,"indices","gatherND","int32"),n={params:R(e,"x","gatherND","string_or_numeric"),indices:a};return z.runKernel(bi,n)}var i4=D({gatherND_:CM});function NM(e,t){if(t==null)return e.shape.slice();if(es(e.shape,t))return t;if(e.shape.length===t.length){let a=[];for(let n=0;n<e.shape.length;n++)t[n]==null&&e.shape[n]!=null?a.push(e.shape[n]):a.push(t[n]);return a}return t}function EM(e,t,a,n){let r=R(e,"x","dropout");if(P(r.dtype==="float32",()=>`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 pt?r.clone():r;let s=NM(r,a),i=1-t,o=me(C2(be(H2(s,0,1,"float32",n),i)),i);return ae(r,o)}var o4=D({dropout_:EM});function J2(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function vh(e,t,a){let n=1-e%2,r=new Float32Array(e);for(let s=0;s<e;++s){let i=2*Math.PI*s/(e+n-1);r[s]=t-a*Math.cos(i)}return Ht(r,"float32")}async function RM(e,t,a=1){let n=R(e,"predictions","inTopK"),r=R(t,"targets","inTopK");P(n.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${n.rank}`),P(n.rank-1===r.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${n.rank} and targets rank ${r.rank}`),Sa(n.shape.slice(0,n.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let s=n.shape[n.shape.length-1];P(a>0&&a<=s,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${a}`);let i=await n.data(),o=await r.data(),[l,u]=[i.length/s,s],p=oA("bool",l);for(let c=0;c<l;c++){let d=c*u,h=i.subarray(d,d+u),f=[];for(let m=0;m<h.length;m++)f.push({value:h[m],index:m});f.sort((m,g)=>g.value-m.value),p[c]=0;for(let m=0;m<a;m++)if(f[m].index===o[c]){p[c]=1;break}}return e!==n&&n.dispose(),t!==r&&r.dispose(),Be(p,r.shape,"bool")}var l4=RM,Q2={};Xe(Q2,{conv2d:()=>PM,depthwiseConv2d:()=>BM,matMul:()=>VM});function MM(e,t,a,n,r,s="NHWC",i){let o=e;e.rank===3&&(o=J(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=J(t,[1,t.shape[0],t.shape[1],t.shape[2]])),P(o.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`),P(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),P(a.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${a}.`);let u=s==="NHWC"?o.shape[3]:o.shape[1],p=s==="NHWC"?l.shape[3]:l.shape[1];P(u===a[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${a[2]}.`),P(p===a[3],()=>`Error in conv2dDerFilter: depth of dy (${p}) must match output depth for filter (${a[3]}).`),Sn("conv2dDerFilter",r,i);let c={x:o,dy:l},d={strides:n,pad:r,dataFormat:s,dimRoundingMode:i,filterShape:a};return z.runKernel(Xc,c,d)}var $M=D({conv2DBackpropFilter_:MM});function wh(e,t,a){if(a==null||a==="linear")return e;if(a==="relu")return ae(e,Z2(t));throw new Error(`Cannot compute gradient for fused activation ${a}.`)}function kh(e,t){let a=t,n=d2(e.shape,t.shape);return n.length>0&&(a=tt(a,n)),J(a,e.shape)}function Ih(e,t,a,n){if(t==="linear")return e;if(t==="relu")return rp(e);if(t==="elu")return I2(e);if(t==="relu6")return j2(e);if(t==="prelu")return W2(e,a);if(t==="leakyrelu")return R2(e,n);if(t==="sigmoid")return Da(e);throw new Error(`Unknown fused activation ${t}.`)}var Sh=(e,t)=>!(e>0)||t==="linear";function _M({x:e,filter:t,strides:a,pad:n,dataFormat:r="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:p}){if(l=l||"linear",Sh(z.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 S=ep(e,t,a,n,r,s,i);return o!=null&&(S=be(S,o)),Ih(S,l,u,p)}let c=R(e,"x","conv2d","float32"),d=R(t,"filter","conv2d","float32"),h=c,f=!1;c.rank===3&&(f=!0,h=J(c,[1,c.shape[0],c.shape[1],c.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}.`),Sn("fused conv2d",n,i);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(kr(a,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${a} and dilations '${s}'`);let g=Jd(h.shape,d.shape,a,s,n,i),x;o!=null&&(x=R(o,"bias","fused conv2d"),[x]=St(x,c),r==="NHWC"?zt(g.outShape,x.shape):(P(x.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${x.shape.length}.`),P(x.shape.length===0||x.shape[0]===g.outChannels||x.shape[0]===1,()=>`Error in fused conv2d: bias shape (${x.shape}) is not compatible with the number of output channels (${g.outChannels})`)));let A;if(u!=null){let S=u.shape;if(P(S.length<=1||S.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-${S.length}.`),S.length===1)P(S[0]===1||S[0]===g.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${S}) is not compatible with the number of output channels (${g.outChannels}).`);else if(S.length===3)try{zt(S,g.outShape)}catch(C){let E=`Error in fused conv2d: PReLU activation weights (${S}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(E)}A=R(u,"prelu weights","fused conv2d")}let y=(S,C)=>{P(r==="NHWC",()=>`Error in gradient of fused conv2D: got dataFormat of ${r} but only NHWC is currently supported.`);let[E,_,$,M]=C,I=wh(S,$,l);P(dd(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let N=$y(_.shape,I,E,a,n),O=$M(_,I,E.shape,a,n),L=[N,O];if(M!=null){let B=kh(M,I);L.push(B)}return L},b={x:h,filter:d,bias:x,preluActivationWeights:A},w={strides:a,pad:n,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:p};return o==null?Qn((S,C,E)=>{let _=z.runKernel(qr,b,w);return E([C,S,_]),f&&(_=J(_,[_.shape[1],_.shape[2],_.shape[3]])),{value:_,gradFunc:y}})(h,d):Qn((S,C,E,_)=>{let $=z.runKernel(qr,b,w);return _([C,S,$,E]),f&&($=J($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:y}})(h,d,x)}var PM=D({fusedConv2d_:_M});function FM(e,t,a,n,r,s=[1,1],i){let o=e;e.rank===3&&(o=J(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=J(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={x:o,dy:l},p={strides:n,pad:r,dimRoundingMode:i,dilations:s,filterShape:a};return z.runKernel(Yc,u,p)}var OM=D({depthwiseConv2dNativeBackpropFilter_:FM});function DM(e,t,a,n,r,s=[1,1],i){let o=t,l=!1;t.rank===3&&(l=!0,o=J(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={dy:o,filter:a},p={strides:n,pad:r,dimRoundingMode:i,dilations:s,inputShape:e},c=z.runKernel(Jc,u,p);return l?J(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var zM=D({depthwiseConv2dNativeBackpropInput_:DM});function LM({x:e,filter:t,strides:a,pad:n,dataFormat:r="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:p}){if(Sh(z.state.gradientDepth,l)===!1){let w=hh(e,t,a,n,r,s,i);return o!=null&&(w=be(w,o)),Ih(w,l,u,p)}let c=R(e,"x","depthwiseConv2d","float32"),d=R(t,"filter","depthwiseConv2d","float32"),h=c,f=!1;c.rank===3&&(f=!0,h=J(c,[1,c.shape[0],c.shape[1],c.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]}.`),s==null&&(s=[1,1]),P(kr(a,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${s}'`),Sn("fused depthwiseConv2d",n,i);let m=Jd(h.shape,d.shape,a,s,n,i,!0),g;o!=null&&(g=R(o,"bias","fused conv2d"),[g]=St(g,c),zt(m.outShape,g.shape));let x;u!=null&&(x=R(u,"prelu weights","fused depthwiseConv2d"));let A=(w,S)=>{P(dd(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[C,E,_,$]=S,M=wh(w,_,l),I=zM(E.shape,M,C,a,n,s,i),N=OM(E,M,C.shape,a,n,s,i);if($!=null){let O=kh(g,M);return[I,N,O]}return[I,N]},y={x:h,filter:d,bias:g,preluActivationWeights:x},b={strides:a,pad:n,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:p};return o==null?Qn((w,S,C)=>{let E=z.runKernel(Xr,y,b);return C([S,w,E]),f&&(E=J(E,[E.shape[1],E.shape[2],E.shape[3]])),{value:E,gradFunc:A}})(h,d):Qn((w,S,C,E)=>{let _=z.runKernel(Xr,y,b);return E([S,w,_,C]),f&&(_=J(_,[_.shape[1],_.shape[2],_.shape[3]])),{value:_,gradFunc:A}})(h,d,g)}var BM=D({fusedDepthwiseConv2d_:LM});function WM({a:e,b:t,transposeA:a=!1,transposeB:n=!1,bias:r,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:o=.2}){if(Sh(z.state.gradientDepth,s)===!1){let $=st(e,t,a,n);return r!=null&&($=be($,r)),Ih($,s,i,o)}let l=R(e,"a","fused matMul"),u=R(t,"b","fused matMul");[l,u]=St(l,u);let p=a?l.shape[l.rank-2]:l.shape[l.rank-1],c=n?u.shape[u.rank-1]:u.shape[u.rank-2],d=a?l.shape[l.rank-1]:l.shape[l.rank-2],h=n?u.shape[u.rank-2]:u.shape[u.rank-1],f=l.shape.slice(0,-2),m=u.shape.slice(0,-2),g=At(f),x=At(m);P(p===c,()=>`Error in fused matMul: inner shapes (${p}) and (${c}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${a} and transposeB=${n} must match.`);let A=zt(l.shape.slice(0,-2),u.shape.slice(0,-2)).concat([d,h]),y=a?J(l,[g,p,d]):J(l,[g,d,p]),b=n?J(u,[x,h,c]):J(u,[x,c,h]),w;r!=null&&(w=R(r,"bias","fused matMul"),[w]=St(w,l),zt(A,w.shape));let S;i!=null&&(S=R(i,"prelu weights","fused matMul"));let C=($,M)=>{let[I,N,O,L]=M,B=wh(J($,O.shape),O,s),G,j;if(!a&&!n?(G=st(B,N,!1,!0),j=st(I,B,!0,!1)):!a&&n?(G=st(B,N,!1,!1),j=st(B,I,!0,!1)):a&&!n?(G=st(N,B,!1,!0),j=st(I,B,!1,!1)):(G=st(N,B,!0,!0),j=st(B,I,!0,!0)),r!=null){let U=kh(L,B);return[G,j,U]}else return[G,j]},E={a:y,b,bias:w,preluActivationWeights:S},_={transposeA:a,transposeB:n,activation:s,leakyreluAlpha:o};return r==null?Qn(($,M,I)=>{let N=z.runKernel(jr,E,_);return I([$,M,N]),{value:J(N,A),gradFunc:C}})(y,b):Qn(($,M,I,N)=>{let O=z.runKernel(jr,E,_);return N([$,M,O,I]),{value:J(O,A),gradFunc:C}})(y,b,w)}var VM=D({fusedMatMul_:WM});function UM(e){return vh(e,.54,.46)}var GM=D({hammingWindow_:UM});function HM(e){return vh(e,.5,.5)}var u4=D({hannWindow_:HM});function jM(e,t,a,n=!1,r=0){let s=0,i=[];for(;s+t<=e.size;)i.push(Pe(e,s,t)),s+=a;if(n)for(;s<e.size;){let o=s+t-e.size,l=at([Pe(e,s,t-o),nr([o],r)]);i.push(l),s+=a}return i.length===0?Kn([],[0,t]):J(at(i),[i.length,t])}var d4=D({frame_:jM});function qM(e,t,a,n,r=u4){n==null&&(n=J2(t));let s=d4(e,t,a),i=ae(s,r(t));return bh(i,n)}var XM=D({stft_:qM});function KM(e,t,a,n,r="bilinear",s=0){let i=R(e,"image","cropAndResize"),o=R(t,"boxes","cropAndResize","float32"),l=R(a,"boxInd","cropAndResize","int32"),u=o.shape[0];P(i.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),P(o.rank===2&&o.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${o.shape}.`),P(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${o.shape}.`),P(n.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${n.length}.`),P(n[0]>=1&&n[1]>=1,()=>`cropSize must be atleast [1,1], but was ${n}`),P(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);let p={image:i,boxes:o,boxInd:l},c={method:r,extrapolationValue:s,cropSize:n};return z.runKernel(ui,p,c)}var ZM=D({cropAndResize_:KM});function YM(e){let t=R(e,"image","flipLeftRight","float32");P(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let a={image:t};return z.runKernel(gi,a,{})}var JM=D({flipLeftRight_:YM});function QM(e){let t=R(e,"image","grayscaleToRGB"),a=t.rank-1,n=t.shape[a];P(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),P(n===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${n}.`);let r=new Array(t.rank);return r.fill(1,0,a),r[a]=3,Gr(t,r)}var e$=D({grayscaleToRGB_:QM});function t$(e,t,a=0,n=.5){let r=R(e,"image","rotateWithOffset","float32");P(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);let s={image:r},i={radians:t,fillValue:a,center:n};return z.runKernel(mo,s,i)}var a$=D({rotateWithOffset_:t$});function iu(e,t,a,n,r,s){n==null&&(n=.5),r==null&&(r=Number.NEGATIVE_INFINITY),s==null&&(s=0);let i=e.shape[0];return a=Math.min(a,i),P(0<=n&&n<=1,()=>`iouThreshold must be in [0, 1], but was '${n}'`),P(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),P(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),P(t.rank===1,()=>"scores must be a 1D tensor"),P(t.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`),P(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:a,iouThreshold:n,scoreThreshold:r,softNmsSigma:s}}function n$(e,t,a,n=.5,r=Number.NEGATIVE_INFINITY){let s=R(e,"boxes","nonMaxSuppression","float32"),i=R(t,"scores","nonMaxSuppression","float32"),o=iu(s,i,a,n,r);a=o.maxOutputSize,n=o.iouThreshold,r=o.scoreThreshold;let l={maxOutputSize:a,iouThreshold:n,scoreThreshold:r};return z.runKernel(Bi,{boxes:s,scores:i},l)}var r$=D({nonMaxSuppression_:n$});function s$(e,t,a){let n=i$(e,t,a),r=n<0?-(n+1):n;e.splice(r,0,t)}function i$(e,t,a){return l$(e,t,a||o$)}function o$(e,t){return e>t?1:e<t?-1:0}function l$(e,t,a){let n=0,r=e.length,s=0,i=!1;for(;n<r;){s=n+(r-n>>>1);let o=a(t,e[s]);o>0?n=s+1:(r=s,i=!o)}return i?n:-n-1}function p4(e,t,a,n,r){return e3(e,t,a,n,r,0)}function c4(e,t,a,n,r,s){return e3(e,t,a,n,r,0,!1,s,!0)}function h4(e,t,a,n,r,s){return e3(e,t,a,n,r,s,!0)}function e3(e,t,a,n,r,s,i=!1,o=!1,l=!1){let u=[];for(let g=0;g<t.length;g++)t[g]>r&&u.push({score:t[g],boxIndex:g,suppressBeginIndex:0});u.sort(X5);let p=s>0?-.5/s:0,c=[],d=[];for(;c.length<a&&u.length>0;){let g=u.pop(),{score:x,boxIndex:A,suppressBeginIndex:y}=g;if(x<r)break;let b=!1;for(let w=c.length-1;w>=y;--w){let S=u$(e,A,c[w]);if(S>=n){b=!0;break}if(g.score=g.score*d$(n,p,S),g.score<=r)break}g.suppressBeginIndex=c.length,b||(g.score===x?(c.push(A),d.push(g.score)):g.score>r&&s$(u,g,X5))}let h=c.length,f=a-h;o&&f>0&&(c.push(...new Array(f).fill(0)),d.push(...new Array(f).fill(0)));let m={selectedIndices:c};return i&&(m.selectedScores=d),l&&(m.validOutputs=h),m}function u$(e,t,a){let n=e.subarray(t*4,t*4+4),r=e.subarray(a*4,a*4+4),s=Math.min(n[0],n[2]),i=Math.min(n[1],n[3]),o=Math.max(n[0],n[2]),l=Math.max(n[1],n[3]),u=Math.min(r[0],r[2]),p=Math.min(r[1],r[3]),c=Math.max(r[0],r[2]),d=Math.max(r[1],r[3]),h=(o-s)*(l-i),f=(c-u)*(d-p);if(h<=0||f<=0)return 0;let m=Math.max(s,u),g=Math.max(i,p),x=Math.min(o,c),A=Math.min(l,d),y=Math.max(x-m,0)*Math.max(A-g,0);return y/(h+f-y)}function d$(e,t,a){let n=Math.exp(t*a*a);return a<=e?n:0}function X5(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function p$(e,t,a,n=.5,r=Number.NEGATIVE_INFINITY){let s=R(e,"boxes","nonMaxSuppressionAsync"),i=R(t,"scores","nonMaxSuppressionAsync"),o=iu(s,i,a,n,r);a=o.maxOutputSize,n=o.iouThreshold,r=o.scoreThreshold;let l=await Promise.all([s.data(),i.data()]),u=l[0],p=l[1],{selectedIndices:c}=p4(u,p,a,n,r);return s!==e&&s.dispose(),i!==t&&i.dispose(),Ht(c,"int32")}var c$=p$;function h$(e,t,a,n=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=R(e,"boxes","nonMaxSuppression"),o=R(t,"scores","nonMaxSuppression"),l=iu(i,o,a,n,r,s);a=l.maxOutputSize,n=l.iouThreshold,r=l.scoreThreshold,s=l.softNmsSigma;let u={boxes:i,scores:o},p={maxOutputSize:a,iouThreshold:n,scoreThreshold:r,softNmsSigma:s},c=z.runKernel(Wi,u,p);return{selectedIndices:c[0],selectedScores:c[1]}}var f$=D({nonMaxSuppressionWithScore_:h$});async function m$(e,t,a,n=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=R(e,"boxes","nonMaxSuppressionAsync"),o=R(t,"scores","nonMaxSuppressionAsync"),l=iu(i,o,a,n,r,s);a=l.maxOutputSize,n=l.iouThreshold,r=l.scoreThreshold,s=l.softNmsSigma;let u=await Promise.all([i.data(),o.data()]),p=u[0],c=u[1],{selectedIndices:d,selectedScores:h}=h4(p,c,a,n,r,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:Ht(d,"int32"),selectedScores:Ht(h)}}var g$=m$;function x$(e,t,a,n=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=R(e,"boxes","nonMaxSuppression"),o=R(t,"scores","nonMaxSuppression"),l=iu(i,o,a,n,r,null),u=l.maxOutputSize,p=l.iouThreshold,c=l.scoreThreshold,d={boxes:i,scores:o},h={maxOutputSize:u,iouThreshold:p,scoreThreshold:c,padToMaxOutputSize:s},f=z.runKernel(Ul,d,h);return{selectedIndices:f[0],validOutputs:f[1]}}var A$=D({nonMaxSuppressionPadded_:x$});async function y$(e,t,a,n=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=R(e,"boxes","nonMaxSuppressionAsync"),o=R(t,"scores","nonMaxSuppressionAsync"),l=iu(i,o,a,n,r,null),u=l.maxOutputSize,p=l.iouThreshold,c=l.scoreThreshold,[d,h]=await Promise.all([i.data(),o.data()]),{selectedIndices:f,validOutputs:m}=c4(d,h,u,p,c,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:Ht(f,"int32"),validOutputs:Fe(m,"int32")}}var b$=y$;function v$(e,t,a=!1,n=!1){let r=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(n===!1||a===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=r,i=!1;r.rank===3&&(i=!0,s=J(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:a,halfPixelCenters:n,size:t},u=z.runKernel(Zi,o,l);return i?J(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var w$=D({resizeBilinear_:v$});function k$(e,t,a=!1,n=!1){let r=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(n===!1||a===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=r,i=!1;r.rank===3&&(i=!0,s=J(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:a,halfPixelCenters:n,size:t},u=z.runKernel(Ki,o,l);return i?J(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var I$=D({resizeNearestNeighbor_:k$});function S$(e,t="binary",a=!1,n=.5){let r=R(e,"image","threshold"),s=.2989,i=.587,o=.114,l=r.shape[0]*r.shape[1],u=ae(Ht([n]),255),p,c,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){[p,c,d]=ka(r,[1,1,1],-1);let m=ae(p,s),g=ae(c,i),x=ae(d,o);h=be(be(m,g),x)}else h=e;if(t==="otsu"){let m=w2(He(q2(h),"int32"),Be([]),256);u=T$(m,l)}let f=a?fh(h,u):np(h,u);return He(ae(f,255),"int32")}function T$(e,t){let a=Ht([-1]),n=Ht([0]),r=Ht([0]),s,i,o,l,u,p;for(let c=0;c<e.size-1;c++){s=Pe(e,0,c+1),i=Pe(e,c+1),u=me(tt(s),t),p=me(tt(i),t);let d=tt(ae(s,hl(0,s.size)));o=me(d,tt(s));let h=nr(i.shape,s.size),f=be(hl(0,i.size),h),m=ae(i,f);l=me(tt(m),tt(i));let g=fe(o,l),x=fe(o,l),A=ae(u,p);r=ae(ae(A,g),x);let y=np(r,n);n=Vs(y,r,n),a=Vs(y,Ht([c]),a)}return a}var C$=D({threshold_:S$});function N$(e,t,a="nearest",n="constant",r=0,s){let i=R(e,"image","transform","float32"),o=R(t,"transforms","transform","float32");P(i.rank===4,()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`),P(o.rank===2&&(o.shape[0]===i.shape[0]||o.shape[0]===1)&&o.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),P(s==null||s.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`);let l={image:i,transforms:o},u={interpolation:a,fillMode:n,fillValue:r,outputShape:s};return z.runKernel(ho,l,u)}var E$=D({transform_:N$});function R$(e,t,a){P(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),P(a%1===0,()=>`bandPart(): numUpper must be an integer, got ${a}.`);let n=R(e,"a","bandPart");P(n.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${n.rank}.`);let r=n.shape,[s,i]=n.shape.slice(-2);if(!(t<=s))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`);if(!(a<=i))throw new Error(`bandPart(): numUpper (${a}) must not be greater than the number of columns (${i}).`);t<0&&(t=s),a<0&&(a=i);let o=J(hl(0,s,1,"int32"),[-1,1]),l=hl(0,i,1,"int32"),u=fe(o,l),p=pd(fh(u,Fe(+t,"int32")),E2(u,Fe(-a,"int32"))),c=fn([s,i],n.dtype);return J(sa(Ta(J(n,[-1,s,i])).map(d=>Vs(p,d,c))),r)}var M$=D({bandPart_:R$});function $$(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 s=1;s<e.length;++s)P(e[s].shape[0]===r,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[s].shape[0]} vs. ${r})`)}else t=!0,e=ka(e,e.shape[0],0).map(r=>_e(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 a=[],n=e;for(let r=0;r<e.length;++r)a.push(z.tidy(()=>{let s=n[r];if(r>0)for(let i=0;i<r;++i){let o=ae(tt(ae(a[i],s)),a[i]);s=fe(s,o)}return me(s,ap(s,"euclidean"))}));return t?sa(a,0):a}var _$=D({gramSchmidt_:$$});function P$(e,t=!1){if(P(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return K5(e,t);{let a=e.shape.slice(0,e.shape.length-2).reduce((l,u)=>l*u),n=Ta(J(e,[a,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],s=[];n.forEach(l=>{let[u,p]=K5(l,t);r.push(u),s.push(p)});let i=J(sa(r,0),e.shape),o=J(sa(s,0),e.shape);return[i,o]}}function K5(e,t=!1){return z.tidy(()=>{P(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let a=e.shape[0],n=e.shape[1],r=T2(a),s=wa(e),i=Kn([[1]],[1,1]),o=wa(i),l=a>=n?n:a;for(let u=0;u<l;++u){let p=s,c=o,d=r;[o,s,r]=z.tidy(()=>{let h=Pe(s,[u,u],[a-u,1]),f=ap(h),m=Pe(s,[u,u],[1,1]),g=Vs(np(m,0),Kn([[-1]]),Kn([[1]])),x=fe(m,ae(g,f)),A=me(h,x);A.shape[0]===1?o=wa(i):o=at([i,Pe(A,[1,0],[A.shape[0]-1,A.shape[1]])],0);let y=Xn(me(st(g,x),f)),b=Pe(s,[u,0],[a-u,n]),w=ae(y,o),S=Ws(o);if(u===0)s=fe(b,st(w,st(S,b)));else{let _=fe(b,st(w,st(S,b)));s=at([Pe(s,[0,0],[u,n]),_],0)}let C=Ws(w),E=Pe(r,[0,u],[a,r.shape[1]-u]);if(u===0)r=fe(E,st(st(E,o),C));else{let _=fe(E,st(st(E,o),C));r=at([Pe(r,[0,0],[a,u]),_],1)}return[o,s,r]}),Y([p,c,d])}return!t&&a>n&&(r=Pe(r,[0,0],[a,n]),s=Pe(s,[0,0],[n,n])),[r,s]})}var F$=D({qr_:P$}),ya;(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"})(ya||(ya={}));function O$(e,t,a=ya.SUM_BY_NONZERO_WEIGHTS){let n=R(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=R(t,"weights","computeWeightedLoss"));let s=r==null?n:ae(n,r);if(a===ya.NONE)return s;if(a===ya.SUM)return tt(s);if(a===ya.MEAN){if(r==null)return cd(s);{let i=n.size/r.size,o=me(tt(s),tt(r));return i>1?me(o,Fe(i)):o}}if(a===ya.SUM_BY_NONZERO_WEIGHTS){if(r==null)return me(tt(s),Fe(n.size));{let i=ae(r,Wr(n.shape)),o=He(tt(L2(i,Fe(0))),"float32");return me(tt(s),o)}}throw Error(`Unknown reduction: ${a}`)}var Ir=D({computeWeightedLoss_:O$});function D$(e,t,a,n=ya.SUM_BY_NONZERO_WEIGHTS){let r=R(e,"labels","absoluteDifference"),s=R(t,"predictions","absoluteDifference"),i=null;a!=null&&(i=R(a,"weights","absoluteDifference")),Sa(r.shape,s.shape,"Error in absoluteDifference: ");let o=qa(fe(r,s));return Ir(o,i,n)}var z$=D({absoluteDifference_:D$});function L$(e,t,a,n,r=ya.SUM_BY_NONZERO_WEIGHTS){let s=R(e,"labels","cosineDistance"),i=R(t,"predictions","cosineDistance"),o=null;n!=null&&(o=R(n,"weights","cosineDistance")),Sa(s.shape,i.shape,"Error in cosineDistance: ");let l=Fe(1),u=fe(l,tt(ae(s,i),a,!0));return Ir(u,o,r)}var B$=D({cosineDistance_:L$});function W$(e,t,a,n=ya.SUM_BY_NONZERO_WEIGHTS){let r=R(e,"labels","hingeLoss"),s=R(t,"predictions","hingeLoss"),i=null;a!=null&&(i=R(a,"weights","hingeLoss")),Sa(r.shape,s.shape,"Error in hingeLoss: ");let o=Fe(1);r=fe(ae(Fe(2),r),o);let l=rp(fe(o,ae(r,s)));return Ir(l,i,n)}var V$=D({hingeLoss_:W$});function U$(e,t,a,n=1,r=ya.SUM_BY_NONZERO_WEIGHTS){let s=R(e,"labels","huberLoss"),i=R(t,"predictions","huberLoss"),o=null;a!=null&&(o=R(a,"weights","huberLoss")),Sa(s.shape,i.shape,"Error in huberLoss: ");let l=Fe(n),u=qa(fe(i,s)),p=z2(u,l),c=fe(u,p),d=be(ae(Fe(.5),In(p)),ae(l,c));return Ir(d,o,r)}var G$=D({huberLoss_:U$});function H$(e,t,a,n=1e-7,r=ya.SUM_BY_NONZERO_WEIGHTS){let s=R(e,"labels","logLoss"),i=R(t,"predictions","logLoss"),o=null;a!=null&&(o=R(a,"weights","logLoss")),Sa(s.shape,i.shape,"Error in logLoss: ");let l=Fe(1),u=Fe(n),p=Xn(ae(s,cl(be(i,u)))),c=ae(fe(l,s),cl(be(fe(l,i),u))),d=fe(p,c);return Ir(d,o,r)}var j$=D({logLoss_:H$});function q$(e,t,a,n=ya.SUM_BY_NONZERO_WEIGHTS){let r=R(e,"labels","meanSquaredError"),s=R(t,"predictions","meanSquaredError"),i=null;a!=null&&(i=R(a,"weights","meanSquaredError")),Sa(r.shape,s.shape,"Error in meanSquaredError: ");let o=K2(r,s);return Ir(o,i,n)}var X$=D({meanSquaredError_:q$});function K$(e,t){let a=R(e,"labels","sigmoidCrossEntropyWithLogits"),n=R(t,"logits","sigmoidCrossEntropyWithLogits");Sa(a.shape,n.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=rp(n),s=ae(n,a),i=M2(Zr(Xn(qa(n))));return be(fe(r,s),i)}function Z$(e,t,a,n=0,r=ya.SUM_BY_NONZERO_WEIGHTS){let s=R(e,"multiClassLabels","sigmoidCrossEntropy"),i=R(t,"logits","sigmoidCrossEntropy"),o=null;if(a!=null&&(o=R(a,"weights","sigmoidCrossEntropy")),Sa(s.shape,i.shape,"Error in sigmoidCrossEntropy: "),n>0){let u=Fe(n),p=Fe(1),c=Fe(.5);s=be(ae(s,fe(p,u)),ae(c,u))}let l=K$(s,i);return Ir(l,o,r)}var Y$=D({sigmoidCrossEntropy_:Z$});function J$(e,t,a=-1){if(a===-1&&(a=t.rank-1),a!==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 ${a}`);return Qn((n,r,s)=>{let i=_2(r,[a],!0),o=fe(He(r,"float32"),i);s([n,o]);let l=Xn(ae(o,n));return{value:tt(l,[a]),gradFunc:(u,p)=>{let[c,d]=p,h=tp(u.shape,[a]);return[ae(J(u,h),fe(He(c,"float32"),Zr(d))),ae(J(u,h),fe(Zr(d),He(c,"float32")))]}}})(e,t)}function Q$(e,t,a,n=0,r=ya.SUM_BY_NONZERO_WEIGHTS){let s=R(e,"onehotLabels","softmaxCrossEntropy"),i=R(t,"logits","softmaxCrossEntropy"),o=null;if(a!=null&&(o=R(a,"weights","softmaxCrossEntropy")),Sa(s.shape,i.shape,"Error in softmaxCrossEntropy: "),n>0){let u=Fe(n),p=Fe(1),c=Fe(s.shape[1]);s=be(ae(s,fe(p,u)),me(u,c))}let l=J$(s,i);return Ir(l,o,r)}var e_=D({softmaxCrossEntropy_:Q$});function t_(e,t,a,n){let r=R(e,"indices","sparseFillEmptyRows","int32"),s=R(t,"values","sparseFillEmptyRows"),i=R(a,"denseShape","sparseFillEmptyRows","int32"),o=R(n,"defaultValue","sparseFillEmptyRows",s.dtype);if(r.rank!==2)throw new Error(`Indices should be Tensor2D but received shape
${r.shape}`);if(s.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);if(i.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(o.rank!==0)throw new Error(`Default value should be a scalar but received shape ${o.shape}`);let l={indices:r,values:s,denseShape:i,defaultValue:o},u=z.runKernel(Od,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var a_=D({sparseFillEmptyRows_:t_});function n_(e,t,a){let n=R(e,"inputIndices","sparseReshape","int32"),r=R(t,"inputShape","sparseReshape","int32"),s=R(a,"newShape","sparseReshape","int32");if(n.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
${n.shape}`);if(r.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${r.shape}`);if(s.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);let i={inputIndices:n,inputShape:r,newShape:s},o=z.runKernel(eu,i);return{outputIndices:o[0],outputShape:o[1]}}var r_=D({sparseReshape_:n_});function s_(e,t,a){let n=R(e,"data","sparseSegmentMean"),r=R(t,"indices","sparseSegmentMean","int32"),s=R(a,"segmentIds","sparseSegmentMean","int32");if(n.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(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
${s.shape}`);let i={data:n,indices:r,segmentIds:s};return z.runKernel(Dd,i)}var i_=D({sparseSegmentMean_:s_});function o_(e,t,a){let n=R(e,"data","sparseSegmentSum"),r=R(t,"indices","sparseSegmentSum","int32"),s=R(a,"segmentIds","sparseSegmentSum","int32");if(n.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(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
${s.shape}`);let i={data:n,indices:r,segmentIds:s};return z.runKernel(zd,i)}var l_=D({sparseSegmentSum_:o_});function u_(e,t,a,n,r,s,i,o){let l=R(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=R(t,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let p={separator:a,nGramWidths:n,leftPad:r,rightPad:s,padWidth:i,preserveShortSequences:o},c={data:l,dataSplits:u},d=z.runKernel(tu,c,p);return{nGrams:d[0],nGramsSplits:d[1]}}var d_=D({stringNGrams_:u_});function p_(e,t,a=!0){let n=R(e,"input","stringSplit","string"),r=R(t,"delimiter","stringSplit","string");if(n.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${n.shape}`);if(r.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);let s={skipEmpty:a},i={input:n,delimiter:r},o=z.runKernel(Wd,i,s);return{indices:o[0],values:o[1],shape:o[2]}}var c_=D({stringSplit_:p_});function h_(e,t){let a=R(e,"input","stringToHashBucketFast","string"),n={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let r={input:a};return z.runKernel(Vd,r,n)}var f_=D({stringToHashBucketFast_:h_}),f4={fft:yh,ifft:hd,rfft:bh,irfft:X2},m4={hammingWindow:GM,hannWindow:u4,frame:d4,stft:XM},ge={flipLeftRight:JM,grayscaleToRGB:e$,resizeNearestNeighbor:I$,resizeBilinear:w$,rotateWithOffset:a$,cropAndResize:ZM,nonMaxSuppression:r$,nonMaxSuppressionAsync:c$,nonMaxSuppressionWithScore:f$,nonMaxSuppressionWithScoreAsync:g$,nonMaxSuppressionPadded:A$,nonMaxSuppressionPaddedAsync:b$,threshold:C$,transform:E$},g4={bandPart:M$,gramSchmidt:_$,qr:F$},x4={absoluteDifference:z$,computeWeightedLoss:Ir,cosineDistance:B$,hingeLoss:V$,huberLoss:G$,logLoss:j$,meanSquaredError:X$,sigmoidCrossEntropy:Y$,softmaxCrossEntropy:e_},A4={sparseFillEmptyRows:a_,sparseReshape:r_,sparseSegmentMean:i_,sparseSegmentSum:l_},y4={stringNGrams:d_,stringSplit:c_,stringToHashBucketFast:f_},is=class extends ny{minimize(e,t=!1,a){let{value:n,grads:r}=this.computeGradients(e,a);if(a!=null){let s=a.map(i=>({name:i.name,tensor:r[i.name]}));this.applyGradients(s)}else this.applyGradients(r);return Y(r),t?n:(n.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return rb(e,t)}dispose(){this.iterations_!=null&&Y(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Fe(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(is,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var Th=class extends is{constructor(e,t,a=null){super(),this.learningRate=e,this.rho=t,this.epsilon=a,this.accumulatedGrads=[],this.accumulatedUpdates=[],a==null&&(this.epsilon=z.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,a)=>{let n=z.registeredVariables[t],r=!1;this.accumulatedGrads[a]==null&&(this.accumulatedGrads[a]={originalName:`${t}/accum_grad`,variable:$e(()=>Ka(n).variable(r))}),this.accumulatedUpdates[a]==null&&(this.accumulatedUpdates[a]={originalName:`${t}/accum_var`,variable:$e(()=>Ka(n).variable(r))});let s=Array.isArray(e)?e[a].tensor:e[t];if(s==null)return;let i=this.accumulatedGrads[a].variable,o=this.accumulatedUpdates[a].variable;$e(()=>{let l=be(ae(i,this.rho),ae(In(s),1-this.rho)),u=ae(me(Jn(be(o,this.epsilon)),Jn(be(i,this.epsilon))),s),p=be(ae(o,this.rho),ae(In(u),1-this.rho));i.assign(l),o.assign(p);let c=be(ae(u,-this.learningRate),n);n.assign(c)})}),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,a=!1;this.accumulatedGrads=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(a)})),this.accumulatedUpdates=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(a)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}};Th.className="Adadelta";ss(Th);var Ch=class extends is{constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,a)=>{let n=z.registeredVariables[t];this.accumulatedGrads[a]==null&&(this.accumulatedGrads[a]={originalName:`${t}/accumulator`,variable:$e(()=>nr(n.shape,this.initialAccumulatorValue).variable(!1))});let r=Array.isArray(e)?e[a].tensor:e[t];if(r==null)return;let s=this.accumulatedGrads[a].variable;$e(()=>{let i=be(s,In(r));s.assign(i);let o=be(ae(me(r,Jn(be(i,z.backend.epsilon()))),-this.learningRate),n);n.assign(o)})}),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(a=>({originalName:a.name,variable:a.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}};Ch.className="Adagrad";ss(Ch);var Nh=class extends is{constructor(e,t,a,n=null){super(),this.learningRate=e,this.beta1=t,this.beta2=a,this.epsilon=n,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],$e(()=>{this.accBeta1=Fe(t).variable(),this.accBeta2=Fe(a).variable()}),n==null&&(this.epsilon=z.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(a=>a.name):Object.keys(e);$e(()=>{let a=fe(1,this.accBeta1),n=fe(1,this.accBeta2);t.forEach((r,s)=>{let i=z.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:$e(()=>Ka(i).variable(o))}),this.accumulatedSecondMoment[s]==null&&(this.accumulatedSecondMoment[s]={originalName:`${r}/v`,variable:$e(()=>Ka(i).variable(o))});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,p=this.accumulatedSecondMoment[s].variable,c=be(ae(u,this.beta1),ae(l,1-this.beta1)),d=be(ae(p,this.beta2),ae(In(l),1-this.beta2)),h=me(c,a),f=me(d,n);u.assign(c),p.assign(d);let m=be(ae(me(h,be(Jn(f),this.epsilon)),-this.learningRate),i);i.assign(m)}),this.accBeta1.assign(ae(this.accBeta1,this.beta1)),this.accBeta2.assign(ae(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),$e(()=>{this.accBeta1.assign(pl(this.beta1,this.iterations_+1)),this.accBeta2.assign(pl(this.beta2,this.iterations_+1))});let t=e.length/2,a=!1;this.accumulatedFirstMoment=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(a)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(a)}))}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)}};Nh.className="Adam";ss(Nh);var Eh=class extends is{constructor(e,t,a,n=null,r=0){super(),this.learningRate=e,this.beta1=t,this.beta2=a,this.epsilon=n,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],$e(()=>{this.iteration=Fe(0).variable(),this.accBeta1=Fe(t).variable()}),n==null&&(this.epsilon=z.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(a=>a.name):Object.keys(e);$e(()=>{let a=fe(1,this.accBeta1),n=me(-this.learningRate,be(ae(this.iteration,this.decay),1));t.forEach((r,s)=>{let i=z.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:Ka(i).variable(o)}),this.accumulatedWeightedInfNorm[s]==null&&(this.accumulatedWeightedInfNorm[s]={originalName:`${r}/v`,variable:Ka(i).variable(o)});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,p=this.accumulatedWeightedInfNorm[s].variable,c=be(ae(u,this.beta1),ae(l,1-this.beta1)),d=ae(p,this.beta2),h=qa(l),f=D2(d,h);u.assign(c),p.assign(f);let m=be(ae(me(n,a),me(c,be(f,this.epsilon))),i);i.assign(m)}),this.iteration.assign(be(this.iteration,1)),this.accBeta1.assign(ae(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)}};Eh.className="Adamax";ss(Eh);var ip=class extends is{constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,a)=>{let n=Array.isArray(e)?e[a].tensor:e[t];if(n==null)return;let r=z.registeredVariables[t];$e(()=>{let s=be(ae(this.c,n),r);r.assign(s)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=On(Fe(-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)}};ip.className="SGD";ss(ip);var Rh=class extends ip{constructor(e,t,a=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=a,this.accumulations=[],this.m=Fe(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,a)=>{let n=z.registeredVariables[t];this.accumulations[a]==null&&(this.accumulations[a]={originalName:`${t}/momentum`,variable:$e(()=>Ka(n).variable(!1))});let r=this.accumulations[a].variable,s=Array.isArray(e)?e[a].tensor:e[t];s!=null&&$e(()=>{let i,o=be(ae(this.m,r),s);this.useNesterov?i=be(ae(this.c,be(s,ae(o,this.m))),n):i=be(ae(this.c,o),n),r.assign(o),n.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(a=>({originalName:a.name,variable:a.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)}};Rh.className="Momentum";ss(Rh);var Mh=class extends is{constructor(e,t=.9,a=0,n=null,r=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=a,this.epsilon=n,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,n==null&&(this.epsilon=z.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,a)=>{let n=z.registeredVariables[t],r=!1;this.accumulatedMeanSquares[a]==null&&(this.accumulatedMeanSquares[a]={originalName:`${t}/rms`,variable:$e(()=>Ka(n).variable(r))}),this.accumulatedMoments[a]==null&&(this.accumulatedMoments[a]={originalName:`${t}/momentum`,variable:$e(()=>Ka(n).variable(r))}),this.accumulatedMeanGrads[a]==null&&this.centered&&(this.accumulatedMeanGrads[a]={originalName:`${t}/mg`,variable:$e(()=>Ka(n).variable(r))});let s=Array.isArray(e)?e[a].tensor:e[t];if(s==null)return;let i=this.accumulatedMeanSquares[a].variable,o=this.accumulatedMoments[a].variable;$e(()=>{let l=be(ae(i,this.decay),ae(In(s),1-this.decay));if(this.centered){let u=this.accumulatedMeanGrads[a].variable,p=be(ae(u,this.decay),ae(s,1-this.decay)),c=me(ae(s,this.learningRate),Jn(fe(l,be(In(p),this.epsilon)))),d=be(ae(o,this.momentum),c);i.assign(l),u.assign(p),o.assign(d);let h=fe(n,d);n.assign(h)}else{let u=be(ae(i,this.decay),ae(In(s),1-this.decay)),p=be(ae(o,this.momentum),me(ae(s,this.learningRate),Jn(be(u,this.epsilon))));i.assign(u),o.assign(p);let c=fe(n,p);n.assign(c)}})}),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,a=!1;this.accumulatedMeanSquares=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(a)})),this.accumulatedMoments=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(a)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(n=>({originalName:n.name,variable:n.tensor.variable(a)})))}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)}};Mh.className="RMSProp";ss(Mh);var Or=class{static sgd(e){return new ip(e)}static momentum(e,t,a=!1){return new Rh(e,t,a)}static rmsprop(e,t=.9,a=0,n=null,r=!1){return new Mh(e,t,a,n,r)}static adam(e=.001,t=.9,a=.999,n=null){return new Nh(e,t,a,n)}static adadelta(e=.001,t=.95,a=null){return new Th(e,t,a)}static adamax(e=.002,t=.9,a=.999,n=null,r=0){return new Eh(e,t,a,n,r)}static adagrad(e,t=.1){return new Ch(e,t)}},m_={sgd:Or.sgd,momentum:Or.momentum,adadelta:Or.adadelta,adagrad:Or.adagrad,rmsprop:Or.rmsprop,adamax:Or.adamax,adam:Or.adam},g_=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function b4(){return new Promise(e=>g_(()=>e()))}var T={};Xe(T,{ERF_A1:()=>__,ERF_A2:()=>P_,ERF_A3:()=>F_,ERF_A4:()=>O_,ERF_A5:()=>D_,ERF_P:()=>$_,PARALLELIZE_THRESHOLD:()=>t3,RowPartitionType:()=>Hn,SELU_SCALE:()=>M_,SELU_SCALEALPHA:()=>R_,applyActivation:()=>Ih,assertAndGetBroadcastShape:()=>zt,assertAxesAreInnerMostDims:()=>hE,assertParamsConsistent:()=>x_,assignToTypedArray:()=>U_,axesAreInnerMostDims:()=>S2,calculateShapes:()=>qA,checkEinsumDimSizes:()=>K_,checkPadOnDimRoundingMode:()=>Sn,combineLocations:()=>Xy,combineRaggedTensorToTensorShapes:()=>y_,complexWithEvenIndex:()=>B_,complexWithOddIndex:()=>W_,computeConv2DInfo:()=>Jd,computeConv3DInfo:()=>Ay,computeDefaultPad:()=>y2,computeDilation2DInfo:()=>cN,computeOptimalWindowSize:()=>k_,computeOutAndReduceShapes:()=>cE,computeOutShape:()=>A_,computePool2DInfo:()=>xy,computePool3DInfo:()=>hN,convertConv2DDataFormat:()=>yy,decodeEinsumEquation:()=>q_,eitherStridesOrDilationsAreOne:()=>kr,expandShapeToKeepDim:()=>tp,exponent:()=>H_,exponents:()=>G_,fromStringArrayToUint8:()=>gP,fromUint8ToStringArray:()=>mP,getAxesPermutation:()=>fE,getBroadcastDims:()=>GA,getComplexWithIndex:()=>V_,getEinsumComputePath:()=>Z_,getEinsumPermutation:()=>X_,getFusedBiasGradient:()=>kh,getFusedDyActivation:()=>wh,getImageCenter:()=>I_,getInnerMostAxes:()=>gE,getPermuted:()=>T_,getRaggedRank:()=>v_,getReductionAxes:()=>d2,getReshaped:()=>S_,getReshapedPermuted:()=>C_,getRowPartitionTypesHelper:()=>b_,getSliceBeginCoords:()=>N_,getSliceSize:()=>E_,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>eP,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>tP,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>aP,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>sP,getSparseReshapeInputOutputMismatchErrorMessage:()=>oP,getSparseReshapeInputOutputMultipleErrorMessage:()=>iP,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>nP,getSparseReshapeNegativeOutputDimErrorMessage:()=>rP,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>pP,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>lP,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>uP,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>dP,getUndoAxesPermutation:()=>mE,isIdentityPermutation:()=>Y_,log:()=>MS,mergeRealAndImagArrays:()=>z_,prepareAndValidate:()=>jA,prepareSplitSize:()=>Q_,segment_util:()=>v4,shouldFuse:()=>Sh,slice_util:()=>It,splitRealAndImagArrays:()=>L_,tupleValuesAreOne:()=>dd,upcastType:()=>ca,validateDefaultValueShape:()=>w_,validateInput:()=>m2,validateUpdateShape:()=>f2,warn:()=>zr});function x_(e,t){let a=e[0].length;e.forEach((r,s)=>{P(r.length===a,()=>`Error in concat${a}D: rank of tensors[${s}] must be the same as the rank of the rest (${a})`)}),P(t>=0&&t<a,()=>`Error in concat${a}D: axis must be between 0 and ${a-1}.`);let n=e[0];e.forEach((r,s)=>{for(let i=0;i<a;i++)P(i===t||r[i]===n[i],()=>`Error in concat${a}D: Shape of tensors[${s}] (${r}) does not match the shape of the rest (${n}) along the non-concatenated axis ${s}.`)})}function A_(e,t){let a=e[0].slice();for(let n=1;n<e.length;n++)a[t]+=e[n][t];return a}var Hn;(function(e){e[e.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",e[e.VALUE_ROWIDS=1]="VALUE_ROWIDS",e[e.ROW_LENGTHS=2]="ROW_LENGTHS",e[e.ROW_SPLITS=3]="ROW_SPLITS",e[e.ROW_LIMITS=4]="ROW_LIMITS",e[e.ROW_STARTS=5]="ROW_STARTS"})(Hn||(Hn={}));function y_(e,t,a){let n=new Array;if(a==null&&t==null)return n;if(t==null)for(;n.length<e+a.length;)n.push(-1);else n=t.slice();if(a==null)return n;if(e+a.length!==n.length)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.rank = ${e+a.length}, but shape.rank = ${n.length}`);for(let r=1;r<a.length;++r){let s=a[r],i=n[n.length-a.length+r],o=n[i];if(s>=0)if(o>=0){if(o!==s)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${r+e}] = ${s} but shape[${r+e}] = ${o}`)}else n[i]=s}return n}function b_(e){let t={FIRST_DIM_SIZE:Hn.FIRST_DIM_SIZE,VALUE_ROWIDS:Hn.VALUE_ROWIDS,ROW_LENGTHS:Hn.ROW_LENGTHS,ROW_SPLITS:Hn.ROW_SPLITS,ROW_LIMITS:Hn.ROW_LIMITS,ROW_STARTS:Hn.ROW_STARTS},a=[];for(let n of e)if(n in t)a.push(t[n]);else break;return a}function v_(e){return e.length===0?0:e[0]===Hn.FIRST_DIM_SIZE?e.length-1:e.length}function w_(e,t){if(e==null||t==null)return;let a=e.length,n=t.length;if(a>=n)throw new Error(`defaultValue.shape=${e} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${a} must be less than ragged tensor input flatValues.rank = ${n})`);for(let r=0;r<Math.min(a,n-1);++r){let s=e[r],i=t[r+1];if(s>=0&&i>=0&&s!==1&&s!==i)throw new Error(`defaultValue.shape=${e}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${r-e.length}] = ${s} but ragged tensor input.flatValues.shape[${r-e.length}] = ${i}`)}}var t3=30;function k_(e){return e<=t3?e:Ic(e,Math.floor(Math.sqrt(e)))}function I_(e,t,a){let n=a*(typeof e=="number"?e:e[0]),r=t*(typeof e=="number"?e:e[1]);return[n,r]}function S_(e,t,a,n=!0){let r=[];if(n)r=r.concat(t.slice(0)),r.push(e[0]/a),r=r.concat(e.slice(1));else{r=r.concat(e[0]);let s=t.length;for(let i=0;i<s;++i)r=r.concat([e[i+1]/t[i],t[i]]);r=r.concat(e.slice(s+1))}return r}function T_(e,t,a=!0){let n=[];if(a){n.push(t);for(let r=t+1;r<e;++r)r<=2*t?(n.push(r),n.push(r-(t+1))):n.push(r)}else{let r=[],s=[];for(let i=1;i<e;++i)i>=t*2+1||i%2===1?s.push(i):r.push(i);n.push(...r),n.push(0),n.push(...s)}return n}function C_(e,t,a,n=!0){let r=[];n?r.push(e[0]/a):r.push(e[0]*a);for(let s=1;s<e.length;++s)s<=t.length?n?r.push(t[s-1]*e[s]):r.push(e[s]/t[s-1]):r.push(e[s]);return r}function N_(e,t){let a=[0];for(let n=0;n<t;++n)a.push(e[n][0]);return a}function E_(e,t,a){let n=e.slice(0,1);for(let r=0;r<a;++r)n.push(e[r+1]-t[r][0]-t[r][1]);return n}var R_=1.7580993408473768,M_=1.0507009873554805,$_=.3275911,__=.254829592,P_=-.284496736,F_=1.421413741,O_=-1.453152027,D_=1.061405429;function z_(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);let a=new Float32Array(e.length*2);for(let n=0;n<a.length;n+=2)a[n]=e[n/2],a[n+1]=t[n/2];return a}function L_(e){let t=new Float32Array(e.length/2),a=new Float32Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=e[n],a[n/2]=e[n+1];return{real:t,imag:a}}function B_(e){let t=Math.ceil(e.length/4),a=new Float32Array(t),n=new Float32Array(t);for(let r=0;r<e.length;r+=4)a[Math.floor(r/4)]=e[r],n[Math.floor(r/4)]=e[r+1];return{real:a,imag:n}}function W_(e){let t=Math.floor(e.length/4),a=new Float32Array(t),n=new Float32Array(t);for(let r=2;r<e.length;r+=4)a[Math.floor(r/4)]=e[r],n[Math.floor(r/4)]=e[r+1];return{real:a,imag:n}}function V_(e,t){let a=e[t*2],n=e[t*2+1];return{real:a,imag:n}}function U_(e,t,a,n){e[n*2]=t,e[n*2+1]=a}function G_(e,t){let a=new Float32Array(e/2),n=new Float32Array(e/2);for(let r=0;r<Math.ceil(e/2);r++){let s=(t?2:-2)*Math.PI*(r/e);a[r]=Math.cos(s),n[r]=Math.sin(s)}return{real:a,imag:n}}function H_(e,t,a){let n=(a?2:-2)*Math.PI*(e/t),r=Math.cos(n),s=Math.sin(n);return{real:r,imag:s}}var Om="->",j_=/->/g,Z5=",",Y5="...";function q_(e,t){e=e.replace(/\s/g,"");let a=(e.length-e.replace(j_,"").length)/Om.length;if(a<1)throw new Error("Equations without an arrow are not supported.");if(a>1)throw new Error(`Equation must contain exactly one arrow ("${Om}").`);let[n,r]=e.split(Om);P(n.indexOf(Y5)===-1,()=>`The ellipsis notation ("${Y5}") is not supported yet.`);let s=n.split(Z5),i=s.length;if(t!==i)throw new Error(`Expected ${i} input tensors, received ${t}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let o=[];for(let d=0;d<r.length;++d){let h=r[d];if(!s.some(f=>f.indexOf(h)!==-1))throw new Error(`Output subscripts contain the label ${h} not present in the input subscripts.`);o.indexOf(h)===-1&&o.push(h)}for(let d=0;d<n.length;++d){let h=n[d];o.indexOf(h)===-1&&h!==Z5&&o.push(h)}let l=new Array(s.length);for(let d=0;d<i;++d){if(new Set(s[d].split("")).size!==s[d].length)throw new Error(`Found duplicate axes in input component ${s[d]}. Support for duplicate axes in input is not implemented yet.`);l[d]=[];for(let h=0;h<s[d].length;++h)l[d].push(o.indexOf(s[d][h]))}let u=o.length,p=r.length,c=[];for(let d=p;d<u;++d)c.push(d);return{allDims:o,summedDims:c,idDims:l}}function X_(e,t){let a=new Array(e);a.fill(-1);for(let r=0;r<t.length;++r)a[t[r]]=r;let n=[];for(let r=0;r<e;++r)a[r]===-1&&n.push(r);return a=a.filter(r=>r!==-1),{permutationIndices:a,expandDims:n}}function K_(e,t,a){let n=new Array(e);for(let r=0;r<a.length;++r){let s=a[r].shape;for(let i=0;i<t[r].length;++i)n[t[r][i]]===void 0?n[t[r][i]]=s[i]:P(n[t[r][i]]===s[i],()=>`Expected dimension ${n[t[r][i]]} at axis ${i} of input shaped ${JSON.stringify(s)}, but got dimension ${s[i]}`)}}function Z_(e,t){let a=e,n=[],r=0;e.length===0&&a.push(-1),r=e.length+1;for(let i=0;i<r;++i)n.push([]);let s=[];for(let i=0;i<a.length;++i){let o=a[i],l=J_(t,o);for(let u of l)s.indexOf(u)===-1&&(n[i].push(u),s.push(u))}return{path:a,steps:n}}function Y_(e){return e.every((t,a)=>t===a)}function J_(e,t){let a=[];for(let n=0;n<e.length;++n)(e[n].length===0||e[n].indexOf(t)!==-1||t===-1)&&a.push(n);return a}function Q_(e,t,a=0){let n=[];if(typeof t=="number")P(e.shape[a]%t===0,()=>"Number of splits must evenly divide the axis."),n=new Array(t).fill(e.shape[a]/t);else{let r=t.reduce((i,o)=>(o===-1&&(i+=1),i),0);P(r<=1,()=>"There should be only one negative value in split array.");let s=t.indexOf(-1);if(s!==-1){let i=t.reduce((o,l)=>l>0?o+l:o);t[s]=e.shape[a]-i}P(e.shape[a]===t.reduce((i,o)=>i+o),()=>"The sum of sizes must match the size of the axis dimension."),n=t}return n}function eP(e){return`Received SparseTensor with denseShape[0] = 0 but
indices.shape[0] = ${e}`}function tP(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function aP(e,t,a){return`indices(${e}, 0) is invalid: ${t} >= ${a}`}function nP(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function rP(e,t){return`size ${e} must be non-negative, not ${t}`}function sP(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function iP(e,t){let a=At(e),n=At(t);return`Input to reshape is a SparseTensor with ${a}
dense values, but the requested shape requires a multiple of ${n}. inputShape=${e} outputShape= ${t}`}function oP(e,t){let a=At(e),n=At(t);return`Input to reshape is a tensor with ${a} dense values, but the requested shape has ${n}. inputShape=${e} outputShape=${t}`}function lP(){return"segment ids must be >= 0"}function uP(){return"segment ids are not increasing"}function dP(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function pP(e,t,a){return`Bad: indices[${e}] == ${t} out of range [0, ${a})`}var v4={};Xe(v4,{collectGatherOpShapeInfo:()=>fP,computeOutShape:()=>hP,segOpComputeOptimalWindowSize:()=>cP});function cP(e,t){let a=!1,n;for(e<=t3?(n=e,a=!0):n=Ic(e,Math.floor(Math.sqrt(e)));!a;)n>t||n===e?a=!0:n=Ic(e,n+1);return n}function hP(e,t,a){let n=[],r=e.length;for(let s=0;s<r;s++)s!==t?n.push(e[s]):n.push(a);return n}function fP(e,t,a,n){let r=t.shape.length,s=e.shape.length;if(n!==0&&(n<-r||n>r))throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${n}`);if(n<0&&(n+=r),n>s)throw new Error(`batchDims (${n}) must be less than rank(x) (
${s}).`);if(a<n)throw new Error(`batchDims (${n}) must be less than or equal to axis (${a}).`);for(let c=0;c<n;++c)if(e.shape[c]!==t.shape[c])throw new Error(`x.shape[${c}]: ${e.shape[c]} should be equal to indices.shape[${c}]: ${t.shape[c]}.`);let i=e.shape[a],o=[],l=1,u=1,p=1;for(let c=0;c<n;++c)o.push(e.shape[c]),l*=e.shape[c];for(let c=n;c<a;c++)o.push(e.shape[c]),u*=e.shape[c];for(let c=n;c<r;c++)o.push(t.shape[c]);for(let c=a+1;c<s;c++)o.push(e.shape[c]),p*=e.shape[c];return{batchSize:l,sliceSize:p,outerSize:u,dimSize:i,outputShape:o}}function mP(e){try{return e.map(t=>Tc(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function gP(e){return e.map(t=>Gd(t))}var Tn={};Xe(Tn,{nonMaxSuppressionV3Impl:()=>p4,nonMaxSuppressionV4Impl:()=>c4,nonMaxSuppressionV5Impl:()=>h4,whereImpl:()=>t4});var xP=W();xP.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 wn;(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"})(wn||(wn={}));var J5;(function(e){let t;(function(a){a[a.LEGACY=0]="LEGACY",a[a.V1=1]="V1",a[a.V2=2]="V2"})(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(J5||(J5={}));var a3={};function AP(e,t){let a={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};a3[e]=a}function w4(e){return a3[e]}function yP(e){delete a3[e]}function k(e,t,a,n,r){let s=t.inputParams[e];if(s&&s.inputIndexStart!==void 0){let o=s.inputIndexStart,l=s.inputIndexEnd===0?void 0:s.inputIndexEnd===void 0?o+1:s.inputIndexEnd;if(s.type==="tensor")return ba(t.inputNames[s.inputIndexStart],a,n,r);if(s.type==="tensors")return t.inputNames.slice(o,l).map(c=>ba(c,a,n,r));let u=ba(t.inputNames.slice(o)[0],a,n,r),p=u.dataSync();return s.type==="number"?p[0]:v.toNestedArray(u.shape,p)}let i=t.attrParams[e];return i&&i.value}function ba(e,t,a,n){let[r,s]=ja(e);if(n!=null){let o=n.getHashTableHandleByName(r);if(o!=null)return o}let i=a.currentContextIds.find(o=>!!t[Mc(r,o)]);return i!==void 0?t[Mc(r,i)][s]:void 0}function bP(e,t,a){return t[Mc(e,a.currentContextId)]}function mr(e,t){let[a,n,r]=ja(e);return[Mc(a,t&&t.currentContextId),n,r]}function Mc(e,t){return t?`${e}-${t}`:e}function ja(e){let t=e.split(":");if(t.length===1)return[e,0,void 0];let a=t[0],n=t.length===3?t[1]:void 0,r=Number(t[t.length-1]);return[a,r,n]}function mc(e,t,a){let n=k("pad",e,t,a);if(n==="explicit"){n=k("explicitPaddings",e,t,a);let r=[[0,0],[0,0],[0,0],[0,0]];for(let s=0;s<4;s++)r[s][0]=n[s*2],r[s][1]=n[s*2+1];return r}return n}function gr(e){return e.kept?e:wa(e)}var k4={};Xe(k4,{json:()=>vP});var vP=[{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}]}],I4={};Xe(I4,{json:()=>wP});var wP=[{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}]}],S4={};Xe(S4,{json:()=>kP});var kP=[{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"}]}],T4={};Xe(T4,{json:()=>IP});var IP=[{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"}]}],C4={};Xe(C4,{json:()=>SP});var SP=[{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"}]}],N4={};Xe(N4,{json:()=>TP});var TP=[{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}]}],E4={};Xe(E4,{json:()=>CP});var CP=[{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"}]}],R4={};Xe(R4,{json:()=>NP});var NP=[{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"}]}],M4={};Xe(M4,{json:()=>EP});var EP=[{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"}]},{tfOpName:"InitializeTable",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]},{tfOpName:"InitializeTableV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]}],$4={};Xe($4,{json:()=>RP});var RP=[{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"}]}],_4={};Xe(_4,{json:()=>MP});var MP=[{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}]}],P4={};Xe(P4,{json:()=>$P});var $P=[{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"}]}],F4={};Xe(F4,{json:()=>_P});var _P=[{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}]}],O4={};Xe(O4,{json:()=>PP});var PP=[{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"}]}],D4={};Xe(D4,{json:()=>FP});var FP=[{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}]}],z4={};Xe(z4,{json:()=>OP});var OP=[{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"}]}],L4={};Xe(L4,{json:()=>DP});var DP=[{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}]}],B4={};Xe(B4,{json:()=>zP});var zP=[{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"}]}],W4={};Xe(W4,{json:()=>LP});var LP=[{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:[]}],Q5=class{constructor(){let e=[k4,I4,S4,T4,C4,N4,E4,R4,M4,$4,_4,P4,F4,O4,D4,z4,L4,B4,W4],t=[].concat(...e.map(a=>a.json));this.opMappers=t.reduce((a,n)=>(a[n.tfOpName]=n,a),{})}static get Instance(){return this._instance||(this._instance=new this)}transformGraph(e,t={}){let a=e.node,n=[],r=[],s=[],i=a.reduce((f,m)=>(f[m.name]=this.mapNode(m),m.op.startsWith("Placeholder")?n.push(f[m.name]):m.op==="Const"?r.push(f[m.name]):(m.input==null||m.input.length===0)&&s.push(f[m.name]),f),{}),o=[],l=[],u={},p={};t!=null&&(u=this.mapSignatureEntries(t.inputs),p=this.mapSignatureEntries(t.outputs));let c=Object.keys(i);c.forEach(f=>{let m=i[f];m.inputNames.forEach((g,x)=>{let[A,,y]=mr(g),b=i[A];if(b.outputs!=null){let w=b.outputs.indexOf(y);if(w!==-1){let S=`${A}:${w}`;m.inputNames[x]=S}}m.inputs.push(b),b.children.push(m)})}),Object.keys(p).length===0?c.forEach(f=>{let m=i[f];m.children.length===0&&l.push(m)}):Object.keys(p).forEach(f=>{let[m]=mr(f),g=i[m];g!=null&&(g.signatureKey=p[f],l.push(g))}),Object.keys(u).length>0?Object.keys(u).forEach(f=>{let[m]=mr(f),g=i[m];g&&(g.signatureKey=u[f],o.push(g))}):o=n;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:i,inputs:o,outputs:l,weights:r,placeholders:n,signature:t,functions:d};return s.length>0&&(h.initNodes=s),h}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,a)=>(t[e[a].name]=a,t),{})}mapNode(e){let t=w4(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});let a={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(n=>n.startsWith("^")?n.slice(1):n),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return t.inputs!=null&&(a.inputParams=t.inputs.reduce((n,r)=>(n[r.name]={type:r.type,inputIndexStart:r.start,inputIndexEnd:r.end},n),{})),t.attrs!=null&&(a.attrParams=t.attrs.reduce((n,r)=>{let s=r.type,i;switch(r.type){case"string":i=o1(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=o1(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"string[]":i=f1(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=f1(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number":i=u1(e.attr,r.tfName,r.defaultValue||0),i===void 0&&!!r.tfDeprecatedName&&(i=u1(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number[]":i=h1(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=h1(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool":i=l1(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=l1(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool[]":i=g1(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=g1(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape":i=c1(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=c1(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape[]":i=m1(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=m1(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype":i=d1(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=d1(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype[]":i=p1(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=p1(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"func":i=ex(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=ex(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 n[r.name]={value:i,type:s},n},{})),a}mapFunction(e){let t=e.nodeDef,a=[],n=[],r={};t!=null&&(r=t.reduce((u,p)=>(u[p.name]=this.mapNode(p),p.op==="Const"&&n.push(u[p.name]),u),{}));let s=[],i=[];e.signature.inputArg.forEach(u=>{let[p]=mr(u.name),c={name:p,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:n3(u.type),type:"dtype"}},children:[]};c.signatureKey=u.name,s.push(c),r[p]=c}),Object.keys(r).forEach(u=>{let p=r[u];p.inputNames.forEach((c,d)=>{let[h,,f]=mr(c),m=r[h];if(m.outputs!=null){let g=m.outputs.indexOf(f);if(g!==-1){let x=`${h}:${g}`;p.inputNames[d]=x}}p.inputs.push(m),m.children.push(p)})});let o=e.ret;e.signature.outputArg.forEach(u=>{let[p,c]=mr(o[u.name]),d=r[p];d!=null&&(d.defaultOutput=c,i.push(d))});let l=this.mapArgsToSignature(e);return{nodes:r,inputs:s,outputs:i,weights:n,placeholders:a,signature:l}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,a)=>(t[a.name]=this.mapArgToTensorInfo(a),t),{}),outputs:e.signature.outputArg.reduce((t,a)=>(t[a.name]=this.mapArgToTensorInfo(a,e.ret),t),{})}}mapArgToTensorInfo(e,t){let a=e.name;return t!=null&&(a=t[a]),{name:a,dtype:e.type}}};function BP(e){let t=W().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 V4(e,t){let a=Array.isArray(e)?String.fromCharCode.apply(null,e):BP(e);return t?a:a.toLowerCase()}function o1(e,t,a,n=!1){let r=e[t];return r!=null?V4(r.s,n):a}function l1(e,t,a){let n=e[t];return n?n.b:a}function u1(e,t,a){let n=e[t]||{},r=n.i!=null?n.i:n.f!=null?n.f:a;return typeof r=="number"?r:parseInt(r,10)}function n3(e){switch(typeof e=="string"&&(e=wn[e]),e){case wn.DT_FLOAT:case wn.DT_HALF:return"float32";case wn.DT_INT32:case wn.DT_INT64:case wn.DT_INT8:case wn.DT_UINT8:return"int32";case wn.DT_BOOL:return"bool";case wn.DT_DOUBLE:return"float32";case wn.DT_STRING:return"string";default:return null}}function ex(e,t,a){let n=e[t];return n&&n.func?n.func.name:a}function d1(e,t,a){let n=e[t];return n&&n.type?n3(n.type):a}function p1(e,t,a){let n=e[t];return n&&n.list&&n.list.type?n.list.type.map(r=>n3(r)):a}function U4(e){if(!e.unknownRank)return e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function c1(e,t,a){let n=e[t];return n&&n.shape?U4(n.shape):a}function h1(e,t,a){let n=e[t];return n?((n.list.f&&n.list.f.length?n.list.f:n.list.i)||[]).map(r=>typeof r=="number"?r:parseInt(r,10)):a}function f1(e,t,a,n=!1){let r=e[t];return r&&r.list&&r.list.s?r.list.s.map(s=>V4(s,n)):a}function m1(e,t,a){let n=e[t];return n&&n.list&&n.list.shape?n.list.shape.map(r=>U4(r)):a}function g1(e,t,a){let n=e[t];return n&&n.list&&n.list.b?n.list.b:a}var WP=class{constructor(e,t,a){this.node=e,this.tensorMap=t,this.context=a,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(n=>this.getInput(n)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((n,r)=>(n[r]=this.getAttr(r),n),{}))}getInput(e){return ba(e,this.tensorMap,this.context)}getAttr(e,t){let a=this.node.rawAttrs[e];if(a.tensor!=null)return ba(e,this.tensorMap,this.context);if(a.i!=null||a.f!=null)return u1(this.node.rawAttrs,e,t);if(a.s!=null)return o1(this.node.rawAttrs,e,t);if(a.b!=null)return l1(this.node.rawAttrs,e,t);if(a.shape!=null)return c1(this.node.rawAttrs,e,t);if(a.type!=null)return d1(this.node.rawAttrs,e,t);if(a.list!=null){if(a.list.i!=null||a.list.f!=null)return h1(this.node.rawAttrs,e,t);if(a.list.s!=null)return f1(this.node.rawAttrs,e,t);if(a.list.shape!=null)return m1(this.node.rawAttrs,e,t);if(a.list.b!=null)return g1(this.node.rawAttrs,e,t);if(a.list.type!=null)return p1(this.node.rawAttrs,e,t)}return t}},Zt={};Xe(Zt,{OP_SCOPE_SUFFIX:()=>e2,abs:()=>qa,acos:()=>oy,acosh:()=>ly,add:()=>be,addN:()=>ch,all:()=>uy,any:()=>dy,argMax:()=>ar,argMin:()=>py,asin:()=>cy,asinh:()=>hy,atan:()=>fy,atan2:()=>my,atanh:()=>gy,avgPool:()=>b2,avgPool3d:()=>by,basicLSTMCell:()=>vy,batchNorm:()=>Qd,batchNorm2d:()=>wy,batchNorm3d:()=>ky,batchNorm4d:()=>Iy,batchToSpaceND:()=>v2,bincount:()=>w2,booleanMaskAsync:()=>a4,broadcastArgs:()=>Sy,broadcastTo:()=>sl,buffer:()=>Me,cast:()=>He,ceil:()=>Ty,clipByValue:()=>Cy,clone:()=>wa,complex:()=>br,concat:()=>at,concat1d:()=>Ny,concat2d:()=>ru,concat3d:()=>Ey,concat4d:()=>Ry,conv1d:()=>My,conv2d:()=>ep,conv2dTranspose:()=>_y,conv3d:()=>Py,conv3dTranspose:()=>Fy,cos:()=>Oy,cosh:()=>Dy,cosineWindow:()=>vh,cumprod:()=>zy,cumsum:()=>Ly,denseBincount:()=>By,depthToSpace:()=>Wy,depthwiseConv2d:()=>hh,diag:()=>Vy,dilation2d:()=>Uy,div:()=>me,divNoNan:()=>Gy,dot:()=>Hy,dropout:()=>o4,einsum:()=>jy,elu:()=>I2,enclosingPowerOfTwo:()=>J2,equal:()=>k2,erf:()=>qy,euclideanNorm:()=>Zy,exp:()=>Zr,expandDims:()=>Gt,expm1:()=>Yy,eye:()=>T2,fft:()=>yh,fill:()=>nr,floor:()=>C2,floorDiv:()=>Yd,fused:()=>Q2,gather:()=>N2,gatherND:()=>i4,greater:()=>np,greaterEqual:()=>E2,ifft:()=>hd,imag:()=>Zd,image:()=>ge,inTopKAsync:()=>l4,irfft:()=>X2,isFinite:()=>Jy,isInf:()=>Qy,isNaN:()=>eb,leakyRelu:()=>R2,less:()=>tb,lessEqual:()=>fh,linalg:()=>g4,linspace:()=>ab,localResponseNormalization:()=>nb,log:()=>cl,log1p:()=>M2,logSigmoid:()=>sb,logSoftmax:()=>ib,logSumExp:()=>_2,logicalAnd:()=>pd,logicalNot:()=>P2,logicalOr:()=>F2,logicalXor:()=>ob,losses:()=>x4,lowerBound:()=>lb,matMul:()=>st,max:()=>pa,maxPool:()=>O2,maxPool3d:()=>ub,maxPoolWithArgmax:()=>db,maximum:()=>D2,mean:()=>cd,meshgrid:()=>pb,min:()=>Kr,minimum:()=>z2,mirrorPad:()=>cb,mod:()=>su,moments:()=>hb,movingAverage:()=>n4,mul:()=>ae,multiRNNCell:()=>fb,multinomial:()=>mb,neg:()=>Xn,norm:()=>ap,notEqual:()=>L2,oneHot:()=>Nc,ones:()=>Wr,onesLike:()=>gb,op:()=>D,outerProduct:()=>xb,pad:()=>rr,pad1d:()=>Ab,pad2d:()=>yb,pad3d:()=>bb,pad4d:()=>vb,pool:()=>wb,pow:()=>pl,prelu:()=>W2,print:()=>r2,prod:()=>kb,raggedGather:()=>Ib,raggedRange:()=>Sb,raggedTensorToTensor:()=>Tb,rand:()=>Cb,randomGamma:()=>Nb,randomNormal:()=>G2,randomStandardNormal:()=>Eb,randomUniform:()=>H2,range:()=>hl,real:()=>dl,reciprocal:()=>Rb,relu:()=>rp,relu6:()=>j2,reshape:()=>J,reverse:()=>Yr,reverse1d:()=>Mb,reverse2d:()=>$b,reverse3d:()=>_b,reverse4d:()=>Pb,rfft:()=>bh,round:()=>q2,rsqrt:()=>Fb,scalar:()=>Fe,scatterND:()=>r4,searchSorted:()=>gh,selu:()=>Ob,separableConv2d:()=>Db,setdiff1dAsync:()=>zb,sigmoid:()=>Da,sign:()=>Lb,signal:()=>m4,sin:()=>Bb,sinh:()=>Wb,slice:()=>Pe,slice1d:()=>Vb,slice2d:()=>Ub,slice3d:()=>sp,slice4d:()=>xh,softmax:()=>Ah,softplus:()=>$2,spaceToBatchND:()=>B2,sparse:()=>A4,sparseToDense:()=>s4,spectral:()=>f4,split:()=>ka,sqrt:()=>Jn,square:()=>In,squaredDifference:()=>K2,squeeze:()=>_e,stack:()=>sa,step:()=>Z2,stridedSlice:()=>Gb,string:()=>y4,sub:()=>fe,sum:()=>tt,tan:()=>Hb,tanh:()=>Rc,tensor:()=>Be,tensor1d:()=>Ht,tensor2d:()=>Kn,tensor3d:()=>p2,tensor4d:()=>jb,tensor5d:()=>qb,tensor6d:()=>Xb,tile:()=>Gr,topk:()=>Kb,transpose:()=>Ws,truncatedNormal:()=>Zb,unique:()=>Yb,unsortedSegmentSum:()=>Jb,unstack:()=>Ta,upperBound:()=>Qb,variable:()=>e4,where:()=>Vs,whereAsync:()=>Y2,zeros:()=>fn,zerosLike:()=>Ka});var VP=(e,t,a,n=Zt)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[n.add(k("a",e,t,a),k("b",e,t,a))];case"AddN":return[n.addN(k("tensors",e,t,a))];case"FloorMod":case"Mod":return[n.mod(k("a",e,t,a),k("b",e,t,a))];case"Mul":return[n.mul(k("a",e,t,a),k("b",e,t,a))];case"RealDiv":case"Div":return[n.div(k("a",e,t,a),k("b",e,t,a))];case"DivNoNan":return[n.divNoNan(k("a",e,t,a),k("b",e,t,a))];case"FloorDiv":return[n.floorDiv(k("a",e,t,a),k("b",e,t,a))];case"Sub":return[n.sub(k("a",e,t,a),k("b",e,t,a))];case"Minimum":return[n.minimum(k("a",e,t,a),k("b",e,t,a))];case"Maximum":return[n.maximum(k("a",e,t,a),k("b",e,t,a))];case"Pow":return[n.pow(k("a",e,t,a),k("b",e,t,a))];case"SquaredDifference":return[n.squaredDifference(k("a",e,t,a),k("b",e,t,a))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},UP=(e,t,a,n=Zt)=>{switch(e.op){case"Abs":case"ComplexAbs":return[n.abs(k("x",e,t,a))];case"Acos":return[n.acos(k("x",e,t,a))];case"Acosh":return[n.acosh(k("x",e,t,a))];case"Asin":return[n.asin(k("x",e,t,a))];case"Asinh":return[n.asinh(k("x",e,t,a))];case"Atan":return[n.atan(k("x",e,t,a))];case"Atan2":return[n.atan2(k("x",e,t,a),k("y",e,t,a))];case"Atanh":return[n.atanh(k("x",e,t,a))];case"Ceil":return[n.ceil(k("x",e,t,a))];case"Complex":return[n.complex(k("real",e,t,a),k("imag",e,t,a))];case"Cos":return[n.cos(k("x",e,t,a))];case"Cosh":return[n.cosh(k("x",e,t,a))];case"Elu":return[n.elu(k("x",e,t,a))];case"Erf":return[n.erf(k("x",e,t,a))];case"Exp":return[n.exp(k("x",e,t,a))];case"Expm1":return[n.expm1(k("x",e,t,a))];case"Floor":return[n.floor(k("x",e,t,a))];case"Log":return[n.log(k("x",e,t,a))];case"Log1p":return[n.log1p(k("x",e,t,a))];case"Imag":return[n.imag(k("x",e,t,a))];case"Neg":return[n.neg(k("x",e,t,a))];case"Reciprocal":return[n.reciprocal(k("x",e,t,a))];case"Real":return[n.real(k("x",e,t,a))];case"Relu":return[n.relu(k("x",e,t,a))];case"Round":return[n.round(k("x",e,t,a))];case"Selu":return[n.selu(k("x",e,t,a))];case"Sigmoid":return[n.sigmoid(k("x",e,t,a))];case"Sin":return[n.sin(k("x",e,t,a))];case"Sign":return[n.sign(k("x",e,t,a))];case"Sinh":return[n.sinh(k("x",e,t,a))];case"Softplus":return[n.softplus(k("x",e,t,a))];case"Sqrt":return[n.sqrt(k("x",e,t,a))];case"Square":return[n.square(k("x",e,t,a))];case"Tanh":return[n.tanh(k("x",e,t,a))];case"Tan":return[n.tan(k("x",e,t,a))];case"ClipByValue":return[n.clipByValue(k("x",e,t,a),k("clipValueMin",e,t,a),k("clipValueMax",e,t,a))];case"Relu6":return[n.relu6(k("x",e,t,a))];case"Rsqrt":return[n.rsqrt(ba(e.inputNames[0],t,a))];case"Prod":return[n.prod(k("x",e,t,a),k("axes",e,t,a))];case"LeakyRelu":return[n.leakyRelu(k("x",e,t,a),k("alpha",e,t,a))];case"Prelu":return[n.prelu(k("x",e,t,a),k("alpha",e,t,a))];case"IsNan":return[n.isNaN(ba(e.inputNames[0],t,a))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function kn(e,t,a=""){if(!(typeof e=="number"||typeof t=="number")){v.assert(e.length===t.length,()=>a+` Shapes ${e} and ${t} must match`);for(let n=0;n<e.length;n++){let r=e[n],s=t[n];v.assert(r<0||s<0||r===s,()=>a+` Shapes ${e} and ${t} must match`)}}}function tx(e){return!(typeof e=="number"||e.some(t=>t<0))}function Vu(e,t,a){let n=x1(e,a),r=!tx(n);if(r&&t.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${n}`);if(r&&t.forEach(s=>{n=x1(s.shape,n)}),!tx(n))throw new Error(`Non-fully-defined elementShape: ${n}`);return n}function x1(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 a=[];for(let n=0;n<e.length;++n){let r=e[n],s=t[n];if(r>=0&&s>=0&&r!==s)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);a[n]=r>=0?r:s}return a}var GP=class{constructor(e,t,a,n,r,s,i){this.name=e,this.dtype=t,this.maxSize=a,this.elementShape=n,this.identicalElementShapes=r,this.dynamicSize=s,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=Fe(0),On(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 a=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),kn(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),a.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(a.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);a.tensor=t,On(t),a.written=!0,this.tensors[e]=a}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((a,n)=>this.write(a,t[n]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let n=0;n<this.size();n++)e.push(n)}if(e.length===0)return Be([],[0].concat(this.elementShape));let a=this.readMany(e);return kn(this.elementShape,a[0].shape,"TensorArray shape mismatch: "),sa(a,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return Be([],[0].concat(this.elementShape));let t=[];for(let n=0;n<this.size();n++)t.push(n);let a=this.readMany(t);return kn(this.elementShape,a[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${a[0].shape})`),at(a,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);let a=Math.max(...e);if(!this.dynamicSize&&a>=this.maxSize)throw new Error(`Max index must be < array size (${a} vs. ${this.maxSize})`);this.writeMany(e,Ta(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 a=0,n=e.map(o=>(a+=o,a));if(a!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${a}, 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=a===0?0:t.size/a,s=[];$e(()=>{t=J(t,[1,a,r]);for(let o=0;o<e.length;++o){let l=[0,o===0?0:n[o-1],0],u=[1,e[o],r];s[o]=J(Pe(t,l,u),this.elementShape)}return s});let i=[];for(let o=0;o<e.length;o++)i[o]=o;this.writeMany(i,s)}},fl=class{constructor(e,t,a,n=-1){this.tensors=e,this.elementShape=t,this.elementDtype=a,e!=null&&e.forEach(r=>{if(a!==r.dtype)throw new Error(`Invalid data types; op elements ${a}, but list elements ${r.dtype}`);kn(t,r.shape,"TensorList shape mismatch: "),On(r)}),this.idTensor=Fe(0),this.maxNumElements=n,On(this.idTensor)}get id(){return this.idTensor.id}copy(){return new fl([...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,a=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(a!==-1&&this.tensors.length!==a)throw new Error(`Operation expected a list with ${a} elements but got a list with ${this.tensors.length} elements.`);kn(e,this.elementShape,"TensorList shape mismatch: ");let n=Vu(this.elementShape,this.tensors,e);return $e(()=>{let r=this.tensors.map(s=>J(s,n));return sa(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 a=Vu(this.elementShape,this.tensors,e),n=this.tensors.pop();return n.kept=!1,kn(n.shape,e,"TensorList shape mismatch: "),J(n,a)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(kn(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");On(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 fl([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let a=0;a<Math.min(this.tensors.length,e);++a)t.tensors[a]=this.tensors[a];return t}getItem(e,t,a){if(a!==this.elementDtype)throw new Error(`Invalid data types; op elements ${a}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);kn(this.tensors[e].shape,t,"TensorList shape mismatch: ");let n=Vu(this.elementShape,this.tensors,t);return J(this.tensors[e],n)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);kn(this.elementShape,t.shape,"TensorList shape mismatch: "),On(t),this.tensors[e]!=null&&(this.tensors[e].kept=!1),this.tensors[e]=t}gather(e,t,a){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);kn(this.elementShape,a,"TensorList shape mismatch: "),e=e.slice(0,this.size());let n=Vu(this.elementShape,this.tensors,a);return e.length===0?Be([],[0].concat(n)):$e(()=>{let r=e.map(s=>J(this.tensors[s],n));return sa(r,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);kn(this.elementShape,t,"TensorList shape mismatch: ");let a=Vu(this.elementShape,this.tensors,t);return this.size()===0?Be([],[0].concat(a)):$e(()=>{let n=this.tensors.map(r=>J(r,a));return at(n,0)})}};function HP(e,t,a){let n=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==a)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${a}`);let r=e.shape.slice(1);kn(r,t,"TensorList shape mismatch: ");let s=Ta(e);return new fl(s,t,n)}function jP(e,t,a,n){return new fl([],e,t,n)}function qP(e,t,a,n){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);let r=Math.max(...t);if(n!=null&&n!==-1&&r>=n)throw new Error(`Max index must be < array size (${r} vs. ${n})`);let s=new fl([],a,e.dtype,n),i=Ta(e,0);return t.forEach((o,l)=>{s.setItem(o,i[l])}),s}function XP(e,t,a){let n=0,r=t.map(p=>(n+=p,n));if(n!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${n}, and tensor's shape is: ${e.shape}`);let s=e.shape.slice(1),i=x1(s,a),o=n===0?0:e.size/n,l=$e(()=>{let p=[];e=J(e,[1,n,o]);for(let c=0;c<t.length;++c){let d=[0,c===0?0:r[c-1],0],h=[1,t[c],o];p[c]=J(Pe(e,d,h),i)}return e.dispose(),p}),u=new fl([],a,e.dtype,t.length);for(let p=0;p<l.length;p++)u.setItem(p,l[p]);return u}var KP=async(e,t,a)=>{switch(e.op){case"If":case"StatelessIf":{let n=k("thenBranch",e,t,a),r=k("elseBranch",e,t,a),s=k("cond",e,t,a),i=k("args",e,t,a);return(await s.data())[0]?a.functionMap[n].executeFunctionAsync(i,a.tensorArrayMap,a.tensorListMap):a.functionMap[r].executeFunctionAsync(i,a.tensorArrayMap,a.tensorListMap)}case"While":case"StatelessWhile":{let n=k("body",e,t,a),r=k("cond",e,t,a),s=k("args",e,t,a),i=await a.functionMap[r].executeFunctionAsync(s,a.tensorArrayMap,a.tensorListMap),o=s.map(p=>p.id),l=await i[0].data();i.forEach(p=>{!p.kept&&o.indexOf(p.id)===-1&&p.dispose()});let u=s;for(;l[0];){let p=u;u=await a.functionMap[n].executeFunctionAsync(u,a.tensorArrayMap,a.tensorListMap);let c=u.map(h=>h.id);p.forEach(h=>{!h.kept&&o.indexOf(h.id)===-1&&c.indexOf(h.id)===-1&&h.dispose()});let d=await a.functionMap[r].executeFunctionAsync(u,a.tensorArrayMap,a.tensorListMap);l=await d[0].data(),d.forEach(h=>{!h.kept&&o.indexOf(h.id)===-1&&c.indexOf(h.id)===-1&&h.dispose()})}return u}case"LoopCond":{let n=k("pred",e,t,a);return[gr(n)]}case"Switch":{let n=k("pred",e,t,a),r=k("data",e,t,a);return r.kept||(r=gr(r)),(await n.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{let n=e.inputNames.find(r=>ba(r,t,a)!==void 0);if(n){let r=ba(n,t,a);return[gr(r)]}return}case"Enter":{let n=k("frameName",e,t,a),r=k("tensor",e,t,a);return a.enterFrame(n),[gr(r)]}case"Exit":{let n=k("tensor",e,t,a);return a.exitFrame(),[gr(n)]}case"NextIteration":{let n=k("tensor",e,t,a);return a.nextIteration(),[gr(n)]}case"TensorArrayV3":{let n=k("size",e,t,a),r=k("dtype",e,t,a),s=k("elementShape",e,t,a),i=k("dynamicSize",e,t,a),o=k("clearAfterRead",e,t,a),l=k("identicalElementShapes",e,t,a),u=k("name",e,t,a),p=new GP(u,r,n,s,l,i,o);return a.addTensorArray(p),[p.idTensor,Fe(1)]}case"TensorArrayWriteV3":{let n=k("tensorArrayId",e,t,a),r=k("index",e,t,a),s=k("tensor",e,t,a),i=a.getTensorArray(n.id);return i.write(r,s),[i.idTensor]}case"TensorArrayReadV3":{let n=k("tensorArrayId",e,t,a),r=k("index",e,t,a);return[a.getTensorArray(n.id).read(r)]}case"TensorArrayGatherV3":{let n=k("tensorArrayId",e,t,a),r=k("indices",e,t,a),s=k("dtype",e,t,a);return[a.getTensorArray(n.id).gather(r,s)]}case"TensorArrayScatterV3":{let n=k("tensorArrayId",e,t,a),r=k("indices",e,t,a),s=k("tensor",e,t,a),i=a.getTensorArray(n.id);return i.scatter(r,s),[i.idTensor]}case"TensorArrayConcatV3":{let n=k("tensorArrayId",e,t,a),r=a.getTensorArray(n.id),s=k("dtype",e,t,a);return[r.concat(s)]}case"TensorArraySplitV3":{let n=k("tensorArrayId",e,t,a),r=k("tensor",e,t,a),s=k("lengths",e,t,a),i=a.getTensorArray(n.id);return i.split(s,r),[i.idTensor]}case"TensorArraySizeV3":{let n=k("tensorArrayId",e,t,a),r=a.getTensorArray(n.id);return[Fe(r.size(),"int32")]}case"TensorArrayCloseV3":{let n=k("tensorArrayId",e,t,a),r=a.getTensorArray(n.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{let n=k("tensorListId",e,t,a),r=k("index",e,t,a),s=k("tensor",e,t,a),i=a.getTensorList(n.id);return i.setItem(r,s),[i.idTensor]}case"TensorListGetItem":{let n=k("tensorListId",e,t,a),r=k("index",e,t,a),s=k("elementShape",e,t,a),i=k("elementDType",e,t,a);return[a.getTensorList(n.id).getItem(r,s,i)]}case"TensorListScatterV2":case"TensorListScatter":{let n=k("indices",e,t,a),r=k("tensor",e,t,a),s=k("elementShape",e,t,a),i=k("numElements",e,t,a),o=qP(r,n,s,i);return a.addTensorList(o),[o.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let n=k("elementShape",e,t,a),r=k("elementDType",e,t,a),s;e.op==="TensorListReserve"?s="numElements":s="maxNumElements";let i=k(s,e,t,a),o=e.op==="TensorListReserve"?-1:i,l=jP(n,r,i,o);return a.addTensorList(l),[l.idTensor]}case"TensorListGather":{let n=k("tensorListId",e,t,a),r=k("indices",e,t,a),s=k("elementShape",e,t,a),i=k("elementDType",e,t,a);return[a.getTensorList(n.id).gather(r,i,s)]}case"TensorListStack":{let n=k("tensorListId",e,t,a),r=k("elementShape",e,t,a),s=k("elementDType",e,t,a),i=k("numElements",e,t,a);return[a.getTensorList(n.id).stack(r,s,i)]}case"TensorListFromTensor":{let n=k("tensor",e,t,a),r=k("elementShape",e,t,a),s=k("elementDType",e,t,a),i=HP(n,r,s);return a.addTensorList(i),[i.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{let n=k("tensorListId",e,t,a),r=a.getTensorList(n.id),s=k("dtype",e,t,a),i=k("elementShape",e,t,a);return[r.concat(s,i)]}case"TensorListPushBack":{let n=k("tensorListId",e,t,a),r=k("tensor",e,t,a),s=a.getTensorList(n.id);return s.pushBack(r),[s.idTensor]}case"TensorListPopBack":{let n=k("tensorListId",e,t,a),r=k("elementShape",e,t,a),s=k("elementDType",e,t,a);return[a.getTensorList(n.id).popBack(r,s)]}case"TensorListSplit":{let n=k("tensor",e,t,a),r=k("elementShape",e,t,a),s=k("lengths",e,t,a),i=XP(n,s,r);return a.addTensorList(i),[i.idTensor]}case"TensorListLength":{let n=k("tensorListId",e,t,a),r=a.getTensorList(n.id);return[Fe(r.size(),"int32")]}case"TensorListResize":{let n=k("tensorListId",e,t,a),r=k("size",e,t,a),s=a.getTensorList(n.id).resize(r);return a.addTensorList(s),[s.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function ax(e,t,a){let[n,r]=k("fusedOps",e,t,a),s=n==="biasadd",i=!s,o=r==="prelu",l=n==="fusedbatchnorm",u=k("numArgs",e,t,a);if(s){if(o&&u!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&s&&u!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");let p=k("strides",e,t,a),c=mc(e,t,a),d=k("dataFormat",e,t,a).toUpperCase(),h=k("dilations",e,t,a),[f,m]=k("args",e,t,a);i&&(m=f,f=void 0);let g=k("leakyreluAlpha",e,t,a);return{stride:p,pad:c,dataFormat:d,dilations:h,biasArg:f,preluArg:m,activationFunc:r,leakyreluAlpha:g}}var ZP=(e,t,a,n=Zt)=>{switch(e.op){case"Conv1D":{let r=k("stride",e,t,a),s=k("pad",e,t,a),i=k("dataFormat",e,t,a).toUpperCase(),o=k("dilation",e,t,a);return[n.conv1d(k("x",e,t,a),k("filter",e,t,a),r,s,i,o)]}case"Conv2D":{let r=k("strides",e,t,a),s=mc(e,t,a),i=k("dataFormat",e,t,a).toUpperCase(),o=k("dilations",e,t,a);return[n.conv2d(k("x",e,t,a),k("filter",e,t,a),[r[1],r[2]],s,i,[o[1],o[2]])]}case"_FusedConv2D":{let{stride:r,pad:s,dataFormat:i,dilations:o,biasArg:l,preluArg:u,activationFunc:p,leakyreluAlpha:c}=ax(e,t,a);return[n.fused.conv2d({x:k("x",e,t,a),filter:k("filter",e,t,a),strides:[r[1],r[2]],pad:s,dataFormat:i,dilations:[o[1],o[2]],bias:l,activation:p,preluActivationWeights:u,leakyreluAlpha:c})]}case"FusedDepthwiseConv2dNative":{let{stride:r,pad:s,dataFormat:i,dilations:o,biasArg:l,preluArg:u,activationFunc:p,leakyreluAlpha:c}=ax(e,t,a);return[n.fused.depthwiseConv2d({x:k("x",e,t,a),filter:k("filter",e,t,a),strides:[r[1],r[2]],pad:s,dataFormat:i,dilations:[o[1],o[2]],bias:l,activation:p,preluActivationWeights:u,leakyreluAlpha:c})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let r=k("outputShape",e,t,a),s=k("strides",e,t,a),i=mc(e,t,a);return[n.conv2dTranspose(k("x",e,t,a),k("filter",e,t,a),r,[s[1],s[2]],i)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let r=k("strides",e,t,a),s=mc(e,t,a),i=k("dilations",e,t,a),o=k("dataFormat",e,t,a).toUpperCase();return[n.depthwiseConv2d(k("input",e,t,a),k("filter",e,t,a),[r[1],r[2]],s,o,[i[1],i[2]])]}case"Conv3D":{let r=k("strides",e,t,a),s=k("pad",e,t,a),i=k("dataFormat",e,t,a).toUpperCase(),o=k("dilations",e,t,a);return[n.conv3d(k("x",e,t,a),k("filter",e,t,a),[r[1],r[2],r[3]],s,i,[o[1],o[2],o[3]])]}case"AvgPool":{let r=k("strides",e,t,a),s=k("pad",e,t,a),i=k("kernelSize",e,t,a);return[n.avgPool(k("x",e,t,a),[i[1],i[2]],[r[1],r[2]],s)]}case"MaxPool":{let r=k("strides",e,t,a),s=k("pad",e,t,a),i=k("kernelSize",e,t,a);return[n.maxPool(k("x",e,t,a),[i[1],i[2]],[r[1],r[2]],s)]}case"MaxPoolWithArgmax":{let r=k("strides",e,t,a),s=k("pad",e,t,a),i=k("kernelSize",e,t,a),o=k("includeBatchInIndex",e,t,a),{result:l,indexes:u}=n.maxPoolWithArgmax(k("x",e,t,a),[i[1],i[2]],[r[1],r[2]],s,o);return[l,u]}case"AvgPool3D":{let r=k("strides",e,t,a),s=k("pad",e,t,a),i=k("kernelSize",e,t,a);return[n.avgPool3d(k("x",e,t,a),[i[1],i[2],i[3]],[r[1],r[2],r[3]],s)]}case"MaxPool3D":{let r=k("strides",e,t,a),s=k("pad",e,t,a),i=k("kernelSize",e,t,a);return[n.maxPool3d(k("x",e,t,a),[i[1],i[2],i[3]],[r[1],r[2],r[3]],s)]}case"Dilation2D":{let r=k("strides",e,t,a),s=k("pad",e,t,a),i=k("dilations",e,t,a),o=r[1],l=r[2],u=i[1],p=i[2];return[n.dilation2d(k("x",e,t,a),k("filter",e,t,a),[o,l],s,[u,p],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},YP=(e,t,a,n=Zt)=>{switch(e.op){case"Fill":{let r=k("shape",e,t,a),s=k("dtype",e,t,a),i=k("value",e,t,a);return[n.fill(r,i,s)]}case"LinSpace":{let r=k("start",e,t,a),s=k("stop",e,t,a),i=k("num",e,t,a);return[n.linspace(r,s,i)]}case"Multinomial":{let r=k("logits",e,t,a),s=k("numSamples",e,t,a),i=k("seed",e,t,a);return[n.multinomial(r,s,i)]}case"OneHot":{let r=k("indices",e,t,a),s=k("depth",e,t,a),i=k("onValue",e,t,a),o=k("offValue",e,t,a),l=k("dtype",e,t,a);return[n.oneHot(r,s,i,o,l)]}case"Ones":return[n.ones(k("shape",e,t,a),k("dtype",e,t,a))];case"OnesLike":return[n.onesLike(k("x",e,t,a))];case"RandomStandardNormal":return[n.randomStandardNormal(k("shape",e,t,a),k("dtype",e,t,a),k("seed",e,t,a))];case"RandomUniform":return[n.randomUniform(k("shape",e,t,a),k("minval",e,t,a),k("maxval",e,t,a),k("dtype",e,t,a))];case"Range":{let r=k("start",e,t,a),s=k("stop",e,t,a),i=k("step",e,t,a);return[n.range(r,s,i,k("dtype",e,t,a))]}case"TruncatedNormal":{let r=k("shape",e,t,a),s=k("mean",e,t,a),i=k("stdDev",e,t,a),o=k("seed",e,t,a);return[n.truncatedNormal(r,s,i,k("dtype",e,t,a),o)]}case"Zeros":return[n.zeros(k("shape",e,t,a),k("dtype",e,t,a))];case"ZerosLike":return[n.zerosLike(k("x",e,t,a))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Dm(e,t,a){let n=k("boxes",e,t,a),r=k("scores",e,t,a),s=k("maxOutputSize",e,t,a),i=k("iouThreshold",e,t,a),o=k("scoreThreshold",e,t,a),l=k("softNmsSigma",e,t,a);return{boxes:n,scores:r,maxOutputSize:s,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}}var JP=async(e,t,a,n,r=Zt)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:s,scores:i,maxOutputSize:o,iouThreshold:l,scoreThreshold:u,softNmsSigma:p}=Dm(e,t,a),c=await r.image.nonMaxSuppressionWithScoreAsync(s,i,o,l,u,p);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:s,scores:i,maxOutputSize:o,iouThreshold:l,scoreThreshold:u}=Dm(e,t,a),p=k("padToMaxOutputSize",e,t,a),c=await r.image.nonMaxSuppressionPaddedAsync(s,i,o,l,u,p);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:s,scores:i,maxOutputSize:o,iouThreshold:l,scoreThreshold:u}=Dm(e,t,a);return[await r.image.nonMaxSuppressionAsync(s,i,o,l,u)]}case"Where":{let s=r.cast(k("condition",e,t,a),"bool"),i=[await r.whereAsync(s)];return s.dispose(),i}case"ListDiff":return r.setdiff1dAsync(k("x",e,t,a),k("y",e,t,a));default:throw TypeError(`Node type ${e.op} is not implemented`)}},QP=(e,t,a,n=Zt)=>{switch(e.op){case"LowerBound":{let r=k("sortedSequence",e,t,a),s=k("values",e,t,a);return[n.lowerBound(r,s)]}case"TopKV2":{let r=k("x",e,t,a),s=k("k",e,t,a),i=k("sorted",e,t,a),o=n.topk(r,s,i);return[o.values,o.indices]}case"UpperBound":{let r=k("sortedSequence",e,t,a),s=k("values",e,t,a);return[n.upperBound(r,s)]}case"Unique":{let r=k("x",e,t,a),s=n.unique(r);return[s.values,s.indices]}case"UniqueV2":{let r=k("x",e,t,a),s=k("axis",e,t,a),i=n.unique(r,s);return[i.values,i.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},eF=(e,t,a,n=Zt)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let r=k("default",e,t,a);return[ba(e.name,t,a)||r];case"Placeholder":return[ba(e.name,t,a)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let p=k("x",e,t,a);return[gr(p)]}case"IdentityN":return k("x",e,t,a).map(p=>gr(p));case"Snapshot":let s=k("x",e,t,a);return[gr(s)];case"Shape":return[n.tensor1d(k("x",e,t,a).shape,"int32")];case"ShapeN":return k("x",e,t,a).map(p=>n.tensor1d(p.shape));case"Size":return[n.scalar(k("x",e,t,a).size,"int32")];case"Rank":return[n.scalar(k("x",e,t,a).rank,"int32")];case"NoOp":return[n.scalar(1)];case"Print":let i=k("x",e,t,a),o=k("data",e,t,a),l=k("message",e,t,a),u=k("summarize",e,t,a);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(l);for(let p=0;p<o.length;p++)console.log(Array.prototype.slice.call(o[p].dataSync()).slice(0,u));return[i];default:throw TypeError(`Node type ${e.op} is not implemented`)}},tF=class{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Fe(0),this.tensorMap=new Map,On(this.handle)}get id(){return this.handle.id}clearAndClose(){this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Fe(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);let a=await e.data();return this.tensorMap.forEach(n=>n.dispose()),this.tensorMap.clear(),$e(()=>{let n=Ta(t),r=a.length,s=n.length;v.assert(r===s,()=>`The number of elements doesn't match, keys has ${r} elements, the values has ${s} elements.`);for(let i=0;i<r;i++){let o=a[i],l=n[i];On(l),this.tensorMap.set(o,l)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);let a=await e.data();return $e(()=>{let n=[];for(let r=0;r<a.length;r++){let s=a[r],i=this.findWithDefault(s,t);n.push(i)}return sa(n)})}findWithDefault(e,t){let a=this.tensorMap.get(e);return a!=null?a:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}},aF=async(e,t,a,n)=>{switch(e.op){case"HashTable":case"HashTableV2":{let r=n.getHashTableHandleByName(e.name);if(r!=null)return[r];{let s=k("keyDType",e,t,a),i=k("valueDType",e,t,a),o=new tF(s,i);return n.addHashTable(e.name,o),[o.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{let r=k("tableHandle",e,t,a,n),s=k("keys",e,t,a),i=k("values",e,t,a);return[await n.getHashTableById(r.id).import(s,i)]}case"LookupTableFind":case"LookupTableFindV2":{let r=k("tableHandle",e,t,a,n),s=k("keys",e,t,a),i=k("defaultValue",e,t,a);return[await n.getHashTableById(r.id).find(s,i)]}case"LookupTableSize":case"LookupTableSizeV2":{let r=k("tableHandle",e,t,a,n);return[n.getHashTableById(r.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},nF=(e,t,a,n=Zt)=>{switch(e.op){case"ResizeBilinear":{let r=k("images",e,t,a),s=k("size",e,t,a),i=k("alignCorners",e,t,a),o=k("halfPixelCenters",e,t,a);return[n.image.resizeBilinear(r,[s[0],s[1]],i,o)]}case"ResizeNearestNeighbor":{let r=k("images",e,t,a),s=k("size",e,t,a),i=k("alignCorners",e,t,a),o=k("halfPixelCenters",e,t,a);return[n.image.resizeNearestNeighbor(r,[s[0],s[1]],i,o)]}case"CropAndResize":{let r=k("image",e,t,a),s=k("boxes",e,t,a),i=k("boxInd",e,t,a),o=k("cropSize",e,t,a),l=k("method",e,t,a),u=k("extrapolationValue",e,t,a);return[n.image.cropAndResize(r,s,i,o,l,u)]}case"ImageProjectiveTransformV3":{let r=k("images",e,t,a),s=k("transforms",e,t,a),i=k("outputShape",e,t,a),o=k("fillValue",e,t,a),l=k("interpolation",e,t,a),u=k("fillMode",e,t,a);return[n.image.transform(r,s,l.toLowerCase(),u.toLowerCase(),o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},rF=(e,t,a,n=Zt)=>{switch(e.op){case"Equal":return[n.equal(k("a",e,t,a),k("b",e,t,a))];case"NotEqual":return[n.notEqual(k("a",e,t,a),k("b",e,t,a))];case"Greater":return[n.greater(k("a",e,t,a),k("b",e,t,a))];case"GreaterEqual":return[n.greaterEqual(k("a",e,t,a),k("b",e,t,a))];case"Less":return[n.less(k("a",e,t,a),k("b",e,t,a))];case"LessEqual":return[n.lessEqual(k("a",e,t,a),k("b",e,t,a))];case"LogicalAnd":return[n.logicalAnd(k("a",e,t,a),k("b",e,t,a))];case"LogicalNot":return[n.logicalNot(k("a",e,t,a))];case"LogicalOr":return[n.logicalOr(k("a",e,t,a),k("b",e,t,a))];case"Select":case"SelectV2":return[n.where(k("condition",e,t,a),k("a",e,t,a),k("b",e,t,a))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},sF=(e,t,a,n=Zt)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[n.matMul(k("a",e,t,a),k("b",e,t,a),k("transposeA",e,t,a),k("transposeB",e,t,a))];case"Einsum":return[n.einsum(k("equation",e,t,a),...k("tensors",e,t,a))];case"Transpose":return[n.transpose(k("x",e,t,a),k("perm",e,t,a))];case"_FusedMatMul":let[r,s]=k("fusedOps",e,t,a),i=r==="biasadd",o=s==="prelu",l=k("numArgs",e,t,a),u=k("leakyreluAlpha",e,t,a);if(i){if(o&&l!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&l!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[p,c]=k("args",e,t,a);return[n.fused.matMul({a:k("a",e,t,a),b:k("b",e,t,a),transposeA:k("transposeA",e,t,a),transposeB:k("transposeB",e,t,a),bias:p,activation:s,preluActivationWeights:c,leakyreluAlpha:u})];default:throw TypeError(`Node type ${e.op} is not implemented`)}},iF=(e,t,a,n=Zt)=>{switch(e.op){case"EuclideanNorm":return[n.euclideanNorm(k("x",e,t,a),k("axis",e,t,a),k("keepDims",e,t,a))];case"FusedBatchNorm":case"FusedBatchNormV2":return[n.batchNorm(k("x",e,t,a),k("mean",e,t,a),k("variance",e,t,a),k("offset",e,t,a),k("scale",e,t,a),k("epsilon",e,t,a))];case"FusedBatchNormV3":return[n.batchNorm(k("x",e,t,a),k("mean",e,t,a),k("variance",e,t,a),k("offset",e,t,a),k("scale",e,t,a),k("epsilon",e,t,a))];case"LRN":return[n.localResponseNormalization(k("x",e,t,a),k("radius",e,t,a),k("bias",e,t,a),k("alpha",e,t,a),k("beta",e,t,a))];case"Softmax":return[n.softmax(k("x",e,t,a))];case"LogSoftmax":return[n.logSoftmax(k("x",e,t,a))];case"SparseToDense":return[n.sparseToDense(k("sparseIndices",e,t,a),k("outputShape",e,t,a),k("sparseValues",e,t,a),k("defaultValue",e,t,a))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},oF=(e,t,a,n=Zt)=>{switch(e.op){case"RaggedGather":{let{outputNestedSplits:r,outputDenseValues:s}=n.raggedGather(k("paramsNestedSplits",e,t,a),k("paramsDenseValues",e,t,a),k("indices",e,t,a),k("outputRaggedRank",e,t,a));return r.concat(s)}case"RaggedRange":{let{rtNestedSplits:r,rtDenseValues:s}=n.raggedRange(k("starts",e,t,a),k("limits",e,t,a),k("splits",e,t,a));return[r,s]}case"RaggedTensorToTensor":return[n.raggedTensorToTensor(k("shape",e,t,a),k("values",e,t,a),k("defaultValue",e,t,a),k("rowPartitionTensors",e,t,a),k("rowPartitionTypes",e,t,a))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},lF=(e,t,a,n=Zt)=>{switch(e.op){case"Max":{let o=k("axis",e,t,a),l=k("keepDims",e,t,a);return[n.max(k("x",e,t,a),o,l)]}case"Mean":{let o=k("axis",e,t,a),l=k("keepDims",e,t,a);return[n.mean(k("x",e,t,a),o,l)]}case"Min":{let o=k("axis",e,t,a),l=k("keepDims",e,t,a);return[n.min(k("x",e,t,a),o,l)]}case"Sum":{let o=k("axis",e,t,a),l=k("keepDims",e,t,a);return[n.sum(k("x",e,t,a),o,l)]}case"All":{let o=k("axis",e,t,a),l=k("keepDims",e,t,a);return[n.all(k("x",e,t,a),o,l)]}case"Any":{let o=k("axis",e,t,a),l=k("keepDims",e,t,a);return[n.any(k("x",e,t,a),o,l)]}case"ArgMax":{let o=k("axis",e,t,a);return[n.argMax(k("x",e,t,a),o)]}case"ArgMin":{let o=k("axis",e,t,a);return[n.argMin(k("x",e,t,a),o)]}case"Prod":{let o=k("axis",e,t,a),l=k("keepDims",e,t,a);return[n.prod(k("x",e,t,a),o,l)]}case"Cumprod":{let o=k("axis",e,t,a),l=k("exclusive",e,t,a),u=k("reverse",e,t,a);return[n.cumprod(k("x",e,t,a),o,l,u)]}case"Cumsum":{let o=k("axis",e,t,a),l=k("exclusive",e,t,a),u=k("reverse",e,t,a);return[n.cumsum(k("x",e,t,a),o,l,u)]}case"Bincount":let r=k("x",e,t,a),s=k("weights",e,t,a),i=k("size",e,t,a);return[n.bincount(r,s,i)];case"DenseBincount":{let o=k("x",e,t,a),l=k("weights",e,t,a),u=k("size",e,t,a),p=k("binaryOutput",e,t,a);return[n.denseBincount(o,l,u,p)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},uF=(e,t,a,n=Zt)=>{switch(e.op){case"ConcatV2":case"Concat":{let r=k("n",e,t,a),s=k("axis",e,t,a),i=k("tensors",e,t,a);return i=i.slice(0,r),[n.concat(i,s)]}case"Gather":{let r=k("x",e,t,a),s=k("indices",e,t,a);return[n.gather(r,n.cast(s,"int32"),0)]}case"GatherV2":{let r=k("axis",e,t,a),s=k("batchDims",e,t,a),i=k("x",e,t,a),o=k("indices",e,t,a);return[n.gather(i,n.cast(o,"int32"),r,s)]}case"Reverse":{let r=k("dims",e,t,a),s=[];for(let o=0;o<r.length;o++)r[o]&&s.push(o);let i=k("x",e,t,a);return[n.reverse(i,s)]}case"ReverseV2":{let r=k("axis",e,t,a),s=k("x",e,t,a);return[n.reverse(s,r)]}case"Slice":{let r=k("begin",e,t,a),s=k("size",e,t,a);return[n.slice(k("x",e,t,a),r,s)]}case"StridedSlice":{let r=k("begin",e,t,a),s=k("end",e,t,a),i=k("strides",e,t,a),o=k("beginMask",e,t,a),l=k("endMask",e,t,a),u=k("ellipsisMask",e,t,a),p=k("newAxisMask",e,t,a),c=k("shrinkAxisMask",e,t,a),d=k("x",e,t,a);return[n.stridedSlice(d,r,s,i,o,l,u,p,c)]}case"Pack":return $e(()=>{let r=k("axis",e,t,a),s=k("tensors",e,t,a),i=s[0].shape,o=n.squeeze(s[0]).shape,l=s.map(u=>{let p=v.arraysEqual(u.shape,i);if(!p&&!v.arraysEqual(n.squeeze(u).shape,o))throw new Error("the input tensors shape does not match");return p?u:n.reshape(u,i)});return[n.stack(l,r)]});case"Unpack":{let r=k("axis",e,t,a),s=k("tensor",e,t,a);return n.unstack(s,r)}case"Tile":{let r=k("reps",e,t,a);return[n.tile(k("x",e,t,a),r)]}case"Split":case"SplitV":{let r=k("axis",e,t,a),s=k("numOrSizeSplits",e,t,a),i=k("x",e,t,a);return n.split(i,s,r)}case"ScatterNd":{let r=k("indices",e,t,a),s=k("values",e,t,a),i=k("shape",e,t,a);return[n.scatterND(r,s,i)]}case"GatherNd":{let r=k("x",e,t,a),s=k("indices",e,t,a);return[n.gatherND(r,s)]}case"SparseToDense":{let r=k("sparseIndices",e,t,a),s=k("outputShape",e,t,a),i=k("sparseValues",e,t,a),o=k("defaultValue",e,t,a);return[n.sparseToDense(r,i,s,i.dtype===o.dtype?o:n.cast(o,i.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},dF=(e,t,a,n=Zt)=>{switch(e.op){case"SparseFillEmptyRows":{let{outputIndices:r,outputValues:s,emptyRowIndicator:i,reverseIndexMap:o}=n.sparse.sparseFillEmptyRows(k("indices",e,t,a),k("values",e,t,a),k("denseShape",e,t,a),k("defaultValue",e,t,a));return[r,s,i,o]}case"SparseReshape":{let{outputIndices:r,outputShape:s}=n.sparse.sparseReshape(k("inputIndices",e,t,a),k("inputShape",e,t,a),k("newShape",e,t,a));return[r,s]}case"SparseSegmentMean":return[n.sparse.sparseSegmentMean(k("data",e,t,a),k("indices",e,t,a),k("segmentIds",e,t,a))];case"SparseSegmentSum":return[n.sparse.sparseSegmentSum(k("data",e,t,a),k("indices",e,t,a),k("segmentIds",e,t,a))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},pF=(e,t,a,n=Zt)=>{switch(e.op){case"FFT":return[n.fft(k("x",e,t,a))];case"IFFT":return[n.ifft(k("x",e,t,a))];case"RFFT":return[n.rfft(k("x",e,t,a))];case"IRFFT":return[n.irfft(k("x",e,t,a))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},cF=(e,t,a,n=Zt)=>{switch(e.op){case"StringNGrams":{let{nGrams:r,nGramsSplits:s}=n.string.stringNGrams(k("data",e,t,a),k("dataSplits",e,t,a),k("separator",e,t,a),k("nGramWidths",e,t,a),k("leftPad",e,t,a),k("rightPad",e,t,a),k("padWidth",e,t,a),k("preserveShortSequences",e,t,a));return[r,s]}case"StringSplit":{let{indices:r,values:s,shape:i}=n.string.stringSplit(k("input",e,t,a),k("delimiter",e,t,a),k("skipEmpty",e,t,a));return[r,s,i]}case"StringToHashBucketFast":return[n.string.stringToHashBucketFast(k("input",e,t,a),k("numBuckets",e,t,a))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},hF=(e,t,a,n=Zt)=>{switch(e.op){case"Cast":return[n.cast(k("x",e,t,a),k("dtype",e,t,a))];case"ExpandDims":{let r=k("axis",e,t,a);return[n.expandDims(k("x",e,t,a),r)]}case"Squeeze":{let r=k("axis",e,t,a);return[n.squeeze(k("x",e,t,a),r)]}case"Reshape":return[n.reshape(k("x",e,t,a),k("shape",e,t,a))];case"MirrorPad":return[n.mirrorPad(k("x",e,t,a),k("padding",e,t,a),k("mode",e,t,a))];case"PadV2":case"Pad":return[n.pad(k("x",e,t,a),k("padding",e,t,a),k("constantValue",e,t,a))];case"SpaceToBatchND":{let r=k("blockShape",e,t,a),s=k("paddings",e,t,a);return[n.spaceToBatchND(k("x",e,t,a),r,s)]}case"BatchToSpaceND":{let r=k("blockShape",e,t,a),s=k("crops",e,t,a);return[n.batchToSpaceND(k("x",e,t,a),r,s)]}case"DepthToSpace":{let r=k("blockSize",e,t,a),s=k("dataFormat",e,t,a).toUpperCase();return[n.depthToSpace(k("x",e,t,a),r,s)]}case"BroadcastTo":return[n.broadcastTo(k("x",e,t,a),k("shape",e,t,a))];case"BroadcastArgs":return[n.broadcastArgs(k("s0",e,t,a),k("s1",e,t,a))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function nx(e,t,a,n,r=$e){let s=((i,o,l)=>{switch(i.category){case"arithmetic":return r(()=>VP(i,o,l));case"basic_math":return r(()=>UP(i,o,l));case"control":return KP(i,o,l);case"convolution":return r(()=>ZP(i,o,l));case"creation":return r(()=>YP(i,o,l));case"dynamic":return JP(i,o,l);case"evaluation":return r(()=>QP(i,o,l));case"image":return r(()=>nF(i,o,l));case"graph":return r(()=>eF(i,o,l));case"logical":return r(()=>rF(i,o,l));case"matrices":return r(()=>sF(i,o,l));case"normalization":return r(()=>iF(i,o,l));case"ragged":return r(()=>oF(i,o,l));case"reduction":return r(()=>lF(i,o,l));case"slice_join":return r(()=>uF(i,o,l));case"sparse":return r(()=>dF(i,o,l));case"spectral":return r(()=>pF(i,o,l));case"string":return r(()=>cF(i,o,l));case"transformation":return r(()=>hF(i,o,l));case"hash_table":return aF(i,o,l,n);case"custom":let u=w4(i.op);if(u&&u.customExecutor)return u.customExecutor(new WP(i,o,l));throw TypeError(`Custom op ${i.op} is not registered.`);default:throw TypeError(`Unknown op '${i.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,a);return v.isPromise(s)?s.then(i=>[].concat(i)):[].concat(s)}var rx=class{constructor(e={},t={},a={},n={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=a,this.functionMap=n,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){let e=[];for(let t=0;t<this.contexts.length-1;t++){let a=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(a))}e.push(""),this._currentContextIds=e}contextIdforContexts(e){return e?e.map(t=>t.id===0&&t.iterationId===0?"":`${t.frameName}-${t.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(this.contexts&&this.contexts.length>1)this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();else throw new Error("Cannot exit frame, the context is empty")}nextIteration(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice(),this.lastId++;let e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else throw new Error("Cannot increase frame iteration, the context is empty")}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(let t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(let t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}};function sx(e,t,a,n){let r=new Set,s=[],i=null,o=null,l=new Set,u=Object.keys(e).map(d=>ja(d)[0]),p=[];n!=null&&(p=n.map(d=>ja(d.name)[0]));let c=[...t];for(;c.length>0;){let d=c.pop();if((G4(d)||AF(d)||yF(d))&&i==null&&(i=d,o=i.children.map(h=>h.name).filter(h=>r.has(h))),r.add(d.name),a[d.name]==null&&u.indexOf(d.name)===-1&&p.indexOf(d.name)===-1){if(d.inputs.length===0){s.push(d.name);continue}d.inputs.forEach(h=>{l.has(h.name)||(l.add(h.name),c.push(h))})}}return{inputs:e,outputs:t,usedNodes:r,missingInputs:s,dynamicNode:i,syncInputs:o}}function fF(e,t,a){let{usedNodes:n,inputs:r}=a,s=[],i=Object.keys(r).map(p=>ja(p)[0]).map(p=>e.nodes[p]),o=e.initNodes;i.forEach(p=>{n.has(p.name)&&s.push(p)}),e.weights.forEach(p=>{n.has(p.name)&&s.push(p)}),o!=null&&o.forEach(p=>{n.has(p.name)&&s.push(p)});let l=new Set,u=[];for(;s.length>0;){let p=s.pop();l.add(p.name),t[p.name]||u.push(p),p.children.forEach(c=>{!l.has(c.name)&&n.has(c.name)&&c.inputs.every(d=>l.has(d.name))&&s.push(c)})}return u}var mF=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],gF=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],xF=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function G4(e){return mF.indexOf(e.op)>=0}function AF(e){return gF.indexOf(e.op)>=0}function yF(e){return xF.indexOf(e.op)>=0}var A1=class{constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},this.keepIntermediateTensors=!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(a=>{this._functionExecutorMap[a]=new A1(e.functions[a],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(a=>e[a].map(n=>n.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{let t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}getCompilationKey(e,t){let a=e.map(r=>r.name).sort(),n=t.map(r=>r.name).sort();return a.join(this.SEPERATOR)+"--"+n.join(this.SEPERATOR)}compile(e,t){let a=sx(e,t,this.weightMap,this._initNodes),{missingInputs:n,dynamicNode:r,syncInputs:s}=a;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 [${s}]`);if(n.length>0){let i=t.map(l=>l.name),o=Object.keys(e);throw new Error(`Cannot compute the outputs [${i}] from the provided inputs [${o}]. Missing the following inputs: [${n}]`)}return fF(this.graph,this.weightMap,a)}cloneAndKeepTensor(e){if(e==null)return null;let t=e.clone();return On(t),t}cloneTensorList(e){return e?e.map(t=>this.cloneAndKeepTensor(t)):null}cloneTensorMap(e){return Object.fromEntries(Object.entries(e).map(([t,a])=>[t,this.cloneTensorList(a)]))}execute(e,t){this.disposeIntermediateTensors(),e=this.mapInputs(e);let a=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);let n=a.map(p=>this.graph.nodes[ja(p)[0]]),r=t.map(p=>ja(p)[0]),s=r.map(p=>this.graph.nodes[p]);s.length===0&&(s=this._outputs);let i=this.getCompilationKey(n,s),o=this.compiledMap.get(i);o==null&&(o=this.compile(e,s),this.compiledMap.set(i,o));try{this.keepIntermediateTensors=W().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(p){this.keepIntermediateTensors=!1,console.warn(p.message)}let l={},u={};return $e(()=>{let p=new rx(this.weightMap,l,u,this.functionExecutorMap),c=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach(f=>{let[m,g]=ja(f),x=[];x[g]=e[f],c[m]=x,this.keepIntermediateTensors&&(this.clonedTensorsMap[m]=this.cloneTensorList(x))});let d=this.getFrozenTensorIds(c),h={};for(let f=0;f<o.length;f++){let m=o[f];if(!c[m.name]){let g=nx(m,c,p,this._resourceManager);if(v.isPromise(g))throw new Error(`The execution of the op '${m.op}' returned a promise. Please use model.executeAsync() instead.`);c[m.name]=g,this.keepIntermediateTensors&&(this.clonedTensorsMap[m.name]=this.cloneTensorList(g)),this.checkTensorForDisposal(m.name,m,c,p,d,r,h)}}return this.parent==null&&p.dispose(d),t.map(f=>ba(f,c,p))})}getFrozenTensorIds(e){let t=[].concat.apply([],Object.keys(e).map(a=>e[a]).map(a=>a.map(n=>n.id)));return new Set(t)}checkTensorForDisposal(e,t,a,n,r,s,i){t.category==="control"||s.indexOf(e)!==-1||(a[e].forEach(o=>{o!=null&&(i[o.id]=(i[o.id]||0)+t.children.length)}),t.inputs.forEach(o=>{if(o.category!=="control"){let l=bP(o.name,a,n);l!=null&&l.forEach(u=>{if(u&&!u.kept&&!r.has(u.id)){let p=i[u.id];p===1?(u.dispose(),delete i[u.id]):p!=null&&i[u.id]--}})}}))}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){!this.clonedTensorsMap||(Object.values(this.clonedTensorsMap).forEach(e=>{for(let t of e)t&&!t.isDisposed&&t.dispose()}),this.clonedTensorsMap=null)}getIntermediateTensors(){return this.clonedTensorsMap}async _executeAsync(e,t,a=!1,n={},r={}){this.disposeIntermediateTensors(),a||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepIntermediateTensors=W().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(c){this.keepIntermediateTensors=!1,console.warn(c.message)}let s=new rx(this.weightMap,n,r,this.functionExecutorMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));let i=await this.executeWithControlFlow(e,s,t,a),o=t.map(c=>ba(c,i,s)),l=o.map(c=>c.id),u=Object.keys(e).map(c=>e[c].id),p=new Set([...l,...u,...this.weightIds]);return Object.values(i).forEach(c=>{c.forEach(d=>{d&&!d.isDisposed&&!p.has(d.id)&&d.dispose()})}),this.parent==null&&s.dispose(p),o}async executeFunctionAsync(e,t,a){let n=e.reduce((r,s,i)=>(r[this.inputs[i].name]=s,r),{});return this._executeAsync(n,this.outputNodes,!0,t,a)}async executeWithControlFlow(e,t,a,n){let r=Object.keys(e),s=r.map(A=>this.graph.nodes[ja(A)[0]]),i=a.map(A=>ja(A)[0]),o=i.map(A=>this.graph.nodes[A]);o.length===0&&(o=this._outputs);let{usedNodes:l,missingInputs:u,dynamicNode:p,syncInputs:c}=sx(e,o,this.weightMap,this._initNodes),d=[...s,...this.graph.weights,...this._initNodes||[]].map(A=>({node:A,contexts:t.currentContext})),h=Object.assign({},this.weightMap);Object.keys(e).forEach(A=>{let[y,b]=ja(A),w=[];w[b]=e[A],h[y]=w});let f={},m=this.getFrozenTensorIds(h),g={};for(;d.length>0;){let A=this.processStack(s,d,t,h,g,m,i,f,l);await Promise.all(A)}p==null&&!n&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let x=o.filter(A=>!G4(A)&&!ba(A.name,h,t)).map(A=>A.name);if(x.length>0){let A="";throw p!=null&&(A=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${c}]`),new Error(`Cannot compute the outputs [${x}] from the provided inputs [${r}]. Consider providing the following inputs: [${u}]. ${A}`)}return h}processStack(e,t,a,n,r,s,i,o,l){let u=[];for(;t.length>0;){let p=t.pop();a.currentContext=p.contexts;let c="";if(p.node.op==="Enter"&&k("isConstant",p.node,n,a)&&([c]=mr(p.node.name,a)),n[p.node.name]==null){let d=nx(p.node,n,a,this._resourceManager);c||([c]=mr(p.node.name,a));let h=a.currentContext;v.isPromise(d)?u.push(d.then(f=>(n[c]=f,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(f)),a.currentContext=h,this.checkTensorForDisposal(c,p.node,n,a,s,i,o),this.processChildNodes(p.node,t,a,n,r,l),f))):(n[c]=d,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(d)),this.checkTensorForDisposal(c,p.node,n,a,s,i,o),this.processChildNodes(p.node,t,a,n,r,l))}else this.processChildNodes(p.node,t,a,n,r,l)}return u}processChildNodes(e,t,a,n,r,s){e.children.forEach(i=>{let[o]=mr(i.name,a);r[o]||!s.has(i.name)||(i.op==="Merge"?i.inputNames.some(l=>!!ba(l,n,a))&&(r[o]=!0,t.push({contexts:a.currentContext,node:i})):i.inputNames.every(l=>!!ba(l,n,a))&&(r[o]=!0,t.push({contexts:a.currentContext,node:i})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{let a=e[t],[n]=ja(t),r=this.graph.nodes[n];if(r.attrParams.shape&&r.attrParams.shape.value){let s=r.attrParams.shape.value,i=s.length===a.shape.length&&a.shape.every((o,l)=>s[l]===-1||s[l]===o);v.assert(i,()=>`The shape of dict['${r.name}'] provided in model.execute(dict) must be [${s}], but was [${a.shape}]`)}r.attrParams.dtype&&r.attrParams.dtype.value&&v.assert(a.dtype===r.attrParams.dtype.value,()=>`The dtype of dict['${r.name}'] provided in model.execute(dict) must be ${r.attrParams.dtype.value}, but was ${a.dtype}`)})}mapInputs(e){var t,a;let n={};for(let r in e){let s=(a=(t=this._signature)===null||t===void 0?void 0:t.inputs)===null||a===void 0?void 0:a[r];s!=null?n[s.name]=e[r]:n[r]=e[r]}return n}checkInputs(e){let t=Object.keys(e).filter(a=>{let[n]=ja(a);return this.graph.nodes[n]==null});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(t=>{var a,n;let r=(n=(a=this._signature)===null||a===void 0?void 0:a.outputs)===null||n===void 0?void 0:n[t];return r!=null?r.name:t},{})}checkOutputs(e){e.forEach(t=>{let[a]=ja(t);if(!this.graph.nodes[a])throw new Error(`The output '${t}' is not found in the graph`)})}},bF=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]}},vF="?tfjs-format=file",wF="model.json",op=class{constructor(e,t={},a=jn){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=a,t==null&&(this.loadOptions={}),this.resourceManager=new bF}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,a=this.artifacts.signature;if(this.artifacts.userDefinedMetadata!=null){let r=this.artifacts.userDefinedMetadata;r.signature!=null&&(a=r.signature),r.structuredOutputKeys!=null&&(this.structuredOutputKeys=r.structuredOutputKeys)}this.signature=a,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;let n=this.io.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new A1(Q5.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(n),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){let r=Q5.Instance.transformGraph(e.modelInitializer);this.initializer=new A1(r),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializerSignature=e.initializerSignature}return!0}async save(e,t){if(typeof e=="string"){let a=this.io.getSaveHandlers(e);if(a.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(a.length>1)throw new Error(`Found more than one (${a.length}) save handlers for URL '${e}'`);e=a[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)}addStructuredOutputNames(e){if(this.structuredOutputKeys){let t=e instanceof pt?[e]:e,a={};return t.forEach((n,r)=>a[this.structuredOutputKeys[r]]=n),a}return e}predict(e,t){let a=this.execute(e,this.outputNodes);return this.addStructuredOutputNames(a)}async predictAsync(e,t){let a=await this.executeAsync(e,this.outputNodes);return this.addStructuredOutputNames(a)}normalizeInputs(e){var t;if(!(e instanceof pt)&&!Array.isArray(e)){let r=(t=this.signature)===null||t===void 0?void 0:t.inputs;if(r!=null)for(let s in r){let i=r[s];i.resourceId!=null&&(e[s]=this.resourceIdToCapturedInput[i.resourceId])}return e}e=Array.isArray(e)?e:[e];let a=Object.keys(this.resourceIdToCapturedInput).length;if(e.length+a!==this.inputNodes.length)throw new Error(`Input tensor count mismatch, the graph model has ${this.inputNodes.length-a} non-resource placeholders, while there are ${e.length} input tensors provided.`);let n=0;return this.inputNodes.reduce((r,s)=>{var i,o,l;let u=(l=(o=(i=this.signature)===null||i===void 0?void 0:i.inputs)===null||o===void 0?void 0:o[s])===null||l===void 0?void 0:l.resourceId;return u!=null?r[s]=this.resourceIdToCapturedInput[u]:r[s]=e[n++],r},{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}executeInitializerGraph(){return this.initializer==null?[]:this.initializerSignature==null?this.initializer.execute({},[]):this.initializer.execute({},Object.keys(this.initializerSignature.outputs))}async executeInitializerGraphAsync(){return this.initializer==null?[]:this.initializerSignature==null?this.initializer.executeAsync({},[]):this.initializer.executeAsync({},Object.keys(this.initializerSignature.outputs))}setResourceIdToCapturedInput(e){if(this.resourceIdToCapturedInput={},this.initializerSignature){let t=this.initializerSignature.outputs,a=Object.keys(t);for(let n=0;n<a.length;n++){let r=a[n],s=t[r];this.resourceIdToCapturedInput[s.resourceId]=e[n]}}}execute(e,t){this.resourceIdToCapturedInput==null&&this.setResourceIdToCapturedInput(this.executeInitializerGraph()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let a=this.executor.execute(e,t);return a.length>1?a:a[0]}async executeAsync(e,t){this.resourceIdToCapturedInput==null&&this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let a=await this.executor.executeAsync(e,t);return a.length>1?a:a[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,a)=>(t[a]=[e[a]],t),{})}dispose(){this.executor.dispose(),this.initializer&&(this.initializer.dispose(),this.resourceIdToCapturedInput&&Y(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}};async function r3(e,t={},a=jn){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=IF(e));let n=new op(e,t,a);return await n.load(),n}function kF(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[n,r]=e;if(!n)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 n))throw new Error("Model JSON is missing 'modelTopology'");if(!("weightsManifest"in n))throw new Error("Model JSON is missing 'weightsManifest'");let s=jn.getWeightSpecs(n.weightsManifest),i=jn.getModelArtifactsForJSONSync(n,s,r);t=jn.fromMemorySync(i)}else if("load"in e)t=e;else if("modelTopology"in e&&"weightSpecs"in e&&"weightData"in e)t=jn.fromMemorySync(e);else throw new Error("Unknown model format");let a=new op(t);return a.load(),a}function IF(e){return e.endsWith("/")||(e=e+"/"),`${e}${wF}${vF}`}var SF="4.1.0";function ye(e,t){Array.isArray(e)||(e=[e]),e.forEach(a=>{a!=null&&v.assert(a.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}var TF=Tn.whereImpl,$h=class extends bl{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new vd(this,kt())}nextDataId(){return $h.nextDataId++}write(e,t,a){this.firstUse&&(this.firstUse=!1,W().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 n={id:this.nextDataId()};return this.data.set(n,{values:e,dtype:a,refCount:1}),n}makeTensorInfo(e,t,a){let n;if(t==="string"&&a!=null&&a.length>0&&v.isString(a[0])){let r=a.map(s=>v.encodeString(s));n=this.write(r,e,t)}else n=this.write(a,e,t);return{dataId:n,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,a,n,r){this.data.set(e,{values:t,dtype:n,refCount:r})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:a}=this.data.get(e);if(t==="complex64"){let n=this.readSync(a.real.dataId),r=this.readSync(a.imag.dataId);return T.mergeRealAndImagArrays(n,r)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId);if(e.dtype==="string")try{let a=t.map(n=>v.decodeString(n));return Me(e.shape,e.dtype,a)}catch(a){throw new Error("Failed to decode encoded string bytes into utf-8")}return Me(e.shape,e.dtype,t)}makeOutput(e,t,a){return kt().makeTensorFromTensorInfo(this.makeTensorInfo(t,a,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:a}=this.data.get(e);a!=null&&(this.disposeData(a.real.dataId,!0),this.disposeData(a.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){ye([e],"where");let t=this.readSync(e.dataId);return TF(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};$h.nextDataId=0;var _h={};Xe(_h,{addImpl:()=>q4,bincountImpl:()=>i3,bincountReduceImpl:()=>X4,castImpl:()=>j4,ceilImpl:()=>K4,concatImpl:()=>o3,equalImpl:()=>Z4,expImpl:()=>J4,expm1Impl:()=>e7,floorImpl:()=>t7,gatherNdImpl:()=>a7,gatherV2Impl:()=>n7,greaterEqualImpl:()=>s7,greaterImpl:()=>r7,lessEqualImpl:()=>o7,lessImpl:()=>i7,linSpaceImpl:()=>l7,logImpl:()=>u7,maxImpl:()=>d7,maximumImpl:()=>p7,minimumImpl:()=>c7,multiplyImpl:()=>l3,negImpl:()=>h7,notEqualImpl:()=>f7,prodImpl:()=>m7,raggedGatherImpl:()=>g7,raggedRangeImpl:()=>x7,raggedTensorToTensorImpl:()=>A7,rangeImpl:()=>d3,rsqrtImpl:()=>y7,scatterImpl:()=>tl,sigmoidImpl:()=>bO,simpleAbsImpl:()=>H4,sliceImpl:()=>_c,sparseFillEmptyRowsImpl:()=>v7,sparseReshapeImpl:()=>w7,sparseSegmentReductionImpl:()=>p3,sqrtImpl:()=>kO,squaredDifferenceImpl:()=>k7,stridedSliceImpl:()=>I7,stringNGramsImpl:()=>c3,stringSplitImpl:()=>h3,stringToHashBucketFastImpl:()=>f3,subImpl:()=>S7,tileImpl:()=>T7,topKImpl:()=>N7,transposeImpl:()=>u3,uniqueImpl:()=>E7});function H4(e){let t=new Float32Array(e.length);for(let a=0;a<e.length;++a)t[a]=Math.abs(e[a]);return t}var CF=e=>{let{x:t}=e.inputs,a=e.backend;ye(t,"abs");let n=new Float32Array(v.sizeFromShape(t.shape)),r=a.data.get(t.dataId).values;return n=H4(r),a.makeOutput(n,t.shape,t.dtype)},NF={kernelName:wl,backendName:"cpu",kernelFunc:CF};function Lt(e){return(t,a,n,r,s)=>{let i=T.assertAndGetBroadcastShape(t,a),o=i.length,l=v.computeStrides(i),u=v.sizeFromShape(i),p=v.getTypedArrayFromDType(s,u),c=t.length,d=a.length,h=v.computeStrides(t),f=v.computeStrides(a),m=T.getBroadcastDims(t,i),g=T.getBroadcastDims(a,i);if(m.length+g.length===0)for(let x=0;x<p.length;++x)p[x]=e(n[x%n.length],r[x%r.length]);else for(let x=0;x<p.length;++x){let A=v.indexToLoc(x,o,l),y=A.slice(-c);m.forEach(C=>y[C]=0);let b=v.locToIndex(y,c,h),w=A.slice(-d);g.forEach(C=>w[C]=0);let S=v.locToIndex(w,d,f);p[x]=e(n[b],r[S])}return[p,i]}}function Xa(e){let{inputs:t,backend:a}=e,{real:n,imag:r}=t,s=a.data.get(n.dataId).values,i=a.data.get(r.dataId).values,o=a.makeTensorInfo(n.shape,"complex64"),l=a.data.get(o.dataId);return l.complexTensorInfos={real:a.makeTensorInfo(n.shape,"float32",s),imag:a.makeTensorInfo(r.shape,"float32",i)},o}var EF={kernelName:Sd,backendName:"cpu",kernelFunc:Xa};function $c(e,t,a="float32"){if(a==="complex64"){let r=$c(e,t,"float32"),s=$c(e,t,"float32");return Xa({inputs:{real:r,imag:s},backend:e})}let n=v.makeZerosTypedArray(v.sizeFromShape(t),a);return e.makeTensorInfo(t,a,n)}function er(e){let{inputs:t,backend:a}=e,{x:n}=t;return a.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}var RF={kernelName:ki,backendName:"cpu",kernelFunc:er};function Us(e){let{inputs:t,backend:a}=e,{input:n}=t,r=a.data.get(n.dataId).complexTensorInfos.real,s=a.data.get(r.dataId).values;return a.makeTensorInfo(r.shape,r.dtype,s)}var MF={kernelName:Md,backendName:"cpu",kernelFunc:Us};function j4(e,t,a,n){if(n==="int32"){let r=Int32Array.from(e);return[t,"int32",r]}if(n==="bool"){let r=v.toTypedArray([0],a),[s,i]=Lt((o,l)=>o!==l?1:0)(t,[],e,r,"bool");return[i,"bool",s]}throw new Error(`Error in Cast: failed to cast ${a} to ${n}`)}function Jr(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{dtype:s}=n;if(s==="complex64"){if(r.dtype==="complex64")return er({inputs:{x:r},backend:a});let p=$c(a,r.shape,r.dtype),c=Jr({inputs:{x:r},backend:a,attrs:{dtype:"float32"}}),d=Xa({inputs:{real:c,imag:p},backend:a});return a.disposeIntermediateTensorInfo(p),a.disposeIntermediateTensorInfo(c),d}if(r.dtype==="complex64"){let p=Us({inputs:{input:r},backend:a}),c=Jr({inputs:{x:p},backend:a,attrs:{dtype:s}});return a.disposeIntermediateTensorInfo(p),c}if(!v.hasEncodingLoss(r.dtype,s)){let p=er({inputs:{x:r},backend:a});return{dataId:p.dataId,shape:p.shape,dtype:s}}let i=a.data.get(r.dataId).values,[o,l,u]=j4(i,r.shape,r.dtype,s);return a.makeTensorInfo(o,l,u)}var $F={kernelName:ti,backendName:"cpu",kernelFunc:Jr};function Yt(e,t,a,n){return a==null?({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;ye([i,o],e);let u=l.data.get(i.dataId).values,p=l.data.get(o.dataId).values,c=i.dtype==="string"?T.fromUint8ToStringArray(u):u,d=i.dtype==="string"?T.fromUint8ToStringArray(p):p,h=n||i.dtype,[f,m]=t(i.shape,o.shape,c,d,h);return l.makeTensorInfo(m,h,f)}:({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;if(i.dtype==="complex64"||o.dtype==="complex64"){let u=Jr({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),p=l.data.get(u.dataId),c=p.complexTensorInfos.real,d=p.complexTensorInfos.imag,h=l.data.get(c.dataId).values,f=l.data.get(d.dataId).values,m=Jr({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(m.dataId),x=g.complexTensorInfos.real,A=g.complexTensorInfos.imag,y=l.data.get(x.dataId).values,b=l.data.get(A.dataId).values,[w,S,C]=a(i.shape,o.shape,h,f,y,b),E=l.makeTensorInfo(C,"float32",w),_=l.makeTensorInfo(C,"float32",S),$=Xa({inputs:{real:E,imag:_},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(m),l.disposeIntermediateTensorInfo(E),l.disposeIntermediateTensorInfo(_),$}else{let u=l.data.get(i.dataId).values,p=l.data.get(o.dataId).values,c=n||i.dtype,[d,h]=t(i.shape,o.shape,u,p,c);return l.makeTensorInfo(h,c,d)}}}function s3(e){return(t,a,n,r,s,i)=>{let o=T.assertAndGetBroadcastShape(t,a),l=v.sizeFromShape(o),u=o.length,p=v.computeStrides(o),c=v.getTypedArrayFromDType("float32",l),d=v.getTypedArrayFromDType("float32",l),h=T.getBroadcastDims(t,o),f=T.getBroadcastDims(a,o),m=T.mergeRealAndImagArrays(n,r),g=T.mergeRealAndImagArrays(s,i),x=t.length,A=v.computeStrides(t),y=a.length,b=v.computeStrides(a);if(h.length+f.length===0)for(let w=0;w<c.length;w++){let S=w%m.length,C=w%g.length,E=e(m[S*2],m[S*2+1],g[C*2],g[C*2+1]);c[w]=E.real,d[w]=E.imag}else for(let w=0;w<c.length;w++){let S=v.indexToLoc(w,u,p),C=S.slice(-x);h.forEach(I=>C[I]=0);let E=v.locToIndex(C,x,A),_=S.slice(-y);f.forEach(I=>_[I]=0);let $=v.locToIndex(_,y,b),M=e(m[E*2],m[E*2+1],g[$*2],g[$*2+1]);c[w]=M.real,d[w]=M.imag}return[c,d,o]}}var q4=Lt((e,t)=>e+t),_F=s3((e,t,a,n)=>({real:e+a,imag:t+n})),ml=Yt(ts,q4,_F),PF={kernelName:ts,backendName:"cpu",kernelFunc:ml};function i3(e,t,a,n,r){let s=v.sizeFromShape(n),i=v.makeZerosTypedArray(r,a);for(let o=0;o<e.length;o++){let l=e[o];if(l<0)throw new Error("Input x must be non-negative!");l>=r||(s>0?i[l]+=t[o]:i[l]+=1)}return i}function X4(e,t,a,n=!1){let r=e.shape[0],s=e.shape[1],i=Me([r,a],t.dtype);for(let o=0;o<r;o++)for(let l=0;l<s;l++){let u=e.get(o,l);if(u<0)throw new Error("Input x must be non-negative!");u>=a||(n?i.set(1,o,u):t.size>0?i.set(i.get(o,u)+t.get(o,l),o,u):i.set(i.get(o,u)+1,o,u))}return i}function os(e){return(t,a,n)=>{let r=v.getTypedArrayFromDType(a,t.length);for(let s=0;s<t.length;++s)r[s]=e(t[s],n);return r}}function ot(e,t,a){return({inputs:n,attrs:r,backend:s})=>{let{x:i}=n;if(ye(i,e),i.dtype==="string"||a==="string")throw new Error("unaryKernelFunc does not support string input/output");let o=s,l=o.data.get(i.dataId).values,u=v.sizeFromShape(i.shape),p=a||i.dtype,c=v.getArrayFromDType(p,u);for(let d=0;d<u;++d)c[d]=t(l[d],r);return o.makeTensorInfo(i.shape,p,c)}}function ou(e,t,a){return({inputs:n,attrs:r,backend:s})=>{let{x:i}=n;if(ye(i,e),i.dtype==="string"||a==="string")throw new Error("unaryKernelFunc does not support string input/output");let o=s,l=o.data.get(i.dataId).values,u=a||i.dtype,p=t(l,u,r);return o.makeTensorInfo(i.shape,u,p)}}var K4=os(e=>Math.ceil(e)),FF=ou(ai,K4),OF={kernelName:ai,backendName:"cpu",kernelFunc:FF};function o3(e,t,a,n){let r=v.getArrayFromDType(a,v.sizeFromShape(t));if(n&&a!=="string"){let s=0;e.forEach(i=>{let o=v.sizeFromShape(i.shape);r.set(i.vals,s),s+=o})}else{let s=0;e.forEach(i=>{let o=a==="string"?T.fromUint8ToStringArray(i.vals):i.vals,l=0;for(let u=0;u<i.shape[0];++u){let p=u*t[1]+s;for(let c=0;c<i.shape[1];++c)r[p+c]=o[l++]}s+=i.shape[1]})}return r}var Z4=Lt((e,t)=>e===t?1:0),Y4=Yt(fi,Z4,null,"bool"),DF={kernelName:fi,backendName:"cpu",kernelFunc:Y4},J4=os(e=>Math.exp(e)),Q4=ou(mi,J4,"float32"),zF={kernelName:mi,backendName:"cpu",kernelFunc:Q4},e7=os(e=>Math.expm1(e)),LF=ou(Pl,e7),BF={kernelName:Pl,backendName:"cpu",kernelFunc:LF},t7=os(e=>Math.floor(e)),WF=ou(xi,t7),VF={kernelName:xi,backendName:"cpu",kernelFunc:WF};function a7(e,t,a,n,r,s,i,o,l){let u=Me([n,s],a);for(let p=0;p<n;p++){let c=[],d=0;for(let h=0;h<r;h++){let f=e[p*r+h];d+=f*i[h],c.push(f)}if(d<0||d>=l/s)throw new Error(`Invalid indices: ${c} does not index into ${o}`);for(let h=0;h<s;h++)u.values[p*s+h]=t.get(...t.indexToLoc(d*s+h))}return u}function n7(e,t,a){let n=Me(a,e.dtype);for(let r=0;r<n.size;++r){let s=n.indexToLoc(r).slice(),i=s[0],o=s[2],l=t.locToIndex([i,o]);s[2]=t.values[l];let u=e.locToIndex(s);0<=u&&u<e.values.length&&(n.values[r]=e.values[u])}return n}var r7=Lt((e,t)=>e>t?1:0),UF=Yt(vi,r7,null,"bool"),GF={kernelName:vi,backendName:"cpu",kernelFunc:UF},s7=Lt((e,t)=>e>=t?1:0),HF=Yt(wi,s7,null,"bool"),jF={kernelName:wi,backendName:"cpu",kernelFunc:HF},i7=Lt((e,t)=>e<t?1:0),qF=Yt(Ti,i7,null,"bool"),XF={kernelName:Ti,backendName:"cpu",kernelFunc:qF},o7=Lt((e,t)=>e<=t?1:0),KF=Yt(Ci,o7,null,"bool"),ZF={kernelName:Ci,backendName:"cpu",kernelFunc:KF};function l7(e,t,a){let n=(t-e)/(a-1),r=v.makeZerosTypedArray(a,"float32");r[0]=e;for(let s=1;s<r.length;s++)r[s]=r[s-1]+n;return r}var u7=os(e=>Math.log(e)),YF=ou(Ni,u7),JF={kernelName:Ni,backendName:"cpu",kernelFunc:YF};function d7(e,t,a,n){let r=v.getTypedArrayFromDType(n,v.sizeFromShape(a));for(let s=0;s<r.length;++s){let i=s*t,o=e[i];for(let l=0;l<t;++l){let u=e[i+l];(Number.isNaN(u)||u>o)&&(o=u)}r[s]=o}return r}var p7=Lt((e,t)=>Math.max(e,t)),QF=Yt($i,p7),eO={kernelName:$i,backendName:"cpu",kernelFunc:QF},c7=Lt((e,t)=>Math.min(e,t)),tO=Yt(Oi,c7),aO={kernelName:Oi,backendName:"cpu",kernelFunc:tO},l3=Lt((e,t)=>e*t),nO=s3((e,t,a,n)=>({real:e*a-t*n,imag:e*n+t*a})),Ph=Yt(zi,l3,nO),rO={kernelName:zi,backendName:"cpu",kernelFunc:Ph};function h7(e,t,a){let n=v.createScalarValue(-1,a);return l3([],t,n,e,a)}function sO(e){let{inputs:t,backend:a}=e,{x:n}=t;ye(n,"neg");let r=a.data.get(n.dataId).values,[s,i]=h7(r,n.shape,n.dtype);return a.makeTensorInfo(i,n.dtype,s)}var iO={kernelName:Vl,backendName:"cpu",kernelFunc:sO},f7=Lt((e,t)=>e!==t?1:0),oO=Yt(Li,f7,null,"bool"),lO={kernelName:Li,backendName:"cpu",kernelFunc:oO};function u3(e,t,a,n,r){let s=t.length,i=v.sizeFromShape(t),o=v.computeStrides(t),l=v.computeStrides(r),u=v.getTypedArrayFromDType(a,v.sizeFromShape(r));for(let p=0;p<i;++p){let c=v.indexToLoc(p,s,o),d=new Array(c.length);for(let f=0;f<d.length;f++)d[f]=c[n[f]];let h=v.locToIndex(d,s,l);u[h]=e[p]}return u}function La(e){let{inputs:t,attrs:a,backend:n}=e,{x:r}=t,{perm:s}=a;ye(r,"transpose");let i=r.shape.length,o=new Array(i);for(let p=0;p<o.length;p++)o[p]=r.shape[s[p]];let l=n.data.get(r.dataId).values,u=u3(l,r.shape,r.dtype,s,o);return{dataId:n.write(u,o,r.dtype),shape:o,dtype:r.dtype}}var uO={kernelName:Ar,backendName:"cpu",kernelFunc:La};function m7(e,t,a,n){let[r,s]=T.computeOutAndReduceShapes(e,n),i=ca(t,"int32"),o=v.makeZerosTypedArray(v.sizeFromShape(r),i),l=v.sizeFromShape(s);for(let u=0;u<o.length;++u){let p=u*l,c=1;for(let d=0;d<l;++d)c*=a[p+d];o[u]=c}return{outVals:o,outShape:r,outDtype:i}}function dO(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;ye(r,"prod");let o=r.shape.length,l=v.parseAxisParam(s,r.shape),u=T.getAxesPermutation(l,o),p=l,c=r,d=[];u!=null&&(c=La({inputs:{x:r},backend:a,attrs:{perm:u}}),d.push(c),p=T.getInnerMostAxes(p.length,o));let h=a.data.get(c.dataId).values,{outVals:f,outShape:m,outDtype:g}=m7(c.shape,c.dtype,h,p),x=m;return i&&(x=T.expandShapeToKeepDim(m,l)),d.forEach(A=>a.disposeIntermediateTensorInfo(A)),a.makeTensorInfo(x,g,f)}var pO={kernelName:ji,backendName:"cpu",kernelFunc:dO};function cO(e,t,a){e.forEach((n,r)=>{if(n<0||n>=a){let s=v.indexToLoc(r,t.length,v.computeStrides(t)).join(",");throw new Error(`indices[${s}] = ${n} is not in [0, ${a})`)}})}function hO(e,t){for(let a=0;a<e.length;++a){let n=e[a],r=a===e.length-1?t:e[a+1].length;if(n.length===0)throw new Error("Ragged splits may not be empty");if(n[0]<0)throw new Error("Ragged splits must be non-negative");if(n[n.length-1]>r)throw new Error("Ragged splits must not point past values");for(let s=1;s<n.length;++s)if(n[s-1]>n[s])throw new Error("Ragged splits must be sorted in ascending order")}}function fO(e,t,a,n){let r=[],s=0,i=t.length-1+a.length,o=new Array(i).fill(null).map(()=>[0]);hO(a,n);let l=1;for(let u=0;u<t.length-1;++u){l*=t[u];let p=t[u+1];for(let c=1;c<l+1;++c)o[u].push(c*p)}for(let u=0;u<e.length;++u){let p=e[u],c=e[u]+1;for(let d=0;d<a.length;++d){let h=a[d],f=d+t.length-1;if(f>=0){let m=o[f],g=m[m.length-1]-h[p];for(let x=p;x<c;++x)o[f].push(h[x+1]+g)}p=h[p],c=h[c]}c!==p&&(r.push([p,c]),s+=c-p)}return{outSplits:o,valueSlices:r,numValues:s}}function mO(e){let t=[];for(let a=0;a<e.length;++a){let n=e[a].length,r=v.getArrayFromDType("int32",n);t.push(r),e[a].forEach((s,i)=>r[i]=s)}return t}function ix(e,t){let a=e.slice(0,t);for(;a.length<t;)a.push(1);for(let n=t;n<e.length;n++)a[t-1]*=e[n];return a}function gO(e,t,a,n,r,s){let i=ix(t,2)[1],o=ix(s,2)[1],l=0;for(let u of a)for(let p=u[0];p<u[1];++p){for(let c=0;c<n;++c)r[l*o+c]=e[p*i+c];++l}}function xO(e,t,a,n,r){let s=t.slice();s[0]=r;let i=v.getArrayFromDType(a,v.sizeFromShape(s)),o=e.length,l=o===0?0:o/t[0];return gO(e,t,n,l,i,s),[i,s]}function g7(e,t,a,n,r,s,i,o){if(e.length===0)throw new Error("paramsNestedSplits must be non empty");if(t[0].length===0)throw new Error("Split tensors must not be scalars");let l=t[0][0]-1;if(cO(s,i,l),n.length===0)throw new Error("params.rank must be nonzero");let u=n[0],{outSplits:p,valueSlices:c,numValues:d}=fO(s,i,e,u),h=mO(p),f=xO(a,n,r,c,d);return[h,f[0],f[1]]}var ox=2147483647;function x7(e,t,a,n,r,s,i){if(t.length>1)throw new Error("starts must be a scalar or vector");if(r.length>1)throw new Error("limits must be a scalar or vector");if(i.length>1)throw new Error("deltas must be a scalar or vector");let o=t.length===0,l=r.length===0,u=i.length===0,p=[];o||p.push(t[0]),l||p.push(r[0]),u||p.push(i[0]);for(let g=1;g<p.length;++g)if(p[g]!==p[g-1])throw new Error("starts, limits, and deltas must have the same shape");let c=p.length===0?1:p[0],d=v.getArrayFromDType("int32",c+1);d[0]=0;for(let g=0;g<c;++g){let x=o?e[0]:e[g],A=l?n[0]:n[g],y=u?s[0]:s[g];if(y===0)throw new Error("Requires delta != 0");let b;if(y>0&&A<x||y<0&&A>x)b=0;else if(b=Math.ceil(Math.abs((A-x)/y)),b>ox)throw new Error(`Requires ((limit - start) / delta) <= ${ox}`);d[g+1]=d[g]+b}let h=d[c],f=v.getArrayFromDType(a,h),m=0;for(let g=0;g<c;++g){let x=d[g+1]-d[g],A=o?e[0]:e[g],y=u?s[0]:s[g];for(let b=0;b<x;++b)f[m++]=A,A+=y}return[d,f]}var vn=T.RowPartitionType,y1=class{constructor(e,t,a,n,r,s,i,o,l,u){this.shape=e,this.shapeShape=t,this.values=a,this.valuesShape=n,this.valuesDType=r,this.defaultValue=s,this.defaultValueShape=i,this.rowPartitionValues=o,this.rowPartitionValuesShapes=l,this.rowPartitionTypes=T.getRowPartitionTypesHelper(u),this.raggedRank=T.getRaggedRank(this.rowPartitionTypes)}getRowPartitionTypeByDimension(e){return this.rowPartitionTypes[0]===vn.FIRST_DIM_SIZE?this.rowPartitionTypes[e+1]:this.rowPartitionTypes[e]}getRowPartitionTensor(e){return this.rowPartitionTypes[0]===vn.FIRST_DIM_SIZE?this.rowPartitionValues[e+1]:this.rowPartitionValues[e]}getMaxWidth(e){let t=this.getRowPartitionTensor(e-1);switch(this.getRowPartitionTypeByDimension(e-1)){case vn.VALUE_ROWIDS:return y1.getMaxWidthValueRowID(t);case vn.ROW_SPLITS:return y1.getMaxWidthRowSplit(t);default:throw new Error(`Cannot handle partition type ${vn[this.getRowPartitionTypeByDimension(e-1)]}`)}}static getMaxWidthRowSplit(e){let t=e.length;if(t===0||t===1)return 0;let a=0;for(let n=0;n<t-1;++n){let r=e[n+1]-e[n];r>a&&(a=r)}return a}static getMaxWidthValueRowID(e){let t=e.length;if(t===0)return 0;let a=0,n=e[0],r=0;for(let s=1;s<t;++s){let i=e[s];i!==n&&(n=i,r=Math.max(s-a,r),a=s)}return Math.max(t-a,r)}tensorShapeFromTensor(e,t,a=!0){if(t.length===0){if(e[0]===-1)return[];throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.")}return ux(e,a)}calculateOutputSize(e){let t=this.valuesShape,a=this.defaultValueShape;T.validateDefaultValueShape(a,t);let n=this.tensorShapeFromTensor(this.shape,this.shapeShape),r=T.combineRaggedTensorToTensorShapes(this.raggedRank,n,t);r[0]<0&&(r[0]=e);for(let s=1;s<=this.raggedRank;++s)r[s]<0&&(r[s]=this.getMaxWidth(s));return r}calculateFirstParentOutputIndex(e,t,a){let n=Math.min(e,a),r=[],s=0;for(let i=0;i<n;++i,s+=t)r.push(s);for(let i=n;i<e;++i)r.push(-1);return v.assert(r.length===e,()=>"Final length of result must be equal to firstDimension."),r}calculateOutputIndexRowSplit(e,t,a,n){let r=e.length,s=[];for(let i=0;i<r-1;++i){let o=e[i+1]-e[i],l=Math.min(n,o),u=t[i];u===-1&&(l=0);for(let p=0;p<l;++p)s.push(u),u+=a;for(let p=0;p<o-l;++p)s.push(-1)}if(r>0&&s.length!==e[r-1])throw new Error("Invalid row split size.");return s}calculateOutputIndexValueRowID(e,t,a,n){let r=e.length,s=[];if(r===0)return[];let i=0,o=e[0];if(o>=t.length)throw new Error(`Got currentValueRowId=${o}, which is not less than ${t.length}`);let l=t[o];s.push(l);for(let u=1;u<r;++u){let p=e[u];if(p===o)l>=0&&(++i,i<n?l+=a:l=-1);else{if(i=0,o=p,p>=t.length)throw new Error(`Got nextValueRowId=${p} which is not less than ${t.length}`);l=t[p]}s.push(l)}if(s.length!==e.length)throw new Error("Invalid row ids.");return s}calculateOutputIndex(e,t,a,n){let r=this.getRowPartitionTensor(e),s=this.getRowPartitionTypeByDimension(e);switch(s){case vn.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(r,t,a,n);case vn.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,a,n);default:throw new Error(`Unsupported partition type: ${vn[s]}`)}}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 vn.FIRST_DIM_SIZE:return e[0];case vn.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case vn.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${vn[t]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");let e=this.getFirstDimensionSize(),t=this.calculateOutputSize(e),a=new Array(this.raggedRank+1);a[a.length-1]=1;for(let s=a.length-2;s>=0;--s)a[s]=a[s+1]*t[s+1];let n=ux(t,!1),r=v.getArrayFromDType(this.valuesDType,v.sizeFromShape(n));if(a[0]*t[0]>0){let s=this.calculateFirstParentOutputIndex(e,a[0],t[0]);for(let i=1;i<=this.raggedRank;++i)s=this.calculateOutputIndex(i-1,s,a[i],t[i]);this.setOutput(this.raggedRank,s,r,n)}return[n,r]}setOutput(e,t,a,n){if(a.length===0)return;let r=this.values,s=a,i=n.slice();i=i.slice(e+1);let o=v.sizeFromShape(i),l=t.length,u=this.defaultValue;if(u.length!==o&&u.length!==1){let h=this.defaultValueShape;$e(()=>{let f=J(u,h);u=sl(f,i).dataSync()})}let p=0,c=0,d=0;for(let h=0;h<=l;++h){let f=h<l?t[h]:-1;if(f===d){++d;continue}if(c<d){let m=r.subarray(p*o),g=s.subarray(c*o),x=(d-c)*o;lx(g,m,x)}if(h>=l){let m=a.length;f=Math.floor(m/o)}if(f>d)if(this.defaultValue.length===1)s.subarray(d*o,f*o).fill(this.defaultValue[0]),d=f;else for(;f>d;){let m=s.slice(d*o);lx(m,u,o),++d}f<0?(p=h+1,c=d):(p=h,c=d,d=c+1)}}};function lx(e,t,a){for(let n=0;n<a;n++)e[n]=t[n]}function ux(e,t){let a=[];for(let n of e){if(n<0){if(!t)throw new Error(`Dimension ${n} must be >= 0`);if(n<-1)throw new Error(`Dimension ${n} must be >= -1`);n=-1}a.push(n)}return a}function A7(e,t,a,n,r,s,i,o,l,u){return new y1(e,t,a,n,r,s,i,o,l,u).compute()}function d3(e,t,a,n){let r=e===t,s=e<t&&a<0,i=t<e&&a>1;if(r||s||i)return v.makeZerosTypedArray(0,n);let o=Math.abs(Math.ceil((t-e)/a)),l=v.makeZerosTypedArray(o,n);t<e&&a===1&&(a=-1),l[0]=e;for(let u=1;u<l.length;u++)l[u]=l[u-1]+a;return l}var y7=os(e=>1/Math.sqrt(e)),AO=ou(Qi,y7),yO={kernelName:Qi,backendName:"cpu",kernelFunc:AO};function tl(e,t,a,n,r,s,i,o,l,u){let p=[n/r,r],c=e.values,d=t.values;if(n===0)return Me(a,t.dtype);let h=Me(p,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;f++){let m=[],g=0;for(let x=0;x<i;x++){let A=c[f*i+x];m.push(A),g+=A*o[x]}if(g<0||g>=n/r)throw new Error(`Invalid indices: ${m} does not index into ${a}`);for(let x=0;x<r;x++)u?h.values[g*r+x]+=d[f*r+x]:h.values[g*r+x]=t.rank===0?d[0]:d[f*r+x]}return h}var bO=os(e=>1/(1+Math.exp(-e))),b7=ot(ao,e=>1/(1+Math.exp(-e))),vO={kernelName:ao,backendName:"cpu",kernelFunc:b7};function _c(e,t,a,n,r){let s=It.isSliceContinous(n,t,a),i=v.sizeFromShape(a),o=v.computeStrides(n);if(s){let c=It.computeFlatOffset(t,o);return r==="string"?e.slice(c,c+i):e.subarray(c,c+i)}let l=r==="string"?T.fromUint8ToStringArray(e):e,u=Me(n,r,l),p=Me(a,r);for(let c=0;c<p.size;++c){let d=p.indexToLoc(c),h=d.map((f,m)=>f+t[m]);p.set(u.get(...h),...d)}return r==="string"?T.fromStringArrayToUint8(p.values):p.values}function Gs(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{begin:s,size:i}=n;ye(r,"slice");let[o,l]=It.parseSliceParams(r,s,i);It.assertParamsValid(r,o,l);let u=a.data.get(r.dataId).values,p=_c(u,o,l,r.shape,r.dtype);return a.makeTensorInfo(l,r.dtype,p)}var wO={kernelName:Zl,backendName:"cpu",kernelFunc:Gs};function v7(e,t,a,n,r,s,i){let o=t[0],l=s[0],u=new Array(l),p=new Array(o),c=t[1];if(l===0){if(o!==0)throw new Error(T.getSparseFillEmptyRowsIndicesDenseShapeMismatch(o));let g=v.getArrayFromDType(a,0),x=v.getArrayFromDType(r,0);return[g,[0,c],x,u,p]}let d=!0,h=0,f=new Array(l).fill(0);for(let g=0;g<o;++g){let x=e[g*c];if(x<0)throw new Error(T.getSparseFillEmptyRowsNegativeIndexErrorMessage(g,x));if(x>=l)throw new Error(T.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(g,x,l));++f[x],d=d&&x>=h,h=x}let m=!0;for(let g=0;g<l;++g){let x=f[g]===0;u[g]=x,m=m&&!x,f[g]=Math.max(f[g],1),g>0&&(f[g]+=f[g-1])}if(m&&d){let g=e,x=n;for(let A=0;A<o;++A)p[A]=A;return[g,[o,c],x,u,p]}else{let g=f[l-1],x=v.getArrayFromDType(a,g*c),A=v.getArrayFromDType(r,g),y=new Array(l).fill(0);for(let b=0;b<o;++b){let w=e[b*c],S=y[w],C=(w===0?0:f[w-1])+S;y[w]++;for(let E=0;E<c;++E)x[C*c+E]=e[b*c+E];A[C]=n[b],p[b]=C}for(let b=0;b<l;++b)if(y[b]===0){let w=b===0?0:f[b-1];x[w*c+0]=b;for(let S=1;S<c;++S)x[w*c+S]=0;A[w]=i}return[x,[g,c],A,u,p]}}function w7(e,t,a,n,r){let s=v.sizeFromShape(n),i=t[0],o=r.length,l=[],u=1,p=-1;for(let m=0;m<o;++m){let g=r[m];if(g===-1){if(p!==-1)throw new Error(T.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(p,m));p=m,l.push(1)}else{if(g<0)throw new Error(T.getSparseReshapeNegativeOutputDimErrorMessage(m,g));u*=g,l.push(g)}}if(p!==-1){if(u<=0)throw new Error(T.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());let m=Math.trunc(s/u);if(u*m!==s)throw new Error(T.getSparseReshapeInputOutputMultipleErrorMessage(n,l));l[p]=m}if(v.sizeFromShape(l)!==s)throw new Error(T.getSparseReshapeInputOutputMismatchErrorMessage(n,l));let c=n.length,d=[];if(c>0){d[c-1]=1;for(let m=c-2;m>=0;--m)d[m]=d[m+1]*n[m+1]}let h=[];if(o>0){h[o-1]=1;for(let m=o-2;m>=0;--m)h[m]=h[m+1]*l[m+1]}let f=v.getArrayFromDType(a,i*o);for(let m=0;m<i;++m){let g=0;for(let x=0;x<c;++x)g+=e[m*c+x]*d[x];for(let x=0;x<o;++x)f[m*o+x]=Math.trunc(g/h[x]),g%=h[x]}return[f,[i,o],l]}function p3(e,t,a,n,r,s=!1,i=0){let o=n.length,l=[t[0],e.length/t[0]],u=l[1],p=o>0?r[o-1]+1:0;if(p<0)throw new Error(T.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let c=t.slice();c[0]=p;let d=c.reduce((A,y)=>A*y,1),h=v.getArrayFromDType(a,d);if(o===0)return p>0&&h.fill(i),[h,c];if(p<=0)throw new Error(T.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let f=0,m=1,g=0,x=r[f];for(;;){let A=0;if(m<o){if(A=r[m],x===A){++m;continue}if(x>=A)throw new Error(T.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage())}if(x<0||x>=p)throw new Error(T.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(x,p));x>g&&h.fill(i,g*u,x*u);for(let y=f;y<m;++y){let b=n[y];if(b<0||b>=l[0])throw new Error(T.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(y,n[y],l[0]));for(let w=0;w<u;w++)h[x*u+w]+=e[b*u+w]}if(s)for(let y=0;y<u;y++)h[x*u+y]/=m-f;if(f=m,++m,g=x+1,x=A,m>o)break}return g<p&&h.fill(i,g*u,p*u),[h,c]}var kO=os(e=>Math.sqrt(e)),IO=ot(no,e=>Math.sqrt(e)),SO={kernelName:no,backendName:"cpu",kernelFunc:IO},k7=Lt((e,t)=>{let a=e-t;return a*a}),TO=Yt(io,k7),CO={kernelName:io,backendName:"cpu",kernelFunc:TO};function I7(e,t,a,n){let r=Me(e,t.dtype);for(let s=0;s<r.size;s++){let i=r.indexToLoc(s),o=new Array(i.length);for(let l=0;l<o.length;l++)o[l]=i[l]*a[l]+n[l];r.set(t.get(...o),...i)}return r}var NO=class{constructor(e,t,a,n,r,s){this.separator=v.encodeString(e),this.nGramWidths=t,this.leftPad=v.encodeString(a),this.rightPad=v.encodeString(n),this.padWidth=r,this.preserveShort=s}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){let a=this.getPadWidth(t);return Math.max(0,e+2*a-t+1)}createNGrams(e,t,a,n,r,s){for(let i=0;i<r;++i){let o=this.getPadWidth(s),l=Math.max(0,o-i),u=Math.max(0,o-(r-(i+1))),p=s-(l+u),c=t+(l>0?0:i-o),d=0;d+=l*this.leftPad.length;for(let x=0;x<p;++x)d+=e[c+x].length;d+=u*this.rightPad.length;let h=l+u+p-1;d+=h*this.separator.length,a[n+i]=new Uint8Array(d);let f=a[n+i],m=0,g=x=>x.forEach(A=>f[m++]=A);for(let x=0;x<l;++x)g(this.leftPad),g(this.separator);for(let x=0;x<p-1;++x)g(e[c+x]),g(this.separator);if(p>0){g(e[c+p-1]);for(let x=0;x<u;++x)g(this.separator),g(this.rightPad)}else{for(let x=0;x<u-1;++x)g(this.rightPad),g(this.separator);g(this.rightPad)}}}compute(e,t){let a=e.length,n=t.length;if(n>0){let o=t[0];if(o!==0)throw new Error(`First split value must be 0, got ${o}`);for(let l=1;l<n;++l){let u=t[l]>=o;if(u=u&&t[l]<=a,!u)throw new Error(`Invalid split value ${t[l]}, must be in [${o}, ${a}]`);o=t[l]}if(o!==a)throw new Error(`Last split value must be data size. Expected ${a}, got ${o}`)}let r=n-1,s=v.getArrayFromDType("int32",n);if(a===0||n===0){let o=new Array(a);for(let l=0;l<=r;++l)s[l]=0;return[o,s]}s[0]=0;for(let o=1;o<=r;++o){let l=t[o]-t[o-1],u=0;this.nGramWidths.forEach(p=>{u+=this.getNumNGrams(l,p)}),this.preserveShort&&l>0&&u===0&&(u=1),s[o]=s[o-1]+u}let i=new Array(s[r]);for(let o=0;o<r;++o){let l=t[o],u=s[o];if(this.nGramWidths.forEach(p=>{let c=t[o+1]-t[o],d=this.getNumNGrams(c,p);this.createNGrams(e,l,i,u,d,p),u+=d}),this.preserveShort&&u===s[o]){let p=t[o+1]-t[o];if(p===0)continue;let c=p+2*this.padWidth,d=1;this.createNGrams(e,l,i,u,d,c)}}return[i,s]}};function c3(e,t,a,n,r,s,i,o){return new NO(a,n,r,s,i,o).compute(e,t)}function EO(e,t,a,n){if(!e.length)return;if(t.length===0){for(let s=0;s<e.length;++s)n.push(e.subarray(s,s+1));return}if(t.length===1){let s=t[0],i=e.indexOf(s);for(;i!==-1;){let o=e.subarray(0,i);(!a||o.length!==0)&&n.push(o),e=e.subarray(i+1),i=e.indexOf(s)}(!a||e.length!==0)&&n.push(e);return}let r=0;for(let s=0;s<e.length+1;s++)if(s===e.length||t.indexOf(e[s])!==-1){let i=e.subarray(r,s);(!a||i.length!==0)&&n.push(i),r=s+1}}function h3(e,t,a){let n=e.length,r=[],s=0,i=0,o=new Array(n);for(let d=0;d<n;++d){let h=r.length;EO(e[d],t,a,r);let f=r.length-h;o[d]=f,s+=f,i=Math.max(i,f)}let l=v.getArrayFromDType("int32",s*2),u=new Array(s),p=[n,i],c=0;for(let d=0;d<n;++d)for(let h=0;h<o[d];++h)l[c*2]=d,l[c*2+1]=h,u[c]=r[c],++c;return[l,u,p]}function f3(e,t){let a=v.getArrayFromDType("int32",e.length);for(let n=0;n<e.length;++n)a[n]=v.fingerPrint64(e[n]).modulo(t).getLowBitsUnsigned();return a}var S7=Lt((e,t)=>e-t),RO=s3((e,t,a,n)=>({real:e-a,imag:t-n})),m3=Yt(lo,S7,RO),MO={kernelName:lo,backendName:"cpu",kernelFunc:m3};function T7(e,t){let a=new Array(e.rank);for(let r=0;r<a.length;r++)a[r]=e.shape[r]*t[r];let n=Me(a,e.dtype);for(let r=0;r<n.values.length;++r){let s=n.indexToLoc(r),i=new Array(e.rank);for(let l=0;l<i.length;l++)i[l]=s[l]%e.shape[l];let o=e.locToIndex(i);n.values[r]=e.values[o]}return n}var Hu=(e,t)=>{let a=t.value-e.value;return a===0?e.index-t.index:a};function C7(e,t,a=0,n=e.length-1){for(;n>a;){if(n-a>600){let o=n-a+1,l=t-a+1,u=Math.log(o),p=.5*Math.exp(2*u/3),c=.5*Math.sqrt(u*p*(o-p)/o)*Math.sign(l-o/2),d=Math.max(a,Math.floor(t-l*p/o+c)),h=Math.min(n,Math.floor(t+(o-l)*p/o+c));C7(e,t,d,h)}let r=e[t],s=a,i=n;for(v.swap(e,a,t),Hu(e[n],r)>0&&v.swap(e,a,n);s<i;){for(v.swap(e,s,i),s++,i--;Hu(e[s],r)<0;)s=s+1;for(;Hu(e[i],r)>0;)i=i-1}Hu(e[a],r)===0?v.swap(e,a,i):(i=i+1,v.swap(e,i,n)),i<=t&&(a=i+1),t<=i&&(n=i-1)}}function N7(e,t,a,n,r){let s=t[t.length-1],[i,o]=[e.length/s,s],l=v.getTypedArrayFromDType(a,i*n),u=v.getTypedArrayFromDType("int32",i*n);for(let c=0;c<i;c++){let d=c*o,h=e.subarray(d,d+o),f=new Array(h.length);h.forEach((A,y)=>f[y]={value:A,index:y}),n<f.length&&(C7(f,n),f=f.slice(0,n)),r&&f.sort(Hu);let m=c*n,g=l.subarray(m,m+n),x=u.subarray(m,m+n);for(let A=0;A<n;A++)g[A]=f[A].value,x[A]=f[A].index}let p=t.slice();return p[p.length-1]=n,[Me(p,a,l),Me(p,"int32",u)]}function E7(e,t,a,n){let r=v.parseAxisParam(t,a)[0],s=[1,a[0],1];for(let f=0;f<r;f++)s[0]*=a[f];s[1]=a[r];for(let f=r+1;f<a.length;f++)s[2]*=a[f];let i={},o=new Int32Array(a[r]),l=new jt(s,n,e),u=[],p=s[0]===1&&s[2]===1;for(let f=0;f<a[r];f++){let m;if(p)m=e[f].toString();else{let g=[];for(let x=0;x<s[0];x++)for(let A=0;A<s[2];A++)g.push(l.get(x,f,A));m=g.join(",")}if(i[m]!==void 0)o[f]=i[m];else{let g=Object.keys(i).length;i[m]=g,o[f]=g,u.push(f)}}let c=s.slice();c[1]=Object.keys(i).length;let d=new jt(c,n);u.forEach((f,m)=>{for(let g=0;g<s[0];g++)for(let x=0;x<s[2];x++)d.set(l.get(g,f,x),g,m,x)});let h=a.slice();return h[r]=c[1],{outputValues:d.values,outputShape:h,indices:o}}var $O="4.1.0";go("cpu",()=>new $h,1);var R7=ot(hi,e=>e>=0?e:Math.exp(e)-1),_O={kernelName:hi,backendName:"cpu",kernelFunc:R7};function M7(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{alpha:s}=n;ye([r],"leakyRelu");let i=v.sizeFromShape(r.shape),o=a.data.get(r.dataId).values,l=v.getTypedArrayFromDType("float32",i);for(let u=0;u<o.length;u++)l[u]=o[u]<0?s*o[u]:o[u];return a.makeTensorInfo(r.shape,"float32",l)}var PO={kernelName:Si,backendName:"cpu",kernelFunc:M7},FO=Lt((e,t)=>e<0?t*e:e);function $7(e){let{inputs:t,backend:a}=e,{x:n,alpha:r}=t;ye([n,r],"prelu");let s=a.data.get(n.dataId).values,i=a.data.get(r.dataId).values,[o,l]=FO(n.shape,r.shape,s,i,"float32");return a.makeTensorInfo(l,"float32",o)}var OO={kernelName:Hi,backendName:"cpu",kernelFunc:$7},_7=ot(Xi,e=>Math.max(0,e)),DO={kernelName:Xi,backendName:"cpu",kernelFunc:_7},P7=ot(Yi,e=>Math.min(Math.max(0,e),6)),zO={kernelName:Yi,backendName:"cpu",kernelFunc:P7};function Pc(e,t,a,n,r){if(a==="linear")return er({inputs:{x:t},backend:e});if(a==="relu")return _7({inputs:{x:t},backend:e});if(a==="elu")return R7({inputs:{x:t},backend:e});if(a==="relu6")return P7({inputs:{x:t},backend:e});if(a==="prelu")return $7({inputs:{x:t,alpha:n},backend:e});if(a==="leakyrelu")return M7({inputs:{x:t},backend:e,attrs:{alpha:r}});if(a==="sigmoid")return b7({inputs:{x:t},backend:e});throw new Error(`Activation ${a} has not been implemented for the CPU backend.`)}function mt(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{shape:s}=n,i=v.sizeFromShape(r.shape),o=v.inferFromImplicitShape(s,i),l=v.sizeFromShape(o);v.assert(i===l,()=>`The new shape (${o}) has ${l} elements and the old shape (${r.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`),a.incRef(r.dataId);let u=a.data.get(r.dataId);if(u.complexTensorInfos!=null){let p=u.complexTensorInfos.real,c=u.complexTensorInfos.imag;p.shape=o,c.shape=o}return{dataId:r.dataId,shape:o,dtype:r.dtype}}var LO={kernelName:ql,backendName:"cpu",kernelFunc:mt};function F7(e){let{inputs:t,backend:a,attrs:n}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=n;ye([r,s],"matMul");let l=r.shape.length,u=s.shape.length,p=i?r.shape[l-2]:r.shape[l-1],c=o?s.shape[u-1]:s.shape[u-2],d=i?r.shape[l-1]:r.shape[l-2],h=o?s.shape[u-2]:s.shape[u-1],f=r.shape.slice(0,-2),m=s.shape.slice(0,-2),g=v.sizeFromShape(f),x=v.sizeFromShape(m),A=xo.assertAndGetBroadcastShape(r.shape.slice(0,-2),s.shape.slice(0,-2)).concat([d,h]);v.assert(p===c,()=>`Error in matMul: inner shapes (${p}) and (${c}) of Tensors with shapes ${r.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let y=i?[g,p,d]:[g,d,p],b=o?[x,h,c]:[x,c,h],w=mt({inputs:{x:r},backend:a,attrs:{shape:y}}),S=mt({inputs:{x:s},backend:a,attrs:{shape:b}}),C=i?w.shape[1]:w.shape[2],E=i?w.shape[2]:w.shape[1],_=o?S.shape[1]:S.shape[2],$=Math.max(g,x),M=a.data.get(w.dataId).values,I=a.data.get(S.dataId).values,N=v.computeStrides(w.shape),O=v.computeStrides(S.shape),[L,B,G]=i?[N[0],1,N[1]]:[N[0],N[1],1],[j,U,H]=o?[1,O[1],O[0]]:[O[1],1,O[0]],V=E*_,Q=Me([$,E,_],w.dtype),Z=Q.values,re=a.blockSize;for(let ee=0;ee<$;ee++)for(let he=0;he<E;he+=re)for(let oe=0;oe<_;oe+=re)for(let Ae=0;Ae<C;Ae+=re){let we=Math.min(he+re,E),Re=Math.min(oe+re,_),Ge=Math.min(Ae+re,C);for(let Ke=he;Ke<we;Ke++)for(let nt=oe;nt<Re;nt++){let ut=0;for(let et=Ae;et<Ge;et++){let rt=Math.min(ee,g-1)*L,je=Math.min(ee,x-1)*H,ht=M[rt+Ke*B+et*G],Va=I[et*j+nt*U+je];ut+=ht*Va}Z[ee*V+(Ke*_+nt)]+=ut}}return a.disposeIntermediateTensorInfo(w),a.disposeIntermediateTensorInfo(S),a.makeTensorInfo(A,Q.dtype,Q.values)}var BO={kernelName:ei,backendName:"cpu",kernelFunc:F7};function WO(e){let{inputs:t,backend:a,attrs:n}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:p,leakyreluAlpha:c}=n,d,h,f,m=[];d=F7({inputs:{a:r,b:s},attrs:{transposeA:l,transposeB:u},backend:a}),i&&(h=ml({inputs:{a:d,b:i},backend:a}),m.push(d),d=h),p&&(f=Pc(a,d,p,o,c),m.push(d),d=f);for(let g of m)a.disposeIntermediateTensorInfo(g);return d}var VO={kernelName:jr,backendName:"cpu",kernelFunc:WO},UO=ot(kl,e=>Math.acos(e)),GO={kernelName:kl,backendName:"cpu",kernelFunc:UO},HO=ot(Il,e=>Math.acosh(e)),jO={kernelName:Il,backendName:"cpu",kernelFunc:HO};function qO(e){let{inputs:t,backend:a}=e,n=t;ye(t,"addN");let r=n.map(o=>a.data.get(o.dataId).values),s=Me(n[0].shape,n[0].dtype),i=s.values;for(let o=0;o<n.length;o++){let l=r[o];for(let u=0;u<i.length;u++)i[u]+=l[u]}return a.makeTensorInfo(s.shape,s.dtype,s.values)}var XO={kernelName:Ks,backendName:"cpu",kernelFunc:qO};function KO(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;ye(r,"all");let o=v.parseAxisParam(s,r.shape),l=o,u=T.getAxesPermutation(l,r.shape.length),p=r;u!=null&&(p=La({inputs:{x:r},backend:a,attrs:{perm:u}}),l=T.getInnerMostAxes(l.length,r.shape.length)),T.assertAxesAreInnerMostDims("all",l,p.shape.length);let[c,d]=T.computeOutAndReduceShapes(p.shape,l),h=v.sizeFromShape(d),f=v.makeZerosTypedArray(v.sizeFromShape(c),p.dtype),m=a.data.get(p.dataId).values;for(let x=0;x<f.length;++x){let A=x*h,y=m[A];for(let b=0;b<h;++b){let w=m[A+b];y=y&&w}f[x]=y}u!=null&&a.disposeIntermediateTensorInfo(p);let g=a.makeTensorInfo(c,p.dtype,f);if(i){let x=T.expandShapeToKeepDim(c,o),A=mt({inputs:{x:g},backend:a,attrs:{shape:x}});return a.disposeIntermediateTensorInfo(g),A}return g}var ZO={kernelName:Zs,backendName:"cpu",kernelFunc:KO};function YO(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;ye(r,"any");let o=v.parseAxisParam(s,r.shape),l=o,u=T.getAxesPermutation(l,r.shape.length),p=r;u!=null&&(p=La({inputs:{x:r},backend:a,attrs:{perm:u}}),l=T.getInnerMostAxes(l.length,r.shape.length)),T.assertAxesAreInnerMostDims("any",l,p.shape.length);let[c,d]=T.computeOutAndReduceShapes(p.shape,l),h=v.sizeFromShape(d),f=v.makeZerosTypedArray(v.sizeFromShape(c),p.dtype),m=a.data.get(p.dataId).values;for(let x=0;x<f.length;++x){let A=x*h,y=m[A];for(let b=0;b<h;++b){let w=m[A+b];y=y||w}f[x]=y}u!=null&&a.disposeIntermediateTensorInfo(p);let g=a.makeTensorInfo(c,p.dtype,f);if(i){let x=T.expandShapeToKeepDim(c,o),A=mt({inputs:{x:g},backend:a,attrs:{shape:x}});return a.disposeIntermediateTensorInfo(g),A}return g}var JO={kernelName:Ys,backendName:"cpu",kernelFunc:YO};function QO(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s}=n;ye(r,"argMax");let i=v.parseAxisParam(s,r.shape),o=T.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=La({inputs:{x:r},backend:a,attrs:{perm:o}}),u.push(l),i=T.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],T.assertAxesAreInnerMostDims("argMax",i,l.shape.length);let[p,c]=T.computeOutAndReduceShapes(l.shape,i),d=v.sizeFromShape(p),h=v.makeZerosTypedArray(d,"int32"),f=v.sizeFromShape(c),m=a.data.get(l.dataId).values;for(let g=0;g<h.length;++g){let x=g*f,A=m[x],y=0;for(let b=0;b<f;++b){let w=m[x+b];w>A&&(A=w,y=b)}h[g]=y}return u.forEach(g=>a.disposeIntermediateTensorInfo(g)),a.makeTensorInfo(p,"int32",h)}var eD={kernelName:Js,backendName:"cpu",kernelFunc:QO};function tD(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s}=n;ye(r,"argMin");let i=v.parseAxisParam(s,r.shape),o=T.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=La({inputs:{x:r},backend:a,attrs:{perm:o}}),u.push(l),i=T.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],T.assertAxesAreInnerMostDims("argMin",i,l.shape.length);let[p,c]=T.computeOutAndReduceShapes(l.shape,i),d=v.sizeFromShape(p),h=v.makeZerosTypedArray(d,"int32"),f=v.sizeFromShape(c),m=a.data.get(l.dataId).values;for(let g=0;g<h.length;++g){let x=g*f,A=m[x],y=0;for(let b=0;b<f;++b){let w=m[x+b];w<A&&(A=w,y=b)}h[g]=y}return u.forEach(g=>a.disposeIntermediateTensorInfo(g)),a.makeTensorInfo(p,"int32",h)}var aD={kernelName:kd,backendName:"cpu",kernelFunc:tD},nD=ot(Sl,e=>Math.asin(e)),rD={kernelName:Sl,backendName:"cpu",kernelFunc:nD},sD=ot(Tl,e=>Math.asinh(e)),iD={kernelName:Tl,backendName:"cpu",kernelFunc:sD},oD=ot(Cl,e=>Math.atan(e)),lD={kernelName:Cl,backendName:"cpu",kernelFunc:oD},uD=Lt((e,t)=>Math.atan2(e,t)),dD=Yt(El,uD),pD={kernelName:El,backendName:"cpu",kernelFunc:dD},cD=ot(Nl,e=>Math.atanh(e)),hD={kernelName:Nl,backendName:"cpu",kernelFunc:cD};function g3(e,t,a,n,r,s){let i=r.strideHeight,o=r.strideWidth,l=r.dilationHeight,u=r.dilationWidth,p=r.effectiveFilterHeight,c=r.effectiveFilterWidth,d=r.padInfo.top,h=r.padInfo.left,f=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=Me(r.outShape,a),g=m.values,x=r.outShape[1]*r.outShape[2]*r.outShape[3],A=r.outShape[2]*r.outShape[3],y=r.outShape[3];for(let b=0;b<r.batchSize;++b){let w=b*x,S=b*n[0];for(let C=0;C<r.inChannels;++C)for(let E=0;E<r.outHeight;++E){let _=E*i-d,$=Math.max(0,_),M=Math.min(r.inHeight,p+_),I=w+E*A;for(let N=0;N<r.outWidth;++N){let O=N*o-h,L=Math.max(0,O),B=Math.min(r.inWidth,c+O),G=f,j=0,U=0;for(let V=$;V<M;V+=l){let Q=S+V*n[1];for(let Z=L;Z<B;Z+=u){let re=Q+Z*n[2],ee=e[re+C];s==="max"&&ee>G?G=ee:s==="avg"&&(j+=ee,U++)}if(isNaN(G))break}let H=I+N*y+C;g[H]=s==="avg"?j/U:G}}}return m}function O7(e,t,a,n,r=!1,s=!1){let i=Me(n.outShape,"int32"),o=n.strideHeight,l=n.strideWidth,u=n.dilationHeight,p=n.dilationWidth,c=n.effectiveFilterHeight,d=n.effectiveFilterWidth,h=n.padInfo.top,f=n.padInfo.left,m=Me(t,a,e);for(let g=0;g<n.batchSize;++g)for(let x=0;x<n.inChannels;++x)for(let A=0;A<n.outHeight;++A){let y=A*o-h,b=y;for(;b<0;)b+=u;let w=Math.min(n.inHeight,c+y);for(let S=0;S<n.outWidth;++S){let C=S*l-f,E=C;for(;E<0;)E+=p;let _=Math.min(n.inWidth,d+C),$=Number.NEGATIVE_INFINITY,M=-1;for(let I=b;I<w;I+=u){let N=I-y;for(let O=E;O<_;O+=p){let L=O-C,B=m.get(g,I,O,x);B>$&&($=B,r?M=s?((g*n.inHeight+I)*n.inWidth+O)*n.inChannels+x:(I*n.inWidth+O)*n.inChannels+x:M=N*d+L)}}i.set(M,g,A,S,x)}}return i}function D7(e,t,a,n,r,s){let i=r.strideDepth,o=r.strideHeight,l=r.strideWidth,u=r.dilationDepth,p=r.dilationHeight,c=r.dilationWidth,d=r.effectiveFilterDepth,h=r.effectiveFilterHeight,f=r.effectiveFilterWidth,m=r.padInfo.front,g=r.padInfo.top,x=r.padInfo.left,A=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,y=Me(r.outShape,a),b=y.values,w=r.outShape[1]*r.outShape[2]*r.outShape[3]*r.outShape[4],S=r.outShape[2]*r.outShape[3]*r.outShape[4],C=r.outShape[3]*r.outShape[4],E=r.outShape[4];for(let _=0;_<r.batchSize;++_){let $=_*w,M=_*n[0];for(let I=0;I<r.inChannels;++I)for(let N=0;N<r.outDepth;++N){let O=N*i-m,L=O;for(;L<0;)L+=u;let B=Math.min(r.inDepth,d+O),G=$+N*S;for(let j=0;j<r.outHeight;++j){let U=j*o-g,H=U;for(;H<0;)H+=p;let V=Math.min(r.inHeight,h+U),Q=G+j*C;for(let Z=0;Z<r.outWidth;++Z){let re=Z*l-x,ee=re;for(;ee<0;)ee+=c;let he=Math.min(r.inWidth,f+re),oe=Q+Z*E,Ae=A,we=0,Re=0;for(let Ke=L;Ke<B;Ke+=u){let nt=M+Ke*n[1];for(let ut=H;ut<V;ut+=p){let et=nt+ut*n[2];for(let rt=ee;rt<he;rt+=c){let je=et+rt*n[3],ht=e[je+I];if(s==="max"&&ht>Ae?Ae=ht:s==="avg"&&(we+=ht,Re++),isNaN(Ae))break}if(isNaN(Ae))break}if(isNaN(Ae))break}let Ge=oe+I;b[Ge]=s==="avg"?we/Re:Ae}}}}return y}function fD(e,t){let a=Me(t.outShape,"int32"),n=t.strideDepth,r=t.strideHeight,s=t.strideWidth,i=t.dilationDepth,o=t.dilationHeight,l=t.dilationWidth,u=t.effectiveFilterDepth,p=t.effectiveFilterHeight,c=t.effectiveFilterWidth,d=t.padInfo.front,h=t.padInfo.top,f=t.padInfo.left;for(let m=0;m<t.batchSize;++m)for(let g=0;g<t.inChannels;++g)for(let x=0;x<t.outDepth;++x){let A=x*n-d,y=A;for(;y<0;)y+=i;let b=Math.min(t.inDepth,u+A);for(let w=0;w<t.outHeight;++w){let S=w*r-h,C=S;for(;C<0;)C+=o;let E=Math.min(t.inHeight,p+S);for(let _=0;_<t.outWidth;++_){let $=_*s-f,M=$;for(;M<0;)M+=l;let I=Math.min(t.inWidth,c+$),N=Number.NEGATIVE_INFINITY,O=-1;for(let L=y;L<b;L+=i){let B=L-A;for(let G=C;G<E;G+=o){let j=G-S;for(let U=M;U<I;U+=l){let H=U-$,V=e.get(m,L,G,U,g);V>=N&&(N=V,O=B*p*c+j*p+H)}}}a.set(O,m,x,w,_,g)}}}return a}function mD(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t;ye(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1;v.assert(T.eitherStridesOrDilationsAreOne(i,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=T.computePool2DInfo(r.shape,s,i,u,o,l),c;if(p.filterWidth===1&&p.filterHeight===1&&v.arraysEqual(p.inShape,p.outShape))c=er({inputs:{x:r},backend:a});else{let d=a.data.get(r.dataId).values,h=v.computeStrides(r.shape),f=g3(d,r.shape,r.dtype,h,p,"avg");c=a.makeTensorInfo(p.outShape,r.dtype,f.values)}return c}var gD={kernelName:Qs,backendName:"cpu",kernelFunc:mD};function xD(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=n;ye(r,"avgPool3d");let p=T.computePool3DInfo(r.shape,s,i,1,o,l,u),c=a.data.get(r.dataId).values,d=D7(c,r.shape,r.dtype,v.computeStrides(r.shape),p,"avg");return a.makeTensorInfo(d.shape,"float32",d.values)}var AD={kernelName:Hc,backendName:"cpu",kernelFunc:xD};function yD(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=n;ye([r,s],"avgPool3DGrad");let p=T.computePool3DInfo(s.shape,i,o,1,l,u),c=p.strideDepth,d=p.strideHeight,h=p.strideWidth,f=p.filterDepth,m=p.filterHeight,g=p.filterWidth,x=p.dilationDepth,A=p.dilationHeight,y=p.dilationWidth,b=p.effectiveFilterDepth,w=p.effectiveFilterHeight,S=p.effectiveFilterWidth,C=b-1-p.padInfo.front,E=S-1-p.padInfo.left,_=w-1-p.padInfo.top,$=Me(s.shape,"float32"),M=1/(f*m*g),I=a.bufferSync(r);for(let N=0;N<p.batchSize;++N)for(let O=0;O<p.inChannels;++O)for(let L=0;L<p.inDepth;++L)for(let B=0;B<p.inHeight;++B)for(let G=0;G<p.inWidth;++G){let j=L-C,U=B-_,H=G-E,V=0;for(let Q=0;Q<b;Q+=x){let Z=(j+Q)/c;if(!(Z<0||Z>=p.outDepth||Math.floor(Z)!==Z))for(let re=0;re<w;re+=A){let ee=(U+re)/d;if(!(ee<0||ee>=p.outHeight||Math.floor(ee)!==ee))for(let he=0;he<S;he+=y){let oe=(H+he)/h;if(oe<0||oe>=p.outWidth||Math.floor(oe)!==oe)continue;let Ae=I.get(N,Z,ee,oe,O);V+=Ae}}}$.set(V*M,N,L,B,G,O)}return a.makeTensorInfo($.shape,$.dtype,$.values)}var bD={kernelName:G1,backendName:"cpu",kernelFunc:yD};function vD(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,i=s;ye([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:u}=n,p=T.computePool2DInfo(i.shape,o,l,1,u),c=p.strideHeight,d=p.strideWidth,h=p.filterHeight,f=p.filterWidth,m=p.dilationHeight,g=p.dilationWidth,x=p.effectiveFilterHeight,A=p.effectiveFilterWidth,y=A-1-p.padInfo.left,b=x-1-p.padInfo.top,w=Me(i.shape,"float32"),S=1/(h*f),C=a.data.get(r.dataId).values,E=Me(r.shape,"float32",C);for(let _=0;_<p.batchSize;++_)for(let $=0;$<p.inChannels;++$)for(let M=0;M<p.inHeight;++M)for(let I=0;I<p.inWidth;++I){let N=M-b,O=I-y,L=0;for(let B=0;B<x;B+=m){let G=(N+B)/c;if(!(G<0||G>=p.outHeight||Math.floor(G)!==G))for(let j=0;j<A;j+=g){let U=(O+j)/d;if(U<0||U>=p.outWidth||Math.floor(U)!==U)continue;let H=E.get(_,G,U,$);L+=H}}w.set(L*S,_,M,I,$)}return a.makeTensorInfo(w.shape,w.dtype,w.values)}var wD={kernelName:U1,backendName:"cpu",kernelFunc:vD};function kD(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,scale:s,offset:i,mean:o,variance:l}=t;v.assert(o.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),v.assert(i==null||o.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),v.assert(s==null||o.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),ye([r,o,l,s,i],"batchNorm");let{varianceEpsilon:u}=n;u==null&&(u=.001);let p=a.data.get(r.dataId).values,c=a.data.get(o.dataId).values,d=a.data.get(l.dataId).values,h=s?a.data.get(s.dataId).values:new Float32Array([1]),f=i?a.data.get(i.dataId).values:new Float32Array([0]),m=new Float32Array(p.length),g=f.length,x=h.length,A=d.length,y=c.length,b=0,w=0,S=0,C=0;for(let E=0;E<p.length;++E)m[E]=f[b++]+(p[E]-c[w++])*h[S++]/Math.sqrt(d[C++]+u),b>=g&&(b=0),w>=y&&(w=0),S>=x&&(S=0),C>=A&&(C=0);return a.makeTensorInfo(r.shape,r.dtype,m)}var ID={kernelName:yi,backendName:"cpu",kernelFunc:kD};function SD(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{blockShape:s,crops:i}=n;ye([r],"batchToSpaceND");let o=s.reduce((x,A)=>x*A),l=T.getReshaped(r.shape,s,o),u=T.getPermuted(l.length,s.length),p=T.getReshapedPermuted(r.shape,s,o),c=T.getSliceBeginCoords(i,s.length),d=T.getSliceSize(p,i,s.length),h=mt({inputs:{x:r},backend:a,attrs:{shape:l}}),f=La({inputs:{x:h},backend:a,attrs:{perm:u}}),m=mt({inputs:{x:f},backend:a,attrs:{shape:p}}),g=Gs({inputs:{x:m},backend:a,attrs:{begin:c,size:d}});return a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(f),a.disposeIntermediateTensorInfo(m),g}var TD={kernelName:Rl,backendName:"cpu",kernelFunc:SD};function CD(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,weights:s}=t,{size:i}=n,o=a.data.get(r.dataId).values,l=a.data.get(s.dataId).values,u=i3(o,l,s.dtype,s.shape,i);return a.makeTensorInfo([i],s.dtype,u)}var ND={kernelName:Id,backendName:"cpu",kernelFunc:CD};function ED(e){let{inputs:t,backend:a}=e,{s0:n,s1:r}=t,s=a.data.get(n.dataId).values,i=a.data.get(r.dataId).values,o=T.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return a.makeTensorInfo([o.length],"int32",Int32Array.from(o))}var RD={kernelName:jc,backendName:"cpu",kernelFunc:ED},MD=ot(as,(e,t)=>{let a=t;return e>a.clipValueMax?a.clipValueMax:e<a.clipValueMin?a.clipValueMin:e}),$D={kernelName:as,backendName:"cpu",kernelFunc:MD},_D=e=>{let{x:t}=e.inputs,a=e.backend,n=new Float32Array(v.sizeFromShape(t.shape)),r=a.data.get(t.dataId),s=r.complexTensorInfos.real,i=r.complexTensorInfos.imag,o=a.data.get(s.dataId).values,l=a.data.get(i.dataId).values;for(let u=0;u<o.length;u++){let p=o[u],c=l[u];n[u]=Math.hypot(p,c)}return a.makeOutput(n,t.shape,"float32")},PD={kernelName:qc,backendName:"cpu",kernelFunc:_D};function gl(e){let{inputs:t,backend:a}=e,{input:n}=t,r=a.data.get(n.dataId).complexTensorInfos.imag,s=a.data.get(r.dataId).values;return a.makeTensorInfo(r.shape,r.dtype,s)}var FD={kernelName:Rd,backendName:"cpu",kernelFunc:gl};function xl(e){let{inputs:t,backend:a,attrs:n}=e,{axis:r}=n,s=v.parseAxisParam(r,t[0].shape)[0],i=t.map(m=>m.shape);T.assertParamsConsistent(i,s);let o=T.computeOutShape(t.map(m=>m.shape),s);if(v.sizeFromShape(o)===0)return a.makeTensorInfo(o,t[0].dtype,[]);let l=t.filter(m=>v.sizeFromShape(m.shape)>0);if(l.length===1)return er({inputs:{x:l[0]},backend:a});if(l[0].dtype==="complex64"){let m=l.map(b=>Us({inputs:{input:b},backend:a})),g=l.map(b=>gl({inputs:{input:b},backend:a})),x=xl({inputs:m,backend:a,attrs:{axis:s}}),A=xl({inputs:g,backend:a,attrs:{axis:s}}),y=Xa({inputs:{real:x,imag:A},backend:a});return m.forEach(b=>a.disposeIntermediateTensorInfo(b)),g.forEach(b=>a.disposeIntermediateTensorInfo(b)),a.disposeIntermediateTensorInfo(x),a.disposeIntermediateTensorInfo(A),y}let u=l.map(m=>{let g=[-1,v.sizeFromShape(m.shape.slice(s))];return mt({inputs:{x:m},backend:a,attrs:{shape:g}})}),p=u.map(m=>({vals:a.data.get(m.dataId).values,shape:m.shape}));o=T.computeOutShape(u.map(m=>m.shape),1);let c=u[0].shape[0]===1,d=o3(p,o,t[0].dtype,c),h=T.computeOutShape(l.map(m=>m.shape),s),f=a.makeTensorInfo(h,t[0].dtype,d);return u.forEach(m=>a.disposeIntermediateTensorInfo(m)),f}var OD={kernelName:Ml,backendName:"cpu",kernelFunc:xl};function z7(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:p}=n;ye([r,s],"conv2d");let c=T.convertConv2DDataFormat(l),d=T.computeConv2DInfo(r.shape,s.shape,i,u,o,p,!1,c),h=d.filterHeight,f=d.filterWidth,m=d.dilationHeight,g=d.dilationWidth,x=d.padInfo.left,A=d.padInfo.top,y=d.dataFormat==="channelsLast",b=new jt(d.outShape,r.dtype),w=v.computeStrides(r.shape),S=v.computeStrides(s.shape),C=w[0],E=y?w[1]:w[2],_=y?w[2]:1,$=y?1:w[1],M=b.strides[0],I=y?b.strides[1]:b.strides[2],N=y?b.strides[2]:1,O=y?1:b.strides[1],L=a.data.get(r.dataId).values,B=a.data.get(s.dataId).values,G=b.values;for(let j=0;j<d.batchSize;++j){let U=j*C,H=j*M;for(let V=0;V<d.outHeight;++V){let Q=H+V*I,Z=V*d.strideHeight-A;for(let re=0;re<h;++re){let ee=Z+re*m;if(ee<0||ee>=d.inHeight)continue;let he=re*S[0],oe=U+ee*E;for(let Ae=0;Ae<d.outWidth;++Ae){let we=Q+Ae*N,Re=Ae*d.strideWidth-x;for(let Ge=0;Ge<f;++Ge){let Ke=Re+Ge*g;if(Ke<0||Ke>=d.inWidth)continue;let nt=he+Ge*S[1],ut=oe+Ke*_,et=nt;for(let rt=0;rt<d.inChannels;++rt){let je=L[ut+rt*$];for(let ht=0;ht<d.outChannels;++ht)G[we+ht*O]+=je*B[et+ht];et+=d.outChannels}}}}}}return a.makeTensorInfo(b.shape,b.dtype,G)}var DD={kernelName:ni,backendName:"cpu",kernelFunc:z7};function zD(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:p}=n;ye([r,s],"conv2dBackpropFilter");let c=T.convertConv2DDataFormat(l),d=T.computeConv2DInfo(r.shape,p,i,1,o,u,!1,c),{strideHeight:h,strideWidth:f,filterHeight:m,filterWidth:g}=d,x=d.dataFormat==="channelsLast",A=new jt(d.filterShape,"float32"),y=d.padInfo.left,b=d.padInfo.top,w=a.data.get(r.dataId).values,S=a.data.get(s.dataId).values,C=new jt(r.shape,r.dtype,w),E=new jt(s.shape,s.dtype,S);for(let _=0;_<m;++_){let $=Math.max(0,Math.ceil((b-_)/h)),M=Math.min(d.outHeight,(d.inHeight+b-_)/h);for(let I=0;I<g;++I){let N=Math.max(0,Math.ceil((y-I)/f)),O=Math.min(d.outWidth,(d.inWidth+y-I)/f);for(let L=0;L<d.inChannels;++L)for(let B=0;B<d.outChannels;++B){let G=0;for(let j=0;j<d.batchSize;++j)for(let U=$;U<M;++U){let H=_+U*h-b;for(let V=N;V<O;++V){let Q=I+V*f-y;x?G+=C.get(j,H,Q,L)*E.get(j,U,V,B):G+=C.get(j,L,H,Q)*E.get(j,B,U,V)}}A.set(G,_,I,L,B)}}}return a.makeTensorInfo(A.shape,A.dtype,A.values)}var LD={kernelName:Xc,backendName:"cpu",kernelFunc:zD};function BD(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:p}=n;ye([r,s],"conv2dBackpropInput");let c=v.computeStrides(s.shape),d=v.computeStrides(r.shape),h=T.convertConv2DDataFormat(u),f=T.computeConv2DInfo(i,s.shape,o,1,l,p,!1,h),m=new jt(f.inShape,"float32"),g=m.values,x=a.data.get(r.dataId).values,A=a.data.get(s.dataId).values,[y,b,w]=c,{batchSize:S,filterHeight:C,filterWidth:E,inChannels:_,inHeight:$,inWidth:M,outChannels:I,outHeight:N,outWidth:O,strideHeight:L,strideWidth:B}=f;h=f.dataFormat;let G=C-1-f.padInfo.top,j=E-1-f.padInfo.left,U=h==="channelsLast",H=m.strides[0],V=U?m.strides[1]:m.strides[2],Q=U?m.strides[2]:1,Z=U?1:m.strides[1],re=d[0],ee=U?d[1]:d[2],he=U?d[2]:1,oe=U?1:d[1];for(let Ae=0;Ae<S;++Ae)for(let we=0;we<_;++we)for(let Re=0;Re<$;++Re){let Ge=Re-G,Ke=Math.max(0,Math.ceil(Ge/L)),nt=Math.min(N,(C+Ge)/L);for(let ut=0;ut<M;++ut){let et=ut-j,rt=Math.max(0,Math.ceil(et/B)),je=Math.min(O,(E+et)/B),ht=0;for(let Ft=Ke;Ft<nt;++Ft){let sn=Ft*L-Ge;for(let aa=rt;aa<je;++aa){let $a=aa*B-et,on=re*Ae+ee*Ft+he*aa,_a=y*(C-1-sn)+b*(E-1-$a)+w*we;for(let dt=0;dt<I;++dt){let Pa=x[on+oe*dt],Ua=A[_a+dt];ht+=Pa*Ua}}}let Va=H*Ae+V*Re+Q*ut+Z*we;g[Va]=ht}}return a.makeTensorInfo(m.shape,m.dtype,m.values)}var WD={kernelName:ri,backendName:"cpu",kernelFunc:BD};function VD(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=n;ye([r,s],"conv3d");let u=T.computeConv3DInfo(r.shape,s.shape,i,l,o),{filterDepth:p,filterHeight:c,filterWidth:d,dilationDepth:h,dilationHeight:f,dilationWidth:m,padInfo:g}=u,x=g.front,A=g.left,y=g.top,b=new jt(u.outShape,r.dtype),w=a.data.get(r.dataId).values,S=a.data.get(s.dataId).values,C=b.values,E=v.computeStrides(r.shape),_=v.computeStrides(s.shape);for(let $=0;$<u.batchSize;++$){let M=$*E[0],I=$*b.strides[0];for(let N=0;N<u.outDepth;++N){let O=I+N*b.strides[1],L=N*u.strideDepth-x;for(let B=0;B<p;++B){let G=L+B*h;if(G<0||G>=u.inDepth)continue;let j=B*_[0],U=M+G*E[1];for(let H=0;H<u.outHeight;++H){let V=O+H*b.strides[2],Q=H*u.strideHeight-y;for(let Z=0;Z<c;++Z){let re=Q+Z*f;if(re<0||re>=u.inHeight)continue;let ee=j+Z*_[1],he=U+re*E[2];for(let oe=0;oe<u.outWidth;++oe){let Ae=V+oe*u.outChannels,we=oe*u.strideWidth-A;for(let Re=0;Re<d;++Re){let Ge=we+Re*m;if(Ge<0||Ge>=u.inWidth)continue;let Ke=ee+Re*_[2],nt=he+Ge*u.inChannels,ut=Ke;for(let et=0;et<u.inChannels;++et){let rt=w[nt+et];for(let je=0;je<u.outChannels;++je)C[Ae+je]+=rt*S[ut+je];ut+=u.outChannels}}}}}}}}return a.makeTensorInfo(b.shape,b.dtype,b.values)}var UD={kernelName:Kc,backendName:"cpu",kernelFunc:VD};function GD(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=n;ye([r,s],"conv3dBackpropFilterV2");let u=v.computeStrides(r.shape),p=v.computeStrides(s.shape),c=T.computeConv3DInfo(r.shape,l,i,1,o),d=c.strideDepth,h=c.strideHeight,f=c.strideWidth,m=c.filterDepth,g=c.filterHeight,x=c.filterWidth,A=new jt(c.filterShape,"float32"),y=A.values,[b,w,S,C]=A.strides,E=a.data.get(s.dataId).values,[_,$,M,I]=p,N=a.data.get(r.dataId).values,[O,L,B,G]=u,j=c.padInfo.front,U=c.padInfo.left,H=c.padInfo.top;for(let V=0;V<m;++V){let Q=Math.max(0,Math.ceil((j-V)/d)),Z=Math.min(c.outDepth,(c.inDepth+j-V)/d),re=V*b;for(let ee=0;ee<g;++ee){let he=Math.max(0,Math.ceil((H-ee)/h)),oe=Math.min(c.outHeight,(c.inHeight+H-ee)/h),Ae=ee*w+re;for(let we=0;we<x;++we){let Re=Math.max(0,Math.ceil((U-we)/f)),Ge=Math.min(c.outWidth,(c.inWidth+U-we)/f),Ke=we*S+Ae;for(let nt=0;nt<c.inChannels;++nt){let ut=nt*C+Ke;for(let et=0;et<c.outChannels;++et){let rt=0;for(let je=0;je<c.batchSize;++je){let ht=je*O,Va=je*_;for(let Ft=Q;Ft<Z;++Ft){let sn=(V+Ft*d-j)*L+ht,aa=Ft*$+Va;for(let $a=he;$a<oe;++$a){let on=(ee+$a*h-H)*B+sn,_a=$a*M+aa;for(let dt=Re;dt<Ge;++dt){let Pa=(we+dt*f-U)*G+on,Ua=dt*I+_a;rt+=N[Pa+nt]*E[Ua+et]}}}}y[ut+et]=rt}}}}}return a.makeTensorInfo(A.shape,A.dtype,A.values)}var HD={kernelName:H1,backendName:"cpu",kernelFunc:GD};function jD(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=n;ye([r],"conv3dBackpropInputV2");let u=v.computeStrides(r.shape),p=v.computeStrides(s.shape),c=T.computeConv3DInfo(l,s.shape,o,1,i),d=new jt(c.inShape,"float32"),h=d.values,[f,m,g,x]=d.strides,A=a.data.get(r.dataId).values,[y,b,w,S]=u,C=a.data.get(s.dataId).values,[E,_,$,M]=p,{batchSize:I,filterDepth:N,filterHeight:O,filterWidth:L,inChannels:B,inDepth:G,inHeight:j,inWidth:U,outChannels:H,outDepth:V,outHeight:Q,outWidth:Z,strideDepth:re,strideHeight:ee,strideWidth:he}=c,oe=N-1-c.padInfo.front,Ae=O-1-c.padInfo.top,we=L-1-c.padInfo.left;for(let Re=0;Re<I;++Re)for(let Ge=0;Ge<B;++Ge)for(let Ke=0;Ke<G;++Ke){let nt=Ke-oe,ut=Math.max(0,Math.ceil(nt/re)),et=Math.min(V,(N+nt)/re);for(let rt=0;rt<j;++rt){let je=rt-Ae,ht=Math.max(0,Math.ceil(je/ee)),Va=Math.min(Q,(O+je)/ee);for(let Ft=0;Ft<U;++Ft){let sn=Ft-we,aa=Math.max(0,Math.ceil(sn/he)),$a=Math.min(Z,(L+sn)/he),on=0;for(let _a=ut;_a<et;++_a){let dt=_a*re-nt;for(let Pa=ht;Pa<Va;++Pa){let Ua=Pa*ee-je;for(let ur=aa;ur<$a;++ur){let Bo=ur*he-sn,Un=y*Re+b*_a+w*Pa+S*ur,$u=E*(N-1-dt)+_*(O-1-Ua)+$*(L-1-Bo)+M*Ge;for(let bn=0;bn<H;++bn){let Wo=A[Un+bn],Xt=C[$u+bn];on+=Wo*Xt}}}}h[f*Re+m*Ke+g*rt+x*Ft+Ge]=on}}}return a.makeTensorInfo(d.shape,d.dtype,d.values)}var qD={kernelName:Zc,backendName:"cpu",kernelFunc:jD},XD=ot(si,e=>Math.cos(e)),KD={kernelName:si,backendName:"cpu",kernelFunc:XD},ZD=ot(ii,e=>Math.cosh(e)),YD={kernelName:ii,backendName:"cpu",kernelFunc:ZD};function JD(e){let{inputs:t,backend:a,attrs:n}=e,{image:r,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=n,[p,c,d,h]=r.shape,f=s.shape[0],[m,g]=o,x=Me([f,m,g,h],"float32"),A=a.data.get(s.dataId).values,y=a.data.get(i.dataId).values,b=a.data.get(r.dataId).values,w=v.computeStrides(r.shape),S=v.computeStrides(x.shape);for(let C=0;C<f;C++){let E=C*4,_=A[E],$=A[E+1],M=A[E+2],I=A[E+3],N=y[C];if(N>=p)continue;let O=m>1?(M-_)*(c-1)/(m-1):0,L=g>1?(I-$)*(d-1)/(g-1):0;for(let B=0;B<m;B++){let G=m>1?_*(c-1)+B*O:.5*(_+M)*(c-1);if(G<0||G>c-1){for(let j=0;j<g;j++)for(let U=0;U<h;U++){let H=U+j*S[2]+B*S[1]+C*S[0];x.values[H]=u}continue}if(l==="bilinear"){let j=Math.floor(G),U=Math.ceil(G),H=G-j;for(let V=0;V<g;V++){let Q=g>1?$*(d-1)+V*L:.5*($+I)*(d-1);if(Q<0||Q>d-1){for(let he=0;he<h;he++){let oe=he+V*S[2]+B*S[1]+C*S[0];x.values[oe]=u}continue}let Z=Math.floor(Q),re=Math.ceil(Q),ee=Q-Z;for(let he=0;he<h;he++){let oe=he+Z*w[2]+j*w[1]+N*w[0],Ae=b[oe];oe=he+re*w[2]+j*w[1]+N*w[0];let we=b[oe];oe=he+Z*w[2]+U*w[1]+N*w[0];let Re=b[oe];oe=he+re*w[2]+U*w[1]+N*w[0];let Ge=b[oe],Ke=Ae+(we-Ae)*ee,nt=Re+(Ge-Re)*ee;oe=he+V*S[2]+B*S[1]+C*S[0],x.values[oe]=Ke+(nt-Ke)*H}}}else for(let j=0;j<g;++j){let U=g>1?$*(d-1)+j*L:.5*($+I)*(d-1);if(U<0||U>d-1){for(let Q=0;Q<h;Q++){let Z=Q+j*S[2]+B*S[1]+C*S[0];x.values[Z]=u}continue}let H=Math.round(U),V=Math.round(G);for(let Q=0;Q<h;Q++){let Z=Q+H*w[2]+V*w[1]+N*w[0],re=Q+j*S[2]+B*S[1]+C*S[0];x.values[re]=b[Z]}}}}return a.makeTensorInfo(x.shape,x.dtype,x.values)}var QD={kernelName:ui,backendName:"cpu",kernelFunc:JD};function ez(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=n;ye(r,"cumprod");let l=T.getAxesPermutation([s],r.shape.length),u=r;l!=null&&(u=La({inputs:{x:r},backend:a,attrs:{perm:l}}));let p=T.getInnerMostAxes(1,r.shape.length)[0];if(p!==u.shape.length-1)throw new Error(`backend.cumprod in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${p}`);let c=ca(u.dtype,"int32"),d=v.makeOnesTypedArray(v.sizeFromShape(u.shape),c),h=a.data.get(u.dataId).values,f=u.shape[u.shape.length-1],m=o?(x,A)=>x+f-A-1:(x,A)=>x+A;for(let x=0;x<h.length;x+=f)for(let A=0;A<f;A++){let y=m(x,A);if(A===0)d[y]=i?1:h[y];else{let b=m(x,A-1);d[y]=i?h[b]*d[b]:h[y]*d[b]}}let g=a.makeTensorInfo(u.shape,c,d);if(l!=null){let x=T.getUndoAxesPermutation(l),A=La({inputs:{x:g},backend:a,attrs:{perm:x}});return a.disposeIntermediateTensorInfo(g),a.disposeIntermediateTensorInfo(u),A}return g}var tz={kernelName:oi,backendName:"cpu",kernelFunc:ez};function az(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=n;ye(r,"cumsum");let l=T.getAxesPermutation([s],r.shape.length),u=r;l!=null&&(u=La({inputs:{x:r},backend:a,attrs:{perm:l}}));let p=T.getInnerMostAxes(1,r.shape.length)[0];if(p!==u.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${p}`);let c=ca(u.dtype,"int32"),d=v.makeZerosTypedArray(v.sizeFromShape(u.shape),c),h=a.data.get(u.dataId).values,f=u.shape[u.shape.length-1],m=o?(x,A)=>x+f-A-1:(x,A)=>x+A;for(let x=0;x<h.length;x+=f)for(let A=0;A<f;A++){let y=m(x,A);if(A===0)d[y]=i?0:h[y];else{let b=m(x,A-1);d[y]=i?h[b]+d[b]:h[y]+d[b]}}let g=a.makeTensorInfo(u.shape,c,d);if(l!=null){let x=T.getUndoAxesPermutation(l),A=La({inputs:{x:g},backend:a,attrs:{perm:x}});return a.disposeIntermediateTensorInfo(g),a.disposeIntermediateTensorInfo(u),A}return g}var nz={kernelName:li,backendName:"cpu",kernelFunc:az};function rz(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,weights:s}=t,{size:i,binaryOutput:o}=n;if(r.shape.length===1){let l=a.data.get(r.dataId).values,u=a.data.get(s.dataId).values,p=i3(l,u,s.dtype,s.shape,i);return a.makeTensorInfo([i],s.dtype,p)}else if(r.shape.length===2){let l=a.bufferSync(r),u=a.bufferSync(s),p=X4(l,u,i,o);return a.makeTensorInfo(p.shape,s.dtype,p.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}var sz={kernelName:Td,backendName:"cpu",kernelFunc:rz};function iz(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{blockSize:s,dataFormat:i}=n;v.assert(i==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`);let o=r.shape[0],l=r.shape[1],u=r.shape[2],p=r.shape[3],c=l*s,d=u*s,h=p/(s*s),f=a.data.get(r.dataId).values,m=new Float32Array(o*c*d*h),g=0;for(let x=0;x<o;++x)for(let A=0;A<c;++A){let y=Math.floor(A/s),b=A%s;for(let w=0;w<d;++w){let S=Math.floor(w/s),C=w%s,E=(b*s+C)*h;for(let _=0;_<h;++_){let $=_+E+p*(S+u*(y+l*x));m[g++]=f[$]}}}return a.makeTensorInfo([o,c,d,h],r.dtype,m)}var oz={kernelName:di,backendName:"cpu",kernelFunc:iz};function L7(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=n;ye([r,s],"depthwiseConv2DNative");let p=v.computeStrides(r.shape),c=v.computeStrides(s.shape),d=l;d==null&&(d=[1,1]),v.assert(T.eitherStridesOrDilationsAreOne(i,d),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${d}'`);let h=T.computeConv2DInfo(r.shape,s.shape,i,d,o,u,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:x,padInfo:A}=h,y=A.left,b=A.top,w=h.outChannels/h.inChannels,S=new jt(h.outShape,r.dtype),C=a.data.get(r.dataId).values,E=a.data.get(s.dataId).values,_=S.values;for(let $=0;$<h.batchSize;++$){let M=$*p[0],I=$*S.strides[0];for(let N=0;N<h.outHeight;++N){let O=I+N*S.strides[1],L=N*h.strideHeight-b;for(let B=0;B<f;++B){let G=L+B*g;if(G<0||G>=h.inHeight)continue;let j=B*c[0],U=M+G*p[1];for(let H=0;H<h.outWidth;++H){let V=O+H*S.strides[2],Q=H*h.strideWidth-y;for(let Z=0;Z<m;++Z){let re=Q+Z*x;if(re<0||re>=h.inWidth)continue;let ee=j+Z*c[1],he=U+re*h.inChannels,oe=V,Ae=ee;for(let we=0;we<h.inChannels;++we){let Re=C[he+we];for(let Ge=0;Ge<w;++Ge)_[oe+Ge]+=Re*E[Ae+Ge];oe+=w,Ae+=w}}}}}}return a.makeTensorInfo(S.shape,S.dtype,S.values)}var lz={kernelName:pi,backendName:"cpu",kernelFunc:L7};function uz(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:p}=n;ye([r,s],"depthwiseConv2dNativeBackpropFilter");let c=T.computeConv2DInfo(r.shape,p,i,o,l,u,!0),{strideHeight:d,strideWidth:h,filterHeight:f,filterWidth:m}=c,g=new jt(c.filterShape,"float32"),x=c.padInfo.left,A=c.padInfo.top,y=c.outChannels/c.inChannels,b=a.data.get(r.dataId).values,w=new jt(r.shape,r.dtype,b),S=a.data.get(s.dataId).values,C=new jt(s.shape,s.dtype,S);for(let E=0;E<f;++E){let _=Math.max(0,Math.ceil((A-E)/d)),$=Math.min(c.outHeight,(c.inHeight+A-E)/d);for(let M=0;M<m;++M){let I=Math.max(0,Math.ceil((x-M)/h)),N=Math.min(c.outWidth,(c.inWidth+x-M)/h);for(let O=0;O<c.outChannels;++O){let L=Math.trunc(O/y),B=O%y,G=0;for(let j=0;j<c.batchSize;++j)for(let U=_;U<$;++U){let H=E+U*d-A;for(let V=I;V<N;++V){let Q=M+V*h-x;G+=w.get(j,H,Q,L)*C.get(j,U,V,O)}}g.set(G,E,M,L,B)}}}return a.makeTensorInfo(g.shape,g.dtype,g.values)}var dz={kernelName:Yc,backendName:"cpu",kernelFunc:uz};function pz(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:p}=n;ye([r,s],"depthwiseConv2DNativeBackpropInput");let c=v.computeStrides(r.shape),d=v.computeStrides(s.shape),h=T.computeConv2DInfo(p,s.shape,i,o,l,u,!0),f=new jt(h.inShape,"float32"),m=f.values,[g,x,A]=f.strides,y=a.data.get(r.dataId).values,[b,w,S]=c,C=a.data.get(s.dataId).values,[E,_,$]=d,{batchSize:M,filterHeight:I,filterWidth:N,inChannels:O,inHeight:L,inWidth:B,outChannels:G,outHeight:j,outWidth:U,strideHeight:H,strideWidth:V}=h,Q=I-1-h.padInfo.top,Z=N-1-h.padInfo.left,re=G/O;for(let ee=0;ee<M;++ee)for(let he=0;he<O;++he)for(let oe=0;oe<L;++oe){let Ae=oe-Q,we=Math.max(0,Math.ceil(Ae/H)),Re=Math.min(j,(I+Ae)/H);for(let Ge=0;Ge<B;++Ge){let Ke=Ge-Z,nt=Math.max(0,Math.ceil(Ke/V)),ut=Math.min(U,(N+Ke)/V),et=0;for(let rt=we;rt<Re;++rt){let je=rt*H-Ae;for(let ht=nt;ht<ut;++ht){let Va=ht*V-Ke,Ft=b*ee+w*rt+S*ht,sn=E*(I-1-je)+_*(N-1-Va)+$*he;for(let aa=0;aa<re;++aa){let $a=he*re+aa,on=y[Ft+$a],_a=C[sn+aa];et+=on*_a}}}m[g*ee+x*oe+A*Ge+he]=et}}return a.makeTensorInfo(f.shape,f.dtype,f.values)}var cz={kernelName:Jc,backendName:"cpu",kernelFunc:pz};function hz(e){let{inputs:t,backend:a}=e,{x:n}=t,r=v.sizeFromShape(n.shape),s=a.data.get(n.dataId).values,i=Me([r,r],n.dtype),o=i.values;for(let u=0;u<s.length;u++)o[u*r+u]=s[u];let l=[...n.shape,...n.shape];return a.makeTensorInfo(l,i.dtype,i.values)}var fz={kernelName:Qc,backendName:"cpu",kernelFunc:hz},mz={kernelName:eh,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:a})=>{let{x:n,filter:r}=e,{strides:s,pad:i,dilations:o}=a,l=t,u=l.data.get(n.dataId).values,p=n.shape.length,c=l.data.get(r.dataId).values,d=r.shape.length,{batchSize:h,inHeight:f,inWidth:m,inChannels:g,outHeight:x,outWidth:A,padInfo:y,strideHeight:b,strideWidth:w,filterHeight:S,filterWidth:C,dilationHeight:E,dilationWidth:_,outShape:$}=T.computeDilation2DInfo(n.shape,r.shape,s,i,"NHWC",o),M=v.sizeFromShape($),I=$.length,N=v.getArrayFromDType(n.dtype,M);for(let O=0;O<h;++O)for(let L=0;L<x;++L){let B=L*b-y.top;for(let G=0;G<A;++G){let j=G*w-y.left;for(let U=0;U<g;++U){let H=Number.MIN_SAFE_INTEGER;for(let Q=0;Q<S;++Q){let Z=B+Q*E;if(Z>=0&&Z<f)for(let re=0;re<C;++re){let ee=j+re*_;if(ee>=0&&ee<m){let he=v.locToIndex([O,Z,ee,U],p,v.computeStrides(n.shape)),oe=v.locToIndex([Q,re,U],d,v.computeStrides(r.shape)),Ae=u[he]+c[oe];Ae>H&&(H=Ae)}}}let V=v.locToIndex([O,L,G,U],I,v.computeStrides($));N[V]=H}}}return{dataId:l.write(v.toTypedArray(N,n.dtype),$,n.dtype),shape:$,dtype:n.dtype}}},gz={kernelName:Gm,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:a})=>{let{x:n,filter:r,dy:s}=e,{strides:i,pad:o,dilations:l}=a,u=t,p=v.toNestedArray(n.shape,u.data.get(n.dataId).values),c=v.toNestedArray(r.shape,u.data.get(r.dataId).values),{batchSize:d,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:x,padInfo:A,strideHeight:y,strideWidth:b,filterHeight:w,filterWidth:S,dilationHeight:C,dilationWidth:E,outShape:_}=T.computeDilation2DInfo(n.shape,r.shape,i,o,"NHWC",l);v.assert(s.rank===_.length,()=>`Error in ${Gm}, dy must have the same rank as output ${_.length}, but got ${s.rank}`);let $=v.toNestedArray(_,u.data.get(s.dataId).values),M=v.makeZerosNestedTypedArray(r.shape,r.dtype);for(let I=0;I<d;++I)for(let N=0;N<g;++N){let O=N*y-A.top;for(let L=0;L<x;++L){let B=L*b-A.left;for(let G=0;G<m;++G){let j=Number.MIN_SAFE_INTEGER,U=0,H=0;for(let V=0;V<w;++V){let Q=O+V*C;if(Q>=0&&Q<h)for(let Z=0;Z<S;++Z){let re=B+Z*E;if(re>=0&&re<f){let ee=p[I][Q][re][G]+c[V][Z][G];ee>j&&(j=ee,U=V,H=Z)}}}M[U][H][G]+=$[I][N][L][G]}}}return{dataId:u.write(v.toTypedArray(M,n.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},xz={kernelName:Um,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:a})=>{let{x:n,filter:r,dy:s}=e,{strides:i,pad:o,dilations:l}=a,u=t,p=v.toNestedArray(n.shape,u.data.get(n.dataId).values),c=v.toNestedArray(r.shape,u.data.get(r.dataId).values),{batchSize:d,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:x,padInfo:A,strideHeight:y,strideWidth:b,filterHeight:w,filterWidth:S,dilationHeight:C,dilationWidth:E,outShape:_}=T.computeDilation2DInfo(n.shape,r.shape,i,o,"NHWC",l);v.assert(s.rank===_.length,()=>`Error in ${Um}, dy must have the same rank as output ${_.length}, but got ${s.rank}`);let $=v.toNestedArray(_,u.data.get(s.dataId).values),M=v.makeZerosNestedTypedArray(n.shape,n.dtype);for(let I=0;I<d;++I)for(let N=0;N<g;++N){let O=N*y-A.top;for(let L=0;L<x;++L){let B=L*b-A.left;for(let G=0;G<m;++G){let j=Number.MIN_SAFE_INTEGER,U=O<0?0:O,H=B<0?0:B;for(let V=0;V<w;++V){let Q=O+V*C;if(Q>=0&&Q<h)for(let Z=0;Z<S;++Z){let re=B+Z*E;if(re>=0&&re<f){let ee=p[I][Q][re][G]+c[V][Z][G];ee>j&&(j=ee,U=Q,H=re)}}}M[I][U][H][G]+=$[I][N][L][G]}}}return{dataId:u.write(v.toTypedArray(M,n.dtype),n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};function lp(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;ye(r,"sum");let o;r.dtype==="bool"?o=Jr({inputs:{x:r},backend:a,attrs:{dtype:"int32"}}):o=er({inputs:{x:r},backend:a});let l=o.shape.length,u=v.parseAxisParam(s,o.shape),p=T.getAxesPermutation(u,l),c=u,d=o;p!=null&&(d=La({inputs:{x:o},backend:a,attrs:{perm:p}}),c=T.getInnerMostAxes(c.length,l)),T.assertAxesAreInnerMostDims("sum",c,d.shape.length);let[h,f]=T.computeOutAndReduceShapes(d.shape,c),m=T.upcastType(d.dtype,"int32"),g=$c(a,h,m),x=v.sizeFromShape(f),A=a.data.get(g.dataId).values,y=a.data.get(d.dataId).values;for(let b=0;b<A.length;++b){let w=b*x,S=0;for(let C=0;C<x;++C)S+=y[w+C];A[b]=S}if(i){let b=T.expandShapeToKeepDim(g.shape,u),w=g;g=mt({inputs:{x:g},backend:a,attrs:{shape:b}}),a.disposeIntermediateTensorInfo(w)}return a.disposeIntermediateTensorInfo(o),p!=null&&a.disposeIntermediateTensorInfo(d),g}var Az={kernelName:ro,backendName:"cpu",kernelFunc:lp};function yz(e){let{inputs:t,backend:a,attrs:n}=e,{equation:r}=n,s=t,{allDims:i,summedDims:o,idDims:l}=T.decodeEinsumEquation(r,s.length);T.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:p}=T.getEinsumComputePath(o,l),c=p.length,d=null,h=i.length,f=[];for(let m=0;m<c;++m){for(let g of p[m]){let{permutationIndices:x,expandDims:A}=T.getEinsumPermutation(h,l[g]),y;T.isIdentityPermutation(x)?y=s[g]:(y=La({inputs:{x:s[g]},backend:a,attrs:{perm:x}}),f.push(y));let b=y.shape.slice();for(let w=0;w<A.length;++w)b.splice(A[w],0,1);v.arraysEqual(y.shape,b)||(y=mt({inputs:{x:y},backend:a,attrs:{shape:b}}),f.push(y)),d===null?d=y:(d=Ph({inputs:{a:y,b:d},backend:a}),f.push(d))}m<c-1&&(u[m]>=0&&(d=lp({inputs:{x:d},backend:a,attrs:{axis:u[m]-(i.length-h),keepDims:!1}}),f.push(d)),h--)}for(let m of f)m!==d&&a.disposeIntermediateTensorInfo(m);return d}var bz={kernelName:Cd,backendName:"cpu",kernelFunc:yz};function vz(e){let{inputs:t,backend:a}=e,{dy:n,y:r}=t;ye([n,r],"eluGrad");let s=new Float32Array(v.sizeFromShape(r.shape)),i=a.data.get(r.dataId).values,o=a.data.get(n.dataId).values;for(let l=0;l<i.length;++l){let u=i[l];u>=1?s[l]=o[l]:s[l]=o[l]*(u+1)}return a.makeTensorInfo(r.shape,"float32",s)}var wz={kernelName:j1,backendName:"cpu",kernelFunc:vz},kz=T.ERF_P,Iz=T.ERF_A1,Sz=T.ERF_A2,Tz=T.ERF_A3,Cz=T.ERF_A4,Nz=T.ERF_A5,Ez=ot($l,e=>{let t=Math.sign(e),a=Math.abs(e),n=1/(1+kz*a);return t*(1-((((Nz*n+Cz)*n+Tz)*n+Sz)*n+Iz)*n*Math.exp(-a*a))}),Rz={kernelName:$l,backendName:"cpu",kernelFunc:Ez};function Fc(e){let{inputs:t,backend:a,attrs:n}=e,{input:r}=t,{dim:s}=n,i=r.shape.length,o=r.shape.slice(),l=s;return s<0&&(v.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),o.splice(l,0,1),mt({inputs:{x:r},backend:a,attrs:{shape:o}})}var Mz={kernelName:_l,backendName:"cpu",kernelFunc:Fc},$z=Lt((e,t)=>e/t),x3=Yt(ci,$z),b1={kernelName:ci,backendName:"cpu",kernelFunc:x3};function B7(e,t,a){let n=e.shape,r=n[0],s=n[1],i=a.data.get(e.dataId),o=i.complexTensorInfos.real,l=i.complexTensorInfos.imag,u=[r,s],p=v.sizeFromShape(u),c=v.getTypedArrayFromDType("float32",p),d=v.getTypedArrayFromDType("float32",p);for(let g=0;g<r;g++){let x=Gs({inputs:{x:o},backend:a,attrs:{begin:[g,0],size:[1,s]}}),A=Gs({inputs:{x:l},backend:a,attrs:{begin:[g,0],size:[1,s]}}),y=Xa({inputs:{real:x,imag:A},backend:a}),{real:b,imag:w}=_z(y,t,a),S=T.mergeRealAndImagArrays(b,w);for(let C=0;C<s;C++){let E=T.getComplexWithIndex(S,C);c[g*s+C]=E.real,d[g*s+C]=E.imag}a.disposeIntermediateTensorInfo(x),a.disposeIntermediateTensorInfo(A),a.disposeIntermediateTensorInfo(y)}let h=a.makeTensorInfo(u,"float32",c),f=a.makeTensorInfo(u,"float32",d),m=Xa({inputs:{real:h,imag:f},backend:a});return a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(f),m}function _z(e,t,a){let n=v.sizeFromShape(e.shape),r=a.data.get(e.dataId),s=a.data.get(r.complexTensorInfos.real.dataId).values,i=a.data.get(r.complexTensorInfos.imag.dataId).values;if(Pz(n)){let o=v1(s,i,n,t,a),l=[e.shape[0],e.shape[1]];if(t){let u=a.makeTensorInfo(l,"float32",o.real),p=a.makeTensorInfo(l,"float32",o.imag),c=a.makeTensorInfo([],"float32",v.createScalarValue(n,"float32")),d=er({inputs:{x:c},backend:a}),h=b1.kernelFunc({inputs:{a:u,b:c},backend:a}),f=b1.kernelFunc({inputs:{a:p,b:d},backend:a}),m=a.data.get(h.dataId).values,g=a.data.get(f.dataId).values;return a.disposeIntermediateTensorInfo(u),a.disposeIntermediateTensorInfo(p),a.disposeIntermediateTensorInfo(c),a.disposeIntermediateTensorInfo(d),a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(f),{real:m,imag:g}}return o}else{let o=T.mergeRealAndImagArrays(s,i),l=Fz(o,n,t);return T.splitRealAndImagArrays(l)}}function Pz(e){return(e&e-1)===0}function v1(e,t,a,n,r){if(a===1)return{real:e,imag:t};let s=T.mergeRealAndImagArrays(e,t),i=a/2,o=T.complexWithEvenIndex(s),l=o.real,u=o.imag,p=[l.length],c=r.makeTensorInfo(p,"float32",l),d=r.makeTensorInfo(p,"float32",u),h=Xa({inputs:{real:c,imag:d},backend:r}),f=T.complexWithOddIndex(s),m=f.real,g=f.imag,x=[m.length],A=r.makeTensorInfo(x,"float32",m),y=r.makeTensorInfo(x,"float32",g),b=Xa({inputs:{real:A,imag:y},backend:r}),w=v1(l,u,i,n,r),S=w.real,C=w.imag,E=[S.length],_=r.makeTensorInfo(E,"float32",S),$=r.makeTensorInfo(E,"float32",C),M=Xa({inputs:{real:_,imag:$},backend:r}),I=v1(m,g,i,n,r),N=I.real,O=I.imag,L=[N.length],B=r.makeTensorInfo(L,"float32",N),G=r.makeTensorInfo(L,"float32",O),j=Xa({inputs:{real:B,imag:G},backend:r}),U=T.exponents(a,n),H=[U.real.length],V=r.makeTensorInfo(H,"float32",U.real),Q=r.makeTensorInfo(H,"float32",U.imag),Z=Xa({inputs:{real:V,imag:Q},backend:r}),re=Ph({inputs:{a:Z,b:j},backend:r}),ee=ml({inputs:{a:M,b:re},backend:r}),he=m3({inputs:{a:M,b:re},backend:r}),oe=Us({inputs:{input:ee},backend:r}),Ae=Us({inputs:{input:he},backend:r}),we=gl({inputs:{input:ee},backend:r}),Re=gl({inputs:{input:he},backend:r}),Ge=xl({inputs:[oe,Ae],backend:r,attrs:{axis:0}}),Ke=xl({inputs:[we,Re],backend:r,attrs:{axis:0}}),nt=r.data.get(Ge.dataId).values,ut=r.data.get(Ke.dataId).values;return r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(A),r.disposeIntermediateTensorInfo(y),r.disposeIntermediateTensorInfo(b),r.disposeIntermediateTensorInfo(_),r.disposeIntermediateTensorInfo($),r.disposeIntermediateTensorInfo(M),r.disposeIntermediateTensorInfo(B),r.disposeIntermediateTensorInfo(G),r.disposeIntermediateTensorInfo(j),r.disposeIntermediateTensorInfo(V),r.disposeIntermediateTensorInfo(Q),r.disposeIntermediateTensorInfo(Z),r.disposeIntermediateTensorInfo(re),r.disposeIntermediateTensorInfo(ee),r.disposeIntermediateTensorInfo(he),r.disposeIntermediateTensorInfo(oe),r.disposeIntermediateTensorInfo(we),r.disposeIntermediateTensorInfo(Ae),r.disposeIntermediateTensorInfo(Re),r.disposeIntermediateTensorInfo(Ge),r.disposeIntermediateTensorInfo(Ke),{real:nt,imag:ut}}function Fz(e,t,a){let n=new Float32Array(t*2);for(let r=0;r<t;r++){let s=0,i=0;for(let o=0;o<t;o++){let l=T.exponent(r*o,t,a),u=T.getComplexWithIndex(e,o);s+=u.real*l.real-u.imag*l.imag,i+=u.real*l.imag+u.imag*l.real}a&&(s/=t,i/=t),T.assignToTypedArray(n,s,i,r)}return n}function Oz(e){let{inputs:t,backend:a}=e,{input:n}=t,r=v.sizeFromShape(n.shape),s=n.shape[n.shape.length-1],i=r/s,o=mt({inputs:{x:n},backend:a,attrs:{shape:[i,s]}}),l=B7(o,!1,a),u=mt({inputs:{x:l},backend:a,attrs:{shape:n.shape}});return a.disposeIntermediateTensorInfo(o),a.disposeIntermediateTensorInfo(l),u}var Dz={kernelName:Nd,backendName:"cpu",kernelFunc:Oz};function A3(e){let{backend:t,attrs:a}=e,{shape:n,value:r,dtype:s}=a,i=s||v.inferDtype(r),o=v.getArrayFromDType(i,v.sizeFromShape(n));return Lz(o,r,i),t.makeTensorInfo(n,i,o)}var zz={kernelName:Fl,backendName:"cpu",kernelFunc:A3};function Lz(e,t,a){e.fill(t)}var Bz={kernelName:gi,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:a})=>{let{image:n}=e,r=a,s=v.getTypedArrayFromDType(n.dtype,v.sizeFromShape(n.shape)),[i,o,l,u]=n.shape,p=r.data.get(n.dataId).values;for(let c=0;c<i;c++){let d=c*l*o*u;for(let h=0;h<o;h++){let f=h*(l*u);for(let m=0;m<l;m++){let g=m*u;for(let x=0;x<u;x++){let A=Math.round(l-m-1),y=d+f+g+x,b=p[y];if(A>=0&&A<l){let w=A*u,S=d+f+w+x;b=p[S]}s[y]=b}}}}return{dataId:r.write(s,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},Wz=Lt((e,t)=>Math.floor(e/t)),Vz=Yt(Ai,Wz,null,"int32"),Uz={kernelName:Ai,backendName:"cpu",kernelFunc:Vz};function Gz(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:p,dilations:c,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=n,m=z7({inputs:{x:r,filter:s},backend:a,attrs:{strides:l,pad:u,dataFormat:p,dilations:c,dimRoundingMode:d}});if(i){let g=m;if(p==="NCHW"&&i.shape.length===1&&i.shape[0]!==1){let x=mt({inputs:{x:i},backend:a,attrs:{shape:[i.shape[0],1,1]}});m=ml({inputs:{a:m,b:x},backend:a}),a.disposeIntermediateTensorInfo(x)}else m=ml({inputs:{a:m,b:i},backend:a});a.disposeIntermediateTensorInfo(g)}if(h){let g=m;if(p==="NCHW"&&h==="prelu"&&o.shape.length===1&&o.shape[0]!==1){let x=mt({inputs:{x:o},backend:a,attrs:{shape:[o.shape[0],1,1]}});m=Pc(a,m,h,x,f),a.disposeIntermediateTensorInfo(x)}else m=Pc(a,m,h,o,f);a.disposeIntermediateTensorInfo(g)}return m}var Hz={kernelName:qr,backendName:"cpu",kernelFunc:Gz};function jz(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:p,dilations:c,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=n,m=L7({inputs:{x:r,filter:s},backend:a,attrs:{strides:l,pad:u,dataFormat:p,dilations:c,dimRoundingMode:d}});if(i){let g=m;m=ml({inputs:{a:m,b:i},backend:a}),a.disposeIntermediateTensorInfo(g)}if(h){let g=m;m=Pc(a,m,h,o,f),a.disposeIntermediateTensorInfo(g)}return m}var qz={kernelName:Xr,backendName:"cpu",kernelFunc:jz};function Xz(e){let{inputs:t,backend:a}=e,{params:n,indices:r}=t,s=v.sizeFromShape(n.shape),i=r.shape,o=i[i.length-1],[l,u,p,c]=T.prepareAndValidate(n,r);if(u===0)return a.makeTensorInfo(l,n.dtype,[]);let d=a.data.get(r.dataId).values,h=a.bufferSync(n),f=a7(d,h,n.dtype,u,o,p,c,n.shape,s);return a.makeTensorInfo(l,n.dtype,f.values)}var Kz={kernelName:bi,backendName:"cpu",kernelFunc:Xz};function Zz(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,indices:s}=t,{axis:i,batchDims:o}=n;ye([r,s],"gatherV2");let l=v.parseAxisParam(i,r.shape)[0],u=a.data.get(s.dataId).values,p=r.shape[l];for(let b=0;b<u.length;++b){let w=u[b];v.assert(w<=p-1&&w>=0,()=>`GatherV2: the index value ${w} is not in [0, ${p-1}]`)}let c=o;o==null&&(c=0);let d=v.sizeFromShape(s.shape),h=T.segment_util.collectGatherOpShapeInfo(r,s,l,c),f=mt({inputs:{x:r},backend:a,attrs:{shape:[h.batchSize,h.outerSize,h.dimSize,h.sliceSize]}}),m=mt({inputs:{x:s},backend:a,attrs:{shape:[h.batchSize,d/h.batchSize]}}),g=[h.batchSize,h.outerSize,d/h.batchSize,h.sliceSize],x=a.bufferSync(m),A=a.bufferSync(f),y=n7(A,x,g);return a.disposeIntermediateTensorInfo(f),a.disposeIntermediateTensorInfo(m),a.makeTensorInfo(h.outputShape,y.dtype,y.values)}var Yz={kernelName:Ol,backendName:"cpu",kernelFunc:Zz};function Jz(e){let{inputs:t,backend:a}=e,{input:n}=t,r=v.sizeFromShape(n.shape),s=n.shape[n.shape.length-1],i=r/s,o=mt({inputs:{x:n},backend:a,attrs:{shape:[i,s]}}),l=B7(o,!0,a),u=mt({inputs:{x:l},backend:a,attrs:{shape:n.shape}});return a.disposeIntermediateTensorInfo(o),a.disposeIntermediateTensorInfo(l),u}var Qz={kernelName:Ed,backendName:"cpu",kernelFunc:Jz},eL=ot(Dl,e=>Number.isFinite(e)?1:0,"bool"),tL={kernelName:Dl,backendName:"cpu",kernelFunc:eL},aL=ot(zl,e=>Math.abs(e)===1/0?1:0,"bool"),nL={kernelName:zl,backendName:"cpu",kernelFunc:aL},rL=ot(Ii,e=>Number.isNaN(e)?1:0,"bool"),sL={kernelName:Ii,backendName:"cpu",kernelFunc:rL};function iL(e){let{backend:t,attrs:a}=e,{start:n,stop:r,num:s}=a,i=l7(n,r,s);return t.makeTensorInfo([i.length],"float32",i)}var oL={kernelName:th,backendName:"cpu",kernelFunc:iL},lL=ot(Ll,e=>Math.log1p(e)),uL={kernelName:Ll,backendName:"cpu",kernelFunc:lL},dL=Lt((e,t)=>e&&t),pL=Yt(Ei,dL,null,"bool"),cL={kernelName:Ei,backendName:"cpu",kernelFunc:pL},hL=ot(Ri,e=>e?0:1,"bool"),fL={kernelName:Ri,backendName:"cpu",kernelFunc:hL},mL=Lt((e,t)=>e||t),gL=Yt(Bl,mL,null,"bool"),xL={kernelName:Bl,backendName:"cpu",kernelFunc:gL};function AL(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n;ye(r,"LRN");let u=r.shape[3],p=u-1,c=a.data.get(r.dataId).values,d=v.sizeFromShape(r.shape),h=new Float32Array(d);function f(m){let g=m%u,x=m-g+Math.max(0,g-s),A=m-g+Math.min(g+s,p),y=0;for(;x<=A;x++){let b=c[x];y+=b*b}return y}for(let m=0;m<d;m++){let g=f(m),x=c[m]*Math.pow(i+o*g,-l);h[m]=x}return a.makeTensorInfo(r.shape,r.dtype,h)}var yL={kernelName:ah,backendName:"cpu",kernelFunc:AL};function bL(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:p}=n;ye(i,"LRNGrad");let c=v.sizeFromShape(i.shape),d=i.shape[3],h=a.data.get(i.dataId).values,f=a.data.get(r.dataId).values,m=a.data.get(s.dataId).values,g=new Float32Array(c),x=c;for(let A=0;A<x;A++){let y=A%d,b=A-y+Math.max(0,y-o),w=A-y+Math.min(d,y+o+1),S=0;for(let C=b;C<w;C++)S+=Math.pow(f[C],2);S=u*S+l;for(let C=b;C<w;C++){let E=-2*u*p*f[C]*m[A]/S;A===C&&(E+=Math.pow(S,-p)),E*=h[A],g[C]+=E}}return a.makeTensorInfo(i.shape,r.dtype,g)}var vL={kernelName:q1,backendName:"cpu",kernelFunc:bL};function W7(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{reductionIndices:s,keepDims:i}=n,o=a,l=r.shape,u=l.length,p=v.parseAxisParam(s,l),c=p,d=T.getAxesPermutation(c,u),h=o.data.get(r.dataId).values;if(d!=null){let b=new Array(u);for(let w=0;w<b.length;w++)b[w]=l[d[w]];h=u3(h,l,r.dtype,d,b),c=T.getInnerMostAxes(c.length,u),l=b}ye(r,"max"),T.assertAxesAreInnerMostDims("max",c,u);let[f,m]=T.computeOutAndReduceShapes(l,c),g=v.sizeFromShape(m),x=d7(h,g,f,r.dtype),A=o.write(x,f,r.dtype),y=f;return i&&(y=T.expandShapeToKeepDim(f,p)),{dataId:A,shape:y,dtype:r.dtype}}var wL={kernelName:Mi,backendName:"cpu",kernelFunc:W7};function kL(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t;ye(r,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1;v.assert(T.eitherStridesOrDilationsAreOne(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=T.computePool2DInfo(r.shape,s,i,u,o,l),c;if(p.filterWidth===1&&p.filterHeight===1&&v.arraysEqual(p.inShape,p.outShape))c=er({inputs:{x:r},backend:a});else{let d=a.data.get(r.dataId).values,h=v.computeStrides(r.shape),f=g3(d,r.shape,r.dtype,h,p,"max");c=a.makeTensorInfo(p.outShape,r.dtype,f.values)}return c}var IL={kernelName:_i,backendName:"cpu",kernelFunc:kL};function SL(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=n;ye(r,"maxPool3d");let p=T.computePool3DInfo(r.shape,s,i,1,o,l,u),c=a.data.get(r.dataId).values,d=D7(c,r.shape,r.dtype,v.computeStrides(r.shape),p,"max");return a.makeTensorInfo(d.shape,"float32",d.values)}var TL={kernelName:nh,backendName:"cpu",kernelFunc:SL};function CL(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=n;ye([r,s],"maxPool3DGrad");let p=T.computePool3DInfo(s.shape,i,o,1,l,u),c=a.bufferSync(s),d=fD(c,p),h=p.strideDepth,f=p.strideHeight,m=p.strideWidth,g=p.dilationDepth,x=p.dilationHeight,A=p.dilationWidth,y=p.effectiveFilterDepth,b=p.effectiveFilterHeight,w=p.effectiveFilterWidth,S=y-1-p.padInfo.front,C=w-1-p.padInfo.left,E=b-1-p.padInfo.top,_=Me(s.shape,"float32"),$=a.bufferSync(r);for(let M=0;M<p.batchSize;++M)for(let I=0;I<p.inChannels;++I)for(let N=0;N<p.inDepth;++N)for(let O=0;O<p.inHeight;++O)for(let L=0;L<p.inWidth;++L){let B=N-S,G=O-E,j=L-C,U=0;for(let H=0;H<y;H+=g){let V=(B+H)/h;if(!(V<0||V>=p.outDepth||Math.floor(V)!==V))for(let Q=0;Q<b;Q+=x){let Z=(G+Q)/f;if(!(Z<0||Z>=p.outHeight||Math.floor(Z)!==Z))for(let re=0;re<w;re+=A){let ee=(j+re)/m;if(ee<0||ee>=p.outWidth||Math.floor(ee)!==ee)continue;let he=y*b*w-1-d.get(M,V,Z,ee,I),oe=H*b*w+Q*w+re,Ae=he===oe?1:0;if(Ae===0)continue;let we=$.get(M,V,Z,ee,I);U+=we*Ae}}}_.set(U,M,N,O,L,I)}return a.makeTensorInfo(_.shape,_.dtype,_.values)}var NL={kernelName:K1,backendName:"cpu",kernelFunc:CL};function EL(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s,output:i}=t,o=s;ye([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:p,dimRoundingMode:c}=n,d=T.computePool2DInfo(o.shape,l,u,1,p,c),h=a.data.get(o.dataId).values,f=Me(d.outShape,o.dtype,O7(h,o.shape,o.dtype,d).values),m=d.strideHeight,g=d.strideWidth,x=d.dilationHeight,A=d.dilationWidth,y=d.effectiveFilterHeight,b=d.effectiveFilterWidth,w=b-1-d.padInfo.left,S=y-1-d.padInfo.top,C=Me(o.shape,"float32"),E=a.data.get(r.dataId).values,_=Me(r.shape,"float32",E);for(let $=0;$<d.batchSize;++$)for(let M=0;M<d.inChannels;++M)for(let I=0;I<d.inHeight;++I)for(let N=0;N<d.inWidth;++N){let O=I-S,L=N-w,B=0;for(let G=0;G<y;G+=x){let j=(O+G)/m;if(!(j<0||j>=d.outHeight||Math.floor(j)!==j))for(let U=0;U<b;U+=A){let H=(L+U)/g;if(H<0||H>=d.outWidth||Math.floor(H)!==H)continue;let V=y*b-1-f.get($,j,H,M),Q=G*b+U,Z=V===Q?1:0;if(Z===0)continue;let re=_.get($,j,H,M);B+=re*Z}}C.set(B,$,I,N,M)}return a.makeTensorInfo(C.shape,C.dtype,C.values)}var RL={kernelName:X1,backendName:"cpu",kernelFunc:EL};function ML(e,t,a,n,r){let s=v.computeStrides(t),i=g3(e,t,a,s,r,"max"),o=O7(e,t,a,r,!0,n);return[i.values,o.values]}var $L={kernelName:rh,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:a})=>{let{x:n}=e,{filterSize:r,strides:s,pad:i,includeBatchInIndex:o}=t,l=a;ye(n,"MaxPoolWithArgmax");let u=l.data.get(n.dataId).values,p=T.computePool2DInfo(n.shape,r,s,[1,1],i),[c,d]=ML(u,n.shape,n.dtype,o,p),h=l.write(c,p.outShape,n.dtype),f=l.write(d,p.outShape,n.dtype);return[{dataId:h,shape:p.outShape,dtype:n.dtype},{dataId:f,shape:p.outShape,dtype:"int32"}]}};function _L(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n,o=v.parseAxisParam(s,r.shape),l=T.computeOutAndReduceShapes(r.shape,o)[1],u=v.sizeFromShape(l),p=[],c=a.makeTensorInfo([],"float32",new Float32Array([u]));p.push(c);let d=Jr({inputs:{x:r},backend:a,attrs:{dtype:"float32"}});p.push(d);let h=x3({inputs:{a:d,b:c},backend:a});p.push(h);let f=lp({inputs:{x:h},backend:a,attrs:{axis:s,keepDims:i}});return p.forEach(m=>a.disposeIntermediateTensorInfo(m)),f}var PL={kernelName:Pi,backendName:"cpu",kernelFunc:_L};function FL(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;ye(r,"min");let o=v.parseAxisParam(s,r.shape),l=o,u=T.getAxesPermutation(l,r.shape.length),p=r;u!=null&&(p=La({inputs:{x:r},backend:a,attrs:{perm:u}}),l=T.getInnerMostAxes(l.length,r.shape.length)),T.assertAxesAreInnerMostDims("min",l,p.shape.length);let[c,d]=T.computeOutAndReduceShapes(p.shape,l),h=v.sizeFromShape(d),f=v.makeZerosTypedArray(v.sizeFromShape(c),p.dtype),m=a.data.get(p.dataId).values;for(let x=0;x<f.length;++x){let A=x*h,y=m[A];for(let b=0;b<h;++b){let w=m[A+b];(Number.isNaN(w)||w<y)&&(y=w)}f[x]=y}u!=null&&a.disposeIntermediateTensorInfo(p);let g=a.makeTensorInfo(c,p.dtype,f);if(i){let x=T.expandShapeToKeepDim(c,o),A=mt({inputs:{x:g},backend:a,attrs:{shape:x}});return a.disposeIntermediateTensorInfo(g),A}return g}var OL={kernelName:Fi,backendName:"cpu",kernelFunc:FL};function DL(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{paddings:s,mode:i}=n;ye(r,"mirrorPad");let o=s.map((A,y)=>A[0]+r.shape[y]+A[1]),l=s.map(A=>A[0]),u=s.map((A,y)=>A[0]+r.shape[y]),p=i==="reflect"?0:1,c=a.data.get(r.dataId).values,d=r.shape.length,h=v.computeStrides(r.shape),f=v.sizeFromShape(o),m=o.length,g=v.computeStrides(o),x=v.getTypedArrayFromDType(r.dtype,f);for(let A=0;A<f;A++){let y=v.indexToLoc(A,m,g);for(let w=0;w<m;w++)y[w]<l[w]?y[w]=l[w]*2-y[w]-p:y[w]>=u[w]&&(y[w]=(u[w]-1)*2-y[w]+p);y=y.map((w,S)=>w-l[S]);let b=v.locToIndex(y,d,h);x[A]=c[b]}return{dataId:a.write(x,o,r.dtype),shape:o,dtype:r.dtype}}var zL={kernelName:Di,backendName:"cpu",kernelFunc:DL},LL=Lt((e,t)=>{let a=e%t;return e<0&&t<0||e>=0&&t>=0?a:(a+t)%t}),BL=Yt(Wl,LL),WL={kernelName:Wl,backendName:"cpu",kernelFunc:BL},VL=yl(nA());function V7(e){let{inputs:t,backend:a,attrs:n}=e,{logits:r}=t,{dim:s}=n,i=r.shape.length,o=s;if(o===-1&&(o=i-1),o!==i-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${o}`);let l=v.parseAxisParam([o],r.shape),u=W7({inputs:{x:r},backend:a,attrs:{reductionIndices:l,keepDims:!1}}),p=T.expandShapeToKeepDim(u.shape,l),c=mt({inputs:{x:u},backend:a,attrs:{shape:p}}),d=m3({inputs:{a:r,b:c},backend:a}),h=Q4({inputs:{x:d},backend:a}),f=lp({inputs:{x:h},backend:a,attrs:{axis:l,keepDims:!1}}),m=mt({inputs:{x:f},backend:a,attrs:{shape:p}}),g=x3({inputs:{a:h,b:m},backend:a});return a.disposeIntermediateTensorInfo(u),a.disposeIntermediateTensorInfo(c),a.disposeIntermediateTensorInfo(d),a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(f),a.disposeIntermediateTensorInfo(m),g}var UL={kernelName:so,backendName:"cpu",kernelFunc:V7};function GL(e){let{inputs:t,backend:a,attrs:n}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=n;ye(r,"multinomial");let l=o?r:V7({inputs:{logits:r},backend:a,attrs:{dim:-1}}),u=l.shape[0],p=l.shape[1],c=a.data.get(l.dataId).values,d=[u,s],h=v.makeZerosTypedArray(v.sizeFromShape(d),"int32");for(let f=0;f<u;++f){let m=f*p,g=new Float32Array(p-1);g[0]=c[m];for(let y=1;y<g.length;++y)g[y]=g[y-1]+c[m+y];let x=VL.alea(i.toString()),A=f*s;for(let y=0;y<s;++y){let b=x();h[A+y]=g.length;for(let w=0;w<g.length;w++)if(b<g[w]){h[A+y]=w;break}}}return o||a.disposeIntermediateTensorInfo(l),a.makeTensorInfo(d,"int32",h)}var HL={kernelName:sh,backendName:"cpu",kernelFunc:GL},jL=Tn.nonMaxSuppressionV3Impl;function qL(e){let{inputs:t,backend:a,attrs:n}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=n;ye(r,"NonMaxSuppression");let u=a.data.get(r.dataId).values,p=a.data.get(s.dataId).values,{selectedIndices:c}=jL(u,p,i,o,l);return a.makeTensorInfo([c.length],"int32",new Int32Array(c))}var XL={kernelName:Bi,backendName:"cpu",kernelFunc:qL},KL=Tn.nonMaxSuppressionV4Impl;function ZL(e){let{inputs:t,backend:a,attrs:n}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=n;ye(r,"NonMaxSuppressionPadded");let p=a.data.get(r.dataId).values,c=a.data.get(s.dataId).values,{selectedIndices:d,validOutputs:h}=KL(p,c,i,o,l,u);return[a.makeTensorInfo([d.length],"int32",new Int32Array(d)),a.makeTensorInfo([],"int32",new Int32Array([h]))]}var YL={kernelName:Ul,backendName:"cpu",kernelFunc:ZL},JL=Tn.nonMaxSuppressionV5Impl;function QL(e){let{inputs:t,backend:a,attrs:n}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=n;ye(r,"NonMaxSuppressionWithScore");let p=a.data.get(r.dataId).values,c=a.data.get(s.dataId).values,d=i,h=o,f=l,m=u,{selectedIndices:g,selectedScores:x}=JL(p,c,d,h,f,m);return[a.makeTensorInfo([g.length],"int32",new Int32Array(g)),a.makeTensorInfo([x.length],"float32",new Float32Array(x))]}var eB={kernelName:Wi,backendName:"cpu",kernelFunc:QL};function tB(e){let{inputs:t,backend:a,attrs:n}=e,{indices:r}=t,{dtype:s,depth:i,onValue:o,offValue:l}=n;ye(r,"oneHot");let u=v.sizeFromShape(r.shape),p=new Float32Array(u*i);p.fill(l);let c=a.data.get(r.dataId).values;for(let d=0;d<u;++d)c[d]>=0&&c[d]<i&&(p[d*i+c[d]]=o);return a.makeTensorInfo([...r.shape,i],s,p)}var aB={kernelName:Vi,backendName:"cpu",kernelFunc:tB};function Oc(e){let{inputs:t,backend:a}=e,{x:n}=t;if(n.dtype==="string")throw new Error("zerosLike is not supported for string tensors");if(n.dtype==="complex64"){let r=Us({inputs:{input:n},backend:a}),s=Oc({inputs:{x:r},backend:a}),i=gl({inputs:{input:n},backend:a}),o=Oc({inputs:{x:i},backend:a}),l=Xa({inputs:{real:s,imag:o},backend:a});return a.disposeIntermediateTensorInfo(r),a.disposeIntermediateTensorInfo(s),a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}else return A3({backend:a,attrs:{shape:n.shape,value:0,dtype:n.dtype}})}var nB={kernelName:nu,backendName:"cpu",kernelFunc:Oc};function U7(e){let{inputs:t,backend:a}=e,{x:n}=t;if(n.dtype==="string")throw new Error("onesLike is not supported for string tensors");if(n.dtype==="complex64"){let r=Us({inputs:{input:n},backend:a}),s=U7({inputs:{x:r},backend:a}),i=gl({inputs:{input:n},backend:a}),o=Oc({inputs:{x:i},backend:a}),l=Xa({inputs:{real:s,imag:o},backend:a});return a.disposeIntermediateTensorInfo(r),a.disposeIntermediateTensorInfo(s),a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}else return A3({backend:a,attrs:{shape:n.shape,value:1,dtype:n.dtype}})}var rB={kernelName:Gl,backendName:"cpu",kernelFunc:U7};function G7(e){let{inputs:t,backend:a,attrs:n}=e,{axis:r}=n;if(t.length===1)return Fc({inputs:{input:t[0]},backend:a,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(p=>{v.assertShapesMatch(s,p.shape,"All tensors passed to stack must have matching shapes"),v.assert(i===p.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(p=>{let c=Fc({inputs:{input:p},backend:a,attrs:{dim:r}});return o.push(c),c}),u=xl({inputs:l,backend:a,attrs:{axis:r}});return o.forEach(p=>a.disposeIntermediateTensorInfo(p)),u}var sB={kernelName:Hl,backendName:"cpu",kernelFunc:G7};function iB(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{paddings:s,constantValue:i}=n;ye(r,"pad");let o=s.map((x,A)=>x[0]+r.shape[A]+x[1]),l=s.map(x=>x[0]),u=a.data.get(r.dataId).values,p=v.sizeFromShape(r.shape),c=r.shape.length,d=v.computeStrides(r.shape),h=v.sizeFromShape(o),f=o.length,m=v.computeStrides(o),g=v.getTypedArrayFromDType(r.dtype,h);i!==0&&g.fill(i);for(let x=0;x<p;x++){let A=v.indexToLoc(x,c,d).map((b,w)=>b+l[w]),y=v.locToIndex(A,f,m);g[y]=u[x]}return{dataId:a.write(g,o,r.dtype),shape:o,dtype:r.dtype}}var H7={kernelName:Ui,backendName:"cpu",kernelFunc:iB},oB=Lt((e,t)=>Math.pow(e,t)),lB=Yt(Gi,oB),uB={kernelName:Gi,backendName:"cpu",kernelFunc:lB};function dB(e){let{inputs:t,backend:a,attrs:n}=e,{paramsNestedSplits:r,paramsDenseValues:s,indices:i}=t,{outputRaggedRank:o}=n,l=r.map(x=>a.data.get(x.dataId).values),u=r.map(x=>x.shape),p=a.data.get(s.dataId).values,c=a.data.get(i.dataId).values,[d,h,f]=g7(l,u,p,s.shape,s.dtype,c,i.shape,o),m=d.map(x=>a.makeTensorInfo([x.length],"int32",x)),g=a.makeTensorInfo(f,s.dtype,h);return m.concat([g])}var pB={kernelName:ih,backendName:"cpu",kernelFunc:dB};function cB(e){let{inputs:t,backend:a}=e,{starts:n,limits:r,deltas:s}=t,i=a.data.get(n.dataId).values,o=a.data.get(r.dataId).values,l=a.data.get(s.dataId).values,[u,p]=x7(i,n.shape,n.dtype,o,r.shape,l,s.shape),c=a.makeTensorInfo([u.length],"int32",u),d=a.makeTensorInfo([p.length],n.dtype,p);return[c,d]}var hB={kernelName:oh,backendName:"cpu",kernelFunc:cB};function fB(e){let{inputs:t,backend:a,attrs:n}=e,{shape:r,values:s,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:l}=n,u=a.data.get(r.dataId).values,p=a.data.get(s.dataId).values,c=a.data.get(i.dataId).values,d=o.map(g=>a.data.get(g.dataId).values),h=o.map(g=>g.shape),[f,m]=A7(u,r.shape,p,s.shape,s.dtype,c,i.shape,d,h,l);return a.makeTensorInfo(f,s.dtype,m)}var mB={kernelName:lh,backendName:"cpu",kernelFunc:fB};function gB(e){let{backend:t,attrs:a}=e,{start:n,stop:r,dtype:s,step:i}=a,o=d3(n,r,i,s);return t.makeTensorInfo([o.length],s,o)}var xB={kernelName:jl,backendName:"cpu",kernelFunc:gB},AB=ot(qi,e=>1/e),yB={kernelName:qi,backendName:"cpu",kernelFunc:AB};function bB(e){let{inputs:t,backend:a,attrs:n}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n;ye(r,"resizeBilinear");let l=v.computeStrides(r.shape),[u,p]=o,[c,d,h,f]=r.shape,m=a.data.get(r.dataId).values,g=new Float32Array(v.sizeFromShape([c,u,p,f])),x=[s&&u>1?d-1:d,s&&p>1?h-1:h],A=[s&&u>1?u-1:u,s&&p>1?p-1:p],y=0,b=x[0]/A[0],w=x[1]/A[1];for(let S=0;S<c;S++)for(let C=0;C<u;C++){let E;i?E=b*(C+.5)-.5:E=b*C;let _=Math.max(0,Math.floor(E)),$=E-_,M=Math.min(d-1,Math.ceil(E)),I=S*l[0]+_*l[1],N=S*l[0]+M*l[1];for(let O=0;O<p;O++){let L;i?L=w*(O+.5)-.5:L=w*O;let B=Math.max(0,Math.floor(L)),G=L-B,j=Math.min(h-1,Math.ceil(L)),U=I+B*l[2],H=N+B*l[2],V=I+j*l[2],Q=N+j*l[2];for(let Z=0;Z<f;Z++){let re=m[U+Z],ee=m[H+Z],he=m[V+Z],oe=m[Q+Z],Ae=re+(he-re)*G,we=ee+(oe-ee)*G,Re=Ae+(we-Ae)*$;g[y++]=Re}}}return a.makeTensorInfo([c,u,p,f],"float32",g)}var vB={kernelName:Zi,backendName:"cpu",kernelFunc:bB};function wB(e){let{inputs:t,backend:a,attrs:n}=e,{images:r,dy:s}=t,{alignCorners:i}=n;ye([s,r],"resizeBilinearGrad");let o=v.computeStrides(r.shape),[l,u,p,c]=r.shape,[,d,h]=s.shape,f=new Float32Array(l*u*p*c),m=[i&&d>1?u-1:u,i&&h>1?p-1:p],g=[i&&d>1?d-1:d,i&&h>1?h-1:h],x=m[0]/g[0],A=m[1]/g[1],y=a.data.get(s.dataId).values,b=0;for(let w=0;w<l;w++){let S=w*o[0];for(let C=0;C<d;C++){let E=C*x,_=Math.floor(E),$=Math.min(Math.ceil(E),u-1),M=S+_*o[1],I=S+$*o[1],N=E-_,O=1-N;for(let L=0;L<h;L++){let B=L*A,G=Math.floor(B),j=Math.min(Math.ceil(B),p-1),U=B-G,H=1-U,V=M+G*o[2],Q=M+j*o[2],Z=I+G*o[2],re=I+j*o[2],ee=O*H,he=O*U,oe=N*H,Ae=N*U;for(let we=0;we<c;we++){let Re=y[b++];f[V+we]+=Re*ee,f[Q+we]+=Re*he,f[Z+we]+=Re*oe,f[re+we]+=Re*Ae}}}}return a.makeTensorInfo([l,p,u,c],"float32",f)}var kB={kernelName:Y1,backendName:"cpu",kernelFunc:wB};function IB(e){let{inputs:t,backend:a,attrs:n}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n;ye(r,"resizeNearestNeighbor");let l=v.computeStrides(r.shape),[u,p]=o,[c,d,h,f]=r.shape,m=a.data.get(r.dataId).values,g=new Float32Array(c*u*p*f),x=[s&&u>1?d-1:d,s&&p>1?h-1:h],A=[s&&u>1?u-1:u,s&&p>1?p-1:p],y=x[0]/A[0],b=x[1]/A[1],w=0;for(let S=0;S<c;S++){let C=S*l[0];for(let E=0;E<u;E++){let _=i?y*(E+.5):y*E,$=Math.min(d-1,s?Math.round(_):Math.floor(_));i&&($=Math.max(0,$));let M=C+$*l[1];for(let I=0;I<p;I++){let N=i?b*(I+.5):b*I,O=Math.min(h-1,s?Math.round(N):Math.floor(N));i&&(O=Math.max(0,O));let L=M+O*l[2];for(let B=0;B<f;B++){let G=m[L+B];g[w++]=G}}}}return a.makeTensorInfo([c,u,p,f],r.dtype,g)}var SB={kernelName:Ki,backendName:"cpu",kernelFunc:IB};function TB(e){let{inputs:t,backend:a,attrs:n}=e,{images:r,dy:s}=t,{alignCorners:i}=n;ye([s,r],"resizeNearestNeighborGrad");let o=v.computeStrides(r.shape),l=v.computeStrides(s.shape),[u,p,c,d]=r.shape,[,h,f]=s.shape,m=new Float32Array(u*p*c*d),g=a.data.get(s.dataId).values,x=[i&&h>1?p-1:p,i&&f>1?c-1:c],A=[i&&h>1?h-1:h,i&&f>1?f-1:f],y=x[0]/A[0],b=x[1]/A[1],w=1/y,S=1/b,C=Math.ceil(w)*2+2,E=Math.ceil(S)*2+2;for(let _=0;_<u;_++){let $=_*o[0];for(let M=0;M<p;M++){let I=$+M*o[1],N=Math.floor(M*w),O=Math.floor(N-C/2);for(let L=0;L<c;L++){let B=I+L*o[2],G=Math.floor(L*S),j=Math.floor(G-E/2);for(let U=0;U<d;U++){let H=0;for(let V=0;V<C;V++){let Q=V+O;if(Q<0||Q>=h)continue;let Z=$+Q*l[1],re=Q*y,ee=Math.min(p-1,i?Math.round(re):Math.floor(re));if(M===ee)for(let he=0;he<E;he++){let oe=he+j;if(oe<0||oe>=f)continue;let Ae=Z+oe*l[2],we=oe*b,Re=Math.min(c-1,i?Math.round(we):Math.floor(we));L===Re&&(H+=g[Ae+U])}}m[B+U]=H}}}}return a.makeTensorInfo(r.shape,r.dtype,m)}var CB={kernelName:Z1,backendName:"cpu",kernelFunc:TB};function NB(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{dims:s}=n;ye(r,"reverse");let i=r.shape.length,o=v.parseAxisParam(s,r.shape);if(i===0)return er({inputs:{x:r},backend:a});let l=new jt(r.shape,r.dtype),u=a.bufferSync(r);for(let p=0;p<l.size;p++){let c=l.indexToLoc(p),d=c.slice();o.forEach(h=>d[h]=r.shape[h]-1-d[h]),l.set(u.get(...d),...c)}return a.makeTensorInfo(l.shape,l.dtype,l.values)}var EB={kernelName:Ji,backendName:"cpu",kernelFunc:NB},RB={kernelName:mo,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:a})=>{let{image:n}=e,{radians:r,fillValue:s,center:i}=t,o=a,l=v.getTypedArrayFromDType(n.dtype,v.sizeFromShape(n.shape)),[u,p,c,d]=n.shape,[h,f]=T.getImageCenter(i,p,c),m=255,g=Math.sin(r),x=Math.cos(r),A=o.data.get(n.dataId).values;for(let y=0;y<u;y++){let b=y*c*p*d;for(let w=0;w<p;w++){let S=w*(c*d);for(let C=0;C<c;C++){let E=C*d;for(let _=0;_<d;_++){let $=[u,w,C,_],M=$[2],I=$[1],N=(M-h)*x-(I-f)*g,O=(M-h)*g+(I-f)*x;N=Math.round(N+h),O=Math.round(O+f);let L=s;if(typeof s!="number"&&(_===3?L=m:L=s[_]),N>=0&&N<c&&O>=0&&O<p){let G=O*(c*d),j=N*d,U=b+G+j+_;L=A[U]}let B=b+S+E+_;l[B]=L}}}}return{dataId:o.write(l,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},MB=ot(Xl,e=>{let t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2===0?t:t+1}),$B={kernelName:Xl,backendName:"cpu",kernelFunc:MB};function _B(e){let{inputs:t,backend:a,attrs:n}=e,{indices:r,updates:s}=t,{shape:i}=n,{sliceRank:o,numUpdates:l,sliceSize:u,strides:p,outputSize:c}=T.calculateShapes(s,r,i),d=!0,h=a.bufferSync(r),f=a.bufferSync(s),m=tl(h,f,i,c,u,l,o,p,0,d);return a.makeTensorInfo(i,m.dtype,m.values)}var PB={kernelName:eo,backendName:"cpu",kernelFunc:_B};function FB(e,t){let a=0,n=e.length,r=0;for(;a<n;)r=Math.floor((a+n)/2),e[r]<t?a=r+1:n=r;return n}function OB(e,t){let a=0,n=e.length,r=0;for(;a<n;)r=Math.floor((a+n)/2),e[r]<=t?a=r+1:n=r;return n}function DB(e,t,a,n,r,s){let i=v.getArrayFromDType("int32",a*r);for(let o=0;o<a;++o){let l=e.slice(o*n,(o+1)*n),u=o*r;for(let p=0;p<r;++p)i[u+p]=s==="left"?FB(l,t[p+u]):OB(l,t[p+u])}return i}function zB(e){let{inputs:t,backend:a,attrs:n}=e,{sortedSequence:r,values:s}=t,{side:i}=n,o=a.data.get(r.dataId).values,l=a.data.get(s.dataId).values,u=DB(o,l,r.shape[0],r.shape[1],s.shape[1],i);return a.makeTensorInfo(s.shape,"int32",u)}var LB={kernelName:$d,backendName:"cpu",kernelFunc:zB};function BB(e){let{inputs:t,backend:a}=e,{condition:n,t:r,e:s}=t;ye([n,r,s],"select");let i=n.shape.length,o=a.data.get(n.dataId).values,l=a.data.get(r.dataId).values,u=a.data.get(s.dataId).values,p=ca(r.dtype,s.dtype),c=v.makeZerosTypedArray(v.sizeFromShape(r.shape),p),d=0,h=i===0||i>1||r.shape.length===1?1:v.sizeFromShape(r.shape.slice(1));for(let f=0;f<o.length;f++)for(let m=0;m<h;m++)o[f]===1?c[d++]=l[f]:c[d++]=u[f];return a.makeTensorInfo(r.shape,p,c)}var WB={kernelName:Kl,backendName:"cpu",kernelFunc:BB},VB=T.SELU_SCALEALPHA,UB=T.SELU_SCALE,GB=ot(_d,e=>e>=0?UB*e:VB*(Math.exp(e)-1)),HB={kernelName:_d,backendName:"cpu",kernelFunc:GB},jB=ot(Pd,e=>e<0?-1:e>0?1:0),qB={kernelName:Pd,backendName:"cpu",kernelFunc:jB},XB=ot(to,e=>Math.sin(e)),KB={kernelName:to,backendName:"cpu",kernelFunc:XB},ZB=ot(Yl,e=>Math.sinh(e)),YB={kernelName:Yl,backendName:"cpu",kernelFunc:ZB},JB=11920928955078125e-23,dx=Math.log(JB)+2,QB=ot(Fd,e=>{let t=e>-dx,a=e<dx,n=Math.exp(e),r;return a?r=n:t?r=e:r=Math.log(1+n),r}),eW={kernelName:Fd,backendName:"cpu",kernelFunc:QB};function tW(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{blockShape:s,paddings:i}=n;ye([r],"spaceToBatchND");let o=v.sizeFromShape(s),l=[[0,0]];l.push(...i);for(let g=1+s.length;g<r.shape.length;++g)l.push([0,0]);let u=H7.kernelFunc({inputs:{x:r},backend:a,attrs:{paddings:l,constantValue:0}}),p=T.getReshaped(u.shape,s,o,!1),c=T.getPermuted(p.length,s.length,!1),d=T.getReshapedPermuted(u.shape,s,o,!1),h=mt({inputs:{x:u},backend:a,attrs:{shape:p}}),f=La({inputs:{x:h},backend:a,attrs:{perm:c}}),m=mt({inputs:{x:f},backend:a,attrs:{shape:d}});return a.disposeIntermediateTensorInfo(u),a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(f),m}var aW={kernelName:Jl,backendName:"cpu",kernelFunc:tW};function nW(e){let{inputs:t,backend:a}=e,{indices:n,values:r,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
${s.shape}`);if(n.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
${n.shape}`);if(r.shape.length!==1)throw new Error(`Values must be a vector, saw:
${r.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
${i.shape}`);let o=a.data.get(n.dataId).values,l=a.data.get(r.dataId).values,u=a.data.get(s.dataId).values,p=a.data.get(i.dataId).values[0],[c,d,h,f,m]=v7(o,n.shape,n.dtype,l,r.dtype,u,p);return[a.makeTensorInfo(d,n.dtype,c),a.makeTensorInfo([d[0]],r.dtype,h),a.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),a.makeTensorInfo([m.length],n.dtype,new Int32Array(m))]}var rW={kernelName:Od,backendName:"cpu",kernelFunc:nW};function sW(e){let{inputs:t,backend:a}=e,{inputIndices:n,inputShape:r,newShape:s}=t;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
${n.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
${r.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(a.data.get(r.dataId).values),o=a.data.get(n.dataId).values,l=Array.from(a.data.get(s.dataId).values),[u,p,c]=w7(o,n.shape,n.dtype,i,l);return[a.makeTensorInfo(p,n.dtype,u),a.makeTensorInfo([c.length],s.dtype,new Int32Array(c))]}var iW={kernelName:eu,backendName:"cpu",kernelFunc:sW};function oW(e){let{inputs:t,backend:a}=e,{data:n,indices:r,segmentIds:s}=t;if(n.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(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);if(r.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=a.data.get(n.dataId).values,o=a.data.get(r.dataId).values,l=a.data.get(s.dataId).values,[u,p]=p3(i,n.shape,n.dtype,o,l,!0);return a.makeTensorInfo(p,n.dtype,u)}var lW={kernelName:Dd,backendName:"cpu",kernelFunc:oW};function uW(e){let{inputs:t,backend:a}=e,{data:n,indices:r,segmentIds:s}=t;if(n.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(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);if(r.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=a.data.get(n.dataId).values,o=a.data.get(r.dataId).values,l=a.data.get(s.dataId).values,[u,p]=p3(i,n.shape,n.dtype,o,l);return a.makeTensorInfo(p,n.dtype,u)}var dW={kernelName:zd,backendName:"cpu",kernelFunc:uW};function pW(e){let{inputs:t,backend:a,attrs:n}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=n,{sliceRank:l,numUpdates:u,sliceSize:p,strides:c,outputSize:d}=T.calculateShapes(s,r,o),h=!1,f=a.bufferSync(r),m;switch(s.dtype){case"bool":{let g=a.bufferSync(s),x=Boolean(a.data.get(i.dataId).values[0]);m=tl(f,g,o,d,p,u,l,c,x,h);break}case"float32":{let g=a.bufferSync(s),x=a.data.get(i.dataId).values[0];m=tl(f,g,o,d,p,u,l,c,x,h);break}case"int32":{let g=a.bufferSync(s),x=a.data.get(i.dataId).values[0];m=tl(f,g,o,d,p,u,l,c,x,h);break}case"string":{let g=a.bufferSync(s),x=v.decodeString(a.data.get(i.dataId).values[0]);m=tl(f,g,o,d,p,u,l,c,x,h);break}default:throw new Error(`Unsupported type ${s.dtype}`)}return a.makeTensorInfo(o,m.dtype,m.values)}var cW={kernelName:Ld,backendName:"cpu",kernelFunc:pW};function hW(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=n,o=v.parseAxisParam(i,r.shape)[0],l=T.prepareSplitSize(r,s,o),u=new Array(r.shape.length).fill(0),p=r.shape.slice();return l.map(c=>{let d=[...p];d[o]=c;let h=Gs({inputs:{x:r},backend:a,attrs:{begin:u,size:d}});return u[o]+=c,h})}var fW={kernelName:Ql,backendName:"cpu",kernelFunc:hW},mW={kernelName:Bd,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:a}=e,n=t;ye(a,"square");let r=n.data.get(a.dataId).values,s=new Float32Array(r.length);for(let i=0;i<r.length;++i){let o=r[i];s[i]=o*o}return{dataId:n.write(s,a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}},gW=ot(fo,(e,t)=>{let a=t;return isNaN(e)?NaN:e>0?1:a.alpha}),xW={kernelName:fo,backendName:"cpu",kernelFunc:gW};function AW(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:p,newAxisMask:c,shrinkAxisMask:d}=n;ye(r,"stridedSlice");let{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:x,begin:A,end:y,strides:b}=It.sliceInfo(r.shape,s,i,o,l,u,p,c,d),w;if(m)w=mt({inputs:{x:r},backend:a,attrs:{shape:f}});else if(g||x){v.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let S=It.computeOutShape(A,y,b),C=Gs({inputs:{x:r},backend:a,attrs:{begin:A,size:S}});w=mt({inputs:{x:C},backend:a,attrs:{shape:f}}),a.disposeIntermediateTensorInfo(C)}else{let S=a.bufferSync(r),C=I7(h,S,b,A);w=a.makeTensorInfo(f,C.dtype,C.values)}return w}var yW={kernelName:oo,backendName:"cpu",kernelFunc:AW};function bW(e){let{inputs:t,backend:a,attrs:n}=e,{separator:r,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=n,{data:p,dataSplits:c}=t,d=a.data.get(p.dataId).values,h=a.data.get(c.dataId).values,[f,m]=c3(d,h,r,s,i,o,l,u);return[a.makeTensorInfo([f.length],"string",f),a.makeTensorInfo(c.shape,"int32",m)]}var vW={kernelName:tu,backendName:"cpu",kernelFunc:bW};function wW(e){let{inputs:t,backend:a,attrs:n}=e,{skipEmpty:r}=n,{input:s,delimiter:i}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let o=a.data.get(s.dataId).values,l=a.data.get(i.dataId).values[0],[u,p,c]=h3(o,l,r),d=p.length;return[a.makeTensorInfo([d,2],"int32",u),a.makeTensorInfo([d],"string",p),a.makeTensorInfo([2],"int32",new Int32Array(c))]}var kW={kernelName:Wd,backendName:"cpu",kernelFunc:wW};function IW(e){let{inputs:t,backend:a,attrs:n}=e,{numBuckets:r}=n,{input:s}=t;if(s.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 i=a.data.get(s.dataId).values,o=f3(i,r);return a.makeTensorInfo(s.shape,"int32",o)}var SW={kernelName:Vd,backendName:"cpu",kernelFunc:IW},TW=ot(uo,e=>Math.tan(e)),CW={kernelName:uo,backendName:"cpu",kernelFunc:TW},NW=ot(po,e=>Math.tanh(e)),EW={kernelName:po,backendName:"cpu",kernelFunc:NW};function RW(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{reps:s}=n;ye(r,"tile");let i=T7(a.bufferSync(r),s);return a.makeTensorInfo(i.shape,i.dtype,i.values)}var MW={kernelName:ns,backendName:"cpu",kernelFunc:RW};function $W(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{k:s,sorted:i}=n;ye(r,"topk");let o=a.data.get(r.dataId).values,[l,u]=N7(o,r.shape,r.dtype,s,i);return[a.makeTensorInfo(l.shape,l.dtype,l.values),a.makeTensorInfo(u.shape,u.dtype,u.values)]}var _W={kernelName:co,backendName:"cpu",kernelFunc:$W};function PW(e){let{inputs:t,attrs:a,backend:n}=e,{image:r,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=a,[p,c,d,h]=r.shape,[f,m]=u!=null?u:[c,d],g=[p,f,m,h],x=v.computeStrides(r.shape),A=x[0],y=x[1],b=x[2],w=v.computeStrides(g),S=w[0],C=w[1],E=w[2],_=v.getTypedArrayFromDType(r.dtype,v.sizeFromShape(g));_.fill(l);let $=n.data.get(r.dataId).values,M=n.data.get(s.dataId).values;for(let I=0;I<p;++I){let N=s.shape[0]===1?M:M.subarray(I*8,I*8+8);for(let O=0;O<f;++O)for(let L=0;L<m;++L)for(let B=0;B<h;++B){let G,j=N[6]*L+N[7]*O+1;if(j===0)continue;let U=(N[0]*L+N[1]*O+N[2])/j,H=(N[3]*L+N[4]*O+N[5])/j,V=px(U,d,o),Q=px(H,c,o);switch(i){case"nearest":G=BW($,c,d,A,y,b,I,Q,V,B,l);break;case"bilinear":G=WW($,c,d,A,y,b,I,Q,V,B,l);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${i}`)}let Z=I*S+O*C+L*E+B;_[Z]=G}return n.makeTensorInfo(g,r.dtype,_)}return{dataId:n.write(_,g,r.dtype),shape:r.shape,dtype:r.dtype}}var FW={kernelName:ho,backendName:"cpu",kernelFunc:PW};function px(e,t,a){switch(a){case"reflect":return OW(e,t);case"wrap":return DW(e,t);case"nearest":return LW(e,t);case"constant":default:return zW(e,t)}}function OW(e,t){let a=e;if(a<0)if(t<=1)a=0;else{let n=2*t;a<n&&(a=n*Math.trunc(-a/n)+a),a=a<-t?a+n:-a-1}else if(a>t-1)if(t<=1)a=0;else{let n=2*t;a-=n*Math.trunc(a/n),a>=t&&(a=n-a-1)}return v.clamp(0,a,t-1)}function DW(e,t){let a=e;if(a<0)if(t<=1)a=0;else{let n=t-1;a+=t*(Math.trunc(-a/n)+1)}else if(a>t-1)if(t<=1)a=0;else{let n=t-1;a-=t*Math.trunc(a/n)}return v.clamp(0,a,t-1)}function zW(e,t){return e}function LW(e,t){return v.clamp(0,e,t-1)}function ju(e,t,a,n,r,s,i,o,l,u,p){let c=i*n+o*r+l*s+u;return 0<=o&&o<t&&0<=l&&l<a?e[c]:p}function BW(e,t,a,n,r,s,i,o,l,u,p){let c=Math.round(o),d=Math.round(l);return ju(e,t,a,n,r,s,i,c,d,u,p)}function WW(e,t,a,n,r,s,i,o,l,u,p){let c=Math.floor(o),d=Math.floor(l),h=c+1,f=d+1,m=(f-l)*ju(e,t,a,n,r,s,i,c,d,u,p)+(l-d)*ju(e,t,a,n,r,s,i,c,f,u,p),g=(f-l)*ju(e,t,a,n,r,s,i,h,d,u,p)+(l-d)*ju(e,t,a,n,r,s,i,h,f,u,p);return(h-o)*m+(o-c)*g}function VW(e){let{inputs:t,attrs:a,backend:n}=e,{axis:r}=a,{x:s}=t;ye(s,"unique");let i=n.data.get(s.dataId).values,{outputValues:o,outputShape:l,indices:u}=E7(i,r,s.shape,s.dtype);return[n.makeTensorInfo(l,s.dtype,o),n.makeTensorInfo([u.length],"int32",u)]}var UW={kernelName:uh,backendName:"cpu",kernelFunc:VW};function GW(e){let{inputs:t,backend:a,attrs:n}=e,{value:r}=t,{axis:s}=n;s<0&&(s+=r.shape.length);let i=r.shape.length,o=r.shape[s],l=new Array(i-1),u=0;for(let h=0;h<i;h++)h!==s&&(l[u++]=r.shape[h]);let p=new Array(i).fill(0),c=r.shape.slice();c[s]=1;let d=new Array(o);for(let h=0;h<d.length;h++){p[s]=h;let f=Gs({inputs:{x:r},backend:a,attrs:{begin:p,size:c}});d[h]=mt({inputs:{x:f},backend:a,attrs:{shape:l}}),a.disposeIntermediateTensorInfo(f)}return d}var HW={kernelName:au,backendName:"cpu",kernelFunc:GW};function jW(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,segmentIds:s}=t,{numSegments:i}=n;ye(r,"unsortedSegmentSum");let o=r.shape.length,l=s.shape.length,u=[],p=[],c=o-l,d=s;for(let f=0;f<c;++f){let m=Fc({inputs:{input:d},backend:a,attrs:{dim:f+1}});d=m,p.push(m)}for(let f=0;f<i;++f){let m=v.createScalarValue(f,"int32"),g=a.makeTensorInfo([],"int32",m),x=Y4({inputs:{a:g,b:d},backend:a}),A=Jr({inputs:{x},backend:a,attrs:{dtype:"float32"}}),y=Ph({inputs:{a:A,b:r},backend:a}),b=lp({inputs:{x:y},backend:a,attrs:{axis:0,keepDims:!1}});u.push(b),p.push(g),p.push(x),p.push(A),p.push(y),p.push(b)}let h=G7({inputs:u,backend:a,attrs:{axis:0}});return p.forEach(f=>a.disposeIntermediateTensorInfo(f)),h}var qW={kernelName:dh,backendName:"cpu",kernelFunc:jW},XW=[VO,NF,GO,jO,PF,XO,ZO,JO,eD,aD,rD,iD,lD,pD,hD,gD,AD,bD,wD,BO,ID,TD,ND,RD,$F,OF,$D,EF,PD,OD,DD,LD,WD,UD,HD,qD,KD,YD,QD,tz,nz,sz,oz,lz,dz,cz,fz,mz,gz,xz,bz,_O,wz,DF,Rz,zF,Mz,BF,Dz,zz,Bz,VF,Uz,Hz,qz,Kz,Yz,GF,jF,RF,Qz,FD,tL,nL,sL,PO,XF,ZF,oL,JF,uL,cL,fL,xL,yL,vL,wL,eO,IL,TL,NL,RL,$L,PL,OL,aO,zL,WL,HL,rO,iO,XL,YL,eB,lO,aB,rB,sB,H7,uB,OO,pO,pB,hB,mB,xB,MF,b1,yB,DO,zO,LO,vB,kB,SB,CB,EB,RB,$B,yO,PB,LB,WB,HB,vO,qB,KB,YB,wO,UL,eW,aW,rW,iW,lW,dW,cW,fW,SO,mW,CO,xW,yW,vW,kW,SW,MO,Az,CW,EW,MW,_W,FW,uO,UW,HW,qW,nB];for(let e of XW)mn(e);var j7={};Xe(j7,{assertNotComplex:()=>uu,bindCanvasToFramebuffer:()=>sV,bindColorTextureToFramebuffer:()=>xc,bindTextureToProgramUniformSampler:()=>o6,bindTextureUnit:()=>r6,bindVertexBufferToProgramAttribute:()=>w1,callAndCheck:()=>le,canBeRepresented:()=>q7,createFragmentShader:()=>Z7,createFramebuffer:()=>n6,createProgram:()=>Y7,createStaticIndexBuffer:()=>e6,createStaticVertexBuffer:()=>Q7,createTexture:()=>t6,createVertexShader:()=>K7,getBatchDim:()=>Hs,getExtensionOrThrow:()=>qu,getFramebufferErrorMessage:()=>l6,getMaxTexturesInShader:()=>c6,getNumChannels:()=>nV,getProgramUniformLocation:()=>i6,getProgramUniformLocationOrThrow:()=>s6,getRowsCols:()=>js,getShapeAs3D:()=>Ku,getTextureShapeFromLogicalShape:()=>d6,getWebGLDisjointQueryTimerVersion:()=>h6,getWebGLErrorMessage:()=>X7,getWebGLMaxTextureSize:()=>p6,hasExtension:()=>cn,isCapableOfRenderingToFloatTexture:()=>f6,isDownloadFloatTextureEnabled:()=>m6,isReshapeFree:()=>md,isWebGLFenceEnabled:()=>g6,isWebGLVersionEnabled:()=>I1,linkProgram:()=>J7,logShaderSourceAndInfoLog:()=>b3,resetMaxTextureSize:()=>iV,resetMaxTexturesInShader:()=>oV,unbindColorTextureFromFramebuffer:()=>k1,unbindTextureUnit:()=>rV,validateFramebuffer:()=>Xu,validateProgram:()=>gc,validateTextureSize:()=>a6});var Ps={},lc={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Fh(e,t){Ps[e]=t}function Dn(e,t){if(!(e in Ps)||t!=null){let n=ZW(e,t);if(n!==null)Ps[e]=n;else return console.log("Could not get context for WebGL version",e),null}let a=Ps[e];return a==null||a.isContextLost()?(delete Ps[e],Dn(e)):(a.disable(a.DEPTH_TEST),a.disable(a.STENCIL_TEST),a.disable(a.BLEND),a.disable(a.DITHER),a.disable(a.POLYGON_OFFSET_FILL),a.disable(a.SAMPLE_COVERAGE),a.enable(a.SCISSOR_TEST),a.enable(a.CULL_FACE),a.cullFace(a.BACK),Ps[e])}function KW(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 ZW(e,t){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let a=t==null?KW(e):t;return a.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete Ps[e]},!1),W().getBool("SOFTWARE_WEBGL_ENABLED")&&(lc.failIfMajorPerformanceCaveat=!1),e===1?a.getContext("webgl",lc)||a.getContext("experimental-webgl",lc):a.getContext("webgl2",lc)}var fd;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(fd||(fd={}));var pn;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(pn||(pn={}));var na;(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"})(na||(na={}));function up(e,t){return[t,e]}function YW(e,t){return e*t}function uc(e){let t=v.sizeFromShape(e),a=Math.ceil(t/4);return v.sizeToSquarishShape(a)}function lu(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function JW(e,t){let[a,n]=lu(e,t);return a*n*4}function y3(e,t){let a=e,n,r,s,i,o,l,u,p,c,d;return W().getNumber("WEBGL_VERSION")===2?(n=a.R32F,r=a.R16F,s=a.RGBA16F,i=a.RGBA32F,o=a.RED,u=4,p=1,c=a.HALF_FLOAT,d=a.FLOAT,l=a.RGBA8):(n=e.RGBA,r=e.RGBA,s=e.RGBA,i=a.RGBA,o=e.RGBA,u=4,p=4,c=t!=null?t.HALF_FLOAT_OES:null,d=e.FLOAT,l=e.RGBA),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:p,textureTypeHalfFloat:c,textureTypeFloat:d}}function le(e,t){let a=t();return W().getBool("DEBUG")&&QW(e),a}function QW(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+X7(e,t))}var eV=596e-10,tV=65504;function q7(e){return!!(W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||eV<Math.abs(e)&&Math.abs(e)<tV)}function X7(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}function qu(e,t){return Sr(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function K7(e,t){let a=Sr(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(le(e,()=>e.shaderSource(a,t)),le(e,()=>e.compileShader(a)),e.getShaderParameter(a,e.COMPILE_STATUS)===!1)throw console.log(e.getShaderInfoLog(a)),new Error("Failed to compile vertex shader.");return a}function Z7(e,t){let a=Sr(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(le(e,()=>e.shaderSource(a,t)),le(e,()=>e.compileShader(a)),W().get("ENGINE_COMPILE_ONLY"))return a;if(e.getShaderParameter(a,e.COMPILE_STATUS)===!1)throw b3(t,e.getShaderInfoLog(a)),new Error("Failed to compile fragment shader.");return a}var aV=/ERROR: [0-9]+:([0-9]+):/g;function b3(e,t){let a=aV.exec(t);if(a==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}let n=+a[1],r=e.split(`
`),s=r.length.toString().length+2,i=r.map((c,d)=>v.rightPad((d+1).toString(),s)+c),o=0;for(let c=0;c<i.length;c++)o=Math.max(i[c].length,o);let l=i.slice(0,n-1),u=i.slice(n-1,n),p=i.slice(n);console.log(l.join(`
`)),console.log(t.split(`
`)[0]),console.log(`%c ${v.rightPad(u[0],o)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(p.join(`
`))}function Y7(e){return Sr(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function J7(e,t){if(le(e,()=>e.linkProgram(t)),!W().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 gc(e,t){if(le(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function Q7(e,t){let a=Sr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return le(e,()=>e.bindBuffer(e.ARRAY_BUFFER,a)),le(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),a}function e6(e,t){let a=Sr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return le(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,a)),le(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),a}function nV(){return W().getNumber("WEBGL_VERSION")===2?1:4}function t6(e){return Sr(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function a6(e,t){let a=W().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let n=`[${e}x${t}]`;throw new Error("Requested texture size "+n+" is invalid.")}if(e>a||t>a){let n=`[${e}x${t}]`,r=`[${a}x${a}]`;throw new Error("Requested texture size "+n+" greater than WebGL maximum on this browser / GPU "+r+".")}}function n6(e){return Sr(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function w1(e,t,a,n,r,s,i){let o=e.getAttribLocation(t,a);return o===-1?!1:(le(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),le(e,()=>e.vertexAttribPointer(o,r,e.FLOAT,!1,s,i)),le(e,()=>e.enableVertexAttribArray(o)),!0)}function r6(e,t,a){u6(e,a),le(e,()=>e.activeTexture(e.TEXTURE0+a)),le(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function rV(e,t){u6(e,t),le(e,()=>e.activeTexture(e.TEXTURE0+t)),le(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function s6(e,t,a){return Sr(e,()=>e.getUniformLocation(t,a),'uniform "'+a+'" not present in program.')}function i6(e,t,a){return e.getUniformLocation(t,a)}function o6(e,t,a,n){le(e,()=>r6(e,t,n)),le(e,()=>e.uniform1i(a,n))}function sV(e){le(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),le(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),le(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function xc(e,t,a){le(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,a)),le(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function k1(e,t){le(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),le(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Xu(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+l6(e,t))}function l6(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 Sr(e,t,a){let n=le(e,()=>t());if(n==null)throw new Error(a);return n}function u6(e,t){let a=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,n=t+e.TEXTURE0;if(n<e.TEXTURE0||n>a){let r=`[gl.TEXTURE0, gl.TEXTURE${a}]`;throw new Error(`textureUnit must be in ${r}.`)}}function Hs(e,t=2){return v.sizeFromShape(e.slice(0,e.length-t))}function js(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 Ku(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[Hs(e),...js(e)]),t}function d6(e,t=!1){let a=W().getNumber("WEBGL_MAX_TEXTURE_SIZE"),n=W().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");n===1/0&&W().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(n=a/2),t&&(a=a*2,n=n*2,e=e.map((o,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),s=null;e.length<=1&&r<=a?s=[1,r]:e.length===2&&e[0]<=a&&e[1]<=a?s=e:e.length===3&&e[0]*e[1]<=a&&e[2]<=a?s=[e[0]*e[1],e[2]]:e.length===3&&e[0]<=a&&e[1]*e[2]<=a?s=[e[0],e[1]*e[2]]:e.length===4&&e[0]*e[1]*e[2]<=a&&e[3]<=a?s=[e[0]*e[1]*e[2],e[3]]:e.length===4&&e[0]<=a&&e[1]*e[2]*e[3]<=a&&(s=[e[0],e[1]*e[2]*e[3]]);let i=s!=null&&Math.max(...s)>n&&Math.min(...s)<=(t?2:1)&&Math.min(...s)>0;if(s==null||i)if(t){let o=Hs(e),l=2,u=2;e.length&&([l,u]=js(e)),r=o*(l/2)*(u/2),s=v.sizeToSquarishShape(r).map(p=>p*2)}else s=v.sizeToSquarishShape(r);return s}function dc(e){return e%2===0}function md(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 a=e.slice(-1)[0],n=t.slice(-1)[0];if(a===n||dc(a)&&dc(n)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&dc(e[0])&&dc(t[0])}var Ac,yc;function p6(e){if(Ac==null){let t=Dn(e);Ac=t.getParameter(t.MAX_TEXTURE_SIZE)}return Ac}function iV(){Ac=null}function oV(){yc=null}function c6(e){if(yc==null){let t=Dn(e);yc=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,yc)}function h6(e){if(e===0)return 0;let t,a=Dn(e);return cn(a,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:cn(a,"EXT_disjoint_timer_query")?t=1:t=0,t}function cn(e,t){return e.getExtension(t)!=null}function I1(e){try{if(Dn(e)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function f6(e){if(e===0)return!1;let t=Dn(e);if(e===1){if(!cn(t,"OES_texture_float"))return!1}else if(!cn(t,"EXT_color_buffer_float"))return!1;return S1(t)}function m6(e){if(e===0)return!1;let t=Dn(e);if(e===1){if(!cn(t,"OES_texture_float")||!cn(t,"WEBGL_color_buffer_float"))return!1}else{if(cn(t,"EXT_color_buffer_float"))return S1(t);let a="EXT_color_buffer_half_float";if(cn(t,a)){let n=t.getExtension(a);return lV(t,n)}return!1}return S1(t)}function S1(e){let t=y3(e),a=e.createTexture();e.bindTexture(e.TEXTURE_2D,a);let n=1,r=1;e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,n,r,0,t.textureFormatFloat,t.textureTypeFloat,null);let s=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,a,0);let i=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(a),e.deleteFramebuffer(s),i}function lV(e,t){let a=y3(e,t),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);let r=1,s=1;e.texImage2D(e.TEXTURE_2D,0,a.internalFormatHalfFloat,r,s,0,a.textureFormatFloat,a.textureTypeHalfFloat,null);let i=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,i),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);let o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(i),o}function g6(e){return e!==2?!1:Dn(e).fenceSync!=null}function uu(e,t){Array.isArray(e)||(e=[e]),e.forEach(a=>{a!=null&&v.assert(a.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}var ve=W();ve.registerFlag("HAS_WEBGL",()=>ve.getNumber("WEBGL_VERSION")>0);ve.registerFlag("WEBGL_VERSION",()=>I1(2)?2:I1(1)?1:0);ve.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);ve.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>ve.get("WEBGL_VERSION")===2);ve.registerFlag("WEBGL_CPU_FORWARD",()=>!0);ve.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);ve.registerFlag("WEBGL_PACK",()=>ve.getBool("HAS_WEBGL"));ve.registerFlag("WEBGL_PACK_NORMALIZATION",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_CLIP",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_REDUCE",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_LAZILY_UNPACK",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_CONV_IM2COL",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>p6(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>c6(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let e=ve.getNumber("WEBGL_VERSION");return e===0?0:h6(e)});ve.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>ve.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!jd.isMobile());ve.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>f6(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>ve.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:ve.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));ve.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>m6(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_FENCE_API_ENABLED",()=>g6(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>ve.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);ve.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}.`)});ve.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>jd.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}.`)});ve.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);ve.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1);ve.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5);ve.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128);ve.registerFlag("WEBGL_EXP_CONV",()=>!1);ve.registerFlag("SOFTWARE_WEBGL_ENABLED",()=>ve.getBool("IS_TEST"));ve.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",()=>1/0);ve.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",()=>!1);ve.registerFlag("WEBGL2_ISNAN_CUSTOM",()=>!1);ve.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);function Ca(){let e,t,a,n,r,s,i,o,l,u;return W().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",a="out",n="in",r="texture",s="outputColor",i="out vec4 outputColor;",o=W().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",a="varying",n="varying",r="texture2D",s="gl_FragColor",i="",o=`
#define isnan(value) isnan_custom(value)
bool isnan_custom(float val) {
return (val > 0. || val < 1. || val == 0.) ? false : true;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
}
`,l=`
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
}
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
`,u=`
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`),{version:e,attribute:t,varyingVs:a,varyingFs:n,texture2D:r,output:s,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:l,defineRound:u}}function Ao(e,t,a="index"){let n=v.computeStrides(t);return n.map((r,s)=>{let i=`int ${e[s]} = ${a} / ${r}`,o=s===n.length-1?`int ${e[s+1]} = ${a} - ${e[s]} * ${r}`:`index -= ${e[s]} * ${r}`;return`${i}; ${o};`}).join("")}function Oh(e,t,a="index"){let n=v.computeStrides(t);return n.map((r,s)=>{let i=`int ${e[s]} = ${a} / outShapeStrides[${s}]`,o=s===n.length-1?`int ${e[s+1]} = ${a} - ${e[s]} * outShapeStrides[${s}]`:`index -= ${e[s]} * outShapeStrides[${s}]`;return`${i}; ${o};`}).join("")}function uV(e,t){let a=e.length,n=e.map(s=>`${t}[${s}]`),r=new Array(a-1);r[a-2]=n[a-1];for(let s=a-3;s>=0;--s)r[s]=`(${r[s+1]} * ${n[s+1]})`;return r}function dV(e,t,a="index"){let n=e.map((s,i)=>i),r=uV(n,t);return r.map((s,i)=>{let o=`int ${e[i]} = ${a} / ${r[i]}`,l=i===r.length-1?`int ${e[i+1]} = ${a} - ${e[i]} * ${r[i]}`:`index -= ${e[i]} * ${r[i]}`;return`${o}; ${l};`}).join("")}function v3(e){let t=v.computeStrides(e).map(a=>a.toString());return`
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
`}function w3(){return`
int getFlatIndex(ivec3 coords) {
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
}
`}var x6=`
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:A6}=T;function pV(e,t,a){let n=[];if(e.forEach(d=>{let h=v.sizeFromShape(d.shapeInfo.logicalShape);if(d.shapeInfo.isUniform?n.push(`uniform float ${d.name}${h>1?`[${h}]`:""};`):(n.push(`uniform sampler2D ${d.name};`),n.push(`uniform int offset${d.name};`)),a.enableShapeUniforms){let{uniformShape:f}=k3(a.packedInputs,d.shapeInfo.logicalShape,d.shapeInfo.texShape);switch(f.length){case 1:n.push(`uniform int ${d.name}Shape;`);break;case 2:n.push(`uniform ivec2 ${d.name}Shape;`);break;case 3:n.push(`uniform ivec3 ${d.name}Shape;`);break;case 4:n.push(`uniform ivec4 ${d.name}Shape;`);break;default:break}n.push(`uniform ivec2 ${d.name}TexShape;`)}}),a.enableShapeUniforms){switch(t.logicalShape.length){case 1:n.push("uniform int outShape;");break;case 2:n.push("uniform ivec2 outShape;"),n.push("uniform int outShapeStrides;");break;case 3:n.push("uniform ivec3 outShape;"),n.push("uniform ivec2 outShapeStrides;");break;case 4:n.push("uniform ivec4 outShape;"),n.push("uniform ivec3 outShapeStrides;");break;default:break}n.push("uniform ivec2 outTexShape;")}a.customUniforms&&a.customUniforms.forEach(d=>{n.push(`uniform ${d.type} ${d.name}${d.arrayIndex?`[${d.arrayIndex}]`:""};`)});let r=n.join(`
`),s=e.map(d=>cV(d,t,a.packedInputs,a.enableShapeUniforms)).join(`
`),i=t.texShape,o=Ca(),l=mV(o),u,p,c=AV(o);return t.isPacked?(u=hV(t.logicalShape,i,a.enableShapeUniforms),p=xV(o)):(u=fV(t.logicalShape,i,a.enableShapeUniforms),p=gV(o)),a.packedInputs&&(c+=wV),[c,l,p,r,u,s,a.userCode].join(`
`)}function du(e,t=!1){let a=e.shapeInfo.logicalShape;switch(a.length){case 0:return PV(e,t);case 1:return OV(e,t);case 2:return zV(e,t);case 3:return BV(e,t);case 4:return VV(e,t);case 5:return UV(e);case 6:return GV(e);default:throw new Error(`${a.length}-D input sampling is not yet supported`)}}function y6(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return _V(e);case 1:return FV(e,t);case 2:return DV(e,t);case 3:return LV(e,t);default:return WV(e,t)}}function cV(e,t,a=!1,n){let r="";a?r+=y6(e,n):r+=du(e,n);let s=e.shapeInfo.logicalShape,i=t.logicalShape;return s.length<=i.length&&(a?r+=HV(e,t):r+=jV(e,t)),r}function hV(e,t,a){switch(e.length){case 0:return b6();case 1:return kV(e,t,a);case 2:return MV(e,t,a);case 3:return SV(e,t,a);default:return CV(e,t,a)}}function fV(e,t,a){switch(e.length){case 0:return b6();case 1:return IV(e,t,a);case 2:return $V(e,t,a);case 3:return TV(e,t,a);case 4:return NV(e,t,a);case 5:return EV(e,t);case 6:return RV(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function mV(e){return`
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
}
`}function gV(e){return`
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
}
`}function xV(e){return`
void setOutput(vec4 val) {
${e.output} = val;
}
`}function AV(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);
}
${yV}
${bV}
${vV}
`}var yV=`
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);
}
`,bV=`
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);
}
`,vV=`
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);
}
`,wV=`
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 b6(){return`
int getOutputCoords() {
return 0;
}
`}function kV(e,t,a){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return n[0]===1?a?`
int getOutputCoords() {
return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
}
`:`
int getOutputCoords() {
return 2 * int(resultUV.x * ${n[1]}.0);
}
`:n[1]===1?a?`
int getOutputCoords() {
return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
}
`:`
int getOutputCoords() {
return 2 * int(resultUV.y * ${n[0]}.0);
}
`:a?`
int getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
return 2 * (resTexRC.x * ${n[1]} + resTexRC.y);
}
`}function IV(e,t,a){return t[0]===1?a?`
int getOutputCoords() {
return int(resultUV.x * float(outTexShape[1]));
}
`:`
int getOutputCoords() {
return int(resultUV.x * ${t[1]}.0);
}
`:t[1]===1?a?`
int getOutputCoords() {
return int(resultUV.y * float(outTexShape[0]));
}
`:`
int getOutputCoords() {
return int(resultUV.y * ${t[0]}.0);
}
`:a?`
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 SV(e,t,a){if(a)return`
ivec3 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int b = index / texelsInBatch;
index -= b * texelsInBatch;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec3(b, r, c);
}
`;let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[2]/2),s=r*Math.ceil(e[1]/2);return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
int b = index / ${s};
index -= b * ${s};
int r = 2 * (index / ${r});
int c = imod(index, ${r}) * 2;
return ivec3(b, r, c);
}
`}function TV(e,t,a){if(a)return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
${Oh(["r","c","d"],e)}
return ivec3(r, c, d);
}
`;let n=Ao(["r","c","d"],e);return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
return ivec3(r, c, d);
}
`}function CV(e,t,a){if(a)return`
ivec4 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));
int texelsInBatchN = texelsInBatch * outShape[1];
int b2 = index / texelsInBatchN;
index -= b2 * texelsInBatchN;
int b = index / texelsInBatch;
index -= b * texelsInBatch;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec4(b2, b, r, c);
}
`;let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[e.length-1]/2),s=r*Math.ceil(e[e.length-2]/2),i=s,o="",l="b, r, c";for(let u=2;u<e.length-1;u++)i*=e[e.length-u-1],o=`
int b${u} = index / ${i};
index -= b${u} * ${i};
`+o,l=`b${u}, `+l;return`
ivec${e.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
${o}
int b = index / ${s};
index -= b * ${s};
int r = 2 * (index / ${r});
int c = imod(index, ${r}) * 2;
return ivec${e.length}(${l});
}
`}function NV(e,t,a){if(a)return`
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
${Oh(["r","c","d","d2"],e)}
return ivec4(r, c, d, d2);
}
`;let n=Ao(["r","c","d","d2"],e);return`
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
return ivec4(r, c, d, d2);
}
`}function EV(e,t){let a=Ao(["r","c","d","d2","d3"],e);return`
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${a}
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
}
`}function RV(e,t){let a=Ao(["r","c","d","d2","d3","d4"],e);return`
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${a}
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
`}function MV(e,t,a){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(v.arraysEqual(e,t))return a?`
ivec2 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));
}
`:`
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(${n[0]}, ${n[1]}));
}
`;let r=Math.ceil(e[1]/2);return a?`
ivec2 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec2(r, c);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
int r = 2 * (index / ${r});
int c = imod(index, ${r}) * 2;
return ivec2(r, c);
}
`}function $V(e,t,a){return v.arraysEqual(e,t)?a?`
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
}
`:`
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
}
`:e[1]===1?a?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(index, 0);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(index, 0);
}
`:e[0]===1?a?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(0, index);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(0, index);
}
`:a?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
int r = index / outShape[1];
int c = index - r * outShape[1];
return ivec2(r, c);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
int r = index / ${e[1]};
int c = index - r * ${e[1]};
return ivec2(r, c);
}
`}function yo(e){return`offset${e}`}function _V(e){let t=e.name,a="get"+t.charAt(0).toUpperCase()+t.slice(1),n=Ca();return`
vec4 ${a}() {
return ${n.texture2D}(${t}, halfCR);
}
`}function PV(e,t){let a=e.name,n="get"+a.charAt(0).toUpperCase()+a.slice(1);if(e.shapeInfo.isUniform)return`float ${n}() {return ${a};}`;let[r,s]=e.shapeInfo.texShape;if(r===1&&s===1)return`
float ${n}() {
return sampleTexture(${a}, halfCR);
}
`;let i=yo(a);if(t)return`
float ${n}() {
vec2 uv = uvFromFlat(${a}TexShape[0], ${a}TexShape[1], ${i});
return sampleTexture(${a}, uv);
}
`;let[o,l]=e.shapeInfo.texShape;return`
float ${n}() {
vec2 uv = uvFromFlat(${o}, ${l}, ${i});
return sampleTexture(${a}, uv);
}
`}function FV(e,t){let a=e.name,n="get"+a.charAt(0).toUpperCase()+a.slice(1),r=e.shapeInfo.texShape,s=Ca();if(t)return`
vec4 ${n}(int index) {
ivec2 packedTexShape = ivec2(ceil(float(${a}TexShape[0]) / 2.0), ceil(float(${a}TexShape[1]) / 2.0));
vec2 uv = packedUVfrom1D(
packedTexShape[0], packedTexShape[1], index);
return ${s.texture2D}(${a}, uv);
}
`;let i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)];return`
vec4 ${n}(int index) {
vec2 uv = packedUVfrom1D(
${i[0]}, ${i[1]}, index);
return ${s.texture2D}(${a}, uv);
}
`}function OV(e,t){let a=e.name,n="get"+a.charAt(0).toUpperCase()+a.slice(1);if(e.shapeInfo.isUniform)return`
float ${n}(int index) {
${pu(e)}
}
`;let r=e.shapeInfo.texShape,s=r[0],i=r[1];if(i===1&&s===1)return`
float ${n}(int index) {
return sampleTexture(${a}, halfCR);
}
`;let o=yo(a);return i===1?t?`
float ${n}(int index) {
vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / float(${a}TexShape[0]));
return sampleTexture(${a}, uv);
}
`:`
float ${n}(int index) {
vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / ${s}.0);
return sampleTexture(${a}, uv);
}
`:s===1?t?`
float ${n}(int index) {
vec2 uv = vec2((float(index + ${o}) + 0.5) / float(${a}TexShape[1]), 0.5);
return sampleTexture(${a}, uv);
}
`:`
float ${n}(int index) {
vec2 uv = vec2((float(index + ${o}) + 0.5) / ${i}.0, 0.5);
return sampleTexture(${a}, uv);
}
`:t?`
float ${n}(int index) {
vec2 uv = uvFromFlat(${a}TexShape[0], ${a}TexShape[1], index + ${o});
return sampleTexture(${a}, uv);
}
`:`
float ${n}(int index) {
vec2 uv = uvFromFlat(${s}, ${i}, index + ${o});
return sampleTexture(${a}, uv);
}
`}function DV(e,t){let a=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,i=s[0],o=s[1],l=Ca();if(s!=null&&v.arraysEqual(a,s))return t?`
vec4 ${r}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
return ${l.texture2D}(${n}, uv);
}
`:`
vec4 ${r}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}.0, ${i}.0);
return ${l.texture2D}(${n}, uv);
}
`;if(t)return`
vec4 ${r}(int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${n}Shape[1]) / 2.0));
vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
return ${l.texture2D}(${n}, uv);
}
`;let u=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],p=Math.ceil(a[1]/2);return`
vec4 ${r}(int row, int col) {
vec2 uv = packedUVfrom2D(${p}, ${u[0]}, ${u[1]}, row, col);
return ${l.texture2D}(${n}, uv);
}
`}function zV(e,t){let a=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape;if(s!=null&&v.arraysEqual(a,s)){if(t)return`
float ${r}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
}
`;let d=s[0],h=s[1];return`
float ${r}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${h}.0, ${d}.0);
return sampleTexture(${n}, uv);
}
`}let{newShape:i,keptDims:o}=v.squeezeShape(a),l=i;if(l.length<a.length){let d=cu(e,l),h=["row","col"];return`
${du(d,t)}
float ${r}(int row, int col) {
return ${r}(${hu(h,o)});
}
`}if(e.shapeInfo.isUniform)return`
float ${r}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${a[1]}, 1)));
${pu(e)}
}
`;let u=s[0],p=s[1],c=yo(n);return p===1?t?`
float ${r}(int row, int col) {
float index = dot(vec3(row, col, ${c}), vec3(${n}Shape[1], 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / float(${n}TexShape[0]));
return sampleTexture(${n}, uv);
}
`:`
float ${r}(int row, int col) {
float index = dot(vec3(row, col, ${c}), vec3(${a[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${u}.0);
return sampleTexture(${n}, uv);
}
`:u===1?t?`
float ${r}(int row, int col) {
float index = dot(vec3(row, col, ${c}), vec3(${n}Shape[1], 1, 1));
vec2 uv = vec2((index + 0.5) / float(${n}TexShape[1]), 0.5);
return sampleTexture(${n}, uv);
}
`:`
float ${r}(int row, int col) {
float index = dot(vec3(row, col, ${c}), vec3(${a[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${p}.0, 0.5);
return sampleTexture(${n}, uv);
}
`:t?`
float ${r}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${n}Shape[1] + col + ${c};
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index);
return sampleTexture(${n}, uv);
}
`:`
float ${r}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${a[1]} + col + ${c};
vec2 uv = uvFromFlat(${u}, ${p}, index);
return sampleTexture(${n}, uv);
}
`}function LV(e,t){let a=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];if(a[0]===1){let d=a.slice(1),h=[1,2],f=cu(e,d),m=["b","row","col"];return`
${y6(f,t)}
vec4 ${r}(int b, int row, int col) {
return ${r}(${hu(m,h)});
}
`}let o=Ca();if(t)return`
vec4 ${r}(int b, int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${n}Shape[2]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[1]) / 2.0));
vec2 uv = packedUVfrom3D(
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
return ${o.texture2D}(${n}, uv);
}
`;let l=i[0],u=i[1],p=Math.ceil(a[2]/2),c=p*Math.ceil(a[1]/2);return`
vec4 ${r}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${l}, ${u}, ${c}, ${p}, b, row, col);
return ${o.texture2D}(${n}, uv);
}
`}function BV(e,t){let a=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=a[1]*a[2],i=a[2],{newShape:o,keptDims:l}=v.squeezeShape(a),u=o;if(u.length<a.length){let m=cu(e,u),g=["row","col","depth"];return`
${du(m,t)}
float ${r}(int row, int col, int depth) {
return ${r}(${hu(g,l)});
}
`}if(e.shapeInfo.isUniform)return`
float ${r}(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(${s}, ${i}, 1)));
${pu(e)}
}
`;let p=e.shapeInfo.texShape,c=p[0],d=p[1],h=e.shapeInfo.flatOffset;if(d===s&&h==null)return t?`
float ${r}(int row, int col, int depth) {
int stride1 = ${n}Shape[2];
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(stride1, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
}
`:`
float ${r}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${i}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${d}.0, ${c}.0);
return sampleTexture(${n}, uv);
}
`;if(d===i&&h==null)return t?`
float ${r}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${n}Shape[1], 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
}
`:`
float ${r}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${a[1]}, 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${d}.0, ${c}.0);
return sampleTexture(${n}, uv);
}
`;let f=yo(n);return t?`
float ${r}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int stride0 = ${n}Shape[1] * ${n}Shape[2];
int stride1 = ${n}Shape[2];
int index = row * stride0 + col * stride1 + depth + ${f};
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index);
return sampleTexture(${n}, uv);
}
`:`
float ${r}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${s} + col * ${i} + depth + ${f};
vec2 uv = uvFromFlat(${c}, ${d}, index);
return sampleTexture(${n}, uv);
}
`}function WV(e,t){let a=e.name,n="get"+a.charAt(0).toUpperCase()+a.slice(1),r=Ca();if(t)return`
vec4 ${n}(int b2, int b, int row, int col) {
int valuesPerRow = int(ceil(float(${a}Shape[3]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${a}Shape[2]) / 2.0));
int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
texelsInBatch *= ${a}Shape[1];
index = b2 * texelsInBatch + index;
ivec2 packedTexShape = ivec2(ceil(float(${a}TexShape[0]) / 2.0), ceil(float(${a}TexShape[1]) / 2.0));
int texR = index / packedTexShape[1];
int texC = index - texR * packedTexShape[1];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${r.texture2D}(${a}, uv);
}
`;let s=e.shapeInfo.logicalShape,i=s.length,o=e.shapeInfo.texShape,l=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],u=l[0],p=l[1],c=Math.ceil(s[i-1]/2),d=c*Math.ceil(s[i-2]/2),h="int b, int row, int col",f=`b * ${d} + (row / 2) * ${c} + (col / 2)`;for(let m=2;m<i-1;m++)h=`int b${m}, `+h,d*=s[i-m-1],f=`b${m} * ${d} + `+f;return`
vec4 ${n}(${h}) {
int index = ${f};
int texR = index / ${p};
int texC = index - texR * ${p};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}, ${u});
return ${r.texture2D}(${a}, uv);
}
`}function VV(e,t){let a=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=a[3],i=a[2]*s,o=a[1]*i,{newShape:l,keptDims:u}=v.squeezeShape(a);if(l.length<a.length){let A=cu(e,l),y=["row","col","depth","depth2"];return`
${du(A,t)}
float ${r}(int row, int col, int depth, int depth2) {
return ${r}(${hu(y,u)});
}
`}if(e.shapeInfo.isUniform)return`
float ${r}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${o}, ${i}, ${s}, 1)));
${pu(e)}
}
`;let p=e.shapeInfo.flatOffset,c=e.shapeInfo.texShape,d=c[0],h=c[1],f=`int stride2 = ${n}Shape[3];`,m=`int stride1 = ${n}Shape[2] * stride2;`,g=`int stride0 = ${n}Shape[1] * stride1;`;if(h===o&&p==null)return t?`
float ${r}(int row, int col, int depth, int depth2) {
${f}
${m}
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(stride1, stride2, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
}
`:`
float ${r}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${i}, ${s}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${d}.0);
return sampleTexture(${n}, uv);
}
`;if(h===s&&p==null)return t?`
float ${r}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${n}Shape[1] * ${n}Shape[2], ${n}Shape[2], 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
}
`:`
float ${r}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${a[1]*a[2]}, ${a[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${d}.0);
return sampleTexture(${n}, uv);
}
`;let x=yo(n);return t?`
float ${r}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
${f}
${m}
${g}
int index = row * stride0 + col * stride1 +
depth * stride2 + depth2;
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${x});
return sampleTexture(${n}, uv);
}
`:`
float ${r}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${o} + col * ${i} +
depth * ${s} + depth2;
vec2 uv = uvFromFlat(${d}, ${h}, index + ${x});
return sampleTexture(${n}, uv);
}
`}function UV(e){let t=e.shapeInfo.logicalShape,a=e.name,n="get"+a.charAt(0).toUpperCase()+a.slice(1),r=t[4],s=t[3]*r,i=t[2]*s,o=t[1]*i,{newShape:l,keptDims:u}=v.squeezeShape(t);if(l.length<t.length){let m=cu(e,l),g=["row","col","depth","depth2","depth3"];return`
${du(m)}
float ${n}(int row, int col, int depth, int depth2, int depth3) {
return ${n}(${hu(g,u)});
}
`}if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(${o}, ${i}, ${s}, ${r})) +
depth3;
${pu(e)}
}
`;let p=e.shapeInfo.flatOffset,c=e.shapeInfo.texShape,d=c[0],h=c[1];if(h===o&&p==null)return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${i}, ${s}, ${r}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${d}.0);
return sampleTexture(${a}, uv);
}
`;if(h===r&&p==null)return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]},
${t[2]*t[3]}, ${t[3]}, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${d}.0);
return sampleTexture(${a}, uv);
}
`;let f=yo(a);return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${o} + col * ${i} + depth * ${s} +
depth2 * ${r} + depth3 + ${f};
vec2 uv = uvFromFlat(${d}, ${h}, index);
return sampleTexture(${a}, uv);
}
`}function GV(e){let t=e.shapeInfo.logicalShape,a=e.name,n="get"+a.charAt(0).toUpperCase()+a.slice(1),{newShape:r,keptDims:s}=v.squeezeShape(t);if(r.length<t.length){let g=cu(e,r),x=["row","col","depth","depth2","depth3","depth4"];return`
${du(g)}
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${n}(${hu(x,s)});
}
`}let i=t[5],o=t[4]*i,l=t[3]*o,u=t[2]*l,p=t[1]*u;if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(${p}, ${u}, ${l}, ${o})) +
dot(
vec2(depth3, depth4),
vec2(${i}, 1)));
${pu(e)}
}
`;let c=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,h=d[0],f=d[1];if(f===p&&c==null)return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${u}, ${l}, ${o}, ${i})) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${h}.0);
return sampleTexture(${a}, uv);
}
`;if(f===i&&c==null)return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]*t[4]},
${t[2]*t[3]*t[4]},
${t[3]*t[4]},
${t[4]})) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${h}.0);
return sampleTexture(${a}, uv);
}
`;let m=yo(a);return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${p} + col * ${u} + depth * ${l} +
depth2 * ${o} + depth3 * ${i} + depth4 + ${m};
vec2 uv = uvFromFlat(${h}, ${f}, index);
return sampleTexture(${a}, uv);
}
`}function pu(e){let t=e.name,a=v.sizeFromShape(e.shapeInfo.logicalShape);return a<2?`return ${t};`:`
for (int i = 0; i < ${a}; i++) {
if (i == index) {
return ${t}[i];
}
}
`}function HV(e,t){let a=e.name,n=a.charAt(0).toUpperCase()+a.slice(1),r="get"+n+"AtOutCoords",s=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o=A6(e.shapeInfo.logicalShape,t.logicalShape),l=gt(i),u=i-s,p,c=["x","y","z","w","u","v"];s===0?p="":i<2&&o.length>=1?p="coords = 0;":p=o.map(g=>`coords.${c[g+u]} = 0;`).join(`
`);let d="";i<2&&s>0?d="coords":d=e.shapeInfo.logicalShape.map((g,x)=>`coords.${c[x+u]}`).join(", ");let h="return outputValue;",f=v.sizeFromShape(e.shapeInfo.logicalShape)===1,m=v.sizeFromShape(t.logicalShape)===1;if(s===1&&!f&&!m)h=`
return vec4(outputValue.xy, outputValue.xy);
`;else if(f&&!m)i===1?h=`
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:h=`
return vec4(outputValue.x);
`;else if(o.length){let g=s-2,x=s-1;o.indexOf(g)>-1&&o.indexOf(x)>-1?h="return vec4(outputValue.x);":o.indexOf(g)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(x)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return`
vec4 ${r}() {
${l} coords = getOutputCoords();
${p}
vec4 outputValue = get${n}(${d});
${h}
}
`}function jV(e,t){let a=e.name,n=a.charAt(0).toUpperCase()+a.slice(1),r="get"+n+"AtOutCoords",s=t.texShape,i=e.shapeInfo.texShape,o=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&o===l&&e.shapeInfo.flatOffset==null&&v.arraysEqual(i,s))return`
float ${r}() {
return sampleTexture(${a}, resultUV);
}
`;let u=gt(l),p=A6(e.shapeInfo.logicalShape,t.logicalShape),c=l-o,d,h=["x","y","z","w","u","v"];o===0?d="":l<2&&p.length>=1?d="coords = 0;":d=p.map(m=>`coords.${h[m+c]} = 0;`).join(`
`);let f="";return l<2&&o>0?f="coords":f=e.shapeInfo.logicalShape.map((m,g)=>`coords.${h[g+c]}`).join(", "),`
float ${r}() {
${u} coords = getOutputCoords();
${d}
return get${n}(${f});
}
`}function gt(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 k3(e,t,a){let{newShape:n,keptDims:r}=v.squeezeShape(t),s=t.length,i=e&&s===3&&t[0]===1,o=i?t.slice(1):n,l=!e&&s>1&&!v.arraysEqual(t,a)&&n.length<s||i;return{useSqueezeShape:l,uniformShape:l?o:t,keptDims:r}}function cu(e,t){let a=JSON.parse(JSON.stringify(e));return a.shapeInfo.logicalShape=t,a}function hu(e,t){return t.map(a=>e[a]).join(", ")}function qV(e,t,a,n){let r=a.map((p,c)=>{let d={logicalShape:p.shape,texShape:p.isUniform?null:p.texData.texShape,isUniform:p.isUniform,isPacked:p.isUniform?!1:p.texData.isPacked,flatOffset:null};return p.texData!=null&&p.texData.slice!=null&&p.texData.slice.flatOffset>0&&(d.flatOffset=p.texData.slice.flatOffset),{name:t.variableNames[c],shapeInfo:d}}),s=r.map(p=>p.shapeInfo),i={logicalShape:n.shape,texShape:n.texData.texShape,isUniform:!1,isPacked:n.texData.isPacked,flatOffset:null},o=pV(r,i,t),l=Z7(e.gl,o),u=e.createProgram(l);return W().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:s,outShapeInfo:i,uniformLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,inShapesLocations:null,inTexShapesLocations:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:Object.assign({program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:s,outShapeInfo:i},v6(e,t,u))}function v6(e,t,a){let n={},r={},s={},i=[],o,l,u,p=null,c=null;c=e.getUniformLocation(a,"NAN",!1),W().getNumber("WEBGL_VERSION")===1&&(p=e.getUniformLocation(a,"INFINITY",!1));let d=!1;for(let h=0;h<t.variableNames.length;h++){let f=t.variableNames[h];n[f]=e.getUniformLocation(a,f,d),n[`offset${f}`]=e.getUniformLocation(a,`offset${f}`,d),t.enableShapeUniforms&&(r[`${f}Shape`]=e.getUniformLocation(a,`${f}Shape`,d),s[`${f}TexShape`]=e.getUniformLocation(a,`${f}TexShape`,d))}return t.enableShapeUniforms&&(o=e.getUniformLocation(a,"outShape",d),u=e.getUniformLocation(a,"outShapeStrides",d),l=e.getUniformLocation(a,"outTexShape",d)),t.customUniforms&&t.customUniforms.forEach((h,f)=>{i[f]=e.getUniformLocation(a,h.name,d)}),{uniformLocations:n,customUniformLocations:i,infLoc:p,nanLoc:c,inShapesLocations:r,inTexShapesLocations:s,outShapeLocation:o,outShapeStridesLocation:u,outTexShapeLocation:l}}function cx(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((a,n)=>{let r=a.logicalShape,s=t[n],i=s.shape;if(!v.arraysEqual(r,i))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${r} and ${i} must match`);if(a.isUniform&&s.isUniform)return;let o=a.texShape,l=s.isUniform?null:s.texData.texShape;if(!v.arraysEqual(o,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${o} and ${l} must match`)})}function XV(e,t,a,n,r){t.program.enableShapeUniforms||(cx(t.inShapeInfos,a),cx([t.outShapeInfo],[n]));let s=n.texData.texture,i=n.texData.texShape;n.texData.isPacked?e.setOutputPackedMatrixTexture(s.texture,i[0],i[1]):e.setOutputMatrixTexture(s.texture,i[0],i[1]),e.setProgram(t.webGLProgram),W().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),a.forEach((l,u)=>{let p=t.program.variableNames[u],c=t.uniformLocations[p],d=t.uniformLocations[`offset${p}`],h=t.inShapesLocations[`${p}Shape`],f=t.inTexShapesLocations[`${p}TexShape`];if(h){let{uniformShape:m}=k3(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]),c!=null){if(l.isUniform){if(v.sizeFromShape(l.shape)<2)e.gl.uniform1f(c,l.uniformValues[0]);else{let m=l.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),e.gl.uniform1fv(c,m)}return}l.texData.slice!=null&&d!=null&&e.gl.uniform1i(d,l.texData.slice.flatOffset),e.setInputMatrixTexture(l.texData.texture.texture,c,u)}});let o=t.outShapeLocation;if(o)switch(n.shape.length){case 1:e.gl.uniform1iv(o,new Int32Array(n.shape));break;case 2:e.gl.uniform2iv(o,new Int32Array(n.shape));break;case 3:e.gl.uniform3iv(o,new Int32Array(n.shape));break;case 4:e.gl.uniform4iv(o,new Int32Array(n.shape));break;default:break}if(t.outShapeStridesLocation){let l=v.computeStrides(n.shape);switch(n.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(l));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(l));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(l));break;default:break}}t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,n.texData.texShape[0],n.texData.texShape[1]),t.program.customUniforms&&r&&t.program.customUniforms.forEach((l,u)=>{let p=t.customUniformLocations[u],c=r[u];if(l.type==="float")e.gl.uniform1fv(p,c);else if(l.type==="vec2")e.gl.uniform2fv(p,c);else if(l.type==="vec3")e.gl.uniform3fv(p,c);else if(l.type==="vec4")e.gl.uniform4fv(p,c);else if(l.type==="int")e.gl.uniform1iv(p,c);else if(l.type==="ivec2")e.gl.uniform2iv(p,c);else if(l.type==="ivec3")e.gl.uniform3iv(p,c);else if(l.type==="ivec4")e.gl.uniform4iv(p,c);else throw Error(`uniform type ${l.type} is not supported yet.`)}),e.executeProgram()}function KV(e,t,a){let n="";t.concat(a).forEach(i=>{let o=i.texData!=null&&i.texData.slice!=null&&i.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!i.isUniform){let l=i.texData.texShape,{useSqueezeShape:u,uniformShape:p,keptDims:c}=k3(e.packedInputs,i.shape,l),d="",h="",f="";if(p.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(p.length===2&&!e.packedInputs)h=`${p[0]>1}_${p[1]>1}`;else if(p.length>2&&!e.packedInputs){let w=v.computeStrides(p);f=`${w[0]===l[1]}_${w[w.length-1]===l[1]}`}let m=i.shape.length,g=p.length===2&&v.arraysEqual(i.shape,l),x=v.sizeFromShape(i.shape)===1,A=T.getBroadcastDims(i.shape,a.shape),y=!e.packedInputs&&m===a.shape.length&&v.arraysEqual(l,a.texData.texShape),b=e.packedInputs||p.length>2?"":`${l[0]>1}_${l[1]>1}`;n+=`${m}_${y}_${u?c:""}_${p.length}_${x}_${A}_${g}_${d}_${h}_${f}_${b}_${o}`}else{let l=i.isUniform?"uniform":i.texData.texShape;n+=`${i.shape}_${l}_${o}`}});let r=e.userCode,s=e.constructor.name;return s+="_"+n+"_"+r+`${W().getNumber("WEBGL_VERSION")}`,s}function Na(e){return W().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}var ZV=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=fd.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Ca();this.outputShape=e,this.enableShapeUniforms=Na(this.outputShape.length),this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${this.enableShapeUniforms?Oh(["r","c","d"],e):Ao(["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;
}
`}},YV=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=fd.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Ca();this.outputShape=e,this.enableShapeUniforms=Na(this.outputShape.length),this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${this.enableShapeUniforms?Oh(["r","c","d"],e):Ao(["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;
}
`}},JV=class{constructor(e){this.variableNames=["A"],this.outTexUsage=pn.DOWNLOAD;let t=Ca();this.outputShape=e,this.userCode=`
${x6}
void main() {
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
`}},QV=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=pn.DOWNLOAD;let t=Ca();this.outputShape=e,this.userCode=`
${x6}
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
}
`}},eU={R:0,G:1,B:2,A:3},hx=class{constructor(e,t=!1,a="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Ca();this.outputShape=e,this.enableShapeUniforms=Na(this.outputShape.length);let r="result";t&&(r="floor(result * 255. + 0.5)");let s="";for(let i=0;i<a.length;i++){let o=a[i];s+=`
if(offset == ${i}) {
result = values[${eU[o]}];
}`}this.userCode=`
${this.enableShapeUniforms?w3():v3(e)}
void main() {
ivec3 coords = getOutputCoords();
int flatIndex = getFlatIndex(coords);
float result = 0.;
int offset = imod(flatIndex, ${a.length});
flatIndex = idiv(flatIndex, ${a.length}, 1.);
int r = flatIndex / texShape[1];
if (r < texShape[0]) {
int c = imod(flatIndex, texShape[1]);
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
vec4 values = ${n.texture2D}(A, uv);
${s}
}
${n.output} = vec4(${r}, 0., 0., 0.);
}
`}},tU=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let a=Ca();this.outputShape=e,this.enableShapeUniforms=Na(this.outputShape.length);let n="",r="result";t&&(r="floor(result * 255. + 0.5)");for(let s=0;s<=1;s++)for(let i=0;i<=1;i++){let o=s*2+i;n+=`
localCoords = coords;
if(localCoords[2] + ${i} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {
localCoords[2] += ${i};
if (localCoords[1] + ${s} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {
localCoords[1] += ${s};
flatIndex = getFlatIndex(localCoords);
offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
int r = flatIndex / texShape[1];
int c = imod(flatIndex, texShape[1]);
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
values = ${a.texture2D}(A, uv);
if (offset == 0) {
result[${o}] = values[0];
} else if (offset == 1) {
result[${o}] = values[1];
} else if (offset == 2) {
result[${o}] = values[2];
} else {
result[${o}] = values[3];
}
}
}
`}this.userCode=`
${this.enableShapeUniforms?w3():v3(e)}
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
${n}
${a.output} = ${r};
}
`}},w6={};Xe(w6,{bindVertexProgramAttributeStreams:()=>M6,createBufferFromOutputTexture:()=>P6,createFloat16MatrixTexture:()=>C6,createFloat16PackedMatrixTexture:()=>R6,createFloat32MatrixTexture:()=>T6,createIndexBuffer:()=>S6,createPackedMatrixTexture:()=>E6,createUnsignedBytesMatrixTexture:()=>N6,createVertexBuffer:()=>I6,createVertexShader:()=>k6,downloadByteEncodedFloatMatrixFromOutputTexture:()=>O6,downloadFloat32MatrixFromBuffer:()=>F6,downloadMatrixFromPackedOutputTexture:()=>z6,downloadPackedMatrixFromBuffer:()=>D6,getInternalFormatForFloat16MatrixTexture:()=>S3,getInternalFormatForFloat16PackedMatrixTexture:()=>N3,getInternalFormatForFloat32MatrixTexture:()=>I3,getInternalFormatForPackedMatrixTexture:()=>C3,getInternalFormatForUnsignedBytesMatrixTexture:()=>T3,uploadDenseMatrixToTexture:()=>$6,uploadPixelDataToTexture:()=>_6});function k6(e){let t=Ca(),a=`${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 K7(e,a)}function I6(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 Q7(e,t)}function S6(e){let t=new Uint16Array([0,1,2,2,1,3]);return e6(e,t)}function dp(e,t,a,n,r,s){a6(t,a);let i=t6(e),o=e.TEXTURE_2D;return le(e,()=>e.bindTexture(o,i)),le(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),le(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),le(e,()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST)),le(e,()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST)),W().getNumber("WEBGL_VERSION")===1?le(e,()=>e.texImage2D(o,0,n,t,a,0,r,s,null)):le(e,()=>e.texStorage2D(o,1,n,t,a)),le(e,()=>e.bindTexture(e.TEXTURE_2D,null)),{texture:i,texShape:[a,t]}}function I3(e){return e.internalFormatFloat}function T6(e,t,a,n){let[r,s]=up(t,a);return dp(e,r,s,I3(n),n.textureFormatFloat,e.FLOAT)}function S3(e){return e.internalFormatHalfFloat}function C6(e,t,a,n){let[r,s]=up(t,a);return dp(e,r,s,S3(n),n.textureFormatFloat,n.textureTypeHalfFloat)}function T3(e){return e.downloadTextureFormat}function N6(e,t,a,n){let[r,s]=up(t,a);return dp(e,r,s,T3(n),e.RGBA,e.UNSIGNED_BYTE)}function C3(e){return e.internalFormatPackedFloat}function E6(e,t,a,n){let[r,s]=lu(t,a);return dp(e,r,s,C3(n),e.RGBA,e.FLOAT)}function N3(e){return e.internalFormatPackedHalfFloat}function R6(e,t,a,n){let[r,s]=lu(t,a);return dp(e,r,s,N3(n),e.RGBA,n.textureTypeHalfFloat)}function M6(e,t,a){return le(e,()=>e.bindBuffer(e.ARRAY_BUFFER,a)),w1(e,t,"clipSpacePos",a,3,20,0)&&w1(e,t,"uv",a,2,20,12)}function $6(e,t,a,n,r,s){le(e,()=>e.bindTexture(e.TEXTURE_2D,t));let i,o,l;r instanceof Uint8Array?(i=new Uint8Array(a*n*4),o=e.UNSIGNED_BYTE,l=e.RGBA):(i=new Float32Array(a*n*4),o=e.FLOAT,l=s.internalFormatPackedFloat),i.set(r),W().getNumber("WEBGL_VERSION")===2?le(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,a,n,e.RGBA,o,i)):le(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,a,n,0,e.RGBA,o,i)),le(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function _6(e,t,a){le(e,()=>e.bindTexture(e.TEXTURE_2D,t)),a.data instanceof Uint8Array?W().getNumber("WEBGL_VERSION")===2?le(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,a.width,a.height,e.RGBA,e.UNSIGNED_BYTE,a.data)):le(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,a.width,a.height,0,e.RGBA,e.UNSIGNED_BYTE,a.data)):W().getNumber("WEBGL_VERSION")===2?le(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,a)):le(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,a)),le(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function P6(e,t,a,n){let r=e.createBuffer();le(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,r));let s=4*4*t*a;return le(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ)),le(e,()=>e.readPixels(0,0,a,t,e.RGBA,e.FLOAT,0)),le(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),r}function F6(e,t,a){let n=e,r=new Float32Array(a);return n.bindBuffer(n.PIXEL_PACK_BUFFER,t),n.getBufferSubData(n.PIXEL_PACK_BUFFER,0,r),n.bindBuffer(n.PIXEL_PACK_BUFFER,null),r}function O6(e,t,a,n){let[r,s]=up(t,a),i=4,o=new Uint8Array(YW(t*a,i));return le(e,()=>e.readPixels(0,0,r,s,n.downloadTextureFormat,e.UNSIGNED_BYTE,o)),new Float32Array(o.buffer)}function D6(e,t,a,n,r,s,i,o){let l=e,u=new Float32Array(JW(s,i));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}function z6(e,t,a){let n=new Float32Array(t*a*4);return le(e,()=>e.readPixels(0,0,a,t,e.RGBA,e.FLOAT,n)),n}var il=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];let t=W().getNumber("WEBGL_VERSION");if(e!=null?(this.gl=e,Fh(t,e)):this.gl=Dn(t),e=this.gl,W().getNumber("WEBGL_VERSION")===2){let r=e;this.createVertexArray=()=>le(r,()=>r.createVertexArray()),this.bindVertexArray=s=>le(r,()=>r.bindVertexArray(s)),this.deleteVertexArray=s=>le(r,()=>r.deleteVertexArray(s)),this.getVertexArray=()=>le(r,()=>r.getParameter(r.VERTEX_ARRAY_BINDING))}else if(e!=null){let r=e.getExtension("OES_vertex_array_object");if(r==null)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>le(e,()=>r.createVertexArrayOES()),this.bindVertexArray=s=>le(e,()=>r.bindVertexArrayOES(s)),this.deleteVertexArray=s=>le(e,()=>r.deleteVertexArrayOES(s)),this.getVertexArray=()=>le(e,()=>e.getParameter(r.VERTEX_ARRAY_BINDING_OES))}let a="WEBGL_color_buffer_float",n="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),W().getNumber("WEBGL_VERSION")===1){let r="OES_texture_float",s="OES_texture_half_float";if(this.textureFloatExtension=qu(this.gl,r),cn(this.gl,s))this.textureHalfFloatExtension=qu(this.gl,s);else if(W().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(a),cn(this.gl,n))this.colorBufferHalfFloatExtension=qu(this.gl,n);else if(W().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(a="EXT_color_buffer_float",cn(this.gl,a))this.colorBufferFloatExtension=this.gl.getExtension(a);else if(cn(this.gl,n))this.colorBufferHalfFloatExtension=this.gl.getExtension(n);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=I6(this.gl),this.indexBuffer=S6(this.gl),this.framebuffer=n6(this.gl),this.textureConfig=y3(this.gl,this.textureHalfFloatExtension)}get debug(){return W().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;le(e,()=>e.finish()),le(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),le(e,()=>e.deleteFramebuffer(this.framebuffer)),le(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),le(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),le(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),T6(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),C6(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),N6(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),_6(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,a,n){this.throwIfDisposed(),$6(this.gl,e,t,a,n,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),R6(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),E6(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(k1(this.gl,this.framebuffer),this.outputTexture=null),le(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,a){return this.downloadMatrixDriver(e,()=>O6(this.gl,t,a,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,a,n,r,s){return D6(this.gl,e,t,a,n,r,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return F6(this.gl,e,t)}createBufferFromTexture(e,t,a){this.bindTextureToFrameBuffer(e);let n=P6(this.gl,t,a,this.textureConfig);return this.unbindTextureToFrameBuffer(),n}createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,a;if(W().getBool("WEBGL_FENCE_API_ENABLED")){let n=e,r=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),a=()=>{let s=n.clientWaitSync(r,0,0);return s===n.ALREADY_SIGNALED||s===n.CONDITION_SATISFIED},t=r}else W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),a=()=>this.isQueryAvailable(t,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):a=()=>!0;return{query:t,isFencePassed:a}}downloadMatrixFromPackedTexture(e,t,a){return this.downloadMatrixDriver(e,()=>z6(this.gl,t,a))}createProgram(e){this.throwIfDisposed();let t=this.gl;this.vertexShader==null&&(this.vertexShader=k6(t));let a=Y7(t);le(t,()=>t.attachShader(a,this.vertexShader)),le(t,()=>t.attachShader(a,e)),J7(t,a);let n;return n=Object.assign(a,{vao:this.createVertexArray()}),this.bindVertexArray(n.vao),le(t,()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer)),console.assert(M6(t,n,this.vertexBuffer),"gpgpu_util.bindVertexProgramAttributeStreams not fully successful."),this.debug&&gc(t,n),this.setProgram(n),n}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&(le(this.gl,()=>this.gl.deleteProgram(e)),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&(this.bindVertexArray(this.program.vao),this.debug&&gc(this.gl,this.program)),le(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,a=!0){return this.throwIfDisposed(),a?s6(this.gl,e,t):i6(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),le(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,a){this.throwIfDisposed(),this.throwIfNoProgram(),o6(this.gl,e,t,a)}setOutputMatrixTexture(e,t,a){this.setOutputMatrixTextureDriver(e,a,t)}setOutputPackedMatrixTexture(e,t,a){this.throwIfDisposed();let[n,r]=lu(t,a);this.setOutputMatrixTextureDriver(e,n,r)}setOutputMatrixWriteRegion(e,t,a,n){this.setOutputMatrixWriteRegionDriver(a,e,n,t)}setOutputPackedMatrixWriteRegion(e,t,a,n){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&gc(this.gl,this.program),Xu(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;if(this.debug){let t=this.getVertexArray();console.assert(t===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}le(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),le(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=qu(this.gl,W().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(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let a=this.gl,n=this.getQueryTimerExtensionWebGL2(),r=a.createQuery();return a.beginQuery(n.TIME_ELAPSED_EXT,r),r}let e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let t=this.gl,a=this.getQueryTimerExtensionWebGL2();t.endQuery(a.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,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){let a=this.gl;return a.getQueryParameter(e,a.QUERY_RESULT)/1e6}else{let a=this.getQueryTimerExtensionWebGL1();return a.getQueryObjectEXT(e,a.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){let a=this.gl,n=this.getQueryTimerExtensionWebGL2(),r=a.getQueryParameter(e,a.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),r&&!this.disjoint}else{let a=this.getQueryTimerExtensionWebGL1(),n=a.getQueryObjectEXT(e,a.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(a.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=aU(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){let{resolveFn:a}=this.itemsToPoll[t];a()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;let a;"setTimeoutCustom"in W().platform&&(a=W().platform.setTimeoutCustom.bind(W().platform)),v.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0),()=>0,null,a)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),xc(this.gl,e,this.framebuffer),this.debug&&Xu(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(xc(this.gl,this.outputTexture,this.framebuffer),this.debug&&Xu(this.gl)):k1(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);let a=t();return this.unbindTextureToFrameBuffer(),a}setOutputMatrixTextureDriver(e,t,a){this.throwIfDisposed();let n=this.gl;xc(n,e,this.framebuffer),this.debug&&Xu(n),this.outputTexture=e,le(n,()=>n.viewport(0,0,t,a)),le(n,()=>n.scissor(0,0,t,a))}setOutputMatrixWriteRegionDriver(e,t,a,n){this.throwIfDisposed(),le(this.gl,()=>this.gl.scissor(e,t,a,n))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}};function aU(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}var{addImpl:nU,bincountImpl:L6,bincountReduceImpl:rU,castImpl:sU,ceilImpl:iU,concatImpl:oU,equalImpl:lU,expImpl:uU,expm1Impl:dU,floorImpl:pU,gatherNdImpl:cU,gatherV2Impl:hU,greaterImpl:fU,greaterEqualImpl:mU,lessImpl:gU,lessEqualImpl:xU,linSpaceImpl:AU,logImpl:yU,maxImpl:bU,maximumImpl:vU,minimumImpl:wU,multiplyImpl:kU,negImpl:IU,notEqualImpl:SU,prodImpl:TU,raggedGatherImpl:CU,raggedRangeImpl:NU,raggedTensorToTensorImpl:EU,rangeImpl:RU,rsqrtImpl:MU,scatterImpl:$U,sigmoidImpl:_U,simpleAbsImpl:B6,sliceImpl:PU,sparseFillEmptyRowsImpl:FU,sparseReshapeImpl:OU,sparseSegmentReductionImpl:W6,sqrtImpl:DU,stridedSliceImpl:zU,stringNGramsImpl:LU,stringSplitImpl:BU,stringToHashBucketFastImpl:WU,subImpl:VU,tileImpl:UU,topKImpl:GU,transposeImpl:E3,uniqueImpl:HU}=_h;function V6(e,t){return["x","y","z","w","u","v"].slice(0,t).map(a=>`${e}.${a}`)}function va(e,t){return t===1?[e]:V6(e,t)}function jU(e,t){if(e===1)return"rc";let a="";for(let n=0;n<e;n++)a+=t[n],n<e-1&&(a+=",");return a}var qU=class{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=Na(this.outputShape.length),this.rank===0)this.userCode=`
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
`;else{let t=va("rc",this.rank),a=gt(this.rank),n=this.getOutOfBoundsCondition(t),r=this.getSetup(t),s=this.getOutput(t);this.userCode=`
void main() {
${a} rc = getOutputCoords();
if(${n}) {
setOutput(vec4(0));
} else {
${r}
setOutput(vec4(${s}));
}
}
`}}getSourceCoordsArr(e){let t=[];for(let a=0;a<=1;a++)for(let n=0;n<=1;n++){let r=`${a===0?"r":"rp1"}, ${n===0?"c":"cp1"}`;for(let s=2;s<this.rank;s++)r=`${e[e.length-1-s]},`+r;t.push(r)}return t}getOutOfBoundsCondition(e){if(this.rank===1)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let a=this.rank-2;a<this.rank;a++)t+=`${e[a]} >= ${this.enableShapeUniforms?`outShape[${a}]`:this.outputShape[a]}`,a<this.rank-1&&(t+="||");return t}getSetup(e){if(this.rank===1)return"";let t=e.slice(-2),a=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],n=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`
int r = ${t[0]};
int c = ${t[1]};
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${a};
bool rEdge = rp1 >= ${n};
`}getOutput(e){let t=this.getSourceCoordsArr(e);return this.rank===1?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${t[0]}),
cEdge ? 0. : getA(${t[1]}),
rEdge ? 0. : getA(${t[2]}),
rEdge || cEdge ? 0. : getA(${t[3]})`}},U6=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=Na(this.outputShape.length);let a="";for(let n=0;n<4;n++){let r="thisRC = rc;";n%2===1&&(r+="thisRC.z += 1;"),n>1&&(r+="thisRC.y += 1;"),a+=`
${r}
${n>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
int flatIndex = getFlatIndex(thisRC);
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
result[${n}] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
${n>0?"}":""}
`}this.userCode=`
${XU(t,this.enableShapeUniforms)}
${this.enableShapeUniforms?w3():v3(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]};
${a}
setOutput(result);
}
`}};function XU(e,t){return`
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t?dV(["r","c","d"],"inputShape"):Ao(["r","c","d"],e)}
return ivec3(r, c, d);
}
`}var KU=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,a){let n=mx(t,a),r=gx(e,n,a);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);let s=fx(e,n,this.gpgpu.gl,this.gpgpu.textureConfig,a);if(this.freeTextures[r].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();let o=this.freeTextures[r].shift();return this.usedTextures[r].push(o),o}let i;return n===na.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):n===na.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):n===na.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):n===na.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):n===na.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[r].push(i),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),i}releaseTexture(e,t,a,n){if(this.freeTextures==null)return;let r=mx(a,n),s=gx(t,r,n);s in this.freeTextures||(this.freeTextures[s]=[]);let i=fx(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,n),o=W().get("WEBGL_DELETE_TEXTURE_THRESHOLD");o!==-1&&this._numBytesAllocated>o?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=i):(this.freeTextures[s].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;let l=this.usedTextures[s],u=l.indexOf(e);if(u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(u,1),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);let t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function ZU(e,t){let a=e;if(t===a.R32F)return 4;if(t===a.R16F)return 2;if(t===a.RGBA32F||t===e.RGBA)return 16;if(t===a.RGBA16F)return 8;if(t===a.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}function fx(e,t,a,n,r){let s=YU(t,n),i;if(r){let[l,u]=lu(e[0],e[1]);i=l*u}else{let[l,u]=up(e[0],e[1]);i=l*u}let o=ZU(a,s);return i*o}function YU(e,t){switch(e){case na.PACKED_2X2_FLOAT32:return C3(t);case na.PACKED_2X2_FLOAT16:return N3(t);case na.UNPACKED_FLOAT32:return I3(t);case na.UNPACKED_FLOAT16:return S3(t);case na.PACKED_4X1_UNSIGNED_BYTE:return T3(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function JU(e){return W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?na.PACKED_2X2_FLOAT32:na.UNPACKED_FLOAT32:e?na.PACKED_2X2_FLOAT16:na.UNPACKED_FLOAT16}function mx(e,t){if(e===pn.UPLOAD)return na.PACKED_2X2_FLOAT32;if(e===pn.RENDER||e==null)return JU(t);if(e===pn.DOWNLOAD||e===pn.PIXELS)return na.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function gx(e,t,a){return`${e[0]}_${e[1]}_${t}_${a}`}var qn=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=Na(this.outputShape.length),this.userCode=`
float unaryOperation(float x) {
${t}
}
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
`}},Cn="if (isnan(x)) return x;",QU="return x;",xx="return abs(x);",eG="return (x >= 0.0) ? x : (exp(x) - 1.0);",tG=Cn+`
return (x < 0.0) ? 0.0 : x;
`,aG=Cn+`
return (x < 0.0) ? 0.0 : min(6.0, x);
`,Dr="return x;",nG="return 1.0 / (1.0 + exp(-1.0 * x));",rG="return x;",sG=`
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;
`,iG=`
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;
`,oG=`
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;
`,lG="return 1.0 / (1.0 + exp(-1.0 * x));",Vr=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=Na(this.outputShape.length),this.userCode=`
vec4 unaryOperation(vec4 x) {
${t}
}
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
}
`}},uG=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=Na(this.outputShape.length);let t=e.length,a=va("rc",t),n=gt(t),r=jU(t,a),s=a.slice(-2),i=t<=1?"rc":`vec2(${s.join(",")})`;this.userCode=`
void main() {
${n} rc = getOutputCoords();
vec4 packedInput = getA(${r});
setOutput(getChannel(packedInput, ${i}));
}
`}},dG=Tn.whereImpl,pG=1e-7,cG=1e-4,zm={};function hG(e){return e in zm||(zm[e]={}),zm[e]}var fG=W().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),mG=600;function gG(){return W().global.screen==null?1024:W().global.screen.height*W().global.screen.width*window.devicePixelRatio*mG/1024/1024}var fu=class extends bl{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,!W().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(e!=null){if(e instanceof il)t=e;else{let a=Dn(W().getNumber("WEBGL_VERSION"),e);t=new il(a)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{let a=Dn(W().getNumber("WEBGL_VERSION"));t=new il(a),this.binaryCache=hG(W().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new KU(this.gpgpu),this.numMBBeforeWarning=gG(),this.texData=new vd(this,kt())}nextDataId(){return fu.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(e,t,a,n,r,s){let i=this.makeTensorInfo(t,a),o=this.texData.get(i.dataId);o.isPacked=!1,o.texture={texture:e,texShape:[n,r]},o.texShape=[n,r];let l=Ku(t),u=new hx(l,!1,s),p=this.runWebGLProgram(u,[i],a,[[n,r]]);return p.shape=t,o.texture=null,this.disposeIntermediateTensorInfo(i),p.dataId}write(e,t,a){if((W().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||W().getBool("DEBUG"))&&this.checkNumericalProblems(e),a==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let n={id:this.nextDataId()};return this.texData.set(n,{shape:t,dtype:a,values:e,usage:pn.UPLOAD,refCount:1}),n}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,a,n,r){if(W().getBool("DEBUG")&&this.checkNumericalProblems(t),n==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:a,dtype:n,values:t,usage:pn.UPLOAD,refCount:r})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){let t=this.texData.get(e),{values:a,dtype:n,complexTensorInfos:r,slice:s,shape:i,isPacked:o}=t;if(s!=null){let c;o?c=new Vr(i,Dr):c=new qn(i,Dr);let d=this.runWebGLProgram(c,[{dataId:e,shape:i,dtype:n}],n),h=this.readSync(d.dataId);return this.disposeIntermediateTensorInfo(d),h}if(a!=null)return this.convertAndCacheOnCPU(e);if(n==="string")return a;let l=this.activeTimers!=null,u;l&&(u=v.now());let p;if(n==="complex64"){let c=this.readSync(r.real.dataId),d=this.readSync(r.imag.dataId);p=T.mergeRealAndImagArrays(c,d)}else p=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=v.now()-u),this.convertAndCacheOnCPU(e,p)}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:a,shape:n,slice:r,dtype:s,complexTensorInfos:i,isPacked:o}=t;if(r!=null){let h;o?h=new Vr(n,Dr):h=new qn(n,Dr);let f=this.runWebGLProgram(h,[{dataId:e,shape:n,dtype:s}],s),m=this.read(f.dataId);return this.disposeIntermediateTensorInfo(f),m}if(a!=null)return this.convertAndCacheOnCPU(e);if(W().getBool("DEBUG")&&!W().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&W().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l=null,u;if(s!=="complex64"&&W().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);let h=this.texData.get(u.dataId);l=this.gpgpu.createBufferFromTexture(h.texture.texture,...uc(n))}this.pendingRead.set(e,[]),s!=="complex64"&&await this.gpgpu.createAndWaitForFence();let p;if(s==="complex64"){let h=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]),f=h[0],m=h[1];p=T.mergeRealAndImagArrays(f,m)}else if(l==null)p=this.getValuesFromTexture(e);else{let h=v.sizeFromShape(n);p=this.gpgpu.downloadFloat32MatrixFromBuffer(l,h)}if(u!=null&&this.disposeIntermediateTensorInfo(u),l!=null){let h=this.gpgpu.gl;le(h,()=>h.deleteBuffer(l))}let c=this.convertAndCacheOnCPU(e,p),d=this.pendingRead.get(e);return this.pendingRead.delete(e),d.forEach(h=>h(c)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&kt().removeDataId(e,this),this.pendingDeletes--),c}readToGPU(e,t={}){let a=this.texData.get(e),{values:n,shape:r,slice:s,dtype:i,isPacked:o,texture:l}=a;if(i==="complex64")throw new Error("Does not support reading texture for complex64 dtype.");if(s!=null){let d;o?d=new Vr(r,Dr):d=new qn(r,Dr);let h=this.runWebGLProgram(d,[{dataId:e,shape:r,dtype:i}],i),f=this.readToGPU(h,t);return this.disposeIntermediateTensorInfo(h),f}if(l==null)throw n!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");let u=this.decode(e,t.customTexShape),p=kt().makeTensorFromTensorInfo(u),c=this.texData.get(u.dataId);return Object.assign({tensorRef:p},c.texture)}bufferSync(e){let t=this.readSync(e.dataId);if(e.dtype==="string")try{let a=t.map(n=>v.decodeString(n));return Me(e.shape,e.dtype,a)}catch(a){throw new Error("Failed to decode encoded string bytes into utf-8")}return Me(e.shape,e.dtype,t)}checkNumericalProblems(e){if(e!=null)for(let t=0;t<e.length;t++){let a=e[t];if(!q7(a))throw W().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${a} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${a} cannot be represented on this device.`)}}getValuesFromTexture(e){let{shape:t,dtype:a,isPacked:n}=this.texData.get(e),r=v.sizeFromShape(t);if(W().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let c=this.decode(e),d=this.texData.get(c.dataId),h=this.gpgpu.downloadMatrixFromPackedTexture(d.texture.texture,...uc(t)).subarray(0,r);return this.disposeIntermediateTensorInfo(c),h}let s=W().getBool("WEBGL_PACK")&&n===!0,i=s?Ku(t):t,o=s?new QV(i):new JV(i),l=this.runWebGLProgram(o,[{shape:i,dtype:a,dataId:e}],"float32"),u=this.texData.get(l.dataId),p=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(u.texture.texture,u.texShape[0],u.texShape[1]).subarray(0,r);return this.disposeIntermediateTensorInfo(l),p}timerAvailable(){return W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(e){let t=this.activeTimers,a=[],n=!1;this.programTimersStack==null?(this.programTimersStack=a,n=!0):this.activeTimers.push(a),this.activeTimers=a,e();let r=v.flatten(this.activeTimers.map(o=>o.query)).filter(o=>o!=null),s=v.flatten(this.activeTimers.map(o=>o.name)).filter(o=>o!=null);this.activeTimers=t,n&&(this.programTimersStack=null);let i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let o=await Promise.all(r);i.kernelMs=v.sum(o),i.getExtraProfileInfo=()=>o.map((l,u)=>({name:s[u],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:v.now(),endMs:null}}endTimer(e){return W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=v.now(),e)}async getQueryTime(e){if(W().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:a}=this.texData.get(e);return a!=null&&(this.disposeData(a.real.dataId,t),this.disposeData(a.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){let{texture:t,dtype:a,texShape:n,usage:r,isPacked:s,slice:i}=this.texData.get(e),o=i&&i.origDataId||e,l=this.dataRefCount.get(o);l>1?this.dataRefCount.set(o,l-1):(this.dataRefCount.delete(o),t!=null&&(this.numBytesInGPU-=this.computeBytes(n,a),this.textureManager.releaseTexture(t,n,r,s)));let u=this.texData.get(e);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=fG){return W().getBool("WEBGL_CPU_FORWARD")&&e.every(a=>this.texData.get(a.dataId).texture==null&&v.sizeFromShape(a.shape)<t)}getGPGPUContext(){return this.gpgpu}where(e){T.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let t=e.dataSync();return dG(e.shape,t)}packedUnaryOp(e,t,a){let n=new Vr(e.shape,t),r=this.compileAndRun(n,[e],a);return kt().makeTensorFromTensorInfo(r)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){let n=B6(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,n)}if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,xx,e.dtype);let t=new qn(e.shape,xx),a=this.compileAndRun(t,[e]);return kt().makeTensorFromTensorInfo(a)}makeTensorInfo(e,t,a){let n;if(t==="string"&&a!=null&&a.length>0&&v.isString(a[0])){let r=a.map(s=>v.encodeString(s));n=this.write(r,e,t)}else n=this.write(a,e,t);return this.texData.get(n).usage=null,{dataId:n,shape:e,dtype:t}}makeOutput(e,t,a){return kt().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,a),this)}unpackTensor(e){let t=new uG(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new qU(e.shape),a=!0;return this.runWebGLProgram(t,[e],e.dtype,null,a)}packedReshape(e,t){let a=[Hs(e.shape),...js(e.shape)],n={dtype:e.dtype,shape:a,dataId:e.dataId},r=[Hs(t),...js(t)],s=new U6(r,a),i=!0,o=[a],l=this.runWebGLProgram(s,[n],e.dtype,o,i);return{dataId:l.dataId,shape:t,dtype:l.dtype}}decode(e,t){let a=this.texData.get(e),{isPacked:n,shape:r,dtype:s}=a;if(t!=null){let c=v.sizeFromShape(r),d=t[0]*t[1]*4;v.assert(c<=d,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.")}let i=Ku(r),o;n?o=new YV(i):o=new ZV(i);let l=!0,u=[t!=null?t:uc(i)],p=this.runWebGLProgram(o,[{shape:i,dtype:s,dataId:e}],s,u,l,t);return{dtype:s,shape:r,dataId:p.dataId}}runWebGLProgram(e,t,a,n,r=!1,s){let i=this.makeTensorInfo(e.outputShape,a),o=this.texData.get(i.dataId);if(e.packedOutput&&(o.isPacked=!0),e.outPackingScheme===fd.DENSE){let g=s!=null?s:uc(e.outputShape);o.texShape=g.map(x=>x*2)}if(e.outTexUsage!=null&&(o.usage=e.outTexUsage),v.sizeFromShape(i.shape)===0)return o.values=v.getTypedArrayFromDType(i.dtype,0),i;let l=[],u=t.map(g=>{if(g.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let x=this.texData.get(g.dataId);if(x.texture==null){if(!e.packedInputs&&v.sizeFromShape(g.shape)<=W().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:g.shape,texData:null,isUniform:!0,uniformValues:x.values};e.packedInputs&&(x.isPacked=!0,x.shape=g.shape)}if(this.uploadToGPU(g.dataId),!!x.isPacked!=!!e.packedInputs)g=x.isPacked?this.unpackTensor(g):this.packTensor(g),l.push(g),x=this.texData.get(g.dataId);else if(x.isPacked&&!md(x.shape,g.shape)){let A=g,y=g.shape;g.shape=x.shape,g=this.packedReshape(g,y),l.push(g),x=this.texData.get(g.dataId),A.shape=y}return{shape:g.shape,texData:x,isUniform:!1}});this.uploadToGPU(i.dataId);let p={shape:i.shape,texData:o,isUniform:!1},c=KV(e,u,p),d=this.getAndSaveBinary(c,()=>qV(this.gpgpu,e,u,p)),h=this.activeTimers!=null,f;h&&(f=this.startTimer()),W().get("ENGINE_COMPILE_ONLY")||XV(this.gpgpu,d,u,p,n),l.forEach(g=>this.disposeIntermediateTensorInfo(g)),h&&(f=this.endTimer(f),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(f)}));let m=W().get("WEBGL_FLUSH_THRESHOLD");if(m>0){let g=v.now();g-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=g)}if(!W().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&r===!1){let g=this.unpackTensor(i);return this.disposeIntermediateTensorInfo(i),g}return i}compileAndRun(e,t,a,n,r=!1){return a=a||t[0].dtype,this.runWebGLProgram(e,t,a,n,r)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(W().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=$e(()=>{if(!W().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=W().getBool("DEBUG");W().set("DEBUG",!1);let t=this.abs(Fe(1e-8)).dataSync()[0];if(W().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?pG:cG}uploadToGPU(e){let t=this.texData.get(e),{shape:a,dtype:n,values:r,texture:s,usage:i,isPacked:o}=t;if(s!=null)return;let l=this.activeTimers!=null,u;l&&(u=v.now());let p=t.texShape;if(p==null&&(p=d6(a,o),t.texShape=p),r!=null){let c=Ku(a),d,h=p[1],f=p[0],m=r instanceof Uint8Array||r instanceof Uint8ClampedArray;(o||!m)&&([h,f]=lu(p[0],p[1])),o?d=new tU(c,m):d=new hx(c,m);let g=m?[f,h]:p,x=this.makeTensorInfo(g,n),A=this.texData.get(x.dataId);m?A.usage=pn.PIXELS:A.usage=pn.UPLOAD,A.texShape=g,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(x.dataId),h,f,r);let y=[[f,h]],b=!0,w=this.runWebGLProgram(d,[x],n,y,b),S=this.texData.get(w.dataId);t.texShape=S.texShape,t.isPacked=S.isPacked,t.usage=S.usage,W().get("ENGINE_COMPILE_ONLY")?this.disposeData(w.dataId):(t.texture=S.texture,t.values=null,this.texData.delete(w.dataId)),this.disposeIntermediateTensorInfo(x),l&&(this.uploadWaitMs+=v.now()-u)}else{let c=this.acquireTexture(p,i,n,o);t.texture=c}}convertAndCacheOnCPU(e,t){let a=this.texData.get(e),{dtype:n}=a;return t!=null&&(a.values=xG(t,n)),a.values}acquireTexture(e,t,a,n){if(this.numBytesInGPU+=this.computeBytes(e,a),!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,n)}computeBytes(e,t){return e[0]*e[1]*v.bytesPerElement(t)}checkCompileCompletion(){for(let[,e]of Object.entries(this.binaryCache))this.checkCompletion_(e)}async checkCompileCompletionAsync(){let e=[];if(this.gpgpu.parallelCompilationExtension){for(let[,t]of Object.entries(this.binaryCache))e.push(this.checkCompletionAsync_(t));return Promise.all(e)}else{for(let[,t]of Object.entries(this.binaryCache)){let a=new Promise(n=>{try{this.checkCompletion_(t),n(!0)}catch(r){throw r}});e.push(a)}return Promise.all(e)}}async checkCompletionAsync_(e){return this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(e):(await b4(),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?(b3(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:a,infLoc:n,nanLoc:r,inShapesLocations:s,inTexShapesLocations:i,outShapeLocation:o,outShapeStridesLocation:l,outTexShapeLocation:u}=v6(this.gpgpu,e.program,e.webGLProgram);e.uniformLocations=t,e.customUniformLocations=a,e.infLoc=n,e.nanLoc=r,e.inShapesLocations=s,e.inTexShapesLocations=i,e.outShapeLocation=o,e.outShapeStridesLocation=l,e.outTexShapeLocation=u}}createTensorFromTexture(e,t,a){let{texture:n,height:r,width:s,channels:i}=e,o=kt().backend;if(!o.gpgpu.gl.isTexture(n))throw new Error("The texture is invalid. Also, please make sure the texture and the TFJS WebGL backend are using the same canvas. If you want to use your own custom canvas, you have to create and use the custom TFJS WebGL backend created from the canvas through 'new tf.MathBackendWebGL(customCanvas)'.");let l=o.writeTexture(n,t,a,r,s,i);return kt().makeTensorFromDataId(l,t,a,o)}};fu.nextDataId=0;function xG(e,t){if(t==="float32"||t==="complex64")return e;if(t==="int32"||t==="bool"){let a=t==="int32"?new Int32Array(e.length):new Uint8Array(e.length);for(let n=0;n<a.length;++n)a[n]=Math.round(e[n]);return a}else throw new Error(`Unknown dtype ${t}`)}var AG="4.1.0";function G6(){W().set("WEBGL_FORCE_F16_TEXTURES",!0)}jd.isBrowser()&&go("webgl",()=>new fu,2);var yG={forceHalfFloat:G6},R3=`
if (isnan(a)) return a;
if (isnan(b)) return b;
`,Al=class{constructor(e,t,a){this.variableNames=["A","B"],this.outputShape=T.assertAndGetBroadcastShape(t,a),this.enableShapeUniforms=Na(this.outputShape.length),this.userCode=`
float binaryOperation(float a, float b) {
${e}
}
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
`}},pp=`
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;
`,cp=class{constructor(e,t,a,n=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=T.assertAndGetBroadcastShape(t,a);let r=this.outputShape.length;this.enableShapeUniforms=Na(r);let s="";if(n)if(r===0||v.sizeFromShape(this.outputShape)===1)s=`
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;else if(s=`
${gt(r)} coords = getOutputCoords();
`,r===1)this.enableShapeUniforms?s+=`
result.y = (coords + 1) >= outShape ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`:s+=`
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`;else{let i=va("coords",r);this.enableShapeUniforms?s+=`
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;
`:s+=`
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);
${s}
setOutput(result);
}
`}};function Za(e){let{inputs:t,backend:a}=e,{x:n}=t;return a.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}var bG={kernelName:ki,backendName:"webgl",kernelFunc:Za};function ls(e){let{inputs:t,backend:a}=e,{real:n,imag:r}=t,s=a.makeTensorInfo(n.shape,"complex64"),i=a.texData.get(s.dataId),o=Za({inputs:{x:n},backend:a}),l=Za({inputs:{x:r},backend:a});return i.complexTensorInfos={real:o,imag:l},s}var vG={kernelName:Sd,backendName:"webgl",kernelFunc:ls},H6="return (a < 0.) ? b * a : a;",j6=`
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;function wG(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{alpha:s}=n,i=a.makeTensorInfo([],"float32",v.createScalarValue(s,"float32")),o=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new cp(j6,r.shape,i.shape):new Al(H6,r.shape,i.shape),l=a.runWebGLProgram(o,[r,i],"float32");return a.disposeIntermediateTensorInfo(i),l}var kG={kernelName:Si,backendName:"webgl",kernelFunc:wG},q6="return (a < 0.) ? b * a : a;",X6=`
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;function IG(e){let{inputs:t,backend:a}=e,{x:n,alpha:r}=t,s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new cp(X6,n.shape,r.shape):new Al(q6,n.shape,r.shape);return a.runWebGLProgram(s,[n,r],"float32")}var SG={kernelName:Hi,backendName:"webgl",kernelFunc:IG},mu="if (isnan(x)) return x;";function Qe({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:a,dtype:n}){return({inputs:r,backend:s})=>{let{x:i}=r,o=s,l=n||i.dtype;if(o.shouldExecuteOnCPU([i])&&a!=null){let c=o.texData.get(i.dataId),d=a(c.values,l);return o.makeTensorInfo(i.shape,l,d)}let u=W().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,p;return u?p=new Vr(i.shape,t):p=new qn(i.shape,e),o.runWebGLProgram(p,[i],l)}}function oa({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:a=!1,supportsComplex:n=!1,cpuKernelImpl:r,dtype:s}){return({inputs:i,backend:o})=>{let{a:l,b:u}=i,p=o;if(n&&l.dtype==="complex64"){let f=p.texData.get(l.dataId),m=p.texData.get(u.dataId),[g,x]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(y=>{let[b,w]=y,S={dataId:b.dataId,dtype:b.dtype,shape:l.shape},C={dataId:w.dataId,dtype:w.dtype,shape:u.shape},E=new Al(e,l.shape,u.shape);return p.runWebGLProgram(E,[S,C],ca(b.dtype,w.dtype))}),A=ls({inputs:{real:g,imag:x},backend:p});return p.disposeIntermediateTensorInfo(g),p.disposeIntermediateTensorInfo(x),A}let c=s||ca(l.dtype,u.dtype);if((l.dtype==="string"||u.dtype==="string"||p.shouldExecuteOnCPU([l,u]))&&r!=null){let f=p.texData.get(l.dataId).values,m=p.texData.get(u.dataId).values,g=l.dtype==="string"?T.fromUint8ToStringArray(f):f,x=l.dtype==="string"?T.fromUint8ToStringArray(m):m,[A,y]=r(l.shape,u.shape,g,x,c),b=p.makeTensorInfo(y,c),w=p.texData.get(b.dataId);return w.values=A,b}let d=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return d?h=new cp(t,l.shape,u.shape,a):h=new Al(e,l.shape,u.shape),p.runWebGLProgram(h,[l,u],c)}}function gd(e,t=!1){if(e==="linear")return t?rG:QU;if(e==="relu")return t?iG:tG;if(e==="elu")return t?sG:eG;if(e==="relu6")return t?oG:aG;if(e==="prelu")return t?X6:q6;if(e==="leakyrelu")return t?j6:H6;if(e==="sigmoid")return t?lG:nG;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var K6=class{constructor(e,t,a,n=!1,r=!1,s=!1,i=null,o=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=a,this.enableShapeUniforms=Na(this.outputShape.length);let u=n?e[1]:e[2],p=Math.ceil(u/2),c=n?"i * 2, rc.y":"rc.y, i * 2",d=r?"rc.z, i * 2":"i * 2, rc.z",h=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],m="",g="";i&&(o?m=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${i}
}`:l?m=`vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${i}
}`:m=`vec4 activation(vec4 x) {
${i}
}`,g="result = activation(result);");let x=s?"result += getBiasAtOutCoords();":"";s&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let A="rc.x",y="rc.x";e[0]<t[0]?A=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(y=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`
${m}
// Don't use uniform for sharedDimensionPacked for performance.
const float sharedDimension = ${p}.0;
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
for (int i = 0; i < ${p}; i++) {
int batchA = ${A};
int batchB = ${y};
vec4 a = getMatrixA(batchA, ${c});
vec4 b = getMatrixB(batchB, ${d});
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${h[0]} * ${f[0]});
result += (${h[1]} * ${f[1]});
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
${x}
${g}
setOutput(result);
}
`}},Ax={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},yx=class{constructor(e,t,a){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=T.assertAndGetBroadcastShape(t,a),this.userCode=`
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${e}
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
`}},bx="return a * b;";function M3(e){let{inputs:t,backend:a}=e,{a:n,b:r}=t,s=T.upcastType(n.dtype,r.dtype);if(n.dtype==="complex64"){let o=a.texData.get(n.dataId),l=a.texData.get(r.dataId),u=new yx(Ax.REAL,n.shape,r.shape),p=new yx(Ax.IMAG,n.shape,r.shape),c=[{dataId:o.complexTensorInfos.real.dataId,dtype:o.complexTensorInfos.real.dtype,shape:n.shape},{dataId:o.complexTensorInfos.imag.dataId,dtype:o.complexTensorInfos.imag.dtype,shape:n.shape},{dataId:l.complexTensorInfos.real.dataId,dtype:l.complexTensorInfos.real.dtype,shape:r.shape},{dataId:l.complexTensorInfos.imag.dataId,dtype:l.complexTensorInfos.imag.dtype,shape:r.shape}],d=a.runWebGLProgram(u,c,"float32"),h=a.runWebGLProgram(p,c,"float32"),f=ls({inputs:{real:d,imag:h},backend:a});return a.disposeIntermediateTensorInfo(d),a.disposeIntermediateTensorInfo(h),f}if(a.shouldExecuteOnCPU([n,r])){let o=a.texData.get(n.dataId),l=a.texData.get(r.dataId),[u,p]=kU(n.shape,r.shape,o.values,l.values,s),c=a.makeTensorInfo(p,s),d=a.texData.get(c.dataId);return d.values=u,c}let i;return W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?i=new cp(bx,n.shape,r.shape):i=new Al(bx,n.shape,r.shape),a.runWebGLProgram(i,[n,r],s)}var TG={kernelName:zi,backendName:"webgl",kernelFunc:M3};function CG(e,t,a){let n=[Hs(e.shape),...js(e.shape)],r={dtype:e.dtype,shape:n,dataId:e.dataId},s=[Hs(t),...js(t)],i=new U6(s,n),o=!0,l=[n],u=a.runWebGLProgram(i,[r],e.dtype,l,o);return{dataId:u.dataId,shape:t,dtype:u.dtype}}function ce(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{shape:s}=n,i=a,o=v.sizeFromShape(r.shape),l=v.inferFromImplicitShape(s,o),u=v.sizeFromShape(l);v.assert(o===u,()=>`The new shape (${l}) has ${u} elements and the old shape (${r.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`);let p=i.texData.get(r.dataId);return p.isPacked&&!md(r.shape,l)&&!(p.texture!==null&&md(p.shape,l))?CG(r,l,i):(i.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype})}var NG={kernelName:ql,backendName:"webgl",kernelFunc:ce},vx=class{constructor(e,t){this.variableNames=["x"];let{windowSize:a,batchSize:n,inSize:r,outSize:s}=e;this.outputShape=[n,s];let i=Math.floor(a/4)*4,o=a%4,l="sumValue += dot(values, ones);";if(t!=null){let p=1/t;l=`sumValue += dot(values * ${v.isInt(p)?p.toPrecision(2):p}, ones);`}let u="";r%a>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 * ${a};
float sumValue = 0.0;
for (int i = 0; i < ${i}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${l}
}
int inIdx = inOffset + ${i};
if (${o===1}) {
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
${l}
} else if (${o===2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1), 0.0, 0.0);
${l}
} else if (${o===3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2), 0.0);
${l}
}
setOutput(sumValue);
}
`}},EG=class{constructor(e,t){this.variableNames=["x"];let{windowSize:a,batchSize:n,inSize:r,outSize:s}=e;this.outputShape=[n,s];let i="0.0",o="";t==="prod"?i="1.0":t==="min"?(i="1.0 / 1e-20",o="min"):t==="max"&&(i="-1.0 / 1e-20",o="max");let l=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?l="sumValue":t==="prod"?l="prodValue":t==="all"?l="allValue":t==="any"&&(l="anyValue");let u=Math.floor(a/4)*4,p=a%4,c=`
if (${t==="sum"}) {
sumValue += dot(values, ones);
} else if (${t==="prod"}) {
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
prodValue *= tmp[0] * tmp[1];
} else {
minMaxValue = ${o}(values, minMaxValue);
if (${t==="min"} || ${t==="max"}) {
minMaxValue = ${o}(values, minMaxValue);
bvec4 isNaN = isnan(values);
if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
minMaxValue = vec4(NAN);
}
}
}
`,d="vec4";t==="all"?(i="1.0",c=`
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
`,d="bvec4"):t==="any"&&(i="0.0",c=`
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
`,d="bvec4");let h="";r%a>0&&(h=`
if (inIdx < 0 || inIdx >= ${r}) {
return initializationValue;
}
`),this.userCode=`
const float initializationValue = ${i};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${h}
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${a};
vec4 minMaxValue = vec4(${i});
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
for (int i = 0; i < ${u}; i += 4) {
int inIdx = inOffset + i;
${d} values = ${d}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${c}
}
int inIdx = inOffset + ${u};
if (${p===1}) {
${d} values = ${d}(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
${c}
} else if (${p===2}) {
${d} values = ${d}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
${c}
} else if (${p===3}) {
${d} values = ${d}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
${c}
}
setOutput(${l});
}
`}};function RG(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let a=t.length?t[t.length-1].outSize:e[1],n=T.computeOptimalWindowSize(a);t.push({inSize:a,windowSize:n,outSize:Math.ceil(a/n)})}return t}function bo(e,t,a,n){let r=RG(e.shape),s=e;for(let i=0;i<r.length;i++){let{inSize:o,windowSize:l,outSize:u}=r[i],p,c;a==="mean"?p=i===0?new vx({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},o):new vx({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u}):p=new EG({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},a),c=s,s=n.runWebGLProgram(p,[s],t),c.dataId!==e.dataId&&n.disposeIntermediateTensorInfo(c)}return s}var MG=class{constructor(e,t){this.variableNames=["A"];let a=new Array(e.length);for(let s=0;s<a.length;s++)a[s]=e[t[s]];this.outputShape=a,this.rank=a.length;let n=gt(this.rank),r=$G(t);this.userCode=`
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${r}));
}
`}};function $G(e){let t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);let a=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],n=new Array(t);for(let r=0;r<e.length;r++)n[e[r]]=a[r];return n.join()}var _G=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let a=new Array(e.length);for(let u=0;u<a.length;u++)a[u]=e[t[u]];if(this.outputShape=a,this.rank=a.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let n=gt(this.rank),r=V6("rc",this.rank),s=new Array(this.rank);for(let u=0;u<t.length;u++)s[t[u]]=r[u];let i=`vec2(${s.slice(-2).join()})`,o=`++${r[this.rank-1]} < ${a[this.rank-1]}`,l=`getChannel(getA(${s.join()}), ${i})`;this.userCode=`
void main() {
${n} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${l};
if(${o}) {
result[1] = ${l};
}
--${r[this.rank-1]};
if(++${r[this.rank-2]} < ${a[this.rank-2]}) {
result[2] = ${l};
if(${o}) {
result[3] = ${l};
}
}
setOutput(result);
}
`}};function Dh(e,t,a){let n=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new _G(e.shape,t):new MG(e.shape,t);return a.runWebGLProgram(n,[e],e.dtype)}function PG(e,t,a,n){let r=t,s=e.shape.length,i=v.parseAxisParam(r,e.shape),o=i,l=T.getAxesPermutation(o,s),u=l!=null,p=e;u&&(p=Dh(e,l,n),o=T.getInnerMostAxes(o.length,s)),T.assertAxesAreInnerMostDims("sum",o,s);let[c,d]=T.computeOutAndReduceShapes(p.shape,o),h=c;a&&(h=T.expandShapeToKeepDim(c,i));let f=v.sizeFromShape(d),m=v.sizeFromShape(e.shape)/f,g=ce({inputs:{x:p},attrs:{shape:[m,f]},backend:n}),x=Hd(e.dtype),A=bo(g,x,"sum",n),y=ce({inputs:{x:A},attrs:{shape:h},backend:n});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(A),u&&n.disposeIntermediateTensorInfo(p),y}function zh(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;return PG(r,s,i,a)}var FG={kernelName:ro,backendName:"webgl",kernelFunc:zh};function Ia(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{perm:s}=n,i=a,o=r.shape.length,l=new Array(o);for(let p=0;p<l.length;p++)l[p]=r.shape[s[p]];let u;if(i.shouldExecuteOnCPU([r])){let p=i.texData.get(r.dataId).values,c=E3(p,r.shape,r.dtype,s,l);u=i.makeTensorInfo(l,r.dtype);let d=i.texData.get(u.dataId);d.values=c}else u=Dh(r,s,i);return u}var OG={kernelName:Ar,backendName:"webgl",kernelFunc:Ia},Z6=1e3;function Dc({a:e,b:t,transposeA:a,transposeB:n,backend:r,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){let u=e.shape.length,p=t.shape.length,c=a?e.shape[u-2]:e.shape[u-1],d=n?t.shape[p-1]:t.shape[p-2],h=a?e.shape[u-1]:e.shape[u-2],f=n?t.shape[p-2]:t.shape[p-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),x=v.sizeFromShape(m),A=v.sizeFromShape(g),y=xo.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([h,f]);v.assert(c===d,()=>`Error in matMul: inner shapes (${c}) and (${d}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${a} and transposeB=${n} must match.`);let b=a?[x,c,h]:[x,h,c],w=n?[A,f,d]:[A,d,f],S=ce({inputs:{x:e},backend:r,attrs:{shape:b}}),C=ce({inputs:{x:t},backend:r,attrs:{shape:w}}),E=[S,C],_=Math.max(x,A),$=a?S.shape[1]:S.shape[2],M=s!=null,I=i!=null,N=l==="leakyrelu",O=l!=null?gd(l,!0):null,L=M||I||N||O!=null,B;if((h===1||f===1)&&$>Z6&&L===!1){let j=S,U=C;a&&(j=Ia({inputs:{x:S},backend:r,attrs:{perm:[0,2,1]}}),E.push(j)),n&&(U=Ia({inputs:{x:C},backend:r,attrs:{perm:[0,2,1]}}),E.push(U));let H=f!==1,V=f===1,Q=j;H&&(Q=ce({inputs:{x:j},backend:r,attrs:{shape:[_,$,1]}}),E.push(Q));let Z=f===1?2:1,re=U;V&&(re=ce({inputs:{x:U},backend:r,attrs:{shape:[_,1,$]}}),E.push(re));let ee=M3({inputs:{a:Q,b:re},backend:r});B=zh({inputs:{x:ee},backend:r,attrs:{axis:Z,keepDims:!0}}),E.push(ee)}else{let j=ca(e.dtype,t.dtype),U=new K6(b,w,[_,h,f],a,n,M,O,I,N),H=[S,C];if(s!=null&&H.push(s),I&&H.push(i),N){let V=r.makeTensorInfo([],"float32",v.createScalarValue(o,"float32"));H.push(V),E.push(V)}B=r.runWebGLProgram(U,H,j)}let G=ce({inputs:{x:B},backend:r,attrs:{shape:y}});E.push(B);for(let j of E)r.disposeIntermediateTensorInfo(j);return G}function DG(e){let{inputs:t,backend:a,attrs:n}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:p,leakyreluAlpha:c}=n;return Dc({a:r,b:s,transposeA:l,transposeB:u,backend:a,bias:i,preluActivationWeights:o,leakyreluAlpha:c,activation:p})}var zG={kernelName:jr,backendName:"webgl",kernelFunc:DG},wx="return abs(x);";function LG(e){let{inputs:t,backend:a}=e,{x:n}=t;if(a.shouldExecuteOnCPU([n])&&n.dtype!=="complex64"){let s=a.texData.get(n.dataId),i=B6(s.values);return a.makeTensorInfo(n.shape,n.dtype,i)}let r;return W().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new Vr(n.shape,wx):r=new qn(n.shape,wx),a.runWebGLProgram(r,[n],n.dtype)}var BG={kernelName:wl,backendName:"webgl",kernelFunc:LG},WG=Cn+`
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
`,VG=Qe({opSnippet:WG}),UG={kernelName:kl,backendName:"webgl",kernelFunc:VG},GG=Cn+`
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`,HG=Qe({opSnippet:GG}),jG={kernelName:Il,backendName:"webgl",kernelFunc:HG},kx="return a + b;",qG=oa({opSnippet:kx,packedOpSnippet:kx,supportsComplex:!0,cpuKernelImpl:nU}),XG={kernelName:ts,backendName:"webgl",kernelFunc:qG},KG=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((r,s)=>`T${s}`);let a=[];this.variableNames.forEach(r=>{a.push(`float v${r} = get${r}AtOutCoords();`)});let n=this.variableNames.map(r=>`v${r}`).join(" + ");this.userCode=`
void main() {
${a.join(`
`)}
float result = ${n};
setOutput(result);
}
`}},ZG=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((r,s)=>`T${s}`);let a=[];this.variableNames.forEach(r=>{a.push(`vec4 v${r} = get${r}AtOutCoords();`)});let n=this.variableNames.map(r=>`v${r}`).join(" + ");this.userCode=`
void main() {
${a.join(`
`)}
vec4 result = ${n};
setOutput(result);
}
`}};function bc(e){let{inputs:t,backend:a}=e,n=t;if(n.length===1)return Za({inputs:{x:n[0]},backend:a});if(n.length>W().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let o=Math.floor(n.length/2),l=bc({inputs:n.slice(0,o),backend:a}),u=bc({inputs:n.slice(o),backend:a});return bc({inputs:[l,u],backend:a})}let r=n.map(o=>o.dtype).reduce((o,l)=>ca(o,l)),s=n.map(o=>o.shape),i=W().getBool("WEBGL_PACK")?new ZG(n[0].shape,s):new KG(n[0].shape,s);return a.runWebGLProgram(i,n,r)}var YG={kernelName:Ks,backendName:"webgl",kernelFunc:bc};function JG(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n,o=r.shape.length,l=v.parseAxisParam(s,r.shape),u=l,p=T.getAxesPermutation(u,o),c=r;p!=null&&(c=Ia({inputs:{x:r},backend:a,attrs:{perm:p}}),u=T.getInnerMostAxes(u.length,o)),T.assertAxesAreInnerMostDims("all",u,o);let[d,h]=T.computeOutAndReduceShapes(c.shape,u),f=v.sizeFromShape(h),m=ce({inputs:{x:c},backend:a,attrs:{shape:[-1,f]}}),g=bo(m,m.dtype,"all",a),x;if(i){let A=T.expandShapeToKeepDim(d,l);x=ce({inputs:{x:g},backend:a,attrs:{shape:A}})}else x=ce({inputs:{x:g},backend:a,attrs:{shape:d}});return a.disposeIntermediateTensorInfo(m),a.disposeIntermediateTensorInfo(g),p!=null&&a.disposeIntermediateTensorInfo(c),x}var QG={kernelName:Zs,backendName:"webgl",kernelFunc:JG};function eH(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n,o=r.shape.length,l=v.parseAxisParam(s,r.shape),u=l,p=T.getAxesPermutation(u,o),c=r;p!=null&&(c=Ia({inputs:{x:r},backend:a,attrs:{perm:p}}),u=T.getInnerMostAxes(u.length,o)),T.assertAxesAreInnerMostDims("any",u,o);let[d,h]=T.computeOutAndReduceShapes(c.shape,u),f=v.sizeFromShape(h),m=ce({inputs:{x:c},backend:a,attrs:{shape:[-1,f]}}),g=bo(m,m.dtype,"any",a),x;if(i){let A=T.expandShapeToKeepDim(d,l);x=ce({inputs:{x:g},backend:a,attrs:{shape:A}})}else x=ce({inputs:{x:g},backend:a,attrs:{shape:d}});return a.disposeIntermediateTensorInfo(m),a.disposeIntermediateTensorInfo(g),p!=null&&a.disposeIntermediateTensorInfo(c),x}var tH={kernelName:Ys,backendName:"webgl",kernelFunc:eH},aH=class{constructor(e,t,a){this.variableNames=["A"];let{windowSize:n,batchSize:r,outSize:s}=e;a||this.variableNames.push("bestIndicesA"),this.outputShape=[r,s];let i=t==="max"?">":"<",o=a?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${n};
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
for (int i = 0; i < ${n}; i++) {
int inIdx = ${o};
float candidate = getA(batch, inIdx);
if (candidate ${i} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
`}},nH=class{constructor(e,t,a,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,v.assert(e.length>2,()=>`Packed arg${a.charAt(0).toUpperCase()+a.slice(1)} supports only inputs with rank above 2.`);let r=e[e.length-1],s=Math.ceil(r/t);this.outputShape=e.slice(0,-1),s>1&&this.outputShape.push(s),n||this.variableNames.push("bestIndicesA");let i=this.outputShape,o=i.length,l=gt(o),u=va("coords",o),p,c;if(s===1){c=o+1;let C=gt(c);p=`
${C} sourceLocR = ${C}(${u.join()}, 0);
++${u[o-1]};
${C} sourceLocG = ${C}(${u.join()}, 0);
++${u[o-2]};
${C} sourceLocA = ${C}(${u.join()}, 0);
--${u[o-1]};
${C} sourceLocB = ${C}(${u.join()}, 0);
--${u[o-2]};`}else c=o,p=`
${l} sourceLocR = coords;
++${u[o-1]};
${l} sourceLocG = coords;
++${u[o-2]};
${l} sourceLocA = coords;
--${u[o-1]};
${l} sourceLocB = coords;
--${u[o-2]};`;let d=["x","y","z","w","u","v"].slice(0,c),h="."+d[c-1],f=d.map(C=>"int "+C),m=va("sourceLocR",c-1).concat("inIdx.r"),g=va("sourceLocG",c-1).concat("inIdx.g"),x=va("sourceLocB",c-1).concat("inIdx.b"),A=va("sourceLocA",c-1).concat("inIdx.a"),y=a==="max"?"greaterThan":"lessThan",b=n?"":`
inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),
getBestIndicesAChannel(${g.join()}),
getBestIndicesAChannel(${x.join()}),
getBestIndicesAChannel(${A.join()})));`,w=`vec4(
getAChannel(${m.join()}),
hasNextCol ? getAChannel(${g.join()}) : 0.,
hasNextRow ? getAChannel(${x.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${A.join()}) : 0.)`,S=n?"":`
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()}));
}
${S}
void main() {
${l} coords = getOutputCoords();
bool hasNextCol = ${u[o-1]} < ${i[o-1]-1};
bool hasNextRow = ${u[o-2]} < ${i[o-2]-1};
${p}
ivec4 srcIdx = ivec4(sourceLocR${h}, sourceLocG${h},
sourceLocB${h}, sourceLocA${h}) * ${t};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = ${w};
for (int i = 0; i < ${t}; i++) {
inIdx = srcIdx;
${b}
vec4 candidate = ${w};
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
vec4(${y}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
}
setOutput(bestIndex);
}
`}};function Y6(e,t,a,n=null){let r=t.shape[0],s=t.shape[1];n!=null&&(r=n.shape[0],s=n.shape[1]);let i=T.computeOptimalWindowSize(s),o={windowSize:i,inSize:s,batchSize:r,outSize:Math.ceil(s/i)},l=new aH(o,a,n==null),u=[t];n!=null&&u.push(n);let p=e.runWebGLProgram(l,u,"int32");if(p.shape[1]===1)return p;let c=Y6(e,t,a,p);return e.disposeIntermediateTensorInfo(p),c}function J6(e,t,a,n=null){let r=n!=null?n.shape:t.shape,s=r[r.length-1],i=T.computeOptimalWindowSize(s),o=new nH(r,i,a,n==null),l=n==null?[t]:[t,n],u=e.runWebGLProgram(o,l,"int32");if(u.shape.length===t.shape.length){let p=J6(e,t,a,u);return e.disposeIntermediateTensorInfo(u),p}return u}function Q6(e,t,a,n){let r=[a];if(T.assertAxesAreInnerMostDims("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.shape.length),!W().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let s=[],i=e.texData.get(t.dataId),o=i!==null&&i.isPacked,l=t;o&&(l=e.unpackTensor(t),s.push(l));let[u,p]=T.computeOutAndReduceShapes(l.shape,r),c=v.sizeFromShape(p),d=ce({inputs:{x:l},backend:e,attrs:{shape:[-1,c]}});s.push(d);let h=Y6(e,d,n);s.push(h);let f=ce({inputs:{x:h},backend:e,attrs:{shape:u}});return s.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}return J6(e,t,n)}function rH(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s}=n,i=v.parseAxisParam(s,r.shape),o=T.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=Ia({inputs:{x:r},backend:a,attrs:{perm:o}}),u.push(l),i=T.getInnerMostAxes(i.length,l.shape.length)),T.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let p=Q6(a,l,i[0],"max");return u.forEach(c=>a.disposeIntermediateTensorInfo(c)),p}var sH={kernelName:Js,backendName:"webgl",kernelFunc:rH};function iH(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s}=n,i=v.parseAxisParam(s,r.shape),o=T.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=Ia({inputs:{x:r},backend:a,attrs:{perm:o}}),u.push(l),i=T.getInnerMostAxes(i.length,l.shape.length)),T.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let p=Q6(a,l,i[0],"min");return u.forEach(c=>a.disposeIntermediateTensorInfo(c)),p}var oH={kernelName:kd,backendName:"webgl",kernelFunc:iH},lH=Cn+`
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
`,uH=Qe({opSnippet:lH}),dH={kernelName:Sl,backendName:"webgl",kernelFunc:uH},pH=Cn+"return log(x + sqrt(x * x + 1.0));",cH=Qe({opSnippet:pH}),hH={kernelName:Tl,backendName:"webgl",kernelFunc:cH},fH=Cn+`
return atan(x);
`,mH=Qe({opSnippet:fH}),gH={kernelName:Cl,backendName:"webgl",kernelFunc:mH},xH=R3+`
return atan(a, b);
`,AH=`
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);
`+pp+`
return result;
`,yH=oa({opSnippet:xH,packedOpSnippet:AH}),bH={kernelName:El,backendName:"webgl",kernelFunc:yH},vH=Cn+`
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,wH=Qe({opSnippet:vH}),kH={kernelName:Nl,backendName:"webgl",kernelFunc:wH},xd=class{constructor(e,t,a,n=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&a)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideHeight,o=e.strideWidth,l=e.dilationHeight,u=e.dilationWidth,p=e.effectiveFilterHeight,c=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`,x="0.0";if(f||(x="-1.0 / 1e-20"),a){let C=">=";this.userCode=`
const ivec2 strides = ivec2(${i}, ${o});
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 < ${p};
wR += ${l}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${c};
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 = ${n?r?m:g:`wR * ${c} + wC`};
}
}
}
setOutput(float(minMaxPosition));
}
`;return}let A="max",y=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(y="avgValue / count");let b=Math.floor(s/4)*4,w=s%4,S=`
if (${f}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${A}(values, minMaxValue);
}
`;this.userCode=`
const ivec2 strides = ivec2(${i}, ${o});
const ivec2 pads = ivec2(${d}, ${h});
const float initializationValue = ${x};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int 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(${x});
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < ${p};
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)
);
${S}
}
int xC = xCCorner + ${b};
if (${w===1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
${S}
} else if (${w===2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${u}, d),
initializationValue,
initializationValue
);
${S}
} 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
);
${S}
}
}
setOutput(${y});
}
`}},$3=class{constructor(e,t,a,n=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&a)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,l=e.strideWidth,u=e.dilationDepth,p=e.dilationHeight,c=e.dilationWidth,d=e.effectiveFilterDepth,h=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,x=e.padInfo.left;this.outputShape=e.outShape;let A=t==="avg",y="0.0";if(A||(y="-1.0 / 1e-20"),a){let _=">=";this.userCode=`
const ivec3 strides =
ivec3(${i}, ${o}, ${l});
const ivec3 pads = ivec3(${m}, ${g}, ${x});
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 += ${p}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${f};
wC += ${c}) {
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 ${_} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${n?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 S=Math.floor(s/4)*4,C=s%4,E=`
if (${A}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${b}(values, minMaxValue);
}
`;this.userCode=`
const ivec3 strides =
ivec3(${i}, ${o}, ${l});
const ivec3 pads = ivec3(${m}, ${g}, ${x});
const float initializationValue = ${y};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
vec4 minMaxValue = vec4(${y});
float avgValue = 0.0;
count = 0.0;
for (int wD = 0; wD < ${d};
wD += ${u}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${h};
wR += ${p}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${S}; wC += 4) {
int xC = xCCorner + wC * ${c};
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${c}, ch),
getValue(batch, xD, xR, xC + 2 * ${c}, ch),
getValue(batch, xD, xR, xC + 3 * ${c}, ch)
);
${E}
}
int xC = xCCorner + ${S};
if (${C===1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${E}
} else if (${C===2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${c}, ch),
initializationValue,
initializationValue
);
${E}
} else if (${C===3}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${c}, ch),
getValue(batch, xD, xR, xC + 2 * ${c}, ch),
initializationValue
);
${E}
}
}
setOutput(${w});
}
}
`}};function IH(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t;uu(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1;v.assert(T.eitherStridesOrDilationsAreOne(i,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=T.computePool2DInfo(r.shape,s,i,u,o,l);if(p.filterWidth===1&&p.filterHeight===1&&v.arraysEqual(p.inShape,p.outShape))return Za({inputs:{x:r},backend:a});let c=new xd(p,"avg",!1);return a.runWebGLProgram(c,[r],"float32")}var SH={kernelName:Qs,backendName:"webgl",kernelFunc:IH};function TH(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=n,p=[1,1,1],c=T.computePool3DInfo(r.shape,s,i,p,o,l,u),d=new $3(c,"avg",!1);return a.runWebGLProgram(d,[r],"float32")}var CH={kernelName:Hc,backendName:"webgl",kernelFunc:TH},NH=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,a=e.filterWidth,n=e.strideHeight,r=e.strideWidth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=o-1-e.padInfo.top,p=l-1-e.padInfo.left,c=1/(t*a);this.userCode=`
const ivec2 pads = ivec2(${u}, ${p});
const float avgMultiplier = float(${c});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${o};
wR += ${s}) {
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${l};
wC+= ${i}) {
float dyC = float(dyCCorner + wC) / ${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);
}
`}},EH=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,a=e.filterHeight,n=e.filterWidth,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,p=e.effectiveFilterDepth,c=e.effectiveFilterHeight,d=e.effectiveFilterWidth,h=p-1-e.padInfo.front,f=c-1-e.padInfo.top,m=d-1-e.padInfo.left,g=1/(t*a*n);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 < ${p};
wD += ${o}) {
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 < ${c};
wR += ${l}) {
float dyR = float(dyRCorner + wR) / ${s}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${d};
wC += ${u}) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
dotProd += dyValue * avgMultiplier;
}
}
}
setOutput(dotProd);
}
`}};function RH(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:p}=n,c=[1,1,1],d=T.computePool3DInfo(i.shape,o,l,c,u,p),h=new EH(d);return a.runWebGLProgram(h,[r],i.dtype)}var MH={kernelName:G1,backendName:"webgl",kernelFunc:RH};function $H(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,i=s;uu([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:u}=n,p=T.computePool2DInfo(i.shape,o,l,1,u),c=new NH(p);return a.runWebGLProgram(c,[r],i.dtype)}var _H={kernelName:U1,backendName:"webgl",kernelFunc:$H};function PH(e){let{inputs:t,backend:a,attrs:n}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=n;return Dc({a:r,b:s,transposeA:i,transposeB:o,backend:a})}var FH={kernelName:ei,backendName:"webgl",kernelFunc:PH},OH=class{constructor(e,t,a,n,r,s){this.outputShape=[],this.variableNames=["x","mean","variance"],T.assertAndGetBroadcastShape(e,t),T.assertAndGetBroadcastShape(e,a);let i="0.0";n!=null&&(T.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";r!=null&&(T.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = ${i};
float scale = ${o};
float inv = scale * inversesqrt(variance + float(${s}));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
`}},DH=class{constructor(e,t,a,n,r,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],T.assertAndGetBroadcastShape(e,t),T.assertAndGetBroadcastShape(e,a);let i="vec4(0.0)";n!=null&&(T.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";r!=null&&(T.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
void main() {
vec4 offset = ${i};
vec4 scale = ${o};
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
vec4 inv = scale * inversesqrt(variance + vec4(${s}));
setOutput((x - mean) * inv + offset);
}
`}},zH=({inputs:e,backend:t,attrs:a})=>{let{x:n,mean:r,variance:s,offset:i,scale:o}=e;v.assert(r.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),v.assert(i==null||r.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),v.assert(o==null||r.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=a;l==null&&(l=.001);let u=[n,r,s],p=null;i!=null&&(p=i.shape,u.push(i));let c=null;o!=null&&(c=o.shape,u.push(o));let d=W().getBool("WEBGL_PACK_NORMALIZATION")?new DH(n.shape,r.shape,s.shape,p,c,l):new OH(n.shape,r.shape,s.shape,p,c,l);return t.runWebGLProgram(d,u,u[0].dtype)},LH={kernelName:yi,backendName:"webgl",kernelFunc:zH},BH=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=gt(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let a=WH(this.rank),n,r=e.map((s,i)=>`sourceLoc.${T1[i]} = start[${i}] + coords.${T1[i]};`);n=`
${t} sourceLoc;
${t} coords = getOutputCoords();
${r.join(`
`)}
`,this.userCode=`
void main() {
${n}
setOutput(getSource(${a}));
}
`}},T1=["x","y","z","w","u","v"];function WH(e){if(e===1)return"sourceLoc";if(e<=6)return T1.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var VH=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=gt(this.rank),a=va("coords",this.rank),n=va("sourceLoc",this.rank),r=this.rank===1?"sourceLoc":`vec2(${n.slice(-2).join()})`,s=`getChannel(getSource(${n.join()}), ${r})`,i=`
result.x = ${s};
if (++${a[this.rank-1]} < ${e[this.rank-1]}) {
++${n[this.rank-1]};
result.y = ${s};
--${n[this.rank-1]};
}
`,o=this.rank===1?"":`
--${a[this.rank-1]};
if (++${a[this.rank-2]} < ${e[this.rank-2]}) {
++${n[this.rank-2]};
result.z = ${s};
if (++${a[this.rank-1]} < ${e[this.rank-1]}) {
++${n[this.rank-1]};
result.w = ${s};
}
}
`,l=this.rank<=4?`sourceLoc = coords +
${t}(${e.map((u,p)=>`start[${p}]`).join()});`:e.map((u,p)=>`${n[p]} = ${a[p]} + start[${p}];`).join(`
`);this.userCode=`
void main() {
${t} coords = getOutputCoords();
${t} sourceLoc;
${l}
vec4 result = vec4(0.);
${i}
${o}
setOutput(result);
}
`}};function UH(e,t,a,n){let r=n.texData.get(e.dataId),s=n.makeTensorInfo(a,e.dtype),i=n.texData.get(s.dataId);Object.assign(i,r),i.refCount=1,i.shape=a,i.dtype=e.dtype;let o=It.computeFlatOffset(t,v.computeStrides(e.shape));r.slice&&(o+=r.slice.flatOffset),i.slice={flatOffset:o,origDataId:r.slice&&r.slice.origDataId||e.dataId};let l=n.dataRefCount.get(i.slice.origDataId)||1;return n.dataRefCount.set(i.slice.origDataId,l+1),s}function gu(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{begin:s,size:i}=n,[o,l]=It.parseSliceParams(r,s,i);if(It.assertParamsValid(r,o,l),v.sizeFromShape(l)===0)return a.makeTensorInfo(l,r.dtype,[]);if(a.shouldExecuteOnCPU([r])||r.dtype==="string"){let c=a.texData.get(r.dataId),d=PU(c.values,o,l,r.shape,r.dtype);return a.makeTensorInfo(l,r.dtype,d)}let{isPacked:u}=a.texData.get(r.dataId),p=It.isSliceContinous(r.shape,o,l);if(u||!p){let c=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new VH(l):new BH(l),d=[o];return a.runWebGLProgram(c,[r],r.dtype,d)}return a.uploadToGPU(r.dataId),UH(r,o,l,a)}var GH={kernelName:Zl,backendName:"webgl",kernelFunc:gu},HH=e=>{let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{blockShape:s,crops:i}=n;v.assert(r.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((A,y)=>A*y),l=T.getReshaped(r.shape,s,o),u=T.getPermuted(l.length,s.length),p=T.getReshapedPermuted(r.shape,s,o),c=T.getSliceBeginCoords(i,s.length),d=T.getSliceSize(p,i,s.length),h=[],f=ce({inputs:{x:r},backend:a,attrs:{shape:l}}),m=Ia({inputs:{x:f},backend:a,attrs:{perm:u}}),g=ce({inputs:{x:m},backend:a,attrs:{shape:p}}),x=gu({inputs:{x:g},backend:a,attrs:{begin:c,size:d}});return h.push(f),h.push(m),h.push(g),h.forEach(A=>a.disposeIntermediateTensorInfo(A)),x},jH={kernelName:Rl,backendName:"webgl",kernelFunc:HH};function qH(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,weights:s}=t,{size:i}=n,o=a.readSync(r.dataId),l=a.readSync(s.dataId),u=L6(o,l,s.dtype,s.shape,i);return a.makeTensorInfo([i],s.dtype,u)}var XH={kernelName:Id,backendName:"webgl",kernelFunc:qH};function KH(e){let{inputs:t,backend:a}=e,{s0:n,s1:r}=t,s=a.readSync(n.dataId),i=a.readSync(r.dataId),o=T.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return a.makeTensorInfo([o.length],"int32",Int32Array.from(o))}var ZH={kernelName:jc,backendName:"webgl",kernelFunc:KH},YH="return float(a != b);",ev=oa({opSnippet:YH,cpuKernelImpl:SU,dtype:"bool"}),JH={kernelName:Li,backendName:"webgl",kernelFunc:ev};function hp(e){let{inputs:t,backend:a}=e,{input:n}=t,r=a.texData.get(n.dataId);return Za({inputs:{x:r.complexTensorInfos.real},backend:a})}var QH={kernelName:Md,backendName:"webgl",kernelFunc:hp},ej="return float(int(x));";function tj(e,t){let a=new qn(e.shape,ej),n=t.runWebGLProgram(a,[e],"int32");return{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}function C1(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{dtype:s}=n;if(s==="complex64"){if(r.dtype==="complex64")return Za({inputs:{x:r},backend:a});let i=fn(r.shape),o=C1({inputs:{x:r},backend:a,attrs:{dtype:"float32"}}),l=ls({inputs:{real:o,imag:i},backend:a});return i.dispose(),a.disposeIntermediateTensorInfo(o),l}if(r.dtype==="complex64"){let i=hp({inputs:{input:r},backend:a}),o=C1({inputs:{x:i},backend:a,attrs:{dtype:s}});return a.disposeIntermediateTensorInfo(i),o}if(!v.hasEncodingLoss(r.dtype,s)){let i=Za({inputs:{x:r},backend:a});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(a.shouldExecuteOnCPU([r])){let i=a.texData.get(r.dataId).values,[o,l,u]=sU(i,r.shape,r.dtype,s);return a.makeTensorInfo(o,l,u)}if(s==="int32")return tj(r,a);if(s==="bool"){let i=a.makeTensorInfo([],"bool",v.getTypedArrayFromDType("bool",1)),o=ev({inputs:{a:r,b:i},backend:a});return a.disposeIntermediateTensorInfo(i),o}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${s}`)}var aj={kernelName:ti,backendName:"webgl",kernelFunc:C1},Ix="return ceil(x);",nj=Qe({opSnippet:Ix,packedOpSnippet:Ix,cpuKernelImpl:iU}),rj={kernelName:ai,backendName:"webgl",kernelFunc:nj},sj=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));
}
`}},ij=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 oj(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{clipValueMin:s,clipValueMax:i}=n,o;W().getBool("WEBGL_PACK_CLIP")?o=new ij(r.shape):o=new sj(r.shape);let l=[[s],[i]];return a.runWebGLProgram(o,[r],r.dtype,l)}var lj={kernelName:as,backendName:"webgl",kernelFunc:oj},uj=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 Sx(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function dj(e){let{inputs:t,backend:a}=e,{x:n}=t,r=a.texData.get(n.dataId),s=new uj(n.shape),i=[Sx(n,r.complexTensorInfos.real),Sx(n,r.complexTensorInfos.imag)];return a.runWebGLProgram(s,i,i[0].dtype)}var pj={kernelName:qc,backendName:"webgl",kernelFunc:dj},cj=class{constructor(e){this.outputShape=[],this.outputShape=T.computeOutShape(e,1),this.variableNames=e.map((s,i)=>`T${i}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let s=1;s<t.length;s++)t[s]=t[s-1]+e[s][1];let a=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let s=1;s<t.length;s++){let i=t[s-1];a.push(`else if (yC < ${t[s]}) setOutput(getT${s}(yR, yC-${i}));`)}let n=t.length,r=t[t.length-1];a.push(`else setOutput(getT${n}(yR, yC-${r}));`),this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
${a.join(`
`)}
}
`}},hj=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=T.computeOutShape(e,t);let a=this.outputShape,n=a.length,r=gt(n),s=va("coords",n),i=["x","y","z","w","u","v"].slice(0,n);this.variableNames=e.map((f,m)=>`T${m}`);let o=new Array(e.length-1);o[0]=e[0][t];for(let f=1;f<o.length;f++)o[f]=o[f-1]+e[f][t];let l=i[t],u=i.slice(-2),p=i.join(),c=`if (${l} < ${o[0]}) {
return getChannel(
getT0(${p}), vec2(${u.join()}));
}`;for(let f=1;f<o.length;f++){let m=o[f-1];c+=`
if (${l} < ${o[f]} && ${l} >= ${o[f-1]}) {
return getChannel(
getT${f}(${pc(i,l,m)}),
vec2(${pc(u,l,m)}));
}`}let d=o.length,h=o[o.length-1];c+=`
return getChannel(
getT${d}(${pc(i,l,h)}),
vec2(${pc(u,l,h)}));`,this.userCode=`
float getValue(${i.map(f=>"int "+f)}) {
${c}
}
void main() {
${r} coords = getOutputCoords();
vec4 result = vec4(getValue(${s}), 0., 0., 0.);
${s[n-1]} = ${s[n-1]} + 1;
if (${s[n-1]} < ${a[n-1]}) {
result.g = getValue(${s});
}
${s[n-2]} = ${s[n-2]} + 1;
if (${s[n-2]} < ${a[n-2]}) {
result.a = getValue(${s});
}
${s[n-1]} = ${s[n-1]} - 1;
if (${s[n-2]} < ${a[n-2]} &&
${s[n-1]} < ${a[n-1]}) {
result.b = getValue(${s});
}
setOutput(result);
}
`}};function pc(e,t,a){let n=e.indexOf(t);return e.map((r,s)=>s===n?`${r} - ${a}`:r).join()}function Lh(e){let{inputs:t,backend:a}=e,{input:n}=t,r=a.texData.get(n.dataId);return Za({inputs:{x:r.complexTensorInfos.imag},backend:a})}var fj={kernelName:Rd,backendName:"webgl",kernelFunc:Lh};function Zu(e,t,a){let n=e[0].dtype;if(n==="complex64"){let h=e.map(A=>hp({inputs:{input:A},backend:a})),f=e.map(A=>Lh({inputs:{input:A},backend:a})),m=Zu(h,t,a),g=Zu(f,t,a),x=ls({inputs:{real:m,imag:g},backend:a});return h.forEach(A=>a.disposeIntermediateTensorInfo(A)),f.forEach(A=>a.disposeIntermediateTensorInfo(A)),a.disposeIntermediateTensorInfo(m),a.disposeIntermediateTensorInfo(g),x}let r=a.shouldExecuteOnCPU(e);if(n==="string"&&(r=!0),r){let h=e.map(b=>{let w=[-1,v.sizeFromShape(b.shape.slice(t))];return ce({inputs:{x:b},backend:a,attrs:{shape:w}})}),f=h.map(b=>({vals:a.readSync(b.dataId),shape:b.shape})),m=T.computeOutShape(h.map(b=>b.shape),1),g=h[0].shape[0]===1,x=oU(f,m,n,g),A=T.computeOutShape(e.map(b=>b.shape),t),y=a.makeTensorInfo(A,n,x);return h.forEach(b=>a.disposeIntermediateTensorInfo(b)),y}let s=e.filter(h=>v.sizeFromShape(h.shape)>0),i=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&s[0].shape.length>1;if(s.length===1){let h=i?new qn(e[0].shape,Dr):new Vr(e[0].shape,Dr);return a.runWebGLProgram(h,e,n)}let o=W().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(s.length>o){let h=[];for(let m=0;m<s.length;m+=o){let g=s.slice(m,m+o);h.push(Zu(g,t,a))}let f=Zu(h,t,a);for(let m of h)a.disposeIntermediateTensorInfo(m);return f}if(i){let h=new hj(s.map(f=>f.shape),t);return a.runWebGLProgram(h,s,n)}let{tensors2D:l,outShape:u}=mj(s,t,a),p=new cj(l.map(h=>h.shape)),c=a.runWebGLProgram(p,l,n);l.forEach(h=>a.disposeIntermediateTensorInfo(h));let d=ce({inputs:{x:c},attrs:{shape:u},backend:a});return a.disposeIntermediateTensorInfo(c),d}function mj(e,t,a){let n=T.computeOutShape(e.map(r=>r.shape),t);return{tensors2D:e.map(r=>ce({inputs:{x:r},attrs:{shape:[-1,v.sizeFromShape(r.shape.slice(t))]},backend:a})),outShape:n}}function tv(e){let{inputs:t,backend:a,attrs:n}=e,{axis:r}=n,s=v.parseAxisParam(r,t[0].shape)[0],i=t.map(u=>u.shape);T.assertParamsConsistent(i,s);let o=T.computeOutShape(t.map(u=>u.shape),s);if(v.sizeFromShape(o)===0)return a.makeTensorInfo(o,t[0].dtype,[]);let l=t.filter(u=>v.sizeFromShape(u.shape)>0);return l.length===1?Za({inputs:{x:l[0]},backend:a}):Zu(l,s,a)}var gj={kernelName:Ml,backendName:"webgl",kernelFunc:tv},av=class{constructor(e,t=!1,a=null,n=!1,r=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let s=e.padInfo.top,i=e.padInfo.left,o=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,p=e.dilationWidth,c=e.filterHeight,d=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4,m=e.dataFormat==="channelsLast",g=m?1:2,x=m?2:3,A=m?3:1,y="",b="";a&&(n?y=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${a}
}`:r?y=`float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${a}
}`:y=`
float activation(float x) {
${a}
}
`,b="result = activation(result);");let w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${y}
const ivec2 strides = ivec2(${o}, ${l});
const ivec2 pads = ivec2(${s}, ${i});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[${A}];
ivec2 xRCCorner =
ivec2(coords[${g}], coords[${x}]) * 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 < ${c}; wR++) {
int xR = xRCorner + wR * ${u};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${d}; wC++) {
int xC = xCCorner + wC * ${p};
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);
}
`}},xj=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,a=e.padInfo.top,n=e.padInfo.left,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,p=e.filterDepth,c=e.filterHeight,d=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4;this.userCode=`
const ivec3 strides = ivec3(${r}, ${s}, ${i});
const ivec3 pads = ivec3(${t}, ${a}, ${n});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d2 = coords.u;
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xFCorner = xFRCCorner.x;
int xRCorner = xFRCCorner.y;
int xCCorner = xFRCCorner.z;
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0;
for (int wF = 0; wF < ${p}; wF++) {
int xF = xFCorner + wF * ${o};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${c}; 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);
}
`}},nv=class{constructor(e,t=!1,a=null,n=!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=Na(this.outputShape.length);let s=e.padInfo.left,i=e.strideWidth,o=e.dilationWidth,l=e.filterHeight,u=e.filterWidth,p=u,c=`
int xR; int xC; int xCOffset;
vec4 wTexel; vec4 previous; vec4 final;`;for(let m=0;m<u;m++)c+=`
vec4 xTexelC${m*2};
int xTexelC${m*2}Ready;
vec4 xTexelC${m*2+1};
int xTexelC${m*2+1}Ready;
vec4 xC${m};`;c+=`
for (int r = 0; r < ${l}; r++) {
for (int d1 = 0; d1 < ${e.inChannels}; d1 += 2) {
`;for(let m=0;m<u;m++)c+=`
xTexelC${m*2} = vec4(0.0);
xTexelC${m*2}Ready = 0;
xTexelC${m*2+1} = vec4(0.0);
xTexelC${m*2+1}Ready = 0;
xC${m} = vec4(0.0);`;c+=`
xR = xRCorner + r * dilations[0];
if (xR >=0 && xR < inDims[0]) {
`;for(let m=0;m<(p+1)/2;m++){let g=m*2;if(c+=`
xC = xCCorner + ${g*o};
`,i===1){if(g<u&&(s%2===1?(c+=`
xCOffset = xC + 1;
if (xCOffset >= 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;
}
`,o===1&&g>0?c+=`
xC${g} = vec4(xTexelC${g-2}.zw, xTexelC${g}.xy);
`:c+=`
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);
}
`):c+=`
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<u)){let x=s%2===0?v.nearestLargerEven(o):o;o%2===0&&s%2===1||o%2!==0&&s%2!==1?(c+=`
xCOffset = xC + imod(pads[1], 2) + ${x};
if (xCOffset >= 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;
}
`,o>1?c+=`
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);
}
`:c+=`
xC${g+1} = vec4(xTexelC${g}.zw, xTexelC${g+1}.xy);
`):x===1?c+=`
xC${g+1} = xTexelC${g};
`:c+=`
xCOffset = xC + ${x};
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<u&&(s%2===1?(c+=`
xCOffset = xC + 1 - strides[1];
if(xCOffset >= 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<u&&(c+=`
final = vec4(0.0);
xCOffset = xC + 1 + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1]) {
final = getX(batch, xR, xCOffset, d1);
}
xC${g+1} = vec4(xTexelC${g+1}.xy, final.xy);
`)):(c+=`
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<u&&(c+=`
xC${g+1} = vec4(xTexelC${g}.zw, xTexelC${g+1}.zw);
`)));g<u&&(c+=`
wTexel = getW(r, ${g}, d1, d2);
dotProd += xC${g}.xxzz * vec4(wTexel.xy, wTexel.xy);
if(d1 + 1 < ${e.inChannels}) {
dotProd += xC${g}.yyww * vec4(wTexel.zw, wTexel.zw);
}
`,g+1<u&&(c+=`
wTexel = getW(r, ${g+1}, d1, d2);
dotProd += xC${g+1}.xxzz * vec4(wTexel.xy, wTexel.xy);
if(d1 + 1 < ${e.inChannels}) {
dotProd += xC${g+1}.yyww * vec4(wTexel.zw, wTexel.zw);
}
`))}c+=`
}
`,c+=`
}
`,c+=`
}
`;let d="",h="";a&&(n?d=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${a}
}`:r?d=`vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${a}
}`:d=`vec4 activation(vec4 x) {
${a}
}`,h="result = activation(result);");let f=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${d}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
vec4 dotProd = vec4(0.000000000000001);
${c}
vec4 result = dotProd - vec4(0.000000000000001);
${f}
${h}
setOutput(result);
}
`}},Aj=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec4"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=Na(this.outputShape.length);let{dataFormat:a}=t,n=Ca(),r=a==="channelsLast",s=r?1:2,i=r?2:3,o=this.enableShapeUniforms?"if(blockIndex < outShape[2] && pos < outShape[1]) {":`if(blockIndex < ${e[2]} && pos < ${e[1]}) {`,l="";for(let u=0;u<=1;u++)for(let p=0;p<=1;p++)l+=`
blockIndex = rc.z + ${p};
pos = rc.y + ${u};
${o}
offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
if(d0 < inputShape[${s}] && d0 >= 0) {
// Use custom imod instead mod. On Intel GPU, mod may generate
// unexpected value.
// https://github.com/tensorflow/tfjs/issues/5447
offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];
d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /
inChannels);
if(d1 < inputShape[${i}] && d1 >= 0) {
ch = imod(pos, inChannels);
if (${r}) {
innerDims = vec2(d1, ch);
result[${u*2+p}] = getChannel(
getA(rc.x, d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${u*2+p}] = getChannel(
getA(rc.x, ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;this.userCode=`
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0);
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
${l}
${n.output} = result;
}
`}};function zc(e,t){let a=e.length;return a>=3?t?[...e.slice(0,-3),e[a-3]*e[a-2],e[a-1]]:[...e.slice(0,-3),e[a-3],e[a-2]*e[a-1]]:!t&&a===1&&e[0]>1?[e[0],1]:null}function rv({x:e,filter:t,convInfo:a,backend:n,bias:r=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=e.shape,u=n.texData.get(e.dataId),p=a.inChannels,c=l[0]*l[1]*l[2],d=a.outChannels,h=a.dataFormat==="channelsLast",f=!1,m=!1,g,x=[];if(s!=null){let A=zc(s.shape,h);A!=null&&(s=ce({inputs:{x:s},backend:n,attrs:{shape:A}}),x.push(s))}if(r!=null){let A=zc(r.shape,h);A!=null&&(r=ce({inputs:{x:r},backend:n,attrs:{shape:A}}),x.push(r))}if(!((c===1||d===1)&&p>Z6)&&u.isPacked&&h&&u.texture!=null&&l[2]%2!==0&&v.arraysEqual(u.shape.slice(-3),l.slice(-3))){let A=l[0]*l[1]*(l[2]+1),y={dataId:e.dataId,shape:[1,A,a.inChannels],dtype:e.dtype},b=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,v.assert(md(u.shape,y.shape),()=>`packed reshape ${u.shape} to ${y.shape} isn't free`);let w=ce({inputs:{x:t},backend:n,attrs:{shape:[1,a.inChannels,a.outChannels]}});x.push(w);let S=Dc({a:y,b:w,backend:n,transposeA:f,transposeB:m,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),C=n.texData.get(S.dataId);v.assert(C.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=b,C.shape=a.outShape,g=Za({inputs:{x:S},backend:n}),g.shape=a.outShape,x.push(S)}else{let A=a.outHeight*a.outWidth,y=ce({inputs:{x:e},backend:n,attrs:{shape:h?[a.batchSize,A,a.inChannels]:[a.batchSize,a.inChannels,A]}}),b=ce({inputs:{x:t},backend:n,attrs:{shape:[1,a.inChannels,a.outChannels]}}),w=Dc({a:h?y:b,b:h?b:y,transposeA:!h,transposeB:m,backend:n,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i});g=ce({inputs:{x:w},backend:n,attrs:{shape:a.outShape}}),x.push(y),x.push(b),x.push(w)}for(let A of x)n.disposeIntermediateTensorInfo(A);return g}function sv({x:e,filter:t,convInfo:a,backend:n,bias:r=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let{filterWidth:l,filterHeight:u,inChannels:p,outWidth:c,outHeight:d,dataFormat:h}=a,f=h==="channelsLast",m=l*u*p,g=d*c,x=[a.batchSize,m,g],A=!0,y=!1,b=[];if(s!=null){let j=zc(s.shape,f);j!=null&&(s=ce({inputs:{x:s},backend:n,attrs:{shape:j}}),b.push(s))}if(r!=null){let j=zc(r.shape,f);j!=null&&(r=ce({inputs:{x:r},backend:n,attrs:{shape:j}}),b.push(r))}let w=ce({inputs:{x:t},backend:n,attrs:{shape:[1,m,v.sizeFromShape(t.shape)/m]}});b.push(w);let S=new Aj(x,a),C=[e.shape,[a.padInfo.top,a.padInfo.left],[a.strideHeight,a.strideWidth],[a.dilationHeight,a.dilationWidth],[a.inChannels],[a.filterWidth*a.inChannels],[a.outWidth]],E=n.runWebGLProgram(S,[e],"float32",C),_=ce({inputs:{x:E},backend:n,attrs:{shape:x}});b.push(E),b.push(_);let $=r!=null,M=s!=null,I=o==="leakyrelu",N=o?gd(o,!0):null,O=new K6(f?_.shape:w.shape,f?w.shape:_.shape,f?[a.batchSize,g,a.outChannels]:[a.batchSize,a.outChannels,g],A,y,$,N,M,I),L=f?[_,w]:[w,_];if(r&&L.push(r),M&&L.push(s),I){let j=n.makeTensorInfo([],"float32",v.createScalarValue(i,"float32"));L.push(j),b.push(j)}let B=n.runWebGLProgram(O,L,"float32"),G=ce({inputs:{x:B},backend:n,attrs:{shape:a.outShape}});b.push(B);for(let j of b)n.disposeIntermediateTensorInfo(j);return G}function yj(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:p}=n,c=T.convertConv2DDataFormat(l),d=T.computeConv2DInfo(r.shape,s.shape,i,u,o,p,!1,c),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=rv({x:r,filter:s,convInfo:d,backend:a});else if(d.strideWidth<=2&&c==="channelsLast"&&W().getBool("WEBGL_EXP_CONV")){let m=new nv(d),g=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];h=a.runWebGLProgram(m,[r,s],"float32",g)}else if(W().getBool("WEBGL_CONV_IM2COL"))h=sv({x:r,filter:s,convInfo:d,backend:a});else{let m=new av(d);h=a.runWebGLProgram(m,[r,s],"float32")}let f=ce({inputs:{x:h},backend:a,attrs:{shape:d.outShape}});return a.disposeIntermediateTensorInfo(h),f}var bj={kernelName:ni,backendName:"webgl",kernelFunc:yj},vj=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,a=e.strideWidth,n=e.padInfo.top,r=e.padInfo.left,s=e.dataFormat==="channelsLast";this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int d2 = coords.w;
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${n};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${a} - ${r};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
if (${s}) {
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
} else {
float dyValue = getDy(b, d2, yR, yC);
float xValue = getX(b, d1, xR, xC);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`}},wj=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,a=e.filterWidth,n=e.strideHeight,r=e.strideWidth,s=e.dataFormat==="channelsLast",i=t-1-e.padInfo.top,o=a-1-e.padInfo.left,l=s?1:2,u=s?2:3,p=s?3:1;this.userCode=`
const ivec2 pads = ivec2(${i}, ${o});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[${p}];
ivec2 dyCorner = ivec2(coords[${l}], coords[${u}]) - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
for (int wC = 0; wC < ${a}; 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 = ${a} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
if (${s}) {
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
} else {
float xValue = getDy(batch, d2, idyR, idyC);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`}},kj=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,a=e.strideHeight,n=e.strideWidth,r=e.padInfo.front,s=e.padInfo.top,i=e.padInfo.left;this.userCode=`
void main() {
ivec5 coords = getOutputCoords();
int wF = coords.x;
int wR = coords.y;
int wC = coords.z;
int d1 = coords.w;
int d2 = coords.u;
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yF = 0; yF < ${e.outDepth}; yF++) {
int xF = wF + yF * ${t} - ${r};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${a} - ${s};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${i};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`}},Ij=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,a=e.filterHeight,n=e.filterWidth,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.front,l=a-1-e.padInfo.top,u=n-1-e.padInfo.left;this.userCode=`
const ivec3 pads = ivec3(${o}, ${l}, ${u});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
float dotProd = 0.0;
for (int wF = 0; wF < ${t}; wF++) {
float dyF = float(dyFCorner + wF) / ${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 < ${a}; 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 = ${a} - 1 - wR;
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${n} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`}};function Sj(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:p}=n,c=T.convertConv2DDataFormat(l),d=T.computeConv2DInfo(r.shape,p,i,1,o,u,!1,c),h=new vj(d);return a.runWebGLProgram(h,[r,s],"float32")}var Tj={kernelName:Xc,backendName:"webgl",kernelFunc:Sj};function Cj(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:p}=n,c=T.convertConv2DDataFormat(u),d=T.computeConv2DInfo(i,s.shape,o,1,l,p,!1,c),h=new wj(d);return a.runWebGLProgram(h,[r,s],"float32")}var Nj={kernelName:ri,backendName:"webgl",kernelFunc:Cj};function Ej(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=n,u=T.computeConv3DInfo(r.shape,s.shape,i,l,o),p=new xj(u);return a.runWebGLProgram(p,[r,s],"float32")}var Rj={kernelName:Kc,backendName:"webgl",kernelFunc:Ej};function Mj(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=n,u=T.computeConv3DInfo(r.shape,l,i,1,o),p=new kj(u);return a.runWebGLProgram(p,[r,s],"float32")}var $j={kernelName:H1,backendName:"webgl",kernelFunc:Mj};function _j(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=n,u=T.computeConv3DInfo(l,s.shape,o,1,i),p=new Ij(u);return a.runWebGLProgram(p,[r,s],"float32")}var Pj={kernelName:Zc,backendName:"webgl",kernelFunc:_j},Fj=mu+`
return cos(x);
`,Oj=Qe({opSnippet:Fj}),Dj={kernelName:si,backendName:"webgl",kernelFunc:Oj},zj=`
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`,Lj=Qe({opSnippet:zj}),Bj={kernelName:ii,backendName:"webgl",kernelFunc:Lj},Wj=class{constructor(e,t,a,n,r){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[s,i,o,l]=e,[u]=t,[p,c]=a;this.outputShape=[u,p,c,l];let d=n==="bilinear"?1:0,[h,f]=[`${i-1}.0`,`${o-1}.0`],[m,g,x]=p>1?[`${(i-1)/(p-1)}`,"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${h}`],[A,y,b]=c>1?[`${(o-1)/(c-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(${A});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int y = coords[1];
int x = coords[2];
int d = coords[3];
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
// get image in batch index
int bInd = round(getBoxInd(b));
if(bInd < 0 || bInd >= ${s}) {
return;
}
float height_scale = ${g};
float width_scale = ${y};
float in_y = ${x};
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);
}
}
`}},Vj=e=>{let{inputs:t,backend:a,attrs:n}=e,{image:r,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=n,p=new Wj(r.shape,s.shape,o,l,u);return a.runWebGLProgram(p,[r,s,i],"float32")},Uj={kernelName:ui,backendName:"webgl",kernelFunc:Vj},Ad;(function(e){e.Prod="*",e.Sum="+"})(Ad||(Ad={}));var Tx=class{constructor(e,t,a,n){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];let r=this.outputShape.length,s=this.op===Ad.Prod?"1.0":"0.0",i=a?s:`getX(${Cx(r,"coords",this.op)})`,o=this.outputShape[this.outputShape.length-1],l="",u="";a?(l=n?`end != ${o-1}`:"end != 0",u=n?"end + 1":"end - 1"):(l=n?`end + pow2 < ${o}`:"end >= pow2",u=n?"end + pow2":"end - pow2"),this.userCode=`
void main() {
${gt(r)} coords = getOutputCoords();
int end = ${Nx(r,"coords",this.op)};
float val = ${i};
int pow2 = int(pow(2.0, index));
if (${l}) {
int idx = ${u};
${Nx(r,"coords",this.op)} = idx;
val ${this.op}= getX(${Cx(r,"coords",this.op)});
}
setOutput(val);
}
`}};function Cx(e,t,a){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 ${a} for rank ${e} is not yet supported`)}function Nx(e,t,a){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 ${a} for rank ${e} is not yet supported`)}function iv(e,t,a,n,r,s){let i=t.shape.length,o=T.getAxesPermutation([n],i),l=t;o!=null&&(l=Ia({inputs:{x:t},backend:a,attrs:{perm:o}}));let u=T.getInnerMostAxes(1,i)[0];if(u!==i-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${n}`);let p=l.shape[u],c=Za({inputs:{x:l},backend:a});for(let d=0;d<=Math.ceil(Math.log2(p))-1;d++){let h=new Tx(e,l.shape,!1,s),f=[[d]],m=c;c=a.runWebGLProgram(h,[c],c.dtype,f),a.disposeIntermediateTensorInfo(m)}if(r){let d=new Tx(e,l.shape,r,s),h=c;c=a.runWebGLProgram(d,[c],c.dtype),a.disposeIntermediateTensorInfo(h)}if(o!=null){let d=T.getUndoAxesPermutation(o),h=Ia({inputs:{x:c},backend:a,attrs:{perm:d}});return a.disposeIntermediateTensorInfo(c),a.disposeIntermediateTensorInfo(l),h}return c}function Gj(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=n;return iv(Ad.Prod,r,a,s,i,o)}var Hj={kernelName:oi,backendName:"webgl",kernelFunc:Gj};function jj(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=n;return iv(Ad.Sum,r,a,s,i,o)}var qj={kernelName:li,backendName:"webgl",kernelFunc:jj};function Xj(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,weights:s}=t,{size:i,binaryOutput:o}=n;if(r.shape.length===1){let l=a.readSync(r.dataId),u=a.readSync(s.dataId),p=L6(l,u,s.dtype,s.shape,i);return a.makeTensorInfo([i],s.dtype,p)}else if(r.shape.length===2){let l=a.bufferSync(r),u=a.bufferSync(s),p=rU(l,u,i,o);return a.makeTensorInfo(p.shape,s.dtype,p.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}var Kj={kernelName:Td,backendName:"webgl",kernelFunc:Xj},Zj=class{constructor(e,t,a){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=a,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 Yj(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{blockSize:s,dataFormat:i}=n,o=r.shape[0],l=i==="NHWC"?r.shape[1]:r.shape[2],u=i==="NHWC"?r.shape[2]:r.shape[3],p=i==="NHWC"?r.shape[3]:r.shape[1],c=l*s,d=u*s,h=p/(s*s),f=i==="NHWC"?[o,c,d,h]:[o,h,c,d],m=new Zj(f,s,i);return a.runWebGLProgram(m,[r],r.dtype)}var Jj={kernelName:di,backendName:"webgl",kernelFunc:Yj},ov=class{constructor(e,t=!1,a=null,n=!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=Na(this.outputShape.length);let s=e.filterHeight,i=e.filterWidth,o=e.outChannels/e.inChannels,l="",u="";a&&(n?l=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${a}
}`:r?l=`float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${a}
}`:l=`
float activation(float x) {
${a}
}
`,u="result = activation(result);");let p=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&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 / ${o};
int q = d2 - d1 * ${o};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
for (int wR = 0; wR < ${s}; wR++) {
int xR = xRCorner + wR * dilations[0];
if (xR < 0 || xR >= inDims[0]) {
continue;
}
for (int wC = 0; wC < ${i}; wC++) {
int xC = xCCorner + wC * dilations[1];
if (xC < 0 || xC >= inDims[1]) {
continue;
}
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
float result = dotProd;
${p}
${u}
setOutput(result);
}
`}},lv=class{constructor(e,t=!1,a=null,n=!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=Na(this.outputShape.length);let s=e.outChannels/e.inChannels,i=e.padInfo.left,o=e.strideWidth,l=e.dilationWidth,u=e.filterHeight,p=e.filterWidth,c=p,d=`
int xR; int xC; int xCOffset;
vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<p;g++)d+=`
vec4 xTexelC${g*2};
int xTexelC${g*2}Ready;
vec4 xTexelC${g*2+1};
int xTexelC${g*2+1}Ready;
vec4 xC${g};`;d+=`
for (int r = 0; r < ${u}; r++) {
`;for(let g=0;g<p;g++)d+=`
xTexelC${g*2} = vec4(0.0);
xTexelC${g*2}Ready = 0;
xTexelC${g*2+1} = vec4(0.0);
xTexelC${g*2+1}Ready = 0;
xC${g} = vec4(0.0);`;d+=`
xR = xRCorner + r * dilations[0];
if (xR >=0 && xR < inDims[0]) {
`;for(let g=0;g<(c+1)/2;g++){let x=g*2;if(d+=`
xC = xCCorner + ${x*l};
`,o===1){if(x<p&&(i%2===1?(d+=`
xCOffset = xC + 1;
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x}Ready == 0) {
xTexelC${x} = 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${x}.zw = vec2(0.0);
}
xTexelC${x}Ready = 1;
}
`,l===1&&x>0?d+=`
xC${x} = vec4(xTexelC${x-2}.zw, xTexelC${x}.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${x} = vec4(previous.zw, xTexelC${x}.xy);
} else {
xC${x} = vec4(0.0, 0.0, xTexelC${x}.xy);
}
`):d+=`
if (xC >= 0 && xC < inDims[1] && xTexelC${x}Ready == 0) {
xTexelC${x} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${x}.zw = vec2(0.0);
}
xTexelC${x}Ready = 1;
}
xC${x} = xTexelC${x};
`,x+1<p)){let A=i%2===0?v.nearestLargerEven(l):l;l%2===0&&i%2===1||l%2!==0&&i%2!==1?(d+=`
xCOffset = xC + imod(pads[1], 2) + ${A};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) {
xTexelC${x+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${x+1}.zw = vec2(0.0);
}
xTexelC${x+1}Ready = 1;
}
`,l>1?d+=`
xCOffset -= 2;
if (xCOffset >= 0 && xCOffset < inDims[1]) {
previous = getX(batch, xR, xCOffset, d1);
xC${x+1} = vec4(previous.zw, xTexelC${x+1}.xy);
} else {
xC${x+1} = vec4(0.0, 0.0, xTexelC${x+1}.xy);
}
`:d+=`
xC${x+1} = vec4(xTexelC${x}.zw, xTexelC${x+1}.xy);
`):A===1?d+=`
xC${x+1} = xTexelC${x};
`:d+=`
xCOffset = xC + ${A};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) {
xTexelC${x+1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${x+1}.zw = vec2(0.0);
}
xTexelC${x+1}Ready = 1;
}
xC${x+1} = xTexelC${x+1};
`}}else x<p&&(i%2===1?(d+=`
xCOffset = xC + 1 - strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x}Ready == 0) {
xTexelC${x} = 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${x}.zw = vec2(0.0);
}
xTexelC${x}Ready = 1;
}
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${x+1}Ready == 0) {
xTexelC${x+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${x+1}.zw = vec2(0.0);
}
xTexelC${x+1}Ready = 1;
}
xC${x} = vec4(xTexelC${x}.zw, xTexelC${x+1}.zw);
`,x+1<p&&(d+=`
final = vec4(0.0);
xCOffset = xC + 1 + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1]) {
final = getX(batch, xR, xCOffset, d1);
}
xC${x+1} = vec4(xTexelC${x+1}.xy, final.xy);
`)):(d+=`
if(xC >= 0 && xC < inDims[1] && xTexelC${x}Ready == 0) {
xTexelC${x} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${x}.zw = vec2(0.0);
}
xTexelC${x}Ready = 1;
}
xCOffset = xC + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) {
xTexelC${x+1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${x+1}.zw = vec2(0.);
}
xTexelC${x+1}Ready = 1;
}
xC${x} = vec4(
xTexelC${x}.xy, xTexelC${x+1}.xy);
`,x+1<p&&(d+=`
xC${x+1} = vec4(xTexelC${x}.zw, xTexelC${x+1}.zw);
`)));x<p&&(d+=`
wTexel = getW(r, ${x}, d1, q);
dotProd += xC${x} * vec4(wTexel.xz, wTexel.xz);
`,x+1<p&&(d+=`
wTexel = getW(r, ${x+1}, d1, q);
dotProd += xC${x+1} * vec4(wTexel.xz, wTexel.xz);
`))}d+=`
}
`,d+=`
}
`;let h="",f="";a&&(n?h=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${a}
}`:r?h=`vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${a}
}`:h=`vec4 activation(vec4 x) {
${a}
}`,f="result = activation(result);");let m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${h}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${s};
int q = d2 - d1 * ${s};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
vec4 dotProd = vec4(0.000000000000001);
${d}
vec4 result = dotProd - vec4(0.000000000000001);
${m}
${f}
setOutput(result);
}
`}};function Qj(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=n,p=l;p==null&&(p=[1,1]),v.assert(T.eitherStridesOrDilationsAreOne(i,p),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${p}'`);let c=T.computeConv2DInfo(r.shape,s.shape,i,p,o,u,!0),d;W().getBool("WEBGL_PACK_DEPTHWISECONV")&&c.strideWidth<=2&&c.outChannels/c.inChannels===1?d=new lv(c):d=new ov(c);let h=[[c.padInfo.top,c.padInfo.left],[c.strideHeight,c.strideWidth],[c.dilationHeight,c.dilationWidth],[c.inHeight,c.inWidth]];return a.runWebGLProgram(d,[r,s],"float32",h)}var eq={kernelName:pi,backendName:"webgl",kernelFunc:Qj},tq=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,a=e.strideWidth,n=e.padInfo.top,r=e.padInfo.left,s=e.outChannels/e.inChannels;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int dm = coords.w;
int d2 = d1 * ${s} + dm;
float dotProd = 0.0;
// TO DO: Vec4 over the batch size
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${n};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${a} - ${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);
}
`}},aq=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,a=e.filterWidth,n=e.strideHeight,r=e.strideWidth,s=t-1-e.padInfo.top,i=a-1-e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=`
const ivec2 pads = ivec2(${s}, ${i});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[3];
ivec2 dyCorner = coords.yz - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
for (int wC = 0; wC < ${a}; 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 = ${a} - 1 - wC;
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < ${o}; dm++) {
int d2 = d1 * ${o} + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
`}};function nq(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:p}=n,c=T.computeConv2DInfo(r.shape,p,i,o,l,u,!0),d=new tq(c);return a.runWebGLProgram(d,[r,s],"float32")}var rq={kernelName:Yc,backendName:"webgl",kernelFunc:nq};function sq(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:p}=n,c=T.computeConv2DInfo(p,s.shape,i,o,l,u,!0),d=new aq(c);return a.runWebGLProgram(d,[r,s],"float32")}var iq={kernelName:Jc,backendName:"webgl",kernelFunc:sq},oq=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 lq(e){let{inputs:t,backend:a}=e,{x:n}=t,r=[...n.shape,...n.shape],s=v.sizeFromShape(n.shape),i=ce({inputs:{x:n},backend:a,attrs:{shape:[s]}}),o=new oq(s),l=a.runWebGLProgram(o,[i],i.dtype),u=ce({inputs:{x:l},backend:a,attrs:{shape:r}});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(l),u}var uq={kernelName:Qc,backendName:"webgl",kernelFunc:lq},dq=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:a,padInfo:n,strideHeight:r,strideWidth:s,filterHeight:i,filterWidth:o,dilationHeight:l,dilationWidth:u}=e,{top:p,left:c}=n;this.userCode=`
const ivec2 strides = ivec2(${r}, ${s});
const ivec2 pads = ivec2(${p}, ${c});
const float neg_infinity = -3.4e38;
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.w;
ivec2 outTopLeftCorner =
coords.yz * strides - pads;
int hBeg = outTopLeftCorner.x;
int wBeg = outTopLeftCorner.y;
float curVal = neg_infinity;
for (int h = 0; h < ${i}; h++) {
int hIn = hBeg + h * ${l};
if (hIn >= 0 && hIn < ${t}) {
for (int w = 0; w < ${o}; w++) {
int wIn = wBeg + w * ${u};
if (wIn >= 0 && wIn < ${a}) {
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 pq(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=n,u=T.computeDilation2DInfo(r.shape,s.shape,i,o,"NHWC",l),p,c=new dq(u);p=a.runWebGLProgram(c,[r,s],"float32");let d=ce({inputs:{x:p},backend:a,attrs:{shape:u.outShape}});return a.disposeIntermediateTensorInfo(p),d}var cq={kernelName:eh,backendName:"webgl",kernelFunc:pq};function hq(e){let{inputs:t,backend:a,attrs:n}=e,{equation:r}=n,s=t,{allDims:i,summedDims:o,idDims:l}=T.decodeEinsumEquation(r,s.length);T.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:p}=T.getEinsumComputePath(o,l),c=p.length,d=null,h=i.length,f=[];for(let m=0;m<c;++m){for(let g of p[m]){let{permutationIndices:x,expandDims:A}=T.getEinsumPermutation(h,l[g]),y;T.isIdentityPermutation(x)?y=s[g]:(y=Ia({inputs:{x:s[g]},backend:a,attrs:{perm:x}}),f.push(y));let b=y.shape.slice();for(let w=0;w<A.length;++w)b.splice(A[w],0,1);v.arraysEqual(y.shape,b)||(y=ce({inputs:{x:y},backend:a,attrs:{shape:b}}),f.push(y)),d===null?d=y:(d=M3({inputs:{a:y,b:d},backend:a}),f.push(d))}m<c-1&&(u[m]>=0&&(d=zh({inputs:{x:d},backend:a,attrs:{axis:u[m]-(i.length-h),keepDims:!1}}),f.push(d)),h--)}for(let m of f)m!==d&&a.disposeIntermediateTensorInfo(m);return d}var fq={kernelName:Cd,backendName:"webgl",kernelFunc:hq},mq="return (x >= 0.0) ? x : (exp(x) - 1.0);",gq=`
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;
`,xq=Qe({opSnippet:mq,packedOpSnippet:gq}),Aq={kernelName:hi,backendName:"webgl",kernelFunc:xq},yq="return (b >= 1.0) ? a : a * (b + 1.0);",bq=`
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`,vq=e=>{let{inputs:t,backend:a}=e,{dy:n,y:r}=t,s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new cp(bq,n.shape,r.shape):new Al(yq,n.shape,r.shape);return a.runWebGLProgram(s,[n,r],n.dtype)},wq={kernelName:j1,backendName:"webgl",kernelFunc:vq},kq=`
return vec4(equal(a, b));
`,Iq="return float(a == b);",Sq=oa({opSnippet:Iq,packedOpSnippet:kq,dtype:"bool",cpuKernelImpl:lU}),Tq={kernelName:fi,backendName:"webgl",kernelFunc:Sq},Cq=`
// 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));
`,Nq=Qe({opSnippet:Cq}),Eq={kernelName:$l,backendName:"webgl",kernelFunc:Nq},Rq=mu+`
return exp(x);
`,Mq=`
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;
`,uv=Qe({opSnippet:Rq,packedOpSnippet:Mq,cpuKernelImpl:uU,dtype:"float32"}),$q={kernelName:mi,backendName:"webgl",kernelFunc:uv};function N1(e){let{inputs:t,attrs:a,backend:n}=e,{dim:r}=a,{input:s}=t,i=s.shape.length,o=s.shape.slice(),l=r;return r<0&&(v.assert(-(i+1)<=r,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+r+1),o.splice(l,0,1),ce({inputs:{x:s},backend:n,attrs:{shape:o}})}var _q={kernelName:_l,backendName:"webgl",kernelFunc:N1},Ex="return exp(x) - 1.0;",Pq=Qe({opSnippet:Ex,packedOpSnippet:Ex,cpuKernelImpl:dU}),Fq={kernelName:Pl,backendName:"webgl",kernelFunc:Pq},Rx=class{constructor(e,t,a){this.variableNames=["real","imag"];let n=t[1];this.outputShape=t;let r=a?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,s=a?`${n}.0`:"1.0",i;if(e==="real")i="return real * expR - imag * expI;";else if(e==="imag")i="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=`
const float exponentMultiplier = ${r};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${i}
}
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${n});
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
for (int i = 0; i < ${n}; i++) {
// x = (-2|2 * PI / N) * index * i;
float x = exponentMultiplierTimesIndexRatio * float(i);
float expR = cos(x);
float expI = sin(x);
float real = getReal(batch, i);
float imag = getImag(batch, i);
result +=
unaryOpComplex(real, expR, imag, expI) / ${s};
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
`}};function dv(e,t,a){let n=a.texData.get(e.dataId),r=v.sizeFromShape(e.shape),s=e.shape[e.shape.length-1],i=r/s,o=ce({inputs:{x:e},backend:a,attrs:{shape:[i,s]}}),l=o.shape,u=new Rx("real",l,t),p=new Rx("imag",l,t),c=[{dataId:n.complexTensorInfos.real.dataId,dtype:n.complexTensorInfos.real.dtype,shape:l},{dataId:n.complexTensorInfos.imag.dataId,dtype:n.complexTensorInfos.imag.dtype,shape:l}],d=a.runWebGLProgram(u,c,"float32"),h=a.runWebGLProgram(p,c,"float32"),f=ls({inputs:{real:d,imag:h},backend:a});a.disposeIntermediateTensorInfo(d),a.disposeIntermediateTensorInfo(h);let m=ce({inputs:{x:f},backend:a,attrs:{shape:e.shape}});return a.disposeIntermediateTensorInfo(o),a.disposeIntermediateTensorInfo(f),m}function Oq(e){let{inputs:t,backend:a}=e,{input:n}=t;return dv(n,!1,a)}var Dq={kernelName:Nd,backendName:"webgl",kernelFunc:Oq},zq=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 fp(e){let{backend:t,attrs:a}=e,{shape:n,value:r}=a,{dtype:s}=a;if(s=s||v.inferDtype(r),s==="string"){let i=v.getArrayFromDType(s,v.sizeFromShape(n));return i.fill(r),t.makeTensorInfo(n,s,i)}else{let i=new zq(n,r),o=[[r]];return t.runWebGLProgram(i,[],s,o)}}var Lq={kernelName:Fl,backendName:"webgl",kernelFunc:fp},Bq=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);
}
`}},Wq={kernelName:gi,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:a}=e,n=t,r=new Bq(a.shape);return n.runWebGLProgram(r,[a],a.dtype)}},Mx="return floor(x);",Vq=Qe({opSnippet:Mx,packedOpSnippet:Mx,cpuKernelImpl:pU}),Uq={kernelName:xi,backendName:"webgl",kernelFunc:Vq},Gq=`
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;
}
`,Hq=`
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);
`,jq=oa({opSnippet:Gq,packedOpSnippet:Hq,dtype:"int32"}),qq={kernelName:Ai,backendName:"webgl",kernelFunc:jq},Xq=class{constructor(e){this.variableNames=["A"];let t=Ca(),[a,n]=e;this.outputShape=e,this.userCode=`
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${n}.0, ${a}.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));
}
`}},Kq=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=Ca(),[a,n]=e;this.outputShape=e,this.userCode=`
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec4 result = vec4(0.);
for(int row=0; row<=1; row++) {
for(int col=0; col<=1; col++) {
texC = coords[1] + row;
depth = coords[2] + col;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${n}.0, ${a}.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;
}
`}},Zq={kernelName:rd,backendName:"webgl",kernelFunc:Yq},Zo,Lm=W().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function Yq(e){let{inputs:t,backend:a,attrs:n}=e,{pixels:r}=t,{numChannels:s}=n,i=typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement,o=typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement,[l,u]=i?[r.videoWidth,r.videoHeight]:[r.width,r.height],p=[u,l],c=[u,l,s];if(o||i){let m=W().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(Zo==null||m!==Lm)&&(Lm=m,Zo=document.createElement("canvas").getContext("2d",{willReadFrequently:Lm})),Zo.canvas.width=l,Zo.canvas.height=u,Zo.drawImage(r,0,0,l,u),r=Zo.canvas}let d=a.makeTensorInfo(p,"int32");a.texData.get(d.dataId).usage=pn.PIXELS,a.gpgpu.uploadPixelDataToTexture(a.getTexture(d.dataId),r);let h=W().getBool("WEBGL_PACK")?new Kq(c):new Xq(c),f=a.runWebGLProgram(h,[d],"int32");return a.disposeData(d.dataId),f}function Jq(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:p,dilations:c,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=n,m=T.convertConv2DDataFormat(p),g=T.computeConv2DInfo(r.shape,s.shape,l,c,u,d,!1,m),x,A=[],y=i!=null,b=o!=null,w=h==="leakyrelu",S=()=>{let E=[r,s],_=($,M)=>{if(M==="NCHW"&&$.shape.length===1&&$.shape[0]!==1){let I=ce({inputs:{x:$},backend:a,attrs:{shape:[$.shape[0],1,1]}});return A.push(I),I}return $};if(y&&E.push(_(i,p)),b&&E.push(_(o,p)),w){let $=a.makeTensorInfo([],"float32",v.createScalarValue(f,"float32"));E.push($),A.push($)}return E};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"))x=rv({x:r,filter:s,convInfo:g,backend:a,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:f});else if(g.strideWidth<=2&&m==="channelsLast"&&W().getBool("WEBGL_EXP_CONV")){let E=h?gd(h,!0):null,_=new nv(g,y,E,b,w),$=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],M=S();x=a.runWebGLProgram(_,M,"float32",$)}else if(W().getBool("WEBGL_CONV_IM2COL"))x=sv({x:r,filter:s,convInfo:g,backend:a,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:f});else{let E=h?gd(h,!1):null,_=new av(g,y,E,b,w),$=S();x=a.runWebGLProgram(_,$,"float32")}let C=ce({inputs:{x},backend:a,attrs:{shape:g.outShape}});return A.push(x),A.forEach(E=>a.disposeIntermediateTensorInfo(E)),C}var Qq={kernelName:qr,backendName:"webgl",kernelFunc:Jq};function eX(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:p,dimRoundingMode:c,activation:d,leakyreluAlpha:h}=n,f=[],m=p;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,s.shape,l,m,u,c,!0),x=W().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,A=d?gd(d,x):null,y=[r,s],b=i!=null,w=o!=null,S=d==="leakyrelu";if(b&&y.push(i),w&&y.push(o),S){let $=a.makeTensorInfo([],"float32",v.createScalarValue(h,"float32"));y.push($),f.push($)}let C;x?C=new lv(g,b,A,w,S):C=new ov(g,b,A,w,S);let E=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],_=a.runWebGLProgram(C,y,"float32",E);return f.forEach($=>a.disposeIntermediateTensorInfo($)),_}var tX={kernelName:Xr,backendName:"webgl",kernelFunc:eX},aX=class{constructor(e,t,a,n){this.sliceDim=e,this.strides=t,this.paramsShape=n,this.variableNames=["x","indices"],this.outputShape=a;let r=gt(a.length),s=`
int index;`;for(let i=0;i<this.sliceDim;i++)s+=`
index = round(getIndices(coords[0], ${i}));
out_of_bounds = out_of_bounds || index < 0;
out_of_bounds = out_of_bounds || index >= ${this.paramsShape[i]};
flattenIndex += index * ${this.strides[i]};`;this.userCode=`
void main() {
${r} coords = getOutputCoords();
int flattenIndex = 0;
bool out_of_bounds = false;
${s}
setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));
}
`}};function nX(e){let{inputs:t,backend:a}=e,{params:n,indices:r}=t,s=r.shape,i=s[s.length-1],o=v.sizeFromShape(n.shape),[l,u,p,c]=T.prepareAndValidate(n,r),d=ce({inputs:{x:r},backend:a,attrs:{shape:[u,i]}}),h=ce({inputs:{x:n},backend:a,attrs:{shape:[v.sizeFromShape(n.shape)/p,p]}});if(a.shouldExecuteOnCPU([n,r])||n.dtype==="string"){let x=a.readSync(r.dataId),A=a.bufferSync(n),y=cU(x,A,n.dtype,u,i,p,c,n.shape,o);return a.makeTensorInfo(l,n.dtype,y.values)}let f=new aX(i,c,[u,p],n.shape),m=a.runWebGLProgram(f,[h,d],h.dtype),g=ce({inputs:{x:m},backend:a,attrs:{shape:l}});return a.disposeIntermediateTensorInfo(d),a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(m),g}var rX={kernelName:bi,backendName:"webgl",kernelFunc:nX},sX=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let a=gt(this.rank),n=iX(e,2);this.userCode=`
void main() {
${a} resRC = getOutputCoords();
int index = int(getIndices(resRC.x, resRC.z));
float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;
setOutput(inBounds * getA(${n}));
}
`}};function iX(e,t){let a=["resRC.x","resRC.y","resRC.z","resRC.w"],n=[];for(let r=0;r<e.length;r++)r===2?n.push("index"):n.push(`${a[r]}`);return n.join()}function pv(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,indices:s}=t,{axis:i,batchDims:o}=n,l=v.parseAxisParam(i,r.shape)[0];if(W().get("DEBUG")){let A=a.readSync(s.dataId),y=r.shape[l];for(let b=0;b<A.length;++b){let w=A[b];v.assert(w<=y-1&&w>=0,()=>`GatherV2: the index value ${w} is not in [0, ${y-1}]`)}}let u=T.segment_util.collectGatherOpShapeInfo(r,s,l,o),p=v.sizeFromShape(s.shape),c=[],d=ce({inputs:{x:r},backend:a,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),h=ce({inputs:{x:s},backend:a,attrs:{shape:[u.batchSize,p/u.batchSize]}});c.push(d),c.push(h);let f=[u.batchSize,u.outerSize,p/u.batchSize,u.sliceSize];if(a.shouldExecuteOnCPU([r,s])||r.dtype==="string"){let A=a.bufferSync(h),y=a.bufferSync(d),b=hU(y,A,f);return c.forEach(w=>a.disposeIntermediateTensorInfo(w)),a.makeTensorInfo(u.outputShape,b.dtype,b.values)}let m=new sX(d.shape,f),g=a.runWebGLProgram(m,[d,h],d.dtype);c.push(g);let x=ce({inputs:{x:g},backend:a,attrs:{shape:u.outputShape}});return c.forEach(A=>a.disposeIntermediateTensorInfo(A)),x}var oX={kernelName:Ol,backendName:"webgl",kernelFunc:pv},lX="return float(a > b);",uX=`
return vec4(greaterThan(a, b));
`,dX=oa({opSnippet:lX,packedOpSnippet:uX,cpuKernelImpl:fU,dtype:"bool"}),pX={kernelName:vi,backendName:"webgl",kernelFunc:dX},cX="return float(a >= b);",hX=`
return vec4(greaterThanEqual(a, b));
`,fX=oa({opSnippet:cX,packedOpSnippet:hX,dtype:"bool",cpuKernelImpl:mU}),mX={kernelName:wi,backendName:"webgl",kernelFunc:fX};function gX(e){let{inputs:t,backend:a}=e,{input:n}=t;return dv(n,!0,a)}var xX={kernelName:Ed,backendName:"webgl",kernelFunc:gX},AX="return float(!isnan(x) && !isinf(x));",yX=Qe({opSnippet:AX,dtype:"bool"}),bX={kernelName:Dl,backendName:"webgl",kernelFunc:yX},vX="return float(isinf(x));",wX=Qe({opSnippet:vX,dtype:"bool"}),kX={kernelName:zl,backendName:"webgl",kernelFunc:wX},IX="return float(isnan(x));",SX=Qe({opSnippet:IX,dtype:"bool"}),TX={kernelName:Ii,backendName:"webgl",kernelFunc:SX},CX="return float(a < b);",NX=`
return vec4(lessThan(a, b));
`,EX=oa({opSnippet:CX,packedOpSnippet:NX,cpuKernelImpl:gU,dtype:"bool"}),RX={kernelName:Ti,backendName:"webgl",kernelFunc:EX},MX="return float(a <= b);",$X=`
return vec4(lessThanEqual(a, b));
`,_X=oa({opSnippet:MX,packedOpSnippet:$X,cpuKernelImpl:xU,dtype:"bool"}),PX={kernelName:Ci,backendName:"webgl",kernelFunc:_X};function FX(e){let{backend:t,attrs:a}=e,{start:n,stop:r,num:s}=a,i=AU(n,r,s);return t.makeTensorInfo([i.length],"float32",i)}var OX={kernelName:th,backendName:"webgl",kernelFunc:FX},DX=mu+`
return x < 0.0 ? 0./0. : log(x);
`,zX=`
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;
`,LX=Qe({opSnippet:DX,packedOpSnippet:zX,cpuKernelImpl:yU}),BX={kernelName:Ni,backendName:"webgl",kernelFunc:LX},WX=mu+`
return log(1.0 + x);
`,VX=Qe({opSnippet:WX}),UX={kernelName:Ll,backendName:"webgl",kernelFunc:VX},GX="return float(a >= 1.0 && b >= 1.0);",HX=`
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`,jX=oa({opSnippet:GX,packedOpSnippet:HX,dtype:"bool"}),qX={kernelName:Ei,backendName:"webgl",kernelFunc:jX},XX="return float(!(x >= 1.0));",KX=Qe({opSnippet:XX}),ZX={kernelName:Ri,backendName:"webgl",kernelFunc:KX},YX="return float(a >= 1.0 || b >= 1.0);",JX=`
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`,QX=oa({opSnippet:YX,packedOpSnippet:JX,dtype:"bool"}),eK={kernelName:Bl,backendName:"webgl",kernelFunc:QX},tK=class{constructor(e,t,a,n,r){this.variableNames=["x"],this.outputShape=[];let s=t,i=e[3]-1;this.outputShape=e;let o,l=`float(${a}) + float(${n}) * sum`;r===.5?o=`inversesqrt(${l})`:r===1?o=`1.0/(${l})`:o=`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 = -${s}; j <= ${s}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${i}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
}
float val = x * ${o};
setOutput(val);
}
`}},aK=class{constructor(e,t,a,n,r){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let s=t,i=e[3]-1;this.outputShape=e;let o,l=`float(${a}) + float(${n}) * sum`;r===.5?o=`inversesqrt(${l})`:r===1?o=`1.0/(${l})`:o=`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 - ${s};
vec2 cache = vec2(0.);
if(firstChannel >= 0){
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
if(hasNextRow){
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
}
}
ivec2 depth = ivec2(d, d + 1);
for (int j = - ${s}; j <= ${s}; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${i}));
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
if(depthInRange || depthPlusOneInRange){
vec4 z = vec4(0.);
vec4 xFragAtCurrentDepth;
z.xz = cache.xy;
if(depthPlusOneInRange && hasNextCol){
xFragAtCurrentDepth = idx.y != d ?
getX(b, r, c, idx.y) : xFragAtOutputCoords;
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
if(hasNextRow){
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
}
}
cache.xy = z.yw;
sum += z * z;
}
}
vec4 result = xAtOutputCoords * ${o};
setOutput(result);
}
`}},nK=e=>{let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n,u=W().getBool("WEBGL_PACK_NORMALIZATION")?new aK(r.shape,s,i,o,l):new tK(r.shape,s,i,o,l);return a.runWebGLProgram(u,[r],r.dtype)},rK={kernelName:ah,backendName:"webgl",kernelFunc:nK},sK=class{constructor(e,t,a,n,r){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=a,this.alpha=n,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(${n}) * norm + float(${a});
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd){
float dyi = -2.0 * float(${n})
* float(${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);
}
`}},iK=e=>{let{inputs:t,backend:a,attrs:n}=e,{x:r,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:p}=n,c=new sK(r.shape,o,l,u,p);return a.runWebGLProgram(c,[r,s,i],r.dtype)},oK={kernelName:q1,backendName:"webgl",kernelFunc:iK};function lK(e,t,a,n){let r=v.sizeFromShape(t),s=v.sizeFromShape(e.shape)/r,i=ce({inputs:{x:e},attrs:{shape:[s,r]},backend:n}),o=bo(i,e.dtype,"max",n),l=ce({inputs:{x:o},attrs:{shape:a},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}function cv(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{reductionIndices:s,keepDims:i}=n,o=r.shape.length,l=v.parseAxisParam(s,r.shape),u=l,p=T.getAxesPermutation(u,o),c=p!=null,d=a.shouldExecuteOnCPU([r]),h=r;if(c){if(d){let A=a.texData.get(h.dataId).values,y=new Array(o);for(let S=0;S<y.length;S++)y[S]=r.shape[p[S]];let b=E3(A,r.shape,r.dtype,p,y);h=a.makeTensorInfo(y,r.dtype);let w=a.texData.get(h.dataId);w.values=b}else h=Dh(r,p,a);u=T.getInnerMostAxes(u.length,o)}T.assertAxesAreInnerMostDims("max",u,o);let[f,m]=T.computeOutAndReduceShapes(h.shape,u),g=f;i&&(g=T.expandShapeToKeepDim(f,l));let x;if(d){let A=a.texData.get(h.dataId).values,y=bU(A,v.sizeFromShape(m),g,r.dtype);x=a.makeTensorInfo(g,r.dtype);let b=a.texData.get(x.dataId);b.values=y}else x=lK(h,m,g,a);return c&&a.disposeIntermediateTensorInfo(h),x}var uK={kernelName:Mi,backendName:"webgl",kernelFunc:cv},dK=R3+`
return max(a, b);
`,pK=`
vec4 result = vec4(max(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);
`+pp+`
return result;
`,cK=oa({opSnippet:dK,packedOpSnippet:pK,cpuKernelImpl:vU}),hK={kernelName:$i,backendName:"webgl",kernelFunc:cK};function fK(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t;uu(r,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1;v.assert(T.eitherStridesOrDilationsAreOne(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=T.computePool2DInfo(r.shape,s,i,u,o,l);if(p.filterWidth===1&&p.filterHeight===1&&v.arraysEqual(p.inShape,p.outShape))return Za({inputs:{x:r},backend:a});let c=new xd(p,"max",!1);return a.runWebGLProgram(c,[r],r.dtype)}var mK={kernelName:_i,backendName:"webgl",kernelFunc:fK};function gK(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dataFormat:l,dimRoundingMode:u}=n,p=[1,1,1],c=T.computePool3DInfo(r.shape,s,i,p,o,u,l),d=new $3(c,"max",!1);return a.runWebGLProgram(d,[r],r.dtype)}var xK={kernelName:nh,backendName:"webgl",kernelFunc:gK},AK=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,a=e.strideWidth,n=e.dilationHeight,r=e.effectiveFilterHeight,s=e.effectiveFilterWidth,i=r-1-e.padInfo.top,o=s-1-e.padInfo.left,l=r*s-1;this.userCode=`
const ivec2 pads = ivec2(${i}, ${o});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${r};
wR += ${n}) {
float dyR = float(dyRCorner + wR) / ${t}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${s}; wC++) {
float dyC = float(dyCCorner + wC) / ${a}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
int maxPosValue = ${l} - int(getMaxPos(b, idyR, idyC, d));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${s} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
`}},yK=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,a=e.strideHeight,n=e.strideWidth,r=e.dilationDepth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterDepth,l=e.effectiveFilterHeight,u=e.effectiveFilterWidth,p=o-1-e.padInfo.front,c=l-1-e.padInfo.top,d=u-1-e.padInfo.left,h=o*l*u-1;this.userCode=`
const ivec3 pads = ivec3(${p}, ${c}, ${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 < ${o};
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 += ${s}) {
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 < ${u};
wC += ${i}) {
float dyC = float(dyCCorner + wC) / ${n}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
int maxPosValue = ${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 bK(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:p}=n,c=[1,1,1],d=T.computePool3DInfo(i.shape,o,l,c,u,p),h=new $3(d,"max",!0),f=a.runWebGLProgram(h,[i],i.dtype),m=new yK(d),g=a.runWebGLProgram(m,[r,f],i.dtype);return a.disposeIntermediateTensorInfo(f),g}var vK={kernelName:K1,backendName:"webgl",kernelFunc:bK};function wK(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s,output:i}=t,o=s;uu([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:p,dimRoundingMode:c}=n,d=T.computePool2DInfo(o.shape,l,u,1,p,c),h=!0,f=new xd(d,"max",h),m=a.runWebGLProgram(f,[o],o.dtype),g=new AK(d),x=a.runWebGLProgram(g,[r,m],o.dtype);return a.disposeIntermediateTensorInfo(m),x}var kK={kernelName:X1,backendName:"webgl",kernelFunc:wK};function IK(e,t,a,n){let r=new xd(a,"max",!1),s=n.runWebGLProgram(r,[e],"float32");r=new xd(a,"max",!0,!0,t);let i=n.runWebGLProgram(r,[e],"float32");return[s,i]}var SK={kernelName:rh,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:a})=>{let{x:n}=e,{filterSize:r,strides:s,pad:i,includeBatchInIndex:o}=t,l=a;v.assert(n.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${n.shape.length}.`);let u=[1,1];v.assert(T.eitherStridesOrDilationsAreOne(s,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);let p=T.computePool2DInfo(n.shape,r,s,u,i),[c,d]=IK(n,o,p,l);return[c,d]}};function TK(e,t,a,n){let r=v.sizeFromShape(t),s=v.sizeFromShape(e.shape)/r,i=ce({inputs:{x:e},attrs:{shape:[s,r]},backend:n}),o=bo(i,"float32","mean",n),l=ce({inputs:{x:o},attrs:{shape:a},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}var CK={kernelName:Pi,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:a})=>{let{x:n}=e,{keepDims:r,axis:s}=t,i=a,o=n.shape.length,l=v.parseAxisParam(s,n.shape),u=l,p=T.getAxesPermutation(u,o),c=p!=null,d=i.shouldExecuteOnCPU([n]),h=[],f=n;if(c){if(d){let y=i.texData.get(f.dataId).values,b=new Array(o);for(let C=0;C<b.length;C++)b[C]=n.shape[p[C]];let w=E3(y,n.shape,n.dtype,p,b);f=i.makeTensorInfo(b,n.dtype);let S=i.texData.get(f.dataId);S.values=w}else f=Dh(n,p,i);h.push(f),u=T.getInnerMostAxes(u.length,o)}T.assertAxesAreInnerMostDims("sum",u,o);let[m,g]=T.computeOutAndReduceShapes(f.shape,u),x=m;r&&(x=T.expandShapeToKeepDim(m,l));let A=TK(f,g,x,i);for(let y of h)i.disposeIntermediateTensorInfo(y);return A}};function NK(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n,o=r.shape.length,l=v.parseAxisParam(s,r.shape),u=l,p=T.getAxesPermutation(u,o),c=r;p!=null&&(c=Ia({inputs:{x:r},backend:a,attrs:{perm:p}}),u=T.getInnerMostAxes(u.length,r.shape.length)),T.assertAxesAreInnerMostDims("min",u,o);let[d,h]=T.computeOutAndReduceShapes(c.shape,u),f=v.sizeFromShape(h),m=ce({inputs:{x:c},backend:a,attrs:{shape:[-1,f]}}),g=bo(m,m.dtype,"min",a),x;if(i){let A=T.expandShapeToKeepDim(d,l);x=ce({inputs:{x:g},backend:a,attrs:{shape:A}})}else x=ce({inputs:{x:g},backend:a,attrs:{shape:d}});return a.disposeIntermediateTensorInfo(m),a.disposeIntermediateTensorInfo(g),p!=null&&a.disposeIntermediateTensorInfo(c),x}var EK={kernelName:Fi,backendName:"webgl",kernelFunc:NK},RK=R3+`
return min(a, b);
`,MK=`
vec4 result = vec4(min(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);
`+pp+`
return result;
`,$K=oa({opSnippet:RK,packedOpSnippet:MK,cpuKernelImpl:wU}),_K={kernelName:Oi,backendName:"webgl",kernelFunc:$K},PK=class{constructor(e,t,a){this.variableNames=["x"],this.outputShape=t.map((u,p)=>u[0]+e[p]+u[1]);let n=e.length,r=gt(n),s=t.map(u=>u[0]).join(","),i=t.map((u,p)=>u[0]+e[p]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n),l=a==="reflect"?0:1;if(n===1){this.userCode=`
int start = ${s};
int end = ${i};
void main() {
int outC = getOutputCoords();
if (outC < start) {
outC = start * 2 - outC - ${l};
} else if(outC >= end) {
outC = (end - 1) * 2 - outC + ${l};
}
setOutput(getX(outC - start));
}
`;return}this.userCode=`
${r} start = ${r}(${s});
${r} end = ${r}(${i});
void main() {
${r} outC = getOutputCoords();
for (int i = 0; i < ${n}; i++) {
if (outC[i] < start[i]) {
outC[i] = start[i] * 2 - outC[i] - ${l};
} else if(outC[i] >= end[i]) {
outC[i] = (end[i] - 1) * 2 - outC[i] + ${l};
}
}
${r} coords = outC - start;
setOutput(getX(${o}));
}
`}},FK=class{constructor(e,t,a){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,f)=>h[0]+e[f]+h[1]);let n=e.length,r=gt(n),s=t.map(h=>h[0]).join(","),i=t.map((h,f)=>h[0]+e[f]).join(","),o=va("rc",n),l=va("source",n),u=`${o[n-1]} < ${this.outputShape[n-1]}`,p=n===1?"source":`vec2(${l.slice(-2).join()})`,c=a==="reflect"?0:1,d="";if(n===1){let h=`
${r} source = rc;
if (source < start) {
source = start * 2 - source - ${c};
} else if (source >= end) {
source = (end - 1) * 2 - source + ${c};
}
source -= start;
`;d=`
${r} rc = outputLoc;
${h}
result[0] = getChannel(getX(${l.join()}), ${p});
${o[n-1]} += 1;
if(${u}) {
${h}
result[1] = getChannel(getX(${l.join()}), ${p});
}
`}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 - ${c}) +
gte * ((end - 1) * 2 - source + ${c});
source -= start;
`;d=`
${r} rc = outputLoc;
${h}
result[0] = getChannel(getX(${l.join()}), ${p});
${o[n-1]} += 1;
if(${u}) {
${h}
result[1] = getChannel(getX(${l.join()}), ${p});
}
rc = outputLoc;
${o[n-2]} += 1;
if(${o[n-2]} < ${this.outputShape[n-2]}) {
${h}
result[2] = getChannel(getX(${l.join()}), ${p});
${o[n-1]} += 1;
if(${u}) {
${h}
result[3] = getChannel(getX(${l.join()}), ${p});
}
}
`}this.userCode=`
const ${r} start = ${r}(${s});
const ${r} end = ${r}(${i});
void main() {
${r} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${d}
setOutput(result);
}
`}},OK=({inputs:e,backend:t,attrs:a})=>{let{x:n}=e,{paddings:r,mode:s}=a,i=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new FK(n.shape,r,s):new PK(n.shape,r,s);return t.runWebGLProgram(i,[n],n.dtype)},DK={kernelName:Di,backendName:"webgl",kernelFunc:OK},zK=`if (b == 0.0) return NAN;
return mod(a, b);`,LK=`
vec4 result = mod(a, b);
bvec4 isNaN = equal(b, vec4(0.0));
`+pp+`
return result;
`,BK=oa({opSnippet:zK,packedOpSnippet:LK}),WK={kernelName:Wl,backendName:"webgl",kernelFunc:BK},VK=class{constructor(e,t,a){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,a],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}));
}
`}},UK=`
if (a == b) {
return 1.0;
};
return a / b;`,GK=`
// 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;
`,hv=oa({opSnippet:UK,packedOpSnippet:GK,checkOutOfBounds:!0}),HK={kernelName:ci,backendName:"webgl",kernelFunc:hv},$x="return a - b;",fv=oa({opSnippet:$x,packedOpSnippet:$x,supportsComplex:!0,cpuKernelImpl:VU}),jK={kernelName:lo,backendName:"webgl",kernelFunc:fv};function mv(e){let{inputs:t,backend:a,attrs:n}=e,{logits:r}=t,{dim:s}=n,i=v.parseAxisParam([s],r.shape),o=cv({inputs:{x:r},backend:a,attrs:{reductionIndices:i,keepDims:!1}}),l=T.expandShapeToKeepDim(o.shape,i),u=ce({inputs:{x:o},backend:a,attrs:{shape:l}}),p=fv({inputs:{a:r,b:u},backend:a}),c=uv({inputs:{x:p},backend:a}),d=zh({inputs:{x:c},backend:a,attrs:{axis:i,keepDims:!1}}),h=ce({inputs:{x:d},backend:a,attrs:{shape:l}}),f=hv({inputs:{a:c,b:h},backend:a});return a.disposeIntermediateTensorInfo(o),a.disposeIntermediateTensorInfo(u),a.disposeIntermediateTensorInfo(p),a.disposeIntermediateTensorInfo(c),a.disposeIntermediateTensorInfo(d),a.disposeIntermediateTensorInfo(h),f}var qK={kernelName:so,backendName:"webgl",kernelFunc:mv};function XK(e){let{inputs:t,backend:a,attrs:n}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=n,l=o?r:mv({inputs:{logits:r},backend:a,attrs:{dim:r.shape.length-1}}),u=l.shape[0],p=l.shape[1],c=new VK(u,p,s),d=[[i]],h=a.runWebGLProgram(c,[l],"int32",d);return o||a.disposeIntermediateTensorInfo(l),h}var KK={kernelName:sh,backendName:"webgl",kernelFunc:XK},ZK=Cn+`
return -x;
`,YK=`
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 JK(e){let{inputs:t,backend:a}=e,{x:n}=t;if(a.shouldExecuteOnCPU([n])){let s=a.texData.get(n.dataId),[i,o]=IU(s.values,n.shape,n.dtype);return a.makeTensorInfo(o,n.dtype,i)}let r;return W().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new Vr(n.shape,YK):r=new qn(n.shape,ZK),a.runWebGLProgram(r,[n],n.dtype)}var QK={kernelName:Vl,backendName:"webgl",kernelFunc:JK},eZ=Tn.nonMaxSuppressionV3Impl;function tZ(e){T.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:a,attrs:n}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=n,u=a.readSync(r.dataId),p=a.readSync(s.dataId),{selectedIndices:c}=eZ(u,p,i,o,l);return a.makeTensorInfo([c.length],"int32",new Int32Array(c))}var aZ={kernelName:Bi,backendName:"webgl",kernelFunc:tZ},nZ=Tn.nonMaxSuppressionV4Impl;function rZ(e){T.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:a,attrs:n}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=n,p=a.readSync(r.dataId),c=a.readSync(s.dataId),{selectedIndices:d,validOutputs:h}=nZ(p,c,i,o,l,u);return[a.makeTensorInfo([d.length],"int32",new Int32Array(d)),a.makeTensorInfo([],"int32",new Int32Array([h]))]}var sZ={kernelName:Ul,backendName:"webgl",kernelFunc:rZ},iZ=Tn.nonMaxSuppressionV5Impl;function oZ(e){T.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:a,attrs:n}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=n,p=a.readSync(r.dataId),c=a.readSync(s.dataId),d=i,h=o,f=l,m=u,{selectedIndices:g,selectedScores:x}=iZ(p,c,d,h,f,m);return[a.makeTensorInfo([g.length],"int32",new Int32Array(g)),a.makeTensorInfo([x.length],"float32",new Float32Array(x))]}var lZ={kernelName:Wi,backendName:"webgl",kernelFunc:oZ},uZ=class{constructor(e,t,a,n){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(${n}), float(${a}),
float(index == coords.y)));
}
`}},dZ=e=>{let{inputs:t,backend:a,attrs:n}=e,{indices:r}=t,{dtype:s,depth:i,onValue:o,offValue:l}=n,u=v.sizeFromShape(r.shape),p=new uZ(u,i,o,l),c=ce({inputs:{x:r},backend:a,attrs:{shape:[u]}}),d=a.runWebGLProgram(p,[c],s);a.disposeIntermediateTensorInfo(c);let h=[...r.shape,i],f=ce({inputs:{x:d},backend:a,attrs:{shape:h}});return a.disposeIntermediateTensorInfo(d),f},pZ={kernelName:Vi,backendName:"webgl",kernelFunc:dZ};function Lc(e){let{inputs:t,backend:a}=e,{x:n}=t;if(n.dtype==="complex64"){let r=hp({inputs:{input:n},backend:a}),s=Lc({inputs:{x:r},backend:a}),i=Lh({inputs:{input:n},backend:a}),o=Lc({inputs:{x:i},backend:a}),l=ls({inputs:{real:s,imag:o},backend:a});return a.disposeIntermediateTensorInfo(r),a.disposeIntermediateTensorInfo(s),a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}else return fp({attrs:{shape:n.shape,dtype:n.dtype,value:n.dtype==="string"?"":0},backend:a})}var cZ={kernelName:nu,backendName:"webgl",kernelFunc:Lc};function gv(e){let{inputs:t,backend:a}=e,{x:n}=t;if(n.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(n.dtype==="complex64"){let r=hp({inputs:{input:n},backend:a}),s=gv({inputs:{x:r},backend:a}),i=Lh({inputs:{input:n},backend:a}),o=Lc({inputs:{x:i},backend:a}),l=ls({inputs:{real:s,imag:o},backend:a});return a.disposeIntermediateTensorInfo(r),a.disposeIntermediateTensorInfo(s),a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}else return fp({attrs:{shape:n.shape,dtype:n.dtype,value:1},backend:a})}var hZ={kernelName:Gl,backendName:"webgl",kernelFunc:gv};function fZ(e){let{inputs:t,backend:a,attrs:n}=e,{axis:r}=n;if(t.length===1)return N1({inputs:{input:t[0]},backend:a,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(p=>{v.assertShapesMatch(s,p.shape,"All tensors passed to stack must have matching shapes"),v.assert(i===p.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(p=>{let c=N1({inputs:{input:p},backend:a,attrs:{dim:r}});return o.push(c),c}),u=tv({inputs:l,backend:a,attrs:{axis:r}});return o.forEach(p=>a.disposeIntermediateTensorInfo(p)),u}var mZ={kernelName:Hl,backendName:"webgl",kernelFunc:fZ},gZ=class{constructor(e,t,a){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((l,u)=>l[0]+e[u]+l[1]);let n=e.length,r=gt(n),s=t.map(l=>l[0]).join(","),i=t.map((l,u)=>l[0]+e[u]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n);if(n===1){this.userCode=`
int start = ${s};
int end = ${i};
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(value);
} else {
setOutput(getX(outC - start));
}
}
`;return}this.userCode=`
${r} start = ${r}(${s});
${r} end = ${r}(${i});
void main() {
${r} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(value);
} else {
${r} coords = outC - start;
setOutput(getX(${o}));
}
}
`}},xZ=class{constructor(e,t,a){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 n=e.length,r=gt(n),s=t.map(f=>f[0]).join(","),i=t.map((f,m)=>f[0]+e[m]).join(","),o=va("rc",n),l=va("source",n),u=`${o[n-1]} < ${this.outputShape[n-1]}`,p=n===1?"source":`vec2(${l.slice(-2).join()})`,c=[`${r} rc = outputLoc;`,`${o[n-1]} += 1;
if(${u}) {
`,n===1?"":`}
rc = outputLoc;
${o[n-2]} += 1;
if(${o[n-2]} < ${this.outputShape[n-2]}) {`,n===1?"":` ${o[n-1]} += 1;
if(${u}) {`],d=n===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="";for(let f=0,m=n===1?2:4;f<m;f++)h+=`
${c[f]}
if (${d}) {
result[${f}] = float(value);
} else {
${r} source = rc - start;
result[${f}] = getChannel(getX(${l.join()}), ${p});
}
`;h+=n===1?"} ":"}}",this.userCode=`
const ${r} start = ${r}(${s});
const ${r} end = ${r}(${i});
void main() {
${r} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${h}
setOutput(result);
}
`}},xv=e=>{let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{paddings:s,constantValue:i}=n;if(v.sizeFromShape(r.shape)===0){let u=s.map((p,c)=>p[0]+r.shape[c]+p[1]);return fp({backend:a,attrs:{shape:u,value:i,dtype:r.dtype}})}let o=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new xZ(r.shape,s,i):new gZ(r.shape,s,i),l=[[i]];return a.runWebGLProgram(o,[r],r.dtype,l)},AZ={kernelName:Ui,backendName:"webgl",kernelFunc:xv},yZ=`
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);
`,bZ=`
// 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);
`+pp+`
return result;
`,vZ=oa({opSnippet:yZ,packedOpSnippet:bZ}),wZ={kernelName:Gi,backendName:"webgl",kernelFunc:vZ};function kZ(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n,o=r.shape.length,l=[],u=v.parseAxisParam(s,r.shape),p=u,c=T.getAxesPermutation(p,o),d=r;c!=null&&(d=Ia({inputs:{x:r},backend:a,attrs:{perm:c}}),p=T.getInnerMostAxes(p.length,o),l.push(d)),T.assertAxesAreInnerMostDims("prod",p,o);let h;if(a.shouldExecuteOnCPU([d])){let f=a.texData.get(d.dataId).values,{outVals:m,outShape:g,outDtype:x}=TU(d.shape,d.dtype,f,p);h=a.makeTensorInfo(g,x,m)}else{let[f,m]=T.computeOutAndReduceShapes(d.shape,p),g=v.sizeFromShape(m),x=ce({inputs:{x:d},backend:a,attrs:{shape:[-1,g]}}),A=Hd(r.dtype),y=bo(x,A,"prod",a);h=ce({inputs:{x:y},backend:a,attrs:{shape:f}}),l.push(x),l.push(y)}if(i){l.push(h);let f=T.expandShapeToKeepDim(h.shape,u);h=ce({inputs:{x:h},backend:a,attrs:{shape:f}})}return l.forEach(f=>a.disposeIntermediateTensorInfo(f)),h}var IZ={kernelName:ji,backendName:"webgl",kernelFunc:kZ};function SZ(e){let{inputs:t,backend:a,attrs:n}=e,{paramsNestedSplits:r,paramsDenseValues:s,indices:i}=t,{outputRaggedRank:o}=n,l=r.map(x=>a.readSync(x.dataId)),u=r.map(x=>x.shape),p=a.readSync(s.dataId),c=a.readSync(i.dataId),[d,h,f]=CU(l,u,p,s.shape,s.dtype,c,i.shape,o),m=d.map(x=>a.makeTensorInfo([x.length],"int32",x)),g=a.makeTensorInfo(f,s.dtype,h);return m.concat([g])}var TZ={kernelName:ih,backendName:"webgl",kernelFunc:SZ};function CZ(e){let{inputs:t,backend:a}=e,{starts:n,limits:r,deltas:s}=t,i=a.readSync(n.dataId),o=a.readSync(r.dataId),l=a.readSync(s.dataId),[u,p]=NU(i,n.shape,n.dtype,o,r.shape,l,s.shape),c=a.makeTensorInfo([u.length],"int32",u),d=a.makeTensorInfo([p.length],n.dtype,p);return[c,d]}var NZ={kernelName:oh,backendName:"webgl",kernelFunc:CZ};function EZ(e){let{inputs:t,backend:a,attrs:n}=e,{shape:r,values:s,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:l}=n,u=a.readSync(r.dataId),p=a.readSync(s.dataId),c=a.readSync(i.dataId),d=o.map(g=>a.readSync(g.dataId)),h=o.map(g=>g.shape),[f,m]=EU(u,r.shape,p,s.shape,s.dtype,c,i.shape,d,h,l);return a.makeTensorInfo(f,s.dtype,m)}var RZ={kernelName:lh,backendName:"webgl",kernelFunc:EZ},Av=e=>{let{backend:t,attrs:a}=e,{start:n,stop:r,step:s,dtype:i}=a,o=RU(n,r,s,i);return t.makeTensorInfo([o.length],i,o)},MZ={kernelName:jl,backendName:"webgl",kernelFunc:Av},$Z="return 1.0 / x;",_Z=Qe({opSnippet:$Z}),PZ={kernelName:qi,backendName:"webgl",kernelFunc:_Z},FZ=Cn+`
return (x < 0.0) ? 0.0 : x;
`,OZ=`
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;
`,DZ=Qe({opSnippet:FZ,packedOpSnippet:OZ}),zZ={kernelName:Xi,backendName:"webgl",kernelFunc:DZ},LZ=Cn+`
return (x < 0.0) ? 0.0 : min(6.0, x);
`,BZ=`
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;
`,WZ=Qe({opSnippet:LZ,packedOpSnippet:BZ}),VZ={kernelName:Yi,backendName:"webgl",kernelFunc:WZ},UZ=class{constructor(e,t,a,n,r){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,a,l];let u=[n&&t>1?i-1:i,n&&a>1?o-1:o],p=[n&&t>1?t-1:t,n&&a>1?a-1:a],c;r?c="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":c="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${u[0]/p[0]},
${u[1]/p[1]});
const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = ${c};
// 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);
}
`}},GZ=class{constructor(e,t,a,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,a,l];let u=[n&&t>1?i-1:i,n&&a>1?o-1:o],p=[n&&t>1?t-1:t,n&&a>1?a-1:a],c;r?c="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":c="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
const vec3 effectiveInputOverOutputRatioRC = vec3(
${u[0]/p[0]},
${u[1]/p[1]},
${u[1]/p[1]});
const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,
${o}.0);
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
// Fractional source index.
vec3 sourceFracIndexRC = ${c};
// 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 < ${a-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 HZ(e){let{inputs:t,backend:a,attrs:n}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,p=W().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new GZ(r.shape,l,u,s,i):new UZ(r.shape,l,u,s,i);return a.runWebGLProgram(p,[r],"float32")}var jZ={kernelName:Zi,backendName:"webgl",kernelFunc:HZ},qZ=class{constructor(e,t,a){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,n,r]=t,[,s,i]=e,o=[a&&s>1?n-1:n,a&&i>1?r-1:r],l=[a&&s>1?s-1:s,a&&i>1?i-1:i],u=o[0]/l[0],p=o[1]/l[1],c=1/u,d=1/p,h=Math.ceil(c)*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(${p});
const float invHeightScale = float(${c});
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 >= ${s}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${i}) {
continue;
}
float dxR = float(dyR) * heightScale;
int topDxRIndex = int(floor(dxR));
int bottomDxRIndex = int(min(ceil(dxR), ${n-1}.0));
float dxRLerp = dxR - float(topDxRIndex);
float inverseDxRLerp = 1.0 - dxRLerp;
float dxC = float(dyC) * widthScale;
int leftDxCIndex = int(floor(dxC));
int rightDxCIndex = int(min(ceil(dxC), ${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 XZ(e){let{inputs:t,backend:a,attrs:n}=e,{images:r,dy:s}=t,{alignCorners:i}=n,o=new qZ(s.shape,r.shape,i);return a.runWebGLProgram(o,[s],s.dtype)}var KZ={kernelName:Y1,backendName:"webgl",kernelFunc:XZ},ZZ=class{constructor(e,t,a,n,r){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,a,l];let u=[n&&t>1?i-1:i,n&&a>1?o-1:o],p=[n&&t>1?t-1:t,n&&a>1?a-1:a],c=n?"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]/p[0]},
${u[1]/p[1]});
const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = ${d};
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${c})));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
}
`}},YZ=class{constructor(e,t,a,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,a,l];let u=[n&&t>1?i-1:i,n&&a>1?o-1:o],p=[n&&t>1?t-1:t,n&&a>1?a-1:a],c=n?"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]/p[0]},
${u[1]/p[1]},
${u[1]/p[1]});
const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,
${o}.0);
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
// Fractional source index.
vec3 sourceFracIndexRC = ${d};
// Compute the coordinators of nearest neighbor point.
ivec3 sourceNearestRC = ivec3(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${c})));
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${l-1};
bool hasNextRow = coords.z < ${a-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 JZ(e){let{inputs:t,backend:a,attrs:n}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,p=W().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new YZ(r.shape,l,u,s,i):new ZZ(r.shape,l,u,s,i);return a.runWebGLProgram(p,[r],r.dtype)}var QZ={kernelName:Ki,backendName:"webgl",kernelFunc:JZ},eY=class{constructor(e,t,a){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,n,r]=t,[,s,i]=e,o=[a&&s>1?n-1:n,a&&i>1?r-1:r],l=[a&&s>1?s-1:s,a&&i>1?i-1:i],u=o[0]/l[0],p=o[1]/l[1],c=1/u,d=1/p,h=Math.ceil(c)*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(${p});
const float invHeightScale = float(${c});
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 >= ${s}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${i}) {
continue;
}
float sourceFracRow =
float(${o[0]}) *
(float(dyR) / float(${l[0]}));
float sourceFracCol =
float(${o[1]}) *
(float(dyC) / float(${l[1]}));
int sourceNearestRow = int(min(
float(int(${n}) - 1),
${a} ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
int sourceNearestCol = int(min(
float(int(${r}) - 1),
${a} ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutput(accumulator);
}
`}};function tY(e){let{inputs:t,backend:a,attrs:n}=e,{images:r,dy:s}=t,{alignCorners:i}=n,o=new eY(s.shape,r.shape,i);return a.runWebGLProgram(o,[s],s.dtype)}var aY={kernelName:Z1,backendName:"webgl",kernelFunc:tY},nY=class{constructor(e,t){this.variableNames=["x"];let a=e.length;if(a>4)throw new Error(`WebGL backend: Reverse of rank-${a} tensor is not yet supported`);if(this.outputShape=e,a===1){this.userCode=`
void main() {
int coord = getOutputCoords();
setOutput(getX(${e[0]} - coord - 1));
}
`;return}let n=i=>t.indexOf(i)!==-1&&e[i]!==1?`${e[i]} - coords[${i}] - 1`:`coords[${i}]`,r=e.map((i,o)=>n(o)).join(","),s=gt(a);this.userCode=`
void main() {
${s} coords = getOutputCoords();
setOutput(getX(${r}));
}
`}},rY=class{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let a=e.length;if(a>4)throw new Error(`WebGL backend: Reverse of rank-${a} tensor is not yet supported`);this.outputShape=e;let n=va("rc",a),r=`${n[a-1]} + 1 < ${this.outputShape[a-1]}`,s=`${n[a-2]} + 1 < ${this.outputShape[a-2]}`,i=gt(a);a===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() {
${i} rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = ${o(n.slice())};
if(${r}){
result.g = ${l(n.slice())};
}
if(${s}) {
result.b = ${u(n.slice())};
if(${r}) {
result.a = ${p(n.slice())};
}
}
setOutput(result);
}
`;function o(h){return c(h)}function l(h){return h[a-1]="("+h[a-1]+" + 1)",c(h)}function u(h){return h[a-2]="("+h[a-2]+" + 1)",c(h)}function p(h){return h[a-1]="("+h[a-1]+" + 1)",h[a-2]="("+h[a-2]+" + 1)",c(h)}function c(h){let f=e.map((x,A)=>d(A,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 sY(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{dims:s}=n,i=r.shape.length,o=v.parseAxisParam(s,r.shape);if(i===0)return Za({inputs:{x:r},backend:a});let l=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new rY(r.shape,o):new nY(r.shape,o);return a.runWebGLProgram(l,[r],r.dtype)}var iY={kernelName:Ji,backendName:"webgl",kernelFunc:sY},oY=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let a=e[1],n=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 < ${n} && coordY >= 0 && coordY < ${a}) {
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
`}},lY={kernelName:mo,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:a})=>{let{image:n}=e,{radians:r,fillValue:s,center:i}=t,o=a,l=new oY(n.shape,s),[u,p]=T.getImageCenter(i,n.shape[1],n.shape[2]),c=[[u,p,Math.sin(r),Math.cos(r)]];return o.runWebGLProgram(l,[n],n.dtype,c)}},uY=`
// 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;
}
}
`,dY=Qe({opSnippet:uY}),pY={kernelName:Xl,backendName:"webgl",kernelFunc:dY},cY="return inversesqrt(x);",hY=Qe({opSnippet:cY,cpuKernelImpl:MU}),fY={kernelName:Qi,backendName:"webgl",kernelFunc:hY},yv=class{constructor(e,t,a,n,r,s,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;let o=gt(r.length),l=gt(s.length),u="";a===1?u="i":a===2&&(u="i, j");let p=`getIndices(${u})`,c="";n===1?c="i":n===2&&(c="i, coords[1]");let d=`getUpdates(${c})`,h=t>1?"strides[j]":"strides";this.userCode=`
${o} strides = ${o}(${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(${p});
flattenedIndex += index * ${h};
}
if (flattenedIndex == coords[0]) {
sum += ${d};
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
`}};function mY(e){let{inputs:t,backend:a,attrs:n}=e,{indices:r,updates:s}=t,{shape:i}=n,{sliceRank:o,numUpdates:l,sliceSize:u,strides:p,outputSize:c}=T.calculateShapes(s,r,i),d=[c/u,u];if(c===0)return a.makeTensorInfo(i,r.dtype);let h=ce({inputs:{x:r},backend:a,attrs:{shape:[l,o]}}),f=ce({inputs:{x:s},backend:a,attrs:{shape:[l,u]}}),m=a.makeTensorInfo([],"float32",new Float32Array([0])),g=new yv(l,o,h.shape.length,f.shape.length,p,d),x=a.runWebGLProgram(g,[f,h,m],f.dtype),A=ce({inputs:{x},backend:a,attrs:{shape:i}});return a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(f),a.disposeIntermediateTensorInfo(x),a.disposeIntermediateTensorInfo(m),A}var gY={kernelName:eo,backendName:"webgl",kernelFunc:mY},xY=class{constructor(e,t,a,n){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,a];let r="while (left < right) {",s=`for (int i = 0; i < ${Math.ceil(Math.log2(t+1))}; ++i) { if (left >= right) break;`,i=W().getNumber("WEBGL_VERSION")===2?r:s,o=n==="left"?"<":"<=";this.userCode=`
int findBound(int batch, float value) {
int left = 0;
int right = numInputs;
int mid;
${i}
mid = (left + right) / 2;
if (getSortedSequence(batch, mid) ${o} value) {
left = mid + 1;
} else {
right = mid;
}
}
return right;
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int valueIndex = coords[1];
float value = getValues(batch, valueIndex);
setOutput(float(findBound(batch, value)));
}
`}};function AY(e){let{inputs:t,backend:a,attrs:n}=e,{sortedSequence:r,values:s}=t,{side:i}=n,o=new xY(r.shape[0],r.shape[1],s.shape[1],i),l=[[r.shape[1]]];return a.runWebGLProgram(o,[r,s],"int32",l)}var yY={kernelName:$d,backendName:"webgl",kernelFunc:AY},bY=class{constructor(e,t,a){this.variableNames=["c","a","b"],this.outputShape=t;let n,r;if(a>4)throw Error(`Where for rank ${a} is not yet supported`);if(a===1)r="resRC",n="resRC";else{let i=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],l=[];for(let u=0;u<t.length;u++)l.push(`${i[u]}`),u<e&&o.push(`${i[u]}`);n=o.join(),r=l.join()}let s=gt(a);this.userCode=`
void main() {
${s} resRC = getOutputCoords();
float cVal = getC(${n});
if (cVal >= 1.0) {
setOutput(getA(${r}));
} else {
setOutput(getB(${r}));
}
}
`}};function vY(e){let{inputs:t,backend:a}=e,{condition:n,t:r,e:s}=t,i=new bY(n.shape.length,r.shape,r.shape.length);return a.runWebGLProgram(i,[n,r,s],ca(r.dtype,s.dtype))}var wY={kernelName:Kl,backendName:"webgl",kernelFunc:vY},kY=`
// 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);
`,IY=Qe({opSnippet:kY}),SY={kernelName:_d,backendName:"webgl",kernelFunc:IY},TY=mu+`
return 1.0 / (1.0 + exp(-1.0 * x));
`,CY=`
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;
`,NY=Qe({opSnippet:TY,packedOpSnippet:CY,cpuKernelImpl:_U}),EY={kernelName:ao,backendName:"webgl",kernelFunc:NY},RY=`
if (isnan(x)) { return 0.0; }
return sign(x);
`,MY=Qe({opSnippet:RY}),$Y={kernelName:Pd,backendName:"webgl",kernelFunc:MY},_Y=mu+`
return sin(x);
`,PY=Qe({opSnippet:_Y}),FY={kernelName:to,backendName:"webgl",kernelFunc:PY},OY=`
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`,DY=Qe({opSnippet:OY}),zY={kernelName:Yl,backendName:"webgl",kernelFunc:DY},LY=`
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;
`,BY=Qe({opSnippet:LY}),WY={kernelName:Fd,backendName:"webgl",kernelFunc:BY},VY=e=>{let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{blockShape:s,paddings:i}=n;v.assert(r.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((x,A)=>x*A),l=[[0,0]];l.push(...i);for(let x=1+s.length;x<r.shape.length;++x)l.push([0,0]);let u=[],p=xv({inputs:{x:r},backend:a,attrs:{paddings:l,constantValue:0}}),c=T.getReshaped(p.shape,s,o,!1),d=T.getPermuted(c.length,s.length,!1),h=T.getReshapedPermuted(p.shape,s,o,!1),f=ce({inputs:{x:p},backend:a,attrs:{shape:c}}),m=Ia({inputs:{x:f},backend:a,attrs:{perm:d}}),g=ce({inputs:{x:m},backend:a,attrs:{shape:h}});return u.push(p),u.push(f),u.push(m),u.forEach(x=>a.disposeIntermediateTensorInfo(x)),g},UY={kernelName:Jl,backendName:"webgl",kernelFunc:VY};function GY(e){let{inputs:t,backend:a}=e,{indices:n,values:r,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
${s.shape}`);if(n.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
${n.shape}`);if(r.shape.length!==1)throw new Error(`Values must be a vector, saw:
${r.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
${i.shape}`);let o=a.readSync(n.dataId),l=a.readSync(r.dataId),u=a.readSync(s.dataId),p=a.readSync(i.dataId)[0],[c,d,h,f,m]=FU(o,n.shape,n.dtype,l,r.dtype,u,p);return[a.makeTensorInfo(d,n.dtype,c),a.makeTensorInfo([d[0]],r.dtype,h),a.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),a.makeTensorInfo([m.length],n.dtype,new Int32Array(m))]}var HY={kernelName:Od,backendName:"webgl",kernelFunc:GY};function jY(e){let{inputs:t,backend:a}=e,{inputIndices:n,inputShape:r,newShape:s}=t;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${n.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${r.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(a.readSync(r.dataId)),o=a.readSync(n.dataId),l=Array.from(a.readSync(s.dataId)),[u,p,c]=OU(o,n.shape,n.dtype,i,l);return[a.makeTensorInfo(p,n.dtype,u),a.makeTensorInfo([c.length],s.dtype,new Int32Array(c))]}var qY={kernelName:eu,backendName:"webgl",kernelFunc:jY};function XY(e){let{inputs:t,backend:a}=e,{data:n,indices:r,segmentIds:s}=t;if(n.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(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);let i=a.readSync(n.dataId),o=a.readSync(r.dataId),l=a.readSync(s.dataId),[u,p]=W6(i,n.shape,n.dtype,o,l,!0);return a.makeTensorInfo(p,n.dtype,u)}var KY={kernelName:Dd,backendName:"webgl",kernelFunc:XY};function ZY(e){let{inputs:t,backend:a}=e,{data:n,indices:r,segmentIds:s}=t;if(n.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(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);let i=a.readSync(n.dataId),o=a.readSync(r.dataId),l=a.readSync(s.dataId),[u,p]=W6(i,n.shape,n.dtype,o,l);return a.makeTensorInfo(p,n.dtype,u)}var YY={kernelName:zd,backendName:"webgl",kernelFunc:ZY};function JY(e){let{inputs:t,backend:a,attrs:n}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=n,{sliceRank:l,numUpdates:u,sliceSize:p,strides:c,outputSize:d}=T.calculateShapes(s,r,o),h=!1;if(s.dtype==="string"){let x=a.bufferSync(r),A=a.bufferSync(s),y=v.decodeString(a.readSync(i.dataId)[0]),b=$U(x,A,o,d,p,u,l,c,y,h);return a.makeTensorInfo(o,b.dtype,b.values)}let f=new yv(u,l,r.shape.length,s.shape.length,c,[d,1],h),m=a.runWebGLProgram(f,[s,r,i],s.dtype),g=ce({inputs:{x:m},backend:a,attrs:{shape:o}});return a.disposeIntermediateTensorInfo(m),g}var QY={kernelName:Ld,backendName:"webgl",kernelFunc:JY};function eJ(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=n,o=v.parseAxisParam(i,r.shape)[0],l=T.prepareSplitSize(r,s,o),u=r.shape.length,p=new Array(u).fill(0),c=r.shape.slice();return l.map(d=>{let h=[...c];h[o]=d;let f=gu({inputs:{x:r},backend:a,attrs:{begin:p,size:h}});return p[o]+=d,f})}var tJ={kernelName:Ql,backendName:"webgl",kernelFunc:eJ},_x="return sqrt(x);",aJ=Qe({opSnippet:_x,packedOpSnippet:_x,cpuKernelImpl:DU}),nJ={kernelName:no,backendName:"webgl",kernelFunc:aJ},rJ="return x * x;",sJ=Qe({opSnippet:rJ}),iJ={kernelName:Bd,backendName:"webgl",kernelFunc:sJ},Px="return (a - b) * (a - b);",oJ=oa({opSnippet:Px,packedOpSnippet:Px}),lJ={kernelName:io,backendName:"webgl",kernelFunc:oJ};function uJ({inputs:e,attrs:t,backend:a}){let{x:n}=e,r=Cn+`
return x > 0.0 ? 1.0 : float(${t.alpha});
`,s=new qn(n.shape,r);return a.runWebGLProgram(s,[n],n.dtype)}var dJ={kernelName:fo,backendName:"webgl",kernelFunc:uJ},pJ=class{constructor(e,t,a){this.variableNames=["x"],this.outputShape=a;let n=a.length,r=gt(a.length),s=gt(a.length),i="";if(n===1)i="coords * strides + begin";else{let o=0;i=a.map((l,u)=>(o++,a.length===1?`coords * strides[${u}] + begin[${u}]`:`coords[${o-1}] * strides[${u}] + begin[${u}]`)).join(",")}this.userCode=`
${r} begin = ${r}(${e});
${r} strides = ${r}(${t});
void main() {
${s} coords = getOutputCoords();
setOutput(getX(${i}));
}
`}};function cJ(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:p,newAxisMask:c,shrinkAxisMask:d}=n,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:x,begin:A,end:y,strides:b}=It.sliceInfo(r.shape,s,i,o,l,u,p,c,d),w;if(m)w=ce({inputs:{x:r},backend:a,attrs:{shape:f}});else if(g||x){v.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let C=It.computeOutShape(A,y,b),E=gu({inputs:{x:r},backend:a,attrs:{begin:A,size:C}});w=ce({inputs:{x:E},backend:a,attrs:{shape:f}}),a.disposeIntermediateTensorInfo(E)}else if(a.shouldExecuteOnCPU([r])){let C=a.readSync(r.dataId),E=Me(r.shape,r.dtype,C),_=zU(h,E,b,A);w=a.makeTensorInfo(f,r.dtype,_.values)}else{let C=new pJ(A,b,h);w=a.runWebGLProgram(C,[r],r.dtype)}let S=ce({inputs:{x:w},backend:a,attrs:{shape:f}});return a.disposeIntermediateTensorInfo(w),S}var hJ={kernelName:oo,backendName:"webgl",kernelFunc:cJ};function fJ(e){let{inputs:t,backend:a,attrs:n}=e,{separator:r,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=n,{data:p,dataSplits:c}=t,d=a.readSync(p.dataId),h=a.readSync(c.dataId),[f,m]=LU(d,h,r,s,i,o,l,u);return[a.makeTensorInfo([f.length],"string",f),a.makeTensorInfo(c.shape,"int32",m)]}var mJ={kernelName:tu,backendName:"webgl",kernelFunc:fJ};function gJ(e){let{inputs:t,backend:a,attrs:n}=e,{skipEmpty:r}=n,{input:s,delimiter:i}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let o=a.readSync(s.dataId),l=a.readSync(i.dataId)[0],[u,p,c]=BU(o,l,r),d=p.length;return[a.makeTensorInfo([d,2],"int32",u),a.makeTensorInfo([d],"string",p),a.makeTensorInfo([2],"int32",new Int32Array(c))]}var xJ={kernelName:Wd,backendName:"webgl",kernelFunc:gJ};function AJ(e){let{inputs:t,backend:a,attrs:n}=e,{numBuckets:r}=n,{input:s}=t;if(s.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 i=a.readSync(s.dataId),o=WU(i,r);return a.makeTensorInfo(s.shape,"int32",o)}var yJ={kernelName:Vd,backendName:"webgl",kernelFunc:AJ},bJ="return tan(x);",vJ=Qe({opSnippet:bJ}),wJ={kernelName:uo,backendName:"webgl",kernelFunc:vJ},kJ=`
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`,IJ=Qe({opSnippet:kJ}),SJ={kernelName:po,backendName:"webgl",kernelFunc:IJ},TJ=class{constructor(e,t){this.variableNames=["A"];let a=new Array(e.length);for(let s=0;s<a.length;s++)a[s]=e[s]*t[s];this.outputShape=a,this.rank=a.length;let n=gt(this.rank),r=CJ(e);this.userCode=`
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${r}));
}
`}};function CJ(e){let t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${e[0]})`;let a=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],n=[];for(let r=0;r<e.length;r++)n.push(`imod(${a[r]}, ${e[r]})`);return n.join()}function bv(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{reps:s}=n;if(r.dtype==="string"||r.shape.length>5){let o=a.readSync(r.dataId),l=r.dtype==="string"?o.map(c=>v.decodeString(c)):o,u=Me(r.shape,r.dtype,l),p=UU(u,s);return a.makeTensorInfo(p.shape,p.dtype,p.values)}let i=new TJ(r.shape,s);return a.runWebGLProgram(i,[r],r.dtype)}var NJ={kernelName:ns,backendName:"webgl",kernelFunc:bv},EJ=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));
}
}
`}},RJ=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 Es(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function Fx(e){let t=1;for(;t<e;)t*=2;return t}function MJ(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{k:s,sorted:i}=n,o=W().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),l=W().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),u=r.shape,p=u[u.length-1];if(a.shouldExecuteOnCPU([r])||p<o||s>l){let _=a.readSync(r.dataId),[$,M]=GU(_,u,r.dtype,s,i);return[a.makeTensorInfo($.shape,$.dtype,$.values),a.makeTensorInfo(M.shape,M.dtype,M.values)]}if(s===0)return u[u.length-1]=0,[a.makeTensorInfo(u,r.dtype,[]),a.makeTensorInfo(u,"int32",[])];if(p===1)return[r,fp({attrs:{shape:u,dtype:"int32",value:0},backend:a})];let c=a.texData.get(r.dataId),d=c!==null&&c.isPacked,h=d?a.unpackTensor(r):r,f=v.sizeFromShape(u)/p,m=ce({inputs:{x:h},attrs:{shape:[f,p]},backend:a});d&&Es(a,h);let g=Fx(s),x=Fx(p),A=null,y=()=>A===null?[m,m]:[m,A],b=(_,$,M)=>{let I=y(),N=new EJ(M),O=[[p],[A===null?1:0],[Number.NEGATIVE_INFINITY],[_],[$]],L=A;A=a.runWebGLProgram(N,I,"int32",O),Es(a,L)};for(let _=1;_<g;_*=2){let $=_*2;for(let M=_;M>=1;M/=2)b($,M,[f,x])}for(let _=x;_>g;_/=2){let $=y(),M=new RJ([f,_/2]),I=[[p],[A===null?1:0],[g]],N=A;A=a.runWebGLProgram(M,$,"int32",I),Es(a,N);let O=g/2,L=O*2;for(let B=O;B>=1;B/=2)b(L,B,A.shape)}let w=A;A=gu({inputs:{x:A},backend:a,attrs:{begin:0,size:[f,s]}}),Es(a,w);let S=pv({inputs:{x:m,indices:A},backend:a,attrs:{axis:1,batchDims:1}});Es(a,m);let C=u.slice(0,-1);C.push(s),w=A,A=ce({inputs:{x:A},attrs:{shape:C},backend:a}),Es(a,w);let E=S;return S=ce({inputs:{x:S},attrs:{shape:C},backend:a}),Es(a,E),[S,A]}var $J={kernelName:co,backendName:"webgl",kernelFunc:MJ},_J=class{constructor(e,t,a,n,r,s){this.variableNames=["Image","Transforms"],this.outputShape=s;let i=a==="nearest"?1:2,o;switch(n){case"constant":o=1;break;case"reflect":o=2;break;case"wrap":o=3;break;case"nearest":o=4;break;default:o=1;break}this.userCode=`
float mapCoord(float outCoord, float len) {
float inCoord = outCoord;
if(${o} == 2) {
if (inCoord < 0.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz2 = 2.0 * len;
if (inCoord < sz2) {
inCoord = sz2 * float(int(float(-inCoord / sz2))) +
inCoord;
}
inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;
}
} else if (inCoord > len - 1.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz2 = 2.0 * len;
inCoord -= sz2 * float(int(float(inCoord / sz2)));
if (inCoord >= len) {
inCoord = sz2 - inCoord - 1.0;
}
}
}
return clamp(inCoord, 0.0, len - 1.0);
} else if (${o} == 3) {
if (inCoord < 0.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz = len - 1.0;
inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);
}
} else if (inCoord > len - 1.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz = len - 1.0;
inCoord -= len * float(int(float(inCoord / sz)));
}
}
return clamp(inCoord, 0.0, len - 1.0);
} else if (${o} == 4) {
return clamp(outCoord, 0.0, len - 1.0);
} else {
return outCoord;
}
}
float readWithFillValue(int batch, int coordY, int coordX,
int channel) {
float outputValue;
if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {
outputValue = getImage(batch, coordY, coordX, channel);
} else {
outputValue = float(${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 (${i} == 1) {
int coordY = int(round(mapY));
int coordX = int(round(mapX));
outputValue = readWithFillValue(batch, coordY, coordX,
channel);
} else {
float yFloor = floor(mapY);
float xFloor = floor(mapX);
float yCeil = yFloor + 1.0;
float xCeil = xFloor + 1.0;
float valueYFloor = (xCeil - mapX) *
readWithFillValue(batch, int(yFloor), int(xFloor), channel) +
(mapX - xFloor) *
readWithFillValue(batch, int(yFloor), int(xCeil), channel);
float valueYCeil = (xCeil - mapX) *
readWithFillValue(batch, int(yCeil), int(xFloor), channel) +
(mapX - xFloor) *
readWithFillValue(batch, int(yCeil), int(xCeil), channel);
outputValue = (yCeil - mapY) * valueYFloor +
(mapY - yFloor) * valueYCeil;
}
}
setOutput(outputValue);
}
`}};function PJ(e){let{inputs:t,backend:a,attrs:n}=e,{image:r,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=n,[p,c,d,h]=r.shape,[f,m]=u!=null?u:[c,d],g=[p,f,m,h],x=new _J(c,d,i,o,l,g);return a.runWebGLProgram(x,[r,s],"float32")}var FJ={kernelName:ho,backendName:"webgl",kernelFunc:PJ};function OJ(e){let{inputs:t,attrs:a,backend:n}=e,{axis:r}=a,{x:s}=t;uu(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let i=n.readSync(s.dataId),{outputValues:o,outputShape:l,indices:u}=HU(i,r,s.shape,s.dtype);return[n.makeTensorInfo(l,s.dtype,o),n.makeTensorInfo([u.length],"int32",u)]}var DJ={kernelName:uh,backendName:"webgl",kernelFunc:OJ};function zJ(e){let{inputs:t,backend:a,attrs:n}=e,{value:r}=t,{axis:s}=n;s<0&&(s+=r.shape.length);let i=r,o=i.shape.length,l=r.shape[s],u=new Array(o-1),p=0;for(let m=0;m<o;m++)m!==s&&(u[p++]=i.shape[m]);let c=[],d=new Array(o).fill(0),h=i.shape.slice();h[s]=1;let f=new Array(l);for(let m=0;m<f.length;m++){d[s]=m;let g=gu({inputs:{x:i},backend:a,attrs:{begin:d,size:h}}),x=ce({inputs:{x:g},backend:a,attrs:{shape:u}});f[m]=x,c.push(g)}return c.forEach(m=>a.disposeIntermediateTensorInfo(m)),f}var LJ={kernelName:au,backendName:"webgl",kernelFunc:zJ},BJ=class{constructor(e,t){this.variableNames=["x","segmentIds"];let a=e.windowSize,n=e.batchSize,r=e.inSize,s=e.numSegments,i=s*Math.ceil(r/a);this.outputShape=[n,i];let o="0.0",l="sumValue",u=Math.floor(a/4)*4,p=a%4,c=`
sumValue += dot(values, segFilter);
`,d="";r%a>0&&(d=`
if (inIdx < 0 || inIdx >= ${r}) {
return initializationValue;
}
`);let h="";r%a>0&&(h=`
if (inIdx < 0 || inIdx >= ${r}) {
return -1.0;
}
`),this.userCode=`
const float initializationValue = ${o};
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(
${s})) * float(${a}));
int currentSeg = int(mod(float(outIdx), float(${s})));
float sumValue = 0.0;
for (int i = 0; i < ${u}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
);
${c}
}
int inIdx = inOffset + ${u};
if (${p===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
);
${c}
} else if (${p===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
);
${c}
} else if (${p===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
);
${c}
}
setOutput(${l});
}
`}};function WJ(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,segmentIds:s}=t,{numSegments:i}=n,o=r.shape.length,l=[],u=0,p=T.getAxesPermutation([u],o),c=r;p!=null&&(c=Ia({inputs:{x:r},backend:a,attrs:{perm:p}}),l.push(c),u=T.getInnerMostAxes(1,o)[0]);let d=T.segment_util.computeOutShape(c.shape,u,i),h=v.sizeFromShape([c.shape[u]]),f=ce({inputs:{x:c},backend:a,attrs:{shape:[-1,h]}});l.push(f);let m=Hd(r.dtype),g=(b,w,S,C,E)=>{let _=b.shape[0],$=b.shape[1],M=T.segment_util.segOpComputeOptimalWindowSize($,E),I={windowSize:M,inSize:$,batchSize:_,numSegments:E},N=new BJ(I,w),O=a.compileAndRun(N,[b,S],C);if(l.push(O),O.shape[1]===E)return O;let L=Av({backend:a,attrs:{start:0,stop:E,step:1,dtype:"float32"}}),B=bv({inputs:{x:L},backend:a,attrs:{reps:[$/M]}});return l.push(L),l.push(B),g(O,w,B,C,E)},x=g(f,"unsortedSegmentSum",s,m,i),A=ce({inputs:{x},backend:a,attrs:{shape:d}}),y=A;if(p!=null){l.push(A);let b=T.getUndoAxesPermutation(p);y=Ia({inputs:{x:y},backend:a,attrs:{perm:b}})}return l.forEach(b=>a.disposeIntermediateTensorInfo(b)),y}var VJ={kernelName:dh,backendName:"webgl",kernelFunc:WJ},UJ=[zG,BG,UG,jG,XG,YG,QG,tH,sH,oH,dH,hH,gH,bH,kH,SH,CH,MH,_H,FH,LH,jH,XH,ZH,aj,rj,lj,vG,pj,gj,bj,Tj,Nj,Rj,$j,Pj,Dj,Bj,Uj,Hj,qj,Kj,Jj,eq,rq,iq,uq,cq,fq,Aq,wq,Tq,Eq,$q,_q,Fq,Dq,Lq,Wq,Uq,qq,Zq,Qq,tX,rX,oX,pX,mX,bG,xX,fj,bX,kX,TX,kG,RX,PX,OX,BX,UX,qX,ZX,eK,rK,oK,uK,hK,mK,xK,vK,kK,SK,CK,EK,_K,DK,WK,KK,TG,QK,aZ,sZ,lZ,JH,pZ,hZ,mZ,AZ,wZ,SG,IZ,TZ,NZ,RZ,MZ,QH,HK,PZ,zZ,VZ,NG,jZ,KZ,QZ,aY,iY,lY,pY,fY,gY,yY,wY,SY,EY,$Y,FY,zY,GH,qK,WY,UY,HY,qY,KY,YY,QY,tJ,nJ,iJ,lJ,dJ,hJ,mJ,xJ,yJ,jK,FG,wJ,SJ,NJ,$J,FJ,OG,DJ,LJ,VJ,cZ];for(let e of UJ)mn(e);var Tt;(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"})(Tt||(Tt={}));var yd;(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"})(yd||(yd={}));var vv;function GJ(e){vv=e.wasm.cwrap(jr,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function HJ(e){let{inputs:t,backend:a,attrs:n}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t;if(r.dtype!=="float32"||s.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:u,activation:p,leakyreluAlpha:c}=n,d=a.dataIdMap.get(r.dataId).id,h=a.dataIdMap.get(s.dataId).id,f=0;if(i!=null){let E=a.dataIdMap.get(i.dataId);if(E.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${E.shape.length}.`);f=E.id}let m=o==null?0:a.dataIdMap.get(o.dataId).id,g=yd[p];if(g==null)throw new Error(`${p} activation not yet supported for FusedConv2D in the wasm backend.`);let x=l?r.shape[2]:r.shape[1],A=u?s.shape[1]:s.shape[2],y=xo.assertAndGetBroadcastShape(r.shape.slice(0,-2),s.shape.slice(0,-2)),b=a.makeOutput([...y,x,A],r.dtype),w=a.dataIdMap.get(b.dataId).id,S=new Uint8Array(new Int32Array(r.shape).buffer),C=new Uint8Array(new Int32Array(s.shape).buffer);return vv(d,S,r.shape.length,h,C,s.shape.length,l,u,g,f,m,c||0,w),b}var jJ={kernelName:jr,backendName:"wasm",setupFunc:GJ,kernelFunc:HJ};function Bt(e,t){let a;function n(s){a=s.wasm.cwrap(e,null,["number","number","number"])}function r(s){let{backend:i,inputs:{x:o}}=s,l=i.dataIdMap.get(o.dataId).id,u=i.makeOutput(o.shape,t||o.dtype),p=i.dataIdMap.get(u.dataId).id;return v.sizeFromShape(u.shape)===0||a(l,Tt[o.dtype],p),u}return{kernelName:e,backendName:"wasm",setupFunc:n,kernelFunc:r}}var qJ=Bt(wl);function la(e,t,a){let n;function r(i){n=i.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function s(i){let{backend:o,inputs:l}=i,{a:u,b:p}=l,c=o.dataIdMap.get(u.dataId).id,d=o.dataIdMap.get(p.dataId).id,h=a!=null?a:u.dtype,f=T.assertAndGetBroadcastShape(u.shape,p.shape),m=o.makeOutput(f,h);if(v.sizeFromShape(f)===0)return m;let g=new Uint8Array(new Int32Array(u.shape).buffer),x=new Uint8Array(new Int32Array(p.shape).buffer),A=o.dataIdMap.get(m.dataId).id;return n(c,g,u.shape.length,d,x,p.shape.length,Tt[u.dtype],A),m}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:s}}var XJ=!0,KJ=la(ts,XJ),wv;function ZJ(e){wv=e.wasm.cwrap(Ks,null,["array","number","number","number"])}function YJ(e){let{inputs:t,backend:a}=e,n=a.makeOutput(t[0].shape,t[0].dtype);if(v.sizeFromShape(n.shape)===0)return n;let r=t.map(o=>a.dataIdMap.get(o.dataId).id),s=new Uint8Array(new Int32Array(r).buffer),i=a.dataIdMap.get(n.dataId).id;return wv(s,r.length,Tt[n.dtype],i),n}var JJ={kernelName:Ks,backendName:"wasm",setupFunc:ZJ,kernelFunc:YJ};function Bh(e){let{inputs:{x:t},backend:a}=e;if(t.dtype==="string")return Be(a.readSync(t.dataId),t.shape,t.dtype);let n=a.makeOutput(t.shape,t.dtype),r=a.typedArrayFromHeap(t);return a.typedArrayFromHeap(n).set(r),n}var QJ={kernelName:ki,backendName:"wasm",kernelFunc:Bh},kv;function eQ(e){kv=e.wasm.cwrap(Ar,null,["number","array","number","number","number","array","number"])}function Qr(e){let{inputs:t,backend:a,attrs:n}=e,[r,s]=aQ(t.x.shape,n.perm),i=!0;for(let f=0;f<s.length;f++)s[f]!==f&&(i=!1);let o=tQ(t.x.shape,n.perm),l={dataId:t.x.dataId,shape:r,dtype:t.x.dtype};if(i){let f=Bh({inputs:t,backend:a});return f.shape=o,f}let u=a.makeOutput(o,l.dtype),p=a.dataIdMap.get(l.dataId).id,c=a.dataIdMap.get(u.dataId).id,d=new Uint8Array(new Int32Array(s).buffer),h=new Uint8Array(new Int32Array(l.shape).buffer);return kv(p,h,l.shape.length,Tt[l.dtype],c,d,s.length),u}function tQ(e,t){let a=new Array(e.length);for(let n=0;n<a.length;n++)a[n]=e[t[n]];return a}function aQ(e,t){let a=[],n=[];for(let r=0;r<e.length;++r)e[r]!==1&&a.push(e[r]),e[t[r]]!==1&&n.push(t[r]);for(let r=0;r<n.length;++r){let s=-1;for(let i=0;i<n.length;++i)n[i]>=r&&(s===-1||n[s]>n[i])&&(s=i);n[s]=r}return[a,n]}var nQ={kernelName:Ar,backendName:"wasm",kernelFunc:Qr,setupFunc:eQ};function us(e,t,a){let n=e.shape,r=e.shape.length,s=v.parseAxisParam(t,n),i=s,o=T.getAxesPermutation(i,r),l=null,u=!1;if(o!=null){let p=new Array(r);for(let d=0;d<p.length;d++)p[d]=n[o[d]];i=T.getInnerMostAxes(i.length,r),l=Qr({inputs:{x:e},attrs:{perm:o},backend:a});let c=a.dataIdMap.get(e.dataId).id;a.dataIdMap.get(l.dataId).id!==c&&(u=!0)}return{transposed:l,originalAxes:s,axes:i,inputWasTransposed:u}}var Iv;function rQ(e){Iv=e.wasm.cwrap(Zs,null,["number, number, number"])}function sQ(e){let{backend:t,inputs:a,attrs:n}=e,{axis:r,keepDims:s}=n,{x:i}=a,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:u,axes:p,originalAxes:c,inputWasTransposed:d}=us(i,r,t);if(d){let A=t.dataIdMap.get(u.dataId).id;l=u,o=A}let h=l.shape.length;T.assertAxesAreInnerMostDims("all",p,h);let[f,m]=T.computeOutAndReduceShapes(l.shape,p),g=v.sizeFromShape(m),x=t.makeOutput(f,i.dtype);if(v.sizeFromShape(l.shape)!==0){let A=t.dataIdMap.get(x.dataId).id;Iv(o,g,A)}if(d&&t.disposeData(u.dataId),s){let A=T.expandShapeToKeepDim(x.shape,c);x.shape=A}return x}var iQ={kernelName:Zs,backendName:"wasm",setupFunc:rQ,kernelFunc:sQ},Sv;function oQ(e){Sv=e.wasm.cwrap(Ys,null,["number, number, number"])}function lQ(e){let{backend:t,inputs:a,attrs:n}=e,{axis:r,keepDims:s}=n,{x:i}=a,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:u,axes:p,originalAxes:c,inputWasTransposed:d}=us(i,r,t);if(d){let A=t.dataIdMap.get(u.dataId).id;l=u,o=A}let h=l.shape.length;T.assertAxesAreInnerMostDims("any",p,h);let[f,m]=T.computeOutAndReduceShapes(l.shape,p),g=v.sizeFromShape(m),x=t.makeOutput(f,i.dtype);if(v.sizeFromShape(l.shape)!==0){let A=t.dataIdMap.get(x.dataId).id;Sv(o,g,A)}if(d&&t.disposeData(u.dataId),s){let A=T.expandShapeToKeepDim(x.shape,c);x.shape=A}return x}var uQ={kernelName:Ys,backendName:"wasm",setupFunc:oQ,kernelFunc:lQ},Tv;function dQ(e){Tv=e.wasm.cwrap(Js,null,["number","number","number","number","number"])}function pQ(e){let{backend:t,inputs:a,attrs:n}=e,{axis:r}=n,{x:s}=a,i=t.dataIdMap.get(s.dataId).id,o=i,l=s,{transposed:u,axes:p,inputWasTransposed:c}=us(s,r,t);if(c){let x=t.dataIdMap.get(u.dataId).id;x!==i&&(l=u,o=x)}let d=l.shape.slice(0,-1),h=t.makeOutput(d,"int32"),f=t.dataIdMap.get(h.dataId).id,m=v.sizeFromShape(h.shape),g=l.shape[p[0]];return Tv(o,Tt[l.dtype],m,g,f),c&&t.disposeData(u.dataId),h}var cQ={kernelName:Js,backendName:"wasm",kernelFunc:pQ,setupFunc:dQ},Cv;function hQ(e){Cv=e.wasm.cwrap(Qs,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function fQ(e){let{inputs:t,attrs:a,backend:n}=e,r=t.x,s=n.dataIdMap.get(r.dataId).id,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=a,p=T.computePool2DInfo(r.shape,i,o,1,l,u),c=p.filterHeight,d=p.filterWidth,h=p.padInfo.top,f=p.padInfo.right,m=p.padInfo.bottom,g=p.padInfo.left,x=p.strideHeight,A=p.strideWidth,y=p.inChannels;if(p.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${p.dataFormat}'. Please use 'channelsLast'.`);if(p.dilationWidth!==1||p.dilationHeight!==1)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${p.dilationHeight}, ${p.dilationWidth}].`);let b=n.makeOutput(p.outShape,"float32"),w=n.dataIdMap.get(b.dataId).id;return Cv(s,r.shape[0],r.shape[1],r.shape[2],c,d,h,f,m,g,x,A,y,w),b}var mQ={kernelName:Qs,backendName:"wasm",setupFunc:hQ,kernelFunc:fQ};function za(e){let{inputs:t,attrs:a}=e,{x:n}=t,{shape:r}=a,s=v.sizeFromShape(n.shape),i=v.inferFromImplicitShape(r,s);return v.assert(s===v.sizeFromShape(i),()=>`new shape: ${i}, old shape: ${n.shape}. New shape and old shape must have the same number of elements.`),e.backend.incRef(n.dataId),{dataId:n.dataId,shape:i,dtype:n.dtype}}var gQ={kernelName:ql,backendName:"wasm",kernelFunc:za},Nv;function xQ(e){Nv=e.wasm.cwrap(ei,null,["number","array","number","number","array","number","number","number","number"])}function AQ(e){let{inputs:t,backend:a,attrs:n}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=n;if(r.dtype!=="float32"||s.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let l=r.shape.length,u=s.shape.length,p=i?r.shape[l-2]:r.shape[l-1],c=o?s.shape[u-1]:s.shape[u-2],d=i?r.shape[l-1]:r.shape[l-2],h=o?s.shape[u-2]:s.shape[u-1],f=r.shape.slice(0,-2),m=s.shape.slice(0,-2),g=v.sizeFromShape(f),x=v.sizeFromShape(m),A=xo.assertAndGetBroadcastShape(r.shape.slice(0,-2),s.shape.slice(0,-2)).concat([d,h]);v.assert(p===c,()=>`Error in matMul: inner shapes (${p}) and (${c}) of Tensors with shapes ${r.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let y=i?[g,p,d]:[g,d,p],b=o?[x,h,c]:[x,c,h],w=za({inputs:{x:r},backend:a,attrs:{shape:y}}),S=za({inputs:{x:s},backend:a,attrs:{shape:b}}),C=a.dataIdMap.get(w.dataId).id,E=a.dataIdMap.get(S.dataId).id,_=i?w.shape[2]:w.shape[1],$=o?S.shape[1]:S.shape[2],M=Math.max(g,x),I=a.makeOutput([M,_,$],w.dtype),N=a.dataIdMap.get(I.dataId).id,O=new Uint8Array(new Int32Array(w.shape).buffer),L=new Uint8Array(new Int32Array(S.shape).buffer);return Nv(C,O,w.shape.length,E,L,S.shape.length,i,o,N),a.disposeData(w.dataId),a.disposeData(S.dataId),I.shape=A,I}var yQ={kernelName:ei,backendName:"wasm",setupFunc:xQ,kernelFunc:AQ};function qs(e){let{inputs:{x:t},attrs:{begin:a,size:n},backend:r}=e,[s,i]=It.parseSliceParams(t,a,n),o=It.isSliceContinous(t.shape,s,i),l=r.readSync(t.dataId),u=r.makeOutput(i,t.dtype),p=v.computeStrides(t.shape),c=r.dataIdMap.get(u.dataId);if(o){let f=It.computeFlatOffset(s,p);return t.dtype==="string"?c.stringBytes=l.slice(f,f+v.sizeFromShape(i)):r.typedArrayFromHeap(u).set(l.subarray(f,f+v.sizeFromShape(i))),u}if(t.dtype==="string"){let f=_c(l,s,i,t.shape,t.dtype);return c.stringBytes=f,u}let d=r.typedArrayFromHeap(u),h=t.shape.length;if(h===2)bQ(l,p[0],d,s,i);else if(h===3)vQ(l,p[0],p[1],d,s,i);else if(h===4)wQ(l,p[0],p[1],p[2],d,s,i);else{let f=_c(l,s,i,t.shape,t.dtype);d.set(f)}return u}function bQ(e,t,a,n,r){let s=0,i=n[0],o=n[1],l=i+r[0];for(let u=i;u<l;u++){let p=u*t+o;a.set(e.subarray(p,p+r[1]),s),s+=r[1]}}function vQ(e,t,a,n,r,s){let i=0,o=r[0],l=r[1],u=r[2],p=o+s[0],c=l+s[1];for(let d=o;d<p;d++)for(let h=l;h<c;h++){let f=d*t+h*a+u;n.set(e.subarray(f,f+s[2]),i),i+=s[2]}}function wQ(e,t,a,n,r,s,i){let o=0,l=s[0],u=s[1],p=s[2],c=l+i[0],d=u+i[1],h=p+i[2],f=s[3];for(let m=l;m<c;m++)for(let g=u;g<d;g++)for(let x=p;x<h;x++){let A=m*t+g*a+x*n+f;r.set(e.subarray(A,A+i[3]),o),o+=i[3]}}var kQ={kernelName:Zl,backendName:"wasm",kernelFunc:qs};function IQ(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{blockShape:s,crops:i}=n,o=s.reduce((x,A)=>x*A),l=T.getReshaped(r.shape,s,o),u=T.getPermuted(l.length,s.length),p=T.getReshapedPermuted(r.shape,s,o),c=T.getSliceBeginCoords(i,s.length),d=T.getSliceSize(p,i,s.length),h=za({inputs:{x:r},backend:a,attrs:{shape:l}}),f=Qr({inputs:{x:h},backend:a,attrs:{perm:u}}),m=za({inputs:{x:f},backend:a,attrs:{shape:p}}),g=qs({inputs:{x:m},backend:a,attrs:{begin:c,size:d}});return a.disposeData(h.dataId),a.disposeData(f.dataId),a.disposeData(h.dataId),g}var SQ={kernelName:Rl,backendName:"wasm",kernelFunc:IQ};function xu(e){let{inputs:{x:t},attrs:{dtype:a},backend:n}=e,r=n.makeOutput(t.shape,a),s=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(r).set(s),r}var TQ={kernelName:ti,backendName:"wasm",kernelFunc:xu},CQ=Bt(ai),Ev;function NQ(e){Ev=e.wasm.cwrap(as,null,["number","number","number","number"])}function EQ(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{clipValueMin:s,clipValueMax:i}=n,o=a.dataIdMap.get(r.dataId).id,l=a.makeOutput(r.shape,r.dtype),u=a.dataIdMap.get(l.dataId).id;return Ev(o,s,i,u),l}var RQ={kernelName:as,backendName:"wasm",setupFunc:NQ,kernelFunc:EQ};function Rv(e){let{inputs:t,backend:a}=e,n=v.parseAxisParam(e.attrs.axis,t[0].shape)[0],r=t.map(h=>h.shape);T.assertParamsConsistent(r,n);let s=T.computeOutShape(t.map(h=>h.shape),n),i=t.filter(h=>v.sizeFromShape(h.shape)>0);if(i.length===1)return Bh({inputs:{x:i[0]},backend:a});let o=a.makeOutput(s,t[0].dtype);if(v.sizeFromShape(s)===0)return o;if(i[0].dtype==="string"){let h=i.map(y=>{let b=[-1,v.sizeFromShape(y.shape.slice(n))];return za({inputs:{x:y},backend:a,attrs:{shape:b}})}),f=h.map(y=>({vals:a.readSync(y.dataId),shape:y.shape}));s=T.computeOutShape(h.map(y=>y.shape),1);let m=h[0].shape[0]===1,g=o3(f,s,t[0].dtype,m),x=T.computeOutShape(i.map(y=>y.shape),n);o.shape=x;let A=a.dataIdMap.get(o.dataId);return A.stringBytes=T.fromStringArrayToUint8(g),h.forEach(y=>a.disposeData(y.dataId)),o}let l=v.sizeFromShape(i[0].shape.slice(0,n)),u=0,p=i.map(h=>{let f=v.sizeFromShape(h.shape.slice(n));return u+=f,f}),c=i.map(h=>a.typedArrayFromHeap(h)),d=a.typedArrayFromHeap(o);for(let h=0;h<l;h++){let f=h*u;for(let m=0;m<c.length;m++){let g=p[m],x=h*g,A=c[m].subarray(x,x+g);d.set(A,f),f+=g}}return o}var MQ={kernelName:Ml,backendName:"wasm",kernelFunc:Rv},Mv;function $Q(e){Mv=e.wasm.cwrap(ni,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function _Q(e){let{inputs:t,attrs:a,backend:n}=e,{x:r,filter:s}=t,i=n.dataIdMap.get(r.dataId).id,o=n.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:p,dimRoundingMode:c,dataFormat:d}=a,h=T.convertConv2DDataFormat(d),f=T.computeConv2DInfo(r.shape,s.shape,l,u,p,c,!1,h),m=f.filterHeight,g=f.filterWidth,x=f.padInfo.top,A=f.padInfo.right,y=f.padInfo.bottom,b=f.padInfo.left,w=f.dilationHeight,S=f.dilationWidth,C=f.strideHeight,E=f.strideWidth,_=f.inChannels,$=f.outChannels,M=f.padInfo.type==="SAME"?1:0;if(f.dataFormat!=="channelsLast")throw new Error(`wasm backend Conv2D does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);let I=n.makeOutput(f.outShape,"float32"),N=n.dataIdMap.get(I.dataId).id;return Mv(i,r.shape[0],r.shape[1],r.shape[2],o,m,g,x,A,y,b,M,w,S,C,E,_,$,N),I}var PQ={kernelName:ni,backendName:"wasm",setupFunc:$Q,kernelFunc:_Q},$v;function FQ(e){$v=e.wasm.cwrap(ri,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function OQ(e){let{backend:t,inputs:a,attrs:n}=e,{dy:r,filter:s}=a,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,inputShape:p}=n,c=1,d=T.convertConv2DDataFormat(l),h=T.computeConv2DInfo(p,s.shape,i,c,o,u,!1,d),{batchSize:f,filterHeight:m,filterWidth:g,inChannels:x,inHeight:A,inWidth:y,outChannels:b,outHeight:w,outWidth:S,strideHeight:C,strideWidth:E}=h,_=m-1-h.padInfo.top,$=g-1-h.padInfo.left,M=h.dataFormat==="channelsLast",I=v.computeStrides(h.inShape),N=v.computeStrides(r.shape),[O,L,B]=v.computeStrides(s.shape),G=I[0],j=M?I[1]:I[2],U=M?I[2]:1,H=M?1:I[1],V=N[0],Q=M?N[1]:N[2],Z=M?N[2]:1,re=M?1:N[1],ee=t.makeOutput(h.inShape,"float32"),he=t.dataIdMap.get(ee.dataId).id,oe=t.dataIdMap.get(r.dataId).id,Ae=t.dataIdMap.get(s.dataId).id;return $v(oe,Ae,f,m,g,A,y,x,w,S,b,C,E,_,$,O,L,B,G,j,U,H,V,Q,Z,re,he),ee}var DQ={kernelName:ri,backendName:"wasm",setupFunc:FQ,kernelFunc:OQ},zQ=Bt(si),LQ=Bt(ii),E1;(function(e){e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest"})(E1||(E1={}));var _v;function BQ(e){_v=e.wasm.cwrap(ui,null,["number","number","number","number","array","number","number","number","number","number"])}function WQ(e){let{backend:t,inputs:a,attrs:n}=e,{method:r,extrapolationValue:s,cropSize:i}=n,{image:o,boxes:l,boxInd:u}=a,p=l.shape[0],[c,d]=i,h=[p,c,d,o.shape[3]],f=t.dataIdMap.get(o.dataId),m;o.dtype!=="float32"&&(m=xu({backend:t,inputs:{x:o},attrs:{dtype:"float32"}}),f=t.dataIdMap.get(m.dataId));let g=f.id,x=t.dataIdMap.get(l.dataId).id,A=t.dataIdMap.get(u.dataId).id,y=t.makeOutput(h,"float32"),b=t.dataIdMap.get(y.dataId).id,w=new Uint8Array(new Int32Array(o.shape).buffer);return _v(g,x,A,p,w,c,d,E1[r],s,b),m!=null&&t.disposeData(m.dataId),y}var VQ={kernelName:ui,backendName:"wasm",setupFunc:BQ,kernelFunc:WQ},Pv;function UQ(e){Pv=e.wasm.cwrap(oi,null,["number","number","number","number","number","number"])}function GQ(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=n,l=r.shape.length;v.assert(r.dtype==="float32"||r.dtype==="int32",()=>`cumprod does not support ${r.dtype} tensors in the WASM backend`);let u=T.getAxesPermutation([s],l),p=r;u!==null&&(p=Qr({inputs:{x:r},attrs:{perm:u},backend:a}));let c=T.getInnerMostAxes(1,l)[0];T.assertAxesAreInnerMostDims("cumprod",[c],l);let d=a.makeOutput(p.shape,p.dtype),h=p.shape[c],f=a.dataIdMap.get(p.dataId).id,m=a.dataIdMap.get(d.dataId).id;Pv(f,i?1:0,o?1:0,h,m,Tt[r.dtype]);let g=d;if(u!==null){let x=T.getUndoAxesPermutation(u);g=Qr({inputs:{x:d},attrs:{perm:x},backend:a}),a.disposeData(p.dataId),a.disposeData(d.dataId)}return g}var HQ={kernelName:oi,backendName:"wasm",setupFunc:UQ,kernelFunc:GQ},Fv;function jQ(e){Fv=e.wasm.cwrap(li,null,["number","number","number","number","number","number"])}function qQ(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=n,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([s],l),p=r;u!==null&&(p=Qr({inputs:{x:r},attrs:{perm:u},backend:a}));let c=T.getInnerMostAxes(1,l)[0];T.assertAxesAreInnerMostDims("cumsum",[c],l);let d=a.makeOutput(p.shape,p.dtype),h=p.shape[c],f=a.dataIdMap.get(p.dataId).id,m=a.dataIdMap.get(d.dataId).id;Fv(f,i?1:0,o?1:0,h,m,Tt[r.dtype]);let g=d;if(u!==null){let x=T.getUndoAxesPermutation(u);g=Qr({inputs:{x:d},attrs:{perm:x},backend:a}),a.disposeData(p.dataId),a.disposeData(d.dataId)}return g}var XQ={kernelName:li,backendName:"wasm",setupFunc:jQ,kernelFunc:qQ},Ov;function KQ(e){Ov=e.wasm.cwrap(di,null,["number","number","number","array","number","array","array","number","number"])}function ZQ(e){let{backend:t,inputs:a,attrs:n}=e,{x:r}=a,{blockSize:s,dataFormat:i}=n,o=r.shape[0],l=i==="NHWC"?r.shape[1]:r.shape[2],u=i==="NHWC"?r.shape[2]:r.shape[3],p=i==="NHWC"?r.shape[3]:r.shape[1],c=l*s,d=u*s,h=p/(s*s),f=i==="NHWC"?[o,c,d,h]:[o,h,c,d],m=t.makeOutput(f,"float32"),g=t.dataIdMap.get(r.dataId).id,x=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),A=new Uint8Array(new Int32Array(f).buffer),y=new Uint8Array(new Int32Array(v.computeStrides(f)).buffer),b=t.dataIdMap.get(m.dataId).id;return Ov(g,s,i==="NHWC"?1:0,x,r.shape.length-1,A,y,f.length,b),m}var YQ={kernelName:di,backendName:"wasm",setupFunc:KQ,kernelFunc:ZQ},Dv;function JQ(e){Dv=e.wasm.cwrap(pi,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function QQ(e){let{inputs:t,attrs:a,backend:n}=e,{x:r,filter:s}=t,i=n.dataIdMap.get(r.dataId).id,o=n.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:p,dimRoundingMode:c}=a,d=u==null?[1,1]:u,h=T.computeConv2DInfo(r.shape,s.shape,l,d,p,c,!0),f=h.filterHeight,m=h.filterWidth,g=h.padInfo.top,x=h.padInfo.right,A=h.padInfo.bottom,y=h.padInfo.left,b=h.dilationHeight,w=h.dilationWidth,S=h.strideHeight,C=h.strideWidth,E=h.inChannels,_=h.outChannels,$=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 M=n.makeOutput(h.outShape,"float32"),I=n.dataIdMap.get(M.dataId).id;return Dv(i,r.shape[0],r.shape[1],r.shape[2],o,f,m,g,x,A,y,$,b,w,S,C,E,_,I),M}var eee={kernelName:pi,backendName:"wasm",setupFunc:JQ,kernelFunc:QQ},tee=Bt(hi),aee=!1,nee=la(fi,aee,"bool"),ree=Bt(mi,"float32");function R1(e){let{inputs:t,attrs:a,backend:n}=e,{input:r}=t,{dim:s}=a,i=r.shape.length,o=r.shape.slice(),l=s;return s<0&&(v.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),o.splice(l,0,1),za({inputs:{x:r},backend:n,attrs:{shape:o}})}var see={kernelName:_l,backendName:"wasm",kernelFunc:R1};function zv(e){let{attrs:{shape:t,value:a,dtype:n},backend:r}=e,s=r.makeOutput(t,n);return r.typedArrayFromHeap(s).fill(a),s}var iee={kernelName:Fl,backendName:"wasm",kernelFunc:zv},Lv;function oee(e){Lv=e.wasm.cwrap(gi,null,["number","number","number","number","number","number"])}function lee(e){let{inputs:t,backend:a}=e,{image:n}=t,r=a.makeOutput(n.shape,n.dtype),s=a.dataIdMap.get(n.dataId).id,i=a.dataIdMap.get(r.dataId).id,[o,l,u,p]=n.shape;return Lv(s,o,l,u,p,i),r}var uee={kernelName:gi,backendName:"wasm",kernelFunc:lee,setupFunc:oee},dee=Bt(xi),pee=!1,cee=la(Ai,pee),Bv;function hee(e){Bv=e.wasm.cwrap(yi,null,["number","number","number","number","number","number","number"])}function fee(e){let{backend:t,inputs:a,attrs:n}=e,{varianceEpsilon:r}=n,{x:s,mean:i,variance:o,offset:l,scale:u}=a,p=t.dataIdMap.get(s.dataId).id,c=t.dataIdMap.get(i.dataId).id,d=t.dataIdMap.get(o.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(s.shape,s.dtype);if(v.sizeFromShape(s.shape)===0)return m;let g=t.dataIdMap.get(m.dataId).id;return Bv(p,c,d,h,f,r,g),m}var mee={kernelName:yi,backendName:"wasm",setupFunc:hee,kernelFunc:fee},Wv;function gee(e){Wv=e.wasm.cwrap(qr,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 xee(e){let{inputs:t,attrs:a,backend:n}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:p,dataFormat:c,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=a,m=T.computeConv2DInfo(r.shape,s.shape,l,p,u,d),g=yd[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedConv2D in the wasm backend.`);let x=n.dataIdMap.get(r.dataId).id,A=n.dataIdMap.get(s.dataId).id,y=m.outChannels,b=0;if(i!=null){let Z=n.dataIdMap.get(i.dataId);if(Z.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${Z.shape.length}.`);if(Z.shape[0]!==y)throw new Error(`FusedConv2D bias shape (${Z.shape}) does not match the number of output channels (${y})`);b=Z.id}let w=m.filterHeight,S=m.filterWidth,C=m.padInfo.top,E=m.padInfo.right,_=m.padInfo.bottom,$=m.padInfo.left,M=m.dilationHeight,I=m.dilationWidth,N=m.strideHeight,O=m.strideWidth,L=m.inChannels,B=m.padInfo.type==="SAME"?1:0,G=m.batchSize,j=m.inHeight,U=m.inWidth;if(c!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${c}'. Please use 'NHWC'.`);let H=n.makeOutput(m.outShape,"float32"),V=n.dataIdMap.get(H.dataId).id,Q=o==null?0:n.dataIdMap.get(o.dataId).id;return Wv(x,G,j,U,A,w,S,b,C,E,_,$,B,M,I,N,O,L,y,g,Q,f||0,V),H}var Aee={kernelName:qr,backendName:"wasm",setupFunc:gee,kernelFunc:xee},Vv;function yee(e){Vv=e.wasm.cwrap(Xr,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 bee(e){let{inputs:t,attrs:a,backend:n}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:p,dataFormat:c,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=a,m=T.computeConv2DInfo(r.shape,s.shape,l,p,u,d,!0),g=yd[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let x=n.dataIdMap.get(r.dataId).id,A=n.dataIdMap.get(s.dataId).id,y=m.outChannels,b=0;if(i!=null){let Z=n.dataIdMap.get(i.dataId);if(Z.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${Z.shape.length}.`);if(Z.shape[0]!==y)throw new Error(`FusedDepthwiseConv2D bias shape (${Z.shape}) does not match the number of output channels (${y})`);b=Z.id}let w=m.filterHeight,S=m.filterWidth,C=m.padInfo.top,E=m.padInfo.right,_=m.padInfo.bottom,$=m.padInfo.left,M=m.dilationHeight,I=m.dilationWidth,N=m.strideHeight,O=m.strideWidth,L=m.inChannels,B=m.padInfo.type==="SAME"?1:0,G=m.batchSize,j=m.inHeight,U=m.inWidth;if(c!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${c}'. Please use 'NHWC'.`);let H=n.makeOutput(m.outShape,"float32"),V=n.dataIdMap.get(H.dataId).id,Q=o==null?0:n.dataIdMap.get(o.dataId).id;return Vv(x,G,j,U,A,w,S,b,C,E,_,$,B,M,I,N,O,L,y,g,Q,f||0,V),H}var vee={kernelName:Xr,backendName:"wasm",setupFunc:yee,kernelFunc:bee},Uv;function wee(e){Uv=e.wasm.cwrap(bi,null,["number","number","number","number","number","number","array","number"])}function kee(e){let{backend:t,inputs:a}=e,{params:n,indices:r}=a,[s,i,o,l]=c2.prepareAndValidate(n,r),u=t.makeOutput(s,n.dtype);if(i===0)return u;let p=r.shape,c=p[p.length-1],d=t.dataIdMap.get(n.dataId).id,h=t.dataIdMap.get(r.dataId).id,f=new Uint8Array(new Int32Array(l).buffer),m=t.dataIdMap.get(u.dataId).id;return Uv(d,Tt[n.dtype],h,i,c,o,f,m),u}var Iee={kernelName:bi,backendName:"wasm",setupFunc:wee,kernelFunc:kee},Gv;function See(e){Gv=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function Tee(e){let{backend:t,inputs:a,attrs:n}=e,{x:r,indices:s}=a,{axis:i,batchDims:o}=n,l=v.parseAxisParam(i,r.shape)[0],u=t.readSync(s.dataId),p=r.shape[l];for(let C=0;C<u.length;++C){let E=u[C];v.assert(E<=p-1&&E>=0,()=>`GatherV2: the index value ${E} is not in [0, ${p-1}]`)}let c=T.segment_util.collectGatherOpShapeInfo(r,s,l,o),d=za({inputs:{x:r},attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]},backend:t}),h=v.sizeFromShape(s.shape),f=za({inputs:{x:s},attrs:{shape:[c.batchSize,h/c.batchSize]},backend:t}),m=[c.batchSize,c.outerSize,h/c.batchSize,c.sliceSize],g=t.makeOutput(m,r.dtype);if(v.sizeFromShape(r.shape)===0)return g;let x=d.shape.length-1,A=t.dataIdMap.get(d.dataId).id,y=t.dataIdMap.get(f.dataId).id,b=t.dataIdMap.get(g.dataId).id,w=new Uint8Array(new Int32Array(v.computeStrides(d.shape)).buffer),S=new Uint8Array(new Int32Array(v.computeStrides(m)).buffer);return Gv(A,Tt[r.dtype],w,x,y,c.batchSize,S,b),t.disposeData(d.dataId),t.disposeData(f.dataId),g.shape=c.outputShape,g}var Cee={kernelName:Ol,backendName:"wasm",setupFunc:See,kernelFunc:Tee},Nee=!1,Eee=la(vi,Nee,"bool"),Ree=!1,Mee=la(wi,Ree,"bool"),$ee=Bt(Ii,"bool"),Hv;function _ee(e){Hv=e.wasm.cwrap(Si,null,["number","number","number","number"])}function Pee(e){let{inputs:{x:t},attrs:{alpha:a},backend:n}=e,r=n.dataIdMap.get(t.dataId).id,s=n.makeOutput(t.shape,"float32");if(v.sizeFromShape(t.shape)!==0){let i=n.dataIdMap.get(s.dataId).id;Hv(r,Tt[t.dtype],a,i)}return s}var Fee={kernelName:Si,backendName:"wasm",setupFunc:_ee,kernelFunc:Pee},Oee=!1,Dee=la(Ti,Oee,"bool"),zee=!1,Lee=la(Ci,zee,"bool"),Bee=Bt(Ni),Wee=!1,Vee=la(Ei,Wee,"bool"),Uee=Bt(Ri),Gee=!1,Hee=la(Bl,Gee,"bool"),jee=!1,qee=la(xA,jee,"bool"),jv;function Xee(e){jv=e.wasm.cwrap(Mi,null,["number","number","number","number"])}function Kee(e){let{backend:t,inputs:a,attrs:n}=e,{reductionIndices:r,keepDims:s}=n,{x:i}=a,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:u,axes:p,originalAxes:c,inputWasTransposed:d}=us(i,r,t);if(d){let A=t.dataIdMap.get(u.dataId).id;l=u,o=A}let h=l.shape.length;T.assertAxesAreInnerMostDims("max",p,h);let[f,m]=T.computeOutAndReduceShapes(l.shape,p),g=v.sizeFromShape(m),x=t.makeOutput(f,i.dtype);if(v.sizeFromShape(l.shape)!==0){let A=t.dataIdMap.get(x.dataId).id;jv(o,Tt[i.dtype],g,A)}if(d&&t.disposeData(u.dataId),s){let A=T.expandShapeToKeepDim(x.shape,c);x.shape=A}return x}var Zee={kernelName:Mi,backendName:"wasm",setupFunc:Xee,kernelFunc:Kee},Yee=!1,Jee=la($i,Yee),qv;function Qee(e){qv=e.wasm.cwrap(_i,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function ete(e){let{inputs:t,attrs:a,backend:n}=e,r=t.x,s=n.dataIdMap.get(r.dataId).id;v.assert(r.dtype==="float32",()=>`Error in MaxPool: only float32 input is supported. Got ${r.dtype}.`);let{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=a,p=T.computePool2DInfo(r.shape,i,o,1,l,u),c=p.filterHeight,d=p.filterWidth,h=p.padInfo.top,f=p.padInfo.right,m=p.padInfo.bottom,g=p.padInfo.left,x=p.dilationHeight,A=p.dilationWidth,y=p.strideHeight,b=p.strideWidth,w=p.inChannels,S=p.outChannels;if(p.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${p.dataFormat}'. Please use 'channelsLast'.`);let C=n.makeOutput(p.outShape,"float32"),E=n.dataIdMap.get(C.dataId).id;return qv(s,r.shape[0],r.shape[1],r.shape[2],c,d,h,f,m,g,x,A,y,b,w,S,E),C}var tte={kernelName:_i,backendName:"wasm",setupFunc:Qee,kernelFunc:ete},Xv;function ate(e){Xv=e.wasm.cwrap(Pi,null,["number, number, number"])}function nte(e){let{backend:t,inputs:a,attrs:n}=e,{axis:r,keepDims:s}=n,{x:i}=a,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:p,axes:c,originalAxes:d,inputWasTransposed:h}=us(i,r,t),f=c;if(h){let b=t.dataIdMap.get(p.dataId).id;b!==o&&(u=p,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),x=v.sizeFromShape(g),A=u;u.dtype!=="float32"&&(A=xu({backend:t,inputs:{x:u},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(A.dataId).id);let y=t.makeOutput(m,"float32");if(v.sizeFromShape(u.shape)!==0){let b=t.dataIdMap.get(y.dataId).id;Xv(l,x,b)}if(h&&t.disposeData(p.dataId),s){let b=T.expandShapeToKeepDim(y.shape,d);y.shape=b}return u.dtype!=="float32"&&t.disposeData(A.dataId),y}var rte={kernelName:Pi,backendName:"wasm",setupFunc:ate,kernelFunc:nte},Kv;function ste(e){Kv=e.wasm.cwrap(Fi,null,["number","number","number","number"])}function ite(e){let{backend:t,inputs:a,attrs:n}=e,{axis:r,keepDims:s}=n,{x:i}=a,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:p,axes:c,originalAxes:d,inputWasTransposed:h}=us(i,r,t);if(h){let y=t.dataIdMap.get(p.dataId).id;y!==o&&(u=p,l=y)}let f=u.shape.length;T.assertAxesAreInnerMostDims("min",c,f);let[m,g]=T.computeOutAndReduceShapes(u.shape,c),x=v.sizeFromShape(g),A=t.makeOutput(m,u.dtype);if(v.sizeFromShape(u.shape)!==0){let y=t.dataIdMap.get(A.dataId).id;Kv(l,Tt[i.dtype],x,y)}if(h&&t.disposeData(p.dataId),s){let y=T.expandShapeToKeepDim(A.shape,d);A.shape=y}return A}var ote={kernelName:Fi,backendName:"wasm",setupFunc:ste,kernelFunc:ite},lte=!1,ute=la(Oi,lte),M1;(function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"})(M1||(M1={}));var Zv;function dte(e){Zv=e.wasm.cwrap(Di,null,["number","array","number","number","array","array","number","number"])}function pte(e){let{inputs:{x:t},backend:a,attrs:{paddings:n,mode:r}}=e,s=n.map((f,m)=>f[0]+t.shape[m]+f[1]),i=a.dataIdMap.get(t.dataId).id,o=a.makeOutput(s,t.dtype),l=a.dataIdMap.get(o.dataId).id,u=new Uint8Array(new Int32Array(t.shape).buffer),p=n.map(f=>f[0]),c=n.map(f=>f[1]),d=new Uint8Array(new Int32Array(p).buffer),h=new Uint8Array(new Int32Array(c).buffer);return Zv(i,u,t.shape.length,Tt[t.dtype],d,h,M1[r],l),o}var cte={kernelName:Di,backendName:"wasm",kernelFunc:pte,setupFunc:dte},hte=!0,fte=la(zi,hte),mte=Bt(Vl);function _3(e,t){let a=new Int32Array(e.wasm.HEAPU8.buffer,t,4),n=a[0],r=a[1],s=a[2],i=a[3];return e.wasm._free(t),{pSelectedIndices:n,selectedSize:r,pSelectedScores:s,pValidOutputs:i}}var Yv;function gte(e){Yv=e.wasm.cwrap(Bi,"number",["number","number","number","number","number"])}function xte(e){let{backend:t,inputs:a,attrs:n}=e,{iouThreshold:r,maxOutputSize:s,scoreThreshold:i}=n,{boxes:o,scores:l}=a,u=t.dataIdMap.get(o.dataId).id,p=t.dataIdMap.get(l.dataId).id,c=Yv(u,p,s,r,i),{pSelectedIndices:d,selectedSize:h,pSelectedScores:f,pValidOutputs:m}=_3(t,c);return t.wasm._free(f),t.wasm._free(m),t.makeOutput([h],"int32",d)}var Ate={kernelName:Bi,backendName:"wasm",setupFunc:gte,kernelFunc:xte},Jv;function yte(e){Jv=e.wasm.cwrap(Ul,"number",["number","number","number","number","number","bool"])}function bte(e){let{backend:t,inputs:a,attrs:n}=e,{iouThreshold:r,maxOutputSize:s,scoreThreshold:i,padToMaxOutputSize:o}=n,{boxes:l,scores:u}=a,p=t.dataIdMap.get(l.dataId).id,c=t.dataIdMap.get(u.dataId).id,d=Jv(p,c,s,r,i,o),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=_3(t,d);t.wasm._free(m);let x=t.makeOutput([f],"int32",h),A=t.makeOutput([],"int32",g);return[x,A]}var vte={kernelName:Ul,backendName:"wasm",setupFunc:yte,kernelFunc:bte},Qv;function wte(e){Qv=e.wasm.cwrap(Wi,"number",["number","number","number","number","number","number"])}function kte(e){let{backend:t,inputs:a,attrs:n}=e,{iouThreshold:r,maxOutputSize:s,scoreThreshold:i,softNmsSigma:o}=n,{boxes:l,scores:u}=a,p=t.dataIdMap.get(l.dataId).id,c=t.dataIdMap.get(u.dataId).id,d=Qv(p,c,s,r,i,o),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=_3(t,d);t.wasm._free(g);let x=t.makeOutput([f],"int32",h),A=t.makeOutput([f],"float32",m);return[x,A]}var Ite={kernelName:Wi,backendName:"wasm",setupFunc:wte,kernelFunc:kte},Ste=!1,Tte=la(Li,Ste,"bool"),e8;function Cte(e){e8=e.wasm.cwrap(Vi,null,["number","number","number","number","number"])}function Nte(e){let{inputs:t,backend:a,attrs:n}=e,{indices:r}=t,{dtype:s,depth:i,onValue:o,offValue:l}=n,u=a.makeOutput([...r.shape,i],s),p=a.dataIdMap.get(u.dataId).id,c=a.dataIdMap.get(r.dataId).id;return e8(c,i,o,l,p),u}var Ete={kernelName:Vi,backendName:"wasm",setupFunc:Cte,kernelFunc:Nte};function Rte(e){let{inputs:{x:t},backend:a}=e,n=a.makeOutput(t.shape,t.dtype);return a.typedArrayFromHeap(n).fill(1),n}var Mte={kernelName:Gl,backendName:"wasm",kernelFunc:Rte};function $te(e){let{inputs:t,backend:a,attrs:n}=e,{axis:r}=n;if(t.length===1)return R1({inputs:{input:t[0]},backend:a,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(p=>{v.assertShapesMatch(s,p.shape,"All tensors passed to stack must have matching shapes"),v.assert(i===p.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(p=>{let c=R1({inputs:{input:p},backend:a,attrs:{dim:r}});return o.push(c),c}),u=Rv({inputs:l,backend:a,attrs:{axis:r}});return o.forEach(p=>a.disposeData(p.dataId)),u}var _te={kernelName:Hl,backendName:"wasm",kernelFunc:$te},t8;function Pte(e){t8=e.wasm.cwrap(Ui,null,["number","array","number","number","array","array","number","number"])}function Fte(e){let{inputs:{x:t},backend:a,attrs:{paddings:n,constantValue:r}}=e,s=n.map((f,m)=>f[0]+t.shape[m]+f[1]);if(v.sizeFromShape(t.shape)===0)return zv({backend:a,attrs:{shape:s,value:r,dtype:t.dtype}});let i=a.dataIdMap.get(t.dataId).id,o=a.makeOutput(s,t.dtype),l=a.dataIdMap.get(o.dataId).id,u=new Uint8Array(new Int32Array(t.shape).buffer),p=n.map(f=>f[0]),c=n.map(f=>f[1]),d=new Uint8Array(new Int32Array(p).buffer),h=new Uint8Array(new Int32Array(c).buffer);return t8(i,u,t.shape.length,Tt[t.dtype],d,h,r,l),o}var a8={kernelName:Ui,backendName:"wasm",kernelFunc:Fte,setupFunc:Pte},Ote=!1,Dte=la(Gi,Ote),n8;function zte(e){n8=e.wasm.cwrap(Hi,null,["number","number","number"])}function Lte(e){let{inputs:t,backend:a}=e,{x:n,alpha:r}=t,s=a.dataIdMap.get(n.dataId).id,i=a.dataIdMap.get(r.dataId).id,o=s,l=n,u=l;l.dtype!=="float32"&&(u=xu({backend:a,inputs:{x:n},attrs:{dtype:"float32"}}),o=a.dataIdMap.get(u.dataId).id);let p=a.makeOutput(n.shape,"float32"),c=a.dataIdMap.get(p.dataId).id;return n8(o,i,c),l.dtype!=="float32"&&a.disposeData(u.dataId),p}var Bte={kernelName:Hi,backendName:"wasm",setupFunc:zte,kernelFunc:Lte},r8;function Wte(e){r8=e.wasm.cwrap(ji,null,["number","number","number","number"])}function Vte(e){let{backend:t,inputs:a,attrs:n}=e,{axis:r,keepDims:s}=n,{x:i}=a,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:p,axes:c,originalAxes:d,inputWasTransposed:h}=us(i,r,t),f=c;if(h){let y=t.dataIdMap.get(p.dataId).id;y!==o&&(u=p,l=y,f=T.getInnerMostAxes(f.length,u.shape.length))}T.assertAxesAreInnerMostDims("prod",f,u.shape.length);let[m,g]=T.computeOutAndReduceShapes(u.shape,f),x=v.sizeFromShape(g),A=t.makeOutput(m,u.dtype);if(v.sizeFromShape(u.shape)!==0){let y=t.dataIdMap.get(A.dataId).id;r8(l,x,Tt[A.dtype],y)}if(h&&t.disposeData(p.dataId),s){let y=T.expandShapeToKeepDim(A.shape,d);A.shape=y}return A}var Ute={kernelName:ji,backendName:"wasm",setupFunc:Wte,kernelFunc:Vte},Gte=e=>{let{backend:t,attrs:a}=e,{start:n,stop:r,step:s,dtype:i}=a,o=d3(n,r,s,i),l=t.makeOutput([o.length],i);return t.typedArrayFromHeap(l).set(o),l},Hte={kernelName:jl,backendName:"wasm",kernelFunc:Gte},jte=!0,qte=la(ci,jte),Xte=Bt(qi),Kte=Bt(Xi),Zte=Bt(Yi),s8;function Yte(e){s8=e.wasm.cwrap(Zi,null,["number","number","number","number","number","number","number","number","number","number"])}function Jte(e){let{backend:t,inputs:a,attrs:n}=e,{images:r}=a,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,[p,c,d,h]=r.shape,f=[p,l,u,h],m=t.dataIdMap.get(r.dataId),g;m.dtype!=="float32"&&(g=xu({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(g.dataId));let x=m.id,A=t.makeOutput(f,"float32");if(v.sizeFromShape(r.shape)===0)return A;let y=t.dataIdMap.get(A.dataId).id;return s8(x,p,c,d,h,l,u,s?1:0,i?1:0,y),g!=null&&t.disposeData(g.dataId),A}var Qte={kernelName:Zi,backendName:"wasm",setupFunc:Yte,kernelFunc:Jte},i8;function eae(e){i8=e.wasm.cwrap(Ki,null,["number","number","number","number","number","number","number","number","number","number"])}function tae(e){let{backend:t,inputs:a,attrs:n}=e,{images:r}=a,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,[p,c,d,h]=r.shape,f=[p,l,u,h],m=t.makeOutput(f,"float32");if(v.sizeFromShape(r.shape)===0)return m;let g=t.dataIdMap.get(r.dataId),x;g.dtype!=="float32"&&(x=xu({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),g=t.dataIdMap.get(x.dataId));let A=g.id,y=t.dataIdMap.get(m.dataId).id;return i8(A,p,c,d,h,l,u,s?1:0,i?1:0,y),x!=null&&t.disposeData(x.dataId),m}var aae={kernelName:Ki,backendName:"wasm",setupFunc:eae,kernelFunc:tae},o8;function nae(e){o8=e.wasm.cwrap(Ji,null,["number","array","number","array","number","number"])}function rae(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{dims:s}=n,i=v.parseAxisParam(s,r.shape);if(r.shape.length===0)return Bh({inputs:{x:r},backend:a});let o=a.makeOutput(r.shape,r.dtype),l=a.dataIdMap.get(r.dataId).id,u=a.dataIdMap.get(o.dataId).id,p=new Uint8Array(new Int32Array(i).buffer),c=new Uint8Array(new Int32Array(r.shape).buffer);o8(l,p,i.length,c,r.shape.length,u);let d=za({inputs:{x:o},attrs:{shape:r.shape},backend:a});return a.disposeData(o.dataId),d}var sae={kernelName:Ji,backendName:"wasm",kernelFunc:rae,setupFunc:nae},l8;function iae(e){l8=e.wasm.cwrap(mo,null,["number","number","number","number","number","number","number","number","array","number","number"])}function oae(e){let{inputs:t,backend:a,attrs:n}=e,{image:r}=t,{radians:s,fillValue:i,center:o}=n,l=a.makeOutput(r.shape,r.dtype),u=a.dataIdMap.get(r.dataId).id,p=a.dataIdMap.get(l.dataId).id,[c,d,h,f]=r.shape,[m,g]=T.getImageCenter(o,d,h),x=i===0,A=255,y=typeof i=="number"?[i,i,i,x?0:A]:[...i,A],b=new Uint8Array(new Int32Array(y).buffer);return l8(u,c,d,h,f,s,m,g,b,y.length,p),l}var lae={kernelName:mo,backendName:"wasm",kernelFunc:oae,setupFunc:iae},uae=Bt(Xl),dae=Bt(Qi),u8;function pae(e){u8=e.wasm.cwrap(eo,null,["number","number","number","number","number","number","array","number","number"])}function cae(e){let{backend:t,inputs:a,attrs:n}=e,{indices:r,updates:s}=a,{shape:i}=n,o=t.makeOutput(i,s.dtype);if(v.sizeFromShape(i)===0)return o;let{sliceRank:l,numUpdates:u,sliceSize:p,strides:c,outputSize:d}=h2.calculateShapes(s,r,i),h=t.dataIdMap.get(r.dataId).id,f=t.dataIdMap.get(s.dataId).id,m=new Uint8Array(new Int32Array(c).buffer),g=t.dataIdMap.get(o.dataId).id;return u8(h,f,Tt[s.dtype],l,u,p,m,d,g),o}var hae={kernelName:eo,backendName:"wasm",setupFunc:pae,kernelFunc:cae},d8;function fae(e){d8=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function mae(e){let{inputs:t,backend:a}=e,{condition:n,t:r,e:s}=t,i=a.dataIdMap.get(n.dataId).id,o=a.dataIdMap.get(r.dataId).id,l=a.dataIdMap.get(s.dataId).id,u=a.makeOutput(r.shape,r.dtype),p=a.dataIdMap.get(u.dataId).id,c=n.shape.length,d=r.shape.length,h=c===0||c>1||d===1?1:v.sizeFromShape(r.shape.slice(1));return d8(i,o,l,h,p),u}var gae={kernelName:Kl,backendName:"wasm",kernelFunc:mae,setupFunc:fae},p8;function xae(e){p8=e.wasm.cwrap(ao,null,["number","number"])}function Aae(e){let{backend:t,inputs:{x:a}}=e,n=t.dataIdMap.get(a.dataId).id,r=t.makeOutput(a.shape,a.dtype),s=t.dataIdMap.get(r.dataId).id;return v.sizeFromShape(r.shape)===0||p8(n,s),r}var yae={kernelName:"Sigmoid",backendName:"wasm",setupFunc:xae,kernelFunc:Aae},bae=Bt(to),c8;function vae(e){c8=e.wasm.cwrap(so,null,["number","number","number","number"])}function wae(e){let{backend:t,inputs:{logits:a},attrs:{dim:n}}=e,r=t.dataIdMap.get(a.dataId).id,s=t.makeOutput(a.shape,a.dtype),i=t.dataIdMap.get(s.dataId).id,o=a.shape[n],l=v.sizeFromShape(a.shape)/o;return v.sizeFromShape(s.shape)===0||c8(r,i,o,l),s}var kae={kernelName:so,backendName:"wasm",setupFunc:vae,kernelFunc:wae};function Iae(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{blockShape:s,paddings:i}=n,o=v.sizeFromShape(s),l=[[0,0]];l.push(...i);for(let g=1+s.length;g<r.shape.length;++g)l.push([0,0]);let u=a8.kernelFunc({inputs:{x:r},backend:a,attrs:{paddings:l,constantValue:0}}),p=T.getReshaped(u.shape,s,o,!1),c=T.getPermuted(p.length,s.length,!1),d=T.getReshapedPermuted(u.shape,s,o,!1),h=za({inputs:{x:u},backend:a,attrs:{shape:p}}),f=Qr({inputs:{x:h},backend:a,attrs:{perm:c}}),m=za({inputs:{x:f},backend:a,attrs:{shape:d}});return a.disposeData(u.dataId),a.disposeData(h.dataId),a.disposeData(f.dataId),m}var Sae={kernelName:Jl,backendName:"wasm",kernelFunc:Iae},h8;function Tae(e){h8=e.wasm.cwrap("SparseFillEmptyRows","number",["number","number","number","number","number","number","number","number","number","number","number","number"])}function Cae(e){let{backend:t,inputs:a}=e,{indices:n,values:r,denseShape:s,defaultValue:i}=a,o=n.shape[0],l=n.shape[1],u=t.readSync(s.dataId)[0],p=[o+u,l],c=t.dataIdMap.get(n.dataId).id,d=t.dataIdMap.get(r.dataId).id,h=t.dataIdMap.get(i.dataId).id,f=t.makeOutput(p,n.dtype),m=t.dataIdMap.get(f.dataId).id,g=t.makeOutput(p.slice(0,1),r.dtype),x=t.dataIdMap.get(g.dataId).id,A=t.makeOutput([u],"bool"),y=t.dataIdMap.get(A.dataId).id,b=t.makeOutput([o],n.dtype),w=t.dataIdMap.get(b.dataId).id,S=t.makeOutput([4],"int32"),C=t.dataIdMap.get(S.dataId).id,E=h8(c,d,Tt[r.dtype],o,u,l,h,m,x,y,w,C),_=t.readSync(S.dataId),$;switch(_[0]){case 1:{$=T.getSparseFillEmptyRowsIndicesDenseShapeMismatch(_[1]);break}case 2:{$=T.getSparseFillEmptyRowsNegativeIndexErrorMessage(_[1],_[2]);break}case 3:$=T.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(_[1],_[2],_[3]);break;default:$=""}if(t.disposeData(S.dataId),$)throw t.disposeData(f.dataId),t.disposeData(g.dataId),t.disposeData(A.dataId),t.disposeData(b.dataId),new Error($);let M=f,I=g;return E!==p[0]&&(M=qs({inputs:{x:f},attrs:{begin:0,size:[E,l]},backend:t}),I=qs({inputs:{x:g},attrs:{begin:0,size:E},backend:t}),t.disposeData(f.dataId),t.disposeData(g.dataId)),[M,I,A,b]}var Nae={kernelName:Od,backendName:"wasm",setupFunc:Tae,kernelFunc:Cae},f8;function Eae(e){f8=e.wasm.cwrap(eu,null,["number","number","number","number","number","number","number"])}function Rae(e){let{backend:t,inputs:a}=e,{inputIndices:n,inputShape:r,newShape:s}=a;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
${n.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
${r.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=t.dataIdMap.get(n.dataId).id,o=t.dataIdMap.get(r.dataId).id,l=t.dataIdMap.get(s.dataId).id,u=n.shape[0],p=v.sizeFromShape(s.shape),c=t.makeOutput([u,p],n.dtype),d=t.dataIdMap.get(c.dataId).id,h=t.makeOutput([p],s.dtype),f=t.dataIdMap.get(h.dataId).id,m=t.makeOutput([3],"int32"),g=t.dataIdMap.get(m.dataId).id;f8(i,o,l,u,d,f,g);let x=t.readSync(m.dataId),A;switch(x[0]){case 0:{A=T.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(x[1],x[2]);break}case 1:{A=T.getSparseReshapeNegativeOutputDimErrorMessage(x[1],x[2]);break}case 2:A=T.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();break;case 3:{let y=Array.from(t.readSync(r.dataId)),b=Array.from(t.readSync(h.dataId));A=T.getSparseReshapeInputOutputMultipleErrorMessage(y,b);break}case 4:{let y=Array.from(t.readSync(r.dataId)),b=Array.from(t.readSync(h.dataId));A=T.getSparseReshapeInputOutputMismatchErrorMessage(y,b);break}default:A=""}if(t.disposeData(m.dataId),A)throw t.disposeData(c.dataId),t.disposeData(h.dataId),new Error(A);return[c,h]}var Mae={kernelName:eu,backendName:"wasm",setupFunc:Eae,kernelFunc:Rae},m8;function g8(e){m8=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function x8(e,t){let{backend:a,inputs:n}=e,{data:r,indices:s,segmentIds:i}=n,o=s.shape[0],l=a.readSync(i.dataId,o-1,o)[0],u=o>0?l+1:0;if(u<0)throw new Error(T.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let p=r.shape.slice();p[0]=u;let c=a.dataIdMap.get(r.dataId).id,d=a.dataIdMap.get(s.dataId).id,h=a.dataIdMap.get(i.dataId).id,f=a.makeOutput(p,r.dtype),m=a.dataIdMap.get(f.dataId).id,g=a.makeOutput([4],"int32"),x=a.dataIdMap.get(g.dataId).id;m8(c,Tt[r.dtype],r.shape[0],d,h,m,x,t,0);let A=a.readSync(g.dataId),y;switch(A[0]){case 0:{y=T.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break}case 1:{y=T.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break}case 2:y=T.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(A[1],A[2]);break;case 3:y=T.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(A[1],A[2],A[3]);break;default:y=""}if(a.disposeData(g.dataId),y)throw a.disposeData(f.dataId),new Error(y);return f}function $ae(e){return x8(e,!0)}var _ae={kernelName:Dd,backendName:"wasm",setupFunc:g8,kernelFunc:$ae};function Pae(e){return x8(e,!1)}var Fae={kernelName:zd,backendName:"wasm",setupFunc:g8,kernelFunc:Pae};function Oae(e){let{inputs:t,attrs:a,backend:n}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=a,o=v.parseAxisParam(i,r.shape)[0],l=T.prepareSplitSize(r,s,o),u=new Array(r.shape.length).fill(0),p=r.shape.slice();return l.map(c=>{let d=[...p];d[o]=c;let h=qs({inputs:{x:r},attrs:{begin:u,size:d},backend:n});return u[o]+=c,h})}var Dae={kernelName:Ql,backendName:"wasm",kernelFunc:Oae},zae=Bt(no),Lae=Bt(Bd),Bae=!0,Wae=la(io,Bae),A8;function Vae(e){A8=e.wasm.cwrap(fo,null,["number","number","number","number"])}function Uae(e){let{backend:t,inputs:a,attrs:n}=e,{alpha:r}=n,{x:s}=a,i=t.dataIdMap.get(s.dataId).id,o=t.makeOutput(s.shape,s.dtype),l=t.dataIdMap.get(o.dataId).id;return A8(i,r,Tt[s.dtype],l),o}var Gae={kernelName:fo,backendName:"wasm",setupFunc:Vae,kernelFunc:Uae},y8;function Hae(e){y8=e.wasm.cwrap(oo,null,["number","array","number","array","array","array","array","array","number","number"])}function jae(e){let{backend:t,inputs:a,attrs:n}=e,{x:r}=a,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:p,newAxisMask:c,shrinkAxisMask:d}=n,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:x,begin:A,end:y,strides:b}=It.sliceInfo(r.shape,s,i,o,l,u,p,c,d),w;if(m)w=za({inputs:{x:r},backend:t,attrs:{shape:f}});else if(g||x){v.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let S=It.computeOutShape(A,y,b),C=qs({inputs:{x:r},backend:t,attrs:{begin:A,size:S}});w=za({inputs:{x:C},backend:t,attrs:{shape:f}}),t.disposeData(C.dataId)}else{let S=t.makeOutput(h,"float32"),C=t.dataIdMap.get(r.dataId).id,E=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),_=new Uint8Array(new Int32Array(A).buffer),$=new Uint8Array(new Int32Array(y).buffer),M=new Uint8Array(new Int32Array(b).buffer),I=new Uint8Array(new Int32Array(h).buffer),N=new Uint8Array(new Int32Array(v.computeStrides(h)).buffer),O=t.dataIdMap.get(S.dataId).id;y8(C,E,r.shape.length,_,$,M,I,N,h.length,O),w=za({inputs:{x:S},backend:t,attrs:{shape:f}}),t.disposeData(S.dataId)}return w}var qae={kernelName:oo,backendName:"wasm",setupFunc:Hae,kernelFunc:jae};function Xae(e){let{backend:t,inputs:a,attrs:n}=e,{data:r,dataSplits:s}=a,{separator:i,nGramWidths:o,leftPad:l,rightPad:u,padWidth:p,preserveShortSequences:c}=n,d=t.readSync(r.dataId),h=t.readSync(s.dataId),[f,m]=c3(d,h,i,o,l,u,p,c),g=t.makeOutput([f.length],"string"),x=t.dataIdMap.get(g.dataId);x.stringBytes=f;let A=t.makeOutput(s.shape,"int32");return t.typedArrayFromHeap(A).set(m),[g,A]}var Kae={kernelName:tu,backendName:"wasm",kernelFunc:Xae};function Zae(e){let{backend:t,inputs:a,attrs:n}=e,{input:r,delimiter:s}=a,{skipEmpty:i}=n,o=t.readSync(r.dataId),l=t.readSync(s.dataId),[u,p,c]=h3(o,l[0],i),d=p.length,h=t.makeOutput([d,2],"int32");t.typedArrayFromHeap(h).set(u);let f=t.makeOutput([d],"string"),m=t.dataIdMap.get(f.dataId);m.stringBytes=p;let g=t.makeOutput([2],"int32");return t.typedArrayFromHeap(g).set(c),[h,f,g]}var Yae={kernelName:Wd,backendName:"wasm",kernelFunc:Zae};function Jae(e){let{backend:t,inputs:a,attrs:n}=e,{input:r}=a,{numBuckets:s}=n,i=t.readSync(r.dataId),o=f3(i,s),l=t.makeOutput(r.shape,"int32");return t.typedArrayFromHeap(l).set(o),l}var Qae={kernelName:Vd,backendName:"wasm",kernelFunc:Jae},ene=!0,tne=la(lo,ene),b8;function ane(e){b8=e.wasm.cwrap(ro,null,["number","number","number","number"])}function nne(e){let{backend:t,inputs:a,attrs:n}=e,{axis:r,keepDims:s}=n,{x:i}=a,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:p,axes:c,originalAxes:d,inputWasTransposed:h}=us(i,r,t),f=c;if(h){let y=t.dataIdMap.get(p.dataId).id;y!==o&&(u=p,l=y,f=T.getInnerMostAxes(f.length,u.shape.length))}T.assertAxesAreInnerMostDims("sum",f,u.shape.length);let[m,g]=T.computeOutAndReduceShapes(u.shape,f),x=v.sizeFromShape(g),A=t.makeOutput(m,u.dtype);if(v.sizeFromShape(u.shape)!==0){let y=t.dataIdMap.get(A.dataId).id;b8(l,x,Tt[A.dtype],y)}if(h&&t.disposeData(p.dataId),s){let y=T.expandShapeToKeepDim(A.shape,d);A.shape=y}return A}var rne={kernelName:ro,backendName:"wasm",setupFunc:ane,kernelFunc:nne},sne=Bt(uo),ine=Bt(po),v8;function one(e){v8=e.wasm.cwrap(ns,null,["number","array","number","array","number","number"])}function lne(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,s=a.dataIdMap.get(r.dataId).id,{reps:i}=n,o=new Array(r.shape.length);for(let d=0;d<o.length;d++)o[d]=r.shape[d]*i[d];let l=new Uint8Array(new Int32Array(r.shape).buffer),u=new Uint8Array(new Int32Array(o).buffer),p=a.makeOutput(o,r.dtype),c=a.dataIdMap.get(p.dataId).id;return v8(s,l,r.shape.length,u,o.length,Tt[p.dtype],c),p}var une={kernelName:ns,backendName:"wasm",setupFunc:one,kernelFunc:lne},w8;function dne(e){w8=e.wasm.cwrap(co,null,["number","array","number","number","number","bool","number","number"])}var pne=({inputs:e,backend:t,attrs:a})=>{let{x:n}=e,{k:r,sorted:s}=a,i=t.dataIdMap.get(n.dataId).id,o=new Uint8Array(new Int32Array(n.shape).buffer),l=n.shape.slice();l[l.length-1]=r;let u=t.makeOutput(l,n.dtype),p=t.dataIdMap.get(u.dataId).id,c=t.makeOutput(l,"int32"),d=t.dataIdMap.get(c.dataId).id;return w8(i,o,n.shape.length,Tt[n.dtype],r,s,p,d),[u,c]},cne={kernelName:co,backendName:"wasm",setupFunc:dne,kernelFunc:pne},k8;function hne(e){k8=e.wasm.cwrap(ho,null,["number","number","bool","number","number","number","number","number","number","array","number","array","number","number","number","number","number"])}function fne(e){let{backend:t,inputs:a,attrs:n}=e,{image:r,transforms:s}=a,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=n,[p,c,d,h]=r.shape,[f,m]=u!=null?u:[c,d],g=[p,f,m,h],x=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),A=new Uint8Array(new Int32Array(v.computeStrides(g)).buffer),y=t.makeOutput(g,r.dtype),b=t.dataIdMap.get(y.dataId).id,w=t.dataIdMap.get(r.dataId).id,S=t.dataIdMap.get(s.dataId).id,C=i==="nearest"?1:2,E;switch(o){case"constant":E=1;break;case"reflect":E=2;break;case"wrap":E=3;break;case"nearest":E=4;break;default:E=1;break}return k8(w,S,s.shape[0]>1,p,f,m,h,d,c,x,r.shape.length-1,A,g.length-1,C,E,l,b),y}var mne={kernelName:ho,backendName:"wasm",setupFunc:hne,kernelFunc:fne};function gne(e){let{inputs:t,backend:a,attrs:n}=e,{value:r}=t,{axis:s}=n;s<0&&(s+=r.shape.length);let i=r.shape[s],o=r.shape.length,l=new Array(o-1),u=0;for(let h=0;h<o;h++)h!==s&&(l[u++]=r.shape[h]);let p=new Array(i),c=new Array(o).fill(0),d=r.shape.slice();d[s]=1;for(let h=0;h<p.length;h++)c[s]=h,p[h]=qs({inputs:{x:r},attrs:{begin:c,size:d},backend:a});return p.map(({dataId:h,dtype:f})=>({dataId:h,dtype:f,shape:l}))}var xne={kernelName:au,backendName:"wasm",kernelFunc:gne};function Ane(e){let{inputs:{x:t},backend:a}=e,n=a.makeOutput(t.shape,t.dtype);return a.typedArrayFromHeap(n).fill(0),n}var yne={kernelName:nu,backendName:"wasm",kernelFunc:Ane},bne=[jJ,qJ,KJ,JJ,iQ,uQ,cQ,mQ,yQ,SQ,TQ,CQ,RQ,MQ,PQ,DQ,zQ,LQ,VQ,HQ,XQ,YQ,eee,tee,nee,ree,see,iee,uee,dee,cee,mee,Aee,vee,Iee,Cee,Eee,Mee,QJ,$ee,Fee,Dee,Lee,Bee,Vee,Uee,Hee,qee,Zee,Jee,tte,rte,ote,ute,cte,fte,mte,Ate,vte,Ite,Tte,Ete,Mte,_te,a8,Dte,Bte,Ute,Hte,qte,Xte,Kte,Zte,gQ,Qte,aae,sae,lae,uae,dae,hae,gae,yae,bae,kQ,kae,Sae,Nae,Mae,_ae,Fae,Dae,zae,Lae,Wae,Gae,qae,Kae,Yae,Qae,tne,rne,sne,ine,une,cne,mne,nQ,xne,yne];for(let e of bne)mn(e);var $1=W();$1.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}});$1.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if($1.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 Ox=yl(nS()),vne=yl(rS()),Dx=yl(sS()),zx=Ox.default||Ox,wne=Dx.default||Dx,I8=class extends bl{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(S8),_1=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new vd(this,kt())}write(e,t,a){let n={id:this.dataIdNextNumber++};return this.move(n,e,t,a,1),n}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=v.now();return e(),{kernelMs:v.now()-t}}move(e,t,a,n,r){let s=this.dataIdNextNumber++;if(n==="string"){let u=t;this.dataIdMap.set(e,{id:s,stringBytes:u,shape:a,dtype:n,memoryOffset:null,refCount:r});return}let i=v.sizeFromShape(a),o=i*v.bytesPerElement(n),l=this.wasm._malloc(o);this.dataIdMap.set(e,{id:s,memoryOffset:l,shape:a,dtype:n,refCount:r}),this.wasm.tfjs.registerTensor(s,i,l),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,o),l)}async read(e){return this.readSync(e)}readSync(e,t,a){let{memoryOffset:n,dtype:r,shape:s,stringBytes:i}=this.dataIdMap.get(e);if(r==="string")return(t==null||t===0)&&(a==null||a>=i.length)?i:i.slice(t,a);t=t||0,a=a||v.sizeFromShape(s);let o=v.bytesPerElement(r),l=this.wasm.HEAPU8.slice(n+t*o,n+a*o);return Sne(l.buffer,r)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){let a=this.dataIdMap.get(e);if(a.refCount--,!t&&a.refCount>0)return!1;this.wasm._free(a.memoryOffset),this.wasm.tfjs.disposeData(a.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,a){let n;if(a==null)n=this.write(null,e,t);else{let r=this.dataIdNextNumber++;n={id:r},this.dataIdMap.set(n,{id:r,memoryOffset:a,shape:e,dtype:t,refCount:1});let s=v.sizeFromShape(e);this.wasm.tfjs.registerTensor(r,s,a)}return{dataId:n,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:a}){let n=this.wasm.HEAPU8.buffer,{memoryOffset:r}=this.dataIdMap.get(a),s=v.sizeFromShape(e);switch(t){case"float32":return new Float32Array(n,r,s);case"int32":return new Int32Array(n,r,s);case"bool":return new Uint8Array(n,r,s);default:throw new Error(`Unknown dtype ${t}`)}}};function kne(e){return(t,a)=>(v.fetch(e,{credentials:"same-origin"}).then(n=>{n.ok||t.env.a(`failed to load wasm binary file at '${e}'`),n.arrayBuffer().then(r=>{WebAssembly.instantiate(r,t).then(s=>{a(s.instance,s.module)})})}),{})}function Lx(e,t,a){if(Bc!=null)return Bc;let n="tfjs-backend-wasm.wasm";return e&&t?n="tfjs-backend-wasm-threaded-simd.wasm":e&&(n="tfjs-backend-wasm-simd.wasm"),ed!=null&&ed[n]!=null?ed[n]:a+n}async function Ine(){let[e,t]=await Promise.all([W().getAsync("WASM_HAS_SIMD_SUPPORT"),W().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((a,n)=>{let r={};r.locateFile=(o,l)=>{if(o.endsWith(".worker.js")){let u=vne.wasmWorkerContents.replace(/\n/g,"\\n"),p=new Blob([u],{type:"application/javascript"});return URL.createObjectURL(p)}return o.endsWith(".wasm")?Lx(e,t,Yu!=null?Yu:l):l+o},P3&&(r.instantiateWasm=kne(Lx(e,t,Yu!=null?Yu:"")));let s=!1;r.onAbort=()=>{s||td||(td=!0,n({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"}))};let i;t&&e&&Bc==null?(r.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+zx.toString()],{type:"text/javascript"}),i=zx(r)):i=wne(r),i.then(o=>{s=!0,td=!1;let l=null;o.tfjs={init:o.cwrap("init",null,[]),initWithThreadsCount:o.cwrap("init_with_threads_count",null,["number"]),getThreadsCount:o.cwrap("get_threads_count","number",[]),registerTensor:o.cwrap("register_tensor",null,["number","number","number"]),disposeData:o.cwrap("dispose_data",l,["number"]),dispose:o.cwrap("dispose",l,[])},a({wasm:o})}).catch(n)})}function Sne(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 Tne=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],Bc=null,Yu=null,ed={},td=!1,P3=!1;function Cne(e,t=!1){if(l2("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),td)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");Bc=e,P3=t}function Wh(e,t=!1){if(td)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")Yu=e;else{ed=e;let a=Tne.filter(n=>ed[n]==null);if(a.length>0)throw new Error(`There were no entries found for the following binaries: ${a.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.`)}P3=t}var S8=-1,_1=-1;function Nne(e){S8=e}function Ene(){if(_1===-1)throw new Error("WASM backend not initialized.");return _1}var Rne="4.1.0",Mne=2;go("wasm",async()=>{let{wasm:e}=await Ine();return new I8(e)},Mne);var zn=W();zn.registerFlag("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE",()=>15);zn.registerFlag("WEBGPU_CPU_FORWARD",()=>!0);zn.registerFlag("WEBGPU_MATMUL_PROGRAM_TYPE",()=>-1);zn.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE",()=>!1);zn.registerFlag("WEBGPU_USE_LOW_POWER_GPU",()=>!1);zn.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e3);zn.registerFlag("WEBGPU_USE_PROFILE_TOOL",()=>!1);zn.registerFlag("WEBGPU_IMPORT_EXTERNAL_TEXTURE",()=>!0);zn.registerFlag("WEBGPU_USE_NAIVE_CONV2D_DEBUG",()=>!1);zn.registerFlag("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL",()=>0);zn.registerFlag("WEBGPU_CONV_SEPARATE_IM2COL_SHADER",()=>!1);var $ne=class{constructor(e){e&&(this.vendor=e.vendor,this.architecture=e.architecture,this.intelGPUGeneration=this.getIntelGPUGeneration())}getIntelGPUGeneration(){if(this.isIntel()){if(this.architecture.startsWith("gen"))return Number(this.architecture.match(/\d+/));if(this.architecture.startsWith("xe"))return 12}return 0}isIntel(){return this.vendor==="intel"}},_ne=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,a=!1){let n=Bx(e,t);if(this.freeBuffers.has(n)||this.freeBuffers.set(n,[]),this.usedBuffers.has(n)||this.usedBuffers.set(n,[]),this.numBytesUsed+=e,this.numUsedBuffers++,this.freeBuffers.get(n).length>0){this.numFreeBuffers--;let s=this.freeBuffers.get(n).shift();return this.usedBuffers.get(n).push(s),s}this.numBytesAllocated+=e;let r=this.device.createBuffer({size:e,usage:t,mappedAtCreation:a});return this.usedBuffers.get(n).push(r),r}releaseBuffer(e,t,a){if(this.freeBuffers.size===0)return;let n=Bx(t,a);this.freeBuffers.has(n)||this.freeBuffers.set(n,[]),this.freeBuffers.get(n).push(e),this.numFreeBuffers++,this.numUsedBuffers--;let r=this.usedBuffers.get(n),s=r.indexOf(e);if(s<0)throw new Error("Cannot release a buffer that was never provided by this buffer manager");r.splice(s,1),this.numBytesUsed-=t}releaseUploadBuffer(e,t,a){e.mapAsync(GPUMapMode.WRITE).then(()=>{this.releaseBuffer(e,t,a)},n=>{})}getNumUsedBuffers(){return this.numUsedBuffers}getNumFreeBuffers(){return this.numFreeBuffers}dispose(){this.freeBuffers.forEach((e,t)=>{e.forEach(a=>{a.destroy()})}),this.usedBuffers.forEach((e,t)=>{e.forEach(a=>{a.destroy()})}),this.freeBuffers=new Map,this.usedBuffers=new Map,this.numUsedBuffers=0,this.numFreeBuffers=0,this.numBytesUsed=0,this.numBytesAllocated=0}};function Bx(e,t){return`${e}_${t}`}var Pne=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,a,n){let r=Vx(a),s=e*t*r,i=Wx(e,t,a,n);if(this.freeTextures.has(i)||this.freeTextures.set(i,[]),this.usedTextures.has(i)||this.usedTextures.set(i,[]),this.numBytesUsed+=s,this.numUsedTextures++,this.freeTextures.get(i).length>0){this.numFreeTextures--;let l=this.freeTextures.get(i).shift();return this.usedTextures.get(i).push(l),l}this.numBytesAllocated+=s;let o=this.device.createTexture({size:[e,t],format:a,usage:n});return this.usedTextures.get(i).push(o),o}releaseTexture(e,t,a,n,r){if(this.freeTextures.size===0)return;let s=Wx(t,a,n,r);this.freeTextures.has(s)||this.freeTextures.set(s,[]),this.freeTextures.get(s).push(e),this.numFreeTextures++,this.numUsedTextures--;let i=this.usedTextures.get(s),o=i.indexOf(e);if(o<0)throw new Error("Cannot release a texture that was never provided by this texture manager");i.splice(o,1);let l=Vx(n),u=t*a*l;this.numBytesUsed-=u}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){this.freeTextures.forEach((e,t)=>{e.forEach(a=>{a.destroy()})}),this.usedTextures.forEach((e,t)=>{e.forEach(a=>{a.destroy()})}),this.freeTextures=new Map,this.usedTextures=new Map,this.numUsedTextures=0,this.numFreeTextures=0,this.numBytesUsed=0,this.numBytesAllocated=0}};function Wx(e,t,a,n){return`${e}_${t}_${a}_${n}`}function Vx(e){if(e==="rgba8unorm")return 16;throw new Error(`${e} is not supported!`)}function Fne(e,t){if(Math.max(...e)>3)throw new Error("Cannot symbolically compute strides for rank > 4 tensor.");let a=e.length,n=e.map(s=>`${t}[${s}]`),r=new Array(a-1);r[a-2]=n[a-1];for(let s=a-3;s>=0;--s)r[s]=`(${r[s+1]} * ${n[s+1]})`;return r}var One=(e,t,a,n)=>{let r={dtype:n.dtype,shape:n.shape},s=zne(a,r,t),i=e.createShaderModule({code:s,label:t.constructor.name});return e.createComputePipeline({compute:{module:i,entryPoint:"_start"},label:t.constructor.name,layout:"auto"})};function ra(e){if(e<=1)return"i32";if(e===2)return"vec2<i32>";if(e===3)return"vec3<i32>";if(e===4)return"vec4<i32>";if(e===5)return"vec5";if(e===6)return"vec6";throw Error(`GPU for rank ${e} is not yet supported`)}function yr(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 Ce(...e){let t;switch(e.length){case 0:t=`
fn main()
`;break;case 1:t=`
fn main(${e[0]} : i32)
`;break;default:throw Error("Unreachable")}return t}function Ux(e){let t;return t=`
${Dne()}
fn _start(@builtin(local_invocation_id) LocalId : vec3<u32>,
@builtin(global_invocation_id) GlobalId : vec3<u32>,
@builtin(local_invocation_index) LocalIndex: u32,
@builtin(workgroup_id) WorkgroupId : vec3<u32>,
@builtin(num_workgroups) NumWorkgroups : vec3<u32>) {
localId = LocalId;
localIndex = LocalIndex;
globalId = GlobalId;
numWorkgroups = NumWorkgroups;
workgroupId = WorkgroupId;
${e?"main(getGlobalIndex());":"main();"};
}
`,t}function Dne(){return`
@compute @workgroup_size(workgroupSizeX, workgroupSizeY, workgroupSizeZ)
`}function zne(e,t,a){let n=[],r=a.workgroupSize[0]*a.workgroupSize[1]*a.workgroupSize[2];if(n.push(`
const workgroupSizeX = ${a.workgroupSize[0]}u;
const workgroupSizeY = ${a.workgroupSize[1]}u;
const workgroupSizeZ = ${a.workgroupSize[2]}u;
var<private> localId: vec3<u32>;
var<private> localIndex: u32;
var<private> globalId: vec3<u32>;
var<private> numWorkgroups: vec3<u32>;
var<private> workgroupId: vec3<u32>;
// Only used when the y/z dimension of workgroup size is 1.
fn getGlobalIndex() -> i32 {
${T8(a)?" return i32(globalId.x);":` return i32((workgroupId.z * numWorkgroups.x * numWorkgroups.y +
workgroupId.y * numWorkgroups.x + workgroupId.x) * ${r} +
localIndex);
`}
}
`),a.isFromPixels){n.push(`
struct Uniform {
size : i32,
numChannels : i32,
outShapeStrides : vec2<i32>,
};
@group(0) @binding(0) var<storage, read_write> result: array<${ad(t.dtype,a.isVec4)}>;
@group(0) @binding(2) var<uniform> uniforms: Uniform;
`);let h=jx(a);return[Gx,n.join(`
`),Hx(t.shape),a.getUserCode(),Ux(h)].join(`
`)}let s="struct Uniforms { NAN : f32, INFINITY : f32, ";a.variableNames.forEach((h,f)=>{let m=ra(e[f].shape.length);s+=`${h.charAt(0).toLowerCase()+h.slice(1)}Shape : ${m}, `});let i=ra(t.shape.length);s+=`outShape : ${i}, `;let o=t.shape.length-1,l=ra(o);s+=`
outShapeStrides: ${l}, `,a.size&&(s+="size : i32, "),a.uniforms&&(s+=a.uniforms),s+="};",s=qne(s),n.push(s),a.atomic?n.push(`
@group(0) @binding(0) var<storage, read_write> result: array<atomic<i32>>;
`):n.push(`
@group(0) @binding(0) var<storage, read_write> result: array<${ad(t.dtype,a.isVec4)}>;
`),a.variableNames.forEach((h,f)=>{n.push(`
@group(0) @binding(${1+f}) var<storage, read> ${h}: array<${a.variableTypes?a.variableTypes[f]:ad(e[f].dtype,a.isVec4)}>;
`)}),s!==""&&n.push(`
@group(0) @binding(${1+a.variableNames.length}) var<uniform> uniforms: Uniforms;
`);let u=Gne(t.shape,a.dispatchLayout),p=[Gx+Bne,n.join(`
`),Hx(t.shape),u,Hne(t.shape.length)];a.atomic||p.push(jne(t.shape,t.dtype,a.isVec4));let c=e.map((h,f)=>Une(h,t.shape,a.variableTypes?a.variableTypes[f]==="vec4<f32>":a.isVec4,a.dispatchLayout.x.length===t.shape.length)).join(`
`);p.push(c),p.push(a.getUserCode());let d=jx(a);return p.push(Ux(d)),p.join(`
`)}function Lne(e,t,a,n){let r=e.shaderKey;if(e.isFromPixels)return r;let s=a.map(p=>p.dtype).concat(n.dtype),i=a.map(p=>T.getBroadcastDims(p.shape,n.shape)),o=a.map(p=>v.arraysEqual(p.shape,n.shape)).join("_"),l=i.map(p=>p.join("_")).join(";"),u=T8(e)?"flatDispatch":"";return r+="_"+(e.workgroupSize?e.workgroupSize.join(","):"")+t.map(p=>p.length).join(",")+s.join(",")+e.variableNames.join(",")+l+o+u,r}var Gx=`
struct vec5 {x: i32, y: i32, z: i32, w: i32, u: i32};
struct vec6 {x: i32, y: i32, z: i32, w: i32, u: i32, v: i32};
// Checks whether coordinates lie within the bounds of the shape.
fn coordsInBounds2D(coord : vec2<i32>, shape : vec2<i32>) -> bool {
return all(coord >= vec2<i32>(0)) && all(coord < shape);
}
fn coordsInBounds3D(coord : vec3<i32>, shape : vec3<i32>) -> bool {
return all(coord >= vec3<i32>(0)) && all(coord < shape);
}
fn coordsInBounds4D(coord : vec4<i32>, shape : vec4<i32>) -> bool {
return all(coord >= vec4<i32>(0)) && all(coord < shape);
}
fn getIndexFromCoords1D(coord : i32, shape : i32) -> i32 {
return coord;
}
fn getIndexFromCoords2D(coords : vec2<i32>, shape : vec2<i32>) -> i32 {
return dot(coords, vec2<i32>(shape.y, 1));
}
fn getIndexFromCoords3D(coords : vec3<i32>, shape : vec3<i32>) -> i32 {
return dot(coords, vec3<i32>(shape.y * shape.z, shape.z, 1));
}
fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {
return dot(coords, vec4<i32>(
shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));
}
fn getIndexFromCoords5D(coords : vec5, shape : vec5) -> i32 {
let shapeStrides: vec5 = vec5(shape.y * shape.z * shape.w * shape.u, shape.z * shape.w * shape.u, shape.w * shape.u, shape.u, 1);
return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u;
}
fn getIndexFromCoords6D(coords : vec6, shape : vec6) -> i32 {
let shapeStrides: vec6 = vec6(shape.y * shape.z * shape.w * shape.u * shape.v, shape.z * shape.w * shape.u * shape.v, shape.w * shape.u * shape.v, shape.u * shape.v, shape.v, 1);
return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u + coords.v*shapeStrides.v;
}
fn idiv(a: i32, b: i32, sign: f32) -> i32 {
var res: i32 = a / b;
let 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<u32>(val);
return (floatToUint & 0x7fffffffu) > 0x7f800000u;
}
fn isnanVec4(val : vec4<f32>) -> vec4<bool> {
return vec4<bool>(isnan(val[0]), isnan(val[1]), isnan(val[2]), isnan(val[3]));
}
`,Bne=`
fn isinf(val: f32) -> bool {
return abs(val) == uniforms.INFINITY;
}
`;function Hx(e){let t=e.length;if(t<=1)return"fn getCoordsFromIndex(index : i32) -> i32 { return index; }";let a=v.computeStrides(e),n=ra(t),r=[];for(let i=0;i<t;i++)r.push(`d${i}`);if(a.length===1)return` fn getCoordsFromIndex(index : i32) -> vec2<i32> {
let d0 = index / uniforms.outShapeStrides; let d1 = index - d0 * uniforms.outShapeStrides;
return vec2<i32>(d0, d1);
}`;let s;return s="var index2 = index;"+a.map((i,o)=>{let l=`let ${r[o]} = index2 / uniforms.outShapeStrides.${yr(o)}`,u=o===a.length-1?`let ${r[o+1]} = index2 - ${r[o]} * uniforms.outShapeStrides.${yr(o)}`:`index2 = index2 - ${r[o]} * uniforms.outShapeStrides.${yr(o)}`;return`${l}; ${u};`}).join(""),`
fn getCoordsFromIndex(index : i32) -> ${n} {
${s}
return ${n}(${r.join(",")});
}
`}function Wne(e,t){let a=e.name,n=e.shape.length,r=ra(n),s="get"+a.charAt(0).toUpperCase()+a.slice(1),i=["d0","d1","d2","d3","d4","d5"].slice(0,n),o=i.map(p=>`${p} : i32`).join(", ");if(n<1)return t?`
fn ${s}() -> vec4<f32> {
return vec4<f32>(${a}[0]);
}
`:`
fn ${s}() ->f32 {
return f32(${a}[0]);
}
`;let l=`uniforms.${a.charAt(0).toLowerCase()+a.slice(1)}Shape`,u=`${n}D`;return n===0&&(u="1D"),t?`
fn ${s}(${o}) -> vec4<f32> {
return vec4<f32>(${a}[getIndexFromCoords${u}(${r}(${i.join(",")}),
${l}) / 4]);
}
`:`
fn ${s}(${o}) -> f32 {
return f32(${a}[getIndexFromCoords${u}(${r}(${i.join(",")}),
${l})]);
}
`}function Vne(e,t,a,n){let r=e.name,s=r.charAt(0).toUpperCase()+r.slice(1),i="get"+s+"ByOutput",o=e.shape.length,l=t.length,u=ra(l);if(v.arraysEqual(e.shape,t)&&n)return a?`
fn ${i}Index(globalIndex : i32) -> vec4<f32> {
return vec4<f32>(${r}[globalIndex]);
}
fn ${i}Coords(coords : ${u}) -> vec4<f32> {
return vec4<f32>(${r}[${l>1?"getOutputIndexFromCoords(coords)":"coords"} / 4]);
}
`:`
fn ${i}Index(globalIndex : i32) -> f32 {
return f32(${r}[globalIndex]);
}
fn ${i}Coords(coords : ${u}) -> f32 {
return f32(${r}[${l>1?"getOutputIndexFromCoords(coords)":"coords"}]);
}
`;let p=T.getBroadcastDims(e.shape,t),c=l-o,d="";if(o===0)return a?`
fn ${i}Index(globalIndex : i32) -> vec4<f32> {
return get${s}();
}
fn ${i}Coords(coords : ${u}) -> vec4<f32> {
return get${s}();
}
`:`
fn ${i}Index(globalIndex : i32) -> f32{
return get${s}();
}
fn ${i}Coords(coords : ${u}) -> f32{
return get${s}();
}
`;l<2&&p.length>=1?d="coords = 0;":d=p.map(g=>`coords.${yr(g+c)} = 0;`).join(`
`);let h="";if(l<2&&o>0)h="coords";else if(l>1){let g=ra(o),x=e.shape.map((A,y)=>`coords.${yr(y+c)}`).join(", ");h=`${g}(${x})`}else h="coords";let f=`uniforms.${r.charAt(0).toLowerCase()+r.slice(1)}Shape`,m=`${o}D`;return a?`
fn ${i}Index(globalIndex : i32) -> vec4<f32> {
var coords = getCoordsFromIndex(globalIndex);
${d}
return ${r}[getIndexFromCoords${m}(${h}, ${f}) / 4];
}
fn ${i}Coords(coordsIn : ${u}) -> vec4<f32> {
var coords = coordsIn;
${d}
return ${r}[getIndexFromCoords${m}(${h}, ${f}) / 4];
}
`:`
fn ${i}Index(globalIndex : i32) -> f32 {
var coords = getCoordsFromIndex(globalIndex);
${d}
return f32(${r}[getIndexFromCoords${m}(${h}, ${f})]);
}
fn ${i}Coords(coordsIn : ${u}) -> f32 {
var coords = coordsIn;
${d}
return f32(${r}[getIndexFromCoords${m}(${h}, ${f})]);
}
`}function Une(e,t,a,n){let r=Wne(e,a);return e.shape.length<=t.length&&(r+=Vne(e,t,a,n)),r}function Gne(e,t){let{x:a,y:n=[],z:r=[]}=t,s=e.length,i=a.length+n.length+r.length;if(i!==s)return"";if(a.length===s)return`fn getOutputCoords() -> ${ra(s)}{
let globalIndex = getGlobalIndex();
return getCoordsFromIndex(globalIndex);
}
`;let o="",l=[a,n,r];for(let d=0;d<l.length;d++){let h=l[d];if(h.length!==0)if(h.length===1)o+=`let d${h[0]} = i32(globalId[${d}]);`;else{let f=Fne(h,"uniforms.outShape");o+=`var index${d} = i32(globalId[${d}]);`;for(let m=0;m<f.length;m++)o+=`let d${h[m]} = index${d} / ${f[m]};`,m===f.length-1?o+=`let d${h[m+1]} = index${d} - d${h[m]} * ${f[m]};`:o+=`index${d} = index${d} - d${h[m]} * ${f[m]};`}}let u=[];for(let d=0;d<i;d++)u.push(`d${d}`);let p=ra(i),c=`fn getOutputCoords() -> ${p} {
${o}
`;return u.length===0?c+=`return ${p}(0); }`:c+=`return ${p}(${u.join(",")}); }`,c}function Hne(e){let t="";switch(e){case 0:case 1:t+=`
fn getOutputIndexFromCoords(coords : i32) -> i32 {
return coords;
}
`;break;case 2:t+=`
fn getOutputIndexFromCoords(coords : vec2<i32>) -> i32 {
return dot(coords, vec2<i32>(uniforms.outShapeStrides, 1));
}
`;break;case 3:t+=`
fn getOutputIndexFromCoords(coords : vec3<i32>) -> i32 {
return dot(coords, vec3<i32>(uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, 1));
}
`;break;case 4:t+=`
fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
return dot(coords, vec4<i32>(
uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, uniforms.outShapeStrides.z, 1));
}
`;break;case 5:t+=`
fn getOutputIndexFromCoords(coords : vec5) -> i32 {
return coords.x * uniforms.outShapeStrides.x +
coords.y * uniforms.outShapeStrides.y +
coords.z * uniforms.outShapeStrides.z +
coords.w * uniforms.outShapeStrides.w +
coords.u;
}
`;break;case 6:t+=`
fn getOutputIndexFromCoords(coords : vec6) -> i32 {
return coords.x * uniforms.outShapeStrides.x +
coords.y * uniforms.outShapeStrides.y +
coords.z * uniforms.outShapeStrides.z +
coords.w * uniforms.outShapeStrides.w +
coords.u * uniforms.outShapeStrides.u +
coords.v;
}
`;break;default:v.assert(!1,()=>`Unsupported ${e}D shape`);break}return t}function T8(e){return e.dispatch[1]===1&&e.dispatch[2]===1}function ad(e,t){return e==="float32"?t?"vec4<f32>":"f32":e==="int32"||e==="bool"?t?"vec4<i32>":"i32":e}function jne(e,t,a){let n=e.length,r=ad(t,a),s;if(a?s=`fn setOutputAtIndex(flatIndex : i32, value : vec4<f32>) {
result[flatIndex] = ${r}(value);
}
fn setOutputAtIndexI32(flatIndex : i32, value : vec4<i32>) {
result[flatIndex] = ${r}(value);
}`:s=`fn setOutputAtIndex(flatIndex : i32, value : f32) {
result[flatIndex] = ${r}(value);
}
fn setOutputAtIndexI32(flatIndex : i32, value : i32) {
result[flatIndex] = ${r}(value);
}`,n>=2){let i=["d0","d1","d2","d3","d4","d5"].slice(0,n),o=ra(n);a?s+=`
fn setOutputAtCoords(${i.map(l=>`${l} : i32`).join(", ")}, value : vec4<f32>) {
let flatIndex = getOutputIndexFromCoords(${o}(${i.join(", ")}));
setOutputAtIndex(flatIndex / 4, value);
}
fn setOutputAtCoordsI32(${i.map(l=>`${l} : i32`).join(", ")}, value : vec4<i32>) {
let flatIndex = getOutputIndexFromCoords(${o}(${i.join(", ")}));
setOutputAtIndexI32(flatIndex / 4, value);
}
`:s+=`
fn setOutputAtCoords(${i.map(l=>`${l} : i32`).join(", ")}, value : f32) {
let flatIndex = getOutputIndexFromCoords(${o}(${i.join(", ")}));
setOutputAtIndex(flatIndex, value);
}
fn setOutputAtCoordsI32(${i.map(l=>`${l} : i32`).join(", ")}, value : i32) {
let flatIndex = getOutputIndexFromCoords(${o}(${i.join(", ")}));
setOutputAtIndexI32(flatIndex, value);
}
`}return s}function qne(e){let t=/(\w+)\s*:\s*vec(5|6)/g;e=e.replace(t,n=>"@align(16) "+n);let a=/vec(5|6)\s*,\s*(\w+)/g;return e=e.replace(a,(n,r,s)=>`vec${r}, @align(16) ${s}`),e}function jx(e){return!(e.dispatchLayout.hasOwnProperty("y")&&e.dispatchLayout.y.length!==0||e.dispatchLayout.hasOwnProperty("z")&&e.dispatchLayout.z.length!==0)}var C8={};Xe(C8,{ArrayBufferToTypedArray:()=>R8,GPUBytesPerElement:()=>E8,MatMulProgramType:()=>Pn,computeDispatch:()=>Ne,computeWorkPerThreadForConv2d:()=>O3,computeWorkgroupInfoForMatMul:()=>N8,computeWorkgroupSizeForConv2d:()=>F3,flatDispatchLayout:()=>Ve,isWebGPUSupported:()=>D3,tilesFitEvenlyIntoShape:()=>Xne});var Ds=e=>{let t=1;for(let a=0;a<e.length;a++)t*=e[a];return t};function Xne(e,t){if(e.length!==t.length)throw new Error(`Cannot compute whether rank ${e.length} tiles fit evenly into rank ${t.length} shape - ranks must match.`);return t.every((a,n)=>a%e[n]===0)}function Ne(e,t,a=[1,1,1],n=[1,1,1]){let[r,s,i]=[Math.ceil(Ds(e.x.map(o=>t[o]))/(a[0]*n[0])),e.y?Math.ceil(Ds(e.y.map(o=>t[o]))/(a[1]*n[1])):1,e.z?Math.ceil(Ds(e.z.map(o=>t[o]))/(a[2]*n[2])):1];return[r,s,i]}function N8(e,t,a,n=!1){let r=[8,8,1],s=[4,4,1];return n||(e<=8&&(s[1]=1),t<=16&&a<=16&&(r[0]=4)),{workgroupSize:r,elementsPerThread:s}}function F3(e,t,a=!1){if(a)return[8,8,1];let n=Ds(e.x.map(s=>t[s])),r=Ds(e.y.map(s=>t[s]));return n<=4?[4,16,1]:r<=4?[16,4,1]:[16,16,1]}function O3(e,t,a=!1){if(a)return[4,4,1];let n=Ds(e.x.map(s=>t[s])),r=Ds(e.y.map(s=>t[s]));return n<=4?[1,2,1]:r<=4?[2,1,1]:[2,2,1]}function Ve(e){return{x:e.map((t,a)=>a)}}function E8(e){if(e==="float32"||e==="int32"||e==="bool"||e==="string")return 4;if(e==="complex64")return 8;throw new Error(`Unknown dtype ${e}`)}function R8(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 D3(){return(typeof window!="undefined"||typeof WorkerGlobalScope!="undefined")&&!!navigator.gpu}var Pn;(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"})(Pn||(Pn={}));var Kne=W().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD"),Zne=(e,t)=>{let a=e.limits.maxComputeWorkgroupsPerDimension,n=t.dispatchLayout,r=t.dispatch;if(r.every(i=>i<=a))return r;v.assert(r[0]>a&&n.y===void 0&&n.z===void 0,()=>"Dispatch size exceeds WebGPU limits in Y or Z dimension.");let s=Math.ceil(Math.sqrt(r[0]));return s>a?(s=Math.ceil(Math.cbrt(r[0])),v.assert(s<=a,()=>"Total dispatch size exceeds WebGPU maximum."),[s,s,s]):[s,s,1]},Vh=class extends bl{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,!D3())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-inside-passes"),this.adapterInfo=new $ne(t),this.thresholdToIncreaseWorkgroups=this.adapterInfo.intelGPUGeneration>=12?16:8,this.bufferManager=new _ne(this.device),this.textureManager=new Pne(this.device),this.tensorMap=new vd(this,kt()),this.supportTimeQuery&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:2})),W().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 Vh.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 a=this.tensorMap.get(e);if(this.decRef(e),!t&&a.refCount>0)return!1;if(this.commandQueueOwnedIds.has(e))return this.tensorDataPendingDisposal.push(e),!1;let{complexTensorInfos:n}=this.tensorMap.get(e);return n!=null&&(this.disposeData(n.real.dataId,t),this.disposeData(n.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 a=t.resourceInfo;a.texture instanceof GPUTexture&&this.textureManager.releaseTexture(a.texture,a.width,a.height,a.format,a.usage),a.texture=null}else{let a=t.resourceInfo;this.bufferManager.releaseBuffer(a.buffer,a.size,a.usage),a.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,a){if(a==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let n={id:this.nextDataId()};return this.tensorMap.set(n,{dtype:a,shape:t,values:e,refCount:1}),n}move(e,t,a,n,r){if(n==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.tensorMap.set(e,{dtype:n,shape:a,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 a=this.bufferManager.acquireBuffer(t,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(e,0,a,0,t),this.submitQueue(),await a.mapAsync(GPUMapMode.READ);let n=a.getMappedRange().slice(0);return a.unmap(),a!=null&&this.bufferManager.releaseBuffer(a,t,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ),W().getBool("WEBGPU_USE_PROFILE_TOOL")&&(v.assert(this.dummyContext!==void 0,()=>"Fail to get context for profiling tool"),this.dummyContext.getCurrentTexture()),n}convertAndCacheOnCPU(e,t){let a=this.tensorMap.get(e);return this.releaseResource(e),a.values=t,a.values}readSync(e){let t=this.tensorMap.get(e),{values:a}=t;if(a==null)throw new Error("WebGPU readSync is only available for CPU-resident tensors.");return a}async read(e){if(!this.tensorMap.has(e))throw new Error(`Tensor ${e} was not registered!`);let t=this.tensorMap.get(e),{values:a}=t;if(a!=null)return this.convertAndCacheOnCPU(e,a);let n;if(t.dtype==="complex64"){let r=await Promise.all([this.read(t.complexTensorInfos.real.dataId),this.read(t.complexTensorInfos.imag.dataId)]),s=r[0],i=r[1];n=T.mergeRealAndImagArrays(s,i)}else{let r=t.resourceInfo,s=await this.getBufferData(r.buffer,r.size);n=R8(s,t.dtype)}return this.convertAndCacheOnCPU(e,n),n}readToGPU(e){let t=this.tensorMap.get(e),{values:a,dtype:n,shape:r,resourceInfo:s}=t;if(n==="complex64")throw new Error("Does not support reading buffer for complex64 dtype.");if(s==null)throw a!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");let i=s.size,o=this.bufferManager.acquireBuffer(i,s.usage);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(s.buffer,0,o,0,i),this.submitQueue();let l=this.makeTensorInfo(r,n),u=kt().makeTensorFromTensorInfo(l),p=this.tensorMap.get(l.dataId);return p.resourceInfo={size:i,usage:this.defaultGpuBufferUsage(),buffer:o},{tensorRef:u,buffer:o,bufSize:i}}bufferSync(e){let t=this.readSync(e.dataId);if(e.dtype==="string")try{let a=t.map(n=>v.decodeString(n));return Me(e.shape,e.dtype,a)}catch(a){throw new Error("Failed to decode encoded string bytes into utf-8")}return Me(e.shape,e.dtype,t)}async time(e){this.supportTimeQuery||console.warn("This device doesn't support timestamp-query-inside-passes 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,a=[],n=!1;this.programTimersStack==null?(this.programTimersStack=a,n=!0):this.activeTimers.push(a),this.activeTimers=a,e();let r=v.flatten(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),s=v.flatten(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=t,n&&(this.programTimersStack=null);let i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},o=await Promise.all(r);return i.kernelMs=v.sum(o),i.getExtraProfileInfo=()=>o.map((l,u)=>({name:s[u],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", "),this.uploadWaitMs=0,this.downloadWaitMs=0,i}makeTensorInfo(e,t,a){return t==="string"&&a!=null&&a.length>0&&v.isString(a[0])&&(a=a.map(n=>v.encodeString(n))),{dataId:this.write(a,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 n=t.resourceInfo;return n.texture instanceof GPUExternalTexture?n.texture:n.texture.createView()}let a=t.resourceInfo;return{offset:0,size:a.size,buffer:a.buffer}}async getQueryTime(e){return this.supportTimeQuery?this.getTimeFromQuerySet(e):0}uploadToGPU(e){let t=this.tensorMap.get(e);if(t.resourceInfo)return;let a=E8(t.dtype)*v.sizeFromShape(t.shape),n=this.bufferManager.acquireBuffer(a,this.defaultGpuBufferUsage());if(t.resourceInfo={size:a,usage:this.defaultGpuBufferUsage(),buffer:n},t.values){let r=this.bufferManager.acquireUploadBuffer(a,GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC),s=r.getMappedRange();t.dtype==="int32"||t.dtype==="bool"?new Int32Array(s).set(t.values):new Float32Array(s).set(t.values),r.unmap(),this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(r,0,n,0,a);let i={size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC,buffer:r};this.stagingPendingDisposal.push(i)}}makeUniforms(e){let t=0,a=0,n=[];e.forEach(o=>{o.data.length===0&&(o.data=[1]);let l;switch(o.data.length){case 1:l=4;break;case 2:l=8;break;case 3:l=16;break;case 4:l=16;break;case 5:l=16;break;case 6:l=16;break;default:v.assert(!1,()=>`Unsupported ${o.data.length}D shape`)}(a===5||a===6)&&(l=16),t=Math.ceil(t/l)*l,a=o.data.length,n.push(t),t+=o.data.length*4});let r=new ArrayBuffer(t);e.forEach((o,l)=>{let u=n[l];o.type==="int32"?new Int32Array(r,u,o.data.length).set(o.data):o.type==="uint32"?new Uint32Array(r,u,o.data.length).set(o.data):new Float32Array(r,u,o.data.length).set(o.data)});let s=this.bufferManager.acquireBuffer(t,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.queue.writeBuffer(s,0,r,0,t);let i={size:t,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM,buffer:s};return this.uniformPendingDisposal.push(i),{offset:0,size:t,buffer:s}}runWebGPUProgram(e,t,a,n,r){if(r||(r=this.makeTensorInfo(e.outputShape,a)),v.sizeFromShape(r.shape)===0)return this.tensorMap.get(r.dataId).values=v.getTypedArrayFromDType(r.dtype,0),r;this.uploadToGPU(r.dataId),e.dispatch=Zne(this.device,e);let s=[],i=[];if(!e.isFromPixels){s.push({type:"float32",data:[NaN]},{type:"float32",data:[1/0]}),i=t.concat(r).map(g=>g.shape);let f="int32";i.map(g=>{s.push({type:f,data:g})});let m=v.computeStrides(r.shape);if(s.push({type:f,data:m}),e.size){let g=v.sizeFromShape(e.outputShape);s.push({type:f,data:[e.isVec4?g/4:g]})}}let o=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=Lne(e,i,o,r),u;l in this.pipelineCache?u=this.pipelineCache[l]:(u=One(this.device,e,o,r),this.pipelineCache[l]=u),n&&(s=[...s,...n]);let p=[this.tensorToBinding(r),...t.map(f=>this.tensorToBinding(f)),this.makeUniforms(s)],c=this.device.createBindGroup({layout:u.getBindGroupLayout(0),entries:p.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,c),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),W().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),a=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,a,0,16),this.submitQueue(),await a.mapAsync(GPUMapMode.READ);let n=new BigUint64Array(a.getMappedRange()),r=Number(n[1]-n[0]);return a.unmap(),this.bufferManager.releaseBuffer(a,16,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST),this.bufferManager.releaseBuffer(t,16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),r/1e6}shouldExecuteOnCPU(e,t=Kne){return W().getBool("WEBGPU_CPU_FORWARD")&&e.every(a=>this.tensorMap.get(a.dataId).resourceInfo==null&&v.sizeFromShape(a.shape)<t)}numDataIds(){return this.tensorMap.numDataIds()-this.tensorDataPendingDisposal.length}dispose(){this.disposed||(this.bufferManager.dispose(),this.textureManager.dispose(),this.disposed=!0)}};Vh.nextDataId=0;D3()&&go("webgpu",async()=>{W().set("CHECK_COMPUTATION_FOR_ERRORS",!1);let e={powerPreference:W().get("WEBGPU_USE_LOW_POWER_GPU")?"low-power":"high-performance"},t=await navigator.gpu.requestAdapter(e),a={};t.features.has("timestamp-query-inside-passes")&&(a.requiredFeatures=["timestamp-query-inside-passes"]);let n=t.limits;a.requiredLimits={maxComputeWorkgroupStorageSize:n.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:n.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:n.maxStorageBufferBindingSize};let r=await t.requestDevice(a),s=await t.requestAdapterInfo();return new Vh(r,s)},3);var De;(function(e){e[e.ADD=0]="ADD",e[e.ATAN2=1]="ATAN2",e[e.COMPLEX_MULTIPLY_IMAG=2]="COMPLEX_MULTIPLY_IMAG",e[e.COMPLEX_MULTIPLY_REAL=3]="COMPLEX_MULTIPLY_REAL",e[e.DIV=4]="DIV",e[e.EQUAL=5]="EQUAL",e[e.GREATER=6]="GREATER",e[e.GREATER_EQUAL=7]="GREATER_EQUAL",e[e.INT_DIV=8]="INT_DIV",e[e.LESS=9]="LESS",e[e.LESS_EQUAL=10]="LESS_EQUAL",e[e.LOGICAL_AND=11]="LOGICAL_AND",e[e.MAX=12]="MAX",e[e.MIN=13]="MIN",e[e.MOD=14]="MOD",e[e.MUL=15]="MUL",e[e.NOT_EQUAL=16]="NOT_EQUAL",e[e.POW=17]="POW",e[e.PRELU=18]="PRELU",e[e.SQUARED_DIFFERENCE=19]="SQUARED_DIFFERENCE",e[e.SUB=20]="SUB"})(De||(De={}));var M8=`
if (isnan(a)) { return a; }
if (isnan(b)) { return b; }
`,$8=`
if (isNaN.r) {
resultTemp.r = valueForNaN;
}
if (isNaN.g) {
resultTemp.g = valueForNaN;
}
if (isNaN.b) {
resultTemp.b = valueForNaN;
}
if (isNaN.a) {
resultTemp.a = valueForNaN;
}
`,z3=`
let isNaN = isnanVec4(a) | isnanVec4(b);
${$8}
`,Yne="return a + b;",Jne="return areal * breal - aimag * bimag;",Qne="return areal * bimag + aimag * breal;",ere="return a / b;",tre="return f32(a == b);",are="return vec4<f32>(a == b);",nre="return f32(a > b);",rre="return vec4<f32>(a > b);",sre="return f32(a >= b);",ire="return vec4<f32>(a >= b);",ore=`
let s = sign(a) * sign(b);
let ia = i32(round(a));
let ib = i32(round(b));
return f32(idiv(ia, ib, s));
`,lre=`
let ia = vec4<i32>(round(a));
let ib = vec4<i32>(round(b));
let cond = ib != vec4<i32>(0);
var resultTemp = vec4<i32>(0);
let s = sign(a) * sign(b);
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if (cond[0]) {
resultTemp[0] = idiv(ia[0], ib[0], s[0]);
}
if (cond[1]) {
resultTemp[1] = idiv(ia[1], ib[1], s[1]);
}
if (cond[2]) {
resultTemp[2] = idiv(ia[2], ib[2], s[2]);
}
if (cond[3]) {
resultTemp[3] = idiv(ia[3], ib[3], s[3]);
}
return vec4<f32>(resultTemp);
`,ure="return f32(a < b);",dre="return vec4<f32>(a < b);",pre="return f32(a <= b);",cre="return vec4<f32>(a <= b);",hre="return f32(f32(a) >= 1.0 && f32(b) >= 1.0);",fre=`return (vec4<f32>(a >= vec4<f32>(1.0)) *
vec4<f32>(b >= vec4<f32>(1.0)));`,mre=`
${M8}
if (b == 0.) {
return uniforms.NAN;
}
var resultTemp = a % b;
if ((a < 0. && b < 0.) || (a >= 0. && b > 0.)) {
return resultTemp;
} else {
return (resultTemp + b) % b;
}
`,gre=`
let valueForNaN = uniforms.NAN;
var resultTemp = vec4<f32>(a % b);
${z3}
if (b[0] == 0.) {
resultTemp[0] = uniforms.NAN;
}
if (b[1] == 0.) {
resultTemp[1] = uniforms.NAN;
}
if (b[2] == 0.) {
resultTemp[2] = uniforms.NAN;
}
if (b[3] == 0.) {
resultTemp[3] = uniforms.NAN;
}
if (!((a[0] < 0. && b[0] < 0.) || (a[0] >= 0. && b[0] > 0.))) {
resultTemp[0] = (resultTemp[0] + b[0]) % b[0];
}
if (!((a[1] < 0. && b[1] < 0.) || (a[1] >= 0. && b[1] > 0.))) {
resultTemp[1] = (resultTemp[1] + b[1]) % b[1];
}
if (!((a[2] < 0. && b[2] < 0.) || (a[2] >= 0. && b[2] > 0.))) {
resultTemp[2] = (resultTemp[2] + b[2]) % b[2];
}
if (!((a[3] < 0. && b[3] < 0.) || (a[3] >= 0. && b[3] > 0.))) {
resultTemp[3] = (resultTemp[3] + b[3]) % b[3];
}
return resultTemp;
`,xre="return a * b;",Are=`
if (isnan(a) || isnan(b)) {
return 1.0;
}
return f32(a != b);
`,yre=`
var resultTemp = vec4<f32>(a != b);
let valueForNaN = 1.0;
${z3}
return resultTemp;
`,bre=`
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);
`,vre=`
let isModRound1Bool = vec4<i32>(round(abs(b) % vec4<f32>(2.0))) == vec4<i32>(1);
let isModRound1 = vec4<f32>(isModRound1Bool);
let multiplier = sign(a) * isModRound1 + (vec4<f32>(1.0) - isModRound1);
var resultTemp = multiplier * pow(abs(a), b);
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
let isExpZero = b == vec4<f32>(0.0);
if (isExpZero.r) {
resultTemp.r = 1.0;
}
if (isExpZero.g) {
resultTemp.g = 1.0;
}
if (isExpZero.b) {
resultTemp.b = 1.0;
}
if (isExpZero.a) {
resultTemp.a = 1.0;
}
let isNaN = (a < vec4<f32>(0.0)) & (floor(b) < b);
let valueForNaN = uniforms.NAN;
${$8}
return resultTemp;
`,wre="if (a < 0.0) { return b * a; } return a;",kre=`
let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
return (aLessThanZero * (b * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
`,Ire="return (a - b) * (a - b);",Sre="return a - b;";function Bm(e,t,a="uniforms.NAN"){let n=t?z3:M8;return t?`
let valueForNaN = ${a};
var resultTemp = vec4<f32>(${e}(a, b));
`+n+`
return resultTemp;
`:n+`
return ${e}(a, b);
`}function L3(e,t){switch(e){case De.ADD:return Yne;case De.ATAN2:return Bm("atan2",t);case De.COMPLEX_MULTIPLY_IMAG:return Qne;case De.COMPLEX_MULTIPLY_REAL:return Jne;case De.DIV:return ere;case De.EQUAL:return t?are:tre;case De.GREATER:return t?rre:nre;case De.GREATER_EQUAL:return t?ire:sre;case De.INT_DIV:return t?lre:ore;case De.LESS:return t?dre:ure;case De.LESS_EQUAL:return t?cre:pre;case De.LOGICAL_AND:return t?fre:hre;case De.MAX:return Bm("max",t);case De.MIN:return Bm("min",t);case De.MOD:return t?gre:mre;case De.MUL:return xre;case De.NOT_EQUAL:return t?yre:Are;case De.POW:return t?vre:bre;case De.PRELU:return t?kre:wre;case De.SQUARED_DIFFERENCE:return Ire;case De.SUB:return Sre;default:throw new Error(`BinaryType ${e} is not implemented!`)}}var de;(function(e){e[e.ABS=0]="ABS",e[e.ACOS=1]="ACOS",e[e.ACOSH=2]="ACOSH",e[e.ASIN=3]="ASIN",e[e.ASINH=4]="ASINH",e[e.ATAN=5]="ATAN",e[e.ATANH=6]="ATANH",e[e.CEIL=7]="CEIL",e[e.COS=8]="COS",e[e.COSH=9]="COSH",e[e.ELU=10]="ELU",e[e.ERF=11]="ERF",e[e.EXP=12]="EXP",e[e.EXPM1=13]="EXPM1",e[e.FLOOR=14]="FLOOR",e[e.IS_FINITE=15]="IS_FINITE",e[e.IS_INF=16]="IS_INF",e[e.IS_NAN=17]="IS_NAN",e[e.LINEAR=18]="LINEAR",e[e.LOG=19]="LOG",e[e.LOG1P=20]="LOG1P",e[e.LOGICAL_NOT=21]="LOGICAL_NOT",e[e.NEG=22]="NEG",e[e.RELU=23]="RELU",e[e.RELU6=24]="RELU6",e[e.LEAKYRELU=25]="LEAKYRELU",e[e.RECIPROCAL=26]="RECIPROCAL",e[e.RSQRT=27]="RSQRT",e[e.SIN=28]="SIN",e[e.SINH=29]="SINH",e[e.SIGMOID=30]="SIGMOID",e[e.SQRT=31]="SQRT",e[e.SQUARE=32]="SQUARE",e[e.TAN=33]="TAN",e[e.TANH=34]="TANH",e[e.TO_INT=35]="TO_INT"})(de||(de={}));var Tre="return abs(a);",Cre=`
if (abs(a) > 1.) {
return uniforms.NAN;
}
return acos(a);
`,Nre=`
if (a < 1.) {
return uniforms.NAN;
}
return acosh(a);
`,Ere=`
if (abs(a) > 1.) {
return uniforms.NAN;
}
return asin(a);
`,Rre="return asinh(a);",Mre=`
if (isnan(a)) {
return uniforms.NAN;
}
return atan(a);
`,$re=`
if (abs(a) > 1.) {
return uniforms.NAN;
}
if (a == 1.) {
return uniforms.INFINITY;
}
if (a == -1.) {
return -uniforms.INFINITY;
}
return atanh(a);
`,_re="return ceil(a);",Pre="return cos(a);",Fre=`
let e2x = exp(-a);
return (e2x + 1.0 / e2x) / 2.0;
`,Ore="return exp(a) - 1.0;",Dre="if (a >= 0.0) { return a; } return (exp(a) - 1.0);",zre=`
var resFloat = exp(a) - vec4<f32>(1.0);
if (a.r >= 0.0) {
resFloat.r = a.r;
}
if (a.g >= 0.0) {
resFloat.g = a.g;
}
if (a.b >= 0.0) {
resFloat.b = a.b;
}
if (a.a >= 0.0) {
resFloat.a = a.a;
}
return resFloat;
`,Lre=`
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
let p = ${T.ERF_P};
let a1 = ${T.ERF_A1};
let a2 = ${T.ERF_A2};
let a3 = ${T.ERF_A3};
let a4 = ${T.ERF_A4};
let a5 = ${T.ERF_A5};
let sign = sign(a);
let absA = abs(a);
let t = 1.0 / (1.0 + p * absA);
return sign * (1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * exp(-absA * absA));
`,Bre="return exp(a);",Wre="return floor(a);",Vre="return f32(!isnan(a) && !isinf(a));",Ure="return f32(isinf(a));",Gre="return f32(isnan(a));",Hre="return a;",jre=`if (a < 0.0) { return uniforms.NAN; }
return log(a);`,qre=`
if (isnan(a)) { return a; }
return log(1.0 + a);
`,Xre="return f32(!(a >= 1.0));",Kre="return -a;",Zre="if (a < 0.0) { return uniforms.alpha * a; } return a;",Yre=`
let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
return (aLessThanZero * (uniforms.alpha * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
`,Jre="return 1.0 / a;",Qre="return select(a, 0.0, a < 0.0);",ese="return clamp(a, 0.0, 6.0);",tse="return clamp(a, vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<f32>(6.0, 6.0, 6.0, 6.0));",ase=`
return select(a, vec4<f32>(0.0), a < vec4<f32>(0.0));
`,nse="return inverseSqrt(a);",rse="return 1.0 / (1.0 + exp(-1.0 * a));",sse="return sin(a);",ise=`
let e2x = exp(a);
return (e2x - 1.0 / e2x) / 2.0;
`,ose="return sqrt(a);",lse="return a * a;",use="return tan(a);",dse=`
let e2x = exp(-2.0 * abs(a));
return sign(a) * (1.0 - e2x) / (1.0 + e2x);
`,pse="return f32(i32((a)));";function Ms(e,t){switch(e){case de.ABS:return Tre;case de.ACOS:return Cre;case de.ACOSH:return Nre;case de.ASIN:return Ere;case de.ASINH:return Rre;case de.ATAN:return Mre;case de.ATANH:return $re;case de.COS:return Pre;case de.COSH:return Fre;case de.CEIL:return _re;case de.ELU:return t?zre:Dre;case de.ERF:return Lre;case de.EXP:return Bre;case de.EXPM1:return Ore;case de.FLOOR:return Wre;case de.IS_FINITE:return Vre;case de.IS_INF:return Ure;case de.IS_NAN:return Gre;case de.LINEAR:return Hre;case de.LOG:return jre;case de.LOG1P:return qre;case de.LOGICAL_NOT:return Xre;case de.NEG:return Kre;case de.LEAKYRELU:return t?Yre:Zre;case de.RECIPROCAL:return Jre;case de.RELU:return t?ase:Qre;case de.RELU6:return t?tse:ese;case de.RSQRT:return nse;case de.SIGMOID:return rse;case de.SIN:return sse;case de.SINH:return ise;case de.SQRT:return ose;case de.SQUARE:return lse;case de.TAN:return use;case de.TANH:return dse;case de.TO_INT:return pse;default:throw new Error(`BinaryType ${e} is not implemented!`)}}var Mt=e=>{switch(e){case 1:return"f32";case 2:return"vec2<f32>";case 3:return"vec3<f32>";case 4:return"vec4<f32>";default:throw new Error(`${e}-component is not supported.`)}};function Tr(e,t=!1,a=!1,n=3){if(e===null)return"";let r="";if(e==="linear")r=Ms(de.LINEAR);else if(e==="relu")r=Ms(de.RELU,a);else if(e==="elu")r=Ms(de.ELU,a);else if(e==="relu6")r=Ms(de.RELU6,a);else if(e==="prelu")r=L3(De.PRELU,a);else if(e==="sigmoid")r=Ms(de.SIGMOID,a);else if(e==="leakyrelu")r=Ms(de.LEAKYRELU,a);else throw new Error(`Activation ${e} has not been implemented for the WebGPU backend.`);let s=Mt(a?4:1),i="";return t?i=`
fn activation(a : ${s}, coords : vec${n}<i32>) -> ${s} {
let b = getPreluActivationWeightsByOutputCoords(coords);
${r}
}`:i=`
fn activation(a : ${s}, coords : vec${n}<i32>) -> ${s} {
${r}
}`,i}function vo(e,t){return`
${e?"value = value + getBiasByOutputCoords(coords);":""}
${t?"value = activation(value, coords);":""}
`}function _8(e,t,a,n,r=!1,s=!1,i=!1,o=1){v.assert(a&&o===1||!a,()=>`transposeA ${a} is not compatible with component size ${o}`);let l=`
let batch = ${e?"0":"batchIn"};
${a?"value = getA(batch, col, row);":"value = getA(batch, row, col);"}
`,u=n?"value = getB(batch, col, row);":"value = getB(batch, row, col);";return`
fn mm_readA(batchIn: i32, row: i32, colIn: i32) -> ${Mt(o)} {
var value = ${Mt(o)}(0.0);
let col = colIn * ${o};
${r&&i?l:`
${a?"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) -> ${Mt(o)} {
let col = colIn * ${o};
let batch = ${t?"0":"batchIn"};
var value = ${Mt(o)}(0.0);
${u}
return value;
}
`}function B3(e,t,a,n,r,s,i=!1,o=!1,l=!1,u=1){return`
${_8(a,n,r,s,i,o,l,u)}
fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Mt(u)}) {
let col = colIn * ${u};
${i&&o?"":"if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)"}
{
var value = valueIn;
let coords = vec3<i32>(batch, row, col);
${vo(e,t)}
setOutputAtCoords(coords[0], coords[1], coords[2], value);
}
}
`}var cse=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);
`,hse=(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 Uh(e,t,a=!1,n=32,r=!1,s=32,i=!1){let o=t[1]*e[1],l=t[0]*e[0],u=a?o:n,p=a?n:o,c=u/t[0],d=n/t[1];return v.assert((a&&c===4&&e[1]===4||!a&&(c===3||c===4))&&u%t[0]===0&&n%t[1]===0&&e[0]===4,()=>`If transposeA ${a} is true, innerElementSize ${c} and workPerThread[1] ${e[1]} must be 4.
Otherwise, innerElementSize ${c} must be 3 or 4.
tileAWidth ${u} must be divisible by workgroupSize[0]${t[0]}. tileInner ${n} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`),`
var<workgroup> mm_Asub : array<array<vec${c}<f32>, ${u/c}>, ${p}>;
var<workgroup> mm_Bsub : array<array<vec4<f32>, ${l/e[0]}>, ${n}>;
const rowPerThread = ${e[1]};
const colPerThread = ${e[0]};
const innerElementSize = ${c};
const tileInner = ${n};
${Ce()} {
let localRow = i32(localId.y);
let tileRow = ${i?"0":"localRow * rowPerThread"};
let tileCol = i32(localId.x);
let globalRow = ${i?"0":"i32(globalId.y) * rowPerThread"};
let globalCol = i32(globalId.x);
let batch = ${r?"0":"i32(globalId.z)"};
let globalRowStart = i32(workgroupId.y) * ${o};
let numTiles = ${r?`${Math.ceil(s/n)}`:"(uniforms.dimInner - 1) / tileInner + 1"};
var kStart = ${r?`i32(globalId.z) * ${s}`:"0"};
var acc: array<vec4<f32>, 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;
${cse(a)}
}
// 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];
${c===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}
${hse(a,c)}
}
workgroupBarrier();
}
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);
}
}`}var qx=e=>e?`
mm_Asub[inputRow][inputCol] = mm_readA(batch,
kStart + inputRow,
globalRowStart + inputCol);
`:`
mm_Asub[inputRow][inputCol] = mm_readA(batch,
globalRowStart + inputRow,
kStart + inputCol);
`,fse=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];";function Gh(e,t,a=!1,n=32,r=!1,s=32,i=!1){let o=e[1]*t[1],l=e[0]*t[0],u=a?o:n,p=a?n:o;v.assert(p%t[1]===0&&u%t[0]===0&&n%t[1]===0,()=>`tileAHight ${p} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${t[0]}, tileInner ${n} must be divisible by workgroupSize[1]${t[1]}`);let c=p/t[1],d=u/t[0],h=n/t[1],f=i?`
let localRow = i32(localId.y);
let localCol = i32(localId.x);
let globalRowStart = i32(workgroupId.y) * ${o};
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 < ${p}; inputRow = inputRow + ${t[1]}) {
for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${t[0]}) {
${qx(a)}
}
}
// Load one tile of B into local memory.
for (var inputRow = localRow; inputRow < ${n}; 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<f32, colPerThread>;
for (var k = 0; k < tileInner; k = k + 1) {
for (var inner = 0; inner < colPerThread; inner = inner + 1) {
BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];
}
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
let ACached = ${a?`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) * ${o};
let tileRowA = i32(localId.y) * ${c};
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 < ${c}; innerRow = innerRow + 1) {
for (var innerCol = 0; innerCol < ${d}; innerCol = innerCol + 1) {
let inputRow = tileRowA + innerRow;
let inputCol = tileColA + innerCol;
${qx(a)}
}
}
// 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<f32, colPerThread>;
for (var k = 0; k < tileInner; k = k + 1) {
for (var inner = 0; inner < colPerThread; inner = inner + 1) {
BCached[inner] = mm_Bsub[k][tileCol + inner];
}
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
${fse(a)}
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<workgroup> mm_Asub : array<array<f32, ${u}>, ${p}>;
var<workgroup> mm_Bsub : array<array<f32, ${l}>, ${n}>;
const rowPerThread = ${e[1]};
const colPerThread = ${e[0]};
const tileInner = ${n};
${Ce()} {
let batch = ${r?"0":"i32(globalId.z)"};
let numTiles = ${r?`${Math.ceil(s/n)}`:"(uniforms.dimInner - 1) / tileInner + 1"};
var kStart = ${r?`i32(globalId.z) * ${s}`:"0"};
var acc : array<array<f32, colPerThread>, rowPerThread>;
// Without this initialization strange values show up in acc.
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
acc[innerRow][innerCol] = 0.0;
}
}
${f}
}
`}var mse=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 gse(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<workgroup> mm_Asub : array<vec4<f32>, ${e[0]}>;
${Ce()} {
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<f32>(${mse(t)});
workgroupBarrier();
// Compute acc values for a single thread.
for (var k = 0; k < tileSize / 4; k = k + 1) {
let rowB = t * tileSize + k * 4;
let BCached = vec4<f32>(mm_readB(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 xse=class{constructor(e,t,a,n,r=!1,s=!1,i=null,o=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 p=r?e[1]:e[2];if(this.isVec4=(p%4===0&&!r||t[1]%4===0&&r)&&t[2]%4===0&&!s,this.isVectorA=t[1]===1&&!r,!this.isVec4&&this.isVectorA)this.elementsPerThread=[1,1,1],this.workgroupSize=[32,1,1];else{let h=N8(t[1],p,t[2],r);this.workgroupSize=h.workgroupSize,this.elementsPerThread=h.elementsPerThread}this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize,this.elementsPerThread);let c=i!=null,d=l!=null;c&&this.variableNames.push("bias"),d&&this.variableNames.push("preluActivationWeights"),this.sequentialAccessByThreads=u,this.transposeA=r,this.transposeB=s,this.addBias=c,this.activation=o,this.hasPreluActivationWeights=d,this.batchAEqualOne=a,this.batchBEqualOne=n,[this.fitAOuter,this.fitBOuter,this.fitInner]=this.getShapeFit(t[1],t[2],p),this.shaderKey=`matMulPacked_${this.elementsPerThread}_${r}_${s}_${this.activation}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.isVec4}_${this.isVectorA}_${this.batchAEqualOne}_${this.batchBEqualOne}_${this.sequentialAccessByThreads}`}getShapeFit(e,t,a){let n=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 s=e%n===0,i=t%r===0,o=a%this.tileInner===0;return[s,i,o]}getUserCode(){return`
${Tr(this.activation,this.hasPreluActivationWeights,this.isVec4)}
${B3(this.addBias,this.activation,this.batchAEqualOne,this.batchBEqualOne,!1,this.transposeB,this.fitAOuter,this.fitBOuter,this.fitInner,this.isVec4?4:1)}
${this.isVec4?Uh(this.elementsPerThread,this.workgroupSize,this.transposeA,this.tileInner,!1,null,this.isVectorA):this.isVectorA?gse(this.workgroupSize,this.transposeA):Gh(this.elementsPerThread,this.workgroupSize,this.transposeA,this.tileInner,!1,null,this.sequentialAccessByThreads)}
`}};function Ase(){return`
var<workgroup> sumValues : array<f32, workgroupSizeX>;
${Ce()} {
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 yse=class{constructor(e,t,a,n=!1,r=!1,s=null,i=null,o=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workgroupSize=[256,1,1],this.outputShape=e,this.dispatchLayout={x:[],y:[1,2],z:[0]},this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize);let l=s!=null,u=o!=null;l&&this.variableNames.push("bias"),u&&this.variableNames.push("preluActivationWeights"),this.transposeA=n,this.transposeB=r,this.addBias=l,this.activation=i,this.hasPreluActivationWeights=u,this.batchAEqualOne=t,this.batchBEqualOne=a,this.shaderKey=`matMulReduce_${this.activation}_${n}_${r}_${this.batchAEqualOne}_${this.batchBEqualOne}`}getUserCode(){return`
${Tr(this.activation,this.hasPreluActivationWeights)}
${B3(this.addBias,this.activation,this.batchAEqualOne,this.batchBEqualOne,this.transposeA,this.transposeB)}
${Ase()}
`}};function bse(e){let t=e[1],a=e[0],n=t>a?t:a;return`
var<workgroup> mm_Asub : array<array<f32, ${n}>, ${t}>;
var<workgroup> mm_Bsub : array<array<f32, ${a}>, ${n}>;
// If the output size is small for matrix multiplication, avoid to use vec4
// and handle some elements per thread to optimally utilize the ALU.
// 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.
${Ce()} {
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) / ${n} + 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 + ${n};
globalRowB = globalRowB + ${n};
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 + ${n};
globalRowB = globalRowB + ${n};
for (var k = 0; k < ${n}; k = k + 1) {
acc = acc + mm_Asub[tileRow][k] * mm_Bsub[k][tileCol];
}
workgroupBarrier();
}
mm_write(batch, globalRow, globalCol, acc);
}
`}var vse=class{constructor(e,t,a,n=!1,r=!1,s=null,i=null,o=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workgroupSize=[16,8,1],this.outputShape=a,this.dispatchLayout={x:[2],y:[1],z:[0]},this.dispatch=[Math.ceil(a[2]/this.workgroupSize[0]),Math.ceil(a[1]/this.workgroupSize[1]),a[0]];let l=s!=null;l&&this.variableNames.push("bias");let u=o!=null;u&&this.variableNames.push("preluActivationWeights"),this.transposeA=n,this.transposeB=r,this.addBias=l,this.activation=i,this.hasPreluActivationWeights=u,this.batchAEqualOne=e[0]===1,this.batchBEqualOne=t[0]===1,this.shaderKey=`matMulSmallOutputSize_${this.activation}_${n}_${r}_${this.batchAEqualOne}_${this.batchBEqualOne}`}getUserCode(){return`
${Tr(this.activation,this.hasPreluActivationWeights)}
${B3(this.addBias,this.activation,this.batchAEqualOne,this.batchBEqualOne,this.transposeA,this.transposeB)}
${bse(this.workgroupSize)}
`}},wse=class{constructor(e,t,a,n,r=!1,s=!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=Ne(this.dispatchLayout,[this.outputShape[0],this.outputShape[1],this.outputShape[2],t],this.workgroupSize,this.elementsPerThread),this.transposeA=r,this.transposeB=s,this.batchAEqualOne=a,this.batchBEqualOne=n,this.shaderKey=`matMulSplitK_${r}_${s}_${a}_${n}_${this.elementsPerThread}_${this.isVec4}`}getUserCode(){let e=a=>`
for (var i = 0; i < ${a}; i = i + 1)
{
var oldValue = atomicLoad(&(result[flatIndex + i]));
var exchanged = false;
for (; !exchanged;) {
let newValueF32 = bitcast<f32>(oldValue) + ${a>1?"value[i]":"value"};
let newValue = bitcast<i32>(newValueF32);
let res = atomicCompareExchangeWeak(&(result[flatIndex + i]), oldValue, newValue);
oldValue = res.old_value;
exchanged = res.exchanged;
}
}
`,t=this.isVec4?4:1;return`
${_8(this.batchAEqualOne,this.batchBEqualOne,!1,this.transposeB,!1,!1,!1,t)}
fn mm_write(batch: i32, row : i32, colIn : i32, value : ${Mt(t)}) {
let col = colIn * ${t};
if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) {
let coords = vec3<i32>(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?Uh(this.elementsPerThread,this.workgroupSize,this.transposeA,32,!0,this.splitedDimInner):Gh(this.elementsPerThread,this.workgroupSize,this.transposeA,32,!0,this.splitedDimInner)}
`}},kse=class{constructor(e,t=null,a=null,n=null){this.uniforms="",this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.addBias=t!=null,this.hasPreluActivationWeights=n!=null,this.activation=a,this.addBias&&this.variableNames.push("bias"),this.hasPreluActivationWeights&&this.variableNames.push("preluActivationWeights"),this.shaderKey=`biasActivation_${a}`}getUserCode(){return`
${Tr(this.activation,this.hasPreluActivationWeights)}
${Ce("index")} {
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
var value = getXByOutputIndex(index);
${vo(this.addBias,this.activation)}
setOutputAtIndex(index, value);
}
}
`}},Ise=class{constructor(e){this.variableNames=[],this.outputShape=[],this.uniforms="value : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="fill"}getUserCode(){return`
${Ce("index")} {
if (index < uniforms.size) {
setOutputAtIndex(index, uniforms.value);
}
}
`}};function Cr(e){let{backend:t,attrs:a}=e,{shape:n,value:r}=a,{dtype:s}=a;if(s=s||v.inferDtype(r),s==="string"){let i=v.getArrayFromDType(s,v.sizeFromShape(n));return i.fill(r),t.makeTensorInfo(n,s,i)}else{let i=new Ise(n),o=[{type:"float32",data:[r]}];return t.runWebGPUProgram(i,[],s,o)}}var Sse={kernelName:Fl,backendName:"webgpu",kernelFunc:Cr};function Ie(e){let{inputs:t,attrs:a}=e,{x:n}=t,{shape:r}=a,s=v.sizeFromShape(n.shape),i=v.inferFromImplicitShape(r,s),o=v.sizeFromShape(i);return v.assert(s===o,()=>`The new shape (${i}) has ${o} elements and the old shape (${n.shape}) has ${s} elements. The new shape and old shape must have the same number of elements.`),e.backend.incRef(n.dataId),{dataId:n.dataId,shape:i,dtype:n.dtype}}var Tse={kernelName:ql,backendName:"webgpu",kernelFunc:Ie};function Hh({a:e,b:t,transposeA:a,transposeB:n,backend:r,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){let u=e.shape.length,p=t.shape.length,c=a?e.shape[u-2]:e.shape[u-1],d=n?t.shape[p-1]:t.shape[p-2],h=a?e.shape[u-1]:e.shape[u-2],f=n?t.shape[p-2]:t.shape[p-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),x=v.sizeFromShape(m),A=v.sizeFromShape(g),y=xo.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([h,f]);v.assert(c===d,()=>`Error in matMul: inner shapes (${c}) and (${d}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${a} and transposeB=${n} must match.`);let b=a?[x,c,h]:[x,h,c],w=n?[A,f,d]:[A,d,f],S=Ie({inputs:{x:e},backend:r,attrs:{shape:b}}),C=Ie({inputs:{x:t},backend:r,attrs:{shape:w}}),E=[S,C],_=Math.max(x,A),$=x===1,M=A===1,I=[S,C],N=[{type:"int32",data:[h]},{type:"int32",data:[f]},{type:"int32",data:[c]}],O,L,B=[_,h,f],G=W().get("WEBGPU_MATMUL_PROGRAM_TYPE");if(G<0){let U=W().getNumber("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL"),H=U>0?U:r.thresholdToIncreaseWorkgroups,V=_*Math.ceil(h/32)*Math.ceil(f/32);V<=H||h<=8&&V<=H*2?_*h*f<=128?G=Pn.MatMulReduceProgram:_===1&&d>=2e3?G=Pn.MatMulSplitKProgram:G=Pn.MatMulSmallOutputSizeProgram:G=Pn.MatMulPackedProgram}switch(G){case Pn.MatMulReduceProgram:O=new yse(B,$,M,a,n,s,l,i);break;case Pn.MatMulSplitKProgram:{if(L=Cr({backend:r,attrs:{shape:B,value:0,dtype:e.dtype}}),O=new wse(B,d,$,M,a,n),s||l){L=r.runWebGPUProgram(O,I,e.dtype,N,L);let H=new kse(L.shape,s,l,i),V=null,Q=[L];s&&Q.push(s),i&&Q.push(i),l==="leakyrelu"&&(V=[{type:"float32",data:[o]}],H.uniforms+=" alpha : f32,");let Z=r.runWebGPUProgram(H,Q,L.dtype,V);E.push(L);let re=Ie({inputs:{x:Z},backend:r,attrs:{shape:y}});E.push(Z);for(let ee of E)r.disposeData(ee.dataId);return re}break}case Pn.MatMulSmallOutputSizeProgram:O=new vse(b,w,B,a,n,s,l,i);break;case Pn.MatMulPackedProgram:let U=r.adapterInfo.isIntel();O=new xse(b,B,$,M,a,n,s,l,i,U);break;default:throw new Error(`Unsupported MatMulProgramType ${G}.`)}s&&I.push(s),i&&I.push(i),l==="leakyrelu"&&(N.push({type:"float32",data:[o]}),O.uniforms+=" alpha : f32,"),L=r.runWebGPUProgram(O,I,e.dtype,N,L);let j=Ie({inputs:{x:L},backend:r,attrs:{shape:y}});E.push(L);for(let U of E)r.disposeData(U.dataId);return j}function Cse(e){let{inputs:t,backend:a,attrs:n}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:p,leakyreluAlpha:c}=n;return Hh({a:r,b:s,transposeA:l,transposeB:u,backend:a,bias:i,preluActivationWeights:o,leakyreluAlpha:c,activation:p})}var Nse={kernelName:jr,backendName:"webgpu",kernelFunc:Cse},Xx=class{constructor(e,t,a){this.variableNames=["AReal","AImag","BReal","BImag"],this.workgroupSize=[128,1,1],this.size=!0,this.outputShape=T.assertAndGetBroadcastShape(t,a),this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(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 {
${L3(this.op,!1)}
}
${Ce("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));
}
}
`}},P1=class{constructor(e,t,a){this.size=!0,this.variableNames=["A","B"],this.outputShape=T.assertAndGetBroadcastShape(t,a),this.dispatchLayout=Ve(this.outputShape),this.op=e,this.useSharedMemoryWithA=t.length<=1&&a.length>1&&t[0]<128,this.useSharedMemoryWithB=a.length<=1&&t.length>1&&a[0]<128,this.useSharedMemoryWithA||this.useSharedMemoryWithB?(this.isVec4=!1,this.lastDimensionSize=this.useSharedMemoryWithB?a[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,a)&&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=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1])}getUserCode(){let e,t=this.isVec4?"vec4<f32>":"f32",a=`
fn binaryOperation(a : ${t}, b : ${t}) -> ${t} {
${L3(this.op,this.isVec4)}
};
`;if(this.type==="shared"){let n=this.lastDimensionSize>1?`coords[${this.outputShape.length-1}]`:"0",r=this.useSharedMemoryWithB?`let a = getAByOutputIndex(index);
let b = sharedBuf[${n}];`:`let a = sharedBuf[${n}];
let b = getBByOutputIndex(index);`;e=`
${a}
var<workgroup> sharedBuf : array<f32, ${this.lastDimensionSize}>;
${Ce("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=`
${a}
${Ce("index")} {
if (index < uniforms.size) {
let a = getAByOutputIndex(index);
let b = getBByOutputIndex(index);
setOutputAtIndex(index, binaryOperation(a, b));
}
}
`;return e}};function Ya(e){let{inputs:t}=e,{x:a}=t;return e.backend.incRef(a.dataId),{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}var Ese={kernelName:ki,backendName:"webgpu",kernelFunc:Ya};function wo(e){let{inputs:t,backend:a}=e,{real:n,imag:r}=t,s=a.makeTensorInfo(n.shape,"complex64"),i=a.tensorMap.get(s.dataId),o=Ya({inputs:{x:n},backend:a}),l=Ya({inputs:{x:r},backend:a});return i.complexTensorInfos={real:o,imag:l},s}var Rse={kernelName:Sd,backendName:"webgpu",kernelFunc:wo},mp=class{constructor(e,t){this.variableNames=["A"],this.size=!0;let a=128;this.workgroupSize=[a,1,1],this.outputShape=e,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.op=t,this.shaderKey=`unary_${t}`}getUserCode(){return`
fn unaryOperation(a : f32) -> f32 {
${Ms(this.op,!1)}
}
${Ce("index")} {
if (index < uniforms.size) {
let a = getAByOutputIndex(index);
setOutputAtIndex(index, unaryOperation(a));
}
}
`}};function it({opType:e,cpuKernelImpl:t,dtype:a}){return({inputs:n,backend:r})=>{let{x:s}=n,i=r,o=a||s.dtype;if(i.shouldExecuteOnCPU([s])&&t!=null){let u=i.tensorMap.get(s.dataId),p=t(u.values,o);return i.makeTensorInfo(s.shape,o,p)}let l=new mp(s.shape,e);return i.runWebGPUProgram(l,[s],o)}}function ua({opType:e,cpuKernelImpl:t,supportsComplex:a=!1,dtype:n}){return({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;if(a&&i.dtype==="complex64"){let c=l.tensorMap.get(i.dataId),d=l.tensorMap.get(o.dataId),h,f;if(e!==De.MUL)[h,f]=[[c.complexTensorInfos.real,d.complexTensorInfos.real],[c.complexTensorInfos.imag,d.complexTensorInfos.imag]].map(g=>{let[x,A]=g,y={dataId:x.dataId,dtype:x.dtype,shape:i.shape},b={dataId:A.dataId,dtype:A.dtype,shape:o.shape},w=new P1(e,i.shape,o.shape);return l.runWebGPUProgram(w,[y,b],ca(x.dtype,A.dtype))});else{let g=new Xx(De.COMPLEX_MULTIPLY_REAL,i.shape,o.shape),x=new Xx(De.COMPLEX_MULTIPLY_IMAG,i.shape,o.shape),A=[{dataId:c.complexTensorInfos.real.dataId,dtype:c.complexTensorInfos.real.dtype,shape:i.shape},{dataId:c.complexTensorInfos.imag.dataId,dtype:c.complexTensorInfos.imag.dtype,shape:i.shape},{dataId:d.complexTensorInfos.real.dataId,dtype:d.complexTensorInfos.real.dtype,shape:o.shape},{dataId:d.complexTensorInfos.imag.dataId,dtype:d.complexTensorInfos.imag.dtype,shape:o.shape}];h=l.runWebGPUProgram(g,A,"float32"),f=l.runWebGPUProgram(x,A,"float32")}let m=wo({inputs:{real:h,imag:f},backend:l});return l.disposeData(h.dataId),l.disposeData(f.dataId),m}let u=n||ca(i.dtype,o.dtype);if((i.dtype==="string"||o.dtype==="string"||l.shouldExecuteOnCPU([i,o]))&&t!=null){let c=l.tensorMap.get(i.dataId).values,d=l.tensorMap.get(o.dataId).values,h=i.dtype==="string"?T.fromUint8ToStringArray(c):c,f=i.dtype==="string"?T.fromUint8ToStringArray(d):d,[m,g]=t(i.shape,o.shape,h,f,u);return l.makeTensorInfo(g,u,m)}let p=new P1(e,i.shape,o.shape);return l.runWebGPUProgram(p,[i,o],u)}}var{addImpl:Mse,castImpl:$se,ceilImpl:_se,concatImpl:Pse,equalImpl:Fse,expImpl:Ose,expm1Impl:Dse,floorImpl:zse,gatherNdImpl:Lse,gatherV2Impl:Bse,greaterEqualImpl:Wse,greaterImpl:Vse,lessEqualImpl:Use,lessImpl:Gse,logImpl:Hse,maxImpl:jse,maximumImpl:qse,minimumImpl:Xse,multiplyImpl:Kse,negImpl:Zse,notEqualImpl:Yse,prodImpl:Jse,rangeImpl:Qse,rsqrtImpl:eie,scatterImpl:tie,simpleAbsImpl:aie,sliceImpl:nie,stridedSliceImpl:rie,stringNGramsImpl:sie,subImpl:iie,tileImpl:oie,topKImpl:lie,transposeImpl:uie,uniqueImpl:I0e}=_h,die=it({opType:de.ABS,cpuKernelImpl:aie}),pie={kernelName:wl,backendName:"webgpu",kernelFunc:die},cie=it({opType:de.ACOS}),hie={kernelName:kl,backendName:"webgpu",kernelFunc:cie},fie=it({opType:de.ACOSH}),mie={kernelName:Il,backendName:"webgpu",kernelFunc:fie},gie=ua({opType:De.ADD,cpuKernelImpl:Mse,supportsComplex:!0}),xie={kernelName:ts,backendName:"webgpu",kernelFunc:gie},Aie=class{constructor(e){this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e[0],this.variableNames=e.map((t,a)=>`T${a}`),this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.shaderKey="addN"}getUserCode(){let e=[];this.variableNames.forEach(a=>{e.push(`let v${a} = get${a}ByOutputCoords(coords);`)});let t=this.variableNames.map(a=>`v${a}`).join(" + ");return`
${Ce("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 yie(e){let{inputs:t,backend:a}=e,n=t;if(n.length===1)return Ya({inputs:{x:n[0]},backend:a});let r=n.map(o=>o.dtype).reduce((o,l)=>ca(o,l)),s=n.map(o=>o.shape),i=new Aie(s);return a.runWebGPUProgram(i,n,r)}var bie={kernelName:Ks,backendName:"webgpu",kernelFunc:yie},vie=class{constructor(e,t){this.variableNames=["A"],this.workgroupSize=[16,16,1];let a=new Array(e.length);for(let n=0;n<a.length;n++)a[n]=e[t[n]];this.outputShape=a,this.dispatchLayout={x:[0],y:[1]},this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize,[1,1,1]),this.shaderKey="transposeShared"}getUserCode(){return v.assert(this.workgroupSize[0]===this.workgroupSize[1],()=>`Must be a square tile, current tile shape is ${this.workgroupSize[0]} x ${this.workgroupSize[1]}`),`
const tileSize = ${this.workgroupSize[0]};
var<workgroup> tile : array<array<f32, ${this.workgroupSize[0]+1}>, ${this.workgroupSize[0]}>;
${Ce()} {
var x = i32(workgroupId.x) * tileSize + i32(localId.x);
var y = i32(workgroupId.y) * tileSize + i32(localId.y);
let width = uniforms.outShape[0];
let height = uniforms.outShape[1];
if (x < width && y < height) {
tile[localId.y][localId.x] = f32(A[y * width + x]);
}
workgroupBarrier();
x = i32(workgroupId.y) * tileSize + i32(localId.x);
y = i32(workgroupId.x) * tileSize + i32(localId.y);
if (x < height && y < width) {
setOutputAtIndex((y * height + x), tile[localId.x]
[localId.y]);
}
}
`}},wie=class{constructor(e,t){this.variableNames=["A"],this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0;let a=new Array(e.length);for(let n=0;n<a.length;n++)a[n]=e[t[n]];this.outputShape=a,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.newDim=t,this.shaderKey=`transpose_${t}`}getUserCode(){let e=ra(this.outputShape.length),t=kie(this.newDim);return`
${Ce("index")} {
for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
let flatIndex = index * ${this.workPerThread} + i;
if(flatIndex < uniforms.size) {
let resRC = getCoordsFromIndex(flatIndex);
setOutputAtIndex(flatIndex, A[getIndexFromCoords${this.outputShape.length}D(
${e}(${t}), uniforms.aShape)]);
}
}
}
`}};function kie(e){let t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);let a=new Array(t);for(let n=0;n<e.length;n++)a[e[n]]=`resRC.${yr(n)}`;return a.join()}function vr(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{perm:s}=n,i=a,o=r.shape.length,l=new Array(o);for(let p=0;p<l.length;p++)l[p]=r.shape[s[p]];if(a.shouldExecuteOnCPU([r])){let p=i.tensorMap.get(r.dataId).values,c=uie(p,r.shape,r.dtype,s,l);return a.makeTensorInfo(l,r.dtype,c)}if(r.shape.length===2&&v.arraysEqual(s,[1,0])){let p=new vie(r.shape,s);return i.runWebGPUProgram(p,[r],r.dtype)}let u=new wie(r.shape,s);return i.runWebGPUProgram(u,[r],r.dtype)}var Iie={kernelName:Ar,backendName:"webgpu",kernelFunc:vr},Sie=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[a]=T.computeOutAndReduceShapes(this.inputShape,[1]);this.outputShape=a.length===0?[1]:a,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(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"):this.reduceType==="all"?(e=" bestValue = f32(bestValue >= 1.0 && candidate >= 1.0); ",t="1.0"):this.reduceType==="any"&&(e=" bestValue = f32(bestValue >= 1.0 || candidate >= 1.0); ",t="0.0");let a=this.reduceType==="mean"?"setOutputAtIndex(outputIndex, bestValue / f32(uniforms.reduceSize));":"setOutputAtIndex(outputIndex, bestValue);";return`
fn DIV_CEIL(a : u32, b : u32) -> u32 {
return ((a - 1u) / b + 1u);
}
${`
var<workgroup> xBestValues : array<f32, ${this.workgroupSize[0]}>;
`}
fn getOffset(outputIndex : i32) -> i32 {
let outputCoords = getCoordsFromIndex(outputIndex);
let offset = ${this.outputShape.length===1?"outputCoords":"outputCoords[0]"} * uniforms.reduceSize;
return offset;
}
${Ce("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) {
${a}
}
}
`}};function ko(e,t,a,n,r){let s=e.shape.length,i=[],o=v.parseAxisParam(t,e.shape),l=o,u=T.getAxesPermutation(l,s),p=e;u!=null&&(p=vr({inputs:{x:e},attrs:{perm:u},backend:r}),l=T.getInnerMostAxes(l.length,s),i.push(p)),T.assertAxesAreInnerMostDims(n,l,s);let[c,d]=T.computeOutAndReduceShapes(p.shape,l),h=c;a&&(h=T.expandShapeToKeepDim(c,o));let f;if((n==="max"||n==="prod")&&r.shouldExecuteOnCPU([p])){let m=r.tensorMap.get(p.dataId).values;switch(n){case"max":let g=jse(m,v.sizeFromShape(d),h,e.dtype);f=r.makeTensorInfo(h,e.dtype,g);break;case"prod":let{outVals:x,outShape:A,outDtype:y}=Jse(p.shape,p.dtype,m,l);f=r.makeTensorInfo(A,y,x);break;default:throw new Error(`${n} CPU implementation is not yet supported.`)}}else{let m=v.sizeFromShape(d),g=v.sizeFromShape(p.shape)/m,x={windowSize:m,inSize:m,batchSize:g,outSize:1},A=n==="mean"?"float32":Hd(e.dtype),y=[{type:"int32",data:[m]}],b=new Sie(x,n),w=r.runWebGPUProgram(b,[p],A,y);i.push(w),f=Ie({inputs:{x:w},attrs:{shape:h},backend:r})}return i.forEach(m=>r.disposeData(m.dataId)),f}function Tie(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{keepDims:s,axis:i}=n;return ko(r,i,s,"all",a)}var Cie={kernelName:Zs,backendName:"webgpu",kernelFunc:Tie};function Nie(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{keepDims:s,axis:i}=n;return ko(r,i,s,"any",a)}var Eie={kernelName:Ys,backendName:"webgpu",kernelFunc:Nie},P8=class{constructor(e,t,a){this.workgroupSize=[64,1,1],this.variableNames=["x"],this.uniforms="infinityValue : f32,",this.size=!0;let n=[t];this.op=a==="min"?"<":">";let[r,s]=T.computeOutAndReduceShapes(e,n);this.outputShape=r.length===0?[1]:r,this.dispatchLayout=Ve(this.outputShape),v.sizeFromShape(s)<32||v.sizeFromShape(r)>1e3?(this.type="plain",this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize)):(this.type="shared",this.dispatch=Ne(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.${yr(this.inputShape.length-1)}`,t=()=>{let a="";if(this.outputShape.length===1)this.inputShape.length!==1&&(a+="outputCoords,");else for(let n=0;n<this.outputShape.length;n++)a+=`outputCoords.${yr(n)},`;return a};return this.type==="shared"?`
fn DIV_CEIL(a : u32, b : u32) -> u32 {
return ((a - 1u) / b + 1u);
}
${`
var<workgroup> xBestIndices : array<i32, ${this.workgroupSize[0]}>;
var<workgroup> xBestValues : array<f32, ${this.workgroupSize[0]}>;
`}
${Ce("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]);
}
}
`:`
${Ce("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);
}
}
`}};function Rie(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s}=n,i=v.parseAxisParam(s,r.shape),o=T.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=vr({inputs:{x:r},backend:a,attrs:{perm:o}}),u.push(l),i=T.getInnerMostAxes(i.length,l.shape.length)),T.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let p=new P8(l.shape,i[0],"max"),c=[{type:"float32",data:[Number.NEGATIVE_INFINITY]}],d=a.runWebGPUProgram(p,[l],"int32",c);return u.forEach(h=>a.disposeData(h.dataId)),d}var Mie={kernelName:Js,backendName:"webgpu",kernelFunc:Rie};function $ie(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s}=n,i=v.parseAxisParam(s,r.shape),o=T.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=vr({inputs:{x:r},backend:a,attrs:{perm:o}}),u.push(l),i=T.getInnerMostAxes(i.length,l.shape.length)),T.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let p=new P8(l.shape,i[0],"min"),c=[{type:"float32",data:[Number.POSITIVE_INFINITY]}],d=a.runWebGPUProgram(p,[l],"int32",c);return u.forEach(h=>a.disposeData(h.dataId)),d}var _ie={kernelName:kd,backendName:"webgpu",kernelFunc:$ie},Pie=it({opType:de.ASIN}),Fie={kernelName:Sl,backendName:"webgpu",kernelFunc:Pie},Oie=it({opType:de.ASINH}),Die={kernelName:Tl,backendName:"webgpu",kernelFunc:Oie},zie=it({opType:de.ATAN}),Lie={kernelName:Cl,backendName:"webgpu",kernelFunc:zie},Bie=ua({opType:De.ATAN2}),Wie={kernelName:El,backendName:"webgpu",kernelFunc:Bie},Vie=it({opType:de.ATANH}),Uie={kernelName:Nl,backendName:"webgpu",kernelFunc:Vie},Kx=class{constructor(e,t){this.variableNames=["x"],this.uniforms="stride : vec2<i32>, pad : vec2<i32>, dilation : vec2<i32>, convDims : vec2<i32>, filterDims : vec2<i32>,",this.workgroupSize=[128,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(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"),`
${Ce("index")} {
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let batch = coords[0];
let xRCCorner = vec2<i32>(coords.yz) * uniforms.stride - uniforms.pad;
let xRCorner = xRCCorner.x;
let xCCorner = xRCCorner.y;
var resultValue = ${this.poolType==="avg"?"0.0":"-1.0 / pow(10.0, -20.0)"};
var count = 0.0;
for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + uniforms.dilation.x) {
let xR = xRCorner + wR;
if (xR < 0 || xR >= uniforms.convDims.x) {
continue;
}
for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + uniforms.dilation.y) {
let xC = xCCorner + wC;
if (xC < 0 || xC >= uniforms.convDims.y) {
continue;
}
let value = getX(batch, xR, xC, coords[3]);
${e}
}
}
setOutputAtIndex(index, ${t});
}
}
`}},Gie=class{constructor(e){this.variableNames=["x"],this.uniforms="stride : vec2<i32>,",this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="poolWithFilterSizeEqualsOne"}getUserCode(){return`
${Ce("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);
}
}
`}};function W3(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{reductionIndices:s,keepDims:i}=n;return ko(r,s,i,"max",a)}var Hie={kernelName:Mi,backendName:"webgpu",kernelFunc:W3};function F8(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{keepDims:s,axis:i}=n;return ko(r,i,s,"mean",a)}var jie={kernelName:Pi,backendName:"webgpu",kernelFunc:F8};function O8(e,t,a,n){if(t.filterWidth===1&&t.filterHeight===1&&v.arraysEqual(t.inShape,t.outShape))return Ya({inputs:{x:e},backend:n});if(t.filterWidth===t.inWidth&&t.filterHeight===t.inHeight&&t.batchSize===1&&t.padInfo.type==="VALID"){let i=e.shape.length,o=Ie({inputs:{x:e},backend:n,attrs:{shape:[e.shape[i-3]*e.shape[i-2],e.shape[i-1]]}}),l;a==="avg"?l=F8({inputs:{x:o},backend:n,attrs:{axis:0,keepDims:!1}}):(v.assert(a==="max",()=>`Invalid pool type ${a}`),l=W3({inputs:{x:o},backend:n,attrs:{reductionIndices:0,keepDims:!1}}));let u=Ie({inputs:{x:l},backend:n,attrs:{shape:t.outShape}});return n.disposeData(o.dataId),n.disposeData(l.dataId),u}let r,s=[{type:"int32",data:[t.strideHeight,t.strideWidth]}];return t.filterHeight===1&&t.filterWidth===1?r=new Gie(t):(a==="avg"?r=new Kx(t,"avg"):(v.assert(a==="max",()=>`Invalid pool type ${a}`),r=new Kx(t,"max")),s.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]})),n.runWebGPUProgram(r,[e],e.dtype,s)}function qie(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1,p=T.computePool2DInfo(r.shape,s,i,u,o,l);return O8(r,p,"avg",a)}var Xie={kernelName:Qs,backendName:"webgpu",kernelFunc:qie};function Kie(e){let{inputs:t,backend:a,attrs:n}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=n;return Hh({a:r,b:s,transposeA:i,transposeB:o,backend:a})}var Zie={kernelName:ei,backendName:"webgpu",kernelFunc:Kie},Yie=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=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.start=e,this.uniforms=`start : ${ra(e.length)}, `,this.shaderKey="slice"}getUserCode(){let e=ra(this.rank),t=Jie(this.rank),a;return this.start.length===1?a=this.outputShape.map((n,r)=>"sourceLoc = uniforms.start + coords;"):a=this.outputShape.map((n,r)=>`sourceLoc.${F1[r]} = uniforms.start.${yr(r)} + coords.${F1[r]};`),`
${Ce("index")} {
if (index < uniforms.size) {
var sourceLoc : ${e};
let coords = getCoordsFromIndex(index);
${a.join(`
`)}
setOutputAtIndex(index, getSource(${t}));
}
}
`}},F1=["x","y","z","w","u","v"];function Jie(e){if(e===1)return"sourceLoc";if(e<=6)return F1.slice(0,e).map(t=>`sourceLoc.${t}`).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}function Au(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{begin:s,size:i}=n,[o,l]=It.parseSliceParams(r,s,i);if(It.assertParamsValid(r,o,l),a.shouldExecuteOnCPU([r])||r.dtype==="string"){let c=a.tensorMap.get(r.dataId),d=nie(c.values,o,l,r.shape,r.dtype);return a.makeTensorInfo(l,r.dtype,d)}if(v.sizeFromShape(l)===0)return a.makeTensorInfo(l,r.dtype,[]);let u=new Yie(o,l),p=[{type:"int32",data:o}];return a.runWebGPUProgram(u,[r],r.dtype,p)}var Qie={kernelName:Zl,backendName:"webgpu",kernelFunc:Au},eoe=e=>{let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{blockShape:s,crops:i}=n;v.assert(r.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGPU backend not implemented yet");let o=s.reduce((A,y)=>A*y),l=T.getReshaped(r.shape,s,o),u=T.getPermuted(l.length,s.length),p=T.getReshapedPermuted(r.shape,s,o),c=T.getSliceBeginCoords(i,s.length),d=T.getSliceSize(p,i,s.length),h=[],f=Ie({inputs:{x:r},backend:a,attrs:{shape:l}}),m=vr({inputs:{x:f},backend:a,attrs:{perm:u}}),g=Ie({inputs:{x:m},backend:a,attrs:{shape:p}}),x=Au({inputs:{x:g},backend:a,attrs:{begin:c,size:d}});return h.push(f),h.push(m),h.push(g),h.forEach(A=>a.disposeData(A.dataId)),x},toe={kernelName:Rl,backendName:"webgpu",kernelFunc:eoe},aoe=`
fn bincount_write(index: i32, value: f32) {
var oldValue = atomicLoad(& (result[index]));
var exchanged = false;
for (; !exchanged;) {
let newValueF32 = bitcast<f32>(oldValue) + value;
let newValue = bitcast<i32>(newValueF32);
let res = atomicCompareExchangeWeak(
&(result[index]), oldValue, newValue);
oldValue = res.old_value;
exchanged = res.exchanged;
}
}
`,noe=`
fn bincount_write(index: i32, value: f32) {
result[index] = value;
}
`,D8=class{constructor(e,t,a=!1){this.outputShape=[],this.variableNames=["x"],this.uniforms="binCountSize : i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.hasWeights=!0,this.binaryOutput=!1,this.outputShape=e,this.rank=e.length,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.binaryOutput=a,a&&(this.atomic=!1),this.hasWeights=t,this.hasWeights&&this.variableNames.push("w"),this.shaderKey=`bincount_${this.hasWeights}_${this.binaryOutput}_${this.rank}`}getUserCode(){return`
${this.binaryOutput?noe:aoe}
${Ce("index")} {
${this.rank===1?`if (index < uniforms.xShape) {
let indexVal = i32(getX(index));
if (indexVal < uniforms.binCountSize) {
let value = ${this.binaryOutput?1:this.hasWeights?"f32(getW(index))":"1."};
bincount_write(indexVal, value);
}
}`:`let coord = getCoordsFromIndex(index);
if (coordsInBounds2D(coord, uniforms.xShape)) {
let indexVal = i32(getX(coord[0], coord[1]));
if (indexVal < uniforms.binCountSize) {
let value = ${this.binaryOutput?1:this.hasWeights?"f32(getW(coord[0], coord[1]))":"1."};
bincount_write(coord.x * uniforms.binCountSize + indexVal, value);
}
}`}
}
`}};function roe(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,weights:s}=t,{size:i}=n,o=v.sizeFromShape(r.shape),l=v.sizeFromShape(s.shape)>0,u=[i],p=s.dtype,c=Cr({backend:a,attrs:{shape:u,value:0,dtype:p}}),d=new D8([o],l),h=[{type:"int32",data:[i]}],f=l?[r,s]:[r];return a.runWebGPUProgram(d,f,p,h,c)}var soe={kernelName:Id,backendName:"webgpu",kernelFunc:roe},z8=ua({opType:De.NOT_EQUAL,dtype:"bool",cpuKernelImpl:Yse}),ioe={kernelName:Li,backendName:"webgpu",kernelFunc:z8};function gp(e){let{inputs:t,backend:a}=e,{input:n}=t,r=a.tensorMap.get(n.dataId);return Ya({inputs:{x:r.complexTensorInfos.real},backend:a})}var ooe={kernelName:Md,backendName:"webgpu",kernelFunc:gp};function loe(e,t){let a=new mp(e.shape,de.TO_INT),n=t.runWebGPUProgram(a,[e],"int32");return{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}function O1(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{dtype:s}=n;if(s==="complex64"){if(r.dtype==="complex64")return Ya({inputs:{x:r},backend:a});let i=fn(r.shape),o=O1({inputs:{x:r},backend:a,attrs:{dtype:"float32"}}),l=wo({inputs:{real:o,imag:i},backend:a});return i.dispose(),a.disposeData(o.dataId),l}if(r.dtype==="complex64"){let i=gp({inputs:{input:r},backend:a}),o=O1({inputs:{x:i},backend:a,attrs:{dtype:s}});return a.disposeData(i.dataId),o}if(!v.hasEncodingLoss(r.dtype,s)){let i=Ya({inputs:{x:r},backend:a});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(a.shouldExecuteOnCPU([r])){let i=a.tensorMap.get(r.dataId).values,[o,l,u]=$se(i,r.shape,r.dtype,s);return a.makeTensorInfo(o,l,u)}if(s==="int32")return loe(r,a);if(s==="bool"){let i=a.makeTensorInfo([],"bool",v.getTypedArrayFromDType("bool",1)),o=z8({inputs:{a:r,b:i},backend:a});return a.disposeData(i.dataId),o}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${s}`)}var uoe={kernelName:ti,backendName:"webgpu",kernelFunc:O1},doe=it({opType:de.CEIL,cpuKernelImpl:_se}),poe={kernelName:ai,backendName:"webgpu",kernelFunc:doe},coe=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=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.shaderKey="clipVec4"}getUserCode(){return`
${Ce("index")} {
if(index < uniforms.size) {
let value = getAByOutputIndex(index);
var clampedValue : vec4<f32>;
for (var i = 0; i < 4; i = i + 1) {
if (isnan(value[i])) {
clampedValue[i] = value[i];
} else {
clampedValue[i] = clamp(value[i], uniforms.minVal, uniforms.maxVal);
}
}
setOutputAtIndex(index, clampedValue);
}
}
`}},hoe=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=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="clip"}getUserCode(){return`
${Ce("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 foe(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{clipValueMin:s,clipValueMax:i}=n,o,l=[{type:"float32",data:[s]},{type:"float32",data:[i]}];return v.sizeFromShape(r.shape)%4===0?o=new coe(r.shape):o=new hoe(r.shape),a.runWebGPUProgram(o,[r],r.dtype,l)}var moe={kernelName:as,backendName:"webgpu",kernelFunc:foe},goe=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,a)=>`T${a}`),this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.offsetLength=e.length-1;for(let t=0;t<this.offsetLength;t++)this.uniforms+=`offset${t} : i32,`;this.shaderKey="concat"}getUserCode(){let e=[];if(this.offsetLength>0){e.push("if (yC < uniforms.offset0){ setOutputAtCoords(coords.x, coords.y, getT0(yR, yC)); }");for(let n=1;n<this.offsetLength;n++)e.push(`else if (yC < uniforms.offset${[n]}){ setOutputAtCoords(coords.x, coords.y, getT${n}(yR, yC - uniforms.offset${n-1})); }`);let t=this.offsetLength,a=this.offsetLength-1;e.push(`else { setOutputAtCoords(coords.x, coords.y, getT${t}(yR, yC - uniforms.offset${a})); }`)}else e.push("setOutputAtCoords(coords.x, coords.y, getT0(yR, yC));");return`
${Ce("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);
let yR = coords.x;
let yC = coords.y;
${e.join(`
`)}
}
}
}
`}};function jh(e){let{inputs:t,backend:a}=e,{input:n}=t,r=a.tensorMap.get(n.dataId);return Ya({inputs:{x:r.complexTensorInfos.imag},backend:a})}var xoe={kernelName:Rd,backendName:"webgpu",kernelFunc:jh};function Ju(e,t,a){let n=e[0].dtype;if(n==="complex64"){let f=e.map(y=>gp({inputs:{input:y},backend:a})),m=e.map(y=>jh({inputs:{input:y},backend:a})),g=Ju(f,t,a),x=Ju(m,t,a),A=wo({inputs:{real:g,imag:x},backend:a});return f.forEach(y=>a.disposeData(y.dataId)),m.forEach(y=>a.disposeData(y.dataId)),a.disposeData(g.dataId),a.disposeData(x.dataId),A}let r=a.shouldExecuteOnCPU(e);if(n==="string"&&(r=!0),r){let f=e.map(w=>{let S=[-1,v.sizeFromShape(w.shape.slice(t))];return Ie({inputs:{x:w},backend:a,attrs:{shape:S}})}),m=f.map(w=>({vals:a.readSync(w.dataId),shape:w.shape})),g=T.computeOutShape(f.map(w=>w.shape),1),x=f[0].shape[0]===1,A=Pse(m,g,n,x),y=T.computeOutShape(e.map(w=>w.shape),t),b=a.makeTensorInfo(y,n,A);return f.forEach(w=>a.disposeData(w.dataId)),b}let s=a.device.limits.maxStorageBuffersPerShaderStage-1;if(e.length>s){let f=[];for(let g=0;g<e.length;g+=s){let x=e.slice(g,g+s);f.push(Ju(x,t,a))}let m=Ju(f,t,a);for(let g of f)a.disposeData(g.dataId);return m}let{tensors2D:i,outShape:o}=Aoe(e,t,a),l=i.map(f=>f.shape),u=new goe(l),p=[],c=new Array(l.length-1);if(c.length>0){c[0]=l[0][1],p.push({type:"int32",data:[c[0]]});for(let f=1;f<c.length;f++)c[f]=c[f-1]+l[f][1],p.push({type:"int32",data:[c[f]]})}let d=a.runWebGPUProgram(u,i,i[0].dtype,p);i.forEach(f=>a.disposeData(f.dataId));let h=Ie({inputs:{x:d},backend:a,attrs:{shape:o}});return a.disposeData(d.dataId),h}function Aoe(e,t,a){let n=T.computeOutShape(e.map(r=>r.shape),t);return{tensors2D:e.map(r=>Ie({inputs:{x:r},backend:a,attrs:{shape:[v.sizeFromShape(r.shape.slice(0,t)),v.sizeFromShape(r.shape.slice(t))]}})),outShape:n}}function L8(e){let{inputs:t,backend:a,attrs:n}=e,{axis:r}=n,s=v.parseAxisParam(r,t[0].shape)[0],i=t.map(u=>u.shape);T.assertParamsConsistent(i,s);let o=T.computeOutShape(t.map(u=>u.shape),s);if(v.sizeFromShape(o)===0)return a.makeTensorInfo(o,t[0].dtype,[]);let l=t.filter(u=>v.sizeFromShape(u.shape)>0);return l.length===1?Ya({inputs:{x:l[0]},backend:a}):Ju(l,s,a)}var yoe={kernelName:Ml,backendName:"webgpu",kernelFunc:L8};function boe(e,t,a,n,r=!1,s=null,i=!1,o=4,l=4,u=4){let p=E=>{switch(E){case 1:return"resData = x[xIndex];";case 3:return"resData = vec3<f32>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);";case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${E} is not supported.`)}},c=E=>{switch(E){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 ${E} is not supported.`)}},d=e?`
let coord = vec4<i32>(batch, xRow, xCol, xCh);
`:`
let coord = vec4<i32>(batch, xCh, xRow, xCol);
`,h=e?`
let coords = vec4<i32>(
batch,
row / outWidth,
row % outWidth,
col);
`:`
let coords = vec4<i32>(
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",x=e?"col":"row",A=`
let inChannels = uniforms.wShape[2];
let outWidth = ${e?"uniforms.outShape[2]":"uniforms.outShape[3]"};
let outRow = ${g} / outWidth;
let outCol = ${g} % outWidth;
let WRow = ${x} / (uniforms.filterDims[1] * inChannels);
let WCol = ${x} / 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 = ${x} % inChannels;
var resData = ${Mt(o)}(0.0);
// The bounds checking is always needed since we use it to pad zero for
// the 'same' padding type.
if (xRow >= 0 && xRow < ${f} && xCol >= 0 && xCol < ${m}) {
${d}
let xIndex = getIndexFromCoords4D(coord, uniforms.xShape);
${p(o)}
}
return resData;`,y=e?t&&n?`
let col = colIn * ${o};
${A}`:`
let col = colIn * ${o};
if (row < uniforms.dimAOuter && col < uniforms.dimInner) {
${A}
}
return ${Mt(o)}(0.0);`:n&&a?`
let col = colIn * ${o};
${A}`:`
let col = colIn * ${o};
if (row < uniforms.dimInner && col < uniforms.dimBOuter) {
${A}
}
return ${Mt(o)}(0.0);`,b=`${c(l)}`,w=Mt(u),S=Mt(e?o:l),C=Mt(e?l:o);return`
${Tr(s,i,u===4,4)}
fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${S} {
${e?y:b}
}
fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${C} {
${e?b:y}
}
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}
${vo(r,s)}
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
}
}`}var voe=class{constructor(e,t,a,n,r=!1,s=null,i=!1,o=!1){this.variableNames=["x","W"],this.uniforms="filterDims : vec2<i32>, pad : vec2<i32>, stride : vec2<i32>, dilation : vec2<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.outputShape=e.outShape,this.isChannelsLast=e.dataFormat==="channelsLast",this.isVec4=((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=F3(this.dispatchLayout,this.outputShape,this.isVec4),this.elementsPerThread=O3(this.dispatchLayout,this.outputShape,this.isVec4),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize,this.elementsPerThread),this.isVec4?(this.isChannelsLast&&e.inChannels%4!==0?(this.innerElementSize=3,this.variableTypes=["f32","vec4<f32>"]):(this.innerElementSize=4,this.variableTypes=["vec4<f32>","vec4<f32>"]),r&&(this.variableNames.push("bias"),this.variableTypes.push("vec4<f32>")),i&&(this.variableNames.push("preluActivationWeights"),this.variableTypes.push("vec4<f32>"))):(this.innerElementSize=this.elementsPerThread[0],r&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights")),this.sequentialAccessByThreads=o,this.addBias=r,this.activation=s,this.hasPreluActivationWeights=i,this.tileAOuter=this.workgroupSize[1]*this.elementsPerThread[1],this.tileBOuter=this.workgroupSize[0]*this.elementsPerThread[0],this.tileInner=Math.max(this.workgroupSize[0]*this.innerElementSize,this.workgroupSize[1]),this.fitAOuter=t%this.tileAOuter===0,this.fitBOuter=a%this.tileBOuter===0,this.fitInner=n%this.tileInner===0,this.shaderKey=`conv2DMM_${this.elementsPerThread}_${this.activation}}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.isVec4}_${this.innerElementSize}_${this.isChannelsLast}_${this.sequentialAccessByThreads}`}getUserCode(){let e=this.isVec4?Uh(this.elementsPerThread,this.workgroupSize,!this.isChannelsLast,this.tileInner):Gh(this.elementsPerThread,this.workgroupSize,!this.isChannelsLast,this.tileInner,!1,null,this.sequentialAccessByThreads),t=this.isVec4?[this.innerElementSize,4,4]:[1,1,1];return`
${boe(this.isChannelsLast,this.fitAOuter,this.fitBOuter,this.fitInner,this.addBias,this.activation,this.hasPreluActivationWeights,t[0],t[1],t[2])}
${e}
`}},woe=class{constructor(e,t=!1,a=null,n=!1){this.variableNames=["x","W"],this.uniforms="filterDims: vec2<i32>, pad: vec2<i32>, stride: vec2<i32>, dilation: vec2<i32>,",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=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.addBias=t,this.activation=a,this.hasPreluActivationWeights=n,t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.shaderKey=`conv2dnaive_${this.activation}_${this.isChannelsLast}`}getUserCode(){return`
${Tr(this.activation,this.hasPreluActivationWeights,!1,4)}
fn readInp(batch : i32, row : i32, col : i32, chan : i32) -> f32{
let coords = vec4<i32>(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<i32>(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<i32>(batch, row, col, chan);":"vec4<i32>(batch, chan, row, col);"}
if (coordsInBounds4D(coords, uniforms.outShape)) {
var value = valueIn;
${vo(this.addBias,this.activation)}
setOutputAtCoords(coords.x, coords.y, coords.z, coords.w, value);
}
}
${Ce("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);
}
`}},koe=class{constructor(e,t){this.variableNames=["x"],this.uniforms=`pad : vec2<i32>, stride : vec2<i32>, dilation : vec2<i32>, outWidth : i32, itemsPerBlockRow : i32,
inChannels : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.isChannelsLast=t,this.shaderKey=`im2col_${this.isChannelsLast}`}getUserCode(){let e=this.isChannelsLast?1:2,t=this.isChannelsLast?2:3,a=this.isChannelsLast?"coords[1]":"coords[2]",n=this.isChannelsLast?"coords[2]":"coords[1]",r=this.isChannelsLast?"getX(batch, xRow, xCol, ch)":"getX(batch, ch, xRow, xCol)";return`
${Ce("index")} {
let coords = getCoordsFromIndex(index);
if(index < uniforms.size) {
let batch = coords[0];
let row = ${a};
let col = ${n};
let offsetY = (row / uniforms.outWidth) * uniforms.stride[0] - uniforms.pad[0];
let xRow = offsetY + uniforms.dilation[0] * (col / uniforms.itemsPerBlockRow);
var value = 0.0;
if(xRow < uniforms.xShape[${e}] && xRow >= 0) {
let offsetX = (row % uniforms.outWidth) * uniforms.stride[1] -
uniforms.pad[1];
let xCol = offsetX + uniforms.dilation[1] * ((col %
uniforms.itemsPerBlockRow) / uniforms.inChannels);
let ch = col % uniforms.inChannels;
if(xCol < uniforms.xShape[${t}] && xCol >= 0) {
value = ${r};
}
}
setOutputAtIndex(index, value);
}
}
`}};function Wc(e,t){let a=e.length;return a>=3?t?[...e.slice(0,-3),e[a-3]*e[a-2],e[a-1]]:[...e.slice(0,-3),e[a-3],e[a-2]*e[a-1]]:!t&&a===1&&e[0]>1?[e[0],1]:null}function Ioe({x:e,filter:t,convInfo:a,backend:n,bias:r=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=a.dataFormat==="channelsLast",u=!l,p=!1,c=l&&a.filterHeight===a.inHeight&&a.filterWidth===a.inWidth&&a.padInfo.type==="VALID",d=[],h,f;if(c){let x=a.inHeight*a.inWidth*a.inChannels;h=Ie({inputs:{x:e},backend:n,attrs:{shape:[1,a.batchSize,x]}}),f=Ie({inputs:{x:t},backend:n,attrs:{shape:[1,x,a.outChannels]}})}else h=Ie({inputs:{x:e},backend:n,attrs:{shape:l?[a.batchSize,a.inHeight*a.inWidth,a.inChannels]:[a.batchSize,a.inChannels,a.inHeight*a.inWidth]}}),f=Ie({inputs:{x:t},backend:n,attrs:{shape:[1,a.inChannels,a.outChannels]}});if(d.push(h),d.push(f),s!=null){let x=Wc(s.shape,l);x!=null&&(s=Ie({inputs:{x:s},backend:n,attrs:{shape:x}}),d.push(s))}if(r!=null){let x=Wc(r.shape,l);x!=null&&(r=Ie({inputs:{x:r},backend:n,attrs:{shape:x}}),d.push(r))}let m=Hh({a:l?h:f,b:l?f:h,transposeA:u,transposeB:p,backend:n,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),g=Ie({inputs:{x:m},backend:n,attrs:{shape:a.outShape}});d.push(m);for(let x of d)n.disposeData(x.dataId);return g}function Soe({x:e,filter:t,convInfo:a,backend:n,bias:r=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let{filterWidth:l,filterHeight:u,inChannels:p,strideWidth:c,strideHeight:d,padInfo:h,outWidth:f,outHeight:m,dilationWidth:g,dilationHeight:x,dataFormat:A}=a,y=A==="channelsLast",b=l*u*p,w=m*f,S=y?[a.batchSize,w,b]:[a.batchSize,b,w],C=new koe(S,y),E=[{type:"int32",data:[h.top,h.left]},{type:"int32",data:[d,c]},{type:"int32",data:[x,g]},{type:"int32",data:[f]},{type:"int32",data:[p*l]},{type:"int32",data:[p]}],_=n.runWebGPUProgram(C,[e],e.dtype,E),$=[];$.push(_);let M=Ie({inputs:{x:t},backend:n,attrs:{shape:[1,b,-1]}});if($.push(M),s!=null){let O=Wc(s.shape,y);O!=null&&(s=Ie({inputs:{x:s},backend:n,attrs:{shape:O}}),$.push(s))}if(r!=null){let O=Wc(r.shape,y);O!=null&&(r=Ie({inputs:{x:r},backend:n,attrs:{shape:O}}),$.push(r))}let I=Hh({a:y?_:M,b:y?M:_,transposeA:!y,transposeB:!1,backend:n,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),N=Ie({inputs:{x:I},backend:n,attrs:{shape:a.outShape}});$.push(I);for(let O of $)n.disposeData(O.dataId);return N}function B8({x:e,filter:t,convInfo:a,backend:n,bias:r=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=r!=null,u=s!=null,p=a.dataFormat==="channelsLast",c=p&&a.filterHeight===a.inHeight&&a.filterWidth===a.inWidth&&a.padInfo.type==="VALID",d=W().getBool("WEBGPU_USE_NAIVE_CONV2D_DEBUG");if(!d&&(c||a.filterHeight===1&&a.filterWidth===1&&a.dilationHeight===1&&a.dilationWidth===1&&a.strideHeight===1&&a.strideWidth===1&&(a.padInfo.type==="SAME"||a.padInfo.type==="VALID")))return Ioe({x:e,filter:t,convInfo:a,backend:n,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i});let h=W().getNumber("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL"),f=h>0?h:n.thresholdToIncreaseWorkgroups,m=a.batchSize*Math.ceil(a.outHeight*a.outWidth/32)*Math.ceil(a.outChannels/32);if(W().getBool("WEBGPU_CONV_SEPARATE_IM2COL_SHADER")||m<=f)return Soe({x:e,filter:t,convInfo:a,backend:n,bias:r,preluActivationWeights:s,leakyreluAlpha:i,activation:o});let g,x=[a.padInfo.top,a.padInfo.left],A=[{type:"int32",data:[a.filterHeight,a.filterWidth]},{type:"int32",data:[...x]},{type:"int32",data:[a.strideHeight,a.strideWidth]},{type:"int32",data:[a.dilationHeight,a.dilationWidth]}];if(d)g=new woe(a,l,o,u);else{let S=p?a.outHeight*a.outWidth:a.outChannels,C=p?a.outChannels:a.outHeight*a.outWidth,E=a.filterHeight*a.filterWidth*a.inChannels;A.push({type:"int32",data:[S]},{type:"int32",data:[C]},{type:"int32",data:[E]});let _=n.adapterInfo.isIntel();g=new voe(a,S,C,E,l,o,u,_)}let y=[],b=[e,t];l&&(!p&&r.shape.length===1&&(r=Ie({inputs:{x:r},backend:n,attrs:{shape:[r.shape[0],1,1]}}),y.push(r)),b.push(r)),u&&(!p&&s.shape.length===1&&(s=Ie({inputs:{x:s},backend:n,attrs:{shape:[s.shape[0],1,1]}}),y.push(s)),b.push(s)),o==="leakyrelu"&&(A.push({type:"float32",data:[i]}),g.uniforms+=" alpha : f32,");let w=n.runWebGPUProgram(g,b,e.dtype,A);for(let S of y)n.disposeData(S.dataId);return w}function Toe(e){let{inputs:t,attrs:a,backend:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:p}=a,c=T.convertConv2DDataFormat(l),d=T.computeConv2DInfo(r.shape,s.shape,i,u,o,p,!1,c);return B8({x:r,filter:s,convInfo:d,backend:n})}var Coe={kernelName:ni,backendName:"webgpu",kernelFunc:Toe};function Noe(e=4){let t=n=>{switch(n){case 1:return"return W[getIndexFromCoords4D(coord, uniforms.wShape)];";case 4:return`
let coord1 = vec4<i32>(coordX, coordY, col + 1, rowInner);
let coord2 = vec4<i32>(coordX, coordY, col + 2, rowInner);
let coord3 = vec4<i32>(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<f32>(v0, v1, v2, v3);
`;default:throw new Error(`innerElementSize ${n} is not supported.`)}},a=`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 ${Mt(e)}(0.0);
}
if (xC < 0.0 || xC >= f32(uniforms.outBackprop[2]) || fract(xC) > 0.0) {
return ${Mt(e)}(0.0);
}
let coord = vec4<i32>(
batch,
i32(xR),
i32(xC),
col % uniforms.outBackprop[3]);
return x[getIndexFromCoords4D(coord, uniforms.xShape)/${e}];`}
}
return ${Mt(e)}(0.0);`;return`
fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Mt(e)} {
let col = colIn * ${e};
${a}
}
fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Mt(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<i32>(coordX, coordY, col, rowInner);
${t(e)}
}
return ${Mt(e)}(0.0);
}
fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${Mt(e)}) {
let col = colIn * ${e};
if (row < uniforms.dimAOuter && (col + ${e-1}) < uniforms.dimBOuter) {
var value = valueInput;
let outCoord = vec4<i32>(
batch,
row / uniforms.outShape[2],
row % uniforms.outShape[2],
col);
result[getIndexFromCoords4D(outCoord, uniforms.outShape)/${e}] = value;
}
}`}var Eoe=class{constructor(e){this.variableNames=["x","W"],this.uniforms="filterDims : vec2<i32>, pads : vec2<i32>, stride : vec2<i32>, outBackprop : vec4<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.outputShape=e.inShape,v.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),this.isVec4=e.inChannels%4===0&&e.outChannels%4===0,this.dispatchLayout={x:[3],y:[1,2],z:[0]},this.workgroupSize=F3(this.dispatchLayout,this.outputShape,this.isVec4),this.elementsPerThread=O3(this.dispatchLayout,this.outputShape,this.isVec4),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize,this.elementsPerThread),this.isVec4&&(this.variableTypes=["vec4<f32>","f32"]),this.shaderKey=`conv2DDerInputMM_${this.isVec4}_${this.elementsPerThread}`}getUserCode(){let e=this.isVec4?Uh(this.elementsPerThread,this.workgroupSize):Gh(this.elementsPerThread,this.workgroupSize);return`
${Noe(this.isVec4?4:1)}
${e}
`}},Roe=class{constructor(e){this.variableNames=["dy","W"],this.uniforms="filterDims : vec2<i32>, pads : vec2<i32>, stride : vec2<i32>, outBackprop : vec4<i32>,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(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,a=this.isChannelsLast?3:1;return`
${Ce("index")} {
if(index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let batch = coords[0];
let d1 = coords[${a}];
let dyCorner = vec2<i32>(coords[${e}], coords[${t}]) - uniforms.pads;
let dyRCorner = dyCorner.x;
let dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
var dotProd = 0.0;
for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + 1) {
let dyR = (f32(dyRCorner) + f32(wR)) / f32(uniforms.stride.x);
let wRPerm = uniforms.filterDims.x - 1 - wR;
if (dyR < 0.0 || dyR >= f32(uniforms.outBackprop[1]) || fract(dyR) > 0.0 ||
wRPerm < 0) {
continue;
}
let idyR = 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 Moe(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:p}=n,c=T.convertConv2DDataFormat(u),d=T.computeConv2DInfo(i,s.shape,o,1,l,p,!1,c),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(W().getBool("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE")||d.filterHeight<=2&&d.filterWidth<=2&&d.outChannels<=16&&d.inChannels===1)f=new Roe(d);else{f=new Eoe(d);let m=d.inHeight*d.inWidth,g=d.inChannels,x=d.filterHeight*d.filterWidth*d.outChannels;h.push({type:"uint32",data:[m]},{type:"uint32",data:[g]},{type:"uint32",data:[x]})}return a.runWebGPUProgram(f,[r,s],"float32",h)}var $oe={kernelName:ri,backendName:"webgpu",kernelFunc:Moe},_oe=it({opType:de.COS}),Poe={kernelName:si,backendName:"webgpu",kernelFunc:_oe},Foe=it({opType:de.COSH}),Ooe={kernelName:ii,backendName:"webgpu",kernelFunc:Foe},Doe=class{constructor(e,t,a,n){this.variableNames=["Image","Boxes","BoxInd"],this.uniforms="extrapolationValue : f32,",this.workgroupSize=[64,1,1],this.size=!0;let[r]=t;this.outputShape=[r,a[0],a[1],e],this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.methodId=n==="bilinear"?1:0,this.cropHeightBiggerThan1=this.outputShape[1]>1,this.cropWidthBiggerThan1=this.outputShape[2]>1,this.shaderKey=`cropAndResize_${this.methodId}_${this.cropHeightBiggerThan1}_${this.cropWidthBiggerThan1}`}getUserCode(){let[e,t]=["f32(uniforms.imageShape[1] - 1)","f32(uniforms.imageShape[2] - 1)"],[a,n,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}`],[s,i,o]=this.cropWidthBiggerThan1?[`(${t} / f32(uniforms.outShape[2] - 1))`,"(x2-x1) * width_ratio",`x1*${t} + f32(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${t}`];return`
${Ce("index")} {
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let height_ratio = f32(${a});
let width_ratio = f32(${s});
let b = coords[0];
let y = coords[1];
let x = coords[2];
let d = coords[3];
// get box vals
let y1 = getBoxes(b, 0);
let x1 = getBoxes(b, 1);
let y2 = getBoxes(b, 2);
let x2 = getBoxes(b, 3);
// get image in batch index
let bInd = i32(round(getBoxInd(b)));
if(bInd < 0 || bInd >= uniforms.outShape[0]) {
return;
}
let height_scale = ${n};
let width_scale = ${i};
let in_y = ${r};
if( in_y < 0.0 || in_y > ${e} ) {
setOutputAtIndex(index, uniforms.extrapolationValue);
return;
}
let in_x = ${o};
if( in_x < 0.0 || in_x > ${t} ) {
setOutputAtIndex(index, uniforms.extrapolationValue);
return;
}
let sourceFracIndexCR = vec2<f32>(in_x,in_y);
if(${this.methodId} == 1) {
// Compute the four integer indices.
let sourceFloorCR = vec2<i32>(sourceFracIndexCR);
let sourceCeilCR = vec2<i32>(ceil(sourceFracIndexCR));
let topLeft = getImage(bInd, sourceFloorCR.y, sourceFloorCR.x, d);
let bottomLeft = getImage(bInd, sourceCeilCR.y, sourceFloorCR.x, d);
let topRight = getImage(bInd, sourceFloorCR.y, sourceCeilCR.x, d);
let bottomRight = getImage(bInd, sourceCeilCR.y, sourceCeilCR.x, d);
let fracCR = sourceFracIndexCR - vec2<f32>(sourceFloorCR);
let top = topLeft + (topRight - topLeft) * fracCR.x;
let bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
let newValue = top + (bottom - top) * fracCR.y;
setOutputAtIndex(index, newValue);
} else {
// Compute the coordinators of nearest neighbor point.
let sourceNearestCR = vec2<i32>(floor(
sourceFracIndexCR + vec2<f32>(0.5,0.5)));
let newValue = getImage(
bInd, sourceNearestCR.y, sourceNearestCR.x, d);
setOutputAtIndex(index, newValue);
}
}
}
`}},zoe=e=>{let{inputs:t,backend:a,attrs:n}=e,{image:r,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=n,p=new Doe(r.shape[3],s.shape,o,l),c=[{type:"float32",data:[u]}];return a.runWebGPUProgram(p,[r,s,i],"float32",c)},Loe={kernelName:ui,backendName:"webgpu",kernelFunc:zoe},bd;(function(e){e.Prod="*",e.Sum="+"})(bd||(bd={}));var Zx=class{constructor(e,t,a,n){this.variableNames=["x"],this.uniforms="index : f32,",this.size=!0,this.workgroupSize=[128,1,1],this.outputShape=t,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.exclusive=a,this.reverse=n,this.op=e,this.shaderKey=`cum_${this.op}_${this.exclusive}_${this.reverse}`}getUserCode(){let e=this.outputShape.length,t=this.op===bd.Prod?"1.0":"0.0",a=this.exclusive?t:`getX(${Yx(e,"coords",this.op)})`,n=this.outputShape[this.outputShape.length-1],r="",s="";return this.exclusive?(r=this.reverse?`end != ${n-1}`:"end != 0",s=this.reverse?"end + 1":"end - 1"):(r=this.reverse?`end + pow2 < ${n}`:"end >= pow2",s=this.reverse?"end + pow2":"end - pow2"),`
${Ce("index")} {
if (index < uniforms.size) {
var coords = getCoordsFromIndex(index);
let end = ${Jx(e,"coords",this.op)};
var val = ${a};
let pow2 = i32(pow(2.0, uniforms.index));
if (${r}) {
let idx = ${s};
${Jx(e,"coords",this.op)} = idx;
val ${this.op}= getX(${Yx(e,"coords",this.op)});
}
setOutputAtIndex(index, val);
}
}
`}};function Yx(e,t,a){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 ${a} for rank ${e} is not yet supported`)}function Jx(e,t,a){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 ${a} for rank ${e} is not yet supported`)}function W8(e,t,a,n,r,s){let i=t.shape.length,o=T.getAxesPermutation([n],i),l=t;o!=null&&(l=vr({inputs:{x:t},backend:a,attrs:{perm:o}}));let u=T.getInnerMostAxes(1,i)[0];if(u!==i-1)throw new Error(`WebGPU cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${n}`);let p=l.shape[u],c=Ya({inputs:{x:l},backend:a});for(let d=0;d<=Math.ceil(Math.log2(p))-1;d++){let h=new Zx(e,l.shape,!1,s),f=c,m=[{type:"float32",data:[d]}];c=a.runWebGPUProgram(h,[c],c.dtype,m),a.disposeData(f.dataId)}if(r){let d=new Zx(e,l.shape,r,s),h=c,f=[{type:"float32",data:[0]}];c=a.runWebGPUProgram(d,[c],c.dtype,f),a.disposeData(h.dataId)}if(o!=null){let d=T.getUndoAxesPermutation(o),h=vr({inputs:{x:c},backend:a,attrs:{perm:d}});return a.disposeData(c.dataId),a.disposeData(l.dataId),h}return c}function Boe(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=n;return W8(bd.Prod,r,a,s,i,o)}var Woe={kernelName:oi,backendName:"webgpu",kernelFunc:Boe};function Voe(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=n;return W8(bd.Sum,r,a,s,i,o)}var Uoe={kernelName:li,backendName:"webgpu",kernelFunc:Voe};function Goe(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,weights:s}=t,{size:i,binaryOutput:o}=n,l=r.shape.length===1,u=v.sizeFromShape(s.shape)>0,p=s.dtype,c=l?[r.shape[0]]:[r.shape[0],r.shape[1]],d=l?[i]:[r.shape[0],i],h=Cr({backend:a,attrs:{shape:d,value:0,dtype:p}}),f=new D8(c,u,o),m=[{type:"int32",data:[i]}],g=u?[r,s]:[r];return a.runWebGPUProgram(f,g,p,m,h)}var Hoe={kernelName:Td,backendName:"webgpu",kernelFunc:Goe},joe=class{constructor(e,t){this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.uniforms="blockSize : i32,",this.outputShape=e,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey=`depthToSpace_${t}`,this.dataFormat=t}getUserCode(){return`
${Ce("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 qoe(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{blockSize:s,dataFormat:i}=n,o=r.shape[0],l=i==="NHWC"?r.shape[1]:r.shape[2],u=i==="NHWC"?r.shape[2]:r.shape[3],p=i==="NHWC"?r.shape[3]:r.shape[1],c=l*s,d=u*s,h=p/(s*s),f=i==="NHWC"?[o,c,d,h]:[o,h,c,d],m=[{type:"int32",data:[s]}],g=new joe(f,i);return a.runWebGPUProgram(g,[r],r.dtype,m)}var Xoe={kernelName:di,backendName:"webgpu",kernelFunc:qoe},Koe=class{constructor(e,t,a,n=!1,r=null,s=!1){this.variableNames=["x","W"],this.uniforms="pad : vec2<i32>, inDims : vec2<i32>,",this.workgroupSize=[16,16,1],this.outputShape=e,this.dispatchLayout={x:[3],y:[2],z:[0,1]},this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),n&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.addBias=n,this.activation=r,this.hasPreluActivation=s,this.filterHeight=t,this.filterWidth=a,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],a=this.workgroupSize[1]+this.filterHeight-1,n=this.workgroupSize[0]+this.filterWidth-1;return`
${Tr(this.activation,this.hasPreluActivation,!1,4)}
var<workgroup> mm_Asub : array<array<f32, ${n}>, ${a}>;
var<workgroup> mm_Bsub : array<array<f32, ${this.filterWidth}>, ${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;
}
${Ce()} {
let coords = getOutputCoords();
let batch = coords[0];
let xRCCorner = vec2<i32>(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 < ${a}; inputRow = inputRow + ${this.workgroupSize[1]}) {
for (var inputCol = localCol; inputCol < ${n}; 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 = i32(localIndex);
${e<t?`if (wIndex < ${e})`:`for(; wIndex < ${e}; wIndex = wIndex + ${t})`}
{
let wRow = wIndex / ${this.filterWidth};
let wCol = wIndex % ${this.filterWidth};
mm_Bsub[wRow][wCol] = getW(wRow, wCol, d1, q);
}
workgroupBarrier();
var value = 0.0;
for (var wR = 0; wR < ${this.filterHeight}; wR = wR + 1) {
for (var wC = 0; wC < ${this.filterWidth}; wC = wC + 1) {
let xVal = mm_Asub[localRow + wR][localCol + wC];
let wVal = mm_Bsub[wR][wC];
value = fma(xVal, wVal, value);
}
}
${vo(this.addBias,this.activation)}
if (coordsInBounds4D(coords, uniforms.outShape)) {
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
}
}
`}},V8=class{constructor(e,t=!1,a=null,n=!1){this.variableNames=["x","W"],this.uniforms="pad : vec2<i32>, inDims : vec2<i32>,",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=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize,[4,this.workPerThread,1]),v.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=a,this.hasPreluActivation=n,this.shaderKey=`depthwiseVec4_${a}_${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`
${Tr(this.activation,this.hasPreluActivation,!0,4)}
fn readX(batch : i32, row : i32, col : i32, channel : i32) -> vec4<f32> {
var value = vec4<f32>(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};
${Ce()} {
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<i32>(r, c) * vec2<i32>(strideHeight, strideWidth) - uniforms.pad;
let xRCorner = xRCCorner.x;
let xCCorner = xRCCorner.y;
var xVals : array<vec4<f32>, ${e}>;
var dotProd : array<vec4<f32>, ${this.workPerThread}>;
for (var i = 0; i < ${this.workPerThread}; i++) {
dotProd[i] = vec4<f32>(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<i32>(batch, r, c + i, d1);
if (coordsInBounds4D(coords, uniforms.outShape)) {
var value = dotProd[i];
${vo(this.addBias,this.activation)}
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
}
}
}
`}},U8=class{constructor(e,t=!1,a=null,n=!1){this.variableNames=["x","W"],this.uniforms=`pad : vec2<i32>, inDims : vec2<i32>, filterHeight : i32,
filterWidth : i32, stride : vec2<i32>, dilation : vec2<i32>,`,this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.isChannelsLast=e.dataFormat==="channelsLast",t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=a,this.hasPreluActivation=n,this.shaderKey=`depthwise_${this.activation}_${this.isChannelsLast}`}getUserCode(){let e=this.isChannelsLast?"getX(batch, xR, xC, d1);":"getX(batch, d1, xR, xC);";return`
${Tr(this.activation,this.hasPreluActivation,!1,4)}
${Ce("index")} {
if (index < uniforms.size) {
let coords = getOutputCoords();
let batch = coords[0];
let xRCCorner = vec2<i32>(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;
}
}
}
${vo(this.addBias,this.activation)}
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
}
}
`}};function Zoe(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:p}=n,c=T.convertConv2DDataFormat(l),d=u;d==null&&(d=[1,1]);let h=T.computeConv2DInfo(r.shape,s.shape,i,d,o,p,!0,c),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 Koe(h.outShape,h.filterHeight,h.filterWidth):m&&h.outHeight>4&&h.outWidth>4&&h.strideWidth<=2&&h.inChannels===h.outChannels&&h.dilationHeight===1&&h.dilationWidth===1&&h.inChannels%4===0?g=new V8(h):(g=new U8(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]})),a.runWebGPUProgram(g,[r,s],r.dtype,f)}var Yoe={kernelName:pi,backendName:"webgpu",kernelFunc:Zoe},G8=ua({opType:De.MUL,cpuKernelImpl:Kse,supportsComplex:!0}),Joe={kernelName:zi,backendName:"webgpu",kernelFunc:G8};function V3(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;return ko(r,s,i,"sum",a)}var Qoe={kernelName:ro,backendName:"webgpu",kernelFunc:V3};function ele(e){let{inputs:t,backend:a,attrs:n}=e,{equation:r}=n,s=t,{allDims:i,summedDims:o,idDims:l}=T.decodeEinsumEquation(r,s.length);T.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:p}=T.getEinsumComputePath(o,l),c=p.length,d=null,h=i.length,f=[];for(let m=0;m<c;++m){for(let g of p[m]){let{permutationIndices:x,expandDims:A}=T.getEinsumPermutation(h,l[g]),y;T.isIdentityPermutation(x)?y=s[g]:(y=vr({inputs:{x:s[g]},backend:a,attrs:{perm:x}}),f.push(y));let b=y.shape.slice();for(let w=0;w<A.length;++w)b.splice(A[w],0,1);v.arraysEqual(y.shape,b)||(y=Ie({inputs:{x:y},backend:a,attrs:{shape:b}}),f.push(y)),d===null?d=y:(d=G8({inputs:{a:y,b:d},backend:a}),f.push(d))}m<c-1&&(u[m]>=0&&(d=V3({inputs:{x:d},backend:a,attrs:{axis:u[m]-(i.length-h),keepDims:!1}}),f.push(d)),h--)}for(let m of f)m!==d&&a.disposeData(m.dataId);return d}var tle={kernelName:Cd,backendName:"webgpu",kernelFunc:ele},ale=it({opType:de.ELU}),nle={kernelName:hi,backendName:"webgpu",kernelFunc:ale},rle=ua({opType:De.EQUAL,dtype:"bool",cpuKernelImpl:Fse}),sle={kernelName:fi,backendName:"webgpu",kernelFunc:rle},ile=it({opType:de.ERF}),ole={kernelName:$l,backendName:"webgpu",kernelFunc:ile},H8=it({opType:de.EXP,cpuKernelImpl:Ose,dtype:"float32"}),lle={kernelName:mi,backendName:"webgpu",kernelFunc:H8};function D1(e){let{inputs:t,attrs:a,backend:n}=e,{dim:r}=a,{input:s}=t,i=s.shape.length,o=s.shape.slice(),l=r;return r<0&&(v.assert(-(i+1)<=r,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+r+1),o.splice(l,0,1),Ie({inputs:{x:s},backend:n,attrs:{shape:o}})}var ule={kernelName:_l,backendName:"webgpu",kernelFunc:D1},dle=it({opType:de.EXPM1,cpuKernelImpl:Dse}),ple={kernelName:Pl,backendName:"webgpu",kernelFunc:dle},Qx=class{constructor(e,t){this.variableNames=["real","imag"],this.outputShape=[],this.uniforms="exponentMultiplier : f32, denominator: f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.component=e,this.shaderKey=`fft_${e}`}getUserCode(){return`
fn unaryOpComplex(real: f32, expR: f32, imag: f32, expI: f32) -> f32 {
${this.component==="real"?"return real * expR - imag * expI;":"return real * expI + imag * expR;"}
}
fn mulMatDFT(batch: i32, index: i32) -> f32 {
let indexRatio = f32(index) / f32(uniforms.realShape[1]);
let exponentMultiplierTimesIndexRatio =
uniforms.exponentMultiplier * indexRatio;
var result = 0.0;
for (var i = 0; i < uniforms.realShape[1]; i = i + 1) {
// x = (-2|2 * PI / N) * index * i;
let x = exponentMultiplierTimesIndexRatio * f32(i);
let expR = cos(x);
let expI = sin(x);
let real = getReal(batch, i);
let imag = getImag(batch, i);
result = result +
unaryOpComplex(real, expR, imag, expI) / uniforms.denominator;
}
return result;
}
${Ce("index")} {
if (index < uniforms.size) {
let coords = getOutputCoords();
setOutputAtIndex(index, mulMatDFT(coords[0], coords[1]));
}
}
`}};function j8(e,t,a){let n=a.tensorMap.get(e.dataId),r=v.sizeFromShape(e.shape),s=e.shape[e.shape.length-1],i=r/s,o=[],l=Ie({inputs:{x:e},backend:a,attrs:{shape:[i,s]}});o.push(l);let u=l.shape,p=new Qx("real",u),c=new Qx("imag",u),d=[{dataId:n.complexTensorInfos.real.dataId,dtype:n.complexTensorInfos.real.dtype,shape:u},{dataId:n.complexTensorInfos.imag.dataId,dtype:n.complexTensorInfos.imag.dtype,shape:u}],h=t?2*Math.PI:-2*Math.PI,f=t?u[1]:1,m=[{type:"float32",data:[h]},{type:"float32",data:[f]}],g=a.runWebGPUProgram(p,d,"float32",m);o.push(g);let x=a.runWebGPUProgram(c,d,"float32",m);o.push(x);let A=wo({inputs:{real:g,imag:x},backend:a});o.push(A);let y=Ie({inputs:{x:A},backend:a,attrs:{shape:e.shape}});return o.forEach(b=>a.disposeData(b.dataId)),y}function cle(e){let{inputs:t,backend:a}=e,{input:n}=t;return j8(n,!1,a)}var hle={kernelName:Nd,backendName:"webgpu",kernelFunc:cle},fle=class{constructor(e){this.outputShape=[],this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="flipLeftRight"}getUserCode(){return`
${Ce("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);
}
}
`}},mle={kernelName:gi,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{image:a}=e,n=t,r=new fle(a.shape);return n.runWebGPUProgram(r,[a],a.dtype)}},gle=it({opType:de.FLOOR,cpuKernelImpl:zse}),xle={kernelName:xi,backendName:"webgpu",kernelFunc:gle},Ale=ua({opType:De.INT_DIV,dtype:"int32"}),yle={kernelName:Ai,backendName:"webgpu",kernelFunc:Ale},ble=class{constructor(e,t,a=!1){this.isFromPixels=!0,this.outputShape=[0],this.variableNames=[],this.workgroupSize=[256,1,1],this.outputShape=e,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize,[t,1,1]),this.importVideo=a,this.shaderKey=`fromPixels_${this.importVideo}`}getUserCode(){let e=this.importVideo?"textureLoad(src, vec2<i32>(coords.yx));":"textureLoad(src, vec2<i32>(coords.yx), 0)";return`
@binding(1) @group(0) var src: ${this.importVideo?"texture_external":"texture_2d<f32>"};
${Ce("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]));
}
}
}
`}},vle={kernelName:rd,backendName:"webgpu",kernelFunc:wle},Yo,Wm=W().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU"),cc=new Map;function wle(e){let{inputs:t,backend:a,attrs:n}=e,{pixels:r}=t,{numChannels:s}=n;if(r==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let i=typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement,o=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,[p,c]=i?[r.videoWidth,r.videoHeight]:[r.width,r.height],d=[c,p,s],h=!1,f=i||o;if(u||l||f){let A;if(h){let $=r;if(!cc.has($)||cc.get($).expired){let M={source:$};cc.set($,a.device.importExternalTexture(M))}A={width:p,height:c,format:null,usage:null,texture:cc.get($)}}else{if(f){let N=W().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(Yo==null||N!==Wm)&&(Wm=N,Yo=document.createElement("canvas").getContext("2d",{willReadFrequently:Wm})),Yo.canvas.width=p,Yo.canvas.height=c,Yo.drawImage(r,0,0,p,c),r=Yo.canvas}let $=GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,M="rgba8unorm",I=a.textureManager.acquireTexture(d[1],d[0],M,$);a.queue.copyExternalImageToTexture({source:r},{texture:I},[d[1],d[0]]),A={width:p,height:c,format:M,usage:$,texture:I}}let y=v.sizeFromShape(d),b=v.computeStrides(d),w=new ble(d,s,h),S=[{type:"uint32",data:[y]},{type:"uint32",data:[s]},{type:"uint32",data:[...b]}],C=a.makeTensorInfo([c,p],"int32"),E=a.tensorMap.get(C.dataId);E.resourceInfo=A;let _=a.runWebGPUProgram(w,[C],"int32",S);return a.disposeData(C.dataId),_}let m=r.data,g=m;if(s!=null&&s!==4){g=new Uint8Array(r.width*r.height*s);let A=m.length,y=0;for(let b=0;b<A;b++)b%4<s&&(g[y++]=m[b])}let x=a.makeTensorInfo(d,"int32",new Int32Array(g));return a.uploadToGPU(x.dataId),x}var kle=class{constructor(e,t,a,n,r){this.uniforms="varianceEpsilon : f32,",this.workgroupSize=[128,1,1],this.size=!0,this.variableNames=["x","mean","variance"],T.assertAndGetBroadcastShape(e,t),T.assertAndGetBroadcastShape(e,a),this.outputShape=e,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),n!=null&&(T.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset")),r!=null&&(T.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale")),this.offsetShape=n,this.scaleShape=r,this.shaderKey="batchNorm"}getUserCode(){let e="0.0";this.offsetShape!=null&&(e="getOffsetByOutputIndex(index)");let t="1.0";return this.scaleShape!=null&&(t="getScaleByOutputIndex(index)"),`
${Ce("index")} {
if (index < uniforms.size)
{
let xValue = getXByOutputIndex(index);
let meanValue = getMeanByOutputIndex(index);
let varianValue = getVarianceByOutputIndex(index);
let offsetValue = ${e};
let scaleValue = ${t};
let inv = scaleValue * inverseSqrt(varianValue + f32(uniforms.varianceEpsilon));
setOutputAtIndex(index,dot(vec3<f32>(xValue, -meanValue, offsetValue), vec3<f32>(inv, inv, 1.0)));
}
}
`}},Ile={kernelName:yi,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:a})=>{let{x:n,scale:r,offset:s,mean:i,variance:o}=e,{varianceEpsilon:l}=t,u=a,p=[n,i,o],c=null;s!=null&&(c=s.shape,p.push(s));let d=null;r!=null&&(d=r.shape,p.push(r));let h=new kle(n.shape,i.shape,o.shape,c,d),f=[{type:"float32",data:[l]}];return u.runWebGPUProgram(h,p,n.dtype,f)}};function Sle(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:p,dilations:c,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=n,m=T.convertConv2DDataFormat(p),g=T.computeConv2DInfo(r.shape,s.shape,l,c,u,d,!1,m);return B8({x:r,filter:s,convInfo:g,backend:a,bias:i,preluActivationWeights:o,leakyreluAlpha:f,activation:h})}var Tle={kernelName:qr,backendName:"webgpu",kernelFunc:Sle};function Cle(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:p,dimRoundingMode:c,activation:d,leakyreluAlpha:h}=n,f=p;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,s.shape,l,f,u,c,!0),g=[r,s],x=i!=null,A=o!=null;x&&g.push(i),A&&g.push(o);let y=[{type:"int32",data:[m.padInfo.top,m.padInfo.left]},{type:"int32",data:[m.inHeight,m.inWidth]}],b;return m.outHeight>4&&m.outWidth>4&&m.strideWidth<=2&&m.inChannels===m.outChannels&&m.dilationHeight===1&&m.dilationWidth===1&&m.inChannels%4===0?b=new V8(m,x,d,A):(b=new U8(m,x,d,A),y.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"&&(y.push({type:"float32",data:[h]}),b.uniforms+=" alpha : f32,"),a.runWebGPUProgram(b,g,"float32",y)}var Nle={kernelName:Xr,backendName:"webgpu",kernelFunc:Cle},Ele=class{constructor(e,t){this.variableNames=["A","indices"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey=`gathernd_${e}`,this.sliceDim=e,this.uniforms=`sliceDim : i32, strides : ${ra(e)},`}getUserCode(){let e;return this.sliceDim>1?e="uniforms.strides[j]":e="uniforms.strides",`
${Ce("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 Rle(e){let{inputs:t,backend:a}=e,{params:n,indices:r}=t,s=r.shape,i=s[s.length-1],o=v.sizeFromShape(n.shape),[l,u,p,c]=T.prepareAndValidate(n,r),d=Ie({inputs:{x:r},backend:a,attrs:{shape:[u,i]}}),h=Ie({inputs:{x:n},backend:a,attrs:{shape:[v.sizeFromShape(n.shape)/p,p]}});if(a.shouldExecuteOnCPU([n,r])||n.dtype==="string"){let A=a.readSync(r.dataId),y=a.bufferSync(n),b=Lse(A,y,n.dtype,u,i,p,c,n.shape,o);return a.makeTensorInfo(l,n.dtype,b.values)}let f=new Ele(i,[u,p]),m=[{type:"int32",data:[i]},{type:"int32",data:c}],g=a.runWebGPUProgram(f,[h,d],h.dtype,m),x=Ie({inputs:{x:g},backend:a,attrs:{shape:l}});return a.disposeData(d.dataId),a.disposeData(h.dataId),a.disposeData(g.dataId),x}var Mle={kernelName:bi,backendName:"webgpu",kernelFunc:Rle},$le=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=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="gather"}getUserCode(){let e=_le(this.aShape);return`
${Ce("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 _le(e){let t=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[];for(let n=0;n<e.length;n++)n===2?a.push("indexZ"):a.push(`${t[n]}`);return a.join()}function q8(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,indices:s}=t,{axis:i,batchDims:o}=n,l=v.parseAxisParam(i,r.shape)[0],u=T.segment_util.collectGatherOpShapeInfo(r,s,l,o),p=v.sizeFromShape(s.shape),c=[],d=Ie({inputs:{x:r},backend:a,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),h=Ie({inputs:{x:s},backend:a,attrs:{shape:[u.batchSize,p/u.batchSize]}});c.push(d),c.push(h);let f=[u.batchSize,u.outerSize,p/u.batchSize,u.sliceSize];if(a.shouldExecuteOnCPU([r,s])){let A=a.tensorMap.get(h.dataId).values,y=Me(h.shape,h.dtype,A),b=a.tensorMap.get(d.dataId).values,w=Me(d.shape,d.dtype,b),S=Bse(w,y,f);return c.forEach(C=>a.disposeData(C.dataId)),a.makeTensorInfo(u.outputShape,S.dtype,S.values)}let m=new $le(d.shape,f),g=a.runWebGPUProgram(m,[d,h],d.dtype);c.push(g);let x=Ie({inputs:{x:g},backend:a,attrs:{shape:u.outputShape}});return c.forEach(A=>a.disposeData(A.dataId)),x}var Ple={kernelName:Ol,backendName:"webgpu",kernelFunc:q8},Fle=ua({opType:De.GREATER,cpuKernelImpl:Vse,dtype:"bool"}),Ole={kernelName:vi,backendName:"webgpu",kernelFunc:Fle},Dle=ua({opType:De.GREATER_EQUAL,dtype:"bool",cpuKernelImpl:Wse}),zle={kernelName:wi,backendName:"webgpu",kernelFunc:Dle};function Lle(e){let{inputs:t,backend:a}=e,{input:n}=t;return j8(n,!0,a)}var Ble={kernelName:Ed,backendName:"webgpu",kernelFunc:Lle},Wle=it({opType:de.IS_FINITE,dtype:"bool"}),Vle={kernelName:Dl,backendName:"webgpu",kernelFunc:Wle},Ule=it({opType:de.IS_INF,dtype:"bool"}),Gle={kernelName:zl,backendName:"webgpu",kernelFunc:Ule},Hle=it({opType:de.IS_NAN,dtype:"bool"}),jle={kernelName:Ii,backendName:"webgpu",kernelFunc:Hle};function qle(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{alpha:s}=n,i=[{type:"float32",data:[s]}],o=new mp(r.shape,de.LEAKYRELU);return o.uniforms="alpha : f32,",a.runWebGPUProgram(o,[r],"float32",i)}var Xle={kernelName:Si,backendName:"webgpu",kernelFunc:qle},Kle=ua({opType:De.LESS,dtype:"bool",cpuKernelImpl:Gse}),Zle={kernelName:Ti,backendName:"webgpu",kernelFunc:Kle},Yle=ua({opType:De.LESS_EQUAL,dtype:"bool",cpuKernelImpl:Use}),Jle={kernelName:Ci,backendName:"webgpu",kernelFunc:Yle},Qle=it({opType:de.LOG,cpuKernelImpl:Hse}),eue={kernelName:Ni,backendName:"webgpu",kernelFunc:Qle},tue=it({opType:de.LOG1P}),aue={kernelName:Ll,backendName:"webgpu",kernelFunc:tue},nue=ua({opType:De.LOGICAL_AND,dtype:"bool"}),rue={kernelName:Ei,backendName:"webgpu",kernelFunc:nue},sue=it({opType:de.LOGICAL_NOT}),iue={kernelName:Ri,backendName:"webgpu",kernelFunc:sue},oue=ua({opType:De.MAX,cpuKernelImpl:qse}),lue={kernelName:$i,backendName:"webgpu",kernelFunc:oue};function uue(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1,p=T.computePool2DInfo(r.shape,s,i,u,o,l);return O8(r,p,"max",a)}var due={kernelName:_i,backendName:"webgpu",kernelFunc:uue};function pue(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;return ko(r,s,i,"min",a)}var cue={kernelName:Fi,backendName:"webgpu",kernelFunc:pue},hue=ua({opType:De.MIN,cpuKernelImpl:Xse}),fue={kernelName:Oi,backendName:"webgpu",kernelFunc:hue},mue=class{constructor(e,t,a){this.uniforms="",this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((n,r)=>n[0]+e[r]+n[1]),this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.xShape=e,t.map((n,r)=>{this.uniforms+=` pad${r} : vec2<i32>,`}),this.offset=a==="reflect"?0:1,this.shaderKey=`mirrorPad_${a}`}getUserCode(){let e=this.xShape.length,t=this.xShape.map((l,u)=>`uniforms.pad${u}[0]`).join(","),a=this.xShape.map((l,u)=>`uniforms.pad${u}[0] + uniforms.xShape${e>1?`[${u}]`:""}`).join(","),n=e===1?"start":"start[i]",r=e===1?"end":"end[i]",s=e===1?"outC":"outC[i]",i=ra(e),o=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return`
${Ce("index")} {
if (index < uniforms.size) {
let start = ${i}(${t});
let end = ${i}(${a});
var outC = getCoordsFromIndex(index);
for (var i = 0; i < ${e}; i = i + 1) {
if (${s} < ${n}) {
${s} = ${n} * 2 - ${s} - ${this.offset};
} else if(${s} >= ${r}) {
${s} = (${r} - 1) * 2 - ${s} + ${this.offset};
}
}
let coords = outC - start;
setOutputAtIndex(index, getX(${o}));
}
}
`}},gue={kernelName:Di,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:a})=>{let{x:n}=e,{paddings:r,mode:s}=t,i=a,o=r.map(u=>({type:"int32",data:[u[0],u[1]]})),l=new mue(n.shape,r,s);return i.runWebGPUProgram(l,[n],n.dtype,o)}},xue=ua({opType:De.MOD}),Aue={kernelName:Wl,backendName:"webgpu",kernelFunc:xue};function yue(e){let{inputs:t,backend:a}=e,{x:n}=t;if(a.shouldExecuteOnCPU([n])){let s=a.tensorMap.get(n.dataId),[i,o]=Zse(s.values,n.shape,n.dtype);return a.makeTensorInfo(o,n.dtype,i)}let r=new mp(n.shape,de.NEG);return a.runWebGPUProgram(r,[n],n.dtype)}var bue={kernelName:Vl,backendName:"webgpu",kernelFunc:yue};function vue(e){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:a,attrs:n}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=n,u=a.readSync(r.dataId),p=a.readSync(s.dataId),{selectedIndices:c}=Tn.nonMaxSuppressionV3Impl(u,p,i,o,l);return a.makeTensorInfo([c.length],"int32",new Int32Array(c))}var wue={kernelName:Bi,backendName:"webgpu",kernelFunc:vue};function kue(e){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:a,attrs:n}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=n,p=a.readSync(r.dataId),c=a.readSync(s.dataId),d=i,h=o,f=l,m=u,{selectedIndices:g,selectedScores:x}=Tn.nonMaxSuppressionV5Impl(p,c,d,h,f,m);return[a.makeTensorInfo([g.length],"int32",new Int32Array(g)),a.makeTensorInfo([x.length],"float32",new Float32Array(x))]}var Iue={kernelName:Wi,backendName:"webgpu",kernelFunc:kue},Sue=class{constructor(e,t){this.variableNames=["x"],this.uniforms="onValue : f32, offValue : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e,t],this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="onehot"}getUserCode(){return`
${Ce("index")} {
if(index < uniforms.size) {
let coords = getCoordsFromIndex(index);
setOutputAtIndex(index, mix(uniforms.offValue, uniforms.onValue,
f32(i32(round(getX(coords.x))) == coords.y)));
}
}
`}};function Tue(e){let{inputs:t,backend:a,attrs:n}=e,{indices:r}=t,{dtype:s,depth:i,onValue:o,offValue:l}=n,u=v.sizeFromShape(r.shape),p=new Sue(u,i),c=Ie({inputs:{x:r},backend:a,attrs:{shape:[u]}}),d=[{type:"float32",data:[o]},{type:"float32",data:[l]}],h=a.runWebGPUProgram(p,[c],s,d);a.disposeData(c.dataId);let f=[...r.shape,i],m=Ie({inputs:{x:h},backend:a,attrs:{shape:f}});return a.disposeData(h.dataId),m}var Cue={kernelName:Vi,backendName:"webgpu",kernelFunc:Tue};function Vc(e){let{inputs:t,backend:a}=e,{x:n}=t;if(n.dtype==="complex64"){let r=gp({inputs:{input:n},backend:a}),s=Vc({inputs:{x:r},backend:a}),i=jh({inputs:{input:n},backend:a}),o=Vc({inputs:{x:i},backend:a}),l=wo({inputs:{real:s,imag:o},backend:a});return a.disposeData(r.dataId),a.disposeData(s.dataId),a.disposeData(i.dataId),a.disposeData(o.dataId),l}else return Cr({attrs:{shape:n.shape,dtype:n.dtype,value:n.dtype==="string"?"":0},backend:a})}var Nue={kernelName:nu,backendName:"webgpu",kernelFunc:Vc};function X8(e){let{inputs:t,backend:a}=e,{x:n}=t;if(n.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(n.dtype==="complex64"){let r=gp({inputs:{input:n},backend:a}),s=X8({inputs:{x:r},backend:a}),i=jh({inputs:{input:n},backend:a}),o=Vc({inputs:{x:i},backend:a}),l=wo({inputs:{real:s,imag:o},backend:a});return a.disposeData(r.dataId),a.disposeData(s.dataId),a.disposeData(i.dataId),a.disposeData(o.dataId),l}else return Cr({attrs:{shape:n.shape,dtype:n.dtype,value:1},backend:a})}var Eue={kernelName:Gl,backendName:"webgpu",kernelFunc:X8};function Rue(e){let{inputs:t,backend:a,attrs:n}=e,{axis:r}=n;if(t.length===1)return D1({inputs:{input:t[0]},backend:a,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(p=>{v.assertShapesMatch(s,p.shape,"All tensors passed to stack must have matching shapes"),v.assert(i===p.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(p=>{let c=D1({inputs:{input:p},backend:a,attrs:{dim:r}});return o.push(c),c}),u=L8({inputs:l,backend:a,attrs:{axis:r}});return o.forEach(p=>a.disposeData(p.dataId)),u}var Mue={kernelName:Hl,backendName:"webgpu",kernelFunc:Rue},$ue=class{constructor(e,t){this.variableNames=["x"],this.uniforms="constantValue : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((a,n)=>a[0]+e[n]+a[1]),this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),t.map((a,n)=>{this.uniforms+=` pad${n} : vec2<i32>,`}),this.xShape=e,this.shaderKey="pad"}getUserCode(){let e=this.xShape.length,t=ra(e),a=this.xShape.map((u,p)=>`uniforms.pad${p}[0]`).join(","),n=this.xShape.map((u,p)=>`uniforms.pad${p}[0] + uniforms.xShape${e>1?`[${p}]`:""}`).join(","),r=e>1?`${t}(${a})`:`${a}`,s=e>1?`${t}(${n})`:`${n}`,i=e>1?"any(outC < start)":"outC < start",o=e>1?"any(outC >= end)":"outC >= end",l=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return`
${Ce("index")} {
if (index < uniforms.size) {
let start = ${r};
let end = ${s};
let outC = getCoordsFromIndex(index);
if (${i} || ${o}) {
setOutputAtIndex(index, uniforms.constantValue);
} else {
let coords = outC - start;
setOutputAtIndex(index, getX(${l}));
}
}
}
`}},K8=e=>{let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{paddings:s,constantValue:i}=n;if(s.every(u=>v.arraysEqual(u,[0,0])))return Ya({inputs:{x:r},backend:a});if(v.sizeFromShape(r.shape)===0){let u=s.map((p,c)=>p[0]+r.shape[c]+p[1]);return Cr({backend:a,attrs:{shape:u,value:i,dtype:r.dtype}})}let o=[{type:"float32",data:[i]}];s.map(u=>o.push({type:"int32",data:[u[0],u[1]]}));let l=new $ue(r.shape,s);return a.runWebGPUProgram(l,[r],r.dtype,o)},_ue={kernelName:Ui,backendName:"webgpu",kernelFunc:K8},Pue=ua({opType:De.POW}),Fue={kernelName:Gi,backendName:"webgpu",kernelFunc:Pue};function Oue(e){let{inputs:t,backend:a}=e,{x:n,alpha:r}=t,s=new P1(De.PRELU,n.shape,r.shape);return a.runWebGPUProgram(s,[n,r],"float32")}var Due={kernelName:Hi,backendName:"webgpu",kernelFunc:Oue};function zue(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;return ko(r,s,i,"prod",a)}var Lue={kernelName:ji,backendName:"webgpu",kernelFunc:zue},Bue=e=>{let{backend:t,attrs:a}=e,{start:n,stop:r,step:s,dtype:i}=a,o=Qse(n,r,s,i);return t.makeTensorInfo([o.length],i,o)},Wue={kernelName:jl,backendName:"webgpu",kernelFunc:Bue},Z8=ua({opType:De.DIV}),Vue={kernelName:ci,backendName:"webgpu",kernelFunc:Z8},Uue=it({opType:de.RECIPROCAL}),Gue={kernelName:qi,backendName:"webgpu",kernelFunc:Uue},Hue=it({opType:de.RELU}),jue={kernelName:Xi,backendName:"webgpu",kernelFunc:Hue},que=it({opType:de.RELU6}),Xue={kernelName:Yi,backendName:"webgpu",kernelFunc:que},Kue=class{constructor(e,t,a){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2<f32>, halfPixelCenters : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,a,e[3]],this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="resizeBilinear"}getUserCode(){return`
${Ce("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>(
f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0],
f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]);
let effectiveOutSize = vec2<f32>(
f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0],
f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]);
let effectiveInputOverOutputRatioRC =
effectiveInSize / effectiveOutSize;
// Fractional source index
let sourceFracIndexRC =
(vec2<f32>(rc) + vec2<f32>(uniforms.halfPixelCenters)) *
effectiveInputOverOutputRatioRC - vec2<f32>(uniforms.halfPixelCenters);
// Compute the four integer indices.
let sourceFloorRC = vec2<i32>(sourceFracIndexRC);
let sourceCeilRC = vec2<i32>(
min(vec2<f32>(uniforms.xShape.yz) - vec2<f32>(1.0), ceil(sourceFracIndexRC)));
let topLeft = getX(b, sourceFloorRC.x, sourceFloorRC.y, d);
let bottomLeft = getX(b, sourceCeilRC.x, sourceFloorRC.y, d);
let topRight = getX(b, sourceFloorRC.x, sourceCeilRC.y, d);
let bottomRight = getX(b, sourceCeilRC.x, sourceCeilRC.y, d);
let fracRC = sourceFracIndexRC - vec2<f32>(sourceFloorRC);
let top = topLeft + (topRight - topLeft) * fracRC.y;
let bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
let newValue = top + (bottom - top) * fracRC.x;
setOutputAtIndex(index, newValue);
}
}
`}};function Zue(e){let{inputs:t,backend:a,attrs:n}=e,{images:r}=t,{alignCorners:s,size:i,halfPixelCenters:o}=n,[l,u]=i,p=s&&l>1?1:0,c=s&&u>1?1:0,d=[{type:"float32",data:[p,c]},{type:"float32",data:[o?.5:0]}],h=new Kue(r.shape,l,u);return a.runWebGPUProgram(h,[r],"float32",d)}var Yue={kernelName:Zi,backendName:"webgpu",kernelFunc:Zue},Jue=class{constructor(e,t,a,n){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2<f32>, roundBase : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,a,e[3]],this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.halfPixelCenters=n,this.shaderKey=`resizeNearest_${n}`}getUserCode(){let e;return this.halfPixelCenters?e="max((vec2<f32>(rc) + vec2<f32>(0.5)) * effectiveInputOverOutputRatioRC, vec2<f32>(0.0))":e="vec2<f32>(rc) * effectiveInputOverOutputRatioRC",`
${Ce("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>(
f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0],
f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]);
let effectiveOutSize = vec2<f32>(
f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0],
f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]);
let effectiveInputOverOutputRatioRC =
effectiveInSize / effectiveOutSize;
// Fractional source index
let sourceFracIndexRC = ${e};
// Compute the coordinators of nearest neighbor point.
let inputShapeRC = vec2<f32>(f32(uniforms.xShape.y), f32(uniforms.xShape.z));
let sourceNearestRC = vec2<i32>(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + uniforms.roundBase)));
let newValue = getX(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutputAtIndex(index, newValue);
}
}
`}};function Que(e){let{inputs:t,backend:a,attrs:n}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,p=s&&l>1?1:0,c=s&&u>1?1:0,d=[{type:"float32",data:[p,c]},{type:"float32",data:[s?.5:0]}],h=new Jue(r.shape,l,u,i);return a.runWebGPUProgram(h,[r],r.dtype,d)}var ede={kernelName:Ki,backendName:"webgpu",kernelFunc:Que},tde=class{constructor(e){this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms=" axis : vec4<i32>,",this.shaderKey="reverse"}getUserCode(){return`
// Using uniform variables as judging conditions, so the function has
// coherent execution within all threads.
fn getReverseCoords(coords : vec4<i32>) -> vec4<i32> {
var reverseCoords = coords;
if (uniforms.axis[0] == 1) {
reverseCoords[0] = uniforms.xShape[0] - coords[0] - 1;
}
if (uniforms.axis[1] == 1) {
reverseCoords[1] = uniforms.xShape[1] - coords[1] - 1;
}
if (uniforms.axis[2] == 1) {
reverseCoords[2] = uniforms.xShape[2] - coords[2] - 1;
}
if (uniforms.axis[3] == 1) {
reverseCoords[3] = uniforms.xShape[3] - coords[3] - 1;
}
return reverseCoords;
}
${Ce("index")} {
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let reverseCoords = getReverseCoords(coords);
setOutputAtIndex(index, getX(reverseCoords[0],
reverseCoords[1], reverseCoords[2], reverseCoords[3]));
}
}
`}};function ade(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{dims:s}=n,i=r.shape.length;if(i===0)return Ya({inputs:{x:r},backend:a});let o=r.shape,l=[1,1,1,1];o.forEach((g,x)=>{let A=x+4-i;l[A]=g});let u=v.parseAxisParam(s,r.shape),p=[0,0,0,0];u.forEach(g=>{let x=g+4-i;p[x]=1});let c=[{type:"int32",data:p}],d=Ie({inputs:{x:r},backend:a,attrs:{shape:l}}),h=new tde(l),f=a.runWebGPUProgram(h,[d],d.dtype,c);a.disposeData(d.dataId);let m=Ie({inputs:{x:f},backend:a,attrs:{shape:o}});return a.disposeData(f.dataId),m}var nde={kernelName:Ji,backendName:"webgpu",kernelFunc:ade},rde=class{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms=`centerX : f32, centerY : f32, sinRadians : f32,
cosRadians : f32,`,this.shaderKey="rotate",this.outputShape=e,typeof t=="number"?(this.uniforms+=" fillValue : f32,",this.fillSnippet="var outputValue = uniforms.fillValue;",this.shaderKey+="_float"):(this.uniforms+=" fillValue : vec3<f32>,",this.fillSnippet="var outputValue = uniforms.fillValue[coords[3]];",this.shaderKey+="_vec3")}getUserCode(){return`
${Ce("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);
}
}
`}},sde={kernelName:mo,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:a})=>{let{image:n}=e,{radians:r,fillValue:s,center:i}=t,o=a,l=new rde(n.shape,s),[u,p]=T.getImageCenter(i,n.shape[1],n.shape[2]),c=[{type:"float32",data:[u]},{type:"float32",data:[p]},{type:"float32",data:[Math.sin(r)]},{type:"float32",data:[Math.cos(r)]}];return typeof s=="number"?c.push({type:"float32",data:[Number.parseFloat(s.toFixed(2))]}):c.push({type:"float32",data:s}),o.runWebGPUProgram(l,[n],n.dtype,c)}},ide=it({opType:de.RSQRT,cpuKernelImpl:eie}),ode={kernelName:Qi,backendName:"webgpu",kernelFunc:ide},vc=class{constructor(e,t,a,n,r,s,i,o=!0){this.variableNames=["updates","indices"],this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=s,this.type=i,this.sumDupeIndices=o,this.dispatchLayout=Ve(e),this.dispatch=Ne(this.dispatchLayout,e,this.workgroupSize),this.sliceDimGreaterThanOne=t>1,this.shaderKey=`scatter_${a}_${n}_${this.sliceDimGreaterThanOne}_${i}_${o}`;let l=ra(r.length);this.uniforms=`sliceDim : i32, strides: ${l}, updatesSize: i32,`,this.updatesRank=n,this.indicesRank=a}getUserCode(){let e="";this.indicesRank===1?e="coords[0]":this.indicesRank===2&&(e="coords[0], j");let t=`getIndices(${e})`,a=this.sliceDimGreaterThanOne?"uniforms.strides[j]":"uniforms.strides",n="",r="";this.dispatchLayout.x.length===1?(n="flattenedIndex",r=`
fn getUpdatesCoordsFromFlatIndex(index : i32) -> i32 {
return index;
}
`):this.dispatchLayout.x.length===2&&(n="vec2<i32>(flattenedIndex, coords[1])",r=`
fn getUpdatesCoordsFromFlatIndex(index : i32) -> vec2<i32> {
// 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<i32>(d0, d1);
}
`);let s=`getUpdates(${Array.from({length:this.updatesRank},(o,l)=>`coords[${l}]`).join(", ")})`,i=(o,l)=>{let u=`atomicAdd(${o}, bitcast<i32>(${l}))`;this.type==="float32"&&(u=`
{
var oldBits = 0;
var newBits = bitcast<i32>(${l});
loop {
let info = atomicCompareExchangeWeak(${o}, oldBits, newBits);
if (info.exchanged) {
break;
}
oldBits = info.old_value;
let oldValue = bitcast<f32>(oldBits);
let newValue = oldValue + (${l});
newBits = bitcast<i32>(newValue);
}
}
`);let p=`atomicStore(${o}, bitcast<i32>(${l}));`;return this.sumDupeIndices?u:p};return`
${r}
${Ce("index")} {
if (index < uniforms.updatesSize) {
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 * ${a};
}
let updateValue =
${ad(this.type,!1)}(${s});
let flatIndex = getOutputIndexFromCoords(${n});
${i("&result[flatIndex]","updateValue")};
}
}`}};function lde(e){let{inputs:t,backend:a,attrs:n}=e,{indices:r,updates:s}=t,{shape:i}=n,{sliceRank:o,numUpdates:l,sliceSize:u,strides:p,outputSize:c}=T.calculateShapes(s,r,i),d=[c/u,u];if(c===0)return a.makeTensorInfo(i,r.dtype);let h=Ie({inputs:{x:r},backend:a,attrs:{shape:[l,o]}}),f=Ie({inputs:{x:s},backend:a,attrs:{shape:[l,u]}}),m=f.dtype,g=Cr({backend:a,attrs:{shape:d,value:0,dtype:m}}),x=v.sizeFromShape(f.shape),A=[{type:"int32",data:[o]},{type:"int32",data:p},{type:"int32",data:[x]}],y=new vc(f.shape,o,h.shape.length,f.shape.length,p,d,m),b=a.runWebGPUProgram(y,[f,h],m,A,g),w=Ie({inputs:{x:b},backend:a,attrs:{shape:i}});return a.disposeData(h.dataId),a.disposeData(f.dataId),a.disposeData(b.dataId),w}var ude={kernelName:eo,backendName:"webgpu",kernelFunc:lde},dde=class{constructor(e,t){this.outputShape=[],this.variableNames=["sortedSequence","values"],this.uniforms="numInputs : i32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.side=t,this.shaderKey=`search_sorted_${t}`}getUserCode(){return`
fn findBound(batch: i32, value: f32) -> i32 {
var left = i32(0);
var right = uniforms.numInputs;
while (left < right) {
var mid = (left + right) / 2;
if (getSortedSequence(batch, mid) ${this.side==="left"?"<":"<="} value) {
left = mid + 1;
} else {
right = mid;
}
}
return right;
}
${Ce("index")} {
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
let value = getValuesByOutputIndex(index);
setOutputAtIndexI32(index, findBound(coords[0], value));
}
}
`}};function pde(e){let{inputs:t,backend:a,attrs:n}=e,{sortedSequence:r,values:s}=t,{side:i}=n,o=new dde([s.shape[0],s.shape[1]],i),l=[{type:"int32",data:[r.shape[1]]}];return a.runWebGPUProgram(o,[r,s],"int32",l)}var cde={kernelName:$d,backendName:"webgpu",kernelFunc:pde},hde=class{constructor(e,t,a){this.variableNames=["c","a","b"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.cRank=e,this.rank=a,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 a=["resRC.x","resRC.y","resRC.z","resRC.w"],n=[],r=[];for(let s=0;s<this.outputShape.length;s++)r.push(`${a[s]}`),s<this.cRank&&n.push(`${a[s]}`);e=n.join(),t=r.join()}return`
${Ce("index")} {
if (index < uniforms.size) {
let resRC = getCoordsFromIndex(index);
let cVal = getC(${e});
if (cVal >= 1.0) {
setOutputAtIndex(index, getA(${t}));
} else {
setOutputAtIndex(index, getB(${t}));
}
}
}
`}};function fde(e){let{inputs:t,backend:a}=e,{condition:n,t:r,e:s}=t,i=new hde(n.shape.length,r.shape,r.shape.length);return a.runWebGPUProgram(i,[n,r,s],ca(r.dtype,s.dtype))}var mde={kernelName:Kl,backendName:"webgpu",kernelFunc:fde},gde=it({opType:de.SIGMOID}),xde={kernelName:ao,backendName:"webgpu",kernelFunc:gde},Ade=it({opType:de.SIN}),yde={kernelName:to,backendName:"webgpu",kernelFunc:Ade},bde=it({opType:de.SINH}),vde={kernelName:Yl,backendName:"webgpu",kernelFunc:bde},Y8=ua({opType:De.SUB,cpuKernelImpl:iie,supportsComplex:!0}),wde={kernelName:lo,backendName:"webgpu",kernelFunc:Y8};function kde(e){let{inputs:t,backend:a,attrs:n}=e,{logits:r}=t,{dim:s}=n,i=v.parseAxisParam([s],r.shape),o=W3({inputs:{x:r},backend:a,attrs:{reductionIndices:i,keepDims:!1}}),l=T.expandShapeToKeepDim(o.shape,i),u=Ie({inputs:{x:o},backend:a,attrs:{shape:l}}),p=Y8({inputs:{a:r,b:u},backend:a}),c=H8({inputs:{x:p},backend:a}),d=V3({inputs:{x:c},backend:a,attrs:{axis:i,keepDims:!1}}),h=Ie({inputs:{x:d},backend:a,attrs:{shape:l}}),f=Z8({inputs:{a:c,b:h},backend:a});return a.disposeData(o.dataId),a.disposeData(u.dataId),a.disposeData(p.dataId),a.disposeData(c.dataId),a.disposeData(d.dataId),a.disposeData(h.dataId),f}var Ide={kernelName:so,backendName:"webgpu",kernelFunc:kde},Sde=e=>{let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{blockShape:s,paddings:i}=n;v.assert(r.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGPU backend not implemented yet");let o=s.reduce((x,A)=>x*A),l=[[0,0]];l.push(...i);for(let x=1+s.length;x<r.shape.length;++x)l.push([0,0]);let u=[],p=K8({inputs:{x:r},backend:a,attrs:{paddings:l,constantValue:0}}),c=T.getReshaped(p.shape,s,o,!1),d=T.getPermuted(c.length,s.length,!1),h=T.getReshapedPermuted(p.shape,s,o,!1),f=Ie({inputs:{x:p},backend:a,attrs:{shape:c}}),m=vr({inputs:{x:f},backend:a,attrs:{perm:d}}),g=Ie({inputs:{x:m},backend:a,attrs:{shape:h}});return u.push(p),u.push(f),u.push(m),u.forEach(x=>a.disposeData(x.dataId)),g},Tde={kernelName:Jl,backendName:"webgpu",kernelFunc:Sde},Cde=class{constructor(e,t){this.variableNames=["A"],this.workgroupSize=[64,1,1],this.size=!0;let a=new Array(e.length);for(let n=0;n<a.length;n++)a[n]=e[n]*t[n];this.outputShape=a,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.rank=this.outputShape.length,this.shaderKey="tile"}getUserCode(){let e=Nde(this.rank,"uniforms.");return`
${Ce("index")} {
if (index < uniforms.size) {
let resRC = getCoordsFromIndex(index);
setOutputAtIndex(index, getA(${e}));
}
}
`}};function Nde(e,t=""){if(e>=5)throw Error(`Tile for rank ${e} is not yet supported`);if(e===1)return`(resRC % ${t}aShape)`;let a=["resRC.x","resRC.y","resRC.z","resRC.w"],n=[];for(let r=0;r<e;r++)n.push(`(${a[r]} % ${t}aShape[${r}])`);return n.join()}function J8(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{reps:s}=n;if(a.shouldExecuteOnCPU([r])||r.dtype==="string"||r.shape.length>=5){let o=a.readSync(r.dataId),l=r.dtype==="string"?o.map(c=>v.decodeString(c)):o,u=Me(r.shape,r.dtype,l),p=oie(u,s);return a.makeTensorInfo(p.shape,p.dtype,p.values)}let i=new Cde(r.shape,s);return a.runWebGPUProgram(i,[r],r.dtype)}var Ede={kernelName:ns,backendName:"webgpu",kernelFunc:J8};function Rde(e){let{inputs:t,backend:a,attrs:n}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=n,{sliceRank:l,numUpdates:u,sliceSize:p,strides:c,outputSize:d}=T.calculateShapes(s,r,o),h=!1;if(s.dtype==="string"){let E=a.bufferSync(r),_=a.bufferSync(s),$=v.decodeString(a.readSync(i.dataId)[0]),M=tie(E,_,o,d,p,u,l,c,$,h);return a.makeTensorInfo(o,M.dtype,M.values)}let f=[d/p,p],m=Ie({inputs:{x:r},backend:a,attrs:{shape:[u,l]}}),g=s.shape.length?Ie({inputs:{x:s},backend:a,attrs:{shape:[u,p]}}):Ya({inputs:{x:s},backend:a}),x=g.dtype,A=a.makeTensorInfo([],x,v.makeZerosTypedArray(1,x)),y=Ie({inputs:{x:i},backend:a,attrs:{shape:Array(f.length).fill(1)}}),b=J8({inputs:{x:y},backend:a,attrs:{reps:f}}),w=v.sizeFromShape([u,p]),S=[{type:"int32",data:[l]},{type:"int32",data:c},{type:"int32",data:[w]}];switch(u){case 0:break;case 1:{let E=new vc([u,p],l,m.shape.length,g.shape.length,c,f,x,h);a.runWebGPUProgram(E,[g,m],x,S,b)}break;default:{let E=new vc([u,p],l,m.shape.length,A.shape.length,c,f,x,h);a.runWebGPUProgram(E,[A,m],x,S,b)}{let E=new vc([u,p],l,m.shape.length,g.shape.length,c,f,x);a.runWebGPUProgram(E,[g,m],x,S,b)}}let C=Ie({inputs:{x:b},backend:a,attrs:{shape:o}});return a.disposeData(m.dataId),a.disposeData(g.dataId),a.disposeData(y.dataId),a.disposeData(A.dataId),a.disposeData(b.dataId),C}var Mde={kernelName:Ld,backendName:"webgpu",kernelFunc:Rde};function $de(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=n,o=v.parseAxisParam(i,r.shape)[0],l=T.prepareSplitSize(r,s,o),u=r.shape.length,p=new Array(u).fill(0),c=r.shape.slice();return l.map(d=>{let h=[...c];h[o]=d;let f=Au({inputs:{x:r},backend:a,attrs:{begin:p,size:h}});return p[o]+=d,f})}var _de={kernelName:Ql,backendName:"webgpu",kernelFunc:$de},Pde=it({opType:de.SQRT}),Fde={kernelName:no,backendName:"webgpu",kernelFunc:Pde},Ode={kernelName:Bd,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{x:a}=e,n=t,r=new mp(a.shape,de.SQUARE);return n.runWebGPUProgram(r,[a],a.dtype)}},Dde=ua({opType:De.SQUARED_DIFFERENCE}),zde={kernelName:io,backendName:"webgpu",kernelFunc:Dde},Lde=class{constructor(e){this.variableNames=["x"],this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]);let t=ra(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 a=0;t=this.outputShape.map((n,r)=>(a++,this.outputShape.length===1?`coords * uniforms.strides[${r}] + uniforms.begin[${r}]`:`coords[${a-1}] * uniforms.strides[${r}] + uniforms.begin[${r}]`)).join(",")}return`
${Ce("index")} {
if (index < uniforms.size) {
let coords = getCoordsFromIndex(index);
setOutputAtIndex(index, getX(${t}));
}
}
`}};function Bde(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:p,newAxisMask:c,shrinkAxisMask:d}=n,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:x,begin:A,end:y,strides:b}=It.sliceInfo(r.shape,s,i,o,l,u,p,c,d),w;if(m)w=Ie({inputs:{x:r},backend:a,attrs:{shape:f}});else if(g||x){v.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let S=It.computeOutShape(A,y,b),C=Au({inputs:{x:r},backend:a,attrs:{begin:A,size:S}});w=Ie({inputs:{x:C},backend:a,attrs:{shape:f}}),a.disposeData(C.dataId)}else if(a.shouldExecuteOnCPU([r])){let S=a.readSync(r.dataId),C=Me(r.shape,r.dtype,S),E=rie(h,C,b,A);w=a.makeTensorInfo(f,r.dtype,E.values)}else{let S=new Lde(h),C=[{type:"int32",data:A},{type:"int32",data:b}],E=a.runWebGPUProgram(S,[r],r.dtype,C);w=Ie({inputs:{x:E},backend:a,attrs:{shape:f}}),a.disposeData(E.dataId)}return w}var Wde={kernelName:oo,backendName:"webgpu",kernelFunc:Bde};function Vde(e){let{inputs:t,backend:a,attrs:n}=e,{separator:r,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=n,{data:p,dataSplits:c}=t,d=a.readSync(p.dataId),h=a.readSync(c.dataId),[f,m]=sie(d,h,r,s,i,o,l,u);return[a.makeTensorInfo([f.length],"string",f),a.makeTensorInfo(c.shape,"int32",m)]}var Ude={kernelName:tu,backendName:"webgpu",kernelFunc:Vde},Gde=it({opType:de.TAN}),Hde={kernelName:uo,backendName:"webgpu",kernelFunc:Gde},jde=it({opType:de.TANH}),qde={kernelName:po,backendName:"webgpu",kernelFunc:jde},Xde=class{constructor(e){this.variableNames=["x","indices"],this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms=`inputSize : i32, firstPass : i32, negativeInf : f32,
dir : i32, inc : i32,`,this.shaderKey="swap"}getUserCode(){return`
${Ce("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));
}
}
}
`}},Kde=class{constructor(e){this.variableNames=["x","indices"],this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Ve(this.outputShape),this.dispatch=Ne(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms="inputSize : i32, firstPass : i32, k : i32,",this.shaderKey="merge"}getUserCode(){return`
${Ce("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 Jo(e,t){t!==null&&e.disposeData(t.dataId)}function eA(e){let t=1;for(;t<e;)t*=2;return t}function Zde(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{k:s,sorted:i}=n,o=r.shape,l=o[o.length-1];if(a.shouldExecuteOnCPU([r])){let b=a.readSync(r.dataId),[w,S]=lie(b,o,r.dtype,s,i);return[a.makeTensorInfo(w.shape,w.dtype,w.values),a.makeTensorInfo(S.shape,S.dtype,S.values)]}if(s===0)return o[o.length-1]=0,[a.makeTensorInfo(o,r.dtype,[]),a.makeTensorInfo(o,"int32",[])];if(l===1)return[r,Cr({attrs:{shape:o,dtype:"int32",value:0},backend:a})];let u=v.sizeFromShape(o)/l,p=Ie({inputs:{x:r},attrs:{shape:[u,l]},backend:a}),c=eA(s),d=eA(l),h=null,f=()=>h===null?[p,p]:[p,h],m=(b,w,S)=>{let C=f(),E=new Xde(S),_=[{type:"int32",data:[l]},{type:"int32",data:[h===null?1:0]},{type:"float32",data:[Number.NEGATIVE_INFINITY]},{type:"int32",data:[b]},{type:"int32",data:[w]}],$=h;h=a.runWebGPUProgram(E,C,"int32",_),Jo(a,$)};for(let b=1;b<c;b*=2){let w=b*2;for(let S=b;S>=1;S/=2)m(w,S,[u,d])}for(let b=d;b>c;b/=2){let w=f(),S=new Kde([u,b/2]),C=[{type:"int32",data:[l]},{type:"int32",data:[h===null?1:0]},{type:"int32",data:[c]}],E=h;h=a.runWebGPUProgram(S,w,"int32",C),Jo(a,E);let _=c/2,$=_*2;for(let M=_;M>=1;M/=2)m($,M,h.shape)}let g=h;h=Au({inputs:{x:h},backend:a,attrs:{begin:0,size:[u,s]}}),Jo(a,g);let x=q8({inputs:{x:p,indices:h},backend:a,attrs:{axis:1,batchDims:1}});Jo(a,p);let A=o.slice(0,-1);A.push(s),g=h,h=Ie({inputs:{x:h},attrs:{shape:A},backend:a}),Jo(a,g);let y=x;return x=Ie({inputs:{x},attrs:{shape:A},backend:a}),Jo(a,y),[x,h]}var Yde={kernelName:co,backendName:"webgpu",kernelFunc:Zde},Jde=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=Ve(this.outputShape),this.dispatch=Ne(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;
}
${Ce("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 Qde(e){let{inputs:t,backend:a,attrs:n}=e,{image:r,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=n,[p,c,d,h]=r.shape,[f,m]=u!=null?u:[c,d],g=[p,f,m,h],x=new Jde(g),A=i==="nearest"?1:2,y;switch(o){case"constant":y=1;break;case"reflect":y=2;break;case"wrap":y=3;break;case"nearest":y=4;break;default:y=1;break}let b=[{type:"int32",data:[A]},{type:"int32",data:[y]},{type:"float32",data:[l]}];return a.runWebGPUProgram(x,[r,s],"float32",b)}var epe={kernelName:ho,backendName:"webgpu",kernelFunc:Qde};function tpe(e){let{inputs:t,backend:a,attrs:n}=e,{value:r}=t,{axis:s}=n;s<0&&(s+=r.shape.length);let i=r,o=i.shape.length,l=r.shape[s],u=new Array(o-1),p=0;for(let m=0;m<o;m++)m!==s&&(u[p++]=i.shape[m]);let c=[],d=new Array(o).fill(0),h=i.shape.slice();h[s]=1;let f=new Array(l);for(let m=0;m<f.length;m++){d[s]=m;let g=Au({inputs:{x:i},backend:a,attrs:{begin:d,size:h}}),x=Ie({inputs:{x:g},backend:a,attrs:{shape:u}});f[m]=x,c.push(g)}return c.forEach(m=>a.disposeData(m.dataId)),f}var ape={kernelName:au,backendName:"webgpu",kernelFunc:tpe},npe=[Nse,pie,hie,mie,xie,bie,Cie,Eie,Mie,_ie,Fie,Die,Lie,Wie,Uie,Xie,Zie,toe,soe,uoe,poe,moe,Rse,yoe,Coe,$oe,Poe,Ooe,Loe,Woe,Uoe,Hoe,Xoe,Yoe,tle,nle,sle,ole,lle,ule,ple,hle,Sse,mle,vle,xle,yle,Ile,Tle,Nle,Mle,Ple,Ole,zle,Ese,Ble,xoe,Vle,Gle,jle,Xle,Zle,Jle,aue,eue,rue,iue,Hie,lue,due,jie,cue,fue,gue,Aue,Joe,bue,wue,Iue,ioe,Cue,Eue,Mue,_ue,Fue,Due,Lue,Wue,ooe,Vue,Gue,jue,Xue,Tse,Yue,ede,nde,sde,ode,ude,cde,mde,xde,yde,vde,Qie,Wde,Ude,Ide,Tde,Mde,_de,Fde,Ode,zde,wde,Qoe,Hde,qde,Ede,Yde,epe,Iie,ape,Nue];for(let e of npe)mn(e);var tA="4.1.0",rpe="4.1.0",spe="4.1.0",ipe="4.1.0",ope="4.1.0",lpe="0.0.1-alpha.16",xp={tfjs:tA,"tfjs-core":tA,"tfjs-converter":rpe,"tfjs-backend-cpu":spe,"tfjs-backend-webgl":ipe,"tfjs-backend-wasm":ope,"tfjs-backend-webgpu":lpe};function K(...e){let t=new Date,a=`${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(a,"Human:",...e)}function Q8(e,t){let a=e.endsWith("/")?"":"/",r=t.startsWith(".")||t.startsWith("/")||t.startsWith("http:")||t.startsWith("https:")||t.startsWith("file:")?`${t}`:`${e}${a}${t}`;if(!r.toLocaleLowerCase().includes(".json"))throw new Error(`modelpath error: expecting json file: ${r}`);return r}var te=()=>typeof performance!="undefined"?performance.now():parseInt((Number(process.hrtime.bigint())/1e3/1e3).toString());function U3(e,t,a="config",n=[]){for(let r of Object.keys(t))if(typeof t[r]=="object")U3(e[r],t[r],r,n);else{let s=e&&typeof e[r]!="undefined";s||n.push({reason:"unknown property",where:`${a}.${r} = ${t[r]}`});let i=e&&typeof e[r]==typeof t[r];s&&!i&&n.push({reason:"property type mismatch",where:`${a}.${r} = ${t[r]}`,expected:typeof e[r]})}return t.debug&&a==="config"&&n.length>0&&K("invalid configuration",n),n}function Ct(...e){let t=a=>a&&typeof a=="object";return e.reduce((a,n)=>(Object.keys(n||{}).forEach(r=>{let s=a[r],i=n[r];Array.isArray(s)&&Array.isArray(i)?a[r]=s.concat(...i):t(s)&&t(i)?a[r]=Ct(s,i):a[r]=i}),a),{})}var Io={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,autoBrightness:!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-lite.json"}},object:{enabled:!1,modelPath:"centernet.json",minConfidence:.2,iouThreshold:.4,maxDetected:10,skipFrames:99,skipTime:2e3},segmentation:{enabled:!1,modelPath:"rvm.json",ratio:.5,mode:"default"}};var e9=`
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 t9=`
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];
}
`,a9=`
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;
}
`,n9=`
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);
}
`,r9=`
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;
}
`,s9=`
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 G3=(e,t,a)=>{let n=new RegExp("\\b"+t+" \\w+ (\\w+)","ig");e.replace(n,(r,s)=>(a[s]=0,r))},H3=class{constructor(t,a,n){ue(this,"uniform",{});ue(this,"attribute",{});ue(this,"gl");ue(this,"id");ue(this,"compile",(t,a)=>{let n=this.gl.createShader(a);return n?(this.gl.shaderSource(n,t),this.gl.compileShader(n),this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS)?n:(K(`filter: gl compile failed: ${this.gl.getShaderInfoLog(n)||"unknown"}`),null)):(K("filter: could not create shader"),null)});this.gl=t;let r=this.compile(a,this.gl.VERTEX_SHADER),s=this.compile(n,this.gl.FRAGMENT_SHADER);if(this.id=this.gl.createProgram(),!(!r||!s)){if(!this.id){K("filter: could not create webgl program");return}if(this.gl.attachShader(this.id,r),this.gl.attachShader(this.id,s),this.gl.linkProgram(this.id),!this.gl.getProgramParameter(this.id,this.gl.LINK_STATUS)){K(`filter: gl link failed: ${this.gl.getProgramInfoLog(this.id)||"unknown"}`);return}this.gl.useProgram(this.id),G3(a,"attribute",this.attribute);for(let i in this.attribute)this.attribute[i]=this.gl.getAttribLocation(this.id,i);G3(a,"uniform",this.uniform),G3(n,"uniform",this.uniform);for(let i in this.uniform)this.uniform[i]=this.gl.getUniformLocation(this.id,i)}}};function i9(){let e=0,t=null,a=!1,n=-1,r=[null,null],s=[],i=null,o=null,l=Nn(100,100),u={},p={INTERMEDIATE:1},c=l.getContext("webgl");if(!c){K("filter: cannot get webgl context");return}this.gl=c;function d(A,y){if(!(A===l.width&&y===l.height)){if(l.width=A,l.height=y,!i){let b=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,-1,1,0,0,1,-1,1,1,1,1,1,0]);i=c.createBuffer(),c.bindBuffer(c.ARRAY_BUFFER,i),c.bufferData(c.ARRAY_BUFFER,b,c.STATIC_DRAW),c.pixelStorei(c.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0)}c.viewport(0,0,l.width,l.height),r=[null,null]}}function h(A,y){let b=c.createFramebuffer();c.bindFramebuffer(c.FRAMEBUFFER,b);let w=c.createRenderbuffer();c.bindRenderbuffer(c.RENDERBUFFER,w);let S=c.createTexture();return c.bindTexture(c.TEXTURE_2D,S),c.texImage2D(c.TEXTURE_2D,0,c.RGBA,A,y,0,c.RGBA,c.UNSIGNED_BYTE,null),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MAG_FILTER,c.LINEAR),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MIN_FILTER,c.LINEAR),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,S,0),c.bindTexture(c.TEXTURE_2D,null),c.bindFramebuffer(c.FRAMEBUFFER,null),{fbo:b,texture:S}}function f(A){return r[A]=r[A]||h(l.width,l.height),r[A]}function m(A=0){if(!o)return;let y=null,b=null,w=!1;e===0?y=t:y=f(n).texture||null,e++,a&&!(A&p.INTERMEDIATE)?(b=null,w=e%2===0):(n=(n+1)%2,b=f(n).fbo||null),c.bindTexture(c.TEXTURE_2D,y),c.bindFramebuffer(c.FRAMEBUFFER,b),c.uniform1f(o.uniform.flipY,w?-1:1),c.drawArrays(c.TRIANGLES,0,6)}function g(A){if(u[A])return o=u[A],c.useProgram((o?o.id:null)||null),o;if(o=new H3(c,e9,A),!o)return K("filter: could not get webgl program"),null;let y=Float32Array.BYTES_PER_ELEMENT,b=4*y;return c.enableVertexAttribArray(o.attribute.pos),c.vertexAttribPointer(o.attribute.pos,2,c.FLOAT,!1,b,0*y),c.enableVertexAttribArray(o.attribute.uv),c.vertexAttribPointer(o.attribute.uv,2,c.FLOAT,!1,b,2*y),u[A]=o,o}let x={colorMatrix:A=>{let y=new Float32Array(A);y[4]/=255,y[9]/=255,y[14]/=255,y[19]/=255;let b=y[18]===1&&y[3]===0&&y[8]===0&&y[13]===0&&y[15]===0&&y[16]===0&&y[17]===0&&y[19]===0?a9:t9,w=g(b);!w||(c.uniform1fv(w.uniform.m,y),m())},brightness:A=>{let y=(A||0)+1;x.colorMatrix([y,0,0,0,0,0,y,0,0,0,0,0,y,0,0,0,0,0,1,0])},saturation:A=>{let y=(A||0)*2/3+1,b=(y-1)*-.5;x.colorMatrix([y,b,b,0,0,b,y,b,0,0,b,b,y,0,0,0,0,0,1,0])},desaturate:()=>{x.saturation(-1)},contrast:A=>{let y=(A||0)+1,b=-128*(y-1);x.colorMatrix([y,0,0,0,b,0,y,0,0,b,0,0,y,0,b,0,0,0,1,0])},negative:()=>{x.contrast(-2)},hue:A=>{A=(A||0)/180*Math.PI;let y=Math.cos(A),b=Math.sin(A),w=.213,S=.715,C=.072;x.colorMatrix([w+y*(1-w)+b*-w,S+y*-S+b*-S,C+y*-C+b*(1-C),0,0,w+y*-w+b*.143,S+y*(1-S)+b*.14,C+y*-C+b*-.283,0,0,w+y*-w+b*-(1-w),S+y*-S+b*S,C+y*(1-C)+b*C,0,0,0,0,0,1,0])},desaturateLuminance:()=>{x.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:()=>{x.colorMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0])},brownie:()=>{x.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:()=>{x.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:()=>{x.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:()=>{x.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:()=>{x.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:()=>{x.colorMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0])},convolution:A=>{let y=new Float32Array(A),b=1/l.width,w=1/l.height,S=g(s9);!S||(c.uniform1fv(S.uniform.m,y),c.uniform2f(S.uniform.px,b,w),m())},detectEdges:()=>{x.convolution.call(this,[0,1,0,1,-4,1,0,1,0])},sobelX:()=>{x.convolution.call(this,[-1,0,1,-2,0,2,-1,0,1])},sobelY:()=>{x.convolution.call(this,[-1,-2,-1,0,0,0,1,2,1])},sharpen:A=>{let y=A||1;x.convolution.call(this,[0,-1*y,0,-1*y,1+4*y,-1*y,0,-1*y,0])},emboss:A=>{let y=A||1;x.convolution.call(this,[-2*y,-1*y,0,-1*y,1,1*y,0,1*y,2*y])},blur:A=>{let y=A/7/l.width,b=A/7/l.height,w=g(r9);!w||(c.uniform2f(w.uniform.px,0,b),m(p.INTERMEDIATE),c.uniform2f(w.uniform.px,y,0),m())},pixelate:A=>{let y=A/l.width,b=A/l.height,w=g(n9);!w||(c.uniform2f(w.uniform.size,y,b),m())}};this.add=function(A){let y=Array.prototype.slice.call(arguments,1),b=x[A];s.push({func:b,args:y})},this.reset=function(){s=[]},this.get=function(){return s},this.apply=function(A){d(A.width,A.height),e=0,t||(t=c.createTexture()),c.bindTexture(c.TEXTURE_2D,t),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MIN_FILTER,c.NEAREST),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MAG_FILTER,c.NEAREST),c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,A);for(let y=0;y<s.length;y++){a=y===s.length-1;let b=s[y];b.func.apply(this,b.args||[])}return l},this.draw=function(A){return this.add("brightness",0),this.apply(A)}}async function qh(e){let t=e.shape.length===4?_e(e):e,a=ka(t,3,2),n=[Kr(a[0]),Kr(a[1]),Kr(a[2])],r=[pa(a[0]),pa(a[1]),pa(a[2])],s=await Promise.all(r.map(p=>p.data())),i=Math.max(s[0][0],s[1][0],s[2][0]),l=(i>1?255:1)/i,u;if(l>1){let p=[fe(a[0],n[0]),fe(a[1],n[1]),fe(a[2],n[2])],c=[fe(r[0],n[0]),fe(r[1],n[1]),fe(r[2],n[2])],d=[ae(p[0],l),ae(p[1],l),ae(p[2],l)],h=sa([d[0],d[1],d[2]],2);u=J(h,[1,t.shape[0]||0,t.shape[1]||0,3]),Y([...p,...c,...d])}else u=Gt(t,0);return Y([...a,...n,...r,a,t,e]),u}var Xh=3840,Jt=null,Qt=null,yu=null,xt,gn={inputSum:0,cacheDiff:1,sumMethod:0,inputTensor:void 0};function j3(){gn.inputSum=0,gn.cacheDiff=1,gn.sumMethod=0,gn.inputTensor=void 0}function Nn(e,t){let a;if(ne.browser)if(ne.worker){if(typeof OffscreenCanvas=="undefined")throw new Error("canvas error: attempted to run in web worker but OffscreenCanvas is not supported");a=new OffscreenCanvas(e,t)}else{if(typeof document=="undefined")throw new Error("canvas error: attempted to run in browser but DOM is not defined");a=document.createElement("canvas"),a.width=e,a.height=t}else typeof ne.Canvas!="undefined"?a=new ne.Canvas(e,t):typeof globalThis.Canvas!="undefined"&&(a=new globalThis.Canvas(e,t));return a}function Kh(e,t){let a=t||Nn(e.width,e.height);return a.getContext("2d").drawImage(e,0,0),a}async function Zh(e,t,a=!0){var d,h,f;if(!e)return t.debug&&K("input error: input is missing"),{tensor:null,canvas:null};if(!(e instanceof pt)&&!(typeof Image!="undefined"&&e instanceof Image)&&!(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 not recognized");if(e instanceof pt){let m=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)m=Gt(e,0);else if(e.shape[2]===4){let g=sp(e,[0,0,0],[-1,-1,3]);m=Gt(g,0),Y(g)}}else e.shape.length===4&&(e.shape[3]===3?m=wa(e):e.shape[3]===4&&(m=xh(e,[0,0,0,0],[-1,-1,-1,3])));if(m==null||m.shape.length!==4||m.shape[0]!==1||m.shape[3]!==3)throw new Error(`input error: attempted to use tensor with unrecognized shape: ${e.shape.toString()}`);if(m.dtype==="int32"){let g=He(m,"float32");Y(m),m=g}return{tensor:m,canvas:t.filter.return?Qt:null}}if(typeof e.readyState!="undefined"&&e.readyState<=2)return t.debug&&K("input stream is not ready"),{tensor:null,canvas:Jt};let n=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(!n||!r)return t.debug&&K("cannot determine input dimensions"),{tensor:null,canvas:Jt};let s=n,i=r;if(s>Xh&&(s=Xh,i=Math.trunc(s*r/n)),i>Xh&&(i=Xh,s=Math.trunc(i*n/r)),(((d=t.filter)==null?void 0:d.width)||0)>0?s=t.filter.width:(((h=t.filter)==null?void 0:h.height)||0)>0&&(s=n*((t.filter.height||0)/r)),(t.filter.height||0)>0?i=t.filter.height:(t.filter.width||0)>0&&(i=r*((t.filter.width||0)/n)),!s||!i)throw new Error("input error: cannot determine dimension");(!Jt||Jt.width!==s||Jt.height!==i)&&(Jt=Nn(s,i));let o=Jt.getContext("2d");if(typeof ImageData!="undefined"&&e instanceof ImageData?o.putImageData(e,0,0):t.filter.flip&&typeof o.translate!="undefined"?(o.translate(n,0),o.scale(-1,1),o.drawImage(e,0,0,n,r,0,0,Jt.width,Jt.height),o.setTransform(1,0,0,1,0,0)):o.drawImage(e,0,0,n,r,0,0,Jt.width,Jt.height),(!Qt||Jt.width!==Qt.width||Jt.height!==Qt.height)&&(Qt=Nn(Jt.width,Jt.height)),t.filter.enabled&&ne.webgl.supported?(xt||(xt=ne.browser?new i9:null),ne.filter=!!xt,xt!=null&&xt.add?(xt.reset(),t.filter.brightness!==0&&xt.add("brightness",t.filter.brightness),t.filter.contrast!==0&&xt.add("contrast",t.filter.contrast),t.filter.sharpness!==0&&xt.add("sharpen",t.filter.sharpness),t.filter.blur!==0&&xt.add("blur",t.filter.blur),t.filter.saturation!==0&&xt.add("saturation",t.filter.saturation),t.filter.hue!==0&&xt.add("hue",t.filter.hue),t.filter.negative&&xt.add("negative"),t.filter.sepia&&xt.add("sepia"),t.filter.vintage&&xt.add("brownie"),t.filter.sepia&&xt.add("sepia"),t.filter.kodachrome&&xt.add("kodachrome"),t.filter.technicolor&&xt.add("technicolor"),t.filter.polaroid&&xt.add("polaroid"),t.filter.pixelate!==0&&xt.add("pixelate",t.filter.pixelate),((f=xt.get())==null?void 0:f.length)>1?Qt=xt.apply(Jt):Qt=xt.draw(Jt)):(t.debug&&K("input process error: cannot initialize filters"),ne.webgl.supported=!1,t.filter.enabled=!1,Kh(Jt,Qt))):(Kh(Jt,Qt),xt&&(xt=null),ne.filter=!!xt),!a)return{tensor:null,canvas:Qt};if(!Qt)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(ne.browser&&wr)l=wr?wr.fromPixels(e):null;else{u=e.data.length/e.height/e.width;let m=new Uint8Array(e.data.buffer);l=Be(m,[e.height,e.width,u],"int32")}else if((!yu||Qt.width!==yu.width||Qt.height!==yu.height)&&(yu=Nn(Qt.width,Qt.height)),wr&&ne.browser)t.backend==="webgl"||t.backend==="humangl"||t.backend==="webgpu"?l=wr.fromPixels(Qt):(yu=Kh(Qt),l=wr.fromPixels(yu));else{let x=Kh(Qt).getContext("2d").getImageData(0,0,s,i);u=x.data.length/s/i;let A=new Uint8Array(x.data.buffer);l=Be(A,[s,i,u])}if(u===4){let m=sp(l,[0,0,0],[-1,-1,3]);Y(l),l=m}if(!l)throw new Error("input error: cannot create tensor");let p=He(l,"float32"),c=t.filter.equalization?await qh(p):Gt(p,0);if(Y([l,p]),t.filter.autoBrightness){let m=pa(c),g=await m.data();t.filter.brightness=g[0]>1?1-g[0]/255:1-g[0],Y(m)}return{tensor:c,canvas:t.filter.return?Qt:null}}async function o9(e,t){let a=!1;if(e.cacheSensitivity===0||!t.shape||t.shape.length!==4||t.shape[1]>3840||t.shape[2]>2160)return a;if(!gn.inputTensor)gn.inputTensor=wa(t);else if(gn.inputTensor.shape[1]!==t.shape[1]||gn.inputTensor.shape[2]!==t.shape[2])Y(gn.inputTensor),gn.inputTensor=wa(t);else{let n={};n.diff=fe(t,gn.inputTensor),n.squared=ae(n.diff,n.diff),n.sum=tt(n.squared);let s=(await n.sum.data())[0]/(t.shape[1]||1)/(t.shape[2]||1)/255/3;Y([gn.inputTensor,n.diff,n.squared,n.sum]),gn.inputTensor=wa(t),a=s<=(e.cacheSensitivity||0)}return a}async function l9(e,t,a){let n={};if(!t||!a||t.shape.length!==4||t.shape.length!==a.shape.length)return e.debug||K("invalid input tensor or tensor shapes do not match:",t.shape,a.shape),0;if(t.shape[0]!==1||a.shape[0]!==1||t.shape[3]!==3||a.shape[3]!==3)return e.debug||K("input tensors must be of shape [1, height, width, 3]:",t.shape,a.shape),0;n.input1=wa(t),n.input2=t.shape[1]!==a.shape[1]||t.shape[2]!==a.shape[2]?ge.resizeBilinear(a,[t.shape[1],t.shape[2]]):wa(a),n.diff=fe(n.input1,n.input2),n.squared=ae(n.diff,n.diff),n.sum=tt(n.squared);let s=(await n.sum.data())[0]/(t.shape[1]||1)/(t.shape[2]||1)/255/3;return Y([n.input1,n.input2,n.diff,n.squared,n.sum]),s}var yp,bp,vp,Ap=class{constructor(){ue(this,"browser");ue(this,"node");ue(this,"worker");ue(this,"platform","");ue(this,"agent","");ue(this,"backends",[]);ue(this,"initial");ue(this,"filter");ue(this,"tfjs");ue(this,"offscreen");ue(this,"perfadd",!1);ue(this,"tensorflow",{version:void 0,gpu:void 0});ue(this,"wasm",{supported:void 0,backend:void 0,simd:void 0,multithread:void 0});ue(this,"webgl",{supported:void 0,backend:void 0,version:void 0,renderer:void 0,shader:void 0,vendor:void 0});ue(this,"webgpu",{supported:void 0,backend:void 0,adapter:void 0});ue(this,"cpu",{model:void 0,flags:[]});ue(this,"kernels",[]);Gn(this,yp,void 0);Gn(this,bp,void 0);Gn(this,vp,void 0);if(this.browser=typeof navigator!="undefined",this.node=typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined",this.tfjs={version:xp["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 a=t[0].match(/\(([^()]+)\)/g);this.platform=a!=null&&a[0]?a[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}`)}get Canvas(){return Ga(this,yp)}set Canvas(t){fr(this,yp,t),globalThis.Canvas=t}get Image(){return Ga(this,bp)}set Image(t){fr(this,bp,t),globalThis.Image=t}get ImageData(){return Ga(this,vp)}set ImageData(t){fr(this,vp,t),globalThis.ImageData=t}async updateBackend(){this.backends=Object.keys(kt().registryFactory);try{this.tensorflow={version:tr().binding?tr().binding.TF_Version:void 0,gpu:tr().binding?tr().binding.isUsingGpuDevice():void 0}}catch(n){}this.wasm.supported=typeof WebAssembly!="undefined",this.wasm.backend=this.backends.includes("wasm"),this.wasm.supported&&this.wasm.backend&&(this.wasm.simd=await W().getAsync("WASM_HAS_SIMD_SUPPORT"),this.wasm.multithread=await W().getAsync("WASM_HAS_MULTITHREAD_SUPPORT"));let t=Nn(100,100),a=t?t.getContext("webgl2"):void 0;this.webgl.supported=typeof a!="undefined",this.webgl.backend=this.backends.includes("webgl"),this.webgl.supported&&this.webgl.backend&&a&&(this.webgl.version=a.getParameter(a.VERSION),this.webgl.vendor=a.getParameter(a.VENDOR),this.webgl.renderer=a.getParameter(a.RENDERER),this.webgl.shader=a.getParameter(a.SHADING_LANGUAGE_VERSION)),this.webgpu.supported=this.browser&&typeof navigator.gpu!="undefined",this.webgpu.backend=this.backends.includes("webgpu");try{if(this.webgpu.supported){let n=await navigator.gpu.requestAdapter();this.webgpu.adapter=await(n==null?void 0:n.requestAdapterInfo())}}catch(n){this.webgpu.supported=!1}try{this.kernels=Zn(ia()).map(n=>n.kernelName.toLowerCase())}catch(n){}}updateCPU(){let t={model:"",flags:[]};this.node&&this.platform.startsWith("linux"),this.cpu?this.cpu=t:Object.defineProperty(this,"cpu",{value:t})}};yp=new WeakMap,bp=new WeakMap,vp=new WeakMap;var ne=new Ap;var Jh=class{constructor(){ue(this,"config");ue(this,"element");ue(this,"stream");ue(this,"devices",[]);ue(this,"enumerate",async()=>{try{let t=await navigator.mediaDevices.enumerateDevices();this.devices=t.filter(a=>a.kind==="videoinput")}catch(t){this.devices=[]}return this.devices});ue(this,"start",async t=>{var r,s;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.id&&(this.config.id=t==null?void 0:t.id),t!=null&&t.element)if(typeof t.element=="string"){let i=document.getElementById(t.element);if(i&&i instanceof HTMLVideoElement)this.element=i;else{this.config.debug&&K("webcam","cannot get dom element",t.element);return}}else if(t.element instanceof HTMLVideoElement)this.element=t.element;else{this.config.debug&&K("webcam","unknown dom element",t.element);return}else this.element=document.createElement("video");let a={audio:!1,video:{facingMode:this.config.mode==="front"?"user":"environment",resizeMode:this.config.crop?"crop-and-scale":"none"}};if(((r=this.config)==null?void 0:r.width)>0&&(a.video.width={ideal:this.config.width}),((s=this.config)==null?void 0:s.height)>0&&(a.video.height={ideal:this.config.height}),this.config.id&&(a.video.deviceId=this.config.id),this.element.addEventListener("play",()=>{this.config.debug&&K("webcam","play")}),this.element.addEventListener("pause",()=>{this.config.debug&&K("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&&K("webcam","no devices");return}try{this.stream=await navigator.mediaDevices.getUserMedia(a)}catch(i){K("webcam",i);return}if(!this.stream){this.config.debug&&K("webcam","no stream");return}this.element.srcObject=this.stream,await new Promise(i=>{this.element?this.element.onloadeddata=()=>i(!0):i(!1)}),await this.element.play(),this.config.debug&&K("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})});ue(this,"pause",()=>{this.element&&this.element.pause()});ue(this,"play",async()=>{this.element&&await this.element.play()});ue(this,"stop",()=>{this.config.debug&&K("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 q3={};hr(q3,{age:()=>Ipe,"anti-spoofing":()=>ece,antispoof:()=>cpe,blazeface:()=>hpe,"blazeface-back":()=>Spe,"blazeface-front":()=>Tpe,"blazepose-detector":()=>Cpe,"blazepose-full":()=>Npe,"blazepose-heavy":()=>Epe,"blazepose-lite":()=>Rpe,centernet:()=>fpe,default:()=>hce,efficientpose:()=>Mpe,"efficientpose-i-lite":()=>tce,"efficientpose-ii-lite":()=>ace,"efficientpose-iv":()=>nce,emotion:()=>mpe,faceboxes:()=>$pe,facemesh:()=>gpe,"facemesh-attention":()=>Ppe,"facemesh-attention-pinto":()=>_pe,"facemesh-detection-full":()=>Fpe,"facemesh-detection-short":()=>Ope,faceres:()=>xpe,"faceres-deep":()=>Dpe,gear:()=>zpe,gender:()=>Bpe,"gender-ssrnet-imdb":()=>Lpe,handdetect:()=>Wpe,"handlandmark-full":()=>Vpe,"handlandmark-lite":()=>Ape,"handlandmark-sparse":()=>Upe,handskeleton:()=>Gpe,handtrack:()=>ype,"insightface-efficientnet-b0":()=>rce,"insightface-ghostnet-strides1":()=>sce,"insightface-ghostnet-strides2":()=>ice,"insightface-mobilenet-emore":()=>oce,"insightface-mobilenet-swish":()=>lce,iris:()=>bpe,liveness:()=>vpe,meet:()=>Hpe,mobileface:()=>jpe,mobilefacenet:()=>qpe,models:()=>wpe,"movenet-lightning":()=>kpe,"movenet-multipose":()=>Xpe,"movenet-thunder":()=>Kpe,nanodet:()=>Zpe,"nanodet-e":()=>uce,"nanodet-g":()=>dce,"nanodet-m":()=>pce,"nanodet-t":()=>cce,posenet:()=>Ype,rvm:()=>Jpe,selfie:()=>Qpe});var cpe=853098,hpe=538928,fpe=4030290,mpe=820516,gpe=1477958,xpe=6978814,Ape=2023432,ype=2964837,bpe=2599092,vpe=592976,wpe=0,kpe=4650216,Ipe=161240,Spe=538928,Tpe=402048,Cpe=5928856,Npe=6339202,Epe=27502466,Rpe=2726402,Mpe=5651240,$pe=2013002,_pe=2387598,Ppe=2382414,Fpe=1026192,Ope=201268,Dpe=13957620,zpe=1498916,Lpe=161236,Bpe=201808,Wpe=3515612,Vpe=5431368,Upe=5286322,Gpe=5502280,Hpe=372228,jpe=2183192,qpe=5171976,Xpe=9448838,Kpe=12477112,Zpe=7574558,Ype=5032780,Jpe=3739355,Qpe=212886,ece=853098,tce=2269064,ace=5651240,nce=25643252,rce=13013224,sce=8093408,ice=8049584,oce=6938536,lce=12168584,uce=12319156,dce=7574558,pce=1887474,cce=5294216,hce={antispoof:cpe,blazeface:hpe,centernet:fpe,emotion:mpe,facemesh:gpe,faceres:xpe,"handlandmark-lite":Ape,handtrack:ype,iris:bpe,liveness:vpe,models:wpe,"movenet-lightning":kpe,age:Ipe,"blazeface-back":Spe,"blazeface-front":Tpe,"blazepose-detector":Cpe,"blazepose-full":Npe,"blazepose-heavy":Epe,"blazepose-lite":Rpe,efficientpose:Mpe,faceboxes:$pe,"facemesh-attention-pinto":_pe,"facemesh-attention":Ppe,"facemesh-detection-full":Fpe,"facemesh-detection-short":Ope,"faceres-deep":Dpe,gear:zpe,"gender-ssrnet-imdb":Lpe,gender:Bpe,handdetect:Wpe,"handlandmark-full":Vpe,"handlandmark-sparse":Upe,handskeleton:Gpe,meet:Hpe,mobileface:jpe,mobilefacenet:qpe,"movenet-multipose":Xpe,"movenet-thunder":Kpe,nanodet:Zpe,posenet:Ype,rvm:Jpe,selfie:Qpe,"anti-spoofing":ece,"efficientpose-i-lite":tce,"efficientpose-ii-lite":ace,"efficientpose-iv":nce,"insightface-efficientnet-b0":rce,"insightface-ghostnet-strides1":sce,"insightface-ghostnet-strides2":ice,"insightface-mobilenet-emore":oce,"insightface-mobilenet-swish":lce,"nanodet-e":uce,"nanodet-g":dce,"nanodet-m":pce,"nanodet-t":cce};var Ea={cacheModels:!0,cacheSupported:!0,verbose:!0,debug:!1,modelBasePath:""},ha={};async function fce(e,t){return Ea.debug&&K("load model fetch:",e,t),fetch(e,t)}function u9(e){Ea.cacheModels=e.cacheModels,Ea.verbose=e.debug,Ea.modelBasePath=e.modelBasePath}async function Ee(e){var u,p,c,d;let t=Q8(Ea.modelBasePath,e||"");t.toLowerCase().endsWith(".json")||(t+=".json");let a=t.includes("/")?t.split("/"):t.split("\\"),n=a[a.length-1].replace(".json",""),r="indexeddb://"+n;ha[n]={name:n,sizeFromManifest:0,sizeLoadedWeights:0,sizeDesired:q3[n],inCache:!1,url:""},Ea.cacheSupported=typeof indexedDB!="undefined";let s={};try{s=Ea.cacheSupported&&Ea.cacheModels?await jn.listModels():{}}catch(h){Ea.cacheSupported=!1}ha[n].inCache=Ea.cacheSupported&&Ea.cacheModels&&Object.keys(s).includes(r),ha[n].url=ha[n].inCache?r:t;let i=typeof fetch=="undefined"?{}:{fetchFunc:(h,f)=>fce(h,f)},o=new op(ha[n].url,i),l=!1;try{o.findIOHandler(),Ea.debug&&K("model load handler:",o.handler)}catch(h){K("error finding model i/o handler:",t,h)}try{let h=await((u=o.handler)==null?void 0:u.load())||null;ha[n].sizeFromManifest=((p=h==null?void 0:h.weightData)==null?void 0:p.byteLength)||0,h?o.loadSync(h):o=await r3(ha[n].inCache?r:t,i),ha[n].sizeLoadedWeights=((d=(c=o.artifacts)==null?void 0:c.weightData)==null?void 0:d.byteLength)||0,Ea.verbose&&K("load:",{model:n,url:o.modelUrl,bytes:ha[n].sizeLoadedWeights}),l=!0}catch(h){K("error loading model:",t,h)}if(l&&Ea.cacheModels&&Ea.cacheSupported&&!ha[n].inCache)try{let h=await o.save(r);Ea.debug&&K("model saved:",r,h)}catch(h){K("error saving model:",t,h)}return o}var X3="3.0.0";var vt={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 xce(){let e=vt.gl;!e||(vt.extensions=e.getSupportedExtensions())}function d9(e){var t;if(e.config.backend==="humangl"&&(vt.name in kt().registry&&!((t=vt==null?void 0:vt.gl)!=null&&t.getParameter(vt.gl.VERSION))&&(K("humangl error: backend invalid context"),e.models.reset()),!u2(vt.name))){try{vt.canvas=Nn(100,100)}catch(r){K("humangl error: cannot create canvas:",r);return}try{if(vt.gl=vt.canvas.getContext("webgl2",vt.webGLattr),!vt.gl){K("humangl error: cannot get webgl context");return}if(!vt.gl.getParameter(vt.gl.VERSION).includes("2.0")){K("backend override: using fallback webgl backend as webgl 2.0 is not detected"),e.config.backend="webgl";return}vt.canvas&&(vt.canvas.addEventListener("webglcontextlost",s=>{throw K("humangl error:",s.type),K("possible browser memory leak using webgl or conflict with multiple backend registrations"),e.emit("error"),new Error("backend error: webgl context lost")}),vt.canvas.addEventListener("webglcontextrestored",s=>{K("humangl error: context restored:",s)}),vt.canvas.addEventListener("webglcontextcreationerror",s=>{K("humangl error: context create:",s)}))}catch(r){K("humangl error: cannot get webgl context:",r);return}try{Fh(2,vt.gl)}catch(r){K("humangl error: cannot set webgl context:",r);return}try{let r=new il(vt.gl);go(vt.name,()=>new fu(r),vt.priority)}catch(r){K("humangl error: cannot register webgl backend:",r);return}try{Zn("webgl").forEach(s=>{let i={...s,backendName:vt.name};mn(i)})}catch(r){K("humangl error: cannot update webgl backend registration:",r);return}try{W().flagRegistry.WEBGL_VERSION&&W().set("WEBGL_VERSION",2)}catch(r){K("humangl error: cannot set WebGL backend flags:",r);return}xce();let a=tr(),n=typeof a.gpgpu!="undefined"?a.getGPGPUContext().gl:null;n?e.config.debug&&K("humangl backend registered:",{webgl:n.getParameter(n.VERSION),renderer:n.getParameter(n.RENDERER)}):K("humangl error: no current gl context:",n,vt.gl)}}var ze={tf255:255,tf1:1,tf2:2,tf05:.5,tf127:127.5,rgb:[.2989,.587,.114]};function p9(){ze.tf255=Fe(255,"float32"),ze.tf1=Fe(1,"float32"),ze.tf2=Fe(2,"float32"),ze.tf05=Fe(.5,"float32"),ze.tf127=Fe(127.5,"float32"),ze.rgb=Ht([.2989,.587,.114],"float32")}async function bce(){var e;return await ne.updateBackend(),(e=ne.tensorflow)!=null&&e.version?"tensorflow":ne.webgpu.supported&&ne.webgpu.backend?"webgpu":ne.webgl.supported&&ne.webgl.backend?"webgl":ne.wasm.supported&&ne.wasm.backend?"wasm":"cpu"}function vce(e){let t=[];if(!ne.kernels.includes("mod")){let a={kernelName:"Mod",backendName:ia(),kernelFunc:n=>$e(()=>fe(n.inputs.a,ae(me(n.inputs.a,n.inputs.b),n.inputs.b)))};mn(a),ne.kernels.push("mod"),t.push("mod")}if(!ne.kernels.includes("floormod")){let a={kernelName:"FloorMod",backendName:ia(),kernelFunc:n=>$e(()=>be(ae(Yd(n.inputs.a,n.inputs.b),n.inputs.b),su(n.inputs.a,n.inputs.b)))};mn(a),ne.kernels.push("floormod"),t.push("floormod")}if(!ne.kernels.includes("rotatewithoffset")&&e.softwareKernels){let a={kernelName:"RotateWithOffset",backendName:ia(),kernelFunc:n=>$e(()=>{let r=ia();Xd("cpu");let s=ge.rotateWithOffset(n.inputs.image,n.attrs.radians,n.attrs.fillValue,n.attrs.center);return Xd(r),s})};mn(a),ne.kernels.push("rotatewithoffset"),t.push("rotatewithoffset")}t.length>0&&e.debug&&K("registered kernels:",t)}var c9={};async function wp(e,t=!1){var a;if(e.state="backend",((a=e.config.backend)==null?void 0:a.length)===0&&(e.config.backend=await bce()),t||ne.initial||e.config.backend&&e.config.backend.length>0&&ia()!==e.config.backend){let n=te();if(e.config.backend&&e.config.backend.length>0){if(typeof window=="undefined"&&typeof WorkerGlobalScope!="undefined"&&e.config.debug&&e.config.debug&&K("running inside web worker"),ne.browser&&e.config.backend==="tensorflow"&&(e.config.debug&&K("override: backend set to tensorflow while running in browser"),e.config.backend="webgl"),ne.node&&(e.config.backend==="webgl"||e.config.backend==="humangl")&&(e.config.debug&&K(`override: backend set to ${e.config.backend} while running in nodejs`),e.config.backend="tensorflow"),ne.browser&&e.config.backend==="webgpu")if(typeof navigator=="undefined"||typeof navigator.gpu=="undefined")K("override: backend set to webgpu but browser does not support webgpu"),e.config.backend="webgl";else{let s=await navigator.gpu.requestAdapter();if(e.config.debug&&K("enumerated webgpu adapter:",s),!s)K("override: backend set to webgpu but browser reports no available gpu"),e.config.backend="webgl";else{let i="requestAdapterInfo"in s?await s.requestAdapterInfo():void 0;K("webgpu adapter info:",i)}}let r=Object.keys(kt().registryFactory);if(e.config.backend==="humangl"&&!r.includes("humangl")&&(d9(e),r=Object.keys(kt().registryFactory)),e.config.debug&&K("available backends:",r),r.includes(e.config.backend)||(K(`error: backend ${e.config.backend} not found in registry`),e.config.backend=ne.node?"tensorflow":"webgl",e.config.debug&&K(`override: setting backend ${e.config.backend}`)),e.config.debug&&K("setting backend:",[e.config.backend]),e.config.backend==="wasm"){if(W().flagRegistry.CANVAS2D_WILL_READ_FREQUENTLY&&W().set("CANVAS2D_WILL_READ_FREQUENTLY",!0),e.config.debug&&K("wasm path:",e.config.wasmPath),typeof Wh!="undefined")Wh(e.config.wasmPath,e.config.wasmPlatformFetch);else throw new Error("backend error: attempting to use wasm backend but wasm path is not set");let s=!1,i=!1;try{s=await W().getAsync("WASM_HAS_MULTITHREAD_SUPPORT"),i=await W().getAsync("WASM_HAS_SIMD_SUPPORT"),e.config.debug&&K(`wasm execution: ${i?"simd":"no simd"} ${s?"multithreaded":"singlethreaded"}`),e.config.debug&&!i&&K("warning: wasm simd support is not enabled")}catch(o){K("wasm detection failed")}}try{await Xd(e.config.backend),await Kd()}catch(s){return K("error: cannot set backend:",e.config.backend,s),!1}e.config.debug&&(c9=JSON.parse(JSON.stringify(W().flags)))}if((ia()==="humangl"||ia()==="webgl")&&(W().flagRegistry.WEBGL_USE_SHAPES_UNIFORMS&&W().set("WEBGL_USE_SHAPES_UNIFORMS",!0),W().flagRegistry.WEBGL_EXP_CONV&&W().set("WEBGL_EXP_CONV",!0),e.config.debug&&typeof e.config.deallocate!="undefined"&&e.config.deallocate&&(K("changing webgl: WEBGL_DELETE_TEXTURE_THRESHOLD:",!0),W().set("WEBGL_DELETE_TEXTURE_THRESHOLD",0))),ia(),e.config.debug){let r=W().flags,s={};for(let i of Object.keys(r))c9[i]!==r[i]&&(s[i]=r[i]);e.config.debug&&Object.keys(s).length>0&&K("backend:",ia(),"flags:",s)}if(e.config.flags&&Object.keys(e.config.flags).length>0){e.config.debug&&K("flags:",e.config.flags);for(let[r,s]of Object.entries(e.config.flags))W().set(r,s)}o2(),p9(),e.performance.initBackend=Math.trunc(te()-n),e.config.backend=ia(),await ne.updateBackend(),vce(e.config),ne.initial=!1}return!0}function Qh(e,t){for(let a of e){let n={kernelName:a,backendName:t.backend,kernelFunc:r=>{var s;return t.debug&&K("kernelFunc",a,t.backend,r),(s=r==null?void 0:r.inputs)==null?void 0:s.info}};mn(n)}ne.kernels=Zn(ia()).map(a=>a.kernelName.toLowerCase())}var s0={};hr(s0,{all:()=>Jce,body:()=>t0,canvas:()=>Yce,face:()=>e0,gesture:()=>r0,hand:()=>a0,init:()=>tg,object:()=>n0,options:()=>$t,person:()=>Zce});var xn=e=>{if(!e)K("draw error: invalid canvas");else if(!e.getContext)K("draw error: canvas context not defined");else{let t=e.getContext("2d");if(!t)K("draw error: cannot get canvas context");else return t}return null},So=e=>Math.round(e*180/Math.PI),ct=(e,t,a)=>e.replace(t,typeof a=="number"?a.toFixed(1):a),To=(e,t)=>{if(!t.useDepth||typeof e=="undefined")return t.color;let a=Uint8ClampedArray.from([127+2*e,127-2*e,255]);return`rgba(${a[0]}, ${a[1]}, ${a[2]}, ${t.alpha})`};function En(e,t,a,n,r){let s=t.replace(/\[.*\]/g,"").split(`
`).map(o=>o.trim()),i=Math.max(0,a);for(let o=s.length-1;o>=0;o--){let l=o*r.lineHeight+n;r.shadowColor&&r.shadowColor!==""&&(e.fillStyle=r.shadowColor,e.fillText(s[o],i+5,l+16)),e.fillStyle=r.labelColor,e.fillText(s[o],i+4,l+15)}}function Nr(e,t,a,n,r){e.fillStyle=To(n,r),e.beginPath(),e.arc(t,a,r.pointSize,0,2*Math.PI),e.fill()}function sr(e,t,a,n,r,s){if(e.beginPath(),e.lineWidth=s.lineWidth,s.useCurves){let i=(t+t+n)/2,o=(a+a+r)/2;e.ellipse(i,o,n/2,r/2,0,0,2*Math.PI)}else e.moveTo(t+s.roundRect,a),e.lineTo(t+n-s.roundRect,a),e.quadraticCurveTo(t+n,a,t+n,a+s.roundRect),e.lineTo(t+n,a+r-s.roundRect),e.quadraticCurveTo(t+n,a+r,t+n-s.roundRect,a+r),e.lineTo(t+s.roundRect,a+r),e.quadraticCurveTo(t,a+r,t,a+r-s.roundRect),e.lineTo(t,a+s.roundRect),e.quadraticCurveTo(t,a,t+s.roundRect,a),e.closePath();e.stroke()}function K3(e,t,a){if(!(t.length<2)){e.beginPath(),e.moveTo(t[0][0],t[0][1]);for(let n of t)e.strokeStyle=To(n[2]||0,a),e.lineTo(Math.trunc(n[0]),Math.trunc(n[1]));e.stroke(),a.fillPolygons&&(e.closePath(),e.fill())}}function f9(e,t,a){if(!(t.length<2)){if(e.lineWidth=a.lineWidth,!a.useCurves||t.length<=2){K3(e,t,a);return}e.moveTo(t[0][0],t[0][1]);for(let n=0;n<t.length-2;n++){let r=(t[n][0]+t[n+1][0])/2,s=(t[n][1]+t[n+1][1])/2;e.quadraticCurveTo(t[n][0],t[n][1],r,s)}e.quadraticCurveTo(t[t.length-2][0],t[t.length-2][1],t[t.length-1][0],t[t.length-1][1]),e.stroke(),a.fillPolygons&&(e.closePath(),e.fill())}}function Z3(e,t,a,n=5){let r,s,i;e.beginPath(),e.moveTo(t[0],t[1]),e.lineTo(a[0],a[1]),r=Math.atan2(a[1]-t[1],a[0]-t[0]),s=n*Math.cos(r)+a[0],i=n*Math.sin(r)+a[1],e.moveTo(s,i),r+=1/3*(2*Math.PI),s=n*Math.cos(r)+a[0],i=n*Math.sin(r)+a[1],e.lineTo(s,i),r+=1/3*(2*Math.PI),s=n*Math.cos(r)+a[0],i=n*Math.sin(r)+a[1],e.lineTo(s,i),e.closePath(),e.stroke(),e.fill()}var $t={color:"rgba(173, 216, 230, 0.6)",labelColor:"rgba(173, 216, 230, 1)",shadowColor:"black",alpha:.5,font:'small-caps 16px "Segoe UI"',lineHeight:18,lineWidth:4,pointSize:2,roundRect:8,drawPoints:!1,drawLabels:!0,drawBoxes:!0,drawAttention:!0,drawGestures:!0,drawPolygons:!0,drawGaze:!0,fillPolygons:!1,useDepth:!0,useCurves:!1,faceLabels:"",bodyLabels:"",bodyPartLabels:"",objectLabels:"",handLabels:"",fingerLabels:"",gestureLabels:""};var Rn={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]},Y3={count:468,mouth:13,symmetryLine:[13,Rn.midwayBetweenEyes[0]]},Co={leftEye:0,rightEye:1,nose:2,mouth:3,leftEar:4,rightEar:5,symmetryLine:[3,2]},J3=[{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]}],kp=[[.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]],No=[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 wce=[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],kce=[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],Ice=[33,133,362,263,1,78,308],R2e=wce.map(e=>kp[e]),M2e=kce.map(e=>kp[e]),$2e=Ice.map(e=>kp[e]);function ds(e){let t=e.map(a=>a[0]);return t.push(e[e.length-1][1]),t}var Sce=[[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]],Tce=[[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]],Cce=[[276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]],Nce=[[474,475],[475,476],[476,477],[477,474]],Ece=[[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]],Rce=[[46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]],Mce=[[469,470],[470,471],[471,472],[472,469]],$ce=[[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]],_2e={lips:ds(Sce),leftEye:ds(Tce),leftEyebrow:ds(Cce),leftIris:ds(Nce),rightEye:ds(Ece),rightEyebrow:ds(Rce),rightIris:ds(Mce),faceOval:ds($ce)};var _ce=[[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]],Pce=[[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]],Fce=[[276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]],Oce=[[474,475],[475,476],[476,477],[477,474]],Dce=[[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]],zce=[[46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]],Lce=[[469,470],[470,471],[471,472],[472,469]],Bce=[[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 ps(e){let t=e.map(a=>a[0]);return t.push(e[e.length-1][1]),t}var Wce={lips:ps(_ce),leftEye:ps(Pce),leftEyebrow:ps(Fce),leftIris:ps(Oce),rightEye:ps(Dce),rightEyebrow:ps(zce),rightIris:ps(Lce),faceOval:ps(Bce)},Vce=Object.entries(Wce).map(([e,t])=>t.map(a=>[a,e])).flat(),P2e=new Map(Vce),Ip=[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],Eo=[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],Ro=[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];var lt;function Uce(e,t){var n,r,s,i,o,l,u,p,c;if(!lt.drawLabels||((n=lt.faceLabels)==null?void 0:n.length)===0)return;let a=lt.faceLabels.slice();if(e.score&&(a=ct(a,"[score]",100*e.score)),e.gender&&(a=ct(a,"[gender]",e.gender)),e.genderScore&&(a=ct(a,"[genderScore]",100*e.genderScore)),e.age&&(a=ct(a,"[age]",e.age)),e.distance&&(a=ct(a,"[distance]",100*e.distance)),e.real&&(a=ct(a,"[real]",100*e.real)),e.live&&(a=ct(a,"[live]",100*e.live)),e.emotion&&e.emotion.length>0){let d=e.emotion.map(h=>`${Math.trunc(100*h.score)}% ${h.emotion}`);d.length>3&&(d.length=3),a=ct(a,"[emotions]",d.join(" "))}(s=(r=e.rotation)==null?void 0:r.angle)!=null&&s.roll&&(a=ct(a,"[roll]",So(e.rotation.angle.roll))),(o=(i=e.rotation)==null?void 0:i.angle)!=null&&o.yaw&&(a=ct(a,"[yaw]",So(e.rotation.angle.yaw))),(u=(l=e.rotation)==null?void 0:l.angle)!=null&&u.pitch&&(a=ct(a,"[pitch]",So(e.rotation.angle.pitch))),(c=(p=e.rotation)==null?void 0:p.gaze)!=null&&c.bearing&&(a=ct(a,"[gaze]",So(e.rotation.gaze.bearing))),En(t,a,e.box[0],e.box[1],lt)}function Gce(e,t){var a,n,r,s;if(((a=e.annotations)==null?void 0:a.leftEyeIris)&&((n=e.annotations)==null?void 0:n.leftEyeIris[0])){t.strokeStyle=lt.useDepth?"rgba(255, 200, 255, 0.3)":lt.color,t.beginPath();let i=Math.abs(e.annotations.leftEyeIris[3][0]-e.annotations.leftEyeIris[1][0])/2,o=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],i,o,0,0,2*Math.PI),t.stroke(),lt.fillPolygons&&(t.fillStyle=lt.useDepth?"rgba(255, 255, 200, 0.3)":lt.color,t.fill())}if(((r=e.annotations)==null?void 0:r.rightEyeIris)&&((s=e.annotations)==null?void 0:s.rightEyeIris[0])){t.strokeStyle=lt.useDepth?"rgba(255, 200, 255, 0.3)":lt.color,t.beginPath();let i=Math.abs(e.annotations.rightEyeIris[3][0]-e.annotations.rightEyeIris[1][0])/2,o=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],i,o,0,0,2*Math.PI),t.stroke(),lt.fillPolygons&&(t.fillStyle=lt.useDepth?"rgba(255, 255, 200, 0.3)":lt.color,t.fill())}}function Hce(e,t){var a;if(lt.drawGaze&&((a=e.rotation)==null?void 0:a.angle)&&typeof Path2D!="undefined"){t.strokeStyle="pink";let n=e.box[0]+e.box[2]/2-e.box[3]*So(e.rotation.angle.yaw)/90,r=e.box[1]+e.box[3]/2+e.box[2]*So(e.rotation.angle.pitch)/90,s=new Path2D(`
M ${e.box[0]+e.box[2]/2} ${e.box[1]}
C
${n} ${e.box[1]},
${n} ${e.box[1]+e.box[3]},
${e.box[0]+e.box[2]/2} ${e.box[1]+e.box[3]}
`),i=new Path2D(`
M ${e.box[0]} ${e.box[1]+e.box[3]/2}
C
${e.box[0]} ${r},
${e.box[0]+e.box[2]} ${r},
${e.box[0]+e.box[2]} ${e.box[1]+e.box[3]/2}
`);t.stroke(i),t.stroke(s)}}function jce(e,t){var a;if(lt.drawGaze&&((a=e.rotation)==null?void 0:a.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 n=[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]];Z3(t,[e.annotations.leftEyeIris[0][0],e.annotations.leftEyeIris[0][1]],[n[0],n[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]];Z3(t,[e.annotations.rightEyeIris[0][0],e.annotations.rightEyeIris[0][1]],[r[0],r[1]],4)}}function qce(e,t){if(lt.drawPolygons&&e.mesh.length>=468){t.lineWidth=1;for(let a=0;a<No.length/3;a++){let n=[No[a*3+0],No[a*3+1],No[a*3+2]].map(r=>e.mesh[r]);K3(t,n,lt)}Gce(e,t)}}function Xce(e,t){if(lt.drawPoints&&e.mesh.length>=468)for(let a=0;a<e.mesh.length;a++)Nr(t,e.mesh[a][0],e.mesh[a][1],e.mesh[a][2],lt),lt.drawAttention&&(Ip.includes(a)&&Nr(t,e.mesh[a][0],e.mesh[a][1],e.mesh[a][2]+127,lt),Eo.includes(a)&&Nr(t,e.mesh[a][0],e.mesh[a][1],e.mesh[a][2]-127,lt),Ro.includes(a)&&Nr(t,e.mesh[a][0],e.mesh[a][1],e.mesh[a][2]-127,lt))}function Kce(e,t){lt.drawBoxes&&sr(t,e.box[0],e.box[1],e.box[2],e.box[3],lt)}function e0(e,t,a){if(lt=Ct($t,a),!t||!e)return;let n=xn(e);if(!!n){n.font=lt.font,n.strokeStyle=lt.color,n.fillStyle=lt.color;for(let r of t)Kce(r,n),Uce(r,n),r.mesh&&r.mesh.length>0&&(Xce(r,n),qce(r,n),Hce(r,n),jce(r,n))}}function t0(e,t,a){var s,i;let n=Ct($t,a);if(!t||!e)return;let r=xn(e);if(!!r){r.lineJoin="round";for(let o=0;o<t.length;o++){if(r.strokeStyle=n.color,r.fillStyle=n.color,r.lineWidth=n.lineWidth,r.font=n.font,n.drawBoxes&&t[o].box&&t[o].box.length===4&&(sr(r,t[o].box[0],t[o].box[1],t[o].box[2],t[o].box[3],n),n.drawLabels&&((s=n.bodyLabels)==null?void 0:s.length)>0)){let l=n.bodyLabels.slice();l=ct(l,"[score]",100*t[o].score),En(r,l,t[o].box[0],t[o].box[1],n)}if(n.drawPoints&&t[o].keypoints)for(let l=0;l<t[o].keypoints.length;l++)!t[o].keypoints[l].score||t[o].keypoints[l].score===0||(r.fillStyle=To(t[o].keypoints[l].position[2],n),Nr(r,t[o].keypoints[l].position[0],t[o].keypoints[l].position[1],0,n));if(n.drawLabels&&((i=n.bodyPartLabels)==null?void 0:i.length)>0&&t[o].keypoints){r.font=n.font;for(let l of t[o].keypoints){if(!l.score||l.score===0)continue;let u=n.bodyPartLabels.slice();u=ct(u,"[label]",l.part),u=ct(u,"[score]",100*l.score),En(r,u,l.position[0],l.position[1],n)}}if(n.drawPolygons&&t[o].keypoints&&t[o].annotations)for(let l of Object.values(t[o].annotations))for(let u of l)f9(r,u,n)}}}function a0(e,t,a){var s,i;let n=Ct($t,a);if(!t||!e)return;let r=xn(e);if(!!r){r.lineJoin="round",r.font=n.font;for(let o of t){if(n.drawBoxes){if(r.strokeStyle=n.color,r.fillStyle=n.color,sr(r,o.box[0],o.box[1],o.box[2],o.box[3],n),n.drawLabels&&((s=n.handLabels)==null?void 0:s.length)>0){let l=n.handLabels.slice();l=ct(l,"[label]",o.label),l=ct(l,"[score]",100*o.score),En(r,l,o.box[0],o.box[1],n)}r.stroke()}if(n.drawPoints&&o.keypoints&&o.keypoints.length>0)for(let l of o.keypoints)r.fillStyle=To(l[2],n),Nr(r,l[0],l[1],0,n);if(n.drawLabels&&o.annotations&&((i=n.fingerLabels)==null?void 0:i.length)>0)for(let[l,u]of Object.entries(o.annotations)){let p=n.fingerLabels.slice();p=ct(p,"[label]",l),En(r,p,u[u.length-1][0],u[u.length-1][1],n)}if(n.drawPolygons&&o.annotations){let l=u=>{if(!(!u||u.length===0||!u[0]))for(let p=0;p<u.length;p++){r.beginPath();let c=u[p][2]||0;r.strokeStyle=To(p*c,n),r.moveTo(u[p>0?p-1:0][0],u[p>0?p-1:0][1]),r.lineTo(u[p][0],u[p][1]),r.stroke()}};r.lineWidth=n.lineWidth,l(o.annotations.index),l(o.annotations.middle),l(o.annotations.ring),l(o.annotations.pinky),l(o.annotations.thumb)}}}}function n0(e,t,a){var s;let n=Ct($t,a);if(!t||!e)return;let r=xn(e);if(!!r){r.lineJoin="round",r.font=n.font;for(let i of t)if(n.drawBoxes){if(r.strokeStyle=n.color,r.fillStyle=n.color,sr(r,i.box[0],i.box[1],i.box[2],i.box[3],n),n.drawLabels&&((s=n.objectLabels)==null?void 0:s.length)>0){let o=n.objectLabels.slice();o=ct(o,"[label]",i.label),o=ct(o,"[score]",100*i.score),En(r,o,i.box[0],i.box[1],n)}r.stroke()}}}function r0(e,t,a){var r;let n=Ct($t,a);if(!(!t||!e)&&n.drawGestures&&((r=n.gestureLabels)==null?void 0:r.length)>0){let s=xn(e);if(!s)return;s.font=n.font,s.fillStyle=n.color;let i=1;for(let o=0;o<t.length;o++){let[l,u]=Object.entries(t[o]);if(u.length>1&&u[1].length>0){let p=l[1]>0?`#${l[1]}`:"",c=n.gestureLabels.slice();c=ct(c,"[where]",l[0]),c=ct(c,"[who]",p),c=ct(c,"[what]",u[1]),En(s,c,8,2+i*n.lineHeight,n),i+=1}}}}var cs={face:`face
confidence: [score]%
[gender] [genderScore]%
age: [age] years
distance: [distance]cm
real: [real]%
live: [live]%
[emotions]
roll: [roll]\xB0 yaw:[yaw]\xB0 pitch:[pitch]\xB0
gaze: [gaze]\xB0`,body:"body [score]%",bodyPart:"[label] [score]%",object:"[label] [score]%",hand:"[label] [score]%",finger:"[label]",gesture:"[where] [who]: [what]"};var eg=0;function Zce(e,t,a){let n=Ct($t,a);if(!t||!e)return;let r=xn(e);if(!!r){r.lineJoin="round",r.font=n.font;for(let s=0;s<t.length;s++)if(n.drawBoxes){if(r.strokeStyle=n.color,r.fillStyle=n.color,sr(r,t[s].box[0],t[s].box[1],t[s].box[2],t[s].box[3],n),n.drawLabels){let i=`person #${s}`;n.shadowColor&&n.shadowColor!==""&&(r.fillStyle=n.shadowColor,r.fillText(i,t[s].box[0]+3,1+t[s].box[1]+n.lineHeight,t[s].box[2])),r.fillStyle=n.labelColor,r.fillText(i,t[s].box[0]+2,0+t[s].box[1]+n.lineHeight,t[s].box[2])}r.stroke()}}}function Yce(e,t){if(!e||!t)return;let a=xn(t);!a||a.drawImage(e,0,0)}async function Jce(e,t,a){if(!(t!=null&&t.performance)||!e)return null;let n=te(),r=Ct($t,a),s=Promise.all([e0(e,t.face,r),t0(e,t.body,r),a0(e,t.hand,r),n0(e,t.object,r),r0(e,t.gesture,r)]);return eg=ne.perfadd?eg+Math.round(te()-n):Math.round(te()-n),t.performance.draw=eg,s}function tg(){$t.faceLabels=cs.face,$t.bodyLabels=cs.body,$t.bodyPartLabels=cs.bodyPart,$t.handLabels=cs.hand,$t.fingerLabels=cs.finger,$t.objectLabels=cs.object,$t.gestureLabels=cs.gesture}var i0={};hr(i0,{connected:()=>ng,kpt:()=>ag});var ag=["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"],ng={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 An,Mo=224,x9,Qce=5,o0=[8,16,32,32,32];function ehe(){let e=[],t=0;for(;t<Qce;){let a=0,n=t;for(;n<o0.length&&o0[n]===o0[t];)a+=2,n++;let r=o0[t],s=Math.ceil(Mo/r),i=Math.ceil(Mo/r);for(let o=0;o<s;++o)for(let l=0;l<i;++l)for(let u=0;u<a;++u)e.push({x:(l+.5)/i,y:(o+.5)/s});t=n}x9={x:Ht(e.map(a=>a.x)),y:Ht(e.map(a=>a.y))}}async function A9(e){if(ne.initial&&(An=null),!An&&e.body.detector&&e.body.detector.modelPath){An=await Ee(e.body.detector.modelPath);let t=An!=null&&An.executor?Object.values(An.modelSignature.inputs):void 0;Mo=Array.isArray(t)?parseInt(t[0].tensorShape.dim[1].size):0}else e.debug&&An&&K("cached model:",An.modelUrl);return ehe(),An}var g9=[5,5];function the(e,t){return $e(()=>{let a=ka(e,12,1),n=_e(a[0]),r=_e(a[1]),s=_e(a[2]),i=_e(a[3]);n=be(me(n,Mo),t.x),r=be(me(r,Mo),t.y),s=ae(me(s,Mo),g9[0]),i=ae(me(i,Mo),g9[1]);let o=fe(n,me(s,2)),l=fe(r,me(i,2)),u=be(o,s),p=be(l,i);return sa([o,l,u,p],1)})}async function ahe(e,t,a,n){var u,p;let r=[],s={};s.boxes=the(e,x9),s.scores=Da(t),s.nms=await ge.nonMaxSuppressionAsync(s.boxes,s.scores,1,((u=a.body.detector)==null?void 0:u.minConfidence)||.1,((p=a.body.detector)==null?void 0:p.iouThreshold)||.1);let i=await s.nms.data(),o=await s.scores.data(),l=await s.boxes.array();for(let c of Array.from(i)){let d=o[c],h=l[c],f=[Math.round(h[0]*n[0]),Math.round(h[1]*n[1]),Math.round(h[2]*n[0]),Math.round(h[3]*n[1])],m={score:d,boxRaw:h,box:f};r.push(m)}return Object.keys(s).forEach(c=>Y(s[c])),r}async function y9(e,t,a){let n={};n.res=An==null?void 0:An.execute(e,["Identity"]),n.logitsRaw=Pe(n.res,[0,0,0],[1,-1,1]),n.boxesRaw=Pe(n.res,[0,0,1],[1,-1,-1]),n.logits=_e(n.logitsRaw),n.boxes=_e(n.boxesRaw);let r=await ahe(n.boxes,n.logits,t,a);return Object.keys(n).forEach(s=>Y(n[s])),r}function Er(e,t=[1,1]){let a=[e.map(o=>o[0]),e.map(o=>o[1])],n=[Math.min(...a[0]),Math.min(...a[1])],r=[Math.max(...a[0]),Math.max(...a[1])],s=[n[0],n[1],r[0]-n[0],r[1]-n[1]],i=[s[0]/t[0],s[1]/t[1],s[2]/t[0],s[3]/t[1]];return{box:s,boxRaw:i}}function b9(e,t=[1,1]){let a=[e.map(u=>u[0]),e.map(u=>u[1])],n=[Math.min(...a[0]),Math.min(...a[1])],r=[Math.max(...a[0]),Math.max(...a[1])],s=[(n[0]+r[0])/2,(n[1]+r[1])/2],i=Math.max(s[0]-n[0],s[1]-n[1],-s[0]+r[0],-s[1]+r[1]),o=[Math.trunc(s[0]-i),Math.trunc(s[1]-i),Math.trunc(2*i),Math.trunc(2*i)],l=[o[0]/t[0],o[1]/t[1],o[2]/t[0],o[3]/t[1]];return{box:o,boxRaw:l}}function l0(e,t){let a=[e[2]*t,e[3]*t];return[e[0]-(a[0]-e[2])/2,e[1]-(a[1]-e[3])/2,a[0],a[1]]}var Ba,sg=256,rg=Number.MAX_SAFE_INTEGER,nhe={landmarks:["ld_3d","activation_segmentation","activation_heatmap","world_3d","output_poseflag"],detector:[]},d0=[],hs=[[0,0],[0,0],[0,0],[0,0]],v9=0,w9=e=>1-1/(1+Math.exp(e)),I9=e=>A9(e);async function S9(e){if(ne.initial&&(Ba=null),Ba)e.debug&&K("cached model:",Ba.modelUrl);else{Ba=await Ee(e.body.modelPath);let t=Ba!=null&&Ba.executor?Object.values(Ba.modelSignature.inputs):void 0;sg=Array.isArray(t)?parseInt(t[0].tensorShape.dim[1].size):0}return Ba}function k9(e,t,a){var s,i;let n={};if(!((s=e==null?void 0:e.shape)!=null&&s[1])||!((i=e==null?void 0:e.shape)!=null&&i[2]))return e;let r;if(a&&(n.cropped=ge.cropAndResize(e,[a],[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],l=[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];hs=[[0,0],o,l,[0,0]],n.pad=rr(n.cropped||e,hs),n.resize=ge.resizeBilinear(n.pad,[t,t]),r=me(n.resize,ze.tf255)}else e.shape[1]!==t?(n.resize=ge.resizeBilinear(n.cropped||e,[t,t]),r=me(n.resize,ze.tf255)):r=me(n.cropped||e,ze.tf255);return Object.keys(n).forEach(o=>Y(n[o])),r}function rhe(e,t,a){for(let n of e)n.position=[Math.trunc(n.position[0]*(t[0]+hs[2][0]+hs[2][1])/t[0]-hs[2][0]),Math.trunc(n.position[1]*(t[1]+hs[1][0]+hs[1][1])/t[1]-hs[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(a){let n=a[2]-a[0],r=a[3]-a[1];for(let s of e)s.positionRaw=[s.positionRaw[0]/r+a[1],s.positionRaw[1]/n+a[0],s.positionRaw[2]],s.position=[Math.trunc(s.positionRaw[0]*t[0]),Math.trunc(s.positionRaw[1]*t[1]),s.positionRaw[2]]}return e}function she(e){let t=e.find(o=>o.part==="leftPalm"),a=e.find(o=>o.part==="leftWrist"),n=e.find(o=>o.part==="leftIndex");t.position[2]=((a.position[2]||0)+(n.position[2]||0))/2;let r=e.find(o=>o.part==="rightPalm"),s=e.find(o=>o.part==="rightWrist"),i=e.find(o=>o.part==="rightIndex");r.position[2]=((s.position[2]||0)+(i.position[2]||0))/2}async function ihe(e,t,a){if(!(Ba!=null&&Ba.executor))return null;let n={};[n.ld,n.segmentation,n.heatmap,n.world,n.poseflag]=Ba==null?void 0:Ba.execute(e,nhe.landmarks);let r=(await n.poseflag.data())[0],s=await n.ld.data(),i=await n.world.data();Object.keys(n).forEach(f=>Y(n[f]));let o=[],l=5;for(let f=0;f<s.length/l;f++){let m=w9(s[l*f+3]),g=w9(s[l*f+4]),x=Math.trunc(100*m*g*r)/100,A=[s[l*f+0]/sg,s[l*f+1]/sg,s[l*f+2]+0],y=[Math.trunc(a[0]*A[0]),Math.trunc(a[1]*A[1]),A[2]],b=[i[l*f+0],i[l*f+1],i[l*f+2]+0];o.push({part:ag[f],positionRaw:A,position:y,distance:b,score:x})}if(r<(t.body.minConfidence||0))return null;she(o);let u=rhe(o,a),p=u.map(f=>f.position),c=Er(p,[a[0],a[1]]),d={};for(let[f,m]of Object.entries(ng)){let g=[];for(let x=0;x<m.length-1;x++){let A=u.find(b=>b.part===m[x]),y=u.find(b=>b.part===m[x+1]);A&&y&&g.push([A.position,y.position])}d[f]=g}return{id:0,score:Math.trunc(100*r)/100,box:c.box,boxRaw:c.boxRaw,keypoints:u,annotations:d}}async function ig(e,t){var s,i,o;let a=[e.shape[2]||0,e.shape[1]||0],n=(t.body.skipTime||0)>te()-v9,r=rg<(t.body.skipFrames||0);if(t.skipAllowed&&n&&r&&d0!==null)rg++;else{let l=[];if((i=(s=t.body)==null?void 0:s.detector)!=null&&i.enabled){let u=k9(e,224);l=await y9(u,t,a),Y(u)}else l=[{box:[0,0,0,0],boxRaw:[0,0,1,1],score:0}];for(let u=0;u<l.length;u++){let p=k9(e,256,(o=l[u])==null?void 0:o.boxRaw);d0.length=0;let c=await ihe(p,t,a);Y(p),c&&(c.id=u,d0.push(c))}v9=te(),rg=0}return d0}var bu=[{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 Wa,$o=0,og=[],C9=0,lg=Number.MAX_SAFE_INTEGER;async function N9(e){if(ne.initial&&(Wa=null),Wa)e.debug&&K("cached model:",Wa.modelUrl);else{Wa=await Ee(e.object.modelPath);let t=Wa!=null&&Wa.executor?Object.values(Wa.modelSignature.inputs):void 0;$o=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}return Wa}async function ohe(e,t,a){if(!e)return[];let n={},r=[],s=await e.array();n.squeeze=_e(e);let i=ka(n.squeeze,6,1);n.stack=sa([i[1],i[0],i[3],i[2]],1),n.boxes=_e(n.stack),n.scores=_e(i[4]),n.classes=_e(i[5]),Y([e,...i]),n.nms=await ge.nonMaxSuppressionAsync(n.boxes,n.scores,a.object.maxDetected||0,a.object.iouThreshold,a.object.minConfidence||0);let o=await n.nms.data(),l=0;for(let u of Array.from(o)){let p=Math.trunc(100*s[0][u][4])/100,c=s[0][u][5];if(Number.isNaN(c))continue;let d=bu[c].label,[h,f]=[s[0][u][0]/$o,s[0][u][1]/$o],m=[h,f,s[0][u][2]/$o-h,s[0][u][3]/$o-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:p,class:c,label:d,box:g,boxRaw:m})}return Object.keys(n).forEach(u=>Y(n[u])),r}async function ug(e,t){if(!(Wa!=null&&Wa.executor))return[];let a=(t.object.skipTime||0)>te()-C9,n=lg<(t.object.skipFrames||0);return t.skipAllowed&&a&&n&&og.length>0?(lg++,og):(lg=0,new Promise(async r=>{let s=[e.shape[2]||0,e.shape[1]||0],i=ge.resizeBilinear(e,[$o,$o]),o=t.object.enabled?Wa==null?void 0:Wa.execute(i,["tower_0/detections"]):null;C9=te(),Y(i);let l=await ohe(o,s,t);og=l,r(l)}))}var p0={};hr(p0,{connected:()=>pg,kpt:()=>dg});var dg=["head","neck","rightShoulder","rightElbow","rightWrist","chest","leftShoulder","leftElbow","leftWrist","bodyCenter","rightHip","rightKnee","rightAnkle","leftHip","leftKnee","leftAnkle"],pg={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var Nt,R9=0,Ra={id:0,keypoints:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,annotations:{}},cg=Number.MAX_SAFE_INTEGER;async function M9(e){return ne.initial&&(Nt=null),Nt?e.debug&&K("cached model:",Nt.modelUrl):Nt=await Ee(e.body.modelPath),Nt}async function lhe(e,t){let[a,n]=e.shape,r=J(e,[n*a]),s=pa(r,0),i=(await s.data())[0];if(i>t){let o=ar(r,0),l=su(o,a),u=(await l.data())[0],p=me(o,a),c=(await p.data())[0];return Y([r,s,o,l,p]),[u,c,i]}return Y([r,s]),[0,0,i]}async function hg(e,t){if(!(Nt!=null&&Nt.executor)||!(Nt!=null&&Nt.inputs[0].shape))return[];let a=(t.body.skipTime||0)>te()-R9,n=cg<(t.body.skipFrames||0);return t.skipAllowed&&a&&n&&Object.keys(Ra.keypoints).length>0?(cg++,[Ra]):(cg=0,new Promise(async r=>{let s=$e(()=>{var f,m;let c=ge.resizeBilinear(e,[((f=Nt==null?void 0:Nt.inputs[0].shape)==null?void 0:f[2])||0,((m=Nt==null?void 0:Nt.inputs[0].shape)==null?void 0:m[1])||0],!1),d=ae(c,ze.tf2);return fe(d,ze.tf1)}),i;if(t.body.enabled&&(i=Nt==null?void 0:Nt.execute(s)),R9=te(),Y(s),i){Ra.keypoints.length=0;let c=_e(i);Y(i);let d=Ta(c,2);Y(c);for(let h=0;h<d.length;h++){let[f,m,g]=await lhe(d[h],t.body.minConfidence);g>(t.body.minConfidence||0)&&Ra.keypoints.push({score:Math.round(100*g)/100,part:dg[h],positionRaw:[f/Nt.inputs[0].shape[2],m/Nt.inputs[0].shape[1]],position:[Math.round(e.shape[2]*f/Nt.inputs[0].shape[2]),Math.round(e.shape[1]*m/Nt.inputs[0].shape[1])]})}d.forEach(h=>Y(h))}Ra.score=Ra.keypoints.reduce((c,d)=>d.score>c?d.score:c,0);let o=Ra.keypoints.map(c=>c.position[0]),l=Ra.keypoints.map(c=>c.position[1]);Ra.box=[Math.min(...o),Math.min(...l),Math.max(...o)-Math.min(...o),Math.max(...l)-Math.min(...l)];let u=Ra.keypoints.map(c=>c.positionRaw[0]),p=Ra.keypoints.map(c=>c.positionRaw[1]);Ra.boxRaw=[Math.min(...u),Math.min(...p),Math.max(...u)-Math.min(...u),Math.max(...p)-Math.min(...p)];for(let[c,d]of Object.entries(pg)){let h=[];for(let f=0;f<d.length-1;f++){let m=Ra.keypoints.find(x=>x.part===d[f]),g=Ra.keypoints.find(x=>x.part===d[f+1]);m&&g&&m.score>(t.body.minConfidence||0)&&g.score>(t.body.minConfidence||0)&&h.push([m.position,g.position])}Ra.annotations[c]=h}r([Ra])}))}var vu=e=>[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])],c0=e=>[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2,1],h0=(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],f0=(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],F9=(e,t)=>{let a=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],n=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]];return{startPoint:a,endPoint:n,landmarks:e.landmarks,confidence:e.confidence}},fg=(e,t,a)=>{let n=t.shape[1],r=t.shape[2],s=[e.startPoint[1]/n,e.startPoint[0]/r,e.endPoint[1]/n,e.endPoint[0]/r],i=ge.cropAndResize(t,[s],[0],a),o=me(i,ze.tf255);return Y(i),o},m0=(e,t)=>{let a=c0(e),n=vu(e),r=[t*n[0]/2,t*n[1]/2];return{startPoint:[a[0]-r[0],a[1]-r[1]],endPoint:[a[0]+r[0],a[1]+r[1]],landmarks:e.landmarks,confidence:e.confidence}},g0=e=>{let t=c0(e),a=vu(e),n=Math.max(...a)/2;return{startPoint:[Math.round(t[0]-n),Math.round(t[1]-n)],endPoint:[Math.round(t[0]+n),Math.round(t[1]+n)],landmarks:e.landmarks,confidence:e.confidence}},O9=e=>{let t=e.map(n=>n[0]),a=e.map(n=>n[1]);return{startPoint:[Math.min(...t),Math.min(...a)],endPoint:[Math.max(...t),Math.max(...a)],landmarks:e}},mg=[[1,0,0],[0,1,0],[0,0,1]],uhe=e=>e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI)),dhe=(e,t)=>uhe(Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]));var _9=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]],_o=(e,t)=>{let a=0;for(let n=0;n<e.length;n++)a+=e[n]*t[n];return a},phe=(e,t)=>{let a=[];for(let n=0;n<e.length;n++)a.push(e[n][t]);return a},P9=(e,t)=>{let a=[],n=e.length;for(let r=0;r<n;r++){a.push([]);for(let s=0;s<n;s++)a[r].push(_o(e[r],phe(t,s)))}return a},D9=(e,t)=>{let a=Math.cos(e),n=Math.sin(e),r=[[a,-n,0],[n,a,0],[0,0,1]],s=_9(t[0],t[1]),i=P9(s,r),o=_9(-t[0],-t[1]);return P9(i,o)},che=e=>{let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],a=[e[0][2],e[1][2]],n=[-_o(t[0],a),-_o(t[1],a)];return[t[0].concat(n[0]),t[1].concat(n[1]),[0,0,1]]},hhe=(e,t)=>[_o(e,t[0]),_o(e,t[1])];function z9(e){let t=e===192?{strides:[4],anchors:[1]}:{strides:[e/16,e/8],anchors:[2,6]},a=[];for(let n=0;n<t.strides.length;n++){let r=t.strides[n],s=Math.floor((e+r-1)/r),i=Math.floor((e+r-1)/r),o=t.anchors[n];for(let l=0;l<s;l++){let u=r*(l+.5);for(let p=0;p<i;p++){let c=r*(p+.5);for(let d=0;d<o;d++)a.push([c,u])}}}return a}function L9(e,t,a,n,r){let s=vu(t),i=e.map(h=>[s[0]/r*(h[0]-r/2),s[1]/r*(h[1]-r/2),h[2]||0]),o=a&&a!==0&&Math.abs(a)>.2,l=o?D9(a,[0,0]):mg,u=o?i.map(h=>[...hhe(h,l),h[2]]):i,p=o?che(n):mg,c=c0(t),d=[_o(c,p[0]),_o(c,p[1])];return u.map(h=>[Math.trunc(h[0]+d[0]),Math.trunc(h[1]+d[1]),Math.trunc(h[2]||0)])}function B9(e,t,a,n){let r=t.landmarks.length>=Y3.count?Y3.symmetryLine:Co.symmetryLine,s=0,i=mg,o;if(e&&ne.kernels.includes("rotatewithoffset"))if(s=dhe(t.landmarks[r[0]],t.landmarks[r[1]]),s&&s!==0&&Math.abs(s)>.2){let u=c0(t),p=[u[0]/a.shape[2],u[1]/a.shape[1]],c=ge.rotateWithOffset(a,s,0,[p[0],p[1]]);i=D9(-s,u),o=fg(t,c,[n,n]),Y(c)}else o=fg(t,a,[n,n]);else o=fg(t,a,[n,n]);return[s,i,o]}var fhe=e=>{let t=e.map(n=>n[0]),a=e.map(n=>n[1]);return[Math.min(...t)+(Math.max(...t)-Math.min(...t))/2,Math.min(...a)+(Math.max(...a)-Math.min(...a))/2]},W9=(e,t)=>{let a=fhe(e),n=vu(t);return{startPoint:[a[0]-n[0]/2,a[1]-n[1]/2],endPoint:[a[0]+n[0]/2,a[1]+n[1]/2]}};var V9=6,mhe=1.4,Ln,xg=null,fs=0,wu=null,ku=()=>fs;async function U9(e){var t;return ne.initial&&(Ln=null),Ln?e.debug&&K("cached model:",Ln.modelUrl):Ln=await Ee((t=e.face.detector)==null?void 0:t.modelPath),fs=Ln.executor&&Ln.inputs[0].shape?Ln.inputs[0].shape[2]:256,wu=Fe(fs,"int32"),xg=Kn(z9(fs)),Ln}function ghe(e){if(!xg||!wu)return fn([0,0]);let t={};t.boxStarts=Pe(e,[0,1],[-1,2]),t.centers=be(t.boxStarts,xg),t.boxSizes=Pe(e,[0,3],[-1,2]),t.boxSizesNormalized=me(t.boxSizes,wu),t.centersNormalized=me(t.centers,wu),t.halfBoxSize=me(t.boxSizesNormalized,ze.tf2),t.starts=fe(t.centersNormalized,t.halfBoxSize),t.ends=be(t.centersNormalized,t.halfBoxSize),t.startNormalized=ae(t.starts,wu),t.endNormalized=ae(t.ends,wu);let a=ru([t.startNormalized,t.endNormalized],1);return Object.keys(t).forEach(n=>Y(t[n])),a}async function G9(e,t){var o,l,u,p;if(!e||e.isDisposedInternal||e.shape.length!==4||e.shape[1]<1||e.shape[2]<1)return[];let a={};a.resized=ge.resizeBilinear(e,[fs,fs]),a.div=me(a.resized,ze.tf127),a.normalized=fe(a.div,ze.tf05);let n=Ln==null?void 0:Ln.execute(a.normalized);if(Array.isArray(n)&&n.length>2){let c=n.sort((d,h)=>d.size-h.size);a.concat384=at([c[0],c[2]],2),a.concat512=at([c[1],c[3]],2),a.concat=at([a.concat512,a.concat384],1),a.batch=_e(a.concat,[0])}else Array.isArray(n)?a.batch=_e(n[0]):a.batch=_e(n);Y(n),a.boxes=ghe(a.batch),a.logits=Pe(a.batch,[0,0],[-1,1]),a.sigmoid=Da(a.logits),a.scores=_e(a.sigmoid),a.nms=await ge.nonMaxSuppressionAsync(a.boxes,a.scores,((o=t.face.detector)==null?void 0:o.maxDetected)||0,((l=t.face.detector)==null?void 0:l.iouThreshold)||0,((u=t.face.detector)==null?void 0:u.minConfidence)||0);let r=await a.nms.array(),s=[],i=await a.scores.data();for(let c=0;c<r.length;c++){let d=i[r[c]];if(d>(((p=t.face.detector)==null?void 0:p.minConfidence)||0)){let h={};h.bbox=Pe(a.boxes,[r[c],0],[1,-1]),h.slice=Pe(a.batch,[r[c],V9-1],[1,-1]),h.squeeze=_e(h.slice),h.landmarks=J(h.squeeze,[V9,-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=F9(m,[(e.shape[2]||0)/fs,(e.shape[1]||0)/fs]),x=m0(g,t.face.scale||mhe),A=g0(x);s.push(A),Object.keys(h).forEach(y=>Y(h[y]))}}return Object.keys(a).forEach(c=>Y(a[c])),s}var Qa,ms=0,xhe=2.3,Ag=Rn.leftEyeLower0,yg=Rn.rightEyeLower0,Iu={leftBounds:[Ag[0],Ag[Ag.length-1]],rightBounds:[yg[0],yg[yg.length-1]]},Su={upperCenter:3,lowerCenter:4,index:71,numCoordinates:76};async function K9(e){var t,a;return ne.initial&&(Qa=null),Qa?e.debug&&K("cached model:",Qa.modelUrl):Qa=await Ee((t=e.face.iris)==null?void 0:t.modelPath),ms=(Qa==null?void 0:Qa.executor)&&((a=Qa.inputs)==null?void 0:a[0].shape)?Qa.inputs[0].shape[2]:0,ms===-1&&(ms=64),Qa}function x0(e,t,a,n){for(let r=0;r<J3.length;r++){let{key:s,indices:i}=J3[r],o=Rn[`${a}${s}`];if(!n||n.includes(s))for(let l=0;l<i.length;l++){let u=i[l];e[o[l]]=[t[u][0],t[u][1],(t[u][2]+e[o[l]][2])/2]}}}var Ahe=e=>{let t=e[Iu.leftBounds[0]][2],a=e[Iu.rightBounds[0]][2];return t-a},j9=(e,t,a,n,r,s=!1)=>{let i=g0(m0(O9([e[a],e[n]]),xhe)),o=vu(i),l=ge.cropAndResize(t,[[i.startPoint[1]/r,i.startPoint[0]/r,i.endPoint[1]/r,i.endPoint[0]/r]],[0],[ms,ms]);if(s&&ne.kernels.includes("flipleftright")){let u=ge.flipLeftRight(l);Y(l),l=u}return{box:i,boxSize:o,crop:l}},q9=(e,t,a,n=!1)=>{let r=[];for(let s=0;s<Su.numCoordinates;s++){let i=e[s*3],o=e[s*3+1],l=e[s*3+2];r.push([(n?1-i/ms:i/ms)*a[0]+t.startPoint[0],o/ms*a[1]+t.startPoint[1],l])}return{rawCoords:r,iris:r.slice(Su.index)}},X9=(e,t,a)=>{let n=e[Rn[`${a}EyeUpper0`][Su.upperCenter]][2],r=e[Rn[`${a}EyeLower0`][Su.lowerCenter]][2],s=(n+r)/2;return t.map((i,o)=>{let l=s;return o===2?l=n:o===4&&(l=r),[i[0],i[1],l]})};async function Z9(e,t,a){if(!(Qa!=null&&Qa.executor))return e;let{box:n,boxSize:r,crop:s}=j9(e,t,Iu.leftBounds[0],Iu.leftBounds[1],a,!0),{box:i,boxSize:o,crop:l}=j9(e,t,Iu.rightBounds[0],Iu.rightBounds[1],a,!0),u=at([s,l]);Y(s),Y(l);let p=Qa.execute(u);Y(u);let c=await p.data();Y(p);let d=c.slice(0,Su.numCoordinates*3),{rawCoords:h,iris:f}=q9(d,n,r,!0),m=c.slice(Su.numCoordinates*3),{rawCoords:g,iris:x}=q9(m,i,o,!1),A=Ahe(e);Math.abs(A)<30?(x0(e,h,"left",null),x0(e,g,"right",null)):A<1?x0(e,h,"left",["EyeUpper0","EyeLower0"]):x0(e,g,"right",["EyeUpper0","EyeLower0"]);let y=X9(e,f,"left"),b=X9(e,x,"right");return e.concat(y).concat(b)}async function J9(e,t){var s,i,o,l,u,p,c,d,h,f;let a={lips:await((i=(s=t.filter(m=>m.size===160))==null?void 0:s[0])==null?void 0:i.data()),irisL:await((l=(o=t.filter(m=>m.size===10))==null?void 0:o[0])==null?void 0:l.data()),eyeL:await((p=(u=t.filter(m=>m.size===142))==null?void 0:u[0])==null?void 0:p.data()),irisR:await((d=(c=t.filter(m=>m.size===10))==null?void 0:c[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(a))if(!m)return e;let n=Eo.reduce((m,g)=>m+=e[g][2],0)/Eo.length;for(let m=0;m<a.irisL.length/2;m++)e.push([a.irisL[2*m+0],a.irisL[2*m+1],n]);let r=Ro.reduce((m,g)=>m+=e[g][2],0)/Ro.length;for(let m=0;m<a.irisR.length/2;m++)e.push([a.irisR[2*m+0],a.irisR[2*m+1],r]);for(let m=0;m<a.eyeL.length/2;m++)e[Eo[m]]=[a.eyeL[2*m+0],a.eyeL[2*m+1],e[Eo[m]][2]];for(let m=0;m<a.eyeR.length/2;m++)e[Ro[m]]=[a.eyeR[2*m+0],a.eyeR[2*m+1],e[Ro[m]][2]];for(let m=0;m<a.lips.length/2;m++)e[Ip[m]]=[a.lips[2*m+0],a.lips[2*m+1],e[Ip[m]][2]];return e}var ir={boxes:[],skipped:Number.MAX_SAFE_INTEGER,timestamp:0},wt=null,Sp=0;async function Q9(e,t){var l,u,p,c,d,h,f,m,g,x;if(!(wt!=null&&wt.executor))return[];let a=(((l=t.face.detector)==null?void 0:l.skipTime)||0)>te()-ir.timestamp,n=ir.skipped<(((u=t.face.detector)==null?void 0:u.skipFrames)||0);!t.skipAllowed||!a||!n||ir.boxes.length===0?(ir.boxes=await G9(e,t),ir.timestamp=te(),ir.skipped=0):ir.skipped++;let r=[],s=[],i=0,o=Sp;for(let A=0;A<ir.boxes.length;A++){let y=ir.boxes[A],b=0,w,S={id:i++,mesh:[],meshRaw:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,boxScore:0,faceScore:0,annotations:{}};if([b,w,S.tensor]=B9((p=t.face.detector)==null?void 0:p.rotation,y,e,(c=t.face.mesh)!=null&&c.enabled?Sp:ku()),t.filter.equalization){let C=S.tensor?await qh(S.tensor):void 0;Y(S.tensor),C&&(S.tensor=C)}if(S.boxScore=Math.round(100*y.confidence)/100,(d=t.face.mesh)!=null&&d.enabled)if(!wt)t.debug&&K("face mesh detection requested, but model is not loaded");else{if(((h=t.face.attention)==null?void 0:h.enabled)&&!ne.kernels.includes("atan2"))return t.face.attention.enabled=!1,Y(S.tensor),r;let C=wt.execute(S.tensor),_=await C.find($=>$.shape[$.shape.length-1]===1).data();if(S.faceScore=Math.round(100*_[0])/100,S.faceScore<(((f=t.face.detector)==null?void 0:f.minConfidence)||1)){if(y.confidence=S.faceScore,t.face.mesh.keepInvalid){S.box=h0(y,e),S.boxRaw=f0(y,e),S.score=S.boxScore,S.mesh=y.landmarks.map($=>[(y.startPoint[0]+y.endPoint[0])/2+(y.endPoint[0]+y.startPoint[0])*$[0]/ku(),(y.startPoint[1]+y.endPoint[1])/2+(y.endPoint[1]+y.startPoint[1])*$[1]/ku()]),S.meshRaw=S.mesh.map($=>[$[0]/(e.shape[2]||1),$[1]/(e.shape[1]||1),($[2]||0)/o]);for(let $ of Object.keys(Co))S.annotations[$]=[S.mesh[Co[$]]]}}else{let $=C.find(O=>O.shape[O.shape.length-1]===1404),M=J($,[-1,3]),I=await M.array();Y(M),(m=t.face.attention)!=null&&m.enabled?I=await J9(I,C):(g=t.face.iris)!=null&&g.enabled&&(I=await Z9(I,S.tensor,Sp)),S.mesh=L9(I,y,b,w,Sp),S.meshRaw=S.mesh.map(O=>[O[0]/(e.shape[2]||0),O[1]/(e.shape[1]||0),(O[2]||0)/o]);for(let O of Object.keys(Rn))S.annotations[O]=Rn[O].map(L=>S.mesh[L]);S.score=S.faceScore;let N={...W9(S.mesh,y),confidence:y.confidence,landmarks:y.landmarks};S.box=h0(N,e),S.boxRaw=f0(N,e),s.push(N)}Y(C)}else{S.box=h0(y,e),S.boxRaw=f0(y,e),S.score=S.boxScore,S.mesh=y.landmarks.map(C=>[(y.startPoint[0]+y.endPoint[0])/2+(y.endPoint[0]+y.startPoint[0])*C[0]/ku(),(y.startPoint[1]+y.endPoint[1])/2+(y.endPoint[1]+y.startPoint[1])*C[1]/ku()]),S.meshRaw=S.mesh.map(C=>[C[0]/(e.shape[2]||0),C[1]/(e.shape[1]||0),(C[2]||0)/o]);for(let C of Object.keys(Co))S.annotations[C]=[S.mesh[Co[C]]]}S.score>(((x=t.face.detector)==null?void 0:x.minConfidence)||1)?r.push(S):Y(S.tensor)}return ir.boxes=s,r}async function ew(e){var t,a,n,r,s,i;return ne.initial&&(wt=null),((t=e.face.attention)==null?void 0:t.enabled)&&(wt==null?void 0:wt.signature)&&Object.keys(((a=wt==null?void 0:wt.signature)==null?void 0:a.outputs)||{}).length<6&&(wt=null),wt?e.debug&&K("cached model:",wt.modelUrl):(n=e.face.attention)!=null&&n.enabled?wt=await Ee(e.face.attention.modelPath):wt=await Ee((r=e.face.mesh)==null?void 0:r.modelPath),Sp=wt.executor&&((s=wt==null?void 0:wt.inputs)==null?void 0:s[0].shape)?(i=wt==null?void 0:wt.inputs)==null?void 0:i[0].shape[2]:256,wt}var tw=No,aw=kp;var bhe=["angry","disgust","fear","happy","sad","surprise","neutral"],yn,A0=[],nw=0,rw=0,vg=Number.MAX_SAFE_INTEGER;async function sw(e){var t;return ne.initial&&(yn=null),yn?e.debug&&K("cached model:",yn.modelUrl):yn=await Ee((t=e.face.emotion)==null?void 0:t.modelPath),yn}async function wg(e,t,a,n){var i,o;if(!yn)return[];let r=vg<(((i=t.face.emotion)==null?void 0:i.skipFrames)||0),s=(((o=t.face.emotion)==null?void 0:o.skipTime)||0)>te()-rw;return t.skipAllowed&&s&&r&&nw===n&&A0[a]&&A0[a].length>0?(vg++,A0[a]):(vg=0,new Promise(async l=>{var p;let u=[];if((p=t.face.emotion)!=null&&p.enabled){let c={},d=yn!=null&&yn.inputs[0].shape?yn.inputs[0].shape[2]:0;c.resize=ge.resizeBilinear(e,[d,d],!1),c.channels=ae(c.resize,ze.rgb),c.grayscale=tt(c.channels,3,!0),c.grayscaleSub=fe(c.grayscale,ze.tf05),c.grayscaleMul=ae(c.grayscaleSub,ze.tf2),c.emotion=yn==null?void 0:yn.execute(c.grayscaleMul),rw=te();let h=await c.emotion.data();for(let f=0;f<h.length;f++)h[f]>(t.face.emotion.minConfidence||0)&&u.push({score:Math.min(.99,Math.trunc(100*h[f])/100),emotion:bhe[f]});u.sort((f,m)=>m.score-f.score),Object.keys(c).forEach(f=>Y(c[f]))}A0[a]=u,nw=n,l(u)}))}var fa,gs=[],ow=0,lw=0,kg=Number.MAX_SAFE_INTEGER;async function uw(e){var t;return ne.initial&&(fa=null),fa?e.debug&&K("cached model:",fa.modelUrl):fa=await Ee((t=e.face.description)==null?void 0:t.modelPath),fa}function vhe(e){let t=e.image||e.tensor||e;if(!(fa!=null&&fa.inputs[0].shape))return t;let a=ge.resizeBilinear(t,[fa.inputs[0].shape[2],fa.inputs[0].shape[1]],!1),n=ae(a,ze.tf255);return Y(a),n}async function Ig(e,t,a,n){var o,l,u,p;let r={age:0,gender:"unknown",genderScore:0,descriptor:[]};if(!(fa!=null&&fa.executor))return r;let s=kg<(((o=t.face.description)==null?void 0:o.skipFrames)||0),i=(((l=t.face.description)==null?void 0:l.skipTime)||0)>te()-ow;return t.skipAllowed&&s&&i&&lw===n&&((u=gs==null?void 0:gs[a])==null?void 0:u.age)>0&&((p=gs==null?void 0:gs[a])==null?void 0:p.genderScore)>0?(kg++,gs[a]):(kg=0,new Promise(async c=>{var d;if((d=t.face.description)!=null&&d.enabled){let h=vhe(e),f=fa==null?void 0:fa.execute(h);ow=te(),Y(h);let g=await f.find(E=>E.shape[1]===1).data(),x=Math.trunc(200*Math.abs(g[0]-.5))/100;x>(t.face.description.minConfidence||0)&&(r.gender=g[0]<=.5?"female":"male",r.genderScore=Math.min(.99,x));let A=ar(f.find(E=>E.shape[1]===100),1),y=(await A.data())[0];Y(A);let w=await f.find(E=>E.shape[1]===100).data();r.age=Math.round(w[y-1]>w[y+1]?10*y-100*w[y-1]:10*y+100*w[y+1])/10,(Number.isNaN(g[0])||Number.isNaN(w[0]))&&K("faceres error:",{model:fa,result:f});let S=f.find(E=>E.shape[1]===1024),C=S?await S.data():[];r.descriptor=Array.from(C),f.forEach(E=>Y(E))}gs[a]=r,lw=n,c(r)}))}var Tu=.1,Sg=.5;function whe(e,t,a){let n=!1,r=a.length-1;for(let s=0;s<a.length;r=s++)a[s].y>t!=a[r].y>t&&e<(a[r].x-a[s].x)*(t-a[s].y)/(a[r].y-a[s].y)+a[s].x&&(n=!n);return n}async function pw(e){if(!e.tensor||!e.mesh||e.mesh.length<100)return e.tensor;let t=e.tensor.shape[2]||0,a=e.tensor.shape[1]||0,n=await e.tensor.buffer(),r=[];for(let i of Rn.silhouette)r.push({x:(e.mesh[i][0]-e.box[0])/e.box[2],y:(e.mesh[i][1]-e.box[1])/e.box[3]});Tu&&Tu>0&&(r=r.map(i=>({x:i.x>.5?i.x+Tu:i.x-Tu,y:i.y>.5?i.y+Tu:i.y-Tu})));for(let i=0;i<t;i++)for(let o=0;o<a;o++)whe(i/t,o/t,r)||(n.set(Sg*n.get(0,o,i,0),0,o,i,0),n.set(Sg*n.get(0,o,i,1),0,o,i,1),n.set(Sg*n.get(0,o,i,2),0,o,i,2));return n.toTensor()}var ea,y0=[],Tg=Number.MAX_SAFE_INTEGER,cw=0,hw=0;async function fw(e){var t;return ne.initial&&(ea=null),ea?e.debug&&K("cached model:",ea.modelUrl):ea=await Ee((t=e.face.antispoof)==null?void 0:t.modelPath),ea}async function Cg(e,t,a,n){var i,o;if(!(ea!=null&&ea.executor))return 0;let r=(((i=t.face.antispoof)==null?void 0:i.skipTime)||0)>te()-hw,s=Tg<(((o=t.face.antispoof)==null?void 0:o.skipFrames)||0);return t.skipAllowed&&r&&s&&cw===n&&y0[a]?(Tg++,y0[a]):(Tg=0,new Promise(async l=>{let u=ge.resizeBilinear(e,[ea!=null&&ea.inputs[0].shape?ea.inputs[0].shape[2]:0,ea!=null&&ea.inputs[0].shape?ea.inputs[0].shape[1]:0],!1),p=ea==null?void 0:ea.execute(u),c=(await p.data())[0];y0[a]=Math.round(100*c)/100,cw=n,hw=te(),Y([u,p]),l(y0[a])}))}var ta,b0=[],Ng=Number.MAX_SAFE_INTEGER,gw=0,xw=0;async function Aw(e){var t;return ne.initial&&(ta=null),ta?e.debug&&K("cached model:",ta.modelUrl):ta=await Ee((t=e.face.liveness)==null?void 0:t.modelPath),ta}async function Eg(e,t,a,n){var i,o;if(!(ta!=null&&ta.executor))return 0;let r=(((i=t.face.liveness)==null?void 0:i.skipTime)||0)>te()-xw,s=Ng<(((o=t.face.liveness)==null?void 0:o.skipFrames)||0);return t.skipAllowed&&r&&s&&gw===n&&b0[a]?(Ng++,b0[a]):(Ng=0,new Promise(async l=>{let u=ge.resizeBilinear(e,[ta!=null&&ta.inputs[0].shape?ta.inputs[0].shape[2]:0,ta!=null&&ta.inputs[0].shape?ta.inputs[0].shape[1]:0],!1),p=ta==null?void 0:ta.execute(u),c=(await p.data())[0];b0[a]=Math.round(100*c)/100,gw=n,xw=te(),Y([u,p]),l(b0[a])}))}var Mn,Rg=[],Ihe=["white","black","asian","indian","other"],She=[15,23,28,35.5,45.5,55.5,65],bw=0,vw=0,Mg=Number.MAX_SAFE_INTEGER;async function ww(e){var t;return ne.initial&&(Mn=null),Mn?e.debug&&K("cached model:",Mn.modelUrl):Mn=await Ee((t=e.face.gear)==null?void 0:t.modelPath),Mn}async function $g(e,t,a,n){var i,o;if(!Mn)return{age:0,gender:"unknown",genderScore:0,race:[]};let r=Mg<(((i=t.face.gear)==null?void 0:i.skipFrames)||0),s=(((o=t.face.gear)==null?void 0:o.skipTime)||0)>te()-vw;return t.skipAllowed&&s&&r&&bw===n&&Rg[a]?(Mg++,Rg[a]):(Mg=0,new Promise(async l=>{var x,A;if(!(Mn!=null&&Mn.inputs[0].shape))return;let u={},p=[[0,.1,.9,.9]];u.resize=ge.cropAndResize(e,p,[0],[Mn.inputs[0].shape[2],Mn.inputs[0].shape[1]]);let c={age:0,gender:"unknown",genderScore:0,race:[]};(x=t.face.gear)!=null&&x.enabled&&([u.age,u.gender,u.race]=Mn.execute(u.resize,["age_output","gender_output","race_output"]));let d=await u.gender.data();c.gender=d[0]>d[1]?"male":"female",c.genderScore=Math.round(100*(d[0]>d[1]?d[0]:d[1]))/100;let h=await u.race.data();for(let y=0;y<h.length;y++)h[y]>(((A=t.face.gear)==null?void 0:A.minConfidence)||.2)&&c.race.push({score:Math.round(100*h[y])/100,race:Ihe[y]});c.race.sort((y,b)=>b.score-y.score);let m=Array.from(await u.age.data()).map((y,b)=>[She[b],y]).sort((y,b)=>b[1]-y[1]),g=m[0][0];for(let y=1;y<m.length;y++)g+=m[y][1]*(m[y][0]-g);c.age=Math.round(10*g)/10,Object.keys(u).forEach(y=>Y(u[y])),Rg[a]=c,bw=n,vw=te(),l(c)}))}var en,v0=[],Iw=0,Sw=0,_g=Number.MAX_SAFE_INTEGER;async function Tw(e){return ne.initial&&(en=null),en?e.debug&&K("cached model:",en.modelUrl):en=await Ee(e.face.ssrnet.modelPathAge),en}async function Pg(e,t,a,n){var i,o,l,u;if(!en)return{age:0};let r=_g<(((i=t.face.ssrnet)==null?void 0:i.skipFrames)||0),s=(((o=t.face.ssrnet)==null?void 0:o.skipTime)||0)>te()-Sw;return t.skipAllowed&&r&&s&&Iw===n&&((l=v0[a])==null?void 0:l.age)&&((u=v0[a])==null?void 0:u.age)>0?(_g++,v0[a]):(_g=0,new Promise(async p=>{var h;if(!(en!=null&&en.inputs)||!en.inputs[0]||!en.inputs[0].shape)return;let c={};c.resize=ge.resizeBilinear(e,[en.inputs[0].shape[2],en.inputs[0].shape[1]],!1),c.enhance=ae(c.resize,ze.tf255);let d={age:0};if((h=t.face.ssrnet)!=null&&h.enabled&&(c.age=en.execute(c.enhance)),c.age){let f=await c.age.data();d.age=Math.trunc(10*f[0])/10}Object.keys(c).forEach(f=>Y(c[f])),v0[a]=d,Iw=n,Sw=te(),p(d)}))}var $n,w0=[],Nw=0,Ew=0,Fg=Number.MAX_SAFE_INTEGER,Og=[.2989,.587,.114];async function Rw(e){var t;return ne.initial&&($n=null),$n?e.debug&&K("cached model:",$n.modelUrl):$n=await Ee((t=e.face.ssrnet)==null?void 0:t.modelPathGender),$n}async function Dg(e,t,a,n){var i,o,l,u;if(!$n)return{gender:"unknown",genderScore:0};let r=Fg<(((i=t.face.ssrnet)==null?void 0:i.skipFrames)||0),s=(((o=t.face.ssrnet)==null?void 0:o.skipTime)||0)>te()-Ew;return t.skipAllowed&&r&&s&&Nw===n&&((l=w0[a])==null?void 0:l.gender)&&((u=w0[a])==null?void 0:u.genderScore)>0?(Fg++,w0[a]):(Fg=0,new Promise(async p=>{var f;if(!($n!=null&&$n.inputs[0].shape))return;let c={};c.resize=ge.resizeBilinear(e,[$n.inputs[0].shape[2],$n.inputs[0].shape[1]],!1),c.enhance=$e(()=>{let[m,g,x]=ka(c.resize,3,3),A=ae(m,Og[0]),y=ae(g,Og[1]),b=ae(x,Og[2]),w=ch([A,y,b]);return ae(fe(w,ze.tf05),2)});let d={gender:"unknown",genderScore:0};(f=t.face.ssrnet)!=null&&f.enabled&&(c.gender=$n.execute(c.enhance));let h=await c.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(c).forEach(m=>Y(c[m])),w0[a]=d,Nw=n,Ew=te(),p(d)}))}var tn,zg=[],$w=0,_w=0,Pw=Number.MAX_SAFE_INTEGER;async function Fw(e){var t;return ne.initial&&(tn=null),tn?e.debug&&K("cached model:",tn.modelUrl):tn=await Ee((t=e.face.mobilefacenet)==null?void 0:t.modelPath),tn}async function Lg(e,t,a,n){var i,o;if(!(tn!=null&&tn.executor))return[];let r=Pw<(((i=t.face.mobilefacenet)==null?void 0:i.skipFrames)||0),s=(((o=t.face.mobilefacenet)==null?void 0:o.skipTime)||0)>te()-_w;return t.skipAllowed&&s&&r&&$w===n&&zg[a]?(Pw++,zg[a]):new Promise(async l=>{var p;let u=[];if(((p=t.face.mobilefacenet)==null?void 0:p.enabled)&&(tn==null?void 0:tn.inputs[0].shape)){let c={};c.crop=ge.resizeBilinear(e,[tn.inputs[0].shape[2],tn.inputs[0].shape[1]],!1),c.data=tn.execute(c.crop);let d=await c.data.data();u=Array.from(d),Object.keys(c).forEach(h=>Y(c[h]))}zg[a]=u,$w=n,_w=te(),l(u)})}var an,Bg=[],Dw=0,zw=0,Lw=Number.MAX_SAFE_INTEGER;async function Bw(e){return ne.initial&&(an=null),an?e.debug&&K("cached model:",an.modelUrl):an=await Ee(e.face.insightface.modelPath),an}async function Wg(e,t,a,n){var i,o;if(!(an!=null&&an.executor))return[];let r=Lw<(((i=t.face.insightface)==null?void 0:i.skipFrames)||0),s=(((o=t.face.insightface)==null?void 0:o.skipTime)||0)>te()-zw;return t.skipAllowed&&s&&r&&Dw===n&&Bg[a]?(Lw++,Bg[a]):new Promise(async l=>{var p;let u=[];if(((p=t.face.insightface)==null?void 0:p.enabled)&&(an==null?void 0:an.inputs[0].shape)){let c={};c.crop=ge.resizeBilinear(e,[an.inputs[0].shape[2],an.inputs[0].shape[1]],!1),c.data=an.execute(c.crop);let d=await c.data.data();u=Array.from(d),Object.keys(c).forEach(h=>Y(c[h]))}Bg[a]=u,Dw=n,zw=te(),l(u)})}var The=e=>{let t=(c,d)=>Math.atan2(c[1]-d[1],c[0]-d[0]);if(!e.annotations.rightEyeIris||!e.annotations.leftEyeIris)return{bearing:0,strength:0};let a=[0,-.1],n=1,r=(e.mesh[33][2]||0)>(e.mesh[263][2]||0),s=r?e.mesh[473]:e.mesh[468],i=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],o=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=[(i[0]-s[0])/o[0]-a[0],n*(s[1]-i[1])/o[1]-a[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}},Vw=(e,t)=>{let a=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},n=(m,g)=>{let x=m[0]-g[0],A=m[1]-g[1],y=m[2]-g[2];return[x,A,y]},r=(m,g)=>{let x=m[1]*g[2]-m[2]*g[1],A=m[2]*g[0]-m[0]*g[2],y=m[0]*g[1]-m[1]*g[0];return[x,A,y]},s=m=>{let[g,x,A,y,b,w,S,C,E]=m,_,$,M;return y<1?y>-1?(M=Math.asin(y),$=Math.atan2(-S,g),_=Math.atan2(-w,b)):(M=-Math.PI/2,$=-Math.atan2(C,E),_=0):(M=Math.PI/2,$=Math.atan2(C,E),_=0),Number.isNaN(_)&&(_=0),Number.isNaN($)&&($=0),Number.isNaN(M)&&(M=0),{pitch:2*-_,yaw:2*-$,roll:2*-M}},i=e.meshRaw;if(!i||i.length<300)return{angle:{pitch:0,yaw:0,roll:0},matrix:[1,0,0,0,1,0,0,0,1],gaze:{bearing:0,strength:0}};let o=Math.max(e.boxRaw[2]*t[0],e.boxRaw[3]*t[1])/1.5,l=[i[10],i[152],i[234],i[454]].map(m=>[m[0]*t[0]/o,m[1]*t[1]/o,m[2]]),u=a(n(l[1],l[0])),p=a(n(l[3],l[2])),c=a(r(p,u));p=r(u,c);let d=[p[0],p[1],p[2],u[0],u[1],u[2],c[0],c[1],c[2]],h=s(d),f=i.length===478?The(e):{bearing:0,strength:0};return{angle:h,matrix:d,gaze:f}};function Uw(e,t){let a=e==null?void 0:e.annotations;if(!a)return 0;let n=Math.max(Math.abs(a.leftEyeIris[3][0]-a.leftEyeIris[1][0]),Math.abs(a.rightEyeIris[3][0]-a.rightEyeIris[1][0]))/t;return Math.round(1.17/n)/100}var Vg=async(e,t)=>{var f,m,g,x,A,y,b,w,S,C,E,_,$,M,I,N,O,L,B,G,j,U,H;let a=te(),n,r,s,i,o,l,u,p,c,d=[];e.state="run:face";let h=await Q9(t,e.config);if(e.performance.face=ne.perfadd?(e.performance.face||0)+Math.trunc(te()-a):Math.trunc(te()-a),!t.shape||t.shape.length!==4)return[];if(!h)return[];for(let V=0;V<h.length;V++){if(e.analyze("Get Face"),!h[V].tensor||h[V].tensor.isDisposedInternal){K("Face object is disposed:",h[V].tensor);continue}if((f=e.config.face.detector)!=null&&f.mask){let he=await pw(h[V]);Y(h[V].tensor),he&&(h[V].tensor=he)}let Q=h[V].mesh&&h[V].mesh.length>200?Vw(h[V],[t.shape[2],t.shape[1]]):null;e.analyze("Start Emotion:"),e.config.async?i=(m=e.config.face.emotion)!=null&&m.enabled?wg(h[V].tensor||Be([]),e.config,V,h.length):[]:(e.state="run:emotion",a=te(),i=(g=e.config.face.emotion)!=null&&g.enabled?await wg(h[V].tensor||Be([]),e.config,V,h.length):[],e.performance.emotion=ne.perfadd?(e.performance.emotion||0)+Math.trunc(te()-a):Math.trunc(te()-a)),e.analyze("End Emotion:"),e.analyze("Start AntiSpoof:"),e.config.async?u=(x=e.config.face.antispoof)!=null&&x.enabled?Cg(h[V].tensor||Be([]),e.config,V,h.length):0:(e.state="run:antispoof",a=te(),u=(A=e.config.face.antispoof)!=null&&A.enabled?await Cg(h[V].tensor||Be([]),e.config,V,h.length):0,e.performance.antispoof=ne.perfadd?(e.performance.antispoof||0)+Math.trunc(te()-a):Math.trunc(te()-a)),e.analyze("End AntiSpoof:"),e.analyze("Start Liveness:"),e.config.async?p=(y=e.config.face.liveness)!=null&&y.enabled?Eg(h[V].tensor||Be([]),e.config,V,h.length):0:(e.state="run:liveness",a=te(),p=(b=e.config.face.liveness)!=null&&b.enabled?await Eg(h[V].tensor||Be([]),e.config,V,h.length):0,e.performance.liveness=ne.perfadd?(e.performance.antispoof||0)+Math.trunc(te()-a):Math.trunc(te()-a)),e.analyze("End Liveness:"),e.analyze("Start GEAR:"),e.config.async?r=(w=e.config.face.gear)!=null&&w.enabled?$g(h[V].tensor||Be([]),e.config,V,h.length):null:(e.state="run:gear",a=te(),r=(S=e.config.face.gear)!=null&&S.enabled?await $g(h[V].tensor||Be([]),e.config,V,h.length):null,e.performance.gear=Math.trunc(te()-a)),e.analyze("End GEAR:"),e.analyze("Start SSRNet:"),e.config.async?(n=(C=e.config.face.ssrnet)!=null&&C.enabled?Pg(h[V].tensor||Be([]),e.config,V,h.length):null,s=(E=e.config.face.ssrnet)!=null&&E.enabled?Dg(h[V].tensor||Be([]),e.config,V,h.length):null):(e.state="run:ssrnet",a=te(),n=(_=e.config.face.ssrnet)!=null&&_.enabled?await Pg(h[V].tensor||Be([]),e.config,V,h.length):null,s=($=e.config.face.ssrnet)!=null&&$.enabled?await Dg(h[V].tensor||Be([]),e.config,V,h.length):null,e.performance.ssrnet=Math.trunc(te()-a)),e.analyze("End SSRNet:"),e.analyze("Start MobileFaceNet:"),e.config.async?o=(M=e.config.face.mobilefacenet)!=null&&M.enabled?Lg(h[V].tensor||Be([]),e.config,V,h.length):null:(e.state="run:mobilefacenet",a=te(),o=(I=e.config.face.mobilefacenet)!=null&&I.enabled?await Lg(h[V].tensor||Be([]),e.config,V,h.length):null,e.performance.mobilefacenet=Math.trunc(te()-a)),e.analyze("End MobileFaceNet:"),e.analyze("Start InsightFace:"),e.config.async?l=(N=e.config.face.insightface)!=null&&N.enabled?Wg(h[V].tensor||Be([]),e.config,V,h.length):null:(e.state="run:mobilefacenet",a=te(),l=(O=e.config.face.insightface)!=null&&O.enabled?await Wg(h[V].tensor||Be([]),e.config,V,h.length):null,e.performance.mobilefacenet=Math.trunc(te()-a)),e.analyze("End InsightFace:"),e.analyze("Start Description:"),e.config.async?c=Ig(h[V].tensor||Be([]),e.config,V,h.length):(e.state="run:description",a=te(),c=await Ig(h[V].tensor||Be([]),e.config,V,h.length),e.performance.description=ne.perfadd?(e.performance.description||0)+Math.trunc(te()-a):Math.trunc(te()-a)),e.analyze("End Description:"),e.config.async&&([n,s,i,o,l,c,r,u,p]=await Promise.all([n,s,i,o,l,c,r,u,p])),e.analyze("Finish Face:"),((L=e.config.face.ssrnet)==null?void 0:L.enabled)&&n&&s&&(c={...c,age:n.age,gender:s.gender,genderScore:s.genderScore}),((B=e.config.face.gear)==null?void 0:B.enabled)&&r&&(c={...c,age:r.age,gender:r.gender,genderScore:r.genderScore,race:r.race}),((G=e.config.face.mobilefacenet)==null?void 0:G.enabled)&&o&&(c.descriptor=o),((j=e.config.face.insightface)==null?void 0:j.enabled)&&l&&(c.descriptor=l);let Z=(U=e.config.face.iris)!=null&&U.enabled?Uw(h[V],t.shape[2]):0,re=(H=e.config.face.detector)!=null&&H.return?_e(h[V].tensor):null;Y(h[V].tensor),h[V].tensor&&delete h[V].tensor;let ee={...h[V],id:V};c.age&&(ee.age=c.age),c.gender&&(ee.gender=c.gender),c.genderScore&&(ee.genderScore=c.genderScore),c.descriptor&&(ee.embedding=c.descriptor),c.race&&(ee.race=c.race),i&&(ee.emotion=i),u&&(ee.real=u),p&&(ee.live=p),Z>0&&(ee.distance=Z),Q&&(ee.rotation=Q),re&&(ee.tensor=re),d.push(ee),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 Ma={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=>Ma.nameMapping[e],getPoints:e=>Ma.pointsMapping[e]},As={none:0,half:1,full:2,nameMapping:{0:"none",1:"half",2:"full"},getName:e=>As.nameMapping[e]},Et={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=>Et.nameMapping[e]},xs=class{constructor(t){ue(this,"name");ue(this,"curls");ue(this,"directions");ue(this,"weights");ue(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,a,n){typeof this.curls[t]=="undefined"&&(this.curls[t]=[]),this.curls[t].push([a,n])}direction(t,a,n){this.directions[t]||(this.directions[t]=[]),this.directions[t].push([a,n])}weight(t,a){this.weights[t]=a;let n=this.weights.reduce((r,s)=>r+s,0);this.weightsRelative=this.weights.map(r=>r*5/n)}matchAgainst(t,a){let n=0;for(let r in t){let s=t[r],i=this.curls[r];if(typeof i=="undefined"){n+=this.weightsRelative[r];continue}for(let[o,l]of i)if(s===o){n+=l*this.weightsRelative[r];break}}for(let r in a){let s=a[r],i=this.directions[r];if(typeof i=="undefined"){n+=this.weightsRelative[r];continue}for(let[o,l]of i)if(s===o){n+=l*this.weightsRelative[r];break}}return n/10}};var{thumb:Bn,index:Rr,middle:Mr,ring:Po,pinky:Fo}=Ma,{none:Wn,half:Nhe,full:Vn}=As,{verticalUp:Cu,verticalDown:zge,horizontalLeft:Ug,horizontalRight:Ehe,diagonalUpRight:Rhe,diagonalUpLeft:Nu,diagonalDownRight:Lge,diagonalDownLeft:Bge}=Et,ys=new xs("thumbs up");ys.curl(Bn,Wn,1);ys.direction(Bn,Cu,1);ys.direction(Bn,Nu,.25);ys.direction(Bn,Rhe,.25);for(let e of[Ma.index,Ma.middle,Ma.ring,Ma.pinky])ys.curl(e,Vn,1),ys.direction(e,Ug,1),ys.direction(e,Ehe,1);var Wt=new xs("victory");Wt.curl(Bn,Nhe,.5);Wt.curl(Bn,Wn,.5);Wt.direction(Bn,Cu,1);Wt.direction(Bn,Nu,1);Wt.curl(Rr,Wn,1);Wt.direction(Rr,Cu,.75);Wt.direction(Rr,Nu,1);Wt.curl(Mr,Wn,1);Wt.direction(Mr,Cu,1);Wt.direction(Mr,Nu,.75);Wt.curl(Po,Vn,1);Wt.direction(Po,Cu,.2);Wt.direction(Po,Nu,1);Wt.direction(Po,Ug,.2);Wt.curl(Fo,Vn,1);Wt.direction(Fo,Cu,.2);Wt.direction(Fo,Nu,1);Wt.direction(Fo,Ug,.2);Wt.weight(Rr,2);Wt.weight(Mr,2);var bs=new xs("point");bs.curl(Bn,Vn,1);bs.curl(Rr,Wn,.5);bs.curl(Mr,Vn,.5);bs.curl(Po,Vn,.5);bs.curl(Fo,Vn,.5);bs.weight(Rr,2);bs.weight(Mr,2);var vs=new xs("middle finger");vs.curl(Bn,Wn,1);vs.curl(Rr,Vn,.5);vs.curl(Mr,Vn,.5);vs.curl(Po,Vn,.5);vs.curl(Fo,Vn,.5);vs.weight(Rr,2);vs.weight(Mr,2);var Eu=new xs("open palm");Eu.curl(Bn,Wn,.75);Eu.curl(Rr,Wn,.75);Eu.curl(Mr,Wn,.75);Eu.curl(Po,Wn,.75);Eu.curl(Fo,Wn,.75);var Gw=[ys,Wt,bs,vs,Eu];var Mhe=.7,Oo={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 Hw(e,t,a,n){let r=(t-n)/(e-a),s=Math.atan(r)*180/Math.PI;return s<=0?s=-s:s>0&&(s=180-s),s}function qw(e,t){if(!e||!t)return[0,0];let a=Hw(e[0],e[1],t[0],t[1]);if(e.length===2)return a;let n=Hw(e[1],e[2],t[1],t[2]);return[a,n]}function jw(e,t=1){let a=0,n=0,r=0;return e>=75&&e<=105?a=1*t:e>=25&&e<=155?n=1*t:r=1*t,[a,n,r]}function $he(e,t,a){let n=e[0]-t[0],r=e[0]-a[0],s=t[0]-a[0],i=e[1]-t[1],o=e[1]-a[1],l=t[1]-a[1],u=e[2]-t[2],p=e[2]-a[2],c=t[2]-a[2],d=Math.sqrt(n*n+i*i+u*u),h=Math.sqrt(r*r+o*o+p*p),f=Math.sqrt(s*s+l*l+c*c),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 x;return g>Oo.NO_CURL_START_LIMIT?x=As.none:g>Oo.HALF_CURL_START_LIMIT?x=As.half:x=As.full,x}function Xw(e,t,a,n){let r;return n===Math.abs(e)?e>0?r=Et.horizontalLeft:r=Et.horizontalRight:n===Math.abs(t)?t>0?r=Et.horizontalLeft:r=Et.horizontalRight:a>0?r=Et.horizontalLeft:r=Et.horizontalRight,r}function Kw(e,t,a,n){let r;return n===Math.abs(e)?e<0?r=Et.verticalDown:r=Et.verticalUp:n===Math.abs(t)?t<0?r=Et.verticalDown:r=Et.verticalUp:a<0?r=Et.verticalDown:r=Et.verticalUp,r}function _he(e,t,a,n,r,s,i,o){let l,u=Kw(e,t,a,n),p=Xw(r,s,i,o);return u===Et.verticalUp?p===Et.horizontalLeft?l=Et.diagonalUpLeft:l=Et.diagonalUpRight:p===Et.horizontalLeft?l=Et.diagonalDownLeft:l=Et.diagonalDownRight,l}function Phe(e,t,a,n){let r=e[0]-t[0],s=e[0]-a[0],i=t[0]-a[0],o=e[1]-t[1],l=e[1]-a[1],u=t[1]-a[1],p=Math.max(Math.abs(r),Math.abs(s),Math.abs(i)),c=Math.max(Math.abs(o),Math.abs(l),Math.abs(u)),d=0,h=0,f=0,m=c/(p+1e-5);m>1.5?d+=Oo.DISTANCE_VOTE_POWER:m>.66?h+=Oo.DISTANCE_VOTE_POWER:f+=Oo.DISTANCE_VOTE_POWER;let g=Math.sqrt(r*r+o*o),x=Math.sqrt(s*s+l*l),A=Math.sqrt(i*i+u*u),y=Math.max(g,x,A),b=e[0],w=e[1],S=a[0],C=a[1];y===g?(S=a[0],C=a[1]):y===A&&(b=t[0],w=t[1]);let $=qw([b,w],[S,C]),M=jw($,Oo.TOTAL_ANGLE_VOTE_POWER);d+=M[0],h+=M[1],f+=M[2];for(let N of n){let O=jw(N,Oo.SINGLE_ANGLE_VOTE_POWER);d+=O[0],h+=O[1],f+=O[2]}let I;return d===Math.max(d,h,f)?I=Kw(l,o,u,c):f===Math.max(h,f)?I=Xw(s,r,i,p):I=_he(l,o,u,c,s,r,i,p),I}function Zw(e){let t=[],a=[],n=[],r=[];if(!e)return{curls:n,directions:r};for(let s of Ma.all){let i=Ma.getPoints(s),o=[],l=[];for(let u of i){let p=e[u[0]],c=e[u[1]],d=qw(p,c),h=d[0],f=d[1];o.push(h),l.push(f)}t.push(o),a.push(l)}for(let s of Ma.all){let i=s===Ma.thumb?1:0,o=Ma.getPoints(s),l=e[o[i][0]],u=e[o[i+1][1]],p=e[o[3][1]],c=$he(l,u,p),d=Phe(l,u,p,t[s].slice(i));n[s]=c,r[s]=d}return{curls:n,directions:r}}function k0(e){if(!e||e.length===0)return null;let t=Zw(e),a={};for(let n of Ma.all)a[Ma.getName(n)]={curl:As.getName(t.curls[n]),direction:Et.getName(t.directions[n])};return a}function Yw(e){let t=[];if(!e||e.length===0)return t;let a=Zw(e);for(let n of Gw){let r=n.matchAgainst(a.curls,a.directions);r>=Mhe&&t.push({name:n.name,confidence:r})}return t}var Jw=e=>{if(!e)return[];let t=[];for(let a=0;a<e.length;a++){let n=e[a].keypoints.find(l=>l.part==="leftWrist"),r=e[a].keypoints.find(l=>l.part==="rightWrist"),s=e[a].keypoints.find(l=>l.part==="nose");s&&n&&r&&n.position[1]<s.position[1]&&r.position[1]<s.position[1]?t.push({body:a,gesture:"i give up"}):s&&n&&n.position[1]<s.position[1]?t.push({body:a,gesture:"raise left hand"}):s&&r&&r.position[1]<s.position[1]&&t.push({body:a,gesture:"raise right hand"});let i=e[a].keypoints.find(l=>l.part==="leftShoulder"),o=e[a].keypoints.find(l=>l.part==="rightShoulder");i&&o&&Math.abs(i.positionRaw[1]-o.positionRaw[1])>.1&&t.push({body:a,gesture:`leaning ${i.position[1]>o.position[1]?"left":"right"}`})}return t},Qw=e=>{if(!e)return[];let t=[];for(let a=0;a<e.length;a++)if(e[a].mesh&&e[a].mesh.length>450){let n=(e[a].mesh[33][2]||0)-(e[a].mesh[263][2]||0),r=e[a].mesh[33][0]-e[a].mesh[263][0];Math.abs(n/r)<=.15?t.push({face:a,gesture:"facing center"}):t.push({face:a,gesture:`facing ${n<0?"left":"right"}`}),Math.abs(e[a].mesh[374][1]-e[a].mesh[386][1])/Math.abs(e[a].mesh[443][1]-e[a].mesh[450][1])<.2&&t.push({face:a,gesture:"blink left eye"}),Math.abs(e[a].mesh[145][1]-e[a].mesh[159][1])/Math.abs(e[a].mesh[223][1]-e[a].mesh[230][1])<.2&&t.push({face:a,gesture:"blink right eye"});let o=Math.min(100,500*Math.abs(e[a].mesh[13][1]-e[a].mesh[14][1])/Math.abs(e[a].mesh[10][1]-e[a].mesh[152][1]));o>10&&t.push({face:a,gesture:`mouth ${Math.trunc(o)}% open`});let l=e[a].mesh[152][2]||0;Math.abs(l)>10&&t.push({face:a,gesture:`head ${l<0?"up":"down"}`})}return t},ek=e=>{var a,n,r,s;if(!e)return[];let t=[];for(let i=0;i<e.length;i++){if(!((n=(a=e[i].annotations)==null?void 0:a.leftEyeIris)!=null&&n[0])||!((s=(r=e[i].annotations)==null?void 0:r.rightEyeIris)!=null&&s[0]))continue;let o=e[i].annotations.leftEyeIris[3][0]-e[i].annotations.leftEyeIris[1][0],l=e[i].annotations.leftEyeIris[4][1]-e[i].annotations.leftEyeIris[2][1],u=Math.abs(o*l),p=e[i].annotations.rightEyeIris[3][0]-e[i].annotations.rightEyeIris[1][0],c=e[i].annotations.rightEyeIris[4][1]-e[i].annotations.rightEyeIris[2][1],d=Math.abs(p*c),h=!1;Math.abs(u-d)/Math.max(u,d)<.25&&(h=!0,t.push({iris:i,gesture:"facing center"}));let m=Math.abs(e[i].mesh[263][0]-e[i].annotations.leftEyeIris[0][0])/e[i].box[2],g=Math.abs(e[i].mesh[33][0]-e[i].annotations.rightEyeIris[0][0])/e[i].box[2];(m>.06||g>.06)&&(h=!1),m>g?m>.05&&t.push({iris:i,gesture:"looking right"}):g>.05&&t.push({iris:i,gesture:"looking left"});let x=Math.abs(e[i].mesh[145][1]-e[i].annotations.rightEyeIris[0][1])/e[i].box[3],A=Math.abs(e[i].mesh[374][1]-e[i].annotations.leftEyeIris[0][1])/e[i].box[3];(A<.01||x<.01||A>.022||x>.022)&&(h=!1),(A<.01||x<.01)&&t.push({iris:i,gesture:"looking down"}),(A>.022||x>.022)&&t.push({iris:i,gesture:"looking up"}),h&&t.push({iris:i,gesture:"looking center"})}return t},tk=e=>{if(!e)return[];let t=[];for(let a=0;a<e.length;a++){let n=[];if(e[a].annotations)for(let[r,s]of Object.entries(e[a].annotations))r!=="palmBase"&&Array.isArray(s)&&s[0]&&n.push({name:r.toLowerCase(),position:s[0]});if(n&&n.length>0){let r=n.reduce((i,o)=>(i.position[2]||0)<(o.position[2]||0)?i:o);t.push({hand:a,gesture:`${r.name} forward`});let s=n.reduce((i,o)=>i.position[1]<o.position[1]?i:o);t.push({hand:a,gesture:`${s.name} up`})}if(e[a].keypoints){let r=Yw(e[a].keypoints);for(let s of r)t.push({hand:a,gesture:s.name})}}return t};function I0(e){return[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])]}function Tp(e){return[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2]}function rk(e,t,a){let n=t.shape[1],r=t.shape[2],s=[[e.startPoint[1]/n,e.startPoint[0]/r,e.endPoint[1]/n,e.endPoint[0]/r]];return ge.cropAndResize(t,s,[0],a)}function sk(e,t){let a=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],n=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]],r=e.palmLandmarks.map(s=>[s[0]*t[0],s[1]*t[1]]);return{startPoint:a,endPoint:n,palmLandmarks:r,confidence:e.confidence}}function S0(e,t=1.5){let a=Tp(e),n=I0(e),r=[t*n[0]/2,t*n[1]/2],s=[a[0]-r[0],a[1]-r[1]],i=[a[0]+r[0],a[1]+r[1]];return{startPoint:s,endPoint:i,palmLandmarks:e.palmLandmarks}}function T0(e){let t=Tp(e),a=I0(e),r=Math.max(...a)/2,s=[t[0]-r,t[1]-r],i=[t[0]+r,t[1]+r];return{startPoint:s,endPoint:i,palmLandmarks:e.palmLandmarks}}function Ohe(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function ik(e,t){let a=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]);return Ohe(a)}var ak=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]];function ws(e,t){let a=0;for(let n=0;n<e.length;n++)a+=e[n]*t[n];return a}function Dhe(e,t){let a=[];for(let n=0;n<e.length;n++)a.push(e[n][t]);return a}function nk(e,t){let a=[],n=e.length;for(let r=0;r<n;r++){a.push([]);for(let s=0;s<n;s++)a[r].push(ws(e[r],Dhe(t,s)))}return a}function Hg(e,t){let a=Math.cos(e),n=Math.sin(e),r=[[a,-n,0],[n,a,0],[0,0,1]],s=ak(t[0],t[1]),i=nk(s,r),o=ak(-t[0],-t[1]);return nk(i,o)}function ok(e){let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],a=[e[0][2],e[1][2]],n=[-ws(t[0],a),-ws(t[1],a)];return[t[0].concat(n[0]),t[1].concat(n[1]),[0,0,1]]}function jg(e,t){return[ws(e,t[0]),ws(e,t[1])]}var uk=[{x:.015625,y:.015625},{x:.015625,y:.015625},{x:.046875,y:.015625},{x:.046875,y:.015625},{x:.078125,y:.015625},{x:.078125,y:.015625},{x:.109375,y:.015625},{x:.109375,y:.015625},{x:.140625,y:.015625},{x:.140625,y:.015625},{x:.171875,y:.015625},{x:.171875,y:.015625},{x:.203125,y:.015625},{x:.203125,y:.015625},{x:.234375,y:.015625},{x:.234375,y:.015625},{x:.265625,y:.015625},{x:.265625,y:.015625},{x:.296875,y:.015625},{x:.296875,y:.015625},{x:.328125,y:.015625},{x:.328125,y:.015625},{x:.359375,y:.015625},{x:.359375,y:.015625},{x:.390625,y:.015625},{x:.390625,y:.015625},{x:.421875,y:.015625},{x:.421875,y:.015625},{x:.453125,y:.015625},{x:.453125,y:.015625},{x:.484375,y:.015625},{x:.484375,y:.015625},{x:.515625,y:.015625},{x:.515625,y:.015625},{x:.546875,y:.015625},{x:.546875,y:.015625},{x:.578125,y:.015625},{x:.578125,y:.015625},{x:.609375,y:.015625},{x:.609375,y:.015625},{x:.640625,y:.015625},{x:.640625,y:.015625},{x:.671875,y:.015625},{x:.671875,y:.015625},{x:.703125,y:.015625},{x:.703125,y:.015625},{x:.734375,y:.015625},{x:.734375,y:.015625},{x:.765625,y:.015625},{x:.765625,y:.015625},{x:.796875,y:.015625},{x:.796875,y:.015625},{x:.828125,y:.015625},{x:.828125,y:.015625},{x:.859375,y:.015625},{x:.859375,y:.015625},{x:.890625,y:.015625},{x:.890625,y:.015625},{x:.921875,y:.015625},{x:.921875,y:.015625},{x:.953125,y:.015625},{x:.953125,y:.015625},{x:.984375,y:.015625},{x:.984375,y:.015625},{x:.015625,y:.046875},{x:.015625,y:.046875},{x:.046875,y:.046875},{x:.046875,y:.046875},{x:.078125,y:.046875},{x:.078125,y:.046875},{x:.109375,y:.046875},{x:.109375,y:.046875},{x:.140625,y:.046875},{x:.140625,y:.046875},{x:.171875,y:.046875},{x:.171875,y:.046875},{x:.203125,y:.046875},{x:.203125,y:.046875},{x:.234375,y:.046875},{x:.234375,y:.046875},{x:.265625,y:.046875},{x:.265625,y:.046875},{x:.296875,y:.046875},{x:.296875,y:.046875},{x:.328125,y:.046875},{x:.328125,y:.046875},{x:.359375,y:.046875},{x:.359375,y:.046875},{x:.390625,y:.046875},{x:.390625,y:.046875},{x:.421875,y:.046875},{x:.421875,y:.046875},{x:.453125,y:.046875},{x:.453125,y:.046875},{x:.484375,y:.046875},{x:.484375,y:.046875},{x:.515625,y:.046875},{x:.515625,y:.046875},{x:.546875,y:.046875},{x:.546875,y:.046875},{x:.578125,y:.046875},{x:.578125,y:.046875},{x:.609375,y:.046875},{x:.609375,y:.046875},{x:.640625,y:.046875},{x:.640625,y:.046875},{x:.671875,y:.046875},{x:.671875,y:.046875},{x:.703125,y:.046875},{x:.703125,y:.046875},{x:.734375,y:.046875},{x:.734375,y:.046875},{x:.765625,y:.046875},{x:.765625,y:.046875},{x:.796875,y:.046875},{x:.796875,y:.046875},{x:.828125,y:.046875},{x:.828125,y:.046875},{x:.859375,y:.046875},{x:.859375,y:.046875},{x:.890625,y:.046875},{x:.890625,y:.046875},{x:.921875,y:.046875},{x:.921875,y:.046875},{x:.953125,y:.046875},{x:.953125,y:.046875},{x:.984375,y:.046875},{x:.984375,y:.046875},{x:.015625,y:.078125},{x:.015625,y:.078125},{x:.046875,y:.078125},{x:.046875,y:.078125},{x:.078125,y:.078125},{x:.078125,y:.078125},{x:.109375,y:.078125},{x:.109375,y:.078125},{x:.140625,y:.078125},{x:.140625,y:.078125},{x:.171875,y:.078125},{x:.171875,y:.078125},{x:.203125,y:.078125},{x:.203125,y:.078125},{x:.234375,y:.078125},{x:.234375,y:.078125},{x:.265625,y:.078125},{x:.265625,y:.078125},{x:.296875,y:.078125},{x:.296875,y:.078125},{x:.328125,y:.078125},{x:.328125,y:.078125},{x:.359375,y:.078125},{x:.359375,y:.078125},{x:.390625,y:.078125},{x:.390625,y:.078125},{x:.421875,y:.078125},{x:.421875,y:.078125},{x:.453125,y:.078125},{x:.453125,y:.078125},{x:.484375,y:.078125},{x:.484375,y:.078125},{x:.515625,y:.078125},{x:.515625,y:.078125},{x:.546875,y:.078125},{x:.546875,y:.078125},{x:.578125,y:.078125},{x:.578125,y:.078125},{x:.609375,y:.078125},{x:.609375,y:.078125},{x:.640625,y:.078125},{x:.640625,y:.078125},{x:.671875,y:.078125},{x:.671875,y:.078125},{x:.703125,y:.078125},{x:.703125,y:.078125},{x:.734375,y:.078125},{x:.734375,y:.078125},{x:.765625,y:.078125},{x:.765625,y:.078125},{x:.796875,y:.078125},{x:.796875,y:.078125},{x:.828125,y:.078125},{x:.828125,y:.078125},{x:.859375,y:.078125},{x:.859375,y:.078125},{x:.890625,y:.078125},{x:.890625,y:.078125},{x:.921875,y:.078125},{x:.921875,y:.078125},{x:.953125,y:.078125},{x:.953125,y:.078125},{x:.984375,y:.078125},{x:.984375,y:.078125},{x:.015625,y:.109375},{x:.015625,y:.109375},{x:.046875,y:.109375},{x:.046875,y:.109375},{x:.078125,y:.109375},{x:.078125,y:.109375},{x:.109375,y:.109375},{x:.109375,y:.109375},{x:.140625,y:.109375},{x:.140625,y:.109375},{x:.171875,y:.109375},{x:.171875,y:.109375},{x:.203125,y:.109375},{x:.203125,y:.109375},{x:.234375,y:.109375},{x:.234375,y:.109375},{x:.265625,y:.109375},{x:.265625,y:.109375},{x:.296875,y:.109375},{x:.296875,y:.109375},{x:.328125,y:.109375},{x:.328125,y:.109375},{x:.359375,y:.109375},{x:.359375,y:.109375},{x:.390625,y:.109375},{x:.390625,y:.109375},{x:.421875,y:.109375},{x:.421875,y:.109375},{x:.453125,y:.109375},{x:.453125,y:.109375},{x:.484375,y:.109375},{x:.484375,y:.109375},{x:.515625,y:.109375},{x:.515625,y:.109375},{x:.546875,y:.109375},{x:.546875,y:.109375},{x:.578125,y:.109375},{x:.578125,y:.109375},{x:.609375,y:.109375},{x:.609375,y:.109375},{x:.640625,y:.109375},{x:.640625,y:.109375},{x:.671875,y:.109375},{x:.671875,y:.109375},{x:.703125,y:.109375},{x:.703125,y:.109375},{x:.734375,y:.109375},{x:.734375,y:.109375},{x:.765625,y:.109375},{x:.765625,y:.109375},{x:.796875,y:.109375},{x:.796875,y:.109375},{x:.828125,y:.109375},{x:.828125,y:.109375},{x:.859375,y:.109375},{x:.859375,y:.109375},{x:.890625,y:.109375},{x:.890625,y:.109375},{x:.921875,y:.109375},{x:.921875,y:.109375},{x:.953125,y:.109375},{x:.953125,y:.109375},{x:.984375,y:.109375},{x:.984375,y:.109375},{x:.015625,y:.140625},{x:.015625,y:.140625},{x:.046875,y:.140625},{x:.046875,y:.140625},{x:.078125,y:.140625},{x:.078125,y:.140625},{x:.109375,y:.140625},{x:.109375,y:.140625},{x:.140625,y:.140625},{x:.140625,y:.140625},{x:.171875,y:.140625},{x:.171875,y:.140625},{x:.203125,y:.140625},{x:.203125,y:.140625},{x:.234375,y:.140625},{x:.234375,y:.140625},{x:.265625,y:.140625},{x:.265625,y:.140625},{x:.296875,y:.140625},{x:.296875,y:.140625},{x:.328125,y:.140625},{x:.328125,y:.140625},{x:.359375,y:.140625},{x:.359375,y:.140625},{x:.390625,y:.140625},{x:.390625,y:.140625},{x:.421875,y:.140625},{x:.421875,y:.140625},{x:.453125,y:.140625},{x:.453125,y:.140625},{x:.484375,y:.140625},{x:.484375,y:.140625},{x:.515625,y:.140625},{x:.515625,y:.140625},{x:.546875,y:.140625},{x:.546875,y:.140625},{x:.578125,y:.140625},{x:.578125,y:.140625},{x:.609375,y:.140625},{x:.609375,y:.140625},{x:.640625,y:.140625},{x:.640625,y:.140625},{x:.671875,y:.140625},{x:.671875,y:.140625},{x:.703125,y:.140625},{x:.703125,y:.140625},{x:.734375,y:.140625},{x:.734375,y:.140625},{x:.765625,y:.140625},{x:.765625,y:.140625},{x:.796875,y:.140625},{x:.796875,y:.140625},{x:.828125,y:.140625},{x:.828125,y:.140625},{x:.859375,y:.140625},{x:.859375,y:.140625},{x:.890625,y:.140625},{x:.890625,y:.140625},{x:.921875,y:.140625},{x:.921875,y:.140625},{x:.953125,y:.140625},{x:.953125,y:.140625},{x:.984375,y:.140625},{x:.984375,y:.140625},{x:.015625,y:.171875},{x:.015625,y:.171875},{x:.046875,y:.171875},{x:.046875,y:.171875},{x:.078125,y:.171875},{x:.078125,y:.171875},{x:.109375,y:.171875},{x:.109375,y:.171875},{x:.140625,y:.171875},{x:.140625,y:.171875},{x:.171875,y:.171875},{x:.171875,y:.171875},{x:.203125,y:.171875},{x:.203125,y:.171875},{x:.234375,y:.171875},{x:.234375,y:.171875},{x:.265625,y:.171875},{x:.265625,y:.171875},{x:.296875,y:.171875},{x:.296875,y:.171875},{x:.328125,y:.171875},{x:.328125,y:.171875},{x:.359375,y:.171875},{x:.359375,y:.171875},{x:.390625,y:.171875},{x:.390625,y:.171875},{x:.421875,y:.171875},{x:.421875,y:.171875},{x:.453125,y:.171875},{x:.453125,y:.171875},{x:.484375,y:.171875},{x:.484375,y:.171875},{x:.515625,y:.171875},{x:.515625,y:.171875},{x:.546875,y:.171875},{x:.546875,y:.171875},{x:.578125,y:.171875},{x:.578125,y:.171875},{x:.609375,y:.171875},{x:.609375,y:.171875},{x:.640625,y:.171875},{x:.640625,y:.171875},{x:.671875,y:.171875},{x:.671875,y:.171875},{x:.703125,y:.171875},{x:.703125,y:.171875},{x:.734375,y:.171875},{x:.734375,y:.171875},{x:.765625,y:.171875},{x:.765625,y:.171875},{x:.796875,y:.171875},{x:.796875,y:.171875},{x:.828125,y:.171875},{x:.828125,y:.171875},{x:.859375,y:.171875},{x:.859375,y:.171875},{x:.890625,y:.171875},{x:.890625,y:.171875},{x:.921875,y:.171875},{x:.921875,y:.171875},{x:.953125,y:.171875},{x:.953125,y:.171875},{x:.984375,y:.171875},{x:.984375,y:.171875},{x:.015625,y:.203125},{x:.015625,y:.203125},{x:.046875,y:.203125},{x:.046875,y:.203125},{x:.078125,y:.203125},{x:.078125,y:.203125},{x:.109375,y:.203125},{x:.109375,y:.203125},{x:.140625,y:.203125},{x:.140625,y:.203125},{x:.171875,y:.203125},{x:.171875,y:.203125},{x:.203125,y:.203125},{x:.203125,y:.203125},{x:.234375,y:.203125},{x:.234375,y:.203125},{x:.265625,y:.203125},{x:.265625,y:.203125},{x:.296875,y:.203125},{x:.296875,y:.203125},{x:.328125,y:.203125},{x:.328125,y:.203125},{x:.359375,y:.203125},{x:.359375,y:.203125},{x:.390625,y:.203125},{x:.390625,y:.203125},{x:.421875,y:.203125},{x:.421875,y:.203125},{x:.453125,y:.203125},{x:.453125,y:.203125},{x:.484375,y:.203125},{x:.484375,y:.203125},{x:.515625,y:.203125},{x:.515625,y:.203125},{x:.546875,y:.203125},{x:.546875,y:.203125},{x:.578125,y:.203125},{x:.578125,y:.203125},{x:.609375,y:.203125},{x:.609375,y:.203125},{x:.640625,y:.203125},{x:.640625,y:.203125},{x:.671875,y:.203125},{x:.671875,y:.203125},{x:.703125,y:.203125},{x:.703125,y:.203125},{x:.734375,y:.203125},{x:.734375,y:.203125},{x:.765625,y:.203125},{x:.765625,y:.203125},{x:.796875,y:.203125},{x:.796875,y:.203125},{x:.828125,y:.203125},{x:.828125,y:.203125},{x:.859375,y:.203125},{x:.859375,y:.203125},{x:.890625,y:.203125},{x:.890625,y:.203125},{x:.921875,y:.203125},{x:.921875,y:.203125},{x:.953125,y:.203125},{x:.953125,y:.203125},{x:.984375,y:.203125},{x:.984375,y:.203125},{x:.015625,y:.234375},{x:.015625,y:.234375},{x:.046875,y:.234375},{x:.046875,y:.234375},{x:.078125,y:.234375},{x:.078125,y:.234375},{x:.109375,y:.234375},{x:.109375,y:.234375},{x:.140625,y:.234375},{x:.140625,y:.234375},{x:.171875,y:.234375},{x:.171875,y:.234375},{x:.203125,y:.234375},{x:.203125,y:.234375},{x:.234375,y:.234375},{x:.234375,y:.234375},{x:.265625,y:.234375},{x:.265625,y:.234375},{x:.296875,y:.234375},{x:.296875,y:.234375},{x:.328125,y:.234375},{x:.328125,y:.234375},{x:.359375,y:.234375},{x:.359375,y:.234375},{x:.390625,y:.234375},{x:.390625,y:.234375},{x:.421875,y:.234375},{x:.421875,y:.234375},{x:.453125,y:.234375},{x:.453125,y:.234375},{x:.484375,y:.234375},{x:.484375,y:.234375},{x:.515625,y:.234375},{x:.515625,y:.234375},{x:.546875,y:.234375},{x:.546875,y:.234375},{x:.578125,y:.234375},{x:.578125,y:.234375},{x:.609375,y:.234375},{x:.609375,y:.234375},{x:.640625,y:.234375},{x:.640625,y:.234375},{x:.671875,y:.234375},{x:.671875,y:.234375},{x:.703125,y:.234375},{x:.703125,y:.234375},{x:.734375,y:.234375},{x:.734375,y:.234375},{x:.765625,y:.234375},{x:.765625,y:.234375},{x:.796875,y:.234375},{x:.796875,y:.234375},{x:.828125,y:.234375},{x:.828125,y:.234375},{x:.859375,y:.234375},{x:.859375,y:.234375},{x:.890625,y:.234375},{x:.890625,y:.234375},{x:.921875,y:.234375},{x:.921875,y:.234375},{x:.953125,y:.234375},{x:.953125,y:.234375},{x:.984375,y:.234375},{x:.984375,y:.234375},{x:.015625,y:.265625},{x:.015625,y:.265625},{x:.046875,y:.265625},{x:.046875,y:.265625},{x:.078125,y:.265625},{x:.078125,y:.265625},{x:.109375,y:.265625},{x:.109375,y:.265625},{x:.140625,y:.265625},{x:.140625,y:.265625},{x:.171875,y:.265625},{x:.171875,y:.265625},{x:.203125,y:.265625},{x:.203125,y:.265625},{x:.234375,y:.265625},{x:.234375,y:.265625},{x:.265625,y:.265625},{x:.265625,y:.265625},{x:.296875,y:.265625},{x:.296875,y:.265625},{x:.328125,y:.265625},{x:.328125,y:.265625},{x:.359375,y:.265625},{x:.359375,y:.265625},{x:.390625,y:.265625},{x:.390625,y:.265625},{x:.421875,y:.265625},{x:.421875,y:.265625},{x:.453125,y:.265625},{x:.453125,y:.265625},{x:.484375,y:.265625},{x:.484375,y:.265625},{x:.515625,y:.265625},{x:.515625,y:.265625},{x:.546875,y:.265625},{x:.546875,y:.265625},{x:.578125,y:.265625},{x:.578125,y:.265625},{x:.609375,y:.265625},{x:.609375,y:.265625},{x:.640625,y:.265625},{x:.640625,y:.265625},{x:.671875,y:.265625},{x:.671875,y:.265625},{x:.703125,y:.265625},{x:.703125,y:.265625},{x:.734375,y:.265625},{x:.734375,y:.265625},{x:.765625,y:.265625},{x:.765625,y:.265625},{x:.796875,y:.265625},{x:.796875,y:.265625},{x:.828125,y:.265625},{x:.828125,y:.265625},{x:.859375,y:.265625},{x:.859375,y:.265625},{x:.890625,y:.265625},{x:.890625,y:.265625},{x:.921875,y:.265625},{x:.921875,y:.265625},{x:.953125,y:.265625},{x:.953125,y:.265625},{x:.984375,y:.265625},{x:.984375,y:.265625},{x:.015625,y:.296875},{x:.015625,y:.296875},{x:.046875,y:.296875},{x:.046875,y:.296875},{x:.078125,y:.296875},{x:.078125,y:.296875},{x:.109375,y:.296875},{x:.109375,y:.296875},{x:.140625,y:.296875},{x:.140625,y:.296875},{x:.171875,y:.296875},{x:.171875,y:.296875},{x:.203125,y:.296875},{x:.203125,y:.296875},{x:.234375,y:.296875},{x:.234375,y:.296875},{x:.265625,y:.296875},{x:.265625,y:.296875},{x:.296875,y:.296875},{x:.296875,y:.296875},{x:.328125,y:.296875},{x:.328125,y:.296875},{x:.359375,y:.296875},{x:.359375,y:.296875},{x:.390625,y:.296875},{x:.390625,y:.296875},{x:.421875,y:.296875},{x:.421875,y:.296875},{x:.453125,y:.296875},{x:.453125,y:.296875},{x:.484375,y:.296875},{x:.484375,y:.296875},{x:.515625,y:.296875},{x:.515625,y:.296875},{x:.546875,y:.296875},{x:.546875,y:.296875},{x:.578125,y:.296875},{x:.578125,y:.296875},{x:.609375,y:.296875},{x:.609375,y:.296875},{x:.640625,y:.296875},{x:.640625,y:.296875},{x:.671875,y:.296875},{x:.671875,y:.296875},{x:.703125,y:.296875},{x:.703125,y:.296875},{x:.734375,y:.296875},{x:.734375,y:.296875},{x:.765625,y:.296875},{x:.765625,y:.296875},{x:.796875,y:.296875},{x:.796875,y:.296875},{x:.828125,y:.296875},{x:.828125,y:.296875},{x:.859375,y:.296875},{x:.859375,y:.296875},{x:.890625,y:.296875},{x:.890625,y:.296875},{x:.921875,y:.296875},{x:.921875,y:.296875},{x:.953125,y:.296875},{x:.953125,y:.296875},{x:.984375,y:.296875},{x:.984375,y:.296875},{x:.015625,y:.328125},{x:.015625,y:.328125},{x:.046875,y:.328125},{x:.046875,y:.328125},{x:.078125,y:.328125},{x:.078125,y:.328125},{x:.109375,y:.328125},{x:.109375,y:.328125},{x:.140625,y:.328125},{x:.140625,y:.328125},{x:.171875,y:.328125},{x:.171875,y:.328125},{x:.203125,y:.328125},{x:.203125,y:.328125},{x:.234375,y:.328125},{x:.234375,y:.328125},{x:.265625,y:.328125},{x:.265625,y:.328125},{x:.296875,y:.328125},{x:.296875,y:.328125},{x:.328125,y:.328125},{x:.328125,y:.328125},{x:.359375,y:.328125},{x:.359375,y:.328125},{x:.390625,y:.328125},{x:.390625,y:.328125},{x:.421875,y:.328125},{x:.421875,y:.328125},{x:.453125,y:.328125},{x:.453125,y:.328125},{x:.484375,y:.328125},{x:.484375,y:.328125},{x:.515625,y:.328125},{x:.515625,y:.328125},{x:.546875,y:.328125},{x:.546875,y:.328125},{x:.578125,y:.328125},{x:.578125,y:.328125},{x:.609375,y:.328125},{x:.609375,y:.328125},{x:.640625,y:.328125},{x:.640625,y:.328125},{x:.671875,y:.328125},{x:.671875,y:.328125},{x:.703125,y:.328125},{x:.703125,y:.328125},{x:.734375,y:.328125},{x:.734375,y:.328125},{x:.765625,y:.328125},{x:.765625,y:.328125},{x:.796875,y:.328125},{x:.796875,y:.328125},{x:.828125,y:.328125},{x:.828125,y:.328125},{x:.859375,y:.328125},{x:.859375,y:.328125},{x:.890625,y:.328125},{x:.890625,y:.328125},{x:.921875,y:.328125},{x:.921875,y:.328125},{x:.953125,y:.328125},{x:.953125,y:.328125},{x:.984375,y:.328125},{x:.984375,y:.328125},{x:.015625,y:.359375},{x:.015625,y:.359375},{x:.046875,y:.359375},{x:.046875,y:.359375},{x:.078125,y:.359375},{x:.078125,y:.359375},{x:.109375,y:.359375},{x:.109375,y:.359375},{x:.140625,y:.359375},{x:.140625,y:.359375},{x:.171875,y:.359375},{x:.171875,y:.359375},{x:.203125,y:.359375},{x:.203125,y:.359375},{x:.234375,y:.359375},{x:.234375,y:.359375},{x:.265625,y:.359375},{x:.265625,y:.359375},{x:.296875,y:.359375},{x:.296875,y:.359375},{x:.328125,y:.359375},{x:.328125,y:.359375},{x:.359375,y:.359375},{x:.359375,y:.359375},{x:.390625,y:.359375},{x:.390625,y:.359375},{x:.421875,y:.359375},{x:.421875,y:.359375},{x:.453125,y:.359375},{x:.453125,y:.359375},{x:.484375,y:.359375},{x:.484375,y:.359375},{x:.515625,y:.359375},{x:.515625,y:.359375},{x:.546875,y:.359375},{x:.546875,y:.359375},{x:.578125,y:.359375},{x:.578125,y:.359375},{x:.609375,y:.359375},{x:.609375,y:.359375},{x:.640625,y:.359375},{x:.640625,y:.359375},{x:.671875,y:.359375},{x:.671875,y:.359375},{x:.703125,y:.359375},{x:.703125,y:.359375},{x:.734375,y:.359375},{x:.734375,y:.359375},{x:.765625,y:.359375},{x:.765625,y:.359375},{x:.796875,y:.359375},{x:.796875,y:.359375},{x:.828125,y:.359375},{x:.828125,y:.359375},{x:.859375,y:.359375},{x:.859375,y:.359375},{x:.890625,y:.359375},{x:.890625,y:.359375},{x:.921875,y:.359375},{x:.921875,y:.359375},{x:.953125,y:.359375},{x:.953125,y:.359375},{x:.984375,y:.359375},{x:.984375,y:.359375},{x:.015625,y:.390625},{x:.015625,y:.390625},{x:.046875,y:.390625},{x:.046875,y:.390625},{x:.078125,y:.390625},{x:.078125,y:.390625},{x:.109375,y:.390625},{x:.109375,y:.390625},{x:.140625,y:.390625},{x:.140625,y:.390625},{x:.171875,y:.390625},{x:.171875,y:.390625},{x:.203125,y:.390625},{x:.203125,y:.390625},{x:.234375,y:.390625},{x:.234375,y:.390625},{x:.265625,y:.390625},{x:.265625,y:.390625},{x:.296875,y:.390625},{x:.296875,y:.390625},{x:.328125,y:.390625},{x:.328125,y:.390625},{x:.359375,y:.390625},{x:.359375,y:.390625},{x:.390625,y:.390625},{x:.390625,y:.390625},{x:.421875,y:.390625},{x:.421875,y:.390625},{x:.453125,y:.390625},{x:.453125,y:.390625},{x:.484375,y:.390625},{x:.484375,y:.390625},{x:.515625,y:.390625},{x:.515625,y:.390625},{x:.546875,y:.390625},{x:.546875,y:.390625},{x:.578125,y:.390625},{x:.578125,y:.390625},{x:.609375,y:.390625},{x:.609375,y:.390625},{x:.640625,y:.390625},{x:.640625,y:.390625},{x:.671875,y:.390625},{x:.671875,y:.390625},{x:.703125,y:.390625},{x:.703125,y:.390625},{x:.734375,y:.390625},{x:.734375,y:.390625},{x:.765625,y:.390625},{x:.765625,y:.390625},{x:.796875,y:.390625},{x:.796875,y:.390625},{x:.828125,y:.390625},{x:.828125,y:.390625},{x:.859375,y:.390625},{x:.859375,y:.390625},{x:.890625,y:.390625},{x:.890625,y:.390625},{x:.921875,y:.390625},{x:.921875,y:.390625},{x:.953125,y:.390625},{x:.953125,y:.390625},{x:.984375,y:.390625},{x:.984375,y:.390625},{x:.015625,y:.421875},{x:.015625,y:.421875},{x:.046875,y:.421875},{x:.046875,y:.421875},{x:.078125,y:.421875},{x:.078125,y:.421875},{x:.109375,y:.421875},{x:.109375,y:.421875},{x:.140625,y:.421875},{x:.140625,y:.421875},{x:.171875,y:.421875},{x:.171875,y:.421875},{x:.203125,y:.421875},{x:.203125,y:.421875},{x:.234375,y:.421875},{x:.234375,y:.421875},{x:.265625,y:.421875},{x:.265625,y:.421875},{x:.296875,y:.421875},{x:.296875,y:.421875},{x:.328125,y:.421875},{x:.328125,y:.421875},{x:.359375,y:.421875},{x:.359375,y:.421875},{x:.390625,y:.421875},{x:.390625,y:.421875},{x:.421875,y:.421875},{x:.421875,y:.421875},{x:.453125,y:.421875},{x:.453125,y:.421875},{x:.484375,y:.421875},{x:.484375,y:.421875},{x:.515625,y:.421875},{x:.515625,y:.421875},{x:.546875,y:.421875},{x:.546875,y:.421875},{x:.578125,y:.421875},{x:.578125,y:.421875},{x:.609375,y:.421875},{x:.609375,y:.421875},{x:.640625,y:.421875},{x:.640625,y:.421875},{x:.671875,y:.421875},{x:.671875,y:.421875},{x:.703125,y:.421875},{x:.703125,y:.421875},{x:.734375,y:.421875},{x:.734375,y:.421875},{x:.765625,y:.421875},{x:.765625,y:.421875},{x:.796875,y:.421875},{x:.796875,y:.421875},{x:.828125,y:.421875},{x:.828125,y:.421875},{x:.859375,y:.421875},{x:.859375,y:.421875},{x:.890625,y:.421875},{x:.890625,y:.421875},{x:.921875,y:.421875},{x:.921875,y:.421875},{x:.953125,y:.421875},{x:.953125,y:.421875},{x:.984375,y:.421875},{x:.984375,y:.421875},{x:.015625,y:.453125},{x:.015625,y:.453125},{x:.046875,y:.453125},{x:.046875,y:.453125},{x:.078125,y:.453125},{x:.078125,y:.453125},{x:.109375,y:.453125},{x:.109375,y:.453125},{x:.140625,y:.453125},{x:.140625,y:.453125},{x:.171875,y:.453125},{x:.171875,y:.453125},{x:.203125,y:.453125},{x:.203125,y:.453125},{x:.234375,y:.453125},{x:.234375,y:.453125},{x:.265625,y:.453125},{x:.265625,y:.453125},{x:.296875,y:.453125},{x:.296875,y:.453125},{x:.328125,y:.453125},{x:.328125,y:.453125},{x:.359375,y:.453125},{x:.359375,y:.453125},{x:.390625,y:.453125},{x:.390625,y:.453125},{x:.421875,y:.453125},{x:.421875,y:.453125},{x:.453125,y:.453125},{x:.453125,y:.453125},{x:.484375,y:.453125},{x:.484375,y:.453125},{x:.515625,y:.453125},{x:.515625,y:.453125},{x:.546875,y:.453125},{x:.546875,y:.453125},{x:.578125,y:.453125},{x:.578125,y:.453125},{x:.609375,y:.453125},{x:.609375,y:.453125},{x:.640625,y:.453125},{x:.640625,y:.453125},{x:.671875,y:.453125},{x:.671875,y:.453125},{x:.703125,y:.453125},{x:.703125,y:.453125},{x:.734375,y:.453125},{x:.734375,y:.453125},{x:.765625,y:.453125},{x:.765625,y:.453125},{x:.796875,y:.453125},{x:.796875,y:.453125},{x:.828125,y:.453125},{x:.828125,y:.453125},{x:.859375,y:.453125},{x:.859375,y:.453125},{x:.890625,y:.453125},{x:.890625,y:.453125},{x:.921875,y:.453125},{x:.921875,y:.453125},{x:.953125,y:.453125},{x:.953125,y:.453125},{x:.984375,y:.453125},{x:.984375,y:.453125},{x:.015625,y:.484375},{x:.015625,y:.484375},{x:.046875,y:.484375},{x:.046875,y:.484375},{x:.078125,y:.484375},{x:.078125,y:.484375},{x:.109375,y:.484375},{x:.109375,y:.484375},{x:.140625,y:.484375},{x:.140625,y:.484375},{x:.171875,y:.484375},{x:.171875,y:.484375},{x:.203125,y:.484375},{x:.203125,y:.484375},{x:.234375,y:.484375},{x:.234375,y:.484375},{x:.265625,y:.484375},{x:.265625,y:.484375},{x:.296875,y:.484375},{x:.296875,y:.484375},{x:.328125,y:.484375},{x:.328125,y:.484375},{x:.359375,y:.484375},{x:.359375,y:.484375},{x:.390625,y:.484375},{x:.390625,y:.484375},{x:.421875,y:.484375},{x:.421875,y:.484375},{x:.453125,y:.484375},{x:.453125,y:.484375},{x:.484375,y:.484375},{x:.484375,y:.484375},{x:.515625,y:.484375},{x:.515625,y:.484375},{x:.546875,y:.484375},{x:.546875,y:.484375},{x:.578125,y:.484375},{x:.578125,y:.484375},{x:.609375,y:.484375},{x:.609375,y:.484375},{x:.640625,y:.484375},{x:.640625,y:.484375},{x:.671875,y:.484375},{x:.671875,y:.484375},{x:.703125,y:.484375},{x:.703125,y:.484375},{x:.734375,y:.484375},{x:.734375,y:.484375},{x:.765625,y:.484375},{x:.765625,y:.484375},{x:.796875,y:.484375},{x:.796875,y:.484375},{x:.828125,y:.484375},{x:.828125,y:.484375},{x:.859375,y:.484375},{x:.859375,y:.484375},{x:.890625,y:.484375},{x:.890625,y:.484375},{x:.921875,y:.484375},{x:.921875,y:.484375},{x:.953125,y:.484375},{x:.953125,y:.484375},{x:.984375,y:.484375},{x:.984375,y:.484375},{x:.015625,y:.515625},{x:.015625,y:.515625},{x:.046875,y:.515625},{x:.046875,y:.515625},{x:.078125,y:.515625},{x:.078125,y:.515625},{x:.109375,y:.515625},{x:.109375,y:.515625},{x:.140625,y:.515625},{x:.140625,y:.515625},{x:.171875,y:.515625},{x:.171875,y:.515625},{x:.203125,y:.515625},{x:.203125,y:.515625},{x:.234375,y:.515625},{x:.234375,y:.515625},{x:.265625,y:.515625},{x:.265625,y:.515625},{x:.296875,y:.515625},{x:.296875,y:.515625},{x:.328125,y:.515625},{x:.328125,y:.515625},{x:.359375,y:.515625},{x:.359375,y:.515625},{x:.390625,y:.515625},{x:.390625,y:.515625},{x:.421875,y:.515625},{x:.421875,y:.515625},{x:.453125,y:.515625},{x:.453125,y:.515625},{x:.484375,y:.515625},{x:.484375,y:.515625},{x:.515625,y:.515625},{x:.515625,y:.515625},{x:.546875,y:.515625},{x:.546875,y:.515625},{x:.578125,y:.515625},{x:.578125,y:.515625},{x:.609375,y:.515625},{x:.609375,y:.515625},{x:.640625,y:.515625},{x:.640625,y:.515625},{x:.671875,y:.515625},{x:.671875,y:.515625},{x:.703125,y:.515625},{x:.703125,y:.515625},{x:.734375,y:.515625},{x:.734375,y:.515625},{x:.765625,y:.515625},{x:.765625,y:.515625},{x:.796875,y:.515625},{x:.796875,y:.515625},{x:.828125,y:.515625},{x:.828125,y:.515625},{x:.859375,y:.515625},{x:.859375,y:.515625},{x:.890625,y:.515625},{x:.890625,y:.515625},{x:.921875,y:.515625},{x:.921875,y:.515625},{x:.953125,y:.515625},{x:.953125,y:.515625},{x:.984375,y:.515625},{x:.984375,y:.515625},{x:.015625,y:.546875},{x:.015625,y:.546875},{x:.046875,y:.546875},{x:.046875,y:.546875},{x:.078125,y:.546875},{x:.078125,y:.546875},{x:.109375,y:.546875},{x:.109375,y:.546875},{x:.140625,y:.546875},{x:.140625,y:.546875},{x:.171875,y:.546875},{x:.171875,y:.546875},{x:.203125,y:.546875},{x:.203125,y:.546875},{x:.234375,y:.546875},{x:.234375,y:.546875},{x:.265625,y:.546875},{x:.265625,y:.546875},{x:.296875,y:.546875},{x:.296875,y:.546875},{x:.328125,y:.546875},{x:.328125,y:.546875},{x:.359375,y:.546875},{x:.359375,y:.546875},{x:.390625,y:.546875},{x:.390625,y:.546875},{x:.421875,y:.546875},{x:.421875,y:.546875},{x:.453125,y:.546875},{x:.453125,y:.546875},{x:.484375,y:.546875},{x:.484375,y:.546875},{x:.515625,y:.546875},{x:.515625,y:.546875},{x:.546875,y:.546875},{x:.546875,y:.546875},{x:.578125,y:.546875},{x:.578125,y:.546875},{x:.609375,y:.546875},{x:.609375,y:.546875},{x:.640625,y:.546875},{x:.640625,y:.546875},{x:.671875,y:.546875},{x:.671875,y:.546875},{x:.703125,y:.546875},{x:.703125,y:.546875},{x:.734375,y:.546875},{x:.734375,y:.546875},{x:.765625,y:.546875},{x:.765625,y:.546875},{x:.796875,y:.546875},{x:.796875,y:.546875},{x:.828125,y:.546875},{x:.828125,y:.546875},{x:.859375,y:.546875},{x:.859375,y:.546875},{x:.890625,y:.546875},{x:.890625,y:.546875},{x:.921875,y:.546875},{x:.921875,y:.546875},{x:.953125,y:.546875},{x:.953125,y:.546875},{x:.984375,y:.546875},{x:.984375,y:.546875},{x:.015625,y:.578125},{x:.015625,y:.578125},{x:.046875,y:.578125},{x:.046875,y:.578125},{x:.078125,y:.578125},{x:.078125,y:.578125},{x:.109375,y:.578125},{x:.109375,y:.578125},{x:.140625,y:.578125},{x:.140625,y:.578125},{x:.171875,y:.578125},{x:.171875,y:.578125},{x:.203125,y:.578125},{x:.203125,y:.578125},{x:.234375,y:.578125},{x:.234375,y:.578125},{x:.265625,y:.578125},{x:.265625,y:.578125},{x:.296875,y:.578125},{x:.296875,y:.578125},{x:.328125,y:.578125},{x:.328125,y:.578125},{x:.359375,y:.578125},{x:.359375,y:.578125},{x:.390625,y:.578125},{x:.390625,y:.578125},{x:.421875,y:.578125},{x:.421875,y:.578125},{x:.453125,y:.578125},{x:.453125,y:.578125},{x:.484375,y:.578125},{x:.484375,y:.578125},{x:.515625,y:.578125},{x:.515625,y:.578125},{x:.546875,y:.578125},{x:.546875,y:.578125},{x:.578125,y:.578125},{x:.578125,y:.578125},{x:.609375,y:.578125},{x:.609375,y:.578125},{x:.640625,y:.578125},{x:.640625,y:.578125},{x:.671875,y:.578125},{x:.671875,y:.578125},{x:.703125,y:.578125},{x:.703125,y:.578125},{x:.734375,y:.578125},{x:.734375,y:.578125},{x:.765625,y:.578125},{x:.765625,y:.578125},{x:.796875,y:.578125},{x:.796875,y:.578125},{x:.828125,y:.578125},{x:.828125,y:.578125},{x:.859375,y:.578125},{x:.859375,y:.578125},{x:.890625,y:.578125},{x:.890625,y:.578125},{x:.921875,y:.578125},{x:.921875,y:.578125},{x:.953125,y:.578125},{x:.953125,y:.578125},{x:.984375,y:.578125},{x:.984375,y:.578125},{x:.015625,y:.609375},{x:.015625,y:.609375},{x:.046875,y:.609375},{x:.046875,y:.609375},{x:.078125,y:.609375},{x:.078125,y:.609375},{x:.109375,y:.609375},{x:.109375,y:.609375},{x:.140625,y:.609375},{x:.140625,y:.609375},{x:.171875,y:.609375},{x:.171875,y:.609375},{x:.203125,y:.609375},{x:.203125,y:.609375},{x:.234375,y:.609375},{x:.234375,y:.609375},{x:.265625,y:.609375},{x:.265625,y:.609375},{x:.296875,y:.609375},{x:.296875,y:.609375},{x:.328125,y:.609375},{x:.328125,y:.609375},{x:.359375,y:.609375},{x:.359375,y:.609375},{x:.390625,y:.609375},{x:.390625,y:.609375},{x:.421875,y:.609375},{x:.421875,y:.609375},{x:.453125,y:.609375},{x:.453125,y:.609375},{x:.484375,y:.609375},{x:.484375,y:.609375},{x:.515625,y:.609375},{x:.515625,y:.609375},{x:.546875,y:.609375},{x:.546875,y:.609375},{x:.578125,y:.609375},{x:.578125,y:.609375},{x:.609375,y:.609375},{x:.609375,y:.609375},{x:.640625,y:.609375},{x:.640625,y:.609375},{x:.671875,y:.609375},{x:.671875,y:.609375},{x:.703125,y:.609375},{x:.703125,y:.609375},{x:.734375,y:.609375},{x:.734375,y:.609375},{x:.765625,y:.609375},{x:.765625,y:.609375},{x:.796875,y:.609375},{x:.796875,y:.609375},{x:.828125,y:.609375},{x:.828125,y:.609375},{x:.859375,y:.609375},{x:.859375,y:.609375},{x:.890625,y:.609375},{x:.890625,y:.609375},{x:.921875,y:.609375},{x:.921875,y:.609375},{x:.953125,y:.609375},{x:.953125,y:.609375},{x:.984375,y:.609375},{x:.984375,y:.609375},{x:.015625,y:.640625},{x:.015625,y:.640625},{x:.046875,y:.640625},{x:.046875,y:.640625},{x:.078125,y:.640625},{x:.078125,y:.640625},{x:.109375,y:.640625},{x:.109375,y:.640625},{x:.140625,y:.640625},{x:.140625,y:.640625},{x:.171875,y:.640625},{x:.171875,y:.640625},{x:.203125,y:.640625},{x:.203125,y:.640625},{x:.234375,y:.640625},{x:.234375,y:.640625},{x:.265625,y:.640625},{x:.265625,y:.640625},{x:.296875,y:.640625},{x:.296875,y:.640625},{x:.328125,y:.640625},{x:.328125,y:.640625},{x:.359375,y:.640625},{x:.359375,y:.640625},{x:.390625,y:.640625},{x:.390625,y:.640625},{x:.421875,y:.640625},{x:.421875,y:.640625},{x:.453125,y:.640625},{x:.453125,y:.640625},{x:.484375,y:.640625},{x:.484375,y:.640625},{x:.515625,y:.640625},{x:.515625,y:.640625},{x:.546875,y:.640625},{x:.546875,y:.640625},{x:.578125,y:.640625},{x:.578125,y:.640625},{x:.609375,y:.640625},{x:.609375,y:.640625},{x:.640625,y:.640625},{x:.640625,y:.640625},{x:.671875,y:.640625},{x:.671875,y:.640625},{x:.703125,y:.640625},{x:.703125,y:.640625},{x:.734375,y:.640625},{x:.734375,y:.640625},{x:.765625,y:.640625},{x:.765625,y:.640625},{x:.796875,y:.640625},{x:.796875,y:.640625},{x:.828125,y:.640625},{x:.828125,y:.640625},{x:.859375,y:.640625},{x:.859375,y:.640625},{x:.890625,y:.640625},{x:.890625,y:.640625},{x:.921875,y:.640625},{x:.921875,y:.640625},{x:.953125,y:.640625},{x:.953125,y:.640625},{x:.984375,y:.640625},{x:.984375,y:.640625},{x:.015625,y:.671875},{x:.015625,y:.671875},{x:.046875,y:.671875},{x:.046875,y:.671875},{x:.078125,y:.671875},{x:.078125,y:.671875},{x:.109375,y:.671875},{x:.109375,y:.671875},{x:.140625,y:.671875},{x:.140625,y:.671875},{x:.171875,y:.671875},{x:.171875,y:.671875},{x:.203125,y:.671875},{x:.203125,y:.671875},{x:.234375,y:.671875},{x:.234375,y:.671875},{x:.265625,y:.671875},{x:.265625,y:.671875},{x:.296875,y:.671875},{x:.296875,y:.671875},{x:.328125,y:.671875},{x:.328125,y:.671875},{x:.359375,y:.671875},{x:.359375,y:.671875},{x:.390625,y:.671875},{x:.390625,y:.671875},{x:.421875,y:.671875},{x:.421875,y:.671875},{x:.453125,y:.671875},{x:.453125,y:.671875},{x:.484375,y:.671875},{x:.484375,y:.671875},{x:.515625,y:.671875},{x:.515625,y:.671875},{x:.546875,y:.671875},{x:.546875,y:.671875},{x:.578125,y:.671875},{x:.578125,y:.671875},{x:.609375,y:.671875},{x:.609375,y:.671875},{x:.640625,y:.671875},{x:.640625,y:.671875},{x:.671875,y:.671875},{x:.671875,y:.671875},{x:.703125,y:.671875},{x:.703125,y:.671875},{x:.734375,y:.671875},{x:.734375,y:.671875},{x:.765625,y:.671875},{x:.765625,y:.671875},{x:.796875,y:.671875},{x:.796875,y:.671875},{x:.828125,y:.671875},{x:.828125,y:.671875},{x:.859375,y:.671875},{x:.859375,y:.671875},{x:.890625,y:.671875},{x:.890625,y:.671875},{x:.921875,y:.671875},{x:.921875,y:.671875},{x:.953125,y:.671875},{x:.953125,y:.671875},{x:.984375,y:.671875},{x:.984375,y:.671875},{x:.015625,y:.703125},{x:.015625,y:.703125},{x:.046875,y:.703125},{x:.046875,y:.703125},{x:.078125,y:.703125},{x:.078125,y:.703125},{x:.109375,y:.703125},{x:.109375,y:.703125},{x:.140625,y:.703125},{x:.140625,y:.703125},{x:.171875,y:.703125},{x:.171875,y:.703125},{x:.203125,y:.703125},{x:.203125,y:.703125},{x:.234375,y:.703125},{x:.234375,y:.703125},{x:.265625,y:.703125},{x:.265625,y:.703125},{x:.296875,y:.703125},{x:.296875,y:.703125},{x:.328125,y:.703125},{x:.328125,y:.703125},{x:.359375,y:.703125},{x:.359375,y:.703125},{x:.390625,y:.703125},{x:.390625,y:.703125},{x:.421875,y:.703125},{x:.421875,y:.703125},{x:.453125,y:.703125},{x:.453125,y:.703125},{x:.484375,y:.703125},{x:.484375,y:.703125},{x:.515625,y:.703125},{x:.515625,y:.703125},{x:.546875,y:.703125},{x:.546875,y:.703125},{x:.578125,y:.703125},{x:.578125,y:.703125},{x:.609375,y:.703125},{x:.609375,y:.703125},{x:.640625,y:.703125},{x:.640625,y:.703125},{x:.671875,y:.703125},{x:.671875,y:.703125},{x:.703125,y:.703125},{x:.703125,y:.703125},{x:.734375,y:.703125},{x:.734375,y:.703125},{x:.765625,y:.703125},{x:.765625,y:.703125},{x:.796875,y:.703125},{x:.796875,y:.703125},{x:.828125,y:.703125},{x:.828125,y:.703125},{x:.859375,y:.703125},{x:.859375,y:.703125},{x:.890625,y:.703125},{x:.890625,y:.703125},{x:.921875,y:.703125},{x:.921875,y:.703125},{x:.953125,y:.703125},{x:.953125,y:.703125},{x:.984375,y:.703125},{x:.984375,y:.703125},{x:.015625,y:.734375},{x:.015625,y:.734375},{x:.046875,y:.734375},{x:.046875,y:.734375},{x:.078125,y:.734375},{x:.078125,y:.734375},{x:.109375,y:.734375},{x:.109375,y:.734375},{x:.140625,y:.734375},{x:.140625,y:.734375},{x:.171875,y:.734375},{x:.171875,y:.734375},{x:.203125,y:.734375},{x:.203125,y:.734375},{x:.234375,y:.734375},{x:.234375,y:.734375},{x:.265625,y:.734375},{x:.265625,y:.734375},{x:.296875,y:.734375},{x:.296875,y:.734375},{x:.328125,y:.734375},{x:.328125,y:.734375},{x:.359375,y:.734375},{x:.359375,y:.734375},{x:.390625,y:.734375},{x:.390625,y:.734375},{x:.421875,y:.734375},{x:.421875,y:.734375},{x:.453125,y:.734375},{x:.453125,y:.734375},{x:.484375,y:.734375},{x:.484375,y:.734375},{x:.515625,y:.734375},{x:.515625,y:.734375},{x:.546875,y:.734375},{x:.546875,y:.734375},{x:.578125,y:.734375},{x:.578125,y:.734375},{x:.609375,y:.734375},{x:.609375,y:.734375},{x:.640625,y:.734375},{x:.640625,y:.734375},{x:.671875,y:.734375},{x:.671875,y:.734375},{x:.703125,y:.734375},{x:.703125,y:.734375},{x:.734375,y:.734375},{x:.734375,y:.734375},{x:.765625,y:.734375},{x:.765625,y:.734375},{x:.796875,y:.734375},{x:.796875,y:.734375},{x:.828125,y:.734375},{x:.828125,y:.734375},{x:.859375,y:.734375},{x:.859375,y:.734375},{x:.890625,y:.734375},{x:.890625,y:.734375},{x:.921875,y:.734375},{x:.921875,y:.734375},{x:.953125,y:.734375},{x:.953125,y:.734375},{x:.984375,y:.734375},{x:.984375,y:.734375},{x:.015625,y:.765625},{x:.015625,y:.765625},{x:.046875,y:.765625},{x:.046875,y:.765625},{x:.078125,y:.765625},{x:.078125,y:.765625},{x:.109375,y:.765625},{x:.109375,y:.765625},{x:.140625,y:.765625},{x:.140625,y:.765625},{x:.171875,y:.765625},{x:.171875,y:.765625},{x:.203125,y:.765625},{x:.203125,y:.765625},{x:.234375,y:.765625},{x:.234375,y:.765625},{x:.265625,y:.765625},{x:.265625,y:.765625},{x:.296875,y:.765625},{x:.296875,y:.765625},{x:.328125,y:.765625},{x:.328125,y:.765625},{x:.359375,y:.765625},{x:.359375,y:.765625},{x:.390625,y:.765625},{x:.390625,y:.765625},{x:.421875,y:.765625},{x:.421875,y:.765625},{x:.453125,y:.765625},{x:.453125,y:.765625},{x:.484375,y:.765625},{x:.484375,y:.765625},{x:.515625,y:.765625},{x:.515625,y:.765625},{x:.546875,y:.765625},{x:.546875,y:.765625},{x:.578125,y:.765625},{x:.578125,y:.765625},{x:.609375,y:.765625},{x:.609375,y:.765625},{x:.640625,y:.765625},{x:.640625,y:.765625},{x:.671875,y:.765625},{x:.671875,y:.765625},{x:.703125,y:.765625},{x:.703125,y:.765625},{x:.734375,y:.765625},{x:.734375,y:.765625},{x:.765625,y:.765625},{x:.765625,y:.765625},{x:.796875,y:.765625},{x:.796875,y:.765625},{x:.828125,y:.765625},{x:.828125,y:.765625},{x:.859375,y:.765625},{x:.859375,y:.765625},{x:.890625,y:.765625},{x:.890625,y:.765625},{x:.921875,y:.765625},{x:.921875,y:.765625},{x:.953125,y:.765625},{x:.953125,y:.765625},{x:.984375,y:.765625},{x:.984375,y:.765625},{x:.015625,y:.796875},{x:.015625,y:.796875},{x:.046875,y:.796875},{x:.046875,y:.796875},{x:.078125,y:.796875},{x:.078125,y:.796875},{x:.109375,y:.796875},{x:.109375,y:.796875},{x:.140625,y:.796875},{x:.140625,y:.796875},{x:.171875,y:.796875},{x:.171875,y:.796875},{x:.203125,y:.796875},{x:.203125,y:.796875},{x:.234375,y:.796875},{x:.234375,y:.796875},{x:.265625,y:.796875},{x:.265625,y:.796875},{x:.296875,y:.796875},{x:.296875,y:.796875},{x:.328125,y:.796875},{x:.328125,y:.796875},{x:.359375,y:.796875},{x:.359375,y:.796875},{x:.390625,y:.796875},{x:.390625,y:.796875},{x:.421875,y:.796875},{x:.421875,y:.796875},{x:.453125,y:.796875},{x:.453125,y:.796875},{x:.484375,y:.796875},{x:.484375,y:.796875},{x:.515625,y:.796875},{x:.515625,y:.796875},{x:.546875,y:.796875},{x:.546875,y:.796875},{x:.578125,y:.796875},{x:.578125,y:.796875},{x:.609375,y:.796875},{x:.609375,y:.796875},{x:.640625,y:.796875},{x:.640625,y:.796875},{x:.671875,y:.796875},{x:.671875,y:.796875},{x:.703125,y:.796875},{x:.703125,y:.796875},{x:.734375,y:.796875},{x:.734375,y:.796875},{x:.765625,y:.796875},{x:.765625,y:.796875},{x:.796875,y:.796875},{x:.796875,y:.796875},{x:.828125,y:.796875},{x:.828125,y:.796875},{x:.859375,y:.796875},{x:.859375,y:.796875},{x:.890625,y:.796875},{x:.890625,y:.796875},{x:.921875,y:.796875},{x:.921875,y:.796875},{x:.953125,y:.796875},{x:.953125,y:.796875},{x:.984375,y:.796875},{x:.984375,y:.796875},{x:.015625,y:.828125},{x:.015625,y:.828125},{x:.046875,y:.828125},{x:.046875,y:.828125},{x:.078125,y:.828125},{x:.078125,y:.828125},{x:.109375,y:.828125},{x:.109375,y:.828125},{x:.140625,y:.828125},{x:.140625,y:.828125},{x:.171875,y:.828125},{x:.171875,y:.828125},{x:.203125,y:.828125},{x:.203125,y:.828125},{x:.234375,y:.828125},{x:.234375,y:.828125},{x:.265625,y:.828125},{x:.265625,y:.828125},{x:.296875,y:.828125},{x:.296875,y:.828125},{x:.328125,y:.828125},{x:.328125,y:.828125},{x:.359375,y:.828125},{x:.359375,y:.828125},{x:.390625,y:.828125},{x:.390625,y:.828125},{x:.421875,y:.828125},{x:.421875,y:.828125},{x:.453125,y:.828125},{x:.453125,y:.828125},{x:.484375,y:.828125},{x:.484375,y:.828125},{x:.515625,y:.828125},{x:.515625,y:.828125},{x:.546875,y:.828125},{x:.546875,y:.828125},{x:.578125,y:.828125},{x:.578125,y:.828125},{x:.609375,y:.828125},{x:.609375,y:.828125},{x:.640625,y:.828125},{x:.640625,y:.828125},{x:.671875,y:.828125},{x:.671875,y:.828125},{x:.703125,y:.828125},{x:.703125,y:.828125},{x:.734375,y:.828125},{x:.734375,y:.828125},{x:.765625,y:.828125},{x:.765625,y:.828125},{x:.796875,y:.828125},{x:.796875,y:.828125},{x:.828125,y:.828125},{x:.828125,y:.828125},{x:.859375,y:.828125},{x:.859375,y:.828125},{x:.890625,y:.828125},{x:.890625,y:.828125},{x:.921875,y:.828125},{x:.921875,y:.828125},{x:.953125,y:.828125},{x:.953125,y:.828125},{x:.984375,y:.828125},{x:.984375,y:.828125},{x:.015625,y:.859375},{x:.015625,y:.859375},{x:.046875,y:.859375},{x:.046875,y:.859375},{x:.078125,y:.859375},{x:.078125,y:.859375},{x:.109375,y:.859375},{x:.109375,y:.859375},{x:.140625,y:.859375},{x:.140625,y:.859375},{x:.171875,y:.859375},{x:.171875,y:.859375},{x:.203125,y:.859375},{x:.203125,y:.859375},{x:.234375,y:.859375},{x:.234375,y:.859375},{x:.265625,y:.859375},{x:.265625,y:.859375},{x:.296875,y:.859375},{x:.296875,y:.859375},{x:.328125,y:.859375},{x:.328125,y:.859375},{x:.359375,y:.859375},{x:.359375,y:.859375},{x:.390625,y:.859375},{x:.390625,y:.859375},{x:.421875,y:.859375},{x:.421875,y:.859375},{x:.453125,y:.859375},{x:.453125,y:.859375},{x:.484375,y:.859375},{x:.484375,y:.859375},{x:.515625,y:.859375},{x:.515625,y:.859375},{x:.546875,y:.859375},{x:.546875,y:.859375},{x:.578125,y:.859375},{x:.578125,y:.859375},{x:.609375,y:.859375},{x:.609375,y:.859375},{x:.640625,y:.859375},{x:.640625,y:.859375},{x:.671875,y:.859375},{x:.671875,y:.859375},{x:.703125,y:.859375},{x:.703125,y:.859375},{x:.734375,y:.859375},{x:.734375,y:.859375},{x:.765625,y:.859375},{x:.765625,y:.859375},{x:.796875,y:.859375},{x:.796875,y:.859375},{x:.828125,y:.859375},{x:.828125,y:.859375},{x:.859375,y:.859375},{x:.859375,y:.859375},{x:.890625,y:.859375},{x:.890625,y:.859375},{x:.921875,y:.859375},{x:.921875,y:.859375},{x:.953125,y:.859375},{x:.953125,y:.859375},{x:.984375,y:.859375},{x:.984375,y:.859375},{x:.015625,y:.890625},{x:.015625,y:.890625},{x:.046875,y:.890625},{x:.046875,y:.890625},{x:.078125,y:.890625},{x:.078125,y:.890625},{x:.109375,y:.890625},{x:.109375,y:.890625},{x:.140625,y:.890625},{x:.140625,y:.890625},{x:.171875,y:.890625},{x:.171875,y:.890625},{x:.203125,y:.890625},{x:.203125,y:.890625},{x:.234375,y:.890625},{x:.234375,y:.890625},{x:.265625,y:.890625},{x:.265625,y:.890625},{x:.296875,y:.890625},{x:.296875,y:.890625},{x:.328125,y:.890625},{x:.328125,y:.890625},{x:.359375,y:.890625},{x:.359375,y:.890625},{x:.390625,y:.890625},{x:.390625,y:.890625},{x:.421875,y:.890625},{x:.421875,y:.890625},{x:.453125,y:.890625},{x:.453125,y:.890625},{x:.484375,y:.890625},{x:.484375,y:.890625},{x:.515625,y:.890625},{x:.515625,y:.890625},{x:.546875,y:.890625},{x:.546875,y:.890625},{x:.578125,y:.890625},{x:.578125,y:.890625},{x:.609375,y:.890625},{x:.609375,y:.890625},{x:.640625,y:.890625},{x:.640625,y:.890625},{x:.671875,y:.890625},{x:.671875,y:.890625},{x:.703125,y:.890625},{x:.703125,y:.890625},{x:.734375,y:.890625},{x:.734375,y:.890625},{x:.765625,y:.890625},{x:.765625,y:.890625},{x:.796875,y:.890625},{x:.796875,y:.890625},{x:.828125,y:.890625},{x:.828125,y:.890625},{x:.859375,y:.890625},{x:.859375,y:.890625},{x:.890625,y:.890625},{x:.890625,y:.890625},{x:.921875,y:.890625},{x:.921875,y:.890625},{x:.953125,y:.890625},{x:.953125,y:.890625},{x:.984375,y:.890625},{x:.984375,y:.890625},{x:.015625,y:.921875},{x:.015625,y:.921875},{x:.046875,y:.921875},{x:.046875,y:.921875},{x:.078125,y:.921875},{x:.078125,y:.921875},{x:.109375,y:.921875},{x:.109375,y:.921875},{x:.140625,y:.921875},{x:.140625,y:.921875},{x:.171875,y:.921875},{x:.171875,y:.921875},{x:.203125,y:.921875},{x:.203125,y:.921875},{x:.234375,y:.921875},{x:.234375,y:.921875},{x:.265625,y:.921875},{x:.265625,y:.921875},{x:.296875,y:.921875},{x:.296875,y:.921875},{x:.328125,y:.921875},{x:.328125,y:.921875},{x:.359375,y:.921875},{x:.359375,y:.921875},{x:.390625,y:.921875},{x:.390625,y:.921875},{x:.421875,y:.921875},{x:.421875,y:.921875},{x:.453125,y:.921875},{x:.453125,y:.921875},{x:.484375,y:.921875},{x:.484375,y:.921875},{x:.515625,y:.921875},{x:.515625,y:.921875},{x:.546875,y:.921875},{x:.546875,y:.921875},{x:.578125,y:.921875},{x:.578125,y:.921875},{x:.609375,y:.921875},{x:.609375,y:.921875},{x:.640625,y:.921875},{x:.640625,y:.921875},{x:.671875,y:.921875},{x:.671875,y:.921875},{x:.703125,y:.921875},{x:.703125,y:.921875},{x:.734375,y:.921875},{x:.734375,y:.921875},{x:.765625,y:.921875},{x:.765625,y:.921875},{x:.796875,y:.921875},{x:.796875,y:.921875},{x:.828125,y:.921875},{x:.828125,y:.921875},{x:.859375,y:.921875},{x:.859375,y:.921875},{x:.890625,y:.921875},{x:.890625,y:.921875},{x:.921875,y:.921875},{x:.921875,y:.921875},{x:.953125,y:.921875},{x:.953125,y:.921875},{x:.984375,y:.921875},{x:.984375,y:.921875},{x:.015625,y:.953125},{x:.015625,y:.953125},{x:.046875,y:.953125},{x:.046875,y:.953125},{x:.078125,y:.953125},{x:.078125,y:.953125},{x:.109375,y:.953125},{x:.109375,y:.953125},{x:.140625,y:.953125},{x:.140625,y:.953125},{x:.171875,y:.953125},{x:.171875,y:.953125},{x:.203125,y:.953125},{x:.203125,y:.953125},{x:.234375,y:.953125},{x:.234375,y:.953125},{x:.265625,y:.953125},{x:.265625,y:.953125},{x:.296875,y:.953125},{x:.296875,y:.953125},{x:.328125,y:.953125},{x:.328125,y:.953125},{x:.359375,y:.953125},{x:.359375,y:.953125},{x:.390625,y:.953125},{x:.390625,y:.953125},{x:.421875,y:.953125},{x:.421875,y:.953125},{x:.453125,y:.953125},{x:.453125,y:.953125},{x:.484375,y:.953125},{x:.484375,y:.953125},{x:.515625,y:.953125},{x:.515625,y:.953125},{x:.546875,y:.953125},{x:.546875,y:.953125},{x:.578125,y:.953125},{x:.578125,y:.953125},{x:.609375,y:.953125},{x:.609375,y:.953125},{x:.640625,y:.953125},{x:.640625,y:.953125},{x:.671875,y:.953125},{x:.671875,y:.953125},{x:.703125,y:.953125},{x:.703125,y:.953125},{x:.734375,y:.953125},{x:.734375,y:.953125},{x:.765625,y:.953125},{x:.765625,y:.953125},{x:.796875,y:.953125},{x:.796875,y:.953125},{x:.828125,y:.953125},{x:.828125,y:.953125},{x:.859375,y:.953125},{x:.859375,y:.953125},{x:.890625,y:.953125},{x:.890625,y:.953125},{x:.921875,y:.953125},{x:.921875,y:.953125},{x:.953125,y:.953125},{x:.953125,y:.953125},{x:.984375,y:.953125},{x:.984375,y:.953125},{x:.015625,y:.984375},{x:.015625,y:.984375},{x:.046875,y:.984375},{x:.046875,y:.984375},{x:.078125,y:.984375},{x:.078125,y:.984375},{x:.109375,y:.984375},{x:.109375,y:.984375},{x:.140625,y:.984375},{x:.140625,y:.984375},{x:.171875,y:.984375},{x:.171875,y:.984375},{x:.203125,y:.984375},{x:.203125,y:.984375},{x:.234375,y:.984375},{x:.234375,y:.984375},{x:.265625,y:.984375},{x:.265625,y:.984375},{x:.296875,y:.984375},{x:.296875,y:.984375},{x:.328125,y:.984375},{x:.328125,y:.984375},{x:.359375,y:.984375},{x:.359375,y:.984375},{x:.390625,y:.984375},{x:.390625,y:.984375},{x:.421875,y:.984375},{x:.421875,y:.984375},{x:.453125,y:.984375},{x:.453125,y:.984375},{x:.484375,y:.984375},{x:.484375,y:.984375},{x:.515625,y:.984375},{x:.515625,y:.984375},{x:.546875,y:.984375},{x:.546875,y:.984375},{x:.578125,y:.984375},{x:.578125,y:.984375},{x:.609375,y:.984375},{x:.609375,y:.984375},{x:.640625,y:.984375},{x:.640625,y:.984375},{x:.671875,y:.984375},{x:.671875,y:.984375},{x:.703125,y:.984375},{x:.703125,y:.984375},{x:.734375,y:.984375},{x:.734375,y:.984375},{x:.765625,y:.984375},{x:.765625,y:.984375},{x:.796875,y:.984375},{x:.796875,y:.984375},{x:.828125,y:.984375},{x:.828125,y:.984375},{x:.859375,y:.984375},{x:.859375,y:.984375},{x:.890625,y:.984375},{x:.890625,y:.984375},{x:.921875,y:.984375},{x:.921875,y:.984375},{x:.953125,y:.984375},{x:.953125,y:.984375},{x:.984375,y:.984375},{x:.984375,y:.984375},{x:.03125,y:.03125},{x:.03125,y:.03125},{x:.09375,y:.03125},{x:.09375,y:.03125},{x:.15625,y:.03125},{x:.15625,y:.03125},{x:.21875,y:.03125},{x:.21875,y:.03125},{x:.28125,y:.03125},{x:.28125,y:.03125},{x:.34375,y:.03125},{x:.34375,y:.03125},{x:.40625,y:.03125},{x:.40625,y:.03125},{x:.46875,y:.03125},{x:.46875,y:.03125},{x:.53125,y:.03125},{x:.53125,y:.03125},{x:.59375,y:.03125},{x:.59375,y:.03125},{x:.65625,y:.03125},{x:.65625,y:.03125},{x:.71875,y:.03125},{x:.71875,y:.03125},{x:.78125,y:.03125},{x:.78125,y:.03125},{x:.84375,y:.03125},{x:.84375,y:.03125},{x:.90625,y:.03125},{x:.90625,y:.03125},{x:.96875,y:.03125},{x:.96875,y:.03125},{x:.03125,y:.09375},{x:.03125,y:.09375},{x:.09375,y:.09375},{x:.09375,y:.09375},{x:.15625,y:.09375},{x:.15625,y:.09375},{x:.21875,y:.09375},{x:.21875,y:.09375},{x:.28125,y:.09375},{x:.28125,y:.09375},{x:.34375,y:.09375},{x:.34375,y:.09375},{x:.40625,y:.09375},{x:.40625,y:.09375},{x:.46875,y:.09375},{x:.46875,y:.09375},{x:.53125,y:.09375},{x:.53125,y:.09375},{x:.59375,y:.09375},{x:.59375,y:.09375},{x:.65625,y:.09375},{x:.65625,y:.09375},{x:.71875,y:.09375},{x:.71875,y:.09375},{x:.78125,y:.09375},{x:.78125,y:.09375},{x:.84375,y:.09375},{x:.84375,y:.09375},{x:.90625,y:.09375},{x:.90625,y:.09375},{x:.96875,y:.09375},{x:.96875,y:.09375},{x:.03125,y:.15625},{x:.03125,y:.15625},{x:.09375,y:.15625},{x:.09375,y:.15625},{x:.15625,y:.15625},{x:.15625,y:.15625},{x:.21875,y:.15625},{x:.21875,y:.15625},{x:.28125,y:.15625},{x:.28125,y:.15625},{x:.34375,y:.15625},{x:.34375,y:.15625},{x:.40625,y:.15625},{x:.40625,y:.15625},{x:.46875,y:.15625},{x:.46875,y:.15625},{x:.53125,y:.15625},{x:.53125,y:.15625},{x:.59375,y:.15625},{x:.59375,y:.15625},{x:.65625,y:.15625},{x:.65625,y:.15625},{x:.71875,y:.15625},{x:.71875,y:.15625},{x:.78125,y:.15625},{x:.78125,y:.15625},{x:.84375,y:.15625},{x:.84375,y:.15625},{x:.90625,y:.15625},{x:.90625,y:.15625},{x:.96875,y:.15625},{x:.96875,y:.15625},{x:.03125,y:.21875},{x:.03125,y:.21875},{x:.09375,y:.21875},{x:.09375,y:.21875},{x:.15625,y:.21875},{x:.15625,y:.21875},{x:.21875,y:.21875},{x:.21875,y:.21875},{x:.28125,y:.21875},{x:.28125,y:.21875},{x:.34375,y:.21875},{x:.34375,y:.21875},{x:.40625,y:.21875},{x:.40625,y:.21875},{x:.46875,y:.21875},{x:.46875,y:.21875},{x:.53125,y:.21875},{x:.53125,y:.21875},{x:.59375,y:.21875},{x:.59375,y:.21875},{x:.65625,y:.21875},{x:.65625,y:.21875},{x:.71875,y:.21875},{x:.71875,y:.21875},{x:.78125,y:.21875},{x:.78125,y:.21875},{x:.84375,y:.21875},{x:.84375,y:.21875},{x:.90625,y:.21875},{x:.90625,y:.21875},{x:.96875,y:.21875},{x:.96875,y:.21875},{x:.03125,y:.28125},{x:.03125,y:.28125},{x:.09375,y:.28125},{x:.09375,y:.28125},{x:.15625,y:.28125},{x:.15625,y:.28125},{x:.21875,y:.28125},{x:.21875,y:.28125},{x:.28125,y:.28125},{x:.28125,y:.28125},{x:.34375,y:.28125},{x:.34375,y:.28125},{x:.40625,y:.28125},{x:.40625,y:.28125},{x:.46875,y:.28125},{x:.46875,y:.28125},{x:.53125,y:.28125},{x:.53125,y:.28125},{x:.59375,y:.28125},{x:.59375,y:.28125},{x:.65625,y:.28125},{x:.65625,y:.28125},{x:.71875,y:.28125},{x:.71875,y:.28125},{x:.78125,y:.28125},{x:.78125,y:.28125},{x:.84375,y:.28125},{x:.84375,y:.28125},{x:.90625,y:.28125},{x:.90625,y:.28125},{x:.96875,y:.28125},{x:.96875,y:.28125},{x:.03125,y:.34375},{x:.03125,y:.34375},{x:.09375,y:.34375},{x:.09375,y:.34375},{x:.15625,y:.34375},{x:.15625,y:.34375},{x:.21875,y:.34375},{x:.21875,y:.34375},{x:.28125,y:.34375},{x:.28125,y:.34375},{x:.34375,y:.34375},{x:.34375,y:.34375},{x:.40625,y:.34375},{x:.40625,y:.34375},{x:.46875,y:.34375},{x:.46875,y:.34375},{x:.53125,y:.34375},{x:.53125,y:.34375},{x:.59375,y:.34375},{x:.59375,y:.34375},{x:.65625,y:.34375},{x:.65625,y:.34375},{x:.71875,y:.34375},{x:.71875,y:.34375},{x:.78125,y:.34375},{x:.78125,y:.34375},{x:.84375,y:.34375},{x:.84375,y:.34375},{x:.90625,y:.34375},{x:.90625,y:.34375},{x:.96875,y:.34375},{x:.96875,y:.34375},{x:.03125,y:.40625},{x:.03125,y:.40625},{x:.09375,y:.40625},{x:.09375,y:.40625},{x:.15625,y:.40625},{x:.15625,y:.40625},{x:.21875,y:.40625},{x:.21875,y:.40625},{x:.28125,y:.40625},{x:.28125,y:.40625},{x:.34375,y:.40625},{x:.34375,y:.40625},{x:.40625,y:.40625},{x:.40625,y:.40625},{x:.46875,y:.40625},{x:.46875,y:.40625},{x:.53125,y:.40625},{x:.53125,y:.40625},{x:.59375,y:.40625},{x:.59375,y:.40625},{x:.65625,y:.40625},{x:.65625,y:.40625},{x:.71875,y:.40625},{x:.71875,y:.40625},{x:.78125,y:.40625},{x:.78125,y:.40625},{x:.84375,y:.40625},{x:.84375,y:.40625},{x:.90625,y:.40625},{x:.90625,y:.40625},{x:.96875,y:.40625},{x:.96875,y:.40625},{x:.03125,y:.46875},{x:.03125,y:.46875},{x:.09375,y:.46875},{x:.09375,y:.46875},{x:.15625,y:.46875},{x:.15625,y:.46875},{x:.21875,y:.46875},{x:.21875,y:.46875},{x:.28125,y:.46875},{x:.28125,y:.46875},{x:.34375,y:.46875},{x:.34375,y:.46875},{x:.40625,y:.46875},{x:.40625,y:.46875},{x:.46875,y:.46875},{x:.46875,y:.46875},{x:.53125,y:.46875},{x:.53125,y:.46875},{x:.59375,y:.46875},{x:.59375,y:.46875},{x:.65625,y:.46875},{x:.65625,y:.46875},{x:.71875,y:.46875},{x:.71875,y:.46875},{x:.78125,y:.46875},{x:.78125,y:.46875},{x:.84375,y:.46875},{x:.84375,y:.46875},{x:.90625,y:.46875},{x:.90625,y:.46875},{x:.96875,y:.46875},{x:.96875,y:.46875},{x:.03125,y:.53125},{x:.03125,y:.53125},{x:.09375,y:.53125},{x:.09375,y:.53125},{x:.15625,y:.53125},{x:.15625,y:.53125},{x:.21875,y:.53125},{x:.21875,y:.53125},{x:.28125,y:.53125},{x:.28125,y:.53125},{x:.34375,y:.53125},{x:.34375,y:.53125},{x:.40625,y:.53125},{x:.40625,y:.53125},{x:.46875,y:.53125},{x:.46875,y:.53125},{x:.53125,y:.53125},{x:.53125,y:.53125},{x:.59375,y:.53125},{x:.59375,y:.53125},{x:.65625,y:.53125},{x:.65625,y:.53125},{x:.71875,y:.53125},{x:.71875,y:.53125},{x:.78125,y:.53125},{x:.78125,y:.53125},{x:.84375,y:.53125},{x:.84375,y:.53125},{x:.90625,y:.53125},{x:.90625,y:.53125},{x:.96875,y:.53125},{x:.96875,y:.53125},{x:.03125,y:.59375},{x:.03125,y:.59375},{x:.09375,y:.59375},{x:.09375,y:.59375},{x:.15625,y:.59375},{x:.15625,y:.59375},{x:.21875,y:.59375},{x:.21875,y:.59375},{x:.28125,y:.59375},{x:.28125,y:.59375},{x:.34375,y:.59375},{x:.34375,y:.59375},{x:.40625,y:.59375},{x:.40625,y:.59375},{x:.46875,y:.59375},{x:.46875,y:.59375},{x:.53125,y:.59375},{x:.53125,y:.59375},{x:.59375,y:.59375},{x:.59375,y:.59375},{x:.65625,y:.59375},{x:.65625,y:.59375},{x:.71875,y:.59375},{x:.71875,y:.59375},{x:.78125,y:.59375},{x:.78125,y:.59375},{x:.84375,y:.59375},{x:.84375,y:.59375},{x:.90625,y:.59375},{x:.90625,y:.59375},{x:.96875,y:.59375},{x:.96875,y:.59375},{x:.03125,y:.65625},{x:.03125,y:.65625},{x:.09375,y:.65625},{x:.09375,y:.65625},{x:.15625,y:.65625},{x:.15625,y:.65625},{x:.21875,y:.65625},{x:.21875,y:.65625},{x:.28125,y:.65625},{x:.28125,y:.65625},{x:.34375,y:.65625},{x:.34375,y:.65625},{x:.40625,y:.65625},{x:.40625,y:.65625},{x:.46875,y:.65625},{x:.46875,y:.65625},{x:.53125,y:.65625},{x:.53125,y:.65625},{x:.59375,y:.65625},{x:.59375,y:.65625},{x:.65625,y:.65625},{x:.65625,y:.65625},{x:.71875,y:.65625},{x:.71875,y:.65625},{x:.78125,y:.65625},{x:.78125,y:.65625},{x:.84375,y:.65625},{x:.84375,y:.65625},{x:.90625,y:.65625},{x:.90625,y:.65625},{x:.96875,y:.65625},{x:.96875,y:.65625},{x:.03125,y:.71875},{x:.03125,y:.71875},{x:.09375,y:.71875},{x:.09375,y:.71875},{x:.15625,y:.71875},{x:.15625,y:.71875},{x:.21875,y:.71875},{x:.21875,y:.71875},{x:.28125,y:.71875},{x:.28125,y:.71875},{x:.34375,y:.71875},{x:.34375,y:.71875},{x:.40625,y:.71875},{x:.40625,y:.71875},{x:.46875,y:.71875},{x:.46875,y:.71875},{x:.53125,y:.71875},{x:.53125,y:.71875},{x:.59375,y:.71875},{x:.59375,y:.71875},{x:.65625,y:.71875},{x:.65625,y:.71875},{x:.71875,y:.71875},{x:.71875,y:.71875},{x:.78125,y:.71875},{x:.78125,y:.71875},{x:.84375,y:.71875},{x:.84375,y:.71875},{x:.90625,y:.71875},{x:.90625,y:.71875},{x:.96875,y:.71875},{x:.96875,y:.71875},{x:.03125,y:.78125},{x:.03125,y:.78125},{x:.09375,y:.78125},{x:.09375,y:.78125},{x:.15625,y:.78125},{x:.15625,y:.78125},{x:.21875,y:.78125},{x:.21875,y:.78125},{x:.28125,y:.78125},{x:.28125,y:.78125},{x:.34375,y:.78125},{x:.34375,y:.78125},{x:.40625,y:.78125},{x:.40625,y:.78125},{x:.46875,y:.78125},{x:.46875,y:.78125},{x:.53125,y:.78125},{x:.53125,y:.78125},{x:.59375,y:.78125},{x:.59375,y:.78125},{x:.65625,y:.78125},{x:.65625,y:.78125},{x:.71875,y:.78125},{x:.71875,y:.78125},{x:.78125,y:.78125},{x:.78125,y:.78125},{x:.84375,y:.78125},{x:.84375,y:.78125},{x:.90625,y:.78125},{x:.90625,y:.78125},{x:.96875,y:.78125},{x:.96875,y:.78125},{x:.03125,y:.84375},{x:.03125,y:.84375},{x:.09375,y:.84375},{x:.09375,y:.84375},{x:.15625,y:.84375},{x:.15625,y:.84375},{x:.21875,y:.84375},{x:.21875,y:.84375},{x:.28125,y:.84375},{x:.28125,y:.84375},{x:.34375,y:.84375},{x:.34375,y:.84375},{x:.40625,y:.84375},{x:.40625,y:.84375},{x:.46875,y:.84375},{x:.46875,y:.84375},{x:.53125,y:.84375},{x:.53125,y:.84375},{x:.59375,y:.84375},{x:.59375,y:.84375},{x:.65625,y:.84375},{x:.65625,y:.84375},{x:.71875,y:.84375},{x:.71875,y:.84375},{x:.78125,y:.84375},{x:.78125,y:.84375},{x:.84375,y:.84375},{x:.84375,y:.84375},{x:.90625,y:.84375},{x:.90625,y:.84375},{x:.96875,y:.84375},{x:.96875,y:.84375},{x:.03125,y:.90625},{x:.03125,y:.90625},{x:.09375,y:.90625},{x:.09375,y:.90625},{x:.15625,y:.90625},{x:.15625,y:.90625},{x:.21875,y:.90625},{x:.21875,y:.90625},{x:.28125,y:.90625},{x:.28125,y:.90625},{x:.34375,y:.90625},{x:.34375,y:.90625},{x:.40625,y:.90625},{x:.40625,y:.90625},{x:.46875,y:.90625},{x:.46875,y:.90625},{x:.53125,y:.90625},{x:.53125,y:.90625},{x:.59375,y:.90625},{x:.59375,y:.90625},{x:.65625,y:.90625},{x:.65625,y:.90625},{x:.71875,y:.90625},{x:.71875,y:.90625},{x:.78125,y:.90625},{x:.78125,y:.90625},{x:.84375,y:.90625},{x:.84375,y:.90625},{x:.90625,y:.90625},{x:.90625,y:.90625},{x:.96875,y:.90625},{x:.96875,y:.90625},{x:.03125,y:.96875},{x:.03125,y:.96875},{x:.09375,y:.96875},{x:.09375,y:.96875},{x:.15625,y:.96875},{x:.15625,y:.96875},{x:.21875,y:.96875},{x:.21875,y:.96875},{x:.28125,y:.96875},{x:.28125,y:.96875},{x:.34375,y:.96875},{x:.34375,y:.96875},{x:.40625,y:.96875},{x:.40625,y:.96875},{x:.46875,y:.96875},{x:.46875,y:.96875},{x:.53125,y:.96875},{x:.53125,y:.96875},{x:.59375,y:.96875},{x:.59375,y:.96875},{x:.65625,y:.96875},{x:.65625,y:.96875},{x:.71875,y:.96875},{x:.71875,y:.96875},{x:.78125,y:.96875},{x:.78125,y:.96875},{x:.84375,y:.96875},{x:.84375,y:.96875},{x:.90625,y:.96875},{x:.90625,y:.96875},{x:.96875,y:.96875},{x:.96875,y:.96875},{x:.0625,y:.0625},{x:.0625,y:.0625},{x:.0625,y:.0625},{x:.0625,y:.0625},{x:.0625,y:.0625},{x:.0625,y:.0625},{x:.1875,y:.0625},{x:.1875,y:.0625},{x:.1875,y:.0625},{x:.1875,y:.0625},{x:.1875,y:.0625},{x:.1875,y:.0625},{x:.3125,y:.0625},{x:.3125,y:.0625},{x:.3125,y:.0625},{x:.3125,y:.0625},{x:.3125,y:.0625},{x:.3125,y:.0625},{x:.4375,y:.0625},{x:.4375,y:.0625},{x:.4375,y:.0625},{x:.4375,y:.0625},{x:.4375,y:.0625},{x:.4375,y:.0625},{x:.5625,y:.0625},{x:.5625,y:.0625},{x:.5625,y:.0625},{x:.5625,y:.0625},{x:.5625,y:.0625},{x:.5625,y:.0625},{x:.6875,y:.0625},{x:.6875,y:.0625},{x:.6875,y:.0625},{x:.6875,y:.0625},{x:.6875,y:.0625},{x:.6875,y:.0625},{x:.8125,y:.0625},{x:.8125,y:.0625},{x:.8125,y:.0625},{x:.8125,y:.0625},{x:.8125,y:.0625},{x:.8125,y:.0625},{x:.9375,y:.0625},{x:.9375,y:.0625},{x:.9375,y:.0625},{x:.9375,y:.0625},{x:.9375,y:.0625},{x:.9375,y:.0625},{x:.0625,y:.1875},{x:.0625,y:.1875},{x:.0625,y:.1875},{x:.0625,y:.1875},{x:.0625,y:.1875},{x:.0625,y:.1875},{x:.1875,y:.1875},{x:.1875,y:.1875},{x:.1875,y:.1875},{x:.1875,y:.1875},{x:.1875,y:.1875},{x:.1875,y:.1875},{x:.3125,y:.1875},{x:.3125,y:.1875},{x:.3125,y:.1875},{x:.3125,y:.1875},{x:.3125,y:.1875},{x:.3125,y:.1875},{x:.4375,y:.1875},{x:.4375,y:.1875},{x:.4375,y:.1875},{x:.4375,y:.1875},{x:.4375,y:.1875},{x:.4375,y:.1875},{x:.5625,y:.1875},{x:.5625,y:.1875},{x:.5625,y:.1875},{x:.5625,y:.1875},{x:.5625,y:.1875},{x:.5625,y:.1875},{x:.6875,y:.1875},{x:.6875,y:.1875},{x:.6875,y:.1875},{x:.6875,y:.1875},{x:.6875,y:.1875},{x:.6875,y:.1875},{x:.8125,y:.1875},{x:.8125,y:.1875},{x:.8125,y:.1875},{x:.8125,y:.1875},{x:.8125,y:.1875},{x:.8125,y:.1875},{x:.9375,y:.1875},{x:.9375,y:.1875},{x:.9375,y:.1875},{x:.9375,y:.1875},{x:.9375,y:.1875},{x:.9375,y:.1875},{x:.0625,y:.3125},{x:.0625,y:.3125},{x:.0625,y:.3125},{x:.0625,y:.3125},{x:.0625,y:.3125},{x:.0625,y:.3125},{x:.1875,y:.3125},{x:.1875,y:.3125},{x:.1875,y:.3125},{x:.1875,y:.3125},{x:.1875,y:.3125},{x:.1875,y:.3125},{x:.3125,y:.3125},{x:.3125,y:.3125},{x:.3125,y:.3125},{x:.3125,y:.3125},{x:.3125,y:.3125},{x:.3125,y:.3125},{x:.4375,y:.3125},{x:.4375,y:.3125},{x:.4375,y:.3125},{x:.4375,y:.3125},{x:.4375,y:.3125},{x:.4375,y:.3125},{x:.5625,y:.3125},{x:.5625,y:.3125},{x:.5625,y:.3125},{x:.5625,y:.3125},{x:.5625,y:.3125},{x:.5625,y:.3125},{x:.6875,y:.3125},{x:.6875,y:.3125},{x:.6875,y:.3125},{x:.6875,y:.3125},{x:.6875,y:.3125},{x:.6875,y:.3125},{x:.8125,y:.3125},{x:.8125,y:.3125},{x:.8125,y:.3125},{x:.8125,y:.3125},{x:.8125,y:.3125},{x:.8125,y:.3125},{x:.9375,y:.3125},{x:.9375,y:.3125},{x:.9375,y:.3125},{x:.9375,y:.3125},{x:.9375,y:.3125},{x:.9375,y:.3125},{x:.0625,y:.4375},{x:.0625,y:.4375},{x:.0625,y:.4375},{x:.0625,y:.4375},{x:.0625,y:.4375},{x:.0625,y:.4375},{x:.1875,y:.4375},{x:.1875,y:.4375},{x:.1875,y:.4375},{x:.1875,y:.4375},{x:.1875,y:.4375},{x:.1875,y:.4375},{x:.3125,y:.4375},{x:.3125,y:.4375},{x:.3125,y:.4375},{x:.3125,y:.4375},{x:.3125,y:.4375},{x:.3125,y:.4375},{x:.4375,y:.4375},{x:.4375,y:.4375},{x:.4375,y:.4375},{x:.4375,y:.4375},{x:.4375,y:.4375},{x:.4375,y:.4375},{x:.5625,y:.4375},{x:.5625,y:.4375},{x:.5625,y:.4375},{x:.5625,y:.4375},{x:.5625,y:.4375},{x:.5625,y:.4375},{x:.6875,y:.4375},{x:.6875,y:.4375},{x:.6875,y:.4375},{x:.6875,y:.4375},{x:.6875,y:.4375},{x:.6875,y:.4375},{x:.8125,y:.4375},{x:.8125,y:.4375},{x:.8125,y:.4375},{x:.8125,y:.4375},{x:.8125,y:.4375},{x:.8125,y:.4375},{x:.9375,y:.4375},{x:.9375,y:.4375},{x:.9375,y:.4375},{x:.9375,y:.4375},{x:.9375,y:.4375},{x:.9375,y:.4375},{x:.0625,y:.5625},{x:.0625,y:.5625},{x:.0625,y:.5625},{x:.0625,y:.5625},{x:.0625,y:.5625},{x:.0625,y:.5625},{x:.1875,y:.5625},{x:.1875,y:.5625},{x:.1875,y:.5625},{x:.1875,y:.5625},{x:.1875,y:.5625},{x:.1875,y:.5625},{x:.3125,y:.5625},{x:.3125,y:.5625},{x:.3125,y:.5625},{x:.3125,y:.5625},{x:.3125,y:.5625},{x:.3125,y:.5625},{x:.4375,y:.5625},{x:.4375,y:.5625},{x:.4375,y:.5625},{x:.4375,y:.5625},{x:.4375,y:.5625},{x:.4375,y:.5625},{x:.5625,y:.5625},{x:.5625,y:.5625},{x:.5625,y:.5625},{x:.5625,y:.5625},{x:.5625,y:.5625},{x:.5625,y:.5625},{x:.6875,y:.5625},{x:.6875,y:.5625},{x:.6875,y:.5625},{x:.6875,y:.5625},{x:.6875,y:.5625},{x:.6875,y:.5625},{x:.8125,y:.5625},{x:.8125,y:.5625},{x:.8125,y:.5625},{x:.8125,y:.5625},{x:.8125,y:.5625},{x:.8125,y:.5625},{x:.9375,y:.5625},{x:.9375,y:.5625},{x:.9375,y:.5625},{x:.9375,y:.5625},{x:.9375,y:.5625},{x:.9375,y:.5625},{x:.0625,y:.6875},{x:.0625,y:.6875},{x:.0625,y:.6875},{x:.0625,y:.6875},{x:.0625,y:.6875},{x:.0625,y:.6875},{x:.1875,y:.6875},{x:.1875,y:.6875},{x:.1875,y:.6875},{x:.1875,y:.6875},{x:.1875,y:.6875},{x:.1875,y:.6875},{x:.3125,y:.6875},{x:.3125,y:.6875},{x:.3125,y:.6875},{x:.3125,y:.6875},{x:.3125,y:.6875},{x:.3125,y:.6875},{x:.4375,y:.6875},{x:.4375,y:.6875},{x:.4375,y:.6875},{x:.4375,y:.6875},{x:.4375,y:.6875},{x:.4375,y:.6875},{x:.5625,y:.6875},{x:.5625,y:.6875},{x:.5625,y:.6875},{x:.5625,y:.6875},{x:.5625,y:.6875},{x:.5625,y:.6875},{x:.6875,y:.6875},{x:.6875,y:.6875},{x:.6875,y:.6875},{x:.6875,y:.6875},{x:.6875,y:.6875},{x:.6875,y:.6875},{x:.8125,y:.6875},{x:.8125,y:.6875},{x:.8125,y:.6875},{x:.8125,y:.6875},{x:.8125,y:.6875},{x:.8125,y:.6875},{x:.9375,y:.6875},{x:.9375,y:.6875},{x:.9375,y:.6875},{x:.9375,y:.6875},{x:.9375,y:.6875},{x:.9375,y:.6875},{x:.0625,y:.8125},{x:.0625,y:.8125},{x:.0625,y:.8125},{x:.0625,y:.8125},{x:.0625,y:.8125},{x:.0625,y:.8125},{x:.1875,y:.8125},{x:.1875,y:.8125},{x:.1875,y:.8125},{x:.1875,y:.8125},{x:.1875,y:.8125},{x:.1875,y:.8125},{x:.3125,y:.8125},{x:.3125,y:.8125},{x:.3125,y:.8125},{x:.3125,y:.8125},{x:.3125,y:.8125},{x:.3125,y:.8125},{x:.4375,y:.8125},{x:.4375,y:.8125},{x:.4375,y:.8125},{x:.4375,y:.8125},{x:.4375,y:.8125},{x:.4375,y:.8125},{x:.5625,y:.8125},{x:.5625,y:.8125},{x:.5625,y:.8125},{x:.5625,y:.8125},{x:.5625,y:.8125},{x:.5625,y:.8125},{x:.6875,y:.8125},{x:.6875,y:.8125},{x:.6875,y:.8125},{x:.6875,y:.8125},{x:.6875,y:.8125},{x:.6875,y:.8125},{x:.8125,y:.8125},{x:.8125,y:.8125},{x:.8125,y:.8125},{x:.8125,y:.8125},{x:.8125,y:.8125},{x:.8125,y:.8125},{x:.9375,y:.8125},{x:.9375,y:.8125},{x:.9375,y:.8125},{x:.9375,y:.8125},{x:.9375,y:.8125},{x:.9375,y:.8125},{x:.0625,y:.9375},{x:.0625,y:.9375},{x:.0625,y:.9375},{x:.0625,y:.9375},{x:.0625,y:.9375},{x:.0625,y:.9375},{x:.1875,y:.9375},{x:.1875,y:.9375},{x:.1875,y:.9375},{x:.1875,y:.9375},{x:.1875,y:.9375},{x:.1875,y:.9375},{x:.3125,y:.9375},{x:.3125,y:.9375},{x:.3125,y:.9375},{x:.3125,y:.9375},{x:.3125,y:.9375},{x:.3125,y:.9375},{x:.4375,y:.9375},{x:.4375,y:.9375},{x:.4375,y:.9375},{x:.4375,y:.9375},{x:.4375,y:.9375},{x:.4375,y:.9375},{x:.5625,y:.9375},{x:.5625,y:.9375},{x:.5625,y:.9375},{x:.5625,y:.9375},{x:.5625,y:.9375},{x:.5625,y:.9375},{x:.6875,y:.9375},{x:.6875,y:.9375},{x:.6875,y:.9375},{x:.6875,y:.9375},{x:.6875,y:.9375},{x:.6875,y:.9375},{x:.8125,y:.9375},{x:.8125,y:.9375},{x:.8125,y:.9375},{x:.8125,y:.9375},{x:.8125,y:.9375},{x:.8125,y:.9375},{x:.9375,y:.9375},{x:.9375,y:.9375},{x:.9375,y:.9375},{x:.9375,y:.9375},{x:.9375,y:.9375},{x:.9375,y:.9375}];var C0=class{constructor(t){ue(this,"model");ue(this,"anchors");ue(this,"anchorsTensor");ue(this,"inputSize");ue(this,"inputSizeTensor");ue(this,"doubleInputSizeTensor");var a,n,r,s;this.model=t,this.anchors=uk.map(i=>[i.x,i.y]),this.anchorsTensor=Kn(this.anchors),this.inputSize=((s=(r=(n=(a=this==null?void 0:this.model)==null?void 0:a.inputs)==null?void 0:n[0])==null?void 0:r.shape)==null?void 0:s[2])||0,this.inputSizeTensor=Ht([this.inputSize,this.inputSize]),this.doubleInputSizeTensor=Ht([this.inputSize*2,this.inputSize*2])}normalizeBoxes(t){let a={};a.boxOffsets=Pe(t,[0,0],[-1,2]),a.boxSizes=Pe(t,[0,2],[-1,2]),a.div=me(a.boxOffsets,this.inputSizeTensor),a.boxCenterPoints=be(a.div,this.anchorsTensor),a.halfBoxSizes=me(a.boxSizes,this.doubleInputSizeTensor),a.sub=fe(a.boxCenterPoints,a.halfBoxSizes),a.startPoints=ae(a.sub,this.inputSizeTensor),a.add=be(a.boxCenterPoints,a.halfBoxSizes),a.endPoints=ae(a.add,this.inputSizeTensor);let n=ru([a.startPoints,a.endPoints],1);return Object.keys(a).forEach(r=>Y(a[r])),n}normalizeLandmarks(t,a){let n={};n.reshape=J(t,[-1,7,2]),n.div=me(n.reshape,this.inputSizeTensor),n.landmarks=be(n.div,this.anchors[a]?this.anchors[a]:0);let r=ae(n.landmarks,this.inputSizeTensor);return Object.keys(n).forEach(s=>Y(n[s])),r}async predict(t,a){var o;let n={};n.resize=ge.resizeBilinear(t,[this.inputSize,this.inputSize]),n.div=me(n.resize,ze.tf127),n.image=fe(n.div,ze.tf1),n.batched=this.model.execute(n.image),n.predictions=_e(n.batched),n.slice=Pe(n.predictions,[0,0],[-1,1]),n.sigmoid=Da(n.slice),n.scores=_e(n.sigmoid);let r=await n.scores.data();n.boxes=Pe(n.predictions,[0,1],[-1,4]),n.norm=this.normalizeBoxes(n.boxes),n.nms=await ge.nonMaxSuppressionAsync(n.norm,n.scores,3*(((o=a.hand)==null?void 0:o.maxDetected)||1),a.hand.iouThreshold,a.hand.minConfidence);let s=await n.nms.array(),i=[];for(let l of s){let u={};u.box=Pe(n.norm,[l,0],[1,-1]),u.slice=Pe(n.predictions,[l,5],[1,14]),u.norm=this.normalizeLandmarks(u.slice,l),u.palmLandmarks=J(u.norm,[-1,2]);let p=await u.box.data(),c=p.slice(0,2),d=p.slice(2,4),h=await u.palmLandmarks.array(),f={startPoint:c,endPoint:d,palmLandmarks:h,confidence:r[l]},m=sk(f,[(t.shape[2]||1)/this.inputSize,(t.shape[1]||0)/this.inputSize]);i.push(m),Object.keys(u).forEach(g=>Y(u[g]))}return Object.keys(n).forEach(l=>Y(n[l])),i}};var Bhe=5,dk=1.65,pk=[0,5,9,13,17,1,2],Whe=0,Vhe=2,ck=0,N0=class{constructor(t,a){ue(this,"handDetector");ue(this,"handPoseModel");ue(this,"inputSize");ue(this,"storedBoxes");ue(this,"skipped");ue(this,"detectedHands");var n,r,s;this.handDetector=t,this.handPoseModel=a,this.inputSize=((s=(r=(n=this.handPoseModel)==null?void 0:n.inputs)==null?void 0:r[0].shape)==null?void 0:s[2])||0,this.storedBoxes=[],this.skipped=Number.MAX_SAFE_INTEGER,this.detectedHands=0}calculateLandmarksBoundingBox(t){let a=t.map(i=>i[0]),n=t.map(i=>i[1]),r=[Math.min(...a),Math.min(...n)],s=[Math.max(...a),Math.max(...n)];return{startPoint:r,endPoint:s}}getBoxForPalmLandmarks(t,a){let n=t.map(s=>jg([...s,1],a)),r=this.calculateLandmarksBoundingBox(n);return S0(T0(r),Bhe)}getBoxForHandLandmarks(t){let a=this.calculateLandmarksBoundingBox(t),n=S0(T0(a),dk);n.palmLandmarks=[];for(let r=0;r<pk.length;r++)n.palmLandmarks.push(t[pk[r]].slice(0,2));return n}transformRawCoords(t,a,n,r){let s=I0(a),i=[s[0]/this.inputSize,s[1]/this.inputSize,(s[0]+s[1])/this.inputSize/2],o=t.map(h=>[i[0]*(h[0]-this.inputSize/2),i[1]*(h[1]-this.inputSize/2),i[2]*h[2]]),l=Hg(n,[0,0]),u=o.map(h=>[...jg(h,l),h[2]]),p=ok(r),c=[...Tp(a),1],d=[ws(c,p[0]),ws(c,p[1])];return u.map(h=>[Math.trunc(h[0]+d[0]),Math.trunc(h[1]+d[1]),Math.trunc(h[2])])}async estimateHands(t,a){let n=!1,r,s=(a.hand.skipTime||0)>te()-ck,i=this.skipped<(a.hand.skipFrames||0);a.skipAllowed&&s&&i&&(r=await this.handDetector.predict(t,a),this.skipped=0),a.skipAllowed&&this.skipped++,r&&r.length>0&&(r.length!==this.detectedHands&&this.detectedHands!==a.hand.maxDetected||!a.hand.landmarks)&&(this.detectedHands=0,this.storedBoxes=[...r],this.storedBoxes.length>0&&(n=!0));let o=[];for(let l=0;l<this.storedBoxes.length;l++){let u=this.storedBoxes[l];if(!!u)if(a.hand.landmarks){let p=a.hand.rotation?ik(u.palmLandmarks[Whe],u.palmLandmarks[Vhe]):0,c=Tp(u),d=[c[0]/t.shape[2],c[1]/t.shape[1]],h=a.hand.rotation&&ne.kernels.includes("rotatewithoffset")?ge.rotateWithOffset(t,p,0,d):t.clone(),f=Hg(-p,c),m=n?this.getBoxForPalmLandmarks(u.palmLandmarks,f):u,g=rk(m,h,[this.inputSize,this.inputSize]),x=me(g,ze.tf255);Y(g),Y(h);let[A,y]=this.handPoseModel.execute(x);ck=te(),Y(x);let b=(await A.data())[0];if(Y(A),b>=a.hand.minConfidence/4){let w=J(y,[-1,3]),S=await w.array();Y(y),Y(w);let C=this.transformRawCoords(S,m,p,f),E=this.getBoxForHandLandmarks(C);this.storedBoxes[l]={...E,confidence:b};let _={landmarks:C,confidence:b,boxConfidence:u.confidence,fingerConfidence:b,box:{topLeft:E.startPoint,bottomRight:E.endPoint}};o.push(_)}else this.storedBoxes[l]=null;Y(y)}else{let p=S0(T0(u),dk),c={confidence:u.confidence,boxConfidence:u.confidence,fingerConfidence:0,box:{topLeft:p.startPoint,bottomRight:p.endPoint},landmarks:[]};o.push(c)}}return this.storedBoxes=this.storedBoxes.filter(l=>l!==null),this.detectedHands=o.length,o.length>a.hand.maxDetected&&(o.length=a.hand.maxDetected),o}};var hk={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]},Do,zo,fk;async function qg(e,t){let a=await fk.estimateHands(e,t);if(!a)return[];let n=[];for(let r=0;r<a.length;r++){let s={};if(a[r].landmarks)for(let p of Object.keys(hk))s[p]=hk[p].map(c=>a[r].landmarks[c]);let i=a[r].landmarks,o=[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,0,0],l=[0,0,0,0];if(i&&i.length>0){for(let p of i)p[0]<o[0]&&(o[0]=p[0]),p[1]<o[1]&&(o[1]=p[1]),p[0]>o[2]&&(o[2]=p[0]),p[1]>o[3]&&(o[3]=p[1]);o[2]-=o[0],o[3]-=o[1],l=[o[0]/(e.shape[2]||0),o[1]/(e.shape[1]||0),o[2]/(e.shape[2]||0),o[3]/(e.shape[1]||0)]}else o=a[r].box?[Math.trunc(Math.max(0,a[r].box.topLeft[0])),Math.trunc(Math.max(0,a[r].box.topLeft[1])),Math.trunc(Math.min(e.shape[2]||0,a[r].box.bottomRight[0])-Math.max(0,a[r].box.topLeft[0])),Math.trunc(Math.min(e.shape[1]||0,a[r].box.bottomRight[1])-Math.max(0,a[r].box.topLeft[1]))]:[0,0,0,0],l=[a[r].box.topLeft[0]/(e.shape[2]||0),a[r].box.topLeft[1]/(e.shape[1]||0),(a[r].box.bottomRight[0]-a[r].box.topLeft[0])/(e.shape[2]||0),(a[r].box.bottomRight[1]-a[r].box.topLeft[1])/(e.shape[1]||0)];let u=k0(i);n.push({id:r,score:Math.round(100*a[r].confidence)/100,boxScore:Math.round(100*a[r].boxConfidence)/100,fingerScore:Math.round(100*a[r].fingerConfidence)/100,label:"hand",box:o,boxRaw:l,keypoints:i,annotations:s,landmarks:u})}return n}async function mk(e){var a,n;ne.initial&&(Do=null,zo=null),!Do||!zo?[Do,zo]=await Promise.all([e.hand.enabled?Ee((a=e.hand.detector)==null?void 0:a.modelPath):null,e.hand.landmarks?Ee((n=e.hand.skeleton)==null?void 0:n.modelPath):null]):(e.debug&&K("cached model:",Do.modelUrl),e.debug&&K("cached model:",zo.modelUrl));let t=Do?new C0(Do):void 0;return t&&zo&&(fk=new N0(t,zo)),[Do,zo]}var Pt=[null,null],Ghe=["StatefulPartitionedCall/Postprocessor/Slice","StatefulPartitionedCall/Postprocessor/ExpandDims_1"],ks=[[0,0],[0,0]],Hhe=["hand","fist","pinch","point","face","tip","pinchtip"],xk=4,Ak=1.6,jhe=512,qhe=1.4,E0=Number.MAX_SAFE_INTEGER,Xg=0,$r=[0,0],_t={boxes:[],hands:[]},yk={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 bk(e){var t;if(ne.initial&&(Pt[0]=null),Pt[0])e.debug&&K("cached model:",Pt[0].modelUrl);else{Qh(["tensorlistreserve","enter","tensorlistfromtensor","merge","loopcond","switch","exit","tensorliststack","nextiteration","tensorlistsetitem","tensorlistgetitem","reciprocal","shape","split","where"],e),Pt[0]=await Ee((t=e.hand.detector)==null?void 0:t.modelPath);let a=Pt[0].executor?Object.values(Pt[0].modelSignature.inputs):void 0;ks[0][0]=Array.isArray(a)?parseInt(a[0].tensorShape.dim[1].size):0,ks[0][1]=Array.isArray(a)?parseInt(a[0].tensorShape.dim[2].size):0}return Pt[0]}async function vk(e){var t;if(ne.initial&&(Pt[1]=null),Pt[1])e.debug&&K("cached model:",Pt[1].modelUrl);else{Pt[1]=await Ee((t=e.hand.skeleton)==null?void 0:t.modelPath);let a=Pt[1].executor?Object.values(Pt[1].modelSignature.inputs):void 0;ks[1][0]=Array.isArray(a)?parseInt(a[0].tensorShape.dim[1].size):0,ks[1][1]=Array.isArray(a)?parseInt(a[0].tensorShape.dim[2].size):0}return Pt[1]}async function Xhe(e,t){let a=[];if(!e||!Pt[0])return a;let n={},r=(e.shape[2]||1)/(e.shape[1]||1),s=Math.min(Math.round((e.shape[1]||0)/8)*8,jhe),i=Math.round(s*r/8)*8;n.resize=ge.resizeBilinear(e,[s,i]),n.cast=He(n.resize,"int32"),[n.rawScores,n.rawBoxes]=await Pt[0].executeAsync(n.cast,Ghe),n.boxes=_e(n.rawBoxes,[0,2]),n.scores=_e(n.rawScores,[0]);let o=Ta(n.scores,1);Y(o[xk]),o.splice(xk,1),n.filtered=sa(o,1),Y(o),n.max=pa(n.filtered,1),n.argmax=ar(n.filtered,1);let l=0;n.nms=await ge.nonMaxSuppressionAsync(n.boxes,n.max,(t.hand.maxDetected||0)+1,t.hand.iouThreshold||0,t.hand.minConfidence||1);let u=await n.nms.data(),p=await n.max.data(),c=await n.argmax.data();for(let d of Array.from(u)){let h=Pe(n.boxes,d,1),f=await h.data();Y(h);let m=[f[1],f[0],f[3]-f[1],f[2]-f[0]],g=l0(m,qhe),x=[Math.trunc(m[0]*$r[0]),Math.trunc(m[1]*$r[1]),Math.trunc(m[2]*$r[0]),Math.trunc(m[3]*$r[1])],A=p[d],y=Hhe[c[d]],b={id:l++,score:A,box:x,boxRaw:g,label:y};a.push(b)}return Object.keys(n).forEach(d=>Y(n[d])),a.sort((d,h)=>h.score-d.score),a.length>(t.hand.maxDetected||1)&&(a.length=t.hand.maxDetected||1),a}async function Kg(e,t,a){let n={id:t.id,score:Math.round(100*t.score)/100,boxScore:Math.round(100*t.score)/100,fingerScore:0,box:t.box,boxRaw:t.boxRaw,label:t.label,keypoints:[],landmarks:{},annotations:{}};if(e&&Pt[1]&&a.hand.landmarks&&t.score>(a.hand.minConfidence||0)){let r={},s=[t.boxRaw[1],t.boxRaw[0],t.boxRaw[3]+t.boxRaw[1],t.boxRaw[2]+t.boxRaw[0]];r.crop=ge.cropAndResize(e,[s],[0],[ks[1][0],ks[1][1]],"bilinear"),r.div=me(r.crop,ze.tf255),[r.score,r.keypoints]=Pt[1].execute(r.div,["Identity_1","Identity"]);let i=(await r.score.data())[0],o=(100-Math.trunc(100/(1+Math.exp(i))))/100;if(o>=(a.hand.minConfidence||0)){n.fingerScore=o,r.reshaped=J(r.keypoints,[-1,3]);let p=(await r.reshaped.array()).map(c=>[c[0]/ks[1][1],c[1]/ks[1][0],c[2]||0]).map(c=>[c[0]*t.boxRaw[2],c[1]*t.boxRaw[3],c[2]||0]);n.keypoints=p.map(c=>[$r[0]*(c[0]+t.boxRaw[0]),$r[1]*(c[1]+t.boxRaw[1]),c[2]||0]),n.landmarks=k0(n.keypoints);for(let c of Object.keys(yk))n.annotations[c]=yk[c].map(d=>n.landmarks&&n.keypoints[d]?n.keypoints[d]:null)}Object.keys(r).forEach(l=>Y(r[l]))}return n}async function Zg(e,t){var r,s;if(!((r=Pt[0])!=null&&r.executor)||!((s=Pt[1])!=null&&s.executor)||!Pt[0].inputs[0].shape||!Pt[1].inputs[0].shape)return[];$r=[e.shape[2]||0,e.shape[1]||0],E0++;let a=(t.hand.skipTime||0)>te()-Xg,n=E0<(t.hand.skipFrames||0);return t.skipAllowed&&a&&n?_t.hands:new Promise(async i=>{let o=3*(t.hand.skipTime||0)>te()-Xg,l=E0<3*(t.hand.skipFrames||0);t.skipAllowed&&_t.hands.length===t.hand.maxDetected?_t.hands=await Promise.all(_t.boxes.map(p=>Kg(e,p,t))):t.skipAllowed&&o&&l&&_t.hands.length>0?_t.hands=await Promise.all(_t.boxes.map(p=>Kg(e,p,t))):(_t.boxes=await Xhe(e,t),Xg=te(),_t.hands=await Promise.all(_t.boxes.map(p=>Kg(e,p,t))),E0=0);let u=[..._t.boxes];if(_t.boxes.length=0,t.cacheSensitivity>0)for(let p=0;p<_t.hands.length;p++){let c=b9(_t.hands[p].keypoints,$r);if(c.box[2]/(e.shape[2]||1)>.05&&c.box[3]/(e.shape[1]||1)>.05&&_t.hands[p].fingerScore&&_t.hands[p].fingerScore>(t.hand.minConfidence||0)){let d=l0(c.box,Ak),h=l0(c.boxRaw,Ak);_t.boxes.push({...u[p],box:d,boxRaw:h})}}for(let p=0;p<_t.hands.length;p++){let c=Er(_t.hands[p].keypoints,$r);_t.hands[p].box=c.box,_t.hands[p].boxRaw=c.boxRaw}i(_t.hands)})}var or=(e=null)=>({face:[],body:[],hand:[],gesture:[],object:[],persons:[],performance:{},timestamp:0,width:0,height:0,error:e});var Cp={};hr(Cp,{connected:()=>M0,horizontal:()=>Yg,kpt:()=>R0,relative:()=>Qg,vertical:()=>Jg});var R0=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],Yg=[["leftEye","rightEye"],["leftEar","rightEar"],["leftShoulder","rightShoulder"],["leftElbow","rightElbow"],["leftWrist","rightWrist"],["leftHip","rightHip"],["leftKnee","rightKnee"],["leftAnkle","rightAnkle"]],Jg=[["leftKnee","leftShoulder"],["rightKnee","rightShoulder"],["leftAnkle","leftKnee"],["rightAnkle","rightKnee"]],Qg=[[["leftHip","rightHip"],["leftShoulder","rightShoulder"]],[["leftElbow","rightElbow"],["leftShoulder","rightShoulder"]]],M0={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var xe=or(),e5=0;function kk(e,t){var i,o,l,u,p,c,d,h,f,m,g,x,A,y,b,w,S,C,E,_,$,M,I;let a=te();if(!e)return or();let n=Date.now()-e.timestamp,r=n<1e3?8-Math.log(n+1):1;if(e.canvas&&(xe.canvas=e.canvas),e.error&&(xe.error=e.error),!xe.body||e.body.length!==xe.body.length)xe.body=JSON.parse(JSON.stringify(e.body));else for(let N=0;N<e.body.length;N++){let O=e.body[N].box.map((U,H)=>((r-1)*xe.body[N].box[H]+U)/r),L=e.body[N].boxRaw.map((U,H)=>((r-1)*xe.body[N].boxRaw[H]+U)/r),B=e.body[N].keypoints.map((U,H)=>{var V,Q,Z,re,ee,he,oe,Ae,we;return{score:U.score,part:U.part,position:[xe.body[N].keypoints[H]?((r-1)*(xe.body[N].keypoints[H].position[0]||0)+(U.position[0]||0))/r:U.position[0],xe.body[N].keypoints[H]?((r-1)*(xe.body[N].keypoints[H].position[1]||0)+(U.position[1]||0))/r:U.position[1],xe.body[N].keypoints[H]?((r-1)*(xe.body[N].keypoints[H].position[2]||0)+(U.position[2]||0))/r:U.position[2]],positionRaw:[xe.body[N].keypoints[H]?((r-1)*(xe.body[N].keypoints[H].positionRaw[0]||0)+(U.positionRaw[0]||0))/r:U.positionRaw[0],xe.body[N].keypoints[H]?((r-1)*(xe.body[N].keypoints[H].positionRaw[1]||0)+(U.positionRaw[1]||0))/r:U.positionRaw[1],xe.body[N].keypoints[H]?((r-1)*(xe.body[N].keypoints[H].positionRaw[2]||0)+(U.positionRaw[2]||0))/r:U.positionRaw[2]],distance:[xe.body[N].keypoints[H]?((r-1)*(((V=xe.body[N].keypoints[H].distance)==null?void 0:V[0])||0)+(((Q=U.distance)==null?void 0:Q[0])||0))/r:(Z=U.distance)==null?void 0:Z[0],xe.body[N].keypoints[H]?((r-1)*(((re=xe.body[N].keypoints[H].distance)==null?void 0:re[1])||0)+(((ee=U.distance)==null?void 0:ee[1])||0))/r:(he=U.distance)==null?void 0:he[1],xe.body[N].keypoints[H]?((r-1)*(((oe=xe.body[N].keypoints[H].distance)==null?void 0:oe[2])||0)+(((Ae=U.distance)==null?void 0:Ae[2])||0))/r:(we=U.distance)==null?void 0:we[2]]}}),G={},j={connected:{}};(i=t.body.modelPath)!=null&&i.includes("efficientpose")?j=p0:(o=t.body.modelPath)!=null&&o.includes("blazepose")?j=i0:(l=t.body.modelPath)!=null&&l.includes("movenet")&&(j=Cp);for(let[U,H]of Object.entries(j.connected)){let V=[];for(let Q=0;Q<H.length-1;Q++){let Z=B.find(ee=>ee.part===H[Q]),re=B.find(ee=>ee.part===H[Q+1]);Z&&re&&V.push([Z.position,re.position])}G[U]=V}xe.body[N]={...e.body[N],box:O,boxRaw:L,keypoints:B,annotations:G}}if(!xe.hand||e.hand.length!==xe.hand.length)xe.hand=JSON.parse(JSON.stringify(e.hand));else for(let N=0;N<e.hand.length;N++){let O=e.hand[N].box.map((j,U)=>((r-1)*xe.hand[N].box[U]+j)/r),L=e.hand[N].boxRaw.map((j,U)=>((r-1)*xe.hand[N].boxRaw[U]+j)/r);xe.hand[N].keypoints.length!==e.hand[N].keypoints.length&&(xe.hand[N].keypoints=e.hand[N].keypoints);let B=e.hand[N].keypoints&&e.hand[N].keypoints.length>0?e.hand[N].keypoints.map((j,U)=>j.map((H,V)=>((r-1)*(xe.hand[N].keypoints[U][V]||1)+(H||0))/r)):[],G={};if(Object.keys(xe.hand[N].annotations).length!==Object.keys(e.hand[N].annotations).length)xe.hand[N].annotations=e.hand[N].annotations,G=xe.hand[N].annotations;else if(e.hand[N].annotations)for(let j of Object.keys(e.hand[N].annotations))G[j]=(c=(p=(u=e.hand[N])==null?void 0:u.annotations)==null?void 0:p[j])!=null&&c[0]?e.hand[N].annotations[j].map((U,H)=>U.map((V,Q)=>((r-1)*xe.hand[N].annotations[j][H][Q]+V)/r)):null;xe.hand[N]={...e.hand[N],box:O,boxRaw:L,keypoints:B,annotations:G}}if(!xe.face||e.face.length!==xe.face.length)xe.face=JSON.parse(JSON.stringify(e.face));else for(let N=0;N<e.face.length;N++){let O=e.face[N].box.map((B,G)=>((r-1)*xe.face[N].box[G]+B)/r),L=e.face[N].boxRaw.map((B,G)=>((r-1)*xe.face[N].boxRaw[G]+B)/r);if(e.face[N].rotation){let B={matrix:[0,0,0,0,0,0,0,0,0],angle:{roll:0,yaw:0,pitch:0},gaze:{bearing:0,strength:0}};B.matrix=(d=e.face[N].rotation)==null?void 0:d.matrix,B.angle={roll:((r-1)*(((f=(h=xe.face[N].rotation)==null?void 0:h.angle)==null?void 0:f.roll)||0)+(((g=(m=e.face[N].rotation)==null?void 0:m.angle)==null?void 0:g.roll)||0))/r,yaw:((r-1)*(((A=(x=xe.face[N].rotation)==null?void 0:x.angle)==null?void 0:A.yaw)||0)+(((b=(y=e.face[N].rotation)==null?void 0:y.angle)==null?void 0:b.yaw)||0))/r,pitch:((r-1)*(((S=(w=xe.face[N].rotation)==null?void 0:w.angle)==null?void 0:S.pitch)||0)+(((E=(C=e.face[N].rotation)==null?void 0:C.angle)==null?void 0:E.pitch)||0))/r},B.gaze={bearing:((r-1)*(((_=xe.face[N].rotation)==null?void 0:_.gaze.bearing)||0)+((($=e.face[N].rotation)==null?void 0:$.gaze.bearing)||0))/r,strength:((r-1)*(((M=xe.face[N].rotation)==null?void 0:M.gaze.strength)||0)+(((I=e.face[N].rotation)==null?void 0:I.gaze.strength)||0))/r},xe.face[N]={...e.face[N],rotation:B,box:O,boxRaw:L}}else xe.face[N]={...e.face[N],box:O,boxRaw:L}}if(!xe.object||e.object.length!==xe.object.length)xe.object=JSON.parse(JSON.stringify(e.object));else for(let N=0;N<e.object.length;N++){let O=e.object[N].box.map((B,G)=>((r-1)*xe.object[N].box[G]+B)/r),L=e.object[N].boxRaw.map((B,G)=>((r-1)*xe.object[N].boxRaw[G]+B)/r);xe.object[N]={...e.object[N],box:O,boxRaw:L}}if(e.persons){let N=e.persons;if(!xe.persons||N.length!==xe.persons.length)xe.persons=JSON.parse(JSON.stringify(N));else for(let O=0;O<N.length;O++)xe.persons[O].box=N[O].box.map((L,B)=>((r-1)*xe.persons[O].box[B]+L)/r)}e.gesture&&(xe.gesture=e.gesture),xe.width=e.width,xe.height=e.height;let s=te();return e5=ne.perfadd?e5+Math.round(s-a):Math.round(s-a),e.performance&&(xe.performance={...e.performance,interpolate:e5}),xe}var ma;async function t5(e){return!ma||ne.initial?ma=await Ee(e.segmentation.modelPath):e.debug&&K("cached model:",ma.modelUrl),ma}async function Ik(e,t){var r;if(ma||(ma=await t5(t)),!(ma!=null&&ma.executor)||!((r=ma==null?void 0:ma.inputs)!=null&&r[0].shape))return null;let a={};a.resize=ge.resizeBilinear(e,[ma.inputs[0].shape?ma.inputs[0].shape[1]:0,ma.inputs[0].shape?ma.inputs[0].shape[2]:0],!1),a.norm=me(a.resize,ze.tf255),a.res=ma.execute(a.norm),a.squeeze=_e(a.res,[0]),[a.bgRaw,a.fgRaw]=Ta(a.squeeze,2),a.fg=Ah(a.fgRaw),a.mul=ae(a.fg,ze.tf255),a.expand=Gt(a.mul,2),a.output=ge.resizeBilinear(a.expand,[e.shape[1]||0,e.shape[2]||0]);let n;switch(t.segmentation.mode||"default"){case"default":a.input=_e(e),a.concat=at([a.input,a.output],-1),n=He(a.concat,"int32");break;case"alpha":n=He(a.output,"int32");break;default:n=Be(0)}return Object.keys(a).forEach(s=>Y(a[s])),n}var $0={};hr($0,{distance:()=>a5,find:()=>Yhe,similarity:()=>Zhe});function a5(e,t,a={order:2,multiplier:25}){if(!e||!e)return Number.MAX_SAFE_INTEGER;let n=0;for(let r=0;r<e.length;r++){let s=!a.order||a.order===2?e[r]-t[r]:Math.abs(e[r]-t[r]);n+=!a.order||a.order===2?s*s:s**a.order}return(a.multiplier||20)*n}var Tk=(e,t,a,n)=>{if(e===0)return 1;let s=(1-(t===2?Math.sqrt(e):e**(1/t))/100-a)/(n-a);return Math.max(Math.min(s,1),0)};function Zhe(e,t,a={order:2,multiplier:25,min:.2,max:.8}){let n=a5(e,t,a);return Tk(n,a.order||2,a.min||0,a.max||1)}function Yhe(e,t,a={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 n=Number.MAX_SAFE_INTEGER,r=-1;for(let i=0;i<t.length;i++){let o=t[i].length===e.length?a5(e,t[i],a):Number.MAX_SAFE_INTEGER;if(o<n&&(n=o,r=i),n<(a.threshold||0))break}let s=Tk(n,a.order||2,a.min||0,a.max||1);return{index:r,distance:n,similarity:s}}var x5={};hr(x5,{Models:()=>Rp,validateModel:()=>L0});var Ck=.005,nn={keypoints:[],padding:[[0,0],[0,0],[0,0],[0,0]]};function n5(e){for(let t of Yg){let a=e.keypoints.findIndex(r=>r.part===t[0]),n=e.keypoints.findIndex(r=>r.part===t[1]);if(e.keypoints[a]&&e.keypoints[n]&&e.keypoints[a].position[0]<e.keypoints[n].position[0]){let r=e.keypoints[a];e.keypoints[a]=e.keypoints[n],e.keypoints[n]=r}}for(let t of Jg){let a=e.keypoints.findIndex(r=>r&&r.part===t[0]),n=e.keypoints.findIndex(r=>r&&r.part===t[1]);e.keypoints[a]&&e.keypoints[n]&&e.keypoints[a].position[1]<e.keypoints[n].position[1]&&e.keypoints.splice(a,1)}for(let[t,a]of Qg){let n=e.keypoints.findIndex(u=>u&&u.part===t[0]),r=e.keypoints.findIndex(u=>u&&u.part===t[1]),s=e.keypoints.findIndex(u=>u&&u.part===a[0]),i=e.keypoints.findIndex(u=>u&&u.part===a[1]);if(!e.keypoints[s]||!e.keypoints[i])continue;let o=e.keypoints[n]?[Math.abs(e.keypoints[s].position[0]-e.keypoints[n].position[0]),Math.abs(e.keypoints[i].position[0]-e.keypoints[n].position[0])]:[0,0],l=e.keypoints[r]?[Math.abs(e.keypoints[i].position[0]-e.keypoints[r].position[0]),Math.abs(e.keypoints[s].position[0]-e.keypoints[r].position[0])]:[0,0];if(o[0]>o[1]||l[0]>l[1]){let u=e.keypoints[n];e.keypoints[n]=e.keypoints[r],e.keypoints[r]=u}}}function Nk(e){for(let t=0;t<e.length;t++)if(e[t]&&nn.keypoints[t]){let a=[Math.abs(e[t].positionRaw[0]-nn.keypoints[t].positionRaw[0]),Math.abs(e[t].positionRaw[1]-nn.keypoints[t].positionRaw[1])];a[0]<Ck&&a[1]<Ck?e[t]=nn.keypoints[t]:nn.keypoints[t]=e[t]}else nn.keypoints[t]=e[t];return e}function Ek(e,t){var r,s;let a={};if(!((r=e==null?void 0:e.shape)!=null&&r[1])||!((s=e==null?void 0:e.shape)!=null&&s[2]))return e;nn.padding=[[0,0],[e.shape[2]>e.shape[1]?Math.trunc((e.shape[2]-e.shape[1])/2):0,e.shape[2]>e.shape[1]?Math.trunc((e.shape[2]-e.shape[1])/2):0],[e.shape[1]>e.shape[2]?Math.trunc((e.shape[1]-e.shape[2])/2):0,e.shape[1]>e.shape[2]?Math.trunc((e.shape[1]-e.shape[2])/2):0],[0,0]],a.pad=rr(e,nn.padding),a.resize=ge.resizeBilinear(a.pad,[t,t]);let n=He(a.resize,"int32");return Object.keys(a).forEach(i=>Y(a[i])),n}function Rk(e,t){e.keypoints=e.keypoints.filter(n=>n==null?void 0:n.position);for(let n of e.keypoints)n.position=[n.position[0]*(t[0]+nn.padding[2][0]+nn.padding[2][1])/t[0]-nn.padding[2][0],n.position[1]*(t[1]+nn.padding[1][0]+nn.padding[1][1])/t[1]-nn.padding[1][0]],n.positionRaw=[n.position[0]/t[0],n.position[1]/t[1]];let a=Er(e.keypoints.map(n=>n.position),t);return e.box=a.box,e.boxRaw=a.boxRaw,e}var Vt,_0=0,r5=Number.MAX_SAFE_INTEGER,Lo={boxes:[],bodies:[],last:0};async function Mk(e){var t;return ne.initial&&(Vt=null),Vt?e.debug&&K("cached model:",Vt.modelUrl):(Qh(["size"],e),Vt=await Ee(e.body.modelPath)),_0=(Vt==null?void 0:Vt.executor)&&((t=Vt==null?void 0:Vt.inputs)==null?void 0:t[0].shape)?Vt.inputs[0].shape[2]:0,_0<64&&(_0=256),Vt}function Qhe(e,t,a){let n=e[0][0],r=[],s=0;for(let p=0;p<n.length;p++)if(s=n[p][2],s>t.body.minConfidence){let c=[n[p][1],n[p][0]];r.push({score:Math.round(100*s)/100,part:R0[p],positionRaw:c,position:[Math.round((a.shape[2]||0)*c[0]),Math.round((a.shape[1]||0)*c[1])]})}s=r.reduce((p,c)=>c.score>p?c.score:p,0);let i=[],o=Er(r.map(p=>p.position),[a.shape[2],a.shape[1]]),l={};for(let[p,c]of Object.entries(M0)){let d=[];for(let h=0;h<c.length-1;h++){let f=r.find(g=>g.part===c[h]),m=r.find(g=>g.part===c[h+1]);f&&m&&f.score>(t.body.minConfidence||0)&&m.score>(t.body.minConfidence||0)&&d.push([f.position,m.position])}l[p]=d}let u={id:0,score:s,box:o.box,boxRaw:o.boxRaw,keypoints:r,annotations:l};return n5(u),i.push(u),i}function e0e(e,t,a){let n=[];for(let r=0;r<e[0].length;r++){let s=e[0][r],i=Math.round(100*s[51+4])/100;if(i>t.body.minConfidence){let o=[];for(let c=0;c<17;c++){let d=s[3*c+2];if(d>t.body.minConfidence){let h=[s[3*c+1],s[3*c+0]];o.push({part:R0[c],score:Math.round(100*d)/100,positionRaw:h,position:[Math.round((a.shape[2]||0)*h[0]),Math.round((a.shape[1]||0)*h[1])]})}}let l=Er(o.map(c=>c.position),[a.shape[2],a.shape[1]]),u={};for(let[c,d]of Object.entries(M0)){let h=[];for(let f=0;f<d.length-1;f++){let m=o.find(x=>x.part===d[f]),g=o.find(x=>x.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[c]=h}let p={id:r,score:i,box:l.box,boxRaw:l.boxRaw,keypoints:[...o],annotations:u};n5(p),n.push(p)}}return n.sort((r,s)=>s.score-r.score),n.length>t.body.maxDetected&&(n.length=t.body.maxDetected),n}async function s5(e,t){var r;if(!(Vt!=null&&Vt.executor)||!((r=Vt==null?void 0:Vt.inputs)!=null&&r[0].shape))return[];t.skipAllowed||(Lo.boxes.length=0),r5++;let a=(t.body.skipTime||0)>te()-Lo.last,n=r5<(t.body.skipFrames||0);return t.skipAllowed&&a&&n?Lo.bodies:new Promise(async s=>{let i={};r5=0,i.input=Ek(e,_0),i.res=Vt==null?void 0:Vt.execute(i.input),Lo.last=te();let o=await i.res.array();Lo.bodies=i.res.shape[2]===17?Qhe(o,t,e):e0e(o,t,e);for(let l of Lo.bodies)Rk(l,[e.shape[2]||1,e.shape[1]||1]),Nk(l.keypoints);Object.keys(i).forEach(l=>Y(i[l])),s(Lo.bodies)})}var _n,P0=[],_k=0,i5=Number.MAX_SAFE_INTEGER,O0=0,F0=2.5;async function Pk(e){if(!_n||ne.initial){_n=await Ee(e.object.modelPath);let t=_n!=null&&_n.executor?Object.values(_n.modelSignature.inputs):void 0;O0=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):416}else e.debug&&K("cached model:",_n.modelUrl);return _n}async function t0e(e,t,a){var u,p;let n=0,r=[],s=O0;for(let c of[1,2,4]){let d=c*13,h=_e(e.find(y=>y.shape[1]===d**2&&(y.shape[2]||0)===bu.length)),f=await h.array(),m=_e(e.find(y=>y.shape[1]===d**2&&(y.shape[2]||0)<bu.length)),g=J(m,[-1,4,(((u=m.shape)==null?void 0:u[1])||0)/4]),x=ar(g,2),A=await x.array();for(let y=0;y<h.shape[0];y++)for(let b=0;b<(((p=h.shape)==null?void 0:p[1])||0);b++){let w=f[y][b];if(w>(a.object.minConfidence||0)&&b!==61){let S=(.5+Math.trunc(y%d))/d,C=(.5+Math.trunc(y/d))/d,E=A[y].map(B=>B*(d/c/s)),[_,$]=[S-F0/c*E[0],C-F0/c*E[1]],[M,I]=[S+F0/c*E[2]-_,C+F0/c*E[3]-$],N=[_,$,M,I];N=N.map(B=>Math.max(0,Math.min(B,1)));let O=[N[0]*t[0],N[1]*t[1],N[2]*t[0],N[3]*t[1]],L={id:n++,score:Math.round(100*w)/100,class:b+1,label:bu[b].label,box:O.map(B=>Math.trunc(B)),boxRaw:N};r.push(L)}}Y([h,m,g,x])}let i=r.map(c=>[c.boxRaw[1],c.boxRaw[0],c.boxRaw[3],c.boxRaw[2]]),o=r.map(c=>c.score),l=[];if(i&&i.length>0){let c=await ge.nonMaxSuppressionAsync(i,o,a.object.maxDetected||0,a.object.iouThreshold,a.object.minConfidence);l=Array.from(await c.data()),Y(c)}return r=r.filter((c,d)=>l.includes(d)).sort((c,d)=>d.score-c.score),r}async function o5(e,t){if(!(_n!=null&&_n.executor))return[];let a=(t.object.skipTime||0)>te()-_k,n=i5<(t.object.skipFrames||0);return t.skipAllowed&&a&&n&&P0.length>0?(i5++,P0):(i5=0,!ne.kernels.includes("mod")||!ne.kernels.includes("sparsetodense")?P0:new Promise(async r=>{let s=[e.shape[2]||0,e.shape[1]||0],i=ge.resizeBilinear(e,[O0,O0],!1),o=me(i,ze.tf255),l=Ws(o,[0,3,1,2]),u;t.object.enabled&&(u=_n.execute(l)),_k=te();let p=await t0e(u,s,t);P0=p,Y([i,o,l,...u]),r(p)}))}var Ep=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],a0e=Ep.length,Np=Ep.reduce((e,t,a)=>(e[t]=a,e),{}),n0e=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]],M5e=n0e.map(([e,t])=>[Np[e],Np[t]]),Ok=[["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 Dk(e){let t=e.reduce(({maxX:a,maxY:n,minX:r,minY:s},{position:{x:i,y:o}})=>({maxX:Math.max(a,i),maxY:Math.max(n,o),minX:Math.min(r,i),minY:Math.min(s,o)}),{maxX:Number.NEGATIVE_INFINITY,maxY:Number.NEGATIVE_INFINITY,minX:Number.POSITIVE_INFINITY,minY:Number.POSITIVE_INFINITY});return[t.minX,t.minY,t.maxX-t.minX,t.maxY-t.minY]}function zk(e,[t,a],[n,r]){let s=t/n,i=a/r,o=(u,p)=>({id:p,score:u.score,boxRaw:[u.box[0]/r,u.box[1]/n,u.box[2]/r,u.box[3]/n],box:[Math.trunc(u.box[0]*i),Math.trunc(u.box[1]*s),Math.trunc(u.box[2]*i),Math.trunc(u.box[3]*s)],keypoints:u.keypoints.map(({score:c,part:d,position:h})=>({score:c,part:d,position:[Math.trunc(h.x*i),Math.trunc(h.y*s)],positionRaw:[h.x/n,h.y/n]})),annotations:{}});return e.map((u,p)=>o(u,p))}var D0=class{constructor(t,a){ue(this,"priorityQueue");ue(this,"numberOfElements");ue(this,"getElementValue");this.priorityQueue=new Array(t),this.numberOfElements=-1,this.getElementValue=a}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 a=2*t;if(a<this.numberOfElements&&this.less(a,a+1)&&a++,!this.less(t,a))break;this.exchange(t,a),t=a}}getValueAt(t){return this.getElementValue(this.priorityQueue[t])}less(t,a){return this.getValueAt(t)<this.getValueAt(a)}exchange(t,a){let n=this.priorityQueue[t];this.priorityQueue[t]=this.priorityQueue[a],this.priorityQueue[a]=n}};function l5(e,t,a,n){return{y:n.get(e,t,a),x:n.get(e,t,a+a0e)}}function u5(e,t,a){let{heatmapY:n,heatmapX:r,id:s}=e,{y:i,x:o}=l5(n,r,s,a);return{x:e.heatmapX*t+o,y:e.heatmapY*t+i}}function d5(e,t,a){return e<t?t:e>a?a:e}function Lk(e,t,a,n){let r=a-e,s=n-t;return r*r+s*s}function p5(e,t){return{x:e.x+t.x,y:e.y+t.y}}var rn,s0e=["MobilenetV1/offset_2/BiasAdd","MobilenetV1/heatmap_2/BiasAdd","MobilenetV1/displacement_fwd_2/BiasAdd","MobilenetV1/displacement_bwd_2/BiasAdd"],z0=1,Ru=16,i0e=50**2;function Bk(e,t,a,n,r,s,i=2){let o=x=>({y:s.get(x.y,x.x,e),x:s.get(x.y,x.x,s.shape[2]/2+e)}),l=(x,A,y)=>({y:d5(Math.round(x.y/Ru),0,A-1),x:d5(Math.round(x.x/Ru),0,y-1)}),[u,p]=n.shape,c=l(t.position,u,p),d=o(c),f=p5(t.position,d);for(let x=0;x<i;x++){let A=l(f,u,p),y=l5(A.y,A.x,a,r);f=p5({x:A.x*Ru,y:A.y*Ru},{x:y.x,y:y.y})}let m=l(f,u,p),g=n.get(m.y,m.x,a);return{position:f,part:Ep[a],score:g}}function o0e(e,t,a,n,r){let s=Ok.map(([d,h])=>[Np[d],Np[h]]),i=s.map(([,d])=>d),o=s.map(([d])=>d),l=t.shape[2],u=i.length,p=new Array(l),c=u5(e.part,Ru,a);p[e.part.id]={score:e.score,part:Ep[e.part.id],position:c};for(let d=u-1;d>=0;--d){let h=i[d],f=o[d];p[h]&&!p[f]&&(p[f]=Bk(d,p[h],f,t,a,r))}for(let d=0;d<u;++d){let h=o[d],f=i[d];p[h]&&!p[f]&&(p[f]=Bk(d,p[h],f,t,a,n))}return p}function l0e(e,t,a,n,r){let[s,i]=r.shape,o=!0,l=Math.max(a-z0,0),u=Math.min(a+z0+1,s);for(let p=l;p<u;++p){let c=Math.max(n-z0,0),d=Math.min(n+z0+1,i);for(let h=c;h<d;++h)if(r.get(p,h,e)>t){o=!1;break}if(!o)break}return o}function u0e(e,t){let[a,n,r]=t.shape,s=new D0(a*n*r,({score:i})=>i);for(let i=0;i<a;++i)for(let o=0;o<n;++o)for(let l=0;l<r;++l){let u=t.get(i,o,l);u<e||l0e(l,u,i,o,t)&&s.enqueue({score:u,part:{heatmapY:i,heatmapX:o,id:l}})}return s}function Wk(e,{x:t,y:a},n){return e.some(({keypoints:r})=>{var i;let s=(i=r[n])==null?void 0:i.position;return s?Lk(a,t,s.y,s.x)<=i0e:!1})}function d0e(e,t){return t.reduce((n,{position:r,score:s},i)=>(Wk(e,r,i)||(n+=s),n),0)/t.length}function p0e(e,t,a,n,r,s){let i=[],o=u0e(s,t);for(;i.length<r&&!o.empty();){let l=o.dequeue(),u=u5(l.part,Ru,e);if(Wk(i,u,l.part.id))continue;let p=o0e(l,t,e,a,n);p=p.filter(h=>h.score>s);let c=d0e(i,p),d=Dk(p);c>s&&i.push({keypoints:p,box:d,score:Math.round(100*c)/100})}return i}async function c5(e,t){if(!(rn!=null&&rn.executor))return[];let a=$e(()=>{if(!rn.inputs[0].shape)return[];let i=ge.resizeBilinear(e,[rn.inputs[0].shape[2],rn.inputs[0].shape[1]]),o=fe(me(He(i,"float32"),127.5),1),u=rn.execute(o,s0e).map(p=>_e(p,[0]));return u[1]=Da(u[1]),u}),n=await Promise.all(a.map(i=>i.buffer()));for(let i of a)Y(i);let r=p0e(n[0],n[1],n[2],n[3],t.body.maxDetected,t.body.minConfidence);return rn.inputs[0].shape?zk(r,[e.shape[1],e.shape[2]],[rn.inputs[0].shape[2],rn.inputs[0].shape[1]]):[]}async function Vk(e){return!rn||ne.initial?rn=await Ee(e.body.modelPath):e.debug&&K("cached model:",rn.modelUrl),rn}var lr,c0e=["fgr","pha","r1o","r2o","r3o","r4o"],Ut={},f5=0;function Hk(e){Y([Ut.r1i,Ut.r2i,Ut.r3i,Ut.r4i,Ut.downsample_ratio]),Ut.r1i=Be(0),Ut.r2i=Be(0),Ut.r3i=Be(0),Ut.r4i=Be(0),f5=e.segmentation.ratio||.5,Ut.downsample_ratio=Be(f5)}async function m5(e){return!lr||ne.initial?lr=await Ee(e.segmentation.modelPath):e.debug&&K("cached model:",lr.modelUrl),Hk(e),lr}var Gk=e=>$e(()=>{let t=_e(e,[0]),a=ae(t,ze.tf255);return He(a,"int32")});function h5(e,t){let a=e?Gk(e):nr([t.shape[1]||0,t.shape[2]||0,3],255,"int32"),n=t?Gk(t):nr([e.shape[1]||0,e.shape[2]||0,1],255,"int32"),r=at([a,n],-1);return Y([a,n]),r}function h0e(e){return $e(()=>{let t={};return t.unstack=Ta(e,-1),t.concat=at(t.unstack,1),t.split=ka(t.concat,4,1),t.stack=at(t.split,2),t.squeeze=_e(t.stack,[0]),t.expand=Gt(t.squeeze,-1),t.add=be(t.expand,1),t.mul=ae(t.add,127.5),t.cast=He(t.mul,"int32"),t.tile=Gr(t.cast,[1,1,3]),t.alpha=nr([t.tile.shape[0]||0,t.tile.shape[1]||0,1],255,"int32"),at([t.tile,t.alpha],-1)})}async function jk(e,t){if(lr||(lr=await m5(t)),!(lr!=null&&lr.executor))return null;Ut.src=me(e,255),f5!==t.segmentation.ratio&&Hk(t);let[a,n,r,s,i,o]=await lr.executeAsync(Ut,c0e),l;switch(t.segmentation.mode||"default"){case"default":l=h5(a,n);break;case"alpha":l=h5(null,n);break;case"foreground":l=h5(a,null);break;case"state":l=h0e(r);break;default:l=Be(0)}return Y([Ut.src,a,n,Ut.r1i,Ut.r2i,Ut.r3i,Ut.r4i]),[Ut.r1i,Ut.r2i,Ut.r3i,Ut.r4i]=[r,s,i,o],l}var ga;async function g5(e){return!ga||ne.initial?ga=await Ee(e.segmentation.modelPath):e.debug&&K("cached model:",ga.modelUrl),ga}async function Xk(e,t){var r;if(ga||(ga=await g5(t)),!(ga!=null&&ga.executor)||!((r=ga==null?void 0:ga.inputs)!=null&&r[0].shape))return null;let a={};a.resize=ge.resizeBilinear(e,[ga.inputs[0].shape?ga.inputs[0].shape[1]:0,ga.inputs[0].shape?ga.inputs[0].shape[2]:0],!1),a.norm=me(a.resize,ze.tf255),a.res=ga.execute(a.norm),a.squeeze=_e(a.res,[0]),a.alpha=ge.resizeBilinear(a.squeeze,[e.shape[1]||0,e.shape[2]||0]),a.mul=ae(a.alpha,ze.tf255);let n;switch(t.segmentation.mode||"default"){case"default":a.input=_e(e),a.concat=at([a.input,a.mul],-1),n=He(a.concat,"int32");break;case"alpha":n=He(a.mul,"int32");break;default:n=Be(0)}return Object.keys(a).forEach(s=>Y(a[s])),n}function L0(e,t,a){var u,p;if(!t||!((u=e==null?void 0:e.config)!=null&&u.validateModels))return null;let n=["const","placeholder","noop","pad","squeeze","add","sub","mul","div"],r=["biasadd","fusedbatchnormv3","matmul","switch","shape","merge","split","broadcastto"],s=[],i=[],o=t.modelUrl,l=t.executor;if((p=l==null?void 0:l.graph)!=null&&p.nodes)for(let c of Object.values(l.graph.nodes)){let d=c.op.toLowerCase();s.includes(d)||s.push(d)}else!l&&e.config.debug&&K("model not loaded",a);for(let c of s)!n.includes(c)&&!r.includes(c)&&!e.env.kernels.includes(c)&&!e.env.kernels.includes(c.replace("_",""))&&!e.env.kernels.includes(c.replace("native",""))&&!e.env.kernels.includes(c.replace("v2",""))&&i.push(c);return e.config.debug&&i.length>0&&K("model validation failed:",a,i),i.length>0?{name:a,missing:i,ops:s,url:o}:null}var Rp=class{constructor(t){ue(this,"instance");ue(this,"models",{});this.models={},this.instance=t}stats(){let t=0,a=0,n=0;for(let s of Object.values(ha))t+=s.sizeFromManifest,a+=s.sizeLoadedWeights,n+=s.sizeDesired;let r=n>0?a/n:0;return{numLoadedModels:Object.values(ha).length,numDefinedModels:Object.keys(this.models).length,percentageLoaded:r,totalSizeFromManifest:t,totalSizeWeights:a,totalSizeLoading:n,modelStats:Object.values(ha)}}reset(){for(let t of Object.keys(this.models))this.models[t]=null}async load(t){var n,r,s,i,o,l,u,p,c,d,h,f,m,g,x,A,y,b,w,S,C,E,_,$,M,I,N;ne.initial&&this.reset(),t&&(this.instance=t);let a={};a.blazeface=this.instance.config.face.enabled&&!this.models.blazeface?U9(this.instance.config):null,a.antispoof=this.instance.config.face.enabled&&((n=this.instance.config.face.antispoof)==null?void 0:n.enabled)&&!this.models.antispoof?fw(this.instance.config):null,a.liveness=this.instance.config.face.enabled&&((r=this.instance.config.face.liveness)==null?void 0:r.enabled)&&!this.models.liveness?Aw(this.instance.config):null,a.faceres=this.instance.config.face.enabled&&((s=this.instance.config.face.description)==null?void 0:s.enabled)&&!this.models.faceres?uw(this.instance.config):null,a.emotion=this.instance.config.face.enabled&&((i=this.instance.config.face.emotion)==null?void 0:i.enabled)&&!this.models.emotion?sw(this.instance.config):null,a.iris=this.instance.config.face.enabled&&((o=this.instance.config.face.iris)==null?void 0:o.enabled)&&!((l=this.instance.config.face.attention)!=null&&l.enabled)&&!this.models.iris?K9(this.instance.config):null,a.facemesh=this.instance.config.face.enabled&&((u=this.instance.config.face.mesh)==null?void 0:u.enabled)&&!this.models.facemesh?ew(this.instance.config):null,a.gear=this.instance.config.face.enabled&&((p=this.instance.config.face.gear)==null?void 0:p.enabled)&&!this.models.gear?ww(this.instance.config):null,a.ssrnetage=this.instance.config.face.enabled&&((c=this.instance.config.face.ssrnet)==null?void 0:c.enabled)&&!this.models.ssrnetage?Tw(this.instance.config):null,a.ssrnetgender=this.instance.config.face.enabled&&((d=this.instance.config.face.ssrnet)==null?void 0:d.enabled)&&!this.models.ssrnetgender?Rw(this.instance.config):null,a.mobilefacenet=this.instance.config.face.enabled&&((h=this.instance.config.face.mobilefacenet)==null?void 0:h.enabled)&&!this.models.mobilefacenet?Fw(this.instance.config):null,a.insightface=this.instance.config.face.enabled&&((f=this.instance.config.face.insightface)==null?void 0:f.enabled)&&!this.models.insightface?Bw(this.instance.config):null,a.blazepose=this.instance.config.body.enabled&&!this.models.blazepose&&((m=this.instance.config.body.modelPath)==null?void 0:m.includes("blazepose"))?S9(this.instance.config):null,a.blazeposedetect=this.instance.config.body.enabled&&!this.models.blazeposedetect&&this.instance.config.body.detector&&this.instance.config.body.detector.modelPath?I9(this.instance.config):null,a.efficientpose=this.instance.config.body.enabled&&!this.models.efficientpose&&((g=this.instance.config.body.modelPath)==null?void 0:g.includes("efficientpose"))?M9(this.instance.config):null,a.movenet=this.instance.config.body.enabled&&!this.models.movenet&&((x=this.instance.config.body.modelPath)==null?void 0:x.includes("movenet"))?Mk(this.instance.config):null,a.posenet=this.instance.config.body.enabled&&!this.models.posenet&&((A=this.instance.config.body.modelPath)==null?void 0:A.includes("posenet"))?Vk(this.instance.config):null,a.handtrack=this.instance.config.hand.enabled&&!this.models.handtrack&&((b=(y=this.instance.config.hand.detector)==null?void 0:y.modelPath)==null?void 0:b.includes("handtrack"))?bk(this.instance.config):null,a.handskeleton=this.instance.config.hand.enabled&&this.instance.config.hand.landmarks&&!this.models.handskeleton&&((S=(w=this.instance.config.hand.detector)==null?void 0:w.modelPath)==null?void 0:S.includes("handtrack"))?vk(this.instance.config):null,(E=(C=this.instance.config.hand.detector)==null?void 0:C.modelPath)!=null&&E.includes("handdetect")&&([a.handpose,a.handskeleton]=this.models.handpose?[null,null]:await mk(this.instance.config)),a.centernet=this.instance.config.object.enabled&&!this.models.centernet&&((_=this.instance.config.object.modelPath)==null?void 0:_.includes("centernet"))?N9(this.instance.config):null,a.nanodet=this.instance.config.object.enabled&&!this.models.nanodet&&(($=this.instance.config.object.modelPath)==null?void 0:$.includes("nanodet"))?Pk(this.instance.config):null,a.selfie=this.instance.config.segmentation.enabled&&!this.models.selfie&&((M=this.instance.config.segmentation.modelPath)==null?void 0:M.includes("selfie"))?g5(this.instance.config):null,a.meet=this.instance.config.segmentation.enabled&&!this.models.meet&&((I=this.instance.config.segmentation.modelPath)==null?void 0:I.includes("meet"))?t5(this.instance.config):null,a.rvm=this.instance.config.segmentation.enabled&&!this.models.rvm&&((N=this.instance.config.segmentation.modelPath)==null?void 0:N.includes("rvm"))?m5(this.instance.config):null;for(let[O,L]of Object.entries(a))L!=null&&L.then&&L.then(B=>this.models[O]=B);await Promise.all(Object.values(a))}list(){let t=Object.keys(this.models).map(a=>{var n;return{name:a,loaded:this.models[a]!==null,size:0,url:this.models[a]?(n=this.models[a])==null?void 0:n.modelUrl:null}});for(let a of t){let n=Object.keys(ha).find(r=>r.startsWith(a.name));!n||(a.size=ha[n].sizeLoadedWeights,a.url=ha[n].url)}return t}loaded(){return this.list().filter(n=>n.loaded).map(n=>n.name)}validate(){let t=[];for(let a of Object.keys(this.models)){let n=this.models[a];if(!n)continue;let r=L0(this.instance,n,a);r&&t.push(r)}return t}};function Zk(e,t,a,n,r){var o,l,u,p,c,d;let s=0,i=[];for(let h of e){let f={id:s++,face:h,body:null,hands:{left:null,right:null},gestures:[],box:[0,0,0,0]};for(let b of t)h.box[0]>b.box[0]&&h.box[0]<b.box[0]+b.box[2]&&h.box[1]+h.box[3]>b.box[1]&&h.box[1]+h.box[3]<b.box[1]+b.box[3]&&(f.body=b);if(f.body)for(let b of a)b.box[0]+b.box[2]>f.body.box[0]&&b.box[0]+b.box[2]<f.body.box[0]+f.body.box[2]&&b.box[1]+b.box[3]>f.body.box[1]&&b.box[1]+b.box[3]<f.body.box[1]+f.body.box[3]&&f.hands&&(f.hands.left=b),b.box[0]<f.body.box[0]+f.body.box[2]&&b.box[0]>f.body.box[0]&&b.box[1]+b.box[3]>f.body.box[1]&&b.box[1]+b.box[3]<f.body.box[1]+f.body.box[3]&&f.hands&&(f.hands.right=b);for(let b of n)(b.face!==void 0&&b.face===h.id||b.iris!==void 0&&b.iris===h.id||b.body!==void 0&&b.body===((o=f.body)==null?void 0:o.id)||b.hand!==void 0&&b.hand===((l=f.hands.left)==null?void 0:l.id)||b.hand!==void 0&&b.hand===((u=f.hands.right)==null?void 0:u.id))&&f.gestures.push(b);let m=[],g=[],x=b=>{b&&b.length===4&&(m.push(b[0],b[0]+b[2]),g.push(b[1],b[1]+b[3]))};x(f.face.box),x((p=f.body)==null?void 0:p.box),x((c=f.hands.left)==null?void 0:c.box),x((d=f.hands.right)==null?void 0:d.box);let A=Math.min(...m),y=Math.min(...g);f.box=[A,y,Math.max(...m)-A,Math.max(...g)-y],(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]]),i.push(f)}return i}var B0=`
/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==`,W0=`
/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 g0e(e){let t=(r,s="application/octet-stream")=>fetch(`data:${s};base64,${r}`).then(i=>i.blob()),a,n;switch(e.config.warmup){case"face":a=await t(B0);break;case"body":case"full":a=await t(W0);break;default:a=null}if(a){let r=await createImageBitmap(a);n=await e.detect(r,e.config),r.close()}return n}async function x0e(e){return new Promise(t=>{let a;switch(e.config.warmup){case"face":a="data:image/jpeg;base64,"+B0;break;case"full":case"body":a="data:image/jpeg;base64,"+W0;break;default:a=""}let n;if(typeof Image!="undefined")n=new Image;else if(ne.Image)n=new ne.Image;else{t(void 0);return}n.onload=async()=>{let r=Nn(n.naturalWidth,n.naturalHeight);if(!r)K("Warmup: Canvas not found"),t(void 0);else{let s=r.getContext("2d");s&&s.drawImage(n,0,0);let i=await e.image(r,!0),o=i.tensor?await e.detect(i.tensor,e.config):void 0;t(o)}},a?n.src=a:t(void 0)})}async function A0e(e){let t=r=>Buffer.from(r,"base64"),a;e.config.warmup==="face"?a=t(B0):a=t(W0);let n;if("node"in Ue&&ia()==="tensorflow"){let r=(void 0).decodeJpeg(a),s=Gt(r,0);e.tf.dispose(r),n=await e.detect(s,e.config),e.tf.dispose(s)}else e.config.debug&&K("Warmup tfjs-node not loaded");return n}async function y0e(e){let t;return typeof createImageBitmap=="function"?t=await g0e(e):typeof Image!="undefined"||ne.Canvas!==void 0?t=await x0e(e):t=await A0e(e),t}async function b0e(e){var o,l,u,p;if(!W().flagRegistry.ENGINE_COMPILE_ONLY)return;let t=ia(),a=tr();if(t!=="webgl"&&t!=="humangl"||!(a!=null&&a.checkCompileCompletion))return;W().set("ENGINE_COMPILE_ONLY",!0);let n=kt().state.numTensors,r=[];for(let[c,d]of Object.entries(e.models.models)){if(!d)continue;let h=(d==null?void 0:d.modelSignature)&&((l=(o=d==null?void 0:d.inputs)==null?void 0:o[0])==null?void 0:l.shape)?[...d.inputs[0].shape]:[1,64,64,3],f=(d==null?void 0:d.modelSignature)&&((p=(u=d==null?void 0:d.inputs)==null?void 0:u[0])==null?void 0:p.dtype)?d.inputs[0].dtype:"float32";for(let g=0;g<h.length;g++)h[g]===-1&&(h[g]=g===0?1:64);let m=fn(h,f);try{let g=d.execute(m);r.push(c),Array.isArray(g)?g.forEach(x=>Y(x)):Y(g)}catch(g){e.config.debug&&K("compile fail model:",c)}Y(m)}let s=await a.checkCompileCompletionAsync();a.getUniformLocations(),e.config.debug&&K("compile pass:",{models:r,kernels:s.length}),W().set("ENGINE_COMPILE_ONLY",!1);let i=kt().state.numTensors;i-n>0&&K("tensor leak:",i-n)}async function Yk(e,t){await wp(e,!1);let a=te();return e.state="warmup",t&&(e.config=Ct(e.config,t)),!e.config.warmup||e.config.warmup.length===0||e.config.warmup==="none"?or():new Promise(async n=>{await e.models.load(),await b0e(e);let r=await y0e(e),s=te();e.config.debug&&K("warmup",e.config.warmup,Math.round(s-a),"ms"),e.emit("warmup"),n(r)})}var Mu,Mp,$p,V0,Is,A5=class{constructor(t){ue(this,"version");ue(this,"config");ue(this,"result");ue(this,"state");ue(this,"process");ue(this,"tf");ue(this,"env",ne);ue(this,"draw",s0);ue(this,"match",$0);ue(this,"models");ue(this,"events");ue(this,"faceTriangulation");ue(this,"faceUVMap");ue(this,"performance");Gn(this,Mu,void 0);Gn(this,Mp,void 0);Gn(this,$p,void 0);ue(this,"analyze",(...t)=>{if(!Ga(this,Mp))return;let a=this.tf.engine().state.numTensors,n=Ga(this,Mu);fr(this,Mu,a);let r=a-n;r!==0&&K(...t,r)});Gn(this,V0,t=>{if(!Ga(this,$p))return null;if(!t)return"input is not defined";if(this.env.node&&!(t instanceof pt))return"input must be a tensor";try{this.tf.getBackend()}catch(a){return"backend not loaded"}return null});ue(this,"webcam",new Jh);ue(this,"emit",t=>{var a;(a=this.events)!=null&&a.dispatchEvent&&this.events.dispatchEvent(new Event(t))});Gn(this,Is,{});let a=(xp.tfjs||A2).replace(/-(.*)/,"");Io.wasmPath=`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${a}/dist/`,Io.modelBasePath=ne.browser?"../models/":"file://models/",this.version=X3,Object.defineProperty(this,"version",{value:X3}),this.config=JSON.parse(JSON.stringify(Io)),Object.seal(this.config),this.config.cacheModels=typeof indexedDB!="undefined",t&&(this.config=Ct(this.config,t)),u9(this.config),this.tf=Ue,this.state="idle",fr(this,Mu,0),fr(this,Mp,!1),fr(this,$p,!1),this.performance={},this.events=typeof EventTarget!="undefined"?new EventTarget:void 0,this.models=new Rp(this),tg(),this.result=or(),this.process={tensor:null,canvas:null},this.faceTriangulation=tw,this.faceUVMap=aw,L0(this,null,""),this.emit("create"),(this.config.debug||this.env.browser)&&K(`version: ${this.version}`),this.config.debug&&K(`tfjs version: ${this.tf.version["tfjs-core"]}`);let n=JSON.parse(JSON.stringify(this.env));delete n.kernels,delete n.initial,delete n.perfadd,this.config.debug&&K("environment:",n)}reset(){let t=this.config.backend;this.config=JSON.parse(JSON.stringify(Io)),this.config.backend=t,j3(),ne.initial=!0}validate(t){let a=U3(Io,t||this.config);return a.length===0&&(this.config=Ct(this.config,t)),a}now(){return te()}image(t,a=!1){return Zh(t,this.config,a)}async segmentation(t,a){var s,i,o;if(a&&(this.config=Ct(this.config,a)),!this.config.segmentation.enabled)return null;let n=await Zh(t,this.config);if(!n.tensor)return null;let r=null;return(s=this.config.segmentation.modelPath)!=null&&s.includes("rvm")&&(r=await jk(n.tensor,this.config)),(i=this.config.segmentation.modelPath)!=null&&i.includes("meet")&&(r=await Ik(n.tensor,this.config)),(o=this.config.segmentation.modelPath)!=null&&o.includes("selfie")&&(r=await Xk(n.tensor,this.config)),Y(n.tensor),r}compare(t,a){return l9(this.config,t,a)}async init(){await wp(this,!0),await this.tf.ready(),j3()}async load(t){this.state="load";let a=te(),n=Object.values(this.models.models).filter(i=>i).length;t&&(this.config=Ct(this.config,t)),this.env.initial&&(await wp(this,!1)||K("error: backend check failed"),await Kd(),this.env.browser&&(this.config.debug&&K("configuration:",this.config),this.config.debug&&K("tf flags:",this.tf.ENV.flags))),await this.models.load(this),this.env.initial&&this.config.debug&&K("tf engine state:",this.tf.engine().state.numBytes,"bytes",this.tf.engine().state.numTensors,"tensors"),this.env.initial=!1,Object.values(this.models.models).filter(i=>i).length!==n&&(this.models.validate(),this.emit("load"));let s=Math.trunc(te()-a);s>(this.performance.loadModels||0)&&(this.performance.loadModels=this.env.perfadd?(this.performance.loadModels||0)+s:s)}next(t=this.result){return kk(t,this.config)}async warmup(t){let a=te(),n=await Yk(this,t),r=te();return this.performance.warmup=Math.trunc(r-a),n}async profile(t,a){let n=await this.tf.profile(()=>this.detect(t,a)),r={},s=0;for(let o of n.kernels){let l=Number(o.kernelTimeMs)||0;r[o.name]?r[o.name]+=l:r[o.name]=l,s+=l}let i=[];Object.entries(r).forEach(o=>i.push({kernel:o[0],time:o[1],perc:0}));for(let o of i)o.perc=Math.round(1e3*o.time/s)/1e3,o.time=Math.round(1e3*o.time)/1e3;return i.sort((o,l)=>l.time-o.time),i.length=20,i}async detect(t,a){return this.state="detect",new Promise(async n=>{var g,x,A,y,b,w,S,C,E,_,$,M,I,N,O,L,B,G,j,U,H;this.state="config";let r;this.config=Ct(this.config,a),this.state="check";let s=Ga(this,V0).call(this,t);s&&(K(s,t),this.emit("error"),n(or(s)));let i=te();await this.load(),r=te(),this.state="image";let o=await Zh(t,this.config);if(this.process=o,this.performance.inputProcess=this.env.perfadd?(this.performance.inputProcess||0)+Math.trunc(te()-r):Math.trunc(te()-r),this.analyze("Get Image:"),!o.tensor){this.config.debug&&K("could not convert input to tensor"),this.emit("error"),n(or("could not convert input to tensor"));return}this.emit("image"),r=te(),this.config.skipAllowed=await o9(this.config,o.tensor),this.config.filter.autoBrightness=(this.config.filter.autoBrightness||!1)&&this.config.skipAllowed,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(te()-r):Math.trunc(te()-r),this.analyze("Check Changed:");let l=[],u=[],p=[],c=[];this.state="detect:face",this.config.async?(l=this.config.face.enabled?Vg(this,o.tensor):[],this.performance.face&&delete this.performance.face):(r=te(),l=this.config.face.enabled?await Vg(this,o.tensor):[],this.performance.face=this.env.perfadd?(this.performance.face||0)+Math.trunc(te()-r):Math.trunc(te()-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?Ct(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?c5(o.tensor,d):[]:(x=this.config.body.modelPath)!=null&&x.includes("blazepose")?u=this.config.body.enabled?ig(o.tensor,d):[]:(A=this.config.body.modelPath)!=null&&A.includes("efficientpose")?u=this.config.body.enabled?hg(o.tensor,d):[]:(y=this.config.body.modelPath)!=null&&y.includes("movenet")&&(u=this.config.body.enabled?s5(o.tensor,d):[]),this.performance.body&&delete this.performance.body):(r=te(),(b=this.config.body.modelPath)!=null&&b.includes("posenet")?u=this.config.body.enabled?await c5(o.tensor,d):[]:(w=this.config.body.modelPath)!=null&&w.includes("blazepose")?u=this.config.body.enabled?await ig(o.tensor,d):[]:(S=this.config.body.modelPath)!=null&&S.includes("efficientpose")?u=this.config.body.enabled?await hg(o.tensor,d):[]:(C=this.config.body.modelPath)!=null&&C.includes("movenet")&&(u=this.config.body.enabled?await s5(o.tensor,d):[]),this.performance.body=this.env.perfadd?(this.performance.body||0)+Math.trunc(te()-r):Math.trunc(te()-r)),this.analyze("End Body:"),this.analyze("Start Hand:"),this.state="detect:hand";let h=this.config.hand.maxDetected===-1?Ct(this.config,{hand:{maxDetected:this.config.face.enabled?2*l.length:1}}):this.config;this.config.async?((_=(E=this.config.hand.detector)==null?void 0:E.modelPath)!=null&&_.includes("handdetect")?p=this.config.hand.enabled?qg(o.tensor,h):[]:(M=($=this.config.hand.detector)==null?void 0:$.modelPath)!=null&&M.includes("handtrack")&&(p=this.config.hand.enabled?Zg(o.tensor,h):[]),this.performance.hand&&delete this.performance.hand):(r=te(),(N=(I=this.config.hand.detector)==null?void 0:I.modelPath)!=null&&N.includes("handdetect")?p=this.config.hand.enabled?await qg(o.tensor,h):[]:(L=(O=this.config.hand.detector)==null?void 0:O.modelPath)!=null&&L.includes("handtrack")&&(p=this.config.hand.enabled?await Zg(o.tensor,h):[]),this.performance.hand=this.env.perfadd?(this.performance.hand||0)+Math.trunc(te()-r):Math.trunc(te()-r)),this.analyze("End Hand:"),this.analyze("Start Object:"),this.state="detect:object",this.config.async?((B=this.config.object.modelPath)!=null&&B.includes("nanodet")?c=this.config.object.enabled?o5(o.tensor,this.config):[]:(G=this.config.object.modelPath)!=null&&G.includes("centernet")&&(c=this.config.object.enabled?ug(o.tensor,this.config):[]),this.performance.object&&delete this.performance.object):(r=te(),(j=this.config.object.modelPath)!=null&&j.includes("nanodet")?c=this.config.object.enabled?await o5(o.tensor,this.config):[]:(U=this.config.object.modelPath)!=null&&U.includes("centernet")&&(c=this.config.object.enabled?await ug(o.tensor,this.config):[]),this.performance.object=this.env.perfadd?(this.performance.object||0)+Math.trunc(te()-r):Math.trunc(te()-r)),this.analyze("End Object:"),this.state="detect:await",this.config.async&&([l,u,p,c]=await Promise.all([l,u,p,c])),this.state="detect:gesture";let f=[];this.config.gesture.enabled&&(r=te(),f=[...Qw(l),...Jw(u),...tk(p),...ek(l)],this.config.async?this.performance.gesture&&delete this.performance.gesture:this.performance.gesture=this.env.perfadd?(this.performance.gesture||0)+Math.trunc(te()-r):Math.trunc(te()-r)),this.performance.total=this.env.perfadd?(this.performance.total||0)+Math.trunc(te()-i):Math.trunc(te()-i);let m=((H=this.process.tensor)==null?void 0:H.shape)||[0,0,0,0];this.result={face:l,body:u,hand:p,gesture:f,object:c,performance:this.performance,canvas:this.process.canvas,timestamp:Date.now(),error:null,width:m[2],height:m[1],get persons(){return Zk(l,u,p,f,m)}},Y(o.tensor),this.emit("detect"),this.state="idle",n(this.result)})}async sleep(t){return new Promise(a=>{setTimeout(a,t)})}async video(t,a=!0,n=0){a?(Ga(this,Is)[t.id]||(this.config.debug&&K("video start",t.id),Ga(this,Is)[t.id]=!0),!t.paused&&Ga(this,Is)[t.id]&&t.readyState>=2&&await this.detect(t),n>0&&await this.sleep(n),Ga(this,Is)[t.id]&&requestAnimationFrame(()=>this.video(t,a,n))):(this.config.debug&&K("video stop",t.id),Ga(this,Is)[t.id]=!1)}};Mu=new WeakMap,Mp=new WeakMap,$p=new WeakMap,V0=new WeakMap,Is=new WeakMap;return OI(w0e);})();