mirror of https://github.com/vladmandic/human
9360 lines
1.5 MiB
9360 lines
1.5 MiB
/*
|
|
Human
|
|
homepage: <https://github.com/vladmandic/human>
|
|
author: <https://github.com/vladmandic>'
|
|
*/
|
|
|
|
"use strict";var Human=(()=>{var Jc=Object.defineProperty;var xC=Object.getOwnPropertyDescriptor;var AC=Object.getOwnPropertyNames;var bC=Object.prototype.hasOwnProperty;var vC=(e,t,a)=>t in e?Jc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a;var vr=(e,t)=>{for(var a in t)Jc(e,a,{get:t[a],enumerable:!0})},wC=(e,t,a,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of AC(t))!bC.call(e,r)&&r!==a&&Jc(e,r,{get:()=>t[r],enumerable:!(n=xC(t,r))||n.enumerable});return e};var kC=e=>wC(Jc({},"__esModule",{value:!0}),e);var he=(e,t,a)=>(vC(e,typeof t!="symbol"?t+"":t,a),a),a5=(e,t,a)=>{if(!t.has(e))throw TypeError("Cannot "+a)};var Xa=(e,t,a)=>(a5(e,t,"read from private field"),a?a.call(e):t.get(e)),Yn=(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)},wr=(e,t,a,n)=>(a5(e,t,"write to private field"),n?n.call(e,a):t.set(e,a),a);var zxe={};vr(zxe,{Env:()=>uc,Human:()=>Ux,default:()=>Ux,defaults:()=>yl,draw:()=>F0,empty:()=>fr,env:()=>ne,match:()=>im,models:()=>Vx});var Ye={};vr(Ye,{Abs:()=>cu,Acos:()=>$i,Acosh:()=>Di,AdadeltaOptimizer:()=>s3,AdagradOptimizer:()=>i3,AdamOptimizer:()=>o3,AdamaxOptimizer:()=>l3,Add:()=>Mr,AddN:()=>Pi,All:()=>_i,Any:()=>Oi,ArgMax:()=>hu,ArgMin:()=>mu,Asin:()=>zi,Asinh:()=>Li,Atan:()=>Wi,Atan2:()=>Vi,Atanh:()=>Bi,AvgPool:()=>Ui,AvgPool3D:()=>fu,AvgPool3DGrad:()=>yp,AvgPoolGrad:()=>gp,BackendWasm:()=>Wk,BatchMatMul:()=>Gi,BatchToSpaceND:()=>gu,Bincount:()=>Hi,BitwiseAnd:()=>ji,BroadcastArgs:()=>yu,BroadcastTo:()=>mN,Cast:()=>qi,Ceil:()=>cs,ClipByValue:()=>hs,Complex:()=>xp,ComplexAbs:()=>Ap,Concat:()=>xu,Conv2D:()=>Xi,Conv2DBackpropFilter:()=>bp,Conv2DBackpropInput:()=>Ki,Conv3D:()=>Yi,Conv3DBackpropFilterV2:()=>Au,Conv3DBackpropInputV2:()=>Zi,Cos:()=>Ji,Cosh:()=>Qi,CropAndResize:()=>ao,Cumprod:()=>eo,Cumsum:()=>to,DataStorage:()=>hp,DenseBincount:()=>bu,DepthToSpace:()=>no,DepthwiseConv2dNative:()=>ro,DepthwiseConv2dNativeBackpropFilter:()=>vp,DepthwiseConv2dNativeBackpropInput:()=>wp,Diag:()=>vu,Dilation2D:()=>so,Dilation2DBackpropFilter:()=>Ql,Dilation2DBackpropInput:()=>Jl,Draw:()=>kp,ENV:()=>lg,Einsum:()=>Ip,Elu:()=>oo,EluGrad:()=>wu,Environment:()=>UA,Equal:()=>ms,Erf:()=>lo,Exp:()=>fs,ExpandDims:()=>ku,Expm1:()=>gs,FFT:()=>Sp,Fill:()=>Iu,FlipLeftRight:()=>uo,Floor:()=>ys,FloorDiv:()=>xs,FromPixels:()=>jd,FusedBatchNorm:()=>po,FusedConv2D:()=>as,FusedDepthwiseConv2D:()=>ns,GPGPUContext:()=>Yl,GatherNd:()=>co,GatherV2:()=>Su,GraphModel:()=>ec,Greater:()=>As,GreaterEqual:()=>bs,IFFT:()=>Tp,Identity:()=>ho,Imag:()=>Cp,IsFinite:()=>mo,IsInf:()=>fo,IsNan:()=>go,KernelBackend:()=>du,LRN:()=>ko,LRNGrad:()=>Tu,LeakyRelu:()=>yo,Less:()=>vs,LessEqual:()=>ws,LinSpace:()=>xo,Log:()=>ks,Log1p:()=>Ao,LogSoftmax:()=>fN,LogicalAnd:()=>bo,LogicalNot:()=>vo,LogicalOr:()=>wo,LogicalXor:()=>HA,LowerBound:()=>gN,MathBackendCPU:()=>A3,MathBackendWebGL:()=>rc,MatrixBandPart:()=>yN,Max:()=>Io,MaxPool:()=>So,MaxPool3D:()=>Cu,MaxPool3DGrad:()=>Rp,MaxPoolGrad:()=>Np,MaxPoolWithArgmax:()=>Nu,Maximum:()=>Is,Mean:()=>To,Min:()=>Co,Minimum:()=>Ss,MirrorPad:()=>No,Mod:()=>Ro,MomentumOptimizer:()=>u3,Multinomial:()=>Eo,Multiply:()=>Ts,Neg:()=>Ru,NonMaxSuppressionV3:()=>Mo,NonMaxSuppressionV4:()=>Eu,NonMaxSuppressionV5:()=>Fo,NotEqual:()=>Cs,OP_SCOPE_SUFFIX:()=>hg,OneHot:()=>$o,OnesLike:()=>Mu,Optimizer:()=>_s,OptimizerConstructors:()=>s6,Pack:()=>Fu,PadV2:()=>Do,Pool:()=>xN,Pow:()=>Po,Prelu:()=>_o,Prod:()=>Oo,RMSPropOptimizer:()=>d3,RaggedGather:()=>Lh,RaggedRange:()=>Wh,RaggedTensorToTensor:()=>Bh,Range:()=>$u,Rank:()=>u1,Real:()=>Ep,RealDiv:()=>io,Reciprocal:()=>zo,Reduction:()=>wa,Relu:()=>Lo,Relu6:()=>Vo,Reshape:()=>Du,ResizeBilinear:()=>Bo,ResizeBilinearGrad:()=>_u,ResizeNearestNeighbor:()=>Wo,ResizeNearestNeighborGrad:()=>Pu,Reverse:()=>Uo,RotateWithOffset:()=>ol,Round:()=>Go,Rsqrt:()=>Ns,SGDOptimizer:()=>i0,ScatterNd:()=>Ho,SearchSorted:()=>qo,Select:()=>Ou,Selu:()=>Xo,Sigmoid:()=>Rs,Sign:()=>Zo,Sin:()=>Ko,Sinh:()=>Yo,Slice:()=>zu,Softmax:()=>el,Softplus:()=>Jo,SpaceToBatchND:()=>Lu,SparseFillEmptyRows:()=>Mp,SparseReshape:()=>Bu,SparseSegmentMean:()=>Vu,SparseSegmentSum:()=>Uu,SparseToDense:()=>tl,SplitV:()=>Wu,Sqrt:()=>Es,Square:()=>Fp,SquaredDifference:()=>Ms,StaticRegexReplace:()=>Gu,Step:()=>Ds,StridedSlice:()=>al,StringNGrams:()=>Hu,StringSplit:()=>$p,StringToHashBucketFast:()=>Dp,Sub:()=>Fs,Sum:()=>Qo,Tan:()=>nl,Tanh:()=>rl,Tensor:()=>yt,TensorBuffer:()=>Rt,TensorScatterUpdate:()=>jo,Tile:()=>$s,TopK:()=>sl,Transform:()=>il,Transpose:()=>Tr,Unique:()=>Pp,Unpack:()=>ju,UnsortedSegmentSum:()=>_p,UpperBound:()=>AN,Variable:()=>Yd,WebGPUBackend:()=>ny,ZerosLike:()=>qu,_FusedMatMul:()=>ts,abs:()=>Ja,acos:()=>xb,acosh:()=>Ab,add:()=>we,addN:()=>Uh,all:()=>bb,any:()=>vb,argMax:()=>or,argMin:()=>wb,asin:()=>kb,asinh:()=>Ib,atan:()=>Sb,atan2:()=>Tb,atanh:()=>Cb,avgPool:()=>vg,avgPool3d:()=>Mb,backend:()=>Gn,backend_util:()=>I,basicLSTMCell:()=>Fb,batchNorm:()=>jp,batchNorm2d:()=>$b,batchNorm3d:()=>Db,batchNorm4d:()=>Pb,batchToSpaceND:()=>wg,bincount:()=>kg,bitwiseAnd:()=>_b,booleanMaskAsync:()=>b7,broadcastArgs:()=>Ob,broadcastTo:()=>Ai,broadcast_util:()=>ul,browser:()=>Pr,buffer:()=>Te,cast:()=>Ue,ceil:()=>zb,clipByValue:()=>Lb,clone:()=>Ia,complex:()=>Rr,concat:()=>lt,concat1d:()=>Wb,concat2d:()=>Xu,concat3d:()=>Bb,concat4d:()=>Vb,conv1d:()=>Ub,conv2d:()=>qp,conv2dTranspose:()=>Hb,conv3d:()=>jb,conv3dTranspose:()=>qb,copyRegisteredKernels:()=>IN,cos:()=>Xb,cosh:()=>Kb,cosineWindow:()=>t0,cumprod:()=>Yb,cumsum:()=>Zb,customGrad:()=>rr,denseBincount:()=>Jb,deprecationWarn:()=>fg,depthToSpace:()=>Qb,depthwiseConv2d:()=>Gh,deregisterOp:()=>TO,device_util:()=>Wp,diag:()=>e4,dilation2d:()=>t4,disableDeprecationWarnings:()=>tR,dispose:()=>J,disposeVariables:()=>aR,div:()=>ve,divNoNan:()=>n4,dot:()=>r4,dropout:()=>S7,einsum:()=>hi,elu:()=>Tg,enableDebugMode:()=>eR,enableProdMode:()=>mg,enclosingPowerOfTwo:()=>a3,engine:()=>St,ensureShape:()=>s4,env:()=>B,equal:()=>Sg,erf:()=>i4,euclideanNorm:()=>u4,exp:()=>ls,expandDims:()=>Bt,expm1:()=>d4,eye:()=>Ng,fft:()=>Zh,fill:()=>lr,findBackend:()=>gg,findBackendFactory:()=>oR,floor:()=>Rg,floorDiv:()=>Gp,forceHalfFloat:()=>Dw,fused:()=>n3,gather:()=>Eg,gatherND:()=>I7,gather_util:()=>h3,getBackend:()=>ea,getGradient:()=>o1,getKernel:()=>Xd,getKernelsForBackend:()=>tr,getThreadsCount:()=>Zle,gpgpu_util:()=>pw,grad:()=>UM,grads:()=>GM,greater:()=>Yp,greaterEqual:()=>Mg,ifft:()=>rp,imag:()=>Zp,image:()=>fe,inTopKAsync:()=>T7,io:()=>Jn,irfft:()=>Yg,isFinite:()=>p4,isInf:()=>c4,isNaN:()=>h4,keep:()=>Bn,kernel_impls:()=>Fn,leakyRelu:()=>Fg,less:()=>bh,lessEqual:()=>Hh,linalg:()=>D7,linspace:()=>m4,loadGraphModel:()=>x3,loadGraphModelSync:()=>Fz,localResponseNormalization:()=>f4,log:()=>au,log1p:()=>$g,logSigmoid:()=>y4,logSoftmax:()=>x4,logSumExp:()=>Pg,logicalAnd:()=>tp,logicalNot:()=>_g,logicalOr:()=>Og,logicalXor:()=>A4,losses:()=>P7,lowerBound:()=>b4,matMul:()=>pt,math:()=>q7,max:()=>fa,maxPool:()=>zg,maxPool3d:()=>v4,maxPoolWithArgmax:()=>w4,maximum:()=>Lg,mean:()=>ap,memory:()=>nR,meshgrid:()=>k4,min:()=>os,minimum:()=>np,mirrorPad:()=>I4,mod:()=>Ku,moments:()=>S4,movingAverage:()=>v7,mul:()=>te,multiRNNCell:()=>T4,multinomial:()=>C4,neg:()=>Vn,nextFrame:()=>i6,node:()=>py,norm:()=>Kp,notEqual:()=>Wg,oneHot:()=>vh,ones:()=>Yr,onesLike:()=>N4,op:()=>z,outerProduct:()=>R4,pad:()=>ur,pad1d:()=>E4,pad2d:()=>M4,pad3d:()=>F4,pad4d:()=>$4,pool:()=>D4,pow:()=>tu,prelu:()=>Vg,print:()=>Ag,prod:()=>P4,profile:()=>rR,raggedGather:()=>_4,raggedRange:()=>O4,raggedTensorToTensor:()=>z4,rand:()=>L4,randomGamma:()=>U4,randomNormal:()=>qg,randomStandardNormal:()=>G4,randomUniform:()=>Xh,randomUniformInt:()=>H4,range:()=>nu,ready:()=>Vp,real:()=>ru,reciprocal:()=>j4,registerBackend:()=>ll,registerGradient:()=>vN,registerKernel:()=>bn,registerOp:()=>SO,relu:()=>Jp,relu6:()=>Xg,removeBackend:()=>iR,reshape:()=>Q,reverse:()=>us,reverse1d:()=>q4,reverse2d:()=>X4,reverse3d:()=>K4,reverse4d:()=>Y4,rfft:()=>Jh,round:()=>Kg,rsqrt:()=>Z4,scalar:()=>Ge,scatterND:()=>w7,scatter_util:()=>Qh,searchSorted:()=>qh,selu:()=>J4,separableConv2d:()=>Q4,serialization:()=>z7,setBackend:()=>Bp,setPlatform:()=>lR,setThreadsCount:()=>Yle,setWasmPath:()=>Kle,setWasmPaths:()=>f0,setWebGLContext:()=>u0,setdiff1dAsync:()=>e7,shared:()=>b3,sigmoid:()=>za,sign:()=>t7,signal:()=>$7,sin:()=>a7,sinh:()=>n7,slice:()=>_e,slice1d:()=>r7,slice2d:()=>s7,slice3d:()=>Qp,slice4d:()=>Kh,slice_util:()=>wt,softmax:()=>Yh,softplus:()=>Dg,spaceToBatchND:()=>Bg,sparse:()=>_7,sparseToDense:()=>k7,spectral:()=>F7,split:()=>Sa,sqrt:()=>nr,square:()=>En,squaredDifference:()=>Zg,squeeze:()=>Oe,stack:()=>ca,step:()=>Jg,stridedSlice:()=>i7,string:()=>O7,sub:()=>xe,sum:()=>ot,sumOutType:()=>Lp,tan:()=>o7,tanh:()=>Ah,tensor:()=>Ve,tensor1d:()=>Vt,tensor2d:()=>er,tensor3d:()=>Qg,tensor4d:()=>l7,tensor5d:()=>u7,tensor6d:()=>d7,tensorScatterUpdate:()=>c7,tensor_util:()=>ZA,test_util:()=>W4,tidy:()=>Pe,tile:()=>Qr,time:()=>sR,topk:()=>h7,train:()=>w_,transpose:()=>Si,truncatedNormal:()=>m7,unique:()=>f7,unregisterGradient:()=>kN,unregisterKernel:()=>wN,unsortedSegmentSum:()=>g7,unstack:()=>Na,upcastType:()=>Qt,upperBound:()=>y7,util:()=>v,valueAndGrad:()=>HM,valueAndGrads:()=>jM,variable:()=>x7,variableGrads:()=>g4,version:()=>lc,version_converter:()=>Dz,version_core:()=>m3,version_cpu:()=>XL,version_wasm:()=>Jle,version_webgl:()=>Oq,webgl:()=>zq,webgl_util:()=>Pv,webgpu_util:()=>Uk,where:()=>Cr,whereAsync:()=>t3,zeros:()=>An,zerosLike:()=>en});var IC=Object.create,sg=Object.defineProperty,SC=Object.getOwnPropertyDescriptor,TC=Object.getOwnPropertyNames,CC=Object.getPrototypeOf,NC=Object.prototype.hasOwnProperty,Xt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ke=(e,t)=>{for(var a in t)sg(e,a,{get:t[a],enumerable:!0})},RC=(e,t,a,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of TC(t))!NC.call(e,r)&&r!==a&&sg(e,r,{get:()=>t[r],enumerable:!(n=SC(t,r))||n.enumerable});return e},uu=(e,t,a)=>(a=e!=null?IC(CC(e)):{},RC(t||!e||!e.__esModule?sg(a,"default",{value:e,enumerable:!0}):a,e)),EC=Xt((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(T){}function n(T,D,O){this.low=T|0,this.high=D|0,this.unsigned=!!O}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0});function r(T){return(T&&T.__isLong__)===!0}n.isLong=r;var s={},i={};function o(T,D){var O,W,$;return D?(T>>>=0,($=0<=T&&T<256)&&(W=i[T],W)?W:(O=u(T,(T|0)<0?-1:0,!0),$&&(i[T]=O),O)):(T|=0,($=-128<=T&&T<128)&&(W=s[T],W)?W:(O=u(T,T<0?-1:0,!1),$&&(s[T]=O),O))}n.fromInt=o;function l(T,D){if(isNaN(T))return D?b:A;if(D){if(T<0)return b;if(T>=g)return M}else{if(T<=-y)return F;if(T+1>=y)return N}return T<0?l(-T,D).neg():u(T%f|0,T/f|0,D)}n.fromNumber=l;function u(T,D,O){return new n(T,D,O)}n.fromBits=u;var d=Math.pow;function c(T,D,O){if(T.length===0)throw Error("empty string");if(T==="NaN"||T==="Infinity"||T==="+Infinity"||T==="-Infinity")return A;if(typeof D=="number"?(O=D,D=!1):D=!!D,O=O||10,O<2||36<O)throw RangeError("radix");var W;if((W=T.indexOf("-"))>0)throw Error("interior hyphen");if(W===0)return c(T.substring(1),D,O).neg();for(var $=l(d(O,8)),U=A,G=0;G<T.length;G+=8){var q=Math.min(8,T.length-G),H=parseInt(T.substring(G,G+q),O);if(q<8){var V=l(d(O,q));U=U.mul(V).add(l(H))}else U=U.mul($),U=U.add(l(H))}return U.unsigned=D,U}n.fromString=c;function p(T,D){return typeof T=="number"?l(T,D):typeof T=="string"?c(T,D):u(T.low,T.high,typeof D=="boolean"?D:T.unsigned)}n.fromValue=p;var h=65536,m=1<<24,f=h*h,g=f*f,y=g/2,x=o(m),A=o(0);n.ZERO=A;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 N=u(-1,2147483647,!1);n.MAX_VALUE=N;var M=u(-1,-1,!0);n.MAX_UNSIGNED_VALUE=M;var F=u(0,-2147483648,!1);n.MIN_VALUE=F;var E=n.prototype;E.toInt=function(){return this.unsigned?this.low>>>0:this.low},E.toNumber=function(){return this.unsigned?(this.high>>>0)*f+(this.low>>>0):this.high*f+(this.low>>>0)},E.toString=function(T){if(T=T||10,T<2||36<T)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(F)){var D=l(T),O=this.div(D),W=O.mul(D).sub(this);return O.toString(T)+W.toInt().toString(T)}else return"-"+this.neg().toString(T);for(var $=l(d(T,6),this.unsigned),U=this,G="";;){var q=U.div($),H=U.sub(q.mul($)).toInt()>>>0,V=H.toString(T);if(U=q,U.isZero())return V+G;for(;V.length<6;)V="0"+V;G=""+V+G}},E.getHighBits=function(){return this.high},E.getHighBitsUnsigned=function(){return this.high>>>0},E.getLowBits=function(){return this.low},E.getLowBitsUnsigned=function(){return this.low>>>0},E.getNumBitsAbs=function(){if(this.isNegative())return this.eq(F)?64:this.neg().getNumBitsAbs();for(var T=this.high!=0?this.high:this.low,D=31;D>0&&!(T&1<<D);D--);return this.high!=0?D+33:D+1},E.isZero=function(){return this.high===0&&this.low===0},E.eqz=E.isZero,E.isNegative=function(){return!this.unsigned&&this.high<0},E.isPositive=function(){return this.unsigned||this.high>=0},E.isOdd=function(){return(this.low&1)===1},E.isEven=function(){return(this.low&1)===0},E.equals=function(T){return r(T)||(T=p(T)),this.unsigned!==T.unsigned&&this.high>>>31===1&&T.high>>>31===1?!1:this.high===T.high&&this.low===T.low},E.eq=E.equals,E.notEquals=function(T){return!this.eq(T)},E.neq=E.notEquals,E.ne=E.notEquals,E.lessThan=function(T){return this.comp(T)<0},E.lt=E.lessThan,E.lessThanOrEqual=function(T){return this.comp(T)<=0},E.lte=E.lessThanOrEqual,E.le=E.lessThanOrEqual,E.greaterThan=function(T){return this.comp(T)>0},E.gt=E.greaterThan,E.greaterThanOrEqual=function(T){return this.comp(T)>=0},E.gte=E.greaterThanOrEqual,E.ge=E.greaterThanOrEqual,E.compare=function(T){if(r(T)||(T=p(T)),this.eq(T))return 0;var D=this.isNegative(),O=T.isNegative();return D&&!O?-1:!D&&O?1:this.unsigned?T.high>>>0>this.high>>>0||T.high===this.high&&T.low>>>0>this.low>>>0?-1:1:this.sub(T).isNegative()?-1:1},E.comp=E.compare,E.negate=function(){return!this.unsigned&&this.eq(F)?F:this.not().add(w)},E.neg=E.negate,E.add=function(T){r(T)||(T=p(T));var D=this.high>>>16,O=this.high&65535,W=this.low>>>16,$=this.low&65535,U=T.high>>>16,G=T.high&65535,q=T.low>>>16,H=T.low&65535,V=0,Z=0,X=0,re=0;return re+=$+H,X+=re>>>16,re&=65535,X+=W+q,Z+=X>>>16,X&=65535,Z+=O+G,V+=Z>>>16,Z&=65535,V+=D+U,V&=65535,u(X<<16|re,V<<16|Z,this.unsigned)},E.subtract=function(T){return r(T)||(T=p(T)),this.add(T.neg())},E.sub=E.subtract,E.multiply=function(T){if(this.isZero())return A;if(r(T)||(T=p(T)),a){var D=a.mul(this.low,this.high,T.low,T.high);return u(D,a.get_high(),this.unsigned)}if(T.isZero())return A;if(this.eq(F))return T.isOdd()?F:A;if(T.eq(F))return this.isOdd()?F:A;if(this.isNegative())return T.isNegative()?this.neg().mul(T.neg()):this.neg().mul(T).neg();if(T.isNegative())return this.mul(T.neg()).neg();if(this.lt(x)&&T.lt(x))return l(this.toNumber()*T.toNumber(),this.unsigned);var O=this.high>>>16,W=this.high&65535,$=this.low>>>16,U=this.low&65535,G=T.high>>>16,q=T.high&65535,H=T.low>>>16,V=T.low&65535,Z=0,X=0,re=0,ee=0;return ee+=U*V,re+=ee>>>16,ee&=65535,re+=$*V,X+=re>>>16,re&=65535,re+=U*H,X+=re>>>16,re&=65535,X+=W*V,Z+=X>>>16,X&=65535,X+=$*H,Z+=X>>>16,X&=65535,X+=U*q,Z+=X>>>16,X&=65535,Z+=O*V+W*H+$*q+U*G,Z&=65535,u(re<<16|ee,Z<<16|X,this.unsigned)},E.mul=E.multiply,E.divide=function(T){if(r(T)||(T=p(T)),T.isZero())throw Error("division by zero");if(a){if(!this.unsigned&&this.high===-2147483648&&T.low===-1&&T.high===-1)return this;var D=(this.unsigned?a.div_u:a.div_s)(this.low,this.high,T.low,T.high);return u(D,a.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?b:A;var O,W,$;if(this.unsigned){if(T.unsigned||(T=T.toUnsigned()),T.gt(this))return b;if(T.gt(this.shru(1)))return S;$=b}else{if(this.eq(F)){if(T.eq(w)||T.eq(C))return F;if(T.eq(F))return w;var U=this.shr(1);return O=U.div(T).shl(1),O.eq(A)?T.isNegative()?w:C:(W=this.sub(T.mul(O)),$=O.add(W.div(T)),$)}else if(T.eq(F))return this.unsigned?b:A;if(this.isNegative())return T.isNegative()?this.neg().div(T.neg()):this.neg().div(T).neg();if(T.isNegative())return this.div(T.neg()).neg();$=A}for(W=this;W.gte(T);){O=Math.max(1,Math.floor(W.toNumber()/T.toNumber()));for(var G=Math.ceil(Math.log(O)/Math.LN2),q=G<=48?1:d(2,G-48),H=l(O),V=H.mul(T);V.isNegative()||V.gt(W);)O-=q,H=l(O,this.unsigned),V=H.mul(T);H.isZero()&&(H=w),$=$.add(H),W=W.sub(V)}return $},E.div=E.divide,E.modulo=function(T){if(r(T)||(T=p(T)),a){var D=(this.unsigned?a.rem_u:a.rem_s)(this.low,this.high,T.low,T.high);return u(D,a.get_high(),this.unsigned)}return this.sub(this.div(T).mul(T))},E.mod=E.modulo,E.rem=E.modulo,E.not=function(){return u(~this.low,~this.high,this.unsigned)},E.and=function(T){return r(T)||(T=p(T)),u(this.low&T.low,this.high&T.high,this.unsigned)},E.or=function(T){return r(T)||(T=p(T)),u(this.low|T.low,this.high|T.high,this.unsigned)},E.xor=function(T){return r(T)||(T=p(T)),u(this.low^T.low,this.high^T.high,this.unsigned)},E.shiftLeft=function(T){return r(T)&&(T=T.toInt()),(T&=63)===0?this:T<32?u(this.low<<T,this.high<<T|this.low>>>32-T,this.unsigned):u(0,this.low<<T-32,this.unsigned)},E.shl=E.shiftLeft,E.shiftRight=function(T){return r(T)&&(T=T.toInt()),(T&=63)===0?this:T<32?u(this.low>>>T|this.high<<32-T,this.high>>T,this.unsigned):u(this.high>>T-32,this.high>=0?0:-1,this.unsigned)},E.shr=E.shiftRight,E.shiftRightUnsigned=function(T){if(r(T)&&(T=T.toInt()),T&=63,T===0)return this;var D=this.high;if(T<32){var O=this.low;return u(O>>>T|D<<32-T,D>>>T,this.unsigned)}else return T===32?u(D,0,this.unsigned):u(D>>>T-32,0,this.unsigned)},E.shru=E.shiftRightUnsigned,E.shr_u=E.shiftRightUnsigned,E.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},E.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},E.toBytes=function(T){return T?this.toBytesLE():this.toBytesBE()},E.toBytesLE=function(){var T=this.high,D=this.low;return[D&255,D>>>8&255,D>>>16&255,D>>>24,T&255,T>>>8&255,T>>>16&255,T>>>24]},E.toBytesBE=function(){var T=this.high,D=this.low;return[T>>>24,T>>>16&255,T>>>8&255,T&255,D>>>24,D>>>16&255,D>>>8&255,D&255]},n.fromBytes=function(T,D,O){return O?n.fromBytesLE(T,D):n.fromBytesBE(T,D)},n.fromBytesLE=function(T,D){return new n(T[0]|T[1]<<8|T[2]<<16|T[3]<<24,T[4]|T[5]<<8|T[6]<<16|T[7]<<24,D)},n.fromBytesBE=function(T,D){return new n(T[4]<<24|T[5]<<16|T[6]<<8|T[7],T[0]<<24|T[1]<<16|T[2]<<8|T[3],D)}}),MC=Xt(()=>{}),FC=Xt(()=>{}),$C=Xt((e,t)=>{(function(a,n,r){function s(u){var d=this,c=l();d.next=function(){var p=2091639*d.s0+d.c*23283064365386963e-26;return d.s0=d.s1,d.s1=d.s2,d.s2=p-(d.c=p|0)},d.c=1,d.s0=c(" "),d.s1=c(" "),d.s2=c(" "),d.s0-=c(u),d.s0<0&&(d.s0+=1),d.s1-=c(u),d.s1<0&&(d.s1+=1),d.s2-=c(u),d.s2<0&&(d.s2+=1),c=null}function i(u,d){return d.c=u.c,d.s0=u.s0,d.s1=u.s1,d.s2=u.s2,d}function o(u,d){var c=new s(u),p=d&&d.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,p&&(typeof p=="object"&&i(p,c),h.state=function(){return i(c,{})}),h}function l(){var u=4022871197,d=function(c){c=String(c);for(var p=0;p<c.length;p++){u+=c.charCodeAt(p);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 d}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)}),DC=Xt((e,t)=>{(function(a,n,r){function s(l){var u=this,d="";u.x=0,u.y=0,u.z=0,u.w=0,u.next=function(){var p=u.x^u.x<<11;return u.x=u.y,u.y=u.z,u.z=u.w,u.w^=u.w>>>19^p^p>>>8},l===(l|0)?u.x=l:d+=l;for(var c=0;c<d.length+64;c++)u.x^=d.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 d=new s(l),c=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var h=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,c&&(typeof c=="object"&&i(c,d),p.state=function(){return i(d,{})}),p}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)}),PC=Xt((e,t)=>{(function(a,n,r){function s(l){var u=this,d="";u.next=function(){var p=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^(p^p<<1))|0},u.x=0,u.y=0,u.z=0,u.w=0,u.v=0,l===(l|0)?u.x=l:d+=l;for(var c=0;c<d.length+64;c++)u.x^=d.charCodeAt(c)|0,c==d.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 d=new s(l),c=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var h=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,c&&(typeof c=="object"&&i(c,d),p.state=function(){return i(d,{})}),p}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)}),_C=Xt((e,t)=>{(function(a,n,r){function s(l){var u=this;u.next=function(){var c=u.x,p=u.i,h,m,f;return h=c[p],h^=h>>>7,m=h^h<<24,h=c[p+1&7],m^=h^h>>>10,h=c[p+3&7],m^=h^h>>>3,h=c[p+4&7],m^=h^h<<7,h=c[p+7&7],h=h^h<<13,m^=h^h<<9,c[p]=m,u.i=p+1&7,m};function d(c,p){var h,m,f=[];if(p===(p|0))m=f[0]=p;else for(p=""+p,h=0;h<p.length;++h)f[h&7]=f[h&7]<<15^p.charCodeAt(h)+f[h+1&7]<<13;for(;f.length<8;)f.push(0);for(h=0;h<8&&f[h]===0;++h);for(h==8?m=f[7]=-1:m=f[h],c.x=f,c.i=0,h=256;h>0;--h)c.next()}d(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 d=new s(l),c=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var h=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,c&&(c.x&&i(c,d),p.state=function(){return i(d,{})}),p}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)}),OC=Xt((e,t)=>{(function(a,n,r){function s(l){var u=this;u.next=function(){var c=u.w,p=u.X,h=u.i,m,f;return u.w=c=c+1640531527|0,f=p[h+34&127],m=p[h=h+1&127],f^=f<<13,m^=m<<17,f^=f>>>15,m^=m>>>12,f=p[h]=f^m,u.i=h,f+(c^c>>>16)|0};function d(c,p){var h,m,f,g,y,x=[],A=128;for(p===(p|0)?(m=p,p=null):(p=p+"\0",m=0,A=Math.max(A,p.length)),f=0,g=-32;g<A;++g)p&&(m^=p.charCodeAt((g+32)%p.length)),g===0&&(y=m),m^=m<<10,m^=m>>>15,m^=m<<4,m^=m>>>13,g>=0&&(y=y+1640531527|0,h=x[g&127]^=m+y,f=h==0?f+1:0);for(f>=128&&(x[(p&&p.length||0)&127]=-1),f=127,g=4*128;g>0;--g)m=x[f+34&127],h=x[f=f+1&127],m^=m<<13,h^=h<<17,m^=m>>>15,h^=h>>>12,x[f]=m^h;c.w=y,c.X=x,c.i=f}d(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 d=new s(l),c=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var h=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,c&&(c.X&&i(c,d),p.state=function(){return i(d,{})}),p}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)}),zC=Xt((e,t)=>{(function(a,n,r){function s(l){var u=this,d="";u.next=function(){var p=u.b,h=u.c,m=u.d,f=u.a;return p=p<<25^p>>>7^h,h=h-m|0,m=m<<24^m>>>8^f,f=f-p|0,u.b=p=p<<20^p>>>12^h,u.c=h=h-m|0,u.d=m<<16^h>>>16^f,u.a=f-p|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):d+=l;for(var c=0;c<d.length+20;c++)u.b^=d.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 d=new s(l),c=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var h=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(h+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,c&&(typeof c=="object"&&i(c,d),p.state=function(){return i(d,{})}),p}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)}),LC=Xt(()=>{}),WC=Xt((e,t)=>{(function(a,n,r){var s=256,i=6,o=52,l="random",u=r.pow(s,i),d=r.pow(2,o),c=d*2,p=s-1,h;function m(w,S,C){var N=[];S=S==!0?{entropy:!0}:S||{};var M=x(y(S.entropy?[w,b(n)]:w==null?A():w,3),N),F=new f(N),E=function(){for(var T=F.g(i),D=u,O=0;T<d;)T=(T+O)*s,D*=s,O=F.g(1);for(;T>=c;)T/=2,D/=2,O>>>=1;return(T+O)/D};return E.int32=function(){return F.g(4)|0},E.quick=function(){return F.g(4)/4294967296},E.double=E,x(b(F.S),n),(S.pass||C||function(T,D,O,W){return W&&(W.S&&g(W,F),T.state=function(){return g(F,{})}),O?(r[l]=T,D):T})(E,M,"global"in S?S.global:this==r,S.state)}function f(w){var S,C=w.length,N=this,M=0,F=N.i=N.j=0,E=N.S=[];for(C||(w=[C++]);M<s;)E[M]=M++;for(M=0;M<s;M++)E[M]=E[F=p&F+w[M%C]+(S=E[M])],E[F]=S;(N.g=function(T){for(var D,O=0,W=N.i,$=N.j,U=N.S;T--;)D=U[W=p&W+1],O=O*s+U[p&(U[W]=U[$=p&$+D])+(U[$]=D)];return N.i=W,N.j=$,O})(s)}function g(w,S){return S.i=w.i,S.j=w.j,S.S=w.S.slice(),S}function y(w,S){var C=[],N=typeof w,M;if(S&&N=="object")for(M in w)try{C.push(y(w[M],S-1))}catch(F){}return C.length?C:N=="string"?w:w+"\0"}function x(w,S){for(var C=w+"",N,M=0;M<C.length;)S[p&M]=p&(N^=S[p&M]*19)+C.charCodeAt(M++);return b(S)}function A(){try{var w;return h&&(w=h.randomBytes)?w=w(s):(w=new Uint8Array(s),(a.crypto||a.msCrypto).getRandomValues(w)),b(w)}catch(N){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(x(r.random(),n),typeof t=="object"&&t.exports){t.exports=m;try{h=LC()}catch(w){}}else typeof define=="function"&&define.amd?define(function(){return m}):r["seed"+l]=m})(typeof self!="undefined"?self:e,[],Math)}),EA=Xt((e,t)=>{var a=$C(),n=DC(),r=PC(),s=_C(),i=OC(),o=zC(),l=WC();l.alea=a,l.xor128=n,l.xorwow=r,l.xorshift7=s,l.xor4096=i,l.tychei=o,t.exports=l}),MA=Xt(()=>{}),FA=Xt(()=>{}),BC=Xt(()=>{}),VC=Xt(()=>{}),UC=Xt(()=>{}),GC=Xt((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 ie.buffer!=He&&ht(ie.buffer),xt}function i(){return ie.buffer!=He&&ht(ie.buffer),ja}function o(){return ie.buffer!=He&&ht(ie.buffer),Lt}function l(){return ie.buffer!=He&&ht(ie.buffer),ua}function u(){return ie.buffer!=He&&ht(ie.buffer),Da}function d(){return ie.buffer!=He&&ht(ie.buffer),cn}function c(){return ie.buffer!=He&&ht(ie.buffer),Pa}var p=typeof r!="undefined"?r:{},h,m;p.ready=new Promise(function(_,j){h=_,m=j});var f;typeof process!="undefined"&&process.listeners&&(f={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var g=Object.assign({},p),y=[],x="./this.program",A=(_,j)=>{throw j},b=typeof window=="object",w=typeof importScripts=="function",S=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",C=p.ENVIRONMENT_IS_PTHREAD||!1,N="";function M(_){return p.locateFile?p.locateFile(_,N):N+_}var F,E,T,D;function O(_){_ instanceof ii||H("exiting due to exception: "+_)}if(S){var W=MA(),$=FA();w?N=$.dirname(N)+"/":N=__dirname+"/",F=(j,oe)=>(j=Pl(j)?new URL(j):$.normalize(j),W.readFileSync(j,oe?void 0:"utf8")),T=j=>{var oe=F(j,!0);return oe.buffer||(oe=new Uint8Array(oe)),oe},E=(j,oe,Fe)=>{j=Pl(j)?new URL(j):$.normalize(j),W.readFile(j,function(je,Be){je?Fe(je):oe(Be.buffer)})},process.argv.length>1&&(x=process.argv[1].replace(/\\/g,"/")),y=process.argv.slice(2),process.on("uncaughtException",function(j){if(!(j instanceof ii))throw j}),process.on("unhandledRejection",function(j){throw j}),A=(j,oe)=>{if(Tn())throw process.exitCode=j,oe;O(oe),process.exit(j)},p.inspect=function(){return"[Emscripten Module object]"};let _;try{_=BC()}catch(j){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),j}global.Worker=_.Worker}else(b||w)&&(w?N=self.location.href:typeof document!="undefined"&&document.currentScript&&(N=document.currentScript.src),typeof n!="undefined"&&n&&(N=n),N.indexOf("blob:")!==0?N=N.substr(0,N.replace(/[?#].*/,"").lastIndexOf("/")+1):N="",S||(F=_=>{var j=new XMLHttpRequest;return j.open("GET",_,!1),j.send(null),j.responseText},w&&(T=_=>{var j=new XMLHttpRequest;return j.open("GET",_,!1),j.responseType="arraybuffer",j.send(null),new Uint8Array(j.response)}),E=(_,j,oe)=>{var Fe=new XMLHttpRequest;Fe.open("GET",_,!0),Fe.responseType="arraybuffer",Fe.onload=()=>{if(Fe.status==200||Fe.status==0&&Fe.response){j(Fe.response);return}oe()},Fe.onerror=oe,Fe.send(null)}),D=_=>document.title=_);S&&typeof performance=="undefined"&&(global.performance=VC().performance);var U=console.log.bind(console),G=console.warn.bind(console);S&&(U=_=>W.writeSync(1,_+`
|
|
`),G=_=>W.writeSync(2,_+`
|
|
`));var q=p.print||U,H=p.printErr||G;Object.assign(p,g),g=null,p.arguments&&(y=p.arguments),p.thisProgram&&(x=p.thisProgram),p.quit&&(A=p.quit);var V=4,Z=Atomics.load,X=Atomics.store,re=Atomics.compareExchange,ee;p.wasmBinary&&(ee=p.wasmBinary);var ge=p.noExitRuntime||!0;typeof WebAssembly!="object"&&si("no native wasm support detected");var ie,be,Ce=!1,Ee;function Le(_,j){_||si(j)}var qe=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function gt(_,j,oe){j>>>=0;for(var Fe=j+oe,je=j;_[je]&&!(je>=Fe);)++je;if(je-j>16&&_.buffer&&qe)return qe.decode(_.buffer instanceof SharedArrayBuffer?_.slice(j,je):_.subarray(j,je));for(var Be="";j<je;){var ye=_[j++];if(!(ye&128)){Be+=String.fromCharCode(ye);continue}var Re=_[j++]&63;if((ye&224)==192){Be+=String.fromCharCode((ye&31)<<6|Re);continue}var Nt=_[j++]&63;if((ye&240)==224?ye=(ye&15)<<12|Re<<6|Nt:ye=(ye&7)<<18|Re<<12|Nt<<6|_[j++]&63,ye<65536)Be+=String.fromCharCode(ye);else{var mn=ye-65536;Be+=String.fromCharCode(55296|mn>>10,56320|mn&1023)}}return Be}function dt(_,j){return _>>>=0,_?gt(i(),_,j):""}function st(_,j,oe,Fe){if(oe>>>=0,!(Fe>0))return 0;for(var je=oe,Be=oe+Fe-1,ye=0;ye<_.length;++ye){var Re=_.charCodeAt(ye);if(Re>=55296&&Re<=57343){var Nt=_.charCodeAt(++ye);Re=65536+((Re&1023)<<10)|Nt&1023}if(Re<=127){if(oe>=Be)break;j[oe++>>>0]=Re}else if(Re<=2047){if(oe+1>=Be)break;j[oe++>>>0]=192|Re>>6,j[oe++>>>0]=128|Re&63}else if(Re<=65535){if(oe+2>=Be)break;j[oe++>>>0]=224|Re>>12,j[oe++>>>0]=128|Re>>6&63,j[oe++>>>0]=128|Re&63}else{if(oe+3>=Be)break;j[oe++>>>0]=240|Re>>18,j[oe++>>>0]=128|Re>>12&63,j[oe++>>>0]=128|Re>>6&63,j[oe++>>>0]=128|Re&63}}return j[oe>>>0]=0,oe-je}function it(_,j,oe){return st(_,i(),j,oe)}var He,xt,ja,Lt,pn,ua,Da,cn,Pa;C&&(He=p.buffer);function ht(_){He=_,p.HEAP8=xt=new Int8Array(_),p.HEAP16=Lt=new Int16Array(_),p.HEAP32=ua=new Int32Array(_),p.HEAPU8=ja=new Uint8Array(_),p.HEAPU16=pn=new Uint16Array(_),p.HEAPU32=Da=new Uint32Array(_),p.HEAPF32=cn=new Float32Array(_),p.HEAPF64=Pa=new Float64Array(_)}var _a=p.INITIAL_MEMORY||16777216;if(C)ie=p.wasmMemory,He=p.buffer;else if(p.wasmMemory)ie=p.wasmMemory;else if(ie=new WebAssembly.Memory({initial:_a/65536,maximum:65536,shared:!0}),!(ie.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&&H("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");ie&&(He=ie.buffer),_a=He.byteLength,ht(He);var qa,yr=[],$l=[],Kn=[],bd=!1;function Tn(){return ge}function Br(){if(p.preRun)for(typeof p.preRun=="function"&&(p.preRun=[p.preRun]);p.preRun.length;)ym(p.preRun.shift());wd(yr)}function Yt(){bd=!0,!C&&wd($l)}function Ic(){if(!C){if(p.postRun)for(typeof p.postRun=="function"&&(p.postRun=[p.postRun]);p.postRun.length;)Gx(p.postRun.shift());wd(Kn)}}function ym(_){yr.unshift(_)}function xm(_){$l.unshift(_)}function Gx(_){Kn.unshift(_)}var Vr=0,Dl=null,xr=null;function Am(_){Vr++,p.monitorRunDependencies&&p.monitorRunDependencies(Vr)}function Sc(_){if(Vr--,p.monitorRunDependencies&&p.monitorRunDependencies(Vr),Vr==0&&(Dl!==null&&(clearInterval(Dl),Dl=null),xr)){var j=xr;xr=null,j()}}function si(_){p.onAbort&&p.onAbort(_),_="Aborted("+_+")",H(_),Ce=!0,Ee=1,_+=". Build with -sASSERTIONS for more info.";var j=new WebAssembly.RuntimeError(_);throw m(j),j}var bm="data:application/octet-stream;base64,";function Tc(_){return _.startsWith(bm)}function Pl(_){return _.startsWith("file://")}var ma;ma="tfjs-backend-wasm-threaded-simd.wasm",Tc(ma)||(ma=M(ma));function Cc(_){try{if(_==ma&&ee)return new Uint8Array(ee);if(T)return T(_);throw"both async and sync fetching of the wasm failed"}catch(j){si(j)}}function vm(){if(!ee&&(b||w)){if(typeof fetch=="function"&&!Pl(ma))return fetch(ma,{credentials:"same-origin"}).then(function(_){if(!_.ok)throw"failed to load wasm binary file at '"+ma+"'";return _.arrayBuffer()}).catch(function(){return Cc(ma)});if(E)return new Promise(function(_,j){E(ma,function(oe){_(new Uint8Array(oe))},j)})}return Promise.resolve().then(function(){return Cc(ma)})}function wm(){var _={env:Wc,wasi_snapshot_preview1:Wc};function j(ye,Re){var Nt=ye.exports;if(p.asm=Nt,Mm(p.asm._emscripten_tls_init),qa=p.asm.__indirect_function_table,xm(p.asm.__wasm_call_ctors),be=Re,!C){var mn=We.unusedWorkers.length;We.unusedWorkers.forEach(function(br){We.loadWasmModuleToWorker(br,function(){--mn||Sc("wasm-instantiate")})})}}C||Am("wasm-instantiate");function oe(ye){j(ye.instance,ye.module)}function Fe(ye){return vm().then(function(Re){return WebAssembly.instantiate(Re,_)}).then(function(Re){return Re}).then(ye,function(Re){H("failed to asynchronously prepare wasm: "+Re),si(Re)})}function je(){return!ee&&typeof WebAssembly.instantiateStreaming=="function"&&!Tc(ma)&&!Pl(ma)&&!S&&typeof fetch=="function"?fetch(ma,{credentials:"same-origin"}).then(function(ye){var Re=WebAssembly.instantiateStreaming(ye,_);return Re.then(oe,function(Nt){return H("wasm streaming compile failed: "+Nt),H("falling back to ArrayBuffer instantiation"),Fe(oe)})}):Fe(oe)}if(p.instantiateWasm)try{var Be=p.instantiateWasm(_,j);return Be}catch(ye){H("Module.instantiateWasm callback failed with error: "+ye),m(ye)}return je().catch(m),{}}var Hx,jx,Nc={};function ii(_){this.name="ExitStatus",this.message="Program terminated with exit("+_+")",this.status=_}function km(_){var j=We.pthreads[_];delete We.pthreads[_],j.terminate(),X2(_),We.runningWorkers.splice(We.runningWorkers.indexOf(j),1),j.pthread_ptr=0}function Im(_){var j=We.pthreads[_];j.postMessage({cmd:"cancel"})}function vd(_){var j=We.pthreads[_];Le(j),We.returnWorkerToPool(j)}function Sm(_){var j=We.getNewWorker();if(!j)return 6;We.runningWorkers.push(j),We.pthreads[_.pthread_ptr]=j,j.pthread_ptr=_.pthread_ptr;var oe={cmd:"run",start_routine:_.startRoutine,arg:_.arg,pthread_ptr:_.pthread_ptr};return j.runPthread=()=>{S&&j.ref(),j.postMessage(oe,_.transferList),delete j.runPthread},j.loaded&&j.runPthread(),0}var Rc={varargs:void 0,get:function(){Rc.varargs+=4;var _=l()[Rc.varargs-4>>>2];return _},getStr:function(_){var j=dt(_);return j}};function Ec(_){if(C)return Ur(1,1,_);Ee=_,Tn()||(We.terminateAllThreads(),p.onExit&&p.onExit(_),Ce=!0),A(_,new ii(_))}function Tm(_,j){if(Ee=_,!j&&C)throw Fc(_),"unwind";Ec(_)}var Mc=Tm;function Cm(_){if(_ instanceof ii||_=="unwind")return Ee;A(1,_)}var We={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init:function(){C?We.initWorker():We.initMainThread()},initMainThread:function(){for(var _=8;_--;)We.allocateUnusedWorker()},initWorker:function(){ge=!1},setExitStatus:function(_){Ee=_},terminateAllThreads:function(){for(var _ of Object.values(We.pthreads))We.returnWorkerToPool(_);for(var _ of We.unusedWorkers)_.terminate();We.unusedWorkers=[]},returnWorkerToPool:function(_){var j=_.pthread_ptr;delete We.pthreads[j],We.unusedWorkers.push(_),We.runningWorkers.splice(We.runningWorkers.indexOf(_),1),_.pthread_ptr=0,S&&_.unref(),X2(j)},receiveObjectTransfer:function(_){},threadInitTLS:function(){We.tlsInitFunctions.forEach(_=>_())},loadWasmModuleToWorker:function(_,j){_.onmessage=Be=>{var ye=Be.data,Re=ye.cmd;if(_.pthread_ptr&&(We.currentProxiedOperationCallerThread=_.pthread_ptr),ye.targetThread&&ye.targetThread!=jc()){var Nt=We.pthreads[ye.targetThread];Nt?Nt.postMessage(ye,ye.transferList):H('Internal error! Worker sent a message "'+Re+'" to target pthread '+ye.targetThread+", but that thread no longer exists!"),We.currentProxiedOperationCallerThread=void 0;return}Re==="processProxyingQueue"?kd(ye.queue):Re==="spawnThread"?Sm(ye):Re==="cleanupThread"?vd(ye.thread):Re==="killThread"?km(ye.thread):Re==="cancelThread"?Im(ye.thread):Re==="loaded"?(_.loaded=!0,S&&_.unref(),j&&j(_),_.runPthread&&_.runPthread()):Re==="print"?q("Thread "+ye.threadId+": "+ye.text):Re==="printErr"?H("Thread "+ye.threadId+": "+ye.text):Re==="alert"?alert("Thread "+ye.threadId+": "+ye.text):ye.target==="setimmediate"?_.postMessage(ye):Re==="callHandler"?p[ye.handler](...ye.args):Re&&H("worker sent an unknown command "+Re),We.currentProxiedOperationCallerThread=void 0},_.onerror=Be=>{var ye="worker sent an error!";throw H(ye+" "+Be.filename+":"+Be.lineno+": "+Be.message),Be},S&&(_.on("message",function(Be){_.onmessage({data:Be})}),_.on("error",function(Be){_.onerror(Be)}),_.on("detachedExit",function(){}));var oe=[],Fe=["onExit","onAbort","print","printErr"];for(var je of Fe)p.hasOwnProperty(je)&&oe.push(je);_.postMessage({cmd:"load",handlers:oe,urlOrBlob:p.mainScriptUrlOrBlob||n,wasmMemory:ie,wasmModule:be})},allocateUnusedWorker:function(){var _,j=M("tfjs-backend-wasm-threaded-simd.worker.js");_=new Worker(j),We.unusedWorkers.push(_)},getNewWorker:function(){return We.unusedWorkers.length==0&&(We.allocateUnusedWorker(),We.loadWasmModuleToWorker(We.unusedWorkers[0])),We.unusedWorkers.pop()}};p.PThread=We;function wd(_){for(;_.length>0;)_.shift()(p)}function Nm(){var _=jc(),j=l()[_+52>>>2],oe=l()[_+56>>>2],Fe=j-oe;Jx(j,Fe),qc(j)}p.establishStackSpace=Nm;function Fc(_){if(C)return Ur(2,0,_);try{Mc(_)}catch(j){Cm(j)}}var _l=[];function Rm(_){var j=_l[_];return j||(_>=_l.length&&(_l.length=_+1),_l[_]=j=qa.get(_)),j}function Em(_,j){var oe=Rm(_)(j);Tn()?We.setExitStatus(oe):Zx(oe)}p.invokeEntryPoint=Em;function Mm(_){We.tlsInitFunctions.push(_)}function Fm(_){Xx(_,!w,1,!b),We.threadInitTLS()}function $m(_){C?postMessage({cmd:"cleanupThread",thread:_}):vd(_)}function $c(_,j,oe,Fe){return C?Ur(3,1,_,j,oe,Fe):Dc(_,j,oe,Fe)}function Dc(_,j,oe,Fe){if(typeof SharedArrayBuffer=="undefined")return H("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var je=[],Be=0;if(C&&(je.length===0||Be))return $c(_,j,oe,Fe);if(Be)return Be;var ye={startRoutine:oe,pthread_ptr:_,arg:Fe,transferList:je};return C?(ye.cmd="spawnThread",postMessage(ye,je),0):Sm(ye)}function Dm(){return 65536}var Pm=!0;function _m(){return Pm}function kd(_){Atomics.store(l(),_>>2,1),jc()&&Yx(_),Atomics.compareExchange(l(),_>>2,1,0)}p.executeNotifiedProxyingQueue=kd;function Om(_,j,oe,Fe){if(_==j)setTimeout(()=>kd(Fe));else if(C)postMessage({targetThread:_,cmd:"processProxyingQueue",queue:Fe});else{var je=We.pthreads[_];if(!je)return;je.postMessage({cmd:"processProxyingQueue",queue:Fe})}return 1}function zm(_,j,oe){return-1}function Lm(){si("")}function oi(_){oi.shown||(oi.shown={}),oi.shown[_]||(oi.shown[_]=1,S&&(_="warning: "+_),H(_))}function Wm(){S||w||oi("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function Bm(){return Date.now()}function Pc(){return 4294901760}function Vm(){return Pc()}var Id;S?Id=()=>{var _=process.hrtime();return _[0]*1e3+_[1]/1e6}:Id=()=>performance.timeOrigin+performance.now();function Um(_,j,oe){i().copyWithin(_>>>0,j>>>0,j+oe>>>0)}function Gm(){return S?UC().cpus().length:navigator.hardwareConcurrency}function Hm(_){var j=K2(),oe=_();return qc(j),oe}function Ur(_,j){var oe=arguments.length-2,Fe=arguments;return Hm(()=>{for(var je=oe,Be=Xc(je*8),ye=Be>>3,Re=0;Re<oe;Re++){var Nt=Fe[2+Re];c()[ye+Re>>>0]=Nt}return Kx(_,je,Be,j)})}var Sd=[];function jm(_,j,oe){Sd.length=j;for(var Fe=oe>>3,je=0;je<j;je++)Sd[je]=c()[Fe+je>>>0];var Be=_<0,ye=Be?Nc[-_-1]:tf[_];return ye.apply(null,Sd)}function qm(_){try{return ie.grow(_-He.byteLength+65535>>>16),ht(ie.buffer),1}catch(j){}}function Xm(_){var j=i().length;if(_=_>>>0,_<=j)return!1;var oe=Pc();if(_>oe)return!1;let Fe=(Nt,mn)=>Nt+(mn-Nt%mn)%mn;for(var je=1;je<=4;je*=2){var Be=j*(1+.2/je);Be=Math.min(Be,_+100663296);var ye=Math.min(oe,Fe(Math.max(_,Be),65536)),Re=qm(ye);if(Re)return!0}return!1}function Km(){throw"unwind"}function _c(_){return C?Ur(4,1,_):52}function Oc(_,j,oe,Fe,je){return C?Ur(5,1,_,j,oe,Fe,je):70}var Ym=[null,[],[]];function Zm(_,j){var oe=Ym[_];j===0||j===10?((_===1?q:H)(gt(oe,0)),oe.length=0):oe.push(j)}function zc(_,j,oe,Fe){if(C)return Ur(6,1,_,j,oe,Fe);for(var je=0,Be=0;Be<oe;Be++){var ye=u()[j>>>2],Re=u()[j+4>>>2];j+=8;for(var Nt=0;Nt<Re;Nt++)Zm(_,i()[ye+Nt>>>0]);je+=Re}return u()[Fe>>>2]=je,0}function Lc(_){var j=p["_"+_];return j}function Jm(_,j){s().set(_,j>>>0)}function Qm(_,j,oe,Fe,je){var Be={string:fn=>{var Wl=0;if(fn!=null&&fn!==0){var t5=(fn.length<<2)+1;Wl=Xc(t5),it(fn,Wl,t5)}return Wl},array:fn=>{var Wl=Xc(fn.length);return Jm(fn,Wl),Wl}};function ye(fn){return j==="string"?dt(fn):j==="boolean"?!!fn:fn}var Re=Lc(_),Nt=[],mn=0;if(Fe)for(var br=0;br<Fe.length;br++){var e5=Be[oe[br]];e5?(mn===0&&(mn=K2()),Nt[br]=e5(Fe[br])):Nt[br]=Fe[br]}var Y2=Re.apply(null,Nt);function yC(fn){return mn!==0&&qc(mn),ye(fn)}return Y2=yC(Y2),Y2}function ef(_,j,oe,Fe){oe=oe||[];var je=oe.every(ye=>ye==="number"||ye==="boolean"),Be=j!=="string";return Be&&je&&!Fe?Lc(_):function(){return Qm(_,j,oe,arguments,Fe)}}We.init();var tf=[null,Ec,Fc,$c,_c,Oc,zc],Wc={__emscripten_init_main_thread_js:Fm,__emscripten_thread_cleanup:$m,__pthread_create_js:Dc,_emscripten_default_pthread_stack_size:Dm,_emscripten_get_now_is_monotonic:_m,_emscripten_notify_task_queue:Om,_emscripten_set_offscreencanvas_size:zm,abort:Lm,emscripten_check_blocking_allowed:Wm,emscripten_date_now:Bm,emscripten_get_heap_max:Vm,emscripten_get_now:Id,emscripten_memcpy_big:Um,emscripten_num_logical_cores:Gm,emscripten_receive_on_main_thread_js:jm,emscripten_resize_heap:Xm,emscripten_unwind_to_js_event_loop:Km,exit:Mc,fd_close:_c,fd_seek:Oc,fd_write:zc,memory:ie||p.wasmMemory},qx=wm(),af=p.___wasm_call_ctors=function(){return(af=p.___wasm_call_ctors=p.asm.__wasm_call_ctors).apply(null,arguments)},nf=p._init=function(){return(nf=p._init=p.asm.init).apply(null,arguments)},rf=p._init_with_threads_count=function(){return(rf=p._init_with_threads_count=p.asm.init_with_threads_count).apply(null,arguments)},sf=p._get_threads_count=function(){return(sf=p._get_threads_count=p.asm.get_threads_count).apply(null,arguments)},of=p._register_tensor=function(){return(of=p._register_tensor=p.asm.register_tensor).apply(null,arguments)},lf=p._dispose_data=function(){return(lf=p._dispose_data=p.asm.dispose_data).apply(null,arguments)},uf=p._dispose=function(){return(uf=p._dispose=p.asm.dispose).apply(null,arguments)},df=p._Abs=function(){return(df=p._Abs=p.asm.Abs).apply(null,arguments)},pf=p._Acos=function(){return(pf=p._Acos=p.asm.Acos).apply(null,arguments)},cf=p._Acosh=function(){return(cf=p._Acosh=p.asm.Acosh).apply(null,arguments)},hf=p._Add=function(){return(hf=p._Add=p.asm.Add).apply(null,arguments)},mf=p._AddN=function(){return(mf=p._AddN=p.asm.AddN).apply(null,arguments)},ff=p._All=function(){return(ff=p._All=p.asm.All).apply(null,arguments)},gf=p._Any=function(){return(gf=p._Any=p.asm.Any).apply(null,arguments)},yf=p._ArgMax=function(){return(yf=p._ArgMax=p.asm.ArgMax).apply(null,arguments)},xf=p._ArgMin=function(){return(xf=p._ArgMin=p.asm.ArgMin).apply(null,arguments)},Af=p._Asin=function(){return(Af=p._Asin=p.asm.Asin).apply(null,arguments)},bf=p._Asinh=function(){return(bf=p._Asinh=p.asm.Asinh).apply(null,arguments)},vf=p._Atan=function(){return(vf=p._Atan=p.asm.Atan).apply(null,arguments)},wf=p._Atan2=function(){return(wf=p._Atan2=p.asm.Atan2).apply(null,arguments)},kf=p._Atanh=function(){return(kf=p._Atanh=p.asm.Atanh).apply(null,arguments)},If=p._AvgPool=function(){return(If=p._AvgPool=p.asm.AvgPool).apply(null,arguments)},Sf=p._AvgPool3D=function(){return(Sf=p._AvgPool3D=p.asm.AvgPool3D).apply(null,arguments)},Tf=p._AvgPool3DGrad=function(){return(Tf=p._AvgPool3DGrad=p.asm.AvgPool3DGrad).apply(null,arguments)},Cf=p._AvgPoolGrad=function(){return(Cf=p._AvgPoolGrad=p.asm.AvgPoolGrad).apply(null,arguments)},Nf=p._BatchMatMul=function(){return(Nf=p._BatchMatMul=p.asm.BatchMatMul).apply(null,arguments)},Rf=p._Bincount=function(){return(Rf=p._Bincount=p.asm.Bincount).apply(null,arguments)},Ef=p._BitwiseAnd=function(){return(Ef=p._BitwiseAnd=p.asm.BitwiseAnd).apply(null,arguments)},Mf=p._Ceil=function(){return(Mf=p._Ceil=p.asm.Ceil).apply(null,arguments)},Ff=p._ClipByValue=function(){return(Ff=p._ClipByValue=p.asm.ClipByValue).apply(null,arguments)},$f=p._Conv2D=function(){return($f=p._Conv2D=p.asm.Conv2D).apply(null,arguments)},Df=p._Conv2DBackpropInput=function(){return(Df=p._Conv2DBackpropInput=p.asm.Conv2DBackpropInput).apply(null,arguments)},Pf=p._Conv3D=function(){return(Pf=p._Conv3D=p.asm.Conv3D).apply(null,arguments)},_f=p._Conv3DBackpropFilterV2=function(){return(_f=p._Conv3DBackpropFilterV2=p.asm.Conv3DBackpropFilterV2).apply(null,arguments)},Of=p._Conv3DBackpropInputV2=function(){return(Of=p._Conv3DBackpropInputV2=p.asm.Conv3DBackpropInputV2).apply(null,arguments)},zf=p._Cos=function(){return(zf=p._Cos=p.asm.Cos).apply(null,arguments)},Lf=p._Cosh=function(){return(Lf=p._Cosh=p.asm.Cosh).apply(null,arguments)},Wf=p._CropAndResize=function(){return(Wf=p._CropAndResize=p.asm.CropAndResize).apply(null,arguments)},Bf=p._Cumprod=function(){return(Bf=p._Cumprod=p.asm.Cumprod).apply(null,arguments)},Vf=p._Cumsum=function(){return(Vf=p._Cumsum=p.asm.Cumsum).apply(null,arguments)},Uf=p._DenseBincount=function(){return(Uf=p._DenseBincount=p.asm.DenseBincount).apply(null,arguments)},Gf=p._DepthToSpace=function(){return(Gf=p._DepthToSpace=p.asm.DepthToSpace).apply(null,arguments)},Hf=p._DepthwiseConv2dNative=function(){return(Hf=p._DepthwiseConv2dNative=p.asm.DepthwiseConv2dNative).apply(null,arguments)},jf=p._Diag=function(){return(jf=p._Diag=p.asm.Diag).apply(null,arguments)},qf=p._Dilation2D=function(){return(qf=p._Dilation2D=p.asm.Dilation2D).apply(null,arguments)},Xf=p._Dilation2DBackpropFilter=function(){return(Xf=p._Dilation2DBackpropFilter=p.asm.Dilation2DBackpropFilter).apply(null,arguments)},Kf=p._Dilation2DBackpropInput=function(){return(Kf=p._Dilation2DBackpropInput=p.asm.Dilation2DBackpropInput).apply(null,arguments)},Yf=p._Elu=function(){return(Yf=p._Elu=p.asm.Elu).apply(null,arguments)},Zf=p._EluGrad=function(){return(Zf=p._EluGrad=p.asm.EluGrad).apply(null,arguments)},Jf=p._Equal=function(){return(Jf=p._Equal=p.asm.Equal).apply(null,arguments)},Qf=p._Erf=function(){return(Qf=p._Erf=p.asm.Erf).apply(null,arguments)},e2=p._Exp=function(){return(e2=p._Exp=p.asm.Exp).apply(null,arguments)},t2=p._Expm1=function(){return(t2=p._Expm1=p.asm.Expm1).apply(null,arguments)},a2=p._FlipLeftRight=function(){return(a2=p._FlipLeftRight=p.asm.FlipLeftRight).apply(null,arguments)},n2=p._Floor=function(){return(n2=p._Floor=p.asm.Floor).apply(null,arguments)},r2=p._FloorDiv=function(){return(r2=p._FloorDiv=p.asm.FloorDiv).apply(null,arguments)},s2=p._FusedBatchNorm=function(){return(s2=p._FusedBatchNorm=p.asm.FusedBatchNorm).apply(null,arguments)},i2=p._FusedConv2D=function(){return(i2=p._FusedConv2D=p.asm.FusedConv2D).apply(null,arguments)},o2=p._FusedDepthwiseConv2D=function(){return(o2=p._FusedDepthwiseConv2D=p.asm.FusedDepthwiseConv2D).apply(null,arguments)},l2=p._Gather=function(){return(l2=p._Gather=p.asm.Gather).apply(null,arguments)},u2=p._GatherNd=function(){return(u2=p._GatherNd=p.asm.GatherNd).apply(null,arguments)},d2=p._Greater=function(){return(d2=p._Greater=p.asm.Greater).apply(null,arguments)},p2=p._GreaterEqual=function(){return(p2=p._GreaterEqual=p.asm.GreaterEqual).apply(null,arguments)},c2=p._IsFinite=function(){return(c2=p._IsFinite=p.asm.IsFinite).apply(null,arguments)},h2=p._IsInf=function(){return(h2=p._IsInf=p.asm.IsInf).apply(null,arguments)},m2=p._IsNan=function(){return(m2=p._IsNan=p.asm.IsNan).apply(null,arguments)},f2=p._LRN=function(){return(f2=p._LRN=p.asm.LRN).apply(null,arguments)},g2=p._LRNGrad=function(){return(g2=p._LRNGrad=p.asm.LRNGrad).apply(null,arguments)},y2=p._LeakyRelu=function(){return(y2=p._LeakyRelu=p.asm.LeakyRelu).apply(null,arguments)},x2=p._Less=function(){return(x2=p._Less=p.asm.Less).apply(null,arguments)},A2=p._LessEqual=function(){return(A2=p._LessEqual=p.asm.LessEqual).apply(null,arguments)},b2=p._LinSpace=function(){return(b2=p._LinSpace=p.asm.LinSpace).apply(null,arguments)},v2=p._Log=function(){return(v2=p._Log=p.asm.Log).apply(null,arguments)},w2=p._Log1p=function(){return(w2=p._Log1p=p.asm.Log1p).apply(null,arguments)},k2=p._LogicalAnd=function(){return(k2=p._LogicalAnd=p.asm.LogicalAnd).apply(null,arguments)},I2=p._LogicalNot=function(){return(I2=p._LogicalNot=p.asm.LogicalNot).apply(null,arguments)},S2=p._LogicalOr=function(){return(S2=p._LogicalOr=p.asm.LogicalOr).apply(null,arguments)},T2=p._LogicalXor=function(){return(T2=p._LogicalXor=p.asm.LogicalXor).apply(null,arguments)},C2=p._Max=function(){return(C2=p._Max=p.asm.Max).apply(null,arguments)},N2=p._MaxPool=function(){return(N2=p._MaxPool=p.asm.MaxPool).apply(null,arguments)},R2=p._MaxPool3D=function(){return(R2=p._MaxPool3D=p.asm.MaxPool3D).apply(null,arguments)},E2=p._MaxPool3DGrad=function(){return(E2=p._MaxPool3DGrad=p.asm.MaxPool3DGrad).apply(null,arguments)},M2=p._MaxPoolGrad=function(){return(M2=p._MaxPoolGrad=p.asm.MaxPoolGrad).apply(null,arguments)},F2=p._MaxPoolWithArgmax=function(){return(F2=p._MaxPoolWithArgmax=p.asm.MaxPoolWithArgmax).apply(null,arguments)},$2=p._Maximum=function(){return($2=p._Maximum=p.asm.Maximum).apply(null,arguments)},D2=p._Mean=function(){return(D2=p._Mean=p.asm.Mean).apply(null,arguments)},P2=p._Min=function(){return(P2=p._Min=p.asm.Min).apply(null,arguments)},_2=p._Minimum=function(){return(_2=p._Minimum=p.asm.Minimum).apply(null,arguments)},O2=p._MirrorPad=function(){return(O2=p._MirrorPad=p.asm.MirrorPad).apply(null,arguments)},z2=p._Mod=function(){return(z2=p._Mod=p.asm.Mod).apply(null,arguments)},L2=p._Multinomial=function(){return(L2=p._Multinomial=p.asm.Multinomial).apply(null,arguments)},W2=p._Multiply=function(){return(W2=p._Multiply=p.asm.Multiply).apply(null,arguments)},B2=p._Neg=function(){return(B2=p._Neg=p.asm.Neg).apply(null,arguments)},V2=p._NonMaxSuppressionV3=function(){return(V2=p._NonMaxSuppressionV3=p.asm.NonMaxSuppressionV3).apply(null,arguments)},U2=p._NonMaxSuppressionV4=function(){return(U2=p._NonMaxSuppressionV4=p.asm.NonMaxSuppressionV4).apply(null,arguments)},Bc=p._NonMaxSuppressionV5=function(){return(Bc=p._NonMaxSuppressionV5=p.asm.NonMaxSuppressionV5).apply(null,arguments)},Vc=p._NotEqual=function(){return(Vc=p._NotEqual=p.asm.NotEqual).apply(null,arguments)},Td=p._OneHot=function(){return(Td=p._OneHot=p.asm.OneHot).apply(null,arguments)},G2=p._PadV2=function(){return(G2=p._PadV2=p.asm.PadV2).apply(null,arguments)},H2=p._Pow=function(){return(H2=p._Pow=p.asm.Pow).apply(null,arguments)},Ol=p._Prelu=function(){return(Ol=p._Prelu=p.asm.Prelu).apply(null,arguments)},Uc=p._Prod=function(){return(Uc=p._Prod=p.asm.Prod).apply(null,arguments)},zl=p._RealDiv=function(){return(zl=p._RealDiv=p.asm.RealDiv).apply(null,arguments)},Ll=p._Reciprocal=function(){return(Ll=p._Reciprocal=p.asm.Reciprocal).apply(null,arguments)},j2=p._Relu=function(){return(j2=p._Relu=p.asm.Relu).apply(null,arguments)},Y=p._Relu6=function(){return(Y=p._Relu6=p.asm.Relu6).apply(null,arguments)},se=p._ResizeBilinear=function(){return(se=p._ResizeBilinear=p.asm.ResizeBilinear).apply(null,arguments)},Me=p._ResizeBilinearGrad=function(){return(Me=p._ResizeBilinearGrad=p.asm.ResizeBilinearGrad).apply(null,arguments)},et=p._ResizeNearestNeighbor=function(){return(et=p._ResizeNearestNeighbor=p.asm.ResizeNearestNeighbor).apply(null,arguments)},kt=p._ResizeNearestNeighborGrad=function(){return(kt=p._ResizeNearestNeighborGrad=p.asm.ResizeNearestNeighborGrad).apply(null,arguments)},It=p._Reverse=function(){return(It=p._Reverse=p.asm.Reverse).apply(null,arguments)},Je=p._RotateWithOffset=function(){return(Je=p._RotateWithOffset=p.asm.RotateWithOffset).apply(null,arguments)},Ze=p._Round=function(){return(Ze=p._Round=p.asm.Round).apply(null,arguments)},Wt=p._Rsqrt=function(){return(Wt=p._Rsqrt=p.asm.Rsqrt).apply(null,arguments)},hn=p._ScatterNd=function(){return(hn=p._ScatterNd=p.asm.ScatterNd).apply(null,arguments)},Ar=p._SearchSorted=function(){return(Ar=p._SearchSorted=p.asm.SearchSorted).apply(null,arguments)},Gc=p._SelectV2=function(){return(Gc=p._SelectV2=p.asm.SelectV2).apply(null,arguments)},Cd=p._Selu=function(){return(Cd=p._Selu=p.asm.Selu).apply(null,arguments)},q2=p._Sigmoid=function(){return(q2=p._Sigmoid=p.asm.Sigmoid).apply(null,arguments)},Oa=p._Sign=function(){return(Oa=p._Sign=p.asm.Sign).apply(null,arguments)},Gr=p._Sin=function(){return(Gr=p._Sin=p.asm.Sin).apply(null,arguments)},Hc=p._Sinh=function(){return(Hc=p._Sinh=p.asm.Sinh).apply(null,arguments)},LT=p._Softmax=function(){return(LT=p._Softmax=p.asm.Softmax).apply(null,arguments)},WT=p._Softplus=function(){return(WT=p._Softplus=p.asm.Softplus).apply(null,arguments)},BT=p._SparseFillEmptyRows=function(){return(BT=p._SparseFillEmptyRows=p.asm.SparseFillEmptyRows).apply(null,arguments)},VT=p._SparseReshape=function(){return(VT=p._SparseReshape=p.asm.SparseReshape).apply(null,arguments)},UT=p._SparseSegmentReduction=function(){return(UT=p._SparseSegmentReduction=p.asm.SparseSegmentReduction).apply(null,arguments)},GT=p._SparseToDense=function(){return(GT=p._SparseToDense=p.asm.SparseToDense).apply(null,arguments)},HT=p._Sqrt=function(){return(HT=p._Sqrt=p.asm.Sqrt).apply(null,arguments)},jT=p._Square=function(){return(jT=p._Square=p.asm.Square).apply(null,arguments)},qT=p._SquaredDifference=function(){return(qT=p._SquaredDifference=p.asm.SquaredDifference).apply(null,arguments)},XT=p._Step=function(){return(XT=p._Step=p.asm.Step).apply(null,arguments)},KT=p._StridedSlice=function(){return(KT=p._StridedSlice=p.asm.StridedSlice).apply(null,arguments)},YT=p._Sub=function(){return(YT=p._Sub=p.asm.Sub).apply(null,arguments)},ZT=p._Sum=function(){return(ZT=p._Sum=p.asm.Sum).apply(null,arguments)},JT=p._Tan=function(){return(JT=p._Tan=p.asm.Tan).apply(null,arguments)},QT=p._Tanh=function(){return(QT=p._Tanh=p.asm.Tanh).apply(null,arguments)},eC=p._TensorScatterUpdate=function(){return(eC=p._TensorScatterUpdate=p.asm.TensorScatterUpdate).apply(null,arguments)},tC=p._Tile=function(){return(tC=p._Tile=p.asm.Tile).apply(null,arguments)},aC=p._TopK=function(){return(aC=p._TopK=p.asm.TopK).apply(null,arguments)},nC=p._Transform=function(){return(nC=p._Transform=p.asm.Transform).apply(null,arguments)},rC=p._Transpose=function(){return(rC=p._Transpose=p.asm.Transpose).apply(null,arguments)},sC=p.__FusedMatMul=function(){return(sC=p.__FusedMatMul=p.asm._FusedMatMul).apply(null,arguments)},iC=p._malloc=function(){return(iC=p._malloc=p.asm.malloc).apply(null,arguments)},oC=p._free=function(){return(oC=p._free=p.asm.free).apply(null,arguments)},lC=p.__emscripten_tls_init=function(){return(lC=p.__emscripten_tls_init=p.asm._emscripten_tls_init).apply(null,arguments)},jc=p._pthread_self=function(){return(jc=p._pthread_self=p.asm.pthread_self).apply(null,arguments)},uC=p.___errno_location=function(){return(uC=p.___errno_location=p.asm.__errno_location).apply(null,arguments)},Xx=p.__emscripten_thread_init=function(){return(Xx=p.__emscripten_thread_init=p.asm._emscripten_thread_init).apply(null,arguments)},dC=p.__emscripten_thread_crashed=function(){return(dC=p.__emscripten_thread_crashed=p.asm._emscripten_thread_crashed).apply(null,arguments)},pC=p._emscripten_main_thread_process_queued_calls=function(){return(pC=p._emscripten_main_thread_process_queued_calls=p.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},cC=p._emscripten_main_browser_thread_id=function(){return(cC=p._emscripten_main_browser_thread_id=p.asm.emscripten_main_browser_thread_id).apply(null,arguments)},Kx=p._emscripten_run_in_main_runtime_thread_js=function(){return(Kx=p._emscripten_run_in_main_runtime_thread_js=p.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)},hC=p._emscripten_dispatch_to_thread_=function(){return(hC=p._emscripten_dispatch_to_thread_=p.asm.emscripten_dispatch_to_thread_).apply(null,arguments)},Yx=p.__emscripten_proxy_execute_task_queue=function(){return(Yx=p.__emscripten_proxy_execute_task_queue=p.asm._emscripten_proxy_execute_task_queue).apply(null,arguments)},X2=p.__emscripten_thread_free_data=function(){return(X2=p.__emscripten_thread_free_data=p.asm._emscripten_thread_free_data).apply(null,arguments)},Zx=p.__emscripten_thread_exit=function(){return(Zx=p.__emscripten_thread_exit=p.asm._emscripten_thread_exit).apply(null,arguments)},Jx=p._emscripten_stack_set_limits=function(){return(Jx=p._emscripten_stack_set_limits=p.asm.emscripten_stack_set_limits).apply(null,arguments)},K2=p.stackSave=function(){return(K2=p.stackSave=p.asm.stackSave).apply(null,arguments)},qc=p.stackRestore=function(){return(qc=p.stackRestore=p.asm.stackRestore).apply(null,arguments)},Xc=p.stackAlloc=function(){return(Xc=p.stackAlloc=p.asm.stackAlloc).apply(null,arguments)},mC=p.dynCall_iijjiiii=function(){return(mC=p.dynCall_iijjiiii=p.asm.dynCall_iijjiiii).apply(null,arguments)},fC=p.dynCall_jiji=function(){return(fC=p.dynCall_jiji=p.asm.dynCall_jiji).apply(null,arguments)};p.keepRuntimeAlive=Tn,p.wasmMemory=ie,p.cwrap=ef,p.ExitStatus=ii,p.PThread=We;var Kc;xr=function _(){Kc||Qx(),Kc||(xr=_)};function Qx(_){if(_=_||y,Vr>0)return;if(C){h(p),Yt(),startWorker(p);return}if(Br(),Vr>0)return;function j(){Kc||(Kc=!0,p.calledRun=!0,!Ce&&(Yt(),h(p),p.onRuntimeInitialized&&p.onRuntimeInitialized(),Ic()))}p.setStatus?(p.setStatus("Running..."),setTimeout(function(){setTimeout(function(){p.setStatus("")},1),j()},1)):j()}if(p.preInit)for(typeof p.preInit=="function"&&(p.preInit=[p.preInit]);p.preInit.length>0;)p.preInit.pop()();Qx();var Yc;f&&(Yc={uncaughtException:process.listeners("uncaughtException").filter(function(_){return!f.uncaughtException.indexOf(_)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(_){return!f.unhandledRejection.indexOf(_)>-1})});var Zc;if(typeof WasmBackendModule!="undefined")Zc=WasmBackendModule;else if(typeof r!="undefined")Zc=r;else throw new Error("Could not find wasm module in post.js");if(Yc){var gC=Zc._dispose;Zc._dispose=function(){gC(),Yc.uncaughtException.forEach(function(_){process.removeListener("uncaughtException",_)}),Yc.unhandledRejection.forEach(function(_){process.removeListener("unhandledRejection",_)})}}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)}),HC=Xt((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")+"//# sourceURL="+f)},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.startWorker=instance=>{Module=instance;postMessage({"cmd":"loaded"})};self.onmessage=e=>{try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;for(const handler of e.data.handlers){Module[handler]=function(){postMessage({cmd:"callHandler",handler:handler,args:[...arguments]})}}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)}else if(e.data.cmd==="run"){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}};`}),jC=Xt((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(Y,se){i=Y,o=se});var l;typeof process!="undefined"&&process.listeners&&(l={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var u=Object.assign({},s),d=[],c="./this.program",p=(Y,se)=>{throw se},h=typeof window=="object",m=typeof importScripts=="function",f=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="";function y(Y){return s.locateFile?s.locateFile(Y,g):g+Y}var x,A,b,w;function S(Y){Y instanceof Dl||F("exiting due to exception: "+Y)}if(f){var C=MA(),N=FA();m?g=N.dirname(g)+"/":g=__dirname+"/",x=(Y,se)=>(Y=Br(Y)?new URL(Y):N.normalize(Y),C.readFileSync(Y,se?void 0:"utf8")),b=Y=>{var se=x(Y,!0);return se.buffer||(se=new Uint8Array(se)),se},A=(Y,se,Me)=>{Y=Br(Y)?new URL(Y):N.normalize(Y),C.readFile(Y,function(et,kt){et?Me(et):se(kt.buffer)})},process.argv.length>1&&(c=process.argv[1].replace(/\\/g,"/")),d=process.argv.slice(2),process.on("uncaughtException",function(Y){if(!(Y instanceof Dl))throw Y}),process.on("unhandledRejection",function(Y){throw Y}),p=(Y,se)=>{if(ja())throw process.exitCode=Y,se;S(se),process.exit(Y)},s.inspect=function(){return"[Emscripten Module object]"}}else(h||m)&&(m?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="",x=Y=>{var se=new XMLHttpRequest;return se.open("GET",Y,!1),se.send(null),se.responseText},m&&(b=Y=>{var se=new XMLHttpRequest;return se.open("GET",Y,!1),se.responseType="arraybuffer",se.send(null),new Uint8Array(se.response)}),A=(Y,se,Me)=>{var et=new XMLHttpRequest;et.open("GET",Y,!0),et.responseType="arraybuffer",et.onload=()=>{if(et.status==200||et.status==0&&et.response){se(et.response);return}Me()},et.onerror=Me,et.send(null)},w=Y=>document.title=Y);var M=s.print||console.log.bind(console),F=s.printErr||console.warn.bind(console);Object.assign(s,u),u=null,s.arguments&&(d=s.arguments),s.thisProgram&&(c=s.thisProgram),s.quit&&(p=s.quit);var E=4,T;s.wasmBinary&&(T=s.wasmBinary);var D=s.noExitRuntime||!0;typeof WebAssembly!="object"&&Kn("no native wasm support detected");var O,W=!1,$;function U(Y,se){Y||Kn(se)}var G=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function q(Y,se,Me){se>>>=0;for(var et=se+Me,kt=se;Y[kt]&&!(kt>=et);)++kt;if(kt-se>16&&Y.buffer&&G)return G.decode(Y.subarray(se,kt));for(var It="";se<kt;){var Je=Y[se++];if(!(Je&128)){It+=String.fromCharCode(Je);continue}var Ze=Y[se++]&63;if((Je&224)==192){It+=String.fromCharCode((Je&31)<<6|Ze);continue}var Wt=Y[se++]&63;if((Je&240)==224?Je=(Je&15)<<12|Ze<<6|Wt:Je=(Je&7)<<18|Ze<<12|Wt<<6|Y[se++]&63,Je<65536)It+=String.fromCharCode(Je);else{var hn=Je-65536;It+=String.fromCharCode(55296|hn>>10,56320|hn&1023)}}return It}function H(Y,se){return Y>>>=0,Y?q(ee,Y,se):""}function V(Y,se,Me,et){if(Me>>>=0,!(et>0))return 0;for(var kt=Me,It=Me+et-1,Je=0;Je<Y.length;++Je){var Ze=Y.charCodeAt(Je);if(Ze>=55296&&Ze<=57343){var Wt=Y.charCodeAt(++Je);Ze=65536+((Ze&1023)<<10)|Wt&1023}if(Ze<=127){if(Me>=It)break;se[Me++>>>0]=Ze}else if(Ze<=2047){if(Me+1>=It)break;se[Me++>>>0]=192|Ze>>6,se[Me++>>>0]=128|Ze&63}else if(Ze<=65535){if(Me+2>=It)break;se[Me++>>>0]=224|Ze>>12,se[Me++>>>0]=128|Ze>>6&63,se[Me++>>>0]=128|Ze&63}else{if(Me+3>=It)break;se[Me++>>>0]=240|Ze>>18,se[Me++>>>0]=128|Ze>>12&63,se[Me++>>>0]=128|Ze>>6&63,se[Me++>>>0]=128|Ze&63}}return se[Me>>>0]=0,Me-kt}function Z(Y,se,Me){return V(Y,ee,se,Me)}var X,re,ee,ge,ie,be,Ce,Ee,Le;function qe(Y){X=Y,s.HEAP8=re=new Int8Array(Y),s.HEAP16=ge=new Int16Array(Y),s.HEAP32=be=new Int32Array(Y),s.HEAPU8=ee=new Uint8Array(Y),s.HEAPU16=ie=new Uint16Array(Y),s.HEAPU32=Ce=new Uint32Array(Y),s.HEAPF32=Ee=new Float32Array(Y),s.HEAPF64=Le=new Float64Array(Y)}var gt=s.INITIAL_MEMORY||16777216,dt,st=[],it=[],He=[],xt=!1;function ja(){return D}function Lt(){if(s.preRun)for(typeof s.preRun=="function"&&(s.preRun=[s.preRun]);s.preRun.length;)Da(s.preRun.shift());xr(st)}function pn(){xt=!0,xr(it)}function ua(){if(s.postRun)for(typeof s.postRun=="function"&&(s.postRun=[s.postRun]);s.postRun.length;)Pa(s.postRun.shift());xr(He)}function Da(Y){st.unshift(Y)}function cn(Y){it.unshift(Y)}function Pa(Y){He.unshift(Y)}var ht=0,_a=null,qa=null;function yr(Y){ht++,s.monitorRunDependencies&&s.monitorRunDependencies(ht)}function $l(Y){if(ht--,s.monitorRunDependencies&&s.monitorRunDependencies(ht),ht==0&&(_a!==null&&(clearInterval(_a),_a=null),qa)){var se=qa;qa=null,se()}}function Kn(Y){s.onAbort&&s.onAbort(Y),Y="Aborted("+Y+")",F(Y),W=!0,$=1,Y+=". Build with -sASSERTIONS for more info.";var se=new WebAssembly.RuntimeError(Y);throw o(se),se}var bd="data:application/octet-stream;base64,";function Tn(Y){return Y.startsWith(bd)}function Br(Y){return Y.startsWith("file://")}var Yt;Yt="tfjs-backend-wasm.wasm",Tn(Yt)||(Yt=y(Yt));function Ic(Y){try{if(Y==Yt&&T)return new Uint8Array(T);if(b)return b(Y);throw"both async and sync fetching of the wasm failed"}catch(se){Kn(se)}}function ym(){if(!T&&(h||m)){if(typeof fetch=="function"&&!Br(Yt))return fetch(Yt,{credentials:"same-origin"}).then(function(Y){if(!Y.ok)throw"failed to load wasm binary file at '"+Yt+"'";return Y.arrayBuffer()}).catch(function(){return Ic(Yt)});if(A)return new Promise(function(Y,se){A(Yt,function(Me){Y(new Uint8Array(Me))},se)})}return Promise.resolve().then(function(){return Ic(Yt)})}function xm(){var Y={env:vd,wasi_snapshot_preview1:vd};function se(Je,Ze){var Wt=Je.exports;s.asm=Wt,O=s.asm.memory,qe(O.buffer),dt=s.asm.__indirect_function_table,cn(s.asm.__wasm_call_ctors),$l("wasm-instantiate")}yr("wasm-instantiate");function Me(Je){se(Je.instance)}function et(Je){return ym().then(function(Ze){return WebAssembly.instantiate(Ze,Y)}).then(function(Ze){return Ze}).then(Je,function(Ze){F("failed to asynchronously prepare wasm: "+Ze),Kn(Ze)})}function kt(){return!T&&typeof WebAssembly.instantiateStreaming=="function"&&!Tn(Yt)&&!Br(Yt)&&!f&&typeof fetch=="function"?fetch(Yt,{credentials:"same-origin"}).then(function(Je){var Ze=WebAssembly.instantiateStreaming(Je,Y);return Ze.then(Me,function(Wt){return F("wasm streaming compile failed: "+Wt),F("falling back to ArrayBuffer instantiation"),et(Me)})}):et(Me)}if(s.instantiateWasm)try{var It=s.instantiateWasm(Y,se);return It}catch(Je){F("Module.instantiateWasm callback failed with error: "+Je),o(Je)}return kt().catch(o),{}}var Gx,Vr;function Dl(Y){this.name="ExitStatus",this.message="Program terminated with exit("+Y+")",this.status=Y}function xr(Y){for(;Y.length>0;)Y.shift()(s)}function Am(){Kn("")}function Sc(){return 4294901760}function si(){return Sc()}function bm(Y,se,Me){ee.copyWithin(Y>>>0,se>>>0,se+Me>>>0)}function Tc(Y){try{return O.grow(Y-X.byteLength+65535>>>16),qe(O.buffer),1}catch(se){}}function Pl(Y){var se=ee.length;Y=Y>>>0;var Me=Sc();if(Y>Me)return!1;let et=(Wt,hn)=>Wt+(hn-Wt%hn)%hn;for(var kt=1;kt<=4;kt*=2){var It=se*(1+.2/kt);It=Math.min(It,Y+100663296);var Je=Math.min(Me,et(Math.max(Y,It),65536)),Ze=Tc(Je);if(Ze)return!0}return!1}var ma={varargs:void 0,get:function(){ma.varargs+=4;var Y=be[ma.varargs-4>>>2];return Y},getStr:function(Y){var se=H(Y);return se}};function Cc(Y){return 52}function vm(Y,se,Me,et,kt){return 70}var wm=[null,[],[]];function Hx(Y,se){var Me=wm[Y];se===0||se===10?((Y===1?M:F)(q(Me,0)),Me.length=0):Me.push(se)}function jx(Y,se,Me,et){for(var kt=0,It=0;It<Me;It++){var Je=Ce[se>>>2],Ze=Ce[se+4>>>2];se+=8;for(var Wt=0;Wt<Ze;Wt++)Hx(Y,ee[Je+Wt>>>0]);kt+=Ze}return Ce[et>>>2]=kt,0}function Nc(Y){var se=s["_"+Y];return se}function ii(Y,se){re.set(Y,se>>>0)}function km(Y,se,Me,et,kt){var It={string:Oa=>{var Gr=0;if(Oa!=null&&Oa!==0){var Hc=(Oa.length<<2)+1;Gr=Td(Hc),Z(Oa,Gr,Hc)}return Gr},array:Oa=>{var Gr=Td(Oa.length);return ii(Oa,Gr),Gr}};function Je(Oa){return se==="string"?H(Oa):se==="boolean"?!!Oa:Oa}var Ze=Nc(Y),Wt=[],hn=0;if(et)for(var Ar=0;Ar<et.length;Ar++){var Gc=It[Me[Ar]];Gc?(hn===0&&(hn=Bc()),Wt[Ar]=Gc(et[Ar])):Wt[Ar]=et[Ar]}var Cd=Ze.apply(null,Wt);function q2(Oa){return hn!==0&&Vc(hn),Je(Oa)}return Cd=q2(Cd),Cd}function Im(Y,se,Me,et){Me=Me||[];var kt=Me.every(Je=>Je==="number"||Je==="boolean"),It=se!=="string";return It&&kt&&!et?Nc(Y):function(){return km(Y,se,Me,arguments,et)}}var vd={abort:Am,emscripten_get_heap_max:si,emscripten_memcpy_big:bm,emscripten_resize_heap:Pl,fd_close:Cc,fd_seek:vm,fd_write:jx},Sm=xm(),Rc=s.___wasm_call_ctors=function(){return(Rc=s.___wasm_call_ctors=s.asm.__wasm_call_ctors).apply(null,arguments)},Ec=s._init=function(){return(Ec=s._init=s.asm.init).apply(null,arguments)},Tm=s._init_with_threads_count=function(){return(Tm=s._init_with_threads_count=s.asm.init_with_threads_count).apply(null,arguments)},Mc=s._get_threads_count=function(){return(Mc=s._get_threads_count=s.asm.get_threads_count).apply(null,arguments)},Cm=s._register_tensor=function(){return(Cm=s._register_tensor=s.asm.register_tensor).apply(null,arguments)},We=s._dispose_data=function(){return(We=s._dispose_data=s.asm.dispose_data).apply(null,arguments)},wd=s._dispose=function(){return(wd=s._dispose=s.asm.dispose).apply(null,arguments)},Nm=s._Abs=function(){return(Nm=s._Abs=s.asm.Abs).apply(null,arguments)},Fc=s._Acos=function(){return(Fc=s._Acos=s.asm.Acos).apply(null,arguments)},_l=s._Acosh=function(){return(_l=s._Acosh=s.asm.Acosh).apply(null,arguments)},Rm=s._Add=function(){return(Rm=s._Add=s.asm.Add).apply(null,arguments)},Em=s._AddN=function(){return(Em=s._AddN=s.asm.AddN).apply(null,arguments)},Mm=s._All=function(){return(Mm=s._All=s.asm.All).apply(null,arguments)},Fm=s._Any=function(){return(Fm=s._Any=s.asm.Any).apply(null,arguments)},$m=s._ArgMax=function(){return($m=s._ArgMax=s.asm.ArgMax).apply(null,arguments)},$c=s._ArgMin=function(){return($c=s._ArgMin=s.asm.ArgMin).apply(null,arguments)},Dc=s._Asin=function(){return(Dc=s._Asin=s.asm.Asin).apply(null,arguments)},Dm=s._Asinh=function(){return(Dm=s._Asinh=s.asm.Asinh).apply(null,arguments)},Pm=s._Atan=function(){return(Pm=s._Atan=s.asm.Atan).apply(null,arguments)},_m=s._Atan2=function(){return(_m=s._Atan2=s.asm.Atan2).apply(null,arguments)},kd=s._Atanh=function(){return(kd=s._Atanh=s.asm.Atanh).apply(null,arguments)},Om=s._AvgPool=function(){return(Om=s._AvgPool=s.asm.AvgPool).apply(null,arguments)},zm=s._AvgPool3D=function(){return(zm=s._AvgPool3D=s.asm.AvgPool3D).apply(null,arguments)},Lm=s._AvgPool3DGrad=function(){return(Lm=s._AvgPool3DGrad=s.asm.AvgPool3DGrad).apply(null,arguments)},oi=s._AvgPoolGrad=function(){return(oi=s._AvgPoolGrad=s.asm.AvgPoolGrad).apply(null,arguments)},Wm=s._BatchMatMul=function(){return(Wm=s._BatchMatMul=s.asm.BatchMatMul).apply(null,arguments)},Bm=s._Bincount=function(){return(Bm=s._Bincount=s.asm.Bincount).apply(null,arguments)},Pc=s._BitwiseAnd=function(){return(Pc=s._BitwiseAnd=s.asm.BitwiseAnd).apply(null,arguments)},Vm=s._Ceil=function(){return(Vm=s._Ceil=s.asm.Ceil).apply(null,arguments)},Id=s._ClipByValue=function(){return(Id=s._ClipByValue=s.asm.ClipByValue).apply(null,arguments)},Um=s._Conv2D=function(){return(Um=s._Conv2D=s.asm.Conv2D).apply(null,arguments)},Gm=s._Conv2DBackpropInput=function(){return(Gm=s._Conv2DBackpropInput=s.asm.Conv2DBackpropInput).apply(null,arguments)},Hm=s._Conv3D=function(){return(Hm=s._Conv3D=s.asm.Conv3D).apply(null,arguments)},Ur=s._Conv3DBackpropFilterV2=function(){return(Ur=s._Conv3DBackpropFilterV2=s.asm.Conv3DBackpropFilterV2).apply(null,arguments)},Sd=s._Conv3DBackpropInputV2=function(){return(Sd=s._Conv3DBackpropInputV2=s.asm.Conv3DBackpropInputV2).apply(null,arguments)},jm=s._Cos=function(){return(jm=s._Cos=s.asm.Cos).apply(null,arguments)},qm=s._Cosh=function(){return(qm=s._Cosh=s.asm.Cosh).apply(null,arguments)},Xm=s._CropAndResize=function(){return(Xm=s._CropAndResize=s.asm.CropAndResize).apply(null,arguments)},Km=s._Cumprod=function(){return(Km=s._Cumprod=s.asm.Cumprod).apply(null,arguments)},_c=s._Cumsum=function(){return(_c=s._Cumsum=s.asm.Cumsum).apply(null,arguments)},Oc=s._DenseBincount=function(){return(Oc=s._DenseBincount=s.asm.DenseBincount).apply(null,arguments)},Ym=s._DepthToSpace=function(){return(Ym=s._DepthToSpace=s.asm.DepthToSpace).apply(null,arguments)},Zm=s._DepthwiseConv2dNative=function(){return(Zm=s._DepthwiseConv2dNative=s.asm.DepthwiseConv2dNative).apply(null,arguments)},zc=s._Diag=function(){return(zc=s._Diag=s.asm.Diag).apply(null,arguments)},Lc=s._Dilation2D=function(){return(Lc=s._Dilation2D=s.asm.Dilation2D).apply(null,arguments)},Jm=s._Dilation2DBackpropFilter=function(){return(Jm=s._Dilation2DBackpropFilter=s.asm.Dilation2DBackpropFilter).apply(null,arguments)},Qm=s._Dilation2DBackpropInput=function(){return(Qm=s._Dilation2DBackpropInput=s.asm.Dilation2DBackpropInput).apply(null,arguments)},ef=s._Elu=function(){return(ef=s._Elu=s.asm.Elu).apply(null,arguments)},tf=s._EluGrad=function(){return(tf=s._EluGrad=s.asm.EluGrad).apply(null,arguments)},Wc=s._Equal=function(){return(Wc=s._Equal=s.asm.Equal).apply(null,arguments)},qx=s._Erf=function(){return(qx=s._Erf=s.asm.Erf).apply(null,arguments)},af=s._Exp=function(){return(af=s._Exp=s.asm.Exp).apply(null,arguments)},nf=s._Expm1=function(){return(nf=s._Expm1=s.asm.Expm1).apply(null,arguments)},rf=s._FlipLeftRight=function(){return(rf=s._FlipLeftRight=s.asm.FlipLeftRight).apply(null,arguments)},sf=s._Floor=function(){return(sf=s._Floor=s.asm.Floor).apply(null,arguments)},of=s._FloorDiv=function(){return(of=s._FloorDiv=s.asm.FloorDiv).apply(null,arguments)},lf=s._FusedBatchNorm=function(){return(lf=s._FusedBatchNorm=s.asm.FusedBatchNorm).apply(null,arguments)},uf=s._FusedConv2D=function(){return(uf=s._FusedConv2D=s.asm.FusedConv2D).apply(null,arguments)},df=s._FusedDepthwiseConv2D=function(){return(df=s._FusedDepthwiseConv2D=s.asm.FusedDepthwiseConv2D).apply(null,arguments)},pf=s._Gather=function(){return(pf=s._Gather=s.asm.Gather).apply(null,arguments)},cf=s._GatherNd=function(){return(cf=s._GatherNd=s.asm.GatherNd).apply(null,arguments)},hf=s._Greater=function(){return(hf=s._Greater=s.asm.Greater).apply(null,arguments)},mf=s._GreaterEqual=function(){return(mf=s._GreaterEqual=s.asm.GreaterEqual).apply(null,arguments)},ff=s._IsFinite=function(){return(ff=s._IsFinite=s.asm.IsFinite).apply(null,arguments)},gf=s._IsInf=function(){return(gf=s._IsInf=s.asm.IsInf).apply(null,arguments)},yf=s._IsNan=function(){return(yf=s._IsNan=s.asm.IsNan).apply(null,arguments)},xf=s._LRN=function(){return(xf=s._LRN=s.asm.LRN).apply(null,arguments)},Af=s._LRNGrad=function(){return(Af=s._LRNGrad=s.asm.LRNGrad).apply(null,arguments)},bf=s._LeakyRelu=function(){return(bf=s._LeakyRelu=s.asm.LeakyRelu).apply(null,arguments)},vf=s._Less=function(){return(vf=s._Less=s.asm.Less).apply(null,arguments)},wf=s._LessEqual=function(){return(wf=s._LessEqual=s.asm.LessEqual).apply(null,arguments)},kf=s._LinSpace=function(){return(kf=s._LinSpace=s.asm.LinSpace).apply(null,arguments)},If=s._Log=function(){return(If=s._Log=s.asm.Log).apply(null,arguments)},Sf=s._Log1p=function(){return(Sf=s._Log1p=s.asm.Log1p).apply(null,arguments)},Tf=s._LogicalAnd=function(){return(Tf=s._LogicalAnd=s.asm.LogicalAnd).apply(null,arguments)},Cf=s._LogicalNot=function(){return(Cf=s._LogicalNot=s.asm.LogicalNot).apply(null,arguments)},Nf=s._LogicalOr=function(){return(Nf=s._LogicalOr=s.asm.LogicalOr).apply(null,arguments)},Rf=s._LogicalXor=function(){return(Rf=s._LogicalXor=s.asm.LogicalXor).apply(null,arguments)},Ef=s._Max=function(){return(Ef=s._Max=s.asm.Max).apply(null,arguments)},Mf=s._MaxPool=function(){return(Mf=s._MaxPool=s.asm.MaxPool).apply(null,arguments)},Ff=s._MaxPool3D=function(){return(Ff=s._MaxPool3D=s.asm.MaxPool3D).apply(null,arguments)},$f=s._MaxPool3DGrad=function(){return($f=s._MaxPool3DGrad=s.asm.MaxPool3DGrad).apply(null,arguments)},Df=s._MaxPoolGrad=function(){return(Df=s._MaxPoolGrad=s.asm.MaxPoolGrad).apply(null,arguments)},Pf=s._MaxPoolWithArgmax=function(){return(Pf=s._MaxPoolWithArgmax=s.asm.MaxPoolWithArgmax).apply(null,arguments)},_f=s._Maximum=function(){return(_f=s._Maximum=s.asm.Maximum).apply(null,arguments)},Of=s._Mean=function(){return(Of=s._Mean=s.asm.Mean).apply(null,arguments)},zf=s._Min=function(){return(zf=s._Min=s.asm.Min).apply(null,arguments)},Lf=s._Minimum=function(){return(Lf=s._Minimum=s.asm.Minimum).apply(null,arguments)},Wf=s._MirrorPad=function(){return(Wf=s._MirrorPad=s.asm.MirrorPad).apply(null,arguments)},Bf=s._Mod=function(){return(Bf=s._Mod=s.asm.Mod).apply(null,arguments)},Vf=s._Multinomial=function(){return(Vf=s._Multinomial=s.asm.Multinomial).apply(null,arguments)},Uf=s._Multiply=function(){return(Uf=s._Multiply=s.asm.Multiply).apply(null,arguments)},Gf=s._Neg=function(){return(Gf=s._Neg=s.asm.Neg).apply(null,arguments)},Hf=s._NonMaxSuppressionV3=function(){return(Hf=s._NonMaxSuppressionV3=s.asm.NonMaxSuppressionV3).apply(null,arguments)},jf=s._NonMaxSuppressionV4=function(){return(jf=s._NonMaxSuppressionV4=s.asm.NonMaxSuppressionV4).apply(null,arguments)},qf=s._NonMaxSuppressionV5=function(){return(qf=s._NonMaxSuppressionV5=s.asm.NonMaxSuppressionV5).apply(null,arguments)},Xf=s._NotEqual=function(){return(Xf=s._NotEqual=s.asm.NotEqual).apply(null,arguments)},Kf=s._OneHot=function(){return(Kf=s._OneHot=s.asm.OneHot).apply(null,arguments)},Yf=s._PadV2=function(){return(Yf=s._PadV2=s.asm.PadV2).apply(null,arguments)},Zf=s._Pow=function(){return(Zf=s._Pow=s.asm.Pow).apply(null,arguments)},Jf=s._Prelu=function(){return(Jf=s._Prelu=s.asm.Prelu).apply(null,arguments)},Qf=s._Prod=function(){return(Qf=s._Prod=s.asm.Prod).apply(null,arguments)},e2=s._RealDiv=function(){return(e2=s._RealDiv=s.asm.RealDiv).apply(null,arguments)},t2=s._Reciprocal=function(){return(t2=s._Reciprocal=s.asm.Reciprocal).apply(null,arguments)},a2=s._Relu=function(){return(a2=s._Relu=s.asm.Relu).apply(null,arguments)},n2=s._Relu6=function(){return(n2=s._Relu6=s.asm.Relu6).apply(null,arguments)},r2=s._ResizeBilinear=function(){return(r2=s._ResizeBilinear=s.asm.ResizeBilinear).apply(null,arguments)},s2=s._ResizeBilinearGrad=function(){return(s2=s._ResizeBilinearGrad=s.asm.ResizeBilinearGrad).apply(null,arguments)},i2=s._ResizeNearestNeighbor=function(){return(i2=s._ResizeNearestNeighbor=s.asm.ResizeNearestNeighbor).apply(null,arguments)},o2=s._ResizeNearestNeighborGrad=function(){return(o2=s._ResizeNearestNeighborGrad=s.asm.ResizeNearestNeighborGrad).apply(null,arguments)},l2=s._Reverse=function(){return(l2=s._Reverse=s.asm.Reverse).apply(null,arguments)},u2=s._RotateWithOffset=function(){return(u2=s._RotateWithOffset=s.asm.RotateWithOffset).apply(null,arguments)},d2=s._Round=function(){return(d2=s._Round=s.asm.Round).apply(null,arguments)},p2=s._Rsqrt=function(){return(p2=s._Rsqrt=s.asm.Rsqrt).apply(null,arguments)},c2=s._ScatterNd=function(){return(c2=s._ScatterNd=s.asm.ScatterNd).apply(null,arguments)},h2=s._SearchSorted=function(){return(h2=s._SearchSorted=s.asm.SearchSorted).apply(null,arguments)},m2=s._SelectV2=function(){return(m2=s._SelectV2=s.asm.SelectV2).apply(null,arguments)},f2=s._Selu=function(){return(f2=s._Selu=s.asm.Selu).apply(null,arguments)},g2=s._Sigmoid=function(){return(g2=s._Sigmoid=s.asm.Sigmoid).apply(null,arguments)},y2=s._Sign=function(){return(y2=s._Sign=s.asm.Sign).apply(null,arguments)},x2=s._Sin=function(){return(x2=s._Sin=s.asm.Sin).apply(null,arguments)},A2=s._Sinh=function(){return(A2=s._Sinh=s.asm.Sinh).apply(null,arguments)},b2=s._Softmax=function(){return(b2=s._Softmax=s.asm.Softmax).apply(null,arguments)},v2=s._Softplus=function(){return(v2=s._Softplus=s.asm.Softplus).apply(null,arguments)},w2=s._SparseFillEmptyRows=function(){return(w2=s._SparseFillEmptyRows=s.asm.SparseFillEmptyRows).apply(null,arguments)},k2=s._SparseReshape=function(){return(k2=s._SparseReshape=s.asm.SparseReshape).apply(null,arguments)},I2=s._SparseSegmentReduction=function(){return(I2=s._SparseSegmentReduction=s.asm.SparseSegmentReduction).apply(null,arguments)},S2=s._SparseToDense=function(){return(S2=s._SparseToDense=s.asm.SparseToDense).apply(null,arguments)},T2=s._Sqrt=function(){return(T2=s._Sqrt=s.asm.Sqrt).apply(null,arguments)},C2=s._Square=function(){return(C2=s._Square=s.asm.Square).apply(null,arguments)},N2=s._SquaredDifference=function(){return(N2=s._SquaredDifference=s.asm.SquaredDifference).apply(null,arguments)},R2=s._Step=function(){return(R2=s._Step=s.asm.Step).apply(null,arguments)},E2=s._StridedSlice=function(){return(E2=s._StridedSlice=s.asm.StridedSlice).apply(null,arguments)},M2=s._Sub=function(){return(M2=s._Sub=s.asm.Sub).apply(null,arguments)},F2=s._Sum=function(){return(F2=s._Sum=s.asm.Sum).apply(null,arguments)},$2=s._Tan=function(){return($2=s._Tan=s.asm.Tan).apply(null,arguments)},D2=s._Tanh=function(){return(D2=s._Tanh=s.asm.Tanh).apply(null,arguments)},P2=s._TensorScatterUpdate=function(){return(P2=s._TensorScatterUpdate=s.asm.TensorScatterUpdate).apply(null,arguments)},_2=s._Tile=function(){return(_2=s._Tile=s.asm.Tile).apply(null,arguments)},O2=s._TopK=function(){return(O2=s._TopK=s.asm.TopK).apply(null,arguments)},z2=s._Transform=function(){return(z2=s._Transform=s.asm.Transform).apply(null,arguments)},L2=s._Transpose=function(){return(L2=s._Transpose=s.asm.Transpose).apply(null,arguments)},W2=s.__FusedMatMul=function(){return(W2=s.__FusedMatMul=s.asm._FusedMatMul).apply(null,arguments)},B2=s._malloc=function(){return(B2=s._malloc=s.asm.malloc).apply(null,arguments)},V2=s._free=function(){return(V2=s._free=s.asm.free).apply(null,arguments)},U2=s.___errno_location=function(){return(U2=s.___errno_location=s.asm.__errno_location).apply(null,arguments)},Bc=s.stackSave=function(){return(Bc=s.stackSave=s.asm.stackSave).apply(null,arguments)},Vc=s.stackRestore=function(){return(Vc=s.stackRestore=s.asm.stackRestore).apply(null,arguments)},Td=s.stackAlloc=function(){return(Td=s.stackAlloc=s.asm.stackAlloc).apply(null,arguments)},G2=s.dynCall_iijjiiii=function(){return(G2=s.dynCall_iijjiiii=s.asm.dynCall_iijjiiii).apply(null,arguments)},H2=s.dynCall_jiji=function(){return(H2=s.dynCall_jiji=s.asm.dynCall_jiji).apply(null,arguments)};s.cwrap=Im;var Ol;qa=function Y(){Ol||Uc(),Ol||(qa=Y)};function Uc(Y){if(Y=Y||d,ht>0||(Lt(),ht>0))return;function se(){Ol||(Ol=!0,s.calledRun=!0,!W&&(pn(),i(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),ua()))}s.setStatus?(s.setStatus("Running..."),setTimeout(function(){setTimeout(function(){s.setStatus("")},1),se()},1)):se()}if(s.preInit)for(typeof s.preInit=="function"&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();Uc();var zl;l&&(zl={uncaughtException:process.listeners("uncaughtException").filter(function(Y){return!l.uncaughtException.indexOf(Y)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(Y){return!l.unhandledRejection.indexOf(Y)>-1})});var Ll;if(typeof r!="undefined")Ll=r;else if(typeof WasmBackendModuleThreadedSimd!="undefined")Ll=WasmBackendModuleThreadedSimd;else throw new Error("Could not find wasm module in post.js");if(zl){var j2=Ll._dispose;Ll._dispose=function(){j2(),zl.uncaughtException.forEach(function(Y){process.removeListener("uncaughtException",Y)}),zl.unhandledRejection.forEach(function(Y){process.removeListener("unhandledRejection",Y)})}}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)}),hp=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}},du=class{refCount(e){return Ka("refCount")}incRef(e){return Ka("incRef")}timerAvailable(){return!0}time(e){return Ka("time")}read(e){return Ka("read")}readSync(e){return Ka("readSync")}readToGPU(e,t){return Ka("readToGPU")}numDataIds(){return Ka("numDataIds")}disposeData(e,t){return Ka("disposeData")}write(e,t,a){return Ka("write")}move(e,t,a,n,r){return Ka("move")}createTensorFromGPUData(e,t,a){return Ka("createTensorFromGPUData")}memory(){return Ka("memory")}floatPrecision(){return Ka("floatPrecision")}epsilon(){return this.floatPrecision()===32?1e-7:1e-4}dispose(){return Ka("dispose")}};function Ka(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 $A(e){let t=e.length,a=0;for(;t>0;)a=Math.random()*t|0,t--,fh(e,t,a)}function qC(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--,fh(e,a,n),fh(t,a,n)}function Hd(e,t,a){return Math.max(e,Math.min(t,a))}function XC(e){return e%2===0?e:e+1}function fh(e,t,a){let n=e[t];e[t]=e[a],e[a]=n}function KC(e){let t=0;for(let a=0;a<e.length;a++)t+=e[a];return t}function YC(e,t){let a=Math.random();return t*a+(1-a)*e}function ZC(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 Ca(e,t,a=""){P(Er(e,t),()=>a+` Shapes ${e} and ${t} must match`)}function Fi(e){P(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function mt(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 JC(e){return e.length===0}function DA(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]!==null&&t[a]!==null&&e[a]!==t[a])return!1;return!0}function Er(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 Zl(e){return e%1===0}function QC(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 eN(e){let t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function tN(e){let t=new Uint32Array(e);for(let a=0;a<e;++a)t[a]=a;return $A(t),t}function Bd(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function aN(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 nN(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 mp(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=>Zl(n)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(n=>n<0?a+n:n)}function PA(e,t){let a=[],n=[],r=t!=null&&Array.isArray(t)&&t.length===0,s=t==null||r?null:mp(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 _A(e,t){return ig(e,t)}function ig(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 OA(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 zA(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function rN(e,t){return!(t==="complex64"||t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64"||t==="bool"&&e==="bool")}function gh(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 LA(e){if(e==null)return 0;let t=0;return e.forEach(a=>t+=a.length),t}function Xr(e){return typeof e=="string"||e instanceof String}function WA(e){return typeof e=="boolean"}function BA(e){return typeof e=="number"}function fp(e){return Array.isArray(e)?fp(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":BA(e)?"float32":Xr(e)?"string":WA(e)?"bool":"float32"}function es(e){return!!(e&&e.constructor&&e.call&&e.apply)}function yh(e,t){for(let a=t;a<e;++a)if(e%a===0)return a;return e}function pu(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 VA(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]=VA(e+l*o,i,a,n)}return r}function ql(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 VA(0,e,t,a)}function sN(e,t){if(Array.isArray(e))return e;if(t==="float32")return e instanceof Float32Array?e:new Float32Array(e);if(t==="int32")return e instanceof Int32Array?e:new Int32Array(e);if(t==="bool"||t==="string")return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}function og(e,t){let a=Oh(e,t);for(let n=0;n<a.length;n++)a[n]=1;return a}function Oh(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 iN(e,t){let a=e.reduce((n,r)=>n*r,1);if(t==null||t==="float32")return ql(e,new Float32Array(a));if(t==="int32")return ql(e,new Int32Array(a));if(t==="bool")return ql(e,new Uint8Array(a));throw new Error(`Unknown data type ${t}`)}function nn(e){e.forEach(t=>{P(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function oN(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 lN(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 zh(e){return e&&e.then&&typeof e.then=="function"}var n5="tfjsflags",UA=class{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=uN,this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&(B().getBool("IS_TEST")||B().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];B().getBool("IS_TEST")||B().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(zh(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)}getString(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);n5 in e&&e[n5].split(",").forEach(t=>{let[a,n]=t.split(":");this.urlFlags[a]=pN(a,n)})}};function uN(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(a,...n)=>(dN(t,n[0],n[1]),n.join("="))),t}function dN(e,t,a){e[decodeURIComponent(t)]=decodeURIComponent(a||"")}function pN(e,t){let a=t.toLowerCase();return a==="true"||a==="false"?a==="true":`${+a}`===a?+a:t}function B(){return lg}var lg=null;function cN(e){lg=e}var Z2;function GA(){if(Z2==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");Z2=e}return Z2}function hN(){let e=GA();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function ug(e,t){let a=hN();if(a.has(e))return a.get(e);{let n=t();return a.set(e,n),a.get(e)}}var cu="Abs",$i="Acos",Di="Acosh",Mr="Add",Pi="AddN",_i="All",Oi="Any",hu="ArgMax",mu="ArgMin",zi="Asin",Li="Asinh",Wi="Atan",Bi="Atanh",Vi="Atan2",Ui="AvgPool",gp="AvgPoolGrad",fu="AvgPool3D",yp="AvgPool3DGrad",Gi="BatchMatMul",gu="BatchToSpaceND",Hi="Bincount",ji="BitwiseAnd",mN="BroadcastTo",yu="BroadcastArgs",qi="Cast",cs="Ceil",hs="ClipByValue",xp="Complex",Ap="ComplexAbs",xu="Concat",Xi="Conv2D",bp="Conv2DBackpropFilter",Ki="Conv2DBackpropInput",Yi="Conv3D",Au="Conv3DBackpropFilterV2",Zi="Conv3DBackpropInputV2",Ji="Cos",Qi="Cosh",eo="Cumprod",to="Cumsum",ao="CropAndResize",bu="DenseBincount",no="DepthToSpace",ro="DepthwiseConv2dNative",vp="DepthwiseConv2dNativeBackpropFilter",wp="DepthwiseConv2dNativeBackpropInput",vu="Diag",so="Dilation2D",Jl="Dilation2DBackpropInput",Ql="Dilation2DBackpropFilter",kp="Draw",io="RealDiv",Ip="Einsum",oo="Elu",wu="EluGrad",lo="Erf",ms="Equal",fs="Exp",ku="ExpandDims",gs="Expm1",Sp="FFT",Iu="Fill",uo="FlipLeftRight",ys="Floor",xs="FloorDiv",po="FusedBatchNorm",Su="GatherV2",co="GatherNd",As="Greater",bs="GreaterEqual",ho="Identity",Tp="IFFT",Cp="Imag",mo="IsFinite",fo="IsInf",go="IsNan",yo="LeakyRelu",vs="Less",ws="LessEqual",xo="LinSpace",ks="Log",Ao="Log1p",bo="LogicalAnd",vo="LogicalNot",wo="LogicalOr",HA="LogicalXor",fN="LogSoftmax",gN="LowerBound",ko="LRN",Tu="LRNGrad",yN="MatrixBandPart",Io="Max",Is="Maximum",So="MaxPool",Np="MaxPoolGrad",Cu="MaxPool3D",Rp="MaxPool3DGrad",Nu="MaxPoolWithArgmax",To="Mean",Co="Min",Ss="Minimum",No="MirrorPad",Ro="Mod",Eo="Multinomial",Ts="Multiply",Ru="Neg",Cs="NotEqual",Mo="NonMaxSuppressionV3",Eu="NonMaxSuppressionV4",Fo="NonMaxSuppressionV5",Mu="OnesLike",$o="OneHot",Fu="Pack",Do="PadV2",xN="Pool",Po="Pow",_o="Prelu",Oo="Prod",Lh="RaggedGather",Wh="RaggedRange",Bh="RaggedTensorToTensor",$u="Range",Ep="Real",zo="Reciprocal",Lo="Relu",Du="Reshape",Wo="ResizeNearestNeighbor",Pu="ResizeNearestNeighborGrad",Bo="ResizeBilinear",_u="ResizeBilinearGrad",Vo="Relu6",Uo="Reverse",Go="Round",Ns="Rsqrt",Ho="ScatterNd",jo="TensorScatterUpdate",qo="SearchSorted",Ou="Select",Xo="Selu",zu="Slice",Ko="Sin",Yo="Sinh",Zo="Sign",Rs="Sigmoid",Jo="Softplus",Es="Sqrt",Qo="Sum",Lu="SpaceToBatchND",Wu="SplitV",el="Softmax",Mp="SparseFillEmptyRows",Bu="SparseReshape",Vu="SparseSegmentMean",Uu="SparseSegmentSum",tl="SparseToDense",Ms="SquaredDifference",Fp="Square",Gu="StaticRegexReplace",al="StridedSlice",Hu="StringNGrams",$p="StringSplit",Dp="StringToHashBucketFast",Fs="Sub",nl="Tan",rl="Tanh",$s="Tile",sl="TopK",il="Transform",Tr="Transpose",Pp="Unique",ju="Unpack",_p="UnsortedSegmentSum",AN="UpperBound",qu="ZerosLike",Ds="Step",jd="FromPixels",ol="RotateWithOffset",ts="_FusedMatMul",as="FusedConv2D",ns="FusedDepthwiseConv2D";function qr(...e){B().getBool("IS_TEST")||B().getBool("PROD")||console.warn(...e)}function bN(...e){B().getBool("IS_TEST")||B().getBool("PROD")||console.log(...e)}var eu=ug("kernelRegistry",()=>new Map),qd=ug("gradRegistry",()=>new Map);function Xd(e,t){let a=dg(e,t);return eu.get(a)}function o1(e){return qd.get(e)}function tr(e){let t=eu.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 bn(e){let{kernelName:t,backendName:a}=e,n=dg(t,a);eu.has(n)&&qr(`The kernel '${t}' for backend '${a}' is already registered`),eu.set(n,e)}function vN(e){let{kernelName:t}=e;qd.has(t)&&B().getBool("DEBUG")&&qr(`Overriding the gradient for '${t}'`),qd.set(t,e)}function wN(e,t){let a=dg(e,t);if(!eu.has(a))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);eu.delete(a)}function kN(e){if(!qd.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);qd.delete(e)}function IN(e,t){tr(e).forEach(a=>{let n=Object.assign({},a,{backendName:t});bn(n)})}function dg(e,t){return`${t}_${e}`}var v={};Ke(v,{arraysEqual:()=>Er,arraysEqualWithNull:()=>DA,assert:()=>P,assertNonNegativeIntegerDimensions:()=>nn,assertNonNull:()=>Fi,assertShapesMatch:()=>Ca,bytesFromStringArray:()=>LA,bytesPerElement:()=>gh,checkConversionForErrors:()=>OA,clamp:()=>Hd,computeStrides:()=>pu,convertBackendValuesAndArrayBuffer:()=>sN,createScalarValue:()=>EN,createShuffledIndices:()=>tN,decodeString:()=>xh,distSquared:()=>ZC,encodeString:()=>zp,fetch:()=>FN,fingerPrint64:()=>RN,flatten:()=>rs,getArrayFromDType:()=>ig,getTypedArrayFromDType:()=>_A,hasEncodingLoss:()=>rN,hexToLong:()=>Op,indexToLoc:()=>lN,inferDtype:()=>fp,inferFromImplicitShape:()=>nN,isBoolean:()=>WA,isFunction:()=>es,isInt:()=>Zl,isNumber:()=>BA,isPromise:()=>zh,isScalarShape:()=>JC,isString:()=>Xr,isTypedArray:()=>Jt,isValidDtype:()=>zA,locToIndex:()=>oN,makeOnesTypedArray:()=>og,makeZerosNestedTypedArray:()=>iN,makeZerosTypedArray:()=>Oh,nearestDivisor:()=>yh,nearestLargerEven:()=>XC,now:()=>Kd,parseAxisParam:()=>mp,randUniform:()=>YC,repeatedTry:()=>aN,rightPad:()=>Bd,shuffle:()=>$A,shuffleCombo:()=>qC,sizeFromShape:()=>mt,sizeToSquarishShape:()=>eN,squeezeShape:()=>PA,sum:()=>KC,swap:()=>fh,tanh:()=>QC,toNestedArray:()=>ql,toTypedArray:()=>Vh});function jA(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var r5=uu(EC()),ci=r5.default||r5;function Op(e){return ci.fromString(e,!0,16)}var qA=Op("c3a5c85c97cb3127"),di=Op("b492b66fbe98f273"),va=Op("9ae16a3b2f90404f");function l1(e){return e.xor(e.shru(47))}function XA(e,t,a){let n=e.slice(t,t+a);return ci.fromBytes(Array.from(n),!0,!0)}function At(e,t){return XA(e,t,8)}function s5(e,t){return XA(e,t,4)}function Zt(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function Jr(e,t,a=Op("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 SN(e,t,a,n,r,s){r=r.add(e),s=Zt(s.add(r).add(n),21);let i=r;return r=r.add(t),r=r.add(a),s=s.add(Zt(r,44)),[r.add(n),s.add(i)]}function Qc(e,t,a,n){return SN(At(e,t),At(e,t+8),At(e,t+16),At(e,t+24),a,n)}function TN(e,t=e.length){if(t>=8){let a=va.add(t*2),n=At(e,0).add(va),r=At(e,t-8),s=Zt(r,37).mul(a).add(n),i=Zt(n,25).add(r).mul(a);return Jr(s,i,a)}if(t>=4){let a=va.add(t*2),n=s5(e,0);return Jr(n.shl(3).add(t),s5(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 l1(va.mul(s).xor(qA.mul(i))).mul(va)}return va}function CN(e,t=e.length){let a=va.add(t*2),n=At(e,0).mul(di),r=At(e,8),s=At(e,t-8).mul(a),i=At(e,t-16).mul(va);return Jr(Zt(n.add(r),43).add(Zt(s,30)).add(i),n.add(Zt(r.add(va),18)).add(s),a)}function NN(e,t=e.length){let a=va.add(t*2),n=At(e,0).mul(va),r=At(e,8),s=At(e,t-8).mul(a),i=At(e,t-16).mul(va),o=Zt(n.add(r),43).add(Zt(s,30)).add(i),l=Jr(o,n.add(Zt(r.add(va),18)).add(s),a),u=At(e,16).mul(a),d=At(e,24),c=o.add(At(e,t-32)).mul(a),p=l.add(At(e,t-24)).mul(a);return Jr(Zt(u.add(d),43).add(Zt(c,30)).add(p),u.add(Zt(d.add(n),18)).add(c),a)}function RN(e,t=e.length){let a=ci.fromNumber(81,!0);if(t<=32)return t<=16?TN(e,t):CN(e,t);if(t<=64)return NN(e,t);let n=a,r=a.mul(di).add(113),s=l1(r.mul(va).add(113)).mul(va),i=[ci.UZERO,ci.UZERO],o=[ci.UZERO,ci.UZERO];n=n.mul(va).add(At(e,0));let l=0,u=(t-1>>6)*64,d=u+(t-1&63)-63;do n=Zt(n.add(r).add(i[0]).add(At(e,l+8)),37).mul(di),r=Zt(r.add(i[1]).add(At(e,l+48)),42).mul(di),n=n.xor(o[1]),r=r.add(i[0]).add(At(e,l+40)),s=Zt(s.add(o[0]),33).mul(di),i=Qc(e,l,i[1].mul(di),n.add(o[0])),o=Qc(e,l+32,s.add(o[1]),r.add(At(e,l+16))),[s,n]=[n,s],l+=64;while(l!==u);let c=di.add(s.and(255).shl(1));return l=d,o[0]=o[0].add(t-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),n=Zt(n.add(r).add(i[0]).add(At(e,l+8)),37).mul(c),r=Zt(r.add(i[1]).add(At(e,l+48)),42).mul(c),n=n.xor(o[1].mul(9)),r=r.add(i[0].mul(9).add(At(e,l+40))),s=Zt(s.add(o[0]),33).mul(c),i=Qc(e,l,i[1].mul(c),n.add(o[0])),o=Qc(e,l+32,s.add(o[1]),r.add(At(e,l+16))),[s,n]=[n,s],Jr(Jr(i[0],o[0],c).add(l1(r).mul(qA)).add(s),Jr(i[1],o[1],c).add(n),c)}function EN(e,t){return t==="string"?zp(e):Vh([e],t)}function MN(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Vh(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=rs(e)),B().getBool("DEBUG")&&OA(e,t),MN(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 Kd(){return B().platform.now()}function FN(e,t){return B().platform.fetch(e,t)}function zp(e,t="utf-8"){return t=t||"utf-8",B().platform.encode(e,t)}function xh(e,t="utf-8"){return t=t||"utf-8",B().platform.decode(e,t)}function Jt(e){return B().platform.isTypedArray!=null?B().platform.isTypedArray(e):jA(e)}function rs(e,t=[],a=!1){if(t==null&&(t=[]),typeof e=="boolean"||typeof e=="number"||typeof e=="string"||zh(e)||e==null||Jt(e)&&a)t.push(e);else if(Array.isArray(e)||Jt(e))for(let n=0;n<e.length;++n)rs(e[n],t,a);else{let n=-1;for(let r of Object.keys(e))/^([1-9]+[0-9]*|0)$/.test(r)&&(n=Math.max(n,Number(r)));for(let r=0;r<=n;r++)rs(e[r],t,a)}return t}var $N=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new PN)}profileKernel(e,t,a){let n,r=()=>{n=a()},s,i=Kd();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(r);else{r();for(let o of n)o.dataSync();s=Promise.resolve({kernelMs:Kd()-i})}if(B().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let o=0;o<n.length;o++){let l=n[o];l.data().then(u=>{DN(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 DN(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 PN=class{logKernelProfile(e,t,a,n,r,s){let i=typeof n=="number"?Bd(`${n}ms`,9):n.error,o=Bd(e,25),l=t.rank,u=t.size,d=Bd(t.shape.toString(),14),c="";for(let p in r){let h=r[p];if(h!=null){let m=h.shape||t.shape,f=m.length;c+=`${p}: ${f}D ${f>0?m:""} `}}console.log(`%c${o} %c${i} %c${l}D ${d} %c${u} %c${c} %c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function _N(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],d=u.inputs;for(let c in d){let p=d[c],h=!1;for(let m=0;m<t.length;m++)if(n[p.id]){u.outputs.forEach(f=>n[f.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],d=u.inputs;for(let c=0;c<u.outputs.length;c++)if(s[u.outputs[c].id]){for(let p in d)s[d[p].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 d={};for(let p in u.inputs){let h=u.inputs[p];n[h.id]&&(d[p]=h)}let c=Object.assign({},u);c.inputs=d,c.outputs=u.outputs,o.push(c)}}return o}function ON(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 d=s.inputs[l];if(!Er(u.shape,d.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 '${d.shape}'`);if(e[d.id]==null)e[d.id]=u;else{let c=e[d.id];e[d.id]=n(c,u),c.dispose()}}}}var i5=20,Nd=3,J2=7;function zN(e,t,a,n){let r=pu(t),s=LN(e,t,a,r),i=t.length,o=ih(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 LN(e,t,a,n){let r=mt(t),s=n[n.length-1],i=new Array(s).fill(0),o=t.length,l=a==="complex64"?Md(e):e;if(o>1)for(let u=0;u<r/s;u++){let d=u*s;for(let c=0;c<s;c++)i[c]=Math.max(i[c],Ed(l[d+c],0,a).length)}return i}function Ed(e,t,a){let n;return Array.isArray(e)?n=`${parseFloat(e[0].toFixed(J2))} + ${parseFloat(e[1].toFixed(J2))}j`:Xr(e)?n=`'${e}'`:a==="bool"?n=KA(e):n=parseFloat(e.toFixed(J2)).toString(),Bd(n,t)}function KA(e){return e===0?"false":"true"}function ih(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 f=Md(e);return[Ed(f[0],0,a)]}return a==="bool"?[KA(e[0])]:[e[0].toString()]}if(l===1){if(o>i5){let f=Nd*i,g=Array.from(e.slice(0,f)),y=Array.from(e.slice((o-Nd)*i,o*i));return a==="complex64"&&(g=Md(g),y=Md(y)),["["+g.map((x,A)=>Ed(x,r[A],a)).join(", ")+", ..., "+y.map((x,A)=>Ed(x,r[o-Nd+A],a)).join(", ")+"]"]}return["["+(a==="complex64"?Md(e):Array.from(e)).map((f,g)=>Ed(f,r[g],a)).join(", ")+"]"]}let u=t.slice(1),d=n.slice(1),c=n[0]*i,p=[];if(o>i5){for(let f=0;f<Nd;f++){let g=f*c,y=g+c;p.push(...ih(e.slice(g,y),u,a,d,r,!1))}p.push("...");for(let f=o-Nd;f<o;f++){let g=f*c,y=g+c;p.push(...ih(e.slice(g,y),u,a,d,r,f===o-1))}}else for(let f=0;f<o;f++){let g=f*c,y=g+c;p.push(...ih(e.slice(g,y),u,a,d,r,f===o-1))}let h=l===2?",":"";p[0]="["+(o>0?p[0]+h:"");for(let f=1;f<p.length-1;f++)p[f]=" "+p[f]+h;let m=`,
|
|
`;for(let f=2;f<l;f++)m+=`
|
|
`;return p[p.length-1]=" "+p[p.length-1]+"]"+(s?"":m),p}function Md(e){let t=[];for(let a=0;a<e.length;a+=2)t.push([e[a],e[a+1]]);return t}var Rt=class{constructor(e,t,a){if(this.dtype=t,this.shape=e.slice(),this.size=mt(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||ig(t,this.size),this.strides=pu(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 Wn().makeTensor(this.values,this.shape,this.dtype)}},Wn=null,Gl=null,WN=null;function BN(e){Wn=e}function VN(e){Gl=e}function UN(e){WN=e}var yt=class{constructor(e,t,a,n){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=mt(e),this.strides=pu(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 Gl.buffer(this.shape,this.dtype,e)}bufferSync(){return Gl.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return ql(this.shape,e,this.dtype==="complex64")}arraySync(){return ql(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=Wn().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(a=>xh(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(),Wn().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();let e=Wn().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>xh(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 Wn().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),Wn().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Gl.print(this,e)}clone(){return this.throwIfDisposed(),Gl.clone(this)}toString(e=!1){let t=this.dataSync();return zN(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Gl.cast(this,e)}variable(e=!0,t,a){return this.throwIfDisposed(),Wn().makeVariable(this,e,t,a)}};Object.defineProperty(yt,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function YA(){return ug("Tensor",()=>yt)}YA();var Yd=class extends yt{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(!Er(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Wn().disposeTensor(this),this.dataId=e.dataId,Wn().incRef(this,null)}dispose(){Wn().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(Yd,Symbol.hasInstance,{value:e=>e instanceof yt&&e.assign!=null&&e.assign instanceof Function});var ZA={};Ke(ZA,{assertTypesMatch:()=>eb,getTensorsInContainer:()=>pg,isTensorInList:()=>HN,makeTypesMatch:()=>Et});var u1;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(u1||(u1={}));var d1;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(d1||(d1={}));var p1;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(p1||(p1={}));var c1;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(c1||(c1={}));var h1;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(h1||(h1={}));var GN={float32:c1,int32:d1,bool:p1,complex64:h1};function Qt(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return GN[e][t]}function Lp(e){return Qt(e,"int32")}function JA(e){return e!=null&&typeof e=="object"&&"texture"in e&&e.texture instanceof WebGLTexture}function QA(e){return typeof GPUBuffer!="undefined"&&e!=null&&typeof e=="object"&&"buffer"in e&&e.buffer instanceof GPUBuffer}function Et(e,t){if(e.dtype===t.dtype)return[e,t];let a=Qt(e.dtype,t.dtype);return[e.cast(a),t.cast(a)]}function eb(e,t){P(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function HN(e,t){return t.some(a=>a.id===e.id)}function pg(e){let t=[];return tb(e,t,new Set),t}function tb(e,t,a){if(e==null)return;if(e instanceof yt){t.push(e);return}if(!jN(e))return;let n=e;for(let r in n){let s=n[r];a.has(s)||(a.add(s),tb(s,t,a))}}function jN(e){return Array.isArray(e)||typeof e=="object"}function Q2(e){return e.kernelName!=null}var o5=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()}},cg=class m1{constructor(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new o5}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let t=this.getSortedBackends();for(let a=0;a<t.length;a++){let n=t[a];if(await this.initializeBackend(n).success){await this.setBackend(n);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:t,asyncInit:a}=this.initializeBackendsAndReturnBest();if(a)throw new Error(`The highest priority backend '${t}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(t)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(t){if(!(t in this.registry))if(t in this.registryFactory){let{asyncInit:a}=this.initializeBackend(t);if(a)return null}else return null;return this.registry[t]}findBackendFactory(t){return t in this.registryFactory?this.registryFactory[t].factory:null}registerBackend(t,a,n=1){return t in this.registryFactory?(qr(`${t} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[t]={factory:a,priority:n},!0)}async setBackend(t){if(this.registryFactory[t]==null)throw new Error(`Backend name '${t}' not found in registry`);if(this.backendName=t,this.registry[t]==null){this.backendInstance=null;let{success:a,asyncInit:n}=this.initializeBackend(t);if(!(n?await a:a))return!1}return this.backendInstance=this.registry[t],this.setupRegisteredKernels(),this.profiler=new $N(this.backendInstance),!0}setupRegisteredKernels(){tr(this.backendName).forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(t){tr(t).forEach(a=>{a.disposeFunc!=null&&a.disposeFunc(this.registry[t])})}initializeBackend(t){let a=this.registryFactory[t];if(a==null)throw new Error(`Cannot initialize backend ${t}, no registration found.`);try{let n=a.factory();if(n&&!(n instanceof du)&&typeof n.then=="function"){let r=++this.pendingBackendInitId,s=n.then(i=>r<this.pendingBackendInitId?!1:(this.registry[t]=i,this.pendingBackendInit=null,!0)).catch(i=>(r<this.pendingBackendInitId||(this.pendingBackendInit=null,qr(`Initialization of backend ${t} failed`),qr(i.stack||i.message)),!1));return this.pendingBackendInit=s,{success:s,asyncInit:!0}}else return this.registry[t]=n,{success:!0,asyncInit:!1}}catch(n){return qr(`Initialization of backend ${t} failed`),qr(n.stack||n.message),{success:!1,asyncInit:!1}}}removeBackend(t){if(!(t in this.registryFactory))throw new Error(`${t} backend not found in registry`);this.backendName===t&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,t in this.registry&&(this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t]),delete this.registryFactory[t],this.backendName===t&&(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((t,a)=>this.registryFactory[a].priority-this.registryFactory[t].priority)}initializeBackendsAndReturnBest(){let t=this.getSortedBackends();for(let a=0;a<t.length;a++){let n=t[a],{success:r,asyncInit:s}=this.initializeBackend(n);if(s||r)return{name:n,asyncInit:s}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(t,a){let n=this.state.tensorInfo.get(a),r=n.backend,s=this.readSync(a),i=r.refCount(a);r.disposeData(a,!0),n.backend=t,t.move(a,s,n.shape,n.dtype,i),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(t,a){let n=null;if(a==null){if(typeof t!="function")throw new Error("Please provide a function to tidy()");a=t}else{if(typeof t!="string"&&!(t instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof a!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");n=t}let r;return this.scopedRun(()=>this.startScope(n),()=>this.endScope(r),()=>(r=a(),r instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),r))}scopedRun(t,a,n){t();try{let r=n();return a(),r}catch(r){throw a(),r}}nextTensorId(){return m1.nextTensorId++}nextVariableId(){return m1.nextVariableId++}clone(t){let a=L.runKernel(ho,{x:t}),n={x:t},r=i=>({x:()=>{let o="float32",l={x:i},u={dtype:o};return L.runKernel(qi,l,u)}}),s=[];return this.addTapeNode(this.state.activeScope.name,n,[a],r,s,{}),a}runKernel(t,a,n){if(this.backendName==null&&this.backend,Xd(t,this.backendName)==null)throw new Error(`Kernel '${t}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:t,inputs:a,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(t,a,n){let r=this.backend.numDataIds(),s=0;n.forEach(l=>{s+=l.dtype==="complex64"?3:1});let i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=r-a-s-i;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${t}'`)}runKernelFunc(t){let a,n=[],r=this.isTapeOn(),s=this.state.numBytes,i=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let o;this.backendName==null&&this.backend;let l,u=Q2(t)?t.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(Q2(t)){let{kernelName:m,inputs:f,attrs:g}=t;this.backendName==null&&this.backend;let y=Xd(m,this.backendName);P(y!=null,()=>`Cannot find registered kernel '${m}' for backend '${this.backendName}'`),o=()=>{let x=this.backend.numDataIds();l=y.kernelFunc({inputs:f,attrs:g,backend:this.backend});let A=Array.isArray(l)?l:[l];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(m,x,A);let b=A.map(w=>w.rank!=null?w:this.makeTensorFromTensorInfo(w));if(r){let w=this.getTensorsForGradient(m,f,b);n=this.saveTensorsForBackwardMode(w)}return b}}else{let{forwardFunc:m}=t,f=g=>{r&&(n=g.map(y=>this.keep(this.clone(y))))};o=()=>{let g=this.backend.numDataIds();l=this.tidy(()=>m(this.backend,f));let y=Array.isArray(l)?l:[l];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,g,y),y}}let{inputs:d,attrs:c}=t,p=Q2(t)?null:t.backwardsFunc,h;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?a=o():(h=this.profiler.profileKernel(u,d,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(h),a=h.outputs)}),r&&this.addTapeNode(u,d,a,p,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:u,bytesAdded:this.state.numBytes-s,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-i,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(d).map(m=>d[m]!=null?d[m].shape:null),outputShapes:a.map(m=>m.shape),kernelTimeMs:h.timeMs,extraInfo:h.extraInfo}),Array.isArray(l)?a:a[0]}saveTensorsForBackwardMode(t){return t.map(a=>this.keep(this.clone(a)))}getTensorsForGradient(t,a,n){let r=o1(t);if(r!=null){let s=r.inputsToSave||[],i=r.outputsToSave||[],o;r.saveAllInputs?(P(Array.isArray(a),()=>"saveAllInputs is true, expected inputs to be an array."),o=Object.keys(a).map(u=>a[u])):o=s.map(u=>a[u]);let l=n.filter((u,d)=>i[d]);return o.concat(l)}return[]}makeTensor(t,a,n,r){if(t==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let s=t;n==="string"&&Xr(t[0])&&(s=t.map(l=>zp(l)));let i=r.write(s,a,n),o=new yt(a,n,i,this.nextTensorId());if(this.trackTensor(o,r),n==="string"){let l=this.state.tensorInfo.get(i),u=LA(s);this.state.numBytes+=u-l.bytes,l.bytes=u}return o}makeTensorFromDataId(t,a,n,r){n=n||"float32";let s={dataId:t,shape:a,dtype:n};return this.makeTensorFromTensorInfo(s,r)}makeTensorFromTensorInfo(t,a){let{dataId:n,shape:r,dtype:s}=t,i=new yt(r,s,n,this.nextTensorId());return this.trackTensor(i,a),i}makeVariable(t,a=!0,n,r){n=n||this.nextVariableId().toString(),r!=null&&r!==t.dtype&&(t=t.cast(r));let s=new Yd(t,a,n,this.nextTensorId());if(this.state.registeredVariables[s.name]!=null)throw new Error(`Variable with name ${s.name} was already registered`);return this.state.registeredVariables[s.name]=s,this.incRef(s,this.backend),s}trackTensor(t,a){this.state.numTensors++,t.dtype==="string"&&this.state.numStringTensors++;let n=0;t.dtype!=="complex64"&&t.dtype!=="string"&&(n=t.size*gh(t.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(t.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(t.dataId,{backend:a||this.backend,dtype:t.dtype,shape:t.shape,bytes:n})),t instanceof Yd||this.track(t)}incRef(t,a){this.trackTensor(t,a),this.backend.incRef(t.dataId)}removeDataId(t,a){this.state.tensorInfo.has(t)&&this.state.tensorInfo.get(t).backend===a&&(this.state.tensorInfo.delete(t),this.state.numDataBuffers--)}disposeTensor(t){if(!this.state.tensorInfo.has(t.dataId))return;let a=this.state.tensorInfo.get(t.dataId);if(this.state.numTensors--,t.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=a.bytes),t.dtype!=="complex64"&&t.dtype!=="string"){let n=t.size*gh(t.dtype);this.state.numBytes-=n}a.backend.disposeData(t.dataId)&&this.removeDataId(t.dataId,a.backend)}disposeVariables(){for(let t in this.state.registeredVariables){let a=this.state.registeredVariables[t];this.disposeVariable(a)}}disposeVariable(t){this.disposeTensor(t),this.state.registeredVariables[t.name]!=null&&delete this.state.registeredVariables[t.name]}memory(){let t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,t.reasons==null&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t}async profile(t){this.state.profiling=!0;let a=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await t(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(r=>r.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-a,this.state.activeProfile.newTensors=this.state.numTensors-n;for(let r of this.state.activeProfile.kernels)r.kernelTimeMs=await r.kernelTimeMs,r.extraInfo=await r.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(t,a,n,r,s,i){let o={id:this.state.nextTapeNodeId++,kernelName:t,inputs:a,outputs:n,saved:s},l=o1(t);l!=null&&(r=l.gradFunc),r!=null&&(o.gradient=u=>(u=u.map((d,c)=>{if(d==null){let p=n[c],h=Oh(p.size,p.dtype);return this.makeTensor(h,p.shape,p.dtype)}return d}),r(u.length>1?u:u[0],s,i))),this.state.activeTape.push(o)}keep(t){return t.kept=!0,t}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(t){let a={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(a.name=t),this.state.scopeStack.push(a),this.state.activeScope=a}endScope(t){let a=pg(t),n=new Set(a.map(s=>s.id));for(let s=0;s<this.state.activeScope.track.length;s++){let i=this.state.activeScope.track[s];!i.kept&&!n.has(i.id)&&i.dispose()}let r=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],a.forEach(s=>{!s.kept&&s.scopeId===r.id&&this.track(s)})}gradients(t,a,n,r=!1){if(P(a.length>0,()=>"gradients() received an empty list of xs."),n!=null&&n.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);let s=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",t));P(s instanceof yt,()=>"The result y returned by f() must be a tensor.");let i=_N(this.state.activeTape,a,s);if(!r&&i.length===0&&a.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{let o={};o[s.id]=n==null?qN(s.shape):n,ON(o,i,u=>this.tidy(u),XN);let l=a.map(u=>o[u.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(u=>{for(let d of u.saved)d.dispose()}),this.state.activeTape=null),{value:s,grads:l}})}customGrad(t){return P(es(t),()=>"The f passed in customGrad(f) must be a function."),(...a)=>{P(a.every(o=>o instanceof yt),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,r={};a.forEach((o,l)=>{r[l]=o});let s=(o,l)=>(n=t(...a,l),P(n.value instanceof yt,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),P(es(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),i=(o,l)=>{let u=n.gradFunc(o,l),d=Array.isArray(u)?u:[u];P(d.length===a.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(d.every(p=>p instanceof yt),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let c={};return d.forEach((p,h)=>{c[h]=()=>p}),c};return this.runKernelFunc({forwardFunc:s,backwardsFunc:i,inputs:r})}}readSync(t){return this.state.tensorInfo.get(t).backend.readSync(t)}read(t){return this.state.tensorInfo.get(t).backend.read(t)}readToGPU(t,a){return this.state.tensorInfo.get(t).backend.readToGPU(t,a)}async time(t){let a=Kd(),n=await this.backend.time(t);return n.wallMs=Kd()-a,n}track(t){return this.state.activeScope!=null&&(t.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(t)),t}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new o5;for(let t in this.registry)this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}};cg.nextTensorId=0;cg.nextVariableId=0;function qN(e){let t=og(mt(e),"float32");return L.makeTensor(t,e,"float32")}function ab(){let e=GA();if(e._tfengine==null){let t=new UA(e);e._tfengine=new cg(t)}return cN(e._tfengine.ENV),BN(()=>e._tfengine),e._tfengine}var L=ab();function XN(e,t){let a={a:e,b:t};return L.runKernel(Mr,a)}var Wp={};Ke(Wp,{isBrowser:()=>nb,isMobile:()=>ZN,mockIsMobile:()=>YN});function KN(){return typeof navigator!="undefined"&&navigator!=null}var f1;function YN(e){f1=e}function ZN(e){if(f1!==void 0)return f1;if(e||KN()){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 nb(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Ba=B();Ba.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.")});Ba.registerFlag("IS_BROWSER",()=>nb());Ba.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Ba.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Ba.registerFlag("IS_SAFARI",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor));Ba.registerFlag("PROD",()=>!1);Ba.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Ba.getBool("DEBUG"));Ba.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Ba.registerFlag("IS_TEST",()=>!1);Ba.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>Ba.getBool("DEBUG"));Ba.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);Ba.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1);Ba.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);function ar(e,t){let a=e;if(Jt(e))return t==="string"?[]:[e.length];if(JA(e)){let r=e.channels||"RGBA";return[e.height,e.width*r.length]}else if(QA(e))return[e.buffer.size/(t==null?4:gh(t))];if(!Array.isArray(e))return[];let n=[];for(;Array.isArray(a)||Jt(a)&&t!=="string";)n.push(a.length),a=a[0];return Array.isArray(e)&&B().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&rb(e,n,[]),n}function rb(e,t,a){if(a=a||[],!Array.isArray(e)&&!Jt(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)rb(e[r],n,a.concat(r))}function l5(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 YA())return l5(n,e.dtype,t,a),e;let r=fp(e);if(r!=="string"&&["bool","int32","float32"].indexOf(n)>=0&&(r=n),l5(n,r,t,a),e==null||!Jt(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=ar(e,r);!Jt(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?Vh(e,r):rs(e,[],!0);return L.makeTensor(i,s,r)}function Zd(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 hg="__op";function z(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+hg;let r=(...s)=>{L.startScope(a);try{let i=n(...s);return zh(i)&&console.error("Cannot return a Promise inside of tidy."),L.endScope(i),i}catch(i){throw L.endScope(null),i}};return Object.defineProperty(r,"name",{value:a,configurable:!0}),r}function JN(e,t){let a=R(e,"real","complex"),n=R(t,"imag","complex");Ca(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 L.runKernel(xp,r)}var Rr=z({complex_:JN});function Ps(e,t,a,n){if(n==null)n=fp(e);else if(n==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(QA(e)||JA(e)){if(n!=="float32"&&n!=="int32")throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${n}.`);return L.backend.createTensorFromGPUData(e,t||a,n)}if(!Jt(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){nn(t);let r=mt(t),s=mt(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!==mt(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!Jt(e)&&!Array.isArray(e)&&(e=[e]),t=t||a,e=n!=="string"?Vh(e,n):rs(e,[],!0),L.makeTensor(e,t,n)}function Ve(e,t,a){let n=ar(e,a);return Ps(e,t,n,a)}var vi={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},Fr=class sb{static join(t){return new sb(t).slice()}constructor(t){if(this.shards=[],this.previousShardIndex=0,t==null||(t instanceof Array||(t=[t]),t=t.map(n=>Jt(n)?n.buffer:n),t.length===0))return;this.bufferUniformSize=t[0].byteLength;let a=0;for(let n=0;n<t.length;n++){let r=t[n];n!==t.length-1&&r.byteLength!==this.bufferUniformSize&&(this.bufferUniformSize=void 0);let s=a+r.byteLength;this.shards.push({buffer:r,start:a,end:s}),a=s}this.shards.length===0&&(this.byteLength=0),this.byteLength=this.shards[this.shards.length-1].end}slice(t=0,a=this.byteLength){if(this.shards.length===0)return new ArrayBuffer(0);if(t=isNaN(Number(t))?0:t,a=isNaN(Number(a))?0:a,t=Math.max(0,t),a=Math.min(this.byteLength,a),a<=t)return new ArrayBuffer(0);let n=this.findShardForByte(t);if(n===-1)throw new Error(`Could not find start shard for byte ${t}`);let r=a-t,s=new ArrayBuffer(r),i=new Uint8Array(s),o=0;for(let l=n;l<this.shards.length;l++){let u=this.shards[l],d=t+o-u.start,c=o,p=Math.min(a,u.end)-u.start,h=new Uint8Array(u.buffer,d,p-d);if(i.set(h,c),o+=h.length,a<u.end)break}return s}findShardForByte(t){if(this.shards.length===0||t<0||t>=this.byteLength)return-1;if(this.bufferUniformSize!=null)return this.previousShardIndex=Math.floor(t/this.bufferUniformSize),this.previousShardIndex;function a(r){return t<r.start?-1:t>=r.end?1:0}if(a(this.shards[this.previousShardIndex])===0)return this.previousShardIndex;let n=QN(this.shards,a);return n===-1?-1:(this.previousShardIndex=n,this.previousShardIndex)}};function QN(e,t){let a=0,n=e.length;for(;a<=n;){let r=Math.floor((n-a)/2)+a,s=t(e[r]);if(s===0)return r;s<0?n=r:a=r+1}return-1}function mg(){B().set("PROD",!0)}function eR(){B().set("DEBUG",!0)}function tR(){B().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function fg(e){B().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}UN(fg);function aR(){L.disposeVariables()}function St(){return L}function nR(){return L.memory()}function rR(e){return L.profile(e)}function Pe(e,t){return L.tidy(e,t)}function J(e){pg(e).forEach(t=>t.dispose())}function Bn(e){return L.keep(e)}function sR(e){return L.time(e)}function Bp(e){return L.setBackend(e)}function Vp(){return L.ready()}function ea(){return L.backendName}function iR(e){L.removeBackend(e)}function gg(e){return L.findBackend(e)}function oR(e){return L.findBackendFactory(e)}function ll(e,t,a=1){return L.registerBackend(e,t,a)}function Gn(){return L.backend}function lR(e,t){B().setPlatform(e,t)}var ss=4;async function uR(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 d=new Promise(async c=>{let p=await l.bytes(),h=p.reduce((g,y)=>g+y.length,0)+ss*p.length,m=new Uint8Array(h),f=0;for(let g=0;g<p.length;g++){let y=p[g],x=new Uint8Array(new Uint32Array([y.length]).buffer);m.set(x,f),f+=ss,m.set(y,f),f+=y.length}c(m)});n.push(d)}else n.push(l.data());t!=null&&(u.group=t),a.push(u)}let s=await Promise.all(n);return{data:cR(s),specs:a}}function ib(e,t){let a=new Fr(e),n={},r=0;for(let s of t){let i=dR(s,(o,l)=>a.slice(r+o,r+l));n[s.name]=ob(s,a.slice(r,r+i)),r+=i}return n}function dR(e,t){let a=mt(e.shape),n;if("quantization"in e){let r=e.quantization;n=vi[r.dtype]}else if(e.dtype==="string"){let r=0;for(let s=0;s<a;s++)r+=ss+new Uint32Array(t(r,r+ss))[0];return r}else n=vi[e.dtype];return a*n}async function pR(e,t){let a=mt(e.shape),n;if("quantization"in e){let r=e.quantization;n=vi[r.dtype]}else if(e.dtype==="string"){let r=0;for(let s=0;s<a;s++)r+=ss+new Uint32Array(await t(r,r+ss))[0];return r}else n=vi[e.dtype];return a*n}function ob(e,t){let a=e.name,n=e.dtype,r=e.shape,s=mt(r),i,o=0;if("quantization"in e){let l=e.quantization;if(l.dtype==="uint8"||l.dtype==="uint16"){if(!("min"in l&&"scale"in l))throw new Error(`Weight ${e.name} with quantization ${l.dtype} doesn't have corresponding metadata min and scale.`)}else if(l.dtype==="float16"){if(n!=="float32")throw new Error(`Weight ${e.name} is quantized with ${l.dtype} which only supports weights of type float32 not ${n}.`)}else throw new Error(`Weight ${e.name} has unknown quantization dtype ${l.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let u=vi[l.dtype],d=l.dtype==="uint8"?new Uint8Array(t):new Uint16Array(t);if(n==="float32")if(l.dtype==="uint8"||l.dtype==="uint16"){i=new Float32Array(d.length);for(let c=0;c<d.length;c++){let p=d[c];i[c]=p*l.scale+l.min}}else if(l.dtype==="float16")i=AR()(d);else throw new Error(`Unsupported quantization type ${l.dtype} for weight type float32.`);else if(n==="int32"){if(l.dtype!=="uint8"&&l.dtype!=="uint16")throw new Error(`Unsupported quantization type ${l.dtype} for weight type int32.`);i=new Int32Array(d.length);for(let c=0;c<d.length;c++){let p=d[c];i[c]=Math.round(p*l.scale+l.min)}}else throw new Error(`Unsupported dtype in weight '${a}': ${n}`);o+=s*u}else if(n==="string"){let l=mt(e.shape);i=[];for(let u=0;u<l;u++){let d=new Uint32Array(t.slice(o,o+ss))[0];o+=ss;let c=new Uint8Array(t.slice(o,o+d));i.push(c),o+=d}}else{let l=vi[n];if(n==="float32")i=new Float32Array(t);else if(n==="int32")i=new Int32Array(t);else if(n==="bool")i=new Uint8Array(t);else if(n==="complex64"){i=new Float32Array(t);let u=new Float32Array(i.length/2),d=new Float32Array(i.length/2);for(let m=0;m<u.length;m++)u[m]=i[m*2],d[m]=i[m*2+1];let c=Ve(u,r,"float32"),p=Ve(d,r,"float32"),h=Rr(c,p);return c.dispose(),p.dispose(),h}else throw new Error(`Unsupported dtype in weight '${a}': ${n}`);o+=s*l}return Ve(i,r,n)}async function u5(e,t,a){let n=new Uint8Array(t);for(;n.byteLength<a;){let{done:r,value:s}=await e.read();if(r&&s==null){let o=a-n.byteLength;throw new Error(`Reader is done but ${o} bytes are still expected`)}let i=new Uint8Array(n.length+s.byteLength);i.set(n,0),i.set(new Uint8Array(s),n.length),n=i}return n.buffer}async function lb(e,t){let a={},n=e.getReader(),r=new ArrayBuffer(0);for(let s of t){let i=await pR(s,async(u,d)=>(r=await u5(n,r,d),r.slice(u,d)));r=await u5(n,r,i);let o=r.slice(0,i);r=r.slice(i);let l=ob(s,o);if(a[s.name]=l,ea()==="webgpu"){let u=Gn();"uploadToGPU"in u&&mt(l.shape)>=B().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&u.uploadToGPU(l.dataId)}}return a}function cR(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 yg=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function d5(e){return yg?Buffer.byteLength(e,"utf8"):new Blob([e]).size}function hR(e){if(yg)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 mR(e){if(yg){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 fR(e){return Fr.join(e)}function p5(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 ub(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 db(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 xg(e,t){let a,n;return e.weightsManifest!=null&&([a,n]=await t(e.weightsManifest)),db(e,a,n)}function Up(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:d5(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:d5(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:new Fr(e.weightData).byteLength}}function g1(e){let t=[];for(let a of e)t.push(...a.weights);return t}function gR(){let e=a=>{let n=a<<13,r=0;for(;!(n&8388608);)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 yR(){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 xR(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function AR(){let e=gR(),t=yR(),a=xR();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 xn=class zn{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return zn.instance==null&&(zn.instance=new zn),zn.instance}static registerSaveRouter(t){zn.getInstance().saveRouters.push(t)}static registerLoadRouter(t){zn.getInstance().loadRouters.push(t)}static getSaveHandlers(t){return zn.getHandlers(t,"save")}static getLoadHandlers(t,a){return zn.getHandlers(t,"load",a)}static getHandlers(t,a,n){let r=[];return(a==="load"?zn.getInstance().loadRouters:zn.getInstance().saveRouters).forEach(s=>{let i=s(t,n);i!==null&&r.push(i)}),r}},bR=e=>xn.registerSaveRouter(e),vR=e=>xn.registerLoadRouter(e),wR=e=>xn.getSaveHandlers(e),kR=(e,t)=>xn.getLoadHandlers(e,t),y1="tensorflowjs",x1=1,yi="models_store",Kr="model_info_store";function pb(){if(!B().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(yi,{keyPath:"modelPath"}),t.createObjectStore(Kr,{keyPath:"modelPath"})}var wi=class{constructor(e){if(this.indexedDB=pb(),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(y1,x1);r.onupgradeneeded=()=>A1(r),r.onsuccess=()=>{let s=r.result;if(t==null){let i=s.transaction(yi,"readonly"),o=i.objectStore(yi).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{t.weightData=Fr.join(t.weightData);let i=Up(t),o=s.transaction(Kr,"readwrite"),l=o.objectStore(Kr),u;try{u=l.put({modelPath:this.modelPath,modelArtifactsInfo:i})}catch(c){return n(c)}let d;u.onsuccess=()=>{d=s.transaction(yi,"readwrite");let c=d.objectStore(yi),p;try{p=c.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i})}catch(h){return n(h)}p.onsuccess=()=>a({modelArtifactsInfo:i}),p.onerror=h=>{l=o.objectStore(Kr);let m=l.delete(this.modelPath);m.onsuccess=()=>(s.close(),n(p.error)),m.onerror=f=>(s.close(),n(p.error))}},u.onerror=c=>(s.close(),n(u.error)),o.oncomplete=()=>{d==null?s.close():d.oncomplete=()=>s.close()}}},r.onerror=s=>n(r.error)})}};wi.URL_SCHEME="indexeddb://";var cb=e=>B().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(wi.URL_SCHEME)?IR(e.slice(wi.URL_SCHEME.length)):null;xn.registerSaveRouter(cb);xn.registerLoadRouter(cb);function IR(e){return new wi(e)}function SR(e){return e.startsWith(wi.URL_SCHEME)?e.slice(wi.URL_SCHEME.length):e}var TR=class{constructor(){this.indexedDB=pb()}async listModels(){return new Promise((e,t)=>{let a=this.indexedDB.open(y1,x1);a.onupgradeneeded=()=>A1(a),a.onsuccess=()=>{let n=a.result,r=n.transaction(Kr,"readonly"),s=r.objectStore(Kr).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=SR(e),new Promise((t,a)=>{let n=this.indexedDB.open(y1,x1);n.onupgradeneeded=()=>A1(n),n.onsuccess=()=>{let r=n.result,s=r.transaction(Kr,"readwrite"),i=s.objectStore(Kr),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),d=()=>{l=r.transaction(yi,"readwrite");let c=l.objectStore(yi).delete(e);c.onsuccess=()=>t(o.result.modelArtifactsInfo),c.onerror=p=>a(o.error)};u.onsuccess=d,u.onerror=c=>(d(),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)})}},Sr="/",Hl="tensorflowjs_models",hb="info",CR="model_topology",NR="weight_specs",RR="weight_data",ER="model_metadata";function mb(e){return{info:[Hl,e,hb].join(Sr),topology:[Hl,e,CR].join(Sr),weightSpecs:[Hl,e,NR].join(Sr),weightData:[Hl,e,RR].join(Sr),modelMetadata:[Hl,e,ER].join(Sr)}}function fb(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function MR(e){let t=e.split(Sr);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Sr)}function FR(e){return e.startsWith(ki.URL_SCHEME)?e.slice(ki.URL_SCHEME.length):e}var ki=class{constructor(e){if(!B().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=mb(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=Up(e),r=Fr.join(e.weightData);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,hR(r));let s={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(s)),{modelArtifactsInfo:n}}catch(s){throw fb(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=mR(s),t}};ki.URL_SCHEME="localstorage://";var gb=e=>B().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ki.URL_SCHEME)?$R(e.slice(ki.URL_SCHEME.length)):null;xn.registerSaveRouter(gb);xn.registerLoadRouter(gb);function $R(e){return new ki(e)}var DR=class{constructor(){P(B().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=Hl+Sr,a=Sr+hb;for(let n=0;n<this.LS.length;++n){let r=this.LS.key(n);if(r.startsWith(t)&&r.endsWith(a)){let s=MR(r);e[s]=JSON.parse(this.LS.getItem(r))}}return e}async removeModel(e){e=FR(e);let t=mb(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 fb(t),a}},Xl="://",is=class Hr{constructor(){this.managers={}}static getInstance(){return Hr.instance==null&&(Hr.instance=new Hr),Hr.instance}static registerManager(t,a){P(t!=null,()=>"scheme must not be undefined or null."),t.endsWith(Xl)&&(t=t.slice(0,t.indexOf(Xl))),P(t.length>0,()=>"scheme must not be an empty string.");let n=Hr.getInstance();P(n.managers[t]==null,()=>`A model store manager is already registered for scheme '${t}'.`),n.managers[t]=a}static getManager(t){let a=Hr.getInstance().managers[t];if(a==null)throw new Error(`Cannot find model manager for scheme '${t}'`);return a}static getSchemes(){return Object.keys(Hr.getInstance().managers)}};function oh(e){if(e.indexOf(Xl)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${is.getSchemes().join(",")}`);return{scheme:e.split(Xl)[0],path:e.split(Xl)[1]}}async function yb(e,t,a=!1){P(e!==t,()=>`Old path and new path are the same: '${e}'`);let n=xn.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=xn.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=oh(e).scheme,l=oh(e).path,u=o===oh(e).scheme,d=await r.load();a&&u&&await is.getManager(o).removeModel(l);let c=await i.save(d);return a&&!u&&await is.getManager(o).removeModel(l),c.modelArtifactsInfo}async function PR(){let e=is.getSchemes(),t={};for(let a of e){let n=await is.getManager(a).listModels();for(let r in n){let s=a+Xl+r;t[s]=n[r]}}return t}async function _R(e){let t=oh(e);return is.getManager(t.scheme).removeModel(t.path)}async function OR(e,t){return yb(e,t,!1)}async function zR(e,t){return yb(e,t,!0)}var LR=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"||!B().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))}isTypedArray(e){return jA(e)}};if(B().get("IS_BROWSER")){B().setPlatform("browser",new LR);try{is.registerManager(ki.URL_SCHEME,new DR)}catch(e){}try{is.registerManager(wi.URL_SCHEME,new TR)}catch(e){}}var WR={importFetch:()=>MC()},e1,BR=class{constructor(){this.util=FC(),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return B().global.fetch!=null?B().global.fetch(e,t):(e1==null&&(e1=WR.importFetch()),e1(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)}isTypedArray(e){return this.util.types.isFloat32Array(e)||this.util.types.isInt32Array(e)||this.util.types.isUint8Array(e)||this.util.types.isUint8ClampedArray(e)}};B().get("IS_NODE")&&!B().get("IS_BROWSER")&&B().setPlatform("node",new BR);function Te(e,t="float32",a){return t=t||"float32",nn(e),new Rt(e,t,a)}function VR(e,t){let a=R(e,"x","cast");if(!zA(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 L.runKernel(qi,n,r)}var Ue=z({cast_:VR});function UR(e){let t={x:R(e,"x","clone","string_or_numeric")};return L.runKernel(ho,t)}var Ia=z({clone_:UR});function Ag(e,t=!1){console.log(e.toString(t))}ab();var GR={buffer:Te,cast:Ue,clone:Ia,print:Ag};VN(GR);function HR(e,t){let a=R(e,"a","add"),n=R(t,"b","add");[a,n]=Et(a,n);let r={a,b:n};return L.runKernel(Mr,r)}var we=z({add_:HR});function jR(e,t){let a=R(e,"a","floorDiv"),n=R(t,"b","floorDiv");[a,n]=Et(a,n);let r={a,b:n};return L.runKernel(xs,r)}var Gp=z({floorDiv_:jR});function qR(e,t){let a=R(e,"a","div"),n=R(t,"b","div");if([a,n]=Et(a,n),a.dtype==="int32"&&n.dtype==="int32")return Gp(a,n);let r={a,b:n},s={};return L.runKernel(io,r,s)}var ve=z({div_:qR});function XR(e,t){let a=R(e,"a","mul"),n=R(t,"b","mul");[a,n]=Et(a,n);let r={a,b:n};return L.runKernel(Ts,r)}var te=z({mul_:XR});function KR(e){let t=R(e,"x","abs");if(t.dtype==="complex64"){let a={x:t};return L.runKernel(Ap,a)}else{let a={x:t};return L.runKernel(cu,a)}}var Ja=z({abs_:KR});function YR(e){let t={x:R(e,"x","acos")};return L.runKernel($i,t)}var xb=z({acos_:YR});function ZR(e){let t={x:R(e,"x","acosh")};return L.runKernel(Di,t)}var Ab=z({acosh_:ZR});function JR(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(!Er(r.shape,a.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let n=t;return L.runKernel(Pi,n)}var Uh=z({addN_:JR});function QR(e,t=null,a=!1){let n={x:R(e,"x","all","bool")},r={axis:t,keepDims:a};return L.runKernel(_i,n,r)}var bb=z({all_:QR});function eE(e,t=null,a=!1){let n={x:R(e,"x","any","bool")},r={axis:t,keepDims:a};return L.runKernel(Oi,n,r)}var vb=z({any_:eE});function tE(e,t=0){let a={x:R(e,"x","argMax")},n={axis:t};return L.runKernel(hu,a,n)}var or=z({argMax_:tE});function aE(e,t=0){let a={x:R(e,"x","argMin")},n={axis:t};return L.runKernel(mu,a,n)}var wb=z({argMin_:aE});function nE(e){let t={x:R(e,"x","asin")};return L.runKernel(zi,t)}var kb=z({asin_:nE});function rE(e){let t={x:R(e,"x","asinh")};return L.runKernel(Li,t)}var Ib=z({asinh_:rE});function sE(e){let t={x:R(e,"x","atan")};return L.runKernel(Wi,t)}var Sb=z({atan_:sE});function iE(e,t){let a=R(e,"a","atan2"),n=R(t,"b","atan2");[a,n]=Et(a,n);let r={a,b:n};return L.runKernel(Vi,r)}var Tb=z({atan2_:iE});function oE(e){let t={x:R(e,"x","atanh")};return L.runKernel(Bi,t)}var Cb=z({atanh_:oE});function lE(e,t,a,n,r="NHWC",s){let i=e[3],o=[...t,i],l=Eb(r);return Hp(e,o,a,s,n,null,null,l)}function Nb(e,t,a,n,r,s,i="channelsLast"){let[o,l]=Jd(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 Hp(e,u,a,n,r,s,!1,i)}function uE(e,t,a,n,r,s,i="NDHWC"){let[o,l,u]=b1(t),d,c;if(i==="NDHWC")c="channelsLast",d=[o,l,u,e[4],e[4]];else if(i==="NCDHW")c="channelsFirst",d=[o,l,u,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return Rb(e,d,a,n,r,!1,c,s)}function Hp(e,t,a,n,r,s,i=!1,o="channelsLast"){let[l,u,d,c]=[-1,-1,-1,-1];if(o==="channelsLast")[l,u,d,c]=e;else if(o==="channelsFirst")[l,c,u,d]=e;else throw new Error(`Unknown dataFormat ${o}`);let[p,h,,m]=t,[f,g]=Jd(a),[y,x]=Jd(n),A=Kl(p,y),b=Kl(h,x),{padInfo:w,outHeight:S,outWidth:C}=cE(r,u,d,f,g,A,b,s,o),N=i?m*c:m,M;return o==="channelsFirst"?M=[l,N,S,C]:o==="channelsLast"&&(M=[l,S,C,N]),{batchSize:l,dataFormat:o,inHeight:u,inWidth:d,inChannels:c,outHeight:S,outWidth:C,outChannels:N,padInfo:w,strideHeight:f,strideWidth:g,filterHeight:p,filterWidth:h,effectiveFilterHeight:A,effectiveFilterWidth:b,dilationHeight:y,dilationWidth:x,inShape:e,outShape:M,filterShape:t}}function Rb(e,t,a,n,r,s=!1,i="channelsLast",o){let[l,u,d,c,p]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[l,u,d,c,p]=e;else if(i==="channelsFirst")[l,p,u,d,c]=e;else throw new Error(`Unknown dataFormat ${i}`);let[h,m,f,,g]=t,[y,x,A]=b1(a),[b,w,S]=b1(n),C=Kl(h,b),N=Kl(m,w),M=Kl(f,S),{padInfo:F,outDepth:E,outHeight:T,outWidth:D}=hE(r,u,d,c,y,x,A,C,N,M,o),O=s?g*p:g,W;return i==="channelsFirst"?W=[l,O,E,T,D]:i==="channelsLast"&&(W=[l,E,T,D,O]),{batchSize:l,dataFormat:i,inDepth:u,inHeight:d,inWidth:c,inChannels:p,outDepth:E,outHeight:T,outWidth:D,outChannels:O,padInfo:F,strideDepth:y,strideHeight:x,strideWidth:A,filterDepth:h,filterHeight:m,filterWidth:f,effectiveFilterDepth:C,effectiveFilterHeight:N,effectiveFilterWidth:M,dilationDepth:b,dilationHeight:w,dilationWidth:S,inShape:e,outShape:W,filterShape:t}}function dE(e,t,a,n,r){n==null&&(n=bg(e,t,a));let s=e[0],i=e[1],o=Qd((s-t+2*n)/a+1,r),l=Qd((i-t+2*n)/a+1,r);return[o,l]}function pE(e,t,a,n,r,s){r==null&&(r=bg(e,t[0],n[0]));let i=[0,0,0,a];for(let o=0;o<3;o++)e[o]+2*r>=t[o]&&(i[o]=Qd((e[o]-t[o]+2*r)/n[o]+1,s));return i}function bg(e,t,a,n=1){let r=Kl(t,n);return Math.floor((e[0]*(a-1)-a+r)/2)}function Jd(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function b1(e){return typeof e=="number"?[e,e,e]:e}function Kl(e,t){return t<=1?e:e+(e-1)*(t-1)}function cE(e,t,a,n,r,s,i,o,l){let u,d,c;if(typeof e=="number"){u={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let p=dE([t,a],s,n,e,o);d=p[0],c=p[1]}else if(e==="same"){d=Math.ceil(t/n),c=Math.ceil(a/r);let p=Math.max(0,(d-1)*n+s-t),h=Math.max(0,(c-1)*r+i-a),m=Math.floor(p/2),f=p-m,g=Math.floor(h/2),y=h-g;u={top:m,bottom:f,left:g,right:y,type:"SAME"}}else if(e==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},d=Math.ceil((t-s+1)/n),c=Math.ceil((a-i+1)/r);else if(typeof e=="object"){let p=l==="channelsLast"?e[1][0]:e[2][0],h=l==="channelsLast"?e[1][1]:e[2][1],m=l==="channelsLast"?e[2][0]:e[3][0],f=l==="channelsLast"?e[2][1]:e[3][1];u={top:p,bottom:h,left:m,right:f,type:p===0&&h===0&&m===0&&f===0?"VALID":"EXPLICIT"},d=Qd((t-s+p+h)/n+1,o),c=Qd((a-i+m+f)/r+1,o)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outHeight:d,outWidth:c}}function hE(e,t,a,n,r,s,i,o,l,u,d){let c,p,h,m;if(e==="valid"&&(e=0),typeof e=="number"){c={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let f=pE([t,a,n,1],[o,l,u],1,[r,s,i],e,d);p=f[0],h=f[1],m=f[2]}else if(e==="same"){p=Math.ceil(t/r),h=Math.ceil(a/s),m=Math.ceil(n/i);let f=(p-1)*r+o-t,g=(h-1)*s+l-a,y=(m-1)*i+u-n,x=Math.floor(f/2),A=f-x,b=Math.floor(g/2),w=g-b,S=Math.floor(y/2),C=y-S;c={top:b,bottom:w,left:S,right:C,front:x,back:A,type:"SAME"}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:c,outDepth:p,outHeight:h,outWidth:m}}function Qd(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 ep(e){let[t,a,n]=Jd(e);return t===1&&a===1&&n===1}function $r(e,t){return ep(e)||ep(t)}function Ii(e){return Jd(e).every(t=>t>0)}function Eb(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Mn(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(Zl(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(Zl(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 mE(e,t){let a={x:R(e,"x","reshape","string_or_numeric")},n={shape:t};return L.runKernel(Du,a,n)}var Q=z({reshape_:mE});function fE(e,t,a,n,r){let s=R(e,"x","avgPool","float32"),i=1;P($r(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=Q(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}.`),Mn("avgPool",n,r);let u={x:o},d={filterSize:t,strides:a,pad:n,dimRoundingMode:r},c=L.runKernel(Ui,u,d);return c=Ue(c,s.dtype),l?Q(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var vg=z({avgPool_:fE});function gE(e,t,a,n,r,s="NDHWC"){let i=R(e,"x","avgPool3d","float32"),o=i,l=!1;i.rank===4&&(l=!0,o=Q(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}`),P(typeof a=="number"&&a>0||Array.isArray(a)&&a[0]>0&&a[1]>0&&a[2]>0,()=>`Error in avgPool3d: Stride must be > 0, but got '${a}'`),Mn("avgPool3d",n,r);let u={x:o},d={filterSize:t,strides:a,pad:n,dimRoundingMode:r,dataFormat:s},c=L.runKernel(fu,u,d);return c=Ue(c,o.dtype),l?Q(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var Mb=z({avgPool3d_:gE});function yE(e,t=0){P(e.length>=1,()=>"Pass at least one tensor to concat");let a=Zd(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 Ia(a[0]);let n=a,r={axis:t};return L.runKernel(xu,n,r)}var lt=z({concat_:yE});function xE(e,t,a=!1,n=!1){let r=R(e,"a","matMul"),s=R(t,"b","matMul");[r,s]=Et(r,s);let i={a:r,b:s},o={transposeA:a,transposeB:n};return L.runKernel(Gi,i,o)}var pt=z({matMul_:xE});function AE(e){let t={x:R(e,"x","sigmoid","float32")};return L.runKernel(Rs,t)}var za=z({sigmoid_:AE});function bE(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 L.runKernel(zu,r,s)}var _e=z({slice_:bE});function vE(e){let t={x:R(e,"x","tanh","float32")};return L.runKernel(rl,t)}var Ah=z({tanh_:vE});function wE(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"),d=R(r,"c","basicLSTMCell"),c=R(s,"h","basicLSTMCell"),p=lt([u,c],1),h=pt(p,o),m=we(h,l),f=m.shape[0],g=m.shape[1]/4,y=[f,g],x=_e(m,[0,0],y),A=_e(m,[0,g],y),b=_e(m,[0,g*2],y),w=_e(m,[0,g*3],y),S=we(te(za(x),Ah(A)),te(d,za(we(i,b)))),C=te(Ah(S),za(w));return[S,C]}var Fb=z({basicLSTMCell_:wE});function kE(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 L.runKernel(gu,s,i)}var wg=z({batchToSpaceND_:kE});function IE(e){let t;return e.rank===0||e.rank===1?t=Q(e,[1,1,1,e.size]):e.rank===2?t=Q(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=Q(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function SE(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 d;n!=null&&(d=R(n,"offset","batchNorm")),P(o.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),P(d==null||o.rank===d.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:IE(i),scale:u,offset:d,mean:o,variance:l},p={varianceEpsilon:s},h=L.runKernel(po,c,p);return Q(h,i.shape)}var jp=z({batchNorm_:SE});function TE(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 d;return n!=null&&(d=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}.`),d!=null&&P(d.rank===2||d.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${d.rank}.`),jp(i,o,l,d,u,s)}var $b=z({batchNorm2d_:TE});function CE(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 d;return n!=null&&(d=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}.`),d!=null&&P(d.rank===3||d.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${d.rank}.`),jp(i,o,l,d,u,s)}var Db=z({batchNorm3d_:CE});function NE(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 d;return n!=null&&(d=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}.`),d!=null&&P(d.rank===4||d.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${d.rank}.`),jp(i,o,l,d,u,s)}var Pb=z({batchNorm4d_:NE});function RE(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 L.runKernel(Hi,s,i)}var kg=z({bincount_:RE});function EE(e,t){let a=R(e,"x","bitwiseAnd"),n=R(t,"y","bitwiseAnd");if(!Er(a.shape,n.shape))throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${a.shape}, y: ${n.shape}`);if(a.dtype!=="int32"||n.dtype!=="int32")throw new Error(`BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${a.dtype} and type of y: ${n.dtype}`);let r={a,b:n};return L.runKernel(ji,r)}var _b=z({bitwiseAnd_:EE});function ME(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 L.runKernel(yu,r)}var Ob=z({broadcastArgs_:ME});function FE(e,t){let a=R(e,"broadcastTo","x"),n=a.shape;if(nn(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=Q(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 Ia(a);let i={x:a},o={reps:s};return L.runKernel($s,i,o)}var Ai=z({broadcastTo_:FE});function $E(e){let t={x:R(e,"x","ceil","float32")};return L.runKernel(cs,t)}var zb=z({ceil_:$E});function lr(e,t,a){nn(e),a=a||fp(t);let n={shape:e,value:t,dtype:a};return L.runKernel(Iu,{},n)}function DE(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 lr(n.shape,t,n.dtype);let r={x:n},s={clipValueMin:t,clipValueMax:a};return L.runKernel(hs,r,s)}var Lb=z({clipByValue_:DE});function PE(e){return lt(e,0)}var Wb=z({concat1d_:PE});function _E(e,t){return lt(e,t)}var Xu=z({concat2d_:_E});function OE(e,t){return lt(e,t)}var Bb=z({concat3d_:OE});function zE(e,t){return lt(e,t)}var Vb=z({concat4d_:zE});function LE(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,d=!1;o.rank===3&&(d=!0,u=Q(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}.`),Mn("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($r(a,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${a} and dilations '${s}'`),P(Ii(s),()=>"Error in conv2D: Dilated rates should be larger than 0."),P(Ii(a),()=>"Error in conv2D: Strides should be larger than 0.");let p={x:u,filter:l},h={strides:a,pad:n,dataFormat:r,dilations:s,dimRoundingMode:i},m=L.runKernel(Xi,p,h);return d?Q(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var qp=z({conv2d_:LE});function WE(e,t,a,n,r="NWC",s=1,i){let o=R(e,"x","conv1d"),l=R(t,"filter","conv1d"),u=o,d=!1;o.rank===2&&(d=!0,u=Q(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}.`),Mn("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($r(a,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${a} and dilation '${s}'`),P(Ii(s),()=>"Error in conv1D: Dilated rates should be larger than 0."),P(Ii(a),()=>"Error in conv1D: Stride should be larger than 0."),P(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);let c=Q(l,[1,l.shape[0],l.shape[1],l.shape[2]]),p=Q(u,[u.shape[0],1,u.shape[1],u.shape[2]]),h=qp(p,c,[1,a],n,"NHWC",[1,s],i);return d?Q(h,[h.shape[2],h.shape[3]]):Q(h,[h.shape[0],h.shape[2],h.shape[3]])}var Ub=z({conv1d_:WE});function BE(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=Q(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 d=s==="NHWC"?o[3]:o[1],c=s==="NHWC"?l.shape[3]:l.shape[1];P(d===a.shape[2],()=>`Error in conv2dDerInput: depth of input (${d}) 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]}.`),Mn("conv2dDerInput",r,i);let p={dy:l,filter:a},h={strides:n,pad:r,dataFormat:s,dimRoundingMode:i,inputShape:o},m=L.runKernel(Ki,p,h);return u?Q(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Gb=z({conv2DBackpropInput_:BE});function VE(e,t,a,n,r,s){let i=R(e,"x","conv2dTranspose"),o=R(t,"filter","conv2dTranspose");return Gb(a,i,o,n,r,"NHWC",s)}var Hb=z({conv2dTranspose_:VE});function UE(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=Q(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($r(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.`),P(Ii(s),()=>"Error in conv3D: Dilated rates should be larger than 0."),P(Ii(a),()=>"Error in conv3D: Strides should be larger than 0.");let d={x:l,filter:o},c={strides:a,pad:n,dataFormat:r,dilations:s},p=L.runKernel(Yi,d,c);return u?Q(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var jb=z({conv3d_:UE});function GE(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=Q(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 d={dy:i,filter:a},c={pad:r,strides:n,inputShape:s},p=L.runKernel(Zi,d,c);return o?Q(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var HE=z({conv3DBackpropInput_:GE});function jE(e,t,a,n,r){let s=R(e,"x","conv3dTranspose"),i=R(t,"filter","conv3dTranspose");return HE(a,s,i,n,r)}var qb=z({conv3dTranspose_:jE});function qE(e){let t={x:R(e,"x","cos","float32")};return L.runKernel(Ji,t)}var Xb=z({cos_:qE});function XE(e){let t={x:R(e,"x","cosh","float32")};return L.runKernel(Qi,t)}var Kb=z({cosh_:XE});function KE(e,t=0,a=!1,n=!1){let r={x:R(e,"x","cumprod")},s={axis:t,exclusive:a,reverse:n};return L.runKernel(eo,r,s)}var Yb=z({cumprod_:KE});function YE(e,t=0,a=!1,n=!1){let r={x:R(e,"x","cumsum")},s={axis:t,exclusive:a,reverse:n};return L.runKernel(to,r,s)}var Zb=z({cumsum_:YE});function ZE(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 L.runKernel(bu,i,o)}var Jb=z({denseBincount_:ZE});function JE(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 L.runKernel(no,o,l)}var Qb=z({depthToSpace_:JE});function QE(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,d=!1;o.rank===3&&(d=!0,u=Q(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]}.`),Mn("depthwiseConv2d",n,i);let p={x:u,filter:l},h={strides:a,pad:n,dataFormat:r,dilations:s,dimRoundingMode:i},m=L.runKernel(ro,p,h);return d?Q(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Gh=z({depthwiseConv2d_:QE});function eM(e){let t={x:R(e,"x","diag")};return L.runKernel(vu,t)}var e4=z({diag_:eM});function tM(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=Q(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=!0),P(l.shape[3]===o.shape[2],()=>`Error in dilation2d: input and filter must have the same depth: ${l.shape[3]} vs ${o.shape[2]}`);let d={x:l,filter:o},c={strides:a,pad:n,dilations:r},p=L.runKernel(so,d,c);return u?Q(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var t4=z({dilation2d_:tM}),ul={};Ke(ul,{assertAndGetBroadcastShape:()=>Ut,getBroadcastDims:()=>a4,getReductionAxes:()=>Ig});function a4(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 Ig(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 Ut(e,t){let a=Math.max(e.length,t.length),n=new Array(a);for(let r=0;r<a;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)n[a-r-1]=i;else if(i===1)n[a-r-1]=s;else if(s!==i){let o=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(o)}else n[a-r-1]=s}return n}function aM(e,t){let a=R(e,"a","equal","string_or_numeric"),n=R(t,"b","equal","string_or_numeric");[a,n]=Et(a,n),Ut(a.shape,n.shape);let r={a,b:n};return L.runKernel(ms,r)}var Sg=z({equal_:aM});function nM(e,t,a){let n=R(t,"a","where"),r=R(a,"b","where"),s=R(e,"condition","where","bool"),i=Ut(Ut(s.shape,n.shape),r.shape),o=Ai(s,i),l=Ai(n,i),u=Ai(r,i),d={condition:o,t:l,e:u};return L.runKernel(Ou,d)}var Cr=z({where_:nM});function rM(e){let t={x:R(e,"x","zerosLike")};return L.runKernel(qu,t)}var en=z({zerosLike_:rM});function sM(e,t){let a=R(e,"a","div"),n=R(t,"b","div");[a,n]=Et(a,n);let r=ve(a,n),s=en(r),i=Sg(n,s);return Cr(i,s,r)}var n4=z({divNoNan_:sM});function iM(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=Q(a,[1,-1]),o=Q(n,[-1,1]),l=pt(i,o);return Q(l,[])}else if(a.rank===1&&n.rank===2){let i=Q(a,[1,-1]),o=Q(n,[n.shape[0],n.shape[1]]),l=pt(i,o);return Q(l,[l.size])}else if(a.rank===2&&n.rank===1){let i=Q(n,[-1,1]),o=pt(a,i);return Q(o,[o.size])}else{let i=Q(n,[n.shape[0],n.shape[1]]);return pt(a,i)}}var r4=z({dot_:iM});function oM(e,...t){let a=t.map((r,s)=>R(r,`tensors${s}`,"einsum")),n={equation:e};return L.runKernel(Ip,a,n)}var hi=z({einsum_:oM});function lM(e){let t={x:R(e,"x","elu","float32")};return L.runKernel(oo,t)}var Tg=z({elu_:lM});function uM(e,t){let a=R(e,"x","ensureShape","string_or_numeric");if(!DA(a.shape,t))throw new Error(`EnsureShape: Shape of tensor ${a.shape} is not compatible with expected shape ${t}`);return e}var s4=z({ensureShape_:uM});function dM(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=Ue(t,"float32"));let a={x:t};return L.runKernel(lo,a)}var i4=z({erf_:dM});function Cg(e,t){for(let a=0;a<e.length;++a)if(e[e.length-a-1]!==t-1-a)return!1;return!0}function o4(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 pM(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 Xp(e,t){let a=t.map(n=>1);return o4(e,a,t)}function cM(e,t,a){P(Cg(t,a),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${a} input.`)}function hM(e,t){if(Cg(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 mM(e){return e.map((t,a)=>[a,t]).sort((t,a)=>t[1]-a[1]).map(t=>t[0])}function fM(e,t){let a=[];for(let n=t-e;n<t;++n)a.push(n);return a}function gM(e,t=null,a=!1){let n={x:R(e,"x","max")},r={reductionIndices:t,keepDims:a};return L.runKernel(Io,n,r)}var fa=z({max_:gM});function yM(e,t=null,a=!1){let n={x:R(e,"x","min")},r={axis:t,keepDims:a};return L.runKernel(Co,n,r)}var os=z({min_:yM});function xM(e,t){let a=R(e,"base","pow"),n=R(t,"exp","pow");[a,n]=Et(a,n);let r={a,b:n};return L.runKernel(Po,r)}var tu=z({pow_:xM});function Ge(e,t){if((Jt(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"&&Jt(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Ps(e,[],[],t)}function AM(e){let t={x:R(e,"x","sqrt","float32")};return L.runKernel(Es,t)}var nr=z({sqrt_:AM});function bM(e){let t=R(e,"x","square"),a={};return L.runKernel("Square",{x:t},a)}var En=z({square_:bM});function vM(e,t=null,a=!1){let n=R(e,"x","sum");n.dtype==="bool"&&(n=Ue(n,"int32"));let r={x:n},s={axis:t,keepDims:a};return L.runKernel(Qo,r,s)}var ot=z({sum_:vM});function wM(e,t="euclidean",a=null,n=!1){e=R(e,"x","norm");let r=l4(e,t,a),s=r.shape;if(n){let i=mp(a,e.shape);s=Xp(r.shape,i)}return Q(r,s)}function l4(e,t,a=null){if(e.rank===0)return Ja(e);if(e.rank!==1&&a===null)return l4(Q(e,[-1]),t,a);if(e.rank===1||typeof a=="number"||Array.isArray(a)&&a.length===1){if(t===1)return ot(Ja(e),a);if(t===1/0)return fa(Ja(e),a);if(t===-1/0)return os(Ja(e),a);if(t==="euclidean"||t===2)return nr(ot(tu(Ja(e),Ge(2,"int32")),a));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(a)&&a.length===2){if(t===1)return fa(ot(Ja(e),a[0]),a[1]-1);if(t===1/0)return fa(ot(Ja(e),a[1]),a[0]);if(t===-1/0)return os(ot(Ja(e),a[1]),a[0]);if(t==="fro"||t==="euclidean")return nr(ot(En(e),a));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${a}`)}var Kp=z({norm_:wM});function kM(e,t=null,a=!1){return Kp(e,"euclidean",t,a)}var u4=z({euclideanNorm_:kM});function IM(e){let t={x:R(e,"x","exp")};return L.runKernel(fs,t)}var ls=z({exp_:IM});function SM(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 L.runKernel(ku,n,r)}var Bt=z({expandDims_:SM});function TM(e){let t={x:R(e,"x","expm1")};return L.runKernel(gs,t)}var d4=z({expm1_:TM});function CM(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 L.runKernel($s,n,r)}var Qr=z({tile_:CM});function NM(e,t,a,n="float32"){t==null&&(t=e);let r=Te([e,t],n),s=e<=t?e:t;for(let o=0;o<s;++o)r.set(1,o,o);let i=Q(r.toTensor(),[e,t]);if(a==null)return i;if(a.length===1)return Qr(Bt(i,0),[a[0],1,1]);if(a.length===2)return Qr(Bt(Bt(i,0),0),[a[0],a[1],1,1]);if(a.length===3)return Qr(Bt(Bt(Bt(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 Ng=z({eye_:NM});function RM(e){let t={x:R(e,"x","floor","float32")};return L.runKernel(ys,t)}var Rg=z({floor_:RM});function EM(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 L.runKernel(Su,i,o)}var Eg=z({gather_:EM});function MM(e,t){let a=R(e,"a","greater","string_or_numeric"),n=R(t,"b","greater","string_or_numeric");[a,n]=Et(a,n),Ut(a.shape,n.shape);let r={a,b:n};return L.runKernel(As,r)}var Yp=z({greater_:MM});function FM(e,t){let a=R(e,"a","greaterEqual","string_or_numeric"),n=R(t,"b","greaterEqual","string_or_numeric");[a,n]=Et(a,n),Ut(a.shape,n.shape);let r={a,b:n};return L.runKernel(bs,r)}var Mg=z({greaterEqual_:FM});function $M(e){let t={input:R(e,"input","imag")};return L.runKernel(Cp,t)}var Zp=z({imag_:$M});function DM(e){let t={x:R(e,"x","isFinite")};return L.runKernel(mo,t)}var p4=z({isFinite_:DM});function PM(e){let t={x:R(e,"x","isInf")};return L.runKernel(fo,t)}var c4=z({isInf_:PM});function _M(e){let t={x:R(e,"x","isNaN")};return L.runKernel(go,t)}var h4=z({isNaN_:_M});function OM(e,t=.2){let a={x:R(e,"x","leakyRelu")},n={alpha:t};return L.runKernel(yo,a,n)}var Fg=z({leakyRelu_:OM});function zM(e,t){let a=R(e,"a","less","string_or_numeric"),n=R(t,"b","less","string_or_numeric");[a,n]=Et(a,n),Ut(a.shape,n.shape);let r={a,b:n};return L.runKernel(vs,r)}var bh=z({less_:zM});function LM(e,t){let a=R(e,"a","lessEqual","string_or_numeric"),n=R(t,"b","lessEqual","string_or_numeric");[a,n]=Et(a,n),Ut(a.shape,n.shape);let r={a,b:n};return L.runKernel(ws,r)}var Hh=z({lessEqual_:LM});function m4(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 L.runKernel(xo,{},n)}function WM(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(Zl(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=s,o=!1;s.rank===3&&(o=!0,i=Q(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:i},u={depthRadius:t,bias:a,alpha:n,beta:r},d=L.runKernel(ko,l,u);return o?Q(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var f4=z({localResponseNormalization_:WM});function BM(e){let t={x:R(e,"x","log","float32")};return L.runKernel(ks,t)}var au=z({log_:BM});function VM(e){let t={x:R(e,"x","log1p")};return L.runKernel(Ao,t)}var $g=z({log1p_:VM});function UM(e){return P(es(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 L.tidy(()=>{let{value:s,grads:i}=L.gradients(()=>e(n),[n],r);return r!=null&&Ca(s.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),jh(i),i[0]})}}function GM(e){return P(es(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=Zd(t,"args","tf.grads","string_or_numeric"),r=a!=null?R(a,"dy","tf.grads"):null;return L.tidy(()=>{let{value:s,grads:i}=L.gradients(()=>e(...n),n,r);return r!=null&&Ca(s.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),jh(i),i})}}function HM(e){return P(es(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,a)=>{P(t instanceof yt,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),P(a==null||a instanceof yt,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:n,value:r}=L.gradients(()=>e(t),[t],a);return jh(n),{grad:n[0],value:r}}}function jM(e){return P(es(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,a)=>{P(Array.isArray(t)&&t.every(r=>r instanceof yt),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),P(a==null||a instanceof yt,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let n=L.gradients(()=>e(...t),t,a);return a!=null&&Ca(n.value.shape,a.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),jh(n.grads),n}}function g4(e,t){P(es(e),()=>"The f passed in variableGrads(f) must be a function"),P(t==null||Array.isArray(t)&&t.every(u=>u instanceof Yd),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let a=t!=null;if(!a){t=[];for(let u in L.registeredVariables)t.push(L.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}=L.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,d)=>{o[d]!=null&&(l[u.name]=o[d])}),n!=null&&n.forEach(u=>l[u.name]=null),{value:i,grads:l}}function rr(e){return L.customGrad(e)}function jh(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 qM(e){let t={x:R(e,"x","neg")};return L.runKernel(Ru,t)}var Vn=z({neg_:qM});function XM(e){let t={x:R(e,"x","softplus")};return L.runKernel(Jo,t)}var Dg=z({softplus_:XM});function KM(e){let t=R(e,"x","logSigmoid");return rr(a=>({value:Vn(Dg(Vn(a))),gradFunc:n=>te(n,za(Vn(a)))}))(t)}var y4=z({logSigmoid_:KM});function YM(e,t){let a=R(e,"a","sub"),n=R(t,"b","sub");[a,n]=Et(a,n);let r={a,b:n};return L.runKernel(Fs,r)}var xe=z({sub_:YM});function ZM(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 rr((n,r)=>{let s=fa(n,t,!0),i=xe(n,s),o=xe(Ue(i,"float32"),au(ot(ls(i),t,!0)));return r([o]),{value:o,gradFunc:(l,u)=>{let[d]=u,c=!0,p=ls(d);return xe(l,te(ot(l,t,c),p))}}})(a)}var x4=z({logSoftmax_:ZM});function JM(e,t=null,a=!1){let n=R(e,"x","logSumExp"),r=mp(t,n.shape),s=fa(n,r,!0),i=xe(n,s),o=ls(i),l=ot(o,r),u=au(l),d=we(Q(s,u.shape),u);if(a){let c=Xp(d.shape,r);return Q(d,c)}return d}var Pg=z({logSumExp_:JM});function QM(e,t){let a=R(e,"a","logicalAnd","bool"),n=R(t,"b","logicalAnd","bool");Ut(a.shape,n.shape);let r={a,b:n};return L.runKernel(bo,r)}var tp=z({logicalAnd_:QM});function eF(e){let t={x:R(e,"x","logicalNot","bool")};return L.runKernel(vo,t)}var _g=z({logicalNot_:eF});function tF(e,t){let a=R(e,"a","logicalOr","bool"),n=R(t,"b","logicalOr","bool");Ut(a.shape,n.shape);let r={a,b:n};return L.runKernel(wo,r)}var Og=z({logicalOr_:tF});function aF(e,t){let a=R(e,"a","logicalXor","bool"),n=R(t,"b","logicalXor","bool");return Ut(a.shape,n.shape),tp(Og(e,t),_g(tp(e,t)))}var A4=z({logicalXor_:aF}),eh=2147483648;function nF(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=Q(n,[-1,s]),l=Q(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(mt(l.shape)>=eh)throw new Error(`values tensor size must less than ${eh}`);if(o.shape[1]>=eh)throw new Error(`trailing dim_size must less than ${eh} for int32 output type, was ${o.shape[1]}`);let u={sortedSequence:o,values:l},d={side:a};return L.runKernel(qo,u,d)}var qh=z({searchSorted_:nF});function b4(e,t){return qh(e,t,"left")}function rF(e,t,a,n,r){let s=R(e,"x","maxPool"),i=1,o=s,l=!1;s.rank===3&&(l=!0,o=Q(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($r(a,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${i}'`),Mn("maxPool",n,r);let u={x:o},d={filterSize:t,strides:a,pad:n,dimRoundingMode:r},c=L.runKernel(So,u,d);return l?Q(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var zg=z({maxPool_:rF});function sF(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=Q(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}`),Mn("maxPool3d",n,r);let u={x:o},d={filterSize:t,strides:a,pad:n,dimRoundingMode:r,dataFormat:s},c=L.runKernel(Cu,u,d);return l?Q(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var v4=z({maxPool3d_:sF});function iF(e,t,a,n,r=!1){let s={x:R(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:a,pad:n,includeBatchInIndex:r},o=L.runKernel(Nu,s,i);return{result:o[0],indexes:o[1]}}var w4=z({maxPoolWithArgmax_:iF});function oF(e,t){let a=R(e,"a","maximum"),n=R(t,"b","maximum");[a,n]=Et(a,n),a.dtype==="bool"&&(a=Ue(a,"int32"),n=Ue(n,"int32")),Ut(a.shape,n.shape);let r={a,b:n};return L.runKernel(Is,r)}var Lg=z({maximum_:oF});function lF(e,t=null,a=!1){let n={x:R(e,"x","mean")},r={axis:t,keepDims:a};return L.runKernel(To,n,r)}var ap=z({mean_:lF});function An(e,t="float32"){if(nn(e),t==="complex64"){let n=An(e,"float32"),r=An(e,"float32");return Rr(n,r)}let a=Oh(mt(e),t);return L.makeTensor(a,e,t)}function Yr(e,t="float32"){if(nn(e),t==="complex64"){let n=Yr(e,"float32"),r=An(e,"float32");return Rr(n,r)}let a=og(mt(e),t);return L.makeTensor(a,e,t)}function k4(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 yt?e.dtype:"float32");if(t===void 0)return[n];let r=R(t,"y","meshgrid",t instanceof yt?t.dtype:"float32"),s=mt(n.shape),i=mt(r.shape);return a==="xy"?(n=Q(n,[1,-1]),r=Q(r,[-1,1]),[pt(Yr([i,1],n.dtype),n),pt(r,Yr([1,s],r.dtype))]):(n=Q(n,[-1,1]),r=Q(r,[1,-1]),[pt(n,Yr([1,i],n.dtype)),pt(Yr([s,1],r.dtype),r)])}function uF(e,t){let a=R(e,"a","minimum"),n=R(t,"b","minimum");[a,n]=Et(a,n),a.dtype==="bool"&&(a=Ue(a,"int32"),n=Ue(n,"int32")),Ut(a.shape,n.shape);let r={a,b:n};return L.runKernel(Ss,r)}var np=z({minimum_:uF});function dF(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 L.runKernel(No,i,s)}var I4=z({mirrorPad_:dF});function pF(e,t){let a=R(e,"a","mod"),n=R(t,"b","mod");[a,n]=Et(a,n);let r={a,b:n};return L.runKernel(Ro,r)}var Ku=z({mod_:pF});function cF(e,t=null,a=!1){e=R(e,"x","moments");let n=mp(t,e.shape),r=ap(e,n,a),s=r.shape;a||(s=Xp(r.shape,n));let i=En(xe(Ue(e,"float32"),Q(r,s))),o=ap(i,n,a);return{mean:r,variance:o}}var S4=z({moments_:cF});function hF(e,t,a,n){let r=R(t,"data","multiRNNCell"),s=Zd(a,"c","multiRNNCell"),i=Zd(n,"h","multiRNNCell"),o=r,l=[];for(let c=0;c<e.length;c++){let p=e[c](o,s[c],i[c]);l.push(p[0]),l.push(p[1]),o=p[1]}let u=[],d=[];for(let c=0;c<l.length;c+=2)u.push(l[c]),d.push(l[c+1]);return[u,d]}var T4=z({multiRNNCell_:hF});function mF(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?Q(r,[1,-1]):r},l={numSamples:t,seed:a,normalized:n},u=L.runKernel(Eo,o,l);return i===1?Q(u,[u.size]):u}var C4=z({multinomial_:mF});function fF(e,t){let a=R(e,"a","notEqual","string_or_numeric"),n=R(t,"b","notEqual","string_or_numeric");[a,n]=Et(a,n),Ut(a.shape,n.shape);let r={a,b:n};return L.runKernel(Cs,r)}var Wg=z({notEqual_:fF});function gF(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 L.runKernel($o,s,i)}var vh=z({oneHot_:gF});function yF(e){let t={x:R(e,"x","onesLike")};return L.runKernel(Mu,t)}var N4=z({onesLike_:yF});function xF(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=Q(a,[-1,1]),s=Q(n,[1,-1]);return pt(r,s)}var R4=z({outerProduct_:xF});function AF(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 L.runKernel(Do,s,r)}var ur=z({pad_:AF});function bF(e,t,a=0){return P(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),ur(e,[t],a)}var E4=z({pad1d_:bF});function vF(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."),ur(e,t,a)}var M4=z({pad2d_:vF});function wF(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."),ur(e,t,a)}var F4=z({pad3d_:wF});function kF(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."),ur(e,t,a)}var $4=z({pad4d_:kF});function IF(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 L.runKernel(Lu,r,s)}var Bg=z({spaceToBatchND_:IF});function SF(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=Q(o,[1,o.shape[0],o.shape[1],o.shape[2]])),P($r(s,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`);let d=Nb(l.shape,t,s,r,n),c=[d.dilationHeight,d.dilationWidth],p;n==="same"?p=CF([d.filterHeight,d.filterWidth],c):p=[[0,0],[0,0]];let h=c[0]===1&&c[1]===1,[m,f]=TF([d.inHeight,d.inWidth],c,p),g=h?n:"valid",y=h?l:Bg(l,c,m),x=(a==="avg"?()=>vg(y,t,s,g,i):()=>zg(y,t,s,g,i))(),A=h?x:wg(x,c,f);return u?Q(A,[A.shape[1],A.shape[2],A.shape[3]]):A}function TF(e,t,a){let n=a.map(d=>d[0]),r=a.map(d=>d[1]),s=e.concat(n,r),i=t.map((d,c)=>(d-s[c]%d)%d),o=r.map((d,c)=>d+i[c]),l=t.map((d,c)=>[n[c],o[c]]),u=t.map((d,c)=>[0,i[c]]);return[l,u]}function CF(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 D4=z({pool_:SF});function NF(e,t){let a=R(e,"x","prelu"),n=R(t,"alpha","prelu"),r={x:a,alpha:n};return L.runKernel(_o,r)}var Vg=z({prelu_:NF});function RF(e,t=null,a=!1){let n=R(e,"x","prod");n.dtype==="bool"&&(n=Ue(n,"int32"));let r={x:n},s={axis:t,keepDims:a};return L.runKernel(Oo,r,s)}var P4=z({prod_:RF});function EF(e,t,a,n){let r=e.map((d,c)=>R(d,`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=L.runKernel(Lh,o,l);return{outputNestedSplits:u.slice(0,u.length-1),outputDenseValues:u[u.length-1]}}var _4=z({raggedGather_:EF});function MF(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=L.runKernel(Wh,i);return{rtNestedSplits:o[0],rtDenseValues:o[1]}}var O4=z({raggedRange_:MF});function FF(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,p)=>R(c,`tensors${p}`,"raggedTensorToTensor","int32")),u={shape:s,values:i,defaultValue:o,rowPartitionTensors:l},d={rowPartitionTypes:r};return L.runKernel(Bh,u,d)}var z4=z({raggedTensorToTensor_:FF});function $F(e,t,a){nn(e);let n=mt(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 L.makeTensor(r,e,a)}var L4=z({rand_:$F}),Ug=uu(EA()),W4={};Ke(W4,{TEST_EPSILON_FLOAT16:()=>B4,createVideoElement:()=>BF,encodeStrings:()=>V4,expectArrayBuffersEqual:()=>WF,expectArraysClose:()=>PF,expectArraysEqual:()=>OF,expectNumbersClose:()=>zF,expectPromiseToFail:()=>_F,expectValuesInRange:()=>LF,play:()=>VF,testEpsilon:()=>Gg});var DF=.001,B4=.1;function PF(e,t,a){return a==null&&(a=Gg()),v1(e,t,(n,r)=>Hg(n,r,a))}function Gg(){return L.backend.floatPrecision()===32?DF:B4}function v1(e,t,a){let n=!0;if((Jt(e)||Jt(t))&&(n=!1),Jt(e)&&Jt(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=ar(e),o=ar(t);if(!Er(i,o))throw new Error(`Arrays have different shapes. Actual: [${i}]. Expected: [${o}]`)}let r=Jt(e)?e:rs(e),s=Jt(t)?t:rs(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 _F(e,t){e().then(()=>t.fail(),()=>t()),typeof expect!="undefined"&&expect().nothing()}function OF(e,t){let a=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Xr(e)||Xr(e[0])||Xr(t)||Xr(t[0])?v1(e,a,(n,r)=>n==r):v1(e,t,(n,r)=>Hg(n,r,0))}function zF(e,t,a){if(a==null&&(a=Gg()),!Hg(e,t,a))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`);typeof expect!="undefined"&&expect().nothing()}function Hg(e,t,a){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>a)}function LF(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 WF(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 V4(e){for(let t=0;t<e.length;t++){let a=e[t];Array.isArray(a)?V4(a):e[t]=zp(a)}return e}function BF(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 VF(e){await e.play(),"requestVideoFrameCallback"in e&&await new Promise(t=>{e.requestVideoFrameCallback(t)})}var jg=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=Ug.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}},UF=class{constructor(e,t,a,n){this.alpha=e,this.beta=1/t,this.dtype=a;let r=n||Math.random();this.randu=Ug.alea(r.toString()),this.randn=new jg(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)}},GF=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=Ug.alea(n)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function HF(e,t,a=1,n="float32",r){if(nn(e),a==null&&(a=1),n==null&&(n="float32"),n!=="float32"&&n!=="int32")throw new Error(`Unsupported data type ${n}`);let s=new UF(t,a,n,r),i=Te(e,n);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var U4=z({randomGamma_:HF});function jF(e,t=0,a=1,n,r){if(nn(e),n!=null&&n==="bool")throw new Error(`Unsupported data type ${n}`);let s=new jg(t,a,n,!1,r),i=Te(e,n);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var qg=z({randomNormal_:jF});function qF(e,t,a){if(t!=null&&t==="bool")throw new Error(`Unsupported data type ${t}`);return qg(e,0,1,t,a)}var G4=z({randomStandardNormal_:qF});function XF(e,t=0,a=1,n="float32",r){nn(e);let s=Te(e,n),i=new GF(t,a,null,r);for(let o=0;o<s.values.length;o++)s.values[o]=i.nextValue();return s.toTensor()}var Xh=z({randomUniform_:XF});function KF(e,t,a,n){return Xh(e,t,a,"int32",n)}var H4=z({randomUniformInt_:KF});function nu(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 L.runKernel($u,{},r)}function YF(e){let t={input:R(e,"input","real")};return L.runKernel(Ep,t)}var ru=z({real_:YF});function ZF(e){let t={x:R(e,"x","reciprocal")};return L.runKernel(zo,t)}var j4=z({reciprocal_:ZF});function JF(e){let t={x:R(e,"x","relu")};return L.runKernel(Lo,t)}var Jp=z({relu_:JF});function QF(e){let t={x:R(e,"x","relu6")};return L.runKernel(Vo,t)}var Xg=z({relu6_:QF});function e$(e,t){let a={x:R(e,"x","reverse")},n={dims:t};return L.runKernel(Uo,a,n)}var us=z({reverse_:e$});function t$(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}.`),us(t,0)}var q4=z({reverse1d_:t$});function a$(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}.`),us(a,t)}var X4=z({reverse2d_:a$});function n$(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}.`),us(a,t)}var K4=z({reverse3d_:n$});function r$(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}.`),us(a,t)}var Y4=z({reverse4d_:r$});function s$(e){let t={x:R(e,"x","round")};return L.runKernel(Go,t)}var Kg=z({round_:s$});function i$(e){let t={x:R(e,"x","rsqrt","float32")};return L.runKernel(Ns,t)}var Z4=z({rsqrt_:i$});function o$(e){let t={x:R(e,"x","selu")};return L.runKernel(Xo,t)}var J4=z({selu_:o$});function l$(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"),d=o,c=!1;if(o.rank===3&&(c=!0,d=Q(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(d.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${d.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 p=l.shape[2],h=l.shape[3];P(u.shape[2]===p*h,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*h}, but got ${u.shape[2]}.`);let m=Gh(d,l,n,r,i,s),f=qp(m,u,1,"valid",i);return c?Q(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Q4=z({separableConv2d_:l$});async function u$(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 d=0;d<r.length;d++)i.has(r[d])||o++;let l=new Rt([o],a.dtype),u=new Rt([o],"int32");for(let d=0,c=0;d<r.length;d++)i.has(r[d])||(l.values[c]=r[d],u.values[c]=d,c++);return[l.toTensor(),u.toTensor()]}var e7=u$;function d$(e){let t={x:R(e,"x","sign")};return L.runKernel(Zo,t)}var t7=z({sign_:d$});function p$(e){let t={x:R(e,"x","sin","float32")};return L.runKernel(Ko,t)}var a7=z({sin_:p$});function c$(e){let t={x:R(e,"x","sinh")};return L.runKernel(Yo,t)}var n7=z({sinh_:c$});function h$(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`),_e(n,[t],[a])}var r7=z({slice1d_:h$});function m$(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`),_e(n,t,a)}var s7=z({slice2d_:m$});function f$(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`),_e(n,t,a)}var Qp=z({slice3d_:f$});function g$(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`),_e(n,t,a)}var Kh=z({slice4d_:g$});function y$(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 L.runKernel(el,n,r)}var Yh=z({softmax_:y$});function x$(e){P(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return L.runKernel(Sp,t)}var Zh=z({fft_:x$});function A$(e){P(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return L.runKernel(Tp,t)}var rp=z({ifft_:A$});function b$(e){let t=e.shape[e.shape.length-1],a=e.size/t,n;if(t<=2){let r=Q(e,[a,t]);n=rp(r)}else{let r=[a,2*(t-1)],s=Q(ru(e),[a,t]),i=Q(Zp(e),[a,t]),o=us(_e(s,[0,1],[a,t-2]),1),l=te(us(_e(i,[0,1],[a,t-2]),1),Ge(-1)),u=lt([s,o],1),d=lt([i,l],1),c=Q(Rr(u,d),[r[0],r[1]]);n=rp(c)}if(n=ru(n),e.rank===3&&e.shape[0]!==0){let r=n,s=e.shape[0];n=Q(n,[s,n.shape[0]/s,n.shape[1]]),r.dispose()}return n}var Yg=z({irfft_:b$});function v$(e,t,a=0){let n={x:R(e,"x","split")},r={numOrSizeSplits:t,axis:a};return L.runKernel(Wu,n,r)}var Sa=z({split_:v$});function w$(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 m=e.shape.map(g=>0),f=e.shape.map(g=>g);f[e.shape.length-1]=t,r=_e(e,m,f),a=t}else if(t!=null&&t>a){let m=e.shape.map(f=>f);m[e.shape.length-1]=t-a,r=lt([e,An(m)],e.shape.length-1),a=t}else r=e;let s=en(r),i=Q(Rr(r,s),[n,a]),o=Zh(i),l=Math.floor(a/2)+1,u=ru(o),d=Zp(o),c=Sa(u,[l,a-l],u.shape.length-1),p=Sa(d,[l,a-l],d.shape.length-1),h=r.shape.slice();return h[r.shape.length-1]=l,Q(Rr(c[0],p[0]),h)}var Jh=z({rfft_:w$});function k$(e,t){let a=R(e,"a","squaredDifference"),n=R(t,"b","squaredDifference");[a,n]=Et(a,n),Ut(a.shape,n.shape);let r={a,b:n},s={};return L.runKernel(Ms,r,s)}var Zg=z({squaredDifference_:k$});function I$(e,t){let a=R(e,"x","squeeze","string_or_numeric");return Q(a,PA(a.shape,t).newShape)}var Oe=z({squeeze_:I$});function S$(e,t=0){let a=Zd(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 L.runKernel(Fu,n,r)}var ca=z({stack_:S$});function T$(e,t=0){let a={x:R(e,"x","step")},n={alpha:t};return L.runKernel(Ds,a,n)}var Jg=z({step_:T$});function C$(e,t,a,n,r=0,s=0,i=0,o=0,l=0){let u={x:R(e,"x","stridedSlice","string_or_numeric")},d={begin:t,end:a,strides:n,beginMask:r,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return L.runKernel(al,u,d)}var i7=z({stridedSlice_:C$});function N$(e){let t={x:R(e,"x","tan","float32")};return L.runKernel(nl,t)}var o7=z({tan_:N$});function Vt(e,t){Fi(e);let a=ar(e,t);if(a.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Ps(e,null,a,t)}function er(e,t,a){if(Fi(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let n=ar(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 Ps(e,t,n,a)}function Qg(e,t,a){if(Fi(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let n=ar(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 Ps(e,t,n,a)}function l7(e,t,a){if(Fi(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let n=ar(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 Ps(e,t,n,a)}function u7(e,t,a){if(Fi(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let n=ar(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 Ps(e,t,n,a)}function d7(e,t,a){if(Fi(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let n=ar(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,Ps(e,t,n,a)}var Qh={};Ke(Qh,{calculateShapes:()=>p7,validateInput:()=>e0,validateUpdateShape:()=>e3});function e3(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 e0(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}`)}e3(a,t,e)}function p7(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=mt(t.shape)/o,u=[...pu(a.slice(0,r)),1],d=mt(a);return{sliceRank:r,numUpdates:l,sliceSize:i,strides:u,outputSize:d}}function R$(e,t,a){let n=R(e,"tensor","tensorScatterupdate"),r=R(t,"indices","tensorScatterupdate","int32"),s=R(a,"updates","tensorScatterupdate");if(e0(s,r,n.shape),n.dtype!==s.dtype)throw new Error(`tensor and updates must have the same dtype, instead they are ${n.dtype} and ${s.dtype}.`);let i={tensor:n,indices:r,updates:s},o={};return L.runKernel(jo,i,o)}var c7=z({tensorScatterUpdate_:R$});function E$(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]=L.runKernel(sl,s,i);return{values:o,indices:l}}var h7=z({topk_:E$});function M$(e,t=0,a=1,n,r){if(nn(e),n!=null&&n==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new jg(t,a,n,!0,r),i=Te(e,n);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var m7=z({truncatedNormal_:M$});function F$(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]=L.runKernel(Pp,n,r);return{values:s,indices:i}}var f7=z({unique_:F$});function $$(e,t,a){let n=R(e,"x","unsortedSegmentSum"),r=R(t,"segmentIds","unsortedSegmentSum","int32");P(Zl(a),()=>"numSegments must be of dtype int");let s={x:n,segmentIds:r},i={numSegments:a};return L.runKernel(_p,s,i)}var g7=z({unsortedSegmentSum_:$$});function D$(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 L.runKernel(ju,n,r)}var Na=z({unstack_:D$});function y7(e,t){return qh(e,t,"right")}function x7(e,t=!0,a,n){return L.makeVariable(e,t,a,n)}function A7(e,t){let a=[];for(let s=0;s<t.length;s++)t[s]&&a.push(s);let n=Te(e,"int32"),r=Te([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 P$(e){let t=R(e,"condition","whereAsync","bool"),a=await t.data(),n=A7(t.shape,a);return e!==t&&t.dispose(),n}var t3=P$;async function _$(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"),Ca(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 f=s;f<s+i;f++)l*=o[f];let u=o.slice(0,s).concat([l],o.slice(s+i)),d=Q(n,u),c=Q(r,[-1]),p=await t3(c),h=Oe(p,[1]),m=Eg(d,h,s);return e!==n&&n.dispose(),t!==r&&r.dispose(),h.dispose(),d.dispose(),c.dispose(),p.dispose(),m}var b7=_$;function O$(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"?Pe(()=>{let i=ru(n),o=Zp(n);return i=L.runKernel(Tr,{x:i},s),o=L.runKernel(Tr,{x:o},s),a&&(o=Vn(o)),Rr(i,o)}):L.runKernel(Tr,r,s)}var Si=z({transpose_:O$});function z$(e,t,a,n,r=!0){let s=R(e,"v","movingAverage"),i=R(t,"x","movingAverage"),o=R(a,"decay","movingAverage");eb(s,i),P(Er(s.shape,i.shape),()=>"Shape mismatch in v and x");let l=Ge(1),u=xe(l,o),d=te(xe(i,s),u);if(r){P(n!=null,()=>"When using zeroDebias: true, step is required.");let c=R(n,"step","movingAverage");d=ve(d,xe(l,tu(o,c)))}return we(s,d)}var v7=z({movingAverage_:z$});function L$(e,t,a){nn(a);let n=R(e,"indices","scatterND","int32"),r=R(t,"updates","scatterND");e0(r,n,a);let s={indices:n,updates:r},i={shape:a};return L.runKernel(Ho,s,i)}var w7=z({scatterND_:L$});function W$(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 B$(e,t,a,n=0){nn(a);let r=R(e,"sparseIndices","sparseToDense","int32"),s=R(t,"sparseValues","sparseToDense","string_or_numeric"),i=R(n,"defaultValue","sparseToDense",s.dtype);W$(r,s,a,i);let o={sparseIndices:r,sparseValues:s,defaultValue:i},l={outputShape:a};return L.runKernel(tl,o,l)}var k7=z({sparseToDense_:B$});function V$(e,t){let a=R(t,"indices","gatherND","int32"),n={params:R(e,"x","gatherND","string_or_numeric"),indices:a};return L.runKernel(co,n)}var I7=z({gatherND_:V$});function U$(e,t){if(t==null)return e.shape.slice();if(Er(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 G$(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 yt?r.clone():r;let s=U$(r,a),i=1-t,o=ve(Rg(we(Xh(s,0,1,"float32",n),i)),i);return te(r,o)}var S7=z({dropout_:G$});function a3(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function t0(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 Vt(r,"float32")}async function H$(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}`),Ca(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],d=_A("bool",l);for(let c=0;c<l;c++){let p=c*u,h=i.subarray(p,p+u),m=[];for(let f=0;f<h.length;f++)m.push({value:h[f],index:f});m.sort((f,g)=>g.value-f.value),d[c]=0;for(let f=0;f<a;f++)if(m[f].index===o[c]){d[c]=1;break}}return e!==n&&n.dispose(),t!==r&&r.dispose(),Ve(d,r.shape,"bool")}var T7=H$,n3={};Ke(n3,{conv2d:()=>K$,depthwiseConv2d:()=>tD,matMul:()=>nD});function j$(e,t,a,n,r,s="NHWC",i){let o=e;e.rank===3&&(o=Q(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=Q(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],d=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(d===a[3],()=>`Error in conv2dDerFilter: depth of dy (${d}) must match output depth for filter (${a[3]}).`),Mn("conv2dDerFilter",r,i);let c={x:o,dy:l},p={strides:n,pad:r,dataFormat:s,dimRoundingMode:i,filterShape:a};return L.runKernel(bp,c,p)}var q$=z({conv2DBackpropFilter_:j$});function a0(e,t,a){if(a==null||a==="linear")return e;if(a==="relu")return te(e,Jg(t));throw new Error(`Cannot compute gradient for fused activation ${a}.`)}function n0(e,t){let a=t,n=Ig(e.shape,t.shape);return n.length>0&&(a=ot(a,n)),Q(a,e.shape)}function r0(e,t,a,n){if(t==="linear")return e;if(t==="relu")return Jp(e);if(t==="elu")return Tg(e);if(t==="relu6")return Xg(e);if(t==="prelu")return Vg(e,a);if(t==="leakyrelu")return Fg(e,n);if(t==="sigmoid")return za(e);throw new Error(`Unknown fused activation ${t}.`)}var s0=(e,t)=>!(e>0)||t==="linear";function X$({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:d}){if(l=l||"linear",s0(L.state.gradientDepth,l)===!1){P(r==="NHWC",()=>`Error in fused conv2d: got dataFormat of ${r} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);let S=qp(e,t,a,n,r,s,i);return o!=null&&(S=we(S,o)),r0(S,l,u,d)}let c=R(e,"x","conv2d","float32"),p=R(t,"filter","conv2d","float32"),h=c,m=!1;c.rank===3&&(m=!0,h=Q(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(p.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`),Mn("fused conv2d",n,i);let f=r==="NHWC"?h.shape[3]:h.shape[1];P(p.shape[2]===f,()=>`Error in conv2d: depth of input (${f}) must match input depth for filter ${p.shape[2]}.`),P($r(a,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${a} and dilations '${s}'`);let g=Hp(h.shape,p.shape,a,s,n,i),y;o!=null&&(y=R(o,"bias","fused conv2d"),[y]=Et(y,c),r==="NHWC"?Ut(g.outShape,y.shape):(P(y.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${y.shape.length}.`),P(y.shape.length===0||y.shape[0]===g.outChannels||y.shape[0]===1,()=>`Error in fused conv2d: bias shape (${y.shape}) is not compatible with the number of output channels (${g.outChannels})`)));let x;if(u!=null){let 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{Ut(S,g.outShape)}catch(C){let N=`Error in fused conv2d: PReLU activation weights (${S}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(N)}x=R(u,"prelu weights","fused conv2d")}let A=(S,C)=>{P(r==="NHWC",()=>`Error in gradient of fused conv2D: got dataFormat of ${r} but only NHWC is currently supported.`);let[N,M,F,E]=C,T=a0(S,F,l);P(ep(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let D=Gb(M.shape,T,N,a,n),O=q$(M,T,N.shape,a,n),W=[D,O];if(E!=null){let $=n0(E,T);W.push($)}return W},b={x:h,filter:p,bias:y,preluActivationWeights:x},w={strides:a,pad:n,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:d};return o==null?rr((S,C,N)=>{let M=L.runKernel(as,b,w);return N([C,S,M]),m&&(M=Q(M,[M.shape[1],M.shape[2],M.shape[3]])),{value:M,gradFunc:A}})(h,p):rr((S,C,N,M)=>{let F=L.runKernel(as,b,w);return M([C,S,F,N]),m&&(F=Q(F,[F.shape[1],F.shape[2],F.shape[3]])),{value:F,gradFunc:A}})(h,p,y)}var K$=z({fusedConv2d_:X$});function Y$(e,t,a,n,r,s=[1,1],i){let o=e;e.rank===3&&(o=Q(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=Q(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={x:o,dy:l},d={strides:n,pad:r,dimRoundingMode:i,dilations:s,filterShape:a};return L.runKernel(vp,u,d)}var Z$=z({depthwiseConv2dNativeBackpropFilter_:Y$});function J$(e,t,a,n,r,s=[1,1],i){let o=t,l=!1;t.rank===3&&(l=!0,o=Q(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={dy:o,filter:a},d={strides:n,pad:r,dimRoundingMode:i,dilations:s,inputShape:e},c=L.runKernel(wp,u,d);return l?Q(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var Q$=z({depthwiseConv2dNativeBackpropInput_:J$});function eD({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:d}){if(s0(L.state.gradientDepth,l)===!1){let w=Gh(e,t,a,n,r,s,i);return o!=null&&(w=we(w,o)),r0(w,l,u,d)}let c=R(e,"x","depthwiseConv2d","float32"),p=R(t,"filter","depthwiseConv2d","float32"),h=c,m=!1;c.rank===3&&(m=!0,h=Q(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(p.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`),P(h.shape[3]===p.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),s==null&&(s=[1,1]),P($r(a,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${s}'`),Mn("fused depthwiseConv2d",n,i);let f=Hp(h.shape,p.shape,a,s,n,i,!0),g;o!=null&&(g=R(o,"bias","fused conv2d"),[g]=Et(g,c),Ut(f.outShape,g.shape));let y;u!=null&&(y=R(u,"prelu weights","fused depthwiseConv2d"));let x=(w,S)=>{P(ep(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[C,N,M,F]=S,E=a0(w,M,l),T=Q$(N.shape,E,C,a,n,s,i),D=Z$(N,E,C.shape,a,n,s,i);if(F!=null){let O=n0(g,E);return[T,D,O]}return[T,D]},A={x:h,filter:p,bias:g,preluActivationWeights:y},b={strides:a,pad:n,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:d};return o==null?rr((w,S,C)=>{let N=L.runKernel(ns,A,b);return C([S,w,N]),m&&(N=Q(N,[N.shape[1],N.shape[2],N.shape[3]])),{value:N,gradFunc:x}})(h,p):rr((w,S,C,N)=>{let M=L.runKernel(ns,A,b);return N([S,w,M,C]),m&&(M=Q(M,[M.shape[1],M.shape[2],M.shape[3]])),{value:M,gradFunc:x}})(h,p,g)}var tD=z({fusedDepthwiseConv2d_:eD});function aD({a:e,b:t,transposeA:a=!1,transposeB:n=!1,bias:r,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:o=.2}){if(s0(L.state.gradientDepth,s)===!1){let F=pt(e,t,a,n);return r!=null&&(F=we(F,r)),r0(F,s,i,o)}let l=R(e,"a","fused matMul"),u=R(t,"b","fused matMul");[l,u]=Et(l,u);let d=a?l.shape[l.rank-2]:l.shape[l.rank-1],c=n?u.shape[u.rank-1]:u.shape[u.rank-2],p=a?l.shape[l.rank-1]:l.shape[l.rank-2],h=n?u.shape[u.rank-2]:u.shape[u.rank-1],m=l.shape.slice(0,-2),f=u.shape.slice(0,-2),g=mt(m),y=mt(f);P(d===c,()=>`Error in fused matMul: inner shapes (${d}) and (${c}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${a} and transposeB=${n} must match.`);let x=Ut(l.shape.slice(0,-2),u.shape.slice(0,-2)).concat([p,h]),A=a?Q(l,[g,d,p]):Q(l,[g,p,d]),b=n?Q(u,[y,h,c]):Q(u,[y,c,h]),w;r!=null&&(w=R(r,"bias","fused matMul"),[w]=Et(w,l),Ut(x,w.shape));let S;i!=null&&(S=R(i,"prelu weights","fused matMul"));let C=(F,E)=>{let[T,D,O,W]=E,$=a0(Q(F,O.shape),O,s),U,G;if(!a&&!n?(U=pt($,D,!1,!0),G=pt(T,$,!0,!1)):!a&&n?(U=pt($,D,!1,!1),G=pt($,T,!0,!1)):a&&!n?(U=pt(D,$,!1,!0),G=pt(T,$,!1,!1)):(U=pt(D,$,!0,!0),G=pt($,T,!0,!0)),r!=null){let q=n0(W,$);return[U,G,q]}else return[U,G]},N={a:A,b,bias:w,preluActivationWeights:S},M={transposeA:a,transposeB:n,activation:s,leakyreluAlpha:o};return r==null?rr((F,E,T)=>{let D=L.runKernel(ts,N,M);return T([F,E,D]),{value:Q(D,x),gradFunc:C}})(A,b):rr((F,E,T,D)=>{let O=L.runKernel(ts,N,M);return D([F,E,O,T]),{value:Q(O,x),gradFunc:C}})(A,b,w)}var nD=z({fusedMatMul_:aD});function rD(e){return t0(e,.54,.46)}var sD=z({hammingWindow_:rD});function iD(e){return t0(e,.5,.5)}var C7=z({hannWindow_:iD});function oD(e,t,a,n=!1,r=0){let s=0,i=[];for(;s+t<=e.size;)i.push(_e(e,s,t)),s+=a;if(n)for(;s<e.size;){let o=s+t-e.size,l=lt([_e(e,s,t-o),lr([o],r)]);i.push(l),s+=a}return i.length===0?er([],[0,t]):Q(lt(i),[i.length,t])}var N7=z({frame_:oD});function lD(e,t,a,n,r=C7){n==null&&(n=a3(t));let s=N7(e,t,a),i=te(s,r(t));return Jh(i,n)}var uD=z({stft_:lD});function dD(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 d={image:i,boxes:o,boxInd:l},c={method:r,extrapolationValue:s,cropSize:n};return L.runKernel(ao,d,c)}var pD=z({cropAndResize_:dD});function cD(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 L.runKernel(uo,a,{})}var hD=z({flipLeftRight_:cD});function mD(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,Qr(t,r)}var fD=z({grayscaleToRGB_:mD});function gD(e){let t=R(e,"image","RGBToGrayscale"),a=t.rank-1,n=t.shape[a];P(t.rank>=2,()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`),P(n===3,()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${n}.`);let r=t.dtype,s=Ue(t,"float32"),i=Vt([.2989,.587,.114]),o;switch(t.rank){case 2:o=hi("ij,j->i",s,i);break;case 3:o=hi("ijk,k->ij",s,i);break;case 4:o=hi("ijkl,l->ijk",s,i);break;case 5:o=hi("ijklm,m->ijkl",s,i);break;case 6:o=hi("ijklmn,n->ijklm",s,i);break;default:throw new Error("Not a valid tensor rank.")}return o=Bt(o,-1),Ue(o,r)}var yD=z({rgbToGrayscale_:gD});function xD(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 L.runKernel(ol,s,i)}var AD=z({rotateWithOffset_:xD});function Yu(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 bD(e,t,a,n=.5,r=Number.NEGATIVE_INFINITY){let s=R(e,"boxes","nonMaxSuppression","float32"),i=R(t,"scores","nonMaxSuppression","float32"),o=Yu(s,i,a,n,r);a=o.maxOutputSize,n=o.iouThreshold,r=o.scoreThreshold;let l={maxOutputSize:a,iouThreshold:n,scoreThreshold:r};return L.runKernel(Mo,{boxes:s,scores:i},l)}var vD=z({nonMaxSuppression_:bD});function wD(e,t,a){let n=kD(e,t,a),r=n<0?-(n+1):n;e.splice(r,0,t)}function kD(e,t,a){return SD(e,t,a||ID)}function ID(e,t){return e>t?1:e<t?-1:0}function SD(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 R7(e,t,a,n,r){return r3(e,t,a,n,r,0)}function E7(e,t,a,n,r,s){return r3(e,t,a,n,r,0,!1,s,!0)}function M7(e,t,a,n,r,s){return r3(e,t,a,n,r,s,!0)}function r3(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(c5);let d=s>0?-.5/s:0,c=[],p=[];for(;c.length<a&&u.length>0;){let g=u.pop(),{score:y,boxIndex:x,suppressBeginIndex:A}=g;if(y<r)break;let b=!1;for(let w=c.length-1;w>=A;--w){let S=TD(e,x,c[w]);if(S>=n){b=!0;break}if(g.score=g.score*CD(n,d,S),g.score<=r)break}g.suppressBeginIndex=c.length,b||(g.score===y?(c.push(x),p.push(g.score)):g.score>r&&wD(u,g,c5))}let h=c.length,m=a-h;o&&m>0&&(c.push(...new Array(m).fill(0)),p.push(...new Array(m).fill(0)));let f={selectedIndices:c};return i&&(f.selectedScores=p),l&&(f.validOutputs=h),f}function TD(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]),d=Math.min(r[1],r[3]),c=Math.max(r[0],r[2]),p=Math.max(r[1],r[3]),h=(o-s)*(l-i),m=(c-u)*(p-d);if(h<=0||m<=0)return 0;let f=Math.max(s,u),g=Math.max(i,d),y=Math.min(o,c),x=Math.min(l,p),A=Math.max(y-f,0)*Math.max(x-g,0);return A/(h+m-A)}function CD(e,t,a){let n=Math.exp(t*a*a);return a<=e?n:0}function c5(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function ND(e,t,a,n=.5,r=Number.NEGATIVE_INFINITY){let s=R(e,"boxes","nonMaxSuppressionAsync"),i=R(t,"scores","nonMaxSuppressionAsync"),o=Yu(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],d=l[1],{selectedIndices:c}=R7(u,d,a,n,r);return s!==e&&s.dispose(),i!==t&&i.dispose(),Vt(c,"int32")}var RD=ND;function ED(e,t,a,n=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=R(e,"boxes","nonMaxSuppression"),o=R(t,"scores","nonMaxSuppression"),l=Yu(i,o,a,n,r,s);a=l.maxOutputSize,n=l.iouThreshold,r=l.scoreThreshold,s=l.softNmsSigma;let u={boxes:i,scores:o},d={maxOutputSize:a,iouThreshold:n,scoreThreshold:r,softNmsSigma:s},c=L.runKernel(Fo,u,d);return{selectedIndices:c[0],selectedScores:c[1]}}var MD=z({nonMaxSuppressionWithScore_:ED});async function FD(e,t,a,n=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=R(e,"boxes","nonMaxSuppressionAsync"),o=R(t,"scores","nonMaxSuppressionAsync"),l=Yu(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()]),d=u[0],c=u[1],{selectedIndices:p,selectedScores:h}=M7(d,c,a,n,r,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:Vt(p,"int32"),selectedScores:Vt(h)}}var $D=FD;function DD(e,t,a,n=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=R(e,"boxes","nonMaxSuppression"),o=R(t,"scores","nonMaxSuppression"),l=Yu(i,o,a,n,r,null),u=l.maxOutputSize,d=l.iouThreshold,c=l.scoreThreshold,p={boxes:i,scores:o},h={maxOutputSize:u,iouThreshold:d,scoreThreshold:c,padToMaxOutputSize:s},m=L.runKernel(Eu,p,h);return{selectedIndices:m[0],validOutputs:m[1]}}var PD=z({nonMaxSuppressionPadded_:DD});async function _D(e,t,a,n=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=R(e,"boxes","nonMaxSuppressionAsync"),o=R(t,"scores","nonMaxSuppressionAsync"),l=Yu(i,o,a,n,r,null),u=l.maxOutputSize,d=l.iouThreshold,c=l.scoreThreshold,[p,h]=await Promise.all([i.data(),o.data()]),{selectedIndices:m,validOutputs:f}=E7(p,h,u,d,c,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:Vt(m,"int32"),validOutputs:Ge(f,"int32")}}var OD=_D;function zD(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=Q(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:a,halfPixelCenters:n,size:t},u=L.runKernel(Bo,o,l);return i?Q(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var LD=z({resizeBilinear_:zD});function WD(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=Q(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:a,halfPixelCenters:n,size:t},u=L.runKernel(Wo,o,l);return i?Q(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var BD=z({resizeNearestNeighbor_:WD});function VD(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=te(Vt([n]),255),d,c,p,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){[d,c,p]=Sa(r,[1,1,1],-1);let f=te(d,s),g=te(c,i),y=te(p,o);h=we(we(f,g),y)}else h=e;if(t==="otsu"){let f=kg(Ue(Kg(h),"int32"),Ve([]),256);u=UD(f,l)}let m=a?Hh(h,u):Yp(h,u);return Ue(te(m,255),"int32")}function UD(e,t){let a=Vt([-1]),n=Vt([0]),r=Vt([0]),s,i,o,l,u,d;for(let c=0;c<e.size-1;c++){s=_e(e,0,c+1),i=_e(e,c+1),u=ve(ot(s),t),d=ve(ot(i),t);let p=ot(te(s,nu(0,s.size)));o=ve(p,ot(s));let h=lr(i.shape,s.size),m=we(nu(0,i.size),h),f=te(i,m);l=ve(ot(f),ot(i));let g=xe(o,l),y=xe(o,l),x=te(u,d);r=te(te(x,g),y);let A=Yp(r,n);n=Cr(A,r,n),a=Cr(A,Vt([c]),a)}return a}var GD=z({threshold_:VD});function HD(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 L.runKernel(il,l,u)}var jD=z({transform_:HD});function qD(e,t,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),o,l;typeof t=="number"?(P(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),P(t<=s,()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`),o=R(t<0?s:t,"numLower","bandPart")):(P(t.dtype==="int32",()=>"bandPart(): numLower's dtype must be an int32."),o=Cr(bh(t,0),s,np(t,s))),typeof a=="number"?(P(a%1===0,()=>`bandPart(): numUpper must be an integer, got ${a}.`),P(a<=i,()=>`bandPart(): numUpper (${a}) must not be greater than the number of columns (${i}).`),l=R(a<0?i:a,"numUpper","bandPart")):(P(a.dtype==="int32",()=>"bandPart(): numUpper's dtype must be an int32."),l=Cr(bh(a,0),i,np(a,i)));let u=Q(nu(0,s,1,"int32"),[-1,1]),d=nu(0,i,1,"int32"),c=xe(u,d),p=tp(Hh(c,o),Mg(c,Vn(l))),h=An([s,i],n.dtype);return Q(ca(Na(Q(n,[-1,s,i])).map(m=>Cr(p,m,h))),r)}var XD=z({bandPart_:qD});function KD(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=Sa(e,e.shape[0],0).map(r=>Oe(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(L.tidy(()=>{let s=n[r];if(r>0)for(let i=0;i<r;++i){let o=te(ot(te(a[i],s)),a[i]);s=xe(s,o)}return ve(s,Kp(s,"euclidean"))}));return t?ca(a,0):a}var YD=z({gramSchmidt_:KD});function ZD(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 h5(e,t);{let a=e.shape.slice(0,e.shape.length-2).reduce((l,u)=>l*u),n=Na(Q(e,[a,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],s=[];n.forEach(l=>{let[u,d]=h5(l,t);r.push(u),s.push(d)});let i=Q(ca(r,0),e.shape),o=Q(ca(s,0),e.shape);return[i,o]}}function h5(e,t=!1){return L.tidy(()=>{P(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let a=e.shape[0],n=e.shape[1],r=Ng(a),s=Ia(e),i=er([[1]],[1,1]),o=Ia(i),l=a>=n?n:a;for(let u=0;u<l;++u){let d=s,c=o,p=r;[o,s,r]=L.tidy(()=>{let h=_e(s,[u,u],[a-u,1]),m=Kp(h),f=_e(s,[u,u],[1,1]),g=Cr(Yp(f,0),er([[-1]]),er([[1]])),y=xe(f,te(g,m)),x=ve(h,y);x.shape[0]===1?o=Ia(i):o=lt([i,_e(x,[1,0],[x.shape[0]-1,x.shape[1]])],0);let A=Vn(ve(pt(g,y),m)),b=_e(s,[u,0],[a-u,n]),w=te(A,o),S=Si(o);if(u===0)s=xe(b,pt(w,pt(S,b)));else{let M=xe(b,pt(w,pt(S,b)));s=lt([_e(s,[0,0],[u,n]),M],0)}let C=Si(w),N=_e(r,[0,u],[a,r.shape[1]-u]);if(u===0)r=xe(N,pt(pt(N,o),C));else{let M=xe(N,pt(pt(N,o),C));r=lt([_e(r,[0,0],[a,u]),M],1)}return[o,s,r]}),J([d,c,p])}return!t&&a>n&&(r=_e(r,[0,0],[a,n]),s=_e(s,[0,0],[n,n])),[r,s]})}var JD=z({qr_:ZD}),wa;(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"})(wa||(wa={}));function QD(e,t,a=wa.SUM_BY_NONZERO_WEIGHTS){let n=R(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=R(t,"weights","computeWeightedLoss"));let s=r==null?n:te(n,r);if(a===wa.NONE)return s;if(a===wa.SUM)return ot(s);if(a===wa.MEAN){if(r==null)return ap(s);{let i=n.size/r.size,o=ve(ot(s),ot(r));return i>1?ve(o,Ge(i)):o}}if(a===wa.SUM_BY_NONZERO_WEIGHTS){if(r==null)return ve(ot(s),Ge(n.size));{let i=te(r,Yr(n.shape)),o=Ue(ot(Wg(i,Ge(0))),"float32");return ve(ot(s),o)}}throw Error(`Unknown reduction: ${a}`)}var Dr=z({computeWeightedLoss_:QD});function eP(e,t,a,n=wa.SUM_BY_NONZERO_WEIGHTS){let r=R(e,"labels","absoluteDifference"),s=R(t,"predictions","absoluteDifference"),i=null;a!=null&&(i=R(a,"weights","absoluteDifference")),Ca(r.shape,s.shape,"Error in absoluteDifference: ");let o=Ja(xe(r,s));return Dr(o,i,n)}var tP=z({absoluteDifference_:eP});function aP(e,t,a,n,r=wa.SUM_BY_NONZERO_WEIGHTS){let s=R(e,"labels","cosineDistance"),i=R(t,"predictions","cosineDistance"),o=null;n!=null&&(o=R(n,"weights","cosineDistance")),Ca(s.shape,i.shape,"Error in cosineDistance: ");let l=Ge(1),u=xe(l,ot(te(s,i),a,!0));return Dr(u,o,r)}var nP=z({cosineDistance_:aP});function rP(e,t,a,n=wa.SUM_BY_NONZERO_WEIGHTS){let r=R(e,"labels","hingeLoss"),s=R(t,"predictions","hingeLoss"),i=null;a!=null&&(i=R(a,"weights","hingeLoss")),Ca(r.shape,s.shape,"Error in hingeLoss: ");let o=Ge(1);r=xe(te(Ge(2),r),o);let l=Jp(xe(o,te(r,s)));return Dr(l,i,n)}var sP=z({hingeLoss_:rP});function iP(e,t,a,n=1,r=wa.SUM_BY_NONZERO_WEIGHTS){let s=R(e,"labels","huberLoss"),i=R(t,"predictions","huberLoss"),o=null;a!=null&&(o=R(a,"weights","huberLoss")),Ca(s.shape,i.shape,"Error in huberLoss: ");let l=Ge(n),u=Ja(xe(i,s)),d=np(u,l),c=xe(u,d),p=we(te(Ge(.5),En(d)),te(l,c));return Dr(p,o,r)}var oP=z({huberLoss_:iP});function lP(e,t,a,n=1e-7,r=wa.SUM_BY_NONZERO_WEIGHTS){let s=R(e,"labels","logLoss"),i=R(t,"predictions","logLoss"),o=null;a!=null&&(o=R(a,"weights","logLoss")),Ca(s.shape,i.shape,"Error in logLoss: ");let l=Ge(1),u=Ge(n),d=Vn(te(s,au(we(i,u)))),c=te(xe(l,s),au(we(xe(l,i),u))),p=xe(d,c);return Dr(p,o,r)}var uP=z({logLoss_:lP});function dP(e,t,a,n=wa.SUM_BY_NONZERO_WEIGHTS){let r=R(e,"labels","meanSquaredError"),s=R(t,"predictions","meanSquaredError"),i=null;a!=null&&(i=R(a,"weights","meanSquaredError")),Ca(r.shape,s.shape,"Error in meanSquaredError: ");let o=Zg(r,s);return Dr(o,i,n)}var pP=z({meanSquaredError_:dP});function cP(e,t){let a=R(e,"labels","sigmoidCrossEntropyWithLogits"),n=R(t,"logits","sigmoidCrossEntropyWithLogits");Ca(a.shape,n.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=Jp(n),s=te(n,a),i=$g(ls(Vn(Ja(n))));return we(xe(r,s),i)}function hP(e,t,a,n=0,r=wa.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")),Ca(s.shape,i.shape,"Error in sigmoidCrossEntropy: "),n>0){let u=Ge(n),d=Ge(1),c=Ge(.5);s=we(te(s,xe(d,u)),te(c,u))}let l=cP(s,i);return Dr(l,o,r)}var mP=z({sigmoidCrossEntropy_:hP});function fP(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 rr((n,r,s)=>{let i=Pg(r,[a],!0),o=xe(Ue(r,"float32"),i);s([n,o]);let l=Vn(te(o,n));return{value:ot(l,[a]),gradFunc:(u,d)=>{let[c,p]=d,h=Xp(u.shape,[a]);return[te(Q(u,h),xe(Ue(c,"float32"),ls(p))),te(Q(u,h),xe(ls(p),Ue(c,"float32")))]}}})(e,t)}function gP(e,t,a,n=0,r=wa.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")),Ca(s.shape,i.shape,"Error in softmaxCrossEntropy: "),n>0){let u=Ge(n),d=Ge(1),c=Ge(s.shape[1]);s=we(te(s,xe(d,u)),ve(u,c))}let l=fP(s,i);return Dr(l,o,r)}var yP=z({softmaxCrossEntropy_:gP});function xP(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=L.runKernel(Mp,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var AP=z({sparseFillEmptyRows_:xP});function bP(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=L.runKernel(Bu,i);return{outputIndices:o[0],outputShape:o[1]}}var vP=z({sparseReshape_:bP});function wP(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 L.runKernel(Vu,i)}var kP=z({sparseSegmentMean_:wP});function IP(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 L.runKernel(Uu,i)}var SP=z({sparseSegmentSum_:IP});function TP(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 d={separator:a,nGramWidths:n,leftPad:r,rightPad:s,padWidth:i,preserveShortSequences:o},c={data:l,dataSplits:u},p=L.runKernel(Hu,c,d);return{nGrams:p[0],nGramsSplits:p[1]}}var CP=z({stringNGrams_:TP});function NP(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=L.runKernel($p,i,s);return{indices:o[0],values:o[1],shape:o[2]}}var RP=z({stringSplit_:NP});function EP(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 L.runKernel(Dp,r,n)}var MP=z({stringToHashBucketFast_:EP});function FP(e,t,a,n=!0){let r=R(e,"input","staticRegexReplace","string"),s={pattern:t,rewrite:a,replaceGlobal:n};return L.runKernel(Gu,{x:r},s)}var $P=z({staticRegexReplace_:FP}),F7={fft:Zh,ifft:rp,rfft:Jh,irfft:Yg},$7={hammingWindow:sD,hannWindow:C7,frame:N7,stft:uD},fe={flipLeftRight:hD,grayscaleToRGB:fD,resizeNearestNeighbor:BD,resizeBilinear:LD,rgbToGrayscale:yD,rotateWithOffset:AD,cropAndResize:pD,nonMaxSuppression:vD,nonMaxSuppressionAsync:RD,nonMaxSuppressionWithScore:MD,nonMaxSuppressionWithScoreAsync:$D,nonMaxSuppressionPadded:PD,nonMaxSuppressionPaddedAsync:OD,threshold:GD,transform:jD},D7={bandPart:XD,gramSchmidt:YD,qr:JD},P7={absoluteDifference:tP,computeWeightedLoss:Dr,cosineDistance:nP,hingeLoss:sP,huberLoss:oP,logLoss:uP,meanSquaredError:pP,sigmoidCrossEntropy:mP,softmaxCrossEntropy:yP},_7={sparseFillEmptyRows:AP,sparseReshape:vP,sparseSegmentMean:kP,sparseSegmentSum:SP},O7={stringNGrams:CP,stringSplit:RP,stringToHashBucketFast:MP,staticRegexReplace:$P},z7={};Ke(z7,{Serializable:()=>L7,SerializationMap:()=>W7,getRegisteredName:()=>PP,registerClass:()=>B7});var DP=new Map,w1=new Map,L7=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},W7=class jl{constructor(){this.classNameMap={}}static getMap(){return jl.instance==null&&(jl.instance=new jl),jl.instance}static register(t){jl.getMap().classNameMap[t.className]=[t,t.fromConfig]}};function B7(e,t,a){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."),typeof t=="undefined"&&(t="Custom"),typeof a=="undefined"&&(a=e.className);let n=a,r=t+">"+n;return W7.register(e),DP.set(r,e),w1.set(e,r),e}function PP(e){return w1.has(e)?w1.get(e):e.className}var _s=class extends L7{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 J(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 g4(e,t)}dispose(){this.iterations_!=null&&J(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Ge(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(_s,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var s3=class extends _s{static get className(){return"Adadelta"}constructor(e,t,a=null){super(),this.learningRate=e,this.rho=t,this.epsilon=a,this.accumulatedGrads=[],this.accumulatedUpdates=[],a==null&&(this.epsilon=L.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,a)=>{let n=L.registeredVariables[t],r=!1;this.accumulatedGrads[a]==null&&(this.accumulatedGrads[a]={originalName:`${t}/accum_grad`,variable:Pe(()=>en(n).variable(r))}),this.accumulatedUpdates[a]==null&&(this.accumulatedUpdates[a]={originalName:`${t}/accum_var`,variable:Pe(()=>en(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;Pe(()=>{let l=we(te(i,this.rho),te(En(s),1-this.rho)),u=te(ve(nr(we(o,this.epsilon)),nr(we(i,this.epsilon))),s),d=we(te(o,this.rho),te(En(u),1-this.rho));i.assign(l),o.assign(d);let c=we(te(u,-this.learningRate),n);n.assign(c)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(J(this.accumulatedGrads.map(e=>e.variable)),J(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)}},i3=class extends _s{static get className(){return"Adagrad"}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=L.registeredVariables[t];this.accumulatedGrads[a]==null&&(this.accumulatedGrads[a]={originalName:`${t}/accumulator`,variable:Pe(()=>lr(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;Pe(()=>{let i=we(s,En(r));s.assign(i);let o=we(te(ve(r,nr(we(i,L.backend.epsilon()))),-this.learningRate),n);n.assign(o)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&J(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)}},o3=class extends _s{static get className(){return"Adam"}constructor(e,t,a,n=null){super(),this.learningRate=e,this.beta1=t,this.beta2=a,this.epsilon=n,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],Pe(()=>{this.accBeta1=Ge(t).variable(),this.accBeta2=Ge(a).variable()}),n==null&&(this.epsilon=L.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(a=>a.name):Object.keys(e);Pe(()=>{let a=xe(1,this.accBeta1),n=xe(1,this.accBeta2);t.forEach((r,s)=>{let i=L.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:Pe(()=>en(i).variable(o))}),this.accumulatedSecondMoment[s]==null&&(this.accumulatedSecondMoment[s]={originalName:`${r}/v`,variable:Pe(()=>en(i).variable(o))});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,d=this.accumulatedSecondMoment[s].variable,c=we(te(u,this.beta1),te(l,1-this.beta1)),p=we(te(d,this.beta2),te(En(l),1-this.beta2)),h=ve(c,a),m=ve(p,n);u.assign(c),d.assign(p);let f=we(te(ve(h,we(nr(m),this.epsilon)),-this.learningRate),i);i.assign(f)}),this.accBeta1.assign(te(this.accBeta1,this.beta1)),this.accBeta2.assign(te(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&J(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&J(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),Pe(()=>{this.accBeta1.assign(tu(this.beta1,this.iterations_+1)),this.accBeta2.assign(tu(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)}},l3=class extends _s{static get className(){return"Adamax"}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=[],Pe(()=>{this.iteration=Ge(0).variable(),this.accBeta1=Ge(t).variable()}),n==null&&(this.epsilon=L.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(a=>a.name):Object.keys(e);Pe(()=>{let a=xe(1,this.accBeta1),n=ve(-this.learningRate,we(te(this.iteration,this.decay),1));t.forEach((r,s)=>{let i=L.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:en(i).variable(o)}),this.accumulatedWeightedInfNorm[s]==null&&(this.accumulatedWeightedInfNorm[s]={originalName:`${r}/v`,variable:en(i).variable(o)});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,d=this.accumulatedWeightedInfNorm[s].variable,c=we(te(u,this.beta1),te(l,1-this.beta1)),p=te(d,this.beta2),h=Ja(l),m=Lg(p,h);u.assign(c),d.assign(m);let f=we(te(ve(n,a),ve(c,we(m,this.epsilon))),i);i.assign(f)}),this.iteration.assign(we(this.iteration,1)),this.accBeta1.assign(te(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&J(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&J(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)}},i0=class extends _s{static get className(){return"SGD"}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=L.registeredVariables[t];Pe(()=>{let s=we(te(this.c,n),r);r.assign(s)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=Bn(Ge(-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)}},u3=class extends i0{static get className(){return"Momentum"}constructor(e,t,a=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=a,this.accumulations=[],this.m=Ge(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,a)=>{let n=L.registeredVariables[t];this.accumulations[a]==null&&(this.accumulations[a]={originalName:`${t}/momentum`,variable:Pe(()=>en(n).variable(!1))});let r=this.accumulations[a].variable,s=Array.isArray(e)?e[a].tensor:e[t];s!=null&&Pe(()=>{let i,o=we(te(this.m,r),s);this.useNesterov?i=we(te(this.c,we(s,te(o,this.m))),n):i=we(te(this.c,o),n),r.assign(o),n.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&J(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)}},d3=class extends _s{static get className(){return"RMSProp"}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=L.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=L.registeredVariables[t],r=!1;this.accumulatedMeanSquares[a]==null&&(this.accumulatedMeanSquares[a]={originalName:`${t}/rms`,variable:Pe(()=>en(n).variable(r))}),this.accumulatedMoments[a]==null&&(this.accumulatedMoments[a]={originalName:`${t}/momentum`,variable:Pe(()=>en(n).variable(r))}),this.accumulatedMeanGrads[a]==null&&this.centered&&(this.accumulatedMeanGrads[a]={originalName:`${t}/mg`,variable:Pe(()=>en(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;Pe(()=>{let l=we(te(i,this.decay),te(En(s),1-this.decay));if(this.centered){let u=this.accumulatedMeanGrads[a].variable,d=we(te(u,this.decay),te(s,1-this.decay)),c=ve(te(s,this.learningRate),nr(xe(l,we(En(d),this.epsilon)))),p=we(te(o,this.momentum),c);i.assign(l),u.assign(d),o.assign(p);let h=xe(n,p);n.assign(h)}else{let u=we(te(i,this.decay),te(En(s),1-this.decay)),d=we(te(o,this.momentum),ve(te(s,this.learningRate),nr(we(u,this.epsilon))));i.assign(u),o.assign(d);let c=xe(n,d);n.assign(c)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&J(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&J(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&J(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)}},_P=[s3,i3,o3,l3,u3,d3,i0];function OP(){for(let e of _P)B7(e)}var Jn={};Ke(Jn,{CompositeArrayBuffer:()=>Fr,browserFiles:()=>GP,browserHTTPRequest:()=>YP,concatenateArrayBuffers:()=>fR,copyModel:()=>OR,decodeWeights:()=>ib,decodeWeightsStream:()=>lb,encodeWeights:()=>uR,fromMemory:()=>JP,fromMemorySync:()=>j7,getLoadHandlers:()=>kR,getModelArtifactsForJSON:()=>xg,getModelArtifactsForJSONSync:()=>db,getModelArtifactsInfoForJSON:()=>Up,getSaveHandlers:()=>wR,getWeightSpecs:()=>g1,http:()=>c3,isHTTPScheme:()=>I1,listModels:()=>PR,loadWeights:()=>jP,moveModel:()=>zR,registerLoadRouter:()=>vR,registerSaveRouter:()=>bR,removeModel:()=>_R,weightsLoaderFactory:()=>U7,withSaveHandler:()=>QP,withSaveHandlerSync:()=>e_});var zP="model",LP=".json",WP=".weights.bin";function m5(e){return new Promise(t=>setTimeout(t)).then(e)}var wh=class k1{constructor(t){if(!B().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");t.startsWith(k1.URL_SCHEME)&&(t=t.slice(k1.URL_SCHEME.length)),(t==null||t.length===0)&&(t=zP),this.modelJsonFileName=t+LP,this.weightDataFileName=t+WP}async save(t){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");let a=Fr.join(t.weightData),n=window.URL.createObjectURL(new Blob([a],{type:"application/octet-stream"}));if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{let r=[{paths:["./"+this.weightDataFileName],weights:t.weightSpecs}],s=ub(t,r),i=window.URL.createObjectURL(new Blob([JSON.stringify(s)],{type:"application/json"})),o=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(o.download=this.modelJsonFileName,o.href=i,await m5(()=>o.dispatchEvent(new MouseEvent("click"))),t.weightData!=null){let l=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;l.download=this.weightDataFileName,l.href=n,await m5(()=>l.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Up(t)}}}};wh.URL_SCHEME="downloads://";var BP=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=xg(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,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=>p5(r.name)),n={};for(let r of e)r.paths.forEach(s=>{let i=p5(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}},VP=e=>B().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(wh.URL_SCHEME)?UP(e.slice(wh.URL_SCHEME.length)):null;xn.registerSaveRouter(VP);function UP(e="model"){return new wh(e)}function GP(e){return new BP(e)}function f5(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 d=a+ ++r/e.length*(n-a);return t(d),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 V7(e,t){t==null&&(t={});let a=t.fetchFunc==null?B().platform.fetch:t.fetchFunc,n=e.map(s=>a(s,t.requestInit,{isBinary:!0})),r=(t.onProgress==null?await Promise.all(n):await f5(n,t.onProgress,0,.5)).map(s=>s.arrayBuffer());return t.onProgress==null?await Promise.all(r):await f5(r,t.onProgress,.5,1)}function HP(e,t){var a;let n=t.fetchFunc==null?B().platform.fetch:t.fetchFunc,r=0,s;return(a=t.onProgress)===null||a===void 0||a.call(t,0),new ReadableStream({pull:async i=>{for(var o;r<e.length;){s||(s=(await n(e[r],t.requestInit,{isBinary:!0})).body.getReader());let{done:l,value:u}=await s.read();if(l){r++,s=void 0,(o=t.onProgress)===null||o===void 0||o.call(t,r/e.length);continue}i.enqueue(u);return}i.close()}})}async function jP(e,t="",a,n){return U7(r=>V7(r,{requestInit:n}))(e,t,a)}function U7(e){return async(t,a="",n)=>{let r=t.map(()=>!1),s={},i=n!=null?n.map(()=>!1):[],o=[];if(t.forEach((h,m)=>{let f=0;h.weights.forEach(g=>{let y="quantization"in g?g.quantization.dtype:g.dtype,x=vi[y]*mt(g.shape),A=()=>{r[m]=!0,s[m]==null&&(s[m]=[]),s[m].push({manifestEntry:g,groupOffset:f,sizeBytes:x})};n!=null?n.forEach((b,w)=>{b===g.name&&(A(),i[w]=!0)}):A(),o.push(g.name),f+=x})}),!i.every(h=>h)){let h=n.filter((m,f)=>!i[f]);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,m,f)=>(m&&h.push(f),h),[]),u=[];l.forEach(h=>{t[h].paths.forEach(m=>{let f=a+(a.endsWith("/")?"":"/")+m;u.push(f)})});let d=await e(u),c={},p=0;return l.forEach(h=>{let m=t[h].paths.length,f=new Fr(d.slice(p,p+m));s[h].forEach(g=>{let y=f.slice(g.groupOffset,g.groupOffset+g.sizeBytes),x=ib(y,[g.manifestEntry]);for(let A in x)c[A]=x[A]}),p+=m}),c}}var qP="application/octet-stream",XP="application/json",p3=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,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=B().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||{},this.loadOptions=t}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=ub(e,a);if(t.body.append("model.json",new Blob([JSON.stringify(n)],{type:XP}),"model.json"),e.weightData!=null){let s=Fr.join(e.weightData);t.body.append("model.weights.bin",new Blob([s],{type:qP}),"model.weights.bin")}let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:Up(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async loadModelJSON(){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 t}async load(){if(this.loadOptions.streamWeights)return this.loadStream();let e=await this.loadModelJSON();return xg(e,t=>this.loadWeights(t))}async loadStream(){let e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),a=g1(e.weightsManifest),n=()=>HP(t,this.loadOptions);return Object.assign(Object.assign({},e),{weightSpecs:a,getWeightStream:n})}async getWeightUrls(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[a,n]=KP(t),r=this.weightPathPrefix||a,s=[],i=[];for(let o of e)for(let l of o.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(l)):s.push(r+l+n);return this.weightUrlConverter&&s.push(...await Promise.all(i)),s}async loadWeights(e){let t=await this.getWeightUrls(e),a=g1(e),n=await V7(t,this.loadOptions);return[a,n]}};p3.URL_SCHEME_REGEX=/^https?:\/\//;function KP(e){let t=e.lastIndexOf("/"),a=e.lastIndexOf("?"),n=e.substring(0,t),r=a>t?e.substring(a):"";return[n+"/",r]}function I1(e){return e.match(p3.URL_SCHEME_REGEX)!=null}var G7=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let a=!0;if(Array.isArray(e)?a=e.every(n=>I1(n)):a=I1(e),a)return c3(e,t)}return null};xn.registerSaveRouter(G7);xn.registerLoadRouter(G7);function c3(e,t){return new p3(e,t)}function YP(e,t){return c3(e,t)}var t1=class{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}},H7=class{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}},ZP=class{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}};function JP(e,t,a,n){let r=arguments;return new ZP(j7(...r))}function j7(e,t,a,n){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new t1(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 t1({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 t1({modelTopology:e,weightSpecs:t,weightData:a,trainingConfig:n}))}function QP(e){return new H7(e)}function e_(e){return new H7(e)}var q7={};Ke(q7,{confusionMatrix:()=>a_});function t_(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=vh(Ue(n,"int32"),a),i=vh(Ue(r,"int32"),a),o=Si(s),l=pt(o,i);return Ue(l,"int32")}var a_=z({confusionMatrix_:t_}),Pr={};Ke(Pr,{draw:()=>d_,fromPixels:()=>p_,fromPixelsAsync:()=>o_,toPixels:()=>u_});var li,g5=!1;function X7(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(Xd(jd,L.backendName)!=null){let p={pixels:e},h={numChannels:t};return L.runKernel(jd,p,h)}let[l,u]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height],d;if(i)d=e.getContext("2d").getImageData(0,0,l,u).data;else if(n||a)d=e.data;else if(s||r||o){if(li==null)if(typeof document=="undefined")if(typeof OffscreenCanvas!="undefined"&&typeof OffscreenCanvasRenderingContext2D!="undefined")li=new OffscreenCanvas(1,1).getContext("2d");else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");else li=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});li.canvas.width=l,li.canvas.height=u,li.drawImage(e,0,0,l,u),d=li.getImageData(0,0,l,u).data}let c;if(t===4)c=new Int32Array(d);else{let p=l*u;c=new Int32Array(p*t);for(let h=0;h<p;h++)for(let m=0;m<t;++m)c[h*t+m]=d[h*4+m]}return Qg(c,[u,l,t],"int32")}function n_(e){return e!=null&&e.data instanceof Uint8Array}function r_(){return typeof window!="undefined"&&typeof ImageBitmap!="undefined"&&window.hasOwnProperty("createImageBitmap")}function s_(e){return e!=null&&e.width!==0&&e.height!==0}function i_(e){return r_()&&!(e instanceof ImageBitmap)&&s_(e)&&!n_(e)}async function o_(e,t=3){let a=null;if(B().getBool("WRAP_TO_IMAGEBITMAP")&&i_(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 X7(a,t)}function K7(e){if(e.rank!==2&&e.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${e.rank}.`);let t=e.rank===2?1:e.shape[2];if(t>4||t===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${t}`);if(e.dtype!=="float32"&&e.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${e.dtype}. Please use float32 or int32 tensors.`)}function l_(e){let t=(e==null?void 0:e.alpha)||1;if(t>1||t<0)throw new Error(`Alpha value ${t} is suppoed to be in range [0 - 1].`)}async function u_(e,t){let a=R(e,"img","toPixels");if(!(e instanceof yt)){let u=a;a=Ue(u,"int32"),u.dispose()}K7(a);let[n,r]=a.shape.slice(0,2),s=a.rank===2?1:a.shape[2],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 d=[0,0,0,255];for(let p=0;p<s;p++){let h=i[u*s+p];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?(d[0]=h*o,d[1]=h*o,d[2]=h*o):d[p]=h*o}let c=u*4;l[c+0]=Math.round(d[0]),l[c+1]=Math.round(d[1]),l[c+2]=Math.round(d[2]),l[c+3]=Math.round(d[3])}if(t!=null){g5||Xd(kp,L.backendName)!=null&&(console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."),g5=!0),t.width=r,t.height=n;let u=t.getContext("2d"),d=new ImageData(l,r,n);u.putImageData(d,0,0)}return a!==e&&a.dispose(),l}function d_(e,t,a){let n=R(e,"img","draw");if(!(e instanceof yt)){let i=n;n=Ue(i,"int32"),i.dispose()}K7(n),l_(a==null?void 0:a.imageOptions);let r={image:n},s={canvas:t,options:a};L.runKernel(kp,r,s)}var p_=z({fromPixels_:X7}),h3={};Ke(h3,{prepareAndValidate:()=>Y7});function Y7(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(mt(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 d=[...pu(e.shape).map(c=>c/u),1].slice(0,s);return[l,i,u,d]}var wt={};Ke(wt,{assertParamsValid:()=>h_,computeFlatOffset:()=>x_,computeOutShape:()=>f_,getNormalizedAxes:()=>g_,isSliceContinous:()=>y_,maskToAxes:()=>m_,parseSliceParams:()=>A_,sliceInfo:()=>b_,startForAxis:()=>n6,startIndicesWithElidedDims:()=>e6,stopForAxis:()=>r6,stopIndicesWithElidedDims:()=>t6,stridesForAxis:()=>a6,stridesWithElidedDims:()=>Z7});var S1=-2,c_=-1;function h_(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 m_(e){let t=[],a=0;for(;e>0;)e&1&&t.push(a),e/=2,a++;return t}function f_(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 Z7(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 J7(e,t,a){return a<=e?a:a-(t-1)}function Q7(e,t){let a=[];for(let n=0;n<e;n++)a.push(t+n);return a}function g_(e,t,a,n,r,s,i,o,l){let u=e.length,d=new Array(u),c=new Array(u),p=new Array(u);if(t.length&&a>0){let h=t[0],m=a+1;d=e6(i,h,m,n,e),c=t6(o,h,m,r,e),p=Z7(s,h,m,e)}else for(let h=0;h<u;h++)d[h]=n6(i,n,s,e,h,l),c[h]=r6(o,r,s,e,h,l),p[h]=a6(s,h,l);return{begin:d,end:c,strides:p}}function e6(e,t,a,n,r){let s=[...r],i=Q7(a,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=0;else{let l=J7(t,a,o),u=n[l];e&1<<l&&(u=0),s[o]=u}return s}function t6(e,t,a,n,r){let s=[...r],i=Q7(a,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=Number.MAX_SAFE_INTEGER;else{let l=J7(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]=Hd(0,s[o],r[o])}return s}function a6(e,t,a){let n=e[t];return(a&1<<t||n==null)&&(n=1),n}function n6(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=Hd(0,i,l-1),i}function r6(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=Hd(0,i,l):i=Hd(-1,i,l-1),i}function y_(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 x_(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 A_(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 b_(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)throw new Error("Multiple ellipses in slice is not allowed.");let d=!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 x=0;x<c.dims;x++)d&&1<<x&o&&c.numAddAxisAfterEllipsis++,1<<x&i&&(d=!0);d||(c.ellipsisMask|=1<<c.dims,c.dims++);let p={dims:e.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};v_(c,p);let h=!0,m=!0,f=!0,g=[],y=[];for(let x=0;x<e.length;++x){if(p.strides[x]===0)throw Error(`strides[${x}] must be non-zero`);let A=!!(p.shrinkAxisMask&1<<x),b=e[x];if(b===-1){g.push(A?1:-1);continue}let w=[p.beginMask&1<<x,p.endMask&1<<x],S=[p.strides[x]>0?0:-1,p.strides[x]>0?b:b-1];if(A&&p.strides[x]<=0)throw Error("only stride 1 allowed on non-range indexing.");f=f&&p.strides[x]===1;let C=!!(p.beginMask&1<<x&&p.endMask&1<<x);if(p.beginValid&&p.endValid){if(A){let E=p.begin[x]<0?b+p.begin[x]:p.begin[x];if(p.begin[x]=E,p.end[x]=p.begin[x]+1,E<0||E>=b)throw Error(`slice index ${p.begin[x]} of dimension ${x} out of bounds.`)}else p.begin[x]=y5(p.begin[x],0,p.strides[x],b,w,S),p.end[x]=y5(p.end[x],1,p.strides[x],b,w,S);let F=p.strides[x]===1&&p.begin[x]===0&&p.end[x]===b;h=h&&F,m=m&&(x===0&&p.strides[x]===1||F)}else h=h&&p.strides[x]===1&&C,m=m&&(x===0&&p.strides[x]===1||C);let N,M=!1;if(p.beginValid&&p.endValid?(N=p.end[x]-p.begin[x],M=!0):A?(N=1,M=!0):C&&b>=0&&(p.strides[x]<0?N=-b:N=b,M=!0),M){let F;N===0||N<0!=p.strides[x]<0?F=0:F=Math.trunc(N/p.strides[x])+(N%p.strides[x]!==0?1:0),g.push(F)}else g.push(-1)}for(let x=0;x<p.finalShapeGatherIndices.length;++x){let A=p.finalShapeGatherIndices[x];A>=0?y.push(g[A]):A===S1&&y.push(1)}return{finalShapeSparse:y.filter((x,A)=>p.finalShapeGatherIndices[A]!==S1),finalShape:y,isIdentity:h,sliceDim0:m,isSimpleSlice:f,begin:p.begin,end:p.end,strides:p.strides}}function v_(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(S1),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(c_),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<a):(t.finalShapeGatherIndices.push(a),t.finalShapeGatherIndicesSparse.push(n)),t.inputShapeGatherIndicesSparse[a]=n,a++}}function y5(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 m3="4.17.0",s6=class{static sgd(e){return new i0(e)}static momentum(e,t,a=!1){return new u3(e,t,a)}static rmsprop(e,t=.9,a=0,n=null,r=!1){return new d3(e,t,a,n,r)}static adam(e=.001,t=.9,a=.999,n=null){return new o3(e,t,a,n)}static adadelta(e=.001,t=.95,a=null){return new s3(e,t,a)}static adamax(e=.002,t=.9,a=.999,n=null,r=0){return new l3(e,t,a,n,r)}static adagrad(e,t=.1){return new i3(e,t)}},w_=s6,k_=typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e();function i6(){return new Promise(e=>k_(()=>e()))}var I={};Ke(I,{ERF_A1:()=>W_,ERF_A2:()=>B_,ERF_A3:()=>V_,ERF_A4:()=>U_,ERF_A5:()=>G_,ERF_P:()=>L_,PARALLELIZE_THRESHOLD:()=>f3,RowPartitionType:()=>Zn,SELU_SCALE:()=>z_,SELU_SCALEALPHA:()=>O_,applyActivation:()=>r0,assertAndGetBroadcastShape:()=>Ut,assertAxesAreInnerMostDims:()=>cM,assertParamsConsistent:()=>I_,assignToTypedArray:()=>Y_,axesAreInnerMostDims:()=>Cg,calculateShapes:()=>p7,checkEinsumDimSizes:()=>aO,checkPadOnDimRoundingMode:()=>Mn,combineLocations:()=>o4,combineRaggedTensorToTensorShapes:()=>T_,complexWithEvenIndex:()=>q_,complexWithOddIndex:()=>X_,computeConv2DInfo:()=>Hp,computeConv3DInfo:()=>Rb,computeDefaultPad:()=>bg,computeDilation2DInfo:()=>lE,computeOptimalWindowSize:()=>E_,computeOutAndReduceShapes:()=>pM,computeOutShape:()=>S_,computePool2DInfo:()=>Nb,computePool3DInfo:()=>uE,convertConv2DDataFormat:()=>Eb,decodeEinsumEquation:()=>eO,eitherStridesOrDilationsAreOne:()=>$r,expandShapeToKeepDim:()=>Xp,exponent:()=>J_,exponents:()=>Z_,fromStringArrayToUint8:()=>kO,fromUint8ToStringArray:()=>wO,getAxesPermutation:()=>hM,getBroadcastDims:()=>a4,getComplexWithIndex:()=>K_,getEinsumComputePath:()=>nO,getEinsumPermutation:()=>tO,getFusedBiasGradient:()=>n0,getFusedDyActivation:()=>a0,getImageCenter:()=>M_,getInnerMostAxes:()=>fM,getPermuted:()=>$_,getRaggedRank:()=>N_,getReductionAxes:()=>Ig,getReshaped:()=>F_,getReshapedPermuted:()=>D_,getRowPartitionTypesHelper:()=>C_,getSliceBeginCoords:()=>P_,getSliceSize:()=>__,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>oO,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>lO,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>uO,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>cO,getSparseReshapeInputOutputMismatchErrorMessage:()=>mO,getSparseReshapeInputOutputMultipleErrorMessage:()=>hO,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>dO,getSparseReshapeNegativeOutputDimErrorMessage:()=>pO,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>xO,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>fO,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>gO,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>yO,getUndoAxesPermutation:()=>mM,isIdentityPermutation:()=>rO,log:()=>bN,mergeRealAndImagArrays:()=>H_,prepareAndValidate:()=>Y7,prepareSplitSize:()=>iO,segment_util:()=>o6,shouldFuse:()=>s0,slice_util:()=>wt,splitRealAndImagArrays:()=>j_,stridesOrDilationsArePositive:()=>Ii,tupleValuesAreOne:()=>ep,upcastType:()=>Qt,validateDefaultValueShape:()=>R_,validateInput:()=>e0,validateUpdateShape:()=>e3,warn:()=>qr});function I_(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 S_(e,t){let a=e[0].slice();for(let n=1;n<e.length;n++)a[t]+=e[n][t];return a}var Zn;(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"})(Zn||(Zn={}));function T_(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 C_(e){let t={FIRST_DIM_SIZE:Zn.FIRST_DIM_SIZE,VALUE_ROWIDS:Zn.VALUE_ROWIDS,ROW_LENGTHS:Zn.ROW_LENGTHS,ROW_SPLITS:Zn.ROW_SPLITS,ROW_LIMITS:Zn.ROW_LIMITS,ROW_STARTS:Zn.ROW_STARTS},a=[];for(let n of e)if(n in t)a.push(t[n]);else break;return a}function N_(e){return e.length===0?0:e[0]===Zn.FIRST_DIM_SIZE?e.length-1:e.length}function R_(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 f3=30;function E_(e){return e<=f3?e:yh(e,Math.floor(Math.sqrt(e)))}function M_(e,t,a){let n=a*(typeof e=="number"?e:e[0]),r=t*(typeof e=="number"?e:e[1]);return[n,r]}function F_(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 $_(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 D_(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 P_(e,t){let a=[0];for(let n=0;n<t;++n)a.push(e[n][0]);return a}function __(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 O_=1.7580993408473768,z_=1.0507009873554805,L_=.3275911,W_=.254829592,B_=-.284496736,V_=1.421413741,U_=-1.453152027,G_=1.061405429;function H_(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 j_(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 q_(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 X_(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 K_(e,t){let a=e[t*2],n=e[t*2+1];return{real:a,imag:n}}function Y_(e,t,a,n){e[n*2]=t,e[n*2+1]=a}function Z_(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 J_(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 a1="->",Q_=/->/g,x5=",",A5="...";function eO(e,t){e=e.replace(/\s/g,"");let a=(e.length-e.replace(Q_,"").length)/a1.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 ("${a1}").`);let[n,r]=e.split(a1);P(n.indexOf(A5)===-1,()=>`The ellipsis notation ("${A5}") is not supported yet.`);let s=n.split(x5),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 p=0;p<r.length;++p){let h=r[p];if(!s.some(m=>m.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 p=0;p<n.length;++p){let h=n[p];o.indexOf(h)===-1&&h!==x5&&o.push(h)}let l=new Array(s.length);for(let p=0;p<i;++p){if(new Set(s[p].split("")).size!==s[p].length)throw new Error(`Found duplicate axes in input component ${s[p]}. Support for duplicate axes in input is not implemented yet.`);l[p]=[];for(let h=0;h<s[p].length;++h)l[p].push(o.indexOf(s[p][h]))}let u=o.length,d=r.length,c=[];for(let p=d;p<u;++p)c.push(p);return{allDims:o,summedDims:c,idDims:l}}function tO(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 aO(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 nO(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=sO(t,o);for(let u of l)s.indexOf(u)===-1&&(n[i].push(u),s.push(u))}return{path:a,steps:n}}function rO(e){return e.every((t,a)=>t===a)}function sO(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 iO(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 oO(e){return`Received SparseTensor with denseShape[0] = 0 but
|
|
indices.shape[0] = ${e}`}function lO(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function uO(e,t,a){return`indices(${e}, 0) is invalid: ${t} >= ${a}`}function dO(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function pO(e,t){return`size ${e} must be non-negative, not ${t}`}function cO(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function hO(e,t){let a=mt(e),n=mt(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 mO(e,t){let a=mt(e),n=mt(t);return`Input to reshape is a tensor with ${a} dense values, but the requested shape has ${n}. inputShape=${e} outputShape=${t}`}function fO(){return"segment ids must be >= 0"}function gO(){return"segment ids are not increasing"}function yO(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function xO(e,t,a){return`Bad: indices[${e}] == ${t} out of range [0, ${a})`}var o6={};Ke(o6,{collectGatherOpShapeInfo:()=>vO,computeOutShape:()=>bO,segOpComputeOptimalWindowSize:()=>AO});function AO(e,t){let a=!1,n;for(e<=f3?(n=e,a=!0):n=yh(e,Math.floor(Math.sqrt(e)));!a;)n>t||n===e?a=!0:n=yh(e,n+1);return n}function bO(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 vO(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,d=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]),d*=e.shape[c];return{batchSize:l,sliceSize:d,outerSize:u,dimSize:i,outputShape:o}}function wO(e){try{return e.map(t=>xh(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function kO(e){return e.map(t=>zp(t))}var Fn={};Ke(Fn,{nonMaxSuppressionV3Impl:()=>R7,nonMaxSuppressionV4Impl:()=>E7,nonMaxSuppressionV5Impl:()=>M7,whereImpl:()=>A7});OP();var IO=B();IO.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 Ya;(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"})(Ya||(Ya={}));var b5;(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={}))})(b5||(b5={}));var g3={};function SO(e,t){let a={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};g3[e]=a}function l6(e){return g3[e]}function TO(e){delete g3[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,u=o<0?t.inputNames.length+o:o;if(s.type==="tensor")return da(t.inputNames[u],a,n,r);if(s.type==="tensors"){let p=t.inputs.slice(o,l);return t.inputNames.slice(o,l).filter((h,m)=>{var f;return((f=p[m])===null||f===void 0?void 0:f.op)!=="NoOp"}).map(h=>da(h,a,n,r))}let d=da(t.inputNames[u],a,n,r),c=d.dataSync();return s.type==="number"?c[0]:v.toNestedArray(d.shape,c)}let i=t.attrParams[e];return i&&i.value}function da(e,t,a,n){let[r,s]=Za(e,a);if(n!=null){let o=n.getHashTableHandleByName(r);if(o!=null)return o}let i=a.currentContextIds.find(o=>!!t[kh(r,o)]);return i!==void 0?t[kh(r,i)][s]:void 0}function v5(e,t,a){return t[kh(e,a.currentContextId)]}function kr(e,t){let[a,n,r]=Za(e,t);return[kh(a,t&&t.currentContextId),n,r]}function kh(e,t){return t?`${e}-${t}`:e}function Za(e,t){if(e==="")return["",0,void 0];let a=t!=null&&t.parseNodeNameCache!=null;if(a){let s=t.parseNodeNameCache.get(e);if(s!=null)return s}let n=e.split(":"),r;if(n.length===1)r=[e,0,void 0];else{let s=n[0],i=n.length===3?n[1]:void 0,o=Number(n[n.length-1]);r=[s,o,i]}return a&&t.parseNodeNameCache.set(e,r),r}function lh(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 Ir(e){return e.kept?e:Ia(e)}var u6={};Ke(u6,{json:()=>CO});var CO=[{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}]}],d6={};Ke(d6,{json:()=>NO});var NO=[{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:"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}]},{tfOpName:"IsFinite",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsInf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],p6={};Ke(p6,{json:()=>RO});var RO=[{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"}]}],c6={};Ke(c6,{json:()=>EO});var EO=[{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"}]}],h6={};Ke(h6,{json:()=>MO});var MO=[{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:"RandomUniformInt",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number"},{tfName:"maxval",name:"maxval",type:"number"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,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"}]}],m6={};Ke(m6,{json:()=>FO});var FO=[{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}]}],f6={};Ke(f6,{json:()=>$O});var $O=[{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"}]}],g6={};Ke(g6,{json:()=>DO});var DO=[{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"}]}],y6={};Ke(y6,{json:()=>PO});var PO=[{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"}]}],x6={};Ke(x6,{json:()=>_O});var _O=[{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"}]}],A6={};Ke(A6,{json:()=>OO});var OO=[{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}]},{tfOpName:"BitwiseAnd",category:"logical",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}]}],b6={};Ke(b6,{json:()=>zO});var zO=[{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"}]},{tfOpName:"MatrixBandPart",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"numLower",type:"tensor"},{start:1,name:"numUpper",type:"tensor"}]}],v6={};Ke(v6,{json:()=>LO});var LO=[{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"}]}],w6={};Ke(w6,{json:()=>WO});var WO=[{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"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{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"}]}],k6={};Ke(k6,{json:()=>BO});var BO=[{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}]},{tfOpName:"TensorScatterUpdate",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"values",type:"tensor"}]}],I6={};Ke(I6,{json:()=>VO});var VO=[{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"}]}],S6={};Ke(S6,{json:()=>UO});var UO=[{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}]}],T6={};Ke(T6,{json:()=>GO});var GO=[{tfOpName:"StaticRegexReplace",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"pattern",name:"pattern",type:"string"},{tfName:"rewrite",name:"rewrite",type:"string"},{tfName:"replace_global",name:"replaceGlobal",type:"bool"}]},{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"}]}],C6={};Ke(C6,{json:()=>HO});var HO=[{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:"EnsureShape",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:[]}],w5=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[u6,d6,p6,c6,h6,m6,f6,g6,y6,x6,A6,b6,v6,w6,k6,I6,S6,T6,C6],t=[].concat(...e.map(a=>a.json));this.opMappers=t.reduce((a,n)=>(a[n.tfOpName]=n,a),{})}transformGraph(e,t={}){let a=e.node,n=[],r=[],s=[],i=a.reduce((m,f)=>(m[f.name]=this.mapNode(f),f.op.startsWith("Placeholder")?n.push(m[f.name]):f.op==="Const"?r.push(m[f.name]):(f.input==null||f.input.length===0)&&s.push(m[f.name]),m),{}),o=[],l=[],u={},d={};t!=null&&(u=this.mapSignatureEntries(t.inputs),d=this.mapSignatureEntries(t.outputs));let c=Object.keys(i);c.forEach(m=>{let f=i[m];f.inputNames.forEach((g,y)=>{let[x,,A]=kr(g),b=i[x];if(b.outputs!=null){let w=b.outputs.indexOf(A);if(w!==-1){let S=`${x}:${w}`;f.inputNames[y]=S}}f.inputs.push(b),b.children.push(f)})}),Object.keys(d).length===0?c.forEach(m=>{let f=i[m];f.children.length===0&&l.push(f)}):Object.keys(d).forEach(m=>{let[f]=kr(m),g=i[f];g!=null&&(g.signatureKey=d[m],l.push(g))}),Object.keys(u).length>0?Object.keys(u).forEach(m=>{let[f]=kr(m),g=i[f];g&&(g.signatureKey=u[m],o.push(g))}):o=n;let p={};e.library!=null&&e.library.function!=null&&(p=e.library.function.reduce((m,f)=>(m[f.signature.name]=this.mapFunction(f),m),{}));let h={nodes:i,inputs:o,outputs:l,weights:r,placeholders:n,signature:t,functions:p};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=l6(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=T1(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=T1(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"string[]":i=$1(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=$1(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number":i=N1(e.attr,r.tfName,r.defaultValue||0),i===void 0&&r.tfDeprecatedName&&(i=N1(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number[]":i=F1(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=F1(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool":i=C1(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=C1(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool[]":i=P1(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=P1(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"shape[]":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=R1(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=R1(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype[]":i=E1(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=E1(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"func":i=k5(e.attr,r.tfName,r.defaultValue),i===void 0&&r.tfDeprecatedName&&(i=k5(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,d)=>(u[d.name]=this.mapNode(d),d.op==="Const"&&n.push(u[d.name]),u),{}));let s=[],i=[];e.signature.inputArg.forEach(u=>{let[d]=kr(u.name),c={name:d,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:y3(u.type),type:"dtype"}},children:[]};c.signatureKey=u.name,s.push(c),r[d]=c}),Object.keys(r).forEach(u=>{let d=r[u];d.inputNames.forEach((c,p)=>{let[h,,m]=kr(c),f=r[h];if(f.outputs!=null){let g=f.outputs.indexOf(m);if(g!==-1){let y=`${h}:${g}`;d.inputNames[p]=y}}d.inputs.push(f),f.children.push(d)})});let o=e.ret;e.signature.outputArg.forEach(u=>{let[d,c]=kr(o[u.name]),p=r[d];p!=null&&(p.defaultOutput=c,i.push(p))});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 jO(e){let t=B().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 N6(e,t){let a=Array.isArray(e)?String.fromCharCode.apply(null,e):jO(e);return t?a:a.toLowerCase()}function T1(e,t,a,n=!1){let r=e[t];return r!=null?N6(r.s,n):a}function C1(e,t,a){let n=e[t];return n?n.b:a}function N1(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 y3(e){switch(typeof e=="string"&&(e=Ya[e]),e){case Ya.DT_FLOAT:case Ya.DT_HALF:return"float32";case Ya.DT_INT32:case Ya.DT_INT64:case Ya.DT_INT8:case Ya.DT_UINT8:return"int32";case Ya.DT_BOOL:return"bool";case Ya.DT_DOUBLE:return"float32";case Ya.DT_STRING:return"string";case Ya.DT_COMPLEX64:case Ya.DT_COMPLEX128:return"complex64";default:return null}}function k5(e,t,a){let n=e[t];return n&&n.func?n.func.name:a}function R1(e,t,a){let n=e[t];return n&&n.type?y3(n.type):a}function E1(e,t,a){let n=e[t];return n&&n.list&&n.list.type?n.list.type.map(r=>y3(r)):a}function R6(e){if(!e.unknownRank)return e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function M1(e,t,a){let n=e[t];return n&&n.shape?R6(n.shape):a}function F1(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 $1(e,t,a,n=!1){let r=e[t];return r&&r.list&&r.list.s?r.list.s.map(s=>N6(s,n)):a}function D1(e,t,a){let n=e[t];return n&&n.list&&n.list.shape?n.list.shape.map(r=>R6(r)):a}function P1(e,t,a){let n=e[t];return n&&n.list&&n.list.b?n.list.b:a}var qO=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 da(e,this.tensorMap,this.context)}getAttr(e,t){let a=this.node.rawAttrs[e];if(a.tensor!=null)return da(e,this.tensorMap,this.context);if(a.i!=null||a.f!=null)return N1(this.node.rawAttrs,e,t);if(a.s!=null)return T1(this.node.rawAttrs,e,t);if(a.b!=null)return C1(this.node.rawAttrs,e,t);if(a.shape!=null)return M1(this.node.rawAttrs,e,t);if(a.type!=null)return R1(this.node.rawAttrs,e,t);if(a.list!=null){if(a.list.i!=null||a.list.f!=null)return F1(this.node.rawAttrs,e,t);if(a.list.s!=null)return $1(this.node.rawAttrs,e,t);if(a.list.shape!=null)return D1(this.node.rawAttrs,e,t);if(a.list.b!=null)return P1(this.node.rawAttrs,e,t);if(a.list.type!=null)return E1(this.node.rawAttrs,e,t)}return t}},ta={};Ke(ta,{OP_SCOPE_SUFFIX:()=>hg,abs:()=>Ja,acos:()=>xb,acosh:()=>Ab,add:()=>we,addN:()=>Uh,all:()=>bb,any:()=>vb,argMax:()=>or,argMin:()=>wb,asin:()=>kb,asinh:()=>Ib,atan:()=>Sb,atan2:()=>Tb,atanh:()=>Cb,avgPool:()=>vg,avgPool3d:()=>Mb,basicLSTMCell:()=>Fb,batchNorm:()=>jp,batchNorm2d:()=>$b,batchNorm3d:()=>Db,batchNorm4d:()=>Pb,batchToSpaceND:()=>wg,bincount:()=>kg,bitwiseAnd:()=>_b,booleanMaskAsync:()=>b7,broadcastArgs:()=>Ob,broadcastTo:()=>Ai,buffer:()=>Te,cast:()=>Ue,ceil:()=>zb,clipByValue:()=>Lb,clone:()=>Ia,complex:()=>Rr,concat:()=>lt,concat1d:()=>Wb,concat2d:()=>Xu,concat3d:()=>Bb,concat4d:()=>Vb,conv1d:()=>Ub,conv2d:()=>qp,conv2dTranspose:()=>Hb,conv3d:()=>jb,conv3dTranspose:()=>qb,cos:()=>Xb,cosh:()=>Kb,cosineWindow:()=>t0,cumprod:()=>Yb,cumsum:()=>Zb,denseBincount:()=>Jb,depthToSpace:()=>Qb,depthwiseConv2d:()=>Gh,diag:()=>e4,dilation2d:()=>t4,div:()=>ve,divNoNan:()=>n4,dot:()=>r4,dropout:()=>S7,einsum:()=>hi,elu:()=>Tg,enclosingPowerOfTwo:()=>a3,ensureShape:()=>s4,equal:()=>Sg,erf:()=>i4,euclideanNorm:()=>u4,exp:()=>ls,expandDims:()=>Bt,expm1:()=>d4,eye:()=>Ng,fft:()=>Zh,fill:()=>lr,floor:()=>Rg,floorDiv:()=>Gp,fused:()=>n3,gather:()=>Eg,gatherND:()=>I7,greater:()=>Yp,greaterEqual:()=>Mg,ifft:()=>rp,imag:()=>Zp,image:()=>fe,inTopKAsync:()=>T7,irfft:()=>Yg,isFinite:()=>p4,isInf:()=>c4,isNaN:()=>h4,leakyRelu:()=>Fg,less:()=>bh,lessEqual:()=>Hh,linalg:()=>D7,linspace:()=>m4,localResponseNormalization:()=>f4,log:()=>au,log1p:()=>$g,logSigmoid:()=>y4,logSoftmax:()=>x4,logSumExp:()=>Pg,logicalAnd:()=>tp,logicalNot:()=>_g,logicalOr:()=>Og,logicalXor:()=>A4,losses:()=>P7,lowerBound:()=>b4,matMul:()=>pt,max:()=>fa,maxPool:()=>zg,maxPool3d:()=>v4,maxPoolWithArgmax:()=>w4,maximum:()=>Lg,mean:()=>ap,meshgrid:()=>k4,min:()=>os,minimum:()=>np,mirrorPad:()=>I4,mod:()=>Ku,moments:()=>S4,movingAverage:()=>v7,mul:()=>te,multiRNNCell:()=>T4,multinomial:()=>C4,neg:()=>Vn,norm:()=>Kp,notEqual:()=>Wg,oneHot:()=>vh,ones:()=>Yr,onesLike:()=>N4,op:()=>z,outerProduct:()=>R4,pad:()=>ur,pad1d:()=>E4,pad2d:()=>M4,pad3d:()=>F4,pad4d:()=>$4,pool:()=>D4,pow:()=>tu,prelu:()=>Vg,print:()=>Ag,prod:()=>P4,raggedGather:()=>_4,raggedRange:()=>O4,raggedTensorToTensor:()=>z4,rand:()=>L4,randomGamma:()=>U4,randomNormal:()=>qg,randomStandardNormal:()=>G4,randomUniform:()=>Xh,randomUniformInt:()=>H4,range:()=>nu,real:()=>ru,reciprocal:()=>j4,relu:()=>Jp,relu6:()=>Xg,reshape:()=>Q,reverse:()=>us,reverse1d:()=>q4,reverse2d:()=>X4,reverse3d:()=>K4,reverse4d:()=>Y4,rfft:()=>Jh,round:()=>Kg,rsqrt:()=>Z4,scalar:()=>Ge,scatterND:()=>w7,searchSorted:()=>qh,selu:()=>J4,separableConv2d:()=>Q4,setdiff1dAsync:()=>e7,sigmoid:()=>za,sign:()=>t7,signal:()=>$7,sin:()=>a7,sinh:()=>n7,slice:()=>_e,slice1d:()=>r7,slice2d:()=>s7,slice3d:()=>Qp,slice4d:()=>Kh,softmax:()=>Yh,softplus:()=>Dg,spaceToBatchND:()=>Bg,sparse:()=>_7,sparseToDense:()=>k7,spectral:()=>F7,split:()=>Sa,sqrt:()=>nr,square:()=>En,squaredDifference:()=>Zg,squeeze:()=>Oe,stack:()=>ca,step:()=>Jg,stridedSlice:()=>i7,string:()=>O7,sub:()=>xe,sum:()=>ot,tan:()=>o7,tanh:()=>Ah,tensor:()=>Ve,tensor1d:()=>Vt,tensor2d:()=>er,tensor3d:()=>Qg,tensor4d:()=>l7,tensor5d:()=>u7,tensor6d:()=>d7,tensorScatterUpdate:()=>c7,tile:()=>Qr,topk:()=>h7,transpose:()=>Si,truncatedNormal:()=>m7,unique:()=>f7,unsortedSegmentSum:()=>g7,unstack:()=>Na,upperBound:()=>y7,variable:()=>x7,where:()=>Cr,whereAsync:()=>t3,zeros:()=>An,zerosLike:()=>en});var XO=(e,t,a,n=ta)=>{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`)}},KO=(e,t,a,n=ta)=>{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(da(e.inputNames[0],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(da(e.inputNames[0],t,a))];case"IsInf":return[n.isInf(da(e.inputNames[0],t,a))];case"IsFinite":return[n.isFinite(da(e.inputNames[0],t,a))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Rn(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 I5(e){return!(typeof e=="number"||e.some(t=>t<0))}function Rd(e,t,a){let n=_1(e,a),r=!I5(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=_1(s.shape,n)}),!I5(n))throw new Error(`Non-fully-defined elementShape: ${n}`);return n}function _1(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 YO=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=Ge(0),Bn(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),Rn(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,Bn(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 Ve([],[0].concat(this.elementShape));let a=this.readMany(e);return Rn(this.elementShape,a[0].shape,"TensorArray shape mismatch: "),ca(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 Ve([],[0].concat(this.elementShape));let t=[];for(let n=0;n<this.size();n++)t.push(n);let a=this.readMany(t);return Rn(this.elementShape,a[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${a[0].shape})`),lt(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,Na(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=[];Pe(()=>{t=Q(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]=Q(_e(t,l,u),this.elementShape)}return s});let i=[];for(let o=0;o<e.length;o++)i[o]=o;this.writeMany(i,s)}},o0=class O1{get id(){return this.idTensor.id}constructor(t,a,n,r=-1){this.tensors=t,this.elementShape=a,this.elementDtype=n,t!=null&&t.forEach(s=>{if(n!==s.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${s.dtype}`);Rn(a,s.shape,"TensorList shape mismatch: "),Bn(s)}),this.idTensor=Ge(0),this.maxNumElements=r,Bn(this.idTensor)}copy(){return new O1([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(t){this.tensors.forEach(a=>{(t==null||!t.has(a.id))&&a.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(t,a,n=-1){if(a!==this.elementDtype)throw new Error(`Invalid data types; op elements ${a}, but list elements ${this.elementDtype}`);if(n!==-1&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);Rn(t,this.elementShape,"TensorList shape mismatch: ");let r=Rd(this.elementShape,this.tensors,t);return Pe(()=>{let s=this.tensors.map(i=>Q(i,r));return ca(s,0)})}popBack(t,a){if(a!==this.elementDtype)throw new Error(`Invalid data types; op elements ${a}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n=Rd(this.elementShape,this.tensors,t),r=this.tensors.pop();return r.kept=!1,Rn(r.shape,t,"TensorList shape mismatch: "),Q(r,n)}pushBack(t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(Rn(t.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Bn(t),this.tensors.push(t)}resize(t){if(t<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${t}`);if(this.maxNumElements!==-1&&t>this.maxNumElements)throw new Error(`TensorListResize input size ${t} is greater maxNumElement ${this.maxNumElements}.`);let a=new O1([],this.elementShape,this.elementDtype,this.maxNumElements);a.tensors.length=t;for(let n=0;n<Math.min(this.tensors.length,t);++n)a.tensors[n]=this.tensors[n];return a}getItem(t,a,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(t<0||t>this.tensors.length)throw new Error(`Trying to access element ${t} in a list with ${this.tensors.length} elements.`);if(this.tensors[t]==null)throw new Error(`element at index ${t} is null.`);Rn(this.tensors[t].shape,a,"TensorList shape mismatch: ");let r=Rd(this.elementShape,this.tensors,a);return Q(this.tensors[t],r)}setItem(t,a){if(a.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${a.dtype}, but list elements ${this.elementDtype}`);if(t<0||this.maxNumElements!==-1&&t>=this.maxNumElements)throw new Error(`Trying to set element ${t} in a list with max ${this.maxNumElements} elements.`);Rn(this.elementShape,a.shape,"TensorList shape mismatch: "),Bn(a),this.tensors[t]!=null&&(this.tensors[t].kept=!1),this.tensors[t]=a}gather(t,a,n){if(a!==this.elementDtype)throw new Error(`Invalid data types; op elements ${a}, but list elements ${this.elementDtype}`);Rn(this.elementShape,n,"TensorList shape mismatch: "),t=t.slice(0,this.size());let r=Rd(this.elementShape,this.tensors,n);return t.length===0?Ve([],[0].concat(r)):Pe(()=>{let s=t.map(i=>Q(this.tensors[i],r));return ca(s,0)})}concat(t,a){if(t&&t!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${t}`);Rn(this.elementShape,a,"TensorList shape mismatch: ");let n=Rd(this.elementShape,this.tensors,a);return this.size()===0?Ve([],[0].concat(n)):Pe(()=>{let r=this.tensors.map(s=>Q(s,n));return lt(r,0)})}};function ZO(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);Rn(r,t,"TensorList shape mismatch: ");let s=Na(e);return new o0(s,t,n)}function JO(e,t,a,n){return new o0([],e,t,n)}function QO(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 o0([],a,e.dtype,n),i=Na(e,0);return t.forEach((o,l)=>{s.setItem(o,i[l])}),s}function ez(e,t,a){let n=0,r=t.map(d=>(n+=d,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=_1(s,a),o=n===0?0:e.size/n,l=Pe(()=>{let d=[];e=Q(e,[1,n,o]);for(let c=0;c<t.length;++c){let p=[0,c===0?0:r[c-1],0],h=[1,t[c],o];d[c]=Q(_e(e,p,h),i)}return e.dispose(),d}),u=new o0([],a,e.dtype,t.length);for(let d=0;d<l.length;d++)u.setItem(d,l[d]);return u}var tz=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(d=>d.id),l=await i[0].data();i.forEach(d=>{!d.kept&&o.indexOf(d.id)===-1&&d.dispose()});let u=s;for(;l[0];){let d=u;u=await a.functionMap[n].executeFunctionAsync(u,a.tensorArrayMap,a.tensorListMap);let c=u.map(h=>h.id);d.forEach(h=>{!h.kept&&o.indexOf(h.id)===-1&&c.indexOf(h.id)===-1&&h.dispose()});let p=await a.functionMap[r].executeFunctionAsync(u,a.tensorArrayMap,a.tensorListMap);l=await p[0].data(),p.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[Ir(n)]}case"Switch":{let n=k("pred",e,t,a),r=k("data",e,t,a);return r.kept||(r=Ir(r)),(await n.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{let n=e.inputNames.find(r=>da(r,t,a)!==void 0);if(n){let r=da(n,t,a);return[Ir(r)]}return}case"Enter":{let n=k("frameName",e,t,a),r=k("tensor",e,t,a);return a.enterFrame(n),[Ir(r)]}case"Exit":{let n=k("tensor",e,t,a);return a.exitFrame(),[Ir(n)]}case"NextIteration":{let n=k("tensor",e,t,a);return a.nextIteration(),[Ir(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),d=new YO(u,r,n,s,l,i,o);return a.addTensorArray(d),[d.idTensor,Ge(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[Ge(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=QO(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=JO(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=ZO(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=ez(n,s,r);return a.addTensorList(i),[i.idTensor]}case"TensorListLength":{let n=k("tensorListId",e,t,a),r=a.getTensorList(n.id);return[Ge(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 S5(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 d=k("strides",e,t,a),c=lh(e,t,a),p=k("dataFormat",e,t,a).toUpperCase(),h=k("dilations",e,t,a),[m,f]=k("args",e,t,a);i&&(f=m,m=void 0);let g=k("leakyreluAlpha",e,t,a);return{stride:d,pad:c,dataFormat:p,dilations:h,biasArg:m,preluArg:f,activationFunc:r,leakyreluAlpha:g}}var az=(e,t,a,n=ta)=>{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=lh(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:d,leakyreluAlpha:c}=S5(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:d,preluActivationWeights:u,leakyreluAlpha:c})]}case"FusedDepthwiseConv2dNative":{let{stride:r,pad:s,dataFormat:i,dilations:o,biasArg:l,preluArg:u,activationFunc:d,leakyreluAlpha:c}=S5(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:d,preluActivationWeights:u,leakyreluAlpha:c})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let r=k("outputShape",e,t,a),s=k("strides",e,t,a),i=lh(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=lh(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],d=i[2];return[n.dilation2d(k("x",e,t,a),k("filter",e,t,a),[o,l],s,[u,d],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},nz=(e,t,a,n=ta)=>{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"RandomUniformInt":return[n.randomUniformInt(k("shape",e,t,a),k("minval",e,t,a),k("maxval",e,t,a),k("seed",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 n1(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 rz=async(e,t,a,n,r=ta)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:s,scores:i,maxOutputSize:o,iouThreshold:l,scoreThreshold:u,softNmsSigma:d}=n1(e,t,a),c=await r.image.nonMaxSuppressionWithScoreAsync(s,i,o,l,u,d);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:s,scores:i,maxOutputSize:o,iouThreshold:l,scoreThreshold:u}=n1(e,t,a),d=k("padToMaxOutputSize",e,t,a),c=await r.image.nonMaxSuppressionPaddedAsync(s,i,o,l,u,d);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:s,scores:i,maxOutputSize:o,iouThreshold:l,scoreThreshold:u}=n1(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`)}},sz=(e,t,a,n=ta)=>{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`)}},iz=(e,t,a,n=ta)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let r=k("default",e,t,a);return[da(e.name,t,a)||r];case"Placeholder":return[da(e.name,t,a)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let d=k("x",e,t,a);return[Ir(d)]}case"IdentityN":return k("x",e,t,a).map(d=>Ir(d));case"Snapshot":let s=k("x",e,t,a);return[Ir(s)];case"Shape":return[n.tensor1d(k("x",e,t,a).shape,"int32")];case"ShapeN":return k("x",e,t,a).map(d=>n.tensor1d(d.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 d=0;d<o.length;d++)console.log(Array.prototype.slice.call(o[d].dataSync()).slice(0,u));return[i];default:throw TypeError(`Node type ${e.op} is not implemented`)}},oz=class{get id(){return this.handle.id}constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Ge(0),this.tensorMap=new Map,Bn(this.handle)}clearAndClose(){this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Ge(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(),Pe(()=>{let n=Na(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];Bn(l),this.tensorMap.set(o,l)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);let a=await e.data();return Pe(()=>{let n=[];for(let r=0;r<a.length;r++){let s=a[r],i=this.findWithDefault(s,t);n.push(i)}return ca(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}`)}},lz=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 oz(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`)}},uz=(e,t,a,n=ta)=>{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`)}},dz=(e,t,a,n=ta)=>{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))];case"BitwiseAnd":return[n.bitwiseAnd(k("a",e,t,a),k("b",e,t,a))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},pz=(e,t,a,n=ta)=>{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[d,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:d,activation:s,preluActivationWeights:c,leakyreluAlpha:u})];case"MatrixBandPart":return[n.linalg.bandPart(k("a",e,t,a),k("numLower",e,t,a),k("numUpper",e,t,a))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},cz=(e,t,a,n=ta)=>{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))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},hz=(e,t,a,n=ta)=>{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`)}},mz=(e,t,a,n=ta)=>{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),d=k("binaryOutput",e,t,a);return[n.denseBincount(o,l,u,d)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},fz=(e,t,a,n=ta)=>{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),d=k("newAxisMask",e,t,a),c=k("shrinkAxisMask",e,t,a),p=k("x",e,t,a);return[n.stridedSlice(p,r,s,i,o,l,u,d,c)]}case"Pack":return Pe(()=>{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 d=v.arraysEqual(u.shape,i);if(!d&&!v.arraysEqual(n.squeeze(u).shape,o))throw new Error("the input tensors shape does not match");return d?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))]}case"TensorScatterUpdate":{let r=k("indices",e,t,a),s=k("values",e,t,a),i=k("tensor",e,t,a);return[n.tensorScatterUpdate(i,r,s)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},gz=(e,t,a,n=ta)=>{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`)}},yz=(e,t,a,n=ta)=>{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`)}},xz=(e,t,a,n=ta)=>{switch(e.op){case"StaticRegexReplace":return[n.string.staticRegexReplace(k("input",e,t,a),k("pattern",e,t,a),k("rewrite",e,t,a),k("replaceGlobal",e,t,a))];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`)}},Az=(e,t,a,n=ta)=>{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"EnsureShape":return[n.ensureShape(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 T5(e,t,a,n,r=Pe){let s=((i,o,l)=>{switch(i.category){case"arithmetic":return r(()=>XO(i,o,l));case"basic_math":return r(()=>KO(i,o,l));case"control":return tz(i,o,l);case"convolution":return r(()=>az(i,o,l));case"creation":return r(()=>nz(i,o,l));case"dynamic":return rz(i,o,l);case"evaluation":return r(()=>sz(i,o,l));case"image":return r(()=>uz(i,o,l));case"graph":return r(()=>iz(i,o,l));case"logical":return r(()=>dz(i,o,l));case"matrices":return r(()=>pz(i,o,l));case"normalization":return r(()=>cz(i,o,l));case"ragged":return r(()=>hz(i,o,l));case"reduction":return r(()=>mz(i,o,l));case"slice_join":return r(()=>fz(i,o,l));case"sparse":return r(()=>gz(i,o,l));case"spectral":return r(()=>yz(i,o,l));case"string":return r(()=>xz(i,o,l));case"transformation":return r(()=>Az(i,o,l));case"hash_table":return lz(i,o,l,n);case"custom":let u=l6(i.op);if(u&&u.customExecutor)return u.customExecutor(new qO(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 C5=class{constructor(e={},t={},a={},n={},r){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=a,this.functionMap=n,this.parseNodeNameCache=r,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 N5(e,t,a,n){let r=new Set,s=[],i=null,o=null,l=new Set,u=new Set(Object.keys(e).map(p=>Za(p)[0]));n=n||[];let d=new Set(n.map(p=>Za(p.name)[0])),c=[...t];for(;c.length>0;){let p=c.pop();if((mi(p)||Cz(p)||Nz(p))&&i==null&&(i=p,o=i.children.map(h=>h.name).filter(h=>r.has(h))),r.add(p.name),a[p.name]==null&&!u.has(p.name)&&!d.has(p.name)){if(p.inputs.length===0){s.push(p.name);continue}p.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 bz(e,t){let{usedNodes:a,inputs:n}=t,r=Object.keys(n).map(g=>Za(g)[0]).map(g=>e.nodes[g]),s=e.initNodes||[],i=g=>a.has(typeof g=="string"?g:g.name);function o(g){return[...new Map(g.map(y=>[y.name,y])).values()]}let l=o([...r,...e.weights,...s]).filter(i),u=o([...l,...Object.values(e.nodes)]).filter(i),d=new Map(u.map(g=>[g.name,g])),c={};for(let g of u){c[g.name]=c[g.name]||0;for(let y of g.children)i(y)||(c[y.name]=Number.POSITIVE_INFINITY),c[y.name]=(c[y.name]||0)+1}let p=Object.entries(c).filter(([,g])=>g===0).map(([g])=>g),h=[...p];for(;p.length>0;){let g=p.pop(),y=d.get(g);for(let x of y.children.filter(i))--c[x.name]===0&&(h.push(x.name),p.push(x.name))}let m=h.map(g=>d.get(g)),f=vz(m,l);return wz(f,l),f}function vz(e,t){let a=new Map(e.map(s=>[s.name,s])),n=t.map(s=>s.name),r=new Set(n);for(;n.length>0;){let s=n.pop(),i=a.get(s);for(let o of i.children)!a.has(o.name)||r.has(o.name)||(r.add(o.name),n.push(o.name))}return e.filter(s=>r.has(s.name))}var th=class extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}};function wz(e,t){let a=new Map(e.map((o,l)=>[o.name,l])),n=new Set(t.map(o=>o.name)),r=o=>n.has(typeof o=="string"?o:o.name),s=new Set(e.map(o=>o.name)),i=o=>s.has(typeof o=="string"?o:o.name);for(let o of e){for(let l of o.children.filter(i)){if(!a.has(l.name))throw new th(`Child ${l.name} of node ${o.name} is unreachable.`);if(a.get(o.name)>a.get(l.name))throw new th(`Node ${o.name} is scheduled to run after its child ${l.name}.`)}if(!r(o))for(let l of o.inputs){if(!a.has(l.name))throw new th(`Input ${l.name} of node ${o.name} is unreachable.`);if(a.get(l.name)>a.get(o.name))throw new th(`Node ${o.name} is scheduled to run before its input ${l.name}.`)}}}function kz(e){let t=new Map(e.map((o,l)=>[o.name,l])),a=Number.MAX_SAFE_INTEGER,n=e.map((o,l)=>mi(o)?a:l),r=o=>{let l=n[t.get(o.name)];return l==null?-1:l},s=e.map((o,l)=>o.children.map(r).reduce((u,d)=>Math.max(u,d),n[l])),i=new Map;for(let o=0;o<e.length;++o){let l=s[o];if(l===a)continue;let u=e[o],d=e[l];i.has(d.name)||i.set(d.name,[]),i.get(d.name).push(u)}return i}var Iz=new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),Sz=new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),Tz=new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function mi(e){return Iz.has(e.op)}function Cz(e){return Sz.has(e.op)}function Nz(e){return Tz.has(e.op)}var R5=class E6{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(t){let a=Object.keys(t).map(n=>t[n].map(r=>r.id));this._weightIds=[].concat(...a),this._weightMap=t}set resourceManager(t){this._resourceManager=t}get inputs(){return this._inputs.map(t=>({name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(t=>({name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(t=>t.signatureKey||t.name)}get outputNodes(){return this._outputs.map(t=>{let a=t.signatureKey||t.name;return t.defaultOutput?`${a}:${t.defaultOutput}`:a})}get functions(){return Object.keys(this._functions).reduce((t,a)=>(t[a]=this._functions[a].signature,t),{})}constructor(t,a){this.graph=t,this.parent=a,this.compiledMap=new Map,this.parseNodeNameCache=new Map,this._weightMap={},this.SEPARATOR=",",this._functions={},this._functionExecutorMap={},this.keepIntermediateTensors=!1,this._outputs=t.outputs,this._inputs=t.inputs,this._initNodes=t.initNodes,this._signature=t.signature,this._functions=t.functions,t.functions!=null&&Object.keys(t.functions).forEach(n=>{this._functionExecutorMap[n]=new E6(t.functions[n],this)})}getCompilationKey(t,a){let n=t.map(s=>s.name).sort(),r=a.map(s=>s.name).sort();return n.join(this.SEPARATOR)+"--"+r.join(this.SEPARATOR)}compile(t,a){let n=N5(t,a,this.weightMap,this._initNodes),{missingInputs:r,dynamicNode:s,syncInputs:i}=n;if(s!=null)throw new Error(`This execution contains the node '${s.name}', which has the dynamic op '${s.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${i}]`);if(r.length>0){let u=a.map(c=>c.name),d=Object.keys(t);throw new Error(`Cannot compute the outputs [${u}] from the provided inputs [${d}]. Missing the following inputs: [${r}]`)}let o=bz(this.graph,n),l=kz(o);return{orderedNodes:o,nodeLiveUntilMap:l}}cloneAndKeepTensor(t){if(t==null)return null;let a=t.clone();return Bn(a),a}cloneTensorList(t){return t?t.map(a=>this.cloneAndKeepTensor(a)):null}cloneTensorMap(t){return Object.fromEntries(Object.entries(t).map(([a,n])=>[a,this.cloneTensorList(n)]))}execute(t,a){this.disposeIntermediateTensors(),t=this.mapInputs(t);let n=Object.keys(t).sort();this.checkInputs(t),this.checkInputShapeAndType(t),a=this.mapOutputs(a),this.checkOutputs(a);let r=n.map(p=>this.graph.nodes[Za(p)[0]]),s=a.map(p=>Za(p)[0]),i=new Set(s),o=s.map(p=>this.graph.nodes[p]);o.length===0&&(o=this._outputs);let l=this.getCompilationKey(r,o),u=this.compiledMap.get(l);u==null&&(u=this.compile(t,o),this.compiledMap.set(l,u));try{this.keepIntermediateTensors=B().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(p){this.keepIntermediateTensors=!1,console.warn(p.message)}let d={},c={};return Pe(()=>{let p=new C5(this.weightMap,d,c,this.functionExecutorMap,this.parseNodeNameCache),h=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(t).forEach(y=>{let[x,A]=Za(y,p),b=[];b[A]=t[y],h[x]=b,this.keepIntermediateTensors&&(this.clonedTensorsMap[x]=this.cloneTensorList(b))});let m=this.getFrozenTensorIds(h),{orderedNodes:f,nodeLiveUntilMap:g}=u;for(let y of f){if(h[y.name])continue;let x=T5(y,h,p,this._resourceManager);if(v.isPromise(x))throw new Error(`The execution of the op '${y.op}' returned a promise. Please use model.executeAsync() instead.`);h[y.name]=x,this.keepIntermediateTensors&&(this.clonedTensorsMap[y.name]=this.cloneTensorList(x)),this.checkTensorForDisposalWithNodeLiveUntilInfo(y,h,p,m,i,g.get(y.name))}return this.parent==null&&p.dispose(m),a.map(y=>da(y,h,p))})}getFrozenTensorIds(t){let a=[].concat.apply([],Object.keys(t).map(n=>t[n]).map(n=>n.map(r=>r.id)));return new Set(a)}checkTensorForDisposal(t,a,n,r,s,i,o){if(!(mi(a)||i.has(t))){for(let l of n[t])l!=null&&(o[l.id]=(o[l.id]||0)+a.children.length);for(let l of a.inputs){if(mi(l))continue;let u=v5(l.name,n,r);if(u!=null)for(let d of u){if(!d||d.kept||s.has(d.id))continue;let c=o[d.id];c===1?(d.dispose(),delete o[d.id]):c!=null&&o[d.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(t,a,n,r,s,i){function o(l){return mi(l)||s.has(l.name)}if(!(mi(t)||i==null))for(let l of i){if(o(l))continue;let u=v5(l.name,a,n);for(let d of u)!d||d.kept||r.has(d.id)||d.dispose()}}async executeAsync(t,a){return this._executeAsync(t,a)}disposeIntermediateTensors(){this.clonedTensorsMap&&(Object.values(this.clonedTensorsMap).forEach(t=>{for(let a of t)a&&!a.isDisposed&&a.dispose()}),this.clonedTensorsMap=null)}getIntermediateTensors(){return this.clonedTensorsMap}async _executeAsync(t,a,n=!1,r={},s={}){this.disposeIntermediateTensors(),n||(t=this.mapInputs(t),this.checkInputs(t),this.checkInputShapeAndType(t),a=this.mapOutputs(a),this.checkOutputs(a));try{this.keepIntermediateTensors=B().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(p){this.keepIntermediateTensors=!1,console.warn(p.message)}let i=new C5(this.weightMap,r,s,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));let o=await this.executeWithControlFlow(t,i,a,n),l=a.map(p=>da(p,o,i)),u=l.map(p=>p.id),d=Object.keys(t).map(p=>t[p].id),c=new Set([...u,...d,...this.weightIds]);return Object.values(o).forEach(p=>{p.forEach(h=>{h&&!h.isDisposed&&!c.has(h.id)&&h.dispose()})}),this.parent==null&&i.dispose(c),l}async executeFunctionAsync(t,a,n){let r=t.reduce((s,i,o)=>(s[this.inputs[o].name]=i,s),{});return this._executeAsync(r,this.outputNodes,!0,a,n)}async executeWithControlFlow(t,a,n,r){let s=Object.keys(t),i=s.map(b=>this.graph.nodes[Za(b)[0]]),o=n.map(b=>Za(b)[0]),l=new Set(o),u=o.map(b=>this.graph.nodes[b]);u.length===0&&(u=this._outputs);let{usedNodes:d,missingInputs:c,dynamicNode:p,syncInputs:h}=N5(t,u,this.weightMap,this._initNodes),m=[...i,...this.graph.weights,...this._initNodes||[]].map(b=>({node:b,contexts:a.currentContext})),f=Object.assign({},this.weightMap);Object.keys(t).forEach(b=>{let[w,S]=Za(b),C=[];C[S]=t[b],f[w]=C});let g={},y=this.getFrozenTensorIds(f),x={};for(;m.length>0;){let b=this.processStack(i,m,a,f,x,y,l,g,d);await Promise.all(b)}p==null&&!r&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let A=u.filter(b=>!mi(b)&&!da(b.name,f,a)).map(b=>b.name);if(A.length>0){let b="";throw p!=null&&(b=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${h}]`),new Error(`Cannot compute the outputs [${A}] from the provided inputs [${s}]. Consider providing the following inputs: [${c}]. ${b}`)}return f}processStack(t,a,n,r,s,i,o,l,u){let d=[];for(;a.length>0;){let c=a.pop();n.currentContext=c.contexts;let p="";if(c.node.op==="Enter"&&k("isConstant",c.node,r,n)&&([p]=kr(c.node.name,n)),r[c.node.name]==null){let h=T5(c.node,r,n,this._resourceManager);p||([p]=kr(c.node.name,n));let m=n.currentContext;v.isPromise(h)?d.push(h.then(f=>(r[p]=f,this.keepIntermediateTensors&&(this.clonedTensorsMap[p]=this.cloneTensorList(f)),n.currentContext=m,this.checkTensorForDisposal(p,c.node,r,n,i,o,l),this.processChildNodes(c.node,a,n,r,s,u),f))):(r[p]=h,this.keepIntermediateTensors&&(this.clonedTensorsMap[p]=this.cloneTensorList(h)),this.checkTensorForDisposal(p,c.node,r,n,i,o,l),this.processChildNodes(c.node,a,n,r,s,u))}else this.processChildNodes(c.node,a,n,r,s,u)}return d}processChildNodes(t,a,n,r,s,i){t.children.forEach(o=>{let[l]=kr(o.name,n);s[l]||!i.has(o.name)||(o.op==="Merge"?o.inputNames.some(u=>!!da(u,r,n))&&(s[l]=!0,a.push({contexts:n.currentContext,node:o})):o.inputNames.every(u=>!!da(u,r,n))&&(s[l]=!0,a.push({contexts:n.currentContext,node:o})))})}dispose(){Object.keys(this.weightMap).forEach(t=>this.weightMap[t].forEach(a=>a.dispose()))}checkInputShapeAndType(t){Object.keys(t).forEach(a=>{let n=t[a],[r]=Za(a),s=this.graph.nodes[r];if(s.attrParams.shape&&s.attrParams.shape.value){let i=s.attrParams.shape.value,o=i.length===n.shape.length&&n.shape.every((l,u)=>i[u]===-1||i[u]===l);v.assert(o,()=>`The shape of dict['${s.name}'] provided in model.execute(dict) must be [${i}], but was [${n.shape}]`)}s.attrParams.dtype&&s.attrParams.dtype.value&&v.assert(n.dtype===s.attrParams.dtype.value,()=>`The dtype of dict['${s.name}'] provided in model.execute(dict) must be ${s.attrParams.dtype.value}, but was ${n.dtype}`)})}mapInputs(t){var a,n;let r={};for(let s in t){let i=(n=(a=this._signature)===null||a===void 0?void 0:a.inputs)===null||n===void 0?void 0:n[s];i!=null?r[i.name]=t[s]:r[s]=t[s]}return r}checkInputs(t){let a=Object.keys(t).filter(n=>{let[r]=Za(n);return this.graph.nodes[r]==null});if(a.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${a}] that are not part of graph`)}mapOutputs(t){return t.map(a=>{var n,r;let s=(r=(n=this._signature)===null||n===void 0?void 0:n.outputs)===null||r===void 0?void 0:r[a];return s!=null?s.name:a},{})}checkOutputs(t){t.forEach(a=>{let[n]=Za(a);if(!this.graph.nodes[n])throw new Error(`The output '${a}' is not found in the graph`)})}},Rz=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]}},Ez="?tfjs-format=file",Mz="model.json",ec=class{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}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 Rz}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=>t.getWeightStream==null?this.loadSync(t):this.loadStreaming(t)):this.loadSync(e)}loadSync(e){let t=this.io.decodeWeights(e.weightData,e.weightSpecs);return this.loadWithWeightMap(e,t)}async loadStreaming(e){if(e.getWeightStream==null)throw new Error("Model artifacts missing streamWeights function");let t=await lb(e.getWeightStream(),e.weightSpecs);return this.loadWithWeightMap(e,t)}loadWithWeightMap(e,t){this.artifacts=e;let a=this.artifacts.modelTopology,n=this.artifacts.signature;if(this.artifacts.userDefinedMetadata!=null){let r=this.artifacts.userDefinedMetadata;r.signature!=null&&(n=r.signature),r.structuredOutputKeys!=null&&(this.structuredOutputKeys=r.structuredOutputKeys)}if(this.signature=n,this.version=`${a.versions.producer}.${a.versions.minConsumer}`,this.executor=new R5(w5.Instance.transformGraph(a,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(t),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){let r=w5.Instance.transformGraph(e.modelInitializer);this.initializer=new R5(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 yt?[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 yt)&&!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&&J(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}};async function x3(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=$z(e));let n=new ec(e,t,a);return await n.load(),n}function Fz(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 ec(t);return a.load(),a}function $z(e){return e.endsWith("/")||(e=e+"/"),`${e}${Mz}${Ez}`}var Dz="4.17.0";function Ie(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 Pz=Fn.whereImpl,A3=class M6 extends du{nextDataId(){return M6.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new hp(this,St())}write(t,a,n){this.firstUse&&(this.firstUse=!1,B().get("IS_NODE")&&I.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 r={id:this.nextDataId()};return this.data.set(r,{values:t,dtype:n,refCount:1}),r}makeTensorInfo(t,a,n){let r;if(a==="string"&&n!=null&&n.length>0&&v.isString(n[0])){let s=n.map(i=>v.encodeString(i));r=this.write(s,t,a)}else r=this.write(n,t,a);return{dataId:r,shape:t,dtype:a}}refCount(t){return this.data.has(t)?this.data.get(t).refCount:0}incRef(t){let a=this.data.get(t);a.refCount++}decRef(t){if(this.data.has(t)){let a=this.data.get(t);a.refCount--}}move(t,a,n,r,s){this.data.set(t,{values:a,dtype:r,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(t){return this.readSync(t)}readSync(t){let{dtype:a,complexTensorInfos:n}=this.data.get(t);if(a==="complex64"){let r=this.readSync(n.real.dataId),s=this.readSync(n.imag.dataId);return I.mergeRealAndImagArrays(r,s)}return v.convertBackendValuesAndArrayBuffer(this.data.get(t).values,a)}bufferSync(t){let a=this.readSync(t.dataId);if(t.dtype==="string")try{let n=a.map(r=>v.decodeString(r));return Te(t.shape,t.dtype,n)}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return Te(t.shape,t.dtype,a)}makeOutput(t,a,n){return St().makeTensorFromTensorInfo(this.makeTensorInfo(a,n,t),this)}disposeData(t,a=!1){if(this.data.has(t)){if(this.data.get(t).refCount--,!a&&this.data.get(t).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(t);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(t)}return!0}disposeIntermediateTensorInfo(t){this.disposeData(t.dataId)}async time(t){let a=v.now();return t(),{kernelMs:v.now()-a}}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(t){Ie([t],"where");let a=this.readSync(t.dataId);return Pz(t.shape,a)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};A3.nextDataId=0;var b3={};Ke(b3,{addImpl:()=>D6,bincountImpl:()=>w3,bincountReduceImpl:()=>P6,bitwiseAndImpl:()=>_6,castImpl:()=>$6,ceilImpl:()=>O6,concatImpl:()=>k3,equalImpl:()=>z6,expImpl:()=>W6,expm1Impl:()=>V6,floorDivImpl:()=>G6,floorImpl:()=>U6,gatherNdImpl:()=>H6,gatherV2Impl:()=>j6,greaterEqualImpl:()=>X6,greaterImpl:()=>q6,lessEqualImpl:()=>Y6,lessImpl:()=>K6,linSpaceImpl:()=>Z6,logImpl:()=>J6,maxImpl:()=>Q6,maximumImpl:()=>ev,minimumImpl:()=>tv,multiplyImpl:()=>I3,negImpl:()=>av,notEqualImpl:()=>nv,prodImpl:()=>rv,raggedGatherImpl:()=>sv,raggedRangeImpl:()=>iv,raggedTensorToTensorImpl:()=>ov,rangeImpl:()=>T3,rsqrtImpl:()=>lv,scatterImpl:()=>xi,sigmoidImpl:()=>DL,simpleAbsImpl:()=>F6,sliceImpl:()=>Sh,sparseFillEmptyRowsImpl:()=>dv,sparseReshapeImpl:()=>pv,sparseSegmentReductionImpl:()=>C3,sqrtImpl:()=>OL,squaredDifferenceImpl:()=>cv,staticRegexReplaceImpl:()=>hv,stridedSliceImpl:()=>mv,stringNGramsImpl:()=>N3,stringSplitImpl:()=>R3,stringToHashBucketFastImpl:()=>E3,subImpl:()=>fv,tileImpl:()=>gv,topKImpl:()=>xv,transposeImpl:()=>S3,uniqueImpl:()=>F3});function F6(e){let t=new Float32Array(e.length);for(let a=0;a<e.length;++a)t[a]=Math.abs(e[a]);return t}var _z=e=>{let{x:t}=e.inputs,a=e.backend;Ie(t,"abs");let n=new Float32Array(v.sizeFromShape(t.shape)),r=a.data.get(t.dataId).values;return n=F6(r),a.makeOutput(n,t.shape,t.dtype)},Oz={kernelName:cu,backendName:"cpu",kernelFunc:_z};function Pt(e){return(t,a,n,r,s)=>{let i=I.assertAndGetBroadcastShape(t,a),o=i.length,l=v.computeStrides(i),u=v.sizeFromShape(i),d=v.getTypedArrayFromDType(s,u),c=t.length,p=a.length,h=v.computeStrides(t),m=v.computeStrides(a),f=I.getBroadcastDims(t,i),g=I.getBroadcastDims(a,i);if(f.length+g.length===0)for(let y=0;y<d.length;++y)d[y]=e(n[y%n.length],r[y%r.length]);else for(let y=0;y<d.length;++y){let x=v.indexToLoc(y,o,l),A=x.slice(-c);f.forEach(C=>A[C]=0);let b=v.locToIndex(A,c,h),w=x.slice(-p);g.forEach(C=>w[C]=0);let S=v.locToIndex(w,p,m);d[y]=e(n[b],r[S])}return[d,i]}}function Qa(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 zz={kernelName:xp,backendName:"cpu",kernelFunc:Qa};function Ih(e,t,a="float32"){if(a==="complex64"){let r=Ih(e,t,"float32"),s=Ih(e,t,"float32");return Qa({inputs:{real:r,imag:s},backend:e})}let n=v.makeZerosTypedArray(v.sizeFromShape(t),a);return e.makeTensorInfo(t,a,n)}function sr(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 Lz={kernelName:ho,backendName:"cpu",kernelFunc:sr};function Ti(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 Wz={kernelName:Ep,backendName:"cpu",kernelFunc:Ti};function $6(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]=Pt((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 ds(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{dtype:s}=n;if(s==="complex64"){if(r.dtype==="complex64")return sr({inputs:{x:r},backend:a});let d=Ih(a,r.shape,r.dtype),c=ds({inputs:{x:r},backend:a,attrs:{dtype:"float32"}}),p=Qa({inputs:{real:c,imag:d},backend:a});return a.disposeIntermediateTensorInfo(d),a.disposeIntermediateTensorInfo(c),p}if(r.dtype==="complex64"){let d=Ti({inputs:{input:r},backend:a}),c=ds({inputs:{x:d},backend:a,attrs:{dtype:s}});return a.disposeIntermediateTensorInfo(d),c}if(!v.hasEncodingLoss(r.dtype,s)){let d=sr({inputs:{x:r},backend:a});return{dataId:d.dataId,shape:d.shape,dtype:s}}let i=a.data.get(r.dataId).values,[o,l,u]=$6(i,r.shape,r.dtype,s);return a.makeTensorInfo(o,l,u)}var Bz={kernelName:qi,backendName:"cpu",kernelFunc:ds};function Kt(e,t,a,n){return a==null?({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;Ie([i,o],e);let u=l.data.get(i.dataId).values,d=l.data.get(o.dataId).values,c=i.dtype==="string"?I.fromUint8ToStringArray(u):u,p=i.dtype==="string"?I.fromUint8ToStringArray(d):d,h=n||i.dtype,[m,f]=t(i.shape,o.shape,c,p,h);return l.makeTensorInfo(f,h,m)}:({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;if(i.dtype==="complex64"||o.dtype==="complex64"){let u=ds({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),d=l.data.get(u.dataId),c=d.complexTensorInfos.real,p=d.complexTensorInfos.imag,h=l.data.get(c.dataId).values,m=l.data.get(p.dataId).values,f=ds({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(f.dataId),y=g.complexTensorInfos.real,x=g.complexTensorInfos.imag,A=l.data.get(y.dataId).values,b=l.data.get(x.dataId).values,[w,S,C]=a(i.shape,o.shape,h,m,A,b),N=l.makeTensorInfo(C,"float32",w),M=l.makeTensorInfo(C,"float32",S),F=Qa({inputs:{real:N,imag:M},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(f),l.disposeIntermediateTensorInfo(N),l.disposeIntermediateTensorInfo(M),F}else{let u=l.data.get(i.dataId).values,d=l.data.get(o.dataId).values,c=n||i.dtype,[p,h]=t(i.shape,o.shape,u,d,c);return l.makeTensorInfo(h,c,p)}}}function v3(e){return(t,a,n,r,s,i)=>{let o=I.assertAndGetBroadcastShape(t,a),l=v.sizeFromShape(o),u=o.length,d=v.computeStrides(o),c=v.getTypedArrayFromDType("float32",l),p=v.getTypedArrayFromDType("float32",l),h=I.getBroadcastDims(t,o),m=I.getBroadcastDims(a,o),f=I.mergeRealAndImagArrays(n,r),g=I.mergeRealAndImagArrays(s,i),y=t.length,x=v.computeStrides(t),A=a.length,b=v.computeStrides(a);if(h.length+m.length===0)for(let w=0;w<c.length;w++){let S=w%f.length,C=w%g.length,N=e(f[S*2],f[S*2+1],g[C*2],g[C*2+1]);c[w]=N.real,p[w]=N.imag}else for(let w=0;w<c.length;w++){let S=v.indexToLoc(w,u,d),C=S.slice(-y);h.forEach(T=>C[T]=0);let N=v.locToIndex(C,y,x),M=S.slice(-A);m.forEach(T=>M[T]=0);let F=v.locToIndex(M,A,b),E=e(f[N*2],f[N*2+1],g[F*2],g[F*2+1]);c[w]=E.real,p[w]=E.imag}return[c,p,o]}}var D6=Pt((e,t)=>e+t),Vz=v3((e,t,a,n)=>({real:e+a,imag:t+n})),su=Kt(Mr,D6,Vz),Uz={kernelName:Mr,backendName:"cpu",kernelFunc:su};function w3(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 P6(e,t,a,n=!1){let r=e.shape[0],s=e.shape[1],i=Te([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}var _6=Pt((e,t)=>e&t),Gz=Kt(ji,_6),Hz={kernelName:ji,backendName:"cpu",kernelFunc:Gz};function dr(e){return(t,a,n)=>{let r=v.getArrayFromDType(a,t.length);for(let s=0;s<t.length;++s)r[s]=e(t[s],n);return r}}function ct(e,t,a){let n=dr(t);return Os(e,n,a)}function Os(e,t,a){return({inputs:n,attrs:r,backend:s})=>{let{x:i}=n;Ie(i,e);let o=s,l=o.data.get(i.dataId).values,u;if(i.dtype==="string"){if(!Array.isArray(l))throw new Error("String tensor's value was not an instance of Array");u=I.fromUint8ToStringArray(l)}else u=l;let d=a||i.dtype,c=t(u,d,r);return o.makeTensorInfo(i.shape,d,c)}}var O6=dr(e=>Math.ceil(e)),jz=Os(cs,O6),qz={kernelName:cs,backendName:"cpu",kernelFunc:jz};function k3(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"?I.fromUint8ToStringArray(i.vals):i.vals,l=0;for(let u=0;u<i.shape[0];++u){let d=u*t[1]+s;for(let c=0;c<i.shape[1];++c)r[d+c]=o[l++]}s+=i.shape[1]})}return r}var z6=Pt((e,t)=>e===t?1:0),L6=Kt(ms,z6,null,"bool"),Xz={kernelName:ms,backendName:"cpu",kernelFunc:L6},W6=dr(e=>Math.exp(e)),B6=Os(fs,W6,"float32"),Kz={kernelName:fs,backendName:"cpu",kernelFunc:B6},V6=dr(e=>Math.expm1(e)),Yz=Os(gs,V6),Zz={kernelName:gs,backendName:"cpu",kernelFunc:Yz},U6=dr(e=>Math.floor(e)),Jz=Os(ys,U6),Qz={kernelName:ys,backendName:"cpu",kernelFunc:Jz},G6=Pt((e,t)=>Math.floor(e/t)),eL=Kt(xs,G6,null,"int32"),tL={kernelName:xs,backendName:"cpu",kernelFunc:eL};function H6(e,t,a,n,r,s,i,o,l){let u=Te([n,s],a);for(let d=0;d<n;d++){let c=[],p=0;for(let h=0;h<r;h++){let m=e[d*r+h];p+=m*i[h],c.push(m)}if(p<0||p>=l/s)throw new Error(`Invalid indices: ${c} does not index into ${o}`);for(let h=0;h<s;h++)u.values[d*s+h]=t.get(...t.indexToLoc(p*s+h))}return u}function j6(e,t,a){let n=Te(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 q6=Pt((e,t)=>e>t?1:0),aL=Kt(As,q6,null,"bool"),nL={kernelName:As,backendName:"cpu",kernelFunc:aL},X6=Pt((e,t)=>e>=t?1:0),rL=Kt(bs,X6,null,"bool"),sL={kernelName:bs,backendName:"cpu",kernelFunc:rL},K6=Pt((e,t)=>e<t?1:0),iL=Kt(vs,K6,null,"bool"),oL={kernelName:vs,backendName:"cpu",kernelFunc:iL},Y6=Pt((e,t)=>e<=t?1:0),lL=Kt(ws,Y6,null,"bool"),uL={kernelName:ws,backendName:"cpu",kernelFunc:lL};function Z6(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 J6=dr(e=>Math.log(e)),dL=Os(ks,J6),pL={kernelName:ks,backendName:"cpu",kernelFunc:dL};function Q6(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 ev=Pt((e,t)=>Math.max(e,t)),cL=Kt(Is,ev),hL={kernelName:Is,backendName:"cpu",kernelFunc:cL},tv=Pt((e,t)=>Math.min(e,t)),mL=Kt(Ss,tv),fL={kernelName:Ss,backendName:"cpu",kernelFunc:mL},I3=Pt((e,t)=>e*t),gL=v3((e,t,a,n)=>({real:e*a-t*n,imag:e*n+t*a})),l0=Kt(Ts,I3,gL),yL={kernelName:Ts,backendName:"cpu",kernelFunc:l0};function av(e,t,a){let n=v.createScalarValue(-1,a);return I3([],t,n,e,a)}function xL(e){let{inputs:t,backend:a}=e,{x:n}=t;Ie(n,"neg");let r=a.data.get(n.dataId).values,[s,i]=av(r,n.shape,n.dtype);return a.makeTensorInfo(i,n.dtype,s)}var AL={kernelName:Ru,backendName:"cpu",kernelFunc:xL},nv=Pt((e,t)=>e!==t?1:0),bL=Kt(Cs,nv,null,"bool"),vL={kernelName:Cs,backendName:"cpu",kernelFunc:bL};function S3(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 d=0;d<i;++d){let c=v.indexToLoc(d,s,o),p=new Array(c.length);for(let m=0;m<p.length;m++)p[m]=c[n[m]];let h=v.locToIndex(p,s,l);u[h]=e[d]}return u}function Va(e){let{inputs:t,attrs:a,backend:n}=e,{x:r}=t,{perm:s}=a;Ie(r,"transpose");let i=r.shape.length,o=new Array(i);for(let d=0;d<o.length;d++)o[d]=r.shape[s[d]];let l=n.data.get(r.dataId).values,u=S3(l,r.shape,r.dtype,s,o);return{dataId:n.write(u,o,r.dtype),shape:o,dtype:r.dtype}}var wL={kernelName:Tr,backendName:"cpu",kernelFunc:Va};function rv(e,t,a,n){let[r,s]=I.computeOutAndReduceShapes(e,n),i=Qt(t,"int32"),o=v.makeZerosTypedArray(v.sizeFromShape(r),i),l=v.sizeFromShape(s);for(let u=0;u<o.length;++u){let d=u*l,c=1;for(let p=0;p<l;++p)c*=a[d+p];o[u]=c}return{outVals:o,outShape:r,outDtype:i}}function kL(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;Ie(r,"prod");let o=r.shape.length,l=v.parseAxisParam(s,r.shape),u=I.getAxesPermutation(l,o),d=l,c=r,p=[];u!=null&&(c=Va({inputs:{x:r},backend:a,attrs:{perm:u}}),p.push(c),d=I.getInnerMostAxes(d.length,o));let h=a.data.get(c.dataId).values,{outVals:m,outShape:f,outDtype:g}=rv(c.shape,c.dtype,h,d),y=f;return i&&(y=I.expandShapeToKeepDim(f,l)),p.forEach(x=>a.disposeIntermediateTensorInfo(x)),a.makeTensorInfo(y,g,m)}var IL={kernelName:Oo,backendName:"cpu",kernelFunc:kL};function SL(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 TL(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 CL(e,t,a,n){let r=[],s=0,i=t.length-1+a.length,o=new Array(i).fill(null).map(()=>[0]);TL(a,n);let l=1;for(let u=0;u<t.length-1;++u){l*=t[u];let d=t[u+1];for(let c=1;c<l+1;++c)o[u].push(c*d)}for(let u=0;u<e.length;++u){let d=e[u],c=e[u]+1;for(let p=0;p<a.length;++p){let h=a[p],m=p+t.length-1;if(m>=0){let f=o[m],g=f[f.length-1]-h[d];for(let y=d;y<c;++y)o[m].push(h[y+1]+g)}d=h[d],c=h[c]}c!==d&&(r.push([d,c]),s+=c-d)}return{outSplits:o,valueSlices:r,numValues:s}}function NL(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 E5(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 RL(e,t,a,n,r,s){let i=E5(t,2)[1],o=E5(s,2)[1],l=0;for(let u of a)for(let d=u[0];d<u[1];++d){for(let c=0;c<n;++c)r[l*o+c]=e[d*i+c];++l}}function EL(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 RL(e,t,n,l,i,s),[i,s]}function sv(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(SL(s,i,l),n.length===0)throw new Error("params.rank must be nonzero");let u=n[0],{outSplits:d,valueSlices:c,numValues:p}=CL(s,i,e,u),h=NL(d),m=EL(a,n,r,c,p);return[h,m[0],m[1]]}var M5=2147483647;function iv(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,d=[];o||d.push(t[0]),l||d.push(r[0]),u||d.push(i[0]);for(let g=1;g<d.length;++g)if(d[g]!==d[g-1])throw new Error("starts, limits, and deltas must have the same shape");let c=d.length===0?1:d[0],p=v.getArrayFromDType("int32",c+1);p[0]=0;for(let g=0;g<c;++g){let y=o?e[0]:e[g],x=l?n[0]:n[g],A=u?s[0]:s[g];if(A===0)throw new Error("Requires delta != 0");let b;if(A>0&&x<y||A<0&&x>y)b=0;else if(b=Math.ceil(Math.abs((x-y)/A)),b>M5)throw new Error(`Requires ((limit - start) / delta) <= ${M5}`);p[g+1]=p[g]+b}let h=p[c],m=v.getArrayFromDType(a,h),f=0;for(let g=0;g<c;++g){let y=p[g+1]-p[g],x=o?e[0]:e[g],A=u?s[0]:s[g];for(let b=0;b<y;++b)m[f++]=x,x+=A}return[p,m]}var Cn=I.RowPartitionType,ML=class z1{constructor(t,a,n,r,s,i,o,l,u,d){this.shape=t,this.shapeShape=a,this.values=n,this.valuesShape=r,this.valuesDType=s,this.defaultValue=i,this.defaultValueShape=o,this.rowPartitionValues=l,this.rowPartitionValuesShapes=u,this.rowPartitionTypes=I.getRowPartitionTypesHelper(d),this.raggedRank=I.getRaggedRank(this.rowPartitionTypes)}getRowPartitionTypeByDimension(t){return this.rowPartitionTypes[0]===Cn.FIRST_DIM_SIZE?this.rowPartitionTypes[t+1]:this.rowPartitionTypes[t]}getRowPartitionTensor(t){return this.rowPartitionTypes[0]===Cn.FIRST_DIM_SIZE?this.rowPartitionValues[t+1]:this.rowPartitionValues[t]}getMaxWidth(t){let a=this.getRowPartitionTensor(t-1);switch(this.getRowPartitionTypeByDimension(t-1)){case Cn.VALUE_ROWIDS:return z1.getMaxWidthValueRowID(a);case Cn.ROW_SPLITS:return z1.getMaxWidthRowSplit(a);default:throw new Error(`Cannot handle partition type ${Cn[this.getRowPartitionTypeByDimension(t-1)]}`)}}static getMaxWidthRowSplit(t){let a=t.length;if(a===0||a===1)return 0;let n=0;for(let r=0;r<a-1;++r){let s=t[r+1]-t[r];s>n&&(n=s)}return n}static getMaxWidthValueRowID(t){let a=t.length;if(a===0)return 0;let n=0,r=t[0],s=0;for(let i=1;i<a;++i){let o=t[i];o!==r&&(r=o,s=Math.max(i-n,s),n=i)}return Math.max(a-n,s)}tensorShapeFromTensor(t,a,n=!0){if(a.length===0){if(t[0]===-1)return[];throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.")}return $5(t,n)}calculateOutputSize(t){let a=this.valuesShape,n=this.defaultValueShape;I.validateDefaultValueShape(n,a);let r=this.tensorShapeFromTensor(this.shape,this.shapeShape),s=I.combineRaggedTensorToTensorShapes(this.raggedRank,r,a);s[0]<0&&(s[0]=t);for(let i=1;i<=this.raggedRank;++i)s[i]<0&&(s[i]=this.getMaxWidth(i));return s}calculateFirstParentOutputIndex(t,a,n){let r=Math.min(t,n),s=[],i=0;for(let o=0;o<r;++o,i+=a)s.push(i);for(let o=r;o<t;++o)s.push(-1);return v.assert(s.length===t,()=>"Final length of result must be equal to firstDimension."),s}calculateOutputIndexRowSplit(t,a,n,r){let s=t.length,i=[];for(let o=0;o<s-1;++o){let l=t[o+1]-t[o],u=Math.min(r,l),d=a[o];d===-1&&(u=0);for(let c=0;c<u;++c)i.push(d),d+=n;for(let c=0;c<l-u;++c)i.push(-1)}if(s>0&&i.length!==t[s-1])throw new Error("Invalid row split size.");return i}calculateOutputIndexValueRowID(t,a,n,r){let s=t.length,i=[];if(s===0)return[];let o=0,l=t[0];if(l>=a.length)throw new Error(`Got currentValueRowId=${l}, which is not less than ${a.length}`);let u=a[l];i.push(u);for(let d=1;d<s;++d){let c=t[d];if(c===l)u>=0&&(++o,o<r?u+=n:u=-1);else{if(o=0,l=c,c>=a.length)throw new Error(`Got nextValueRowId=${c} which is not less than ${a.length}`);u=a[c]}i.push(u)}if(i.length!==t.length)throw new Error("Invalid row ids.");return i}calculateOutputIndex(t,a,n,r){let s=this.getRowPartitionTensor(t),i=this.getRowPartitionTypeByDimension(t);switch(i){case Cn.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(s,a,n,r);case Cn.ROW_SPLITS:if(s.length-1>a.length)throw new Error(`Row partition size is greater than output size: ${s.length-1} > ${a.length}`);return this.calculateOutputIndexRowSplit(s,a,n,r);default:throw new Error(`Unsupported partition type: ${Cn[i]}`)}}getFirstDimensionSize(){let t=this.rowPartitionValues[0];if(this.rowPartitionTypes.length===0)throw new Error("No row_partition_types given.");let a=this.rowPartitionTypes[0];switch(a){case Cn.FIRST_DIM_SIZE:return t[0];case Cn.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case Cn.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${Cn[a]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");let t=this.getFirstDimensionSize(),a=this.calculateOutputSize(t),n=new Array(this.raggedRank+1);n[n.length-1]=1;for(let i=n.length-2;i>=0;--i)n[i]=n[i+1]*a[i+1];let r=$5(a,!1),s=v.getArrayFromDType(this.valuesDType,v.sizeFromShape(r));if(n[0]*a[0]>0){let i=this.calculateFirstParentOutputIndex(t,n[0],a[0]);for(let o=1;o<=this.raggedRank;++o)i=this.calculateOutputIndex(o-1,i,n[o],a[o]);this.setOutput(this.raggedRank,i,s,r)}return[r,s]}setOutput(t,a,n,r){if(n.length===0)return;let s=this.values,i=n,o=r.slice();o=o.slice(t+1);let l=v.sizeFromShape(o),u=a.length,d=this.defaultValue;if(d.length!==l&&d.length!==1){let m=this.defaultValueShape;Pe(()=>{let f=Q(d,m);d=Ai(f,o).dataSync()})}let c=0,p=0,h=0;for(let m=0;m<=u;++m){let f=m<u?a[m]:-1;if(f===h){++h;continue}if(p<h){let g=s.subarray(c*l),y=i.subarray(p*l),x=(h-p)*l;F5(y,g,x)}if(m>=u){let g=n.length;f=Math.floor(g/l)}if(f>h)if(this.defaultValue.length===1)i.subarray(h*l,f*l).fill(this.defaultValue[0]),h=f;else for(;f>h;){let g=i.slice(h*l);F5(g,d,l),++h}f<0?(c=m+1,p=h):(c=m,p=h,h=p+1)}}};function F5(e,t,a){for(let n=0;n<a;n++)e[n]=t[n]}function $5(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 ov(e,t,a,n,r,s,i,o,l,u){return new ML(e,t,a,n,r,s,i,o,l,u).compute()}function T3(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 lv=dr(e=>1/Math.sqrt(e)),FL=Os(Ns,lv),$L={kernelName:Ns,backendName:"cpu",kernelFunc:FL};function xi(e,t,a,n,r,s,i,o,l,u){let d=[n/r,r],c=e.values,p=t.values;if(n===0)return Te(a,t.dtype);let h=l instanceof Rt?l:Te(d,t.dtype);typeof l=="string"||typeof l=="number"?h.values.fill(l):typeof l=="boolean"&&h.values.fill(+l);for(let m=0;m<s;m++){let f=[],g=0;for(let y=0;y<i;y++){let x=c[m*i+y];f.push(x),g+=x*o[y]}if(g<0||g>=n/r)throw new Error(`Invalid indices: ${f} does not index into ${a}`);for(let y=0;y<r;y++)u?h.values[g*r+y]+=p[m*r+y]:h.values[g*r+y]=t.rank===0?p[0]:p[m*r+y]}return h}var DL=dr(e=>1/(1+Math.exp(-e))),uv=ct(Rs,e=>1/(1+Math.exp(-e))),PL={kernelName:Rs,backendName:"cpu",kernelFunc:uv};function Sh(e,t,a,n,r){let s=wt.isSliceContinous(n,t,a),i=v.sizeFromShape(a),o=v.computeStrides(n);if(s){let c=wt.computeFlatOffset(t,o);return r==="string"?e.slice(c,c+i):e.subarray(c,c+i)}let l=r==="string"?I.fromUint8ToStringArray(e):e,u=Te(n,r,l),d=Te(a,r);for(let c=0;c<d.size;++c){let p=d.indexToLoc(c),h=p.map((m,f)=>m+t[f]);d.set(u.get(...h),...p)}return r==="string"?I.fromStringArrayToUint8(d.values):d.values}function Ci(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{begin:s,size:i}=n;Ie(r,"slice");let[o,l]=wt.parseSliceParams(r,s,i);wt.assertParamsValid(r,o,l);let u=a.data.get(r.dataId).values,d=Sh(u,o,l,r.shape,r.dtype);return a.makeTensorInfo(l,r.dtype,d)}var _L={kernelName:zu,backendName:"cpu",kernelFunc:Ci};function dv(e,t,a,n,r,s,i){let o=t[0],l=s[0],u=new Array(l),d=new Array(o),c=t[1];if(l===0){if(o!==0)throw new Error(I.getSparseFillEmptyRowsIndicesDenseShapeMismatch(o));let g=v.getArrayFromDType(a,0),y=v.getArrayFromDType(r,0);return[g,[0,c],y,u,d]}let p=!0,h=0,m=new Array(l).fill(0);for(let g=0;g<o;++g){let y=e[g*c];if(y<0)throw new Error(I.getSparseFillEmptyRowsNegativeIndexErrorMessage(g,y));if(y>=l)throw new Error(I.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(g,y,l));++m[y],p=p&&y>=h,h=y}let f=!0;for(let g=0;g<l;++g){let y=m[g]===0;u[g]=y,f=f&&!y,m[g]=Math.max(m[g],1),g>0&&(m[g]+=m[g-1])}if(f&&p){let g=e,y=n;for(let x=0;x<o;++x)d[x]=x;return[g,[o,c],y,u,d]}else{let g=m[l-1],y=v.getArrayFromDType(a,g*c),x=v.getArrayFromDType(r,g),A=new Array(l).fill(0);for(let b=0;b<o;++b){let w=e[b*c],S=A[w],C=(w===0?0:m[w-1])+S;A[w]++;for(let N=0;N<c;++N)y[C*c+N]=e[b*c+N];x[C]=n[b],d[b]=C}for(let b=0;b<l;++b)if(A[b]===0){let w=b===0?0:m[b-1];y[w*c+0]=b;for(let S=1;S<c;++S)y[w*c+S]=0;x[w]=i}return[y,[g,c],x,u,d]}}function pv(e,t,a,n,r){let s=v.sizeFromShape(n),i=t[0],o=r.length,l=[],u=1,d=-1;for(let f=0;f<o;++f){let g=r[f];if(g===-1){if(d!==-1)throw new Error(I.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(d,f));d=f,l.push(1)}else{if(g<0)throw new Error(I.getSparseReshapeNegativeOutputDimErrorMessage(f,g));u*=g,l.push(g)}}if(d!==-1){if(u<=0)throw new Error(I.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());let f=Math.trunc(s/u);if(u*f!==s)throw new Error(I.getSparseReshapeInputOutputMultipleErrorMessage(n,l));l[d]=f}if(v.sizeFromShape(l)!==s)throw new Error(I.getSparseReshapeInputOutputMismatchErrorMessage(n,l));let c=n.length,p=[];if(c>0){p[c-1]=1;for(let f=c-2;f>=0;--f)p[f]=p[f+1]*n[f+1]}let h=[];if(o>0){h[o-1]=1;for(let f=o-2;f>=0;--f)h[f]=h[f+1]*l[f+1]}let m=v.getArrayFromDType(a,i*o);for(let f=0;f<i;++f){let g=0;for(let y=0;y<c;++y)g+=e[f*c+y]*p[y];for(let y=0;y<o;++y)m[f*o+y]=Math.trunc(g/h[y]),g%=h[y]}return[m,[i,o],l]}function C3(e,t,a,n,r,s=!1,i=0){let o=n.length,l=[t[0],e.length/t[0]],u=l[1],d=o>0?r[o-1]+1:0;if(d<0)throw new Error(I.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let c=t.slice();c[0]=d;let p=c.reduce((x,A)=>x*A,1),h=v.getArrayFromDType(a,p);if(o===0)return d>0&&h.fill(i),[h,c];if(d<=0)throw new Error(I.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let m=0,f=1,g=0,y=r[m];for(;;){let x=0;if(f<o){if(x=r[f],y===x){++f;continue}if(y>=x)throw new Error(I.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage())}if(y<0||y>=d)throw new Error(I.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(y,d));y>g&&h.fill(i,g*u,y*u);for(let A=m;A<f;++A){let b=n[A];if(b<0||b>=l[0])throw new Error(I.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(A,n[A],l[0]));for(let w=0;w<u;w++)h[y*u+w]+=e[b*u+w]}if(s)for(let A=0;A<u;A++)h[y*u+A]/=f-m;if(m=f,++f,g=y+1,y=x,f>o)break}return g<d&&h.fill(i,g*u,d*u),[h,c]}var OL=dr(e=>Math.sqrt(e)),zL=ct(Es,e=>Math.sqrt(e)),LL={kernelName:Es,backendName:"cpu",kernelFunc:zL},cv=Pt((e,t)=>{let a=e-t;return a*a}),WL=Kt(Ms,cv),BL={kernelName:Ms,backendName:"cpu",kernelFunc:WL},hv=dr((e,t)=>{let{pattern:a,replaceGlobal:n,rewrite:r}=t;return e.replace(new RegExp(a,n?"g":""),r)}),VL=Os(Gu,hv),UL={kernelName:Gu,backendName:"cpu",kernelFunc:VL};function mv(e,t,a,n){let r=Te(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 GL=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))),d=s-(l+u),c=t+(l>0?0:i-o),p=0;p+=l*this.leftPad.length;for(let y=0;y<d;++y)p+=e[c+y].length;p+=u*this.rightPad.length;let h=l+u+d-1;p+=h*this.separator.length,a[n+i]=new Uint8Array(p);let m=a[n+i],f=0,g=y=>y.forEach(x=>m[f++]=x);for(let y=0;y<l;++y)g(this.leftPad),g(this.separator);for(let y=0;y<d-1;++y)g(e[c+y]),g(this.separator);if(d>0){g(e[c+d-1]);for(let y=0;y<u;++y)g(this.separator),g(this.rightPad)}else{for(let y=0;y<u-1;++y)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(d=>{u+=this.getNumNGrams(l,d)}),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(d=>{let c=t[o+1]-t[o],p=this.getNumNGrams(c,d);this.createNGrams(e,l,i,u,p,d),u+=p}),this.preserveShort&&u===s[o]){let d=t[o+1]-t[o];if(d===0)continue;let c=d+2*this.padWidth;this.createNGrams(e,l,i,u,1,c)}}return[i,s]}};function N3(e,t,a,n,r,s,i,o){return new GL(a,n,r,s,i,o).compute(e,t)}function HL(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 R3(e,t,a){let n=e.length,r=[],s=0,i=0,o=new Array(n);for(let p=0;p<n;++p){let h=r.length;HL(e[p],t,a,r);let m=r.length-h;o[p]=m,s+=m,i=Math.max(i,m)}let l=v.getArrayFromDType("int32",s*2),u=new Array(s),d=[n,i],c=0;for(let p=0;p<n;++p)for(let h=0;h<o[p];++h)l[c*2]=p,l[c*2+1]=h,u[c]=r[c],++c;return[l,u,d]}function E3(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 fv=Pt((e,t)=>e-t),jL=v3((e,t,a,n)=>({real:e-a,imag:t-n})),M3=Kt(Fs,fv,jL),qL={kernelName:Fs,backendName:"cpu",kernelFunc:M3};function gv(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=Te(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 Fd=(e,t)=>{let a=t.value-e.value;return a===0?e.index-t.index:a};function yv(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),d=.5*Math.exp(2*u/3),c=.5*Math.sqrt(u*d*(o-d)/o)*Math.sign(l-o/2),p=Math.max(a,Math.floor(t-l*d/o+c)),h=Math.min(n,Math.floor(t+(o-l)*d/o+c));yv(e,t,p,h)}let r=e[t],s=a,i=n;for(v.swap(e,a,t),Fd(e[n],r)>0&&v.swap(e,a,n);s<i;){for(v.swap(e,s,i),s++,i--;Fd(e[s],r)<0;)s=s+1;for(;Fd(e[i],r)>0;)i=i-1}Fd(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 xv(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 p=c*o,h=e.subarray(p,p+o),m=new Array(h.length);h.forEach((x,A)=>m[A]={value:x,index:A}),n<m.length&&(yv(m,n),m=m.slice(0,n)),r&&m.sort(Fd);let f=c*n,g=l.subarray(f,f+n),y=u.subarray(f,f+n);for(let x=0;x<n;x++)g[x]=m[x].value,y[x]=m[x].index}let d=t.slice();return d[d.length-1]=n,[Te(d,a,l),Te(d,"int32",u)]}function F3(e,t,a,n){let r=v.parseAxisParam(t,a)[0],s=[1,a[0],1];for(let m=0;m<r;m++)s[0]*=a[m];s[1]=a[r];for(let m=r+1;m<a.length;m++)s[2]*=a[m];let i=new Map,o=new Int32Array(a[r]),l=new Rt(s,n,e),u=[],d=s[0]===1&&s[2]===1;for(let m=0;m<a[r];m++){let f;if(d)f=e[m].toString();else{let y=[];for(let x=0;x<s[0];x++)for(let A=0;A<s[2];A++)y.push(l.get(x,m,A));f=y.join(",")}let g=i.get(f);if(g!=null)o[m]=g;else{let y=i.size;i.set(f,y),o[m]=y,u.push(m)}}let c=s.slice();c[1]=i.size;let p=new Rt(c,n);u.forEach((m,f)=>{for(let g=0;g<s[0];g++)for(let y=0;y<s[2];y++)p.set(l.get(g,m,y),g,f,y)});let h=a.slice();return h[r]=c[1],{outputValues:p.values,outputShape:h,indices:o}}var XL="4.17.0";ll("cpu",()=>new A3,1);var Av=ct(oo,e=>e>=0?e:Math.exp(e)-1),KL={kernelName:oo,backendName:"cpu",kernelFunc:Av};function bv(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{alpha:s}=n;Ie([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 YL={kernelName:yo,backendName:"cpu",kernelFunc:bv},ZL=Pt((e,t)=>e<0?t*e:e);function vv(e){let{inputs:t,backend:a}=e,{x:n,alpha:r}=t;Ie([n,r],"prelu");let s=a.data.get(n.dataId).values,i=a.data.get(r.dataId).values,[o,l]=ZL(n.shape,r.shape,s,i,"float32");return a.makeTensorInfo(l,"float32",o)}var JL={kernelName:_o,backendName:"cpu",kernelFunc:vv},wv=ct(Lo,e=>Math.max(0,e)),QL={kernelName:Lo,backendName:"cpu",kernelFunc:wv},kv=ct(Vo,e=>Math.min(Math.max(0,e),6)),eW={kernelName:Vo,backendName:"cpu",kernelFunc:kv};function Th(e,t,a,n,r){if(a==="linear")return sr({inputs:{x:t},backend:e});if(a==="relu")return wv({inputs:{x:t},backend:e});if(a==="elu")return Av({inputs:{x:t},backend:e});if(a==="relu6")return kv({inputs:{x:t},backend:e});if(a==="prelu")return vv({inputs:{x:t,alpha:n},backend:e});if(a==="leakyrelu")return bv({inputs:{x:t},backend:e,attrs:{alpha:r}});if(a==="sigmoid")return uv({inputs:{x:t},backend:e});throw new Error(`Activation ${a} has not been implemented for the CPU backend.`)}function bt(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 d=u.complexTensorInfos.real,c=u.complexTensorInfos.imag;d.shape=o,c.shape=o}return{dataId:r.dataId,shape:o,dtype:r.dtype}}var tW={kernelName:Du,backendName:"cpu",kernelFunc:bt};function Iv(e){let{inputs:t,backend:a,attrs:n}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=n;Ie([r,s],"matMul");let l=r.shape.length,u=s.shape.length,d=i?r.shape[l-2]:r.shape[l-1],c=o?s.shape[u-1]:s.shape[u-2],p=i?r.shape[l-1]:r.shape[l-2],h=o?s.shape[u-2]:s.shape[u-1],m=r.shape.slice(0,-2),f=s.shape.slice(0,-2),g=v.sizeFromShape(m),y=v.sizeFromShape(f),x=ul.assertAndGetBroadcastShape(r.shape.slice(0,-2),s.shape.slice(0,-2)).concat([p,h]);v.assert(d===c,()=>`Error in matMul: inner shapes (${d}) and (${c}) of Tensors with shapes ${r.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let A=i?[g,d,p]:[g,p,d],b=o?[y,h,c]:[y,c,h],w=bt({inputs:{x:r},backend:a,attrs:{shape:A}}),S=bt({inputs:{x:s},backend:a,attrs:{shape:b}}),C=i?w.shape[1]:w.shape[2],N=i?w.shape[2]:w.shape[1],M=o?S.shape[1]:S.shape[2],F=Math.max(g,y),E=a.data.get(w.dataId).values,T=a.data.get(S.dataId).values,D=v.computeStrides(w.shape),O=v.computeStrides(S.shape),[W,$,U]=i?[D[0],1,D[1]]:[D[0],D[1],1],[G,q,H]=o?[1,O[1],O[0]]:[O[1],1,O[0]],V=N*M,Z=Te([F,N,M],w.dtype),X=Z.values,re=a.blockSize;for(let ee=0;ee<F;ee++){let ge=ee%g,ie=ee%y;for(let be=0;be<N;be+=re){let Ce=Math.min(be+re,N);for(let Ee=0;Ee<M;Ee+=re){let Le=Math.min(Ee+re,M);for(let qe=0;qe<C;qe+=re){let gt=Math.min(qe+re,C);for(let dt=be;dt<Ce;dt++)for(let st=Ee;st<Le;st++){let it=0;for(let He=qe;He<gt;He++){let xt=E[ge*W+dt*$+He*U],ja=T[He*G+st*q+ie*H];it+=xt*ja}X[ee*V+(dt*M+st)]+=it}}}}}return a.disposeIntermediateTensorInfo(w),a.disposeIntermediateTensorInfo(S),a.makeTensorInfo(x,Z.dtype,Z.values)}var aW={kernelName:Gi,backendName:"cpu",kernelFunc:Iv};function nW(e){let{inputs:t,backend:a,attrs:n}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:d,leakyreluAlpha:c}=n,p,h,m,f=[];p=Iv({inputs:{a:r,b:s},attrs:{transposeA:l,transposeB:u},backend:a}),i&&(h=su({inputs:{a:p,b:i},backend:a}),f.push(p),p=h),d&&(m=Th(a,p,d,o,c),f.push(p),p=m);for(let g of f)a.disposeIntermediateTensorInfo(g);return p}var rW={kernelName:ts,backendName:"cpu",kernelFunc:nW},sW=ct($i,e=>Math.acos(e)),iW={kernelName:$i,backendName:"cpu",kernelFunc:sW},oW=ct(Di,e=>Math.acosh(e)),lW={kernelName:Di,backendName:"cpu",kernelFunc:oW};function uW(e){let{inputs:t,backend:a}=e,n=t;Ie(t,"addN");let r=n.map(o=>a.data.get(o.dataId).values),s=Te(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 dW={kernelName:Pi,backendName:"cpu",kernelFunc:uW};function pW(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;Ie(r,"all");let o=v.parseAxisParam(s,r.shape),l=o,u=I.getAxesPermutation(l,r.shape.length),d=r;u!=null&&(d=Va({inputs:{x:r},backend:a,attrs:{perm:u}}),l=I.getInnerMostAxes(l.length,r.shape.length)),I.assertAxesAreInnerMostDims("all",l,d.shape.length);let[c,p]=I.computeOutAndReduceShapes(d.shape,l),h=v.sizeFromShape(p),m=v.makeZerosTypedArray(v.sizeFromShape(c),d.dtype),f=a.data.get(d.dataId).values;for(let y=0;y<m.length;++y){let x=y*h,A=f[x];for(let b=0;b<h;++b){let w=f[x+b];A=A&&w}m[y]=A}u!=null&&a.disposeIntermediateTensorInfo(d);let g=a.makeTensorInfo(c,d.dtype,m);if(i){let y=I.expandShapeToKeepDim(c,o),x=bt({inputs:{x:g},backend:a,attrs:{shape:y}});return a.disposeIntermediateTensorInfo(g),x}return g}var cW={kernelName:_i,backendName:"cpu",kernelFunc:pW};function hW(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;Ie(r,"any");let o=v.parseAxisParam(s,r.shape),l=o,u=I.getAxesPermutation(l,r.shape.length),d=r;u!=null&&(d=Va({inputs:{x:r},backend:a,attrs:{perm:u}}),l=I.getInnerMostAxes(l.length,r.shape.length)),I.assertAxesAreInnerMostDims("any",l,d.shape.length);let[c,p]=I.computeOutAndReduceShapes(d.shape,l),h=v.sizeFromShape(p),m=v.makeZerosTypedArray(v.sizeFromShape(c),d.dtype),f=a.data.get(d.dataId).values;for(let y=0;y<m.length;++y){let x=y*h,A=f[x];for(let b=0;b<h;++b){let w=f[x+b];A=A||w}m[y]=A}u!=null&&a.disposeIntermediateTensorInfo(d);let g=a.makeTensorInfo(c,d.dtype,m);if(i){let y=I.expandShapeToKeepDim(c,o),x=bt({inputs:{x:g},backend:a,attrs:{shape:y}});return a.disposeIntermediateTensorInfo(g),x}return g}var mW={kernelName:Oi,backendName:"cpu",kernelFunc:hW};function fW(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s}=n;Ie(r,"argMax");let i=v.parseAxisParam(s,r.shape),o=I.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=Va({inputs:{x:r},backend:a,attrs:{perm:o}}),u.push(l),i=I.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],I.assertAxesAreInnerMostDims("argMax",i,l.shape.length);let[d,c]=I.computeOutAndReduceShapes(l.shape,i),p=v.sizeFromShape(d),h=v.makeZerosTypedArray(p,"int32"),m=v.sizeFromShape(c),f=a.data.get(l.dataId).values;for(let g=0;g<h.length;++g){let y=g*m,x=f[y],A=0;for(let b=0;b<m;++b){let w=f[y+b];w>x&&(x=w,A=b)}h[g]=A}return u.forEach(g=>a.disposeIntermediateTensorInfo(g)),a.makeTensorInfo(d,"int32",h)}var gW={kernelName:hu,backendName:"cpu",kernelFunc:fW};function yW(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s}=n;Ie(r,"argMin");let i=v.parseAxisParam(s,r.shape),o=I.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=Va({inputs:{x:r},backend:a,attrs:{perm:o}}),u.push(l),i=I.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],I.assertAxesAreInnerMostDims("argMin",i,l.shape.length);let[d,c]=I.computeOutAndReduceShapes(l.shape,i),p=v.sizeFromShape(d),h=v.makeZerosTypedArray(p,"int32"),m=v.sizeFromShape(c),f=a.data.get(l.dataId).values;for(let g=0;g<h.length;++g){let y=g*m,x=f[y],A=0;for(let b=0;b<m;++b){let w=f[y+b];w<x&&(x=w,A=b)}h[g]=A}return u.forEach(g=>a.disposeIntermediateTensorInfo(g)),a.makeTensorInfo(d,"int32",h)}var xW={kernelName:mu,backendName:"cpu",kernelFunc:yW},AW=ct(zi,e=>Math.asin(e)),bW={kernelName:zi,backendName:"cpu",kernelFunc:AW},vW=ct(Li,e=>Math.asinh(e)),wW={kernelName:Li,backendName:"cpu",kernelFunc:vW},kW=ct(Wi,e=>Math.atan(e)),IW={kernelName:Wi,backendName:"cpu",kernelFunc:kW},SW=Pt((e,t)=>Math.atan2(e,t)),TW=Kt(Vi,SW),CW={kernelName:Vi,backendName:"cpu",kernelFunc:TW},NW=ct(Bi,e=>Math.atanh(e)),RW={kernelName:Bi,backendName:"cpu",kernelFunc:NW};function $3(e,t,a,n,r,s){let i=r.strideHeight,o=r.strideWidth,l=r.dilationHeight,u=r.dilationWidth,d=r.effectiveFilterHeight,c=r.effectiveFilterWidth,p=r.padInfo.top,h=r.padInfo.left,m=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,f=Te(r.outShape,a),g=f.values,y=r.outShape[1]*r.outShape[2]*r.outShape[3],x=r.outShape[2]*r.outShape[3],A=r.outShape[3];for(let b=0;b<r.batchSize;++b){let w=b*y,S=b*n[0];for(let C=0;C<r.inChannels;++C)for(let N=0;N<r.outHeight;++N){let M=N*i-p,F=Math.max(0,M),E=Math.min(r.inHeight,d+M),T=w+N*x;for(let D=0;D<r.outWidth;++D){let O=D*o-h,W=Math.max(0,O),$=Math.min(r.inWidth,c+O),U=m,G=0,q=0;for(let V=F;V<E;V+=l){let Z=S+V*n[1];for(let X=W;X<$;X+=u){let re=Z+X*n[2],ee=e[re+C];s==="max"&&ee>U?U=ee:s==="avg"&&(G+=ee,q++)}if(isNaN(U))break}let H=T+D*A+C;g[H]=s==="avg"?G/q:U}}}return f}function Sv(e,t,a,n,r=!1,s=!1){let i=Te(n.outShape,"int32"),o=n.strideHeight,l=n.strideWidth,u=n.dilationHeight,d=n.dilationWidth,c=n.effectiveFilterHeight,p=n.effectiveFilterWidth,h=n.padInfo.top,m=n.padInfo.left,f=Te(t,a,e);for(let g=0;g<n.batchSize;++g)for(let y=0;y<n.inChannels;++y)for(let x=0;x<n.outHeight;++x){let A=x*o-h,b=A;for(;b<0;)b+=u;let w=Math.min(n.inHeight,c+A);for(let S=0;S<n.outWidth;++S){let C=S*l-m,N=C;for(;N<0;)N+=d;let M=Math.min(n.inWidth,p+C),F=Number.NEGATIVE_INFINITY,E=-1;for(let T=b;T<w;T+=u){let D=T-A;for(let O=N;O<M;O+=d){let W=O-C,$=f.get(g,T,O,y);$>F&&(F=$,r?E=s?((g*n.inHeight+T)*n.inWidth+O)*n.inChannels+y:(T*n.inWidth+O)*n.inChannels+y:E=D*p+W)}}i.set(E,g,x,S,y)}}return i}function Tv(e,t,a,n,r,s){let i=r.strideDepth,o=r.strideHeight,l=r.strideWidth,u=r.dilationDepth,d=r.dilationHeight,c=r.dilationWidth,p=r.effectiveFilterDepth,h=r.effectiveFilterHeight,m=r.effectiveFilterWidth,f=r.padInfo.front,g=r.padInfo.top,y=r.padInfo.left,x=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,A=Te(r.outShape,a),b=A.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],N=r.outShape[4];for(let M=0;M<r.batchSize;++M){let F=M*w,E=M*n[0];for(let T=0;T<r.inChannels;++T)for(let D=0;D<r.outDepth;++D){let O=D*i-f,W=O;for(;W<0;)W+=u;let $=Math.min(r.inDepth,p+O),U=F+D*S;for(let G=0;G<r.outHeight;++G){let q=G*o-g,H=q;for(;H<0;)H+=d;let V=Math.min(r.inHeight,h+q),Z=U+G*C;for(let X=0;X<r.outWidth;++X){let re=X*l-y,ee=re;for(;ee<0;)ee+=c;let ge=Math.min(r.inWidth,m+re),ie=Z+X*N,be=x,Ce=0,Ee=0;for(let qe=W;qe<$;qe+=u){let gt=E+qe*n[1];for(let dt=H;dt<V;dt+=d){let st=gt+dt*n[2];for(let it=ee;it<ge;it+=c){let He=st+it*n[3],xt=e[He+T];if(s==="max"&&xt>be?be=xt:s==="avg"&&(Ce+=xt,Ee++),isNaN(be))break}if(isNaN(be))break}if(isNaN(be))break}let Le=ie+T;b[Le]=s==="avg"?Ce/Math.max(Ee,1):be}}}}return A}function EW(e,t){let a=Te(t.outShape,"int32"),n=t.strideDepth,r=t.strideHeight,s=t.strideWidth,i=t.dilationDepth,o=t.dilationHeight,l=t.dilationWidth,u=t.effectiveFilterDepth,d=t.effectiveFilterHeight,c=t.effectiveFilterWidth,p=t.padInfo.front,h=t.padInfo.top,m=t.padInfo.left;for(let f=0;f<t.batchSize;++f)for(let g=0;g<t.inChannels;++g)for(let y=0;y<t.outDepth;++y){let x=y*n-p,A=x;for(;A<0;)A+=i;let b=Math.min(t.inDepth,u+x);for(let w=0;w<t.outHeight;++w){let S=w*r-h,C=S;for(;C<0;)C+=o;let N=Math.min(t.inHeight,d+S);for(let M=0;M<t.outWidth;++M){let F=M*s-m,E=F;for(;E<0;)E+=l;let T=Math.min(t.inWidth,c+F),D=Number.NEGATIVE_INFINITY,O=-1;for(let W=A;W<b;W+=i){let $=W-x;for(let U=C;U<N;U+=o){let G=U-S;for(let q=E;q<T;q+=l){let H=q-F,V=e.get(f,W,U,q,g);V>=D&&(D=V,O=$*d*c+G*d+H)}}}a.set(O,f,y,w,M,g)}}}return a}function MW(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t;Ie(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1;v.assert(I.eitherStridesOrDilationsAreOne(i,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=I.computePool2DInfo(r.shape,s,i,u,o,l),c;if(d.filterWidth===1&&d.filterHeight===1&&v.arraysEqual(d.inShape,d.outShape))c=sr({inputs:{x:r},backend:a});else{let p=a.data.get(r.dataId).values,h=v.computeStrides(r.shape),m=$3(p,r.shape,r.dtype,h,d,"avg");c=a.makeTensorInfo(d.outShape,r.dtype,m.values)}return c}var FW={kernelName:Ui,backendName:"cpu",kernelFunc:MW};function $W(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=n;Ie(r,"avgPool3d");let d=I.computePool3DInfo(r.shape,s,i,1,o,l,u),c=a.data.get(r.dataId).values,p=Tv(c,r.shape,r.dtype,v.computeStrides(r.shape),d,"avg");return a.makeTensorInfo(p.shape,"float32",p.values)}var DW={kernelName:fu,backendName:"cpu",kernelFunc:$W};function PW(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=n;Ie([r,s],"avgPool3DGrad");let d=I.computePool3DInfo(s.shape,i,o,1,l,u),c=d.strideDepth,p=d.strideHeight,h=d.strideWidth,m=d.filterDepth,f=d.filterHeight,g=d.filterWidth,y=d.dilationDepth,x=d.dilationHeight,A=d.dilationWidth,b=d.effectiveFilterDepth,w=d.effectiveFilterHeight,S=d.effectiveFilterWidth,C=b-1-d.padInfo.front,N=S-1-d.padInfo.left,M=w-1-d.padInfo.top,F=Te(s.shape,"float32"),E=1/(m*f*g),T=a.bufferSync(r);for(let D=0;D<d.batchSize;++D)for(let O=0;O<d.inChannels;++O)for(let W=0;W<d.inDepth;++W)for(let $=0;$<d.inHeight;++$)for(let U=0;U<d.inWidth;++U){let G=W-C,q=$-M,H=U-N,V=0;for(let Z=0;Z<b;Z+=y){let X=(G+Z)/c;if(!(X<0||X>=d.outDepth||Math.floor(X)!==X))for(let re=0;re<w;re+=x){let ee=(q+re)/p;if(!(ee<0||ee>=d.outHeight||Math.floor(ee)!==ee))for(let ge=0;ge<S;ge+=A){let ie=(H+ge)/h;if(ie<0||ie>=d.outWidth||Math.floor(ie)!==ie)continue;let be=T.get(D,X,ee,ie,O);V+=be}}}F.set(V*E,D,W,$,U,O)}return a.makeTensorInfo(F.shape,F.dtype,F.values)}var _W={kernelName:yp,backendName:"cpu",kernelFunc:PW};function OW(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,i=s;Ie([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:u}=n,d=I.computePool2DInfo(i.shape,o,l,1,u),c=d.strideHeight,p=d.strideWidth,h=d.filterHeight,m=d.filterWidth,f=d.dilationHeight,g=d.dilationWidth,y=d.effectiveFilterHeight,x=d.effectiveFilterWidth,A=x-1-d.padInfo.left,b=y-1-d.padInfo.top,w=Te(i.shape,"float32"),S=1/(h*m),C=a.data.get(r.dataId).values,N=Te(r.shape,"float32",C);for(let M=0;M<d.batchSize;++M)for(let F=0;F<d.inChannels;++F)for(let E=0;E<d.inHeight;++E)for(let T=0;T<d.inWidth;++T){let D=E-b,O=T-A,W=0;for(let $=0;$<y;$+=f){let U=(D+$)/c;if(!(U<0||U>=d.outHeight||Math.floor(U)!==U))for(let G=0;G<x;G+=g){let q=(O+G)/p;if(q<0||q>=d.outWidth||Math.floor(q)!==q)continue;let H=N.get(M,U,q,F);W+=H}}w.set(W*S,M,E,T,F)}return a.makeTensorInfo(w.shape,w.dtype,w.values)}var zW={kernelName:gp,backendName:"cpu",kernelFunc:OW};function LW(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."),Ie([r,o,l,s,i],"batchNorm");let{varianceEpsilon:u}=n;u==null&&(u=.001);let d=a.data.get(r.dataId).values,c=a.data.get(o.dataId).values,p=a.data.get(l.dataId).values,h=s?a.data.get(s.dataId).values:new Float32Array([1]),m=i?a.data.get(i.dataId).values:new Float32Array([0]),f=new Float32Array(d.length),g=m.length,y=h.length,x=p.length,A=c.length,b=0,w=0,S=0,C=0;for(let N=0;N<d.length;++N)f[N]=m[b++]+(d[N]-c[w++])*h[S++]/Math.sqrt(p[C++]+u),b>=g&&(b=0),w>=A&&(w=0),S>=y&&(S=0),C>=x&&(C=0);return a.makeTensorInfo(r.shape,r.dtype,f)}var WW={kernelName:po,backendName:"cpu",kernelFunc:LW};function BW(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{blockShape:s,crops:i}=n;Ie([r],"batchToSpaceND");let o=s.reduce((y,x)=>y*x),l=I.getReshaped(r.shape,s,o),u=I.getPermuted(l.length,s.length),d=I.getReshapedPermuted(r.shape,s,o),c=I.getSliceBeginCoords(i,s.length),p=I.getSliceSize(d,i,s.length),h=bt({inputs:{x:r},backend:a,attrs:{shape:l}}),m=Va({inputs:{x:h},backend:a,attrs:{perm:u}}),f=bt({inputs:{x:m},backend:a,attrs:{shape:d}}),g=Ci({inputs:{x:f},backend:a,attrs:{begin:c,size:p}});return a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(m),a.disposeIntermediateTensorInfo(f),g}var VW={kernelName:gu,backendName:"cpu",kernelFunc:BW};function UW(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=w3(o,l,s.dtype,s.shape,i);return a.makeTensorInfo([i],s.dtype,u)}var GW={kernelName:Hi,backendName:"cpu",kernelFunc:UW};function HW(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=I.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return a.makeTensorInfo([o.length],"int32",Int32Array.from(o))}var jW={kernelName:yu,backendName:"cpu",kernelFunc:HW},qW=ct(hs,(e,t)=>{let a=t;return e>a.clipValueMax?a.clipValueMax:e<a.clipValueMin?a.clipValueMin:e}),XW={kernelName:hs,backendName:"cpu",kernelFunc:qW},KW=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 d=o[u],c=l[u];n[u]=Math.hypot(d,c)}return a.makeOutput(n,t.shape,"float32")},YW={kernelName:Ap,backendName:"cpu",kernelFunc:KW};function iu(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 ZW={kernelName:Cp,backendName:"cpu",kernelFunc:iu};function ou(e){let{inputs:t,backend:a,attrs:n}=e,{axis:r}=n,s=v.parseAxisParam(r,t[0].shape)[0],i=t.map(f=>f.shape);I.assertParamsConsistent(i,s);let o=I.computeOutShape(t.map(f=>f.shape),s);if(v.sizeFromShape(o)===0)return a.makeTensorInfo(o,t[0].dtype,[]);let l=t.filter(f=>v.sizeFromShape(f.shape)>0);if(l.length===1)return sr({inputs:{x:l[0]},backend:a});if(l[0].dtype==="complex64"){let f=l.map(b=>Ti({inputs:{input:b},backend:a})),g=l.map(b=>iu({inputs:{input:b},backend:a})),y=ou({inputs:f,backend:a,attrs:{axis:s}}),x=ou({inputs:g,backend:a,attrs:{axis:s}}),A=Qa({inputs:{real:y,imag:x},backend:a});return f.forEach(b=>a.disposeIntermediateTensorInfo(b)),g.forEach(b=>a.disposeIntermediateTensorInfo(b)),a.disposeIntermediateTensorInfo(y),a.disposeIntermediateTensorInfo(x),A}let u=l.map(f=>{let g=[-1,v.sizeFromShape(f.shape.slice(s))];return bt({inputs:{x:f},backend:a,attrs:{shape:g}})}),d=u.map(f=>({vals:a.data.get(f.dataId).values,shape:f.shape}));o=I.computeOutShape(u.map(f=>f.shape),1);let c=u[0].shape[0]===1,p=k3(d,o,t[0].dtype,c),h=I.computeOutShape(l.map(f=>f.shape),s),m=a.makeTensorInfo(h,t[0].dtype,p);return u.forEach(f=>a.disposeIntermediateTensorInfo(f)),m}var JW={kernelName:xu,backendName:"cpu",kernelFunc:ou};function Cv(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:d}=n;Ie([r,s],"conv2d");let c=I.convertConv2DDataFormat(l),p=I.computeConv2DInfo(r.shape,s.shape,i,u,o,d,!1,c),h=p.filterHeight,m=p.filterWidth,f=p.dilationHeight,g=p.dilationWidth,y=p.padInfo.left,x=p.padInfo.top,A=p.dataFormat==="channelsLast",b=new Rt(p.outShape,r.dtype),w=v.computeStrides(r.shape),S=v.computeStrides(s.shape),C=w[0],N=A?w[1]:w[2],M=A?w[2]:1,F=A?1:w[1],E=b.strides[0],T=A?b.strides[1]:b.strides[2],D=A?b.strides[2]:1,O=A?1:b.strides[1],W=a.data.get(r.dataId).values,$=a.data.get(s.dataId).values,U=b.values;for(let G=0;G<p.batchSize;++G){let q=G*C,H=G*E;for(let V=0;V<p.outHeight;++V){let Z=H+V*T,X=V*p.strideHeight-x;for(let re=0;re<h;++re){let ee=X+re*f;if(ee<0||ee>=p.inHeight)continue;let ge=re*S[0],ie=q+ee*N;for(let be=0;be<p.outWidth;++be){let Ce=Z+be*D,Ee=be*p.strideWidth-y;for(let Le=0;Le<m;++Le){let qe=Ee+Le*g;if(qe<0||qe>=p.inWidth)continue;let gt=ge+Le*S[1],dt=ie+qe*M,st=gt;for(let it=0;it<p.inChannels;++it){let He=W[dt+it*F];for(let xt=0;xt<p.outChannels;++xt)U[Ce+xt*O]+=He*$[st+xt];st+=p.outChannels}}}}}}return a.makeTensorInfo(b.shape,b.dtype,U)}var QW={kernelName:Xi,backendName:"cpu",kernelFunc:Cv};function eB(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:d}=n;Ie([r,s],"conv2dBackpropFilter");let c=I.convertConv2DDataFormat(l),p=I.computeConv2DInfo(r.shape,d,i,1,o,u,!1,c),{strideHeight:h,strideWidth:m,filterHeight:f,filterWidth:g}=p,y=p.dataFormat==="channelsLast",x=new Rt(p.filterShape,"float32"),A=p.padInfo.left,b=p.padInfo.top,w=a.data.get(r.dataId).values,S=a.data.get(s.dataId).values,C=new Rt(r.shape,r.dtype,w),N=new Rt(s.shape,s.dtype,S);for(let M=0;M<f;++M){let F=Math.max(0,Math.ceil((b-M)/h)),E=Math.min(p.outHeight,(p.inHeight+b-M)/h);for(let T=0;T<g;++T){let D=Math.max(0,Math.ceil((A-T)/m)),O=Math.min(p.outWidth,(p.inWidth+A-T)/m);for(let W=0;W<p.inChannels;++W)for(let $=0;$<p.outChannels;++$){let U=0;for(let G=0;G<p.batchSize;++G)for(let q=F;q<E;++q){let H=M+q*h-b;for(let V=D;V<O;++V){let Z=T+V*m-A;y?U+=C.get(G,H,Z,W)*N.get(G,q,V,$):U+=C.get(G,W,H,Z)*N.get(G,$,q,V)}}x.set(U,M,T,W,$)}}}return a.makeTensorInfo(x.shape,x.dtype,x.values)}var tB={kernelName:bp,backendName:"cpu",kernelFunc:eB};function aB(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:d}=n;Ie([r,s],"conv2dBackpropInput");let c=v.computeStrides(s.shape),p=v.computeStrides(r.shape),h=I.convertConv2DDataFormat(u),m=I.computeConv2DInfo(i,s.shape,o,1,l,d,!1,h),f=new Rt(m.inShape,"float32"),g=f.values,y=a.data.get(r.dataId).values,x=a.data.get(s.dataId).values,[A,b,w]=c,{batchSize:S,filterHeight:C,filterWidth:N,inChannels:M,inHeight:F,inWidth:E,outChannels:T,outHeight:D,outWidth:O,strideHeight:W,strideWidth:$}=m;h=m.dataFormat;let U=C-1-m.padInfo.top,G=N-1-m.padInfo.left,q=h==="channelsLast",H=f.strides[0],V=q?f.strides[1]:f.strides[2],Z=q?f.strides[2]:1,X=q?1:f.strides[1],re=p[0],ee=q?p[1]:p[2],ge=q?p[2]:1,ie=q?1:p[1];for(let be=0;be<S;++be)for(let Ce=0;Ce<M;++Ce)for(let Ee=0;Ee<F;++Ee){let Le=Ee-U,qe=Math.max(0,Math.ceil(Le/W)),gt=Math.min(D,(C+Le)/W);for(let dt=0;dt<E;++dt){let st=dt-G,it=Math.max(0,Math.ceil(st/$)),He=Math.min(O,(N+st)/$),xt=0;for(let Lt=qe;Lt<gt;++Lt){let pn=Lt*W-Le;for(let ua=it;ua<He;++ua){let Da=ua*$-st,cn=re*be+ee*Lt+ge*ua,Pa=A*(C-1-pn)+b*(N-1-Da)+w*Ce;for(let ht=0;ht<T;++ht){let _a=y[cn+ie*ht],qa=x[Pa+ht];xt+=_a*qa}}}let ja=H*be+V*Ee+Z*dt+X*Ce;g[ja]=xt}}return a.makeTensorInfo(f.shape,f.dtype,f.values)}var nB={kernelName:Ki,backendName:"cpu",kernelFunc:aB};function rB(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=n;Ie([r,s],"conv3d");let u=I.computeConv3DInfo(r.shape,s.shape,i,l,o),{filterDepth:d,filterHeight:c,filterWidth:p,dilationDepth:h,dilationHeight:m,dilationWidth:f,padInfo:g}=u,y=g.front,x=g.left,A=g.top,b=new Rt(u.outShape,r.dtype),w=a.data.get(r.dataId).values,S=a.data.get(s.dataId).values,C=b.values,N=v.computeStrides(r.shape),M=v.computeStrides(s.shape);for(let F=0;F<u.batchSize;++F){let E=F*N[0],T=F*b.strides[0];for(let D=0;D<u.outDepth;++D){let O=T+D*b.strides[1],W=D*u.strideDepth-y;for(let $=0;$<d;++$){let U=W+$*h;if(U<0||U>=u.inDepth)continue;let G=$*M[0],q=E+U*N[1];for(let H=0;H<u.outHeight;++H){let V=O+H*b.strides[2],Z=H*u.strideHeight-A;for(let X=0;X<c;++X){let re=Z+X*m;if(re<0||re>=u.inHeight)continue;let ee=G+X*M[1],ge=q+re*N[2];for(let ie=0;ie<u.outWidth;++ie){let be=V+ie*u.outChannels,Ce=ie*u.strideWidth-x;for(let Ee=0;Ee<p;++Ee){let Le=Ce+Ee*f;if(Le<0||Le>=u.inWidth)continue;let qe=ee+Ee*M[2],gt=ge+Le*u.inChannels,dt=qe;for(let st=0;st<u.inChannels;++st){let it=w[gt+st];for(let He=0;He<u.outChannels;++He)C[be+He]+=it*S[dt+He];dt+=u.outChannels}}}}}}}}return a.makeTensorInfo(b.shape,b.dtype,b.values)}var sB={kernelName:Yi,backendName:"cpu",kernelFunc:rB};function iB(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=n;Ie([r,s],"conv3dBackpropFilterV2");let u=v.computeStrides(r.shape),d=v.computeStrides(s.shape),c=I.computeConv3DInfo(r.shape,l,i,1,o),p=c.strideDepth,h=c.strideHeight,m=c.strideWidth,f=c.filterDepth,g=c.filterHeight,y=c.filterWidth,x=new Rt(c.filterShape,"float32"),A=x.values,[b,w,S,C]=x.strides,N=a.data.get(s.dataId).values,[M,F,E,T]=d,D=a.data.get(r.dataId).values,[O,W,$,U]=u,G=c.padInfo.front,q=c.padInfo.left,H=c.padInfo.top;for(let V=0;V<f;++V){let Z=Math.max(0,Math.ceil((G-V)/p)),X=Math.min(c.outDepth,(c.inDepth+G-V)/p),re=V*b;for(let ee=0;ee<g;++ee){let ge=Math.max(0,Math.ceil((H-ee)/h)),ie=Math.min(c.outHeight,(c.inHeight+H-ee)/h),be=ee*w+re;for(let Ce=0;Ce<y;++Ce){let Ee=Math.max(0,Math.ceil((q-Ce)/m)),Le=Math.min(c.outWidth,(c.inWidth+q-Ce)/m),qe=Ce*S+be;for(let gt=0;gt<c.inChannels;++gt){let dt=gt*C+qe;for(let st=0;st<c.outChannels;++st){let it=0;for(let He=0;He<c.batchSize;++He){let xt=He*O,ja=He*M;for(let Lt=Z;Lt<X;++Lt){let pn=(V+Lt*p-G)*W+xt,ua=Lt*F+ja;for(let Da=ge;Da<ie;++Da){let cn=(ee+Da*h-H)*$+pn,Pa=Da*E+ua;for(let ht=Ee;ht<Le;++ht){let _a=(Ce+ht*m-q)*U+cn,qa=ht*T+Pa;it+=D[_a+gt]*N[qa+st]}}}}A[dt+st]=it}}}}}return a.makeTensorInfo(x.shape,x.dtype,x.values)}var oB={kernelName:Au,backendName:"cpu",kernelFunc:iB};function lB(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=n;Ie([r],"conv3dBackpropInputV2");let u=v.computeStrides(r.shape),d=v.computeStrides(s.shape),c=I.computeConv3DInfo(l,s.shape,o,1,i),p=new Rt(c.inShape,"float32"),h=p.values,[m,f,g,y]=p.strides,x=a.data.get(r.dataId).values,[A,b,w,S]=u,C=a.data.get(s.dataId).values,[N,M,F,E]=d,{batchSize:T,filterDepth:D,filterHeight:O,filterWidth:W,inChannels:$,inDepth:U,inHeight:G,inWidth:q,outChannels:H,outDepth:V,outHeight:Z,outWidth:X,strideDepth:re,strideHeight:ee,strideWidth:ge}=c,ie=D-1-c.padInfo.front,be=O-1-c.padInfo.top,Ce=W-1-c.padInfo.left;for(let Ee=0;Ee<T;++Ee)for(let Le=0;Le<$;++Le)for(let qe=0;qe<U;++qe){let gt=qe-ie,dt=Math.max(0,Math.ceil(gt/re)),st=Math.min(V,(D+gt)/re);for(let it=0;it<G;++it){let He=it-be,xt=Math.max(0,Math.ceil(He/ee)),ja=Math.min(Z,(O+He)/ee);for(let Lt=0;Lt<q;++Lt){let pn=Lt-Ce,ua=Math.max(0,Math.ceil(pn/ge)),Da=Math.min(X,(W+pn)/ge),cn=0;for(let Pa=dt;Pa<st;++Pa){let ht=Pa*re-gt;for(let _a=xt;_a<ja;++_a){let qa=_a*ee-He;for(let yr=ua;yr<Da;++yr){let $l=yr*ge-pn,Kn=A*Ee+b*Pa+w*_a+S*yr,bd=N*(D-1-ht)+M*(O-1-qa)+F*(W-1-$l)+E*Le;for(let Tn=0;Tn<H;++Tn){let Br=x[Kn+Tn],Yt=C[bd+Tn];cn+=Br*Yt}}}}h[m*Ee+f*qe+g*it+y*Lt+Le]=cn}}}return a.makeTensorInfo(p.shape,p.dtype,p.values)}var uB={kernelName:Zi,backendName:"cpu",kernelFunc:lB},dB=ct(Ji,e=>Math.cos(e)),pB={kernelName:Ji,backendName:"cpu",kernelFunc:dB},cB=ct(Qi,e=>Math.cosh(e)),hB={kernelName:Qi,backendName:"cpu",kernelFunc:cB};function mB(e){let{inputs:t,backend:a,attrs:n}=e,{image:r,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=n,[d,c,p,h]=r.shape,m=s.shape[0],[f,g]=o,y=Te([m,f,g,h],"float32"),x=a.data.get(s.dataId).values,A=a.data.get(i.dataId).values,b=a.data.get(r.dataId).values,w=v.computeStrides(r.shape),S=v.computeStrides(y.shape);for(let C=0;C<m;C++){let N=C*4,M=x[N],F=x[N+1],E=x[N+2],T=x[N+3],D=A[C];if(D>=d)continue;let O=f>1?(E-M)*(c-1)/(f-1):0,W=g>1?(T-F)*(p-1)/(g-1):0;for(let $=0;$<f;$++){let U=f>1?M*(c-1)+$*O:.5*(M+E)*(c-1);if(U<0||U>c-1){for(let G=0;G<g;G++)for(let q=0;q<h;q++){let H=q+G*S[2]+$*S[1]+C*S[0];y.values[H]=u}continue}if(l==="bilinear"){let G=Math.floor(U),q=Math.ceil(U),H=U-G;for(let V=0;V<g;V++){let Z=g>1?F*(p-1)+V*W:.5*(F+T)*(p-1);if(Z<0||Z>p-1){for(let ge=0;ge<h;ge++){let ie=ge+V*S[2]+$*S[1]+C*S[0];y.values[ie]=u}continue}let X=Math.floor(Z),re=Math.ceil(Z),ee=Z-X;for(let ge=0;ge<h;ge++){let ie=ge+X*w[2]+G*w[1]+D*w[0],be=b[ie];ie=ge+re*w[2]+G*w[1]+D*w[0];let Ce=b[ie];ie=ge+X*w[2]+q*w[1]+D*w[0];let Ee=b[ie];ie=ge+re*w[2]+q*w[1]+D*w[0];let Le=b[ie],qe=be+(Ce-be)*ee,gt=Ee+(Le-Ee)*ee;ie=ge+V*S[2]+$*S[1]+C*S[0],y.values[ie]=qe+(gt-qe)*H}}}else for(let G=0;G<g;++G){let q=g>1?F*(p-1)+G*W:.5*(F+T)*(p-1);if(q<0||q>p-1){for(let Z=0;Z<h;Z++){let X=Z+G*S[2]+$*S[1]+C*S[0];y.values[X]=u}continue}let H=Math.round(q),V=Math.round(U);for(let Z=0;Z<h;Z++){let X=Z+H*w[2]+V*w[1]+D*w[0],re=Z+G*S[2]+$*S[1]+C*S[0];y.values[re]=b[X]}}}}return a.makeTensorInfo(y.shape,y.dtype,y.values)}var fB={kernelName:ao,backendName:"cpu",kernelFunc:mB};function gB(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=n;Ie(r,"cumprod");let l=I.getAxesPermutation([s],r.shape.length),u=r;l!=null&&(u=Va({inputs:{x:r},backend:a,attrs:{perm:l}}));let d=I.getInnerMostAxes(1,r.shape.length)[0];if(d!==u.shape.length-1)throw new Error(`backend.cumprod in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${d}`);let c=Qt(u.dtype,"int32"),p=v.makeOnesTypedArray(v.sizeFromShape(u.shape),c),h=a.data.get(u.dataId).values,m=u.shape[u.shape.length-1],f=o?(y,x)=>y+m-x-1:(y,x)=>y+x;for(let y=0;y<h.length;y+=m)for(let x=0;x<m;x++){let A=f(y,x);if(x===0)p[A]=i?1:h[A];else{let b=f(y,x-1);p[A]=i?h[b]*p[b]:h[A]*p[b]}}let g=a.makeTensorInfo(u.shape,c,p);if(l!=null){let y=I.getUndoAxesPermutation(l),x=Va({inputs:{x:g},backend:a,attrs:{perm:y}});return a.disposeIntermediateTensorInfo(g),a.disposeIntermediateTensorInfo(u),x}return g}var yB={kernelName:eo,backendName:"cpu",kernelFunc:gB};function xB(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=n;Ie(r,"cumsum");let l=I.getAxesPermutation([s],r.shape.length),u=r;l!=null&&(u=Va({inputs:{x:r},backend:a,attrs:{perm:l}}));let d=I.getInnerMostAxes(1,r.shape.length)[0];if(d!==u.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${d}`);let c=Qt(u.dtype,"int32"),p=v.makeZerosTypedArray(v.sizeFromShape(u.shape),c),h=a.data.get(u.dataId).values,m=u.shape[u.shape.length-1],f=o?(y,x)=>y+m-x-1:(y,x)=>y+x;for(let y=0;y<h.length;y+=m)for(let x=0;x<m;x++){let A=f(y,x);if(x===0)p[A]=i?0:h[A];else{let b=f(y,x-1);p[A]=i?h[b]+p[b]:h[A]+p[b]}}let g=a.makeTensorInfo(u.shape,c,p);if(l!=null){let y=I.getUndoAxesPermutation(l),x=Va({inputs:{x:g},backend:a,attrs:{perm:y}});return a.disposeIntermediateTensorInfo(g),a.disposeIntermediateTensorInfo(u),x}return g}var AB={kernelName:to,backendName:"cpu",kernelFunc:xB};function bB(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,d=w3(l,u,s.dtype,s.shape,i);return a.makeTensorInfo([i],s.dtype,d)}else if(r.shape.length===2){let l=a.bufferSync(r),u=a.bufferSync(s),d=P6(l,u,i,o);return a.makeTensorInfo(d.shape,s.dtype,d.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}var vB={kernelName:bu,backendName:"cpu",kernelFunc:bB};function wB(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],d=r.shape[3],c=l*s,p=u*s,h=d/(s*s),m=a.data.get(r.dataId).values,f=new Float32Array(o*c*p*h),g=0;for(let y=0;y<o;++y)for(let x=0;x<c;++x){let A=Math.floor(x/s),b=x%s;for(let w=0;w<p;++w){let S=Math.floor(w/s),C=w%s,N=(b*s+C)*h;for(let M=0;M<h;++M){let F=M+N+d*(S+u*(A+l*y));f[g++]=m[F]}}}return a.makeTensorInfo([o,c,p,h],r.dtype,f)}var kB={kernelName:no,backendName:"cpu",kernelFunc:wB};function Nv(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=n;Ie([r,s],"depthwiseConv2DNative");let d=v.computeStrides(r.shape),c=v.computeStrides(s.shape),p=l;p==null&&(p=[1,1]),v.assert(I.eitherStridesOrDilationsAreOne(i,p),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${p}'`);let h=I.computeConv2DInfo(r.shape,s.shape,i,p,o,u,!0),{filterHeight:m,filterWidth:f,dilationHeight:g,dilationWidth:y,padInfo:x}=h,A=x.left,b=x.top,w=h.outChannels/h.inChannels,S=new Rt(h.outShape,r.dtype),C=a.data.get(r.dataId).values,N=a.data.get(s.dataId).values,M=S.values;for(let F=0;F<h.batchSize;++F){let E=F*d[0],T=F*S.strides[0];for(let D=0;D<h.outHeight;++D){let O=T+D*S.strides[1],W=D*h.strideHeight-b;for(let $=0;$<m;++$){let U=W+$*g;if(U<0||U>=h.inHeight)continue;let G=$*c[0],q=E+U*d[1];for(let H=0;H<h.outWidth;++H){let V=O+H*S.strides[2],Z=H*h.strideWidth-A;for(let X=0;X<f;++X){let re=Z+X*y;if(re<0||re>=h.inWidth)continue;let ee=G+X*c[1],ge=q+re*h.inChannels,ie=V,be=ee;for(let Ce=0;Ce<h.inChannels;++Ce){let Ee=C[ge+Ce];for(let Le=0;Le<w;++Le)M[ie+Le]+=Ee*N[be+Le];ie+=w,be+=w}}}}}}return a.makeTensorInfo(S.shape,S.dtype,S.values)}var IB={kernelName:ro,backendName:"cpu",kernelFunc:Nv};function SB(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:d}=n;Ie([r,s],"depthwiseConv2dNativeBackpropFilter");let c=I.computeConv2DInfo(r.shape,d,i,o,l,u,!0),{strideHeight:p,strideWidth:h,filterHeight:m,filterWidth:f}=c,g=new Rt(c.filterShape,"float32"),y=c.padInfo.left,x=c.padInfo.top,A=c.outChannels/c.inChannels,b=a.data.get(r.dataId).values,w=new Rt(r.shape,r.dtype,b),S=a.data.get(s.dataId).values,C=new Rt(s.shape,s.dtype,S);for(let N=0;N<m;++N){let M=Math.max(0,Math.ceil((x-N)/p)),F=Math.min(c.outHeight,(c.inHeight+x-N)/p);for(let E=0;E<f;++E){let T=Math.max(0,Math.ceil((y-E)/h)),D=Math.min(c.outWidth,(c.inWidth+y-E)/h);for(let O=0;O<c.outChannels;++O){let W=Math.trunc(O/A),$=O%A,U=0;for(let G=0;G<c.batchSize;++G)for(let q=M;q<F;++q){let H=N+q*p-x;for(let V=T;V<D;++V){let Z=E+V*h-y;U+=w.get(G,H,Z,W)*C.get(G,q,V,O)}}g.set(U,N,E,W,$)}}}return a.makeTensorInfo(g.shape,g.dtype,g.values)}var TB={kernelName:vp,backendName:"cpu",kernelFunc:SB};function CB(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:d}=n;Ie([r,s],"depthwiseConv2DNativeBackpropInput");let c=v.computeStrides(r.shape),p=v.computeStrides(s.shape),h=I.computeConv2DInfo(d,s.shape,i,o,l,u,!0),m=new Rt(h.inShape,"float32"),f=m.values,[g,y,x]=m.strides,A=a.data.get(r.dataId).values,[b,w,S]=c,C=a.data.get(s.dataId).values,[N,M,F]=p,{batchSize:E,filterHeight:T,filterWidth:D,inChannels:O,inHeight:W,inWidth:$,outChannels:U,outHeight:G,outWidth:q,strideHeight:H,strideWidth:V}=h,Z=T-1-h.padInfo.top,X=D-1-h.padInfo.left,re=U/O;for(let ee=0;ee<E;++ee)for(let ge=0;ge<O;++ge)for(let ie=0;ie<W;++ie){let be=ie-Z,Ce=Math.max(0,Math.ceil(be/H)),Ee=Math.min(G,(T+be)/H);for(let Le=0;Le<$;++Le){let qe=Le-X,gt=Math.max(0,Math.ceil(qe/V)),dt=Math.min(q,(D+qe)/V),st=0;for(let it=Ce;it<Ee;++it){let He=it*H-be;for(let xt=gt;xt<dt;++xt){let ja=xt*V-qe,Lt=b*ee+w*it+S*xt,pn=N*(T-1-He)+M*(D-1-ja)+F*ge;for(let ua=0;ua<re;++ua){let Da=ge*re+ua,cn=A[Lt+Da],Pa=C[pn+ua];st+=cn*Pa}}}f[g*ee+y*ie+x*Le+ge]=st}}return a.makeTensorInfo(m.shape,m.dtype,m.values)}var NB={kernelName:wp,backendName:"cpu",kernelFunc:CB};function RB(e){let{inputs:t,backend:a}=e,{x:n}=t,r=v.sizeFromShape(n.shape),s=a.data.get(n.dataId).values,i=Te([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 EB={kernelName:vu,backendName:"cpu",kernelFunc:RB},MB={kernelName:so,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,d=n.shape.length,c=l.data.get(r.dataId).values,p=r.shape.length,{batchSize:h,inHeight:m,inWidth:f,inChannels:g,outHeight:y,outWidth:x,padInfo:A,strideHeight:b,strideWidth:w,filterHeight:S,filterWidth:C,dilationHeight:N,dilationWidth:M,outShape:F}=I.computeDilation2DInfo(n.shape,r.shape,s,i,"NHWC",o),E=v.sizeFromShape(F),T=F.length,D=v.getArrayFromDType(n.dtype,E);for(let O=0;O<h;++O)for(let W=0;W<y;++W){let $=W*b-A.top;for(let U=0;U<x;++U){let G=U*w-A.left;for(let q=0;q<g;++q){let H=Number.MIN_SAFE_INTEGER;for(let Z=0;Z<S;++Z){let X=$+Z*N;if(X>=0&&X<m)for(let re=0;re<C;++re){let ee=G+re*M;if(ee>=0&&ee<f){let ge=v.locToIndex([O,X,ee,q],d,v.computeStrides(n.shape)),ie=v.locToIndex([Z,re,q],p,v.computeStrides(r.shape)),be=u[ge]+c[ie];be>H&&(H=be)}}}let V=v.locToIndex([O,W,U,q],T,v.computeStrides(F));D[V]=H}}}return{dataId:l.write(v.toTypedArray(D,n.dtype),F,n.dtype),shape:F,dtype:n.dtype}}},FB={kernelName:Ql,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,d=v.toNestedArray(n.shape,u.data.get(n.dataId).values),c=v.toNestedArray(r.shape,u.data.get(r.dataId).values),{batchSize:p,inHeight:h,inWidth:m,inChannels:f,outHeight:g,outWidth:y,padInfo:x,strideHeight:A,strideWidth:b,filterHeight:w,filterWidth:S,dilationHeight:C,dilationWidth:N,outShape:M}=I.computeDilation2DInfo(n.shape,r.shape,i,o,"NHWC",l);v.assert(s.rank===M.length,()=>`Error in ${Ql}, dy must have the same rank as output ${M.length}, but got ${s.rank}`);let F=v.toNestedArray(M,u.data.get(s.dataId).values),E=v.makeZerosNestedTypedArray(r.shape,r.dtype);for(let T=0;T<p;++T)for(let D=0;D<g;++D){let O=D*A-x.top;for(let W=0;W<y;++W){let $=W*b-x.left;for(let U=0;U<f;++U){let G=Number.MIN_SAFE_INTEGER,q=0,H=0;for(let V=0;V<w;++V){let Z=O+V*C;if(Z>=0&&Z<h)for(let X=0;X<S;++X){let re=$+X*N;if(re>=0&&re<m){let ee=d[T][Z][re][U]+c[V][X][U];ee>G&&(G=ee,q=V,H=X)}}}E[q][H][U]+=F[T][D][W][U]}}}return{dataId:u.write(v.toTypedArray(E,n.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},$B={kernelName:Jl,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,d=v.toNestedArray(n.shape,u.data.get(n.dataId).values),c=v.toNestedArray(r.shape,u.data.get(r.dataId).values),{batchSize:p,inHeight:h,inWidth:m,inChannels:f,outHeight:g,outWidth:y,padInfo:x,strideHeight:A,strideWidth:b,filterHeight:w,filterWidth:S,dilationHeight:C,dilationWidth:N,outShape:M}=I.computeDilation2DInfo(n.shape,r.shape,i,o,"NHWC",l);v.assert(s.rank===M.length,()=>`Error in ${Jl}, dy must have the same rank as output ${M.length}, but got ${s.rank}`);let F=v.toNestedArray(M,u.data.get(s.dataId).values),E=v.makeZerosNestedTypedArray(n.shape,n.dtype);for(let T=0;T<p;++T)for(let D=0;D<g;++D){let O=D*A-x.top;for(let W=0;W<y;++W){let $=W*b-x.left;for(let U=0;U<f;++U){let G=Number.MIN_SAFE_INTEGER,q=O<0?0:O,H=$<0?0:$;for(let V=0;V<w;++V){let Z=O+V*C;if(Z>=0&&Z<h)for(let X=0;X<S;++X){let re=$+X*N;if(re>=0&&re<m){let ee=d[T][Z][re][U]+c[V][X][U];ee>G&&(G=ee,q=Z,H=re)}}}E[T][q][H][U]+=F[T][D][W][U]}}}return{dataId:u.write(v.toTypedArray(E,n.dtype),n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};function DB(e){let{inputs:t,backend:a,attrs:n}=e,{image:r}=t,{canvas:s,options:i}=n,{contextOptions:o,imageOptions:l}=i||{},u=(l==null?void 0:l.alpha)||1,d=(o==null?void 0:o.contextType)||"2d";if(d!=="2d")throw new Error(`Context type ${o.contextType} is not supported by the CPU backend.`);let c=s.getContext(d,(o==null?void 0:o.contextAttributes)||{});if(c==null)throw new Error(`Could not get the context with ${d} type.`);let[p,h]=r.shape.slice(0,2),m=r.shape.length===2?1:r.shape[2],f=a.data.get(r.dataId).values,g=r.dtype==="float32"?255:1,y=new Uint8ClampedArray(h*p*4);for(let A=0;A<p*h;++A){let b=[0,0,0,255*u];for(let S=0;S<m;S++){let C=f[A*m+S];if(r.dtype==="float32"){if(C<0||C>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${C}.`)}else if(r.dtype==="int32"&&(C<0||C>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${C}.`);m===1?(b[0]=C*g,b[1]=C*g,b[2]=C*g):b[S]=C*g}let w=A*4;y[w+0]=Math.round(b[0]),y[w+1]=Math.round(b[1]),y[w+2]=Math.round(b[2]),y[w+3]=Math.round(b[3])}s.width=h,s.height=p;let x=new ImageData(y,h,p);return c.putImageData(x,0,0),r}var PB={kernelName:kp,backendName:"cpu",kernelFunc:DB};function tc(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;Ie(r,"sum");let o;r.dtype==="bool"?o=ds({inputs:{x:r},backend:a,attrs:{dtype:"int32"}}):o=sr({inputs:{x:r},backend:a});let l=o.shape.length,u=v.parseAxisParam(s,o.shape),d=I.getAxesPermutation(u,l),c=u,p=o;d!=null&&(p=Va({inputs:{x:o},backend:a,attrs:{perm:d}}),c=I.getInnerMostAxes(c.length,l)),I.assertAxesAreInnerMostDims("sum",c,p.shape.length);let[h,m]=I.computeOutAndReduceShapes(p.shape,c),f=I.upcastType(p.dtype,"int32"),g=Ih(a,h,f),y=v.sizeFromShape(m),x=a.data.get(g.dataId).values,A=a.data.get(p.dataId).values;for(let b=0;b<x.length;++b){let w=b*y,S=0;for(let C=0;C<y;++C)S+=A[w+C];x[b]=S}if(i){let b=I.expandShapeToKeepDim(g.shape,u),w=g;g=bt({inputs:{x:g},backend:a,attrs:{shape:b}}),a.disposeIntermediateTensorInfo(w)}return a.disposeIntermediateTensorInfo(o),d!=null&&a.disposeIntermediateTensorInfo(p),g}var _B={kernelName:Qo,backendName:"cpu",kernelFunc:tc};function OB(e){let{inputs:t,backend:a,attrs:n}=e,{equation:r}=n,s=t,{allDims:i,summedDims:o,idDims:l}=I.decodeEinsumEquation(r,s.length);I.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:d}=I.getEinsumComputePath(o,l),c=d.length,p=null,h=i.length,m=[];for(let f=0;f<c;++f){for(let g of d[f]){let{permutationIndices:y,expandDims:x}=I.getEinsumPermutation(h,l[g]),A;I.isIdentityPermutation(y)?A=s[g]:(A=Va({inputs:{x:s[g]},backend:a,attrs:{perm:y}}),m.push(A));let b=A.shape.slice();for(let w=0;w<x.length;++w)b.splice(x[w],0,1);v.arraysEqual(A.shape,b)||(A=bt({inputs:{x:A},backend:a,attrs:{shape:b}}),m.push(A)),p===null?p=A:(p=l0({inputs:{a:A,b:p},backend:a}),m.push(p))}f<c-1&&(u[f]>=0&&(p=tc({inputs:{x:p},backend:a,attrs:{axis:u[f]-(i.length-h),keepDims:!1}}),m.push(p)),h--)}for(let f of m)f!==p&&a.disposeIntermediateTensorInfo(f);return p}var zB={kernelName:Ip,backendName:"cpu",kernelFunc:OB};function LB(e){let{inputs:t,backend:a}=e,{dy:n,y:r}=t;Ie([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>=0?s[l]=o[l]:s[l]=o[l]*(u+1)}return a.makeTensorInfo(r.shape,"float32",s)}var WB={kernelName:wu,backendName:"cpu",kernelFunc:LB},BB=I.ERF_P,VB=I.ERF_A1,UB=I.ERF_A2,GB=I.ERF_A3,HB=I.ERF_A4,jB=I.ERF_A5,qB=ct(lo,e=>{let t=Math.sign(e),a=Math.abs(e),n=1/(1+BB*a);return t*(1-((((jB*n+HB)*n+GB)*n+UB)*n+VB)*n*Math.exp(-a*a))}),XB={kernelName:lo,backendName:"cpu",kernelFunc:qB};function Ch(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),bt({inputs:{x:r},backend:a,attrs:{shape:o}})}var KB={kernelName:ku,backendName:"cpu",kernelFunc:Ch},YB=Pt((e,t)=>e/t),D3=Kt(io,YB),L1={kernelName:io,backendName:"cpu",kernelFunc:D3};function Rv(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],d=v.sizeFromShape(u),c=v.getTypedArrayFromDType("float32",d),p=v.getTypedArrayFromDType("float32",d);for(let g=0;g<r;g++){let y=Ci({inputs:{x:o},backend:a,attrs:{begin:[g,0],size:[1,s]}}),x=Ci({inputs:{x:l},backend:a,attrs:{begin:[g,0],size:[1,s]}}),A=Qa({inputs:{real:y,imag:x},backend:a}),{real:b,imag:w}=ZB(A,t,a),S=I.mergeRealAndImagArrays(b,w);for(let C=0;C<s;C++){let N=I.getComplexWithIndex(S,C);c[g*s+C]=N.real,p[g*s+C]=N.imag}a.disposeIntermediateTensorInfo(y),a.disposeIntermediateTensorInfo(x),a.disposeIntermediateTensorInfo(A)}let h=a.makeTensorInfo(u,"float32",c),m=a.makeTensorInfo(u,"float32",p),f=Qa({inputs:{real:h,imag:m},backend:a});return a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(m),f}function ZB(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(JB(n)){let o=W1(s,i,n,t,a),l=[e.shape[0],e.shape[1]];if(t){let u=a.makeTensorInfo(l,"float32",o.real),d=a.makeTensorInfo(l,"float32",o.imag),c=a.makeTensorInfo([],"float32",v.createScalarValue(n,"float32")),p=sr({inputs:{x:c},backend:a}),h=L1.kernelFunc({inputs:{a:u,b:c},backend:a}),m=L1.kernelFunc({inputs:{a:d,b:p},backend:a}),f=a.data.get(h.dataId).values,g=a.data.get(m.dataId).values;return a.disposeIntermediateTensorInfo(u),a.disposeIntermediateTensorInfo(d),a.disposeIntermediateTensorInfo(c),a.disposeIntermediateTensorInfo(p),a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(m),{real:f,imag:g}}return o}else{let o=I.mergeRealAndImagArrays(s,i),l=QB(o,n,t);return I.splitRealAndImagArrays(l)}}function JB(e){return(e&e-1)===0}function W1(e,t,a,n,r){if(a===1)return{real:e,imag:t};let s=I.mergeRealAndImagArrays(e,t),i=a/2,o=I.complexWithEvenIndex(s),l=o.real,u=o.imag,d=[l.length],c=r.makeTensorInfo(d,"float32",l),p=r.makeTensorInfo(d,"float32",u),h=Qa({inputs:{real:c,imag:p},backend:r}),m=I.complexWithOddIndex(s),f=m.real,g=m.imag,y=[f.length],x=r.makeTensorInfo(y,"float32",f),A=r.makeTensorInfo(y,"float32",g),b=Qa({inputs:{real:x,imag:A},backend:r}),w=W1(l,u,i,n,r),S=w.real,C=w.imag,N=[S.length],M=r.makeTensorInfo(N,"float32",S),F=r.makeTensorInfo(N,"float32",C),E=Qa({inputs:{real:M,imag:F},backend:r}),T=W1(f,g,i,n,r),D=T.real,O=T.imag,W=[D.length],$=r.makeTensorInfo(W,"float32",D),U=r.makeTensorInfo(W,"float32",O),G=Qa({inputs:{real:$,imag:U},backend:r}),q=I.exponents(a,n),H=[q.real.length],V=r.makeTensorInfo(H,"float32",q.real),Z=r.makeTensorInfo(H,"float32",q.imag),X=Qa({inputs:{real:V,imag:Z},backend:r}),re=l0({inputs:{a:X,b:G},backend:r}),ee=su({inputs:{a:E,b:re},backend:r}),ge=M3({inputs:{a:E,b:re},backend:r}),ie=Ti({inputs:{input:ee},backend:r}),be=Ti({inputs:{input:ge},backend:r}),Ce=iu({inputs:{input:ee},backend:r}),Ee=iu({inputs:{input:ge},backend:r}),Le=ou({inputs:[ie,be],backend:r,attrs:{axis:0}}),qe=ou({inputs:[Ce,Ee],backend:r,attrs:{axis:0}}),gt=r.data.get(Le.dataId).values,dt=r.data.get(qe.dataId).values;return r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(x),r.disposeIntermediateTensorInfo(A),r.disposeIntermediateTensorInfo(b),r.disposeIntermediateTensorInfo(M),r.disposeIntermediateTensorInfo(F),r.disposeIntermediateTensorInfo(E),r.disposeIntermediateTensorInfo($),r.disposeIntermediateTensorInfo(U),r.disposeIntermediateTensorInfo(G),r.disposeIntermediateTensorInfo(V),r.disposeIntermediateTensorInfo(Z),r.disposeIntermediateTensorInfo(X),r.disposeIntermediateTensorInfo(re),r.disposeIntermediateTensorInfo(ee),r.disposeIntermediateTensorInfo(ge),r.disposeIntermediateTensorInfo(ie),r.disposeIntermediateTensorInfo(Ce),r.disposeIntermediateTensorInfo(be),r.disposeIntermediateTensorInfo(Ee),r.disposeIntermediateTensorInfo(Le),r.disposeIntermediateTensorInfo(qe),{real:gt,imag:dt}}function QB(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=I.exponent(r*o,t,a),u=I.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),I.assignToTypedArray(n,s,i,r)}return n}function eV(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=bt({inputs:{x:n},backend:a,attrs:{shape:[i,s]}}),l=Rv(o,!1,a),u=bt({inputs:{x:l},backend:a,attrs:{shape:n.shape}});return a.disposeIntermediateTensorInfo(o),a.disposeIntermediateTensorInfo(l),u}var tV={kernelName:Sp,backendName:"cpu",kernelFunc:eV};function P3(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 nV(o,r,i),t.makeTensorInfo(n,i,o)}var aV={kernelName:Iu,backendName:"cpu",kernelFunc:P3};function nV(e,t,a){e.fill(t)}var rV={kernelName:uo,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,d=r.data.get(n.dataId).values;for(let c=0;c<i;c++){let p=c*l*o*u;for(let h=0;h<o;h++){let m=h*(l*u);for(let f=0;f<l;f++){let g=f*u;for(let y=0;y<u;y++){let x=Math.round(l-f-1),A=p+m+g+y,b=d[A];if(x>=0&&x<l){let w=x*u,S=p+m+w+y;b=d[S]}s[A]=b}}}}return{dataId:r.write(s,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};function sV(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:d,dilations:c,dimRoundingMode:p,activation:h,leakyreluAlpha:m}=n,f=Cv({inputs:{x:r,filter:s},backend:a,attrs:{strides:l,pad:u,dataFormat:d,dilations:c,dimRoundingMode:p}});if(i){let g=f;if(d==="NCHW"&&i.shape.length===1&&i.shape[0]!==1){let y=bt({inputs:{x:i},backend:a,attrs:{shape:[i.shape[0],1,1]}});f=su({inputs:{a:f,b:y},backend:a}),a.disposeIntermediateTensorInfo(y)}else f=su({inputs:{a:f,b:i},backend:a});a.disposeIntermediateTensorInfo(g)}if(h){let g=f;if(d==="NCHW"&&h==="prelu"&&o.shape.length===1&&o.shape[0]!==1){let y=bt({inputs:{x:o},backend:a,attrs:{shape:[o.shape[0],1,1]}});f=Th(a,f,h,y,m),a.disposeIntermediateTensorInfo(y)}else f=Th(a,f,h,o,m);a.disposeIntermediateTensorInfo(g)}return f}var iV={kernelName:as,backendName:"cpu",kernelFunc:sV};function oV(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:d,dilations:c,dimRoundingMode:p,activation:h,leakyreluAlpha:m}=n,f=Nv({inputs:{x:r,filter:s},backend:a,attrs:{strides:l,pad:u,dataFormat:d,dilations:c,dimRoundingMode:p}});if(i){let g=f;f=su({inputs:{a:f,b:i},backend:a}),a.disposeIntermediateTensorInfo(g)}if(h){let g=f;f=Th(a,f,h,o,m),a.disposeIntermediateTensorInfo(g)}return f}var lV={kernelName:ns,backendName:"cpu",kernelFunc:oV};function uV(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,d,c]=I.prepareAndValidate(n,r);if(u===0)return a.makeTensorInfo(l,n.dtype,[]);let p=a.data.get(r.dataId).values,h=a.bufferSync(n),m=H6(p,h,n.dtype,u,o,d,c,n.shape,s);return a.makeTensorInfo(l,n.dtype,m.values)}var dV={kernelName:co,backendName:"cpu",kernelFunc:uV};function pV(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,indices:s}=t,{axis:i,batchDims:o}=n;Ie([r,s],"gatherV2");let l=v.parseAxisParam(i,r.shape)[0],u=a.data.get(s.dataId).values,d=r.shape[l];for(let b=0;b<u.length;++b){let w=u[b];v.assert(w<=d-1&&w>=0,()=>`GatherV2: the index value ${w} is not in [0, ${d-1}]`)}let c=o;o==null&&(c=0);let p=v.sizeFromShape(s.shape),h=I.segment_util.collectGatherOpShapeInfo(r,s,l,c),m=bt({inputs:{x:r},backend:a,attrs:{shape:[h.batchSize,h.outerSize,h.dimSize,h.sliceSize]}}),f=bt({inputs:{x:s},backend:a,attrs:{shape:[h.batchSize,p/h.batchSize]}}),g=[h.batchSize,h.outerSize,p/h.batchSize,h.sliceSize],y=a.bufferSync(f),x=a.bufferSync(m),A=j6(x,y,g);return a.disposeIntermediateTensorInfo(m),a.disposeIntermediateTensorInfo(f),a.makeTensorInfo(h.outputShape,A.dtype,A.values)}var cV={kernelName:Su,backendName:"cpu",kernelFunc:pV};function hV(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=bt({inputs:{x:n},backend:a,attrs:{shape:[i,s]}}),l=Rv(o,!0,a),u=bt({inputs:{x:l},backend:a,attrs:{shape:n.shape}});return a.disposeIntermediateTensorInfo(o),a.disposeIntermediateTensorInfo(l),u}var mV={kernelName:Tp,backendName:"cpu",kernelFunc:hV},fV=ct(mo,e=>Number.isFinite(e)?1:0,"bool"),gV={kernelName:mo,backendName:"cpu",kernelFunc:fV},yV=ct(fo,e=>Math.abs(e)===1/0?1:0,"bool"),xV={kernelName:fo,backendName:"cpu",kernelFunc:yV},AV=ct(go,e=>Number.isNaN(e)?1:0,"bool"),bV={kernelName:go,backendName:"cpu",kernelFunc:AV};function vV(e){let{backend:t,attrs:a}=e,{start:n,stop:r,num:s}=a,i=Z6(n,r,s);return t.makeTensorInfo([i.length],"float32",i)}var wV={kernelName:xo,backendName:"cpu",kernelFunc:vV},kV=ct(Ao,e=>Math.log1p(e)),IV={kernelName:Ao,backendName:"cpu",kernelFunc:kV},SV=Pt((e,t)=>e&&t),TV=Kt(bo,SV,null,"bool"),CV={kernelName:bo,backendName:"cpu",kernelFunc:TV},NV=ct(vo,e=>e?0:1,"bool"),RV={kernelName:vo,backendName:"cpu",kernelFunc:NV},EV=Pt((e,t)=>e||t),MV=Kt(wo,EV,null,"bool"),FV={kernelName:wo,backendName:"cpu",kernelFunc:MV};function $V(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n;Ie(r,"LRN");let u=r.shape[3],d=u-1,c=a.data.get(r.dataId).values,p=v.sizeFromShape(r.shape),h=new Float32Array(p);function m(f){let g=f%u,y=f-g+Math.max(0,g-s),x=f-g+Math.min(g+s,d),A=0;for(;y<=x;y++){let b=c[y];A+=b*b}return A}for(let f=0;f<p;f++){let g=m(f),y=c[f]*Math.pow(i+o*g,-l);h[f]=y}return a.makeTensorInfo(r.shape,r.dtype,h)}var DV={kernelName:ko,backendName:"cpu",kernelFunc:$V};function PV(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:d}=n;Ie(i,"LRNGrad");let c=v.sizeFromShape(i.shape),p=i.shape[3],h=a.data.get(i.dataId).values,m=a.data.get(r.dataId).values,f=a.data.get(s.dataId).values,g=new Float32Array(c),y=c;for(let x=0;x<y;x++){let A=x%p,b=x-A+Math.max(0,A-o),w=x-A+Math.min(p,A+o+1),S=0;for(let C=b;C<w;C++)S+=Math.pow(m[C],2);S=u*S+l;for(let C=b;C<w;C++){let N=-2*u*d*m[C]*f[x]/S;x===C&&(N+=Math.pow(S,-d)),N*=h[x],g[C]+=N}}return a.makeTensorInfo(i.shape,r.dtype,g)}var _V={kernelName:Tu,backendName:"cpu",kernelFunc:PV};function Ev(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,d=v.parseAxisParam(s,l),c=d,p=I.getAxesPermutation(c,u),h=o.data.get(r.dataId).values;if(p!=null){let b=new Array(u);for(let w=0;w<b.length;w++)b[w]=l[p[w]];h=S3(h,l,r.dtype,p,b),c=I.getInnerMostAxes(c.length,u),l=b}Ie(r,"max"),I.assertAxesAreInnerMostDims("max",c,u);let[m,f]=I.computeOutAndReduceShapes(l,c),g=v.sizeFromShape(f),y=Q6(h,g,m,r.dtype),x=o.write(y,m,r.dtype),A=m;return i&&(A=I.expandShapeToKeepDim(m,d)),{dataId:x,shape:A,dtype:r.dtype}}var OV={kernelName:Io,backendName:"cpu",kernelFunc:Ev};function zV(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t;Ie(r,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1;v.assert(I.eitherStridesOrDilationsAreOne(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=I.computePool2DInfo(r.shape,s,i,u,o,l),c;if(d.filterWidth===1&&d.filterHeight===1&&v.arraysEqual(d.inShape,d.outShape))c=sr({inputs:{x:r},backend:a});else{let p=a.data.get(r.dataId).values,h=v.computeStrides(r.shape),m=$3(p,r.shape,r.dtype,h,d,"max");c=a.makeTensorInfo(d.outShape,r.dtype,m.values)}return c}var LV={kernelName:So,backendName:"cpu",kernelFunc:zV};function WV(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=n;Ie(r,"maxPool3d");let d=I.computePool3DInfo(r.shape,s,i,1,o,l,u),c=a.data.get(r.dataId).values,p=Tv(c,r.shape,r.dtype,v.computeStrides(r.shape),d,"max");return a.makeTensorInfo(p.shape,"float32",p.values)}var BV={kernelName:Cu,backendName:"cpu",kernelFunc:WV};function VV(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=n;Ie([r,s],"maxPool3DGrad");let d=I.computePool3DInfo(s.shape,i,o,1,l,u),c=a.bufferSync(s),p=EW(c,d),h=d.strideDepth,m=d.strideHeight,f=d.strideWidth,g=d.dilationDepth,y=d.dilationHeight,x=d.dilationWidth,A=d.effectiveFilterDepth,b=d.effectiveFilterHeight,w=d.effectiveFilterWidth,S=A-1-d.padInfo.front,C=w-1-d.padInfo.left,N=b-1-d.padInfo.top,M=Te(s.shape,"float32"),F=a.bufferSync(r);for(let E=0;E<d.batchSize;++E)for(let T=0;T<d.inChannels;++T)for(let D=0;D<d.inDepth;++D)for(let O=0;O<d.inHeight;++O)for(let W=0;W<d.inWidth;++W){let $=D-S,U=O-N,G=W-C,q=0;for(let H=0;H<A;H+=g){let V=($+H)/h;if(!(V<0||V>=d.outDepth||Math.floor(V)!==V))for(let Z=0;Z<b;Z+=y){let X=(U+Z)/m;if(!(X<0||X>=d.outHeight||Math.floor(X)!==X))for(let re=0;re<w;re+=x){let ee=(G+re)/f;if(ee<0||ee>=d.outWidth||Math.floor(ee)!==ee)continue;let ge=A*b*w-1-p.get(E,V,X,ee,T),ie=H*b*w+Z*w+re,be=ge===ie?1:0;if(be===0)continue;let Ce=F.get(E,V,X,ee,T);q+=Ce*be}}}M.set(q,E,D,O,W,T)}return a.makeTensorInfo(M.shape,M.dtype,M.values)}var UV={kernelName:Rp,backendName:"cpu",kernelFunc:VV};function GV(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s,output:i}=t,o=s;Ie([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:d,dimRoundingMode:c}=n,p=I.computePool2DInfo(o.shape,l,u,1,d,c),h=a.data.get(o.dataId).values,m=Te(p.outShape,o.dtype,Sv(h,o.shape,o.dtype,p).values),f=p.strideHeight,g=p.strideWidth,y=p.dilationHeight,x=p.dilationWidth,A=p.effectiveFilterHeight,b=p.effectiveFilterWidth,w=b-1-p.padInfo.left,S=A-1-p.padInfo.top,C=Te(o.shape,"float32"),N=a.data.get(r.dataId).values,M=Te(r.shape,"float32",N);for(let F=0;F<p.batchSize;++F)for(let E=0;E<p.inChannels;++E)for(let T=0;T<p.inHeight;++T)for(let D=0;D<p.inWidth;++D){let O=T-S,W=D-w,$=0;for(let U=0;U<A;U+=y){let G=(O+U)/f;if(!(G<0||G>=p.outHeight||Math.floor(G)!==G))for(let q=0;q<b;q+=x){let H=(W+q)/g;if(H<0||H>=p.outWidth||Math.floor(H)!==H)continue;let V=A*b-1-m.get(F,G,H,E),Z=U*b+q,X=V===Z?1:0;if(X===0)continue;let re=M.get(F,G,H,E);$+=re*X}}C.set($,F,T,D,E)}return a.makeTensorInfo(C.shape,C.dtype,C.values)}var HV={kernelName:Np,backendName:"cpu",kernelFunc:GV};function jV(e,t,a,n,r){let s=v.computeStrides(t),i=$3(e,t,a,s,r,"max"),o=Sv(e,t,a,r,!0,n);return[i.values,o.values]}var qV={kernelName:Nu,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:a})=>{let{x:n}=e,{filterSize:r,strides:s,pad:i,includeBatchInIndex:o}=t,l=a;Ie(n,"MaxPoolWithArgmax");let u=l.data.get(n.dataId).values,d=I.computePool2DInfo(n.shape,r,s,[1,1],i),[c,p]=jV(u,n.shape,n.dtype,o,d),h=l.write(c,d.outShape,n.dtype),m=l.write(p,d.outShape,n.dtype);return[{dataId:h,shape:d.outShape,dtype:n.dtype},{dataId:m,shape:d.outShape,dtype:"int32"}]}};function XV(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n,o=v.parseAxisParam(s,r.shape),l=I.computeOutAndReduceShapes(r.shape,o)[1],u=v.sizeFromShape(l),d=[],c=a.makeTensorInfo([],"float32",new Float32Array([u]));d.push(c);let p=ds({inputs:{x:r},backend:a,attrs:{dtype:"float32"}});d.push(p);let h=D3({inputs:{a:p,b:c},backend:a});d.push(h);let m=tc({inputs:{x:h},backend:a,attrs:{axis:s,keepDims:i}});return d.forEach(f=>a.disposeIntermediateTensorInfo(f)),m}var KV={kernelName:To,backendName:"cpu",kernelFunc:XV};function YV(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;Ie(r,"min");let o=v.parseAxisParam(s,r.shape),l=o,u=I.getAxesPermutation(l,r.shape.length),d=r;u!=null&&(d=Va({inputs:{x:r},backend:a,attrs:{perm:u}}),l=I.getInnerMostAxes(l.length,r.shape.length)),I.assertAxesAreInnerMostDims("min",l,d.shape.length);let[c,p]=I.computeOutAndReduceShapes(d.shape,l),h=v.sizeFromShape(p),m=v.makeZerosTypedArray(v.sizeFromShape(c),d.dtype),f=a.data.get(d.dataId).values;for(let y=0;y<m.length;++y){let x=y*h,A=f[x];for(let b=0;b<h;++b){let w=f[x+b];(Number.isNaN(w)||w<A)&&(A=w)}m[y]=A}u!=null&&a.disposeIntermediateTensorInfo(d);let g=a.makeTensorInfo(c,d.dtype,m);if(i){let y=I.expandShapeToKeepDim(c,o),x=bt({inputs:{x:g},backend:a,attrs:{shape:y}});return a.disposeIntermediateTensorInfo(g),x}return g}var ZV={kernelName:Co,backendName:"cpu",kernelFunc:YV};function JV(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{paddings:s,mode:i}=n;Ie(r,"mirrorPad");let o=s.map((x,A)=>x[0]+r.shape[A]+x[1]),l=s.map(x=>x[0]),u=s.map((x,A)=>x[0]+r.shape[A]),d=i==="reflect"?0:1,c=a.data.get(r.dataId).values,p=r.shape.length,h=v.computeStrides(r.shape),m=v.sizeFromShape(o),f=o.length,g=v.computeStrides(o),y=v.getTypedArrayFromDType(r.dtype,m);for(let x=0;x<m;x++){let A=v.indexToLoc(x,f,g);for(let w=0;w<f;w++)A[w]<l[w]?A[w]=l[w]*2-A[w]-d:A[w]>=u[w]&&(A[w]=(u[w]-1)*2-A[w]+d);A=A.map((w,S)=>w-l[S]);let b=v.locToIndex(A,p,h);y[x]=c[b]}return{dataId:a.write(y,o,r.dtype),shape:o,dtype:r.dtype}}var QV={kernelName:No,backendName:"cpu",kernelFunc:JV},eU=Pt((e,t)=>{let a=e%t;return e<0&&t<0||e>=0&&t>=0?a:(a+t)%t}),tU=Kt(Ro,eU),aU={kernelName:Ro,backendName:"cpu",kernelFunc:tU},nU=uu(EA());function Mv(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=Ev({inputs:{x:r},backend:a,attrs:{reductionIndices:l,keepDims:!1}}),d=I.expandShapeToKeepDim(u.shape,l),c=bt({inputs:{x:u},backend:a,attrs:{shape:d}}),p=M3({inputs:{a:r,b:c},backend:a}),h=B6({inputs:{x:p},backend:a}),m=tc({inputs:{x:h},backend:a,attrs:{axis:l,keepDims:!1}}),f=bt({inputs:{x:m},backend:a,attrs:{shape:d}}),g=D3({inputs:{a:h,b:f},backend:a});return a.disposeIntermediateTensorInfo(u),a.disposeIntermediateTensorInfo(c),a.disposeIntermediateTensorInfo(p),a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(m),a.disposeIntermediateTensorInfo(f),g}var rU={kernelName:el,backendName:"cpu",kernelFunc:Mv};function sU(e){let{inputs:t,backend:a,attrs:n}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=n;Ie(r,"multinomial");let l=o?r:Mv({inputs:{logits:r},backend:a,attrs:{dim:-1}}),u=l.shape[0],d=l.shape[1],c=a.data.get(l.dataId).values,p=[u,s],h=v.makeZerosTypedArray(v.sizeFromShape(p),"int32");for(let m=0;m<u;++m){let f=m*d,g=new Float32Array(d-1);g[0]=c[f];for(let A=1;A<g.length;++A)g[A]=g[A-1]+c[f+A];let y=nU.alea(i.toString()),x=m*s;for(let A=0;A<s;++A){let b=y();h[x+A]=g.length;for(let w=0;w<g.length;w++)if(b<g[w]){h[x+A]=w;break}}}return o||a.disposeIntermediateTensorInfo(l),a.makeTensorInfo(p,"int32",h)}var iU={kernelName:Eo,backendName:"cpu",kernelFunc:sU},oU=Fn.nonMaxSuppressionV3Impl;function lU(e){let{inputs:t,backend:a,attrs:n}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=n;Ie(r,"NonMaxSuppression");let u=a.data.get(r.dataId).values,d=a.data.get(s.dataId).values,{selectedIndices:c}=oU(u,d,i,o,l);return a.makeTensorInfo([c.length],"int32",new Int32Array(c))}var uU={kernelName:Mo,backendName:"cpu",kernelFunc:lU},dU=Fn.nonMaxSuppressionV4Impl;function pU(e){let{inputs:t,backend:a,attrs:n}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=n;Ie(r,"NonMaxSuppressionPadded");let d=a.data.get(r.dataId).values,c=a.data.get(s.dataId).values,{selectedIndices:p,validOutputs:h}=dU(d,c,i,o,l,u);return[a.makeTensorInfo([p.length],"int32",new Int32Array(p)),a.makeTensorInfo([],"int32",new Int32Array([h]))]}var cU={kernelName:Eu,backendName:"cpu",kernelFunc:pU},hU=Fn.nonMaxSuppressionV5Impl;function mU(e){let{inputs:t,backend:a,attrs:n}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=n;Ie(r,"NonMaxSuppressionWithScore");let d=a.data.get(r.dataId).values,c=a.data.get(s.dataId).values,p=i,h=o,m=l,f=u,{selectedIndices:g,selectedScores:y}=hU(d,c,p,h,m,f);return[a.makeTensorInfo([g.length],"int32",new Int32Array(g)),a.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var fU={kernelName:Fo,backendName:"cpu",kernelFunc:mU};function gU(e){let{inputs:t,backend:a,attrs:n}=e,{indices:r}=t,{dtype:s,depth:i,onValue:o,offValue:l}=n;Ie(r,"oneHot");let u=v.sizeFromShape(r.shape),d=new Float32Array(u*i);d.fill(l);let c=a.data.get(r.dataId).values;for(let p=0;p<u;++p)c[p]>=0&&c[p]<i&&(d[p*i+c[p]]=o);return a.makeTensorInfo([...r.shape,i],s,d)}var yU={kernelName:$o,backendName:"cpu",kernelFunc:gU};function Nh(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=Ti({inputs:{input:n},backend:a}),s=Nh({inputs:{x:r},backend:a}),i=iu({inputs:{input:n},backend:a}),o=Nh({inputs:{x:i},backend:a}),l=Qa({inputs:{real:s,imag:o},backend:a});return a.disposeIntermediateTensorInfo(r),a.disposeIntermediateTensorInfo(s),a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}else return P3({backend:a,attrs:{shape:n.shape,value:0,dtype:n.dtype}})}var xU={kernelName:qu,backendName:"cpu",kernelFunc:Nh};function Fv(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=Ti({inputs:{input:n},backend:a}),s=Fv({inputs:{x:r},backend:a}),i=iu({inputs:{input:n},backend:a}),o=Nh({inputs:{x:i},backend:a}),l=Qa({inputs:{real:s,imag:o},backend:a});return a.disposeIntermediateTensorInfo(r),a.disposeIntermediateTensorInfo(s),a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}else return P3({backend:a,attrs:{shape:n.shape,value:1,dtype:n.dtype}})}var AU={kernelName:Mu,backendName:"cpu",kernelFunc:Fv};function $v(e){let{inputs:t,backend:a,attrs:n}=e,{axis:r}=n;if(t.length===1)return Ch({inputs:{input:t[0]},backend:a,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(d=>{v.assertShapesMatch(s,d.shape,"All tensors passed to stack must have matching shapes"),v.assert(i===d.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(d=>{let c=Ch({inputs:{input:d},backend:a,attrs:{dim:r}});return o.push(c),c}),u=ou({inputs:l,backend:a,attrs:{axis:r}});return o.forEach(d=>a.disposeIntermediateTensorInfo(d)),u}var bU={kernelName:Fu,backendName:"cpu",kernelFunc:$v};function vU(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{paddings:s,constantValue:i}=n;Ie(r,"pad");let o=s.map((y,x)=>y[0]+r.shape[x]+y[1]),l=s.map(y=>y[0]),u=a.data.get(r.dataId).values,d=v.sizeFromShape(r.shape),c=r.shape.length,p=v.computeStrides(r.shape),h=v.sizeFromShape(o),m=o.length,f=v.computeStrides(o),g=v.getTypedArrayFromDType(r.dtype,h);i!==0&&g.fill(i);for(let y=0;y<d;y++){let x=v.indexToLoc(y,c,p).map((b,w)=>b+l[w]),A=v.locToIndex(x,m,f);g[A]=u[y]}return{dataId:a.write(g,o,r.dtype),shape:o,dtype:r.dtype}}var Dv={kernelName:Do,backendName:"cpu",kernelFunc:vU},wU=Pt((e,t)=>Math.pow(e,t)),kU=Kt(Po,wU),IU={kernelName:Po,backendName:"cpu",kernelFunc:kU};function SU(e){let{inputs:t,backend:a,attrs:n}=e,{paramsNestedSplits:r,paramsDenseValues:s,indices:i}=t,{outputRaggedRank:o}=n,l=r.map(y=>a.data.get(y.dataId).values),u=r.map(y=>y.shape),d=a.data.get(s.dataId).values,c=a.data.get(i.dataId).values,[p,h,m]=sv(l,u,d,s.shape,s.dtype,c,i.shape,o),f=p.map(y=>a.makeTensorInfo([y.length],"int32",y)),g=a.makeTensorInfo(m,s.dtype,h);return f.concat([g])}var TU={kernelName:Lh,backendName:"cpu",kernelFunc:SU};function CU(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,d]=iv(i,n.shape,n.dtype,o,r.shape,l,s.shape),c=a.makeTensorInfo([u.length],"int32",u),p=a.makeTensorInfo([d.length],n.dtype,d);return[c,p]}var NU={kernelName:Wh,backendName:"cpu",kernelFunc:CU};function RU(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,d=a.data.get(s.dataId).values,c=a.data.get(i.dataId).values,p=o.map(g=>a.data.get(g.dataId).values),h=o.map(g=>g.shape),[m,f]=ov(u,r.shape,d,s.shape,s.dtype,c,i.shape,p,h,l);return a.makeTensorInfo(m,s.dtype,f)}var EU={kernelName:Bh,backendName:"cpu",kernelFunc:RU};function MU(e){let{backend:t,attrs:a}=e,{start:n,stop:r,dtype:s,step:i}=a,o=T3(n,r,i,s);return t.makeTensorInfo([o.length],s,o)}var FU={kernelName:$u,backendName:"cpu",kernelFunc:MU},$U=ct(zo,e=>1/e),DU={kernelName:zo,backendName:"cpu",kernelFunc:$U};function PU(e){let{inputs:t,backend:a,attrs:n}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n;Ie(r,"resizeBilinear");let l=v.computeStrides(r.shape),[u,d]=o,[c,p,h,m]=r.shape,f=a.data.get(r.dataId).values,g=new Float32Array(v.sizeFromShape([c,u,d,m])),y=[s&&u>1?p-1:p,s&&d>1?h-1:h],x=[s&&u>1?u-1:u,s&&d>1?d-1:d],A=0,b=y[0]/x[0],w=y[1]/x[1];for(let S=0;S<c;S++)for(let C=0;C<u;C++){let N;i?N=b*(C+.5)-.5:N=b*C;let M=Math.max(0,Math.floor(N)),F=N-M,E=Math.min(p-1,Math.ceil(N)),T=S*l[0]+M*l[1],D=S*l[0]+E*l[1];for(let O=0;O<d;O++){let W;i?W=w*(O+.5)-.5:W=w*O;let $=Math.max(0,Math.floor(W)),U=W-$,G=Math.min(h-1,Math.ceil(W)),q=T+$*l[2],H=D+$*l[2],V=T+G*l[2],Z=D+G*l[2];for(let X=0;X<m;X++){let re=f[q+X],ee=f[H+X],ge=f[V+X],ie=f[Z+X],be=re+(ge-re)*U,Ce=ee+(ie-ee)*U,Ee=be+(Ce-be)*F;g[A++]=Ee}}}return a.makeTensorInfo([c,u,d,m],"float32",g)}var _U={kernelName:Bo,backendName:"cpu",kernelFunc:PU};function OU(e){let{inputs:t,backend:a,attrs:n}=e,{images:r,dy:s}=t,{alignCorners:i}=n;Ie([s,r],"resizeBilinearGrad");let o=v.computeStrides(r.shape),[l,u,d,c]=r.shape,[,p,h]=s.shape,m=new Float32Array(l*u*d*c),f=[i&&p>1?u-1:u,i&&h>1?d-1:d],g=[i&&p>1?p-1:p,i&&h>1?h-1:h],y=f[0]/g[0],x=f[1]/g[1],A=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<p;C++){let N=C*y,M=Math.floor(N),F=Math.min(Math.ceil(N),u-1),E=S+M*o[1],T=S+F*o[1],D=N-M,O=1-D;for(let W=0;W<h;W++){let $=W*x,U=Math.floor($),G=Math.min(Math.ceil($),d-1),q=$-U,H=1-q,V=E+U*o[2],Z=E+G*o[2],X=T+U*o[2],re=T+G*o[2],ee=O*H,ge=O*q,ie=D*H,be=D*q;for(let Ce=0;Ce<c;Ce++){let Ee=A[b++];m[V+Ce]+=Ee*ee,m[Z+Ce]+=Ee*ge,m[X+Ce]+=Ee*ie,m[re+Ce]+=Ee*be}}}}return a.makeTensorInfo([l,d,u,c],"float32",m)}var zU={kernelName:_u,backendName:"cpu",kernelFunc:OU};function LU(e){let{inputs:t,backend:a,attrs:n}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n;Ie(r,"resizeNearestNeighbor");let l=v.computeStrides(r.shape),[u,d]=o,[c,p,h,m]=r.shape,f=a.data.get(r.dataId).values,g=new Float32Array(c*u*d*m),y=[s&&u>1?p-1:p,s&&d>1?h-1:h],x=[s&&u>1?u-1:u,s&&d>1?d-1:d],A=y[0]/x[0],b=y[1]/x[1],w=0;for(let S=0;S<c;S++){let C=S*l[0];for(let N=0;N<u;N++){let M=i?A*(N+.5):A*N,F=Math.min(p-1,s?Math.round(M):Math.floor(M));i&&(F=Math.max(0,F));let E=C+F*l[1];for(let T=0;T<d;T++){let D=i?b*(T+.5):b*T,O=Math.min(h-1,s?Math.round(D):Math.floor(D));i&&(O=Math.max(0,O));let W=E+O*l[2];for(let $=0;$<m;$++){let U=f[W+$];g[w++]=U}}}}return a.makeTensorInfo([c,u,d,m],r.dtype,g)}var WU={kernelName:Wo,backendName:"cpu",kernelFunc:LU};function BU(e){let{inputs:t,backend:a,attrs:n}=e,{images:r,dy:s}=t,{alignCorners:i}=n;Ie([s,r],"resizeNearestNeighborGrad");let o=v.computeStrides(r.shape),l=v.computeStrides(s.shape),[u,d,c,p]=r.shape,[,h,m]=s.shape,f=new Float32Array(u*d*c*p),g=a.data.get(s.dataId).values,y=[i&&h>1?d-1:d,i&&m>1?c-1:c],x=[i&&h>1?h-1:h,i&&m>1?m-1:m],A=y[0]/x[0],b=y[1]/x[1],w=1/A,S=1/b,C=Math.ceil(w)*2+2,N=Math.ceil(S)*2+2;for(let M=0;M<u;M++){let F=M*o[0];for(let E=0;E<d;E++){let T=F+E*o[1],D=Math.floor(E*w),O=Math.floor(D-C/2);for(let W=0;W<c;W++){let $=T+W*o[2],U=Math.floor(W*S),G=Math.floor(U-N/2);for(let q=0;q<p;q++){let H=0;for(let V=0;V<C;V++){let Z=V+O;if(Z<0||Z>=h)continue;let X=F+Z*l[1],re=Z*A,ee=Math.min(d-1,i?Math.round(re):Math.floor(re));if(E===ee)for(let ge=0;ge<N;ge++){let ie=ge+G;if(ie<0||ie>=m)continue;let be=X+ie*l[2],Ce=ie*b,Ee=Math.min(c-1,i?Math.round(Ce):Math.floor(Ce));W===Ee&&(H+=g[be+q])}}f[$+q]=H}}}}return a.makeTensorInfo(r.shape,r.dtype,f)}var VU={kernelName:Pu,backendName:"cpu",kernelFunc:BU};function UU(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{dims:s}=n;Ie(r,"reverse");let i=r.shape.length,o=v.parseAxisParam(s,r.shape);if(i===0)return sr({inputs:{x:r},backend:a});let l=new Rt(r.shape,r.dtype),u=a.bufferSync(r);for(let d=0;d<l.size;d++){let c=l.indexToLoc(d),p=c.slice();o.forEach(h=>p[h]=r.shape[h]-1-p[h]),l.set(u.get(...p),...c)}return a.makeTensorInfo(l.shape,l.dtype,l.values)}var GU={kernelName:Uo,backendName:"cpu",kernelFunc:UU},HU={kernelName:ol,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,d,c,p]=n.shape,[h,m]=I.getImageCenter(i,d,c),f=255,g=Math.sin(r),y=Math.cos(r),x=o.data.get(n.dataId).values;for(let A=0;A<u;A++){let b=A*c*d*p;for(let w=0;w<d;w++){let S=w*(c*p);for(let C=0;C<c;C++){let N=C*p;for(let M=0;M<p;M++){let F=[u,w,C,M],E=F[2],T=F[1],D=(E-h)*y-(T-m)*g,O=(E-h)*g+(T-m)*y;D=Math.round(D+h),O=Math.round(O+m);let W=s;if(typeof s!="number"&&(M===3?W=f:W=s[M]),D>=0&&D<c&&O>=0&&O<d){let U=O*(c*p),G=D*p,q=b+U+G+M;W=x[q]}let $=b+S+N+M;l[$]=W}}}}return{dataId:o.write(l,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},jU=ct(Go,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}),qU={kernelName:Go,backendName:"cpu",kernelFunc:jU};function XU(e){let{inputs:t,backend:a,attrs:n}=e,{indices:r,updates:s}=t,{shape:i}=n,{sliceRank:o,numUpdates:l,sliceSize:u,strides:d,outputSize:c}=I.calculateShapes(s,r,i),p=!0,h=a.bufferSync(r),m=a.bufferSync(s),f=xi(h,m,i,c,u,l,o,d,0,p);return a.makeTensorInfo(i,f.dtype,f.values)}var KU={kernelName:Ho,backendName:"cpu",kernelFunc:XU};function YU(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 ZU(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 JU(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 d=0;d<r;++d)i[u+d]=s==="left"?YU(l,t[d+u]):ZU(l,t[d+u])}return i}function QU(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=JU(o,l,r.shape[0],r.shape[1],s.shape[1],i);return a.makeTensorInfo(s.shape,"int32",u)}var eG={kernelName:qo,backendName:"cpu",kernelFunc:QU};function tG(e){let{inputs:t,backend:a}=e,{condition:n,t:r,e:s}=t;Ie([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,d=Qt(r.dtype,s.dtype),c=v.makeZerosTypedArray(v.sizeFromShape(r.shape),d),p=0,h=i===0||i>1||r.shape.length===1?1:v.sizeFromShape(r.shape.slice(1));for(let m=0;m<o.length;m++)for(let f=0;f<h;f++)o[m]===1?c[p++]=l[m]:c[p++]=u[m];return a.makeTensorInfo(r.shape,d,c)}var aG={kernelName:Ou,backendName:"cpu",kernelFunc:tG},nG=I.SELU_SCALEALPHA,rG=I.SELU_SCALE,sG=ct(Xo,e=>e>=0?rG*e:nG*(Math.exp(e)-1)),iG={kernelName:Xo,backendName:"cpu",kernelFunc:sG},oG=ct(Zo,e=>e<0?-1:e>0?1:0),lG={kernelName:Zo,backendName:"cpu",kernelFunc:oG},uG=ct(Ko,e=>Math.sin(e)),dG={kernelName:Ko,backendName:"cpu",kernelFunc:uG},pG=ct(Yo,e=>Math.sinh(e)),cG={kernelName:Yo,backendName:"cpu",kernelFunc:pG},hG=11920928955078125e-23,D5=Math.log(hG)+2,mG=ct(Jo,e=>{let t=e>-D5,a=e<D5,n=Math.exp(e),r;return a?r=n:t?r=e:r=Math.log(1+n),r}),fG={kernelName:Jo,backendName:"cpu",kernelFunc:mG};function gG(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{blockShape:s,paddings:i}=n;Ie([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=Dv.kernelFunc({inputs:{x:r},backend:a,attrs:{paddings:l,constantValue:0}}),d=I.getReshaped(u.shape,s,o,!1),c=I.getPermuted(d.length,s.length,!1),p=I.getReshapedPermuted(u.shape,s,o,!1),h=bt({inputs:{x:u},backend:a,attrs:{shape:d}}),m=Va({inputs:{x:h},backend:a,attrs:{perm:c}}),f=bt({inputs:{x:m},backend:a,attrs:{shape:p}});return a.disposeIntermediateTensorInfo(u),a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(m),f}var yG={kernelName:Lu,backendName:"cpu",kernelFunc:gG};function xG(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,d=a.data.get(i.dataId).values[0],[c,p,h,m,f]=dv(o,n.shape,n.dtype,l,r.dtype,u,d);return[a.makeTensorInfo(p,n.dtype,c),a.makeTensorInfo([p[0]],r.dtype,h),a.makeTensorInfo([m.length],"bool",new Uint8Array(m.map(g=>Number(g)))),a.makeTensorInfo([f.length],n.dtype,new Int32Array(f))]}var AG={kernelName:Mp,backendName:"cpu",kernelFunc:xG};function bG(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,d,c]=pv(o,n.shape,n.dtype,i,l);return[a.makeTensorInfo(d,n.dtype,u),a.makeTensorInfo([c.length],s.dtype,new Int32Array(c))]}var vG={kernelName:Bu,backendName:"cpu",kernelFunc:bG};function wG(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,d]=C3(i,n.shape,n.dtype,o,l,!0);return a.makeTensorInfo(d,n.dtype,u)}var kG={kernelName:Vu,backendName:"cpu",kernelFunc:wG};function IG(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,d]=C3(i,n.shape,n.dtype,o,l);return a.makeTensorInfo(d,n.dtype,u)}var SG={kernelName:Uu,backendName:"cpu",kernelFunc:IG};function TG(e){let{inputs:t,backend:a,attrs:n}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=n,{sliceRank:l,numUpdates:u,sliceSize:d,strides:c,outputSize:p}=I.calculateShapes(s,r,o),h=!1,m=a.bufferSync(r),f;switch(s.dtype){case"bool":{let g=a.bufferSync(s),y=!!a.data.get(i.dataId).values[0];f=xi(m,g,o,p,d,u,l,c,y,h);break}case"float32":{let g=a.bufferSync(s),y=a.data.get(i.dataId).values[0];f=xi(m,g,o,p,d,u,l,c,y,h);break}case"int32":{let g=a.bufferSync(s),y=a.data.get(i.dataId).values[0];f=xi(m,g,o,p,d,u,l,c,y,h);break}case"string":{let g=a.bufferSync(s),y=v.decodeString(a.data.get(i.dataId).values[0]);f=xi(m,g,o,p,d,u,l,c,y,h);break}default:throw new Error(`Unsupported type ${s.dtype}`)}return a.makeTensorInfo(o,f.dtype,f.values)}var CG={kernelName:tl,backendName:"cpu",kernelFunc:TG};function NG(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=I.prepareSplitSize(r,s,o),u=new Array(r.shape.length).fill(0),d=r.shape.slice();return l.map(c=>{let p=[...d];p[o]=c;let h=Ci({inputs:{x:r},backend:a,attrs:{begin:u,size:p}});return u[o]+=c,h})}var RG={kernelName:Wu,backendName:"cpu",kernelFunc:NG},EG={kernelName:Fp,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:a}=e,n=t;Ie(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}}},MG=ct(Ds,(e,t)=>{let a=t;return isNaN(e)?NaN:e>0?1:a.alpha}),FG={kernelName:Ds,backendName:"cpu",kernelFunc:MG};function $G(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:d,newAxisMask:c,shrinkAxisMask:p}=n;Ie(r,"stridedSlice");let{finalShapeSparse:h,finalShape:m,isIdentity:f,sliceDim0:g,isSimpleSlice:y,begin:x,end:A,strides:b}=wt.sliceInfo(r.shape,s,i,o,l,u,d,c,p),w;if(f)w=bt({inputs:{x:r},backend:a,attrs:{shape:m}});else if(g||y){v.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let S=wt.computeOutShape(x,A,b),C=Ci({inputs:{x:r},backend:a,attrs:{begin:x,size:S}});w=bt({inputs:{x:C},backend:a,attrs:{shape:m}}),a.disposeIntermediateTensorInfo(C)}else{let S=a.bufferSync(r),C=mv(h,S,b,x);w=a.makeTensorInfo(m,C.dtype,C.values)}return w}var DG={kernelName:al,backendName:"cpu",kernelFunc:$G};function PG(e){let{inputs:t,backend:a,attrs:n}=e,{separator:r,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=n,{data:d,dataSplits:c}=t,p=a.data.get(d.dataId).values,h=a.data.get(c.dataId).values,[m,f]=N3(p,h,r,s,i,o,l,u);return[a.makeTensorInfo([m.length],"string",m),a.makeTensorInfo(c.shape,"int32",f)]}var _G={kernelName:Hu,backendName:"cpu",kernelFunc:PG};function OG(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,d,c]=R3(o,l,r),p=d.length;return[a.makeTensorInfo([p,2],"int32",u),a.makeTensorInfo([p],"string",d),a.makeTensorInfo([2],"int32",new Int32Array(c))]}var zG={kernelName:$p,backendName:"cpu",kernelFunc:OG};function LG(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=E3(i,r);return a.makeTensorInfo(s.shape,"int32",o)}var WG={kernelName:Dp,backendName:"cpu",kernelFunc:LG},BG=ct(nl,e=>Math.tan(e)),VG={kernelName:nl,backendName:"cpu",kernelFunc:BG},UG=ct(rl,e=>Math.tanh(e)),GG={kernelName:rl,backendName:"cpu",kernelFunc:UG};function HG(e){let{inputs:t,backend:a}=e,{tensor:n,indices:r,updates:s}=t,{sliceRank:i,numUpdates:o,sliceSize:l,strides:u,outputSize:d}=I.calculateShapes(s,r,n.shape),c=!1,p=a.bufferSync(r),h=a.bufferSync(s),m=a.bufferSync(n),f=xi(p,h,n.shape,d,l,o,i,u,m,c);return a.makeTensorInfo(n.shape,f.dtype,f.values)}var jG={kernelName:jo,backendName:"cpu",kernelFunc:HG};function qG(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{reps:s}=n;Ie(r,"tile");let i=gv(a.bufferSync(r),s);return a.makeTensorInfo(i.shape,i.dtype,i.values)}var XG={kernelName:$s,backendName:"cpu",kernelFunc:qG};function KG(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{k:s,sorted:i}=n;Ie(r,"topk");let o=a.data.get(r.dataId).values,[l,u]=xv(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 YG={kernelName:sl,backendName:"cpu",kernelFunc:KG};function ZG(e){let{inputs:t,attrs:a,backend:n}=e,{image:r,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=a,[d,c,p,h]=r.shape,[m,f]=u!=null?u:[c,p],g=[d,m,f,h],y=v.computeStrides(r.shape),x=y[0],A=y[1],b=y[2],w=v.computeStrides(g),S=w[0],C=w[1],N=w[2],M=v.getTypedArrayFromDType(r.dtype,v.sizeFromShape(g));M.fill(l);let F=n.data.get(r.dataId).values,E=n.data.get(s.dataId).values;for(let T=0;T<d;++T){let D=s.shape[0]===1?E:E.subarray(T*8,T*8+8);for(let O=0;O<m;++O)for(let W=0;W<f;++W)for(let $=0;$<h;++$){let U,G=D[6]*W+D[7]*O+1;if(G===0)continue;let q=(D[0]*W+D[1]*O+D[2])/G,H=(D[3]*W+D[4]*O+D[5])/G,V=P5(q,p,o),Z=P5(H,c,o);switch(i){case"nearest":U=nH(F,c,p,x,A,b,T,Z,V,$,l);break;case"bilinear":U=rH(F,c,p,x,A,b,T,Z,V,$,l);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${i}`)}let X=T*S+O*C+W*N+$;M[X]=U}return n.makeTensorInfo(g,r.dtype,M)}return{dataId:n.write(M,g,r.dtype),shape:r.shape,dtype:r.dtype}}var JG={kernelName:il,backendName:"cpu",kernelFunc:ZG};function P5(e,t,a){switch(a){case"reflect":return QG(e,t);case"wrap":return eH(e,t);case"nearest":return aH(e,t);case"constant":default:return tH(e,t)}}function QG(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 eH(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 tH(e,t){return e}function aH(e,t){return v.clamp(0,e,t-1)}function $d(e,t,a,n,r,s,i,o,l,u,d){let c=i*n+o*r+l*s+u;return 0<=o&&o<t&&0<=l&&l<a?e[c]:d}function nH(e,t,a,n,r,s,i,o,l,u,d){let c=Math.round(o),p=Math.round(l);return $d(e,t,a,n,r,s,i,c,p,u,d)}function rH(e,t,a,n,r,s,i,o,l,u,d){let c=Math.floor(o),p=Math.floor(l),h=c+1,m=p+1,f=(m-l)*$d(e,t,a,n,r,s,i,c,p,u,d)+(l-p)*$d(e,t,a,n,r,s,i,c,m,u,d),g=(m-l)*$d(e,t,a,n,r,s,i,h,p,u,d)+(l-p)*$d(e,t,a,n,r,s,i,h,m,u,d);return(h-o)*f+(o-c)*g}function sH(e){let{inputs:t,attrs:a,backend:n}=e,{axis:r}=a,{x:s}=t;Ie(s,"unique");let i=n.data.get(s.dataId).values,{outputValues:o,outputShape:l,indices:u}=F3(i,r,s.shape,s.dtype);return[n.makeTensorInfo(l,s.dtype,o),n.makeTensorInfo([u.length],"int32",u)]}var iH={kernelName:Pp,backendName:"cpu",kernelFunc:sH};function oH(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 d=new Array(i).fill(0),c=r.shape.slice();c[s]=1;let p=new Array(o);for(let h=0;h<p.length;h++){d[s]=h;let m=Ci({inputs:{x:r},backend:a,attrs:{begin:d,size:c}});p[h]=bt({inputs:{x:m},backend:a,attrs:{shape:l}}),a.disposeIntermediateTensorInfo(m)}return p}var lH={kernelName:ju,backendName:"cpu",kernelFunc:oH};function uH(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,segmentIds:s}=t,{numSegments:i}=n;Ie(r,"unsortedSegmentSum");let o=r.shape.length,l=s.shape.length,u=[],d=[],c=o-l,p=s;for(let m=0;m<c;++m){let f=Ch({inputs:{input:p},backend:a,attrs:{dim:m+1}});p=f,d.push(f)}for(let m=0;m<i;++m){let f=v.createScalarValue(m,"int32"),g=a.makeTensorInfo([],"int32",f),y=L6({inputs:{a:g,b:p},backend:a}),x=ds({inputs:{x:y},backend:a,attrs:{dtype:"float32"}}),A=l0({inputs:{a:x,b:r},backend:a}),b=tc({inputs:{x:A},backend:a,attrs:{axis:0,keepDims:!1}});u.push(b),d.push(g),d.push(y),d.push(x),d.push(A),d.push(b)}let h=$v({inputs:u,backend:a,attrs:{axis:0}});return d.forEach(m=>a.disposeIntermediateTensorInfo(m)),h}var dH={kernelName:_p,backendName:"cpu",kernelFunc:uH},pH=[rW,Oz,iW,lW,Uz,dW,cW,mW,gW,xW,bW,wW,IW,CW,RW,FW,DW,_W,zW,aW,WW,VW,GW,Hz,jW,Bz,qz,XW,zz,YW,JW,QW,tB,nB,sB,oB,uB,pB,hB,fB,yB,AB,vB,kB,IB,TB,NB,EB,MB,FB,$B,PB,zB,KL,WB,Xz,XB,Kz,KB,Zz,tV,aV,rV,Qz,tL,iV,lV,dV,cV,nL,sL,Lz,mV,ZW,gV,xV,bV,YL,oL,uL,wV,pL,IV,CV,RV,FV,DV,_V,OV,hL,LV,BV,UV,HV,qV,KV,ZV,fL,QV,aU,iU,yL,AL,uU,cU,fU,vL,yU,AU,bU,Dv,IU,JL,IL,TU,NU,EU,FU,Wz,L1,DU,QL,eW,tW,_U,zU,WU,VU,GU,HU,qU,$L,KU,eG,aG,iG,PL,lG,dG,cG,_L,rU,fG,yG,AG,vG,kG,SG,CG,RG,LL,EG,BL,UL,FG,DG,_G,zG,WG,qL,_B,VG,GG,jG,XG,YG,JG,wL,iH,lH,dH,xU];for(let e of pH)bn(e);var Pv={};Ke(Pv,{assertNotComplex:()=>Ju,bindCanvasToFramebuffer:()=>wH,bindColorTextureToFramebuffer:()=>dh,bindTextureToProgramUniformSampler:()=>Yv,bindTextureUnit:()=>qv,bindVertexBufferToProgramAttribute:()=>B1,callAndCheck:()=>ce,canBeRepresented:()=>_v,createFragmentShader:()=>Lv,createFramebuffer:()=>jv,createProgram:()=>Wv,createStaticIndexBuffer:()=>Uv,createStaticVertexBuffer:()=>Vv,createTexture:()=>Gv,createVertexShader:()=>zv,getBatchDim:()=>Ni,getExtensionOrThrow:()=>Dd,getFramebufferErrorMessage:()=>Zv,getMaxTexturesInShader:()=>tw,getNumChannels:()=>bH,getProgramUniformLocation:()=>Kv,getProgramUniformLocationOrThrow:()=>Xv,getRowsCols:()=>Ri,getShapeAs3D:()=>_d,getTextureShapeFromLogicalShape:()=>Qv,getWebGLDisjointQueryTimerVersion:()=>aw,getWebGLErrorMessage:()=>Ov,getWebGLMaxTextureSize:()=>ew,hasExtension:()=>yn,isCapableOfRenderingToFloatTexture:()=>nw,isDownloadFloatTextureEnabled:()=>rw,isReshapeFree:()=>ip,isWebGLFenceEnabled:()=>sw,isWebGLVersionEnabled:()=>U1,linkProgram:()=>Bv,logShaderSourceAndInfoLog:()=>O3,resetMaxTextureSize:()=>kH,resetMaxTexturesInShader:()=>IH,unbindColorTextureFromFramebuffer:()=>V1,unbindTextureUnit:()=>vH,validateFramebuffer:()=>Pd,validateProgram:()=>uh,validateTextureSize:()=>Hv});var fi={},ah={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function u0(e,t){fi[e]=t}function Un(e,t){if(!(e in fi)||t!=null){let n=hH(e,t);if(n!==null)fi[e]=n;else return console.log("Could not get context for WebGL version",e),null}let a=fi[e];return a==null||a.isContextLost()?(delete fi[e],Un(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),fi[e])}function cH(e){if(!B().getBool("IS_SAFARI")&&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 hH(e,t){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let a=t==null?cH(e):t;return a.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete fi[e]},!1),B().getBool("SOFTWARE_WEBGL_ENABLED")&&(ah.failIfMajorPerformanceCaveat=!1),e===1?a.getContext("webgl",ah)||a.getContext("experimental-webgl",ah):a.getContext("webgl2",ah)}var sp;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(sp||(sp={}));var gn;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(gn||(gn={}));var pa;(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"})(pa||(pa={}));function ac(e,t){return[t,e]}function mH(e,t){return e*t}function nh(e){let t=v.sizeFromShape(e),a=Math.ceil(t/4);return v.sizeToSquarishShape(a)}function Zu(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function fH(e,t){let[a,n]=Zu(e,t);return a*n*4}function _3(e,t){let a=e,n,r,s,i,o,l,u,d,c,p;return B().getNumber("WEBGL_VERSION")===2?(n=a.R32F,r=a.R16F,s=a.RGBA16F,i=a.RGBA32F,o=a.RED,u=4,d=1,c=a.HALF_FLOAT,p=a.FLOAT,l=a.RGBA8):(n=e.RGBA,r=e.RGBA,s=e.RGBA,i=a.RGBA,o=e.RGBA,u=4,d=4,c=t!=null?t.HALF_FLOAT_OES:null,p=e.FLOAT,l=e.RGBA),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:d,textureTypeHalfFloat:c,textureTypeFloat:p}}function ce(e,t){let a=t();return B().getBool("DEBUG")&&gH(e),a}function gH(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+Ov(e,t))}var yH=596e-10,xH=65504;function _v(e){return!!(B().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||yH<Math.abs(e)&&Math.abs(e)<xH)}function Ov(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 Dd(e,t){return _r(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function zv(e,t){let a=_r(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(ce(e,()=>e.shaderSource(a,t)),ce(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 Lv(e,t){let a=_r(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(ce(e,()=>e.shaderSource(a,t)),ce(e,()=>e.compileShader(a)),B().get("ENGINE_COMPILE_ONLY"))return a;if(e.getShaderParameter(a,e.COMPILE_STATUS)===!1)throw O3(t,e.getShaderInfoLog(a)),new Error("Failed to compile fragment shader.");return a}var AH=/ERROR: [0-9]+:([0-9]+):/g;function O3(e,t){let a=AH.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,p)=>v.rightPad((p+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),d=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(d.join(`
|
|
`))}function Wv(e){return _r(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function Bv(e,t){if(ce(e,()=>e.linkProgram(t)),!B().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 uh(e,t){if(ce(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function Vv(e,t){let a=_r(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return ce(e,()=>e.bindBuffer(e.ARRAY_BUFFER,a)),ce(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),a}function Uv(e,t){let a=_r(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return ce(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,a)),ce(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),a}function bH(){return B().getNumber("WEBGL_VERSION")===2?1:4}function Gv(e){return _r(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function Hv(e,t){let a=B().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 jv(e){return _r(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function B1(e,t,a,n,r,s,i){let o=e.getAttribLocation(t,a);return o===-1?!1:(ce(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),ce(e,()=>e.vertexAttribPointer(o,r,e.FLOAT,!1,s,i)),ce(e,()=>e.enableVertexAttribArray(o)),!0)}function qv(e,t,a){Jv(e,a),ce(e,()=>e.activeTexture(e.TEXTURE0+a)),ce(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function vH(e,t){Jv(e,t),ce(e,()=>e.activeTexture(e.TEXTURE0+t)),ce(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function Xv(e,t,a){return _r(e,()=>e.getUniformLocation(t,a),'uniform "'+a+'" not present in program.')}function Kv(e,t,a){return e.getUniformLocation(t,a)}function Yv(e,t,a,n){ce(e,()=>qv(e,t,n)),ce(e,()=>e.uniform1i(a,n))}function wH(e){ce(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),ce(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),ce(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function dh(e,t,a){ce(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,a)),ce(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function V1(e,t){ce(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),ce(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Pd(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Zv(e,t))}function Zv(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 _r(e,t,a){let n=ce(e,()=>t());if(n==null)throw new Error(a);return n}function Jv(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 Ni(e,t=2){return v.sizeFromShape(e.slice(0,e.length-t))}function Ri(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 _d(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[Ni(e),...Ri(e)]),t}function Qv(e,t=!1){let a=B().getNumber("WEBGL_MAX_TEXTURE_SIZE"),n=B().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");n===1/0&&B().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=Ni(e),l=2,u=2;e.length&&([l,u]=Ri(e)),r=o*(l/2)*(u/2),s=v.sizeToSquarishShape(r).map(d=>d*2)}else s=v.sizeToSquarishShape(r);return s}function rh(e){return e%2===0}function ip(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[e.length-1],n=t[t.length-1];if(a===n||rh(a)&&rh(n)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&rh(e[0])&&rh(t[0])}var ph,ch;function ew(e){if(ph==null){let t=Un(e);ph=t.getParameter(t.MAX_TEXTURE_SIZE)}return ph}function kH(){ph=null}function IH(){ch=null}function tw(e){if(ch==null){let t=Un(e);ch=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,ch)}function aw(e){if(e===0)return 0;let t,a=Un(e);return yn(a,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:yn(a,"EXT_disjoint_timer_query")?t=1:t=0,t}function yn(e,t){return e.getExtension(t)!=null}function U1(e){try{if(Un(e)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function nw(e){if(e===0)return!1;let t=Un(e);if(e===1){if(!yn(t,"OES_texture_float"))return!1}else if(!yn(t,"EXT_color_buffer_float"))return!1;return G1(t)}function rw(e){if(e===0)return!1;let t=Un(e);if(e===1){if(!yn(t,"OES_texture_float")||!yn(t,"WEBGL_color_buffer_float"))return!1}else{if(yn(t,"EXT_color_buffer_float"))return G1(t);let a="EXT_color_buffer_half_float";if(yn(t,a)){let n=t.getExtension(a);return SH(t,n)}return!1}return G1(t)}function G1(e){let t=_3(e),a=e.createTexture();e.bindTexture(e.TEXTURE_2D,a),e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);let n=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,n),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,a,0);let r=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(a),e.deleteFramebuffer(n),r}function SH(e,t){let a=_3(e,t),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texImage2D(e.TEXTURE_2D,0,a.internalFormatHalfFloat,1,1,0,a.textureFormatFloat,a.textureTypeHalfFloat,null);let r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);let s=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(r),s}function sw(e){return e!==2?!1:Un(e).fenceSync!=null}function Ju(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 Se=B();Se.registerFlag("HAS_WEBGL",()=>Se.getNumber("WEBGL_VERSION")>0);Se.registerFlag("WEBGL_VERSION",()=>U1(2)?2:U1(1)?1:0);Se.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);Se.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Se.get("WEBGL_VERSION")===2);Se.registerFlag("WEBGL_CPU_FORWARD",()=>!0);Se.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);Se.registerFlag("WEBGL_PACK",()=>Se.getBool("HAS_WEBGL"));Se.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Se.getBool("WEBGL_PACK"));Se.registerFlag("WEBGL_PACK_CLIP",()=>Se.getBool("WEBGL_PACK"));Se.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>Se.getBool("WEBGL_PACK"));Se.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Se.getBool("WEBGL_PACK"));Se.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Se.getBool("WEBGL_PACK"));Se.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Se.getBool("WEBGL_PACK"));Se.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Se.getBool("WEBGL_PACK"));Se.registerFlag("WEBGL_PACK_REDUCE",()=>Se.getBool("WEBGL_PACK"));Se.registerFlag("WEBGL_LAZILY_UNPACK",()=>Se.getBool("WEBGL_PACK"));Se.registerFlag("WEBGL_CONV_IM2COL",()=>Se.getBool("WEBGL_PACK"));Se.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE",()=>Se.getBool("WEBGL_PACK"));Se.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>ew(Se.getNumber("WEBGL_VERSION")));Se.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>tw(Se.getNumber("WEBGL_VERSION")));Se.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let e=Se.getNumber("WEBGL_VERSION");return e===0?0:aw(e)});Se.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Se.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!Wp.isMobile());Se.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>nw(Se.getNumber("WEBGL_VERSION")));Se.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>Se.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Se.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));Se.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>rw(Se.getNumber("WEBGL_VERSION")));Se.registerFlag("WEBGL_FENCE_API_ENABLED",()=>sw(Se.getNumber("WEBGL_VERSION")));Se.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>Se.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);Se.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,e=>{if(typeof e!="number")throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but got ${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}.`)});Se.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>Wp.isMobile()?1:-1,e=>{if(typeof e!="number")throw new Error(`WEBGL_FLUSH_THRESHOLD must be a number but got ${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}.`)});Se.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);Se.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1);Se.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5);Se.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128);Se.registerFlag("WEBGL_EXP_CONV",()=>!1);Se.registerFlag("SOFTWARE_WEBGL_ENABLED",()=>Se.getBool("IS_TEST"));Se.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",()=>1/0);Se.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",()=>!1);Se.registerFlag("WEBGL2_ISNAN_CUSTOM",()=>!1);Se.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);function Ra(){let e,t,a,n,r,s,i,o,l,u;return B().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",a="out",n="in",r="texture",s="outputColor",i="out vec4 outputColor;",o=B().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 dl(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 d0(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 TH(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 CH(e,t,a="index"){let n=e.map((s,i)=>i),r=TH(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 z3(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 L3(){return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
|
|
}
|
|
`}var iw=`
|
|
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:ow}=I;function NH(e,t,a){let n=[];if(e.forEach(p=>{let h=v.sizeFromShape(p.shapeInfo.logicalShape);if(p.shapeInfo.isUniform?n.push(`uniform float ${p.name}${h>1?`[${h}]`:""};`):(n.push(`uniform sampler2D ${p.name};`),n.push(`uniform int offset${p.name};`)),a.enableShapeUniforms){let{uniformShape:m}=W3(a.packedInputs,p.shapeInfo.logicalShape,p.shapeInfo.texShape);switch(m.length){case 1:n.push(`uniform int ${p.name}Shape;`);break;case 2:n.push(`uniform ivec2 ${p.name}Shape;`);break;case 3:n.push(`uniform ivec3 ${p.name}Shape;`);break;case 4:n.push(`uniform ivec4 ${p.name}Shape;`);break;default:break}n.push(`uniform ivec2 ${p.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(p=>{n.push(`uniform ${p.type} ${p.name}${p.arrayIndex?`[${p.arrayIndex}]`:""};`)});let r=n.join(`
|
|
`),s=e.map(p=>RH(p,t,a.packedInputs,a.enableShapeUniforms)).join(`
|
|
`),i=t.texShape,o=Ra(),l=FH(o),u,d,c=PH(o);return t.isPacked?(u=EH(t.logicalShape,i,a.enableShapeUniforms),d=DH(o)):(u=MH(t.logicalShape,i,a.enableShapeUniforms),d=$H(o)),a.packedInputs&&(c+=LH),[c,l,d,r,u,s,a.userCode].join(`
|
|
`)}function Qu(e,t=!1){let a=e.shapeInfo.logicalShape;switch(a.length){case 0:return ZH(e,t);case 1:return QH(e,t);case 2:return tj(e,t);case 3:return nj(e,t);case 4:return sj(e,t);case 5:return ij(e);case 6:return oj(e);default:throw new Error(`${a.length}-D input sampling is not yet supported`)}}function lw(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return YH(e);case 1:return JH(e,t);case 2:return ej(e,t);case 3:return aj(e,t);default:return rj(e,t)}}function RH(e,t,a=!1,n){let r="";a?r+=lw(e,n):r+=Qu(e,n);let s=e.shapeInfo.logicalShape,i=t.logicalShape;return s.length<=i.length&&(a?r+=lj(e,t):r+=uj(e,t)),r}function EH(e,t,a){switch(e.length){case 0:return uw();case 1:return WH(e,t,a);case 2:return XH(e,t,a);case 3:return VH(e,t,a);default:return GH(e,t,a)}}function MH(e,t,a){switch(e.length){case 0:return uw();case 1:return BH(e,t,a);case 2:return KH(e,t,a);case 3:return UH(e,t,a);case 4:return HH(e,t,a);case 5:return jH(e,t);case 6:return qH(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function FH(e){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return ${e.texture2D}(textureSampler, uv).r;
|
|
}
|
|
`}function $H(e){return`
|
|
void setOutput(float val) {
|
|
${e.output} = vec4(val, 0, 0, 0);
|
|
}
|
|
`}function DH(e){return`
|
|
void setOutput(vec4 val) {
|
|
${e.output} = val;
|
|
}
|
|
`}function PH(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);
|
|
}
|
|
|
|
${_H}
|
|
${OH}
|
|
${zH}
|
|
`}var _H=`
|
|
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);
|
|
}
|
|
`,OH=`
|
|
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);
|
|
}
|
|
`,zH=`
|
|
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);
|
|
}
|
|
`,LH=`
|
|
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 uw(){return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`}function WH(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 BH(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 VH(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 UH(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;
|
|
${d0(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`;let n=dl(["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 GH(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 HH(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;
|
|
${d0(["r","c","d","d2"],e)}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`;let n=dl(["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 jH(e,t){let a=dl(["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 qH(e,t){let a=dl(["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 XH(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 KH(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 pl(e){return`offset${e}`}function YH(e){let t=e.name,a="get"+t.charAt(0).toUpperCase()+t.slice(1),n=Ra();return`
|
|
vec4 ${a}() {
|
|
return ${n.texture2D}(${t}, halfCR);
|
|
}
|
|
`}function ZH(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=pl(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 JH(e,t){let a=e.name,n="get"+a.charAt(0).toUpperCase()+a.slice(1),r=e.shapeInfo.texShape,s=Ra();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 QH(e,t){let a=e.name,n="get"+a.charAt(0).toUpperCase()+a.slice(1);if(e.shapeInfo.isUniform)return`
|
|
float ${n}(int index) {
|
|
${ed(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=pl(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 ej(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=Ra();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)],d=Math.ceil(a[1]/2);return`
|
|
vec4 ${r}(int row, int col) {
|
|
vec2 uv = packedUVfrom2D(${d}, ${u[0]}, ${u[1]}, row, col);
|
|
return ${l.texture2D}(${n}, uv);
|
|
}
|
|
`}function tj(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 p=s[0],h=s[1];return`
|
|
float ${r}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${h}.0, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}let{newShape:i,keptDims:o}=v.squeezeShape(a),l=i;if(l.length<a.length){let p=td(e,l),h=["row","col"];return`
|
|
${Qu(p,t)}
|
|
float ${r}(int row, int col) {
|
|
return ${r}(${ad(h,o)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${r}(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(${a[1]}, 1)));
|
|
${ed(e)}
|
|
}
|
|
`;let u=s[0],d=s[1],c=pl(n);return d===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) / ${d}.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}, ${d}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function aj(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 p=a.slice(1),h=[1,2],m=td(e,p),f=["b","row","col"];return`
|
|
${lw(m,t)}
|
|
vec4 ${r}(int b, int row, int col) {
|
|
return ${r}(${ad(f,h)});
|
|
}
|
|
`}let o=Ra();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],d=Math.ceil(a[2]/2),c=d*Math.ceil(a[1]/2);return`
|
|
vec4 ${r}(int b, int row, int col) {
|
|
vec2 uv = packedUVfrom3D(
|
|
${l}, ${u}, ${c}, ${d}, b, row, col);
|
|
return ${o.texture2D}(${n}, uv);
|
|
}
|
|
`}function nj(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 f=td(e,u),g=["row","col","depth"];return`
|
|
${Qu(f,t)}
|
|
float ${r}(int row, int col, int depth) {
|
|
return ${r}(${ad(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)));
|
|
${ed(e)}
|
|
}
|
|
`;let d=e.shapeInfo.texShape,c=d[0],p=d[1],h=e.shapeInfo.flatOffset;if(p===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(${p}.0, ${c}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(p===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(${p}.0, ${c}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let m=pl(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 + ${m};
|
|
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 + ${m};
|
|
vec2 uv = uvFromFlat(${c}, ${p}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function rj(e,t){let a=e.name,n="get"+a.charAt(0).toUpperCase()+a.slice(1),r=Ra();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],d=l[1],c=Math.ceil(s[i-1]/2),p=c*Math.ceil(s[i-2]/2),h="int b, int row, int col",m=`b * ${p} + (row / 2) * ${c} + (col / 2)`;for(let f=2;f<i-1;f++)h=`int b${f}, `+h,p*=s[i-f-1],m=`b${f} * ${p} + `+m;return`
|
|
vec4 ${n}(${h}) {
|
|
int index = ${m};
|
|
int texR = index / ${d};
|
|
int texC = index - texR * ${d};
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${d}, ${u});
|
|
return ${r.texture2D}(${a}, uv);
|
|
}
|
|
`}function sj(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 x=td(e,l),A=["row","col","depth","depth2"];return`
|
|
${Qu(x,t)}
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
return ${r}(${ad(A,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)));
|
|
${ed(e)}
|
|
}
|
|
`;let d=e.shapeInfo.flatOffset,c=e.shapeInfo.texShape,p=c[0],h=c[1],m=`int stride2 = ${n}Shape[3];`,f=`int stride1 = ${n}Shape[2] * stride2;`,g=`int stride0 = ${n}Shape[1] * stride1;`;if(h===o&&d==null)return t?`
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
${m}
|
|
${f}
|
|
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, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(h===s&&d==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, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let y=pl(n);return t?`
|
|
float ${r}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
${m}
|
|
${f}
|
|
${g}
|
|
int index = row * stride0 + col * stride1 +
|
|
depth * stride2 + depth2;
|
|
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${y});
|
|
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(${p}, ${h}, index + ${y});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function ij(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 f=td(e,l),g=["row","col","depth","depth2","depth3"];return`
|
|
${Qu(f)}
|
|
float ${n}(int row, int col, int depth, int depth2, int depth3) {
|
|
return ${n}(${ad(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;
|
|
${ed(e)}
|
|
}
|
|
`;let d=e.shapeInfo.flatOffset,c=e.shapeInfo.texShape,p=c[0],h=c[1];if(h===o&&d==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, ${p}.0);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`;if(h===r&&d==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, ${p}.0);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`;let m=pl(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 + ${m};
|
|
vec2 uv = uvFromFlat(${p}, ${h}, index);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`}function oj(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=td(e,r),y=["row","col","depth","depth2","depth3","depth4"];return`
|
|
${Qu(g)}
|
|
float ${n}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return ${n}(${ad(y,s)});
|
|
}
|
|
`}let i=t[5],o=t[4]*i,l=t[3]*o,u=t[2]*l,d=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(${d}, ${u}, ${l}, ${o})) +
|
|
dot(
|
|
vec2(depth3, depth4),
|
|
vec2(${i}, 1)));
|
|
${ed(e)}
|
|
}
|
|
`;let c=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],m=p[1];if(m===d&&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(${m}.0, ${h}.0);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`;if(m===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(${m}.0, ${h}.0);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`;let f=pl(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 * ${d} + col * ${u} + depth * ${l} +
|
|
depth2 * ${o} + depth3 * ${i} + depth4 + ${f};
|
|
vec2 uv = uvFromFlat(${h}, ${m}, index);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`}function ed(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 lj(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=ow(e.shapeInfo.logicalShape,t.logicalShape),l=ft(i),u=i-s,d,c=["x","y","z","w","u","v"];s===0?d="":i<2&&o.length>=1?d="coords = 0;":d=o.map(g=>`coords.${c[g+u]} = 0;`).join(`
|
|
`);let p="";i<2&&s>0?p="coords":p=e.shapeInfo.logicalShape.map((g,y)=>`coords.${c[y+u]}`).join(", ");let h="return outputValue;",m=v.sizeFromShape(e.shapeInfo.logicalShape)===1,f=v.sizeFromShape(t.logicalShape)===1;if(s===1&&!m&&!f)h=`
|
|
return vec4(outputValue.xy, outputValue.xy);
|
|
`;else if(m&&!f)i===1?h=`
|
|
return vec4(outputValue.x, outputValue.x, 0., 0.);
|
|
`:h=`
|
|
return vec4(outputValue.x);
|
|
`;else if(o.length){let g=s-2,y=s-1;o.indexOf(g)>-1&&o.indexOf(y)>-1?h="return vec4(outputValue.x);":o.indexOf(g)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(y)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return`
|
|
vec4 ${r}() {
|
|
${l} coords = getOutputCoords();
|
|
${d}
|
|
vec4 outputValue = get${n}(${p});
|
|
${h}
|
|
}
|
|
`}function uj(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=ft(l),d=ow(e.shapeInfo.logicalShape,t.logicalShape),c=l-o,p,h=["x","y","z","w","u","v"];o===0?p="":l<2&&d.length>=1?p="coords = 0;":p=d.map(f=>`coords.${h[f+c]} = 0;`).join(`
|
|
`);let m="";return l<2&&o>0?m="coords":m=e.shapeInfo.logicalShape.map((f,g)=>`coords.${h[g+c]}`).join(", "),`
|
|
float ${r}() {
|
|
${u} coords = getOutputCoords();
|
|
${p}
|
|
return get${n}(${m});
|
|
}
|
|
`}function ft(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 W3(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 td(e,t){let a=JSON.parse(JSON.stringify(e));return a.shapeInfo.logicalShape=t,a}function ad(e,t){return t.map(a=>e[a]).join(", ")}function dj(e,t,a,n){let r=a.map((d,c)=>{let p={logicalShape:d.shape,texShape:d.isUniform?null:d.texData.texShape,isUniform:d.isUniform,isPacked:d.isUniform?!1:d.texData.isPacked,flatOffset:null};return d.texData!=null&&d.texData.slice!=null&&d.texData.slice.flatOffset>0&&(p.flatOffset=d.texData.slice.flatOffset),{name:t.variableNames[c],shapeInfo:p}}),s=r.map(d=>d.shapeInfo),i={logicalShape:n.shape,texShape:n.texData.texShape,isUniform:!1,isPacked:n.texData.isPacked,flatOffset:null},o=NH(r,i,t),l=Lv(e.gl,o),u=e.createProgram(l);return B().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:s,outShapeInfo:i,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(e.buildVao(u),Object.assign({program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:s,outShapeInfo:i},dw(e,t,u)))}function dw(e,t,a){let n=[],r=[],s,i,o,l=null,u=null;u=e.getUniformLocation(a,"NAN",!1),B().getNumber("WEBGL_VERSION")===1&&(l=e.getUniformLocation(a,"INFINITY",!1));let d=!1;for(let c of t.variableNames){let p={name:c,uniform:e.getUniformLocation(a,c,d),offset:e.getUniformLocation(a,`offset${c}`,d)};t.enableShapeUniforms&&(p.shape=e.getUniformLocation(a,`${c}Shape`,d),p.texShape=e.getUniformLocation(a,`${c}TexShape`,d)),n.push(p)}if(t.enableShapeUniforms&&(s=e.getUniformLocation(a,"outShape",d),o=e.getUniformLocation(a,"outShapeStrides",d),i=e.getUniformLocation(a,"outTexShape",d)),t.customUniforms)for(let c of t.customUniforms)r.push(e.getUniformLocation(a,c.name,d));return{variablesLocations:n,customUniformLocations:r,infLoc:l,nanLoc:u,outShapeLocation:s,outShapeStridesLocation:o,outTexShapeLocation:i}}function _5(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 pj(e,t,a,n,r){t.program.enableShapeUniforms||(_5(t.inShapeInfos,a),_5([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),e.bindVertexArray(t.webGLProgram.vao),B().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN);for(let l=0;l<a.length;++l){let u=a[l],{uniform:d,offset:c,shape:p,texShape:h}=t.variablesLocations[l];if(p){let{uniformShape:m}=W3(t.program.packedInputs,u.shape,u.texData.texShape);switch(m.length){case 1:e.gl.uniform1iv(p,new Int32Array(m));break;case 2:e.gl.uniform2iv(p,new Int32Array(m));break;case 3:e.gl.uniform3iv(p,new Int32Array(m));break;case 4:e.gl.uniform4iv(p,new Int32Array(m));break;default:break}}if(h&&e.gl.uniform2i(h,u.texData.texShape[0],u.texData.texShape[1]),d!=null){if(u.isUniform){if(v.sizeFromShape(u.shape)<2)e.gl.uniform1f(d,u.uniformValues[0]);else{let m=u.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),e.gl.uniform1fv(d,m)}continue}u.texData.slice!=null&&c!=null&&e.gl.uniform1i(c,u.texData.slice.flatOffset),e.setInputMatrixTexture(u.texData.texture.texture,d,l)}}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}}if(t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,n.texData.texShape[0],n.texData.texShape[1]),t.program.customUniforms&&r)for(let l=0;l<t.program.customUniforms.length;++l){let u=t.program.customUniforms[l],d=t.customUniformLocations[l],c=r[l];if(u.type==="float")e.gl.uniform1fv(d,c);else if(u.type==="vec2")e.gl.uniform2fv(d,c);else if(u.type==="vec3")e.gl.uniform3fv(d,c);else if(u.type==="vec4")e.gl.uniform4fv(d,c);else if(u.type==="int")e.gl.uniform1iv(d,c);else if(u.type==="ivec2")e.gl.uniform2iv(d,c);else if(u.type==="ivec3")e.gl.uniform3iv(d,c);else if(u.type==="ivec4")e.gl.uniform4iv(d,c);else throw Error(`uniform type ${u.type} is not supported yet.`)}e.executeProgram()}function cj(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:d,keptDims:c}=W3(e.packedInputs,i.shape,l),p="",h="",m="";if(d.length===1&&e.packedInputs){let w=[Math.ceil(l[0]/2),Math.ceil(l[1]/2)];p=`${w[0]>1}_${w[1]>1}`}else if(d.length===2&&!e.packedInputs)h=`${d[0]>1}_${d[1]>1}`;else if(d.length>2&&!e.packedInputs){let w=v.computeStrides(d);m=`${w[0]===l[1]}_${w[w.length-1]===l[1]}`}let f=i.shape.length,g=d.length===2&&v.arraysEqual(i.shape,l),y=v.sizeFromShape(i.shape)===1,x=I.getBroadcastDims(i.shape,a.shape),A=!e.packedInputs&&f===a.shape.length&&v.arraysEqual(l,a.texData.texShape),b=e.packedInputs||d.length>2?"":`${l[0]>1}_${l[1]>1}`;n+=`${f}_${A}_${u?c:""}_${d.length}_${y}_${x}_${g}_${p}_${h}_${m}_${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+`${B().getNumber("WEBGL_VERSION")}`,s}function ga(e){return B().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}var hj=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=sp.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Ra();this.outputShape=e,this.enableShapeUniforms=ga(this.outputShape.length),this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms?d0(["r","c","d"],e):dl(["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;
|
|
}
|
|
`}},mj=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=sp.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Ra();this.outputShape=e,this.enableShapeUniforms=ga(this.outputShape.length),this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms?d0(["r","c","d"],e):dl(["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;
|
|
}
|
|
`}},fj=class{constructor(e){this.variableNames=["A"],this.outTexUsage=gn.DOWNLOAD;let t=Ra();this.outputShape=e,this.userCode=`
|
|
${iw}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},gj=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=gn.DOWNLOAD;let t=Ra();this.outputShape=e,this.userCode=`
|
|
${iw}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},yj={R:0,G:1,B:2,A:3},O5=class{constructor(e,t=!1,a="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Ra();this.outputShape=e,this.enableShapeUniforms=ga(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[${yj[o]}];
|
|
}`}this.userCode=`
|
|
${this.enableShapeUniforms?L3():z3(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.);
|
|
}
|
|
`}},xj=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let a=Ra();this.outputShape=e,this.enableShapeUniforms=ga(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?L3():z3(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};
|
|
}
|
|
`}},pw={};Ke(pw,{bindVertexProgramAttributeStreams:()=>bw,createBufferFromOutputTexture:()=>kw,createFloat16MatrixTexture:()=>gw,createFloat16PackedMatrixTexture:()=>Aw,createFloat32MatrixTexture:()=>fw,createIndexBuffer:()=>mw,createPackedMatrixTexture:()=>xw,createUnsignedBytesMatrixTexture:()=>yw,createVertexBuffer:()=>hw,createVertexShader:()=>cw,downloadByteEncodedFloatMatrixFromOutputTexture:()=>Sw,downloadFloat32MatrixFromBuffer:()=>Iw,downloadMatrixFromPackedOutputTexture:()=>Cw,downloadPackedMatrixFromBuffer:()=>Tw,getInternalFormatForFloat16MatrixTexture:()=>V3,getInternalFormatForFloat16PackedMatrixTexture:()=>H3,getInternalFormatForFloat32MatrixTexture:()=>B3,getInternalFormatForPackedMatrixTexture:()=>G3,getInternalFormatForUnsignedBytesMatrixTexture:()=>U3,uploadDenseMatrixToTexture:()=>vw,uploadPixelDataToTexture:()=>ww});function cw(e){let t=Ra(),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 zv(e,a)}function hw(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 Vv(e,t)}function mw(e){let t=new Uint16Array([0,1,2,2,1,3]);return Uv(e,t)}function nc(e,t,a,n,r,s){Hv(t,a);let i=Gv(e),o=e.TEXTURE_2D;return ce(e,()=>e.bindTexture(o,i)),ce(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),ce(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),ce(e,()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST)),ce(e,()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST)),B().getNumber("WEBGL_VERSION")===1?ce(e,()=>e.texImage2D(o,0,n,t,a,0,r,s,null)):ce(e,()=>e.texStorage2D(o,1,n,t,a)),ce(e,()=>e.bindTexture(e.TEXTURE_2D,null)),{texture:i,texShape:[a,t]}}function B3(e){return e.internalFormatFloat}function fw(e,t,a,n){let[r,s]=ac(t,a);return nc(e,r,s,B3(n),n.textureFormatFloat,e.FLOAT)}function V3(e){return e.internalFormatHalfFloat}function gw(e,t,a,n){let[r,s]=ac(t,a);return nc(e,r,s,V3(n),n.textureFormatFloat,n.textureTypeHalfFloat)}function U3(e){return e.downloadTextureFormat}function yw(e,t,a,n){let[r,s]=ac(t,a);return nc(e,r,s,U3(n),e.RGBA,e.UNSIGNED_BYTE)}function G3(e){return e.internalFormatPackedFloat}function xw(e,t,a,n){let[r,s]=Zu(t,a);return nc(e,r,s,G3(n),e.RGBA,e.FLOAT)}function H3(e){return e.internalFormatPackedHalfFloat}function Aw(e,t,a,n){let[r,s]=Zu(t,a);return nc(e,r,s,H3(n),e.RGBA,n.textureTypeHalfFloat)}function bw(e,t,a){return ce(e,()=>e.bindBuffer(e.ARRAY_BUFFER,a)),B1(e,t,"clipSpacePos",a,3,20,0)&&B1(e,t,"uv",a,2,20,12)}function vw(e,t,a,n,r,s){ce(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),B().getNumber("WEBGL_VERSION")===2?ce(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,a,n,e.RGBA,o,i)):ce(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,a,n,0,e.RGBA,o,i)),ce(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function ww(e,t,a){ce(e,()=>e.bindTexture(e.TEXTURE_2D,t)),a.data instanceof Uint8Array?B().getNumber("WEBGL_VERSION")===2?ce(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,a.width,a.height,e.RGBA,e.UNSIGNED_BYTE,a.data)):ce(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,a.width,a.height,0,e.RGBA,e.UNSIGNED_BYTE,a.data)):B().getNumber("WEBGL_VERSION")===2?ce(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,a)):ce(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,a)),ce(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function kw(e,t,a,n){let r=e.createBuffer();ce(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,r));let s=4*4*t*a;return ce(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ)),ce(e,()=>e.readPixels(0,0,a,t,e.RGBA,e.FLOAT,0)),ce(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),r}function Iw(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 Sw(e,t,a,n){let[r,s]=ac(t,a),i=4,o=new Uint8Array(mH(t*a,i));return ce(e,()=>e.readPixels(0,0,r,s,n.downloadTextureFormat,e.UNSIGNED_BYTE,o)),new Float32Array(o.buffer)}function Tw(e,t,a,n,r,s,i,o){let l=e,u=new Float32Array(fH(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 Cw(e,t,a){let n=new Float32Array(t*a*4);return ce(e,()=>e.readPixels(0,0,a,t,e.RGBA,e.FLOAT,n)),n}var Yl=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];let t=B().getNumber("WEBGL_VERSION");if(e!=null?(this.gl=e,u0(t,e)):this.gl=Un(t),e=this.gl,B().getNumber("WEBGL_VERSION")===2){let r=e;this.createVertexArray=()=>ce(r,()=>r.createVertexArray()),this.bindVertexArray=s=>ce(r,()=>r.bindVertexArray(s)),this.deleteVertexArray=s=>ce(r,()=>r.deleteVertexArray(s)),this.getVertexArray=()=>ce(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=()=>ce(e,()=>r.createVertexArrayOES()),this.bindVertexArray=s=>ce(e,()=>r.bindVertexArrayOES(s)),this.deleteVertexArray=s=>ce(e,()=>r.deleteVertexArrayOES(s)),this.getVertexArray=()=>ce(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"),B().getNumber("WEBGL_VERSION")===1){let r="OES_texture_float",s="OES_texture_half_float";if(this.textureFloatExtension=Dd(this.gl,r),yn(this.gl,s))this.textureHalfFloatExtension=Dd(this.gl,s);else if(B().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),yn(this.gl,n))this.colorBufferHalfFloatExtension=Dd(this.gl,n);else if(B().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",yn(this.gl,a))this.colorBufferFloatExtension=this.gl.getExtension(a);else if(yn(this.gl,n))this.colorBufferHalfFloatExtension=this.gl.getExtension(n);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=hw(this.gl),this.indexBuffer=mw(this.gl),this.framebuffer=jv(this.gl),this.textureConfig=_3(this.gl,this.textureHalfFloatExtension)}get debug(){return B().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;ce(e,()=>e.finish()),ce(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),ce(e,()=>e.deleteFramebuffer(this.framebuffer)),ce(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),ce(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),ce(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),fw(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),gw(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),yw(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),ww(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,a,n){this.throwIfDisposed(),vw(this.gl,e,t,a,n,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),Aw(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),xw(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(V1(this.gl,this.framebuffer),this.outputTexture=null),ce(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,a){return this.downloadMatrixDriver(e,()=>Sw(this.gl,t,a,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,a,n,r,s){return Tw(this.gl,e,t,a,n,r,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return Iw(this.gl,e,t)}createBufferFromTexture(e,t,a){this.bindTextureToFrameBuffer(e);let n=kw(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(B().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 B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),a=()=>this.isQueryAvailable(t,B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):a=()=>!0;return{query:t,isFencePassed:a}}downloadMatrixFromPackedTexture(e,t,a){return this.downloadMatrixDriver(e,()=>Cw(this.gl,t,a))}createProgram(e){this.throwIfDisposed();let t=this.gl;this.vertexShader==null&&(this.vertexShader=cw(t));let a=Wv(t);ce(t,()=>t.attachShader(a,this.vertexShader)),ce(t,()=>t.attachShader(a,e)),Bv(t,a);let n=Object.assign(a,{vao:this.createVertexArray()});return this.debug&&uh(t,n),n}buildVao(e){this.setProgram(e),this.bindVertexArray(e.vao);let t=this.gl;ce(t,()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer)),bw(t,e,this.vertexBuffer)}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&(ce(this.gl,()=>this.gl.deleteProgram(e)),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&uh(this.gl,this.program),ce(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,a=!0){return this.throwIfDisposed(),a?Xv(this.gl,e,t):Kv(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),ce(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(),Yv(this.gl,e,t,a)}setOutputMatrixTexture(e,t,a){this.setOutputMatrixTextureDriver(e,a,t)}setOutputPackedMatrixTexture(e,t,a){this.throwIfDisposed();let[n,r]=Zu(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&&uh(this.gl,this.program),Pd(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()}ce(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),ce(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Dd(this.gl,B().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(B().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(B().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,B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,B().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=Aj(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 B().platform&&(a=B().platform.setTimeoutCustom.bind(B().platform)),v.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0),()=>0,null,a)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),dh(this.gl,e,this.framebuffer),this.debug&&Pd(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(dh(this.gl,this.outputTexture,this.framebuffer),this.debug&&Pd(this.gl)):V1(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;dh(n,e,this.framebuffer),this.debug&&Pd(n),this.outputTexture=e,ce(n,()=>n.viewport(0,0,t,a)),ce(n,()=>n.scissor(0,0,t,a))}setOutputMatrixWriteRegionDriver(e,t,a,n){this.throwIfDisposed(),ce(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 Aj(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}var{addImpl:bj,bincountImpl:Nw,bincountReduceImpl:vj,bitwiseAndImpl:wj,castImpl:kj,ceilImpl:Ij,concatImpl:Sj,equalImpl:Tj,expImpl:Cj,expm1Impl:Nj,floorImpl:Rj,gatherNdImpl:Ej,gatherV2Impl:Mj,greaterImpl:Fj,greaterEqualImpl:$j,lessImpl:Dj,lessEqualImpl:Pj,linSpaceImpl:_j,logImpl:Oj,maxImpl:zj,maximumImpl:Lj,minimumImpl:Wj,multiplyImpl:Bj,negImpl:Vj,notEqualImpl:Uj,prodImpl:Gj,raggedGatherImpl:Hj,raggedRangeImpl:jj,raggedTensorToTensorImpl:qj,rangeImpl:Xj,rsqrtImpl:Kj,scatterImpl:Yj,sigmoidImpl:Zj,simpleAbsImpl:Rw,sliceImpl:Jj,sparseFillEmptyRowsImpl:Qj,sparseReshapeImpl:eq,sparseSegmentReductionImpl:Ew,sqrtImpl:tq,staticRegexReplaceImpl:aq,stridedSliceImpl:nq,stringNGramsImpl:rq,stringSplitImpl:sq,stringToHashBucketFastImpl:iq,subImpl:oq,tileImpl:lq,topKImpl:uq,transposeImpl:j3,uniqueImpl:dq}=b3;function Mw(e,t){return["x","y","z","w","u","v"].slice(0,t).map(a=>`${e}.${a}`)}function ka(e,t){return t===1?[e]:Mw(e,t)}function pq(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 cq=class{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=ga(this.outputShape.length),this.rank===0)this.userCode=`
|
|
void main() {
|
|
setOutput(vec4(getA(), 0., 0., 0.));
|
|
}
|
|
`;else{let t=ka("rc",this.rank),a=ft(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]})`}},Fw=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=ga(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=`
|
|
${hq(t,this.enableShapeUniforms)}
|
|
${this.enableShapeUniforms?L3():z3(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 hq(e,t){return`
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${t?CH(["r","c","d"],"inputShape"):dl(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}var mq=class{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.usedTextures={},this.logEnabled=!1}acquireTexture(e,t,a){let n=L5(t,a),r=W5(e,n,a);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);let s=z5(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].pop();return this.usedTextures[r].push(o),o}let i;return n===pa.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):n===pa.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):n===pa.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):n===pa.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):n===pa.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=L5(a,n),s=W5(t,r,n);s in this.freeTextures||(this.freeTextures[s]=[]);let i=z5(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,n),o=B().getNumber("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&&l.indexOf(e);if(u==null||u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l[u]=l[l.length-1],l.pop(),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 fq(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 z5(e,t,a,n,r){let s=gq(t,n),i;if(r){let[l,u]=Zu(e[0],e[1]);i=l*u}else{let[l,u]=ac(e[0],e[1]);i=l*u}let o=fq(a,s);return i*o}function gq(e,t){switch(e){case pa.PACKED_2X2_FLOAT32:return G3(t);case pa.PACKED_2X2_FLOAT16:return H3(t);case pa.UNPACKED_FLOAT32:return B3(t);case pa.UNPACKED_FLOAT16:return V3(t);case pa.PACKED_4X1_UNSIGNED_BYTE:return U3(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function yq(e){return B().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?pa.PACKED_2X2_FLOAT32:pa.UNPACKED_FLOAT32:e?pa.PACKED_2X2_FLOAT16:pa.UNPACKED_FLOAT16}function L5(e,t){if(e===gn.UPLOAD)return pa.PACKED_2X2_FLOAT32;if(e===gn.RENDER||e==null)return yq(t);if(e===gn.DOWNLOAD||e===gn.PIXELS)return pa.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function W5(e,t,a){return`${e[0]}_${e[1]}_${t}_${a}`}var Qn=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=ga(this.outputShape.length),this.userCode=`
|
|
float unaryOperation(float x) {
|
|
${t}
|
|
}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
float y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`}},$n="if (isnan(x)) return x;",xq="return x;",B5="return abs(x);",Aq="return (x >= 0.0) ? x : (exp(x) - 1.0);",bq=$n+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,vq=$n+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,jr="return x;",wq="return 1.0 / (1.0 + exp(-1.0 * x));",kq="return x;",Iq=`
|
|
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;
|
|
`,Sq=`
|
|
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;
|
|
`,Tq=`
|
|
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;
|
|
`,Cq="return 1.0 / (1.0 + exp(-1.0 * x));",Zr=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=ga(this.outputShape.length),this.userCode=`
|
|
vec4 unaryOperation(vec4 x) {
|
|
${t}
|
|
}
|
|
|
|
void main() {
|
|
vec4 x = getAAtOutCoords();
|
|
vec4 y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`}},Nq=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=ga(this.outputShape.length);let t=e.length,a=ka("rc",t),n=ft(t),r=pq(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}));
|
|
}
|
|
`}},Rq=Fn.whereImpl,Eq=1e-7,Mq=1e-4,r1={};function Fq(e){return e in r1||(r1[e]={}),r1[e]}var $q=B().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),Dq=600;function Pq(){return B().global.screen==null?1024:B().global.screen.height*B().global.screen.width*window.devicePixelRatio*Dq/1024/1024}var rc=class $w extends du{nextDataId(){return $w.nextDataId++}constructor(t){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,!B().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let a;if(t!=null){if(t instanceof Yl)a=t;else{let n=Un(B().getNumber("WEBGL_VERSION"),t);a=new Yl(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{let n=Un(B().getNumber("WEBGL_VERSION"));a=new Yl(n),this.binaryCache=Fq(B().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=a,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new mq(this.gpgpu),this.numMBBeforeWarning=Pq(),this.texData=new hp(this,St())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(t,a,n,r,s,i){let o=this.makeTensorInfo(a,n),l=this.texData.get(o.dataId);l.isPacked=!1,l.texture={texture:t,texShape:[r,s]},l.texShape=[r,s];let u=_d(a),d=new O5(u,!1,i),c=this.runWebGLProgram(d,[o],n,[[r,s]]);return c.shape=a,l.texture=null,this.disposeIntermediateTensorInfo(o),c.dataId}write(t,a,n){if((B().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||B().getBool("DEBUG"))&&this.checkNumericalProblems(t),n==="complex64"&&t!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let r={id:this.nextDataId()};return this.texData.set(r,{shape:a,dtype:n,values:t,usage:gn.UPLOAD,refCount:1}),r}refCount(t){return this.texData.has(t)?this.texData.get(t).refCount:0}incRef(t){let a=this.texData.get(t);a.refCount++}decRef(t){if(this.texData.has(t)){let a=this.texData.get(t);a.refCount--}}move(t,a,n,r,s){if(B().getBool("DEBUG")&&this.checkNumericalProblems(a),r==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(t,{shape:n,dtype:r,values:a,usage:gn.UPLOAD,refCount:s})}disposeIntermediateTensorInfo(t){this.disposeData(t.dataId)}readSync(t){let a=this.texData.get(t),{values:n,dtype:r,complexTensorInfos:s,slice:i,shape:o,isPacked:l}=a;if(i!=null){let p;l?p=new Zr(o,jr):p=new Qn(o,jr);let h=this.runWebGLProgram(p,[{dataId:t,shape:o,dtype:r}],r),m=this.readSync(h.dataId);return this.disposeIntermediateTensorInfo(h),m}if(n!=null)return this.convertAndCacheOnCPU(t);if(r==="string")return n;let u=this.activeTimers!=null,d;u&&(d=v.now());let c;if(r==="complex64"){let p=this.readSync(s.real.dataId),h=this.readSync(s.imag.dataId);c=I.mergeRealAndImagArrays(p,h)}else c=this.getValuesFromTexture(t);return u&&(this.downloadWaitMs+=v.now()-d),this.convertAndCacheOnCPU(t,c)}async read(t){if(this.pendingRead.has(t)){let m=this.pendingRead.get(t);return new Promise(f=>m.push(f))}let a=this.texData.get(t),{values:n,shape:r,slice:s,dtype:i,complexTensorInfos:o,isPacked:l}=a;if(s!=null){let m;l?m=new Zr(r,jr):m=new Qn(r,jr);let f=this.runWebGLProgram(m,[{dataId:t,shape:r,dtype:i}],i),g=this.read(f.dataId);return this.disposeIntermediateTensorInfo(f),g}if(n!=null)return this.convertAndCacheOnCPU(t);if(B().getBool("DEBUG")&&!B().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&B().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u=null,d;if(i!=="complex64"&&B().get("WEBGL_BUFFER_SUPPORTED")){d=this.decode(t);let m=this.texData.get(d.dataId);u=this.gpgpu.createBufferFromTexture(m.texture.texture,...nh(r))}this.pendingRead.set(t,[]),i!=="complex64"&&await this.gpgpu.createAndWaitForFence();let c;if(i==="complex64"){let m=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]),f=m[0],g=m[1];c=I.mergeRealAndImagArrays(f,g)}else if(u==null)c=this.getValuesFromTexture(t);else{let m=v.sizeFromShape(r);c=this.gpgpu.downloadFloat32MatrixFromBuffer(u,m)}if(d!=null&&this.disposeIntermediateTensorInfo(d),u!=null){let m=this.gpgpu.gl;ce(m,()=>m.deleteBuffer(u))}let p=this.convertAndCacheOnCPU(t,c),h=this.pendingRead.get(t);return this.pendingRead.delete(t),h.forEach(m=>m(p)),this.pendingDisposal.has(t)&&(this.pendingDisposal.delete(t),this.disposeData(t)&&St().removeDataId(t,this),this.pendingDeletes--),p}readToGPU(t,a={}){let n=this.texData.get(t),{values:r,shape:s,slice:i,dtype:o,isPacked:l,texture:u}=n;if(o==="complex64")throw new Error("Does not support reading texture for complex64 dtype.");if(i!=null){let h;l?h=new Zr(s,jr):h=new Qn(s,jr);let m=this.runWebGLProgram(h,[{dataId:t,shape:s,dtype:o}],o),f=this.readToGPU(m,a);return this.disposeIntermediateTensorInfo(m),f}if(u==null)throw r!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");let d=this.decode(t,a.customTexShape),c=St().makeTensorFromTensorInfo(d),p=this.texData.get(d.dataId);return Object.assign({tensorRef:c},p.texture)}bufferSync(t){let a=this.readSync(t.dataId);if(t.dtype==="string")try{let n=a.map(r=>v.decodeString(r));return Te(t.shape,t.dtype,n)}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return Te(t.shape,t.dtype,a)}checkNumericalProblems(t){if(t!=null)for(let a=0;a<t.length;a++){let n=t[a];if(!_v(n))throw B().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${n} cannot be represented on this device.`)}}getValuesFromTexture(t){let{shape:a,dtype:n,isPacked:r}=this.texData.get(t),s=v.sizeFromShape(a);if(B().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let p=this.decode(t),h=this.texData.get(p.dataId),m=this.gpgpu.downloadMatrixFromPackedTexture(h.texture.texture,...nh(a)).subarray(0,s);return this.disposeIntermediateTensorInfo(p),m}let i=B().getBool("WEBGL_PACK")&&r===!0,o=i?_d(a):a,l=i?new gj(o):new fj(o),u=this.runWebGLProgram(l,[{shape:o,dtype:n,dataId:t}],"float32"),d=this.texData.get(u.dataId),c=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(d.texture.texture,d.texShape[0],d.texShape[1]).subarray(0,s);return this.disposeIntermediateTensorInfo(u),c}timerAvailable(){return B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(t){let a=this.activeTimers,n=[],r=!1;this.programTimersStack==null?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,t();let s=v.flatten(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),i=v.flatten(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=a,r&&(this.programTimersStack=null);let o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let l=await Promise.all(s);o.kernelMs=v.sum(l),o.getExtraProfileInfo=()=>l.map((u,d)=>({name:i[d],ms:u})).map(u=>`${u.name}: ${u.ms}`).join(", ")}else o.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,o})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:v.now(),endMs:null}}endTimer(t){return B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),t):(t.endMs=v.now(),t)}async getQueryTime(t){if(B().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(t);let a=t;return a.endMs-a.startMs}disposeData(t,a=!1){if(this.pendingDisposal.has(t))return!1;if(!this.texData.has(t))return!0;if(a?this.texData.get(t).refCount=0:this.texData.get(t).refCount--,!a&&this.texData.get(t).refCount>0)return!1;if(this.pendingRead.has(t))return this.pendingDisposal.add(t),this.pendingDeletes++,!1;this.releaseGPUData(t);let{complexTensorInfos:n}=this.texData.get(t);return n!=null&&(this.disposeData(n.real.dataId,a),this.disposeData(n.imag.dataId,a)),this.texData.delete(t),!0}releaseGPUData(t){let{texture:a,dtype:n,texShape:r,usage:s,isPacked:i,slice:o}=this.texData.get(t),l=o&&o.origDataId||t,u=this.dataRefCount.get(l);u>1?this.dataRefCount.set(l,u-1):(this.dataRefCount.delete(l),a!=null&&(this.numBytesInGPU-=this.computeBytes(r,n),this.textureManager.releaseTexture(a,r,s,i)));let d=this.texData.get(t);d.texture=null,d.texShape=null,d.isPacked=!1,d.slice=null}getTexture(t){return this.uploadToGPU(t),this.texData.get(t).texture.texture}getDataInfo(t){return this.texData.get(t)}shouldExecuteOnCPU(t,a=$q){return B().getBool("WEBGL_CPU_FORWARD")&&t.every(n=>this.texData.get(n.dataId).texture==null&&v.sizeFromShape(n.shape)<a)}getGPGPUContext(){return this.gpgpu}where(t){I.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let a=t.dataSync();return Rq(t.shape,a)}packedUnaryOp(t,a,n){let r=new Zr(t.shape,a),s=this.compileAndRun(r,[t],n);return St().makeTensorFromTensorInfo(s)}abs(t){if(this.shouldExecuteOnCPU([t])&&t.dtype!=="complex64"){let r=Rw(this.texData.get(t.dataId).values);return this.makeOutput(t.shape,t.dtype,r)}if(B().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,B5,t.dtype);let a=new Qn(t.shape,B5),n=this.compileAndRun(a,[t]);return St().makeTensorFromTensorInfo(n)}makeTensorInfo(t,a,n){let r;if(a==="string"&&n!=null&&n.length>0&&v.isString(n[0])){let s=n.map(i=>v.encodeString(i));r=this.write(s,t,a)}else r=this.write(n,t,a);return this.texData.get(r).usage=null,{dataId:r,shape:t,dtype:a}}makeOutput(t,a,n){return St().makeTensorFromTensorInfo(this.makeTensorInfo(t,a,n),this)}unpackTensor(t){let a=new Nq(t.shape);return this.runWebGLProgram(a,[t],t.dtype)}packTensor(t){let a=new cq(t.shape);return this.runWebGLProgram(a,[t],t.dtype,null,!0)}packedReshape(t,a){let n=[Ni(t.shape),...Ri(t.shape)],r={dtype:t.dtype,shape:n,dataId:t.dataId},s=[Ni(a),...Ri(a)],i=new Fw(s,n),o=!0,l=[n],u=this.runWebGLProgram(i,[r],t.dtype,l,o);return{dataId:u.dataId,shape:a,dtype:u.dtype}}decode(t,a){let n=this.texData.get(t),{isPacked:r,shape:s,dtype:i}=n;if(a!=null){let p=v.sizeFromShape(s),h=a[0]*a[1]*4;v.assert(p<=h,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.")}let o=_d(s),l;r?l=new mj(o):l=new hj(o);let u=!0,d=[a!=null?a:nh(o)],c=this.runWebGLProgram(l,[{shape:o,dtype:i,dataId:t}],i,d,u,a);return{dtype:i,shape:s,dataId:c.dataId}}runWebGLProgram(t,a,n,r,s=!1,i){let o=this.makeTensorInfo(t.outputShape,n),l=this.texData.get(o.dataId);if(t.packedOutput&&(l.isPacked=!0),t.outPackingScheme===sp.DENSE){let y=i!=null?i:nh(t.outputShape);l.texShape=y.map(x=>x*2)}if(t.outTexUsage!=null&&(l.usage=t.outTexUsage),v.sizeFromShape(o.shape)===0)return l.values=v.getTypedArrayFromDType(o.dtype,0),o;let u=[],d=a.map(y=>{if(y.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(y.dataId);if(x.texture==null){if(!t.packedInputs&&v.sizeFromShape(y.shape)<=B().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:y.shape,texData:null,isUniform:!0,uniformValues:x.values};t.packedInputs&&(x.isPacked=!0,x.shape=y.shape)}if(this.uploadToGPU(y.dataId),!!x.isPacked!=!!t.packedInputs)y=x.isPacked?this.unpackTensor(y):this.packTensor(y),u.push(y),x=this.texData.get(y.dataId);else if(x.isPacked&&!ip(x.shape,y.shape)){let A=y,b=y.shape;y.shape=x.shape,y=this.packedReshape(y,b),u.push(y),x=this.texData.get(y.dataId),A.shape=b}return{shape:y.shape,texData:x,isUniform:!1}});this.uploadToGPU(o.dataId);let c={shape:o.shape,texData:l,isUniform:!1},p=cj(t,d,c),h=this.getAndSaveBinary(p,()=>dj(this.gpgpu,t,d,c)),m=this.activeTimers!=null,f;m&&(f=this.startTimer()),B().get("ENGINE_COMPILE_ONLY")||pj(this.gpgpu,h,d,c,r),u.forEach(y=>this.disposeIntermediateTensorInfo(y)),m&&(f=this.endTimer(f),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(f)}));let g=B().getNumber("WEBGL_FLUSH_THRESHOLD");if(g>0){let y=v.now();y-this.lastGlFlushTime>g&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=y)}if(!B().getBool("WEBGL_LAZILY_UNPACK")&&l.isPacked&&s===!1){let y=this.unpackTensor(o);return this.disposeIntermediateTensorInfo(o),y}return o}compileAndRun(t,a,n,r,s=!1){return n=n||a[0].dtype,this.runWebGLProgram(t,a,n,r,s)}getAndSaveBinary(t,a){return t in this.binaryCache||(this.binaryCache[t]=a()),this.binaryCache[t]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(B().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(t=>{this.gpgpu.deleteProgram(this.binaryCache[t].webGLProgram),delete this.binaryCache[t]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=Pe(()=>{if(!B().get("WEBGL_RENDER_FLOAT32_ENABLED")){let t=B().getBool("DEBUG");B().set("DEBUG",!1);let a=this.abs(Ge(1e-8)).dataSync()[0];if(B().set("DEBUG",t),a>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?Eq:Mq}uploadToGPU(t){let a=this.texData.get(t),{shape:n,dtype:r,values:s,texture:i,usage:o,isPacked:l}=a;if(i!=null)return;let u=this.activeTimers!=null,d;u&&(d=v.now());let c=a.texShape;if(c==null&&(c=Qv(n,l),a.texShape=c),s!=null){let p=_d(n),h,m=c[1],f=c[0],g=s instanceof Uint8Array||s instanceof Uint8ClampedArray;(l||!g)&&([m,f]=Zu(c[0],c[1])),l?h=new xj(p,g):h=new O5(p,g);let y=g?[f,m]:c,x=this.makeTensorInfo(y,r),A=this.texData.get(x.dataId);g?A.usage=gn.PIXELS:A.usage=gn.UPLOAD,A.texShape=y,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(x.dataId),m,f,s);let b=[[f,m]],w=this.runWebGLProgram(h,[x],r,b,!0),S=this.texData.get(w.dataId);a.texShape=S.texShape,a.isPacked=S.isPacked,a.usage=S.usage,B().get("ENGINE_COMPILE_ONLY")?this.disposeData(w.dataId):(a.texture=S.texture,a.values=null,this.texData.delete(w.dataId)),this.disposeIntermediateTensorInfo(x),u&&(this.uploadWaitMs+=v.now()-d)}else{let p=this.acquireTexture(c,o,r,l);a.texture=p}}convertAndCacheOnCPU(t,a){let n=this.texData.get(t),{dtype:r}=n;return a!=null&&(n.values=_q(a,r)),n.values}acquireTexture(t,a,n,r){if(this.numBytesInGPU+=this.computeBytes(t,n),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){let s=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${s} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(t,a,r)}computeBytes(t,a){return t[0]*t[1]*v.bytesPerElement(a)}checkCompileCompletion(){for(let[,t]of Object.entries(this.binaryCache))this.checkCompletion_(t)}async checkCompileCompletionAsync(){let t=[];if(this.gpgpu.parallelCompilationExtension){for(let[,a]of Object.entries(this.binaryCache))t.push(this.checkCompletionAsync_(a));return Promise.all(t)}else{for(let[,a]of Object.entries(this.binaryCache)){let n=new Promise(r=>{try{this.checkCompletion_(a),r(!0)}catch(s){throw s}});t.push(n)}return Promise.all(t)}}async checkCompletionAsync_(t){return this.gpgpu.gl.getProgramParameter(t.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(t):(await i6(),this.checkCompletionAsync_(t))}checkCompletion_(t){if(this.gpgpu.gl.getProgramParameter(t.webGLProgram,this.gpgpu.gl.LINK_STATUS)===!1)throw console.log(this.gpgpu.gl.getProgramInfoLog(t.webGLProgram)),this.gpgpu.gl.getShaderParameter(t.fragmentShader,this.gpgpu.gl.COMPILE_STATUS)===!1?(O3(t.source,this.gpgpu.gl.getShaderInfoLog(t.fragmentShader)),new Error("Failed to compile fragment shader.")):new Error("Failed to link vertex and fragment shaders.");return!0}getUniformLocations(){for(let t of Object.values(this.binaryCache)){this.gpgpu.buildVao(t.webGLProgram);let{variablesLocations:a,customUniformLocations:n,infLoc:r,nanLoc:s,outShapeLocation:i,outShapeStridesLocation:o,outTexShapeLocation:l}=dw(this.gpgpu,t.program,t.webGLProgram);t.variablesLocations=a,t.customUniformLocations=n,t.infLoc=r,t.nanLoc=s,t.outShapeLocation=i,t.outShapeStridesLocation=o,t.outTexShapeLocation=l}}createTensorFromGPUData(t,a,n){t.channels=t.channels||"RGBA";let{texture:r,height:s,width:i,channels:o}=t,l=St().backend;if(!l.gpgpu.gl.isTexture(r))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 u=l.writeTexture(r,a,n,s,i,o);return St().makeTensorFromDataId(u,a,n,l)}};rc.nextDataId=0;function _q(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 Oq="4.17.0";function Dw(){B().set("WEBGL_FORCE_F16_TEXTURES",!0)}Wp.isBrowser()&&ll("webgl",()=>new rc,2);var zq={forceHalfFloat:Dw},q3=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,Ei=class{constructor(e,t,a){this.variableNames=["A","B"],this.outputShape=I.assertAndGetBroadcastShape(t,a),this.enableShapeUniforms=ga(this.outputShape.length),this.userCode=`
|
|
float binaryOperation(float a, float b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float a = getAAtOutCoords();
|
|
float b = getBAtOutCoords();
|
|
setOutput(binaryOperation(a, b));
|
|
}
|
|
`}},cl=`
|
|
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;
|
|
`,nd=class{constructor(e,t,a,n=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=I.assertAndGetBroadcastShape(t,a);let r=this.outputShape.length;this.enableShapeUniforms=ga(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=`
|
|
${ft(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=ka("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 tn(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 Lq={kernelName:ho,backendName:"webgl",kernelFunc:tn};function zs(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=tn({inputs:{x:n},backend:a}),l=tn({inputs:{x:r},backend:a});return i.complexTensorInfos={real:o,imag:l},s}var Wq={kernelName:xp,backendName:"webgl",kernelFunc:zs},Pw="return (a < 0.) ? b * a : a;",_w=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function Bq(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{alpha:s}=n,i=a.makeTensorInfo([],"float32",v.createScalarValue(s,"float32")),o=B().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new nd(_w,r.shape,i.shape):new Ei(Pw,r.shape,i.shape),l=a.runWebGLProgram(o,[r,i],"float32");return a.disposeIntermediateTensorInfo(i),l}var Vq={kernelName:yo,backendName:"webgl",kernelFunc:Bq},Ow="return (a < 0.) ? b * a : a;",zw=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function Uq(e){let{inputs:t,backend:a}=e,{x:n,alpha:r}=t,s=B().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new nd(zw,n.shape,r.shape):new Ei(Ow,n.shape,r.shape);return a.runWebGLProgram(s,[n,r],"float32")}var Gq={kernelName:_o,backendName:"webgl",kernelFunc:Uq},rd="if (isnan(x)) return x;";function tt({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),p=a(c.values,l);return o.makeTensorInfo(i.shape,l,p)}let u=B().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,d;return u?d=new Zr(i.shape,t):d=new Qn(i.shape,e),o.runWebGLProgram(d,[i],l)}}function ha({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,d=o;if(n&&l.dtype==="complex64"){let m=d.texData.get(l.dataId),f=d.texData.get(u.dataId),[g,y]=[[m.complexTensorInfos.real,f.complexTensorInfos.real],[m.complexTensorInfos.imag,f.complexTensorInfos.imag]].map(A=>{let[b,w]=A,S={dataId:b.dataId,dtype:b.dtype,shape:l.shape},C={dataId:w.dataId,dtype:w.dtype,shape:u.shape},N=new Ei(e,l.shape,u.shape);return d.runWebGLProgram(N,[S,C],Qt(b.dtype,w.dtype))}),x=zs({inputs:{real:g,imag:y},backend:d});return d.disposeIntermediateTensorInfo(g),d.disposeIntermediateTensorInfo(y),x}let c=s||Qt(l.dtype,u.dtype);if((l.dtype==="string"||u.dtype==="string"||d.shouldExecuteOnCPU([l,u]))&&r!=null){let m=d.texData.get(l.dataId).values,f=d.texData.get(u.dataId).values,g=l.dtype==="string"?I.fromUint8ToStringArray(m):m,y=l.dtype==="string"?I.fromUint8ToStringArray(f):f,[x,A]=r(l.shape,u.shape,g,y,c),b=d.makeTensorInfo(A,c),w=d.texData.get(b.dataId);return w.values=x,b}let p=B().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return p?h=new nd(t,l.shape,u.shape,a):h=new Ei(e,l.shape,u.shape),d.runWebGLProgram(h,[l,u],c)}}function op(e,t=!1){if(e==="linear")return t?kq:xq;if(e==="relu")return t?Sq:bq;if(e==="elu")return t?Iq:Aq;if(e==="relu6")return t?Tq:vq;if(e==="prelu")return t?zw:Ow;if(e==="leakyrelu")return t?_w:Pw;if(e==="sigmoid")return t?Cq:wq;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var Lw=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=ga(this.outputShape.length);let u=n?e[1]:e[2],d=Math.ceil(u/2),c=n?"i * 2, rc.y":"rc.y, i * 2",p=r?"rc.z, i * 2":"i * 2, rc.z",h=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],m=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],f="",g="";i&&(o?f=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${i}
|
|
}`:l?f=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${i}
|
|
}`:f=`vec4 activation(vec4 x) {
|
|
${i}
|
|
}`,g="result = activation(result);");let y=s?"result += getBiasAtOutCoords();":"";s&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let x="rc.x",A="rc.x";e[0]<t[0]?x=`imod(rc.x, ${e[0]})`:t[0]<e[0]&&(A=`imod(rc.x, ${t[0]})`),this.userCode=`
|
|
${f}
|
|
// Don't use uniform for sharedDimensionPacked for performance.
|
|
const float sharedDimension = ${d}.0;
|
|
|
|
vec4 dot2x2ARowBCol(ivec3 rc) {
|
|
vec4 result = vec4(0);
|
|
int batchA = ${x};
|
|
int batchB = ${A};
|
|
for (int i = 0; i < ${d}; i++) {
|
|
vec4 a = getMatrixA(batchA, ${c});
|
|
vec4 b = getMatrixB(batchB, ${p});
|
|
|
|
// These swizzled products need to be separately added.
|
|
// See: https://github.com/tensorflow/tfjs/issues/1735
|
|
result += (${h[0]} * ${m[0]});
|
|
result += (${h[1]} * ${m[1]});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
vec4 result = dot2x2ARowBCol(rc);
|
|
|
|
${y}
|
|
|
|
${g}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}},V5={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},U5=class{constructor(e,t,a){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=I.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));
|
|
}
|
|
`}},G5="return a * b;";function X3(e){let{inputs:t,backend:a}=e,{a:n,b:r}=t,s=I.upcastType(n.dtype,r.dtype);if(n.dtype==="complex64"){let o=a.texData.get(n.dataId),l=a.texData.get(r.dataId),u=new U5(V5.REAL,n.shape,r.shape),d=new U5(V5.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}],p=a.runWebGLProgram(u,c,"float32"),h=a.runWebGLProgram(d,c,"float32"),m=zs({inputs:{real:p,imag:h},backend:a});return a.disposeIntermediateTensorInfo(p),a.disposeIntermediateTensorInfo(h),m}if(a.shouldExecuteOnCPU([n,r])){let o=a.texData.get(n.dataId),l=a.texData.get(r.dataId),[u,d]=Bj(n.shape,r.shape,o.values,l.values,s),c=a.makeTensorInfo(d,s),p=a.texData.get(c.dataId);return p.values=u,c}let i;return B().getBool("WEBGL_PACK_BINARY_OPERATIONS")?i=new nd(G5,n.shape,r.shape):i=new Ei(G5,n.shape,r.shape),a.runWebGLProgram(i,[n,r],s)}var Hq={kernelName:Ts,backendName:"webgl",kernelFunc:X3};function jq(e,t,a){let n=[Ni(e.shape),...Ri(e.shape)],r={dtype:e.dtype,shape:n,dataId:e.dataId},s=[Ni(t),...Ri(t)],i=new Fw(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 pe(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 d=i.texData.get(r.dataId);return d.isPacked&&!ip(r.shape,l)&&!(d.texture!==null&&ip(d.shape,l))?jq(r,l,i):(i.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype})}var qq={kernelName:Du,backendName:"webgl",kernelFunc:pe},H5=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 d=1/t;l=`sumValue += dot(values * ${v.isInt(d)?d.toPrecision(2):d}, 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);
|
|
}
|
|
`}},Xq=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,d=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);
|
|
}
|
|
}
|
|
}
|
|
`,p="vec4";t==="all"?(i="1.0",c=`
|
|
bool reducedAllValue = all(values);
|
|
float floatedReducedAllValue = float(reducedAllValue);
|
|
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
|
|
`,p="bvec4"):t==="any"&&(i="0.0",c=`
|
|
bool reducedAnyValue = any(values);
|
|
float floatedReducedAnyValue = float(reducedAnyValue);
|
|
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
|
|
`,p="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;
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${c}
|
|
}
|
|
|
|
int inIdx = inOffset + ${u};
|
|
if (${d===1}) {
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${c}
|
|
} else if (${d===2}) {
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${c}
|
|
} else if (${d===3}) {
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
${c}
|
|
}
|
|
setOutput(${l});
|
|
}
|
|
`}};function Kq(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=I.computeOptimalWindowSize(a);t.push({inSize:a,windowSize:n,outSize:Math.ceil(a/n)})}return t}function hl(e,t,a,n){let r=Kq(e.shape),s=e;for(let i=0;i<r.length;i++){let{inSize:o,windowSize:l,outSize:u}=r[i],d,c;a==="mean"?d=i===0?new H5({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},o):new H5({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u}):d=new Xq({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},a),c=s,s=n.runWebGLProgram(d,[s],t),c.dataId!==e.dataId&&n.disposeIntermediateTensorInfo(c)}return s}var Yq=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=ft(this.rank),r=Zq(t);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${r}));
|
|
}
|
|
`}};function Zq(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 Jq=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=ft(this.rank),r=Mw("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 p0(e,t,a){let n=B().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Jq(e.shape,t):new Yq(e.shape,t);return a.runWebGLProgram(n,[e],e.dtype)}function Qq(e,t,a,n){let r=t,s=e.shape.length,i=v.parseAxisParam(r,e.shape),o=i,l=I.getAxesPermutation(o,s),u=l!=null,d=e;u&&(d=p0(e,l,n),o=I.getInnerMostAxes(o.length,s)),I.assertAxesAreInnerMostDims("sum",o,s);let[c,p]=I.computeOutAndReduceShapes(d.shape,o),h=c;a&&(h=I.expandShapeToKeepDim(c,i));let m=v.sizeFromShape(p),f=v.sizeFromShape(e.shape)/m,g=pe({inputs:{x:d},attrs:{shape:[f,m]},backend:n}),y=Lp(e.dtype),x=hl(g,y,"sum",n),A=pe({inputs:{x},attrs:{shape:h},backend:n});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(x),u&&n.disposeIntermediateTensorInfo(d),A}function c0(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;return Qq(r,s,i,a)}var eX={kernelName:Qo,backendName:"webgl",kernelFunc:c0};function Ta(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 d=0;d<l.length;d++)l[d]=r.shape[s[d]];let u;if(i.shouldExecuteOnCPU([r])){let d=i.texData.get(r.dataId).values,c=j3(d,r.shape,r.dtype,s,l);u=i.makeTensorInfo(l,r.dtype);let p=i.texData.get(u.dataId);p.values=c}else u=p0(r,s,i);return u}var tX={kernelName:Tr,backendName:"webgl",kernelFunc:Ta},Ww=1e3;function Rh({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,d=t.shape.length,c=a?e.shape[u-2]:e.shape[u-1],p=n?t.shape[d-1]:t.shape[d-2],h=a?e.shape[u-1]:e.shape[u-2],m=n?t.shape[d-2]:t.shape[d-1],f=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=v.sizeFromShape(f),x=v.sizeFromShape(g),A=ul.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([h,m]);v.assert(c===p,()=>`Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${a} and transposeB=${n} must match.`);let b=a?[y,c,h]:[y,h,c],w=n?[x,m,p]:[x,p,m],S=pe({inputs:{x:e},backend:r,attrs:{shape:b}}),C=pe({inputs:{x:t},backend:r,attrs:{shape:w}}),N=[S,C],M=Math.max(y,x),F=a?S.shape[1]:S.shape[2],E=s!=null,T=i!=null,D=l==="leakyrelu",O=l!=null?op(l,!0):null,W=E||T||D||O!=null,$;if((h===1||m===1)&&F>Ww&&W===!1){let G=S,q=C;a&&(G=Ta({inputs:{x:S},backend:r,attrs:{perm:[0,2,1]}}),N.push(G)),n&&(q=Ta({inputs:{x:C},backend:r,attrs:{perm:[0,2,1]}}),N.push(q));let H=m!==1,V=m===1,Z=G;H&&(Z=pe({inputs:{x:G},backend:r,attrs:{shape:[M,F,1]}}),N.push(Z));let X=m===1?2:1,re=q;V&&(re=pe({inputs:{x:q},backend:r,attrs:{shape:[M,1,F]}}),N.push(re));let ee=X3({inputs:{a:Z,b:re},backend:r});$=c0({inputs:{x:ee},backend:r,attrs:{axis:X,keepDims:!0}}),N.push(ee)}else{let G=Qt(e.dtype,t.dtype),q=new Lw(b,w,[M,h,m],a,n,E,O,T,D),H=[S,C];if(s!=null&&H.push(s),T&&H.push(i),D){let V=r.makeTensorInfo([],"float32",v.createScalarValue(o,"float32"));H.push(V),N.push(V)}$=r.runWebGLProgram(q,H,G)}let U=pe({inputs:{x:$},backend:r,attrs:{shape:A}});N.push($);for(let G of N)r.disposeIntermediateTensorInfo(G);return U}function aX(e){let{inputs:t,backend:a,attrs:n}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:d,leakyreluAlpha:c}=n;return Rh({a:r,b:s,transposeA:l,transposeB:u,backend:a,bias:i,preluActivationWeights:o,leakyreluAlpha:c,activation:d})}var nX={kernelName:ts,backendName:"webgl",kernelFunc:aX},j5="return abs(x);";function rX(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=Rw(s.values);return a.makeTensorInfo(n.shape,n.dtype,i)}let r;return B().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new Zr(n.shape,j5):r=new Qn(n.shape,j5),a.runWebGLProgram(r,[n],n.dtype)}var sX={kernelName:cu,backendName:"webgl",kernelFunc:rX},iX=$n+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,oX=tt({opSnippet:iX}),lX={kernelName:$i,backendName:"webgl",kernelFunc:oX},uX=$n+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,dX=tt({opSnippet:uX}),pX={kernelName:Di,backendName:"webgl",kernelFunc:dX},q5="return a + b;",cX=ha({opSnippet:q5,packedOpSnippet:q5,supportsComplex:!0,cpuKernelImpl:bj}),hX={kernelName:Mr,backendName:"webgl",kernelFunc:cX},mX=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);
|
|
}
|
|
`}},fX=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 hh(e){let{inputs:t,backend:a}=e,n=t;if(n.length===1)return tn({inputs:{x:n[0]},backend:a});if(n.length>B().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let o=Math.floor(n.length/2),l=hh({inputs:n.slice(0,o),backend:a}),u=hh({inputs:n.slice(o),backend:a});return hh({inputs:[l,u],backend:a})}let r=n.map(o=>o.dtype).reduce((o,l)=>Qt(o,l)),s=n.map(o=>o.shape),i=B().getBool("WEBGL_PACK")?new fX(n[0].shape,s):new mX(n[0].shape,s);return a.runWebGLProgram(i,n,r)}var gX={kernelName:Pi,backendName:"webgl",kernelFunc:hh};function yX(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,d=I.getAxesPermutation(u,o),c=r;d!=null&&(c=Ta({inputs:{x:r},backend:a,attrs:{perm:d}}),u=I.getInnerMostAxes(u.length,o)),I.assertAxesAreInnerMostDims("all",u,o);let[p,h]=I.computeOutAndReduceShapes(c.shape,u),m=v.sizeFromShape(h),f=pe({inputs:{x:c},backend:a,attrs:{shape:[-1,m]}}),g=hl(f,f.dtype,"all",a),y;if(i){let x=I.expandShapeToKeepDim(p,l);y=pe({inputs:{x:g},backend:a,attrs:{shape:x}})}else y=pe({inputs:{x:g},backend:a,attrs:{shape:p}});return a.disposeIntermediateTensorInfo(f),a.disposeIntermediateTensorInfo(g),d!=null&&a.disposeIntermediateTensorInfo(c),y}var xX={kernelName:_i,backendName:"webgl",kernelFunc:yX};function AX(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,d=I.getAxesPermutation(u,o),c=r;d!=null&&(c=Ta({inputs:{x:r},backend:a,attrs:{perm:d}}),u=I.getInnerMostAxes(u.length,o)),I.assertAxesAreInnerMostDims("any",u,o);let[p,h]=I.computeOutAndReduceShapes(c.shape,u),m=v.sizeFromShape(h),f=pe({inputs:{x:c},backend:a,attrs:{shape:[-1,m]}}),g=hl(f,f.dtype,"any",a),y;if(i){let x=I.expandShapeToKeepDim(p,l);y=pe({inputs:{x:g},backend:a,attrs:{shape:x}})}else y=pe({inputs:{x:g},backend:a,attrs:{shape:p}});return a.disposeIntermediateTensorInfo(f),a.disposeIntermediateTensorInfo(g),d!=null&&a.disposeIntermediateTensorInfo(c),y}var bX={kernelName:Oi,backendName:"webgl",kernelFunc:AX},vX=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));
|
|
}
|
|
`}},wX=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=ft(o),u=ka("coords",o),d,c;if(s===1){c=o+1;let C=ft(c);d=`
|
|
${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,d=`
|
|
${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 p=["x","y","z","w","u","v"].slice(0,c),h="."+p[c-1],m=p.map(C=>"int "+C),f=ka("sourceLocR",c-1).concat("inIdx.r"),g=ka("sourceLocG",c-1).concat("inIdx.g"),y=ka("sourceLocB",c-1).concat("inIdx.b"),x=ka("sourceLocA",c-1).concat("inIdx.a"),A=a==="max"?"greaterThan":"lessThan",b=n?"":`
|
|
inIdx = round(vec4(getBestIndicesAChannel(${f.join()}),
|
|
getBestIndicesAChannel(${g.join()}),
|
|
getBestIndicesAChannel(${y.join()}),
|
|
getBestIndicesAChannel(${x.join()})));`,w=`vec4(
|
|
getAChannel(${f.join()}),
|
|
hasNextCol ? getAChannel(${g.join()}) : 0.,
|
|
hasNextRow ? getAChannel(${y.join()}) : 0.,
|
|
hasNextRow && hasNextCol ? getAChannel(${x.join()}) : 0.)`,S=n?"":`
|
|
float getBestIndicesAChannel(${m.join()}) {
|
|
return getChannel(getBestIndicesA(${p.join()}),
|
|
vec2(${p.slice(-2).join()}));
|
|
}`;this.userCode=`
|
|
float getAChannel(${m.join()}) {
|
|
return getChannel(getA(${p.join()}),
|
|
vec2(${p.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};
|
|
${d}
|
|
ivec4 srcIdx = ivec4(sourceLocR${h}, sourceLocG${h},
|
|
sourceLocB${h}, sourceLocA${h}) * ${t};
|
|
ivec4 inIdx = srcIdx;
|
|
vec4 bestIndex = vec4(inIdx);
|
|
vec4 bestValue = ${w};
|
|
|
|
for (int i = 0; i < ${t}; i++) {
|
|
inIdx = srcIdx;
|
|
${b}
|
|
vec4 candidate = ${w};
|
|
bvec4 nan = isnan(candidate);
|
|
bvec4 replace = bvec4(
|
|
vec4(${A}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
|
|
|
|
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
|
|
replace.y ? candidate.y : bestValue.y,
|
|
replace.z ? candidate.z : bestValue.z,
|
|
replace.w ? candidate.w : bestValue.w);
|
|
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
|
|
srcIdx++;
|
|
}
|
|
setOutput(bestIndex);
|
|
}
|
|
`}};function Bw(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=I.computeOptimalWindowSize(s),o={windowSize:i,inSize:s,batchSize:r,outSize:Math.ceil(s/i)},l=new vX(o,a,n==null),u=[t];n!=null&&u.push(n);let d=e.runWebGLProgram(l,u,"int32");if(d.shape[1]===1)return d;let c=Bw(e,t,a,d);return e.disposeIntermediateTensorInfo(d),c}function Vw(e,t,a,n=null){let r=n!=null?n.shape:t.shape,s=r[r.length-1],i=I.computeOptimalWindowSize(s),o=new wX(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 d=Vw(e,t,a,u);return e.disposeIntermediateTensorInfo(u),d}return u}function Uw(e,t,a,n){let r=[a];if(I.assertAxesAreInnerMostDims("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.shape.length),!B().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,d]=I.computeOutAndReduceShapes(l.shape,r),c=v.sizeFromShape(d),p=pe({inputs:{x:l},backend:e,attrs:{shape:[-1,c]}});s.push(p);let h=Bw(e,p,n);s.push(h);let m=pe({inputs:{x:h},backend:e,attrs:{shape:u}});return s.forEach(f=>e.disposeIntermediateTensorInfo(f)),m}return Vw(e,t,n)}function kX(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s}=n,i=v.parseAxisParam(s,r.shape),o=I.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=Ta({inputs:{x:r},backend:a,attrs:{perm:o}}),u.push(l),i=I.getInnerMostAxes(i.length,l.shape.length)),I.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let d=Uw(a,l,i[0],"max");return u.forEach(c=>a.disposeIntermediateTensorInfo(c)),d}var IX={kernelName:hu,backendName:"webgl",kernelFunc:kX};function SX(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s}=n,i=v.parseAxisParam(s,r.shape),o=I.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=Ta({inputs:{x:r},backend:a,attrs:{perm:o}}),u.push(l),i=I.getInnerMostAxes(i.length,l.shape.length)),I.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let d=Uw(a,l,i[0],"min");return u.forEach(c=>a.disposeIntermediateTensorInfo(c)),d}var TX={kernelName:mu,backendName:"webgl",kernelFunc:SX},CX=$n+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,NX=tt({opSnippet:CX}),RX={kernelName:zi,backendName:"webgl",kernelFunc:NX},EX=$n+"return log(x + sqrt(x * x + 1.0));",MX=tt({opSnippet:EX}),FX={kernelName:Li,backendName:"webgl",kernelFunc:MX},$X=$n+`
|
|
return atan(x);
|
|
`,DX=tt({opSnippet:$X}),PX={kernelName:Wi,backendName:"webgl",kernelFunc:DX},_X=q3+`
|
|
return atan(a, b);
|
|
`,OX=`
|
|
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);
|
|
`+cl+`
|
|
return result;
|
|
`,zX=ha({opSnippet:_X,packedOpSnippet:OX}),LX={kernelName:Vi,backendName:"webgl",kernelFunc:zX},WX=$n+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,BX=tt({opSnippet:WX}),VX={kernelName:Bi,backendName:"webgl",kernelFunc:BX},lp=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,d=e.effectiveFilterHeight,c=e.effectiveFilterWidth,p=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;let m=t==="avg",f=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,y="0.0";if(m||(y="-1.0 / 1e-20"),a){let C=">=";this.userCode=`
|
|
const ivec2 strides = ivec2(${i}, ${o});
|
|
const ivec2 pads = ivec2(${p}, ${h});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// max/min x(?, ?, d) to get y(yR, yC, d).
|
|
// ? = to be determined
|
|
float minMaxValue = 0.0;
|
|
float minMaxValueFound = 0.0;
|
|
int minMaxPosition = 0;
|
|
float avgValue = 0.0;
|
|
|
|
for (int wR = 0; wR < ${d};
|
|
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?f:g:`wR * ${c} + wC`};
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let x="max",A=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(A="avgValue / max(count, 1.0)");let b=Math.floor(s/4)*4,w=s%4,S=`
|
|
if (${m}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${x}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec2 strides = ivec2(${i}, ${o});
|
|
const ivec2 pads = ivec2(${p}, ${h});
|
|
const float initializationValue = ${y};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float count = 0.0;
|
|
|
|
float getValue(int batch, int xR, int xC, int d) {
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
return initializationValue;
|
|
}
|
|
count += 1.0;
|
|
return getX(batch, xR, xC, d);
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// max/min x(?, ?, d) to get y(yR, yC, d).
|
|
// ? = to be determined
|
|
vec4 minMaxValue = vec4(${y});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wR = 0; wR < ${d};
|
|
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(${A});
|
|
}
|
|
`}},K3=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,d=e.dilationHeight,c=e.dilationWidth,p=e.effectiveFilterDepth,h=e.effectiveFilterHeight,m=e.effectiveFilterWidth,f=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;let x=t==="avg",A="0.0";if(x||(A="-1.0 / 1e-20"),a){let M=">=";this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${i}, ${o}, ${l});
|
|
const ivec3 pads = ivec3(${f}, ${g}, ${y});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xDCorner = xCorner.x;
|
|
int xRCorner = xCorner.y;
|
|
int xCCorner = xCorner.z;
|
|
|
|
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
|
|
// ? = to be determined
|
|
float minMaxValue = 0.0;
|
|
float minMaxValueFound = 0.0;
|
|
int minMaxPosition = 0;
|
|
|
|
for (int wD = 0; wD < ${p};
|
|
wD += ${u}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${h};
|
|
wR += ${d}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${m};
|
|
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 ${M} 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} * ${m} +
|
|
wR * ${m} + wC`};
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let b="max",w=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(w="avgValue / max(count, 1.0)");let S=Math.floor(s/4)*4,C=s%4,N=`
|
|
if (${x}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${b}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${i}, ${o}, ${l});
|
|
const ivec3 pads = ivec3(${f}, ${g}, ${y});
|
|
const float initializationValue = ${A};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float count = 0.0;
|
|
|
|
float getValue(int batch, int xD, int xR, int xC, int ch) {
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
return initializationValue;
|
|
}
|
|
count += 1.0;
|
|
return getX(batch, xD, xR, xC, ch);
|
|
}
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xDCorner = xCorner.x;
|
|
int xRCorner = xCorner.y;
|
|
int xCCorner = xCorner.z;
|
|
|
|
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
|
|
// ? = to be determined
|
|
vec4 minMaxValue = vec4(${A});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wD = 0; wD < ${p};
|
|
wD += ${u}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${h};
|
|
wR += ${d}) {
|
|
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)
|
|
);
|
|
|
|
${N}
|
|
}
|
|
|
|
int xC = xCCorner + ${S};
|
|
if (${C===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${N}
|
|
} else if (${C===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${c}, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${N}
|
|
} 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
|
|
);
|
|
|
|
${N}
|
|
}
|
|
}
|
|
}
|
|
setOutput(${w});
|
|
}
|
|
`}};function UX(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t;Ju(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1;v.assert(I.eitherStridesOrDilationsAreOne(i,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=I.computePool2DInfo(r.shape,s,i,u,o,l);if(d.filterWidth===1&&d.filterHeight===1&&v.arraysEqual(d.inShape,d.outShape))return tn({inputs:{x:r},backend:a});let c=new lp(d,"avg",!1);return a.runWebGLProgram(c,[r],"float32")}var GX={kernelName:Ui,backendName:"webgl",kernelFunc:UX};function HX(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=n,d=[1,1,1],c=I.computePool3DInfo(r.shape,s,i,d,o,l,u),p=new K3(c,"avg",!1);return a.runWebGLProgram(p,[r],"float32")}var jX={kernelName:fu,backendName:"webgl",kernelFunc:HX},qX=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,d=l-1-e.padInfo.left,c=1/(t*a);this.userCode=`
|
|
const ivec2 pads = ivec2(${u}, ${d});
|
|
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);
|
|
}
|
|
`}},XX=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,d=e.effectiveFilterDepth,c=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=d-1-e.padInfo.front,m=c-1-e.padInfo.top,f=p-1-e.padInfo.left,g=1/(t*a*n);this.userCode=`
|
|
const ivec3 pads = ivec3(${h}, ${m}, ${f});
|
|
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 < ${d};
|
|
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 < ${p};
|
|
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 KX(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:d}=n,c=[1,1,1],p=I.computePool3DInfo(i.shape,o,l,c,u,d),h=new XX(p);return a.runWebGLProgram(h,[r],i.dtype)}var YX={kernelName:yp,backendName:"webgl",kernelFunc:KX};function ZX(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,i=s;Ju([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:u}=n,d=I.computePool2DInfo(i.shape,o,l,1,u),c=new qX(d);return a.runWebGLProgram(c,[r],i.dtype)}var JX={kernelName:gp,backendName:"webgl",kernelFunc:ZX};function QX(e){let{inputs:t,backend:a,attrs:n}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=n;return Rh({a:r,b:s,transposeA:i,transposeB:o,backend:a})}var eK={kernelName:Gi,backendName:"webgl",kernelFunc:QX},tK=class{constructor(e,t,a,n,r,s){this.outputShape=[],this.variableNames=["x","mean","variance"],I.assertAndGetBroadcastShape(e,t),I.assertAndGetBroadcastShape(e,a);let i="0.0";n!=null&&(I.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";r!=null&&(I.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)));
|
|
}
|
|
`}},aK=class{constructor(e,t,a,n,r,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],I.assertAndGetBroadcastShape(e,t),I.assertAndGetBroadcastShape(e,a);let i="vec4(0.0)";n!=null&&(I.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";r!=null&&(I.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);
|
|
}
|
|
`}},nK=({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],d=null;i!=null&&(d=i.shape,u.push(i));let c=null;o!=null&&(c=o.shape,u.push(o));let p=B().getBool("WEBGL_PACK_NORMALIZATION")?new aK(n.shape,r.shape,s.shape,d,c,l):new tK(n.shape,r.shape,s.shape,d,c,l);return t.runWebGLProgram(p,u,u[0].dtype)},rK={kernelName:po,backendName:"webgl",kernelFunc:nK},sK=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=ft(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let a=iK(this.rank),n,r=e.map((s,i)=>`sourceLoc.${H1[i]} = start[${i}] + coords.${H1[i]};`);n=`
|
|
${t} sourceLoc;
|
|
${t} coords = getOutputCoords();
|
|
${r.join(`
|
|
`)}
|
|
`,this.userCode=`
|
|
void main() {
|
|
${n}
|
|
setOutput(getSource(${a}));
|
|
}
|
|
`}},H1=["x","y","z","w","u","v"];function iK(e){if(e===1)return"sourceLoc";if(e<=6)return H1.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var oK=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=ft(this.rank),a=ka("coords",this.rank),n=ka("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,d)=>`start[${d}]`).join()});`:e.map((u,d)=>`${n[d]} = ${a[d]} + start[${d}];`).join(`
|
|
`);this.userCode=`
|
|
void main() {
|
|
${t} coords = getOutputCoords();
|
|
${t} sourceLoc;
|
|
${l}
|
|
vec4 result = vec4(0.);
|
|
${i}
|
|
${o}
|
|
setOutput(result);
|
|
}
|
|
`}};function lK(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=wt.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 sd(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{begin:s,size:i}=n,[o,l]=wt.parseSliceParams(r,s,i);if(wt.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),p=Jj(c.values,o,l,r.shape,r.dtype);return a.makeTensorInfo(l,r.dtype,p)}let{isPacked:u}=a.texData.get(r.dataId),d=wt.isSliceContinous(r.shape,o,l);if(u||!d){let c=B().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new oK(l):new sK(l),p=[o];return a.runWebGLProgram(c,[r],r.dtype,p)}return a.uploadToGPU(r.dataId),lK(r,o,l,a)}var uK={kernelName:zu,backendName:"webgl",kernelFunc:sd},dK=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((x,A)=>x*A),l=I.getReshaped(r.shape,s,o),u=I.getPermuted(l.length,s.length),d=I.getReshapedPermuted(r.shape,s,o),c=I.getSliceBeginCoords(i,s.length),p=I.getSliceSize(d,i,s.length),h=[],m=pe({inputs:{x:r},backend:a,attrs:{shape:l}}),f=Ta({inputs:{x:m},backend:a,attrs:{perm:u}}),g=pe({inputs:{x:f},backend:a,attrs:{shape:d}}),y=sd({inputs:{x:g},backend:a,attrs:{begin:c,size:p}});return h.push(m),h.push(f),h.push(g),h.forEach(x=>a.disposeIntermediateTensorInfo(x)),y},pK={kernelName:gu,backendName:"webgl",kernelFunc:dK};function cK(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=Nw(o,l,s.dtype,s.shape,i);return a.makeTensorInfo([i],s.dtype,u)}var hK={kernelName:Hi,backendName:"webgl",kernelFunc:cK},mK=`
|
|
int r = int(a.r) & int(b.r);
|
|
int g = int(a.g) & int(b.g);
|
|
int rb = int(a.b) & int(b.b);
|
|
int ra = int(a.a) & int(b.a);
|
|
return vec4(r, g, rb, ra);
|
|
`,fK=`
|
|
return float(int(a.r) & int(b.r));
|
|
`;function gK(e){let{inputs:t,backend:a}=e,{a:n,b:r}=t,s=B().getBool("WEBGL_PACK_BINARY_OPERATIONS"),i=B().getNumber("WEBGL_VERSION");if(a.shouldExecuteOnCPU([n,r])||i===1){let l=a.texData.get(n.dataId).values,u=a.texData.get(r.dataId).values,[d,c]=wj(n.shape,r.shape,l,u,n.dtype),p=a.makeTensorInfo(c,n.dtype),h=a.texData.get(p.dataId);return h.values=d,p}let o;return s?o=new nd(mK,n.shape,r.shape,!1):o=new Ei(fK,n.shape,r.shape),a.runWebGLProgram(o,[n,r],n.dtype)}var yK={kernelName:ji,backendName:"webgl",kernelFunc:gK};function xK(e){let{inputs:t,backend:a}=e,{s0:n,s1:r}=t,s=a.readSync(n.dataId),i=a.readSync(r.dataId),o=I.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return a.makeTensorInfo([o.length],"int32",Int32Array.from(o))}var AK={kernelName:yu,backendName:"webgl",kernelFunc:xK},bK="return float(a != b);",Gw=ha({opSnippet:bK,cpuKernelImpl:Uj,dtype:"bool"}),vK={kernelName:Cs,backendName:"webgl",kernelFunc:Gw};function sc(e){let{inputs:t,backend:a}=e,{input:n}=t,r=a.texData.get(n.dataId);return tn({inputs:{x:r.complexTensorInfos.real},backend:a})}var wK={kernelName:Ep,backendName:"webgl",kernelFunc:sc},kK="return float(int(x));";function IK(e,t){let a=new Qn(e.shape,kK),n=t.runWebGLProgram(a,[e],"int32");return{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}function j1(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{dtype:s}=n;if(s==="complex64"){if(r.dtype==="complex64")return tn({inputs:{x:r},backend:a});let i=An(r.shape),o=j1({inputs:{x:r},backend:a,attrs:{dtype:"float32"}}),l=zs({inputs:{real:o,imag:i},backend:a});return i.dispose(),a.disposeIntermediateTensorInfo(o),l}if(r.dtype==="complex64"){let i=sc({inputs:{input:r},backend:a}),o=j1({inputs:{x:i},backend:a,attrs:{dtype:s}});return a.disposeIntermediateTensorInfo(i),o}if(!v.hasEncodingLoss(r.dtype,s)){let i=tn({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]=kj(i,r.shape,r.dtype,s);return a.makeTensorInfo(o,l,u)}if(s==="int32")return IK(r,a);if(s==="bool"){let i=a.makeTensorInfo([],"bool",v.getTypedArrayFromDType("bool",1)),o=Gw({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 SK={kernelName:qi,backendName:"webgl",kernelFunc:j1},X5="return ceil(x);",TK=tt({opSnippet:X5,packedOpSnippet:X5,cpuKernelImpl:Ij}),CK={kernelName:cs,backendName:"webgl",kernelFunc:TK},NK=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));
|
|
}
|
|
`}},RK=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 EK(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{clipValueMin:s,clipValueMax:i}=n,o;B().getBool("WEBGL_PACK_CLIP")?o=new RK(r.shape):o=new NK(r.shape);let l=[[s],[i]];return a.runWebGLProgram(o,[r],r.dtype,l)}var MK={kernelName:hs,backendName:"webgl",kernelFunc:EK},FK=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 K5(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function $K(e){let{inputs:t,backend:a}=e,{x:n}=t,r=a.texData.get(n.dataId),s=new FK(n.shape),i=[K5(n,r.complexTensorInfos.real),K5(n,r.complexTensorInfos.imag)];return a.runWebGLProgram(s,i,i[0].dtype)}var DK={kernelName:Ap,backendName:"webgl",kernelFunc:$K},PK=class{constructor(e){this.outputShape=[],this.outputShape=I.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(`
|
|
`)}
|
|
}
|
|
`}},_K=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=I.computeOutShape(e,t);let a=this.outputShape,n=a.length,r=ft(n),s=ka("coords",n),i=["x","y","z","w","u","v"].slice(0,n);this.variableNames=e.map((m,f)=>`T${f}`);let o=new Array(e.length-1);o[0]=e[0][t];for(let m=1;m<o.length;m++)o[m]=o[m-1]+e[m][t];let l=i[t],u=i.slice(-2),d=i.join(),c=`if (${l} < ${o[0]}) {
|
|
return getChannel(
|
|
getT0(${d}), vec2(${u.join()}));
|
|
}`;for(let m=1;m<o.length;m++){let f=o[m-1];c+=`
|
|
if (${l} < ${o[m]} && ${l} >= ${o[m-1]}) {
|
|
return getChannel(
|
|
getT${m}(${sh(i,l,f)}),
|
|
vec2(${sh(u,l,f)}));
|
|
}`}let p=o.length,h=o[o.length-1];c+=`
|
|
return getChannel(
|
|
getT${p}(${sh(i,l,h)}),
|
|
vec2(${sh(u,l,h)}));`,this.userCode=`
|
|
float getValue(${i.map(m=>"int "+m)}) {
|
|
${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 sh(e,t,a){let n=e.indexOf(t);return e.map((r,s)=>s===n?`${r} - ${a}`:r).join()}function h0(e){let{inputs:t,backend:a}=e,{input:n}=t,r=a.texData.get(n.dataId);return tn({inputs:{x:r.complexTensorInfos.imag},backend:a})}var OK={kernelName:Cp,backendName:"webgl",kernelFunc:h0};function Od(e,t,a){let n=e[0].dtype;if(n==="complex64"){let h=e.map(x=>sc({inputs:{input:x},backend:a})),m=e.map(x=>h0({inputs:{input:x},backend:a})),f=Od(h,t,a),g=Od(m,t,a),y=zs({inputs:{real:f,imag:g},backend:a});return h.forEach(x=>a.disposeIntermediateTensorInfo(x)),m.forEach(x=>a.disposeIntermediateTensorInfo(x)),a.disposeIntermediateTensorInfo(f),a.disposeIntermediateTensorInfo(g),y}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 pe({inputs:{x:b},backend:a,attrs:{shape:w}})}),m=h.map(b=>({vals:a.readSync(b.dataId),shape:b.shape})),f=I.computeOutShape(h.map(b=>b.shape),1),g=h[0].shape[0]===1,y=Sj(m,f,n,g),x=I.computeOutShape(e.map(b=>b.shape),t),A=a.makeTensorInfo(x,n,y);return h.forEach(b=>a.disposeIntermediateTensorInfo(b)),A}let s=e.filter(h=>v.sizeFromShape(h.shape)>0),i=B().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&s[0].shape.length>1;if(s.length===1){let h=i?new Qn(e[0].shape,jr):new Zr(e[0].shape,jr);return a.runWebGLProgram(h,e,n)}let o=B().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(s.length>o){let h=[];for(let f=0;f<s.length;f+=o){let g=s.slice(f,f+o);h.push(Od(g,t,a))}let m=Od(h,t,a);for(let f of h)a.disposeIntermediateTensorInfo(f);return m}if(i){let h=new _K(s.map(m=>m.shape),t);return a.runWebGLProgram(h,s,n)}let{tensors2D:l,outShape:u}=zK(s,t,a),d=new PK(l.map(h=>h.shape)),c=a.runWebGLProgram(d,l,n);l.forEach(h=>a.disposeIntermediateTensorInfo(h));let p=pe({inputs:{x:c},attrs:{shape:u},backend:a});return a.disposeIntermediateTensorInfo(c),p}function zK(e,t,a){let n=I.computeOutShape(e.map(r=>r.shape),t);return{tensors2D:e.map(r=>pe({inputs:{x:r},attrs:{shape:[-1,v.sizeFromShape(r.shape.slice(t))]},backend:a})),outShape:n}}function Hw(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);I.assertParamsConsistent(i,s);let o=I.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?tn({inputs:{x:l[0]},backend:a}):Od(l,s,a)}var LK={kernelName:xu,backendName:"webgl",kernelFunc:Hw},jw=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,d=e.dilationWidth,c=e.filterHeight,p=e.filterWidth,h=Math.floor(e.inChannels/4)*4,m=e.inChannels%4,f=e.dataFormat==="channelsLast",g=f?1:2,y=f?2:3,x=f?3:1,A="",b="";a&&(n?A=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${a}
|
|
}`:r?A=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${a}
|
|
}`:A=`
|
|
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=`
|
|
${A}
|
|
|
|
const ivec2 strides = ivec2(${o}, ${l});
|
|
const ivec2 pads = ivec2(${s}, ${i});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d2 = coords[${x}];
|
|
|
|
ivec2 xRCCorner =
|
|
ivec2(coords[${g}], coords[${y}]) * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${c}; wR++) {
|
|
int xR = xRCorner + wR * ${u};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${p}; wC++) {
|
|
int xC = xCCorner + wC * ${d};
|
|
|
|
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 (${f}) {
|
|
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 (${m===1}) {
|
|
|
|
if (${f}) {
|
|
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 (${m===2}) {
|
|
vec2 wValues = vec2(
|
|
getW(wR, wC, ${h}, d2),
|
|
getW(wR, wC, ${h} + 1, d2)
|
|
);
|
|
|
|
if (${f}) {
|
|
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 (${m===3}) {
|
|
vec3 wValues = vec3(
|
|
getW(wR, wC, ${h}, d2),
|
|
getW(wR, wC, ${h} + 1, d2),
|
|
getW(wR, wC, ${h} + 2, d2)
|
|
);
|
|
|
|
if (${f}) {
|
|
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);
|
|
}
|
|
`}},WK=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,d=e.filterDepth,c=e.filterHeight,p=e.filterWidth,h=Math.floor(e.inChannels/4)*4,m=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 < ${d}; 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 < ${p}; 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 (${m===1}) {
|
|
dotProd +=
|
|
getX(batch, xF, xR, xC, ${h}) *
|
|
getW(wF, wR, wC, ${h}, d2);
|
|
} else if (${m===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 (${m===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);
|
|
}
|
|
`}},qw=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=ga(this.outputShape.length);let s=e.padInfo.left,i=e.strideWidth,o=e.dilationWidth,l=e.filterHeight,u=e.filterWidth,d=u,c=`
|
|
int xR; int xC; int xCOffset;
|
|
vec4 wTexel; vec4 previous; vec4 final;`;for(let f=0;f<u;f++)c+=`
|
|
vec4 xTexelC${f*2};
|
|
int xTexelC${f*2}Ready;
|
|
vec4 xTexelC${f*2+1};
|
|
int xTexelC${f*2+1}Ready;
|
|
vec4 xC${f};`;c+=`
|
|
for (int r = 0; r < ${l}; r++) {
|
|
for (int d1 = 0; d1 < ${e.inChannels}; d1 += 2) {
|
|
`;for(let f=0;f<u;f++)c+=`
|
|
xTexelC${f*2} = vec4(0.0);
|
|
xTexelC${f*2}Ready = 0;
|
|
xTexelC${f*2+1} = vec4(0.0);
|
|
xTexelC${f*2+1}Ready = 0;
|
|
xC${f} = vec4(0.0);`;c+=`
|
|
xR = xRCorner + r * dilations[0];
|
|
if (xR >=0 && xR < inDims[0]) {
|
|
`;for(let f=0;f<(d+1)/2;f++){let g=f*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 y=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) + ${y};
|
|
|
|
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);
|
|
`):y===1?c+=`
|
|
xC${g+1} = xTexelC${g};
|
|
`:c+=`
|
|
xCOffset = xC + ${y};
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g+1}Ready == 0) {
|
|
xTexelC${g+1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${g+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${g+1}Ready = 1;
|
|
}
|
|
|
|
xC${g+1} = xTexelC${g+1};
|
|
`}}else g<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 p="",h="";a&&(n?p=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${a}
|
|
}`:r?p=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${a}
|
|
}`:p=`vec4 activation(vec4 x) {
|
|
${a}
|
|
}`,h="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=`
|
|
${p}
|
|
|
|
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);
|
|
${m}
|
|
${h}
|
|
setOutput(result);
|
|
}
|
|
`}},BK=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=ga(this.outputShape.length);let{dataFormat:a}=t,n=Ra(),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 d=0;d<=1;d++)l+=`
|
|
blockIndex = rc.z + ${d};
|
|
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+d}] = getChannel(
|
|
getA(rc.x, d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[${u*2+d}] = 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 Eh(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 Xw({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),d=a.inChannels,c=l[0]*l[1]*l[2],p=a.outChannels,h=a.dataFormat==="channelsLast",m=!1,f=!1,g,y=[];if(s!=null){let x=Eh(s.shape,h);x!=null&&(s=pe({inputs:{x:s},backend:n,attrs:{shape:x}}),y.push(s))}if(r!=null){let x=Eh(r.shape,h);x!=null&&(r=pe({inputs:{x:r},backend:n,attrs:{shape:x}}),y.push(r))}if(!((c===1||p===1)&&d>Ww)&&u.isPacked&&h&&u.texture!=null&&l[2]%2!==0&&v.arraysEqual(u.shape.slice(-3),l.slice(-3))){let x=l[0]*l[1]*(l[2]+1),A={dataId:e.dataId,shape:[1,x,a.inChannels],dtype:e.dtype},b=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,v.assert(ip(u.shape,A.shape),()=>`packed reshape ${u.shape} to ${A.shape} isn't free`);let w=pe({inputs:{x:t},backend:n,attrs:{shape:[1,a.inChannels,a.outChannels]}});y.push(w);let S=Rh({a:A,b:w,backend:n,transposeA:m,transposeB:f,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=tn({inputs:{x:S},backend:n}),g.shape=a.outShape,y.push(S)}else{let x=a.outHeight*a.outWidth,A=pe({inputs:{x:e},backend:n,attrs:{shape:h?[a.batchSize,x,a.inChannels]:[a.batchSize,a.inChannels,x]}}),b=pe({inputs:{x:t},backend:n,attrs:{shape:[1,a.inChannels,a.outChannels]}}),w=Rh({a:h?A:b,b:h?b:A,transposeA:!h,transposeB:f,backend:n,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i});g=pe({inputs:{x:w},backend:n,attrs:{shape:a.outShape}}),y.push(A),y.push(b),y.push(w)}for(let x of y)n.disposeIntermediateTensorInfo(x);return g}function Kw({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:d,outWidth:c,outHeight:p,dataFormat:h}=a,m=h==="channelsLast",f=l*u*d,g=p*c,y=[a.batchSize,f,g],x=!0,A=!1,b=[];if(s!=null){let G=Eh(s.shape,m);G!=null&&(s=pe({inputs:{x:s},backend:n,attrs:{shape:G}}),b.push(s))}if(r!=null){let G=Eh(r.shape,m);G!=null&&(r=pe({inputs:{x:r},backend:n,attrs:{shape:G}}),b.push(r))}let w=pe({inputs:{x:t},backend:n,attrs:{shape:[1,f,v.sizeFromShape(t.shape)/f]}});b.push(w);let S=new BK(y,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]],N=n.runWebGLProgram(S,[e],"float32",C),M=pe({inputs:{x:N},backend:n,attrs:{shape:y}});b.push(N),b.push(M);let F=r!=null,E=s!=null,T=o==="leakyrelu",D=o?op(o,!0):null,O=new Lw(m?M.shape:w.shape,m?w.shape:M.shape,m?[a.batchSize,g,a.outChannels]:[a.batchSize,a.outChannels,g],x,A,F,D,E,T),W=m?[M,w]:[w,M];if(r&&W.push(r),E&&W.push(s),T){let G=n.makeTensorInfo([],"float32",v.createScalarValue(i,"float32"));W.push(G),b.push(G)}let $=n.runWebGLProgram(O,W,"float32"),U=pe({inputs:{x:$},backend:n,attrs:{shape:a.outShape}});b.push($);for(let G of b)n.disposeIntermediateTensorInfo(G);return U}function VK(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:d}=n,c=I.convertConv2DDataFormat(l),p=I.computeConv2DInfo(r.shape,s.shape,i,u,o,d,!1,c),h;if(p.filterHeight===1&&p.filterWidth===1&&p.dilationHeight===1&&p.dilationWidth===1&&p.strideHeight===1&&p.strideWidth===1&&(p.padInfo.type==="SAME"||p.padInfo.type==="VALID"))h=Xw({x:r,filter:s,convInfo:p,backend:a});else if(p.strideWidth<=2&&c==="channelsLast"&&B().getBool("WEBGL_EXP_CONV")){let f=new qw(p),g=[[p.padInfo.top,p.padInfo.left],[p.strideHeight,p.strideWidth],[p.dilationHeight,p.dilationWidth],[p.inHeight,p.inWidth]];h=a.runWebGLProgram(f,[r,s],"float32",g)}else if(B().getBool("WEBGL_CONV_IM2COL"))h=Kw({x:r,filter:s,convInfo:p,backend:a});else{let f=new jw(p);h=a.runWebGLProgram(f,[r,s],"float32")}let m=pe({inputs:{x:h},backend:a,attrs:{shape:p.outShape}});return a.disposeIntermediateTensorInfo(h),m}var UK={kernelName:Xi,backendName:"webgl",kernelFunc:VK},GK=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;
|
|
}
|
|
|
|
${s?`float dyValue = getDy(b, yR, yC, d2);
|
|
float xValue = getX(b, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);`:`float dyValue = getDy(b, d2, yR, yC);
|
|
float xValue = getX(b, d1, xR, xC);
|
|
dotProd += (xValue * dyValue);`}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},HK=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,d=s?3:1;this.userCode=`
|
|
const ivec2 pads = ivec2(${i}, ${o});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[${d}];
|
|
|
|
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);
|
|
}
|
|
`}},jK=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);
|
|
}
|
|
`}},qK=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 XK(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:d}=n,c=I.convertConv2DDataFormat(l),p=I.computeConv2DInfo(r.shape,d,i,1,o,u,!1,c),h=new GK(p);return a.runWebGLProgram(h,[r,s],"float32")}var KK={kernelName:bp,backendName:"webgl",kernelFunc:XK},YK=class{constructor(e){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=e.inShape,this.enableShapeUniforms=ga(this.outputShape.length);let t=e.filterHeight,a=e.filterWidth,n=t-1-e.padInfo.top,r=a-1-e.padInfo.left;this.userCode=`
|
|
const ivec2 pads = ivec2(${n}, ${r});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[3];
|
|
|
|
ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads;
|
|
int dyRCorner = dyCorner.x;
|
|
int dyCCorner = dyCorner.y;
|
|
|
|
vec4 result = vec4(0.);
|
|
for (int wR = 0; wR < ${t}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / strides[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++) {
|
|
int wCPerm = ${a} - 1 - wC;
|
|
|
|
float dyC = float(dyCCorner + wC) / strides[1];
|
|
bool idyCVal = (dyC >= 0.0) && (dyC < ${e.outWidth}.0)
|
|
&& (fract(dyC) == 0.0);
|
|
int idyC = int(dyC);
|
|
|
|
float dyC2 = float(dyCCorner + wC + 1) / strides[1];
|
|
bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${e.outWidth}.0)
|
|
&& (fract(dyC2) == 0.0);
|
|
int idyC2 = int(dyC2);
|
|
|
|
if (idyCVal && idyCVal2) {
|
|
for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
|
|
vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
vec4 dySample = getDy(batch, idyR, idyC, d2);
|
|
vec4 dySample2 = (idyC / 2 == idyC2 / 2) ?
|
|
dySample : getDy(batch, idyR, idyC2, d2);
|
|
|
|
vec2 dyValue = mod(float(idyC), 2.) == 0. ?
|
|
dySample.xy : dySample.zw;
|
|
result.xy += vec2(dot(dyValue, wValue.xy),
|
|
dot(dyValue, wValue.zw));
|
|
|
|
dyValue = mod(float(idyC2), 2.) == 0. ?
|
|
dySample2.xy : dySample2.zw;
|
|
result.zw += vec2(dot(dyValue, wValue.xy),
|
|
dot(dyValue, wValue.zw));
|
|
}
|
|
} else if (idyCVal) {
|
|
for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
|
|
vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
vec4 dySample = getDy(batch, idyR, idyC, d2);
|
|
vec2 dyValue = mod(float(idyC), 2.) == 0. ?
|
|
dySample.xy : dySample.zw;
|
|
result.xy += vec2(dot(dyValue, wValue.xy),
|
|
dot(dyValue, wValue.zw));
|
|
}
|
|
} else if (idyCVal2) {
|
|
for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
|
|
vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
vec4 dySample = getDy(batch, idyR, idyC2, d2);
|
|
vec2 dyValue = mod(float(idyC2), 2.) == 0. ?
|
|
dySample.xy : dySample.zw;
|
|
result.zw += vec2(dot(dyValue, wValue.xy),
|
|
dot(dyValue, wValue.zw));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function ZK(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:d}=n,c=I.convertConv2DDataFormat(u),p=I.computeConv2DInfo(i,s.shape,o,1,l,d,!1,c);if(B().getBool("WEBGL_PACK_CONV2DTRANSPOSE")&&c==="channelsLast"){let h=[[p.strideHeight,p.strideWidth]],m=new YK(p);return a.runWebGLProgram(m,[r,s],"float32",h)}else{let h=new HK(p);return a.runWebGLProgram(h,[r,s],"float32")}}var JK={kernelName:Ki,backendName:"webgl",kernelFunc:ZK};function QK(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=n,u=I.computeConv3DInfo(r.shape,s.shape,i,l,o),d=new WK(u);return a.runWebGLProgram(d,[r,s],"float32")}var eY={kernelName:Yi,backendName:"webgl",kernelFunc:QK};function tY(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=n,u=I.computeConv3DInfo(r.shape,l,i,1,o),d=new jK(u);return a.runWebGLProgram(d,[r,s],"float32")}var aY={kernelName:Au,backendName:"webgl",kernelFunc:tY};function nY(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=n,u=I.computeConv3DInfo(l,s.shape,o,1,i),d=new qK(u);return a.runWebGLProgram(d,[r,s],"float32")}var rY={kernelName:Zi,backendName:"webgl",kernelFunc:nY},sY=rd+`
|
|
return cos(x);
|
|
`,iY=`
|
|
vec4 result = cos(x);
|
|
bvec4 isNaN = isnan(x);
|
|
${cl}
|
|
return result;
|
|
`,oY=tt({opSnippet:sY,packedOpSnippet:iY}),lY={kernelName:Ji,backendName:"webgl",kernelFunc:oY},uY=`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,dY=tt({opSnippet:uY}),pY={kernelName:Qi,backendName:"webgl",kernelFunc:dY},cY=class{constructor(e,t,a,n,r){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[s,i,o,l]=e,[u]=t,[d,c]=a;this.outputShape=[u,d,c,l];let p=n==="bilinear"?1:0,[h,m]=[`${i-1}.0`,`${o-1}.0`],[f,g,y]=d>1?[`${(i-1)/(d-1)}`,"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${h}`],[x,A,b]=c>1?[`${(o-1)/(c-1)}`,"(x2-x1) * width_ratio",`x1*${m} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${m}`];this.userCode=`
|
|
const float height_ratio = float(${f});
|
|
const float width_ratio = float(${x});
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int y = coords[1];
|
|
int x = coords[2];
|
|
int d = coords[3];
|
|
|
|
// get box vals
|
|
float y1 = getBoxes(b,0);
|
|
float x1 = getBoxes(b,1);
|
|
float y2 = getBoxes(b,2);
|
|
float x2 = getBoxes(b,3);
|
|
|
|
// get image in batch index
|
|
int bInd = round(getBoxInd(b));
|
|
if(bInd < 0 || bInd >= ${s}) {
|
|
return;
|
|
}
|
|
|
|
float height_scale = ${g};
|
|
float width_scale = ${A};
|
|
|
|
float in_y = ${y};
|
|
if( in_y < 0.0 || in_y > ${h} ) {
|
|
setOutput(float(${r}));
|
|
return;
|
|
}
|
|
float in_x = ${b};
|
|
if( in_x < 0.0 || in_x > ${m} ) {
|
|
setOutput(float(${r}));
|
|
return;
|
|
}
|
|
|
|
vec2 sourceFracIndexCR = vec2(in_x,in_y);
|
|
if(${p} == 1) {
|
|
// Compute the four integer indices.
|
|
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
|
|
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
|
|
|
|
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
|
|
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
|
|
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
|
|
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
|
|
|
|
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
|
|
|
|
float top = topLeft + (topRight - topLeft) * fracCR.x;
|
|
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
|
|
float newValue = top + (bottom - top) * fracCR.y;
|
|
setOutput(newValue);
|
|
} else {
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec2 sourceNearestCR = ivec2(floor(
|
|
sourceFracIndexCR + vec2(0.5,0.5)));
|
|
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
|
|
setOutput(newValue);
|
|
}
|
|
}
|
|
`}},hY=e=>{let{inputs:t,backend:a,attrs:n}=e,{image:r,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=n,d=new cY(r.shape,s.shape,o,l,u);return a.runWebGLProgram(d,[r,s,i],"float32")},mY={kernelName:ao,backendName:"webgl",kernelFunc:hY},up;(function(e){e.Prod="*",e.Sum="+"})(up||(up={}));var Y5=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===up.Prod?"1.0":"0.0",i=a?s:`getX(${Z5(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() {
|
|
${ft(r)} coords = getOutputCoords();
|
|
int end = ${J5(r,"coords",this.op)};
|
|
float val = ${i};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${l}) {
|
|
int idx = ${u};
|
|
${J5(r,"coords",this.op)} = idx;
|
|
val ${this.op}= getX(${Z5(r,"coords",this.op)});
|
|
}
|
|
setOutput(val);
|
|
}
|
|
`}};function Z5(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 J5(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 Yw(e,t,a,n,r,s){let i=t.shape.length,o=I.getAxesPermutation([n],i),l=t;o!=null&&(l=Ta({inputs:{x:t},backend:a,attrs:{perm:o}}));let u=I.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 d=l.shape[u],c=tn({inputs:{x:l},backend:a});for(let p=0;p<=Math.ceil(Math.log2(d))-1;p++){let h=new Y5(e,l.shape,!1,s),m=[[p]],f=c;c=a.runWebGLProgram(h,[c],c.dtype,m),a.disposeIntermediateTensorInfo(f)}if(r){let p=new Y5(e,l.shape,r,s),h=c;c=a.runWebGLProgram(p,[c],c.dtype),a.disposeIntermediateTensorInfo(h)}if(o!=null){let p=I.getUndoAxesPermutation(o),h=Ta({inputs:{x:c},backend:a,attrs:{perm:p}});return a.disposeIntermediateTensorInfo(c),a.disposeIntermediateTensorInfo(l),h}return c}function fY(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=n;return Yw(up.Prod,r,a,s,i,o)}var gY={kernelName:eo,backendName:"webgl",kernelFunc:fY};function yY(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=n;return Yw(up.Sum,r,a,s,i,o)}var xY={kernelName:to,backendName:"webgl",kernelFunc:yY};function AY(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),d=Nw(l,u,s.dtype,s.shape,i);return a.makeTensorInfo([i],s.dtype,d)}else if(r.shape.length===2){let l=a.bufferSync(r),u=a.bufferSync(s),d=vj(l,u,i,o);return a.makeTensorInfo(d.shape,s.dtype,d.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}var bY={kernelName:bu,backendName:"webgl",kernelFunc:AY},vY=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 wY(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],d=i==="NHWC"?r.shape[3]:r.shape[1],c=l*s,p=u*s,h=d/(s*s),m=i==="NHWC"?[o,c,p,h]:[o,h,c,p],f=new vY(m,s,i);return a.runWebGLProgram(f,[r],r.dtype)}var kY={kernelName:no,backendName:"webgl",kernelFunc:wY},Zw=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=ga(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 d=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;
|
|
${d}
|
|
${u}
|
|
setOutput(result);
|
|
}
|
|
`}},Jw=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=ga(this.outputShape.length);let s=e.outChannels/e.inChannels,i=e.padInfo.left,o=e.strideWidth,l=e.dilationWidth,u=e.filterHeight,d=e.filterWidth,c=d,p=`
|
|
int xR; int xC; int xCOffset;
|
|
vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<d;g++)p+=`
|
|
vec4 xTexelC${g*2};
|
|
int xTexelC${g*2}Ready;
|
|
vec4 xTexelC${g*2+1};
|
|
int xTexelC${g*2+1}Ready;
|
|
vec4 xC${g};`;p+=`
|
|
for (int r = 0; r < ${u}; r++) {
|
|
`;for(let g=0;g<d;g++)p+=`
|
|
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);`;p+=`
|
|
xR = xRCorner + r * dilations[0];
|
|
if (xR >=0 && xR < inDims[0]) {
|
|
`;for(let g=0;g<(c+1)/2;g++){let y=g*2;if(p+=`
|
|
xC = xCCorner + ${y*l};
|
|
`,o===1){if(y<d&&(i%2===1?(p+=`
|
|
xCOffset = xC + 1;
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${y}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
`,l===1&&y>0?p+=`
|
|
xC${y} = vec4(xTexelC${y-2}.zw, xTexelC${y}.xy);
|
|
`:p+=`
|
|
xCOffset = xC + 1 - 2;
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
previous = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
previous.zw = vec2(0.0);
|
|
}
|
|
|
|
xC${y} = vec4(previous.zw, xTexelC${y}.xy);
|
|
} else {
|
|
xC${y} = vec4(0.0, 0.0, xTexelC${y}.xy);
|
|
}
|
|
`):p+=`
|
|
if (xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${y}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
|
|
xC${y} = xTexelC${y};
|
|
`,y+1<d)){let x=i%2===0?v.nearestLargerEven(l):l;l%2===0&&i%2===1||l%2!==0&&i%2!==1?(p+=`
|
|
xCOffset = xC + imod(pads[1], 2) + ${x};
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
|
|
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${y+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y+1}Ready = 1;
|
|
}
|
|
`,l>1?p+=`
|
|
xCOffset -= 2;
|
|
if (xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
previous = getX(batch, xR, xCOffset, d1);
|
|
xC${y+1} = vec4(previous.zw, xTexelC${y+1}.xy);
|
|
} else {
|
|
xC${y+1} = vec4(0.0, 0.0, xTexelC${y+1}.xy);
|
|
}
|
|
`:p+=`
|
|
xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.xy);
|
|
`):x===1?p+=`
|
|
xC${y+1} = xTexelC${y};
|
|
`:p+=`
|
|
xCOffset = xC + ${x};
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
|
|
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${y+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y+1}Ready = 1;
|
|
}
|
|
|
|
xC${y+1} = xTexelC${y+1};
|
|
`}}else y<d&&(i%2===1?(p+=`
|
|
xCOffset = xC + 1 - strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = getX(batch, xR, xCOffset, d1);
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${y}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
|
|
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${y+1}Ready == 0) {
|
|
xTexelC${y+1} = getX(batch, xR, xC + 1, d1);
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xC + 2 >= inDims[1]) {
|
|
xTexelC${y+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y+1}Ready = 1;
|
|
}
|
|
|
|
xC${y} = vec4(xTexelC${y}.zw, xTexelC${y+1}.zw);
|
|
`,y+1<d&&(p+=`
|
|
final = vec4(0.0);
|
|
xCOffset = xC + 1 + strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
final = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
xC${y+1} = vec4(xTexelC${y+1}.xy, final.xy);
|
|
`)):(p+=`
|
|
if(xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${y}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
|
|
xCOffset = xC + strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
|
|
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${y+1}.zw = vec2(0.);
|
|
}
|
|
xTexelC${y+1}Ready = 1;
|
|
}
|
|
|
|
xC${y} = vec4(
|
|
xTexelC${y}.xy, xTexelC${y+1}.xy);
|
|
`,y+1<d&&(p+=`
|
|
xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.zw);
|
|
`)));y<d&&(p+=`
|
|
wTexel = getW(r, ${y}, d1, q);
|
|
dotProd += xC${y} * vec4(wTexel.xz, wTexel.xz);
|
|
`,y+1<d&&(p+=`
|
|
wTexel = getW(r, ${y+1}, d1, q);
|
|
dotProd += xC${y+1} * vec4(wTexel.xz, wTexel.xz);
|
|
`))}p+=`
|
|
}
|
|
`,p+=`
|
|
}
|
|
`;let h="",m="";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}
|
|
}`,m="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=`
|
|
${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);
|
|
|
|
${p}
|
|
|
|
vec4 result = dotProd - vec4(0.000000000000001);
|
|
${f}
|
|
${m}
|
|
setOutput(result);
|
|
}
|
|
`}};function IY(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=n,d=l;d==null&&(d=[1,1]),v.assert(I.eitherStridesOrDilationsAreOne(i,d),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${d}'`);let c=I.computeConv2DInfo(r.shape,s.shape,i,d,o,u,!0),p;B().getBool("WEBGL_PACK_DEPTHWISECONV")&&c.strideWidth<=2&&c.outChannels/c.inChannels===1?p=new Jw(c):p=new Zw(c);let h=[[c.padInfo.top,c.padInfo.left],[c.strideHeight,c.strideWidth],[c.dilationHeight,c.dilationWidth],[c.inHeight,c.inWidth]];return a.runWebGLProgram(p,[r,s],"float32",h)}var SY={kernelName:ro,backendName:"webgl",kernelFunc:IY},TY=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);
|
|
}
|
|
`}},CY=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 NY(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:d}=n,c=I.computeConv2DInfo(r.shape,d,i,o,l,u,!0),p=new TY(c);return a.runWebGLProgram(p,[r,s],"float32")}var RY={kernelName:vp,backendName:"webgl",kernelFunc:NY};function EY(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:d}=n,c=I.computeConv2DInfo(d,s.shape,i,o,l,u,!0),p=new CY(c);return a.runWebGLProgram(p,[r,s],"float32")}var MY={kernelName:wp,backendName:"webgl",kernelFunc:EY},FY=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 $Y(e){let{inputs:t,backend:a}=e,{x:n}=t,r=[...n.shape,...n.shape],s=v.sizeFromShape(n.shape),i=pe({inputs:{x:n},backend:a,attrs:{shape:[s]}}),o=new FY(s),l=a.runWebGLProgram(o,[i],i.dtype),u=pe({inputs:{x:l},backend:a,attrs:{shape:r}});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(l),u}var DY={kernelName:vu,backendName:"webgl",kernelFunc:$Y},PY=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:d,left:c}=n;this.userCode=`
|
|
const ivec2 strides = ivec2(${r}, ${s});
|
|
const ivec2 pads = ivec2(${d}, ${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 _Y(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=n,u=I.computeDilation2DInfo(r.shape,s.shape,i,o,"NHWC",l),d,c=new PY(u);d=a.runWebGLProgram(c,[r,s],"float32");let p=pe({inputs:{x:d},backend:a,attrs:{shape:u.outShape}});return a.disposeIntermediateTensorInfo(d),p}var OY={kernelName:so,backendName:"webgl",kernelFunc:_Y};function zY(e){let{inputs:t,backend:a,attrs:n}=e,{equation:r}=n,s=t,{allDims:i,summedDims:o,idDims:l}=I.decodeEinsumEquation(r,s.length);I.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:d}=I.getEinsumComputePath(o,l),c=d.length,p=null,h=i.length,m=[];for(let f=0;f<c;++f){for(let g of d[f]){let{permutationIndices:y,expandDims:x}=I.getEinsumPermutation(h,l[g]),A;I.isIdentityPermutation(y)?A=s[g]:(A=Ta({inputs:{x:s[g]},backend:a,attrs:{perm:y}}),m.push(A));let b=A.shape.slice();for(let w=0;w<x.length;++w)b.splice(x[w],0,1);v.arraysEqual(A.shape,b)||(A=pe({inputs:{x:A},backend:a,attrs:{shape:b}}),m.push(A)),p===null?p=A:(p=X3({inputs:{a:A,b:p},backend:a}),m.push(p))}f<c-1&&(u[f]>=0&&(p=c0({inputs:{x:p},backend:a,attrs:{axis:u[f]-(i.length-h),keepDims:!1}}),m.push(p)),h--)}for(let f of m)f!==p&&a.disposeIntermediateTensorInfo(f);return p}var LY={kernelName:Ip,backendName:"webgl",kernelFunc:zY},WY="return (x >= 0.0) ? x : (exp(x) - 1.0);",BY=`
|
|
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;
|
|
`,VY=tt({opSnippet:WY,packedOpSnippet:BY}),UY={kernelName:oo,backendName:"webgl",kernelFunc:VY},GY="return (b >= 0.0) ? a : a * (b + 1.0);",HY=`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,jY=e=>{let{inputs:t,backend:a}=e,{dy:n,y:r}=t,s=B().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new nd(HY,n.shape,r.shape):new Ei(GY,n.shape,r.shape);return a.runWebGLProgram(s,[n,r],n.dtype)},qY={kernelName:wu,backendName:"webgl",kernelFunc:jY},XY=`
|
|
return vec4(equal(a, b));
|
|
`,KY="return float(a == b);",YY=ha({opSnippet:KY,packedOpSnippet:XY,dtype:"bool",cpuKernelImpl:Tj}),ZY={kernelName:ms,backendName:"webgl",kernelFunc:YY},JY=`
|
|
// Error function is calculated approximately with elementary function.
|
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
float p = ${I.ERF_P};
|
|
float a1 = ${I.ERF_A1};
|
|
float a2 = ${I.ERF_A2};
|
|
float a3 = ${I.ERF_A3};
|
|
float a4 = ${I.ERF_A4};
|
|
float a5 = ${I.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));
|
|
`,QY=tt({opSnippet:JY}),eZ={kernelName:lo,backendName:"webgl",kernelFunc:QY},tZ=rd+`
|
|
return exp(x);
|
|
`,aZ=`
|
|
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;
|
|
`,Qw=tt({opSnippet:tZ,packedOpSnippet:aZ,cpuKernelImpl:Cj,dtype:"float32"}),nZ={kernelName:fs,backendName:"webgl",kernelFunc:Qw};function q1(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),pe({inputs:{x:s},backend:n,attrs:{shape:o}})}var rZ={kernelName:ku,backendName:"webgl",kernelFunc:q1},Q5="return exp(x) - 1.0;",sZ=tt({opSnippet:Q5,packedOpSnippet:Q5,cpuKernelImpl:Nj}),iZ={kernelName:gs,backendName:"webgl",kernelFunc:sZ},eA=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 e8(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=pe({inputs:{x:e},backend:a,attrs:{shape:[i,s]}}),l=o.shape,u=new eA("real",l,t),d=new eA("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}],p=a.runWebGLProgram(u,c,"float32"),h=a.runWebGLProgram(d,c,"float32"),m=zs({inputs:{real:p,imag:h},backend:a});a.disposeIntermediateTensorInfo(p),a.disposeIntermediateTensorInfo(h);let f=pe({inputs:{x:m},backend:a,attrs:{shape:e.shape}});return a.disposeIntermediateTensorInfo(o),a.disposeIntermediateTensorInfo(m),f}function oZ(e){let{inputs:t,backend:a}=e,{input:n}=t;return e8(n,!1,a)}var lZ={kernelName:Sp,backendName:"webgl",kernelFunc:oZ},uZ=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 ic(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 uZ(n,r),o=[[r]];return t.runWebGLProgram(i,[],s,o)}}var dZ={kernelName:Iu,backendName:"webgl",kernelFunc:ic},pZ=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);
|
|
}
|
|
`}},cZ={kernelName:uo,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:a}=e,n=t,r=new pZ(a.shape);return n.runWebGLProgram(r,[a],a.dtype)}},tA="return floor(x);",hZ=tt({opSnippet:tA,packedOpSnippet:tA,cpuKernelImpl:Rj}),mZ={kernelName:ys,backendName:"webgl",kernelFunc:hZ},fZ=`
|
|
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;
|
|
}
|
|
`,gZ=`
|
|
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);
|
|
`,yZ=ha({opSnippet:fZ,packedOpSnippet:gZ,dtype:"int32"}),xZ={kernelName:xs,backendName:"webgl",kernelFunc:yZ},AZ=class{constructor(e){this.variableNames=["A"];let t=Ra(),[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));
|
|
}
|
|
`}},bZ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=Ra(),[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;
|
|
}
|
|
`}},vZ={kernelName:jd,backendName:"webgl",kernelFunc:wZ},Bl,s1=B().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function wZ(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],d=[u,l],c=[u,l,s];if(o||i){let f=B().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(Bl==null||f!==s1)&&(s1=f,Bl=document.createElement("canvas").getContext("2d",{willReadFrequently:s1})),Bl.canvas.width=l,Bl.canvas.height=u,Bl.drawImage(r,0,0,l,u),r=Bl.canvas}let p=a.makeTensorInfo(d,"int32");a.texData.get(p.dataId).usage=gn.PIXELS,a.gpgpu.uploadPixelDataToTexture(a.getTexture(p.dataId),r);let h=B().getBool("WEBGL_PACK")?new bZ(c):new AZ(c),m=a.runWebGLProgram(h,[p],"int32");return a.disposeData(p.dataId),m}function kZ(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:d,dilations:c,dimRoundingMode:p,activation:h,leakyreluAlpha:m}=n,f=I.convertConv2DDataFormat(d),g=I.computeConv2DInfo(r.shape,s.shape,l,c,u,p,!1,f),y,x=[],A=i!=null,b=o!=null,w=h==="leakyrelu",S=()=>{let N=[r,s],M=(F,E)=>{if(E==="NCHW"&&F.shape.length===1&&F.shape[0]!==1){let T=pe({inputs:{x:F},backend:a,attrs:{shape:[F.shape[0],1,1]}});return x.push(T),T}return F};if(A&&N.push(M(i,d)),b&&N.push(M(o,d)),w){let F=a.makeTensorInfo([],"float32",v.createScalarValue(m,"float32"));N.push(F),x.push(F)}return N};if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))y=Xw({x:r,filter:s,convInfo:g,backend:a,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:m});else if(g.strideWidth<=2&&f==="channelsLast"&&B().getBool("WEBGL_EXP_CONV")){let N=h?op(h,!0):null,M=new qw(g,A,N,b,w),F=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],E=S();y=a.runWebGLProgram(M,E,"float32",F)}else if(B().getBool("WEBGL_CONV_IM2COL"))y=Kw({x:r,filter:s,convInfo:g,backend:a,bias:i,activation:h,preluActivationWeights:o,leakyreluAlpha:m});else{let N=h?op(h,!1):null,M=new jw(g,A,N,b,w),F=S();y=a.runWebGLProgram(M,F,"float32")}let C=pe({inputs:{x:y},backend:a,attrs:{shape:g.outShape}});return x.push(y),x.forEach(N=>a.disposeIntermediateTensorInfo(N)),C}var IZ={kernelName:as,backendName:"webgl",kernelFunc:kZ};function SZ(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:d,dimRoundingMode:c,activation:p,leakyreluAlpha:h}=n,m=[],f=d;f==null&&(f=[1,1]),v.assert(I.eitherStridesOrDilationsAreOne(l,f),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${f}'`);let g=I.computeConv2DInfo(r.shape,s.shape,l,f,u,c,!0),y=B().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,x=p?op(p,y):null,A=[r,s],b=i!=null,w=o!=null,S=p==="leakyrelu";if(b&&A.push(i),w&&A.push(o),S){let F=a.makeTensorInfo([],"float32",v.createScalarValue(h,"float32"));A.push(F),m.push(F)}let C;y?C=new Jw(g,b,x,w,S):C=new Zw(g,b,x,w,S);let N=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],M=a.runWebGLProgram(C,A,"float32",N);return m.forEach(F=>a.disposeIntermediateTensorInfo(F)),M}var TZ={kernelName:ns,backendName:"webgl",kernelFunc:SZ},CZ=class{constructor(e,t,a,n){this.sliceDim=e,this.strides=t,this.paramsShape=n,this.variableNames=["x","indices"],this.outputShape=a;let r=ft(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 NZ(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,d,c]=I.prepareAndValidate(n,r),p=pe({inputs:{x:r},backend:a,attrs:{shape:[u,i]}}),h=pe({inputs:{x:n},backend:a,attrs:{shape:[v.sizeFromShape(n.shape)/d,d]}});if(a.shouldExecuteOnCPU([n,r])||n.dtype==="string"){let y=a.readSync(r.dataId),x=a.bufferSync(n),A=Ej(y,x,n.dtype,u,i,d,c,n.shape,o);return a.makeTensorInfo(l,n.dtype,A.values)}let m=new CZ(i,c,[u,d],n.shape),f=a.runWebGLProgram(m,[h,p],h.dtype),g=pe({inputs:{x:f},backend:a,attrs:{shape:l}});return a.disposeIntermediateTensorInfo(p),a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(f),g}var RZ={kernelName:co,backendName:"webgl",kernelFunc:NZ},EZ=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let a=ft(this.rank),n=MZ(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 MZ(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 t8(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(B().get("DEBUG")){let x=a.readSync(s.dataId),A=r.shape[l];for(let b=0;b<x.length;++b){let w=x[b];v.assert(w<=A-1&&w>=0,()=>`GatherV2: the index value ${w} is not in [0, ${A-1}]`)}}let u=I.segment_util.collectGatherOpShapeInfo(r,s,l,o),d=v.sizeFromShape(s.shape),c=[],p=pe({inputs:{x:r},backend:a,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),h=pe({inputs:{x:s},backend:a,attrs:{shape:[u.batchSize,d/u.batchSize]}});c.push(p),c.push(h);let m=[u.batchSize,u.outerSize,d/u.batchSize,u.sliceSize];if(a.shouldExecuteOnCPU([r,s])||r.dtype==="string"){let x=a.bufferSync(h),A=a.bufferSync(p),b=Mj(A,x,m);return c.forEach(w=>a.disposeIntermediateTensorInfo(w)),a.makeTensorInfo(u.outputShape,b.dtype,b.values)}let f=new EZ(p.shape,m),g=a.runWebGLProgram(f,[p,h],p.dtype);c.push(g);let y=pe({inputs:{x:g},backend:a,attrs:{shape:u.outputShape}});return c.forEach(x=>a.disposeIntermediateTensorInfo(x)),y}var FZ={kernelName:Su,backendName:"webgl",kernelFunc:t8},$Z="return float(a > b);",DZ=`
|
|
return vec4(greaterThan(a, b));
|
|
`,PZ=ha({opSnippet:$Z,packedOpSnippet:DZ,cpuKernelImpl:Fj,dtype:"bool"}),_Z={kernelName:As,backendName:"webgl",kernelFunc:PZ},OZ="return float(a >= b);",zZ=`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,LZ=ha({opSnippet:OZ,packedOpSnippet:zZ,dtype:"bool",cpuKernelImpl:$j}),WZ={kernelName:bs,backendName:"webgl",kernelFunc:LZ};function BZ(e){let{inputs:t,backend:a}=e,{input:n}=t;return e8(n,!0,a)}var VZ={kernelName:Tp,backendName:"webgl",kernelFunc:BZ},UZ="return float(!isnan(x) && !isinf(x));",GZ=tt({opSnippet:UZ,dtype:"bool"}),HZ={kernelName:mo,backendName:"webgl",kernelFunc:GZ},jZ="return float(isinf(x));",qZ=tt({opSnippet:jZ,dtype:"bool"}),XZ={kernelName:fo,backendName:"webgl",kernelFunc:qZ},KZ="return float(isnan(x));",YZ=tt({opSnippet:KZ,dtype:"bool"}),ZZ={kernelName:go,backendName:"webgl",kernelFunc:YZ},JZ="return float(a < b);",QZ=`
|
|
return vec4(lessThan(a, b));
|
|
`,eJ=ha({opSnippet:JZ,packedOpSnippet:QZ,cpuKernelImpl:Dj,dtype:"bool"}),tJ={kernelName:vs,backendName:"webgl",kernelFunc:eJ},aJ="return float(a <= b);",nJ=`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,rJ=ha({opSnippet:aJ,packedOpSnippet:nJ,cpuKernelImpl:Pj,dtype:"bool"}),sJ={kernelName:ws,backendName:"webgl",kernelFunc:rJ};function iJ(e){let{backend:t,attrs:a}=e,{start:n,stop:r,num:s}=a,i=_j(n,r,s);return t.makeTensorInfo([i.length],"float32",i)}var oJ={kernelName:xo,backendName:"webgl",kernelFunc:iJ},lJ=rd+`
|
|
return x < 0.0 ? 0./0. : log(x);
|
|
`,uJ=`
|
|
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;
|
|
`,dJ=tt({opSnippet:lJ,packedOpSnippet:uJ,cpuKernelImpl:Oj}),pJ={kernelName:ks,backendName:"webgl",kernelFunc:dJ},cJ=rd+`
|
|
return log(1.0 + x);
|
|
`,hJ=tt({opSnippet:cJ}),mJ={kernelName:Ao,backendName:"webgl",kernelFunc:hJ},fJ="return float(a >= 1.0 && b >= 1.0);",gJ=`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,yJ=ha({opSnippet:fJ,packedOpSnippet:gJ,dtype:"bool"}),xJ={kernelName:bo,backendName:"webgl",kernelFunc:yJ},AJ="return float(!(x >= 1.0));",bJ=tt({opSnippet:AJ}),vJ={kernelName:vo,backendName:"webgl",kernelFunc:bJ},wJ="return float(a >= 1.0 || b >= 1.0);",kJ=`
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`,IJ=ha({opSnippet:wJ,packedOpSnippet:kJ,dtype:"bool"}),SJ={kernelName:wo,backendName:"webgl",kernelFunc:IJ},TJ=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);
|
|
}
|
|
`}},CJ=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);
|
|
}
|
|
`}},NJ=e=>{let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n,u=B().getBool("WEBGL_PACK_NORMALIZATION")?new CJ(r.shape,s,i,o,l):new TJ(r.shape,s,i,o,l);return a.runWebGLProgram(u,[r],r.dtype)},RJ={kernelName:ko,backendName:"webgl",kernelFunc:NJ},EJ=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);
|
|
}
|
|
`}},MJ=e=>{let{inputs:t,backend:a,attrs:n}=e,{x:r,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:d}=n,c=new EJ(r.shape,o,l,u,d);return a.runWebGLProgram(c,[r,s,i],r.dtype)},FJ={kernelName:Tu,backendName:"webgl",kernelFunc:MJ};function $J(e,t,a,n){let r=v.sizeFromShape(t),s=v.sizeFromShape(e.shape)/r,i=pe({inputs:{x:e},attrs:{shape:[s,r]},backend:n}),o=hl(i,e.dtype,"max",n),l=pe({inputs:{x:o},attrs:{shape:a},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}function a8(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,d=I.getAxesPermutation(u,o),c=d!=null,p=a.shouldExecuteOnCPU([r]),h=r;if(c){if(p){let x=a.texData.get(h.dataId).values,A=new Array(o);for(let S=0;S<A.length;S++)A[S]=r.shape[d[S]];let b=j3(x,r.shape,r.dtype,d,A);h=a.makeTensorInfo(A,r.dtype);let w=a.texData.get(h.dataId);w.values=b}else h=p0(r,d,a);u=I.getInnerMostAxes(u.length,o)}I.assertAxesAreInnerMostDims("max",u,o);let[m,f]=I.computeOutAndReduceShapes(h.shape,u),g=m;i&&(g=I.expandShapeToKeepDim(m,l));let y;if(p){let x=a.texData.get(h.dataId).values,A=zj(x,v.sizeFromShape(f),g,r.dtype);y=a.makeTensorInfo(g,r.dtype);let b=a.texData.get(y.dataId);b.values=A}else y=$J(h,f,g,a);return c&&a.disposeIntermediateTensorInfo(h),y}var DJ={kernelName:Io,backendName:"webgl",kernelFunc:a8},PJ=q3+`
|
|
return max(a, b);
|
|
`,_J=`
|
|
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);
|
|
`+cl+`
|
|
return result;
|
|
`,OJ=ha({opSnippet:PJ,packedOpSnippet:_J,cpuKernelImpl:Lj}),zJ={kernelName:Is,backendName:"webgl",kernelFunc:OJ};function LJ(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t;Ju(r,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1;v.assert(I.eitherStridesOrDilationsAreOne(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=I.computePool2DInfo(r.shape,s,i,u,o,l);if(d.filterWidth===1&&d.filterHeight===1&&v.arraysEqual(d.inShape,d.outShape))return tn({inputs:{x:r},backend:a});let c=new lp(d,"max",!1);return a.runWebGLProgram(c,[r],r.dtype)}var WJ={kernelName:So,backendName:"webgl",kernelFunc:LJ};function BJ(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dataFormat:l,dimRoundingMode:u}=n,d=[1,1,1],c=I.computePool3DInfo(r.shape,s,i,d,o,u,l),p=new K3(c,"max",!1);return a.runWebGLProgram(p,[r],r.dtype)}var VJ={kernelName:Cu,backendName:"webgl",kernelFunc:BJ},UJ=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);
|
|
}
|
|
`}},GJ=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,d=o-1-e.padInfo.front,c=l-1-e.padInfo.top,p=u-1-e.padInfo.left,h=o*l*u-1;this.userCode=`
|
|
const ivec3 pads = ivec3(${d}, ${c}, ${p});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
|
|
// dx(xD, xR, xC, ch).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int wD = 0; wD < ${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 HJ(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:d}=n,c=[1,1,1],p=I.computePool3DInfo(i.shape,o,l,c,u,d),h=new K3(p,"max",!0),m=a.runWebGLProgram(h,[i],i.dtype),f=new GJ(p),g=a.runWebGLProgram(f,[r,m],i.dtype);return a.disposeIntermediateTensorInfo(m),g}var jJ={kernelName:Rp,backendName:"webgl",kernelFunc:HJ};function qJ(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s,output:i}=t,o=s;Ju([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:d,dimRoundingMode:c}=n,p=I.computePool2DInfo(o.shape,l,u,1,d,c),h=!0,m=new lp(p,"max",h),f=a.runWebGLProgram(m,[o],o.dtype),g=new UJ(p),y=a.runWebGLProgram(g,[r,f],o.dtype);return a.disposeIntermediateTensorInfo(f),y}var XJ={kernelName:Np,backendName:"webgl",kernelFunc:qJ};function KJ(e,t,a,n){let r=new lp(a,"max",!1),s=n.runWebGLProgram(r,[e],"float32");r=new lp(a,"max",!0,!0,t);let i=n.runWebGLProgram(r,[e],"float32");return[s,i]}var YJ={kernelName:Nu,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(I.eitherStridesOrDilationsAreOne(s,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);let d=I.computePool2DInfo(n.shape,r,s,u,i),[c,p]=KJ(n,o,d,l);return[c,p]}};function ZJ(e,t,a,n){let r=v.sizeFromShape(t),s=v.sizeFromShape(e.shape)/r,i=pe({inputs:{x:e},attrs:{shape:[s,r]},backend:n}),o=hl(i,"float32","mean",n),l=pe({inputs:{x:o},attrs:{shape:a},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}var JJ={kernelName:To,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,d=I.getAxesPermutation(u,o),c=d!=null,p=i.shouldExecuteOnCPU([n]),h=[],m=n;if(c){if(p){let A=i.texData.get(m.dataId).values,b=new Array(o);for(let C=0;C<b.length;C++)b[C]=n.shape[d[C]];let w=j3(A,n.shape,n.dtype,d,b);m=i.makeTensorInfo(b,n.dtype);let S=i.texData.get(m.dataId);S.values=w}else m=p0(n,d,i);h.push(m),u=I.getInnerMostAxes(u.length,o)}I.assertAxesAreInnerMostDims("sum",u,o);let[f,g]=I.computeOutAndReduceShapes(m.shape,u),y=f;r&&(y=I.expandShapeToKeepDim(f,l));let x=ZJ(m,g,y,i);for(let A of h)i.disposeIntermediateTensorInfo(A);return x}};function QJ(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,d=I.getAxesPermutation(u,o),c=r;d!=null&&(c=Ta({inputs:{x:r},backend:a,attrs:{perm:d}}),u=I.getInnerMostAxes(u.length,r.shape.length)),I.assertAxesAreInnerMostDims("min",u,o);let[p,h]=I.computeOutAndReduceShapes(c.shape,u),m=v.sizeFromShape(h),f=pe({inputs:{x:c},backend:a,attrs:{shape:[-1,m]}}),g=hl(f,f.dtype,"min",a),y;if(i){let x=I.expandShapeToKeepDim(p,l);y=pe({inputs:{x:g},backend:a,attrs:{shape:x}})}else y=pe({inputs:{x:g},backend:a,attrs:{shape:p}});return a.disposeIntermediateTensorInfo(f),a.disposeIntermediateTensorInfo(g),d!=null&&a.disposeIntermediateTensorInfo(c),y}var eQ={kernelName:Co,backendName:"webgl",kernelFunc:QJ},tQ=q3+`
|
|
return min(a, b);
|
|
`,aQ=`
|
|
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);
|
|
`+cl+`
|
|
return result;
|
|
`,nQ=ha({opSnippet:tQ,packedOpSnippet:aQ,cpuKernelImpl:Wj}),rQ={kernelName:Ss,backendName:"webgl",kernelFunc:nQ},sQ=class{constructor(e,t,a){this.variableNames=["x"],this.outputShape=t.map((u,d)=>u[0]+e[d]+u[1]);let n=e.length,r=ft(n),s=t.map(u=>u[0]).join(","),i=t.map((u,d)=>u[0]+e[d]).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}));
|
|
}
|
|
`}},iQ=class{constructor(e,t,a){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,m)=>h[0]+e[m]+h[1]);let n=e.length,r=ft(n),s=t.map(h=>h[0]).join(","),i=t.map((h,m)=>h[0]+e[m]).join(","),o=ka("rc",n),l=ka("source",n),u=`${o[n-1]} < ${this.outputShape[n-1]}`,d=n===1?"source":`vec2(${l.slice(-2).join()})`,c=a==="reflect"?0:1,p="";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;
|
|
`;p=`
|
|
${r} rc = outputLoc;
|
|
${h}
|
|
result[0] = getChannel(getX(${l.join()}), ${d});
|
|
${o[n-1]} += 1;
|
|
if(${u}) {
|
|
${h}
|
|
result[1] = getChannel(getX(${l.join()}), ${d});
|
|
}
|
|
`}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;
|
|
`;p=`
|
|
${r} rc = outputLoc;
|
|
${h}
|
|
result[0] = getChannel(getX(${l.join()}), ${d});
|
|
${o[n-1]} += 1;
|
|
if(${u}) {
|
|
${h}
|
|
result[1] = getChannel(getX(${l.join()}), ${d});
|
|
}
|
|
rc = outputLoc;
|
|
${o[n-2]} += 1;
|
|
if(${o[n-2]} < ${this.outputShape[n-2]}) {
|
|
${h}
|
|
result[2] = getChannel(getX(${l.join()}), ${d});
|
|
${o[n-1]} += 1;
|
|
if(${u}) {
|
|
${h}
|
|
result[3] = getChannel(getX(${l.join()}), ${d});
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
const ${r} start = ${r}(${s});
|
|
const ${r} end = ${r}(${i});
|
|
|
|
void main() {
|
|
${r} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${p}
|
|
setOutput(result);
|
|
}
|
|
`}},oQ=({inputs:e,backend:t,attrs:a})=>{let{x:n}=e,{paddings:r,mode:s}=a,i=B().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new iQ(n.shape,r,s):new sQ(n.shape,r,s);return t.runWebGLProgram(i,[n],n.dtype)},lQ={kernelName:No,backendName:"webgl",kernelFunc:oQ},uQ=`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,dQ=`
|
|
vec4 result = mod(a, b);
|
|
bvec4 isNaN = equal(b, vec4(0.0));
|
|
`+cl+`
|
|
return result;
|
|
`,pQ=ha({opSnippet:uQ,packedOpSnippet:dQ}),cQ={kernelName:Ro,backendName:"webgl",kernelFunc:pQ},hQ=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}));
|
|
}
|
|
`}},mQ=`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,fQ=`
|
|
// 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;
|
|
`,n8=ha({opSnippet:mQ,packedOpSnippet:fQ,checkOutOfBounds:!0}),gQ={kernelName:io,backendName:"webgl",kernelFunc:n8},aA="return a - b;",r8=ha({opSnippet:aA,packedOpSnippet:aA,supportsComplex:!0,cpuKernelImpl:oq}),yQ={kernelName:Fs,backendName:"webgl",kernelFunc:r8};function s8(e){let{inputs:t,backend:a,attrs:n}=e,{logits:r}=t,{dim:s}=n,i=v.parseAxisParam([s],r.shape),o=a8({inputs:{x:r},backend:a,attrs:{reductionIndices:i,keepDims:!1}}),l=I.expandShapeToKeepDim(o.shape,i),u=pe({inputs:{x:o},backend:a,attrs:{shape:l}}),d=r8({inputs:{a:r,b:u},backend:a}),c=Qw({inputs:{x:d},backend:a}),p=c0({inputs:{x:c},backend:a,attrs:{axis:i,keepDims:!1}}),h=pe({inputs:{x:p},backend:a,attrs:{shape:l}}),m=n8({inputs:{a:c,b:h},backend:a});return a.disposeIntermediateTensorInfo(o),a.disposeIntermediateTensorInfo(u),a.disposeIntermediateTensorInfo(d),a.disposeIntermediateTensorInfo(c),a.disposeIntermediateTensorInfo(p),a.disposeIntermediateTensorInfo(h),m}var xQ={kernelName:el,backendName:"webgl",kernelFunc:s8};function AQ(e){let{inputs:t,backend:a,attrs:n}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=n,l=o?r:s8({inputs:{logits:r},backend:a,attrs:{dim:r.shape.length-1}}),u=l.shape[0],d=l.shape[1],c=new hQ(u,d,s),p=[[i]],h=a.runWebGLProgram(c,[l],"int32",p);return o||a.disposeIntermediateTensorInfo(l),h}var bQ={kernelName:Eo,backendName:"webgl",kernelFunc:AQ},vQ=$n+`
|
|
return -x;
|
|
`,wQ=`
|
|
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 kQ(e){let{inputs:t,backend:a}=e,{x:n}=t;if(a.shouldExecuteOnCPU([n])){let s=a.texData.get(n.dataId),[i,o]=Vj(s.values,n.shape,n.dtype);return a.makeTensorInfo(o,n.dtype,i)}let r;return B().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new Zr(n.shape,wQ):r=new Qn(n.shape,vQ),a.runWebGLProgram(r,[n],n.dtype)}var IQ={kernelName:Ru,backendName:"webgl",kernelFunc:kQ},SQ=Fn.nonMaxSuppressionV3Impl;function TQ(e){I.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),d=a.readSync(s.dataId),{selectedIndices:c}=SQ(u,d,i,o,l);return a.makeTensorInfo([c.length],"int32",new Int32Array(c))}var CQ={kernelName:Mo,backendName:"webgl",kernelFunc:TQ},NQ=Fn.nonMaxSuppressionV4Impl;function RQ(e){I.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,d=a.readSync(r.dataId),c=a.readSync(s.dataId),{selectedIndices:p,validOutputs:h}=NQ(d,c,i,o,l,u);return[a.makeTensorInfo([p.length],"int32",new Int32Array(p)),a.makeTensorInfo([],"int32",new Int32Array([h]))]}var EQ={kernelName:Eu,backendName:"webgl",kernelFunc:RQ},MQ=Fn.nonMaxSuppressionV5Impl;function FQ(e){I.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,d=a.readSync(r.dataId),c=a.readSync(s.dataId),p=i,h=o,m=l,f=u,{selectedIndices:g,selectedScores:y}=MQ(d,c,p,h,m,f);return[a.makeTensorInfo([g.length],"int32",new Int32Array(g)),a.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var $Q={kernelName:Fo,backendName:"webgl",kernelFunc:FQ},DQ=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)));
|
|
}
|
|
`}},PQ=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),d=new DQ(u,i,o,l),c=pe({inputs:{x:r},backend:a,attrs:{shape:[u]}}),p=a.runWebGLProgram(d,[c],s);a.disposeIntermediateTensorInfo(c);let h=[...r.shape,i],m=pe({inputs:{x:p},backend:a,attrs:{shape:h}});return a.disposeIntermediateTensorInfo(p),m},_Q={kernelName:$o,backendName:"webgl",kernelFunc:PQ};function Mh(e){let{inputs:t,backend:a}=e,{x:n}=t;if(n.dtype==="complex64"){let r=sc({inputs:{input:n},backend:a}),s=Mh({inputs:{x:r},backend:a}),i=h0({inputs:{input:n},backend:a}),o=Mh({inputs:{x:i},backend:a}),l=zs({inputs:{real:s,imag:o},backend:a});return a.disposeIntermediateTensorInfo(r),a.disposeIntermediateTensorInfo(s),a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}else return ic({attrs:{shape:n.shape,dtype:n.dtype,value:n.dtype==="string"?"":0},backend:a})}var OQ={kernelName:qu,backendName:"webgl",kernelFunc:Mh};function i8(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=sc({inputs:{input:n},backend:a}),s=i8({inputs:{x:r},backend:a}),i=h0({inputs:{input:n},backend:a}),o=Mh({inputs:{x:i},backend:a}),l=zs({inputs:{real:s,imag:o},backend:a});return a.disposeIntermediateTensorInfo(r),a.disposeIntermediateTensorInfo(s),a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}else return ic({attrs:{shape:n.shape,dtype:n.dtype,value:1},backend:a})}var zQ={kernelName:Mu,backendName:"webgl",kernelFunc:i8};function LQ(e){let{inputs:t,backend:a,attrs:n}=e,{axis:r}=n;if(t.length===1)return q1({inputs:{input:t[0]},backend:a,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(d=>{v.assertShapesMatch(s,d.shape,"All tensors passed to stack must have matching shapes"),v.assert(i===d.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(d=>{let c=q1({inputs:{input:d},backend:a,attrs:{dim:r}});return o.push(c),c}),u=Hw({inputs:l,backend:a,attrs:{axis:r}});return o.forEach(d=>a.disposeIntermediateTensorInfo(d)),u}var WQ={kernelName:Fu,backendName:"webgl",kernelFunc:LQ},BQ=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=ft(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}));
|
|
}
|
|
}
|
|
`}},VQ=class{constructor(e,t,a){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((m,f)=>m[0]+e[f]+m[1]);let n=e.length,r=ft(n),s=t.map(m=>m[0]).join(","),i=t.map((m,f)=>m[0]+e[f]).join(","),o=ka("rc",n),l=ka("source",n),u=`${o[n-1]} < ${this.outputShape[n-1]}`,d=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}) {`],p=n===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="";for(let m=0,f=n===1?2:4;m<f;m++)h+=`
|
|
${c[m]}
|
|
if (${p}) {
|
|
result[${m}] = float(value);
|
|
} else {
|
|
${r} source = rc - start;
|
|
result[${m}] = getChannel(getX(${l.join()}), ${d});
|
|
}
|
|
`;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);
|
|
}
|
|
`}},o8=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((d,c)=>d[0]+r.shape[c]+d[1]);return ic({backend:a,attrs:{shape:u,value:i,dtype:r.dtype}})}let o=B().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new VQ(r.shape,s,i):new BQ(r.shape,s,i),l=[[i]];return a.runWebGLProgram(o,[r],r.dtype,l)},UQ={kernelName:Do,backendName:"webgl",kernelFunc:o8},GQ=`
|
|
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);
|
|
`,HQ=`
|
|
// 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);
|
|
`+cl+`
|
|
return result;
|
|
`,jQ=ha({opSnippet:GQ,packedOpSnippet:HQ}),qQ={kernelName:Po,backendName:"webgl",kernelFunc:jQ};function XQ(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),d=u,c=I.getAxesPermutation(d,o),p=r;c!=null&&(p=Ta({inputs:{x:r},backend:a,attrs:{perm:c}}),d=I.getInnerMostAxes(d.length,o),l.push(p)),I.assertAxesAreInnerMostDims("prod",d,o);let h;if(a.shouldExecuteOnCPU([p])){let m=a.texData.get(p.dataId).values,{outVals:f,outShape:g,outDtype:y}=Gj(p.shape,p.dtype,m,d);h=a.makeTensorInfo(g,y,f)}else{let[m,f]=I.computeOutAndReduceShapes(p.shape,d),g=v.sizeFromShape(f),y=pe({inputs:{x:p},backend:a,attrs:{shape:[-1,g]}}),x=Lp(r.dtype),A=hl(y,x,"prod",a);h=pe({inputs:{x:A},backend:a,attrs:{shape:m}}),l.push(y),l.push(A)}if(i){l.push(h);let m=I.expandShapeToKeepDim(h.shape,u);h=pe({inputs:{x:h},backend:a,attrs:{shape:m}})}return l.forEach(m=>a.disposeIntermediateTensorInfo(m)),h}var KQ={kernelName:Oo,backendName:"webgl",kernelFunc:XQ};function YQ(e){let{inputs:t,backend:a,attrs:n}=e,{paramsNestedSplits:r,paramsDenseValues:s,indices:i}=t,{outputRaggedRank:o}=n,l=r.map(y=>a.readSync(y.dataId)),u=r.map(y=>y.shape),d=a.readSync(s.dataId),c=a.readSync(i.dataId),[p,h,m]=Hj(l,u,d,s.shape,s.dtype,c,i.shape,o),f=p.map(y=>a.makeTensorInfo([y.length],"int32",y)),g=a.makeTensorInfo(m,s.dtype,h);return f.concat([g])}var ZQ={kernelName:Lh,backendName:"webgl",kernelFunc:YQ};function JQ(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,d]=jj(i,n.shape,n.dtype,o,r.shape,l,s.shape),c=a.makeTensorInfo([u.length],"int32",u),p=a.makeTensorInfo([d.length],n.dtype,d);return[c,p]}var QQ={kernelName:Wh,backendName:"webgl",kernelFunc:JQ};function eee(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),d=a.readSync(s.dataId),c=a.readSync(i.dataId),p=o.map(g=>a.readSync(g.dataId)),h=o.map(g=>g.shape),[m,f]=qj(u,r.shape,d,s.shape,s.dtype,c,i.shape,p,h,l);return a.makeTensorInfo(m,s.dtype,f)}var tee={kernelName:Bh,backendName:"webgl",kernelFunc:eee},l8=e=>{let{backend:t,attrs:a}=e,{start:n,stop:r,step:s,dtype:i}=a,o=Xj(n,r,s,i);return t.makeTensorInfo([o.length],i,o)},aee={kernelName:$u,backendName:"webgl",kernelFunc:l8},nee="return 1.0 / x;",ree=tt({opSnippet:nee}),see={kernelName:zo,backendName:"webgl",kernelFunc:ree},iee=$n+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,oee=`
|
|
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;
|
|
`,lee=tt({opSnippet:iee,packedOpSnippet:oee}),uee={kernelName:Lo,backendName:"webgl",kernelFunc:lee},dee=$n+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,pee=`
|
|
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;
|
|
`,cee=tt({opSnippet:dee,packedOpSnippet:pee}),hee={kernelName:Vo,backendName:"webgl",kernelFunc:cee},mee=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],d=[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]/d[0]},
|
|
${u[1]/d[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);
|
|
}
|
|
`}},fee=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],d=[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]/d[0]},
|
|
${u[1]/d[1]},
|
|
${u[1]/d[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 gee(e){let{inputs:t,backend:a,attrs:n}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,d=B().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new fee(r.shape,l,u,s,i):new mee(r.shape,l,u,s,i);return a.runWebGLProgram(d,[r],"float32")}var yee={kernelName:Bo,backendName:"webgl",kernelFunc:gee},xee=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],d=o[1]/l[1],c=1/u,p=1/d,h=Math.ceil(c)*2+2,m=Math.ceil(p)*2+2;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float accumulator = 0.0;
|
|
|
|
const float heightScale = float(${u});
|
|
const float widthScale = float(${d});
|
|
|
|
const float invHeightScale = float(${c});
|
|
const float invWidthScale = float(${p});
|
|
|
|
const int winHeight = int(${h});
|
|
const int winWidth = int(${m});
|
|
|
|
// 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 Aee(e){let{inputs:t,backend:a,attrs:n}=e,{images:r,dy:s}=t,{alignCorners:i}=n,o=new xee(s.shape,r.shape,i);return a.runWebGLProgram(o,[s],s.dtype)}var bee={kernelName:_u,backendName:"webgl",kernelFunc:Aee},vee=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],d=[n&&t>1?t-1:t,n&&a>1?a-1:a],c=n?"0.5":"0.0",p;r?p="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${u[0]/d[0]},
|
|
${u[1]/d[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 = ${p};
|
|
|
|
// 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);
|
|
}
|
|
`}},wee=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],d=[n&&t>1?t-1:t,n&&a>1?a-1:a],c=n?"0.5":"0.0",p;r?p="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${u[0]/d[0]},
|
|
${u[1]/d[1]},
|
|
${u[1]/d[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 = ${p};
|
|
|
|
// 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 kee(e){let{inputs:t,backend:a,attrs:n}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,d=B().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new wee(r.shape,l,u,s,i):new vee(r.shape,l,u,s,i);return a.runWebGLProgram(d,[r],r.dtype)}var Iee={kernelName:Wo,backendName:"webgl",kernelFunc:kee},See=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],d=o[1]/l[1],c=1/u,p=1/d,h=Math.ceil(c)*2+2,m=Math.ceil(p)*2+2;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float accumulator = 0.0;
|
|
|
|
const float heightScale = float(${u});
|
|
const float widthScale = float(${d});
|
|
|
|
const float invHeightScale = float(${c});
|
|
const float invWidthScale = float(${p});
|
|
|
|
const int winHeight = int(${h});
|
|
const int winWidth = int(${m});
|
|
|
|
// 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 Tee(e){let{inputs:t,backend:a,attrs:n}=e,{images:r,dy:s}=t,{alignCorners:i}=n,o=new See(s.shape,r.shape,i);return a.runWebGLProgram(o,[s],s.dtype)}var Cee={kernelName:Pu,backendName:"webgl",kernelFunc:Tee},Nee=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=ft(a);this.userCode=`
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
setOutput(getX(${r}));
|
|
}
|
|
`}},Ree=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=ka("rc",a),r=`${n[a-1]} + 1 < ${this.outputShape[a-1]}`,s=`${n[a-2]} + 1 < ${this.outputShape[a-2]}`,i=ft(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 = ${d(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 d(h){return h[a-1]="("+h[a-1]+" + 1)",h[a-2]="("+h[a-2]+" + 1)",c(h)}function c(h){let m=e.map((y,x)=>p(x,h)),f=m.join(","),g=m.slice(-2).join(",");return`getChannel(getX(${f}), vec2(${g}))`}function p(h,m){return t.indexOf(h)!==-1&&e[h]!==1?`${e[h]} - ${m[h]} - 1`:`${m[h]}`}}};function Eee(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 tn({inputs:{x:r},backend:a});let l=B().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ree(r.shape,o):new Nee(r.shape,o);return a.runWebGLProgram(l,[r],r.dtype)}var Mee={kernelName:Uo,backendName:"webgl",kernelFunc:Eee},Fee=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);
|
|
}
|
|
`}},$ee={kernelName:ol,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:a})=>{let{image:n}=e,{radians:r,fillValue:s,center:i}=t,o=a,l=new Fee(n.shape,s),[u,d]=I.getImageCenter(i,n.shape[1],n.shape[2]),c=[[u,d,Math.sin(r),Math.cos(r)]];return o.runWebGLProgram(l,[n],n.dtype,c)}},Dee=`
|
|
// 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;
|
|
}
|
|
}
|
|
`,Pee=tt({opSnippet:Dee}),_ee={kernelName:Go,backendName:"webgl",kernelFunc:Pee},Oee="return inversesqrt(x);",zee=tt({opSnippet:Oee,cpuKernelImpl:Kj}),Lee={kernelName:Ns,backendName:"webgl",kernelFunc:zee},Y3=class{constructor(e,t,a,n,r,s,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;let l=ft(r.length),u=ft(s.length),d="";a===1?d="i":a===2&&(d="i, j");let c=`getIndices(${d})`,p="";n===1?p="i":n===2&&(p="i, coords[1]");let h=`getUpdates(${p})`,m="";o&&(m="coords[0], coords[1]");let f=`getDefaultValue(${m})`,g=t>1?"strides[j]":"strides";this.userCode=`
|
|
${l} strides = ${l}(${r});
|
|
|
|
void main() {
|
|
${u} coords = getOutputCoords();
|
|
float sum = 0.0;
|
|
bool found = false;
|
|
for (int i = 0; i < ${e}; i++) {
|
|
int flattenedIndex = 0;
|
|
for (int j = 0; j < ${t}; j++) {
|
|
int index = round(${c});
|
|
flattenedIndex += index * ${g};
|
|
}
|
|
if (flattenedIndex == coords[0]) {
|
|
sum += ${h};
|
|
found = true;
|
|
}
|
|
}
|
|
setOutput(mix(${f}, sum, float(found)));
|
|
}
|
|
`}},Wee=class{constructor(e,t,a,n,r,s,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=s;let l=ft(r.length),u=ft(s.length),d="";a===1?d="i":a===2&&(d="i, j");let c=`getIndices(${d})`,p="";n===1?p="i":n===2&&(p="i, coords[1]");let h=`getUpdates(${p})`,m="";o&&(m="coords[0], coords[1]");let f=`getDefaultValue(${m})`,g=t>1?"strides[j]":"strides",y=t>1?"strides[j + 1]":"strides";this.userCode=`
|
|
${l} strides = ${l}(${r});
|
|
|
|
void main() {
|
|
${u} coords = getOutputCoords();
|
|
vec4 sum = vec4(0.);
|
|
vec4 found = vec4(0.);
|
|
for (int i = 0; i < ${e}; i+=2) {
|
|
ivec2 flattenedIndex = ivec2(0);
|
|
for (int j = 0; j < ${t}; j+=2) {
|
|
ivec4 index = round(${c});
|
|
flattenedIndex += index.xz * ${g};
|
|
if (j + 1 < ${t}) {
|
|
flattenedIndex += index.yw * ${y};
|
|
}
|
|
}
|
|
if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] ||
|
|
flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) {
|
|
vec4 updVals = ${h};
|
|
if (flattenedIndex[0] == coords[0]) {
|
|
sum.xy += updVals.xy;
|
|
found.xy = vec2(1.);
|
|
} else if (flattenedIndex[0] == coords[0] + 1) {
|
|
sum.zw += updVals.xy;
|
|
found.zw = vec2(1.);
|
|
}
|
|
if (flattenedIndex[1] == coords[0]) {
|
|
sum.xy += updVals.zw;
|
|
found.xy = vec2(1.);
|
|
} else if (flattenedIndex[1] == coords[0] + 1) {
|
|
sum.zw += updVals.zw;
|
|
found.zw = vec2(1.);
|
|
}
|
|
}
|
|
}
|
|
setOutput(mix(${f}, sum, found));
|
|
}
|
|
`}};function Bee(e){let{inputs:t,backend:a,attrs:n}=e,{indices:r,updates:s}=t,{shape:i}=n,{sliceRank:o,numUpdates:l,sliceSize:u,strides:d,outputSize:c}=I.calculateShapes(s,r,i),p=[c/u,u];if(c===0)return a.makeTensorInfo(i,r.dtype);let h=pe({inputs:{x:r},backend:a,attrs:{shape:[l,o]}}),m=pe({inputs:{x:s},backend:a,attrs:{shape:[l,u]}}),f=a.makeTensorInfo([],"float32",new Float32Array([0])),g;B().getBool("WEBGL_PACK")?g=new Wee(l,o,h.shape.length,m.shape.length,d,p):g=new Y3(l,o,h.shape.length,m.shape.length,d,p);let y=a.runWebGLProgram(g,[m,h,f],m.dtype),x=pe({inputs:{x:y},backend:a,attrs:{shape:i}});return a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(m),a.disposeIntermediateTensorInfo(y),a.disposeIntermediateTensorInfo(f),x}var Vee={kernelName:Ho,backendName:"webgl",kernelFunc:Bee},Uee=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=B().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 Gee(e){let{inputs:t,backend:a,attrs:n}=e,{sortedSequence:r,values:s}=t,{side:i}=n,o=new Uee(r.shape[0],r.shape[1],s.shape[1],i),l=[[r.shape[1]]];return a.runWebGLProgram(o,[r,s],"int32",l)}var Hee={kernelName:qo,backendName:"webgl",kernelFunc:Gee},jee=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=ft(a);this.userCode=`
|
|
void main() {
|
|
${s} resRC = getOutputCoords();
|
|
float cVal = getC(${n});
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(${r}));
|
|
} else {
|
|
setOutput(getB(${r}));
|
|
}
|
|
}
|
|
`}};function qee(e){let{inputs:t,backend:a}=e,{condition:n,t:r,e:s}=t,i=new jee(n.shape.length,r.shape,r.shape.length);return a.runWebGLProgram(i,[n,r,s],Qt(r.dtype,s.dtype))}var Xee={kernelName:Ou,backendName:"webgl",kernelFunc:qee},Kee=`
|
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
|
// see: https://arxiv.org/abs/1706.02515
|
|
float scaleAlpha = ${I.SELU_SCALEALPHA};
|
|
float scale = ${I.SELU_SCALE};
|
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
|
`,Yee=tt({opSnippet:Kee}),Zee={kernelName:Xo,backendName:"webgl",kernelFunc:Yee},Jee=rd+`
|
|
return 1.0 / (1.0 + exp(-1.0 * x));
|
|
`,Qee=`
|
|
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;
|
|
`,ete=tt({opSnippet:Jee,packedOpSnippet:Qee,cpuKernelImpl:Zj}),tte={kernelName:Rs,backendName:"webgl",kernelFunc:ete},ate=`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`,nte=tt({opSnippet:ate}),rte={kernelName:Zo,backendName:"webgl",kernelFunc:nte},ste=rd+`
|
|
return sin(x);
|
|
`,ite=`
|
|
vec4 result = sin(x);
|
|
bvec4 isNaN = isnan(x);
|
|
${cl}
|
|
return result;
|
|
`,ote=tt({opSnippet:ste,packedOpSnippet:ite}),lte={kernelName:Ko,backendName:"webgl",kernelFunc:ote},ute=`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,dte=tt({opSnippet:ute}),pte={kernelName:Yo,backendName:"webgl",kernelFunc:dte},cte=`
|
|
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;
|
|
`,hte=tt({opSnippet:cte}),mte={kernelName:Jo,backendName:"webgl",kernelFunc:hte},fte=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((y,x)=>y*x),l=[[0,0]];l.push(...i);for(let y=1+s.length;y<r.shape.length;++y)l.push([0,0]);let u=[],d=o8({inputs:{x:r},backend:a,attrs:{paddings:l,constantValue:0}}),c=I.getReshaped(d.shape,s,o,!1),p=I.getPermuted(c.length,s.length,!1),h=I.getReshapedPermuted(d.shape,s,o,!1),m=pe({inputs:{x:d},backend:a,attrs:{shape:c}}),f=Ta({inputs:{x:m},backend:a,attrs:{perm:p}}),g=pe({inputs:{x:f},backend:a,attrs:{shape:h}});return u.push(d),u.push(m),u.push(f),u.forEach(y=>a.disposeIntermediateTensorInfo(y)),g},gte={kernelName:Lu,backendName:"webgl",kernelFunc:fte};function yte(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),d=a.readSync(i.dataId)[0],[c,p,h,m,f]=Qj(o,n.shape,n.dtype,l,r.dtype,u,d);return[a.makeTensorInfo(p,n.dtype,c),a.makeTensorInfo([p[0]],r.dtype,h),a.makeTensorInfo([m.length],"bool",new Uint8Array(m.map(g=>Number(g)))),a.makeTensorInfo([f.length],n.dtype,new Int32Array(f))]}var xte={kernelName:Mp,backendName:"webgl",kernelFunc:yte};function Ate(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,d,c]=eq(o,n.shape,n.dtype,i,l);return[a.makeTensorInfo(d,n.dtype,u),a.makeTensorInfo([c.length],s.dtype,new Int32Array(c))]}var bte={kernelName:Bu,backendName:"webgl",kernelFunc:Ate};function vte(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,d]=Ew(i,n.shape,n.dtype,o,l,!0);return a.makeTensorInfo(d,n.dtype,u)}var wte={kernelName:Vu,backendName:"webgl",kernelFunc:vte};function kte(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,d]=Ew(i,n.shape,n.dtype,o,l);return a.makeTensorInfo(d,n.dtype,u)}var Ite={kernelName:Uu,backendName:"webgl",kernelFunc:kte};function Ste(e){let{inputs:t,backend:a,attrs:n}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=n,{sliceRank:l,numUpdates:u,sliceSize:d,strides:c,outputSize:p}=I.calculateShapes(s,r,o),h=!1;if(s.dtype==="string"){let y=a.bufferSync(r),x=a.bufferSync(s),A=v.decodeString(a.readSync(i.dataId)[0]),b=Yj(y,x,o,p,d,u,l,c,A,h);return a.makeTensorInfo(o,b.dtype,b.values)}let m=new Y3(u,l,r.shape.length,s.shape.length,c,[p,1],h),f=a.runWebGLProgram(m,[s,r,i],s.dtype),g=pe({inputs:{x:f},backend:a,attrs:{shape:o}});return a.disposeIntermediateTensorInfo(f),g}var Tte={kernelName:tl,backendName:"webgl",kernelFunc:Ste};function Cte(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=I.prepareSplitSize(r,s,o),u=r.shape.length,d=new Array(u).fill(0),c=r.shape.slice();return l.map(p=>{let h=[...c];h[o]=p;let m=sd({inputs:{x:r},backend:a,attrs:{begin:d,size:h}});return d[o]+=p,m})}var Nte={kernelName:Wu,backendName:"webgl",kernelFunc:Cte},nA="return sqrt(x);",Rte=tt({opSnippet:nA,packedOpSnippet:nA,cpuKernelImpl:tq}),Ete={kernelName:Es,backendName:"webgl",kernelFunc:Rte},Mte="return x * x;",Fte=tt({opSnippet:Mte}),$te={kernelName:Fp,backendName:"webgl",kernelFunc:Fte},rA="return (a - b) * (a - b);",Dte=ha({opSnippet:rA,packedOpSnippet:rA}),Pte={kernelName:Ms,backendName:"webgl",kernelFunc:Dte};function _te(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t;if(r.dtype!=="string")throw new Error("Input must be of datatype string");let s=a.readSync(r.dataId),i=I.fromUint8ToStringArray(s),o=aq(i,"string",n);return a.makeTensorInfo(r.shape,"string",o)}var Ote={kernelName:Gu,backendName:"webgl",kernelFunc:_te};function zte({inputs:e,attrs:t,backend:a}){let{x:n}=e,r=$n+`
|
|
return x > 0.0 ? 1.0 : float(${t.alpha});
|
|
`,s=new Qn(n.shape,r);return a.runWebGLProgram(s,[n],n.dtype)}var Lte={kernelName:Ds,backendName:"webgl",kernelFunc:zte},Wte=class{constructor(e,t,a){this.variableNames=["x"],this.outputShape=a;let n=a.length,r=ft(a.length),s=ft(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 Bte(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:d,newAxisMask:c,shrinkAxisMask:p}=n,{finalShapeSparse:h,finalShape:m,isIdentity:f,sliceDim0:g,isSimpleSlice:y,begin:x,end:A,strides:b}=wt.sliceInfo(r.shape,s,i,o,l,u,d,c,p),w;if(f)w=pe({inputs:{x:r},backend:a,attrs:{shape:m}});else if(g||y){v.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let C=wt.computeOutShape(x,A,b),N=sd({inputs:{x:r},backend:a,attrs:{begin:x,size:C}});w=pe({inputs:{x:N},backend:a,attrs:{shape:m}}),a.disposeIntermediateTensorInfo(N)}else if(a.shouldExecuteOnCPU([r])){let C=a.readSync(r.dataId),N=Te(r.shape,r.dtype,C),M=nq(h,N,b,x);w=a.makeTensorInfo(m,r.dtype,M.values)}else{let C=new Wte(x,b,h);w=a.runWebGLProgram(C,[r],r.dtype)}let S=pe({inputs:{x:w},backend:a,attrs:{shape:m}});return a.disposeIntermediateTensorInfo(w),S}var Vte={kernelName:al,backendName:"webgl",kernelFunc:Bte};function Ute(e){let{inputs:t,backend:a,attrs:n}=e,{separator:r,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=n,{data:d,dataSplits:c}=t,p=a.readSync(d.dataId),h=a.readSync(c.dataId),[m,f]=rq(p,h,r,s,i,o,l,u);return[a.makeTensorInfo([m.length],"string",m),a.makeTensorInfo(c.shape,"int32",f)]}var Gte={kernelName:Hu,backendName:"webgl",kernelFunc:Ute};function Hte(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,d,c]=sq(o,l,r),p=d.length;return[a.makeTensorInfo([p,2],"int32",u),a.makeTensorInfo([p],"string",d),a.makeTensorInfo([2],"int32",new Int32Array(c))]}var jte={kernelName:$p,backendName:"webgl",kernelFunc:Hte};function qte(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=iq(i,r);return a.makeTensorInfo(s.shape,"int32",o)}var Xte={kernelName:Dp,backendName:"webgl",kernelFunc:qte},Kte="return tan(x);",Yte=tt({opSnippet:Kte}),Zte={kernelName:nl,backendName:"webgl",kernelFunc:Yte},Jte=`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,Qte=tt({opSnippet:Jte}),eae={kernelName:rl,backendName:"webgl",kernelFunc:Qte};function tae(e){let{inputs:t,backend:a,attrs:n}=e,{tensor:r,indices:s,updates:i}=t,{}=n,{sliceRank:o,numUpdates:l,sliceSize:u,strides:d,outputSize:c}=I.calculateShapes(i,s,r.shape),p=[c/u,u];if(c===0)return a.makeTensorInfo(r.shape,s.dtype);let h=pe({inputs:{x:s},backend:a,attrs:{shape:[l,o]}}),m=pe({inputs:{x:i},backend:a,attrs:{shape:[l,u]}}),f=pe({inputs:{x:r},backend:a,attrs:{shape:p}}),g=new Y3(l,o,h.shape.length,m.shape.length,d,p,!1,!0),y=a.runWebGLProgram(g,[m,h,f],f.dtype),x=pe({inputs:{x:y},backend:a,attrs:{shape:r.shape}});return a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(m),a.disposeIntermediateTensorInfo(f),a.disposeIntermediateTensorInfo(y),x}var aae={kernelName:jo,backendName:"webgl",kernelFunc:tae},nae=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=ft(this.rank),r=rae(e);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${r}));
|
|
}
|
|
`}};function rae(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 u8(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=Te(r.shape,r.dtype,l),d=lq(u,s);return a.makeTensorInfo(d.shape,d.dtype,d.values)}let i=new nae(r.shape,s);return a.runWebGLProgram(i,[r],r.dtype)}var sae={kernelName:$s,backendName:"webgl",kernelFunc:u8},iae=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));
|
|
}
|
|
}
|
|
`}},oae=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 ui(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function sA(e){let t=1;for(;t<e;)t*=2;return t}function lae(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{k:s,sorted:i}=n,o=B().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),l=B().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),u=r.shape,d=u[u.length-1];if(a.shouldExecuteOnCPU([r])||d<o||s>l){let M=a.readSync(r.dataId),[F,E]=uq(M,u,r.dtype,s,i);return[a.makeTensorInfo(F.shape,F.dtype,F.values),a.makeTensorInfo(E.shape,E.dtype,E.values)]}if(s===0)return u[u.length-1]=0,[a.makeTensorInfo(u,r.dtype,[]),a.makeTensorInfo(u,"int32",[])];if(d===1)return[r,ic({attrs:{shape:u,dtype:"int32",value:0},backend:a})];let c=a.texData.get(r.dataId),p=c!==null&&c.isPacked,h=p?a.unpackTensor(r):r,m=v.sizeFromShape(u)/d,f=pe({inputs:{x:h},attrs:{shape:[m,d]},backend:a});p&&ui(a,h);let g=sA(s),y=sA(d),x=null,A=()=>x===null?[f,f]:[f,x],b=(M,F,E)=>{let T=A(),D=new iae(E),O=[[d],[x===null?1:0],[Number.NEGATIVE_INFINITY],[M],[F]],W=x;x=a.runWebGLProgram(D,T,"int32",O),ui(a,W)};for(let M=1;M<g;M*=2){let F=M*2;for(let E=M;E>=1;E/=2)b(F,E,[m,y])}for(let M=y;M>g;M/=2){let F=A(),E=new oae([m,M/2]),T=[[d],[x===null?1:0],[g]],D=x;x=a.runWebGLProgram(E,F,"int32",T),ui(a,D);let O=g/2,W=O*2;for(let $=O;$>=1;$/=2)b(W,$,x.shape)}let w=x;x=sd({inputs:{x},backend:a,attrs:{begin:0,size:[m,s]}}),ui(a,w);let S=t8({inputs:{x:f,indices:x},backend:a,attrs:{axis:1,batchDims:1}});ui(a,f);let C=u.slice(0,-1);C.push(s),w=x,x=pe({inputs:{x},attrs:{shape:C},backend:a}),ui(a,w);let N=S;return S=pe({inputs:{x:S},attrs:{shape:C},backend:a}),ui(a,N),[S,x]}var uae={kernelName:sl,backendName:"webgl",kernelFunc:lae},dae=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 pae(e){let{inputs:t,backend:a,attrs:n}=e,{image:r,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=n,[d,c,p,h]=r.shape,[m,f]=u!=null?u:[c,p],g=[d,m,f,h],y=new dae(c,p,i,o,l,g);return a.runWebGLProgram(y,[r,s],"float32")}var cae={kernelName:il,backendName:"webgl",kernelFunc:pae};function hae(e){let{inputs:t,attrs:a,backend:n}=e,{axis:r}=a,{x:s}=t;Ju(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}=dq(i,r,s.shape,s.dtype);return[n.makeTensorInfo(l,s.dtype,o),n.makeTensorInfo([u.length],"int32",u)]}var mae={kernelName:Pp,backendName:"webgl",kernelFunc:hae};function fae(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),d=0;for(let f=0;f<o;f++)f!==s&&(u[d++]=i.shape[f]);let c=[],p=new Array(o).fill(0),h=i.shape.slice();h[s]=1;let m=new Array(l);for(let f=0;f<m.length;f++){p[s]=f;let g=sd({inputs:{x:i},backend:a,attrs:{begin:p,size:h}}),y=pe({inputs:{x:g},backend:a,attrs:{shape:u}});m[f]=y,c.push(g)}return c.forEach(f=>a.disposeIntermediateTensorInfo(f)),m}var gae={kernelName:ju,backendName:"webgl",kernelFunc:fae},yae=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,d=a%4,c=`
|
|
sumValue += dot(values, segFilter);
|
|
`,p="";r%a>0&&(p=`
|
|
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) {
|
|
${p}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
float getSegmentIdAtIndex(int inIdx) {
|
|
${h}
|
|
return getSegmentIds(inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = int(floor(float(outIdx) / float(
|
|
${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 (${d===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 (${d===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 (${d===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 xae(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,segmentIds:s}=t,{numSegments:i}=n,o=r.shape.length,l=[],u=0,d=I.getAxesPermutation([u],o),c=r;d!=null&&(c=Ta({inputs:{x:r},backend:a,attrs:{perm:d}}),l.push(c),u=I.getInnerMostAxes(1,o)[0]);let p=I.segment_util.computeOutShape(c.shape,u,i),h=v.sizeFromShape([c.shape[u]]),m=pe({inputs:{x:c},backend:a,attrs:{shape:[-1,h]}});l.push(m);let f=Lp(r.dtype),g=(b,w,S,C,N)=>{let M=b.shape[0],F=b.shape[1],E=I.segment_util.segOpComputeOptimalWindowSize(F,N),T={windowSize:E,inSize:F,batchSize:M,numSegments:N},D=new yae(T,w),O=a.compileAndRun(D,[b,S],C);if(l.push(O),O.shape[1]===N)return O;let W=l8({backend:a,attrs:{start:0,stop:N,step:1,dtype:"float32"}}),$=u8({inputs:{x:W},backend:a,attrs:{reps:[F/E]}});return l.push(W),l.push($),g(O,w,$,C,N)},y=g(m,"unsortedSegmentSum",s,f,i),x=pe({inputs:{x:y},backend:a,attrs:{shape:p}}),A=x;if(d!=null){l.push(x);let b=I.getUndoAxesPermutation(d);A=Ta({inputs:{x:A},backend:a,attrs:{perm:b}})}return l.forEach(b=>a.disposeIntermediateTensorInfo(b)),A}var Aae={kernelName:_p,backendName:"webgl",kernelFunc:xae},bae=[nX,sX,lX,pX,hX,gX,xX,bX,IX,TX,RX,FX,PX,LX,VX,GX,jX,YX,JX,eK,rK,pK,hK,yK,AK,SK,CK,MK,Wq,DK,LK,UK,KK,JK,eY,aY,rY,lY,pY,mY,gY,xY,bY,kY,SY,RY,MY,DY,OY,LY,UY,qY,ZY,eZ,nZ,rZ,iZ,lZ,dZ,cZ,mZ,xZ,vZ,IZ,TZ,RZ,FZ,_Z,WZ,Lq,VZ,OK,HZ,XZ,ZZ,Vq,tJ,sJ,oJ,pJ,mJ,xJ,vJ,SJ,RJ,FJ,DJ,zJ,WJ,VJ,jJ,XJ,YJ,JJ,eQ,rQ,lQ,cQ,bQ,Hq,IQ,CQ,EQ,$Q,vK,_Q,zQ,WQ,UQ,qQ,Gq,KQ,ZQ,QQ,tee,aee,wK,gQ,see,uee,hee,qq,yee,bee,Iee,Cee,Mee,$ee,_ee,Lee,Vee,Hee,Xee,Zee,tte,rte,lte,pte,uK,xQ,mte,gte,xte,bte,wte,Ite,Tte,Nte,Ete,$te,Pte,Ote,Lte,Vte,Gte,jte,Xte,yQ,eX,Zte,eae,aae,sae,uae,cae,tX,mae,gae,Aae,OQ];for(let e of bae)bn(e);var nt;(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"})(nt||(nt={}));var dp;(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"})(dp||(dp={}));var d8;function vae(e){d8=e.wasm.cwrap(ts,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function wae(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:d,leakyreluAlpha:c}=n,p=a.dataIdMap.get(r.dataId).id,h=a.dataIdMap.get(s.dataId).id,m=0;if(i!=null){let N=a.dataIdMap.get(i.dataId);if(N.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${N.shape.length}.`);m=N.id}let f=o==null?0:a.dataIdMap.get(o.dataId).id,g=dp[d];if(g==null)throw new Error(`${d} activation not yet supported for FusedConv2D in the wasm backend.`);let y=l?r.shape[2]:r.shape[1],x=u?s.shape[1]:s.shape[2],A=ul.assertAndGetBroadcastShape(r.shape.slice(0,-2),s.shape.slice(0,-2)),b=a.makeOutput([...A,y,x],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 d8(p,S,r.shape.length,h,C,s.shape.length,l,u,g,m,f,c||0,w),b}var kae={kernelName:ts,backendName:"wasm",setupFunc:vae,kernelFunc:wae};function Qe(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),d=i.dataIdMap.get(u.dataId).id;return v.sizeFromShape(u.shape)===0||a(l,nt[o.dtype],d),u}return{kernelName:e,backendName:"wasm",setupFunc:n,kernelFunc:r}}var Iae=Qe(cu),Sae=Qe($i),Tae=Qe(Di);function Gt(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:d}=l,c=o.dataIdMap.get(u.dataId).id,p=o.dataIdMap.get(d.dataId).id,h=a!=null?a:u.dtype,m=I.assertAndGetBroadcastShape(u.shape,d.shape),f=o.makeOutput(m,h);if(v.sizeFromShape(m)===0)return f;let g=new Uint8Array(new Int32Array(u.shape).buffer),y=new Uint8Array(new Int32Array(d.shape).buffer),x=o.dataIdMap.get(f.dataId).id;return n(c,g,u.shape.length,p,y,d.shape.length,nt[u.dtype],x),f}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:s}}var Cae=!0,Nae=Gt(Mr,Cae),p8;function Rae(e){p8=e.wasm.cwrap(Pi,null,["array","number","number","number"])}function Eae(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 p8(s,r.length,nt[n.dtype],i),n}var Mae={kernelName:Pi,backendName:"wasm",setupFunc:Rae,kernelFunc:Eae};function m0(e){let{inputs:{x:t},backend:a}=e;if(t.dtype==="string")return Ve(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 Fae={kernelName:ho,backendName:"wasm",kernelFunc:m0},c8;function $ae(e){c8=e.wasm.cwrap(Tr,null,["number","array","number","number","number","array","number"])}function ps(e){let{inputs:t,backend:a,attrs:n}=e,[r,s]=Pae(t.x.shape,n.perm),i=!0;for(let m=0;m<s.length;m++)s[m]!==m&&(i=!1);let o=Dae(t.x.shape,n.perm),l={dataId:t.x.dataId,shape:r,dtype:t.x.dtype};if(i){let m=m0({inputs:t,backend:a});return m.shape=o,m}let u=a.makeOutput(o,l.dtype),d=a.dataIdMap.get(l.dataId).id,c=a.dataIdMap.get(u.dataId).id,p=new Uint8Array(new Int32Array(s).buffer),h=new Uint8Array(new Int32Array(l.shape).buffer);return c8(d,h,l.shape.length,nt[l.dtype],c,p,s.length),u}function Dae(e,t){let a=new Array(e.length);for(let n=0;n<a.length;n++)a[n]=e[t[n]];return a}function Pae(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 _ae={kernelName:Tr,backendName:"wasm",kernelFunc:ps,setupFunc:$ae};function Ls(e,t,a){let n=e.shape,r=e.shape.length,s=v.parseAxisParam(t,n),i=s,o=I.getAxesPermutation(i,r),l=null,u=!1;if(o!=null){let d=new Array(r);for(let p=0;p<d.length;p++)d[p]=n[o[p]];i=I.getInnerMostAxes(i.length,r),l=ps({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 h8;function Oae(e){h8=e.wasm.cwrap(_i,null,["number, number, number"])}function zae(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:d,originalAxes:c,inputWasTransposed:p}=Ls(i,r,t);if(p){let x=t.dataIdMap.get(u.dataId).id;l=u,o=x}let h=l.shape.length;I.assertAxesAreInnerMostDims("all",d,h);let[m,f]=I.computeOutAndReduceShapes(l.shape,d),g=v.sizeFromShape(f),y=t.makeOutput(m,i.dtype);if(v.sizeFromShape(l.shape)!==0){let x=t.dataIdMap.get(y.dataId).id;h8(o,g,x)}if(p&&t.disposeData(u.dataId),s){let x=I.expandShapeToKeepDim(y.shape,c);y.shape=x}return y}var Lae={kernelName:_i,backendName:"wasm",setupFunc:Oae,kernelFunc:zae},m8;function Wae(e){m8=e.wasm.cwrap(Oi,null,["number, number, number"])}function Bae(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:d,originalAxes:c,inputWasTransposed:p}=Ls(i,r,t);if(p){let x=t.dataIdMap.get(u.dataId).id;l=u,o=x}let h=l.shape.length;I.assertAxesAreInnerMostDims("any",d,h);let[m,f]=I.computeOutAndReduceShapes(l.shape,d),g=v.sizeFromShape(f),y=t.makeOutput(m,i.dtype);if(v.sizeFromShape(l.shape)!==0){let x=t.dataIdMap.get(y.dataId).id;m8(o,g,x)}if(p&&t.disposeData(u.dataId),s){let x=I.expandShapeToKeepDim(y.shape,c);y.shape=x}return y}var Vae={kernelName:Oi,backendName:"wasm",setupFunc:Wae,kernelFunc:Bae};function f8(e){let t;function a(r){t=r.wasm.cwrap(e,null,["number","number","number","number","number"])}function n(r){let{backend:s,inputs:i,attrs:o}=r,{axis:l}=o,{x:u}=i,d=s.dataIdMap.get(u.dataId).id,c=d,p=u,{transposed:h,axes:m,inputWasTransposed:f}=Ls(u,l,s);if(f){let w=s.dataIdMap.get(h.dataId).id;w!==d&&(p=h,c=w)}let g=p.shape.slice(0,-1),y=s.makeOutput(g,"int32"),x=s.dataIdMap.get(y.dataId).id,A=v.sizeFromShape(y.shape),b=p.shape[m[0]];return t(c,nt[p.dtype],A,b,x),f&&s.disposeData(h.dataId),y}return{kernelName:e,backendName:"wasm",setupFunc:a,kernelFunc:n}}var Uae=f8(hu),Gae=f8(mu),Hae=Qe(zi),jae=Qe(Li),qae=Qe(Wi),Xae=Gt(Vi,!1),Kae=Qe(Bi),g8;function Yae(e){g8=e.wasm.cwrap(Ui,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Zae(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,d=I.computePool2DInfo(r.shape,i,o,1,l,u),c=d.filterHeight,p=d.filterWidth,h=d.padInfo.top,m=d.padInfo.right,f=d.padInfo.bottom,g=d.padInfo.left,y=d.strideHeight,x=d.strideWidth,A=d.inChannels;if(d.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);if(d.dilationWidth!==1||d.dilationHeight!==1)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${d.dilationHeight}, ${d.dilationWidth}].`);let b=n.makeOutput(d.outShape,"float32"),w=n.dataIdMap.get(b.dataId).id;return g8(s,r.shape[0],r.shape[1],r.shape[2],c,p,h,m,f,g,y,x,A,w),b}var Jae={kernelName:Ui,backendName:"wasm",setupFunc:Yae,kernelFunc:Zae},y8;function Qae(e){y8=e.wasm.cwrap("AvgPool3D",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function ene(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=n,d=I.computePool3DInfo(r.shape,s,i,1,o,l,u),c=a.makeOutput(d.outShape,r.dtype);return y8(a.dataIdMap.get(r.dataId).id,a.dataIdMap.get(c.dataId).id,d.batchSize,d.inChannels,d.inDepth,d.inHeight,d.inWidth,d.outDepth,d.outHeight,d.outWidth,d.strideDepth,d.strideHeight,d.strideWidth,d.dilationDepth,d.dilationHeight,d.dilationWidth,d.effectiveFilterDepth,d.effectiveFilterHeight,d.effectiveFilterWidth,d.padInfo.front,d.padInfo.top,d.padInfo.left),c}var tne={kernelName:fu,backendName:"wasm",setupFunc:Qae,kernelFunc:ene},x8;function ane(e){x8=e.wasm.cwrap("AvgPool3DGrad",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"])}function nne(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=n,d=I.computePool3DInfo(s.shape,i,o,1,l,u),c=a.makeOutput(s.shape,s.dtype);return x8(a.dataIdMap.get(r.dataId).id,a.dataIdMap.get(c.dataId).id,d.batchSize,d.inChannels,d.inDepth,d.inHeight,d.inWidth,d.outDepth,d.outHeight,d.outWidth,d.strideDepth,d.strideHeight,d.strideWidth,d.dilationDepth,d.dilationHeight,d.dilationWidth,d.effectiveFilterDepth,d.effectiveFilterHeight,d.effectiveFilterWidth,d.padInfo.front,d.padInfo.top,d.padInfo.left,d.filterDepth,d.filterHeight,d.filterWidth),c}var rne={kernelName:yp,backendName:"wasm",setupFunc:ane,kernelFunc:nne},A8;function sne(e){A8=e.wasm.cwrap("AvgPoolGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function ine(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l}=n,u=I.computePool2DInfo(s.shape,i,o,1,l),d=a.makeOutput(s.shape,s.dtype);return A8(a.dataIdMap.get(r.dataId).id,a.dataIdMap.get(d.dataId).id,u.batchSize,u.inChannels,u.inHeight,u.inWidth,u.outHeight,u.outWidth,u.strideHeight,u.strideWidth,u.dilationHeight,u.dilationWidth,u.effectiveFilterHeight,u.effectiveFilterWidth,u.padInfo.top,u.padInfo.left,u.filterHeight,u.filterWidth),d}var one={kernelName:gp,backendName:"wasm",setupFunc:sne,kernelFunc:ine};function La(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 lne={kernelName:Du,backendName:"wasm",kernelFunc:La},b8;function une(e){b8=e.wasm.cwrap(Gi,null,["number","array","number","number","array","number","number","number","number"])}function dne(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,d=i?r.shape[l-2]:r.shape[l-1],c=o?s.shape[u-1]:s.shape[u-2],p=i?r.shape[l-1]:r.shape[l-2],h=o?s.shape[u-2]:s.shape[u-1],m=r.shape.slice(0,-2),f=s.shape.slice(0,-2),g=v.sizeFromShape(m),y=v.sizeFromShape(f),x=ul.assertAndGetBroadcastShape(r.shape.slice(0,-2),s.shape.slice(0,-2)).concat([p,h]);v.assert(d===c,()=>`Error in matMul: inner shapes (${d}) and (${c}) of Tensors with shapes ${r.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let A=i?[g,d,p]:[g,p,d],b=o?[y,h,c]:[y,c,h],w=La({inputs:{x:r},backend:a,attrs:{shape:A}}),S=La({inputs:{x:s},backend:a,attrs:{shape:b}}),C=a.dataIdMap.get(w.dataId).id,N=a.dataIdMap.get(S.dataId).id,M=i?w.shape[2]:w.shape[1],F=o?S.shape[1]:S.shape[2],E=Math.max(g,y),T=a.makeOutput([E,M,F],w.dtype),D=a.dataIdMap.get(T.dataId).id,O=new Uint8Array(new Int32Array(w.shape).buffer),W=new Uint8Array(new Int32Array(S.shape).buffer);return b8(C,O,w.shape.length,N,W,S.shape.length,i,o,D),a.disposeData(w.dataId),a.disposeData(S.dataId),T.shape=x,T}var pne={kernelName:Gi,backendName:"wasm",setupFunc:une,kernelFunc:dne};function Mi(e){let{inputs:{x:t},attrs:{begin:a,size:n},backend:r}=e,[s,i]=wt.parseSliceParams(t,a,n),o=wt.isSliceContinous(t.shape,s,i),l=r.readSync(t.dataId),u=r.makeOutput(i,t.dtype),d=v.computeStrides(t.shape),c=r.dataIdMap.get(u.dataId);if(o){let m=wt.computeFlatOffset(s,d);return t.dtype==="string"?c.stringBytes=l.slice(m,m+v.sizeFromShape(i)):r.typedArrayFromHeap(u).set(l.subarray(m,m+v.sizeFromShape(i))),u}if(t.dtype==="string"){let m=Sh(l,s,i,t.shape,t.dtype);return c.stringBytes=m,u}let p=r.typedArrayFromHeap(u),h=t.shape.length;if(h===2)cne(l,d[0],p,s,i);else if(h===3)hne(l,d[0],d[1],p,s,i);else if(h===4)mne(l,d[0],d[1],d[2],p,s,i);else{let m=Sh(l,s,i,t.shape,t.dtype);p.set(m)}return u}function cne(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 d=u*t+o;a.set(e.subarray(d,d+r[1]),s),s+=r[1]}}function hne(e,t,a,n,r,s){let i=0,o=r[0],l=r[1],u=r[2],d=o+s[0],c=l+s[1];for(let p=o;p<d;p++)for(let h=l;h<c;h++){let m=p*t+h*a+u;n.set(e.subarray(m,m+s[2]),i),i+=s[2]}}function mne(e,t,a,n,r,s,i){let o=0,l=s[0],u=s[1],d=s[2],c=l+i[0],p=u+i[1],h=d+i[2],m=s[3];for(let f=l;f<c;f++)for(let g=u;g<p;g++)for(let y=d;y<h;y++){let x=f*t+g*a+y*n+m;r.set(e.subarray(x,x+i[3]),o),o+=i[3]}}var fne={kernelName:zu,backendName:"wasm",kernelFunc:Mi};function gne(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{blockShape:s,crops:i}=n,o=s.reduce((y,x)=>y*x),l=I.getReshaped(r.shape,s,o),u=I.getPermuted(l.length,s.length),d=I.getReshapedPermuted(r.shape,s,o),c=I.getSliceBeginCoords(i,s.length),p=I.getSliceSize(d,i,s.length),h=La({inputs:{x:r},backend:a,attrs:{shape:l}}),m=ps({inputs:{x:h},backend:a,attrs:{perm:u}}),f=La({inputs:{x:m},backend:a,attrs:{shape:d}}),g=Mi({inputs:{x:f},backend:a,attrs:{begin:c,size:p}});return a.disposeData(h.dataId),a.disposeData(m.dataId),a.disposeData(f.dataId),g}var yne={kernelName:gu,backendName:"wasm",kernelFunc:gne},v8;function xne(e){v8=e.wasm.cwrap(Hi,null,["number","number","boolean","number","number","number"])}function Ane(e){let{backend:t,inputs:a,attrs:n}=e,{x:r,weights:s}=a,{size:i}=n,o=s.shape.reduce((c,p)=>c*p,1)!==0,l=r.shape.length===1?[i]:[r.shape[0],i],u=t.makeOutput(l,s.dtype);function d(c){return t.dataIdMap.get(c.dataId).id}return v8(d(r),i,o,d(s),nt[s.dtype],d(u)),u}var bne={kernelName:Hi,backendName:"wasm",setupFunc:xne,kernelFunc:Ane},vne=!0,wne=Gt(ji,vne);function kne(e){let{inputs:t,backend:a}=e,{s0:n,s1:r}=t,s=a.typedArrayFromHeap(n),i=a.typedArrayFromHeap(r),o=I.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return a.makeOutput([o.length],"int32",void 0,new Int32Array(o))}var Ine={kernelName:yu,backendName:"wasm",kernelFunc:kne};function Ws(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 Sne={kernelName:qi,backendName:"wasm",kernelFunc:Ws},Tne=Qe(cs),w8;function Cne(e){w8=e.wasm.cwrap(hs,null,["number","number","number","number"])}function Nne(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 w8(o,s,i,u),l}var Rne={kernelName:hs,backendName:"wasm",setupFunc:Cne,kernelFunc:Nne};function k8(e){let{inputs:t,backend:a}=e,n=v.parseAxisParam(e.attrs.axis,t[0].shape)[0],r=t.map(h=>h.shape);I.assertParamsConsistent(r,n);let s=I.computeOutShape(t.map(h=>h.shape),n),i=t.filter(h=>v.sizeFromShape(h.shape)>0);if(i.length===1)return m0({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(A=>{let b=[-1,v.sizeFromShape(A.shape.slice(n))];return La({inputs:{x:A},backend:a,attrs:{shape:b}})}),m=h.map(A=>({vals:a.readSync(A.dataId),shape:A.shape}));s=I.computeOutShape(h.map(A=>A.shape),1);let f=h[0].shape[0]===1,g=k3(m,s,t[0].dtype,f),y=I.computeOutShape(i.map(A=>A.shape),n);o.shape=y;let x=a.dataIdMap.get(o.dataId);return x.stringBytes=I.fromStringArrayToUint8(g),h.forEach(A=>a.disposeData(A.dataId)),o}let l=v.sizeFromShape(i[0].shape.slice(0,n)),u=0,d=i.map(h=>{let m=v.sizeFromShape(h.shape.slice(n));return u+=m,m}),c=i.map(h=>a.typedArrayFromHeap(h)),p=a.typedArrayFromHeap(o);for(let h=0;h<l;h++){let m=h*u;for(let f=0;f<c.length;f++){let g=d[f],y=h*g,x=c[f].subarray(y,y+g);p.set(x,m),m+=g}}return o}var Ene={kernelName:xu,backendName:"wasm",kernelFunc:k8},I8;function Mne(e){I8=e.wasm.cwrap(Xi,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Fne(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:d,dimRoundingMode:c,dataFormat:p}=a,h=I.convertConv2DDataFormat(p),m=I.computeConv2DInfo(r.shape,s.shape,l,u,d,c,!1,h),f=m.filterHeight,g=m.filterWidth,y=m.padInfo.top,x=m.padInfo.right,A=m.padInfo.bottom,b=m.padInfo.left,w=m.dilationHeight,S=m.dilationWidth,C=m.strideHeight,N=m.strideWidth,M=m.inChannels,F=m.outChannels,E=m.padInfo.type==="SAME"?1:0;if(m.dataFormat!=="channelsLast")throw new Error(`wasm backend Conv2D does not support dataFormat:'${m.dataFormat}'. Please use 'channelsLast'.`);let T=n.makeOutput(m.outShape,"float32"),D=n.dataIdMap.get(T.dataId).id;return I8(i,r.shape[0],r.shape[1],r.shape[2],o,f,g,y,x,A,b,E,w,S,C,N,M,F,D),T}var $ne={kernelName:Xi,backendName:"wasm",setupFunc:Mne,kernelFunc:Fne},S8;function Dne(e){S8=e.wasm.cwrap(Ki,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 Pne(e){let{backend:t,inputs:a,attrs:n}=e,{dy:r,filter:s}=a,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,inputShape:d}=n,c=1,p=I.convertConv2DDataFormat(l),h=I.computeConv2DInfo(d,s.shape,i,c,o,u,!1,p),{batchSize:m,filterHeight:f,filterWidth:g,inChannels:y,inHeight:x,inWidth:A,outChannels:b,outHeight:w,outWidth:S,strideHeight:C,strideWidth:N}=h,M=f-1-h.padInfo.top,F=g-1-h.padInfo.left,E=h.dataFormat==="channelsLast",T=v.computeStrides(h.inShape),D=v.computeStrides(r.shape),[O,W,$]=v.computeStrides(s.shape),U=T[0],G=E?T[1]:T[2],q=E?T[2]:1,H=E?1:T[1],V=D[0],Z=E?D[1]:D[2],X=E?D[2]:1,re=E?1:D[1],ee=t.makeOutput(h.inShape,"float32"),ge=t.dataIdMap.get(ee.dataId).id,ie=t.dataIdMap.get(r.dataId).id,be=t.dataIdMap.get(s.dataId).id;return S8(ie,be,m,f,g,x,A,y,w,S,b,C,N,M,F,O,W,$,U,G,q,H,V,Z,X,re,ge),ee}var _ne={kernelName:Ki,backendName:"wasm",setupFunc:Dne,kernelFunc:Pne},T8;function One(e){T8=e.wasm.cwrap(Yi,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"])}function zne(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=n;if(r.dtype!=="float32")throw new Error(`Tensor x must have dtype float32, got ${r.dtype}`);if(s.dtype!=="float32")throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);let u=I.computeConv3DInfo(r.shape,s.shape,i,l,o),d=a.makeOutput(u.outShape,r.dtype);return T8(a.dataIdMap.get(r.dataId).id,a.dataIdMap.get(s.dataId).id,a.dataIdMap.get(d.dataId).id,u.batchSize,u.inDepth,u.inHeight,u.inWidth,u.inChannels,u.outDepth,u.outHeight,u.outWidth,u.outChannels,u.strideDepth,u.strideHeight,u.strideWidth,u.dilationDepth,u.dilationHeight,u.dilationWidth,u.filterDepth,u.filterHeight,u.filterWidth,u.padInfo.front,u.padInfo.top,u.padInfo.left),d}var Lne={kernelName:Yi,backendName:"wasm",setupFunc:One,kernelFunc:zne},C8;function Wne(e){C8=e.wasm.cwrap(Au,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"])}function Bne(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=n;if(r.dtype!=="float32")throw new Error(`Tensor dy must have dtype float32, got ${r.dtype}`);if(s.dtype!=="float32")throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);let u=I.computeConv3DInfo(r.shape,l,i,1,o),d=a.makeOutput(u.filterShape,s.dtype);return C8(a.dataIdMap.get(r.dataId).id,a.dataIdMap.get(s.dataId).id,a.dataIdMap.get(d.dataId).id,u.batchSize,u.inDepth,u.inHeight,u.inWidth,u.inChannels,u.outDepth,u.outHeight,u.outWidth,u.outChannels,u.strideDepth,u.strideHeight,u.strideWidth,u.dilationDepth,u.dilationHeight,u.dilationWidth,u.filterDepth,u.filterHeight,u.filterWidth,u.padInfo.front,u.padInfo.top,u.padInfo.left),d}var Vne={kernelName:Au,backendName:"wasm",setupFunc:Wne,kernelFunc:Bne},N8;function Une(e){N8=e.wasm.cwrap(Zi,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"])}function Gne(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=n;if(r.dtype!=="float32")throw new Error(`Tensor dy must have dtype float32, got ${r.dtype}`);if(s.dtype!=="float32")throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);let u=I.computeConv3DInfo(l,s.shape,o,1,i),d=a.makeOutput(u.inShape,r.dtype);return N8(a.dataIdMap.get(s.dataId).id,a.dataIdMap.get(r.dataId).id,a.dataIdMap.get(d.dataId).id,u.batchSize,u.inDepth,u.inHeight,u.inWidth,u.inChannels,u.outDepth,u.outHeight,u.outWidth,u.outChannels,u.strideDepth,u.strideHeight,u.strideWidth,u.dilationDepth,u.dilationHeight,u.dilationWidth,u.filterDepth,u.filterHeight,u.filterWidth,u.padInfo.front,u.padInfo.top,u.padInfo.left),d}var Hne={kernelName:Zi,backendName:"wasm",setupFunc:Une,kernelFunc:Gne},jne=Qe(Ji),qne=Qe(Qi),X1;(function(e){e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest"})(X1||(X1={}));var R8;function Xne(e){R8=e.wasm.cwrap(ao,null,["number","number","number","number","array","number","number","number","number","number"])}function Kne(e){let{backend:t,inputs:a,attrs:n}=e,{method:r,extrapolationValue:s,cropSize:i}=n,{image:o,boxes:l,boxInd:u}=a,d=l.shape[0],[c,p]=i,h=[d,c,p,o.shape[3]],m=t.dataIdMap.get(o.dataId),f;o.dtype!=="float32"&&(f=Ws({backend:t,inputs:{x:o},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(f.dataId));let g=m.id,y=t.dataIdMap.get(l.dataId).id,x=t.dataIdMap.get(u.dataId).id,A=t.makeOutput(h,"float32"),b=t.dataIdMap.get(A.dataId).id,w=new Uint8Array(new Int32Array(o.shape).buffer);return R8(g,y,x,d,w,c,p,X1[r],s,b),f!=null&&t.disposeData(f.dataId),A}var Yne={kernelName:ao,backendName:"wasm",setupFunc:Xne,kernelFunc:Kne},E8;function Zne(e){E8=e.wasm.cwrap(eo,null,["number","number","number","number","number","number"])}function Jne(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=I.getAxesPermutation([s],l),d=r;u!==null&&(d=ps({inputs:{x:r},attrs:{perm:u},backend:a}));let c=I.getInnerMostAxes(1,l)[0];I.assertAxesAreInnerMostDims("cumprod",[c],l);let p=a.makeOutput(d.shape,d.dtype),h=d.shape[c],m=a.dataIdMap.get(d.dataId).id,f=a.dataIdMap.get(p.dataId).id;E8(m,i?1:0,o?1:0,h,f,nt[r.dtype]);let g=p;if(u!==null){let y=I.getUndoAxesPermutation(u);g=ps({inputs:{x:p},attrs:{perm:y},backend:a}),a.disposeData(d.dataId),a.disposeData(p.dataId)}return g}var Qne={kernelName:eo,backendName:"wasm",setupFunc:Zne,kernelFunc:Jne},M8;function ere(e){M8=e.wasm.cwrap(to,null,["number","number","number","number","number","number"])}function tre(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=I.getAxesPermutation([s],l),d=r;u!==null&&(d=ps({inputs:{x:r},attrs:{perm:u},backend:a}));let c=I.getInnerMostAxes(1,l)[0];I.assertAxesAreInnerMostDims("cumsum",[c],l);let p=a.makeOutput(d.shape,d.dtype),h=d.shape[c],m=a.dataIdMap.get(d.dataId).id,f=a.dataIdMap.get(p.dataId).id;M8(m,i?1:0,o?1:0,h,f,nt[r.dtype]);let g=p;if(u!==null){let y=I.getUndoAxesPermutation(u);g=ps({inputs:{x:p},attrs:{perm:y},backend:a}),a.disposeData(d.dataId),a.disposeData(p.dataId)}return g}var are={kernelName:to,backendName:"wasm",setupFunc:ere,kernelFunc:tre},F8;function nre(e){F8=e.wasm.cwrap("DenseBincount",null,["number","array","number","number","boolean","number","number","boolean","number"])}function rre(e){let{backend:t,inputs:a,attrs:n}=e,{x:r,weights:s}=a,{size:i,binaryOutput:o}=n,l=s.shape.reduce((p,h)=>p*h,1)!==0,u=r.shape.length===1?[i]:[r.shape[0],i],d=t.makeOutput(u,s.dtype);function c(p){return t.dataIdMap.get(p.dataId).id}return F8(c(r),new Uint8Array(new Int32Array(r.shape).buffer),r.shape.length,i,l,c(s),nt[s.dtype],o,c(d)),d}var sre={kernelName:bu,backendName:"wasm",setupFunc:nre,kernelFunc:rre},$8;function ire(e){$8=e.wasm.cwrap(no,null,["number","number","number","array","number","array","array","number","number"])}function ore(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],d=i==="NHWC"?r.shape[3]:r.shape[1],c=l*s,p=u*s,h=d/(s*s),m=i==="NHWC"?[o,c,p,h]:[o,h,c,p],f=t.makeOutput(m,"float32"),g=t.dataIdMap.get(r.dataId).id,y=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),x=new Uint8Array(new Int32Array(m).buffer),A=new Uint8Array(new Int32Array(v.computeStrides(m)).buffer),b=t.dataIdMap.get(f.dataId).id;return $8(g,s,i==="NHWC"?1:0,y,r.shape.length-1,x,A,m.length,b),f}var lre={kernelName:no,backendName:"wasm",setupFunc:ire,kernelFunc:ore},D8;function ure(e){D8=e.wasm.cwrap(ro,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function dre(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:d,dimRoundingMode:c}=a,p=u==null?[1,1]:u,h=I.computeConv2DInfo(r.shape,s.shape,l,p,d,c,!0),m=h.filterHeight,f=h.filterWidth,g=h.padInfo.top,y=h.padInfo.right,x=h.padInfo.bottom,A=h.padInfo.left,b=h.dilationHeight,w=h.dilationWidth,S=h.strideHeight,C=h.strideWidth,N=h.inChannels,M=h.outChannels,F=h.padInfo.type==="SAME"?1:0;if(h.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${h.dataFormat}'. Please use 'channelsLast'.`);let E=n.makeOutput(h.outShape,"float32"),T=n.dataIdMap.get(E.dataId).id;return D8(i,r.shape[0],r.shape[1],r.shape[2],o,m,f,g,y,x,A,F,b,w,S,C,N,M,T),E}var pre={kernelName:ro,backendName:"wasm",setupFunc:ure,kernelFunc:dre},P8;function cre(e){P8=e.wasm.cwrap("Diag",null,["number","number","number","number"])}function hre(e){let{inputs:t,backend:a}=e,{x:n}=t,r=v.sizeFromShape(n.shape),s=a.makeOutput([...n.shape,...n.shape],n.dtype);return P8(a.dataIdMap.get(n.dataId).id,nt[n.dtype],r,a.dataIdMap.get(s.dataId).id),s}var mre={kernelName:vu,backendName:"wasm",setupFunc:cre,kernelFunc:hre},_8;function fre(e){_8=e.wasm.cwrap(so,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function gre(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=n;if(r.dtype!==s.dtype)throw new Error(`Dilation2D error: x must have the same dtype as filter. Got ${r.dtype} and ${s.dtype}`);let u=I.computeDilation2DInfo(r.shape,s.shape,i,o,"NHWC",l),d=a.makeOutput(u.outShape,r.dtype);return _8(a.dataIdMap.get(r.dataId).id,a.dataIdMap.get(s.dataId).id,a.dataIdMap.get(d.dataId).id,nt[r.dtype],u.batchSize,u.inChannels,u.inHeight,u.inWidth,u.outHeight,u.outWidth,u.strideHeight,u.strideWidth,u.dilationHeight,u.dilationWidth,u.filterHeight,u.filterWidth,u.padInfo.top,u.padInfo.left),d}var yre={kernelName:so,backendName:"wasm",setupFunc:fre,kernelFunc:gre},O8;function xre(e){O8=e.wasm.cwrap(Ql,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Are(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s,dy:i}=t,{strides:o,pad:l,dilations:u}=n;if(r.dtype!==s.dtype||r.dtype!==i.dtype)throw new Error(`Dilation2DBackpropFilter error: x must have the same dtype as filter and dy. Got ${r.dtype}, ${s.dtype}, and ${i.dtype}`);let d=I.computeDilation2DInfo(r.shape,s.shape,o,l,"NHWC",u),c=a.makeOutput(s.shape,s.dtype);return O8(a.dataIdMap.get(r.dataId).id,a.dataIdMap.get(s.dataId).id,a.dataIdMap.get(i.dataId).id,a.dataIdMap.get(c.dataId).id,nt[r.dtype],d.batchSize,d.inChannels,d.inHeight,d.inWidth,d.outHeight,d.outWidth,d.strideHeight,d.strideWidth,d.dilationHeight,d.dilationWidth,d.filterHeight,d.filterWidth,d.padInfo.top,d.padInfo.left),c}var bre={kernelName:Ql,backendName:"wasm",setupFunc:xre,kernelFunc:Are},z8;function vre(e){z8=e.wasm.cwrap(Jl,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function wre(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s,dy:i}=t,{strides:o,pad:l,dilations:u}=n;if(r.dtype!==s.dtype||r.dtype!==i.dtype)throw new Error(`Dilation2DBackpropInput error: x must have the same dtype as filter and dy. Got ${r.dtype}, ${s.dtype}, and ${i.dtype}`);let d=I.computeDilation2DInfo(r.shape,s.shape,o,l,"NHWC",u),c=a.makeOutput(r.shape,r.dtype);return z8(a.dataIdMap.get(r.dataId).id,a.dataIdMap.get(s.dataId).id,a.dataIdMap.get(i.dataId).id,a.dataIdMap.get(c.dataId).id,nt[r.dtype],d.batchSize,d.inChannels,d.inHeight,d.inWidth,d.outHeight,d.outWidth,d.strideHeight,d.strideWidth,d.dilationHeight,d.dilationWidth,d.filterHeight,d.filterWidth,d.padInfo.top,d.padInfo.left),c}var kre={kernelName:Jl,backendName:"wasm",setupFunc:vre,kernelFunc:wre},Ire=Qe(oo),L8;function Sre(e){L8=e.wasm.cwrap(wu,null,["number","number","number"])}function Tre(e){let{inputs:t,backend:a}=e,{dy:n,y:r}=t,s=a.makeOutput(r.shape,"float32"),i=o=>a.dataIdMap.get(o.dataId).id;return L8(i(r),i(n),i(s)),s}var Cre={kernelName:wu,backendName:"wasm",setupFunc:Sre,kernelFunc:Tre},Nre=!1,Rre=Gt(ms,Nre,"bool"),Ere=Qe(lo),Mre=Qe(fs,"float32");function K1(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),La({inputs:{x:r},backend:n,attrs:{shape:o}})}var Fre={kernelName:ku,backendName:"wasm",kernelFunc:K1},$re=Qe(gs,"float32");function W8(e){let{attrs:{shape:t,value:a},backend:n}=e,{attrs:{dtype:r}}=e;r=r||v.inferDtype(a);let s=n.makeOutput(t,r);return n.typedArrayFromHeap(s).fill(a),s}var Dre={kernelName:Iu,backendName:"wasm",kernelFunc:W8},B8;function Pre(e){B8=e.wasm.cwrap(uo,null,["number","number","number","number","number","number"])}function _re(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,d]=n.shape;return B8(s,o,l,u,d,i),r}var Ore={kernelName:uo,backendName:"wasm",kernelFunc:_re,setupFunc:Pre},zre=Qe(ys),Lre=!1,Wre=Gt(xs,Lre),V8;function Bre(e){V8=e.wasm.cwrap(po,null,["number","number","number","number","number","number","number"])}function Vre(e){let{backend:t,inputs:a,attrs:n}=e,{varianceEpsilon:r}=n,{x:s,mean:i,variance:o,offset:l,scale:u}=a,d=t.dataIdMap.get(s.dataId).id,c=t.dataIdMap.get(i.dataId).id,p=t.dataIdMap.get(o.dataId).id,h=l!=null?t.dataIdMap.get(l.dataId).id:0,m=u!=null?t.dataIdMap.get(u.dataId).id:0,f=t.makeOutput(s.shape,s.dtype);if(v.sizeFromShape(s.shape)===0)return f;let g=t.dataIdMap.get(f.dataId).id;return V8(d,c,p,h,m,r,g),f}var Ure={kernelName:po,backendName:"wasm",setupFunc:Bre,kernelFunc:Vre},U8;function Gre(e){U8=e.wasm.cwrap(as,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 Hre(e){let{inputs:t,attrs:a,backend:n}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:d,dataFormat:c,dimRoundingMode:p,activation:h,leakyreluAlpha:m}=a,f=I.computeConv2DInfo(r.shape,s.shape,l,d,u,p),g=dp[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedConv2D in the wasm backend.`);let y=n.dataIdMap.get(r.dataId).id,x=n.dataIdMap.get(s.dataId).id,A=f.outChannels,b=0;if(i!=null){let X=n.dataIdMap.get(i.dataId);if(X.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${X.shape.length}.`);if(X.shape[0]!==A)throw new Error(`FusedConv2D bias shape (${X.shape}) does not match the number of output channels (${A})`);b=X.id}let w=f.filterHeight,S=f.filterWidth,C=f.padInfo.top,N=f.padInfo.right,M=f.padInfo.bottom,F=f.padInfo.left,E=f.dilationHeight,T=f.dilationWidth,D=f.strideHeight,O=f.strideWidth,W=f.inChannels,$=f.padInfo.type==="SAME"?1:0,U=f.batchSize,G=f.inHeight,q=f.inWidth;if(c!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${c}'. Please use 'NHWC'.`);let H=n.makeOutput(f.outShape,"float32"),V=n.dataIdMap.get(H.dataId).id,Z=o==null?0:n.dataIdMap.get(o.dataId).id;return U8(y,U,G,q,x,w,S,b,C,N,M,F,$,E,T,D,O,W,A,g,Z,m||0,V),H}var jre={kernelName:as,backendName:"wasm",setupFunc:Gre,kernelFunc:Hre},G8;function qre(e){G8=e.wasm.cwrap(ns,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 Xre(e){let{inputs:t,attrs:a,backend:n}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:d,dataFormat:c,dimRoundingMode:p,activation:h,leakyreluAlpha:m}=a,f=I.computeConv2DInfo(r.shape,s.shape,l,d,u,p,!0),g=dp[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let y=n.dataIdMap.get(r.dataId).id,x=n.dataIdMap.get(s.dataId).id,A=f.outChannels,b=0;if(i!=null){let X=n.dataIdMap.get(i.dataId);if(X.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${X.shape.length}.`);if(X.shape[0]!==A)throw new Error(`FusedDepthwiseConv2D bias shape (${X.shape}) does not match the number of output channels (${A})`);b=X.id}let w=f.filterHeight,S=f.filterWidth,C=f.padInfo.top,N=f.padInfo.right,M=f.padInfo.bottom,F=f.padInfo.left,E=f.dilationHeight,T=f.dilationWidth,D=f.strideHeight,O=f.strideWidth,W=f.inChannels,$=f.padInfo.type==="SAME"?1:0,U=f.batchSize,G=f.inHeight,q=f.inWidth;if(c!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${c}'. Please use 'NHWC'.`);let H=n.makeOutput(f.outShape,"float32"),V=n.dataIdMap.get(H.dataId).id,Z=o==null?0:n.dataIdMap.get(o.dataId).id;return G8(y,U,G,q,x,w,S,b,C,N,M,F,$,E,T,D,O,W,A,g,Z,m||0,V),H}var Kre={kernelName:ns,backendName:"wasm",setupFunc:qre,kernelFunc:Xre},H8;function Yre(e){H8=e.wasm.cwrap(co,null,["number","number","number","number","number","number","array","number"])}function Zre(e){let{backend:t,inputs:a}=e,{params:n,indices:r}=a,[s,i,o,l]=h3.prepareAndValidate(n,r),u=t.makeOutput(s,n.dtype);if(i===0)return u;let d=r.shape,c=d[d.length-1],p=t.dataIdMap.get(n.dataId).id,h=t.dataIdMap.get(r.dataId).id,m=new Uint8Array(new Int32Array(l).buffer),f=t.dataIdMap.get(u.dataId).id;return H8(p,nt[n.dtype],h,i,c,o,m,f),u}var Jre={kernelName:co,backendName:"wasm",setupFunc:Yre,kernelFunc:Zre},j8;function Qre(e){j8=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function ese(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),d=r.shape[l];for(let C=0;C<u.length;++C){let N=u[C];v.assert(N<=d-1&&N>=0,()=>`GatherV2: the index value ${N} is not in [0, ${d-1}]`)}let c=I.segment_util.collectGatherOpShapeInfo(r,s,l,o),p=La({inputs:{x:r},attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]},backend:t}),h=v.sizeFromShape(s.shape),m=La({inputs:{x:s},attrs:{shape:[c.batchSize,h/c.batchSize]},backend:t}),f=[c.batchSize,c.outerSize,h/c.batchSize,c.sliceSize],g=t.makeOutput(f,r.dtype);if(v.sizeFromShape(r.shape)===0)return g;let y=p.shape.length-1,x=t.dataIdMap.get(p.dataId).id,A=t.dataIdMap.get(m.dataId).id,b=t.dataIdMap.get(g.dataId).id,w=new Uint8Array(new Int32Array(v.computeStrides(p.shape)).buffer),S=new Uint8Array(new Int32Array(v.computeStrides(f)).buffer);return j8(x,nt[r.dtype],w,y,A,c.batchSize,S,b),t.disposeData(p.dataId),t.disposeData(m.dataId),g.shape=c.outputShape,g}var tse={kernelName:Su,backendName:"wasm",setupFunc:Qre,kernelFunc:ese},ase=!1,nse=Gt(As,ase,"bool"),rse=!1,sse=Gt(bs,rse,"bool"),ise=Qe(mo,"bool"),ose=Qe(fo,"bool"),lse=Qe(go,"bool"),q8;function use(e){q8=e.wasm.cwrap(yo,null,["number","number","number","number"])}function dse(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;q8(r,nt[t.dtype],a,i)}return s}var pse={kernelName:yo,backendName:"wasm",setupFunc:use,kernelFunc:dse},cse=!1,hse=Gt(vs,cse,"bool"),mse=!1,fse=Gt(ws,mse,"bool"),X8;function gse(e){X8=e.wasm.cwrap(xo,null,["number","number","number","number"])}function yse(e){let{attrs:t,backend:a}=e,{start:n,stop:r,num:s}=t,i=Math.floor(s),o=a.makeOutput([i],"float32");return X8(a.dataIdMap.get(o.dataId).id,n,r,i),o}var xse={kernelName:xo,backendName:"wasm",setupFunc:gse,kernelFunc:yse},Ase=Qe(ks),bse=Qe(Ao),vse=!1,wse=Gt(bo,vse,"bool"),kse=Qe(vo),Ise=!1,Sse=Gt(wo,Ise,"bool"),Tse=!1,Cse=Gt(HA,Tse,"bool"),K8;function Nse(e){K8=e.wasm.cwrap(ko,null,["number","number","number","number","number","number","number"])}function Rse(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n;if(r.dtype!=="float32")throw new Error("LRN error: x must have dtype float32");let u=a.makeOutput(r.shape,r.dtype);return K8(a.dataIdMap.get(r.dataId).id,a.dataIdMap.get(u.dataId).id,r.shape[3],s,i,o,l),u}var Ese={kernelName:ko,backendName:"wasm",setupFunc:Nse,kernelFunc:Rse},Y8;function Mse(e){Y8=e.wasm.cwrap(Tu,null,["number","number","number","number","number","number","number","number","number"])}function Fse(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:d}=n;if(r.dtype!=="float32"||s.dtype!=="float32"||i.dtype!=="float32")throw new Error("LRNGrad error: x, y, and dy must have dtype float32");let c=a.makeOutput(r.shape,r.dtype);return Y8(a.dataIdMap.get(r.dataId).id,a.dataIdMap.get(s.dataId).id,a.dataIdMap.get(i.dataId).id,a.dataIdMap.get(c.dataId).id,i.shape[3],o,l,u,d),c}var $se={kernelName:Tu,backendName:"wasm",setupFunc:Mse,kernelFunc:Fse},Z8;function Dse(e){Z8=e.wasm.cwrap(Io,null,["number","number","number","number"])}function Pse(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:d,originalAxes:c,inputWasTransposed:p}=Ls(i,r,t);if(p){let x=t.dataIdMap.get(u.dataId).id;l=u,o=x}let h=l.shape.length;I.assertAxesAreInnerMostDims("max",d,h);let[m,f]=I.computeOutAndReduceShapes(l.shape,d),g=v.sizeFromShape(f),y=t.makeOutput(m,i.dtype);if(v.sizeFromShape(l.shape)!==0){let x=t.dataIdMap.get(y.dataId).id;Z8(o,nt[i.dtype],g,x)}if(p&&t.disposeData(u.dataId),s){let x=I.expandShapeToKeepDim(y.shape,c);y.shape=x}return y}var _se={kernelName:Io,backendName:"wasm",setupFunc:Dse,kernelFunc:Pse},Ose=!1,zse=Gt(Is,Ose),J8;function Lse(e){J8=e.wasm.cwrap(So,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Wse(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,d=I.computePool2DInfo(r.shape,i,o,1,l,u),c=d.filterHeight,p=d.filterWidth,h=d.padInfo.top,m=d.padInfo.right,f=d.padInfo.bottom,g=d.padInfo.left,y=d.dilationHeight,x=d.dilationWidth,A=d.strideHeight,b=d.strideWidth,w=d.inChannels,S=d.outChannels;if(d.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);let C=n.makeOutput(d.outShape,"float32"),N=n.dataIdMap.get(C.dataId).id;return J8(s,r.shape[0],r.shape[1],r.shape[2],c,p,h,m,f,g,y,x,A,b,w,S,N),C}var Bse={kernelName:So,backendName:"wasm",setupFunc:Lse,kernelFunc:Wse},Q8;function Vse(e){Q8=e.wasm.cwrap("MaxPool3D",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Use(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=n,d=I.computePool3DInfo(r.shape,s,i,1,o,l,u),c=a.makeOutput(d.outShape,r.dtype);return Q8(a.dataIdMap.get(r.dataId).id,a.dataIdMap.get(c.dataId).id,d.batchSize,d.inChannels,d.inDepth,d.inHeight,d.inWidth,d.outDepth,d.outHeight,d.outWidth,d.strideDepth,d.strideHeight,d.strideWidth,d.dilationDepth,d.dilationHeight,d.dilationWidth,d.effectiveFilterDepth,d.effectiveFilterHeight,d.effectiveFilterWidth,d.padInfo.front,d.padInfo.top,d.padInfo.left),c}var Gse={kernelName:Cu,backendName:"wasm",setupFunc:Vse,kernelFunc:Use},ek;function Hse(e){ek=e.wasm.cwrap("MaxPool3DGrad",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 jse(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=n,d=I.computePool3DInfo(s.shape,i,o,1,l,u),c=a.makeOutput(s.shape,s.dtype);return ek(a.dataIdMap.get(s.dataId).id,a.dataIdMap.get(r.dataId).id,a.dataIdMap.get(c.dataId).id,d.batchSize,d.inChannels,d.inDepth,d.inHeight,d.inWidth,d.outDepth,d.outHeight,d.outWidth,d.strideDepth,d.strideHeight,d.strideWidth,d.dilationDepth,d.dilationHeight,d.dilationWidth,d.effectiveFilterDepth,d.effectiveFilterHeight,d.effectiveFilterWidth,d.padInfo.front,d.padInfo.top,d.padInfo.left),c}var qse={kernelName:Rp,backendName:"wasm",setupFunc:Hse,kernelFunc:jse},tk;function Xse(e){tk=e.wasm.cwrap("MaxPoolGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Kse(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=n,d=I.computePool2DInfo(s.shape,i,o,1,l,u),c=a.makeOutput(s.shape,s.dtype);return tk(a.dataIdMap.get(s.dataId).id,a.dataIdMap.get(r.dataId).id,a.dataIdMap.get(c.dataId).id,d.batchSize,d.inChannels,d.inHeight,d.inWidth,d.outHeight,d.outWidth,d.strideHeight,d.strideWidth,d.dilationHeight,d.dilationWidth,d.effectiveFilterHeight,d.effectiveFilterWidth,d.padInfo.top,d.padInfo.left),c}var Yse={kernelName:Np,backendName:"wasm",setupFunc:Xse,kernelFunc:Kse},ak;function Zse(e){ak=e.wasm.cwrap("MaxPoolWithArgmax",null,["number","number","number","number","boolean","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Jse(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,includeBatchInIndex:l}=n;v.assert(r.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${r.shape.length}.`);let u=[1,1];v.assert(I.eitherStridesOrDilationsAreOne(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=I.computePool2DInfo(r.shape,s,i,[1,1],o),c=a.makeOutput(d.outShape,r.dtype),p=a.makeOutput(d.outShape,"int32");return ak(a.dataIdMap.get(r.dataId).id,a.dataIdMap.get(c.dataId).id,a.dataIdMap.get(p.dataId).id,nt[r.dtype],l,d.batchSize,d.inChannels,d.inHeight,d.inWidth,d.outHeight,d.outWidth,d.strideHeight,d.strideWidth,d.dilationHeight,d.dilationWidth,d.effectiveFilterHeight,d.effectiveFilterWidth,d.padInfo.top,d.padInfo.left),[c,p]}var Qse={kernelName:Nu,backendName:"wasm",setupFunc:Zse,kernelFunc:Jse},nk;function eie(e){nk=e.wasm.cwrap(To,null,["number, number, number"])}function tie(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:d,axes:c,originalAxes:p,inputWasTransposed:h}=Ls(i,r,t),m=c;if(h){let b=t.dataIdMap.get(d.dataId).id;b!==o&&(u=d,l=b,m=I.getInnerMostAxes(m.length,u.shape.length))}I.assertAxesAreInnerMostDims("mean",m,u.shape.length);let[f,g]=I.computeOutAndReduceShapes(u.shape,m),y=v.sizeFromShape(g),x=u;u.dtype!=="float32"&&(x=Ws({backend:t,inputs:{x:u},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(x.dataId).id);let A=t.makeOutput(f,"float32");if(v.sizeFromShape(u.shape)!==0){let b=t.dataIdMap.get(A.dataId).id;nk(l,y,b)}if(h&&t.disposeData(d.dataId),s){let b=I.expandShapeToKeepDim(A.shape,p);A.shape=b}return u.dtype!=="float32"&&t.disposeData(x.dataId),A}var aie={kernelName:To,backendName:"wasm",setupFunc:eie,kernelFunc:tie},rk;function nie(e){rk=e.wasm.cwrap(Co,null,["number","number","number","number"])}function rie(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:d,axes:c,originalAxes:p,inputWasTransposed:h}=Ls(i,r,t);if(h){let A=t.dataIdMap.get(d.dataId).id;A!==o&&(u=d,l=A)}let m=u.shape.length;I.assertAxesAreInnerMostDims("min",c,m);let[f,g]=I.computeOutAndReduceShapes(u.shape,c),y=v.sizeFromShape(g),x=t.makeOutput(f,u.dtype);if(v.sizeFromShape(u.shape)!==0){let A=t.dataIdMap.get(x.dataId).id;rk(l,nt[i.dtype],y,A)}if(h&&t.disposeData(d.dataId),s){let A=I.expandShapeToKeepDim(x.shape,p);x.shape=A}return x}var sie={kernelName:Co,backendName:"wasm",setupFunc:nie,kernelFunc:rie},iie=!1,oie=Gt(Ss,iie),Y1;(function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"})(Y1||(Y1={}));var sk;function lie(e){sk=e.wasm.cwrap(No,null,["number","array","number","number","array","array","number","number"])}function uie(e){let{inputs:{x:t},backend:a,attrs:{paddings:n,mode:r}}=e,s=n.map((m,f)=>m[0]+t.shape[f]+m[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),d=n.map(m=>m[0]),c=n.map(m=>m[1]),p=new Uint8Array(new Int32Array(d).buffer),h=new Uint8Array(new Int32Array(c).buffer);return sk(i,u,t.shape.length,nt[t.dtype],p,h,Y1[r],l),o}var die={kernelName:No,backendName:"wasm",kernelFunc:uie,setupFunc:lie},ik;function pie(e){ik=e.wasm.cwrap(el,null,["number","number","number","number"])}function ok(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||ik(r,i,o,l),s}var cie={kernelName:el,backendName:"wasm",setupFunc:pie,kernelFunc:ok},lk;function hie(e){lk=e.wasm.cwrap(Eo,null,["number","number","number","number","number","number"])}function mie(e){let{inputs:t,backend:a,attrs:n}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=n;if(r.dtype!=="float32")throw new Error(`Tensor logits must have dtype float32, got ${r.dtype}`);let l=o?r:ok({inputs:{logits:r},backend:a,attrs:{dim:r.shape.length-1}}),[u,d]=l.shape,c=a.makeOutput([u,s],"int32");return lk(a.dataIdMap.get(l.dataId).id,u,d,s,i,a.dataIdMap.get(c.dataId).id),o||a.disposeData(l.dataId),c}var fie={kernelName:Eo,backendName:"wasm",setupFunc:hie,kernelFunc:mie},gie=Gt(Ro,!0),yie=!0,xie=Gt(Ts,yie),Aie=Qe(Ru);function Z3(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 uk;function bie(e){uk=e.wasm.cwrap(Mo,"number",["number","number","number","number","number"])}function vie(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,d=t.dataIdMap.get(l.dataId).id,c=uk(u,d,s,r,i),{pSelectedIndices:p,selectedSize:h,pSelectedScores:m,pValidOutputs:f}=Z3(t,c);return t.wasm._free(m),t.wasm._free(f),t.makeOutput([h],"int32",p)}var wie={kernelName:Mo,backendName:"wasm",setupFunc:bie,kernelFunc:vie},dk;function kie(e){dk=e.wasm.cwrap(Eu,"number",["number","number","number","number","number","bool"])}function Iie(e){let{backend:t,inputs:a,attrs:n}=e,{iouThreshold:r,maxOutputSize:s,scoreThreshold:i,padToMaxOutputSize:o}=n,{boxes:l,scores:u}=a,d=t.dataIdMap.get(l.dataId).id,c=t.dataIdMap.get(u.dataId).id,p=dk(d,c,s,r,i,o),{pSelectedIndices:h,selectedSize:m,pSelectedScores:f,pValidOutputs:g}=Z3(t,p);t.wasm._free(f);let y=t.makeOutput([m],"int32",h),x=t.makeOutput([],"int32",g);return[y,x]}var Sie={kernelName:Eu,backendName:"wasm",setupFunc:kie,kernelFunc:Iie},pk;function Tie(e){pk=e.wasm.cwrap(Fo,"number",["number","number","number","number","number","number"])}function Cie(e){let{backend:t,inputs:a,attrs:n}=e,{iouThreshold:r,maxOutputSize:s,scoreThreshold:i,softNmsSigma:o}=n,{boxes:l,scores:u}=a,d=t.dataIdMap.get(l.dataId).id,c=t.dataIdMap.get(u.dataId).id,p=pk(d,c,s,r,i,o),{pSelectedIndices:h,selectedSize:m,pSelectedScores:f,pValidOutputs:g}=Z3(t,p);t.wasm._free(g);let y=t.makeOutput([m],"int32",h),x=t.makeOutput([m],"float32",f);return[y,x]}var Nie={kernelName:Fo,backendName:"wasm",setupFunc:Tie,kernelFunc:Cie},Rie=!1,Eie=Gt(Cs,Rie,"bool"),ck;function Mie(e){ck=e.wasm.cwrap($o,null,["number","number","number","number","number"])}function Fie(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),d=a.dataIdMap.get(u.dataId).id,c=a.dataIdMap.get(r.dataId).id;return ck(c,i,o,l,d),u}var $ie={kernelName:$o,backendName:"wasm",setupFunc:Mie,kernelFunc:Fie};function Die(e){let{inputs:{x:t},backend:a}=e,n=a.makeOutput(t.shape,t.dtype);return a.typedArrayFromHeap(n).fill(1),n}var Pie={kernelName:Mu,backendName:"wasm",kernelFunc:Die};function _ie(e){let{inputs:t,backend:a,attrs:n}=e,{axis:r}=n;if(t.length===1)return K1({inputs:{input:t[0]},backend:a,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(d=>{v.assertShapesMatch(s,d.shape,"All tensors passed to stack must have matching shapes"),v.assert(i===d.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(d=>{let c=K1({inputs:{input:d},backend:a,attrs:{dim:r}});return o.push(c),c}),u=k8({inputs:l,backend:a,attrs:{axis:r}});return o.forEach(d=>a.disposeData(d.dataId)),u}var Oie={kernelName:Fu,backendName:"wasm",kernelFunc:_ie},hk;function zie(e){hk=e.wasm.cwrap(Do,null,["number","array","number","number","array","array","number","number"])}function Lie(e){let{inputs:{x:t},backend:a,attrs:{paddings:n,constantValue:r}}=e,s=n.map((m,f)=>m[0]+t.shape[f]+m[1]);if(v.sizeFromShape(t.shape)===0)return W8({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),d=n.map(m=>m[0]),c=n.map(m=>m[1]),p=new Uint8Array(new Int32Array(d).buffer),h=new Uint8Array(new Int32Array(c).buffer);return hk(i,u,t.shape.length,nt[t.dtype],p,h,r,l),o}var mk={kernelName:Do,backendName:"wasm",kernelFunc:Lie,setupFunc:zie},Wie=!1,Bie=Gt(Po,Wie),fk;function Vie(e){fk=e.wasm.cwrap(_o,null,["number","number","number"])}function Uie(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=Ws({backend:a,inputs:{x:n},attrs:{dtype:"float32"}}),o=a.dataIdMap.get(u.dataId).id);let d=a.makeOutput(n.shape,"float32"),c=a.dataIdMap.get(d.dataId).id;return fk(o,i,c),l.dtype!=="float32"&&a.disposeData(u.dataId),d}var Gie={kernelName:_o,backendName:"wasm",setupFunc:Vie,kernelFunc:Uie},gk;function Hie(e){gk=e.wasm.cwrap(Oo,null,["number","number","number","number"])}function jie(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:d,axes:c,originalAxes:p,inputWasTransposed:h}=Ls(i,r,t),m=c;if(h){let A=t.dataIdMap.get(d.dataId).id;A!==o&&(u=d,l=A,m=I.getInnerMostAxes(m.length,u.shape.length))}I.assertAxesAreInnerMostDims("prod",m,u.shape.length);let[f,g]=I.computeOutAndReduceShapes(u.shape,m),y=v.sizeFromShape(g),x=t.makeOutput(f,u.dtype);if(v.sizeFromShape(u.shape)!==0){let A=t.dataIdMap.get(x.dataId).id;gk(l,y,nt[x.dtype],A)}if(h&&t.disposeData(d.dataId),s){let A=I.expandShapeToKeepDim(x.shape,p);x.shape=A}return x}var qie={kernelName:Oo,backendName:"wasm",setupFunc:Hie,kernelFunc:jie},Xie=e=>{let{backend:t,attrs:a}=e,{start:n,stop:r,step:s,dtype:i}=a,o=T3(n,r,s,i),l=t.makeOutput([o.length],i);return t.typedArrayFromHeap(l).set(o),l},Kie={kernelName:$u,backendName:"wasm",kernelFunc:Xie},Yie=!0,Zie=Gt(io,Yie),Jie=Qe(zo),Qie=Qe(Lo),eoe=Qe(Vo),yk;function toe(e){yk=e.wasm.cwrap(Bo,null,["number","number","number","number","number","number","number","number","number","number"])}function aoe(e){let{backend:t,inputs:a,attrs:n}=e,{images:r}=a,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,[d,c,p,h]=r.shape,m=[d,l,u,h],f=t.dataIdMap.get(r.dataId),g;f.dtype!=="float32"&&(g=Ws({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),f=t.dataIdMap.get(g.dataId));let y=f.id,x=t.makeOutput(m,"float32");if(v.sizeFromShape(r.shape)===0)return x;let A=t.dataIdMap.get(x.dataId).id;return yk(y,d,c,p,h,l,u,s?1:0,i?1:0,A),g!=null&&t.disposeData(g.dataId),x}var noe={kernelName:Bo,backendName:"wasm",setupFunc:toe,kernelFunc:aoe},xk;function roe(e){xk=e.wasm.cwrap(_u,null,["number","number","number","array","array","boolean"])}function soe(e){let{inputs:t,backend:a,attrs:n}=e,{images:r,dy:s}=t,{alignCorners:i}=n,o=a.makeOutput(r.shape,"float32"),l=a.dataIdMap.get(r.dataId),u;return l.dtype!=="float32"&&(u=Ws({backend:a,inputs:{x:r},attrs:{dtype:"float32"}}),l=a.dataIdMap.get(u.dataId)),xk(a.dataIdMap.get(r.dataId).id,a.dataIdMap.get(s.dataId).id,a.dataIdMap.get(o.dataId).id,new Uint8Array(new Int32Array(r.shape).buffer),new Uint8Array(new Int32Array(s.shape).buffer),i),u!=null&&a.disposeData(u.dataId),o}var ioe={kernelName:_u,backendName:"wasm",setupFunc:roe,kernelFunc:soe},Ak;function ooe(e){Ak=e.wasm.cwrap(Wo,null,["number","number","number","number","number","number","number","number","number","number"])}function loe(e){let{backend:t,inputs:a,attrs:n}=e,{images:r}=a,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,[d,c,p,h]=r.shape,m=[d,l,u,h],f=t.makeOutput(m,"float32");if(v.sizeFromShape(r.shape)===0)return f;let g=t.dataIdMap.get(r.dataId),y;g.dtype!=="float32"&&(y=Ws({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),g=t.dataIdMap.get(y.dataId));let x=g.id,A=t.dataIdMap.get(f.dataId).id;return Ak(x,d,c,p,h,l,u,s?1:0,i?1:0,A),y!=null&&t.disposeData(y.dataId),f}var uoe={kernelName:Wo,backendName:"wasm",setupFunc:ooe,kernelFunc:loe},bk;function doe(e){bk=e.wasm.cwrap(Pu,null,["number","number","number","array","array","boolean"])}function poe(e){let{inputs:t,backend:a,attrs:n}=e,{images:r,dy:s}=t,{alignCorners:i}=n,o=a.makeOutput(r.shape,"float32"),l=a.dataIdMap.get(r.dataId),u;return l.dtype!=="float32"&&(u=Ws({backend:a,inputs:{x:r},attrs:{dtype:"float32"}}),l=a.dataIdMap.get(u.dataId)),bk(a.dataIdMap.get(r.dataId).id,a.dataIdMap.get(s.dataId).id,a.dataIdMap.get(o.dataId).id,new Uint8Array(new Int32Array(r.shape).buffer),new Uint8Array(new Int32Array(s.shape).buffer),i),u!=null&&a.disposeData(u.dataId),o}var coe={kernelName:Pu,backendName:"wasm",setupFunc:doe,kernelFunc:poe},vk;function hoe(e){vk=e.wasm.cwrap(Uo,null,["number","array","number","array","number","number"])}function moe(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 m0({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,d=new Uint8Array(new Int32Array(i).buffer),c=new Uint8Array(new Int32Array(r.shape).buffer);vk(l,d,i.length,c,r.shape.length,u);let p=La({inputs:{x:o},attrs:{shape:r.shape},backend:a});return a.disposeData(o.dataId),p}var foe={kernelName:Uo,backendName:"wasm",kernelFunc:moe,setupFunc:hoe},wk;function goe(e){wk=e.wasm.cwrap(ol,null,["number","number","number","number","number","number","number","number","array","number","number"])}function yoe(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,d=a.dataIdMap.get(l.dataId).id,[c,p,h,m]=r.shape,[f,g]=I.getImageCenter(o,p,h),y=i===0,x=255,A=typeof i=="number"?[i,i,i,y?0:x]:[...i,x],b=new Uint8Array(new Int32Array(A).buffer);return wk(u,c,p,h,m,s,f,g,b,A.length,d),l}var xoe={kernelName:ol,backendName:"wasm",kernelFunc:yoe,setupFunc:goe},Aoe=Qe(Go),boe=Qe(Ns),kk;function voe(e){kk=e.wasm.cwrap(Ho,null,["number","number","number","number","number","number","array","number","number"])}function woe(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:d,strides:c,outputSize:p}=Qh.calculateShapes(s,r,i),h=t.dataIdMap.get(r.dataId).id,m=t.dataIdMap.get(s.dataId).id,f=new Uint8Array(new Int32Array(c).buffer),g=t.dataIdMap.get(o.dataId).id;return kk(h,m,nt[s.dtype],l,u,d,f,p,g),o}var koe={kernelName:Ho,backendName:"wasm",setupFunc:voe,kernelFunc:woe},Ik;function Ioe(e){Ik=e.wasm.cwrap(qo,null,["number","number","number","number","number","number","bool","number"])}function Soe(e){let{inputs:t,backend:a,attrs:n}=e,{sortedSequence:r,values:s}=t,{side:i}=n;if(r.dtype!==s.dtype)throw new Error(`SearchSorted error: sorted_sequence must have the same dtype as values. Got ${r.dtype} and ${s.dtype}`);let o=a.makeOutput(s.shape,"int32");function l(u){return a.dataIdMap.get(u.dataId).id}return Ik(l(r),l(s),r.shape[0],r.shape[1],s.shape[1],nt[r.dtype],i==="left",l(o)),o}var Toe={kernelName:qo,backendName:"wasm",setupFunc:Ioe,kernelFunc:Soe},Sk;function Coe(e){Sk=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function Noe(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),d=a.dataIdMap.get(u.dataId).id,c=n.shape.length,p=r.shape.length,h=c===0||c>1||p===1?1:v.sizeFromShape(r.shape.slice(1));return Sk(i,o,l,h,d),u}var Roe={kernelName:Ou,backendName:"wasm",kernelFunc:Noe,setupFunc:Coe},Eoe=Qe(Xo),Tk;function Moe(e){Tk=e.wasm.cwrap(Rs,null,["number","number"])}function Foe(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||Tk(n,s),r}var $oe={kernelName:"Sigmoid",backendName:"wasm",setupFunc:Moe,kernelFunc:Foe},Doe=Qe(Zo),Poe=Qe(Ko),_oe=Qe(Yo),Ooe=Qe(Jo);function zoe(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=mk.kernelFunc({inputs:{x:r},backend:a,attrs:{paddings:l,constantValue:0}}),d=I.getReshaped(u.shape,s,o,!1),c=I.getPermuted(d.length,s.length,!1),p=I.getReshapedPermuted(u.shape,s,o,!1),h=La({inputs:{x:u},backend:a,attrs:{shape:d}}),m=ps({inputs:{x:h},backend:a,attrs:{perm:c}}),f=La({inputs:{x:m},backend:a,attrs:{shape:p}});return a.disposeData(u.dataId),a.disposeData(h.dataId),a.disposeData(m.dataId),f}var Loe={kernelName:Lu,backendName:"wasm",kernelFunc:zoe},Ck;function Woe(e){Ck=e.wasm.cwrap("SparseFillEmptyRows","number",["number","number","number","number","number","number","number","number","number","number","number","number"])}function Boe(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],d=[o+u,l],c=t.dataIdMap.get(n.dataId).id,p=t.dataIdMap.get(r.dataId).id,h=t.dataIdMap.get(i.dataId).id,m=t.makeOutput(d,n.dtype),f=t.dataIdMap.get(m.dataId).id,g=t.makeOutput(d.slice(0,1),r.dtype),y=t.dataIdMap.get(g.dataId).id,x=t.makeOutput([u],"bool"),A=t.dataIdMap.get(x.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,N=Ck(c,p,nt[r.dtype],o,u,l,h,f,y,A,w,C),M=t.readSync(S.dataId),F;switch(M[0]){case 1:{F=I.getSparseFillEmptyRowsIndicesDenseShapeMismatch(M[1]);break}case 2:{F=I.getSparseFillEmptyRowsNegativeIndexErrorMessage(M[1],M[2]);break}case 3:F=I.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(M[1],M[2],M[3]);break;default:F=""}if(t.disposeData(S.dataId),F)throw t.disposeData(m.dataId),t.disposeData(g.dataId),t.disposeData(x.dataId),t.disposeData(b.dataId),new Error(F);let E=m,T=g;return N!==d[0]&&(E=Mi({inputs:{x:m},attrs:{begin:0,size:[N,l]},backend:t}),T=Mi({inputs:{x:g},attrs:{begin:0,size:N},backend:t}),t.disposeData(m.dataId),t.disposeData(g.dataId)),[E,T,x,b]}var Voe={kernelName:Mp,backendName:"wasm",setupFunc:Woe,kernelFunc:Boe},Nk;function Uoe(e){Nk=e.wasm.cwrap(Bu,null,["number","number","number","number","number","number","number"])}function Goe(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],d=v.sizeFromShape(s.shape),c=t.makeOutput([u,d],n.dtype),p=t.dataIdMap.get(c.dataId).id,h=t.makeOutput([d],s.dtype),m=t.dataIdMap.get(h.dataId).id,f=t.makeOutput([3],"int32"),g=t.dataIdMap.get(f.dataId).id;Nk(i,o,l,u,p,m,g);let y=t.readSync(f.dataId),x;switch(y[0]){case 0:{x=I.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(y[1],y[2]);break}case 1:{x=I.getSparseReshapeNegativeOutputDimErrorMessage(y[1],y[2]);break}case 2:x=I.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();break;case 3:{let A=Array.from(t.readSync(r.dataId)),b=Array.from(t.readSync(h.dataId));x=I.getSparseReshapeInputOutputMultipleErrorMessage(A,b);break}case 4:{let A=Array.from(t.readSync(r.dataId)),b=Array.from(t.readSync(h.dataId));x=I.getSparseReshapeInputOutputMismatchErrorMessage(A,b);break}default:x=""}if(t.disposeData(f.dataId),x)throw t.disposeData(c.dataId),t.disposeData(h.dataId),new Error(x);return[c,h]}var Hoe={kernelName:Bu,backendName:"wasm",setupFunc:Uoe,kernelFunc:Goe},Rk;function Ek(e){Rk=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function Mk(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(I.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let d=r.shape.slice();d[0]=u;let c=a.dataIdMap.get(r.dataId).id,p=a.dataIdMap.get(s.dataId).id,h=a.dataIdMap.get(i.dataId).id,m=a.makeOutput(d,r.dtype),f=a.dataIdMap.get(m.dataId).id,g=a.makeOutput([4],"int32"),y=a.dataIdMap.get(g.dataId).id;Rk(c,nt[r.dtype],r.shape[0],p,h,f,y,t,0);let x=a.readSync(g.dataId),A;switch(x[0]){case 0:{A=I.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break}case 1:{A=I.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break}case 2:A=I.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(x[1],x[2]);break;case 3:A=I.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(x[1],x[2],x[3]);break;default:A=""}if(a.disposeData(g.dataId),A)throw a.disposeData(m.dataId),new Error(A);return m}function joe(e){return Mk(e,!0)}var qoe={kernelName:Vu,backendName:"wasm",setupFunc:Ek,kernelFunc:joe};function Xoe(e){return Mk(e,!1)}var Koe={kernelName:Uu,backendName:"wasm",setupFunc:Ek,kernelFunc:Xoe},Fk;function Yoe(e){Fk=e.wasm.cwrap(tl,null,["number","number","number","number","number","number","number","number","array","number","number"])}function Zoe(e){let{backend:t,inputs:a,attrs:n}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=a,{outputShape:o}=n,l=t.makeOutput(o,i.dtype);if(v.sizeFromShape(o)===0)return l;let{sliceRank:u,numUpdates:d,sliceSize:c,strides:p,outputSize:h}=I.calculateShapes(s,r,o),m=t.dataIdMap.get(r.dataId).id,f=t.dataIdMap.get(s.dataId).id,g=t.dataIdMap.get(i.dataId).id,y=new Uint8Array(new Int32Array(p).buffer),x=t.dataIdMap.get(l.dataId).id;return Fk(m,f,s.shape.length,g,nt[i.dtype],u,d,c,y,h,x),l}var Joe={kernelName:tl,backendName:"wasm",setupFunc:Yoe,kernelFunc:Zoe};function Qoe(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=I.prepareSplitSize(r,s,o),u=new Array(r.shape.length).fill(0),d=r.shape.slice();return l.map(c=>{let p=[...d];p[o]=c;let h=Mi({inputs:{x:r},attrs:{begin:u,size:p},backend:n});return u[o]+=c,h})}var ele={kernelName:Wu,backendName:"wasm",kernelFunc:Qoe},tle=Qe(Es),ale=Qe(Fp),nle=!0,rle=Gt(Ms,nle),$k;function sle(e){$k=e.wasm.cwrap(Ds,null,["number","number","number","number"])}function ile(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 $k(i,r,nt[s.dtype],l),o}var ole={kernelName:Ds,backendName:"wasm",setupFunc:sle,kernelFunc:ile},Dk;function lle(e){Dk=e.wasm.cwrap(al,null,["number","array","number","array","array","array","array","array","number","number"])}function ule(e){let{backend:t,inputs:a,attrs:n}=e,{x:r}=a,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:d,newAxisMask:c,shrinkAxisMask:p}=n,{finalShapeSparse:h,finalShape:m,isIdentity:f,sliceDim0:g,isSimpleSlice:y,begin:x,end:A,strides:b}=wt.sliceInfo(r.shape,s,i,o,l,u,d,c,p),w;if(f)w=La({inputs:{x:r},backend:t,attrs:{shape:m}});else if(g||y){v.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let S=wt.computeOutShape(x,A,b),C=Mi({inputs:{x:r},backend:t,attrs:{begin:x,size:S}});w=La({inputs:{x:C},backend:t,attrs:{shape:m}}),t.disposeData(C.dataId)}else{let S=t.makeOutput(h,"float32"),C=t.dataIdMap.get(r.dataId).id,N=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),M=new Uint8Array(new Int32Array(x).buffer),F=new Uint8Array(new Int32Array(A).buffer),E=new Uint8Array(new Int32Array(b).buffer),T=new Uint8Array(new Int32Array(h).buffer),D=new Uint8Array(new Int32Array(v.computeStrides(h)).buffer),O=t.dataIdMap.get(S.dataId).id;Dk(C,N,r.shape.length,M,F,E,T,D,h.length,O),w=La({inputs:{x:S},backend:t,attrs:{shape:m}}),t.disposeData(S.dataId)}return w}var dle={kernelName:al,backendName:"wasm",setupFunc:lle,kernelFunc:ule};function ple(e){let{backend:t,inputs:a,attrs:n}=e,{data:r,dataSplits:s}=a,{separator:i,nGramWidths:o,leftPad:l,rightPad:u,padWidth:d,preserveShortSequences:c}=n,p=t.readSync(r.dataId),h=t.readSync(s.dataId),[m,f]=N3(p,h,i,o,l,u,d,c),g=t.makeOutput([m.length],"string"),y=t.dataIdMap.get(g.dataId);y.stringBytes=m;let x=t.makeOutput(s.shape,"int32");return t.typedArrayFromHeap(x).set(f),[g,x]}var cle={kernelName:Hu,backendName:"wasm",kernelFunc:ple};function hle(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,d,c]=R3(o,l[0],i),p=d.length,h=t.makeOutput([p,2],"int32");t.typedArrayFromHeap(h).set(u);let m=t.makeOutput([p],"string"),f=t.dataIdMap.get(m.dataId);f.stringBytes=d;let g=t.makeOutput([2],"int32");return t.typedArrayFromHeap(g).set(c),[h,m,g]}var mle={kernelName:$p,backendName:"wasm",kernelFunc:hle};function fle(e){let{backend:t,inputs:a,attrs:n}=e,{input:r}=a,{numBuckets:s}=n,i=t.readSync(r.dataId),o=E3(i,s),l=t.makeOutput(r.shape,"int32");return t.typedArrayFromHeap(l).set(o),l}var gle={kernelName:Dp,backendName:"wasm",kernelFunc:fle},yle=!0,xle=Gt(Fs,yle),Pk;function Ale(e){Pk=e.wasm.cwrap(Qo,null,["number","number","number","number"])}function ble(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:d,axes:c,originalAxes:p,inputWasTransposed:h}=Ls(i,r,t),m=c;if(h){let A=t.dataIdMap.get(d.dataId).id;A!==o&&(u=d,l=A,m=I.getInnerMostAxes(m.length,u.shape.length))}I.assertAxesAreInnerMostDims("sum",m,u.shape.length);let[f,g]=I.computeOutAndReduceShapes(u.shape,m),y=v.sizeFromShape(g),x=t.makeOutput(f,u.dtype);if(v.sizeFromShape(u.shape)!==0){let A=t.dataIdMap.get(x.dataId).id;Pk(l,y,nt[x.dtype],A)}if(h&&t.disposeData(d.dataId),s){let A=I.expandShapeToKeepDim(x.shape,p);x.shape=A}return x}var vle={kernelName:Qo,backendName:"wasm",setupFunc:Ale,kernelFunc:ble},wle=Qe(nl),kle=Qe(rl),_k;function Ile(e){_k=e.wasm.cwrap(jo,null,["number","number","number","number","number","number","array","number","number","number"])}function Sle(e){let{backend:t,inputs:a,attrs:n}=e,{tensor:r,indices:s,updates:i}=a,{}=n,o=t.makeOutput(r.shape,r.dtype);if(v.sizeFromShape(r.shape)===0)return o;let{sliceRank:l,numUpdates:u,sliceSize:d,strides:c,outputSize:p}=Qh.calculateShapes(i,s,r.shape),h=t.dataIdMap.get(s.dataId).id,m=t.dataIdMap.get(i.dataId).id,f=t.dataIdMap.get(r.dataId).id,g=new Uint8Array(new Int32Array(c).buffer),y=t.dataIdMap.get(o.dataId).id;return _k(h,m,nt[i.dtype],l,u,d,g,p,y,f),o}var Tle={kernelName:jo,backendName:"wasm",setupFunc:Ile,kernelFunc:Sle},Ok;function Cle(e){Ok=e.wasm.cwrap($s,null,["number","array","number","array","number","number"])}function Nle(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 p=0;p<o.length;p++)o[p]=r.shape[p]*i[p];let l=new Uint8Array(new Int32Array(r.shape).buffer),u=new Uint8Array(new Int32Array(o).buffer),d=a.makeOutput(o,r.dtype),c=a.dataIdMap.get(d.dataId).id;return Ok(s,l,r.shape.length,u,o.length,nt[d.dtype],c),d}var Rle={kernelName:$s,backendName:"wasm",setupFunc:Cle,kernelFunc:Nle},zk;function Ele(e){zk=e.wasm.cwrap(sl,null,["number","array","number","number","number","bool","number","number"])}var Mle=({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),d=t.dataIdMap.get(u.dataId).id,c=t.makeOutput(l,"int32"),p=t.dataIdMap.get(c.dataId).id;return zk(i,o,n.shape.length,nt[n.dtype],r,s,d,p),[u,c]},Fle={kernelName:sl,backendName:"wasm",setupFunc:Ele,kernelFunc:Mle},Lk;function $le(e){Lk=e.wasm.cwrap(il,null,["number","number","bool","number","number","number","number","number","number","array","number","array","number","number","number","number","number"])}function Dle(e){let{backend:t,inputs:a,attrs:n}=e,{image:r,transforms:s}=a,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=n,[d,c,p,h]=r.shape,[m,f]=u!=null?u:[c,p],g=[d,m,f,h],y=new Uint8Array(new Int32Array(v.computeStrides(r.shape)).buffer),x=new Uint8Array(new Int32Array(v.computeStrides(g)).buffer),A=t.makeOutput(g,r.dtype),b=t.dataIdMap.get(A.dataId).id,w=t.dataIdMap.get(r.dataId).id,S=t.dataIdMap.get(s.dataId).id,C=i==="nearest"?1:2,N;switch(o){case"constant":N=1;break;case"reflect":N=2;break;case"wrap":N=3;break;case"nearest":N=4;break;default:N=1;break}return Lk(w,S,s.shape[0]>1,d,m,f,h,p,c,y,r.shape.length-1,x,g.length-1,C,N,l,b),A}var Ple={kernelName:il,backendName:"wasm",setupFunc:$le,kernelFunc:Dle};function _le(e){let{inputs:t,attrs:a,backend:n}=e,{axis:r}=a,{x:s}=t,{outputValues:i,outputShape:o,indices:l}=F3(n.readSync(s.dataId),r,s.shape,s.dtype);return[n.makeOutput(o,s.dtype,void 0,i),n.makeOutput([l.length],"int32",void 0,l)]}var Ole={kernelName:Pp,backendName:"wasm",kernelFunc:_le};function zle(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 d=new Array(i),c=new Array(o).fill(0),p=r.shape.slice();p[s]=1;for(let h=0;h<d.length;h++)c[s]=h,d[h]=Mi({inputs:{x:r},attrs:{begin:c,size:p},backend:a});return d.map(({dataId:h,dtype:m})=>({dataId:h,dtype:m,shape:l}))}var Lle={kernelName:ju,backendName:"wasm",kernelFunc:zle};function Wle(e){let{inputs:{x:t},backend:a}=e,n=a.makeOutput(t.shape,t.dtype);return a.typedArrayFromHeap(n).fill(0),n}var Ble={kernelName:qu,backendName:"wasm",kernelFunc:Wle},Vle=[kae,Iae,Sae,Tae,Nae,Mae,Lae,Vae,Uae,Gae,Hae,jae,qae,Xae,Kae,Jae,one,tne,rne,pne,yne,bne,wne,Ine,Sne,Tne,Rne,Ene,$ne,_ne,Lne,Vne,Hne,jne,qne,Yne,Qne,are,sre,lre,pre,mre,yre,bre,kre,Ire,Cre,Rre,Ere,Mre,Fre,$re,Dre,Ore,zre,Wre,Ure,jre,Kre,Jre,tse,nse,sse,Fae,ise,ose,lse,pse,hse,fse,xse,bse,Ase,wse,kse,Sse,Cse,Ese,$se,_se,zse,Bse,Gse,qse,Yse,Qse,aie,sie,oie,die,fie,gie,xie,Aie,wie,Sie,Nie,Eie,$ie,Pie,Oie,mk,Bie,Gie,qie,Kie,Zie,Jie,Qie,eoe,lne,noe,ioe,uoe,coe,foe,xoe,Aoe,boe,koe,Toe,Roe,Eoe,$oe,Doe,Poe,_oe,fne,cie,Ooe,Loe,Voe,Hoe,qoe,Koe,Joe,ele,tle,ale,rle,ole,dle,cle,mle,gle,xle,vle,wle,kle,Tle,Rle,Fle,Ple,_ae,Ole,Lle,Ble];for(let e of Vle)bn(e);var Z1=B();Z1.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}});Z1.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(Z1.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 iA=uu(GC()),Ule=uu(HC()),oA=uu(jC()),lA=iA.default||iA,Gle=oA.default||oA,Wk=class extends du{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(Bk),J1=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new hp(this,St())}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)>>>0;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 qle(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,n){let r;if(a==null)r=this.write(n!=null?n:null,e,t);else{let s=this.dataIdNextNumber++;r={id:s},this.dataIdMap.set(r,{id:s,memoryOffset:a,shape:e,dtype:t,refCount:1});let i=v.sizeFromShape(e);this.wasm.tfjs.registerTensor(s,i,a)}return{dataId:r,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 Hle(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 uA(e,t,a){if(Fh!=null)return Fh;let n="tfjs-backend-wasm.wasm";return e&&t?n="tfjs-backend-wasm-threaded-simd.wasm":e&&(n="tfjs-backend-wasm-simd.wasm"),Vd!=null&&Vd[n]!=null?Vd[n]:a+n}async function jle(){let[e,t]=await Promise.all([B().getAsync("WASM_HAS_SIMD_SUPPORT"),B().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((a,n)=>{let r={};r.locateFile=(o,l)=>{if(o.endsWith(".worker.js")){let u=Ule.wasmWorkerContents.replace(/\n/g,"\\n"),d=new Blob([u],{type:"application/javascript"});return URL.createObjectURL(d)}return o.endsWith(".wasm")?uA(e,t,zd!=null?zd:l):l+o},J3&&(r.instantiateWasm=Hle(uA(e,t,zd!=null?zd:"")));let s=!1;r.onAbort=()=>{s||Ud||(Ud=!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&&Fh==null?(r.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+lA.toString()],{type:"text/javascript"}),i=lA(r)):i=Gle(r),i.then(o=>{s=!0,Ud=!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 qle(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 Xle=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],Fh=null,zd=null,Vd={},Ud=!1,J3=!1;function Kle(e,t=!1){if(fg("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),Ud)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");Fh=e,J3=t}function f0(e,t=!1){if(Ud)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")zd=e;else{Vd=e;let a=Xle.filter(n=>Vd[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.`)}J3=t}var Bk=-1,J1=-1;function Yle(e){Bk=e}function Zle(){if(J1===-1)throw new Error("WASM backend not initialized.");return J1}var Jle="4.17.0",Qle=2;ll("wasm",async()=>{let{wasm:e}=await jle();return new Wk(e)},Qle);var vn=B();vn.registerFlag("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE",()=>15);vn.registerFlag("WEBGPU_CPU_FORWARD",()=>!0);vn.registerFlag("WEBGPU_MATMUL_PROGRAM_TYPE",()=>-1);vn.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE",()=>!0);vn.registerFlag("WEBGPU_USE_LOW_POWER_GPU",()=>!1);vn.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e3);vn.registerFlag("WEBGPU_USE_PROFILE_TOOL",()=>!1);vn.registerFlag("WEBGPU_IMPORT_EXTERNAL_TEXTURE",()=>!0);vn.registerFlag("WEBGPU_USE_NAIVE_CONV2D_DEBUG",()=>!1);vn.registerFlag("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL",()=>-1);vn.registerFlag("WEBGPU_CONV_SEPARATE_IM2COL_SHADER",()=>!1);vn.registerFlag("WEBGPU_PRINT_SHADER",()=>"");vn.registerFlag("WEBGPU_ENGINE_COMPILE_ONLY",()=>!1);var eue=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"}},tue=class{constructor(e){this.device=e,this.numUsedBuffers=0,this.numFreeBuffers=0,this.freeBuffers=new Map,this.usedBuffers=new Map,this.numBytesUsed=0,this.numBytesAllocated=0}acquireBuffer(e,t,a=!1,n=!0){let r,s=dA(e,t);return n?(this.freeBuffers.has(s)||this.freeBuffers.set(s,[]),this.freeBuffers.get(s).length>0?(r=this.freeBuffers.get(s).pop(),this.numFreeBuffers--):(r=this.device.createBuffer({size:e,usage:t,mappedAtCreation:a}),this.numBytesAllocated+=e)):(r=this.device.createBuffer({size:e,usage:t,mappedAtCreation:a}),this.numBytesAllocated+=e),this.usedBuffers.has(s)||this.usedBuffers.set(s,[]),this.usedBuffers.get(s).push(r),this.numUsedBuffers++,this.numBytesUsed+=e,r}releaseBuffer(e,t=!0){if(this.freeBuffers.size===0)return;let a=e.size,n=e.usage,r=dA(a,n),s=this.usedBuffers.get(r),i=s.indexOf(e);if(i<0)throw new Error("Cannot find the buffer in buffer manager");s[i]=s[s.length-1],s.pop(),this.numUsedBuffers--,this.numBytesUsed-=a,t?(this.freeBuffers.get(r).push(e),this.numFreeBuffers++):(e.destroy(),this.numBytesAllocated-=a)}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 dA(e,t){return`${e}_${t}`}var aue=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=cA(a),s=e*t*r,i=pA(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){if(this.freeTextures.size===0)return;let t=e.width,a=e.height,n=e.format,r=e.usage,s=pA(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=cA(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 pA(e,t,a,n){return`${e}_${t}_${a}_${n}`}function cA(e){if(e==="rgba8unorm")return 16;throw new Error(`${e} is not supported!`)}function nue(e,t){if(Math.max(...e)>5)throw new Error("Cannot symbolically compute strides for rank > 6 tensor.");let a=e.length,n="xyzwuv",r=e.map(i=>`${t}.${n[i]}`),s=new Array(a-1);s[a-2]=r[a-1];for(let i=a-3;i>=0;--i)s[i]=`(${s[i+1]} * ${r[i+1]})`;return s}var Bs=(e,t,a)=>a==="int32"?`atomicAdd(${e}, bitcast<i32>(${t}));`:`
|
|
{
|
|
var oldValue = 0;
|
|
loop {
|
|
let newValueF32 = bitcast<f32>(oldValue) + (${t});
|
|
let newValue = bitcast<i32>(newValueF32);
|
|
let res = atomicCompareExchangeWeak(${e}, oldValue, newValue);
|
|
if res.exchanged {
|
|
break;
|
|
}
|
|
oldValue = res.old_value;
|
|
}
|
|
}`,lu;(function(e){e[e.FROM_PIXELS=0]="FROM_PIXELS",e[e.DRAW=1]="DRAW"})(lu||(lu={}));var rue=(e,t,a,n,r)=>{let s={dtype:n.dtype,shape:n.shape},i=iue(a,s,t),o=e.createShaderModule({code:i,label:t.constructor.name}),l=B().get("WEBGPU_PRINT_SHADER");if(l!==""){l=l.toLowerCase();let u=l.split(",");(l==="all"||u.some(d=>t.shaderKey.toLowerCase().includes(d)))&&(console.group(t.shaderKey),console.debug(i),console.groupEnd())}return r?e.createComputePipelineAsync({compute:{module:o,entryPoint:"_start"},label:t.constructor.name,layout:"auto"}):e.createComputePipeline({compute:{module:o,entryPoint:"_start"},label:t.constructor.name,layout:"auto"})},Xe=(e,t="f32")=>{switch(e){case 1:return`${t}`;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component ${t} is not supported.`)}};function Dt(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 Nr(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 ue(...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 hA(e,t){let a;return a=`
|
|
${sue(t)}
|
|
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();"};
|
|
}
|
|
`,a}function sue(e){return`
|
|
@compute @workgroup_size(${e.workgroupSize[0]}, ${e.workgroupSize[1]}, ${e.workgroupSize[2]})
|
|
`}function iue(e,t,a){let n=[],r=a.workgroupSize[0]*a.workgroupSize[1]*a.workgroupSize[2];if(a.outputComponent=a.outputComponent?a.outputComponent:1,n.push(`
|
|
|
|
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 {
|
|
${Vk(a)?" return i32(globalId.x);":` return i32((workgroupId.z * numWorkgroups.x * numWorkgroups.y +
|
|
workgroupId.y * numWorkgroups.x + workgroupId.x) * ${r}u +
|
|
localIndex);
|
|
`}
|
|
}
|
|
`),a.pixelsOpType!=null){let h=a.pixelsOpType===lu.FROM_PIXELS?`@group(0) @binding(0) var<storage, read_write> result: array<${gi(t.dtype,a.outputComponent)}>;`:`@group(0) @binding(1) var<storage, read> inBuf : array<${gi(e[0].dtype,a.outputComponent)}>;`,m=t.shape.length===3?"vec2<i32>":"i32";n.push(`
|
|
struct Uniform {
|
|
outShapeStrides : ${m},
|
|
size : i32,
|
|
numChannels : i32,
|
|
alpha : f32,
|
|
};
|
|
|
|
${h}
|
|
@group(0) @binding(2) var<uniform> uniforms: Uniform;
|
|
`);let f=fA(a);return[mA,n.join(`
|
|
`),mh(t.shape),a.getUserCode(),hA(f,a)].join(`
|
|
`)}let s,i,o="struct Uniforms { NAN : f32, INFINITY : f32, ";a.variableNames.forEach((h,m)=>{let f=Dt(e[m].shape.length);o+=`${h.charAt(0).toLowerCase()+h.slice(1)}Shape : ${f}, `,s=e[m].shape.length-1,i=Dt(s),o+=`${h.charAt(0).toLowerCase()+h.slice(1)}ShapeStrides: ${i}, `});let l=Dt(t.shape.length);o+=`outShape : ${l}, `,s=t.shape.length-1,i=Dt(s),o+=`
|
|
outShapeStrides: ${i}, `,a.size&&(o+="size : i32, "),a.uniforms&&(o+=a.uniforms),o+="};",o=fue(o),n.push(o),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<${gi(t.dtype,a.outputComponent)}>;
|
|
`),a.variableNames.forEach((h,m)=>{n.push(`
|
|
@group(0) @binding(${1+m}) var<storage, read> ${h}: array<${a.variableComponents?gi(e[m].dtype,a.variableComponents[m]):gi(e[m].dtype,a.outputComponent)}>;
|
|
`)}),o!==""&&n.push(`
|
|
@group(0) @binding(${1+a.variableNames.length}) var<uniform> uniforms: Uniforms;
|
|
`);let u=cue(t.shape,a.dispatchLayout),d=[mA,n.join(`
|
|
`)+lue,mh(t.shape),u,hue(t.shape.length)];a.atomic||d.push(mue(t.shape,t.dtype,a.outputComponent)),a.variableNames.forEach((h,m)=>{d.push(`${mh(e[m].shape,h)}`)});let c=e.map((h,m)=>pue(h,t.shape,a.variableComponents?a.variableComponents[m]:a.outputComponent,a.dispatchLayout.x.length===t.shape.length)).join(`
|
|
`);d.push(c),d.push(a.getUserCode());let p=fA(a);return d.push(hA(p,a)),d.join(`
|
|
`)}function oue(e,t,a){let n=e.shaderKey;if(e.pixelsOpType!=null)return n;let r=[],s=[];t.forEach(d=>{r.push(d.shape),s.push(d.dtype)}),r.push(a.shape),s.push(a.dtype);let i=t.map(d=>I.getBroadcastDims(d.shape,a.shape)),o=t.map(d=>v.arraysEqual(d.shape,a.shape)).join("_"),l=i.map(d=>d.join("_")).join(";"),u=Vk(e)?"flatDispatch":"";return n+="_"+(e.workgroupSize?e.workgroupSize.join(","):"")+r.map(d=>d.length).join(",")+s.join(",")+e.variableNames.join(",")+l+o+u,n}var mA=`
|
|
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;
|
|
}
|
|
|
|
// 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> {
|
|
let floatToUint: vec4<u32> = bitcast<vec4<u32>>(val);
|
|
return (floatToUint & vec4<u32>(0x7fffffffu)) > vec4<u32>(0x7f800000u);
|
|
}
|
|
`,lue=`
|
|
fn isinf(val: f32) -> bool {
|
|
return abs(val) == uniforms.INFINITY;
|
|
}
|
|
`;function mh(e,t=""){let a=e.length,n=t!==""?`get${t.charAt(0).toUpperCase()+t.slice(1)}CoordsFromIndex`:"getCoordsFromIndex",r=t!==""?`${t.charAt(0).toLowerCase()+t.slice(1)}ShapeStrides`:"outShapeStrides";if(a<=1)return`fn ${n}(index : i32) -> i32 { return index; }`;let s=v.computeStrides(e),i=Dt(a),o=[];for(let u=0;u<a;u++)o.push(`d${u}`);if(s.length===1)return` fn ${n}(index : i32) -> vec2<i32> {
|
|
let d0 = index / uniforms.${r}; let d1 = index - d0 * uniforms.${r};
|
|
return vec2<i32>(d0, d1);
|
|
}`;let l;return l="var index2 = index;"+s.map((u,d)=>{let c=`let ${o[d]} = index2 / uniforms.${r}.${Nr(d)}`,p=d===s.length-1?`let ${o[d+1]} = index2 - ${o[d]} * uniforms.${r}.${Nr(d)}`:`index2 = index2 - ${o[d]} * uniforms.${r}.${Nr(d)}`;return`${c}; ${p};`}).join(""),`
|
|
fn ${n}(index : i32) -> ${i} {
|
|
${l}
|
|
return ${i}(${o.join(",")});
|
|
}
|
|
`}function uue(e,t){let a=e.name,n=e.shape.length,r=Dt(n),s="get"+a.charAt(0).toUpperCase()+a.slice(1),i=["d0","d1","d2","d3","d4","d5"].slice(0,n),o=i.map(d=>`${d} : i32`).join(", ");if(n<1)return`
|
|
fn ${s}() -> ${Xe(t)} {
|
|
return ${Xe(t)}(${a}[0]);
|
|
}
|
|
`;let l=`uniforms.${a.charAt(0).toLowerCase()+a.slice(1)}Shape`,u=`${n}D`;return n===0&&(u="1D"),`
|
|
fn ${s}(${o}) -> ${Xe(t)} {
|
|
return ${Xe(t)}(${a}[getIndexFromCoords${u}(${r}(${i.join(",")}),
|
|
${l})${t===1?"":` / ${t}`}]);
|
|
}
|
|
`}function due(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=Dt(l);if(v.arraysEqual(e.shape,t)&&n)return`
|
|
fn ${i}Index(globalIndex : i32) -> ${Xe(a)} {
|
|
return ${Xe(a)}(${r}[globalIndex]);
|
|
}
|
|
|
|
fn ${i}Coords(coords : ${u}) -> ${Xe(a)} {
|
|
return ${Xe(a)}(${r}[${l>1?"getOutputIndexFromCoords(coords)":"coords"}${a===1?"":` / ${a}`}]);
|
|
}
|
|
`;let d=I.getBroadcastDims(e.shape,t),c=l-o,p="";if(o===0)return`
|
|
fn ${i}Index(globalIndex : i32) -> ${Xe(a)}{
|
|
return get${s}();
|
|
}
|
|
|
|
fn ${i}Coords(coords : ${u}) -> ${Xe(a)}{
|
|
return get${s}();
|
|
}
|
|
`;l<2&&d.length>=1?p="coords = 0;":p=d.map(g=>`coords.${Nr(g+c)} = 0;`).join(`
|
|
`);let h="";if(l<2&&o>0)h="coords";else if(l>1){let g=Dt(o),y=e.shape.map((x,A)=>`coords.${Nr(A+c)}`).join(", ");h=`${g}(${y})`}else h="coords";let m=`uniforms.${r.charAt(0).toLowerCase()+r.slice(1)}Shape`,f=`${o}D`;return`
|
|
fn ${i}Index(globalIndex : i32) -> ${Xe(a)} {
|
|
var coords = getCoordsFromIndex(globalIndex);
|
|
${p}
|
|
return ${Xe(a)}(${r}[getIndexFromCoords${f}(${h}, ${m})${a===1?"":` / ${a}`}]);
|
|
}
|
|
|
|
fn ${i}Coords(coordsIn : ${u}) -> ${Xe(a)} {
|
|
var coords = coordsIn;
|
|
${p}
|
|
return ${Xe(a)}(${r}[getIndexFromCoords${f}(${h}, ${m})${a===1?"":` / ${a}`}]);
|
|
}
|
|
`}function pue(e,t,a,n){let r=uue(e,a);return e.shape.length<=t.length&&(r+=due(e,t,a,n)),r}function cue(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() -> ${Dt(s)}{
|
|
let globalIndex = getGlobalIndex();
|
|
return getCoordsFromIndex(globalIndex);
|
|
}
|
|
`;let o="",l=[a,n,r];for(let p=0;p<l.length;p++){let h=l[p];if(h.length!==0)if(h.length===1)o+=`let d${h[0]} = i32(globalId[${p}]);`;else{let m=nue(h,"uniforms.outShape");o+=`var index${p} = i32(globalId[${p}]);`;for(let f=0;f<m.length;f++)o+=`let d${h[f]} = index${p} / ${m[f]};`,f===m.length-1?o+=`let d${h[f+1]} = index${p} - d${h[f]} * ${m[f]};`:o+=`index${p} = index${p} - d${h[f]} * ${m[f]};`}}let u=[];for(let p=0;p<i;p++)u.push(`d${p}`);let d=Dt(i),c=`fn getOutputCoords() -> ${d} {
|
|
${o}
|
|
`;return u.length===0?c+=`return ${d}(0); }`:c+=`return ${d}(${u.join(",")}); }`,c}function hue(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 Vk(e){return e.dispatch[1]===1&&e.dispatch[2]===1}function gi(e,t=1){if(e==="float32")return Xe(t,"f32");if(e==="int32"||e==="bool")return Xe(t,"i32");throw new Error(`type ${e} is not supported.`)}function mue(e,t,a){let n=e.length,r=gi(t,a),s=`fn setOutputAtIndex(flatIndex : i32, value : ${Xe(a)}) {
|
|
result[flatIndex] = ${r}(value);
|
|
}
|
|
|
|
fn setOutputAtIndexI32(flatIndex : i32, value : ${Xe(a,"i32")}) {
|
|
result[flatIndex] = ${r}(value);
|
|
}
|
|
`;if(n>=2){let i=["d0","d1","d2","d3","d4","d5"].slice(0,n),o=Dt(n);s+=`
|
|
fn setOutputAtCoords(${i.map(l=>`${l} : i32`).join(", ")}, value : ${Xe(a)}) {
|
|
let flatIndex = getOutputIndexFromCoords(${o}(${i.join(", ")}));
|
|
setOutputAtIndex(flatIndex${a===1?"":` / ${a}`}, value);
|
|
}
|
|
fn setOutputAtCoordsI32(${i.map(l=>`${l} : i32`).join(", ")}, value : ${Xe(a,"i32")}) {
|
|
let flatIndex = getOutputIndexFromCoords(${o}(${i.join(", ")}));
|
|
setOutputAtIndexI32(flatIndex${a===1?"":` / ${a}`}, value);
|
|
}
|
|
`}return s}function fue(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 fA(e){return!(e.dispatchLayout.hasOwnProperty("y")&&e.dispatchLayout.y.length!==0||e.dispatchLayout.hasOwnProperty("z")&&e.dispatchLayout.z.length!==0)}var Uk={};Ke(Uk,{GPUBytesPerElement:()=>Q1,MatMulProgramType:()=>Ln,assertNotComplex:()=>ay,computeDispatch:()=>de,computeWorkPerThreadForConv2d:()=>ey,computeWorkgroupInfoForMatMul:()=>Gk,computeWorkgroupSizeForConv2d:()=>Q3,flatDispatchLayout:()=>me,isWebGPUSupported:()=>ty,tilesFitEvenlyIntoShape:()=>gue});var bi=e=>{let t=1;for(let a=0;a<e.length;a++)t*=e[a];return t};function gue(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 de(e,t,a=[1,1,1],n=[1,1,1]){let[r,s,i]=[Math.ceil(bi(e.x.map(o=>t[o]))/(a[0]*n[0])),e.y?Math.ceil(bi(e.y.map(o=>t[o]))/(a[1]*n[1])):1,e.z?Math.ceil(bi(e.z.map(o=>t[o]))/(a[2]*n[2])):1];return[r,s,i]}function Gk(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 Q3(e,t,a=!1){if(a)return[8,8,1];let n=bi(e.x.map(s=>t[s])),r=bi(e.y.map(s=>t[s]));return n<=4?[4,16,1]:r<=4?[16,4,1]:[16,16,1]}function ey(e,t,a=!1){if(a)return[4,4,1];let n=bi(e.x.map(s=>t[s])),r=bi(e.y.map(s=>t[s]));return n<=4?[1,2,1]:r<=4?[2,1,1]:[2,2,1]}function me(e){return{x:e.map((t,a)=>a)}}function Q1(e){if(e==="float32"||e==="int32"||e==="bool"||e==="string")return 4;if(e==="complex64")return 8;throw new Error(`Unknown dtype ${e}`)}function ty(){return!!(globalThis&&globalThis.navigator&&globalThis.navigator.gpu)}function ay(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 WebGPU backend.`)})}var Ln;(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"})(Ln||(Ln={}));var yue=B().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD"),xue=(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]},ny=class Hk extends du{nextDataId(){return Hk.nextDataId++}constructor(t,a){if(super(),this.commandQueueOwnedIds=new WeakSet,this.dispatchCountInPass=0,this.disposed=!1,this.downloadWaitMs=0,this.tensorDataPendingDisposal=[],this.queryResolveBuffer=null,this.querySet=null,this.querySetCount=2,this.stagingPendingDisposal=[],this.uniformPendingDisposal=[],this.uploadWaitMs=0,this.hasReadSyncWarned=!1,this.hasTimestampQueryWarned=!1,!ty())throw new Error("WebGPU is not supported on this device");this.pipelineCache={},this.device=t,this.queue=t.queue,this.commandEncoder=null,this.computePassEncoder=null,this.adapterInfo=new eue(a),this.supportTimestampQuery=this.device.features.has("timestamp-query"),this.thresholdToIncreaseWorkgroups=this.adapterInfo.intelGPUGeneration>=12?16:8,this.bufferManager=new tue(this.device),this.textureManager=new aue(this.device),this.tensorMap=new hp(this,St()),B().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:t,format:"bgra8unorm"}),document.body.appendChild(this.dummyCanvas))}floatPrecision(){return 32}disposeData(t,a=!1){if(!this.tensorMap.has(t))return!0;let n=this.tensorMap.get(t);return a?n.refCount=0:n.refCount--,n.refCount>0?!1:(n.complexTensorInfos!=null&&(this.disposeData(n.complexTensorInfos.real.dataId),this.disposeData(n.complexTensorInfos.imag.dataId)),this.commandQueueOwnedIds.has(t)?(this.tensorDataPendingDisposal.push(t),!0):(this.releaseResource(t),this.tensorMap.delete(t),!0))}memory(){return{numBytesInGPU:this.bufferManager.numBytesUsed,numBytesAllocatedInGPU:this.bufferManager.numBytesAllocated,unreliable:!1}}releaseResource(t){let a=this.tensorMap.get(t);if(!(!a||!a.resource)){if(a.external){a.resource=null;return}a.resource instanceof GPUBuffer?this.bufferManager.releaseBuffer(a.resource):a.resource instanceof GPUTexture&&this.textureManager.releaseTexture(a.resource),a.resource=null}}refCount(t){return this.tensorMap.has(t)?this.tensorMap.get(t).refCount:0}incRef(t){let a=this.tensorMap.get(t);a.refCount++}decRef(t){if(this.tensorMap.has(t)){let a=this.tensorMap.get(t);a.refCount--}}write(t,a,n){if(n==="complex64"&&t!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let r={id:this.nextDataId()};return this.tensorMap.set(r,{dtype:n,shape:a,values:t,refCount:1}),r}move(t,a,n,r,s){if(r==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.tensorMap.set(t,{dtype:r,shape:n,values:a,refCount:s})}submitQueue(){this.queue.submit([this.commandEncoder.finish()]),this.commandEncoder=null,this.dispatchCountInPass=0,this.commandQueueOwnedIds=new WeakSet,this.tensorDataPendingDisposal.forEach(t=>{this.releaseResource(t),this.tensorMap.delete(t)}),this.uniformPendingDisposal.forEach(t=>this.bufferManager.releaseBuffer(t)),this.stagingPendingDisposal.forEach(t=>this.bufferManager.releaseBuffer(t,!1)),this.tensorDataPendingDisposal=[],this.uniformPendingDisposal=[],this.stagingPendingDisposal=[]}ensureCommandEncoderReady(){this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder())}endComputePassEncoder(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}async checkCompileCompletionAsync(){let t;try{t=await Promise.all(Object.values(this.pipelineCache))}catch(a){throw new Error(a.message)}Object.keys(this.pipelineCache).map((a,n)=>{this.pipelineCache[a]=t[n]})}async getBufferData(t){if(B().getBool("WEBGPU_ENGINE_COMPILE_ONLY"))return console.warn("The data may be invalid since WEBGPU_ENGINE_COMPILE_ONLY is true, this can only be called when WEBGPU_ENGINE_COMPILE_ONLY is false"),null;let a=t.size,n=this.bufferManager.acquireBuffer(a,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ);this.ensureCommandEncoderReady(),this.endComputePassEncoder(),this.commandEncoder.copyBufferToBuffer(t,0,n,0,a),this.submitQueue(),await n.mapAsync(GPUMapMode.READ);let r=n.getMappedRange().slice(0);return n.unmap(),n!=null&&this.bufferManager.releaseBuffer(n),B().getBool("WEBGPU_USE_PROFILE_TOOL")&&(v.assert(this.dummyContext!==void 0,()=>"Fail to get context for profiling tool"),this.dummyContext.getCurrentTexture()),r}convertAndCacheOnCPU(t,a){let n=this.tensorMap.get(t);return n.values=a,n.values}readSync(t){let a=this.tensorMap.get(t),{values:n,complexTensorInfos:r}=a;if(n!=null||a.dtype==="string")return n;if(a.dtype==="complex64"){let f=this.readSync(r.real.dataId),g=this.readSync(r.imag.dataId),y=v.convertBackendValuesAndArrayBuffer(I.mergeRealAndImagArrays(f,g).buffer,"float32");return this.convertAndCacheOnCPU(t,y),y}this.hasReadSyncWarned||(this.hasReadSyncWarned=!0,console.warn("The performance of synchronously reading data from GPU to CPU is poor on the webgpu backend, please use asynchronous APIs instead."));let s=["opaque","premultiplied"],i=a.resource,o=i.size;v.assert(o%4===0,()=>"Because there is 4 bytes for one pixel, buffer size must be multiple of 4.");let l=o/4,u=new ArrayBuffer(o),d=256,c=256,p=s.map(f=>new OffscreenCanvas(d,c)),h=new OffscreenCanvas(d,c);this.endComputePassEncoder(),p.map((f,g)=>{let y=f.getContext("webgpu");return y.configure({device:this.device,format:"bgra8unorm",usage:GPUTextureUsage.COPY_DST,alphaMode:s[g]}),y.getCurrentTexture()}).map((f,g)=>{let y=d*4,x=(N,M,F)=>{this.ensureCommandEncoderReady(),this.commandEncoder.copyBufferToTexture({buffer:i,bytesPerRow:y,offset:F},{texture:f},{width:N,height:M}),this.submitQueue();let E=h.getContext("2d",{willReadFrequently:!0});E.clearRect(0,0,N,M),E.drawImage(p[g],0,0);let T=E.getImageData(0,0,N,M).data,D=s[g],O=new Uint8ClampedArray(u,F,N*M*4);for(let W=0;W<O.length;W+=4)if(D==="premultiplied")O[W+3]=T[W+3];else{let $=T[W];O[W]=T[W+2],O[W+1]=T[W+1],O[W+2]=$}},A=Math.floor(l/(d*c)),b=d,w=c,S=0;for(let N=0;N<A;N++)x(b,w,S),S+=d*c*4;let C=l%(d*c);w=Math.floor(C/d),w>0&&(x(b,w,S),S+=w*(d*4)),b=C%d,b>0&&x(b,1,S)});let m=v.convertBackendValuesAndArrayBuffer(u,a.dtype);return this.convertAndCacheOnCPU(t,m),m}async read(t){if(!this.tensorMap.has(t))throw new Error(`Tensor ${t} was not registered!`);let a=this.tensorMap.get(t),{values:n}=a;if(n!=null)return n;let r;if(a.dtype==="complex64"){let s=await Promise.all([this.read(a.complexTensorInfos.real.dataId),this.read(a.complexTensorInfos.imag.dataId)]),i=s[0],o=s[1];r=I.mergeRealAndImagArrays(i,o)}else{let s=await this.getBufferData(a.resource);r=v.convertBackendValuesAndArrayBuffer(s,a.dtype)}return this.convertAndCacheOnCPU(t,r),r}copyBuffer(t){let a=t.size,n=t.usage,r=this.bufferManager.acquireBuffer(a,n);return this.ensureCommandEncoderReady(),this.endComputePassEncoder(),this.commandEncoder.copyBufferToBuffer(t,0,r,0,a),this.submitQueue(),r}createTensorFromGPUData(t,a,n){let r=t.buffer;if(n==="complex64")throw new Error("Cannot write to a complex64 dtype. ");let s={id:this.nextDataId()};this.tensorMap.set(s,{dtype:n,shape:a,values:null,refCount:1,external:t.zeroCopy});let i=this.tensorMap.get(s),o=Q1(i.dtype)*v.sizeFromShape(i.shape);if(t.buffer.size<o)throw new Error(`GPUBuffer size(${t.buffer.size}) is smaller than tensor size(${o})!`);if((t.buffer.usage&(GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC))!==(GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC))throw new Error("GPUBuffer.usage should include GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC!");return t.zeroCopy!==!0&&(r=this.copyBuffer(r)),i.resource=r,St().makeTensorFromDataId(s,a,n,this)}readToGPU(t){let a=this.tensorMap.get(t),{values:n,dtype:r,shape:s,resource:i}=a;if(r==="complex64")throw new Error("Does not support reading buffer for complex64 dtype.");if(i==null)throw n!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");let o=i,l=o.size,u=o.usage,d=this.bufferManager.acquireBuffer(l,u);this.ensureCommandEncoderReady(),this.endComputePassEncoder(),this.commandEncoder.copyBufferToBuffer(i,0,d,0,l),this.submitQueue();let c=this.makeTensorInfo(s,r),p=St().makeTensorFromTensorInfo(c),h=this.tensorMap.get(c.dataId);return h.resource=d,{tensorRef:p,buffer:d}}bufferSync(t){let a=this.readSync(t.dataId);if(t.dtype==="string")try{let n=a.map(r=>v.decodeString(r));return Te(t.shape,t.dtype,n)}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return Te(t.shape,t.dtype,a)}async time(t){!this.supportTimestampQuery&&!this.hasTimestampQueryWarned&&(console.warn("This device doesn't support timestamp-query extension. Start Chrome browser with flag --enable-dawn-features=allow_unsafe_apis to try it again. Otherwise, zero will be shown for the kernel time when profiling mode is enabled."),this.hasTimestampQueryWarned=!0);let a=this.activeTimers,n=[],r=!1;this.programTimersStack==null?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,t();let s=v.flatten(this.activeTimers.map(u=>u.query)).filter(u=>u!=null),i=v.flatten(this.activeTimers.map(u=>u.name)).filter(u=>u!=null);this.activeTimers=a,r&&(this.programTimersStack=null);let o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},l=await Promise.all(s);return o.kernelMs=v.sum(l),o.getExtraProfileInfo=()=>l.map((u,d)=>({name:i[d],ms:u})).map(u=>`${u.name}: ${u.ms}`).join(", "),this.uploadWaitMs=0,this.downloadWaitMs=0,o}makeTensorInfo(t,a,n){return a==="string"&&n!=null&&n.length>0&&v.isString(n[0])&&(n=n.map(r=>v.encodeString(r))),{dataId:this.write(n,t,a),shape:t,dtype:a}}tensorToBinding(t){if(!t)return null;let a=this.tensorMap.get(t.dataId).resource;return a instanceof GPUBuffer?{buffer:a}:a instanceof GPUTexture?a.createView():a}uploadToGPU(t){let a=this.tensorMap.get(t);if(a.resource!=null)return;let n=Q1(a.dtype)*v.sizeFromShape(a.shape),r,s=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST;if(a.values){if(r=this.bufferManager.acquireBuffer(n,s,!0),r.mapState==="unmapped"){let i=this.bufferManager.acquireBuffer(n,GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC,!0,!1),o=i.getMappedRange();a.dtype==="int32"||a.dtype==="bool"?new Int32Array(o).set(a.values):new Float32Array(o).set(a.values),i.unmap(),this.ensureCommandEncoderReady(),this.endComputePassEncoder(),this.commandEncoder.copyBufferToBuffer(i,0,r,0,n),this.stagingPendingDisposal.push(i)}else{let i=r.getMappedRange();a.dtype==="int32"||a.dtype==="bool"?new Int32Array(i).set(a.values):new Float32Array(i).set(a.values),r.unmap()}a.values=null}else r=this.bufferManager.acquireBuffer(n,s);a.resource=r}makeUniforms(t){let a=0,n=0,r=[],s=1;t.forEach(l=>{l.data.length===0&&(l.data=[1]);let u;switch(l.data.length){case 1:u=4;break;case 2:u=8;break;case 3:u=16;break;case 4:u=16;break;case 5:u=16;break;case 6:u=16;break;default:v.assert(!1,()=>`Unsupported ${l.data.length}D shape`)}(n===5||n===6)&&(u=16),u>s&&(s=u),a=Math.ceil(a/u)*u,n=l.data.length,r.push(a),a+=l.data.length*4}),a=Math.ceil(a/s)*s;let i=new ArrayBuffer(a);t.forEach((l,u)=>{let d=r[u];l.type==="int32"?new Int32Array(i,d,l.data.length).set(l.data):l.type==="uint32"?new Uint32Array(i,d,l.data.length).set(l.data):new Float32Array(i,d,l.data.length).set(l.data)});let o=this.bufferManager.acquireBuffer(a,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);return this.queue.writeBuffer(o,0,i,0,a),this.uniformPendingDisposal.push(o),{offset:0,size:a,buffer:o}}runWebGPUProgram(t,a,n,r,s){if(s||(s=this.makeTensorInfo(t.outputShape,n)),v.sizeFromShape(s.shape)===0)return this.tensorMap.get(s.dataId).values=v.getTypedArrayFromDType(s.dtype,0),s;this.uploadToGPU(s.dataId),t.dispatch=xue(this.device,t);let i=a.map((l,u)=>{if(l.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(l.dataId),{dtype:this.tensorMap.get(l.dataId).dtype,shape:l.shape,name:t.variableNames[u]}});t.shaderKey=oue(t,i,s);let o=B().getBool("WEBGPU_ENGINE_COMPILE_ONLY");return t.shaderKey in this.pipelineCache||(this.pipelineCache[t.shaderKey]=rue(this.device,t,i,s,o)),t.pipeline=this.pipelineCache[t.shaderKey],o||this.recordAndSubmit(t,s,a,r),s}recordAndSubmit(t,a,n,r){if(t.pipeline instanceof Promise)throw new Error("Please call checkCompileCompletionAsync to ensure parallel compilation is done!");let s=[],i=[],o="int32";if(t.pixelsOpType==null){s.push({type:"float32",data:[NaN]},{type:"float32",data:[1/0]}),i=n.concat(a).map(h=>h.shape);let p="int32";i.map(h=>{s.push({type:p,data:h});let m=v.computeStrides(h);s.push({type:p,data:m})})}else{let p=v.computeStrides(a.shape);s.push({type:o,data:p})}if(t.size){let p=v.sizeFromShape(t.outputShape);s.push({type:o,data:[t.outputComponent?p/t.outputComponent:p]})}r&&(s=[...s,...r]);let l=[this.tensorToBinding(a),...n.map(p=>this.tensorToBinding(p)),this.makeUniforms(s)];n.forEach(p=>{this.commandQueueOwnedIds.add(p.dataId)}),this.commandQueueOwnedIds.add(a.dataId);let u=this.device.createBindGroup({layout:t.pipeline.getBindGroupLayout(0),entries:l.map((p,h)=>({binding:h,resource:p}))}),d=this.activeTimers!=null;this.ensureCommandEncoderReady();let c={};d&&this.supportTimestampQuery?(this.endComputePassEncoder(),this.querySet==null&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.querySetCount})),c.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:0,endOfPassWriteIndex:1},this.computePassEncoder=this.commandEncoder.beginComputePass(c)):this.computePassEncoder||(this.computePassEncoder=this.commandEncoder.beginComputePass(c)),this.computePassEncoder.setPipeline(t.pipeline),this.computePassEncoder.setBindGroup(0,u),this.computePassEncoder.dispatchWorkgroups(t.dispatch[0],t.dispatch[1],t.dispatch[2]),this.dispatchCountInPass++,(d||B().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE")<=this.dispatchCountInPass||t.pixelsOpType===lu.DRAW)&&(this.endComputePassEncoder(),d?this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime()}):this.submitQueue())}async getQueryTime(){if(!this.supportTimestampQuery)return 0;this.queryResolveBuffer==null&&(this.queryResolveBuffer=this.bufferManager.acquireBuffer(this.querySetCount*8,GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST|GPUBufferUsage.QUERY_RESOLVE)),this.commandEncoder.resolveQuerySet(this.querySet,0,this.querySetCount,this.queryResolveBuffer,0);let t=this.bufferManager.acquireBuffer(this.querySetCount*8,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST);this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.querySetCount*8),this.submitQueue(),await t.mapAsync(GPUMapMode.READ);let a=new BigUint64Array(t.getMappedRange()),n=Number(a[1]-a[0])/1e6;return t.unmap(),this.bufferManager.releaseBuffer(t),n}shouldExecuteOnCPU(t,a=yue){return B().getBool("WEBGPU_CPU_FORWARD")&&t.every(n=>this.tensorMap.get(n.dataId).resource==null&&v.sizeFromShape(n.shape)<a)}numDataIds(){return this.tensorMap.numDataIds()-this.tensorDataPendingDisposal.length}dispose(){this.disposed||(this.querySet!=null&&this.querySet.destroy(),this.bufferManager.dispose(),this.textureManager.dispose(),this.disposed=!0)}};ny.nextDataId=0;ty()&&ll("webgpu",async()=>{let e={powerPreference:B().get("WEBGPU_USE_LOW_POWER_GPU")?"low-power":"high-performance"},t=await navigator.gpu.requestAdapter(e),a={},n=[];t.features.has("timestamp-query")&&n.push("timestamp-query"),t.features.has("bgra8unorm-storage")&&n.push(["bgra8unorm-storage"]),a.requiredFeatures=n;let r=t.limits;a.requiredLimits={maxComputeWorkgroupStorageSize:r.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.maxStorageBufferBindingSize,maxBufferSize:r.maxBufferSize,maxComputeWorkgroupSizeX:r.maxComputeWorkgroupSizeX,maxComputeInvocationsPerWorkgroup:r.maxComputeInvocationsPerWorkgroup};let s=await t.requestDevice(a),i=await t.requestAdapterInfo();return new ny(s,i)},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.ELU_DER=5]="ELU_DER",e[e.EQUAL=6]="EQUAL",e[e.FLOOR_DIV=7]="FLOOR_DIV",e[e.GREATER=8]="GREATER",e[e.GREATER_EQUAL=9]="GREATER_EQUAL",e[e.LESS=10]="LESS",e[e.LESS_EQUAL=11]="LESS_EQUAL",e[e.LOGICAL_AND=12]="LOGICAL_AND",e[e.LOGICAL_OR=13]="LOGICAL_OR",e[e.MAX=14]="MAX",e[e.MIN=15]="MIN",e[e.MOD=16]="MOD",e[e.MUL=17]="MUL",e[e.NOT_EQUAL=18]="NOT_EQUAL",e[e.POW=19]="POW",e[e.PRELU=20]="PRELU",e[e.SQUARED_DIFFERENCE=21]="SQUARED_DIFFERENCE",e[e.SUB=22]="SUB"})(De||(De={}));var Aue="let resultTemp = a + b;",bue="let resultTemp = atan2(a, b);",vue="let resultTemp = areal * breal - aimag * bimag;",wue="let resultTemp = areal * bimag + aimag * breal;",kue="let resultTemp = a / b;",Iue="let resultTemp = select(a * (b + 1.0), a, b >= b - b);",Sue=`
|
|
let zero = sign(a) * 0 + 0;
|
|
let one = sign(b) * 0 + 1;
|
|
let resultTemp = select(zero, one, a == b);
|
|
`,Tue=`
|
|
let remainder =
|
|
select(a % b, round(a % b), (round(a) == a) & (round(b) == b));
|
|
let quotient = (a - remainder) / b;
|
|
let resultTemp =
|
|
round(select(quotient, quotient - 1, sign(remainder) == -sign(b)));
|
|
`,Cue=`
|
|
let zero = sign(a) * 0 + 0;
|
|
let one = sign(b) * 0 + 1;
|
|
let resultTemp = select(zero, one, a > b);
|
|
`,Nue=`
|
|
let zero = sign(a) * 0 + 0;
|
|
let one = sign(b) * 0 + 1;
|
|
let resultTemp = select(zero, one, a >= b);
|
|
`,Rue=`
|
|
let zero = sign(a) * 0 + 0;
|
|
let one = sign(b) * 0 + 1;
|
|
let resultTemp = select(zero, one, a < b);
|
|
`,Eue=`
|
|
let zero = sign(a) * 0 + 0;
|
|
let one = sign(b) * 0 + 1;
|
|
let resultTemp = select(zero, one, a <= b);
|
|
`,Mue="return f32(a >= 1.0 && b >= 1.0);",Fue=`return (vec4<f32>(a >= vec4<f32>(1.0)) *
|
|
vec4<f32>(b >= vec4<f32>(1.0)));`,$ue="return f32(a >= 1.0 || b >= 1.0);",Due=`return min(vec4<f32>(a >= vec4<f32>(1.0)) +
|
|
vec4<f32>(b >= vec4<f32>(1.0)), vec4<f32>(1.0));`,Pue="let resultTemp = max(a, b);",_ue="let resultTemp = min(a, b);",Oue=`
|
|
let isNaN = b == 0.;
|
|
var resultTemp = a % b;
|
|
resultTemp = select((resultTemp + b) % b, resultTemp,
|
|
(a < 0. && b < 0.) || (a >= 0. && b > 0.));
|
|
`,zue=`
|
|
let isNaN = !vec4<bool>(b);
|
|
var resultTemp = vec4<f32>(a % b);
|
|
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];
|
|
}
|
|
`,Lue="let resultTemp = a * b;",Wue=`
|
|
var resultTemp = f32(a != b);
|
|
let valueForNaN = 1.0;
|
|
`,Bue=`
|
|
var resultTemp = vec4<f32>(a != b);
|
|
let valueForNaN = 1.0;
|
|
`,Vue=`
|
|
let isNaN = a < 0.0 && floor(b) < b;
|
|
if (b == 0.0) {
|
|
return 1.0;
|
|
}
|
|
var resultTemp = select(sign(a) * pow(abs(a), b), pow(abs(a), b),
|
|
round(abs(b) % 2.0) != 1.0);
|
|
`,Uue=`
|
|
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);
|
|
`,Gue="if (a < 0.0) { return b * a; } return a;",Hue=`
|
|
let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
|
|
return (aLessThanZero * (b * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
|
|
`,jue="let resultTemp = (a - b) * (a - b);",que="let resultTemp = a - b;";function ry(e,t){let a;do{switch(e){case De.ATAN2:a=bue;break;case De.MAX:a=Pue;break;case De.MIN:a=_ue;break;case De.MOD:a=t?zue:Oue;break;case De.NOT_EQUAL:a=t?Bue:Wue;break;case De.POW:a=t?Uue:Vue;break;default:continue}let n,r,s;return t?(n="isnanVec4",r="vec4<f32>",s="vec4<bool>"):(n="isnan",r="f32",s="bool"),`
|
|
let aIsNaN = ${n}(a);
|
|
let aPostLegalization = select(a, ${r}(42), aIsNaN);
|
|
let bIsNaN = ${n}(b);
|
|
let bPostLegalization = select(b, ${r}(42), bIsNaN);
|
|
let isNaN = false;
|
|
let valueForNaN = uniforms.NAN;
|
|
{
|
|
let a = aPostLegalization;
|
|
let b = bPostLegalization;
|
|
${a}
|
|
return select(
|
|
resultTemp, ${r}(valueForNaN),
|
|
${s}(isNaN) | aIsNaN | bIsNaN);
|
|
}
|
|
`}while(!1);switch(e){case De.ADD:a=Aue;break;case De.COMPLEX_MULTIPLY_IMAG:a=wue;break;case De.COMPLEX_MULTIPLY_REAL:a=vue;break;case De.DIV:a=kue;break;case De.ELU_DER:a=Iue;break;case De.EQUAL:a=Sue;break;case De.FLOOR_DIV:a=Tue;break;case De.GREATER:a=Cue;break;case De.GREATER_EQUAL:a=Nue;break;case De.LESS:a=Rue;break;case De.LESS_EQUAL:a=Eue;break;case De.LOGICAL_AND:return t?Fue:Mue;case De.LOGICAL_OR:return t?Due:$ue;case De.MUL:a=Lue;break;case De.PRELU:return t?Hue:Gue;case De.SQUARED_DIFFERENCE:a=jue;break;case De.SUB:a=que;break;default:}return`
|
|
${a}
|
|
return resultTemp;
|
|
`}var le;(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.ROUND=27]="ROUND",e[e.RSQRT=28]="RSQRT",e[e.SELU=29]="SELU",e[e.SIGMOID=30]="SIGMOID",e[e.SIGN=31]="SIGN",e[e.SIN=32]="SIN",e[e.SINH=33]="SINH",e[e.SOFTPLUS=34]="SOFTPLUS",e[e.SQRT=35]="SQRT",e[e.SQUARE=36]="SQUARE",e[e.STEP=37]="STEP",e[e.TAN=38]="TAN",e[e.TANH=39]="TANH",e[e.TO_INT=40]="TO_INT"})(le||(le={}));var Xue="return abs(a);",Kue=`
|
|
if (abs(a) > 1.) {
|
|
return uniforms.NAN;
|
|
}
|
|
return acos(a);
|
|
`,Yue=`
|
|
if (a < 1.) {
|
|
return uniforms.NAN;
|
|
}
|
|
return acosh(a);
|
|
`,Zue=`
|
|
if (abs(a) > 1.) {
|
|
return uniforms.NAN;
|
|
}
|
|
return asin(a);
|
|
`,Jue="return asinh(a);",Que=`
|
|
if (isnan(a)) {
|
|
return uniforms.NAN;
|
|
}
|
|
return atan(a);
|
|
`,ede=`
|
|
if (abs(a) > 1.) {
|
|
return uniforms.NAN;
|
|
}
|
|
if (a == 1.) {
|
|
return uniforms.INFINITY;
|
|
}
|
|
if (a == -1.) {
|
|
return -uniforms.INFINITY;
|
|
}
|
|
return atanh(a);
|
|
`,tde="return ceil(a);",ade="return cos(a);",nde=`
|
|
let e2x = exp(-a);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,rde="return exp(a) - 1.0;",sde="if (a >= 0.0) { return a; } return (exp(a) - 1.0);",ide=`
|
|
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;
|
|
`,ode=`
|
|
// Error function is calculated approximately with elementary function.
|
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
let p = ${I.ERF_P};
|
|
let a1 = ${I.ERF_A1};
|
|
let a2 = ${I.ERF_A2};
|
|
let a3 = ${I.ERF_A3};
|
|
let a4 = ${I.ERF_A4};
|
|
let a5 = ${I.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));
|
|
`,lde="return exp(a);",ude="return floor(a);",dde="return f32(!isnan(a) && !isinf(a));",pde="return f32(isinf(a));",cde="return f32(isnan(a));",hde="return a;",mde=`if (a < 0.0) { return uniforms.NAN; }
|
|
return log(a);`,fde=`
|
|
if (isnan(a)) { return a; }
|
|
return log(1.0 + a);
|
|
`,gde="return f32(!(a >= 1.0));",yde="return -a;",xde="if (a < 0.0) { return uniforms.alpha * a; } return a;",Ade=`
|
|
let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
|
|
return (aLessThanZero * (uniforms.alpha * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
|
|
`,bde="return 1.0 / a;",vde="return select(a, 0.0, a < 0.0);",wde="return clamp(a, 0.0, 6.0);",kde="return clamp(a, vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<f32>(6.0, 6.0, 6.0, 6.0));",Ide=`
|
|
return select(a, vec4<f32>(0.0), a < vec4<f32>(0.0));
|
|
`,Sde="return round(a);",Tde="return inverseSqrt(a);",Cde=`
|
|
if (a >= 0.0) {
|
|
return ${I.SELU_SCALE} * a;
|
|
} else {
|
|
return ${I.SELU_SCALEALPHA} * (exp(a) - 1.0);
|
|
}
|
|
`,Nde="return 1.0 / (1.0 + exp(-1.0 * a));",Rde="return sign(a);",Ede="return sin(a);",Mde=`
|
|
let e2x = exp(a);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,Fde=`
|
|
let epsilon = 1.1920928955078125e-7;
|
|
let threshold = log(epsilon) + 2.0;
|
|
|
|
let too_large = a > -threshold;
|
|
let too_small = a < threshold;
|
|
let exp_a = exp(a);
|
|
|
|
if (too_large) {
|
|
return a;
|
|
} else if (too_small) {
|
|
return exp_a;
|
|
} else {
|
|
return log(exp_a + 1.0);
|
|
}
|
|
`,$de="return sqrt(a);",Dde="return a * a;",Pde=`
|
|
if (isnan(a)) {
|
|
return a;
|
|
}
|
|
|
|
return select(uniforms.stepAlpha, 1.0, a > 0.0);
|
|
`,_de="return tan(a);",Ode=`
|
|
let e2x = exp(-2.0 * abs(a));
|
|
return sign(a) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,zde="return f32(i32((a)));";function pi(e,t){switch(e){case le.ABS:return Xue;case le.ACOS:return Kue;case le.ACOSH:return Yue;case le.ASIN:return Zue;case le.ASINH:return Jue;case le.ATAN:return Que;case le.ATANH:return ede;case le.COS:return ade;case le.COSH:return nde;case le.CEIL:return tde;case le.ELU:return t?ide:sde;case le.ERF:return ode;case le.EXP:return lde;case le.EXPM1:return rde;case le.FLOOR:return ude;case le.IS_FINITE:return dde;case le.IS_INF:return pde;case le.IS_NAN:return cde;case le.LINEAR:return hde;case le.LOG:return mde;case le.LOG1P:return fde;case le.LOGICAL_NOT:return gde;case le.NEG:return yde;case le.LEAKYRELU:return t?Ade:xde;case le.RECIPROCAL:return bde;case le.RELU:return t?Ide:vde;case le.RELU6:return t?kde:wde;case le.ROUND:return Sde;case le.RSQRT:return Tde;case le.SELU:return Cde;case le.SIGMOID:return Nde;case le.SIGN:return Rde;case le.SIN:return Ede;case le.SINH:return Mde;case le.SOFTPLUS:return Fde;case le.SQRT:return $de;case le.SQUARE:return Dde;case le.STEP:return Pde;case le.TAN:return _de;case le.TANH:return Ode;case le.TO_INT:return zde;default:throw new Error(`BinaryType ${e} is not implemented!`)}}function Or(e,t=!1,a=!1,n=3){if(e===null)return"";let r="";if(e==="linear")r=pi(le.LINEAR);else if(e==="relu")r=pi(le.RELU,a);else if(e==="elu")r=pi(le.ELU,a);else if(e==="relu6")r=pi(le.RELU6,a);else if(e==="prelu")r=ry(De.PRELU,a);else if(e==="sigmoid")r=pi(le.SIGMOID,a);else if(e==="leakyrelu")r=pi(le.LEAKYRELU,a);else throw new Error(`Activation ${e} has not been implemented for the WebGPU backend.`);let s=Xe(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 ml(e,t){return`
|
|
${e?"value = value + getBiasByOutputCoords(coords);":""}
|
|
${t?"value = activation(value, coords);":""}
|
|
`}function jk(e,t,a=!1,n=!1,r=!1,s=1){v.assert(e&&s===1||!e,()=>`transposeA ${e} is not compatible with component size ${s}`);let i=`
|
|
${e?"value = getA(batch, col, row);":"value = getA(batch, row, col);"}
|
|
|
|
`,o=t?"value = getB(batch, col, row);":"value = getB(batch, row, col);";return`
|
|
fn mm_readA(batch: i32, row: i32, col: i32) -> ${Xe(s)} {
|
|
var value = ${Xe(s)}(0.0);
|
|
${a&&r?i:`
|
|
${e?"if(row < uniforms.dimAOuter && col < uniforms.dimInner)":"if(row < uniforms.aShape[1] && col < uniforms.aShape[2])"}
|
|
{
|
|
${i}
|
|
}
|
|
`}
|
|
return value;
|
|
}
|
|
|
|
fn mm_readB(batch: i32, row: i32, col: i32) -> ${Xe(s)} {
|
|
var value = ${Xe(s)}(0.0);
|
|
${o}
|
|
return value;
|
|
}
|
|
`}function sy(e,t,a,n,r=!1,s=!1,i=!1,o=1){return`
|
|
${jk(a,n,r,s,i,o)}
|
|
fn mm_write(batch: i32, row: i32, col: i32, valueIn: ${Xe(o)}) {
|
|
${r&&s?"":"if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)"}
|
|
{
|
|
var value = valueIn;
|
|
let coords = vec3<i32>(batch, row, col);
|
|
${ml(e,t)}
|
|
setOutputAtCoords(coords[0], coords[1], coords[2], value);
|
|
}
|
|
}
|
|
`}var Lde=(e,t)=>e?`
|
|
mm_Asub[inputRow][inputCol] = mm_readA(batchA,
|
|
kStart + inputRow,
|
|
globalRowStart + inputCol * ${t});
|
|
`:`
|
|
mm_Asub[inputRow][inputCol] = mm_readA(batchA,
|
|
globalRow + innerRow,
|
|
kStart + inputCol * ${t});
|
|
`,Wde=(e,t,a,n)=>{if(e)return`
|
|
for (var k = 0; k < ${n}; k++) {
|
|
let BCached0 = mm_Bsub[k][tileCol];
|
|
let ACached0 = mm_Asub[k][localRow];
|
|
for (var i = 0; i < ${a}; i++) {
|
|
acc[i] = fma(BCached0, vec4<f32>(ACached0[i]), acc[i]);
|
|
}
|
|
}`;{let r="",s="";for(let i=0;i<t;i++)r+=`let BCached${i} = mm_Bsub[k * ${t} + ${i}][tileCol];`,s+=`acc[i] = fma(BCached${i}, vec4<f32>(ACached[${i}]), acc[i]);`;return`
|
|
for (var k = 0; k < ${n/t}; k++) {
|
|
${r}
|
|
for (var i = 0; i < ${a}; i++) {
|
|
let ACached = mm_Asub[tileRow + i][k];
|
|
${s}
|
|
}
|
|
}`}};function g0(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,d=a?n:o,c=u/t[0],p=n/t[1],h=e[1],m=e[0];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}>, ${d}>;
|
|
var<workgroup> mm_Bsub : array<array<vec4<f32>, ${l/e[0]}>, ${n}>;
|
|
|
|
${ue()} {
|
|
let localRow = i32(localId.y);
|
|
let tileRow = localRow * ${h};
|
|
let tileCol = i32(localId.x);
|
|
|
|
let globalRow = i32(globalId.y) * ${h};
|
|
let globalCol = i32(globalId.x) * ${m};
|
|
let batch = ${r?"0":"i32(globalId.z)"};
|
|
let batchA = ${r||!i?"batch":"batch % uniforms.aShape[0]"};
|
|
let batchB = ${r||!i?"batch":"batch % uniforms.bShape[0]"};
|
|
let globalRowStart = i32(workgroupId.y) * ${o};
|
|
|
|
let numTiles = ${r?`${Math.ceil(s/n)}`:`(uniforms.dimInner - 1) / ${n} + 1`};
|
|
var kStart = ${r?`i32(globalId.z) * ${s}`:"0"};
|
|
|
|
var acc: array<vec4<f32>, ${h}>;
|
|
|
|
// Loop over shared dimension.
|
|
let tileRowB = localRow * ${p};
|
|
for (var t = 0; t < numTiles; t++) {
|
|
// Load one tile of A into local memory.
|
|
for (var innerRow = 0; innerRow < ${h}; innerRow++) {
|
|
let inputRow = tileRow + innerRow;
|
|
let inputCol = tileCol;
|
|
${Lde(a,c)}
|
|
}
|
|
|
|
// Load one tile of B into local memory.
|
|
for (var innerRow = 0; innerRow < ${p}; innerRow++) {
|
|
let inputRow = tileRowB + innerRow;
|
|
let inputCol = tileCol;
|
|
mm_Bsub[inputRow][inputCol] = mm_readB(batchB, kStart + inputRow, globalCol);
|
|
}
|
|
kStart = kStart + ${n};
|
|
workgroupBarrier();
|
|
|
|
// Compute acc values for a single thread.
|
|
${Wde(a,c,h,n)}
|
|
workgroupBarrier();
|
|
}
|
|
|
|
for (var innerRow = 0; innerRow < ${h}; innerRow++) {
|
|
mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);
|
|
}
|
|
}`}var gA=e=>e?`
|
|
mm_Asub[inputRow][inputCol] = mm_readA(batchA,
|
|
kStart + inputRow,
|
|
globalRowStart + inputCol);
|
|
`:`
|
|
mm_Asub[inputRow][inputCol] = mm_readA(batchA,
|
|
globalRowStart + inputRow,
|
|
kStart + inputCol);
|
|
`,Bde=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];";function y0(e,t,a=!1,n=32,r=!1,s=32,i=!1,o=!1){let l=e[1]*t[1],u=e[0]*t[0],d=a?l:n,c=a?n:l;v.assert(c%t[1]===0&&d%t[0]===0&&n%t[1]===0,()=>`tileAHight ${c} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${d} must be divisible by workgroupSize[0]${t[0]}, tileInner ${n} must be divisible by workgroupSize[1]${t[1]}`);let p=c/t[1],h=d/t[0],m=n/t[1],f=e[1],g=e[0],y=i?`
|
|
let localRow = i32(localId.y);
|
|
let localCol = i32(localId.x);
|
|
let globalRowStart = i32(workgroupId.y) * ${l};
|
|
let globalColStart = i32(workgroupId.x) * ${u};
|
|
|
|
// Loop over shared dimension.
|
|
for (var t = 0; t < numTiles; t++) {
|
|
// Load one tile of A into local memory.
|
|
for (var inputRow = localRow; inputRow < ${c}; inputRow = inputRow + ${t[1]}) {
|
|
for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${t[0]}) {
|
|
${gA(a)}
|
|
}
|
|
}
|
|
// Load one tile of B into local memory.
|
|
for (var inputRow = localRow; inputRow < ${n}; inputRow = inputRow + ${t[1]}) {
|
|
for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${t[0]}) {
|
|
mm_Bsub[inputRow][inputCol] = mm_readB(batchB,
|
|
kStart + inputRow,
|
|
globalColStart + inputCol);
|
|
}
|
|
}
|
|
kStart = kStart + ${n};
|
|
workgroupBarrier();
|
|
|
|
// Compute acc values for a single thread.
|
|
var BCached : array<f32, ${g}>;
|
|
for (var k = 0; k < ${n}; k++) {
|
|
for (var inner = 0; inner < ${g}; inner++) {
|
|
BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];
|
|
}
|
|
for (var innerRow = 0; innerRow < ${f}; innerRow++) {
|
|
let ACached = ${a?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}
|
|
for (var innerCol = 0; innerCol < ${g}; innerCol++) {
|
|
acc[innerRow][innerCol] =
|
|
fma(ACached, BCached[innerCol], acc[innerRow][innerCol]);
|
|
}
|
|
}
|
|
}
|
|
workgroupBarrier();
|
|
}
|
|
for (var innerRow = 0; innerRow < ${f}; innerRow++) {
|
|
let gRow = globalRowStart + localRow + innerRow * ${t[1]};
|
|
for (var innerCol = 0; innerCol < ${g}; innerCol++) {
|
|
let gCol = globalColStart + localCol + innerCol * ${t[0]};
|
|
mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);
|
|
}
|
|
}
|
|
`:`
|
|
let tileRow = i32(localId.y) * ${f};
|
|
let tileCol = i32(localId.x) * ${g};
|
|
|
|
let globalRow = i32(globalId.y) * ${f};
|
|
let globalCol = i32(globalId.x) * ${g};
|
|
let globalRowStart = i32(workgroupId.y) * ${l};
|
|
|
|
let tileRowA = i32(localId.y) * ${p};
|
|
let tileColA = i32(localId.x) * ${h};
|
|
let tileRowB = i32(localId.y) * ${m};
|
|
// Loop over shared dimension.
|
|
for (var t = 0; t < numTiles; t++) {
|
|
// Load one tile of A into local memory.
|
|
for (var innerRow = 0; innerRow < ${p}; innerRow++) {
|
|
for (var innerCol = 0; innerCol < ${h}; innerCol++) {
|
|
let inputRow = tileRowA + innerRow;
|
|
let inputCol = tileColA + innerCol;
|
|
${gA(a)}
|
|
}
|
|
}
|
|
|
|
// Load one tile of B into local memory.
|
|
for (var innerRow = 0; innerRow < ${m}; innerRow++) {
|
|
for (var innerCol = 0; innerCol < ${g}; innerCol++) {
|
|
let inputRow = tileRowB + innerRow;
|
|
let inputCol = tileCol + innerCol;
|
|
mm_Bsub[inputRow][inputCol] = mm_readB(batchB,
|
|
kStart + inputRow,
|
|
globalCol + innerCol);
|
|
}
|
|
}
|
|
kStart = kStart + ${n};
|
|
workgroupBarrier();
|
|
|
|
// Compute acc values for a single thread.
|
|
var BCached : array<f32, ${g}>;
|
|
for (var k = 0; k < ${n}; k++) {
|
|
for (var inner = 0; inner < ${g}; inner++) {
|
|
BCached[inner] = mm_Bsub[k][tileCol + inner];
|
|
}
|
|
|
|
for (var innerRow = 0; innerRow < ${f}; innerRow++) {
|
|
${Bde(a)}
|
|
for (var innerCol = 0; innerCol < ${g}; innerCol++) {
|
|
acc[innerRow][innerCol] =
|
|
fma(ACached, BCached[innerCol], acc[innerRow][innerCol]);
|
|
}
|
|
}
|
|
}
|
|
|
|
workgroupBarrier();
|
|
}
|
|
|
|
for (var innerRow = 0; innerRow < ${f}; innerRow++) {
|
|
for (var innerCol = 0; innerCol < ${g}; innerCol++) {
|
|
mm_write(batch, globalRow + innerRow, globalCol + innerCol,
|
|
acc[innerRow][innerCol]);
|
|
}
|
|
}
|
|
`;return`
|
|
var<workgroup> mm_Asub : array<array<f32, ${d}>, ${c}>;
|
|
var<workgroup> mm_Bsub : array<array<f32, ${u}>, ${n}>;
|
|
|
|
${ue()} {
|
|
let batch = ${r?"0":"i32(globalId.z)"};
|
|
let batchA = ${r||!o?"batch":"batch % uniforms.aShape[0]"};
|
|
let batchB = ${r||!o?"batch":"batch % uniforms.bShape[0]"};
|
|
let numTiles = ${r?`${Math.ceil(s/n)}`:`(uniforms.dimInner - 1) / ${n} + 1`};
|
|
var kStart = ${r?`i32(globalId.z) * ${s}`:"0"};
|
|
|
|
var acc : array<array<f32, ${g}>, ${f}>;
|
|
|
|
// Without this initialization strange values show up in acc.
|
|
for (var innerRow = 0; innerRow < ${f}; innerRow++) {
|
|
for (var innerCol = 0; innerCol < ${g}; innerCol++) {
|
|
acc[innerRow][innerCol] = 0.0;
|
|
}
|
|
}
|
|
${y}
|
|
}
|
|
`}var Vde=e=>e?`
|
|
mm_readA(batchA, colA, globalRow),
|
|
mm_readA(batchA, colA + 1, globalRow),
|
|
mm_readA(batchA, colA + 2, globalRow),
|
|
mm_readA(batchA, colA + 3, globalRow)
|
|
`:`
|
|
mm_readA(batchA, globalRow, colA),
|
|
mm_readA(batchA, globalRow, colA + 1),
|
|
mm_readA(batchA, globalRow, colA + 2),
|
|
mm_readA(batchA, globalRow, colA + 3)
|
|
`;function Ude(e,t=!1){v.assert(e[1]===1&&e[2]===1,()=>`A linear work group size is required. But got ${e}.`);let a=e[0]*4;return`
|
|
var<workgroup> mm_Asub : array<vec4<f32>, ${e[0]}>;
|
|
|
|
${ue()} {
|
|
let tileCol = i32(localId.x);
|
|
let globalCol = i32(globalId.x);
|
|
let globalRow = i32(globalId.y);
|
|
|
|
let numTiles = (uniforms.dimInner - 1) / ${a} + 1;
|
|
let batch = i32(globalId.z);
|
|
let batchA = batch % uniforms.aShape[0];
|
|
let batchB = batch % uniforms.bShape[0];
|
|
// Without this initialization strange values show up in acc.
|
|
var acc = 0.0;
|
|
|
|
// Loop over shared dimension.
|
|
for (var t = 0; t < numTiles; t++) {
|
|
// Load one tile of A into local memory.
|
|
let colA = t * ${a} + tileCol * 4;
|
|
mm_Asub[tileCol] = vec4<f32>(${Vde(t)});
|
|
workgroupBarrier();
|
|
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < ${a/4}; k++) {
|
|
let rowB = t * ${a} + k * 4;
|
|
let BCached = vec4<f32>(mm_readB(batchB, rowB, globalCol),
|
|
mm_readB(batchB, rowB + 1, globalCol),
|
|
mm_readB(batchB, rowB + 2, globalCol),
|
|
mm_readB(batchB, rowB + 3, globalCol));
|
|
|
|
let ACached = mm_Asub[k];
|
|
acc = acc + dot(ACached, BCached);
|
|
}
|
|
|
|
workgroupBarrier();
|
|
}
|
|
|
|
mm_write(batch, globalRow, globalCol, acc);
|
|
}
|
|
`}var Gde=class{constructor(e,t,a=!1,n=!1,r=null,s=null,i=null,o=!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 l=a?e[1]:e[2];if(this.isVec4=(l%4===0&&!a||t[1]%4===0&&a)&&t[2]%4===0&&!n,this.outputComponent=this.isVec4?4:1,this.isVectorA=t[1]===1&&!a,!this.isVec4&&this.isVectorA)this.elementsPerThread=[1,1,1],this.workgroupSize=[32,1,1];else{let c=Gk(t[1],l,t[2],a);this.workgroupSize=c.workgroupSize,this.elementsPerThread=c.elementsPerThread}this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize,this.elementsPerThread);let u=r!=null,d=i!=null;u&&this.variableNames.push("bias"),d&&this.variableNames.push("preluActivationWeights"),this.sequentialAccessByThreads=o,this.transposeA=a,this.transposeB=n,this.addBias=u,this.activation=s,this.hasPreluActivationWeights=d,[this.fitAOuter,this.fitBOuter,this.fitInner]=this.getShapeFit(t[1],t[2],l),this.shaderKey=`matMulPacked_${this.elementsPerThread}_${a}_${n}_${this.activation}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.isVec4}_${this.isVectorA}_${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`
|
|
${Or(this.activation,this.hasPreluActivationWeights,this.isVec4)}
|
|
${sy(this.addBias,this.activation,!1,this.transposeB,this.fitAOuter,this.fitBOuter,this.fitInner,this.isVec4?4:1)}
|
|
${this.isVec4?g0(this.elementsPerThread,this.workgroupSize,this.transposeA,this.tileInner,!1,null,!0):this.isVectorA?Ude(this.workgroupSize,this.transposeA):y0(this.elementsPerThread,this.workgroupSize,this.transposeA,this.tileInner,!1,null,this.sequentialAccessByThreads,!0)}
|
|
`}};function Hde(e){return`
|
|
var<workgroup> sumValues : array<f32, ${e}>;
|
|
${ue()} {
|
|
let coords = getOutputCoords();
|
|
let batch = coords[0];
|
|
let batchA = batch % uniforms.aShape[0];
|
|
let batchB = batch % uniforms.bShape[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 + ${e}) {
|
|
let dataA = mm_readA(batchA, row, k);
|
|
let dataB = mm_readB(batchB, k, col);
|
|
sum = sum + dataA * dataB;
|
|
}
|
|
sumValues[localId.x] = sum;
|
|
workgroupBarrier();
|
|
|
|
for(var currentSize = ${e/2}u; 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 jde=class{constructor(e,t=!1,a=!1,n=null,r=null,s=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=de(this.dispatchLayout,this.outputShape,this.workgroupSize);let i=n!=null,o=s!=null;i&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),this.transposeA=t,this.transposeB=a,this.addBias=i,this.activation=r,this.hasPreluActivationWeights=o,this.shaderKey=`matMulReduce_${this.activation}_${t}_${a}`}getUserCode(){return`
|
|
${Or(this.activation,this.hasPreluActivationWeights)}
|
|
${sy(this.addBias,this.activation,this.transposeA,this.transposeB)}
|
|
${Hde(this.workgroupSize[0])}
|
|
`}};function qde(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.
|
|
${ue()} {
|
|
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);
|
|
let batchA = batch % uniforms.aShape[0];
|
|
let batchB = batch % uniforms.bShape[0];
|
|
|
|
// 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(batchA, globalRow, globalColA);
|
|
var regB0 = mm_readB(batchB, globalRowB + 2 * tileRow, globalCol);
|
|
var regB1 = mm_readB(batchB, 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(batchA, globalRow, globalColA);
|
|
regB0 = mm_readB(batchB, globalRowB + 2 * tileRow, globalCol);
|
|
regB1 = mm_readB(batchB, 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 Xde=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.shaderKey=`matMulSmallOutputSize_${this.activation}_${n}_${r}`}getUserCode(){return`
|
|
${Or(this.activation,this.hasPreluActivationWeights)}
|
|
${sy(this.addBias,this.activation,this.transposeA,this.transposeB)}
|
|
${qde(this.workgroupSize)}
|
|
`}},Kde=class{constructor(e,t,a=!1,n=!1){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32, dimBOuter : i32, dimInner : i32,",this.workgroupSize=[8,8,1],this.atomic=!0,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]};let r=(a&&this.outputShape[1]%4===0||!a&&t%4===0)&&this.outputShape[2]%4===0;this.elementsPerThread=[4,4,this.splitedDimInner],this.outputComponent=r?4:1,r||(this.outputShape[1]<16&&(this.elementsPerThread[1]=1),this.outputShape[2]<16&&(this.elementsPerThread[0]=1)),this.dispatch=de(this.dispatchLayout,[this.outputShape[0],this.outputShape[1],this.outputShape[2],t],this.workgroupSize,this.elementsPerThread),this.transposeA=a,this.transposeB=n,this.shaderKey=`matMulSplitK_${a}_${n}_${this.elementsPerThread}_${this.outputComponent}`}getUserCode(){let e=this.outputComponent;return`
|
|
${jk(!1,this.transposeB,!1,!1,!1,e)}
|
|
fn mm_write(batch: i32, row : i32, col : i32, value : ${Xe(e)}) {
|
|
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.
|
|
for (var i = 0; i < ${e}; i = i + 1) {
|
|
${Bs("&result[flatIndex + i]",`${e>1?"value[i]":"value"}`,"float32")}
|
|
}
|
|
}
|
|
}
|
|
${e===4?g0(this.elementsPerThread,this.workgroupSize,this.transposeA,32,!0,this.splitedDimInner):y0(this.elementsPerThread,this.workgroupSize,this.transposeA,32,!0,this.splitedDimInner)}
|
|
`}},Yde=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=me(this.outputShape),this.dispatch=de(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`
|
|
${Or(this.activation,this.hasPreluActivationWeights)}
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
var value = getXByOutputIndex(index);
|
|
${ml(this.addBias,this.activation)}
|
|
setOutputAtIndex(index, value);
|
|
}
|
|
}
|
|
`}},Zde=class{constructor(e){this.variableNames=[],this.outputShape=[],this.uniforms="value : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="fill"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
setOutputAtIndex(index, uniforms.value);
|
|
}
|
|
}
|
|
`}};function Wa(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 Zde(n),o=[{type:"float32",data:[r]}];return t.runWebGPUProgram(i,[],s,o)}}var Jde={kernelName:Iu,backendName:"webgpu",kernelFunc:Wa};function ke(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 Qde={kernelName:Du,backendName:"webgpu",kernelFunc:ke};function x0({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,d=t.shape.length,c=a?e.shape[u-2]:e.shape[u-1],p=n?t.shape[d-1]:t.shape[d-2],h=a?e.shape[u-1]:e.shape[u-2],m=n?t.shape[d-2]:t.shape[d-1],f=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=v.sizeFromShape(f),x=v.sizeFromShape(g),A=ul.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([h,m]);v.assert(c===p,()=>`Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${a} and transposeB=${n} must match.`);let b=a?[y,c,h]:[y,h,c],w=n?[x,m,p]:[x,p,m],S=ke({inputs:{x:e},backend:r,attrs:{shape:b}}),C=ke({inputs:{x:t},backend:r,attrs:{shape:w}}),N=[S,C],M=Math.max(y,x),F=[S,C],E=[{type:"int32",data:[h]},{type:"int32",data:[m]},{type:"int32",data:[c]}],T,D,O=[M,h,m],W=B().get("WEBGPU_MATMUL_PROGRAM_TYPE");if(W<0){let U=B().getNumber("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL"),G=U>0?U:r.thresholdToIncreaseWorkgroups,q=M*Math.ceil(h/32)*Math.ceil(m/32);q<=G||h<=8&&q<=G*2?M*h*m<=128?W=Ln.MatMulReduceProgram:M===1&&p>=2e3?W=Ln.MatMulSplitKProgram:W=Ln.MatMulSmallOutputSizeProgram:W=Ln.MatMulPackedProgram}switch(W){case Ln.MatMulReduceProgram:T=new jde(O,a,n,s,l,i);break;case Ln.MatMulSplitKProgram:{if(D=Wa({backend:r,attrs:{shape:O,value:0,dtype:e.dtype}}),T=new Kde(O,p,a,n),s||l){D=r.runWebGPUProgram(T,F,e.dtype,E,D);let G=new Yde(D.shape,s,l,i),q=null,H=[D];s&&H.push(s),i&&H.push(i),l==="leakyrelu"&&(q=[{type:"float32",data:[o]}],G.uniforms+=" alpha : f32,");let V=r.runWebGPUProgram(G,H,D.dtype,q);N.push(D);let Z=ke({inputs:{x:V},backend:r,attrs:{shape:A}});N.push(V);for(let X of N)r.disposeData(X.dataId);return Z}break}case Ln.MatMulSmallOutputSizeProgram:T=new Xde(b,w,O,a,n,s,l,i);break;case Ln.MatMulPackedProgram:let U=r.adapterInfo.isIntel();T=new Gde(b,O,a,n,s,l,i,U);break;default:throw new Error(`Unsupported MatMulProgramType ${W}.`)}s&&F.push(s),i&&F.push(i),l==="leakyrelu"&&(E.push({type:"float32",data:[o]}),T.uniforms+=" alpha : f32,"),D=r.runWebGPUProgram(T,F,e.dtype,E,D);let $=ke({inputs:{x:D},backend:r,attrs:{shape:A}});N.push(D);for(let U of N)r.disposeData(U.dataId);return $}function epe(e){let{inputs:t,backend:a,attrs:n}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:d,leakyreluAlpha:c}=n;return x0({a:r,b:s,transposeA:l,transposeB:u,backend:a,bias:i,preluActivationWeights:o,leakyreluAlpha:c,activation:d})}var tpe={kernelName:ts,backendName:"webgpu",kernelFunc:epe},yA=class{constructor(e,t,a){this.variableNames=["AReal","AImag","BReal","BImag"],this.workgroupSize=[128,1,1],this.size=!0,this.outputShape=I.assertAndGetBroadcastShape(t,a),this.dispatchLayout=me(this.outputShape),this.dispatch=de(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 {
|
|
${ry(this.op,!1)}
|
|
}
|
|
|
|
${ue("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));
|
|
}
|
|
}
|
|
`}},$h=class{constructor(e,t,a){if(this.size=!0,this.variableNames=["A","B"],this.outputShape=I.assertAndGetBroadcastShape(t,a),this.dispatchLayout=me(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.outputComponent=1,this.variableComponents=[1,1],this.lastDimensionSize=this.useSharedMemoryWithB?a[0]:t[0],this.shaderKey=`binary_${e}_${this.lastDimensionSize}`,this.type="shared",this.workgroupSize=[256,1,1];else{let n=t.length>0&&t[t.length-1]%4===0,r=a.length>0&&a[a.length-1]%4===0;n&&r?(this.outputComponent=4,this.variableComponents=[4,4]):n&&(v.isScalarShape(a)||a[a.length-1]===1)||r&&(v.isScalarShape(t)||t[t.length-1]===1)?(this.outputComponent=4,this.variableComponents=n?[4,1]:[1,4]):(this.outputComponent=1,this.variableComponents=[1,1]),this.type="nonshared",this.shaderKey=`binary_${e}_${this.variableComponents}`,this.workgroupSize=[128,1,1]}this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.outputComponent,1,1])}getUserCode(){let e,t=this.outputComponent===4?"vec4<f32>":"f32",a=`
|
|
fn binaryOperation(a : ${t}, b : ${t}) -> ${t} {
|
|
${ry(this.op,this.outputComponent===4)}
|
|
};
|
|
`;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}>;
|
|
${ue("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}
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index * ${this.outputComponent});
|
|
let a = ${t}(getAByOutputCoords(coords));
|
|
let b = ${t}(getBByOutputCoords(coords));
|
|
setOutputAtIndex(index, binaryOperation(a, b));
|
|
}
|
|
}
|
|
`;return e}};function an(e){let{inputs:t}=e,{x:a}=t;return e.backend.incRef(a.dataId),{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}var ape={kernelName:ho,backendName:"webgpu",kernelFunc:an};function fl(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=an({inputs:{x:n},backend:a}),l=an({inputs:{x:r},backend:a});return i.complexTensorInfos={real:o,imag:l},s}var npe={kernelName:xp,backendName:"webgpu",kernelFunc:fl},id=class{constructor(e,t,a=""){this.variableNames=["A"],this.size=!0;let n=128;this.workgroupSize=[n,1,1],this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.op=t,a!==""&&(this.uniforms=a),this.shaderKey=`unary_${t}`}getUserCode(){return`
|
|
fn unaryOperation(a : f32) -> f32 {
|
|
${pi(this.op,!1)}
|
|
}
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let a = getAByOutputIndex(index);
|
|
setOutputAtIndex(index, unaryOperation(a));
|
|
}
|
|
}
|
|
`}};function at({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),d=t(u.values,o);return i.makeTensorInfo(s.shape,o,d)}let l=new id(s.shape,e);return i.runWebGPUProgram(l,[s],o)}}function aa({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),p=l.tensorMap.get(o.dataId),h,m;if(e!==De.MUL)[h,m]=[[c.complexTensorInfos.real,p.complexTensorInfos.real],[c.complexTensorInfos.imag,p.complexTensorInfos.imag]].map(g=>{let[y,x]=g,A={dataId:y.dataId,dtype:y.dtype,shape:i.shape},b={dataId:x.dataId,dtype:x.dtype,shape:o.shape},w=new $h(e,i.shape,o.shape);return l.runWebGPUProgram(w,[A,b],Qt(y.dtype,x.dtype))});else{let g=new yA(De.COMPLEX_MULTIPLY_REAL,i.shape,o.shape),y=new yA(De.COMPLEX_MULTIPLY_IMAG,i.shape,o.shape),x=[{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:p.complexTensorInfos.real.dataId,dtype:p.complexTensorInfos.real.dtype,shape:o.shape},{dataId:p.complexTensorInfos.imag.dataId,dtype:p.complexTensorInfos.imag.dtype,shape:o.shape}];h=l.runWebGPUProgram(g,x,"float32"),m=l.runWebGPUProgram(y,x,"float32")}let f=fl({inputs:{real:h,imag:m},backend:l});return l.disposeData(h.dataId),l.disposeData(m.dataId),f}let u=n||Qt(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,p=l.tensorMap.get(o.dataId).values,h=i.dtype==="string"?I.fromUint8ToStringArray(c):c,m=i.dtype==="string"?I.fromUint8ToStringArray(p):p,[f,g]=t(i.shape,o.shape,h,m,u);return l.makeTensorInfo(g,u,f)}let d=new $h(e,i.shape,o.shape);return l.runWebGPUProgram(d,[i,o],u)}}var qk={};Ke(qk,{addImpl:()=>Yk,bincountImpl:()=>ope,bincountReduceImpl:()=>lpe,bitwiseAndImpl:()=>Zk,castImpl:()=>Kk,ceilImpl:()=>Qk,concatImpl:()=>upe,equalImpl:()=>e9,expImpl:()=>t9,expm1Impl:()=>a9,floorDivImpl:()=>r9,floorImpl:()=>n9,gatherNdImpl:()=>dpe,gatherV2Impl:()=>ppe,greaterEqualImpl:()=>i9,greaterImpl:()=>s9,lessEqualImpl:()=>l9,lessImpl:()=>o9,linSpaceImpl:()=>cpe,logImpl:()=>u9,maxImpl:()=>hpe,maximumImpl:()=>d9,minimumImpl:()=>p9,multiplyImpl:()=>ly,negImpl:()=>fpe,notEqualImpl:()=>c9,prodImpl:()=>ype,raggedGatherImpl:()=>Ipe,raggedRangeImpl:()=>Spe,raggedTensorToTensorImpl:()=>Cpe,rangeImpl:()=>Npe,rsqrtImpl:()=>h9,scatterImpl:()=>Rpe,sigmoidImpl:()=>Epe,simpleAbsImpl:()=>rpe,sliceImpl:()=>Mpe,sparseFillEmptyRowsImpl:()=>Fpe,sparseReshapeImpl:()=>$pe,sparseSegmentReductionImpl:()=>Dpe,sqrtImpl:()=>Ppe,squaredDifferenceImpl:()=>m9,staticRegexReplaceImpl:()=>f9,stridedSliceImpl:()=>_pe,stringNGramsImpl:()=>zpe,stringSplitImpl:()=>Wpe,stringToHashBucketFastImpl:()=>Bpe,subImpl:()=>g9,tileImpl:()=>Upe,topKImpl:()=>Gpe,transposeImpl:()=>gpe,uniqueImpl:()=>Hpe});function Xk(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.`)})}function rpe(e){let t=new Float32Array(e.length);for(let a=0;a<e.length;++a)t[a]=Math.abs(e[a]);return t}function Ua(e){return(t,a,n,r,s)=>{let i=I.assertAndGetBroadcastShape(t,a),o=i.length,l=v.computeStrides(i),u=v.sizeFromShape(i),d=v.getTypedArrayFromDType(s,u),c=t.length,p=a.length,h=v.computeStrides(t),m=v.computeStrides(a),f=I.getBroadcastDims(t,i),g=I.getBroadcastDims(a,i);if(f.length+g.length===0)for(let y=0;y<d.length;++y)d[y]=e(n[y%n.length],r[y%r.length]);else for(let y=0;y<d.length;++y){let x=v.indexToLoc(y,o,l),A=x.slice(-c);f.forEach(C=>A[C]=0);let b=v.locToIndex(A,c,h),w=x.slice(-p);g.forEach(C=>w[C]=0);let S=v.locToIndex(w,p,m);d[y]=e(n[b],r[S])}return[d,i]}}function iy(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}function eg(e,t,a="float32"){if(a==="complex64"){let r=eg(e,t,"float32"),s=eg(e,t,"float32");return iy({inputs:{real:r,imag:s},backend:e})}let n=v.makeZerosTypedArray(v.sizeFromShape(t),a);return e.makeTensorInfo(t,a,n)}function xA(e){let{inputs:t,backend:a}=e,{x:n}=t;return a.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}function spe(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)}function Kk(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]=Ua((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 Dh(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{dtype:s}=n;if(s==="complex64"){if(r.dtype==="complex64")return xA({inputs:{x:r},backend:a});let d=eg(a,r.shape,r.dtype),c=Dh({inputs:{x:r},backend:a,attrs:{dtype:"float32"}}),p=iy({inputs:{real:c,imag:d},backend:a});return a.disposeIntermediateTensorInfo(d),a.disposeIntermediateTensorInfo(c),p}if(r.dtype==="complex64"){let d=spe({inputs:{input:r},backend:a}),c=Dh({inputs:{x:d},backend:a,attrs:{dtype:s}});return a.disposeIntermediateTensorInfo(d),c}if(!v.hasEncodingLoss(r.dtype,s)){let d=xA({inputs:{x:r},backend:a});return{dataId:d.dataId,shape:d.shape,dtype:s}}let i=a.data.get(r.dataId).values,[o,l,u]=Kk(i,r.shape,r.dtype,s);return a.makeTensorInfo(o,l,u)}function rn(e,t,a,n){return a==null?({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;Xk([i,o],e);let u=l.data.get(i.dataId).values,d=l.data.get(o.dataId).values,c=i.dtype==="string"?I.fromUint8ToStringArray(u):u,p=i.dtype==="string"?I.fromUint8ToStringArray(d):d,h=n||i.dtype,[m,f]=t(i.shape,o.shape,c,p,h);return l.makeTensorInfo(f,h,m)}:({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;if(i.dtype==="complex64"||o.dtype==="complex64"){let u=Dh({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),d=l.data.get(u.dataId),c=d.complexTensorInfos.real,p=d.complexTensorInfos.imag,h=l.data.get(c.dataId).values,m=l.data.get(p.dataId).values,f=Dh({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(f.dataId),y=g.complexTensorInfos.real,x=g.complexTensorInfos.imag,A=l.data.get(y.dataId).values,b=l.data.get(x.dataId).values,[w,S,C]=a(i.shape,o.shape,h,m,A,b),N=l.makeTensorInfo(C,"float32",w),M=l.makeTensorInfo(C,"float32",S),F=iy({inputs:{real:N,imag:M},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(f),l.disposeIntermediateTensorInfo(N),l.disposeIntermediateTensorInfo(M),F}else{let u=l.data.get(i.dataId).values,d=l.data.get(o.dataId).values,c=n||i.dtype,[p,h]=t(i.shape,o.shape,u,d,c);return l.makeTensorInfo(h,c,p)}}}function oy(e){return(t,a,n,r,s,i)=>{let o=I.assertAndGetBroadcastShape(t,a),l=v.sizeFromShape(o),u=o.length,d=v.computeStrides(o),c=v.getTypedArrayFromDType("float32",l),p=v.getTypedArrayFromDType("float32",l),h=I.getBroadcastDims(t,o),m=I.getBroadcastDims(a,o),f=I.mergeRealAndImagArrays(n,r),g=I.mergeRealAndImagArrays(s,i),y=t.length,x=v.computeStrides(t),A=a.length,b=v.computeStrides(a);if(h.length+m.length===0)for(let w=0;w<c.length;w++){let S=w%f.length,C=w%g.length,N=e(f[S*2],f[S*2+1],g[C*2],g[C*2+1]);c[w]=N.real,p[w]=N.imag}else for(let w=0;w<c.length;w++){let S=v.indexToLoc(w,u,d),C=S.slice(-y);h.forEach(T=>C[T]=0);let N=v.locToIndex(C,y,x),M=S.slice(-A);m.forEach(T=>M[T]=0);let F=v.locToIndex(M,A,b),E=e(f[N*2],f[N*2+1],g[F*2],g[F*2+1]);c[w]=E.real,p[w]=E.imag}return[c,p,o]}}var Yk=Ua((e,t)=>e+t),ipe=oy((e,t,a,n)=>({real:e+a,imag:t+n})),Wxe=rn(Mr,Yk,ipe);function ope(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 lpe(e,t,a,n=!1){let r=e.shape[0],s=e.shape[1],i=Te([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}var Zk=Ua((e,t)=>e&t),Bxe=rn(ji,Zk);function pr(e){return(t,a,n)=>{let r=v.getArrayFromDType(a,t.length);for(let s=0;s<t.length;++s)r[s]=e(t[s],n);return r}}function Jk(e,t,a){let n=pr(t);return Vs(e,n,a)}function Vs(e,t,a){return({inputs:n,attrs:r,backend:s})=>{let{x:i}=n;Xk(i,e);let o=s,l=o.data.get(i.dataId).values,u;if(i.dtype==="string"){if(!Array.isArray(l))throw new Error("String tensor's value was not an instance of Array");u=I.fromUint8ToStringArray(l)}else u=l;let d=a||i.dtype,c=t(u,d,r);return o.makeTensorInfo(i.shape,d,c)}}var Qk=pr(e=>Math.ceil(e)),Vxe=Vs(cs,Qk);function upe(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"?I.fromUint8ToStringArray(i.vals):i.vals,l=0;for(let u=0;u<i.shape[0];++u){let d=u*t[1]+s;for(let c=0;c<i.shape[1];++c)r[d+c]=o[l++]}s+=i.shape[1]})}return r}var e9=Ua((e,t)=>e===t?1:0),Uxe=rn(ms,e9,null,"bool"),t9=pr(e=>Math.exp(e)),Gxe=Vs(fs,t9,"float32"),a9=pr(e=>Math.expm1(e)),Hxe=Vs(gs,a9),n9=pr(e=>Math.floor(e)),jxe=Vs(ys,n9),r9=Ua((e,t)=>Math.floor(e/t)),qxe=rn(xs,r9,null,"int32");function dpe(e,t,a,n,r,s,i,o,l){let u=Te([n,s],a);for(let d=0;d<n;d++){let c=[],p=0;for(let h=0;h<r;h++){let m=e[d*r+h];p+=m*i[h],c.push(m)}if(p<0||p>=l/s)throw new Error(`Invalid indices: ${c} does not index into ${o}`);for(let h=0;h<s;h++)u.values[d*s+h]=t.get(...t.indexToLoc(p*s+h))}return u}function ppe(e,t,a){let n=Te(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 s9=Ua((e,t)=>e>t?1:0),Xxe=rn(As,s9,null,"bool"),i9=Ua((e,t)=>e>=t?1:0),Kxe=rn(bs,i9,null,"bool"),o9=Ua((e,t)=>e<t?1:0),Yxe=rn(vs,o9,null,"bool"),l9=Ua((e,t)=>e<=t?1:0),Zxe=rn(ws,l9,null,"bool");function cpe(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 u9=pr(e=>Math.log(e)),Jxe=Vs(ks,u9);function hpe(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 d9=Ua((e,t)=>Math.max(e,t)),Qxe=rn(Is,d9),p9=Ua((e,t)=>Math.min(e,t)),e5e=rn(Ss,p9),ly=Ua((e,t)=>e*t),mpe=oy((e,t,a,n)=>({real:e*a-t*n,imag:e*n+t*a})),t5e=rn(Ts,ly,mpe);function fpe(e,t,a){let n=v.createScalarValue(-1,a);return ly([],t,n,e,a)}var c9=Ua((e,t)=>e!==t?1:0),a5e=rn(Cs,c9,null,"bool");function gpe(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 d=0;d<i;++d){let c=v.indexToLoc(d,s,o),p=new Array(c.length);for(let m=0;m<p.length;m++)p[m]=c[n[m]];let h=v.locToIndex(p,s,l);u[h]=e[d]}return u}function ype(e,t,a,n){let[r,s]=I.computeOutAndReduceShapes(e,n),i=Qt(t,"int32"),o=v.makeZerosTypedArray(v.sizeFromShape(r),i),l=v.sizeFromShape(s);for(let u=0;u<o.length;++u){let d=u*l,c=1;for(let p=0;p<l;++p)c*=a[d+p];o[u]=c}return{outVals:o,outShape:r,outDtype:i}}function xpe(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 Ape(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 bpe(e,t,a,n){let r=[],s=0,i=t.length-1+a.length,o=new Array(i).fill(null).map(()=>[0]);Ape(a,n);let l=1;for(let u=0;u<t.length-1;++u){l*=t[u];let d=t[u+1];for(let c=1;c<l+1;++c)o[u].push(c*d)}for(let u=0;u<e.length;++u){let d=e[u],c=e[u]+1;for(let p=0;p<a.length;++p){let h=a[p],m=p+t.length-1;if(m>=0){let f=o[m],g=f[f.length-1]-h[d];for(let y=d;y<c;++y)o[m].push(h[y+1]+g)}d=h[d],c=h[c]}c!==d&&(r.push([d,c]),s+=c-d)}return{outSplits:o,valueSlices:r,numValues:s}}function vpe(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 AA(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 wpe(e,t,a,n,r,s){let i=AA(t,2)[1],o=AA(s,2)[1],l=0;for(let u of a)for(let d=u[0];d<u[1];++d){for(let c=0;c<n;++c)r[l*o+c]=e[d*i+c];++l}}function kpe(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 wpe(e,t,n,l,i,s),[i,s]}function Ipe(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(xpe(s,i,l),n.length===0)throw new Error("params.rank must be nonzero");let u=n[0],{outSplits:d,valueSlices:c,numValues:p}=bpe(s,i,e,u),h=vpe(d),m=kpe(a,n,r,c,p);return[h,m[0],m[1]]}var bA=2147483647;function Spe(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,d=[];o||d.push(t[0]),l||d.push(r[0]),u||d.push(i[0]);for(let g=1;g<d.length;++g)if(d[g]!==d[g-1])throw new Error("starts, limits, and deltas must have the same shape");let c=d.length===0?1:d[0],p=v.getArrayFromDType("int32",c+1);p[0]=0;for(let g=0;g<c;++g){let y=o?e[0]:e[g],x=l?n[0]:n[g],A=u?s[0]:s[g];if(A===0)throw new Error("Requires delta != 0");let b;if(A>0&&x<y||A<0&&x>y)b=0;else if(b=Math.ceil(Math.abs((x-y)/A)),b>bA)throw new Error(`Requires ((limit - start) / delta) <= ${bA}`);p[g+1]=p[g]+b}let h=p[c],m=v.getArrayFromDType(a,h),f=0;for(let g=0;g<c;++g){let y=p[g+1]-p[g],x=o?e[0]:e[g],A=u?s[0]:s[g];for(let b=0;b<y;++b)m[f++]=x,x+=A}return[p,m]}var Nn=I.RowPartitionType,Tpe=class tg{constructor(t,a,n,r,s,i,o,l,u,d){this.shape=t,this.shapeShape=a,this.values=n,this.valuesShape=r,this.valuesDType=s,this.defaultValue=i,this.defaultValueShape=o,this.rowPartitionValues=l,this.rowPartitionValuesShapes=u,this.rowPartitionTypes=I.getRowPartitionTypesHelper(d),this.raggedRank=I.getRaggedRank(this.rowPartitionTypes)}getRowPartitionTypeByDimension(t){return this.rowPartitionTypes[0]===Nn.FIRST_DIM_SIZE?this.rowPartitionTypes[t+1]:this.rowPartitionTypes[t]}getRowPartitionTensor(t){return this.rowPartitionTypes[0]===Nn.FIRST_DIM_SIZE?this.rowPartitionValues[t+1]:this.rowPartitionValues[t]}getMaxWidth(t){let a=this.getRowPartitionTensor(t-1);switch(this.getRowPartitionTypeByDimension(t-1)){case Nn.VALUE_ROWIDS:return tg.getMaxWidthValueRowID(a);case Nn.ROW_SPLITS:return tg.getMaxWidthRowSplit(a);default:throw new Error(`Cannot handle partition type ${Nn[this.getRowPartitionTypeByDimension(t-1)]}`)}}static getMaxWidthRowSplit(t){let a=t.length;if(a===0||a===1)return 0;let n=0;for(let r=0;r<a-1;++r){let s=t[r+1]-t[r];s>n&&(n=s)}return n}static getMaxWidthValueRowID(t){let a=t.length;if(a===0)return 0;let n=0,r=t[0],s=0;for(let i=1;i<a;++i){let o=t[i];o!==r&&(r=o,s=Math.max(i-n,s),n=i)}return Math.max(a-n,s)}tensorShapeFromTensor(t,a,n=!0){if(a.length===0){if(t[0]===-1)return[];throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.")}return wA(t,n)}calculateOutputSize(t){let a=this.valuesShape,n=this.defaultValueShape;I.validateDefaultValueShape(n,a);let r=this.tensorShapeFromTensor(this.shape,this.shapeShape),s=I.combineRaggedTensorToTensorShapes(this.raggedRank,r,a);s[0]<0&&(s[0]=t);for(let i=1;i<=this.raggedRank;++i)s[i]<0&&(s[i]=this.getMaxWidth(i));return s}calculateFirstParentOutputIndex(t,a,n){let r=Math.min(t,n),s=[],i=0;for(let o=0;o<r;++o,i+=a)s.push(i);for(let o=r;o<t;++o)s.push(-1);return v.assert(s.length===t,()=>"Final length of result must be equal to firstDimension."),s}calculateOutputIndexRowSplit(t,a,n,r){let s=t.length,i=[];for(let o=0;o<s-1;++o){let l=t[o+1]-t[o],u=Math.min(r,l),d=a[o];d===-1&&(u=0);for(let c=0;c<u;++c)i.push(d),d+=n;for(let c=0;c<l-u;++c)i.push(-1)}if(s>0&&i.length!==t[s-1])throw new Error("Invalid row split size.");return i}calculateOutputIndexValueRowID(t,a,n,r){let s=t.length,i=[];if(s===0)return[];let o=0,l=t[0];if(l>=a.length)throw new Error(`Got currentValueRowId=${l}, which is not less than ${a.length}`);let u=a[l];i.push(u);for(let d=1;d<s;++d){let c=t[d];if(c===l)u>=0&&(++o,o<r?u+=n:u=-1);else{if(o=0,l=c,c>=a.length)throw new Error(`Got nextValueRowId=${c} which is not less than ${a.length}`);u=a[c]}i.push(u)}if(i.length!==t.length)throw new Error("Invalid row ids.");return i}calculateOutputIndex(t,a,n,r){let s=this.getRowPartitionTensor(t),i=this.getRowPartitionTypeByDimension(t);switch(i){case Nn.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(s,a,n,r);case Nn.ROW_SPLITS:if(s.length-1>a.length)throw new Error(`Row partition size is greater than output size: ${s.length-1} > ${a.length}`);return this.calculateOutputIndexRowSplit(s,a,n,r);default:throw new Error(`Unsupported partition type: ${Nn[i]}`)}}getFirstDimensionSize(){let t=this.rowPartitionValues[0];if(this.rowPartitionTypes.length===0)throw new Error("No row_partition_types given.");let a=this.rowPartitionTypes[0];switch(a){case Nn.FIRST_DIM_SIZE:return t[0];case Nn.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case Nn.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${Nn[a]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");let t=this.getFirstDimensionSize(),a=this.calculateOutputSize(t),n=new Array(this.raggedRank+1);n[n.length-1]=1;for(let i=n.length-2;i>=0;--i)n[i]=n[i+1]*a[i+1];let r=wA(a,!1),s=v.getArrayFromDType(this.valuesDType,v.sizeFromShape(r));if(n[0]*a[0]>0){let i=this.calculateFirstParentOutputIndex(t,n[0],a[0]);for(let o=1;o<=this.raggedRank;++o)i=this.calculateOutputIndex(o-1,i,n[o],a[o]);this.setOutput(this.raggedRank,i,s,r)}return[r,s]}setOutput(t,a,n,r){if(n.length===0)return;let s=this.values,i=n,o=r.slice();o=o.slice(t+1);let l=v.sizeFromShape(o),u=a.length,d=this.defaultValue;if(d.length!==l&&d.length!==1){let m=this.defaultValueShape;Pe(()=>{let f=Q(d,m);d=Ai(f,o).dataSync()})}let c=0,p=0,h=0;for(let m=0;m<=u;++m){let f=m<u?a[m]:-1;if(f===h){++h;continue}if(p<h){let g=s.subarray(c*l),y=i.subarray(p*l),x=(h-p)*l;vA(y,g,x)}if(m>=u){let g=n.length;f=Math.floor(g/l)}if(f>h)if(this.defaultValue.length===1)i.subarray(h*l,f*l).fill(this.defaultValue[0]),h=f;else for(;f>h;){let g=i.slice(h*l);vA(g,d,l),++h}f<0?(c=m+1,p=h):(c=m,p=h,h=p+1)}}};function vA(e,t,a){for(let n=0;n<a;n++)e[n]=t[n]}function wA(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 Cpe(e,t,a,n,r,s,i,o,l,u){return new Tpe(e,t,a,n,r,s,i,o,l,u).compute()}function Npe(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 h9=pr(e=>1/Math.sqrt(e)),n5e=Vs(Ns,h9);function Rpe(e,t,a,n,r,s,i,o,l,u){let d=[n/r,r],c=e.values,p=t.values;if(n===0)return Te(a,t.dtype);let h=l instanceof Rt?l:Te(d,t.dtype);typeof l=="string"||typeof l=="number"?h.values.fill(l):typeof l=="boolean"&&h.values.fill(+l);for(let m=0;m<s;m++){let f=[],g=0;for(let y=0;y<i;y++){let x=c[m*i+y];f.push(x),g+=x*o[y]}if(g<0||g>=n/r)throw new Error(`Invalid indices: ${f} does not index into ${a}`);for(let y=0;y<r;y++)u?h.values[g*r+y]+=p[m*r+y]:h.values[g*r+y]=t.rank===0?p[0]:p[m*r+y]}return h}var Epe=pr(e=>1/(1+Math.exp(-e))),r5e=Jk(Rs,e=>1/(1+Math.exp(-e)));function Mpe(e,t,a,n,r){let s=wt.isSliceContinous(n,t,a),i=v.sizeFromShape(a),o=v.computeStrides(n);if(s){let c=wt.computeFlatOffset(t,o);return r==="string"?e.slice(c,c+i):e.subarray(c,c+i)}let l=r==="string"?I.fromUint8ToStringArray(e):e,u=Te(n,r,l),d=Te(a,r);for(let c=0;c<d.size;++c){let p=d.indexToLoc(c),h=p.map((m,f)=>m+t[f]);d.set(u.get(...h),...p)}return r==="string"?I.fromStringArrayToUint8(d.values):d.values}function Fpe(e,t,a,n,r,s,i){let o=t[0],l=s[0],u=new Array(l),d=new Array(o),c=t[1];if(l===0){if(o!==0)throw new Error(I.getSparseFillEmptyRowsIndicesDenseShapeMismatch(o));let g=v.getArrayFromDType(a,0),y=v.getArrayFromDType(r,0);return[g,[0,c],y,u,d]}let p=!0,h=0,m=new Array(l).fill(0);for(let g=0;g<o;++g){let y=e[g*c];if(y<0)throw new Error(I.getSparseFillEmptyRowsNegativeIndexErrorMessage(g,y));if(y>=l)throw new Error(I.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(g,y,l));++m[y],p=p&&y>=h,h=y}let f=!0;for(let g=0;g<l;++g){let y=m[g]===0;u[g]=y,f=f&&!y,m[g]=Math.max(m[g],1),g>0&&(m[g]+=m[g-1])}if(f&&p){let g=e,y=n;for(let x=0;x<o;++x)d[x]=x;return[g,[o,c],y,u,d]}else{let g=m[l-1],y=v.getArrayFromDType(a,g*c),x=v.getArrayFromDType(r,g),A=new Array(l).fill(0);for(let b=0;b<o;++b){let w=e[b*c],S=A[w],C=(w===0?0:m[w-1])+S;A[w]++;for(let N=0;N<c;++N)y[C*c+N]=e[b*c+N];x[C]=n[b],d[b]=C}for(let b=0;b<l;++b)if(A[b]===0){let w=b===0?0:m[b-1];y[w*c+0]=b;for(let S=1;S<c;++S)y[w*c+S]=0;x[w]=i}return[y,[g,c],x,u,d]}}function $pe(e,t,a,n,r){let s=v.sizeFromShape(n),i=t[0],o=r.length,l=[],u=1,d=-1;for(let f=0;f<o;++f){let g=r[f];if(g===-1){if(d!==-1)throw new Error(I.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(d,f));d=f,l.push(1)}else{if(g<0)throw new Error(I.getSparseReshapeNegativeOutputDimErrorMessage(f,g));u*=g,l.push(g)}}if(d!==-1){if(u<=0)throw new Error(I.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());let f=Math.trunc(s/u);if(u*f!==s)throw new Error(I.getSparseReshapeInputOutputMultipleErrorMessage(n,l));l[d]=f}if(v.sizeFromShape(l)!==s)throw new Error(I.getSparseReshapeInputOutputMismatchErrorMessage(n,l));let c=n.length,p=[];if(c>0){p[c-1]=1;for(let f=c-2;f>=0;--f)p[f]=p[f+1]*n[f+1]}let h=[];if(o>0){h[o-1]=1;for(let f=o-2;f>=0;--f)h[f]=h[f+1]*l[f+1]}let m=v.getArrayFromDType(a,i*o);for(let f=0;f<i;++f){let g=0;for(let y=0;y<c;++y)g+=e[f*c+y]*p[y];for(let y=0;y<o;++y)m[f*o+y]=Math.trunc(g/h[y]),g%=h[y]}return[m,[i,o],l]}function Dpe(e,t,a,n,r,s=!1,i=0){let o=n.length,l=[t[0],e.length/t[0]],u=l[1],d=o>0?r[o-1]+1:0;if(d<0)throw new Error(I.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let c=t.slice();c[0]=d;let p=c.reduce((x,A)=>x*A,1),h=v.getArrayFromDType(a,p);if(o===0)return d>0&&h.fill(i),[h,c];if(d<=0)throw new Error(I.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let m=0,f=1,g=0,y=r[m];for(;;){let x=0;if(f<o){if(x=r[f],y===x){++f;continue}if(y>=x)throw new Error(I.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage())}if(y<0||y>=d)throw new Error(I.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(y,d));y>g&&h.fill(i,g*u,y*u);for(let A=m;A<f;++A){let b=n[A];if(b<0||b>=l[0])throw new Error(I.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(A,n[A],l[0]));for(let w=0;w<u;w++)h[y*u+w]+=e[b*u+w]}if(s)for(let A=0;A<u;A++)h[y*u+A]/=f-m;if(m=f,++f,g=y+1,y=x,f>o)break}return g<d&&h.fill(i,g*u,d*u),[h,c]}var Ppe=pr(e=>Math.sqrt(e)),s5e=Jk(Es,e=>Math.sqrt(e)),m9=Ua((e,t)=>{let a=e-t;return a*a}),i5e=rn(Ms,m9),f9=pr((e,t)=>{let{pattern:a,replaceGlobal:n,rewrite:r}=t;return e.replace(new RegExp(a,n?"g":""),r)}),o5e=Vs(Gu,f9);function _pe(e,t,a,n){let r=Te(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 Ope=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))),d=s-(l+u),c=t+(l>0?0:i-o),p=0;p+=l*this.leftPad.length;for(let y=0;y<d;++y)p+=e[c+y].length;p+=u*this.rightPad.length;let h=l+u+d-1;p+=h*this.separator.length,a[n+i]=new Uint8Array(p);let m=a[n+i],f=0,g=y=>y.forEach(x=>m[f++]=x);for(let y=0;y<l;++y)g(this.leftPad),g(this.separator);for(let y=0;y<d-1;++y)g(e[c+y]),g(this.separator);if(d>0){g(e[c+d-1]);for(let y=0;y<u;++y)g(this.separator),g(this.rightPad)}else{for(let y=0;y<u-1;++y)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(d=>{u+=this.getNumNGrams(l,d)}),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(d=>{let c=t[o+1]-t[o],p=this.getNumNGrams(c,d);this.createNGrams(e,l,i,u,p,d),u+=p}),this.preserveShort&&u===s[o]){let d=t[o+1]-t[o];if(d===0)continue;let c=d+2*this.padWidth;this.createNGrams(e,l,i,u,1,c)}}return[i,s]}};function zpe(e,t,a,n,r,s,i,o){return new Ope(a,n,r,s,i,o).compute(e,t)}function Lpe(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 Wpe(e,t,a){let n=e.length,r=[],s=0,i=0,o=new Array(n);for(let p=0;p<n;++p){let h=r.length;Lpe(e[p],t,a,r);let m=r.length-h;o[p]=m,s+=m,i=Math.max(i,m)}let l=v.getArrayFromDType("int32",s*2),u=new Array(s),d=[n,i],c=0;for(let p=0;p<n;++p)for(let h=0;h<o[p];++h)l[c*2]=p,l[c*2+1]=h,u[c]=r[c],++c;return[l,u,d]}function Bpe(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 g9=Ua((e,t)=>e-t),Vpe=oy((e,t,a,n)=>({real:e-a,imag:t-n})),l5e=rn(Fs,g9,Vpe);function Upe(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=Te(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 Ld=(e,t)=>{let a=t.value-e.value;return a===0?e.index-t.index:a};function y9(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),d=.5*Math.exp(2*u/3),c=.5*Math.sqrt(u*d*(o-d)/o)*Math.sign(l-o/2),p=Math.max(a,Math.floor(t-l*d/o+c)),h=Math.min(n,Math.floor(t+(o-l)*d/o+c));y9(e,t,p,h)}let r=e[t],s=a,i=n;for(v.swap(e,a,t),Ld(e[n],r)>0&&v.swap(e,a,n);s<i;){for(v.swap(e,s,i),s++,i--;Ld(e[s],r)<0;)s=s+1;for(;Ld(e[i],r)>0;)i=i-1}Ld(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 Gpe(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 p=c*o,h=e.subarray(p,p+o),m=new Array(h.length);h.forEach((x,A)=>m[A]={value:x,index:A}),n<m.length&&(y9(m,n),m=m.slice(0,n)),r&&m.sort(Ld);let f=c*n,g=l.subarray(f,f+n),y=u.subarray(f,f+n);for(let x=0;x<n;x++)g[x]=m[x].value,y[x]=m[x].index}let d=t.slice();return d[d.length-1]=n,[Te(d,a,l),Te(d,"int32",u)]}function Hpe(e,t,a,n){let r=v.parseAxisParam(t,a)[0],s=[1,a[0],1];for(let m=0;m<r;m++)s[0]*=a[m];s[1]=a[r];for(let m=r+1;m<a.length;m++)s[2]*=a[m];let i=new Map,o=new Int32Array(a[r]),l=new Rt(s,n,e),u=[],d=s[0]===1&&s[2]===1;for(let m=0;m<a[r];m++){let f;if(d)f=e[m].toString();else{let y=[];for(let x=0;x<s[0];x++)for(let A=0;A<s[2];A++)y.push(l.get(x,m,A));f=y.join(",")}let g=i.get(f);if(g!=null)o[m]=g;else{let y=i.size;i.set(f,y),o[m]=y,u.push(m)}}let c=s.slice();c[1]=i.size;let p=new Rt(c,n);u.forEach((m,f)=>{for(let g=0;g<s[0];g++)for(let y=0;y<s[2];y++)p.set(l.get(g,m,y),g,f,y)});let h=a.slice();return h[r]=c[1],{outputValues:p.values,outputShape:h,indices:o}}var{addImpl:jpe,castImpl:qpe,ceilImpl:Xpe,concatImpl:Kpe,equalImpl:Ype,expImpl:Zpe,expm1Impl:Jpe,floorImpl:Qpe,floorDivImpl:ece,gatherNdImpl:tce,gatherV2Impl:ace,greaterEqualImpl:nce,greaterImpl:rce,lessEqualImpl:sce,lessImpl:ice,logImpl:oce,maxImpl:lce,maximumImpl:uce,minimumImpl:dce,multiplyImpl:pce,negImpl:cce,notEqualImpl:hce,prodImpl:mce,rangeImpl:fce,rsqrtImpl:gce,scatterImpl:yce,simpleAbsImpl:xce,sliceImpl:Ace,stridedSliceImpl:bce,stringNGramsImpl:vce,subImpl:wce,tileImpl:kce,topKImpl:Ice,transposeImpl:Sce,uniqueImpl:u5e}=qk,Tce=at({opType:le.ABS,cpuKernelImpl:xce}),Cce={kernelName:cu,backendName:"webgpu",kernelFunc:Tce},Nce=at({opType:le.ACOS}),Rce={kernelName:$i,backendName:"webgpu",kernelFunc:Nce},Ece=at({opType:le.ACOSH}),Mce={kernelName:Di,backendName:"webgpu",kernelFunc:Ece},Fce=aa({opType:De.ADD,cpuKernelImpl:jpe,supportsComplex:!0}),$ce={kernelName:Mr,backendName:"webgpu",kernelFunc:Fce},Dce=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=me(this.outputShape),this.dispatch=de(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`
|
|
${ue("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 Pce(e){let{inputs:t,backend:a}=e,n=t;if(n.length===1)return an({inputs:{x:n[0]},backend:a});let r=n.map(o=>o.dtype).reduce((o,l)=>Qt(o,l)),s=n.map(o=>o.shape),i=new Dce(s);return a.runWebGPUProgram(i,n,r)}var _ce={kernelName:Pi,backendName:"webgpu",kernelFunc:Pce},Oce=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=de(this.dispatchLayout,this.outputShape,this.workgroupSize,[1,1,1]),this.shaderKey="transposeShared"}getUserCode(){v.assert(this.workgroupSize[0]===this.workgroupSize[1],()=>`Must be a square tile, current tile shape is ${this.workgroupSize[0]} x ${this.workgroupSize[1]}`);let e=this.workgroupSize[0];return`
|
|
var<workgroup> tile : array<array<f32, ${this.workgroupSize[0]+1}>, ${this.workgroupSize[0]}>;
|
|
${ue()} {
|
|
var x = i32(workgroupId.x) * ${e} + i32(localId.x);
|
|
var y = i32(workgroupId.y) * ${e} + 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) * ${e} + i32(localId.x);
|
|
y = i32(workgroupId.x) * ${e} + i32(localId.y);
|
|
if (x < height && y < width) {
|
|
setOutputAtIndex((y * height + x), tile[localId.x]
|
|
[localId.y]);
|
|
}
|
|
}
|
|
`}},zce=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=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.newDim=t,this.shaderKey=`transpose_${t}`}getUserCode(){let e=Dt(this.outputShape.length),t=x9(this.newDim);return`
|
|
${ue("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);
|
|
setOutputAtIndex(flatIndex, A[getIndexFromCoords${this.outputShape.length}D(
|
|
${e}(${t}), uniforms.aShape)]);
|
|
}
|
|
}
|
|
}
|
|
`}};function x9(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]]=`coords.${Nr(n)}`;return a.join()}function ir(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 d=0;d<l.length;d++)l[d]=r.shape[s[d]];if(a.shouldExecuteOnCPU([r])){let d=i.tensorMap.get(r.dataId).values,c=Sce(d,r.shape,r.dtype,s,l);return a.makeTensorInfo(l,r.dtype,c)}if(r.shape.length===2&&v.arraysEqual(s,[1,0])){let d=new Oce(r.shape,s);return i.runWebGPUProgram(d,[r],r.dtype)}let u=new zce(r.shape,s);return i.runWebGPUProgram(u,[r],r.dtype)}var Lce={kernelName:Tr,backendName:"webgpu",kernelFunc:ir},Wce=class{constructor(e,t,a){this.variableNames=["x"],this.uniforms="reduceSize : i32,",this.size=!0,this.inputShape=[e.batchSize,e.inSize];let[n]=I.computeOutAndReduceShapes(this.inputShape,[1]);this.outputShape=n.length===0?[1]:n,e.inSize>=32768&&a>=512?this.workgroupSize=[512,1,1]:e.inSize>=4096?this.workgroupSize=[256,1,1]:this.workgroupSize=[64,1,1],this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,[1,1,1]),this.reduceType=t,this.shaderKey=`reduce_${t}`}getUserCode(){let e="",t="0.0",a=this.workgroupSize[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 n=this.reduceType==="mean"?"setOutputAtIndex(outputIndex, bestValue / f32(uniforms.reduceSize));":"setOutputAtIndex(outputIndex, bestValue);";return`
|
|
fn DIV_CEIL(a : u32, b : u32) -> u32 {
|
|
return ((a - 1u) / b + 1u);
|
|
}
|
|
|
|
${`
|
|
var<workgroup> xBestValues : array<f32, ${a}>;
|
|
`}
|
|
fn getOffset(outputIndex : i32) -> i32 {
|
|
let outputCoords = getCoordsFromIndex(outputIndex);
|
|
let offset = ${this.outputShape.length===1?"outputCoords":"outputCoords[0]"} * uniforms.reduceSize;
|
|
return offset;
|
|
}
|
|
${ue("index")} {
|
|
let outputIndex = index / ${a};
|
|
let offset = getOffset(outputIndex);
|
|
var bestValue = ${t};
|
|
let Length = uniforms.reduceSize;
|
|
let WorkPerThread = DIV_CEIL(u32(Length), ${a}u);
|
|
for (var k = i32(localId.x); k < Length && outputIndex < uniforms.size;
|
|
k = k + ${a}) {
|
|
let candidate = f32(x[offset + k]);
|
|
${e}
|
|
}
|
|
xBestValues[localId.x] = bestValue;
|
|
workgroupBarrier();
|
|
|
|
var reduceSize = min(u32(Length), ${a}u);
|
|
for (var currentSize = reduceSize / 2u; reduceSize > 1u;
|
|
currentSize = reduceSize / 2u) {
|
|
let interval = DIV_CEIL(reduceSize, 2u);
|
|
if (localId.x < currentSize) {
|
|
let candidate = xBestValues[localId.x + interval];
|
|
${e}
|
|
xBestValues[localId.x] = bestValue;
|
|
}
|
|
reduceSize = interval;
|
|
workgroupBarrier();
|
|
}
|
|
|
|
if (localId.x == 0u && outputIndex < uniforms.size) {
|
|
${n}
|
|
}
|
|
}
|
|
`}},Bce={mean:"float32",all:"bool",any:"bool"};function gl(e,t,a,n,r){let s=e.shape.length,i=[],o=v.parseAxisParam(t,e.shape),l=o,u=I.getAxesPermutation(l,s),d=e;u!=null&&(d=ir({inputs:{x:e},attrs:{perm:u},backend:r}),l=I.getInnerMostAxes(l.length,s),i.push(d)),I.assertAxesAreInnerMostDims(n,l,s);let[c,p]=I.computeOutAndReduceShapes(d.shape,l),h=c;a&&(h=I.expandShapeToKeepDim(c,o));let m;if((n==="max"||n==="prod")&&r.shouldExecuteOnCPU([d])){let f=r.tensorMap.get(d.dataId).values;switch(n){case"max":let g=lce(f,v.sizeFromShape(p),h,e.dtype);m=r.makeTensorInfo(h,e.dtype,g);break;case"prod":let{outVals:y,outShape:x,outDtype:A}=mce(d.shape,d.dtype,f,l);m=r.makeTensorInfo(x,A,y);break;default:throw new Error(`${n} CPU implementation is not yet supported.`)}}else{let f=v.sizeFromShape(p),g=v.sizeFromShape(d.shape)/f,y={windowSize:f,inSize:f,batchSize:g,outSize:1},x=Bce[n]||Lp(e.dtype),A=[{type:"int32",data:[f]}],b=new Wce(y,n,r.device.limits.maxComputeWorkgroupSizeX),w=r.runWebGPUProgram(b,[d],x,A);i.push(w),m=ke({inputs:{x:w},attrs:{shape:h},backend:r})}return i.forEach(f=>r.disposeData(f.dataId)),m}function Vce(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{keepDims:s,axis:i}=n;return gl(r,i,s,"all",a)}var Uce={kernelName:_i,backendName:"webgpu",kernelFunc:Vce};function Gce(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{keepDims:s,axis:i}=n;return gl(r,i,s,"any",a)}var Hce={kernelName:Oi,backendName:"webgpu",kernelFunc:Gce},A9=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]=I.computeOutAndReduceShapes(e,n);this.outputShape=r.length===0?[1]:r,this.dispatchLayout=me(this.outputShape),v.sizeFromShape(s)<32?(this.type="plain",this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize)):(this.type="shared",this.dispatch=de(this.dispatchLayout,this.outputShape,[1,1,1])),this.inputShape=e,this.shaderKey=`argMinMax_${this.op}_${this.type}`}getUserCode(){let e=this.workgroupSize[0],t=()=>this.inputShape.length===1?"uniforms.xShape":`uniforms.xShape.${Nr(this.inputShape.length-1)}`,a=()=>{let n="";if(this.outputShape.length===1)this.inputShape.length!==1&&(n+="outputCoords,");else for(let r=0;r<this.outputShape.length;r++)n+=`outputCoords.${Nr(r)},`;return n};return this.type==="shared"?`
|
|
fn DIV_CEIL(a : u32, b : u32) -> u32 {
|
|
return ((a - 1u) / b + 1u);
|
|
}
|
|
|
|
${`
|
|
var<workgroup> xBestIndices : array<i32, ${e}>;
|
|
var<workgroup> xBestValues : array<f32, ${e}>;
|
|
`}
|
|
|
|
${ue("index")} {
|
|
let outputIndex = index / ${e};
|
|
let reduceLength = ${t()};
|
|
|
|
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 + ${e}) {
|
|
let candidate = getX(${a()} 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), ${e}u);
|
|
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]);
|
|
}
|
|
}
|
|
`:`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let outputCoords = getCoordsFromIndex(index);
|
|
var bestIndex = 0;
|
|
var bestValue = getX(${a()} 0);
|
|
let reduceLength = ${t()};
|
|
for (var i = 1; i < reduceLength; i++) {
|
|
let candidate = getX(${a()} i);
|
|
if (candidate ${this.op} bestValue) {
|
|
bestValue = candidate;
|
|
bestIndex = i;
|
|
}
|
|
}
|
|
setOutputAtIndexI32(index, bestIndex);
|
|
}
|
|
}
|
|
`}};function jce(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s}=n,i=v.parseAxisParam(s,r.shape),o=I.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=ir({inputs:{x:r},backend:a,attrs:{perm:o}}),u.push(l),i=I.getInnerMostAxes(i.length,l.shape.length)),I.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let d=new A9(l.shape,i[0],"max"),c=[{type:"float32",data:[Number.NEGATIVE_INFINITY]}],p=a.runWebGPUProgram(d,[l],"int32",c);return u.forEach(h=>a.disposeData(h.dataId)),p}var qce={kernelName:hu,backendName:"webgpu",kernelFunc:jce};function Xce(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s}=n,i=v.parseAxisParam(s,r.shape),o=I.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=ir({inputs:{x:r},backend:a,attrs:{perm:o}}),u.push(l),i=I.getInnerMostAxes(i.length,l.shape.length)),I.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let d=new A9(l.shape,i[0],"min"),c=[{type:"float32",data:[Number.POSITIVE_INFINITY]}],p=a.runWebGPUProgram(d,[l],"int32",c);return u.forEach(h=>a.disposeData(h.dataId)),p}var Kce={kernelName:mu,backendName:"webgpu",kernelFunc:Xce},Yce=at({opType:le.ASIN}),Zce={kernelName:zi,backendName:"webgpu",kernelFunc:Yce},Jce=at({opType:le.ASINH}),Qce={kernelName:Li,backendName:"webgpu",kernelFunc:Jce},ehe=at({opType:le.ATAN}),the={kernelName:Wi,backendName:"webgpu",kernelFunc:ehe},ahe=aa({opType:De.ATAN2}),nhe={kernelName:Vi,backendName:"webgpu",kernelFunc:ahe},rhe=at({opType:le.ATANH}),she={kernelName:Bi,backendName:"webgpu",kernelFunc:rhe},ihe=class{constructor(e){this.variableNames=["x"],this.uniforms="strides : vec2<i32>,",this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="poolWithFilterSizeEqualsOne"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let batch = coords[0];
|
|
let d = coords[3];
|
|
|
|
let xRCCorner = coords.yz * uniforms.strides;
|
|
let xRCorner = xRCCorner.x;
|
|
let xCCorner = xRCCorner.y;
|
|
|
|
let value = getX(batch, xRCorner, xCCorner, d);
|
|
setOutputAtIndex(index, value);
|
|
}
|
|
}
|
|
`}},pp=class{constructor(e,t,a=!1,n=!1,r=!1){if(this.variableNames=["x"],this.uniforms="strides : vec2<i32>, pads : vec2<i32>, dilations : vec2<i32>, convDims : vec2<i32>, filterDims : vec2<i32>,",this.workgroupSize=[128,1,1],this.size=!0,t==="avg"&&a)throw new Error("Cannot compute positions for average pool.");this.outputShape=e.outShape,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.poolType=t,this.computePositions=a,this.flattenPositions=n,this.includeBatchIndex=r,this.shaderKey=`pool2D_${t}_${a}_${n}_${r}`}getUserCode(){let e;this.poolType==="avg"?e="resultValue = resultValue + value; count = count + 1.0;":this.computePositions?e=`let currMaxValue = mix(value, maxValue, maxValueFound);
|
|
if (value >= currMaxValue) {
|
|
maxValue = value;
|
|
maxValueFound = 1.0;
|
|
maxPosition = ${this.flattenPositions?this.includeBatchIndex?"((batch * uniforms.xShape[1] + xR) * uniforms.xShape[2] + xC) * uniforms.xShape[3] + d":"(xR * uniforms.xShape[2] + xC) * uniforms.xShape[3] + d":"wR * uniforms.filterDims.y + wC"};
|
|
}`:e="resultValue = max(value, resultValue);";let t="resultValue";return this.poolType==="avg"&&(t="resultValue / max(count, 1.0)"),`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let batch = coords[0];
|
|
let d = coords[3];
|
|
let xRCCorner = vec2<i32>(coords.yz) * uniforms.strides - uniforms.pads;
|
|
let xRCorner = xRCCorner.x;
|
|
let xCCorner = xRCCorner.y;
|
|
|
|
${this.computePositions?`var maxValue = 0.0;
|
|
var maxValueFound = 0.0;
|
|
var maxPosition = 0;`:`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.dilations.x) {
|
|
let xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= uniforms.convDims.x) {
|
|
continue;
|
|
}
|
|
|
|
for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + uniforms.dilations.y) {
|
|
let xC = xCCorner + wC;
|
|
if (xC < 0 || xC >= uniforms.convDims.y) {
|
|
continue;
|
|
}
|
|
|
|
let value = getX(batch, xR, xC, d);
|
|
${e}
|
|
}
|
|
}
|
|
|
|
${this.computePositions?"setOutputAtIndexI32(index, maxPosition);":`setOutputAtIndex(index, ${t});`}
|
|
}
|
|
}
|
|
`}},uy=class{constructor(e,t,a=!1,n=!1,r=!1){if(this.variableNames=["x"],this.uniforms="strides : vec3<i32>, pads : vec3<i32>, convDims : vec3<i32>, filterDims : vec3<i32>,",this.workgroupSize=[128,1,1],this.size=!0,t==="avg"&&a)throw new Error("Cannot compute positions for average pool.");this.outputShape=e.outShape,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.poolType=t,this.computePositions=a,this.flattenPositions=n,this.includeBatchIndex=r,this.shaderKey=`pool3D_${t}_${a}_${n}_${r}`}getUserCode(){let e;this.poolType==="avg"?e="resultValue += value; count += 1.0;":this.computePositions?e=`let currMaxValue = mix(value, maxValue, maxValueFound);
|
|
if (value >= currMaxValue) {
|
|
maxValue = value;
|
|
maxValueFound = 1.0;
|
|
maxPosition = ${this.flattenPositions?this.includeBatchIndex?"(((batch * uniforms.xShape.y + xD) * uniforms.xShape.z + xR) * uniforms.xShape.w + xC) * uniforms.xShape.u + ch":"((xD * uniforms.xShape.z + xR) * uniforms.xShape.w + xC) * uniforms.xShape.u + ch":"wD * uniforms.filterDims.y * uniforms.filterDims.y + wR * uniforms.filterDims.z + wC"};
|
|
}`:e="resultValue = max(value, resultValue);";let t="resultValue";return this.poolType==="avg"&&(t="resultValue / max(count, 1.0)"),`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let batch = coords.x;
|
|
let ch = coords.u;
|
|
|
|
let xCorner = vec3<i32>(coords.y, coords.z, coords.w) * uniforms.strides - uniforms.pads;
|
|
let xDCorner = xCorner.x;
|
|
let xRCorner = xCorner.y;
|
|
let xCCorner = xCorner.z;
|
|
|
|
${this.computePositions?`var maxValue = 0.0;
|
|
var maxValueFound = 0.0;
|
|
var maxPosition = 0;`:`var resultValue = ${this.poolType==="avg"?"0.0":"-1.0 / pow(10.0, -20.0)"};`}
|
|
|
|
var count = 0.0;
|
|
for (var wD = 0; wD < uniforms.filterDims.x; wD++) {
|
|
let xD = xDCorner + wD;
|
|
if (xD < 0 || xD >= uniforms.convDims.x) {
|
|
continue;
|
|
}
|
|
|
|
for (var wR = 0; wR < uniforms.filterDims.y; wR++) {
|
|
let xR = xRCorner + wR;
|
|
if (xR < 0 || xR >= uniforms.convDims.y) {
|
|
continue;
|
|
}
|
|
|
|
for (var wC = 0; wC < uniforms.filterDims.z; wC++) {
|
|
let xC = xCCorner + wC;
|
|
if (xC < 0 || xC >= uniforms.convDims.z) {
|
|
continue;
|
|
}
|
|
|
|
let value = getX(batch, xD, xR, xC, ch);
|
|
${e}
|
|
}
|
|
}
|
|
}
|
|
|
|
${this.computePositions?"setOutputAtIndexI32(index, maxPosition);":`setOutputAtIndex(index, ${t});`}
|
|
}
|
|
}
|
|
`}};function b9(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{reductionIndices:s,keepDims:i}=n;return gl(r,s,i,"max",a)}var ohe={kernelName:Io,backendName:"webgpu",kernelFunc:b9};function v9(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{keepDims:s,axis:i}=n;return gl(r,i,s,"mean",a)}var lhe={kernelName:To,backendName:"webgpu",kernelFunc:v9};function w9(e,t,a,n){if(t.filterWidth===1&&t.filterHeight===1&&v.arraysEqual(t.inShape,t.outShape))return an({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=ke({inputs:{x:e},backend:n,attrs:{shape:[e.shape[i-3]*e.shape[i-2],e.shape[i-1]]}}),l;a==="avg"?l=v9({inputs:{x:o},backend:n,attrs:{axis:0,keepDims:!1}}):(v.assert(a==="max",()=>`Invalid pool type ${a}`),l=b9({inputs:{x:o},backend:n,attrs:{reductionIndices:0,keepDims:!1}}));let u=ke({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 ihe(t):(a==="avg"?r=new pp(t,"avg"):(v.assert(a==="max",()=>`Invalid pool type ${a}`),r=new pp(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 uhe(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=I.computePool2DInfo(r.shape,s,i,1,o,l);return w9(r,u,"avg",a)}var dhe={kernelName:Ui,backendName:"webgpu",kernelFunc:uhe};function phe(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dataFormat:l,dimRoundingMode:u}=n,d=[1,1,1],c=I.computePool3DInfo(r.shape,s,i,d,o,u,l),p=new uy(c,"avg"),h=[{type:"int32",data:[c.strideDepth,c.strideHeight,c.strideWidth]},{type:"int32",data:[c.padInfo.front,c.padInfo.top,c.padInfo.left]},{type:"int32",data:[c.inDepth,c.inHeight,c.inWidth]},{type:"int32",data:[c.effectiveFilterDepth,c.effectiveFilterHeight,c.effectiveFilterWidth]}];return a.runWebGPUProgram(p,[r],r.dtype,h)}var che={kernelName:fu,backendName:"webgpu",kernelFunc:phe},hhe=class{constructor(e){this.variableNames=["dy"],this.uniforms=`strides : vec2<i32>, pads : vec2<i32>, dilations : vec2<i32>, filterDims : vec2<i32>,
|
|
outHeight : i32, outWidth : i32, avgMultiplier : f32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="avgPool2DBackprop"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let batch = coords[0];
|
|
let d = coords[3];
|
|
|
|
let dyRCCorner = vec2<i32>(coords.yz) - uniforms.pads;
|
|
let dyRCorner = dyRCCorner.x;
|
|
let 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.
|
|
var dotProd = 0.0;
|
|
for (var wR = 0; wR < uniforms.filterDims[0]; wR = wR + uniforms.dilations[0]) {
|
|
let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[0]);
|
|
|
|
if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
let idyR = i32(dyR);
|
|
|
|
for (var wC = 0; wC < uniforms.filterDims[1]; wC = wC + uniforms.dilations[1]) {
|
|
let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[1]);
|
|
|
|
if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
let idyC = i32(dyC);
|
|
|
|
let dyValue = getDy(batch, idyR, idyC, d);
|
|
|
|
dotProd = dotProd + dyValue * uniforms.avgMultiplier;
|
|
}
|
|
}
|
|
setOutputAtIndex(index, dotProd);
|
|
}
|
|
}
|
|
`}},mhe=class{constructor(e){this.variableNames=["dy"],this.uniforms=`strides : vec3<i32>, pads : vec3<i32>, filterDims : vec3<i32>,
|
|
outDepth : i32, outHeight : i32, outWidth : i32, avgMultiplier : f32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="avgPool3DBackprop"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let batch = coords.x;
|
|
let ch = coords.u;
|
|
|
|
let dyCorner = vec3<i32>(coords.y, coords.z, coords.w) - uniforms.pads;
|
|
let dyDCorner = dyCorner.x;
|
|
let dyRCorner = dyCorner.y;
|
|
let 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.
|
|
var dotProd = 0.0;
|
|
for (var wD = 0; wD < uniforms.filterDims[0]; wD++) {
|
|
let dyD = f32(dyDCorner + wD) / f32(uniforms.strides[0]);
|
|
|
|
if (dyD < 0.0 || dyD >= f32(uniforms.outDepth) || fract(dyD) > 0.0) {
|
|
continue;
|
|
}
|
|
let idyD = i32(dyD);
|
|
|
|
for (var wR = 0; wR < uniforms.filterDims[1]; wR++) {
|
|
let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[1]);
|
|
|
|
if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
let idyR = i32(dyR);
|
|
|
|
for (var wC = 0; wC < uniforms.filterDims[2]; wC++) {
|
|
let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[2]);
|
|
|
|
if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
let idyC = i32(dyC);
|
|
|
|
let dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
dotProd += dyValue * uniforms.avgMultiplier;
|
|
}
|
|
}
|
|
}
|
|
setOutputAtIndex(index, dotProd);
|
|
}
|
|
}
|
|
`}};function fhe(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:d}=n,c=I.computePool3DInfo(i.shape,o,l,1,u,d),p=new mhe(c),h=1/(c.filterDepth*c.filterHeight*c.filterWidth),m=[{type:"int32",data:[c.strideDepth,c.strideHeight,c.strideWidth]},{type:"int32",data:[c.effectiveFilterDepth-1-c.padInfo.front,c.effectiveFilterHeight-1-c.padInfo.top,c.effectiveFilterWidth-1-c.padInfo.left]},{type:"int32",data:[c.effectiveFilterDepth,c.effectiveFilterHeight,c.effectiveFilterWidth]},{type:"int32",data:[c.outDepth]},{type:"int32",data:[c.outHeight]},{type:"int32",data:[c.outWidth]},{type:"float32",data:[h]}];return a.runWebGPUProgram(p,[r],i.dtype,m)}var ghe={kernelName:yp,backendName:"webgpu",kernelFunc:fhe};function yhe(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,i=s;ay([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:u}=n,d=I.computePool2DInfo(i.shape,o,l,1,u),c=new hhe(d),p=1/(d.filterHeight*d.filterWidth),h=[{type:"int32",data:[d.strideHeight,d.strideWidth]},{type:"int32",data:[d.effectiveFilterHeight-1-d.padInfo.top,d.effectiveFilterWidth-1-d.padInfo.left]},{type:"int32",data:[d.dilationHeight,d.dilationWidth]},{type:"int32",data:[d.effectiveFilterHeight,d.effectiveFilterWidth]},{type:"int32",data:[d.outHeight]},{type:"int32",data:[d.outWidth]},{type:"float32",data:[p]}];return a.runWebGPUProgram(c,[r],i.dtype,h)}var xhe={kernelName:gp,backendName:"webgpu",kernelFunc:yhe};function Ahe(e){let{inputs:t,backend:a,attrs:n}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=n;return x0({a:r,b:s,transposeA:i,transposeB:o,backend:a})}var bhe={kernelName:Gi,backendName:"webgpu",kernelFunc:Ahe},vhe=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=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.start=e,this.uniforms=`start : ${Dt(e.length)}, `,this.shaderKey="slice"}getUserCode(){let e=Dt(this.rank),t=whe(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.${ag[r]} = uniforms.start.${Nr(r)} + coords.${ag[r]};`),`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
var sourceLoc : ${e};
|
|
let coords = getCoordsFromIndex(index);
|
|
${a.join(`
|
|
`)}
|
|
setOutputAtIndex(index, getSource(${t}));
|
|
}
|
|
}
|
|
`}},ag=["x","y","z","w","u","v"];function whe(e){if(e===1)return"sourceLoc";if(e<=6)return ag.slice(0,e).map(t=>`sourceLoc.${t}`).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}function od(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{begin:s,size:i}=n,[o,l]=wt.parseSliceParams(r,s,i);if(wt.assertParamsValid(r,o,l),a.shouldExecuteOnCPU([r])||r.dtype==="string"){let c=a.tensorMap.get(r.dataId),p=Ace(c.values,o,l,r.shape,r.dtype);return a.makeTensorInfo(l,r.dtype,p)}if(v.sizeFromShape(l)===0)return a.makeTensorInfo(l,r.dtype,[]);let u=new vhe(o,l),d=[{type:"int32",data:o}];return a.runWebGPUProgram(u,[r],r.dtype,d)}var khe={kernelName:zu,backendName:"webgpu",kernelFunc:od},Ihe=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((x,A)=>x*A),l=I.getReshaped(r.shape,s,o),u=I.getPermuted(l.length,s.length),d=I.getReshapedPermuted(r.shape,s,o),c=I.getSliceBeginCoords(i,s.length),p=I.getSliceSize(d,i,s.length),h=[],m=ke({inputs:{x:r},backend:a,attrs:{shape:l}}),f=ir({inputs:{x:m},backend:a,attrs:{perm:u}}),g=ke({inputs:{x:f},backend:a,attrs:{shape:d}}),y=od({inputs:{x:g},backend:a,attrs:{begin:c,size:p}});return h.push(m),h.push(f),h.push(g),h.forEach(x=>a.disposeData(x.dataId)),y},She={kernelName:gu,backendName:"webgpu",kernelFunc:Ihe},The=`
|
|
fn bincount_write(index: i32, value: f32) {
|
|
${Bs("&result[index]","value","float32")}
|
|
}
|
|
`,Che=`
|
|
fn bincount_write(index: i32, value: f32) {
|
|
atomicStore(&result[index], bitcast<i32>(value));
|
|
}
|
|
`,k9=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=me(this.outputShape),this.dispatch=de(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?Che:The}
|
|
${ue("index")} {
|
|
${this.rank===1?`if (index < uniforms.xShape) {
|
|
let indexVal = i32(getX(index));
|
|
if (indexVal < uniforms.binCountSize) {
|
|
let value = ${this.binaryOutput?1:this.hasWeights?"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?"getW(coord[0], coord[1])":"1."};
|
|
bincount_write(coord.x * uniforms.binCountSize + indexVal, value);
|
|
}
|
|
}`}
|
|
}
|
|
`}};function Nhe(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],d=s.dtype,c=Wa({backend:a,attrs:{shape:u,value:0,dtype:d}}),p=new k9([o],l),h=[{type:"int32",data:[i]}],m=l?[r,s]:[r];return a.runWebGPUProgram(p,m,d,h,c)}var Rhe={kernelName:Hi,backendName:"webgpu",kernelFunc:Nhe},Ehe=class{constructor(e){this.outputShape=[],this.variableNames=["s0","s1"],this.uniforms="s0Size : i32, s1Size : i32, ",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e],this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="broadcastArgs"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
var s0 = 1.0;
|
|
var s1 = 1.0;
|
|
let indexS0 = index - uniforms.size + uniforms.s0Size;
|
|
let indexS1 = index - uniforms.size + uniforms.s1Size;
|
|
if (indexS0 >= 0) {
|
|
s0 = getS0(indexS0);
|
|
}
|
|
if (indexS1 >= 0) {
|
|
s1 = getS1(indexS1);
|
|
}
|
|
|
|
if (s0 == 1.0) {
|
|
setOutputAtIndex(index, s1);
|
|
} else if (s1 == 1.0) {
|
|
setOutputAtIndex(index, s0);
|
|
} else if (s0 != s1) {
|
|
setOutputAtIndex(index, uniforms.NAN);
|
|
} else {
|
|
setOutputAtIndex(index, s0);
|
|
}
|
|
}
|
|
}
|
|
`}};function Mhe(e){let{inputs:t,backend:a}=e,{s0:n,s1:r}=t;if(a.shouldExecuteOnCPU([n,r])){let d=a.tensorMap.get(n.dataId),c=a.tensorMap.get(r.dataId),p=d.values,h=c.values,m=I.assertAndGetBroadcastShape(Array.from(p),Array.from(h));return a.makeTensorInfo([m.length],"int32",Int32Array.from(m))}let s=v.sizeFromShape(n.shape),i=v.sizeFromShape(r.shape),o=Math.max(s,i),l=new Ehe(o),u=[{type:"int32",data:[s]},{type:"int32",data:[i]}];return a.runWebGPUProgram(l,[n,r],"int32",u)}var Fhe={kernelName:yu,backendName:"webgpu",kernelFunc:Mhe},I9=aa({opType:De.NOT_EQUAL,dtype:"bool",cpuKernelImpl:hce}),$he={kernelName:Cs,backendName:"webgpu",kernelFunc:I9};function oc(e){let{inputs:t,backend:a}=e,{input:n}=t,r=a.tensorMap.get(n.dataId);return an({inputs:{x:r.complexTensorInfos.real},backend:a})}var Dhe={kernelName:Ep,backendName:"webgpu",kernelFunc:oc};function Phe(e,t){let a=new id(e.shape,le.TO_INT),n=t.runWebGPUProgram(a,[e],"int32");return{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}function ng(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{dtype:s}=n;if(s==="complex64"){if(r.dtype==="complex64")return an({inputs:{x:r},backend:a});let i=An(r.shape),o=ng({inputs:{x:r},backend:a,attrs:{dtype:"float32"}}),l=fl({inputs:{real:o,imag:i},backend:a});return i.dispose(),a.disposeData(o.dataId),l}if(r.dtype==="complex64"){let i=oc({inputs:{input:r},backend:a}),o=ng({inputs:{x:i},backend:a,attrs:{dtype:s}});return a.disposeData(i.dataId),o}if(!v.hasEncodingLoss(r.dtype,s)){let i=an({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]=qpe(i,r.shape,r.dtype,s);return a.makeTensorInfo(o,l,u)}if(s==="int32")return Phe(r,a);if(s==="bool"){let i=a.makeTensorInfo([],"bool",v.getTypedArrayFromDType("bool",1)),o=I9({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 _he={kernelName:qi,backendName:"webgpu",kernelFunc:ng},Ohe=at({opType:le.CEIL,cpuKernelImpl:Xpe}),zhe={kernelName:cs,backendName:"webgpu",kernelFunc:Ohe},Lhe=class{constructor(e){this.variableNames=["A"],this.uniforms="minVal : f32, maxVal : f32,",this.workPerThread=4,this.workgroupSize=[64,1,1],this.outputComponent=4,this.size=!0,this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]),this.shaderKey="clipVec4"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if(index < uniforms.size) {
|
|
let value = getAByOutputIndex(index);
|
|
var clampedValue = clamp(
|
|
value, vec4<f32>(uniforms.minVal), vec4<f32>(uniforms.maxVal));
|
|
clampedValue = select(clampedValue, value, isnanVec4(value));
|
|
setOutputAtIndex(index, clampedValue);
|
|
}
|
|
}
|
|
`}},Whe=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=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="clip"}getUserCode(){return`
|
|
${ue("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 Bhe(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 Lhe(r.shape):o=new Whe(r.shape),a.runWebGPUProgram(o,[r],r.dtype,l)}var Vhe={kernelName:hs,backendName:"webgpu",kernelFunc:Bhe},Uhe=class{constructor(e){this.outputShape=[],this.variableNames=["real","imag"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="complexAbs"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let re = abs(getRealByOutputIndex(index));
|
|
let im = abs(getImagByOutputIndex(index));
|
|
let mx = max(re, im);
|
|
|
|
// The length function in wgsl may be not underflow-safe on some GPUs.
|
|
// So the safe solution is to ensure underflow-safety in all cases.
|
|
setOutputAtIndex(index, select(mx * length(vec2<f32>(1, min(re, im)/mx)), 0.0, mx == 0.0));
|
|
}
|
|
}
|
|
`}};function kA(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function Ghe(e){let{inputs:t,backend:a}=e,{x:n}=t,r=a.tensorMap.get(n.dataId),s=new Uhe(n.shape),i=[kA(n,r.complexTensorInfos.real),kA(n,r.complexTensorInfos.imag)];return a.runWebGPUProgram(s,i,i[0].dtype)}var Hhe={kernelName:Ap,backendName:"webgpu",kernelFunc:Ghe},jhe=class{constructor(e){this.uniforms="",this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=I.computeOutShape(e,1),this.variableNames=e.map((t,a)=>`T${a}`),this.dispatchLayout=me(this.outputShape),this.dispatch=de(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`
|
|
${ue("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 A0(e){let{inputs:t,backend:a}=e,{input:n}=t,r=a.tensorMap.get(n.dataId);return an({inputs:{x:r.complexTensorInfos.imag},backend:a})}var qhe={kernelName:Cp,backendName:"webgpu",kernelFunc:A0};function Wd(e,t,a){let n=e[0].dtype;if(n==="complex64"){let m=e.map(A=>oc({inputs:{input:A},backend:a})),f=e.map(A=>A0({inputs:{input:A},backend:a})),g=Wd(m,t,a),y=Wd(f,t,a),x=fl({inputs:{real:g,imag:y},backend:a});return m.forEach(A=>a.disposeData(A.dataId)),f.forEach(A=>a.disposeData(A.dataId)),a.disposeData(g.dataId),a.disposeData(y.dataId),x}let r=a.shouldExecuteOnCPU(e);if(n==="string"&&(r=!0),r){let m=e.map(w=>{let S=[-1,v.sizeFromShape(w.shape.slice(t))];return ke({inputs:{x:w},backend:a,attrs:{shape:S}})}),f=m.map(w=>({vals:a.readSync(w.dataId),shape:w.shape})),g=I.computeOutShape(m.map(w=>w.shape),1),y=m[0].shape[0]===1,x=Kpe(f,g,n,y),A=I.computeOutShape(e.map(w=>w.shape),t),b=a.makeTensorInfo(A,n,x);return m.forEach(w=>a.disposeData(w.dataId)),b}let s=a.device.limits.maxStorageBuffersPerShaderStage-1;if(e.length>s){let m=[];for(let g=0;g<e.length;g+=s){let y=e.slice(g,g+s);m.push(Wd(y,t,a))}let f=Wd(m,t,a);for(let g of m)a.disposeData(g.dataId);return f}let{tensors2D:i,outShape:o}=Xhe(e,t,a),l=i.map(m=>m.shape),u=new jhe(l),d=[],c=new Array(l.length-1);if(c.length>0){c[0]=l[0][1],d.push({type:"int32",data:[c[0]]});for(let m=1;m<c.length;m++)c[m]=c[m-1]+l[m][1],d.push({type:"int32",data:[c[m]]})}let p=a.runWebGPUProgram(u,i,i[0].dtype,d);i.forEach(m=>a.disposeData(m.dataId));let h=ke({inputs:{x:p},backend:a,attrs:{shape:o}});return a.disposeData(p.dataId),h}function Xhe(e,t,a){let n=I.computeOutShape(e.map(r=>r.shape),t);return{tensors2D:e.map(r=>ke({inputs:{x:r},backend:a,attrs:{shape:[v.sizeFromShape(r.shape.slice(0,t)),v.sizeFromShape(r.shape.slice(t))]}})),outShape:n}}function S9(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);I.assertParamsConsistent(i,s);let o=I.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?an({inputs:{x:l[0]},backend:a}):Wd(l,s,a)}var Khe={kernelName:xu,backendName:"webgpu",kernelFunc:S9};function Yhe(e,t,a,n,r=!1,s=null,i=!1,o=4,l=4,u=4){let d=N=>{switch(N){case 1:return"resData = f32(x[xIndex]);";case 3:return"resData = vec3<f32>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);";case 4:return"resData = vec4<f32>(x[xIndex / 4]);";default:throw new Error(`innerElementSize ${N} is not supported.`)}},c=N=>{switch(N){case 1:return"return f32(W[row * uniforms.wShape[3] + col]);";case 4:return"return vec4<f32>(W[(row * uniforms.wShape[3] + col) / 4]);";default:throw new Error(`innerElementSize ${N} is not supported.`)}},p=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);
|
|
`,m=e?"uniforms.xShape[1]":"uniforms.xShape[2]",f=e?"uniforms.xShape[2]":"uniforms.xShape[3]",g=e?"row":"col",y=e?"col":"row",x=`
|
|
let inChannels = uniforms.wShape[2];
|
|
let outWidth = ${e?"uniforms.outShape[2]":"uniforms.outShape[3]"};
|
|
let outRow = ${g} / outWidth;
|
|
let outCol = ${g} % outWidth;
|
|
|
|
let WRow = ${y} / (uniforms.filterDims[1] * inChannels);
|
|
let WCol = ${y} / inChannels % uniforms.filterDims[1];
|
|
let xRow = outRow * uniforms.strides[0] + uniforms.dilations[0] * WRow - uniforms.pads[0];
|
|
let xCol = outCol * uniforms.strides[1] + uniforms.dilations[1] * WCol - uniforms.pads[1];
|
|
let xCh = ${y} % inChannels;
|
|
var resData = ${Xe(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 < ${m} && xCol >= 0 && xCol < ${f}) {
|
|
${p}
|
|
let xIndex = getIndexFromCoords4D(coord, uniforms.xShape);
|
|
${d(o)}
|
|
}
|
|
return resData;`,A=e?t&&n?`
|
|
${x}`:`
|
|
if (row < uniforms.dimAOuter && col < uniforms.dimInner) {
|
|
${x}
|
|
}
|
|
return ${Xe(o)}(0.0);`:n&&a?`
|
|
${x}`:`
|
|
if (row < uniforms.dimInner && col < uniforms.dimBOuter) {
|
|
${x}
|
|
}
|
|
return ${Xe(o)}(0.0);`,b=`${c(l)}`,w=Xe(u),S=Xe(e?o:l),C=Xe(e?l:o);return`
|
|
${Or(s,i,u===4,4)}
|
|
fn mm_readA(batch: i32, row : i32, col : i32) -> ${S} {
|
|
${e?A:b}
|
|
}
|
|
|
|
fn mm_readB(batch: i32, row : i32, col : i32) -> ${C} {
|
|
${e?b:A}
|
|
}
|
|
|
|
fn mm_write(batch: i32, row : i32, col : i32, valueIn : ${w}) {
|
|
if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)
|
|
{
|
|
var value = valueIn;
|
|
let outWidth = ${e?"uniforms.outShape[2]":"uniforms.outShape[3]"};
|
|
${h}
|
|
${ml(r,s)}
|
|
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
|
|
}
|
|
}`}var Zhe=class{constructor(e,t,a,n,r=!1,s=null,i=!1,o=!1){this.variableNames=["x","W"],this.uniforms="filterDims : vec2<i32>, pads : vec2<i32>, strides : vec2<i32>, dilations : 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=Q3(this.dispatchLayout,this.outputShape,this.isVec4),this.elementsPerThread=ey(this.dispatchLayout,this.outputShape,this.isVec4),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize,this.elementsPerThread),this.isVec4?(this.outputComponent=4,this.isChannelsLast&&e.inChannels%4!==0?(this.innerElementSize=3,this.variableComponents=[1,4]):(this.innerElementSize=4,this.variableComponents=[4,4]),r&&(this.variableNames.push("bias"),this.variableComponents.push(4)),i&&(this.variableNames.push("preluActivationWeights"),this.variableComponents.push(4))):(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?g0(this.elementsPerThread,this.workgroupSize,!this.isChannelsLast,this.tileInner):y0(this.elementsPerThread,this.workgroupSize,!this.isChannelsLast,this.tileInner,!1,null,this.sequentialAccessByThreads),t=this.isVec4?[this.innerElementSize,4,4]:[1,1,1];return`
|
|
${Yhe(this.isChannelsLast,this.fitAOuter,this.fitBOuter,this.fitInner,this.addBias,this.activation,this.hasPreluActivationWeights,t[0],t[1],t[2])}
|
|
${e}
|
|
`}},Jhe=class{constructor(e,t=!1,a=null,n=!1){this.variableNames=["x","W"],this.uniforms="filterDims: vec2<i32>, pads: vec2<i32>, strides: vec2<i32>, dilations: 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=de(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`
|
|
${Or(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;
|
|
${ml(this.addBias,this.activation)}
|
|
setOutputAtCoords(coords.x, coords.y, coords.z, coords.w, value);
|
|
}
|
|
}
|
|
${ue("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.strides[0] + uniforms.dilations[0] * row - uniforms.pads[0];
|
|
let xCol = outCol * uniforms.strides[1] + uniforms.dilations[1] * col - uniforms.pads[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);
|
|
}
|
|
`}},Qhe=class{constructor(e,t){this.variableNames=["x"],this.uniforms=`pads : vec2<i32>, strides : vec2<i32>, dilations : vec2<i32>, outWidth : i32, itemsPerBlockRow : i32,
|
|
inChannels : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(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`
|
|
${ue("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.strides[0] - uniforms.pads[0];
|
|
let xRow = offsetY + uniforms.dilations[0] * (col / uniforms.itemsPerBlockRow);
|
|
var value = 0.0;
|
|
if(xRow < uniforms.xShape[${e}] && xRow >= 0) {
|
|
let offsetX = (row % uniforms.outWidth) * uniforms.strides[1] -
|
|
uniforms.pads[1];
|
|
let xCol = offsetX + uniforms.dilations[1] * ((col %
|
|
uniforms.itemsPerBlockRow) / uniforms.inChannels);
|
|
let ch = col % uniforms.inChannels;
|
|
if(xCol < uniforms.xShape[${t}] && xCol >= 0) {
|
|
value = ${r};
|
|
}
|
|
}
|
|
setOutputAtIndex(index, value);
|
|
}
|
|
}
|
|
`}};function Ph(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 e0e({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,d=!1,c=l&&a.filterHeight===a.inHeight&&a.filterWidth===a.inWidth&&a.padInfo.type==="VALID",p=[],h,m;if(c){let y=a.inHeight*a.inWidth*a.inChannels;h=ke({inputs:{x:e},backend:n,attrs:{shape:[1,a.batchSize,y]}}),m=ke({inputs:{x:t},backend:n,attrs:{shape:[1,y,a.outChannels]}})}else h=ke({inputs:{x:e},backend:n,attrs:{shape:l?[a.batchSize,a.inHeight*a.inWidth,a.inChannels]:[a.batchSize,a.inChannels,a.inHeight*a.inWidth]}}),m=ke({inputs:{x:t},backend:n,attrs:{shape:[1,a.inChannels,a.outChannels]}});if(p.push(h),p.push(m),s!=null){let y=Ph(s.shape,l);y!=null&&(s=ke({inputs:{x:s},backend:n,attrs:{shape:y}}),p.push(s))}if(r!=null){let y=Ph(r.shape,l);y!=null&&(r=ke({inputs:{x:r},backend:n,attrs:{shape:y}}),p.push(r))}let f=x0({a:l?h:m,b:l?m:h,transposeA:u,transposeB:d,backend:n,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),g=ke({inputs:{x:f},backend:n,attrs:{shape:a.outShape}});p.push(f);for(let y of p)n.disposeData(y.dataId);return g}function t0e({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:d,strideWidth:c,strideHeight:p,padInfo:h,outWidth:m,outHeight:f,dilationWidth:g,dilationHeight:y,dataFormat:x}=a,A=x==="channelsLast",b=l*u*d,w=f*m,S=A?[a.batchSize,w,b]:[a.batchSize,b,w],C=new Qhe(S,A),N=[{type:"int32",data:[h.top,h.left]},{type:"int32",data:[p,c]},{type:"int32",data:[y,g]},{type:"int32",data:[m]},{type:"int32",data:[d*l]},{type:"int32",data:[d]}],M=n.runWebGPUProgram(C,[e],e.dtype,N),F=[];F.push(M);let E=ke({inputs:{x:t},backend:n,attrs:{shape:[1,b,-1]}});if(F.push(E),s!=null){let O=Ph(s.shape,A);O!=null&&(s=ke({inputs:{x:s},backend:n,attrs:{shape:O}}),F.push(s))}if(r!=null){let O=Ph(r.shape,A);O!=null&&(r=ke({inputs:{x:r},backend:n,attrs:{shape:O}}),F.push(r))}let T=x0({a:A?M:E,b:A?E:M,transposeA:!A,transposeB:!1,backend:n,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),D=ke({inputs:{x:T},backend:n,attrs:{shape:a.outShape}});F.push(T);for(let O of F)n.disposeData(O.dataId);return D}function T9({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,d=a.dataFormat==="channelsLast",c=d&&a.filterHeight===a.inHeight&&a.filterWidth===a.inWidth&&a.padInfo.type==="VALID",p=B().getBool("WEBGPU_USE_NAIVE_CONV2D_DEBUG");if(!p&&(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 e0e({x:e,filter:t,convInfo:a,backend:n,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i});let h=B().getNumber("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL"),m=h>-1?h:n.thresholdToIncreaseWorkgroups,f=a.batchSize*Math.ceil(a.outHeight*a.outWidth/32)*Math.ceil(a.outChannels/32);if(B().getBool("WEBGPU_CONV_SEPARATE_IM2COL_SHADER")||f<=m)return t0e({x:e,filter:t,convInfo:a,backend:n,bias:r,preluActivationWeights:s,leakyreluAlpha:i,activation:o});let g,y=[a.padInfo.top,a.padInfo.left],x=[{type:"int32",data:[a.filterHeight,a.filterWidth]},{type:"int32",data:[...y]},{type:"int32",data:[a.strideHeight,a.strideWidth]},{type:"int32",data:[a.dilationHeight,a.dilationWidth]}];if(p)g=new Jhe(a,l,o,u);else{let S=d?a.outHeight*a.outWidth:a.outChannels,C=d?a.outChannels:a.outHeight*a.outWidth,N=a.filterHeight*a.filterWidth*a.inChannels;x.push({type:"int32",data:[S]},{type:"int32",data:[C]},{type:"int32",data:[N]});let M=n.adapterInfo.isIntel();g=new Zhe(a,S,C,N,l,o,u,M)}let A=[],b=[e,t];l&&(!d&&r.shape.length===1&&(r=ke({inputs:{x:r},backend:n,attrs:{shape:[r.shape[0],1,1]}}),A.push(r)),b.push(r)),u&&(!d&&s.shape.length===1&&(s=ke({inputs:{x:s},backend:n,attrs:{shape:[s.shape[0],1,1]}}),A.push(s)),b.push(s)),o==="leakyrelu"&&(x.push({type:"float32",data:[i]}),g.uniforms+=" alpha : f32,");let w=n.runWebGPUProgram(g,b,e.dtype,x);for(let S of A)n.disposeData(S.dataId);return w}function a0e(e){let{inputs:t,attrs:a,backend:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:d}=a,c=I.convertConv2DDataFormat(l),p=I.computeConv2DInfo(r.shape,s.shape,i,u,o,d,!1,c);return T9({x:r,filter:s,convInfo:p,backend:n})}var n0e={kernelName:Xi,backendName:"webgpu",kernelFunc:a0e},r0e=class{constructor(e){this.variableNames=["dy","W"],this.uniforms="filterDims : vec2<i32>, pads : vec2<i32>, strides : vec2<i32>, outBackprop : vec4<i32>,",this.workgroupSize=[64,1,1],this.size=!1,this.isVec4=!1,this.workPerThread=1,this.outputShape=e.inShape,this.isChannelsLast=e.dataFormat==="channelsLast",this.isVec4=this.isChannelsLast&&e.outChannels%4===0&&e.inChannels%4===0,this.isVec4?(this.workPerThread=2,this.outputComponent=4,this.workgroupSize=[4,4,4],this.dispatchLayout={x:[3],y:[2],z:[0,1]},this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize,[4,this.workPerThread,1])):(this.size=!0,this.workPerThread=1,this.workgroupSize=[64,1,1],this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize)),this.shaderKey=`conv2DDerInput_${this.isChannelsLast}_${this.isVec4}_${this.workPerThread}`}getUserCode(){let e=this.isChannelsLast?1:2,t=this.isChannelsLast?2:3,a=this.isChannelsLast?3:1,n=`
|
|
${ue()} {
|
|
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 dyCorner = vec2<i32>(r, c) - uniforms.pads;
|
|
|
|
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
var dotProd: array<vec4<f32>, ${this.workPerThread}>;
|
|
for (var i = 0; i < ${this.workPerThread}; i++) {
|
|
dotProd[i] = vec4<f32>(0.0);
|
|
}
|
|
for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + 1) {
|
|
let dyR = f32(dyCorner.x + wR) / f32(uniforms.strides.x);
|
|
let wRPerm = uniforms.filterDims.x - 1 - wR;
|
|
if (dyR < 0.0 || dyR >= f32(uniforms.outBackprop[1]) ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
let idyR = i32(dyR);
|
|
|
|
for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + 1) {
|
|
let dyC = f32(dyCorner.y + wC) / f32(uniforms.strides.y);
|
|
let dyC2 = f32(dyCorner.y + 1 + wC) / f32(uniforms.strides.y);
|
|
let wCPerm = uniforms.filterDims.y - 1 - wC;
|
|
var bDyCVal = true;
|
|
var bDyCVal2 = true;
|
|
if (dyC < 0.0 || dyC >= f32(uniforms.outBackprop[2]) ||
|
|
fract(dyC) > 0.0) {
|
|
bDyCVal = false;
|
|
}
|
|
if (dyC2 < 0.0 || dyC2 >= f32(uniforms.outBackprop[2]) ||
|
|
fract(dyC2) > 0.0) {
|
|
bDyCVal2 = false;
|
|
}
|
|
|
|
let idyC = i32(dyC);
|
|
let idyC2 = i32(dyC2);
|
|
if (bDyCVal && bDyCVal2) {
|
|
let d2Length = uniforms.outBackprop[3];
|
|
for (var d2 = 0; d2 < d2Length; d2 = d2 + 4) {
|
|
let wValue0 = getW(wRPerm, wCPerm, d1, d2);
|
|
let wValue1 = getW(wRPerm, wCPerm, d1 + 1, d2);
|
|
let wValue2 = getW(wRPerm, wCPerm, d1 + 2, d2);
|
|
let wValue3 = getW(wRPerm, wCPerm, d1 + 3, d2);
|
|
var xValue = getDy(batch, idyR, idyC, d2);
|
|
let tmpval = vec4<f32>(dot(xValue, wValue0),
|
|
dot(xValue, wValue1),
|
|
dot(xValue, wValue2),
|
|
dot(xValue, wValue3));
|
|
dotProd[0] = dotProd[0] + tmpval;
|
|
xValue = getDy(batch, idyR, idyC2, d2);
|
|
dotProd[1] = dotProd[1] + vec4<f32>(dot(xValue, wValue0),
|
|
dot(xValue, wValue1),
|
|
dot(xValue, wValue2),
|
|
dot(xValue, wValue3));
|
|
}
|
|
} else if (bDyCVal) {
|
|
let d2Length = uniforms.outBackprop[3];
|
|
for (var d2 = 0; d2 < d2Length; d2 = d2 + 4) {
|
|
let wValue0 = getW(wRPerm, wCPerm, d1, d2);
|
|
let wValue1 = getW(wRPerm, wCPerm, d1 + 1, d2);
|
|
let wValue2 = getW(wRPerm, wCPerm, d1 + 2, d2);
|
|
let wValue3 = getW(wRPerm, wCPerm, d1 + 3, d2);
|
|
var xValue = getDy(batch, idyR, idyC, d2);
|
|
let tmpval = vec4<f32>(dot(xValue, wValue0),
|
|
dot(xValue, wValue1),
|
|
dot(xValue, wValue2),
|
|
dot(xValue, wValue3));
|
|
dotProd[0] = dotProd[0] + tmpval;
|
|
}
|
|
} else if (bDyCVal2) {
|
|
let d2Length = uniforms.outBackprop[3];
|
|
for (var d2 = 0; d2 < d2Length; d2 = d2 + 4) {
|
|
let wValue0 = getW(wRPerm, wCPerm, d1, d2);
|
|
let wValue1 = getW(wRPerm, wCPerm, d1 + 1, d2);
|
|
let wValue2 = getW(wRPerm, wCPerm, d1 + 2, d2);
|
|
let wValue3 = getW(wRPerm, wCPerm, d1 + 3, d2);
|
|
var xValue = getDy(batch, idyR, idyC2, d2);
|
|
let tmpval = vec4<f32>(dot(xValue, wValue0),
|
|
dot(xValue, wValue1),
|
|
dot(xValue, wValue2),
|
|
dot(xValue, wValue3));
|
|
dotProd[1] = dotProd[1] + tmpval;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
for (var i = 0; i < ${this.workPerThread}; i = i + 1) {
|
|
let coords = vec4<i32>(batch, r, c + i, d1);
|
|
if (coordsInBounds4D(coords, uniforms.outShape)) {
|
|
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], dotProd[i]);
|
|
}
|
|
}
|
|
}
|
|
`;return this.isVec4?`
|
|
${n}
|
|
`:`
|
|
${ue("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.strides.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.strides.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) {
|
|
let xValue = ${this.isChannelsLast?"getDy(batch, idyR, idyC, d2)":"getDy(batch, d2, idyR, idyC)"};
|
|
let wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
dotProd = dotProd + xValue * wValue;
|
|
}
|
|
}
|
|
}
|
|
setOutputAtIndex(index, dotProd);
|
|
}
|
|
}
|
|
`}},s0e=class{constructor(e){this.variableNames=["x","dy"],this.uniforms="pads : vec2<i32>, strides : vec2<i32>, batchSize : i32, outHeight : i32, outWidth : i32, inHeight : i32, inWidth : i32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.filterShape,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.isChannelsLast=e.dataFormat==="channelsLast",this.shaderKey=`conv2DDerFilter_${this.isChannelsLast}`}getUserCode(){return`
|
|
${ue("index")} {
|
|
if(index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let wR = coords[0];
|
|
let wC = coords[1];
|
|
let d1 = coords[2];
|
|
let d2 = coords[3];
|
|
|
|
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
var dotProd = 0.0;
|
|
for (var b = 0; b < uniforms.batchSize; b = b + 1) {
|
|
for (var yR = 0; yR < uniforms.outHeight; yR = yR + 1) {
|
|
let xR = wR + yR * uniforms.strides[0] - uniforms.pads[0];
|
|
if (xR < 0 || xR >= uniforms.inHeight) {
|
|
continue;
|
|
}
|
|
|
|
for (var yC = 0; yC < uniforms.outWidth; yC = yC + 1) {
|
|
let xC = wC + yC * uniforms.strides[1] - uniforms.pads[1];
|
|
|
|
if (xC < 0 || xC >= uniforms.inWidth) {
|
|
continue;
|
|
}
|
|
|
|
if (${this.isChannelsLast}) {
|
|
let dyValue = getDy(b, yR, yC, d2);
|
|
let xValue = getX(b, xR, xC, d1);
|
|
dotProd = dotProd + xValue * dyValue;
|
|
} else {
|
|
let dyValue = getDy(b, d2, yR, yC);
|
|
let xValue = getX(b, d1, xR, xC);
|
|
dotProd = dotProd + xValue * dyValue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutputAtIndex(index, dotProd);
|
|
}
|
|
}
|
|
`}},i0e=class{constructor(e){this.variableNames=["x","dy"],this.uniforms=`pads : vec3<i32>, strides : vec3<i32>, batchSize : i32, outDepth : i32,
|
|
outHeight : i32, outWidth : i32, inDepth : i32, inHeight : i32, inWidth : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.filterShape,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="conv3DDerFilter"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if(index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let wF = coords.x;
|
|
let wR = coords.y;
|
|
let wC = coords.z;
|
|
let d1 = coords.w;
|
|
let d2 = coords.u;
|
|
|
|
var dotProd = 0.0;
|
|
for (var b = 0; b < uniforms.batchSize; b++) {
|
|
for (var yF = 0; yF < uniforms.outDepth; yF++) {
|
|
let xF = wF + yF * uniforms.strides[0] - uniforms.pads[0];
|
|
if (xF < 0 || xF >= uniforms.inDepth) {
|
|
continue;
|
|
}
|
|
|
|
for (var yR = 0; yR < uniforms.outHeight; yR++) {
|
|
let xR = wR + yR * uniforms.strides[1] - uniforms.pads[1];
|
|
if (xR < 0 || xR >= uniforms.inHeight) {
|
|
continue;
|
|
}
|
|
|
|
for (var yC = 0; yC < uniforms.outWidth; yC++) {
|
|
let xC = wC + yC * uniforms.strides[2] - uniforms.pads[2];
|
|
if (xC < 0 || xC >= uniforms.inWidth) {
|
|
continue;
|
|
}
|
|
|
|
let dyValue = getDy(b, yF, yR, yC, d2);
|
|
let xValue = getX(b, xF, xR, xC, d1);
|
|
dotProd += xValue * dyValue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutputAtIndex(index, dotProd);
|
|
}
|
|
}
|
|
`}},o0e=class{constructor(e){this.variableNames=["dy","W"],this.uniforms=`filterDims : vec3<i32>, pads : vec3<i32>, strides : vec3<i32>,
|
|
outDepth : i32, outHeight : i32, outWidth : i32, outChannels : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="conv3DDerInput"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if(index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let batch = coords.x;
|
|
let d1 = coords.u;
|
|
|
|
let dyCorner = vec3<i32>(coords.y, coords.z, coords.w) - uniforms.pads;
|
|
let dyFCorner = dyCorner.x;
|
|
let dyRCorner = dyCorner.y;
|
|
let dyCCorner = dyCorner.z;
|
|
|
|
var dotProd = 0.0;
|
|
for (var wF = 0; wF < uniforms.filterDims[0]; wF++) {
|
|
let dyF = f32(dyFCorner + wF) / f32(uniforms.strides[0]);
|
|
if (dyF < 0.0 || dyF >= f32(uniforms.outDepth) || fract(dyF) > 0.0) {
|
|
continue;
|
|
}
|
|
let idyF = i32(dyF);
|
|
|
|
let wFPerm = uniforms.filterDims[0] - 1 - wF;
|
|
|
|
for (var wR = 0; wR < uniforms.filterDims[1]; wR++) {
|
|
let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[1]);
|
|
|
|
if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
let idyR = i32(dyR);
|
|
|
|
let wRPerm = uniforms.filterDims[1] - 1 - wR;
|
|
|
|
for (var wC = 0; wC < uniforms.filterDims[2]; wC++) {
|
|
let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[2]);
|
|
|
|
if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
let idyC = i32(dyC);
|
|
|
|
let wCPerm = uniforms.filterDims[2] - 1 - wC;
|
|
|
|
for (var d2 = 0; d2 < uniforms.outChannels; d2++) {
|
|
let xValue = getDy(batch, idyF, idyR, idyC, d2);
|
|
let wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutputAtIndex(index, dotProd);
|
|
}
|
|
}
|
|
`}};function l0e(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:d}=n,c=I.convertConv2DDataFormat(l),p=I.computeConv2DInfo(r.shape,d,i,1,o,u,!1,c),h=new s0e(p),m=[{type:"int32",data:[p.padInfo.top,p.padInfo.left]},{type:"int32",data:[p.strideHeight,p.strideWidth]},{type:"int32",data:[p.batchSize]},{type:"int32",data:[p.outHeight]},{type:"int32",data:[p.outWidth]},{type:"int32",data:[p.inHeight]},{type:"int32",data:[p.inWidth]}];return a.runWebGPUProgram(h,[r,s],r.dtype,m)}var u0e={kernelName:bp,backendName:"webgpu",kernelFunc:l0e};function d0e(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.strides[0]);
|
|
let xC = f32(outCol - uniforms.pads[1] + WCol) / f32(uniforms.strides[1]);
|
|
if (xR < 0.0 || xR >= f32(uniforms.outBackprop[1]) || fract(xR) > 0.0) {
|
|
return ${Xe(e)}(0.0);
|
|
}
|
|
if (xC < 0.0 || xC >= f32(uniforms.outBackprop[2]) || fract(xC) > 0.0) {
|
|
return ${Xe(e)}(0.0);
|
|
}
|
|
let coord = vec4<i32>(
|
|
batch,
|
|
i32(xR),
|
|
i32(xC),
|
|
col % uniforms.outBackprop[3]);
|
|
return x[getIndexFromCoords4D(coord, uniforms.xShape)/${e}];`}
|
|
}
|
|
return ${Xe(e)}(0.0);`;return`
|
|
fn mm_readA(batch: i32, row : i32, col : i32) -> ${Xe(e)} {
|
|
${a}
|
|
}
|
|
|
|
fn mm_readB(batch: i32, row : i32, col : i32) -> ${Xe(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 ${Xe(e)}(0.0);
|
|
}
|
|
|
|
fn mm_write(batch: i32, row : i32, col : i32, valueInput : ${Xe(e)}) {
|
|
if (row < uniforms.dimAOuter && col < 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 p0e=class{constructor(e){this.variableNames=["x","W"],this.uniforms="filterDims : vec2<i32>, pads : vec2<i32>, strides : 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=Q3(this.dispatchLayout,this.outputShape,this.isVec4),this.elementsPerThread=ey(this.dispatchLayout,this.outputShape,this.isVec4),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize,this.elementsPerThread),this.isVec4&&(this.outputComponent=4,this.variableComponents=[4,1]),this.shaderKey=`conv2DDerInputMM_${this.isVec4}_${this.elementsPerThread}`}getUserCode(){let e=this.isVec4?g0(this.elementsPerThread,this.workgroupSize):y0(this.elementsPerThread,this.workgroupSize);return`
|
|
${d0e(this.isVec4?4:1)}
|
|
${e}
|
|
`}};function c0e(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:d}=n,c=I.convertConv2DDataFormat(u),p=I.computeConv2DInfo(i,s.shape,o,1,l,d,!1,c),h=[{type:"int32",data:[p.filterHeight,p.filterWidth]},{type:"int32",data:[p.filterHeight-1-p.padInfo.top,p.filterWidth-1-p.padInfo.left]},{type:"int32",data:[p.strideHeight,p.strideWidth]},{type:"int32",data:[p.batchSize,p.outHeight,p.outWidth,p.outChannels]}],m;if(B().getBool("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE")||p.dataFormat!=="channelsLast")m=new r0e(p);else{m=new p0e(p);let f=p.inHeight*p.inWidth,g=p.inChannels,y=p.filterHeight*p.filterWidth*p.outChannels;h.push({type:"uint32",data:[f]},{type:"uint32",data:[g]},{type:"uint32",data:[y]})}return a.runWebGPUProgram(m,[r,s],"float32",h)}var h0e={kernelName:Ki,backendName:"webgpu",kernelFunc:c0e},m0e=class{constructor(e){this.variableNames=["x","W"],this.uniforms="filterDims: vec3<i32>, pads: vec3<i32>, strides: vec3<i32>, dilations: vec3<i32>,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="conv3dnaive"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getOutputCoords();
|
|
let batch = coords.x;
|
|
let d2 = coords.u;
|
|
|
|
let xFRCCorner = vec3<i32>(coords.y, coords.z, coords.w) * uniforms.strides - uniforms.pads;
|
|
let xFCorner = xFRCCorner.x;
|
|
let xRCorner = xFRCCorner.y;
|
|
let xCCorner = xFRCCorner.z;
|
|
|
|
let inputDepthNearestVec4 = (uniforms.xShape.u / 4) * 4;
|
|
let inputDepthVec4Remainder = uniforms.xShape.u % 4;
|
|
|
|
var dotProd = 0.0;
|
|
for (var wF = 0; wF < uniforms.filterDims[0]; wF++) {
|
|
let xF = xFCorner + wF * uniforms.dilations[0];
|
|
if (xF < 0 || xF >= uniforms.xShape.y) {
|
|
continue;
|
|
}
|
|
|
|
for (var wR = 0; wR < uniforms.filterDims[1]; wR++) {
|
|
let xR = xRCorner + wR * uniforms.dilations[1];
|
|
if (xR < 0 || xR >= uniforms.xShape.z) {
|
|
continue;
|
|
}
|
|
|
|
for (var wC = 0; wC < uniforms.filterDims[2]; wC++) {
|
|
let xC = xCCorner + wC * uniforms.dilations[2];
|
|
if (xC < 0 || xC >= uniforms.xShape.w) {
|
|
continue;
|
|
}
|
|
|
|
for (var d1 = 0; d1 < inputDepthNearestVec4; d1 += 4) {
|
|
let xValues = vec4<f32>(
|
|
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)
|
|
);
|
|
let wValues = vec4<f32>(
|
|
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 (inputDepthVec4Remainder == 1) {
|
|
dotProd += getX(batch, xF, xR, xC, inputDepthNearestVec4) *
|
|
getW(wF, wR, wC, inputDepthNearestVec4, d2);
|
|
} else if (inputDepthVec4Remainder == 2) {
|
|
let xValues = vec2<f32>(
|
|
getX(batch, xF, xR, xC, inputDepthNearestVec4),
|
|
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)
|
|
);
|
|
let wValues = vec2<f32>(
|
|
getW(wF, wR, wC, inputDepthNearestVec4, d2),
|
|
getW(wF, wR, wC, inputDepthNearestVec4 + 1, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else if (inputDepthVec4Remainder == 3) {
|
|
let xValues = vec3<f32>(
|
|
getX(batch, xF, xR, xC, inputDepthNearestVec4),
|
|
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1),
|
|
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)
|
|
);
|
|
let wValues = vec3<f32>(
|
|
getW(wF, wR, wC, inputDepthNearestVec4, d2),
|
|
getW(wF, wR, wC, inputDepthNearestVec4 + 1, d2),
|
|
getW(wF, wR, wC, inputDepthNearestVec4 + 2, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutputAtIndex(index, dotProd);
|
|
}
|
|
}`}};function f0e(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=n,u=I.computeConv3DInfo(r.shape,s.shape,i,l,o),d=[u.padInfo.front,u.padInfo.top,u.padInfo.left],c=[{type:"int32",data:[u.filterDepth,u.filterHeight,u.filterWidth]},{type:"int32",data:[...d]},{type:"int32",data:[u.strideDepth,u.strideHeight,u.strideWidth]},{type:"int32",data:[u.dilationDepth,u.dilationHeight,u.dilationWidth]}],p=new m0e(u),h=Qt(r.dtype,s.dtype);return a.runWebGPUProgram(p,[r,s],h,c)}var g0e={kernelName:Yi,backendName:"webgpu",kernelFunc:f0e};function y0e(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=n,u=I.computeConv3DInfo(r.shape,l,i,1,o),d=new i0e(u),c=[{type:"int32",data:[u.padInfo.front,u.padInfo.top,u.padInfo.left]},{type:"int32",data:[u.strideDepth,u.strideHeight,u.strideWidth]},{type:"int32",data:[u.batchSize]},{type:"int32",data:[u.outDepth]},{type:"int32",data:[u.outHeight]},{type:"int32",data:[u.outWidth]},{type:"int32",data:[u.inDepth]},{type:"int32",data:[u.inHeight]},{type:"int32",data:[u.inWidth]}];return a.runWebGPUProgram(d,[r,s],s.dtype,c)}var x0e={kernelName:Au,backendName:"webgpu",kernelFunc:y0e};function A0e(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,filter:s}=t,{strides:i,pad:o,inputShape:l}=n,u=I.computeConv3DInfo(l,s.shape,i,1,o),d=new o0e(u),c=[{type:"int32",data:[u.filterDepth,u.filterHeight,u.filterWidth]},{type:"int32",data:[u.filterDepth-1-u.padInfo.front,u.filterHeight-1-u.padInfo.top,u.filterWidth-1-u.padInfo.left]},{type:"int32",data:[u.strideDepth,u.strideHeight,u.strideWidth]},{type:"int32",data:[u.outDepth]},{type:"int32",data:[u.outHeight]},{type:"int32",data:[u.outWidth]},{type:"int32",data:[u.outChannels]}];return a.runWebGPUProgram(d,[r,s],r.dtype,c)}var b0e={kernelName:Zi,backendName:"webgpu",kernelFunc:A0e},v0e=at({opType:le.COS}),w0e={kernelName:Ji,backendName:"webgpu",kernelFunc:v0e},k0e=at({opType:le.COSH}),I0e={kernelName:Qi,backendName:"webgpu",kernelFunc:k0e},S0e=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=me(this.outputShape),this.dispatch=de(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`
|
|
${ue("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);
|
|
}
|
|
}
|
|
}
|
|
`}},T0e=e=>{let{inputs:t,backend:a,attrs:n}=e,{image:r,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=n,d=new S0e(r.shape[3],s.shape,o,l),c=[{type:"float32",data:[u]}];return a.runWebGPUProgram(d,[r,s,i],"float32",c)},C0e={kernelName:ao,backendName:"webgpu",kernelFunc:T0e},cp;(function(e){e.Prod="*",e.Sum="+"})(cp||(cp={}));var IA=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=me(this.outputShape),this.dispatch=de(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===cp.Prod?"1.0":"0.0",a=this.exclusive?t:`getX(${SA(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"),`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
var coords = getCoordsFromIndex(index);
|
|
|
|
let end = ${TA(e,"coords",this.op)};
|
|
var val = ${a};
|
|
let pow2 = i32(pow(2.0, uniforms.index));
|
|
if (${r}) {
|
|
let idx = ${s};
|
|
${TA(e,"coords",this.op)} = idx;
|
|
val ${this.op}= getX(${SA(e,"coords",this.op)});
|
|
}
|
|
setOutputAtIndex(index, val);
|
|
}
|
|
}
|
|
`}};function SA(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 TA(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 C9(e,t,a,n,r,s){let i=t.shape.length,o=I.getAxesPermutation([n],i),l=t;o!=null&&(l=ir({inputs:{x:t},backend:a,attrs:{perm:o}}));let u=I.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 d=l.shape[u],c=an({inputs:{x:l},backend:a});for(let p=0;p<=Math.ceil(Math.log2(d))-1;p++){let h=new IA(e,l.shape,!1,s),m=c,f=[{type:"float32",data:[p]}];c=a.runWebGPUProgram(h,[c],c.dtype,f),a.disposeData(m.dataId)}if(r){let p=new IA(e,l.shape,r,s),h=c,m=[{type:"float32",data:[0]}];c=a.runWebGPUProgram(p,[c],c.dtype,m),a.disposeData(h.dataId)}if(o!=null){let p=I.getUndoAxesPermutation(o),h=ir({inputs:{x:c},backend:a,attrs:{perm:p}});return a.disposeData(c.dataId),a.disposeData(l.dataId),h}return c}function N0e(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=n;return C9(cp.Prod,r,a,s,i,o)}var R0e={kernelName:eo,backendName:"webgpu",kernelFunc:N0e};function E0e(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=n;return C9(cp.Sum,r,a,s,i,o)}var M0e={kernelName:to,backendName:"webgpu",kernelFunc:E0e};function F0e(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,d=s.dtype,c=l?[r.shape[0]]:[r.shape[0],r.shape[1]],p=l?[i]:[r.shape[0],i],h=Wa({backend:a,attrs:{shape:p,value:0,dtype:d}}),m=new k9(c,u,o),f=[{type:"int32",data:[i]}],g=u?[r,s]:[r];return a.runWebGPUProgram(m,g,d,f,h)}var $0e={kernelName:bu,backendName:"webgpu",kernelFunc:F0e},D0e=class{constructor(e,t){this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.uniforms="blockSize : i32,",this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey=`depthToSpace_${t}`,this.dataFormat=t}getUserCode(){return`
|
|
${ue("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 P0e(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],d=i==="NHWC"?r.shape[3]:r.shape[1],c=l*s,p=u*s,h=d/(s*s),m=i==="NHWC"?[o,c,p,h]:[o,h,c,p],f=[{type:"int32",data:[s]}],g=new D0e(m,i);return a.runWebGPUProgram(g,[r],r.dtype,f)}var _0e={kernelName:no,backendName:"webgpu",kernelFunc:P0e},O0e=class{constructor(e,t,a,n=!1,r=null,s=!1){this.variableNames=["x","W"],this.uniforms="pads : vec2<i32>, inDims : vec2<i32>,",this.workgroupSize=[16,16,1],this.outputShape=e,this.dispatchLayout={x:[3],y:[2],z:[0,1]},this.dispatch=de(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`
|
|
${Or(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;
|
|
}
|
|
|
|
${ue()} {
|
|
let coords = getOutputCoords();
|
|
let batch = coords[0];
|
|
let xRCCorner = vec2<i32>(coords.zw) - uniforms.pads;
|
|
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);
|
|
}
|
|
}
|
|
${ml(this.addBias,this.activation)}
|
|
if (coordsInBounds4D(coords, uniforms.outShape)) {
|
|
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
|
|
}
|
|
}
|
|
`}},N9=class{constructor(e,t=!1,a=null,n=!1){this.variableNames=["x","W"],this.uniforms="pads : vec2<i32>, inDims : vec2<i32>, virtualWidth : i32,",this.workgroupSize=[64,1,1],this.workPerThread=4,this.outputComponent=4,this.outputShape=e.outShape,this.virtualWidth=Math.ceil(this.outputShape[2]/this.workPerThread)*this.workPerThread;let r=[this.outputShape[0],this.outputShape[1],this.virtualWidth,this.outputShape[3]];this.dispatchLayout=me(r),this.dispatch=de(this.dispatchLayout,r,this.workgroupSize,[this.outputComponent*this.workPerThread,1,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,t=this.convInfo.strideHeight,a=this.convInfo.strideWidth;return`
|
|
${Or(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;
|
|
}
|
|
|
|
${ue("index")} {
|
|
let width0 = uniforms.outShape[3] / ${this.outputComponent};
|
|
let d1 = (index % width0) * ${this.outputComponent};
|
|
var index1 = index / width0;
|
|
let width1 = uniforms.virtualWidth / ${this.workPerThread};
|
|
let c = (index1 % width1) * ${this.workPerThread};
|
|
index1 = index1 / width1;
|
|
let r = index1 % uniforms.outShape[1];
|
|
let batch = index1 / uniforms.outShape[1];
|
|
|
|
let xRCCorner = vec2<i32>(r, c) * vec2<i32>(${t}, ${a}) - uniforms.pads;
|
|
|
|
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 * ${a} + 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];
|
|
${ml(this.addBias,this.activation)}
|
|
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
|
|
}
|
|
}
|
|
}
|
|
`}},R9=class{constructor(e,t=!1,a=null,n=!1){this.variableNames=["x","W"],this.uniforms=`pads : vec2<i32>, inDims : vec2<i32>, filterHeight : i32,
|
|
filterWidth : i32, strides : vec2<i32>, dilations : vec2<i32>,`,this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=me(this.outputShape),this.dispatch=de(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`
|
|
${Or(this.activation,this.hasPreluActivation,!1,4)}
|
|
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getOutputCoords();
|
|
let batch = coords[0];
|
|
let xRCCorner = vec2<i32>(coords.${this.isChannelsLast?"yz":"zw"}) * uniforms.strides - uniforms.pads;
|
|
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.dilations[0];
|
|
let inputColEnd = inputColStart + uniforms.filterWidth *
|
|
uniforms.dilations[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.dilations[0];
|
|
|
|
for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) {
|
|
let xC = inputColStart + wC * uniforms.dilations[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.dilations[0];
|
|
|
|
if (xR < 0 || xR >= uniforms.inDims[0]) {
|
|
continue;
|
|
}
|
|
|
|
for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) {
|
|
let xC = inputColStart + wC * uniforms.dilations[1];
|
|
|
|
if (xC < 0 || xC >= uniforms.inDims[1]) {
|
|
continue;
|
|
}
|
|
|
|
let xVal = ${e};
|
|
let wVal = getW(wR, wC, d1, q);
|
|
value = value + xVal * wVal;
|
|
}
|
|
}
|
|
}
|
|
${ml(this.addBias,this.activation)}
|
|
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
|
|
}
|
|
}
|
|
`}};function z0e(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:d}=n,c=I.convertConv2DDataFormat(l),p=u;p==null&&(p=[1,1]);let h=I.computeConv2DInfo(r.shape,s.shape,i,p,o,d,!0,c),m=[{type:"int32",data:[h.padInfo.top,h.padInfo.left]},{type:"int32",data:[h.inHeight,h.inWidth]}],f=h.dataFormat==="channelsLast",g;return!f&&h.inHeight>16&&h.inWidth>16&&h.strideHeight===1&&h.strideWidth===1&&h.dilationWidth===1&&h.dilationHeight===1&&h.inChannels===h.outChannels?g=new O0e(h.outShape,h.filterHeight,h.filterWidth):f&&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 N9(h),m.push({type:"int32",data:[g.virtualWidth]})):(g=new R9(h),m.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,m)}var L0e={kernelName:ro,backendName:"webgpu",kernelFunc:z0e},W0e=class{constructor(e){this.variableNames=["x","dy"],this.uniforms=`strides : vec2<i32>, pads : vec2<i32>, filterDims : vec2<i32>, outHeight : i32,
|
|
outWidth : i32, inHeight : i32, inWidth : i32, batchSize : i32, channelMul : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.filterShape,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="depthwise_conv2d_backprop_filter"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let wR = coords[0];
|
|
let wC = coords[1];
|
|
let d1 = coords[2];
|
|
let dm = coords[3];
|
|
let d2 = d1 * uniforms.channelMul + dm;
|
|
|
|
var dotProd = 0.0;
|
|
for (var b = 0; b < uniforms.batchSize; b++) {
|
|
for (var yR = 0; yR < uniforms.outHeight; yR++) {
|
|
let xR = wR + yR * uniforms.strides[0] - uniforms.pads[0];
|
|
|
|
if (xR < 0 || xR >= uniforms.inHeight) {
|
|
continue;
|
|
}
|
|
|
|
for (var yC = 0; yC < uniforms.outWidth; yC++) {
|
|
let xC = wC + yC * uniforms.strides[1] - uniforms.pads[1];
|
|
|
|
if (xC < 0 || xC >= uniforms.inWidth) {
|
|
continue;
|
|
}
|
|
|
|
let dyValue = getDy(b, yR, yC, d2);
|
|
let xValue = getX(b, xR, xC, d1);
|
|
dotProd += xValue * dyValue;
|
|
}
|
|
}
|
|
}
|
|
setOutputAtIndex(index, dotProd);
|
|
}
|
|
}
|
|
`}},B0e=class{constructor(e){this.variableNames=["dy","W"],this.uniforms=`strides : vec2<i32>, pads : vec2<i32>, filterDims : vec2<i32>,
|
|
outHeight : i32, outWidth : i32, channelMul : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="depthwise_conv2d_backprop_input"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let batch = coords[0];
|
|
let d1 = coords[3];
|
|
let dyCorner = coords.yz - uniforms.pads;
|
|
let dyRCorner = dyCorner.x;
|
|
let dyCCorner = dyCorner.y;
|
|
|
|
var dotProd = 0.0;
|
|
for (var wR = 0; wR < uniforms.filterDims[0]; wR++) {
|
|
let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[0]);
|
|
|
|
if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
|
|
let idyR = i32(dyR);
|
|
let wRPerm = uniforms.filterDims[0] - 1 - wR;
|
|
|
|
for (var wC = 0; wC < uniforms.filterDims[1]; wC++) {
|
|
let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[1]);
|
|
|
|
if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
|
|
let idyC = i32(dyC);
|
|
let wCPerm = uniforms.filterDims[1] - 1 - wC;
|
|
|
|
for (var dm = 0; dm < uniforms.channelMul; dm++) {
|
|
let d2 = d1 * uniforms.channelMul + dm;
|
|
let xValue = getDy(batch, idyR, idyC, d2);
|
|
let wValue = getW(wRPerm, wCPerm, d1, dm);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
}
|
|
}
|
|
setOutputAtIndex(index, dotProd);
|
|
}
|
|
}
|
|
`}};function V0e(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:d}=n,c=I.computeConv2DInfo(r.shape,d,i,o,l,u,!0),p=new W0e(c),h=[{type:"int32",data:[c.strideHeight,c.strideWidth]},{type:"int32",data:[c.padInfo.top,c.padInfo.left]},{type:"int32",data:[c.filterHeight,c.filterWidth]},{type:"int32",data:[c.outHeight]},{type:"int32",data:[c.outWidth]},{type:"int32",data:[c.inHeight]},{type:"int32",data:[c.inWidth]},{type:"int32",data:[c.batchSize]},{type:"int32",data:[c.outChannels/c.inChannels]}];return a.runWebGPUProgram(p,[r,s],"float32",h)}var U0e={kernelName:vp,backendName:"webgpu",kernelFunc:V0e};function G0e(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:d}=n,c=I.computeConv2DInfo(d,s.shape,i,o,l,u,!0),p=new B0e(c),h=[{type:"int32",data:[c.strideHeight,c.strideWidth]},{type:"int32",data:[c.filterHeight-1-c.padInfo.top,c.filterWidth-1-c.padInfo.left]},{type:"int32",data:[c.filterHeight,c.filterWidth]},{type:"int32",data:[c.outHeight]},{type:"int32",data:[c.outWidth]},{type:"int32",data:[c.outChannels/c.inChannels]}];return a.runWebGPUProgram(p,[r,s],r.dtype,h)}var H0e={kernelName:wp,backendName:"webgpu",kernelFunc:G0e},j0e=class{constructor(e){this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e,e],this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="diag"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getOutputCoords();
|
|
let value = select(0.0, getX(coords[0]), coords[0] == coords[1]);
|
|
setOutputAtIndex(index, value);
|
|
}
|
|
}
|
|
`}};function q0e(e){let{inputs:t,backend:a}=e,{x:n}=t,r=[...n.shape,...n.shape],s=v.sizeFromShape(n.shape),i=ke({inputs:{x:n},backend:a,attrs:{shape:[s]}}),o=new j0e(s),l=a.runWebGPUProgram(o,[i],i.dtype),u=ke({inputs:{x:l},backend:a,attrs:{shape:r}});return a.disposeData(i.dataId),a.disposeData(l.dataId),u}var X0e={kernelName:vu,backendName:"webgpu",kernelFunc:q0e},K0e=class{constructor(e){this.variableNames=["x","w"],this.uniforms="filterDims: vec2<i32>, pads: vec2<i32>, strides: vec2<i32>, dilations: vec2<i32>",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="dilation2d"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let neg_infinity = -3.4e38;
|
|
let coords = getOutputCoords();
|
|
let batch = coords.x;
|
|
let d1 = coords.w;
|
|
let outTopLeftCorner = coords.yz * uniforms.strides - uniforms.pads;
|
|
let hBeg = outTopLeftCorner.x;
|
|
let wBeg = outTopLeftCorner.y;
|
|
|
|
var curVal = neg_infinity;
|
|
for (var h = 0; h < uniforms.filterDims[0]; h = h + 1) {
|
|
let hIn = hBeg + h * uniforms.dilations[0];
|
|
|
|
if (hIn >= 0 && hIn < uniforms.xShape[1]) {
|
|
for (var w = 0; w < uniforms.filterDims[1]; w = w + 1) {
|
|
let wIn = wBeg + w * uniforms.dilations[1];
|
|
|
|
if (wIn >= 0 && wIn < uniforms.xShape[2]) {
|
|
let val = getX(batch, hIn, wIn, d1) + getW(h, w, d1);
|
|
if (val > curVal) {
|
|
curVal = val;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
setOutputAtIndex(index, curVal);
|
|
}
|
|
}
|
|
`}};function Y0e(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=n,u=I.computeDilation2DInfo(r.shape,s.shape,i,o,"NHWC",l),d=[u.padInfo.top,u.padInfo.left],c=[{type:"int32",data:[u.filterHeight,u.filterWidth]},{type:"int32",data:[...d]},{type:"int32",data:[u.strideHeight,u.strideWidth]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]}],p=new K0e(u);return a.runWebGPUProgram(p,[r,s],r.dtype,c)}var Z0e={kernelName:so,backendName:"webgpu",kernelFunc:Y0e},J0e=class{constructor(e,t){if(this.variableNames=["x","w","dy"],this.uniforms="filterDims: vec2<i32>, pads: vec2<i32>, strides: vec2<i32>, dilations: vec2<i32>, dySize: i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=e.inShape,this.dispatchLayout=me(e.outShape),this.dispatch=de(this.dispatchLayout,e.outShape,this.workgroupSize),t!=="float32"&&t!=="int32")throw new Error(`Dilation2DBackpropInput only supports float32 and int32
|
|
types, does not support ${t} type.`);this.type=t,this.shaderKey="dilation2DBackpropInput"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.dySize) {
|
|
let coords = getDyCoordsFromIndex(index);
|
|
let b = coords[0];
|
|
let r = coords[1];
|
|
let c = coords[2];
|
|
let d = coords[3];
|
|
|
|
let dyCorner = vec2<i32>(r, c) * uniforms.strides - uniforms.pads;
|
|
var curVal = -3.4e38; // neg_infinity
|
|
var xRMax = 0;
|
|
var xCMax = 0;
|
|
|
|
// In the case of multiple argmax branches, we only back-propagate
|
|
// along the last branch, i.e., the one with largest value of
|
|
// 'wR * uniforms.filterDims[1] + wC', similarly to the max-pooling
|
|
// backward routines.
|
|
for (var wR = 0; wR < uniforms.filterDims[0]; wR++) {
|
|
let xR = dyCorner.x + wR * uniforms.dilations[0];
|
|
|
|
if (xR >= 0 && xR < uniforms.xShape[1]) {
|
|
for (var wC = 0; wC < uniforms.filterDims[1]; wC++) {
|
|
let xC = dyCorner.y + wC * uniforms.dilations[1];
|
|
|
|
if (xC >= 0 && xC < uniforms.xShape[2]) {
|
|
let val = getX(b, xR, xC, d) + getW(wR, wC, d);
|
|
if (val > curVal) {
|
|
curVal = val;
|
|
xRMax = xR;
|
|
xCMax = xC;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
let flatIndexIn = d + uniforms.xShape[3] *
|
|
(xCMax + uniforms.xShape[2] * (xRMax + uniforms.xShape[1] * b));
|
|
let value = getDy(b, r, c, d);
|
|
${Bs("&result[flatIndexIn]","value",this.type)}
|
|
}
|
|
}
|
|
`}},Q0e=class{constructor(e,t,a){if(this.variableNames=["x","w","dy"],this.uniforms="filterDims: vec2<i32>, pads: vec2<i32>, strides: vec2<i32>, dilations: vec2<i32>, dySize: i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=e.filterShape,this.dispatchLayout=me(e.outShape),this.dispatch=de(this.dispatchLayout,e.outShape,this.workgroupSize),a!=="float32"&&a!=="int32")throw new Error(`Dilation2DBackpropFilter only supports float32 and int32
|
|
types, does not support ${a} type.`);this.type=a,this.shaderKey="dilation2DBackpropFilter"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.dySize) {
|
|
let coords = getDyCoordsFromIndex(index);
|
|
let b = coords[0];
|
|
let r = coords[1];
|
|
let c = coords[2];
|
|
let d = coords[3];
|
|
|
|
let dyCorner = vec2<i32>(r, c) * uniforms.strides - uniforms.pads;
|
|
var curVal = -3.4e38; // neg_infinity
|
|
var wRMax = 0;
|
|
var wCMax = 0;
|
|
|
|
// In the case of multiple argmax branches, we only back-propagate
|
|
// along the last branch, i.e., the one with largest value of
|
|
// 'wR * uniforms.filterDims[1] + wC', similarly to the max-pooling
|
|
// backward routines.
|
|
for (var wR = 0; wR < uniforms.filterDims[0]; wR++) {
|
|
let xR = dyCorner.x + wR * uniforms.dilations[0];
|
|
|
|
if (xR >= 0 && xR < uniforms.xShape[1]) {
|
|
for (var wC = 0; wC < uniforms.filterDims[1]; wC++) {
|
|
let xC = dyCorner.y + wC * uniforms.dilations[1];
|
|
|
|
if (xC >= 0 && xC < uniforms.xShape[2]) {
|
|
let val = getX(b, xR, xC, d) + getW(wR, wC, d);
|
|
if (val > curVal) {
|
|
curVal = val;
|
|
wRMax = wR;
|
|
wCMax = wC;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
let flatIndexIn = d + uniforms.wShape[2] * (wCMax + wRMax * uniforms.wShape[1]);
|
|
let value = getDy(b, r, c, d);
|
|
${Bs("&result[flatIndexIn]","value",this.type)}
|
|
}
|
|
}
|
|
`}};function eme(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s,dy:i}=t,{strides:o,pad:l,dilations:u}=n,d=I.computeDilation2DInfo(r.shape,s.shape,o,l,"NHWC",u),c=s.dtype,p=new Q0e(d,s.shape,c),h=[{type:"int32",data:[d.filterHeight,d.filterWidth]},{type:"int32",data:[d.padInfo.top,d.padInfo.left]},{type:"int32",data:[d.strideHeight,d.strideWidth]},{type:"int32",data:[d.dilationHeight,d.dilationWidth]},{type:"int32",data:[v.sizeFromShape(d.outShape)]}],m=Wa({backend:a,attrs:{shape:s.shape,value:0,dtype:c}});return a.runWebGPUProgram(p,[r,s,i],c,h,m)}var tme={kernelName:Ql,backendName:"webgpu",kernelFunc:eme};function ame(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s,dy:i}=t,{strides:o,pad:l,dilations:u}=n,d=I.computeDilation2DInfo(r.shape,s.shape,o,l,"NHWC",u),c=r.dtype,p=new J0e(d,c),h=[{type:"int32",data:[d.filterHeight,d.filterWidth]},{type:"int32",data:[d.padInfo.top,d.padInfo.left]},{type:"int32",data:[d.strideHeight,d.strideWidth]},{type:"int32",data:[d.dilationHeight,d.dilationWidth]},{type:"int32",data:[v.sizeFromShape(d.outShape)]}],m=Wa({backend:a,attrs:{shape:d.inShape,value:0,dtype:c}});return a.runWebGPUProgram(p,[r,s,i],c,h,m)}var nme={kernelName:Jl,backendName:"webgpu",kernelFunc:ame},rme=class{constructor(e,t,a){this.variableNames=["Image"],this.uniforms="alpha: f32,",this.workgroupSize=[64,1,1],this.pixelsOpType=lu.DRAW,this.size=!0,this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.type=t,this.textureFormat=a,this.shaderKey=`draw_${t}_${a}`}getUserCode(){let e,t=this.type==="float32"?"value":"value / 255.0";return e=`
|
|
if (uniforms.numChannels == 1) {
|
|
rgba[0] = ${t};
|
|
rgba[1] = ${t};
|
|
rgba[2] = ${t};
|
|
} else {
|
|
rgba[d] = ${t};
|
|
}`,`
|
|
@group(0) @binding(0) var outImage : texture_storage_2d<${this.textureFormat}, write>;
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
var rgba = vec4<f32>(0.0, 0.0, 0.0, uniforms.alpha);
|
|
for (var d = 0; d < uniforms.numChannels; d = d + 1) {
|
|
let value = f32(inBuf[index * uniforms.numChannels + d]);
|
|
${e}
|
|
}
|
|
rgba.x = rgba.x * rgba.w;
|
|
rgba.y = rgba.y * rgba.w;
|
|
rgba.z = rgba.z * rgba.w;
|
|
let coords = getCoordsFromIndex(index);
|
|
textureStore(outImage, vec2<i32>(coords.yx), rgba);
|
|
}
|
|
}
|
|
`}};function sme(e){let{inputs:t,backend:a,attrs:n}=e,{image:r}=t,{canvas:s,options:i}=n,[o,l]=r.shape.slice(0,2),{imageOptions:u}=i||{},d=(u==null?void 0:u.alpha)||1,c=a.device.features.has("bgra8unorm-storage")?"bgra8unorm":"rgba8unorm",p=[o,l],h=new rme(p,r.dtype,c);s.width=l,s.height=o;let m="webgpu",f=s.getContext(m),g;f||(g=new OffscreenCanvas(l,o),f=g.getContext(m));let y=r.shape.length===3?r.shape[2]:1;f.configure({device:a.device,format:c,usage:GPUTextureUsage.STORAGE_BINDING,alphaMode:"premultiplied"});let x="int32",A=a.makeTensorInfo(p,x),b=a.tensorMap.get(A.dataId);b.resource=f.getCurrentTexture(),b.external=!0;let w=[{type:"uint32",data:[y]},{type:"float32",data:[d]}];if(a.runWebGPUProgram(h,[r],x,w,A),g){let S=s.getContext("2d");if(!S)throw new Error("Please make sure this canvas has only been used for 2d or webgpu context!");S.drawImage(g,0,0)}return a.disposeData(A.dataId),r}var ime={kernelName:kp,backendName:"webgpu",kernelFunc:sme},E9=aa({opType:De.MUL,cpuKernelImpl:pce,supportsComplex:!0}),ome={kernelName:Ts,backendName:"webgpu",kernelFunc:E9};function M9(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;return gl(r,s,i,"sum",a)}var lme={kernelName:Qo,backendName:"webgpu",kernelFunc:M9};function ume(e){let{inputs:t,backend:a,attrs:n}=e,{equation:r}=n,s=t,{allDims:i,summedDims:o,idDims:l}=I.decodeEinsumEquation(r,s.length);I.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:d}=I.getEinsumComputePath(o,l),c=d.length,p=null,h=i.length,m=[];for(let f=0;f<c;++f){for(let g of d[f]){let{permutationIndices:y,expandDims:x}=I.getEinsumPermutation(h,l[g]),A;I.isIdentityPermutation(y)?A=s[g]:(A=ir({inputs:{x:s[g]},backend:a,attrs:{perm:y}}),m.push(A));let b=A.shape.slice();for(let w=0;w<x.length;++w)b.splice(x[w],0,1);v.arraysEqual(A.shape,b)||(A=ke({inputs:{x:A},backend:a,attrs:{shape:b}}),m.push(A)),p===null?p=A:(p=E9({inputs:{a:A,b:p},backend:a}),m.push(p))}f<c-1&&(u[f]>=0&&(p=M9({inputs:{x:p},backend:a,attrs:{axis:u[f]-(i.length-h),keepDims:!1}}),m.push(p)),h--)}for(let f of m)f!==p&&a.disposeData(f.dataId);return p}var dme={kernelName:Ip,backendName:"webgpu",kernelFunc:ume},pme=at({opType:le.ELU}),cme={kernelName:oo,backendName:"webgpu",kernelFunc:pme},hme=e=>{let{inputs:t,backend:a}=e,{dy:n,y:r}=t,s=new $h(De.ELU_DER,n.shape,r.shape);return a.runWebGPUProgram(s,[n,r],n.dtype)},mme={kernelName:wu,backendName:"webgpu",kernelFunc:hme},fme=aa({opType:De.EQUAL,dtype:"bool",cpuKernelImpl:Ype}),gme={kernelName:ms,backendName:"webgpu",kernelFunc:fme},yme=at({opType:le.ERF}),xme={kernelName:lo,backendName:"webgpu",kernelFunc:yme},Ame=at({opType:le.EXP,cpuKernelImpl:Zpe,dtype:"float32"}),bme={kernelName:fs,backendName:"webgpu",kernelFunc:Ame};function rg(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),ke({inputs:{x:s},backend:n,attrs:{shape:o}})}var vme={kernelName:ku,backendName:"webgpu",kernelFunc:rg},wme=at({opType:le.EXPM1,cpuKernelImpl:Jpe}),kme={kernelName:gs,backendName:"webgpu",kernelFunc:wme},CA=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=me(this.outputShape),this.dispatch=de(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;
|
|
}
|
|
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getOutputCoords();
|
|
setOutputAtIndex(index, mulMatDFT(coords[0], coords[1]));
|
|
}
|
|
}
|
|
`}};function F9(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=ke({inputs:{x:e},backend:a,attrs:{shape:[i,s]}});o.push(l);let u=l.shape,d=new CA("real",u),c=new CA("imag",u),p=[{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,m=t?u[1]:1,f=[{type:"float32",data:[h]},{type:"float32",data:[m]}],g=a.runWebGPUProgram(d,p,"float32",f);o.push(g);let y=a.runWebGPUProgram(c,p,"float32",f);o.push(y);let x=fl({inputs:{real:g,imag:y},backend:a});o.push(x);let A=ke({inputs:{x},backend:a,attrs:{shape:e.shape}});return o.forEach(b=>a.disposeData(b.dataId)),A}function Ime(e){let{inputs:t,backend:a}=e,{input:n}=t;return F9(n,!1,a)}var Sme={kernelName:Sp,backendName:"webgpu",kernelFunc:Ime},Tme=class{constructor(e){this.outputShape=[],this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="flipLeftRight"}getUserCode(){return`
|
|
${ue("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);
|
|
}
|
|
}
|
|
`}},Cme={kernelName:uo,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{image:a}=e,n=t,r=new Tme(a.shape);return n.runWebGPUProgram(r,[a],a.dtype)}},Nme=at({opType:le.FLOOR,cpuKernelImpl:Qpe}),Rme={kernelName:ys,backendName:"webgpu",kernelFunc:Nme},Eme=aa({opType:De.FLOOR_DIV,cpuKernelImpl:ece,dtype:"int32"}),Mme={kernelName:xs,backendName:"webgpu",kernelFunc:Eme},Fme=class{constructor(e,t,a=!1){this.pixelsOpType=lu.FROM_PIXELS,this.outputShape=[0],this.variableNames=[],this.workgroupSize=[256,1,1],this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(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>"};
|
|
${ue("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]));
|
|
}
|
|
}
|
|
}
|
|
`}},$me={kernelName:jd,backendName:"webgpu",kernelFunc:Dme},Vl,i1=B().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function Dme(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,[d,c]=i?[r.videoWidth,r.videoHeight]:[r.width,r.height],p=[c,d,s],h=B().getBool("WEBGPU_IMPORT_EXTERNAL_TEXTURE")&&i,m=i||o;if(u||l||m){let x;if(h)x=a.device.importExternalTexture({source:r});else{if(m){let T=B().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(Vl==null||T!==i1)&&(i1=T,Vl=document.createElement("canvas").getContext("2d",{willReadFrequently:i1})),Vl.canvas.width=d,Vl.canvas.height=c,Vl.drawImage(r,0,0,d,c),r=Vl.canvas}let F=GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,E=a.textureManager.acquireTexture(p[1],p[0],"rgba8unorm",F);a.queue.copyExternalImageToTexture({source:r},{texture:E},[p[1],p[0]]),x=E}let A=v.sizeFromShape(p),b=v.computeStrides(p),w=new Fme(p,s,h),S=[{type:"uint32",data:[A]},{type:"uint32",data:[s]},{type:"uint32",data:[...b]}],C=a.makeTensorInfo([c,d],"int32"),N=a.tensorMap.get(C.dataId);N.resource=x;let M=a.runWebGPUProgram(w,[C],"int32",S);return a.disposeData(C.dataId),M}let f=r.data,g=f;if(s!=null&&s!==4){g=new Uint8Array(r.width*r.height*s);let x=f.length,A=0;for(let b=0;b<x;b++)b%4<s&&(g[A++]=f[b])}let y=a.makeTensorInfo(p,"int32",new Int32Array(g));return a.uploadToGPU(y.dataId),y}var Pme=class{constructor(e,t,a,n,r){this.uniforms="varianceEpsilon : f32,",this.workgroupSize=[128,1,1],this.size=!0,this.variableNames=["x","mean","variance"],I.assertAndGetBroadcastShape(e,t),I.assertAndGetBroadcastShape(e,a),this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),n!=null&&(I.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset")),r!=null&&(I.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)"),`
|
|
${ue("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)));
|
|
}
|
|
}
|
|
`}},_me={kernelName:po,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,d=[n,i,o],c=null;s!=null&&(c=s.shape,d.push(s));let p=null;r!=null&&(p=r.shape,d.push(r));let h=new Pme(n.shape,i.shape,o.shape,c,p),m=[{type:"float32",data:[l]}];return u.runWebGPUProgram(h,d,n.dtype,m)}};function Ome(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:d,dilations:c,dimRoundingMode:p,activation:h,leakyreluAlpha:m}=n,f=I.convertConv2DDataFormat(d),g=I.computeConv2DInfo(r.shape,s.shape,l,c,u,p,!1,f);return T9({x:r,filter:s,convInfo:g,backend:a,bias:i,preluActivationWeights:o,leakyreluAlpha:m,activation:h})}var zme={kernelName:as,backendName:"webgpu",kernelFunc:Ome};function Lme(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:d,dimRoundingMode:c,activation:p,leakyreluAlpha:h}=n,m=d;m==null&&(m=[1,1]),v.assert(I.eitherStridesOrDilationsAreOne(l,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`);let f=I.computeConv2DInfo(r.shape,s.shape,l,m,u,c,!0),g=[r,s],y=i!=null,x=o!=null;y&&g.push(i),x&&g.push(o);let A=[{type:"int32",data:[f.padInfo.top,f.padInfo.left]},{type:"int32",data:[f.inHeight,f.inWidth]}],b;return f.outHeight>4&&f.outWidth>4&&f.strideWidth<=2&&f.inChannels===f.outChannels&&f.dilationHeight===1&&f.dilationWidth===1&&f.inChannels%4===0?(b=new N9(f,y,p,x),A.push({type:"int32",data:[b.virtualWidth]})):(b=new R9(f,y,p,x),A.push({type:"int32",data:[f.filterHeight]},{type:"int32",data:[f.filterWidth]},{type:"int32",data:[f.strideHeight,f.strideWidth]},{type:"int32",data:[f.dilationHeight,f.dilationWidth]})),p==="leakyrelu"&&(A.push({type:"float32",data:[h]}),b.uniforms+=" alpha : f32,"),a.runWebGPUProgram(b,g,"float32",A)}var Wme={kernelName:ns,backendName:"webgpu",kernelFunc:Lme},Bme=class{constructor(e,t){this.variableNames=["A","indices"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey=`gathernd_${e}`,this.sliceDim=e,this.uniforms=`sliceDim : i32, strides : ${Dt(e)},`}getUserCode(){let e;return this.sliceDim>1?e="uniforms.strides[j]":e="uniforms.strides",`
|
|
${ue("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 Vme(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,d,c]=I.prepareAndValidate(n,r),p=ke({inputs:{x:r},backend:a,attrs:{shape:[u,i]}}),h=ke({inputs:{x:n},backend:a,attrs:{shape:[v.sizeFromShape(n.shape)/d,d]}});if(a.shouldExecuteOnCPU([n,r])||n.dtype==="string"){let x=a.readSync(r.dataId),A=a.bufferSync(n),b=tce(x,A,n.dtype,u,i,d,c,n.shape,o);return a.makeTensorInfo(l,n.dtype,b.values)}let m=new Bme(i,[u,d]),f=[{type:"int32",data:[i]},{type:"int32",data:c}],g=a.runWebGPUProgram(m,[h,p],h.dtype,f),y=ke({inputs:{x:g},backend:a,attrs:{shape:l}});return a.disposeData(p.dataId),a.disposeData(h.dataId),a.disposeData(g.dataId),y}var Ume={kernelName:co,backendName:"webgpu",kernelFunc:Vme},Gme=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=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="gather"}getUserCode(){let e=Hme(this.aShape);return`
|
|
${ue("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 Hme(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 $9(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=I.segment_util.collectGatherOpShapeInfo(r,s,l,o),d=v.sizeFromShape(s.shape),c=[],p=ke({inputs:{x:r},backend:a,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),h=ke({inputs:{x:s},backend:a,attrs:{shape:[u.batchSize,d/u.batchSize]}});c.push(p),c.push(h);let m=[u.batchSize,u.outerSize,d/u.batchSize,u.sliceSize];if(a.shouldExecuteOnCPU([r,s])){let x=a.tensorMap.get(h.dataId).values,A=Te(h.shape,h.dtype,x),b=a.tensorMap.get(p.dataId).values,w=Te(p.shape,p.dtype,b),S=ace(w,A,m);return c.forEach(C=>a.disposeData(C.dataId)),a.makeTensorInfo(u.outputShape,S.dtype,S.values)}let f=new Gme(p.shape,m),g=a.runWebGPUProgram(f,[p,h],p.dtype);c.push(g);let y=ke({inputs:{x:g},backend:a,attrs:{shape:u.outputShape}});return c.forEach(x=>a.disposeData(x.dataId)),y}var jme={kernelName:Su,backendName:"webgpu",kernelFunc:$9},qme=aa({opType:De.GREATER,cpuKernelImpl:rce,dtype:"bool"}),Xme={kernelName:As,backendName:"webgpu",kernelFunc:qme},Kme=aa({opType:De.GREATER_EQUAL,dtype:"bool",cpuKernelImpl:nce}),Yme={kernelName:bs,backendName:"webgpu",kernelFunc:Kme};function Zme(e){let{inputs:t,backend:a}=e,{input:n}=t;return F9(n,!0,a)}var Jme={kernelName:Tp,backendName:"webgpu",kernelFunc:Zme},Qme=at({opType:le.IS_FINITE,dtype:"bool"}),efe={kernelName:mo,backendName:"webgpu",kernelFunc:Qme},tfe=at({opType:le.IS_INF,dtype:"bool"}),afe={kernelName:fo,backendName:"webgpu",kernelFunc:tfe},nfe=at({opType:le.IS_NAN,dtype:"bool"}),rfe={kernelName:go,backendName:"webgpu",kernelFunc:nfe};function sfe(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{alpha:s}=n,i=[{type:"float32",data:[s]}],o=new id(r.shape,le.LEAKYRELU,"alpha : f32,");return a.runWebGPUProgram(o,[r],"float32",i)}var ife={kernelName:yo,backendName:"webgpu",kernelFunc:sfe},ofe=aa({opType:De.LESS,dtype:"bool",cpuKernelImpl:ice}),lfe={kernelName:vs,backendName:"webgpu",kernelFunc:ofe},ufe=aa({opType:De.LESS_EQUAL,dtype:"bool",cpuKernelImpl:sce}),dfe={kernelName:ws,backendName:"webgpu",kernelFunc:ufe},pfe=class{constructor(e){this.variableNames=[],this.outputShape=[],this.uniforms="start : f32, step : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e],this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="linSpace"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
setOutputAtIndex(index, uniforms.start + f32(index) * uniforms.step);
|
|
}
|
|
}
|
|
`}};function cfe(e){let{backend:t,attrs:a}=e,{start:n,stop:r,num:s}=a,i=(r-n)/(s-1),o=new pfe(s),l=[{type:"float32",data:[n]},{type:"float32",data:[i]}];return t.runWebGPUProgram(o,[],"float32",l)}var hfe={kernelName:xo,backendName:"webgpu",kernelFunc:cfe},mfe=at({opType:le.LOG,cpuKernelImpl:oce}),ffe={kernelName:ks,backendName:"webgpu",kernelFunc:mfe},gfe=at({opType:le.LOG1P}),yfe={kernelName:Ao,backendName:"webgpu",kernelFunc:gfe},xfe=aa({opType:De.LOGICAL_AND,dtype:"bool"}),Afe={kernelName:bo,backendName:"webgpu",kernelFunc:xfe},bfe=at({opType:le.LOGICAL_NOT}),vfe={kernelName:vo,backendName:"webgpu",kernelFunc:bfe},wfe=aa({opType:De.LOGICAL_OR}),kfe={kernelName:wo,backendName:"webgpu",kernelFunc:wfe},D9=`
|
|
var powValue = 0.0;
|
|
let basis = uniforms.bias + uniforms.alpha * sum;
|
|
if (uniforms.beta == 0.5) {
|
|
powValue = inverseSqrt(basis);
|
|
} else if (uniforms.beta == 1.0) {
|
|
powValue = 1.0 / basis;
|
|
} else {
|
|
powValue = exp(log(basis) * (-uniforms.beta));
|
|
}
|
|
`,Ife=class{constructor(e){this.outputShape=[],this.variableNames=["x"],this.uniforms="radius : i32, bias : f32, alpha : f32, beta : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="lrn"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getOutputCoords();
|
|
let b = coords[0];
|
|
let r = coords[1];
|
|
let c = coords[2];
|
|
let d = coords[3];
|
|
|
|
let x = getX(b, r, c, d);
|
|
var sum = 0.0;
|
|
for (var i = -uniforms.radius; i <= uniforms.radius; i = i + 1) {
|
|
let idx = d + i;
|
|
if (idx >= 0 && idx < uniforms.xShape[3]) {
|
|
let z = getX(b, r, c, idx);
|
|
sum = sum + z * z;
|
|
}
|
|
}
|
|
${D9}
|
|
|
|
setOutputAtIndex(index, x * powValue);
|
|
}
|
|
}
|
|
`}},Sfe=class{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.uniforms="radius : i32, bias : f32, alpha : f32, beta : f32,",this.workgroupSize=[256,1,1],this.maxAllowRadius=16,v.assert(t<=this.maxAllowRadius,()=>`Radius must be less than or equal to ${this.maxAllowRadius}, current radius is ${t}`),this.outputShape=e,this.elementsPerWorkgroup=this.workgroupSize[0]-2*this.maxAllowRadius,this.dispatchLayout={x:[3],y:[2],z:[0,1]},this.dispatch=de(this.dispatchLayout,this.outputShape,[this.elementsPerWorkgroup,this.workgroupSize[1],this.workgroupSize[2]]),this.shaderKey="lrn_shared"}getUserCode(){return`
|
|
var <workgroup>lrnSub: array<f32, ${this.workgroupSize[0]}>;
|
|
const elementsPerWorkgroup = ${this.elementsPerWorkgroup};
|
|
const maxAllowRadius = ${this.maxAllowRadius};
|
|
|
|
${ue()} {
|
|
let localDepth = i32(localId.x);
|
|
let workgroupDepth = i32(workgroupId.x) * elementsPerWorkgroup;
|
|
let xDepth = workgroupDepth + localDepth - maxAllowRadius;
|
|
let b = i32(globalId.z) / uniforms.xShape[1];
|
|
let r = i32(globalId.z) - b * uniforms.xShape[1];
|
|
let c = i32(globalId.y);
|
|
let d = workgroupDepth + localDepth;
|
|
|
|
var x = 0.0;
|
|
if (xDepth >= 0 && xDepth < uniforms.xShape[3]) {
|
|
x = getX(b, r, c, xDepth);
|
|
}
|
|
lrnSub[localDepth] = x;
|
|
workgroupBarrier();
|
|
|
|
if (localDepth < elementsPerWorkgroup && d < uniforms.outShape[3]) {
|
|
var sum = 0.0;
|
|
let index = localDepth + maxAllowRadius;
|
|
for (var i = -uniforms.radius; i <= uniforms.radius; i = i + 1) {
|
|
let z = lrnSub[index + i];
|
|
sum = sum + z * z;
|
|
}
|
|
${D9}
|
|
|
|
setOutputAtCoords(b, r, c, d, lrnSub[index] * powValue);
|
|
}
|
|
} `}};function Tfe(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n,u;s>16?u=new Ife(r.shape):u=new Sfe(r.shape,s);let d=[{type:"int32",data:[s]},{type:"float32",data:[i]},{type:"float32",data:[o]},{type:"float32",data:[l]}];return a.runWebGPUProgram(u,[r],r.dtype,d)}var Cfe={kernelName:ko,backendName:"webgpu",kernelFunc:Tfe},Nfe=class{constructor(e){this.outputShape=[],this.variableNames=["inputImage","outputImage","dy"],this.uniforms="depthRadius : i32, bias : f32, alpha : f32, beta : f32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="lrn_grad"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getOutputCoords();
|
|
let b = coords[0];
|
|
let r = coords[1];
|
|
let c = coords[2];
|
|
|
|
let MIN_DEPTH_BEGIN = 0;
|
|
let MAX_DEPTH_END = uniforms.outShape[3];
|
|
var result = 0.0;
|
|
for (var d = MIN_DEPTH_BEGIN; d < MAX_DEPTH_END; d++) {
|
|
let depthBegin = max(MIN_DEPTH_BEGIN, d - uniforms.depthRadius);
|
|
let depthEnd = min(MAX_DEPTH_END, d + uniforms.depthRadius + 1);
|
|
|
|
var norm = 0.0;
|
|
for (var 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 = uniforms.alpha * norm + uniforms.bias;
|
|
|
|
for (var k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; k++) {
|
|
if (k < depthBegin) {
|
|
continue;
|
|
} else if (k >= depthBegin && k < depthEnd) {
|
|
var dyi = -2.0 * uniforms.alpha * uniforms.beta
|
|
* getInputImage(b, r, c, k) * getOutputImage(b, r, c, d) / norm;
|
|
if (k == d) {
|
|
dyi += pow(norm, -1.0 * uniforms.beta);
|
|
}
|
|
if (k == coords[3]) {
|
|
dyi *= getDy(b, r, c, d);
|
|
result += dyi;
|
|
}
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
setOutputAtIndex(index, result);
|
|
}
|
|
}
|
|
`}};function Rfe(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:d}=n,c=new Nfe(r.shape),p=[{type:"int32",data:[o]},{type:"float32",data:[l]},{type:"float32",data:[u]},{type:"float32",data:[d]}];return a.runWebGPUProgram(c,[r,s,i],r.dtype,p)}var Efe={kernelName:Tu,backendName:"webgpu",kernelFunc:Rfe},Mfe=aa({opType:De.MAX,cpuKernelImpl:uce}),Ffe={kernelName:Is,backendName:"webgpu",kernelFunc:Mfe};function $fe(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=I.computePool2DInfo(r.shape,s,i,1,o,l);return w9(r,u,"max",a)}var Dfe={kernelName:So,backendName:"webgpu",kernelFunc:$fe};function Pfe(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dataFormat:l,dimRoundingMode:u}=n,d=[1,1,1],c=I.computePool3DInfo(r.shape,s,i,d,o,u,l),p=new uy(c,"max"),h=[{type:"int32",data:[c.strideDepth,c.strideHeight,c.strideWidth]},{type:"int32",data:[c.padInfo.front,c.padInfo.top,c.padInfo.left]},{type:"int32",data:[c.inDepth,c.inHeight,c.inWidth]},{type:"int32",data:[c.effectiveFilterDepth,c.effectiveFilterHeight,c.effectiveFilterWidth]}];return a.runWebGPUProgram(p,[r],r.dtype,h)}var _fe={kernelName:Cu,backendName:"webgpu",kernelFunc:Pfe},Ofe=class{constructor(e){this.variableNames=["dy","maxPos"],this.uniforms=`strides : vec2<i32>, pads : vec2<i32>, dilations : vec2<i32>, filterDims : vec2<i32>,
|
|
outHeight : i32, outWidth : i32`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="maxPool2DBackprop"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let batch = coords[0];
|
|
let d = coords[3];
|
|
|
|
let dyRCCorner = vec2<i32>(coords.yz) - uniforms.pads;
|
|
let dyRCorner = dyRCCorner.x;
|
|
let 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.
|
|
var dotProd = 0.0;
|
|
let lastIndex = uniforms.filterDims[0] * uniforms.filterDims[1] - 1;
|
|
for (var wR = 0; wR < uniforms.filterDims[0]; wR += uniforms.dilations[0]) {
|
|
let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[0]);
|
|
|
|
if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
let idyR = i32(dyR);
|
|
|
|
for (var wC = 0; wC < uniforms.filterDims[1]; wC += uniforms.dilations[1]) {
|
|
let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[1]);
|
|
|
|
if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
let idyC = i32(dyC);
|
|
|
|
let dyValue = getDy(batch, idyR, idyC, d);
|
|
let maxPosValue = lastIndex - i32(getMaxPos(batch, idyR, idyC, d));
|
|
|
|
// Get the current value, check it against the value from the
|
|
// position matrix.
|
|
let curPosValue = wR * uniforms.filterDims[1] + wC;
|
|
let mask = select(0.0, 1.0, maxPosValue == curPosValue);
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
setOutputAtIndex(index, dotProd);
|
|
}
|
|
}
|
|
`}},zfe=class{constructor(e){this.variableNames=["dy","maxPos"],this.uniforms=`strides : vec3<i32>, pads : vec3<i32>, filterDims : vec3<i32>,
|
|
outDepth : i32, outHeight : i32, outWidth : i32`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="maxPool3DBackprop"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let batch = coords.x;
|
|
let ch = coords.u;
|
|
|
|
let dyCorner = vec3<i32>(coords.y, coords.z, coords.w) - uniforms.pads;
|
|
let dyDCorner = dyCorner.x;
|
|
let dyRCorner = dyCorner.y;
|
|
let 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.
|
|
var dotProd = 0.0;
|
|
let lastIndex = uniforms.filterDims[0] * uniforms.filterDims[1] * uniforms.filterDims[2] - 1;
|
|
|
|
for (var wD = 0; wD < uniforms.filterDims[0]; wD++) {
|
|
let dyD = f32(dyDCorner + wD) / f32(uniforms.strides[0]);
|
|
|
|
if (dyD < 0.0 || dyD >= f32(uniforms.outDepth) || fract(dyD) > 0.0) {
|
|
continue;
|
|
}
|
|
let idyD = i32(dyD);
|
|
|
|
for (var wR = 0; wR < uniforms.filterDims[1]; wR++) {
|
|
let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[1]);
|
|
|
|
if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
let idyR = i32(dyR);
|
|
|
|
for (var wC = 0; wC < uniforms.filterDims[2]; wC++) {
|
|
let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[2]);
|
|
|
|
if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
let idyC = i32(dyC);
|
|
|
|
let dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
let maxPosValue = lastIndex - i32(getMaxPos(batch, idyD, idyR, idyC, ch));
|
|
|
|
// Get the current value, check it against the value from the
|
|
// position matrix.
|
|
let curPosValue = wD * uniforms.filterDims[1] * uniforms.filterDims[2] + wR * uniforms.filterDims[2] + wC;
|
|
let mask = select(0.0, 1.0, maxPosValue == curPosValue);
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
}
|
|
|
|
setOutputAtIndex(index, dotProd);
|
|
}
|
|
}
|
|
`}};function Lfe(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:d}=n,c=[1,1,1],p=I.computePool3DInfo(i.shape,o,l,c,u,d),h=new uy(p,"max",!0),m=[{type:"int32",data:[p.strideDepth,p.strideHeight,p.strideWidth]},{type:"int32",data:[p.padInfo.front,p.padInfo.top,p.padInfo.left]},{type:"int32",data:[p.inDepth,p.inHeight,p.inWidth]},{type:"int32",data:[p.effectiveFilterDepth,p.effectiveFilterHeight,p.effectiveFilterWidth]}],f=a.runWebGPUProgram(h,[i],"int32",m),g=new zfe(p);m=[{type:"int32",data:[p.strideDepth,p.strideHeight,p.strideWidth]},{type:"int32",data:[p.effectiveFilterDepth-1-p.padInfo.front,p.effectiveFilterHeight-1-p.padInfo.top,p.effectiveFilterWidth-1-p.padInfo.left]},{type:"int32",data:[p.effectiveFilterDepth,p.effectiveFilterHeight,p.effectiveFilterWidth]},{type:"int32",data:[p.outDepth]},{type:"int32",data:[p.outHeight]},{type:"int32",data:[p.outWidth]}];let y=a.runWebGPUProgram(g,[r,f],i.dtype,m);return a.disposeData(f.dataId),y}var Wfe={kernelName:Rp,backendName:"webgpu",kernelFunc:Lfe};function Bfe(e){let{inputs:t,backend:a,attrs:n}=e,{dy:r,input:s,output:i}=t,o=s;ay([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:d,dimRoundingMode:c}=n,p=I.computePool2DInfo(o.shape,l,u,1,d,c),h=new pp(p,"max",!0),m=[{type:"int32",data:[p.strideHeight,p.strideWidth]},{type:"int32",data:[p.padInfo.top,p.padInfo.left]},{type:"int32",data:[p.dilationHeight,p.dilationWidth]},{type:"int32",data:[p.inHeight,p.inWidth]},{type:"int32",data:[p.effectiveFilterHeight,p.effectiveFilterWidth]}],f=a.runWebGPUProgram(h,[o],"int32",m),g=new Ofe(p);m=[{type:"int32",data:[p.strideHeight,p.strideWidth]},{type:"int32",data:[p.effectiveFilterHeight-1-p.padInfo.top,p.effectiveFilterWidth-1-p.padInfo.left]},{type:"int32",data:[p.dilationHeight,p.dilationWidth]},{type:"int32",data:[p.effectiveFilterHeight,p.effectiveFilterWidth]},{type:"int32",data:[p.outHeight]},{type:"int32",data:[p.outWidth]}];let y=a.runWebGPUProgram(g,[r,f],o.dtype,m);return a.disposeData(f.dataId),y}var Vfe={kernelName:Np,backendName:"webgpu",kernelFunc:Bfe};function Ufe(e){let{inputs:t,backend:a,attrs:n}=e,{filterSize:r,strides:s,pad:i,includeBatchInIndex:o}=n,{x:l}=t;v.assert(l.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${l.shape.length}.`);let u=[1,1];v.assert(I.eitherStridesOrDilationsAreOne(s,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);let d=I.computePool2DInfo(l.shape,r,s,u,i),c=[{type:"int32",data:[d.strideHeight,d.strideWidth]},{type:"int32",data:[d.padInfo.top,d.padInfo.left]},{type:"int32",data:[d.dilationHeight,d.dilationWidth]},{type:"int32",data:[d.inHeight,d.inWidth]},{type:"int32",data:[d.effectiveFilterHeight,d.effectiveFilterWidth]}],p=new pp(d,"max",!1),h=a.runWebGPUProgram(p,[l],l.dtype,c);p=new pp(d,"max",!0,!0,o);let m=a.runWebGPUProgram(p,[l],"int32",c);return[h,m]}var Gfe={kernelName:Nu,backendName:"webgpu",kernelFunc:Ufe};function Hfe(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;return gl(r,s,i,"min",a)}var jfe={kernelName:Co,backendName:"webgpu",kernelFunc:Hfe},qfe=aa({opType:De.MIN,cpuKernelImpl:dce}),Xfe={kernelName:Ss,backendName:"webgpu",kernelFunc:qfe},Kfe=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=me(this.outputShape),this.dispatch=de(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=Dt(e),o=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return`
|
|
${ue("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}));
|
|
}
|
|
}
|
|
`}},Yfe={kernelName:No,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 Kfe(n.shape,r,s);return i.runWebGPUProgram(l,[n],n.dtype,o)}},Zfe=aa({opType:De.MOD}),Jfe={kernelName:Ro,backendName:"webgpu",kernelFunc:Zfe},Qfe=class{constructor(e,t){this.variableNames=["probs"],this.outputShape=[],this.uniforms="seed : f32, numOutcomes: i32,",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=[e,t],this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="multinomial"}getUserCode(){return`
|
|
//Based on the work of Dave Hoskins
|
|
//https://www.shadertoy.com/view/4djSRW
|
|
fn random (seed : f32, resultUV : vec2<f32>) -> f32 {
|
|
let HASHSCALE1 = 443.8975;
|
|
let p = resultUV * seed;
|
|
var p3 = fract(vec3<f32>(p.xyx) * HASHSCALE1);
|
|
p3 = p3 + dot(p3, p3.yzx + 19.19);
|
|
return fract((p3.x + p3.y) * p3.z);
|
|
}
|
|
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getOutputCoords();
|
|
let batch = coords[0];
|
|
|
|
let resUV = vec2<f32>(f32(coords[1]) / f32(uniforms.outShape[1]),
|
|
f32(coords[0]) / f32(uniforms.outShape[0]));
|
|
let r = random(uniforms.seed, resUV);
|
|
var cdf = 0.0;
|
|
for (var i = 0; i < uniforms.numOutcomes - 1; i = i + 1) {
|
|
cdf = cdf + getProbs(batch, i);
|
|
|
|
if (r < cdf) {
|
|
setOutputAtIndexI32(index, i);
|
|
return;
|
|
}
|
|
}
|
|
|
|
// If no other event happened, last event happened.
|
|
setOutputAtIndexI32(index, uniforms.numOutcomes - 1);
|
|
}
|
|
}
|
|
`}},e2e=class{constructor(e){this.variableNames=["logits"],this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=[this.outputShape[0],1,1],this.outputShape[1]>=4096?this.workgroupSize=[256,1,1]:this.workgroupSize=[64,1,1],this.shaderKey="softmax"}getUserCode(){return`
|
|
var<workgroup> buf : array<f32, ${this.workgroupSize[0]}>;
|
|
var<workgroup> rowMaxShared : f32;
|
|
var<workgroup> rowSumShared : f32;
|
|
const blockSize = ${this.workgroupSize[0]};
|
|
${ue("index")} {
|
|
let row = index / blockSize;
|
|
let tid = i32(localId.x);
|
|
let cols = uniforms.outShape[1];
|
|
|
|
var threadMax = -3.402823e+38f;
|
|
for (var col = tid; col < cols; col += blockSize) {
|
|
let value = getLogits(row, col);
|
|
threadMax = max(threadMax, value);
|
|
}
|
|
if (tid < cols) {
|
|
buf[tid] = threadMax;
|
|
}
|
|
workgroupBarrier();
|
|
|
|
var reduceSize = min(cols, blockSize);
|
|
for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {
|
|
reduceSize = currSize + (reduceSize & 1);
|
|
if (tid < currSize) {
|
|
buf[tid] = max(buf[tid], buf[tid + reduceSize]);
|
|
}
|
|
workgroupBarrier();
|
|
}
|
|
|
|
if (tid == 0) {
|
|
rowMaxShared = buf[0];
|
|
}
|
|
workgroupBarrier();
|
|
|
|
var threadSum = 0.0;
|
|
for (var col = tid; col < cols; col += blockSize) {
|
|
let subExp = exp(getLogits(row, col) - rowMaxShared);
|
|
threadSum += subExp;
|
|
}
|
|
buf[tid] = threadSum;
|
|
workgroupBarrier();
|
|
|
|
for (var currSize = blockSize >> 1; currSize > 0; currSize = currSize >> 1) {
|
|
if (tid < currSize) {
|
|
buf[tid] = buf[tid] + buf[tid + currSize];
|
|
}
|
|
workgroupBarrier();
|
|
}
|
|
|
|
if (tid == 0) {
|
|
rowSumShared = buf[0];
|
|
}
|
|
workgroupBarrier();
|
|
|
|
for (var col = tid; col < cols; col += blockSize) {
|
|
let value = exp(getLogits(row, col) - rowMaxShared) / rowSumShared;
|
|
setOutputAtCoords(row, col, value);
|
|
}
|
|
}
|
|
`}};function P9(e){let{inputs:t,backend:a,attrs:n}=e,{logits:r}=t,{dim:s}=n,i=ke({inputs:{x:r},backend:a,attrs:{shape:[v.sizeFromShape(r.shape)/r.shape[s],r.shape[s]]}}),o=new e2e(i.shape),l=a.runWebGPUProgram(o,[i],r.dtype),u=ke({inputs:{x:l},backend:a,attrs:{shape:r.shape}});return a.disposeData(i.dataId),a.disposeData(l.dataId),u}var t2e={kernelName:el,backendName:"webgpu",kernelFunc:P9};function a2e(e){let{inputs:t,backend:a,attrs:n}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=n,l=o?r:P9({inputs:{logits:r},backend:a,attrs:{dim:r.shape.length-1}}),u=l.shape[0],d=l.shape[1],c=new Qfe(u,s),p=[{type:"float32",data:[i]},{type:"int32",data:[d]}],h=a.runWebGPUProgram(c,[l],"int32",p);return o||a.disposeData(l.dataId),h}var n2e={kernelName:Eo,backendName:"webgpu",kernelFunc:a2e};function r2e(e){let{inputs:t,backend:a}=e,{x:n}=t;if(a.shouldExecuteOnCPU([n])){let s=a.tensorMap.get(n.dataId),[i,o]=cce(s.values,n.shape,n.dtype);return a.makeTensorInfo(o,n.dtype,i)}let r=new id(n.shape,le.NEG);return a.runWebGPUProgram(r,[n],n.dtype)}var s2e={kernelName:Ru,backendName:"webgpu",kernelFunc:r2e};function i2e(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),d=a.readSync(s.dataId),{selectedIndices:c}=Fn.nonMaxSuppressionV3Impl(u,d,i,o,l);return a.makeTensorInfo([c.length],"int32",new Int32Array(c))}var o2e={kernelName:Mo,backendName:"webgpu",kernelFunc:i2e};function l2e(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,d=a.readSync(r.dataId),c=a.readSync(s.dataId),p=i,h=o,m=l,f=u,{selectedIndices:g,selectedScores:y}=Fn.nonMaxSuppressionV5Impl(d,c,p,h,m,f);return[a.makeTensorInfo([g.length],"int32",new Int32Array(g)),a.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var u2e={kernelName:Fo,backendName:"webgpu",kernelFunc:l2e},d2e=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=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="onehot"}getUserCode(){return`
|
|
${ue("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 p2e(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),d=new d2e(u,i),c=ke({inputs:{x:r},backend:a,attrs:{shape:[u]}}),p=[{type:"float32",data:[o]},{type:"float32",data:[l]}],h=a.runWebGPUProgram(d,[c],s,p);a.disposeData(c.dataId);let m=[...r.shape,i],f=ke({inputs:{x:h},backend:a,attrs:{shape:m}});return a.disposeData(h.dataId),f}var c2e={kernelName:$o,backendName:"webgpu",kernelFunc:p2e};function _h(e){let{inputs:t,backend:a}=e,{x:n}=t;if(n.dtype==="complex64"){let r=oc({inputs:{input:n},backend:a}),s=_h({inputs:{x:r},backend:a}),i=A0({inputs:{input:n},backend:a}),o=_h({inputs:{x:i},backend:a}),l=fl({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 Wa({attrs:{shape:n.shape,dtype:n.dtype,value:n.dtype==="string"?"":0},backend:a})}var h2e={kernelName:qu,backendName:"webgpu",kernelFunc:_h};function _9(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=oc({inputs:{input:n},backend:a}),s=_9({inputs:{x:r},backend:a}),i=A0({inputs:{input:n},backend:a}),o=_h({inputs:{x:i},backend:a}),l=fl({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 Wa({attrs:{shape:n.shape,dtype:n.dtype,value:1},backend:a})}var m2e={kernelName:Mu,backendName:"webgpu",kernelFunc:_9};function f2e(e){let{inputs:t,backend:a,attrs:n}=e,{axis:r}=n;if(t.length===1)return rg({inputs:{input:t[0]},backend:a,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(d=>{v.assertShapesMatch(s,d.shape,"All tensors passed to stack must have matching shapes"),v.assert(i===d.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(d=>{let c=rg({inputs:{input:d},backend:a,attrs:{dim:r}});return o.push(c),c}),u=S9({inputs:l,backend:a,attrs:{axis:r}});return o.forEach(d=>a.disposeData(d.dataId)),u}var g2e={kernelName:Fu,backendName:"webgpu",kernelFunc:f2e};function O9(e,t=!1){let a=e.length,n=Dt(a),r=e.map((c,p)=>`uniforms.pad${p}[0]`).join(","),s=e.map((c,p)=>`uniforms.pad${p}[0] + uniforms.xShape${a>1?`[${p}]`:""}`).join(","),i=a>1?`${n}(${r})`:`${r}`,o=a>1?`${n}(${s})`:`${s}`,l=a>1?"any(paddedCoords < start)":"paddedCoords < start",u=a>1?"any(paddedCoords >= end)":"paddedCoords >= end",d=a>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,a):"coords";return`
|
|
let start = ${i};
|
|
let end = ${o};
|
|
if (${l} || ${u}) {
|
|
setOutputAtIndex(index, ${t?0:"uniforms.constantValue"});
|
|
} else {
|
|
let coords = paddedCoords - start;
|
|
setOutputAtIndex(index, getX(${d}));
|
|
}
|
|
`}var y2e=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=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),t.map((a,n)=>{this.uniforms+=` pad${n} : vec2<i32>,`}),this.xShape=e,this.shaderKey="pad"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let paddedCoords = getCoordsFromIndex(index);
|
|
${O9(this.xShape)}
|
|
}
|
|
}
|
|
`}},x2e=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 an({inputs:{x:r},backend:a});if(v.sizeFromShape(r.shape)===0){let u=s.map((d,c)=>d[0]+r.shape[c]+d[1]);return Wa({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 y2e(r.shape,s);return a.runWebGPUProgram(l,[r],r.dtype,o)},A2e={kernelName:Do,backendName:"webgpu",kernelFunc:x2e},b2e=aa({opType:De.POW}),v2e={kernelName:Po,backendName:"webgpu",kernelFunc:b2e};function w2e(e){let{inputs:t,backend:a}=e,{x:n,alpha:r}=t,s=new $h(De.PRELU,n.shape,r.shape);return a.runWebGPUProgram(s,[n,r],"float32")}var k2e={kernelName:_o,backendName:"webgpu",kernelFunc:w2e};function I2e(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{axis:s,keepDims:i}=n;return gl(r,s,i,"prod",a)}var S2e={kernelName:Oo,backendName:"webgpu",kernelFunc:I2e},T2e=e=>{let{backend:t,attrs:a}=e,{start:n,stop:r,step:s,dtype:i}=a,o=fce(n,r,s,i);return t.makeTensorInfo([o.length],i,o)},C2e={kernelName:$u,backendName:"webgpu",kernelFunc:T2e},N2e=aa({opType:De.DIV}),R2e={kernelName:io,backendName:"webgpu",kernelFunc:N2e},E2e=at({opType:le.RECIPROCAL}),M2e={kernelName:zo,backendName:"webgpu",kernelFunc:E2e},F2e=at({opType:le.RELU}),$2e={kernelName:Lo,backendName:"webgpu",kernelFunc:F2e},D2e=at({opType:le.RELU6}),P2e={kernelName:Vo,backendName:"webgpu",kernelFunc:D2e},_2e=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=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.shaderKey="resizeBilinear"}getUserCode(){return`
|
|
${ue("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 O2e(e){let{inputs:t,backend:a,attrs:n}=e,{images:r}=t,{alignCorners:s,size:i,halfPixelCenters:o}=n,[l,u]=i,d=s&&l>1?1:0,c=s&&u>1?1:0,p=[{type:"float32",data:[d,c]},{type:"float32",data:[o?.5:0]}],h=new _2e(r.shape,l,u);return a.runWebGPUProgram(h,[r],"float32",p)}var z2e={kernelName:Bo,backendName:"webgpu",kernelFunc:O2e},L2e=class{constructor(e,t){this.variableNames=["dy"],this.uniforms=`effectiveXSize : vec2<i32>, effectiveYSize : vec2<i32>, heightScale : f32, widthScale : f32,
|
|
invHeightScale : f32, invWidthScale : f32, winHeight : i32, winWidth : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.alignCorners=t,this.shaderKey=`resizeBilinearBackprop_${t}`}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getOutputCoords();
|
|
let b = coords[0];
|
|
let d = coords[3];
|
|
let r = coords[1];
|
|
let c = coords[2];
|
|
|
|
var accumulator = 0.0;
|
|
|
|
// Compute bounds for where in dy we will look
|
|
let startRLerp = floor(f32(r) * uniforms.invHeightScale);
|
|
let startDyR = i32(startRLerp - f32(uniforms.winHeight / 2));
|
|
|
|
let startCLerp = floor(f32(c) * uniforms.invWidthScale);
|
|
let startDyC = i32(startCLerp - f32(uniforms.winWidth / 2));
|
|
|
|
// Loop over dy
|
|
for (var dyROffset = 0; dyROffset < uniforms.winHeight; dyROffset++) {
|
|
let dyR = startDyR + dyROffset;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyR < 0 || dyR >= uniforms.dyShape[1]) {
|
|
continue;
|
|
}
|
|
|
|
for (var dyCOffset = 0; dyCOffset < uniforms.winWidth; dyCOffset++) {
|
|
let dyC = startDyC + dyCOffset;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= uniforms.dyShape[2]) {
|
|
continue;
|
|
}
|
|
|
|
let dxR = f32(dyR) * uniforms.heightScale;
|
|
let topDxRIndex = i32(floor(dxR));
|
|
let bottomDxRIndex = i32(min(ceil(dxR), f32(uniforms.outShape[1] - 1)));
|
|
let dxRLerp = dxR - f32(topDxRIndex);
|
|
let inverseDxRLerp = 1.0 - dxRLerp;
|
|
|
|
let dxC = f32(dyC) * uniforms.widthScale;
|
|
let leftDxCIndex = i32(floor(dxC));
|
|
let rightDxCIndex = i32(min(ceil(dxC), f32(uniforms.outShape[2] - 1)));
|
|
let dxCLerp = dxC - f32(leftDxCIndex);
|
|
let 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
|
|
|
|
setOutputAtIndex(index, accumulator);
|
|
}
|
|
}
|
|
`}};function W2e(e){let{inputs:t,backend:a,attrs:n}=e,{images:r,dy:s}=t,{alignCorners:i}=n,[,o,l]=r.shape,[,u,d]=s.shape,c=[i&&u>1?o-1:o,i&&d>1?l-1:l],p=[i&&u>1?u-1:u,i&&d>1?d-1:d],h=c[0]/p[0],m=c[1]/p[1],f=1/h,g=1/m,y=Math.ceil(f)*2+2,x=Math.ceil(g)*2+2,A=new L2e(r.shape,i),b=[{type:"int32",data:c},{type:"int32",data:p},{type:"float32",data:[h]},{type:"float32",data:[m]},{type:"float32",data:[f]},{type:"float32",data:[g]},{type:"int32",data:[y]},{type:"int32",data:[x]}];return a.runWebGPUProgram(A,[s],s.dtype,b)}var B2e={kernelName:_u,backendName:"webgpu",kernelFunc:W2e},V2e=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=me(this.outputShape),this.dispatch=de(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",`
|
|
${ue("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 U2e(e){let{inputs:t,backend:a,attrs:n}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,d=s&&l>1?1:0,c=s&&u>1?1:0,p=[{type:"float32",data:[d,c]},{type:"float32",data:[s?.5:0]}],h=new V2e(r.shape,l,u,i);return a.runWebGPUProgram(h,[r],r.dtype,p)}var G2e={kernelName:Wo,backendName:"webgpu",kernelFunc:U2e},H2e=class{constructor(e,t){this.variableNames=["dy"],this.uniforms=`effectiveXSize : vec2<i32>, effectiveYSize : vec2<i32>, invHeightScale : f32, invWidthScale : f32,
|
|
winHeight : i32, winWidth : i32,`,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.alignCorners=t,this.shaderKey=`resizeNearestNeigborBackprop_${t}`}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getOutputCoords();
|
|
let b = coords[0];
|
|
let d = coords[3];
|
|
let r = coords[1];
|
|
let c = coords[2];
|
|
|
|
var accumulator = 0.0;
|
|
|
|
// Compute bounds for where in dy we will look
|
|
let startRLerp = floor(f32(r) * uniforms.invHeightScale);
|
|
let startDyR = i32(floor(startRLerp - f32(uniforms.winHeight / 2)));
|
|
|
|
let startCLerp = floor(f32(c) * uniforms.invWidthScale);
|
|
let startDyC = i32(floor(startCLerp - f32(uniforms.winWidth / 2)));
|
|
|
|
// Loop over dy
|
|
for (var dyROffset = 0; dyROffset < uniforms.winHeight; dyROffset++) {
|
|
let dyR = startDyR + dyROffset;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyR < 0 || dyR >= uniforms.dyShape[1]) {
|
|
continue;
|
|
}
|
|
|
|
for (var dyCOffset = 0; dyCOffset < uniforms.winWidth; dyCOffset++) {
|
|
let dyC = startDyC + dyCOffset;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= uniforms.dyShape[2]) {
|
|
continue;
|
|
}
|
|
|
|
let sourceFracRow = f32(uniforms.effectiveXSize[0]) *
|
|
(f32(dyR) / f32(uniforms.effectiveYSize[0]));
|
|
|
|
let sourceFracCol = f32(uniforms.effectiveXSize[1]) *
|
|
(f32(dyC) / f32(uniforms.effectiveYSize[1]));
|
|
|
|
let sourceNearestRow =
|
|
i32(min(f32(uniforms.outShape[1] - 1),
|
|
${this.alignCorners?"floor(sourceFracRow + 0.5)":"floor(sourceFracRow)"}));
|
|
|
|
let sourceNearestCol =
|
|
i32(min(f32(uniforms.outShape[2] - 1),
|
|
${this.alignCorners?"floor(sourceFracCol + 0.5)":"floor(sourceFracCol)"}));
|
|
|
|
if (r == sourceNearestRow && c == sourceNearestCol) {
|
|
accumulator += getDy(b, dyR, dyC, d);
|
|
}
|
|
}
|
|
}
|
|
// End loop over dy
|
|
|
|
setOutputAtIndex(index, accumulator);
|
|
}
|
|
}
|
|
`}};function j2e(e){let{inputs:t,backend:a,attrs:n}=e,{images:r,dy:s}=t,{alignCorners:i}=n,[,o,l]=r.shape,[,u,d]=s.shape,c=[i&&u>1?o-1:o,i&&d>1?l-1:l],p=[i&&u>1?u-1:u,i&&d>1?d-1:d],h=c[0]/p[0],m=c[1]/p[1],f=1/h,g=1/m,y=Math.ceil(f)*2+2,x=Math.ceil(g)*2+2,A=new H2e(r.shape,i),b=[{type:"int32",data:c},{type:"int32",data:p},{type:"float32",data:[f]},{type:"float32",data:[g]},{type:"int32",data:[y]},{type:"int32",data:[x]}];return a.runWebGPUProgram(A,[s],s.dtype,b)}var q2e={kernelName:Pu,backendName:"webgpu",kernelFunc:j2e},X2e=class{constructor(e){this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(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;
|
|
}
|
|
|
|
${ue("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 K2e(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{dims:s}=n,i=r.shape.length;if(i===0)return an({inputs:{x:r},backend:a});let o=r.shape,l=[1,1,1,1];o.forEach((g,y)=>{let x=y+4-i;l[x]=g});let u=v.parseAxisParam(s,r.shape),d=[0,0,0,0];u.forEach(g=>{let y=g+4-i;d[y]=1});let c=[{type:"int32",data:d}],p=ke({inputs:{x:r},backend:a,attrs:{shape:l}}),h=new X2e(l),m=a.runWebGPUProgram(h,[p],p.dtype,c);a.disposeData(p.dataId);let f=ke({inputs:{x:m},backend:a,attrs:{shape:o}});return a.disposeData(m.dataId),f}var Y2e={kernelName:Uo,backendName:"webgpu",kernelFunc:K2e},Z2e=class{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(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`
|
|
${ue("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);
|
|
}
|
|
}
|
|
`}},J2e={kernelName:ol,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:a})=>{let{image:n}=e,{radians:r,fillValue:s,center:i}=t,o=a,l=new Z2e(n.shape,s),[u,d]=I.getImageCenter(i,n.shape[1],n.shape[2]),c=[{type:"float32",data:[u]},{type:"float32",data:[d]},{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)}},Q2e=at({opType:le.ROUND}),e1e={kernelName:Go,backendName:"webgpu",kernelFunc:Q2e},t1e=at({opType:le.RSQRT,cpuKernelImpl:gce}),a1e={kernelName:Ns,backendName:"webgpu",kernelFunc:t1e},Gd=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=me(e),this.dispatch=de(this.dispatchLayout,e,this.workgroupSize),this.sliceDimGreaterThanOne=t>1,this.shaderKey=`scatter_${a}_${n}_${this.sliceDimGreaterThanOne}_${i}_${o}_${r.length}`;let l=Dt(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},(i,o)=>`coords[${o}]`).join(", ")})`;return`
|
|
${r}
|
|
${ue("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 =
|
|
${gi(this.type)}(${s});
|
|
let flatIndex = getOutputIndexFromCoords(${n});
|
|
|
|
${this.sumDupeIndices?Bs("&result[flatIndex]","updateValue",this.type):"atomicStore(&result[flatIndex], bitcast<i32>(updateValue));"}
|
|
}
|
|
}`}};function n1e(e){let{inputs:t,backend:a,attrs:n}=e,{indices:r,updates:s}=t,{shape:i}=n,{sliceRank:o,numUpdates:l,sliceSize:u,strides:d,outputSize:c}=I.calculateShapes(s,r,i),p=[c/u,u];if(c===0)return a.makeTensorInfo(i,r.dtype);let h=ke({inputs:{x:r},backend:a,attrs:{shape:[l,o]}}),m=ke({inputs:{x:s},backend:a,attrs:{shape:[l,u]}}),f=m.dtype,g=Wa({backend:a,attrs:{shape:p,value:0,dtype:f}}),y=v.sizeFromShape(m.shape),x=[{type:"int32",data:[o]},{type:"int32",data:d},{type:"int32",data:[y]}],A=new Gd(m.shape,o,h.shape.length,m.shape.length,d,p,f),b=a.runWebGPUProgram(A,[m,h],f,x,g),w=ke({inputs:{x:b},backend:a,attrs:{shape:i}});return a.disposeData(h.dataId),a.disposeData(m.dataId),a.disposeData(b.dataId),w}var r1e={kernelName:Ho,backendName:"webgpu",kernelFunc:n1e},s1e=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=me(this.outputShape),this.dispatch=de(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;
|
|
}
|
|
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let value = getValuesByOutputIndex(index);
|
|
setOutputAtIndexI32(index, findBound(coords[0], value));
|
|
}
|
|
}
|
|
`}};function i1e(e){let{inputs:t,backend:a,attrs:n}=e,{sortedSequence:r,values:s}=t,{side:i}=n,o=new s1e([s.shape[0],s.shape[1]],i),l=[{type:"int32",data:[r.shape[1]]}];return a.runWebGPUProgram(o,[r,s],"int32",l)}var o1e={kernelName:qo,backendName:"webgpu",kernelFunc:i1e},l1e=class{constructor(e,t,a){this.variableNames=["c","a","b"],this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=me(this.outputShape),this.dispatch=de(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`
|
|
${ue("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 u1e(e){let{inputs:t,backend:a}=e,{condition:n,t:r,e:s}=t,i=new l1e(n.shape.length,r.shape,r.shape.length);return a.runWebGPUProgram(i,[n,r,s],Qt(r.dtype,s.dtype))}var d1e={kernelName:Ou,backendName:"webgpu",kernelFunc:u1e},p1e=at({opType:le.SELU}),c1e={kernelName:Xo,backendName:"webgpu",kernelFunc:p1e},h1e=at({opType:le.SIGMOID}),m1e={kernelName:Rs,backendName:"webgpu",kernelFunc:h1e},f1e=at({opType:le.SIGN}),g1e={kernelName:Zo,backendName:"webgpu",kernelFunc:f1e},y1e=at({opType:le.SIN}),x1e={kernelName:Ko,backendName:"webgpu",kernelFunc:y1e},A1e=at({opType:le.SINH}),b1e={kernelName:Yo,backendName:"webgpu",kernelFunc:A1e},v1e=at({opType:le.SOFTPLUS}),w1e={kernelName:Jo,backendName:"webgpu",kernelFunc:v1e},k1e=class{constructor(e,t,a,n,r,s){this.variableNames=["x"],this.outputShape=[],this.uniforms="",this.workgroupSize=[64,1,1],this.size=!0;let i=new Array(n.length);for(let o=0;o<i.length;o++)i[o]=n[r[o]];this.outputShape=i,this.newDim=r,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.xShape=e,this.paddedXShape=t,this.uniforms+=`reshapedPaddedXShape : ${Dt(n.length)}, paddedXShapeStrides : ${Dt(s)}, `,a.map((o,l)=>{this.uniforms+=` pad${l} : vec2<i32>,`}),this.shaderKey=`spaceToBatchND_${r}`}getUserCode(){let e=Dt(this.outputShape.length),t=x9(this.newDim);return`
|
|
${mh(this.paddedXShape,"PaddedX")}
|
|
${ue("index")} {
|
|
if(index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let switchedIndex = getIndexFromCoords${this.outputShape.length}D(${e}(${t}), uniforms.reshapedPaddedXShape);
|
|
let paddedCoords = getPaddedXCoordsFromIndex(switchedIndex);
|
|
${O9(this.xShape,!0)}
|
|
}
|
|
}
|
|
`}},I1e=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=l.map((x,A)=>x[0]+r.shape[A]+x[1]),d=I.getReshaped(u,s,o,!1),c=I.getPermuted(d.length,s.length,!1),p=I.getReshapedPermuted(u,s,o,!1),h=v.computeStrides(u),m=new k1e(r.shape,u,l,d,c,h.length),f=[{type:"int32",data:d},{type:"int32",data:h}];l.map(x=>f.push({type:"int32",data:[x[0],x[1]]}));let g=a.runWebGPUProgram(m,[r],r.dtype,f),y=ke({inputs:{x:g},backend:a,attrs:{shape:p}});return a.disposeData(g.dataId),y},S1e={kernelName:Lu,backendName:"webgpu",kernelFunc:I1e},T1e=class{constructor(e,t,a){this.variableNames=["input","indices","segmentIds"],this.outputShape=[],this.uniforms="segmentSize : i32, sparseSize : i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=e,this.type=a,this.dispatchLayout=me([t]),this.dispatch=de(this.dispatchLayout,[t],this.workgroupSize),this.shaderKey="sparseSegmentSum"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.sparseSize) {
|
|
let indexInSegmentIds = index / uniforms.segmentSize;
|
|
let indexInSegment = index % uniforms.segmentSize;
|
|
let indexInInput = indices[indexInSegmentIds];
|
|
let segmentId = segmentIds[indexInSegmentIds];
|
|
|
|
let value = input[indexInInput * uniforms.segmentSize + indexInSegment];
|
|
let outIndex = segmentId * uniforms.segmentSize + indexInSegment;
|
|
${Bs("&result[outIndex]","value",this.type)}
|
|
}
|
|
}
|
|
`}},C1e=class{constructor(e,t){this.variableNames=["segmentIds"],this.outputShape=[],this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=[e],this.dispatchLayout=me(t),this.dispatch=de(this.dispatchLayout,t,this.workgroupSize),this.shaderKey="sparseSegmentIdCountProgram"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.segmentIdsShape) {
|
|
let segmentId = segmentIds[index];
|
|
${Bs("&result[segmentId]","1","int32")}
|
|
}
|
|
}
|
|
`}},N1e=class{constructor(e,t){this.variableNames=["segmentSum","sameSegmentIdCount"],this.outputShape=[],this.uniforms="segmentSize : i32",this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.type=t,this.dispatchLayout=me(e),this.dispatch=de(this.dispatchLayout,e,this.workgroupSize),this.shaderKey="sparseSegmentMean"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let segmentId = index / uniforms.segmentSize;
|
|
let count = sameSegmentIdCount[segmentId];
|
|
if (count != 0) {
|
|
${this.type==="float32"?"setOutputAtIndex(index, segmentSum[index] / f32(count));":"setOutputAtIndexI32(index, segmentSum[index] / count);"}
|
|
}
|
|
}
|
|
}
|
|
`}};function z9(e,t,a,n=!1,r){let s=v.sizeFromShape(e.shape)/e.shape[0],i=e.dtype,o=v.sizeFromShape(t.shape),l=r.readSync(a.dataId),u=o>0?l[o-1]+1:0,d,c=e.shape.slice();c[0]=u;let p=o*s,h=Wa({backend:r,attrs:{shape:c,value:0,dtype:i}});d=new T1e(c,p,i);let m=[{type:"int32",data:[s]},{type:"int32",data:[p]}],f=r.runWebGPUProgram(d,[e,t,a],i,m,h);if(n)return f;let g=Wa({backend:r,attrs:{shape:[u],value:0,dtype:"int32"}});d=new C1e(u,a.shape);let y=r.runWebGPUProgram(d,[a],"int32",null,g),x=Wa({backend:r,attrs:{shape:c,value:0,dtype:i}});d=new N1e(c,i),m=[{type:"int32",data:[s]}];let A=r.runWebGPUProgram(d,[f,y],i,m,x);return r.disposeData(f.dataId),r.disposeData(y.dataId),A}function R1e(e){let{inputs:t,backend:a}=e,{data:n,indices:r,segmentIds:s}=t;return z9(n,r,s,!1,a)}var E1e={kernelName:Vu,backendName:"webgpu",kernelFunc:R1e};function M1e(e){let{inputs:t,backend:a}=e,{data:n,indices:r,segmentIds:s}=t;return z9(n,r,s,!0,a)}var F1e={kernelName:Uu,backendName:"webgpu",kernelFunc:M1e},$1e=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=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.rank=this.outputShape.length,this.shaderKey="tile"}getUserCode(){let e=D1e(this.rank,"uniforms.");return`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let resRC = getCoordsFromIndex(index);
|
|
setOutputAtIndex(index, getA(${e}));
|
|
}
|
|
}
|
|
`}};function D1e(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 dy(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=Te(r.shape,r.dtype,l),d=kce(u,s);return a.makeTensorInfo(d.shape,d.dtype,d.values)}let i=new $1e(r.shape,s);return a.runWebGPUProgram(i,[r],r.dtype)}var P1e={kernelName:$s,backendName:"webgpu",kernelFunc:dy};function _1e(e){let{inputs:t,backend:a,attrs:n}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=n,{sliceRank:l,numUpdates:u,sliceSize:d,strides:c,outputSize:p}=I.calculateShapes(s,r,o),h=!1;if(s.dtype==="string"){let N=a.bufferSync(r),M=a.bufferSync(s),F=v.decodeString(a.readSync(i.dataId)[0]),E=yce(N,M,o,p,d,u,l,c,F,h);return a.makeTensorInfo(o,E.dtype,E.values)}let m=[p/d,d],f=ke({inputs:{x:r},backend:a,attrs:{shape:[u,l]}}),g=s.shape.length?ke({inputs:{x:s},backend:a,attrs:{shape:[u,d]}}):an({inputs:{x:s},backend:a}),y=g.dtype,x=a.makeTensorInfo([],y,v.makeZerosTypedArray(1,y)),A=ke({inputs:{x:i},backend:a,attrs:{shape:Array(m.length).fill(1)}}),b=dy({inputs:{x:A},backend:a,attrs:{reps:m}}),w=v.sizeFromShape([u,d]),S=[{type:"int32",data:[l]},{type:"int32",data:c},{type:"int32",data:[w]}];switch(u){case 0:break;case 1:{let N=new Gd([u,d],l,f.shape.length,g.shape.length,c,m,y,h);a.runWebGPUProgram(N,[g,f],y,S,b)}break;default:{let N=new Gd([u,d],l,f.shape.length,x.shape.length,c,m,y,h);a.runWebGPUProgram(N,[x,f],y,S,b)}{let N=new Gd([u,d],l,f.shape.length,g.shape.length,c,m,y);a.runWebGPUProgram(N,[g,f],y,S,b)}}let C=ke({inputs:{x:b},backend:a,attrs:{shape:o}});return a.disposeData(f.dataId),a.disposeData(g.dataId),a.disposeData(A.dataId),a.disposeData(x.dataId),a.disposeData(b.dataId),C}var O1e={kernelName:tl,backendName:"webgpu",kernelFunc:_1e};function z1e(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=I.prepareSplitSize(r,s,o),u=r.shape.length,d=new Array(u).fill(0),c=r.shape.slice();return l.map(p=>{let h=[...c];h[o]=p;let m=od({inputs:{x:r},backend:a,attrs:{begin:d,size:h}});return d[o]+=p,m})}var L1e={kernelName:Wu,backendName:"webgpu",kernelFunc:z1e},W1e=at({opType:le.SQRT}),B1e={kernelName:Es,backendName:"webgpu",kernelFunc:W1e},V1e={kernelName:Fp,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{x:a}=e,n=t,r=new id(a.shape,le.SQUARE);return n.runWebGPUProgram(r,[a],a.dtype)}},U1e=aa({opType:De.SQUARED_DIFFERENCE}),G1e={kernelName:Ms,backendName:"webgpu",kernelFunc:U1e};function H1e({inputs:e,attrs:t,backend:a}){let{x:n}=e,r=new id(n.shape,le.STEP,"stepAlpha : f32,"),s=[{type:"float32",data:[t.alpha]}];return a.runWebGPUProgram(r,[n],n.dtype,s)}var j1e={kernelName:Ds,backendName:"webgpu",kernelFunc:H1e},q1e=class{constructor(e){this.variableNames=["x"],this.workPerThread=1,this.workgroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize,[this.workPerThread,1,1]);let t=Dt(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`
|
|
${ue("index")} {
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
setOutputAtIndex(index, getX(${t}));
|
|
}
|
|
}
|
|
`}};function X1e(e){let{inputs:t,backend:a,attrs:n}=e,{x:r}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:d,newAxisMask:c,shrinkAxisMask:p}=n,{finalShapeSparse:h,finalShape:m,isIdentity:f,sliceDim0:g,isSimpleSlice:y,begin:x,end:A,strides:b}=wt.sliceInfo(r.shape,s,i,o,l,u,d,c,p),w;if(f)w=ke({inputs:{x:r},backend:a,attrs:{shape:m}});else if(g||y){v.assert(r.shape.length>=1,()=>`Input must have rank at least 1, got: ${r.shape.length}`);let S=wt.computeOutShape(x,A,b),C=od({inputs:{x:r},backend:a,attrs:{begin:x,size:S}});w=ke({inputs:{x:C},backend:a,attrs:{shape:m}}),a.disposeData(C.dataId)}else if(a.shouldExecuteOnCPU([r])){let S=a.readSync(r.dataId),C=Te(r.shape,r.dtype,S),N=bce(h,C,b,x);w=a.makeTensorInfo(m,r.dtype,N.values)}else{let S=new q1e(h),C=[{type:"int32",data:x},{type:"int32",data:b}],N=a.runWebGPUProgram(S,[r],r.dtype,C);w=ke({inputs:{x:N},backend:a,attrs:{shape:m}}),a.disposeData(N.dataId)}return w}var K1e={kernelName:al,backendName:"webgpu",kernelFunc:X1e};function Y1e(e){let{inputs:t,backend:a,attrs:n}=e,{separator:r,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=n,{data:d,dataSplits:c}=t,p=a.readSync(d.dataId),h=a.readSync(c.dataId),[m,f]=vce(p,h,r,s,i,o,l,u);return[a.makeTensorInfo([m.length],"string",m),a.makeTensorInfo(c.shape,"int32",f)]}var Z1e={kernelName:Hu,backendName:"webgpu",kernelFunc:Y1e},J1e=aa({opType:De.SUB,cpuKernelImpl:wce,supportsComplex:!0}),Q1e={kernelName:Fs,backendName:"webgpu",kernelFunc:J1e},ege=at({opType:le.TAN}),tge={kernelName:nl,backendName:"webgpu",kernelFunc:ege},age=at({opType:le.TANH}),nge={kernelName:rl,backendName:"webgpu",kernelFunc:age};function rge(e){let{inputs:t,backend:a,attrs:n}=e,{tensor:r,indices:s,updates:i}=t,{}=n,{sliceRank:o,numUpdates:l,sliceSize:u,strides:d,outputSize:c}=I.calculateShapes(i,s,r.shape),p=[c/u,u];if(c===0)return a.makeTensorInfo(r.shape,s.dtype);let h=[],m=ke({inputs:{x:s},backend:a,attrs:{shape:[l,o]}});h.push(m);let f=ke({inputs:{x:i},backend:a,attrs:{shape:[l,u]}});h.push(f);let g=ke({inputs:{x:r},backend:a,attrs:{shape:p}});h.push(g);let y=dy({inputs:{x:g},backend:a,attrs:{reps:Array(p.length).fill(1)}}),x=new Gd([l,u],o,m.shape.length,f.shape.length,d,p,r.dtype,!1),A=v.sizeFromShape([l,u]),b=[{type:"int32",data:[o]},{type:"int32",data:d},{type:"int32",data:[A]}],w=a.runWebGPUProgram(x,[f,m],g.dtype,b,y);h.push(w);let S=ke({inputs:{x:w},backend:a,attrs:{shape:r.shape}});return h.forEach(C=>a.disposeData(C.dataId)),S}var sge={kernelName:jo,backendName:"webgpu",kernelFunc:rge},ige=class{constructor(e){this.variableNames=["x","indices"],this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms=`inputSize : i32, firstPass : i32, negativeInf : f32,
|
|
dir : i32, inc : i32,`,this.shaderKey="swap"}getUserCode(){return`
|
|
${ue("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));
|
|
}
|
|
}
|
|
}
|
|
`}},oge=class{constructor(e){this.variableNames=["x","indices"],this.workgroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=me(this.outputShape),this.dispatch=de(this.dispatchLayout,this.outputShape,this.workgroupSize),this.uniforms="inputSize : i32, firstPass : i32, k : i32,",this.shaderKey="merge"}getUserCode(){return`
|
|
${ue("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 Ul(e,t){t!==null&&e.disposeData(t.dataId)}function NA(e){let t=1;for(;t<e;)t*=2;return t}function lge(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]=Ice(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,Wa({attrs:{shape:o,dtype:"int32",value:0},backend:a})];let u=v.sizeFromShape(o)/l,d=ke({inputs:{x:r},attrs:{shape:[u,l]},backend:a}),c=NA(s),p=NA(l),h=null,m=()=>h===null?[d,d]:[d,h],f=(b,w,S)=>{let C=m(),N=new ige(S),M=[{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]}],F=h;h=a.runWebGPUProgram(N,C,"int32",M),Ul(a,F)};for(let b=1;b<c;b*=2){let w=b*2;for(let S=b;S>=1;S/=2)f(w,S,[u,p])}for(let b=p;b>c;b/=2){let w=m(),S=new oge([u,b/2]),C=[{type:"int32",data:[l]},{type:"int32",data:[h===null?1:0]},{type:"int32",data:[c]}],N=h;h=a.runWebGPUProgram(S,w,"int32",C),Ul(a,N);let M=c/2,F=M*2;for(let E=M;E>=1;E/=2)f(F,E,h.shape)}let g=h;h=od({inputs:{x:h},backend:a,attrs:{begin:0,size:[u,s]}}),Ul(a,g);let y=$9({inputs:{x:d,indices:h},backend:a,attrs:{axis:1,batchDims:1}});Ul(a,d);let x=o.slice(0,-1);x.push(s),g=h,h=ke({inputs:{x:h},attrs:{shape:x},backend:a}),Ul(a,g);let A=y;return y=ke({inputs:{x:y},attrs:{shape:x},backend:a}),Ul(a,A),[y,h]}var uge={kernelName:sl,backendName:"webgpu",kernelFunc:lge},dge=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=me(this.outputShape),this.dispatch=de(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;
|
|
}
|
|
|
|
${ue("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 pge(e){let{inputs:t,backend:a,attrs:n}=e,{image:r,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=n,[d,c,p,h]=r.shape,[m,f]=u!=null?u:[c,p],g=[d,m,f,h],y=new dge(g),x=i==="nearest"?1:2,A;switch(o){case"constant":A=1;break;case"reflect":A=2;break;case"wrap":A=3;break;case"nearest":A=4;break;default:A=1;break}let b=[{type:"int32",data:[x]},{type:"int32",data:[A]},{type:"float32",data:[l]}];return a.runWebGPUProgram(y,[r,s],"float32",b)}var cge={kernelName:il,backendName:"webgpu",kernelFunc:pge};function hge(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),d=0;for(let f=0;f<o;f++)f!==s&&(u[d++]=i.shape[f]);let c=[],p=new Array(o).fill(0),h=i.shape.slice();h[s]=1;let m=new Array(l);for(let f=0;f<m.length;f++){p[s]=f;let g=od({inputs:{x:i},backend:a,attrs:{begin:p,size:h}}),y=ke({inputs:{x:g},backend:a,attrs:{shape:u}});m[f]=y,c.push(g)}return c.forEach(f=>a.disposeData(f.dataId)),m}var mge={kernelName:ju,backendName:"webgpu",kernelFunc:hge},fge=class{constructor(e,t,a){if(this.outputShape=[],this.variableNames=["x","segmentIds"],this.uniforms="numSegments : i32, xSize: i32,",this.workgroupSize=[64,1,1],this.atomic=!0,this.outputShape=t,this.dispatchLayout=me(e),this.dispatch=de(this.dispatchLayout,e,this.workgroupSize),a!=="float32"&&a!=="int32")throw new Error(`UnsortedSegmentSum only supports float32 and int32
|
|
types, does not support ${a} type.`);this.type=a,this.shaderKey="unsortedSegmentSum"}getUserCode(){return`
|
|
${ue("index")} {
|
|
if (index < uniforms.xSize) {
|
|
let coords = getXCoordsFromIndex(index);
|
|
let b = coords[0];
|
|
let inCol = coords[1];
|
|
|
|
let segmentId = i32(getSegmentIds(inCol));
|
|
if (segmentId >= 0) {
|
|
let flatIndex = b * uniforms.numSegments + segmentId % uniforms.numSegments;
|
|
let value = getX(b, inCol);
|
|
|
|
${Bs("&result[flatIndex]","value",this.type)}
|
|
}
|
|
}
|
|
}
|
|
`}};function gge(e){let{inputs:t,backend:a,attrs:n}=e,{x:r,segmentIds:s}=t,{numSegments:i}=n,o=r.shape.length,l=[],u=0,d=I.getAxesPermutation([u],o),c=r;d!=null&&(c=ir({inputs:{x:r},backend:a,attrs:{perm:d}}),l.push(c),u=I.getInnerMostAxes(1,o)[0]);let p=I.segment_util.computeOutShape(c.shape,u,i),h=v.sizeFromShape([c.shape[u]]),m=ke({inputs:{x:c},backend:a,attrs:{shape:[-1,h]}});l.push(m);let f=r.dtype,g=[m.shape[0],i],y=Wa({backend:a,attrs:{shape:g,value:0,dtype:f}}),x=new fge(m.shape,g,f),A=[{type:"int32",data:[i]},{type:"int32",data:[v.sizeFromShape(m.shape)]}],b=a.runWebGPUProgram(x,[m,s],f,A,y),w=ke({inputs:{x:b},backend:a,attrs:{shape:p}});l.push(b);let S=w;if(d!=null){l.push(w);let C=I.getUndoAxesPermutation(d);S=ir({inputs:{x:S},backend:a,attrs:{perm:C}})}return l.forEach(C=>a.disposeData(C.dataId)),S}var yge={kernelName:_p,backendName:"webgpu",kernelFunc:gge},xge=[tpe,Cce,Rce,Mce,$ce,_ce,Uce,Hce,qce,Kce,Zce,Qce,the,nhe,she,dhe,che,ghe,xhe,bhe,She,Rhe,Fhe,_he,zhe,Vhe,npe,Hhe,Khe,n0e,u0e,h0e,g0e,x0e,b0e,w0e,I0e,C0e,R0e,M0e,$0e,_0e,U0e,H0e,L0e,X0e,Z0e,tme,nme,ime,dme,cme,mme,gme,xme,bme,vme,kme,Sme,Jde,Cme,$me,Rme,Mme,_me,zme,Wme,Ume,jme,Xme,Yme,ape,Jme,qhe,efe,afe,rfe,ife,lfe,dfe,hfe,yfe,ffe,Afe,vfe,kfe,Cfe,Efe,ohe,Ffe,Dfe,Vfe,_fe,Wfe,Gfe,lhe,jfe,Xfe,Yfe,Jfe,n2e,ome,s2e,o2e,u2e,$he,c2e,m2e,g2e,A2e,v2e,k2e,S2e,C2e,Dhe,R2e,M2e,$2e,P2e,Qde,z2e,B2e,G2e,q2e,Y2e,J2e,e1e,a1e,r1e,o1e,d1e,c1e,m1e,g1e,x1e,b1e,khe,j1e,K1e,Z1e,t2e,w1e,S1e,E1e,F1e,O1e,L1e,B1e,V1e,G1e,Q1e,lme,tge,nge,sge,P1e,uge,cge,Lce,mge,yge,h2e];for(let e of xge)bn(e);var RA="4.17.0",Age="4.17.0",bge="4.17.0",vge="4.17.0",wge="4.17.0",kge="4.14.0",lc={tfjs:RA,"tfjs-core":RA,"tfjs-converter":Age,"tfjs-backend-cpu":bge,"tfjs-backend-webgl":vge,"tfjs-backend-wasm":wge,"tfjs-backend-webgpu":kge},py=void 0;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 L9(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 ae=()=>typeof performance!="undefined"?performance.now():parseInt((Number(process.hrtime.bigint())/1e3/1e3).toString());function cy(e,t,a="config",n=[]){for(let r of Object.keys(t))if(typeof t[r]=="object")cy(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 Mt(...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]=Mt(s,i):a[r]=i}),a),{})}var yl={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:!1,maxDetected:1,skipFrames:99,skipTime:2500,minConfidence:.2,minSize:0,iouThreshold:.1,scale:1.4,mask:!1,return:!1},mesh:{enabled:!0,modelPath:"facemesh.json",keepInvalid:!1},attention:{enabled:!1,modelPath:"facemesh-attention.json"},iris:{enabled:!0,scale:2.3,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 W9=`
|
|
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 B9=`
|
|
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];
|
|
}
|
|
`,V9=`
|
|
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;
|
|
}
|
|
`,U9=`
|
|
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);
|
|
}
|
|
`,G9=`
|
|
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;
|
|
}
|
|
`,H9=`
|
|
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 hy=(e,t,a)=>{let n=new RegExp("\\b"+t+" \\w+ (\\w+)","ig");e.replace(n,(r,s)=>(a[s]=0,r))},my=class{constructor(t,a,n){he(this,"uniform",{});he(this,"attribute",{});he(this,"gl");he(this,"id");he(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),hy(a,"attribute",this.attribute);for(let i in this.attribute)this.attribute[i]=this.gl.getAttribLocation(this.id,i);hy(a,"uniform",this.uniform),hy(n,"uniform",this.uniform);for(let i in this.uniform)this.uniform[i]=this.gl.getUniformLocation(this.id,i)}}};function j9(){let e=0,t=null,a=!1,n=-1,r=[null,null],s=[],i=null,o=null,l=Dn(100,100),u={},d={INTERMEDIATE:1},c=l.getContext("webgl");if(!c){K("filter: cannot get webgl context");return}this.gl=c;function p(x,A){if(!(x===l.width&&A===l.height)){if(l.width=x,l.height=A,!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(x,A){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,x,A,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 m(x){return r[x]=r[x]||h(l.width,l.height),r[x]}function f(x=0){if(!o)return;let A=null,b=null,w=!1;e===0?A=t:A=m(n).texture||null,e++,a&&!(x&d.INTERMEDIATE)?(b=null,w=e%2===0):(n=(n+1)%2,b=m(n).fbo||null),c.bindTexture(c.TEXTURE_2D,A),c.bindFramebuffer(c.FRAMEBUFFER,b),c.uniform1f(o.uniform.flipY,w?-1:1),c.drawArrays(c.TRIANGLES,0,6)}function g(x){if(u[x])return o=u[x],c.useProgram((o?o.id:null)||null),o;if(o=new my(c,W9,x),!o)return K("filter: could not get webgl program"),null;let A=Float32Array.BYTES_PER_ELEMENT,b=4*A;return c.enableVertexAttribArray(o.attribute.pos),c.vertexAttribPointer(o.attribute.pos,2,c.FLOAT,!1,b,0*A),c.enableVertexAttribArray(o.attribute.uv),c.vertexAttribPointer(o.attribute.uv,2,c.FLOAT,!1,b,2*A),u[x]=o,o}let y={colorMatrix:x=>{let A=new Float32Array(x);A[4]/=255,A[9]/=255,A[14]/=255,A[19]/=255;let b=A[18]===1&&A[3]===0&&A[8]===0&&A[13]===0&&A[15]===0&&A[16]===0&&A[17]===0&&A[19]===0?V9:B9,w=g(b);w&&(c.uniform1fv(w.uniform.m,A),f())},brightness:x=>{let A=(x||0)+1;y.colorMatrix([A,0,0,0,0,0,A,0,0,0,0,0,A,0,0,0,0,0,1,0])},saturation:x=>{let A=(x||0)*2/3+1,b=(A-1)*-.5;y.colorMatrix([A,b,b,0,0,b,A,b,0,0,b,b,A,0,0,0,0,0,1,0])},desaturate:()=>{y.saturation(-1)},contrast:x=>{let A=(x||0)+1,b=-128*(A-1);y.colorMatrix([A,0,0,0,b,0,A,0,0,b,0,0,A,0,b,0,0,0,1,0])},negative:()=>{y.contrast(-2)},hue:x=>{x=(x||0)/180*Math.PI;let A=Math.cos(x),b=Math.sin(x),w=.213,S=.715,C=.072;y.colorMatrix([w+A*(1-w)+b*-w,S+A*-S+b*-S,C+A*-C+b*(1-C),0,0,w+A*-w+b*.143,S+A*(1-S)+b*.14,C+A*-C+b*-.283,0,0,w+A*-w+b*-(1-w),S+A*-S+b*S,C+A*(1-C)+b*C,0,0,0,0,0,1,0])},desaturateLuminance:()=>{y.colorMatrix([.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,0,0,0,1,0])},sepia:()=>{y.colorMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0])},brownie:()=>{y.colorMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0])},vintagePinhole:()=>{y.colorMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0])},kodachrome:()=>{y.colorMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0])},technicolor:()=>{y.colorMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0])},polaroid:()=>{y.colorMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0])},shiftToBGR:()=>{y.colorMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0])},convolution:x=>{let A=new Float32Array(x),b=1/l.width,w=1/l.height,S=g(H9);S&&(c.uniform1fv(S.uniform.m,A),c.uniform2f(S.uniform.px,b,w),f())},detectEdges:()=>{y.convolution.call(this,[0,1,0,1,-4,1,0,1,0])},sobelX:()=>{y.convolution.call(this,[-1,0,1,-2,0,2,-1,0,1])},sobelY:()=>{y.convolution.call(this,[-1,-2,-1,0,0,0,1,2,1])},sharpen:x=>{let A=x||1;y.convolution.call(this,[0,-1*A,0,-1*A,1+4*A,-1*A,0,-1*A,0])},emboss:x=>{let A=x||1;y.convolution.call(this,[-2*A,-1*A,0,-1*A,1,1*A,0,1*A,2*A])},blur:x=>{let A=x/7/l.width,b=x/7/l.height,w=g(G9);w&&(c.uniform2f(w.uniform.px,0,b),f(d.INTERMEDIATE),c.uniform2f(w.uniform.px,A,0),f())},pixelate:x=>{let A=x/l.width,b=x/l.height,w=g(U9);w&&(c.uniform2f(w.uniform.size,A,b),f())}};this.add=function(x){let A=Array.prototype.slice.call(arguments,1),b=y[x];s.push({func:b,args:A})},this.reset=function(){s=[]},this.get=function(){return s},this.apply=function(x){p(x.width,x.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,x);for(let A=0;A<s.length;A++){a=A===s.length-1;let b=s[A];b.func.apply(this,b.args||[])}return l},this.draw=function(x){return this.add("brightness",0),this.apply(x)}}async function b0(e){let t=e.shape.length===4?Oe(e):e,a=Sa(t,3,2),n=[os(a[0]),os(a[1]),os(a[2])],r=[fa(a[0]),fa(a[1]),fa(a[2])],s=await Promise.all(r.map(d=>d.data())),i=Math.max(s[0][0],s[1][0],s[2][0]),l=(i>1?255:1)/i,u;if(l>1){let d=[xe(a[0],n[0]),xe(a[1],n[1]),xe(a[2],n[2])],c=[xe(r[0],n[0]),xe(r[1],n[1]),xe(r[2],n[2])],p=[te(d[0],l),te(d[1],l),te(d[2],l)],h=ca([p[0],p[1],p[2]],2);u=Q(h,[1,t.shape[0]||0,t.shape[1]||0,3]),J([...d,...c,...p,h])}else u=Bt(t,0);return J([...a,...n,...r,a,t,e]),u}var v0=3840,na=null,ra=null,ld=null,vt,wn={inputSum:0,cacheDiff:1,sumMethod:0,inputTensor:void 0};function fy(){wn.inputSum=0,wn.cacheDiff=1,wn.sumMethod=0,wn.inputTensor=void 0}function Dn(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")a=document.createElement("canvas"),a.width=e,a.height=t;else if(typeof navigator!="undefined"&&navigator.product==="ReactNative")if(typeof ne.Canvas!="undefined")a=new ne.Canvas(e,t);else if(typeof globalThis.Canvas!="undefined")a=new globalThis.Canvas(e,t);else throw new Error("canvas error: attempted to use canvas in react-native without canvas support installed");else throw new Error("canvas error: attempted to run in browser but DOM is not defined");else typeof ne.Canvas!="undefined"?a=new ne.Canvas(e,t):typeof globalThis.Canvas!="undefined"&&(a=new globalThis.Canvas(e,t));return a}function w0(e,t){let a=t||Dn(e.width,e.height);return a.getContext("2d").drawImage(e,0,0),a}async function k0(e,t,a=!0){var p,h,m;if(!e)return t.debug&&K("input error: input is missing"),{tensor:null,canvas:null};if(!(e instanceof yt)&&!(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 yt){let f=null;if(e.isDisposedInternal)throw new Error("input error: attempted to use tensor but it is disposed");if(!e.shape)throw new Error("input error: attempted to use tensor without a shape");if(e.shape.length===3){if(e.shape[2]===3)f=Bt(e,0);else if(e.shape[2]===4){let g=Qp(e,[0,0,0],[-1,-1,3]);f=Bt(g,0),J(g)}}else e.shape.length===4&&(e.shape[3]===3?f=Ia(e):e.shape[3]===4&&(f=Kh(e,[0,0,0,0],[-1,-1,-1,3])));if(f==null||f.shape.length!==4||f.shape[0]!==1||f.shape[3]!==3)throw new Error(`input error: attempted to use tensor with unrecognized shape: ${e.shape.toString()}`);if(f.dtype==="int32"){let g=Ue(f,"float32");J(f),f=g}return{tensor:f,canvas:t.filter.return?ra:null}}if(typeof e.readyState!="undefined"&&e.readyState<=2)return t.debug&&K("input stream is not ready"),{tensor:null,canvas:na};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:na};let s=n,i=r;if(s>v0&&(s=v0,i=Math.trunc(s*r/n)),i>v0&&(i=v0,s=Math.trunc(i*n/r)),(((p=t.filter)==null?void 0:p.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");(!na||na.width!==s||na.height!==i)&&(na=Dn(s,i));let o=na.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,na.width,na.height),o.setTransform(1,0,0,1,0,0)):o.drawImage(e,0,0,n,r,0,0,na.width,na.height),(!ra||na.width!==ra.width||na.height!==ra.height)&&(ra=Dn(na.width,na.height)),t.filter.enabled&&ne.webgl.supported?(vt||(vt=ne.browser?new j9:null),ne.filter=!!vt,vt!=null&&vt.add?(vt.reset(),t.filter.brightness!==0&&vt.add("brightness",t.filter.brightness),t.filter.contrast!==0&&vt.add("contrast",t.filter.contrast),t.filter.sharpness!==0&&vt.add("sharpen",t.filter.sharpness),t.filter.blur!==0&&vt.add("blur",t.filter.blur),t.filter.saturation!==0&&vt.add("saturation",t.filter.saturation),t.filter.hue!==0&&vt.add("hue",t.filter.hue),t.filter.negative&&vt.add("negative"),t.filter.sepia&&vt.add("sepia"),t.filter.vintage&&vt.add("brownie"),t.filter.sepia&&vt.add("sepia"),t.filter.kodachrome&&vt.add("kodachrome"),t.filter.technicolor&&vt.add("technicolor"),t.filter.polaroid&&vt.add("polaroid"),t.filter.pixelate!==0&&vt.add("pixelate",t.filter.pixelate),((m=vt.get())==null?void 0:m.length)>1?ra=vt.apply(na):ra=vt.draw(na)):(t.debug&&K("input process error: cannot initialize filters"),ne.webgl.supported=!1,t.filter.enabled=!1,w0(na,ra))):(w0(na,ra),vt&&(vt=null),ne.filter=!!vt),!a)return{tensor:null,canvas:ra};if(!ra)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&&Pr)l=Pr?Pr.fromPixels(e):null;else{u=e.data.length/e.height/e.width;let f=new Uint8Array(e.data.buffer);l=Ve(f,[e.height,e.width,u],"int32")}else if((!ld||ra.width!==ld.width||ra.height!==ld.height)&&(ld=Dn(ra.width,ra.height)),Pr&&ne.browser)t.backend==="webgl"||t.backend==="humangl"||t.backend==="webgpu"?l=Pr.fromPixels(ra):(ld=w0(ra),l=Pr.fromPixels(ld));else{let y=w0(ra).getContext("2d").getImageData(0,0,s,i);u=y.data.length/s/i;let x=new Uint8Array(y.data.buffer);l=Ve(x,[s,i,u])}if(u===4){let f=Qp(l,[0,0,0],[-1,-1,3]);J(l),l=f}if(!l)throw new Error("input error: cannot create tensor");let d=Ue(l,"float32"),c=t.filter.equalization?await b0(d):Bt(d,0);if(J([l,d]),t.filter.autoBrightness){let f=fa(c),g=await f.data();t.filter.brightness=g[0]>1?1-g[0]/255:1-g[0],J(f)}return{tensor:c,canvas:t.filter.return?ra:null}}async function q9(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(!wn.inputTensor)wn.inputTensor=Ia(t);else if(wn.inputTensor.shape[1]!==t.shape[1]||wn.inputTensor.shape[2]!==t.shape[2])J(wn.inputTensor),wn.inputTensor=Ia(t);else{let n={};n.diff=xe(t,wn.inputTensor),n.squared=te(n.diff,n.diff),n.sum=ot(n.squared);let s=(await n.sum.data())[0]/(t.shape[1]||1)/(t.shape[2]||1)/255/3;J([wn.inputTensor,n.diff,n.squared,n.sum]),wn.inputTensor=Ia(t),a=s<=(e.cacheSensitivity||0)}return a}async function X9(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=Ia(t),n.input2=t.shape[1]!==a.shape[1]||t.shape[2]!==a.shape[2]?fe.resizeBilinear(a,[t.shape[1],t.shape[2]]):Ia(a),n.diff=xe(n.input1,n.input2),n.squared=te(n.diff,n.diff),n.sum=ot(n.squared);let s=(await n.sum.data())[0]/(t.shape[1]||1)/(t.shape[2]||1)/255/3;return J([n.input1,n.input2,n.diff,n.squared,n.sum]),s}var dc,pc,cc,uc=class{constructor(){he(this,"browser");he(this,"node");he(this,"worker");he(this,"platform","");he(this,"agent","");he(this,"backends",[]);he(this,"initial");he(this,"filter");he(this,"tfjs");he(this,"offscreen");he(this,"perfadd",!1);he(this,"tensorflow",{version:void 0,gpu:void 0});he(this,"wasm",{supported:void 0,backend:void 0,simd:void 0,multithread:void 0});he(this,"webgl",{supported:void 0,backend:void 0,version:void 0,renderer:void 0,shader:void 0,vendor:void 0});he(this,"webgpu",{supported:void 0,backend:void 0,adapter:void 0});he(this,"cpu",{model:void 0,flags:[]});he(this,"kernels",[]);Yn(this,dc,void 0);Yn(this,pc,void 0);Yn(this,cc,void 0);if(this.browser=typeof navigator!="undefined"&&typeof navigator.appVersion!="undefined",this.node=typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined",this.tfjs={version:lc["tfjs-core"]},this.offscreen=typeof OffscreenCanvas!="undefined",this.initial=!0,this.worker=this.browser&&this.offscreen?typeof WorkerGlobalScope!="undefined":void 0,typeof navigator!="undefined"&&typeof navigator.userAgent!="undefined"){let t=navigator.userAgent||"",a=t.match(/\(([^()]+)\)/g);if(a!=null&&a[0]){let n=a[0].match(/\(([^()]+)\)/g);this.platform=n!=null&&n[0]?n[0].replace(/\(|\)/g,""):"",this.agent=t.replace(a[0],""),this.platform[1]&&(this.agent=this.agent.replace(a[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 Xa(this,dc)}set Canvas(t){wr(this,dc,t),globalThis.Canvas=t}get Image(){return Xa(this,pc)}set Image(t){wr(this,pc,t),globalThis.Image=t}get ImageData(){return Xa(this,cc)}set ImageData(t){wr(this,cc,t),globalThis.ImageData=t}async updateBackend(){this.backends=Object.keys(St().registryFactory);try{this.tensorflow={version:Gn().binding?Gn().binding.TF_Version:void 0,gpu:Gn().binding?Gn().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 B().getAsync("WASM_HAS_SIMD_SUPPORT"),this.wasm.multithread=await B().getAsync("WASM_HAS_MULTITHREAD_SUPPORT"));let t=Dn(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!="undefined"&&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=tr(ea()).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})}};dc=new WeakMap,pc=new WeakMap,cc=new WeakMap;var ne=new uc;var S0=class{constructor(){he(this,"config");he(this,"element");he(this,"stream");he(this,"devices",[]);he(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});he(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 return this.config.debug&&K("webcam","cannot get dom element",t.element),`webcam error: cannot get dom element: ${t.element}`}else if(t.element instanceof HTMLVideoElement)this.element=t.element;else return this.config.debug&&K("webcam","unknown dom element",t.element),`webcam error: unknown dom element: ${t.element}`;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))return this.config.debug&&K("webcam error","no devices"),"webcam error: no devices";try{this.stream=await navigator.mediaDevices.getUserMedia(a)}catch(i){return K("webcam",i),`webcam error: ${i}`}return this.stream?(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}),`webcam: ${this.label}`):(this.config.debug&&K("webcam error","no stream"),"webcam error no stream")});he(this,"pause",()=>{this.element&&this.element.pause()});he(this,"play",async()=>{this.element&&await this.element.play()});he(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 gy={};vr(gy,{"affectnet-mobilenet":()=>Lge,age:()=>Wge,"anti-spoofing":()=>x3e,antispoof:()=>Cge,blazeface:()=>Nge,"blazeface-back":()=>Bge,"blazeface-front":()=>Vge,"blazepose-detector":()=>Uge,"blazepose-full":()=>Gge,"blazepose-heavy":()=>Hge,"blazepose-lite":()=>jge,centernet:()=>Rge,default:()=>M3e,efficientpose:()=>qge,"efficientpose-i-lite":()=>A3e,"efficientpose-ii-lite":()=>b3e,"efficientpose-iv":()=>v3e,emotion:()=>Ege,faceboxes:()=>Xge,facemesh:()=>Mge,"facemesh-attention":()=>Yge,"facemesh-attention-pinto":()=>Kge,"facemesh-detection-full":()=>Zge,"facemesh-detection-short":()=>Jge,faceres:()=>Fge,"faceres-deep":()=>Qge,gear:()=>a3e,"gear-e1":()=>e3e,"gear-e2":()=>t3e,gender:()=>r3e,"gender-ssrnet-imdb":()=>n3e,handdetect:()=>s3e,"handlandmark-full":()=>i3e,"handlandmark-lite":()=>$ge,"handlandmark-sparse":()=>o3e,handskeleton:()=>l3e,handtrack:()=>Dge,"insightface-efficientnet-b0":()=>w3e,"insightface-ghostnet-strides1":()=>k3e,"insightface-ghostnet-strides2":()=>I3e,"insightface-mobilenet-emore":()=>S3e,"insightface-mobilenet-swish":()=>T3e,iris:()=>Pge,liveness:()=>_ge,meet:()=>u3e,mobileface:()=>d3e,mobilefacenet:()=>p3e,models:()=>Oge,"movenet-lightning":()=>zge,"movenet-multipose":()=>c3e,"movenet-thunder":()=>h3e,nanodet:()=>m3e,"nanodet-e":()=>C3e,"nanodet-g":()=>N3e,"nanodet-m":()=>R3e,"nanodet-t":()=>E3e,posenet:()=>f3e,rvm:()=>g3e,selfie:()=>y3e});var Cge=853098,Nge=538928,Rge=4030290,Ege=820516,Mge=1477958,Fge=6978814,$ge=2023432,Dge=2964837,Pge=2599092,_ge=592976,Oge=0,zge=4650216,Lge=6920630,Wge=161240,Bge=538928,Vge=402048,Uge=5928856,Gge=6339202,Hge=27502466,jge=2726402,qge=5651240,Xge=2013002,Kge=2387598,Yge=2382414,Zge=1026192,Jge=201268,Qge=13957620,e3e=112438,t3e=112438,a3e=1498916,n3e=161236,r3e=201808,s3e=3515612,i3e=5431368,o3e=5286322,l3e=5502280,u3e=372228,d3e=2183192,p3e=5171976,c3e=9448838,h3e=12477112,m3e=7574558,f3e=5032780,g3e=3739355,y3e=212886,x3e=853098,A3e=2269064,b3e=5651240,v3e=25643252,w3e=13013224,k3e=8093408,I3e=8049584,S3e=6938536,T3e=12168584,C3e=12319156,N3e=7574558,R3e=1887474,E3e=5294216,M3e={antispoof:Cge,blazeface:Nge,centernet:Rge,emotion:Ege,facemesh:Mge,faceres:Fge,"handlandmark-lite":$ge,handtrack:Dge,iris:Pge,liveness:_ge,models:Oge,"movenet-lightning":zge,"affectnet-mobilenet":Lge,age:Wge,"blazeface-back":Bge,"blazeface-front":Vge,"blazepose-detector":Uge,"blazepose-full":Gge,"blazepose-heavy":Hge,"blazepose-lite":jge,efficientpose:qge,faceboxes:Xge,"facemesh-attention-pinto":Kge,"facemesh-attention":Yge,"facemesh-detection-full":Zge,"facemesh-detection-short":Jge,"faceres-deep":Qge,"gear-e1":e3e,"gear-e2":t3e,gear:a3e,"gender-ssrnet-imdb":n3e,gender:r3e,handdetect:s3e,"handlandmark-full":i3e,"handlandmark-sparse":o3e,handskeleton:l3e,meet:u3e,mobileface:d3e,mobilefacenet:p3e,"movenet-multipose":c3e,"movenet-thunder":h3e,nanodet:m3e,posenet:f3e,rvm:g3e,selfie:y3e,"anti-spoofing":x3e,"efficientpose-i-lite":A3e,"efficientpose-ii-lite":b3e,"efficientpose-iv":v3e,"insightface-efficientnet-b0":w3e,"insightface-ghostnet-strides1":k3e,"insightface-ghostnet-strides2":I3e,"insightface-mobilenet-emore":S3e,"insightface-mobilenet-swish":T3e,"nanodet-e":C3e,"nanodet-g":N3e,"nanodet-m":R3e,"nanodet-t":E3e};var Ea={cacheModels:!0,cacheSupported:!0,verbose:!0,debug:!1,modelBasePath:""},ya={};async function F3e(e,t){return Ea.debug&&K("load model fetch:",e,t),fetch(e,t)}function K9(e){Ea.cacheModels=e.cacheModels,Ea.verbose=e.debug,Ea.modelBasePath=e.modelBasePath}async function $e(e){var u,d,c,p;let t=L9(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;ya[n]={name:n,sizeFromManifest:0,sizeLoadedWeights:0,sizeDesired:gy[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}ya[n].inCache=Ea.cacheSupported&&Ea.cacheModels&&Object.keys(s).includes(r),ya[n].url=ya[n].inCache?r:t;let i=typeof fetch=="undefined"?{}:{fetchFunc:(h,m)=>F3e(h,m)},o=new ec(ya[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;ya[n].sizeFromManifest=((d=h==null?void 0:h.weightData)==null?void 0:d.byteLength)||0,h?o.loadSync(h):o=await x3(ya[n].inCache?r:t,i),ya[n].sizeLoadedWeights=((p=(c=o.artifacts)==null?void 0:c.weightData)==null?void 0:p.byteLength)||0,Ea.verbose&&K("load:",{model:n,url:o.modelUrl,bytes:ya[n].sizeLoadedWeights}),l=!0}catch(h){K("error loading model:",t,h)}if(l&&Ea.cacheModels&&Ea.cacheSupported&&!ya[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 yy="3.2.1";var Tt={name:"humangl",priority:999,canvas:null,gl:null,extensions:[],webGLattr:{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!1,desynchronized:!0}};function P3e(){let e=Tt.gl;e&&(Tt.extensions=e.getSupportedExtensions())}function Y9(e){var t;if(e.config.backend==="humangl"&&(Tt.name in St().registry&&!((t=Tt==null?void 0:Tt.gl)!=null&&t.getParameter(Tt.gl.VERSION))&&(K("humangl error: backend invalid context"),e.models.reset()),!gg(Tt.name))){try{Tt.canvas=Dn(100,100)}catch(r){K("humangl error: cannot create canvas:",r);return}try{if(Tt.gl=Tt.canvas.getContext("webgl2",Tt.webGLattr),!Tt.gl){K("humangl error: cannot get webgl context");return}if(!Tt.gl.getParameter(Tt.gl.VERSION).includes("2.0")){K("backend override: using fallback webgl backend as webgl 2.0 is not detected"),e.config.backend="webgl";return}Tt.canvas&&(Tt.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")}),Tt.canvas.addEventListener("webglcontextrestored",s=>{K("humangl error: context restored:",s)}),Tt.canvas.addEventListener("webglcontextcreationerror",s=>{K("humangl error: context create:",s)}))}catch(r){K("humangl error: cannot get webgl context:",r);return}try{u0(2,Tt.gl)}catch(r){K("humangl error: cannot set webgl context:",r);return}try{let r=new Yl(Tt.gl);ll(Tt.name,()=>new rc(r),Tt.priority)}catch(r){K("humangl error: cannot register webgl backend:",r);return}try{tr("webgl").forEach(s=>{let i={...s,backendName:Tt.name};bn(i)})}catch(r){K("humangl error: cannot update webgl backend registration:",r);return}try{B().flagRegistry.WEBGL_VERSION&&B().set("WEBGL_VERSION",2)}catch(r){K("humangl error: cannot set WebGL backend flags:",r);return}P3e();let a=Gn(),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,Tt.gl)}}var ze={tf255:255,tf1:1,tf2:2,tf05:.5,tf127:127.5,rgb:[.2989,.587,.114]};function Z9(){ze.tf255=Ge(255,"float32"),ze.tf1=Ge(1,"float32"),ze.tf2=Ge(2,"float32"),ze.tf05=Ge(.5,"float32"),ze.tf127=Ge(127.5,"float32"),ze.rgb=Vt([.2989,.587,.114],"float32")}async function z3e(){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 L3e(e){let t=[];if(!ne.kernels.includes("mod")){let a={kernelName:"Mod",backendName:ea(),kernelFunc:n=>Pe(()=>xe(n.inputs.a,te(ve(n.inputs.a,n.inputs.b),n.inputs.b)))};bn(a),ne.kernels.push("mod"),t.push("mod")}if(!ne.kernels.includes("floormod")){let a={kernelName:"FloorMod",backendName:ea(),kernelFunc:n=>Pe(()=>we(te(Gp(n.inputs.a,n.inputs.b),n.inputs.b),Ku(n.inputs.a,n.inputs.b)))};bn(a),ne.kernels.push("floormod"),t.push("floormod")}if(!ne.kernels.includes("rotatewithoffset")&&e.softwareKernels){let a={kernelName:"RotateWithOffset",backendName:ea(),kernelFunc:n=>Pe(()=>{let r=ea();Bp("cpu");let s=fe.rotateWithOffset(n.inputs.image,n.attrs.radians,n.attrs.fillValue,n.attrs.center);return Bp(r),s})};bn(a),ne.kernels.push("rotatewithoffset"),t.push("rotatewithoffset")}t.length>0&&e.debug&&K("registered kernels:",t)}var J9={};async function hc(e,t=!1){var a,n;if(e.state="backend",((a=e.config.backend)==null?void 0:a.length)===0&&(e.config.backend=await z3e()),t||ne.initial||e.config.backend&&e.config.backend.length>0&&ea()!==e.config.backend){let r=ae();if(e.config.backend&&e.config.backend.length>0){typeof window=="undefined"&&typeof WorkerGlobalScope!="undefined"&&e.config.debug&&e.config.debug&&K("running inside web worker"),typeof navigator!="undefined"&&((n=navigator==null?void 0:navigator.userAgent)!=null&&n.toLowerCase().includes("electron"))&&e.config.debug&&K("running inside electron");let s=Object.keys(St().registryFactory);if(e.config.backend==="humangl"&&!s.includes("humangl")&&(Y9(e),s=Object.keys(St().registryFactory)),e.config.debug&&K("available backends:",s),ne.browser&&!ne.node&&e.config.backend==="tensorflow"&&s.includes("webgl")&&(e.config.debug&&K("override: backend set to tensorflow while running in browser"),e.config.backend="webgl"),ne.node&&!ne.browser&&(e.config.backend==="webgl"||e.config.backend==="humangl")&&s.includes("tensorflow")&&(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 i=await navigator.gpu.requestAdapter();if(e.config.debug&&K("enumerated webgpu adapter:",i),!i)K("override: backend set to webgpu but browser reports no available gpu"),e.config.backend="webgl";else{let o="requestAdapterInfo"in i?await i.requestAdapterInfo():void 0;K("webgpu adapter info:",o)}}if(s.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(B().flagRegistry.CANVAS2D_WILL_READ_FREQUENTLY&&B().set("CANVAS2D_WILL_READ_FREQUENTLY",!0),e.config.debug&&K("wasm path:",e.config.wasmPath),typeof f0!="undefined")f0(e.config.wasmPath,e.config.wasmPlatformFetch);else throw new Error("backend error: attempting to use wasm backend but wasm path is not set");let i=!1,o=!1;try{i=await B().getAsync("WASM_HAS_MULTITHREAD_SUPPORT"),o=await B().getAsync("WASM_HAS_SIMD_SUPPORT"),e.config.debug&&K(`wasm execution: ${o?"simd":"no simd"} ${i?"multithreaded":"singlethreaded"}`),e.config.debug&&!o&&K("warning: wasm simd support is not enabled")}catch(l){K("wasm detection failed")}}try{await Bp(e.config.backend),await Vp()}catch(i){return K("error: cannot set backend:",e.config.backend,i),!1}e.config.debug&&(J9=JSON.parse(JSON.stringify(B().flags)))}if((ea()==="humangl"||ea()==="webgl")&&(B().flagRegistry.WEBGL_USE_SHAPES_UNIFORMS&&B().set("WEBGL_USE_SHAPES_UNIFORMS",!0),B().flagRegistry.WEBGL_EXP_CONV&&B().set("WEBGL_EXP_CONV",!0),e.config.debug&&typeof e.config.deallocate!="undefined"&&e.config.deallocate&&(K("changing webgl: WEBGL_DELETE_TEXTURE_THRESHOLD:",!0),B().set("WEBGL_DELETE_TEXTURE_THRESHOLD",0))),ea(),e.config.debug){let s=B().flags,i={};for(let o of Object.keys(s))J9[o]!==s[o]&&(i[o]=s[o]);e.config.debug&&Object.keys(i).length>0&&K("backend:",ea(),"flags:",i)}if(e.config.flags&&Object.keys(e.config.flags).length>0){e.config.debug&&K("flags:",e.config.flags);for(let[s,i]of Object.entries(e.config.flags))B().set(s,i)}mg(),Z9(),e.performance.initBackend=Math.trunc(ae()-r),e.config.backend=ea(),await ne.updateBackend(),L3e(e.config)}return!0}function T0(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}};bn(n)}ne.kernels=tr(ea()).map(a=>a.kernelName.toLowerCase())}var F0={};vr(F0,{all:()=>gye,body:()=>N0,canvas:()=>fye,face:()=>C0,gesture:()=>M0,hand:()=>R0,init:()=>Iy,object:()=>E0,options:()=>_t,person:()=>mye});var kn=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",{willReadFrequently:!0});if(!t)K("draw error: cannot get canvas context");else return t}return null},xl=e=>Math.round(e*180/Math.PI),ut=(e,t,a)=>e.replace(t,typeof a=="number"?a.toFixed(1):a),Al=(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 In(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 cr(e,t,a,n,r){e.fillStyle=Al(n,r),e.beginPath(),e.arc(t,a,r.pointSize,0,2*Math.PI),e.fill()}function hr(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 xy(e,t,a){if(!(t.length<2)){e.beginPath(),e.moveTo(t[0][0],t[0][1]);for(let n of t)e.strokeStyle=Al(n[2]||0,a),e.lineTo(Math.trunc(n[0]),Math.trunc(n[1]));e.stroke(),a.fillPolygons&&(e.closePath(),e.fill())}}function eI(e,t,a){if(!(t.length<2)){if(e.lineWidth=a.lineWidth,!a.useCurves||t.length<=2){xy(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 Ay(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 Pn={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]},by={count:468,mouth:13,symmetryLine:[13,Pn.midwayBetweenEyes[0]]},bl={leftEye:0,rightEye:1,nose:2,mouth:3,leftEar:4,rightEar:5,symmetryLine:[3,2]},vy=[{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]}],mc=[[.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]],vl=[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 W3e=[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],B3e=[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],V3e=[33,133,362,263,1,78,308],z7e=W3e.map(e=>mc[e]),L7e=B3e.map(e=>mc[e]),W7e=V3e.map(e=>mc[e]);function Us(e){let t=e.map(a=>a[0]);return t.push(e[e.length-1][1]),t}var U3e=[[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]],G3e=[[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]],H3e=[[276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]],j3e=[[474,475],[475,476],[476,477],[477,474]],q3e=[[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]],X3e=[[46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]],K3e=[[469,470],[470,471],[471,472],[472,469]],Y3e=[[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]],B7e={lips:Us(U3e),leftEye:Us(G3e),leftEyebrow:Us(H3e),leftIris:Us(j3e),rightEye:Us(q3e),rightEyebrow:Us(X3e),rightIris:Us(K3e),faceOval:Us(Y3e)};var Z3e=[[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]],J3e=[[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]],Q3e=[[276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]],eye=[[474,475],[475,476],[476,477],[477,474]],tye=[[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]],aye=[[46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]],nye=[[469,470],[470,471],[471,472],[472,469]],rye=[[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 Gs(e){let t=e.map(a=>a[0]);return t.push(e[e.length-1][1]),t}var sye={lips:Gs(Z3e),leftEye:Gs(J3e),leftEyebrow:Gs(Q3e),leftIris:Gs(eye),rightEye:Gs(tye),rightEyebrow:Gs(aye),rightIris:Gs(nye),faceOval:Gs(rye)},iye=Object.entries(sye).map(([e,t])=>t.map(a=>[a,e])).flat(),V7e=new Map(iye),fc=[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],wl=[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],kl=[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 rt;function oye(e,t){var n,r,s,i,o,l,u,d,c;if(!rt.drawLabels||((n=rt.faceLabels)==null?void 0:n.length)===0)return;let a=rt.faceLabels.slice();if(a=ut(a,"[id]",e.id.toFixed(0)),e.score&&(a=ut(a,"[score]",100*e.score)),e.gender&&(a=ut(a,"[gender]",e.gender)),e.genderScore&&(a=ut(a,"[genderScore]",100*e.genderScore)),e.age&&(a=ut(a,"[age]",e.age)),e.distance&&(a=ut(a,"[distance]",100*e.distance)),e.real&&(a=ut(a,"[real]",100*e.real)),e.live&&(a=ut(a,"[live]",100*e.live)),e.emotion&&e.emotion.length>0){let p=e.emotion.map(h=>`${Math.trunc(100*h.score)}% ${h.emotion}`);p.length>3&&(p.length=3),a=ut(a,"[emotions]",p.join(" "))}(s=(r=e.rotation)==null?void 0:r.angle)!=null&&s.roll&&(a=ut(a,"[roll]",xl(e.rotation.angle.roll))),(o=(i=e.rotation)==null?void 0:i.angle)!=null&&o.yaw&&(a=ut(a,"[yaw]",xl(e.rotation.angle.yaw))),(u=(l=e.rotation)==null?void 0:l.angle)!=null&&u.pitch&&(a=ut(a,"[pitch]",xl(e.rotation.angle.pitch))),(c=(d=e.rotation)==null?void 0:d.gaze)!=null&&c.bearing&&(a=ut(a,"[gaze]",xl(e.rotation.gaze.bearing))),In(t,a,e.box[0],e.box[1],rt)}function lye(e,t){var a,n,r,s;if((a=e.annotations)!=null&&a.leftEyeIris&&((n=e.annotations)!=null&&n.leftEyeIris[0])){t.strokeStyle=rt.useDepth?"rgba(255, 200, 255, 0.3)":rt.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(),rt.fillPolygons&&(t.fillStyle=rt.useDepth?"rgba(255, 255, 200, 0.3)":rt.color,t.fill())}if((r=e.annotations)!=null&&r.rightEyeIris&&((s=e.annotations)!=null&&s.rightEyeIris[0])){t.strokeStyle=rt.useDepth?"rgba(255, 200, 255, 0.3)":rt.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(),rt.fillPolygons&&(t.fillStyle=rt.useDepth?"rgba(255, 255, 200, 0.3)":rt.color,t.fill())}}function uye(e,t){var a;if(rt.drawGaze&&((a=e.rotation)!=null&&a.angle)&&typeof Path2D!="undefined"){t.strokeStyle="pink";let n=e.box[0]+e.box[2]/2-e.box[3]*xl(e.rotation.angle.yaw)/90,r=e.box[1]+e.box[3]/2+e.box[2]*xl(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 dye(e,t){var a;if(rt.drawGaze&&((a=e.rotation)!=null&&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]];Ay(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]];Ay(t,[e.annotations.rightEyeIris[0][0],e.annotations.rightEyeIris[0][1]],[r[0],r[1]],4)}}function pye(e,t){if(rt.drawPolygons&&e.mesh.length>=468){t.lineWidth=1;for(let a=0;a<vl.length/3;a++){let n=[vl[a*3+0],vl[a*3+1],vl[a*3+2]].map(r=>e.mesh[r]);xy(t,n,rt)}lye(e,t)}}function cye(e,t){if(rt.drawPoints)if((e==null?void 0:e.mesh.length)>=468)for(let a=0;a<e.mesh.length;a++)cr(t,e.mesh[a][0],e.mesh[a][1],e.mesh[a][2],rt),rt.drawAttention&&(fc.includes(a)&&cr(t,e.mesh[a][0],e.mesh[a][1],e.mesh[a][2]+127,rt),wl.includes(a)&&cr(t,e.mesh[a][0],e.mesh[a][1],e.mesh[a][2]-127,rt),kl.includes(a)&&cr(t,e.mesh[a][0],e.mesh[a][1],e.mesh[a][2]-127,rt));else for(let[a,n]of Object.entries((e==null?void 0:e.annotations)||{})){if(!(n!=null&&n[0]))continue;let r=n[0];cr(t,r[0],r[1],0,rt),rt.drawLabels&&In(t,a,r[0],r[1],rt)}}function hye(e,t){rt.drawBoxes&&hr(t,e.box[0],e.box[1],e.box[2],e.box[3],rt)}function C0(e,t,a){if(rt=Mt(_t,a),!t||!e)return;let n=kn(e);if(n){n.font=rt.font,n.strokeStyle=rt.color,n.fillStyle=rt.color;for(let r of t)hye(r,n),oye(r,n),r.mesh&&r.mesh.length>0&&(cye(r,n),pye(r,n),uye(r,n),dye(r,n))}}function N0(e,t,a){var s,i;let n=Mt(_t,a);if(!t||!e)return;let r=kn(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&&(hr(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=ut(l,"[id]",t[o].id.toFixed(0)),l=ut(l,"[score]",100*t[o].score),In(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=Al(t[o].keypoints[l].position[2],n),cr(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=ut(u,"[label]",l.part),u=ut(u,"[score]",100*l.score),In(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)eI(r,u,n)}}}function R0(e,t,a){var s,i;let n=Mt(_t,a);if(!t||!e)return;let r=kn(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,hr(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=ut(l,"[id]",o.id.toFixed(0)),l=ut(l,"[label]",o.label),l=ut(l,"[score]",100*o.score),In(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=Al(l[2],n),cr(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 d=n.fingerLabels.slice();d=ut(d,"[label]",l),In(r,d,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 d=0;d<u.length;d++){r.beginPath();let c=u[d][2]||0;r.strokeStyle=Al(d*c,n),r.moveTo(u[d>0?d-1:0][0],u[d>0?d-1:0][1]),r.lineTo(u[d][0],u[d][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 E0(e,t,a){var s;let n=Mt(_t,a);if(!t||!e)return;let r=kn(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,hr(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=ut(o,"[id]",i.id.toFixed(0)),o=ut(o,"[label]",i.label),o=ut(o,"[score]",100*i.score),In(r,o,i.box[0],i.box[1],n)}r.stroke()}}}function M0(e,t,a){var r;let n=Mt(_t,a);if(!(!t||!e)&&n.drawGestures&&((r=n.gestureLabels)==null?void 0:r.length)>0){let s=kn(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 d=l[1]>0?`#${l[1]}`:"",c=n.gestureLabels.slice();c=ut(c,"[where]",l[0]),c=ut(c,"[who]",d),c=ut(c,"[what]",u[1]),In(s,c,8,2+i*n.lineHeight,n),i+=1}}}}var Hs={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 ky=0;function mye(e,t,a){let n=Mt(_t,a);if(!t||!e)return;let r=kn(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,hr(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 fye(e,t){if(!e||!t)return;let a=kn(t);a&&a.drawImage(e,0,0)}async function gye(e,t,a){if(!(t!=null&&t.performance)||!e)return null;let n=ae(),r=Mt(_t,a),s=Promise.all([C0(e,t.face,r),N0(e,t.body,r),R0(e,t.hand,r),E0(e,t.object,r),M0(e,t.gesture,r)]);return ky=ne.perfadd?ky+Math.round(ae()-n):Math.round(ae()-n),t.performance.draw=ky,s}function Iy(){_t.faceLabels=Hs.face,_t.bodyLabels=Hs.body,_t.bodyPartLabels=Hs.bodyPart,_t.handLabels=Hs.hand,_t.fingerLabels=Hs.finger,_t.objectLabels=Hs.object,_t.gestureLabels=Hs.gesture}var $0={};vr($0,{connected:()=>Ty,kpt:()=>Sy});var Sy=["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"],Ty={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 Sn,Il=224,nI,yye=5,D0=[8,16,32,32,32];function xye(){let e=[],t=0;for(;t<yye;){let a=0,n=t;for(;n<D0.length&&D0[n]===D0[t];)a+=2,n++;let r=D0[t],s=Math.ceil(Il/r),i=Math.ceil(Il/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}nI={x:Vt(e.map(a=>a.x)),y:Vt(e.map(a=>a.y))}}async function rI(e){if(ne.initial&&(Sn=null),!Sn&&e.body.detector&&e.body.detector.modelPath){Sn=await $e(e.body.detector.modelPath);let t=Sn!=null&&Sn.executor?Object.values(Sn.modelSignature.inputs):void 0;Il=Array.isArray(t)?parseInt(t[0].tensorShape.dim[1].size):0}else e.debug&&Sn&&K("cached model:",Sn.modelUrl);return xye(),Sn}var aI=[5,5];function Aye(e,t){return Pe(()=>{let a=Sa(e,12,1),n=Oe(a[0]),r=Oe(a[1]),s=Oe(a[2]),i=Oe(a[3]);n=we(ve(n,Il),t.x),r=we(ve(r,Il),t.y),s=te(ve(s,Il),aI[0]),i=te(ve(i,Il),aI[1]);let o=xe(n,ve(s,2)),l=xe(r,ve(i,2)),u=we(o,s),d=we(l,i);return ca([o,l,u,d],1)})}async function bye(e,t,a,n){var u,d;let r=[],s={};s.boxes=Aye(e,nI),s.scores=za(t),s.nms=await fe.nonMaxSuppressionAsync(s.boxes,s.scores,1,((u=a.body.detector)==null?void 0:u.minConfidence)||.1,((d=a.body.detector)==null?void 0:d.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 p=o[c],h=l[c],m=[Math.round(h[0]*n[0]),Math.round(h[1]*n[1]),Math.round(h[2]*n[0]),Math.round(h[3]*n[1])],f={score:p,boxRaw:h,box:m};r.push(f)}return Object.keys(s).forEach(c=>J(s[c])),r}async function sI(e,t,a){let n={};n.res=Sn==null?void 0:Sn.execute(e,["Identity"]),n.logitsRaw=_e(n.res,[0,0,0],[1,-1,1]),n.boxesRaw=_e(n.res,[0,0,1],[1,-1,-1]),n.logits=Oe(n.logitsRaw),n.boxes=Oe(n.boxesRaw);let r=await bye(n.boxes,n.logits,t,a);return Object.keys(n).forEach(s=>J(n[s])),r}function js(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 iI(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 P0(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 Ga,Ny=256,Cy=Number.MAX_SAFE_INTEGER,vye={landmarks:["ld_3d","activation_segmentation","activation_heatmap","world_3d","output_poseflag"],detector:[]},O0=[],qs=[[0,0],[0,0],[0,0],[0,0]],oI=0,lI=e=>1-1/(1+Math.exp(e)),dI=e=>rI(e);async function pI(e){if(ne.initial&&(Ga=null),Ga)e.debug&&K("cached model:",Ga.modelUrl);else{Ga=await $e(e.body.modelPath);let t=Ga!=null&&Ga.executor?Object.values(Ga.modelSignature.inputs):void 0;Ny=Array.isArray(t)?parseInt(t[0].tensorShape.dim[1].size):0}return Ga}function uI(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=fe.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];qs=[[0,0],o,l,[0,0]],n.pad=ur(n.cropped||e,qs),n.resize=fe.resizeBilinear(n.pad,[t,t]),r=ve(n.resize,ze.tf255)}else e.shape[1]!==t?(n.resize=fe.resizeBilinear(n.cropped||e,[t,t]),r=ve(n.resize,ze.tf255)):r=ve(n.cropped||e,ze.tf255);return Object.keys(n).forEach(o=>J(n[o])),r}function wye(e,t,a){for(let n of e)n.position=[Math.trunc(n.position[0]*(t[0]+qs[2][0]+qs[2][1])/t[0]-qs[2][0]),Math.trunc(n.position[1]*(t[1]+qs[1][0]+qs[1][1])/t[1]-qs[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 kye(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 Iye(e,t,a){if(!(Ga!=null&&Ga.executor))return null;let n={};[n.ld,n.segmentation,n.heatmap,n.world,n.poseflag]=Ga==null?void 0:Ga.execute(e,vye.landmarks);let r=(await n.poseflag.data())[0],s=await n.ld.data(),i=await n.world.data();Object.keys(n).forEach(m=>J(n[m]));let o=[],l=5;for(let m=0;m<s.length/l;m++){let f=lI(s[l*m+3]),g=lI(s[l*m+4]),y=Math.trunc(100*f*g*r)/100,x=[s[l*m+0]/Ny,s[l*m+1]/Ny,s[l*m+2]+0],A=[Math.trunc(a[0]*x[0]),Math.trunc(a[1]*x[1]),x[2]],b=[i[l*m+0],i[l*m+1],i[l*m+2]+0];o.push({part:Sy[m],positionRaw:x,position:A,distance:b,score:y})}if(r<(t.body.minConfidence||0))return null;kye(o);let u=wye(o,a),d=u.map(m=>m.position),c=js(d,[a[0],a[1]]),p={};for(let[m,f]of Object.entries(Ty)){let g=[];for(let y=0;y<f.length-1;y++){let x=u.find(b=>b.part===f[y]),A=u.find(b=>b.part===f[y+1]);x&&A&&g.push([x.position,A.position])}p[m]=g}return{id:0,score:Math.trunc(100*r)/100,box:c.box,boxRaw:c.boxRaw,keypoints:u,annotations:p}}async function Ry(e,t){var s,i,o;let a=[e.shape[2]||0,e.shape[1]||0],n=(t.body.skipTime||0)>ae()-oI,r=Cy<(t.body.skipFrames||0);if(t.skipAllowed&&n&&r&&O0!==null)Cy++;else{let l=[];if((i=(s=t.body)==null?void 0:s.detector)!=null&&i.enabled){let u=uI(e,224);l=await sI(u,t,a),J(u)}else l=[{box:[0,0,0,0],boxRaw:[0,0,1,1],score:0}];for(let u=0;u<l.length;u++){let d=uI(e,256,(o=l[u])==null?void 0:o.boxRaw);O0.length=0;let c=await Iye(d,t,a);J(d),c&&(c.id=u,O0.push(c))}oI=ae(),Cy=0}return O0}var ud=[{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 Ha,Sl=0,Ey=[],hI=0,My=Number.MAX_SAFE_INTEGER;async function mI(e){if(ne.initial&&(Ha=null),Ha)e.debug&&K("cached model:",Ha.modelUrl);else{Ha=await $e(e.object.modelPath);let t=Ha!=null&&Ha.executor?Object.values(Ha.modelSignature.inputs):void 0;Sl=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}return Ha}async function Sye(e,t,a){if(!e)return[];let n={},r=[],s=await e.array();n.squeeze=Oe(e);let i=Sa(n.squeeze,6,1);n.stack=ca([i[1],i[0],i[3],i[2]],1),n.boxes=Oe(n.stack),n.scores=Oe(i[4]),n.classes=Oe(i[5]),J([e,...i]),n.nms=await fe.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 d=Math.trunc(100*s[0][u][4])/100,c=s[0][u][5];if(Number.isNaN(c))continue;let p=ud[c].label,[h,m]=[s[0][u][0]/Sl,s[0][u][1]/Sl],f=[h,m,s[0][u][2]/Sl-h,s[0][u][3]/Sl-m],g=[Math.trunc(f[0]*t[0]),Math.trunc(f[1]*t[1]),Math.trunc(f[2]*t[0]),Math.trunc(f[3]*t[1])];r.push({id:l++,score:d,class:c,label:p,box:g,boxRaw:f})}return Object.keys(n).forEach(u=>J(n[u])),r}async function Fy(e,t){if(!(Ha!=null&&Ha.executor))return[];let a=(t.object.skipTime||0)>ae()-hI,n=My<(t.object.skipFrames||0);return t.skipAllowed&&a&&n&&Ey.length>0?(My++,Ey):(My=0,new Promise(async r=>{let s=[e.shape[2]||0,e.shape[1]||0],i=fe.resizeBilinear(e,[Sl,Sl]),o=t.object.enabled?Ha==null?void 0:Ha.execute(i,["tower_0/detections"]):null;hI=ae(),J(i);let l=await Sye(o,s,t);Ey=l,r(l)}))}var z0={};vr(z0,{connected:()=>Dy,kpt:()=>$y});var $y=["head","neck","rightShoulder","rightElbow","rightWrist","chest","leftShoulder","leftElbow","leftWrist","bodyCenter","rightHip","rightKnee","rightAnkle","leftHip","leftKnee","leftAnkle"],Dy={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var Ft,gI=0,Ma={id:0,keypoints:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,annotations:{}},Py=Number.MAX_SAFE_INTEGER;async function yI(e){return ne.initial&&(Ft=null),Ft?e.debug&&K("cached model:",Ft.modelUrl):Ft=await $e(e.body.modelPath),Ft}async function Tye(e,t){let[a,n]=e.shape,r=Q(e,[n*a]),s=fa(r,0),i=(await s.data())[0];if(i>t){let o=or(r,0),l=Ku(o,a),u=(await l.data())[0],d=ve(o,a),c=(await d.data())[0];return J([r,s,o,l,d]),[u,c,i]}return J([r,s]),[0,0,i]}async function _y(e,t){if(!(Ft!=null&&Ft.executor)||!(Ft!=null&&Ft.inputs[0].shape))return[];let a=(t.body.skipTime||0)>ae()-gI,n=Py<(t.body.skipFrames||0);return t.skipAllowed&&a&&n&&Object.keys(Ma.keypoints).length>0?(Py++,[Ma]):(Py=0,new Promise(async r=>{let s=Pe(()=>{var m,f;let c=fe.resizeBilinear(e,[((m=Ft==null?void 0:Ft.inputs[0].shape)==null?void 0:m[2])||0,((f=Ft==null?void 0:Ft.inputs[0].shape)==null?void 0:f[1])||0],!1),p=te(c,ze.tf2);return xe(p,ze.tf1)}),i;if(t.body.enabled&&(i=Ft==null?void 0:Ft.execute(s)),gI=ae(),J(s),i){Ma.keypoints.length=0;let c=Oe(i);J(i);let p=Na(c,2);J(c);for(let h=0;h<p.length;h++){let[m,f,g]=await Tye(p[h],t.body.minConfidence);g>(t.body.minConfidence||0)&&Ma.keypoints.push({score:Math.round(100*g)/100,part:$y[h],positionRaw:[m/Ft.inputs[0].shape[2],f/Ft.inputs[0].shape[1]],position:[Math.round(e.shape[2]*m/Ft.inputs[0].shape[2]),Math.round(e.shape[1]*f/Ft.inputs[0].shape[1])]})}p.forEach(h=>J(h))}Ma.score=Ma.keypoints.reduce((c,p)=>p.score>c?p.score:c,0);let o=Ma.keypoints.map(c=>c.position[0]),l=Ma.keypoints.map(c=>c.position[1]);Ma.box=[Math.min(...o),Math.min(...l),Math.max(...o)-Math.min(...o),Math.max(...l)-Math.min(...l)];let u=Ma.keypoints.map(c=>c.positionRaw[0]),d=Ma.keypoints.map(c=>c.positionRaw[1]);Ma.boxRaw=[Math.min(...u),Math.min(...d),Math.max(...u)-Math.min(...u),Math.max(...d)-Math.min(...d)];for(let[c,p]of Object.entries(Dy)){let h=[];for(let m=0;m<p.length-1;m++){let f=Ma.keypoints.find(y=>y.part===p[m]),g=Ma.keypoints.find(y=>y.part===p[m+1]);f&&g&&f.score>(t.body.minConfidence||0)&&g.score>(t.body.minConfidence||0)&&h.push([f.position,g.position])}Ma.annotations[c]=h}r([Ma])}))}var dd=e=>[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])],L0=e=>[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2,1],W0=(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],B0=(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],vI=(e,t,a)=>{let n=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],r=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]],s=e.landmarks.map(i=>[(i[0]+a[0])*t[0],(i[1]+a[1])*t[1]]);return{startPoint:n,endPoint:r,landmarks:s,confidence:e.confidence}},Oy=(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=fe.cropAndResize(t,[s],[0],a),o=ve(i,ze.tf255);return J(i),o},V0=(e,t)=>{let a=L0(e),n=dd(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,size:n}},U0=e=>{let t=L0(e),a=dd(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,size:[Math.round(a[0]),Math.round(a[1])]}},wI=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}},zy=[[1,0,0],[0,1,0],[0,0,1]],Cye=e=>e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI)),Nye=(e,t)=>Cye(Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]));var AI=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]],Tl=(e,t)=>{let a=0;for(let n=0;n<e.length;n++)a+=e[n]*t[n];return a},Rye=(e,t)=>{let a=[];for(let n=0;n<e.length;n++)a.push(e[n][t]);return a},bI=(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(Tl(e[r],Rye(t,s)))}return a},kI=(e,t)=>{let a=Math.cos(e),n=Math.sin(e),r=[[a,-n,0],[n,a,0],[0,0,1]],s=AI(t[0],t[1]),i=bI(s,r),o=AI(-t[0],-t[1]);return bI(i,o)},Eye=e=>{let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],a=[e[0][2],e[1][2]],n=[-Tl(t[0],a),-Tl(t[1],a)];return[t[0].concat(n[0]),t[1].concat(n[1]),[0,0,1]]},Mye=(e,t)=>[Tl(e,t[0]),Tl(e,t[1])];function II(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 d=0;d<i;d++){let c=r*(d+.5);for(let p=0;p<o;p++)a.push([c,u])}}}return a}function SI(e,t,a,n,r){let s=dd(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?kI(a,[0,0]):zy,u=o?i.map(h=>[...Mye(h,l),h[2]]):i,d=o?Eye(n):zy,c=L0(t),p=[Tl(c,d[0]),Tl(c,d[1])];return u.map(h=>[Math.trunc(h[0]+p[0]),Math.trunc(h[1]+p[1]),Math.trunc(h[2]||0)])}function TI(e,t,a,n){let r=t.landmarks.length>=by.count?by.symmetryLine:bl.symmetryLine,s=0,i=zy,o;if(e&&ne.kernels.includes("rotatewithoffset"))if(s=Nye(t.landmarks[r[0]],t.landmarks[r[1]]),s&&s!==0&&Math.abs(s)>.2){let u=L0(t),d=[u[0]/a.shape[2],u[1]/a.shape[1]],c=fe.rotateWithOffset(a,s,0,[d[0],d[1]]);i=kI(-s,u),o=Oy(t,c,[n,n]),J(c)}else o=Oy(t,a,[n,n]);else o=Oy(t,a,[n,n]);return[s,i,o]}var Fye=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]},CI=(e,t)=>{let a=Fye(e),n=dd(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 NI=6,Hn,G0=null,Xs=0,pd=null,RI=()=>Xs;async function EI(e){var t;return ne.initial&&(Hn=null),Hn?e.debug&&K("cached model:",Hn.modelUrl):Hn=await $e((t=e.face.detector)==null?void 0:t.modelPath),Xs=Hn.executor&&Hn.inputs[0].shape?Hn.inputs[0].shape[2]:256,pd=Ge(Xs,"int32"),G0=er(II(Xs)),Hn}function $ye(e){if(!G0||!pd)return An([0,0]);let t={};t.boxStarts=_e(e,[0,1],[-1,2]),t.centers=we(t.boxStarts,G0),t.boxSizes=_e(e,[0,3],[-1,2]),t.boxSizesNormalized=ve(t.boxSizes,pd),t.centersNormalized=ve(t.centers,pd),t.halfBoxSize=ve(t.boxSizesNormalized,ze.tf2),t.starts=xe(t.centersNormalized,t.halfBoxSize),t.ends=we(t.centersNormalized,t.halfBoxSize),t.startNormalized=te(t.starts,pd),t.endNormalized=te(t.ends,pd);let a=Xu([t.startNormalized,t.endNormalized],1);return Object.keys(t).forEach(n=>J(t[n])),a}async function MI(e,t){var o,l,u,d,c,p,h;if(!e||e.isDisposedInternal||e.shape.length!==4||e.shape[1]<1||e.shape[2]<1)return[];let a={};a.resized=fe.resizeBilinear(e,[Xs,Xs]),a.div=ve(a.resized,ze.tf127),a.normalized=xe(a.div,ze.tf05);let n=Hn==null?void 0:Hn.execute(a.normalized);if(Array.isArray(n)&&n.length>2){let m=n.sort((f,g)=>f.size-g.size);a.concat384=lt([m[0],m[2]],2),a.concat512=lt([m[1],m[3]],2),a.concat=lt([a.concat512,a.concat384],1),a.batch=Oe(a.concat,[0])}else Array.isArray(n)?a.batch=Oe(n[0]):a.batch=Oe(n);J(n),a.boxes=$ye(a.batch),a.logits=_e(a.batch,[0,0],[-1,1]),a.sigmoid=za(a.logits),a.scores=Oe(a.sigmoid),a.nms=await fe.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 m=0;m<r.length;m++){let f=i[r[m]];if(f>(((d=t.face.detector)==null?void 0:d.minConfidence)||0)){let g={};g.bbox=_e(a.boxes,[r[m],0],[1,-1]),g.slice=_e(a.batch,[r[m],NI-1],[1,-1]),g.squeeze=Oe(g.slice),g.landmarks=Q(g.squeeze,[NI,-1]);let y=await g.bbox.data(),x={startPoint:[y[0],y[1]],endPoint:[y[2],y[3]],landmarks:await g.landmarks.array(),confidence:f};g.anchor=_e(G0,[r[m],0],[1,2]);let A=await g.anchor.data(),b=vI(x,[(e.shape[2]||0)/Xs,(e.shape[1]||0)/Xs],A),w=V0(b,((c=t.face.detector)==null?void 0:c.scale)||1.4),S=U0(w);S.size[0]>(((p=t.face.detector)==null?void 0:p.minSize)||0)&&S.size[1]>(((h=t.face.detector)==null?void 0:h.minSize)||0)&&s.push(S),Object.keys(g).forEach(C=>J(g[C]))}}return Object.keys(a).forEach(m=>J(a[m])),s}var sn,Ks=0,Wy=Pn.leftEyeLower0,By=Pn.rightEyeLower0,cd={leftBounds:[Wy[0],Wy[Wy.length-1]],rightBounds:[By[0],By[By.length-1]]},hd={upperCenter:3,lowerCenter:4,index:71,numCoordinates:76};async function _I(e){var t,a;return ne.initial&&(sn=null),sn?e.debug&&K("cached model:",sn.modelUrl):sn=await $e((t=e.face.iris)==null?void 0:t.modelPath),Ks=sn!=null&&sn.executor&&((a=sn.inputs)!=null&&a[0].shape)?sn.inputs[0].shape[2]:0,Ks===-1&&(Ks=64),sn}function H0(e,t,a,n){for(let r=0;r<vy.length;r++){let{key:s,indices:i}=vy[r],o=Pn[`${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 Dye=e=>{let t=e[cd.leftBounds[0]][2],a=e[cd.rightBounds[0]][2];return t-a},$I=(e,t,a,n,r,s=!1,i=2.3)=>{let o=U0(V0(wI([e[a],e[n]]),i)),l=dd(o),u=fe.cropAndResize(t,[[o.startPoint[1]/r,o.startPoint[0]/r,o.endPoint[1]/r,o.endPoint[0]/r]],[0],[Ks,Ks]);if(s&&ne.kernels.includes("flipleftright")){let d=fe.flipLeftRight(u);J(u),u=d}return{box:o,boxSize:l,crop:u}},DI=(e,t,a,n=!1)=>{let r=[];for(let s=0;s<hd.numCoordinates;s++){let i=e[s*3],o=e[s*3+1],l=e[s*3+2];r.push([(n?1-i/Ks:i/Ks)*a[0]+t.startPoint[0],o/Ks*a[1]+t.startPoint[1],l])}return{rawCoords:r,iris:r.slice(hd.index)}},PI=(e,t,a)=>{let n=e[Pn[`${a}EyeUpper0`][hd.upperCenter]][2],r=e[Pn[`${a}EyeLower0`][hd.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 OI(e,t,a,n){var C,N;if(!(sn!=null&&sn.executor))return e;let{box:r,boxSize:s,crop:i}=$I(e,t,cd.leftBounds[0],cd.leftBounds[1],a,!0,((C=n.face.iris)==null?void 0:C.scale)||2.3),{box:o,boxSize:l,crop:u}=$I(e,t,cd.rightBounds[0],cd.rightBounds[1],a,!0,((N=n.face.iris)==null?void 0:N.scale)||2.3),d=lt([i,u]);J(i),J(u);let c=sn.execute(d);J(d);let p=await c.data();J(c);let h=p.slice(0,hd.numCoordinates*3),{rawCoords:m,iris:f}=DI(h,r,s,!0),g=p.slice(hd.numCoordinates*3),{rawCoords:y,iris:x}=DI(g,o,l,!1),A=Dye(e);Math.abs(A)<30?(H0(e,m,"left",null),H0(e,y,"right",null)):A<1?H0(e,m,"left",["EyeUpper0","EyeLower0"]):H0(e,y,"right",["EyeUpper0","EyeLower0"]);let b=PI(e,f,"left"),w=PI(e,x,"right");return e.concat(b).concat(w)}async function LI(e,t){var s,i,o,l,u,d,c,p,h,m;let a={lips:await((i=(s=t.filter(f=>f.size===160))==null?void 0:s[0])==null?void 0:i.data()),irisL:await((l=(o=t.filter(f=>f.size===10))==null?void 0:o[0])==null?void 0:l.data()),eyeL:await((d=(u=t.filter(f=>f.size===142))==null?void 0:u[0])==null?void 0:d.data()),irisR:await((p=(c=t.filter(f=>f.size===10))==null?void 0:c[1])==null?void 0:p.data()),eyeR:await((m=(h=t.filter(f=>f.size===142))==null?void 0:h[1])==null?void 0:m.data())};for(let f of Object.values(a))if(!f)return e;let n=wl.reduce((f,g)=>f+=e[g][2],0)/wl.length;for(let f=0;f<a.irisL.length/2;f++)e.push([a.irisL[2*f+0],a.irisL[2*f+1],n]);let r=kl.reduce((f,g)=>f+=e[g][2],0)/kl.length;for(let f=0;f<a.irisR.length/2;f++)e.push([a.irisR[2*f+0],a.irisR[2*f+1],r]);for(let f=0;f<a.eyeL.length/2;f++)e[wl[f]]=[a.eyeL[2*f+0],a.eyeL[2*f+1],e[wl[f]][2]];for(let f=0;f<a.eyeR.length/2;f++)e[kl[f]]=[a.eyeR[2*f+0],a.eyeR[2*f+1],e[kl[f]][2]];for(let f=0;f<a.lips.length/2;f++)e[fc[f]]=[a.lips[2*f+0],a.lips[2*f+1],e[fc[f]][2]];return e}var mr={boxes:[],skipped:Number.MAX_SAFE_INTEGER,timestamp:0},Ct=null,gc=0;async function WI(e,t){var l,u,d,c,p,h,m,f,g,y;let a=(((l=t.face.detector)==null?void 0:l.skipTime)||0)>ae()-mr.timestamp,n=mr.skipped<(((u=t.face.detector)==null?void 0:u.skipFrames)||0);!t.skipAllowed||!a||!n||mr.boxes.length===0?(mr.boxes=await MI(e,t),mr.timestamp=ae(),mr.skipped=0):mr.skipped++;let r=[],s=[],i=0,o=gc;for(let x=0;x<mr.boxes.length;x++){let A=mr.boxes[x],b=0,w,S={id:i++,mesh:[],meshRaw:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,boxScore:0,faceScore:0,size:[0,0],annotations:{}};if([b,w,S.tensor]=TI((d=t.face.detector)==null?void 0:d.rotation,A,e,(c=t.face.mesh)!=null&&c.enabled?gc:RI()),t.filter.equalization){let C=S.tensor?await b0(S.tensor):void 0;J(S.tensor),C&&(S.tensor=C)}if(S.boxScore=Math.round(100*A.confidence)/100,!((p=t.face.mesh)!=null&&p.enabled)||!(Ct!=null&&Ct.executor)){S.box=W0(A,e),S.boxRaw=B0(A,e),S.score=S.boxScore,S.size=A.size,S.mesh=A.landmarks,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(bl))S.annotations[C]=[S.mesh[bl[C]]]}else if(!Ct)t.debug&&K("face mesh detection requested, but model is not loaded");else{if((h=t.face.attention)!=null&&h.enabled&&!ne.kernels.includes("atan2"))return t.face.attention.enabled=!1,J(S.tensor),r;let C=Ct.execute(S.tensor),M=await C.find(F=>F.shape[F.shape.length-1]===1).data();if(S.faceScore=Math.round(100*M[0])/100,S.faceScore<(((m=t.face.detector)==null?void 0:m.minConfidence)||1)){if(A.confidence=S.faceScore,t.face.mesh.keepInvalid){S.box=W0(A,e),S.boxRaw=B0(A,e),S.size=A.size,S.score=S.boxScore,S.mesh=A.landmarks,S.meshRaw=S.mesh.map(F=>[F[0]/(e.shape[2]||1),F[1]/(e.shape[1]||1),(F[2]||0)/o]);for(let F of Object.keys(bl))S.annotations[F]=[S.mesh[bl[F]]]}}else{let F=C.find(O=>O.shape[O.shape.length-1]===1404),E=Q(F,[-1,3]),T=await E.array();J(E),(f=t.face.attention)!=null&&f.enabled?T=await LI(T,C):(g=t.face.iris)!=null&&g.enabled&&(T=await OI(T,S.tensor,gc,t)),S.mesh=SI(T,A,b,w,gc),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(Pn))S.annotations[O]=Pn[O].map(W=>S.mesh[W]);S.score=S.faceScore;let D={...CI(S.mesh,A),confidence:A.confidence,landmarks:A.landmarks,size:A.size};S.box=W0(D,e),S.boxRaw=B0(D,e),S.size=D.size,s.push(D)}J(C)}S.score>(((y=t.face.detector)==null?void 0:y.minConfidence)||1)?r.push(S):J(S.tensor)}return mr.boxes=s,r}async function BI(e){var t,a,n,r,s,i;return ne.initial&&(Ct=null),(t=e.face.attention)!=null&&t.enabled&&(Ct!=null&&Ct.signature)&&Object.keys(((a=Ct==null?void 0:Ct.signature)==null?void 0:a.outputs)||{}).length<6&&(Ct=null),Ct?e.debug&&K("cached model:",Ct.modelUrl):(n=e.face.attention)!=null&&n.enabled?Ct=await $e(e.face.attention.modelPath):Ct=await $e((r=e.face.mesh)==null?void 0:r.modelPath),gc=Ct.executor&&((s=Ct==null?void 0:Ct.inputs)!=null&&s[0].shape)?(i=Ct==null?void 0:Ct.inputs)==null?void 0:i[0].shape[2]:256,Ct}var VI=vl,UI=mc;var Gy=[],sa,j0=[],GI=0,HI=0,Uy=Number.MAX_SAFE_INTEGER,Hy=!1;async function jI(e){var t,a,n;return ne.initial&&(sa=null),sa?e.debug&&K("cached model:",sa.modelUrl):(sa=await $e((t=e.face.emotion)==null?void 0:t.modelPath),Hy=((n=(a=sa==null?void 0:sa.inputs)==null?void 0:a[0].shape)==null?void 0:n[3])===3,Hy?Gy=["angry","disgust","fear","happy","neutral","sad","surprise"]:Gy=["angry","disgust","fear","happy","sad","surprise","neutral"]),sa}async function jy(e,t,a,n){var i,o;if(!sa)return[];let r=Uy<(((i=t.face.emotion)==null?void 0:i.skipFrames)||0),s=(((o=t.face.emotion)==null?void 0:o.skipTime)||0)>ae()-HI;return t.skipAllowed&&s&&r&&GI===n&&j0[a]&&j0[a].length>0?(Uy++,j0[a]):(Uy=0,new Promise(async l=>{var d,c,p;let u=[];if((d=t.face.emotion)!=null&&d.enabled){let h={},m=sa!=null&&sa.inputs[0].shape?sa.inputs[0].shape[2]:0;if(((c=t.face.emotion)==null?void 0:c.crop)>0){let g=(p=t.face.emotion)==null?void 0:p.crop,y=[[g,g,1-g,1-g]];h.resize=fe.cropAndResize(e,y,[0],[m,m])}else h.resize=fe.resizeBilinear(e,[m,m],!1);Hy?(h.mul=te(h.resize,255),h.normalize=xe(h.mul,[103.939,116.779,123.68]),h.emotion=sa==null?void 0:sa.execute(h.normalize)):(h.channels=te(h.resize,ze.rgb),h.grayscale=ot(h.channels,3,!0),h.grayscaleSub=xe(h.grayscale,ze.tf05),h.grayscaleMul=te(h.grayscaleSub,ze.tf2),h.emotion=sa==null?void 0:sa.execute(h.grayscaleMul)),HI=ae();let f=await h.emotion.data();for(let g=0;g<f.length;g++)f[g]>(t.face.emotion.minConfidence||0)&&u.push({score:Math.min(.99,Math.trunc(100*f[g])/100),emotion:Gy[g]});u.sort((g,y)=>y.score-g.score),Object.keys(h).forEach(g=>J(h[g]))}j0[a]=u,GI=n,l(u)}))}var ia,Ys=[],XI=0,KI=0,qy=Number.MAX_SAFE_INTEGER;async function YI(e){var t;return ne.initial&&(ia=null),ia?e.debug&&K("cached model:",ia.modelUrl):ia=await $e((t=e.face.description)==null?void 0:t.modelPath),ia}function _ye(e,t){var s,i;let a=e.image||e.tensor||e;if(!(ia!=null&&ia.inputs[0].shape))return a;let n;if(((s=t.face.description)==null?void 0:s.crop)>0){let o=(i=t.face.description)==null?void 0:i.crop,l=[[o,o,1-o,1-o]];n=fe.cropAndResize(a,l,[0],[ia.inputs[0].shape[2],ia.inputs[0].shape[1]])}else n=fe.resizeBilinear(a,[ia.inputs[0].shape[2],ia.inputs[0].shape[1]],!1);let r=te(n,ze.tf255);return J(n),r}async function Xy(e,t,a,n){var o,l,u,d;let r={age:0,gender:"unknown",genderScore:0,descriptor:[]};if(!(ia!=null&&ia.executor))return r;let s=qy<(((o=t.face.description)==null?void 0:o.skipFrames)||0),i=(((l=t.face.description)==null?void 0:l.skipTime)||0)>ae()-XI;return t.skipAllowed&&s&&i&&KI===n&&((u=Ys==null?void 0:Ys[a])==null?void 0:u.age)>0&&((d=Ys==null?void 0:Ys[a])==null?void 0:d.genderScore)>0?(qy++,Ys[a]):(qy=0,new Promise(async c=>{var p;if((p=t.face.description)!=null&&p.enabled){let h=_ye(e,t),m=ia==null?void 0:ia.execute(h);XI=ae(),J(h);let g=await m.find(N=>N.shape[1]===1).data(),y=Math.trunc(200*Math.abs(g[0]-.5))/100;y>(t.face.description.minConfidence||0)&&(r.gender=g[0]<=.5?"female":"male",r.genderScore=Math.min(.99,y));let x=or(m.find(N=>N.shape[1]===100),1),A=(await x.data())[0];J(x);let w=await m.find(N=>N.shape[1]===100).data();r.age=Math.round(w[A-1]>w[A+1]?10*A-100*w[A-1]:10*A+100*w[A+1])/10,(Number.isNaN(g[0])||Number.isNaN(w[0]))&&K("faceres error:",{model:ia,result:m});let S=m.find(N=>N.shape[1]===1024),C=S?await S.data():[];r.descriptor=Array.from(C),m.forEach(N=>J(N))}Ys[a]=r,KI=n,c(r)}))}var md=.1,Ky=.5;function Oye(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 JI(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 Pn.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]});md&&md>0&&(r=r.map(i=>({x:i.x>.5?i.x+md:i.x-md,y:i.y>.5?i.y+md:i.y-md})));for(let i=0;i<t;i++)for(let o=0;o<a;o++)Oye(i/t,o/t,r)||(n.set(Ky*n.get(0,o,i,0),0,o,i,0),n.set(Ky*n.get(0,o,i,1),0,o,i,1),n.set(Ky*n.get(0,o,i,2),0,o,i,2));return n.toTensor()}var oa,q0=[],Yy=Number.MAX_SAFE_INTEGER,QI=0,eS=0;async function tS(e){var t;return ne.initial&&(oa=null),oa?e.debug&&K("cached model:",oa.modelUrl):oa=await $e((t=e.face.antispoof)==null?void 0:t.modelPath),oa}async function Zy(e,t,a,n){var i,o;if(!(oa!=null&&oa.executor))return 0;let r=(((i=t.face.antispoof)==null?void 0:i.skipTime)||0)>ae()-eS,s=Yy<(((o=t.face.antispoof)==null?void 0:o.skipFrames)||0);return t.skipAllowed&&r&&s&&QI===n&&q0[a]?(Yy++,q0[a]):(Yy=0,new Promise(async l=>{let u=fe.resizeBilinear(e,[oa!=null&&oa.inputs[0].shape?oa.inputs[0].shape[2]:0,oa!=null&&oa.inputs[0].shape?oa.inputs[0].shape[1]:0],!1),d=oa==null?void 0:oa.execute(u),c=(await d.data())[0];q0[a]=Math.round(100*c)/100,QI=n,eS=ae(),J([u,d]),l(q0[a])}))}var la,X0=[],Jy=Number.MAX_SAFE_INTEGER,nS=0,rS=0;async function sS(e){var t;return ne.initial&&(la=null),la?e.debug&&K("cached model:",la.modelUrl):la=await $e((t=e.face.liveness)==null?void 0:t.modelPath),la}async function Qy(e,t,a,n){var i,o;if(!(la!=null&&la.executor))return 0;let r=(((i=t.face.liveness)==null?void 0:i.skipTime)||0)>ae()-rS,s=Jy<(((o=t.face.liveness)==null?void 0:o.skipFrames)||0);return t.skipAllowed&&r&&s&&nS===n&&X0[a]?(Jy++,X0[a]):(Jy=0,new Promise(async l=>{let u=fe.resizeBilinear(e,[la!=null&&la.inputs[0].shape?la.inputs[0].shape[2]:0,la!=null&&la.inputs[0].shape?la.inputs[0].shape[1]:0],!1),d=la==null?void 0:la.execute(u),c=(await d.data())[0];X0[a]=Math.round(100*c)/100,nS=n,rS=ae(),J([u,d]),l(X0[a])}))}var _n,ex=[],Lye=["white","black","asian","indian","other"],Wye=[15,23,28,35.5,45.5,55.5,65],oS=0,lS=0,tx=Number.MAX_SAFE_INTEGER;async function uS(e){var t;return ne.initial&&(_n=null),_n?e.debug&&K("cached model:",_n.modelUrl):_n=await $e((t=e.face.gear)==null?void 0:t.modelPath),_n}async function ax(e,t,a,n){var i,o;if(!_n)return{age:0,gender:"unknown",genderScore:0,race:[]};let r=tx<(((i=t.face.gear)==null?void 0:i.skipFrames)||0),s=(((o=t.face.gear)==null?void 0:o.skipTime)||0)>ae()-lS;return t.skipAllowed&&s&&r&&oS===n&&ex[a]?(tx++,ex[a]):(tx=0,new Promise(async l=>{var y,x,A,b;if(!(_n!=null&&_n.inputs[0].shape))return;let u={},d=[[0,.1,.9,.9]];if(((y=t.face.gear)==null?void 0:y.crop)>0){let w=(x=t.face.gear)==null?void 0:x.crop;d=[[w,w,1-w,1-w]]}u.resize=fe.cropAndResize(e,d,[0],[_n.inputs[0].shape[2],_n.inputs[0].shape[1]]);let c={age:0,gender:"unknown",genderScore:0,race:[]};(A=t.face.gear)!=null&&A.enabled&&([u.age,u.gender,u.race]=_n.execute(u.resize,["age_output","gender_output","race_output"]));let p=await u.gender.data();c.gender=p[0]>p[1]?"male":"female",c.genderScore=Math.round(100*(p[0]>p[1]?p[0]:p[1]))/100;let h=await u.race.data();for(let w=0;w<h.length;w++)h[w]>(((b=t.face.gear)==null?void 0:b.minConfidence)||.2)&&c.race.push({score:Math.round(100*h[w])/100,race:Lye[w]});c.race.sort((w,S)=>S.score-w.score);let f=Array.from(await u.age.data()).map((w,S)=>[Wye[S],w]).sort((w,S)=>S[1]-w[1]),g=f[0][0];for(let w=1;w<f.length;w++)g+=f[w][1]*(f[w][0]-g);c.age=Math.round(10*g)/10,Object.keys(u).forEach(w=>J(u[w])),ex[a]=c,oS=n,lS=ae(),l(c)}))}var Fa,K0=[],pS=0,cS=0,nx=Number.MAX_SAFE_INTEGER;async function hS(e){return ne.initial&&(Fa=null),Fa?e.debug&&K("cached model:",Fa.modelUrl):Fa=await $e(e.face.ssrnet.modelPathAge),Fa}async function rx(e,t,a,n){var i,o,l,u;if(!Fa)return{age:0};let r=nx<(((i=t.face.ssrnet)==null?void 0:i.skipFrames)||0),s=(((o=t.face.ssrnet)==null?void 0:o.skipTime)||0)>ae()-cS;return t.skipAllowed&&r&&s&&pS===n&&((l=K0[a])!=null&&l.age)&&((u=K0[a])==null?void 0:u.age)>0?(nx++,K0[a]):(nx=0,new Promise(async d=>{var h,m,f;if(!(Fa!=null&&Fa.inputs)||!Fa.inputs[0]||!Fa.inputs[0].shape)return;let c={};if(((h=t.face.ssrnet)==null?void 0:h.crop)>0){let g=(m=t.face.ssrnet)==null?void 0:m.crop,y=[[g,g,1-g,1-g]];c.resize=fe.cropAndResize(e,y,[0],[Fa.inputs[0].shape[2],Fa.inputs[0].shape[1]])}else c.resize=fe.resizeBilinear(e,[Fa.inputs[0].shape[2],Fa.inputs[0].shape[1]],!1);c.enhance=te(c.resize,ze.tf255);let p={age:0};if((f=t.face.ssrnet)!=null&&f.enabled&&(c.age=Fa.execute(c.enhance)),c.age){let g=await c.age.data();p.age=Math.trunc(10*g[0])/10}Object.keys(c).forEach(g=>J(c[g])),K0[a]=p,pS=n,cS=ae(),d(p)}))}var xa,Y0=[],fS=0,gS=0,sx=Number.MAX_SAFE_INTEGER,ix=[.2989,.587,.114];async function yS(e){var t;return ne.initial&&(xa=null),xa?e.debug&&K("cached model:",xa.modelUrl):xa=await $e((t=e.face.ssrnet)==null?void 0:t.modelPathGender),xa}async function ox(e,t,a,n){var i,o,l,u;if(!xa)return{gender:"unknown",genderScore:0};let r=sx<(((i=t.face.ssrnet)==null?void 0:i.skipFrames)||0),s=(((o=t.face.ssrnet)==null?void 0:o.skipTime)||0)>ae()-gS;return t.skipAllowed&&r&&s&&fS===n&&((l=Y0[a])!=null&&l.gender)&&((u=Y0[a])==null?void 0:u.genderScore)>0?(sx++,Y0[a]):(sx=0,new Promise(async d=>{var m,f,g;if(!(xa!=null&&xa.inputs[0].shape))return;let c={};if(((m=t.face.ssrnet)==null?void 0:m.crop)>0){let y=(f=t.face.ssrnet)==null?void 0:f.crop,x=[[y,y,1-y,1-y]];c.resize=fe.cropAndResize(e,x,[0],[xa.inputs[0].shape[2],xa.inputs[0].shape[1]])}else c.resize=fe.resizeBilinear(e,[xa.inputs[0].shape[2],xa.inputs[0].shape[1]],!1);c.enhance=Pe(()=>{var x,A;let y;if(((A=(x=xa==null?void 0:xa.inputs)==null?void 0:x[0].shape)==null?void 0:A[3])===1){let[b,w,S]=Sa(c.resize,3,3),C=te(b,ix[0]),N=te(w,ix[1]),M=te(S,ix[2]),F=Uh([C,N,M]);y=te(xe(F,ze.tf05),2)}else y=te(xe(c.resize,ze.tf05),2);return y});let p={gender:"unknown",genderScore:0};(g=t.face.ssrnet)!=null&&g.enabled&&(c.gender=xa.execute(c.enhance));let h=await c.gender.data();p.gender=h[0]>h[1]?"female":"male",p.genderScore=h[0]>h[1]?Math.trunc(100*h[0])/100:Math.trunc(100*h[1])/100,Object.keys(c).forEach(y=>J(c[y])),Y0[a]=p,fS=n,gS=ae(),d(p)}))}var on,lx=[],AS=0,bS=0,vS=Number.MAX_SAFE_INTEGER;async function wS(e){var t;return ne.initial&&(on=null),on?e.debug&&K("cached model:",on.modelUrl):on=await $e((t=e.face.mobilefacenet)==null?void 0:t.modelPath),on}async function ux(e,t,a,n){var i,o;if(!(on!=null&&on.executor))return[];let r=vS<(((i=t.face.mobilefacenet)==null?void 0:i.skipFrames)||0),s=(((o=t.face.mobilefacenet)==null?void 0:o.skipTime)||0)>ae()-bS;return t.skipAllowed&&s&&r&&AS===n&&lx[a]?(vS++,lx[a]):new Promise(async l=>{var d;let u=[];if((d=t.face.mobilefacenet)!=null&&d.enabled&&(on!=null&&on.inputs[0].shape)){let c={};c.crop=fe.resizeBilinear(e,[on.inputs[0].shape[2],on.inputs[0].shape[1]],!1),c.data=on.execute(c.crop);let p=await c.data.data();u=Array.from(p),Object.keys(c).forEach(h=>J(c[h]))}lx[a]=u,AS=n,bS=ae(),l(u)})}var ln,dx=[],IS=0,SS=0,TS=Number.MAX_SAFE_INTEGER;async function CS(e){return ne.initial&&(ln=null),ln?e.debug&&K("cached model:",ln.modelUrl):ln=await $e(e.face.insightface.modelPath),ln}async function px(e,t,a,n){var i,o;if(!(ln!=null&&ln.executor))return[];let r=TS<(((i=t.face.insightface)==null?void 0:i.skipFrames)||0),s=(((o=t.face.insightface)==null?void 0:o.skipTime)||0)>ae()-SS;return t.skipAllowed&&s&&r&&IS===n&&dx[a]?(TS++,dx[a]):new Promise(async l=>{var d;let u=[];if((d=t.face.insightface)!=null&&d.enabled&&(ln!=null&&ln.inputs[0].shape)){let c={};c.crop=fe.resizeBilinear(e,[ln.inputs[0].shape[2],ln.inputs[0].shape[1]],!1),c.data=ln.execute(c.crop);let p=await c.data.data();u=Array.from(p),Object.keys(c).forEach(h=>J(c[h]))}dx[a]=u,IS=n,SS=ae(),l(u)})}var Bye=e=>{let t=(c,p)=>Math.atan2(c[1]-p[1],c[0]-p[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}},RS=(e,t)=>{let a=f=>{let g=Math.sqrt(f[0]*f[0]+f[1]*f[1]+f[2]*f[2]);return f[0]/=g,f[1]/=g,f[2]/=g,f},n=(f,g)=>{let y=f[0]-g[0],x=f[1]-g[1],A=f[2]-g[2];return[y,x,A]},r=(f,g)=>{let y=f[1]*g[2]-f[2]*g[1],x=f[2]*g[0]-f[0]*g[2],A=f[0]*g[1]-f[1]*g[0];return[y,x,A]},s=f=>{let[g,y,x,A,b,w,S,C,N]=f,M,F,E;return A<1?A>-1?(E=Math.asin(A),F=Math.atan2(-S,g),M=Math.atan2(-w,b)):(E=-Math.PI/2,F=-Math.atan2(C,N),M=0):(E=Math.PI/2,F=Math.atan2(C,N),M=0),Number.isNaN(M)&&(M=0),Number.isNaN(F)&&(F=0),Number.isNaN(E)&&(E=0),{pitch:2*-M,yaw:2*-F,roll:2*-E}},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(f=>[f[0]*t[0]/o,f[1]*t[1]/o,f[2]]),u=a(n(l[1],l[0])),d=a(n(l[3],l[2])),c=a(r(d,u));d=r(u,c);let p=[d[0],d[1],d[2],u[0],u[1],u[2],c[0],c[1],c[2]],h=s(p),m=i.length===478?Bye(e):{bearing:0,strength:0};return{angle:h,matrix:p,gaze:m}};function ES(e,t){let a=e==null?void 0:e.annotations;if(!(a!=null&&a.leftEyeIris)||!(a!=null&&a.rightEyeIris))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 cx=async(e,t)=>{var m,f,g,y,x,A,b,w,S,C,N,M,F,E,T,D,O,W,$,U,G,q,H;let a=ae(),n,r,s,i,o,l,u,d,c,p=[];e.state="run:face";let h=await WI(t,e.config);if(e.performance.face=ne.perfadd?(e.performance.face||0)+Math.trunc(ae()-a):Math.trunc(ae()-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((m=e.config.face.detector)!=null&&m.mask){let ge=await JI(h[V]);J(h[V].tensor),ge&&(h[V].tensor=ge)}let Z=h[V].mesh&&h[V].mesh.length>200?RS(h[V],[t.shape[2],t.shape[1]]):null;e.analyze("Start Emotion:"),e.config.async?i=(f=e.config.face.emotion)!=null&&f.enabled?jy(h[V].tensor||Ve([]),e.config,V,h.length):[]:(e.state="run:emotion",a=ae(),i=(g=e.config.face.emotion)!=null&&g.enabled?await jy(h[V].tensor||Ve([]),e.config,V,h.length):[],e.performance.emotion=ne.perfadd?(e.performance.emotion||0)+Math.trunc(ae()-a):Math.trunc(ae()-a)),e.analyze("End Emotion:"),e.analyze("Start AntiSpoof:"),e.config.async?u=(y=e.config.face.antispoof)!=null&&y.enabled?Zy(h[V].tensor||Ve([]),e.config,V,h.length):0:(e.state="run:antispoof",a=ae(),u=(x=e.config.face.antispoof)!=null&&x.enabled?await Zy(h[V].tensor||Ve([]),e.config,V,h.length):0,e.performance.antispoof=ne.perfadd?(e.performance.antispoof||0)+Math.trunc(ae()-a):Math.trunc(ae()-a)),e.analyze("End AntiSpoof:"),e.analyze("Start Liveness:"),e.config.async?d=(A=e.config.face.liveness)!=null&&A.enabled?Qy(h[V].tensor||Ve([]),e.config,V,h.length):0:(e.state="run:liveness",a=ae(),d=(b=e.config.face.liveness)!=null&&b.enabled?await Qy(h[V].tensor||Ve([]),e.config,V,h.length):0,e.performance.liveness=ne.perfadd?(e.performance.antispoof||0)+Math.trunc(ae()-a):Math.trunc(ae()-a)),e.analyze("End Liveness:"),e.analyze("Start GEAR:"),e.config.async?r=(w=e.config.face.gear)!=null&&w.enabled?ax(h[V].tensor||Ve([]),e.config,V,h.length):null:(e.state="run:gear",a=ae(),r=(S=e.config.face.gear)!=null&&S.enabled?await ax(h[V].tensor||Ve([]),e.config,V,h.length):null,e.performance.gear=Math.trunc(ae()-a)),e.analyze("End GEAR:"),e.analyze("Start SSRNet:"),e.config.async?(n=(C=e.config.face.ssrnet)!=null&&C.enabled?rx(h[V].tensor||Ve([]),e.config,V,h.length):null,s=(N=e.config.face.ssrnet)!=null&&N.enabled?ox(h[V].tensor||Ve([]),e.config,V,h.length):null):(e.state="run:ssrnet",a=ae(),n=(M=e.config.face.ssrnet)!=null&&M.enabled?await rx(h[V].tensor||Ve([]),e.config,V,h.length):null,s=(F=e.config.face.ssrnet)!=null&&F.enabled?await ox(h[V].tensor||Ve([]),e.config,V,h.length):null,e.performance.ssrnet=Math.trunc(ae()-a)),e.analyze("End SSRNet:"),e.analyze("Start MobileFaceNet:"),e.config.async?o=(E=e.config.face.mobilefacenet)!=null&&E.enabled?ux(h[V].tensor||Ve([]),e.config,V,h.length):null:(e.state="run:mobilefacenet",a=ae(),o=(T=e.config.face.mobilefacenet)!=null&&T.enabled?await ux(h[V].tensor||Ve([]),e.config,V,h.length):null,e.performance.mobilefacenet=Math.trunc(ae()-a)),e.analyze("End MobileFaceNet:"),e.analyze("Start InsightFace:"),e.config.async?l=(D=e.config.face.insightface)!=null&&D.enabled?px(h[V].tensor||Ve([]),e.config,V,h.length):null:(e.state="run:mobilefacenet",a=ae(),l=(O=e.config.face.insightface)!=null&&O.enabled?await px(h[V].tensor||Ve([]),e.config,V,h.length):null,e.performance.mobilefacenet=Math.trunc(ae()-a)),e.analyze("End InsightFace:"),e.analyze("Start Description:"),e.config.async?c=Xy(h[V].tensor||Ve([]),e.config,V,h.length):(e.state="run:description",a=ae(),c=await Xy(h[V].tensor||Ve([]),e.config,V,h.length),e.performance.description=ne.perfadd?(e.performance.description||0)+Math.trunc(ae()-a):Math.trunc(ae()-a)),e.analyze("End Description:"),e.config.async&&([n,s,i,o,l,c,r,u,d]=await Promise.all([n,s,i,o,l,c,r,u,d])),e.analyze("Finish Face:"),(W=e.config.face.ssrnet)!=null&&W.enabled&&n&&s&&(c={...c,age:n.age,gender:s.gender,genderScore:s.genderScore}),($=e.config.face.gear)!=null&&$.enabled&&r&&(c={...c,age:r.age,gender:r.gender,genderScore:r.genderScore,race:r.race}),(U=e.config.face.mobilefacenet)!=null&&U.enabled&&o&&(c.descriptor=o),(G=e.config.face.insightface)!=null&&G.enabled&&l&&(c.descriptor=l);let X=(q=e.config.face.iris)!=null&&q.enabled?ES(h[V],t.shape[2]):0,re=(H=e.config.face.detector)!=null&&H.return?Oe(h[V].tensor):null;J(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),d&&(ee.live=d),X>0&&(ee.distance=X),Z&&(ee.rotation=Z),re&&(ee.tensor=re),p.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),p};var $a={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=>$a.nameMapping[e],getPoints:e=>$a.pointsMapping[e]},Js={none:0,half:1,full:2,nameMapping:{0:"none",1:"half",2:"full"},getName:e=>Js.nameMapping[e]},$t={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=>$t.nameMapping[e]},Zs=class{constructor(t){he(this,"name");he(this,"curls");he(this,"directions");he(this,"weights");he(this,"weightsRelative");this.name=t,this.curls={},this.directions={},this.weights=[1,1,1,1,1],this.weightsRelative=[1,1,1,1,1]}curl(t,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:jn,index:zr,middle:Lr,ring:Cl,pinky:Nl}=$a,{none:qn,half:Uye,full:Xn}=Js,{verticalUp:fd,verticalDown:jve,horizontalLeft:hx,horizontalRight:Gye,diagonalUpRight:Hye,diagonalUpLeft:gd,diagonalDownRight:qve,diagonalDownLeft:Xve}=$t,Qs=new Zs("thumbs up");Qs.curl(jn,qn,1);Qs.direction(jn,fd,1);Qs.direction(jn,gd,.25);Qs.direction(jn,Hye,.25);for(let e of[$a.index,$a.middle,$a.ring,$a.pinky])Qs.curl(e,Xn,1),Qs.direction(e,hx,1),Qs.direction(e,Gye,1);var Ht=new Zs("victory");Ht.curl(jn,Uye,.5);Ht.curl(jn,qn,.5);Ht.direction(jn,fd,1);Ht.direction(jn,gd,1);Ht.curl(zr,qn,1);Ht.direction(zr,fd,.75);Ht.direction(zr,gd,1);Ht.curl(Lr,qn,1);Ht.direction(Lr,fd,1);Ht.direction(Lr,gd,.75);Ht.curl(Cl,Xn,1);Ht.direction(Cl,fd,.2);Ht.direction(Cl,gd,1);Ht.direction(Cl,hx,.2);Ht.curl(Nl,Xn,1);Ht.direction(Nl,fd,.2);Ht.direction(Nl,gd,1);Ht.direction(Nl,hx,.2);Ht.weight(zr,2);Ht.weight(Lr,2);var ei=new Zs("point");ei.curl(jn,Xn,1);ei.curl(zr,qn,.5);ei.curl(Lr,Xn,.5);ei.curl(Cl,Xn,.5);ei.curl(Nl,Xn,.5);ei.weight(zr,2);ei.weight(Lr,2);var ti=new Zs("middle finger");ti.curl(jn,qn,1);ti.curl(zr,Xn,.5);ti.curl(Lr,Xn,.5);ti.curl(Cl,Xn,.5);ti.curl(Nl,Xn,.5);ti.weight(zr,2);ti.weight(Lr,2);var yd=new Zs("open palm");yd.curl(jn,qn,.75);yd.curl(zr,qn,.75);yd.curl(Lr,qn,.75);yd.curl(Cl,qn,.75);yd.curl(Nl,qn,.75);var MS=[Qs,Ht,ei,ti,yd];var jye=.7,Rl={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 FS(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 DS(e,t){if(!e||!t)return[0,0];let a=FS(e[0],e[1],t[0],t[1]);if(e.length===2)return a;let n=FS(e[1],e[2],t[1],t[2]);return[a,n]}function $S(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 qye(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],d=e[2]-a[2],c=t[2]-a[2],p=Math.sqrt(n*n+i*i+u*u),h=Math.sqrt(r*r+o*o+d*d),m=Math.sqrt(s*s+l*l+c*c),f=(m*m+p*p-h*h)/(2*m*p);f>1?f=1:f<-1&&(f=-1);let g=Math.acos(f);g=57.2958*g%180;let y;return g>Rl.NO_CURL_START_LIMIT?y=Js.none:g>Rl.HALF_CURL_START_LIMIT?y=Js.half:y=Js.full,y}function PS(e,t,a,n){let r;return n===Math.abs(e)?e>0?r=$t.horizontalLeft:r=$t.horizontalRight:n===Math.abs(t)?t>0?r=$t.horizontalLeft:r=$t.horizontalRight:a>0?r=$t.horizontalLeft:r=$t.horizontalRight,r}function _S(e,t,a,n){let r;return n===Math.abs(e)?e<0?r=$t.verticalDown:r=$t.verticalUp:n===Math.abs(t)?t<0?r=$t.verticalDown:r=$t.verticalUp:a<0?r=$t.verticalDown:r=$t.verticalUp,r}function Xye(e,t,a,n,r,s,i,o){let l,u=_S(e,t,a,n),d=PS(r,s,i,o);return u===$t.verticalUp?d===$t.horizontalLeft?l=$t.diagonalUpLeft:l=$t.diagonalUpRight:d===$t.horizontalLeft?l=$t.diagonalDownLeft:l=$t.diagonalDownRight,l}function Kye(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],d=Math.max(Math.abs(r),Math.abs(s),Math.abs(i)),c=Math.max(Math.abs(o),Math.abs(l),Math.abs(u)),p=0,h=0,m=0,f=c/(d+1e-5);f>1.5?p+=Rl.DISTANCE_VOTE_POWER:f>.66?h+=Rl.DISTANCE_VOTE_POWER:m+=Rl.DISTANCE_VOTE_POWER;let g=Math.sqrt(r*r+o*o),y=Math.sqrt(s*s+l*l),x=Math.sqrt(i*i+u*u),A=Math.max(g,y,x),b=e[0],w=e[1],S=a[0],C=a[1];A===g?(S=a[0],C=a[1]):A===x&&(b=t[0],w=t[1]);let F=DS([b,w],[S,C]),E=$S(F,Rl.TOTAL_ANGLE_VOTE_POWER);p+=E[0],h+=E[1],m+=E[2];for(let D of n){let O=$S(D,Rl.SINGLE_ANGLE_VOTE_POWER);p+=O[0],h+=O[1],m+=O[2]}let T;return p===Math.max(p,h,m)?T=_S(l,o,u,c):m===Math.max(h,m)?T=PS(s,r,i,d):T=Xye(l,o,u,c,s,r,i,d),T}function OS(e){let t=[],a=[],n=[],r=[];if(!e)return{curls:n,directions:r};for(let s of $a.all){let i=$a.getPoints(s),o=[],l=[];for(let u of i){let d=e[u[0]],c=e[u[1]],p=DS(d,c),h=p[0],m=p[1];o.push(h),l.push(m)}t.push(o),a.push(l)}for(let s of $a.all){let i=s===$a.thumb?1:0,o=$a.getPoints(s),l=e[o[i][0]],u=e[o[i+1][1]],d=e[o[3][1]],c=qye(l,u,d),p=Kye(l,u,d,t[s].slice(i));n[s]=c,r[s]=p}return{curls:n,directions:r}}function Z0(e){if(!e||e.length===0)return null;let t=OS(e),a={};for(let n of $a.all)a[$a.getName(n)]={curl:Js.getName(t.curls[n]),direction:$t.getName(t.directions[n])};return a}function zS(e){let t=[];if(!e||e.length===0)return t;let a=OS(e);for(let n of MS){let r=n.matchAgainst(a.curls,a.directions);r>=jye&&t.push({name:n.name,confidence:r})}return t}var LS=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},WS=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},BS=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),d=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],p=Math.abs(d*c),h=!1;Math.abs(u-p)/Math.max(u,p)<.25&&(h=!0,t.push({iris:i,gesture:"facing center"}));let f=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];(f>.06||g>.06)&&(h=!1),f>g?g>.04&&t.push({iris:i,gesture:"looking right"}):f>.04&&t.push({iris:i,gesture:"looking left"});let y=Math.abs(e[i].mesh[145][1]-e[i].annotations.rightEyeIris[0][1])/e[i].box[3],x=Math.abs(e[i].mesh[374][1]-e[i].annotations.leftEyeIris[0][1])/e[i].box[3];(x<.01||y<.01||x>.022||y>.022)&&(h=!1),(x<.01||y<.01)&&t.push({iris:i,gesture:"looking down"}),(x>.022||y>.022)&&t.push({iris:i,gesture:"looking up"}),h&&t.push({iris:i,gesture:"looking center"})}return t},VS=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=zS(e[a].keypoints);for(let s of r)t.push({hand:a,gesture:s.name})}}return t};function J0(e){return[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])]}function yc(e){return[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2]}function HS(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 fe.cropAndResize(t,s,[0],a)}function jS(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 Q0(e,t=1.5){let a=yc(e),n=J0(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 em(e){let t=yc(e),a=J0(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 Zye(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function qS(e,t){let a=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]);return Zye(a)}var US=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]];function ai(e,t){let a=0;for(let n=0;n<e.length;n++)a+=e[n]*t[n];return a}function Jye(e,t){let a=[];for(let n=0;n<e.length;n++)a.push(e[n][t]);return a}function GS(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(ai(e[r],Jye(t,s)))}return a}function fx(e,t){let a=Math.cos(e),n=Math.sin(e),r=[[a,-n,0],[n,a,0],[0,0,1]],s=US(t[0],t[1]),i=GS(s,r),o=US(-t[0],-t[1]);return GS(i,o)}function XS(e){let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],a=[e[0][2],e[1][2]],n=[-ai(t[0],a),-ai(t[1],a)];return[t[0].concat(n[0]),t[1].concat(n[1]),[0,0,1]]}function gx(e,t){return[ai(e,t[0]),ai(e,t[1])]}var YS=[{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 tm=class{constructor(t){he(this,"model");he(this,"anchors");he(this,"anchorsTensor");he(this,"inputSize");he(this,"inputSizeTensor");he(this,"doubleInputSizeTensor");var a,n,r,s;this.model=t,this.anchors=YS.map(i=>[i.x,i.y]),this.anchorsTensor=er(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=Vt([this.inputSize,this.inputSize]),this.doubleInputSizeTensor=Vt([this.inputSize*2,this.inputSize*2])}normalizeBoxes(t){let a={};a.boxOffsets=_e(t,[0,0],[-1,2]),a.boxSizes=_e(t,[0,2],[-1,2]),a.div=ve(a.boxOffsets,this.inputSizeTensor),a.boxCenterPoints=we(a.div,this.anchorsTensor),a.halfBoxSizes=ve(a.boxSizes,this.doubleInputSizeTensor),a.sub=xe(a.boxCenterPoints,a.halfBoxSizes),a.startPoints=te(a.sub,this.inputSizeTensor),a.add=we(a.boxCenterPoints,a.halfBoxSizes),a.endPoints=te(a.add,this.inputSizeTensor);let n=Xu([a.startPoints,a.endPoints],1);return Object.keys(a).forEach(r=>J(a[r])),n}normalizeLandmarks(t,a){let n={};n.reshape=Q(t,[-1,7,2]),n.div=ve(n.reshape,this.inputSizeTensor),n.landmarks=we(n.div,this.anchors[a]?this.anchors[a]:0);let r=te(n.landmarks,this.inputSizeTensor);return Object.keys(n).forEach(s=>J(n[s])),r}async predict(t,a){var o;let n={};n.resize=fe.resizeBilinear(t,[this.inputSize,this.inputSize]),n.div=ve(n.resize,ze.tf127),n.image=xe(n.div,ze.tf1),n.batched=this.model.execute(n.image),n.predictions=Oe(n.batched),n.slice=_e(n.predictions,[0,0],[-1,1]),n.sigmoid=za(n.slice),n.scores=Oe(n.sigmoid);let r=await n.scores.data();n.boxes=_e(n.predictions,[0,1],[-1,4]),n.norm=this.normalizeBoxes(n.boxes),n.nms=await fe.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=_e(n.norm,[l,0],[1,-1]),u.slice=_e(n.predictions,[l,5],[1,14]),u.norm=this.normalizeLandmarks(u.slice,l),u.palmLandmarks=Q(u.norm,[-1,2]);let d=await u.box.data(),c=d.slice(0,2),p=d.slice(2,4),h=await u.palmLandmarks.array(),m={startPoint:c,endPoint:p,palmLandmarks:h,confidence:r[l]},f=jS(m,[(t.shape[2]||1)/this.inputSize,(t.shape[1]||0)/this.inputSize]);i.push(f),Object.keys(u).forEach(g=>J(u[g]))}return Object.keys(n).forEach(l=>J(n[l])),i}};var txe=5,ZS=1.65,JS=[0,5,9,13,17,1,2],axe=0,nxe=2,QS=0,am=class{constructor(t,a){he(this,"handDetector");he(this,"handPoseModel");he(this,"inputSize");he(this,"storedBoxes");he(this,"skipped");he(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=>gx([...s,1],a)),r=this.calculateLandmarksBoundingBox(n);return Q0(em(r),txe)}getBoxForHandLandmarks(t){let a=this.calculateLandmarksBoundingBox(t),n=Q0(em(a),ZS);n.palmLandmarks=[];for(let r=0;r<JS.length;r++)n.palmLandmarks.push(t[JS[r]].slice(0,2));return n}transformRawCoords(t,a,n,r){let s=J0(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=fx(n,[0,0]),u=o.map(h=>[...gx(h,l),h[2]]),d=XS(r),c=[...yc(a),1],p=[ai(c,d[0]),ai(c,d[1])];return u.map(h=>[Math.trunc(h[0]+p[0]),Math.trunc(h[1]+p[1]),Math.trunc(h[2])])}async estimateHands(t,a){let n=!1,r,s=(a.hand.skipTime||0)>ae()-QS,i=this.skipped<(a.hand.skipFrames||0);a.skipAllowed&&s&&i?this.skipped++:(r=await this.handDetector.predict(t,a),this.skipped=0),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 d=a.hand.rotation?qS(u.palmLandmarks[axe],u.palmLandmarks[nxe]):0,c=yc(u),p=[c[0]/t.shape[2],c[1]/t.shape[1]],h=a.hand.rotation&&ne.kernels.includes("rotatewithoffset")?fe.rotateWithOffset(t,d,0,p):t.clone(),m=fx(-d,c),f=n?this.getBoxForPalmLandmarks(u.palmLandmarks,m):u,g=HS(f,h,[this.inputSize,this.inputSize]),y=ve(g,ze.tf255);J(g),J(h);let[x,A]=this.handPoseModel.execute(y);QS=ae(),J(y);let b=(await x.data())[0];if(J(x),b>=a.hand.minConfidence/4){let w=Q(A,[-1,3]),S=await w.array();J(A),J(w);let C=this.transformRawCoords(S,f,d,m),N=this.getBoxForHandLandmarks(C);this.storedBoxes[l]={...N,confidence:b};let M={landmarks:C,confidence:b,boxConfidence:u.confidence,fingerConfidence:b,box:{topLeft:N.startPoint,bottomRight:N.endPoint}};o.push(M)}else this.storedBoxes[l]=null;J(A)}else{let d=Q0(em(u),ZS),c={confidence:u.confidence,boxConfidence:u.confidence,fingerConfidence:0,box:{topLeft:d.startPoint,bottomRight:d.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 eT={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]},El,Ml,yx;function sxe(){let e=El?new tm(El):void 0;e&&Ml&&(yx=new am(e,Ml))}async function xx(e,t){yx||sxe();let a=await yx.estimateHands(e,t);if(!a)return[];let n=[];for(let r=0;r<a.length;r++){let s={};if(a[r].landmarks)for(let d of Object.keys(eT))s[d]=eT[d].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 d of i)d[0]<o[0]&&(o[0]=d[0]),d[1]<o[1]&&(o[1]=d[1]),d[0]>o[2]&&(o[2]=d[0]),d[1]>o[3]&&(o[3]=d[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=Z0(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 tT(e){var t;return ne.initial&&(El=null),El?e.debug&&K("cached model:",El.modelUrl):El=await $e((t=e.hand.detector)==null?void 0:t.modelPath),El}async function aT(e){var t;return ne.initial&&(Ml=null),Ml?e.debug&&K("cached model:",Ml.modelUrl):Ml=await $e((t=e.hand.skeleton)==null?void 0:t.modelPath),Ml}var zt=[null,null],ixe=["StatefulPartitionedCall/Postprocessor/Slice","StatefulPartitionedCall/Postprocessor/ExpandDims_1"],ni=[[0,0],[0,0]],oxe=["hand","fist","pinch","point","face","tip","pinchtip"],rT=4,sT=1.6,lxe=512,uxe=1.4,nm=Number.MAX_SAFE_INTEGER,Ax=0,Wr=[0,0],Ot={boxes:[],hands:[]},iT={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 oT(e){var t;if(ne.initial&&(zt[0]=null),zt[0])e.debug&&K("cached model:",zt[0].modelUrl);else{T0(["tensorlistreserve","enter","tensorlistfromtensor","merge","loopcond","switch","exit","tensorliststack","nextiteration","tensorlistsetitem","tensorlistgetitem","reciprocal","shape","split","where"],e),zt[0]=await $e((t=e.hand.detector)==null?void 0:t.modelPath);let a=zt[0].executor?Object.values(zt[0].modelSignature.inputs):void 0;ni[0][0]=Array.isArray(a)?parseInt(a[0].tensorShape.dim[1].size):0,ni[0][1]=Array.isArray(a)?parseInt(a[0].tensorShape.dim[2].size):0}return zt[0]}async function lT(e){var t;if(ne.initial&&(zt[1]=null),zt[1])e.debug&&K("cached model:",zt[1].modelUrl);else{zt[1]=await $e((t=e.hand.skeleton)==null?void 0:t.modelPath);let a=zt[1].executor?Object.values(zt[1].modelSignature.inputs):void 0;ni[1][0]=Array.isArray(a)?parseInt(a[0].tensorShape.dim[1].size):0,ni[1][1]=Array.isArray(a)?parseInt(a[0].tensorShape.dim[2].size):0}return zt[1]}async function dxe(e,t){let a=[];if(!e||!zt[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,lxe),i=Math.round(s*r/8)*8;n.resize=fe.resizeBilinear(e,[s,i]),n.cast=Ue(n.resize,"int32"),[n.rawScores,n.rawBoxes]=await zt[0].executeAsync(n.cast,ixe),n.boxes=Oe(n.rawBoxes,[0,2]),n.scores=Oe(n.rawScores,[0]);let o=Na(n.scores,1);J(o[rT]),o.splice(rT,1),n.filtered=ca(o,1),J(o),n.max=fa(n.filtered,1),n.argmax=or(n.filtered,1);let l=0;n.nms=await fe.nonMaxSuppressionAsync(n.boxes,n.max,(t.hand.maxDetected||0)+1,t.hand.iouThreshold||0,t.hand.minConfidence||1);let u=await n.nms.data(),d=await n.max.data(),c=await n.argmax.data();for(let p of Array.from(u)){let h=_e(n.boxes,p,1),m=await h.data();J(h);let f=[m[1],m[0],m[3]-m[1],m[2]-m[0]],g=P0(f,uxe),y=[Math.trunc(f[0]*Wr[0]),Math.trunc(f[1]*Wr[1]),Math.trunc(f[2]*Wr[0]),Math.trunc(f[3]*Wr[1])],x=d[p],A=oxe[c[p]],b={id:l++,score:x,box:y,boxRaw:g,label:A};a.push(b)}return Object.keys(n).forEach(p=>J(n[p])),a.sort((p,h)=>h.score-p.score),a.length>(t.hand.maxDetected||1)&&(a.length=t.hand.maxDetected||1),a}async function bx(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&&zt[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=fe.cropAndResize(e,[s],[0],[ni[1][0],ni[1][1]],"bilinear"),r.div=ve(r.crop,ze.tf255),[r.score,r.keypoints]=zt[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=Q(r.keypoints,[-1,3]);let d=(await r.reshaped.array()).map(c=>[c[0]/ni[1][1],c[1]/ni[1][0],c[2]||0]).map(c=>[c[0]*t.boxRaw[2],c[1]*t.boxRaw[3],c[2]||0]);n.keypoints=d.map(c=>[Wr[0]*(c[0]+t.boxRaw[0]),Wr[1]*(c[1]+t.boxRaw[1]),c[2]||0]),n.landmarks=Z0(n.keypoints);for(let c of Object.keys(iT))n.annotations[c]=iT[c].map(p=>n.landmarks&&n.keypoints[p]?n.keypoints[p]:null)}Object.keys(r).forEach(l=>J(r[l]))}return n}async function vx(e,t){var r,s;if(!((r=zt[0])!=null&&r.executor)||!((s=zt[1])!=null&&s.executor)||!zt[0].inputs[0].shape||!zt[1].inputs[0].shape)return[];Wr=[e.shape[2]||0,e.shape[1]||0],nm++;let a=(t.hand.skipTime||0)>ae()-Ax,n=nm<(t.hand.skipFrames||0);return t.skipAllowed&&a&&n?Ot.hands:new Promise(async i=>{let o=3*(t.hand.skipTime||0)>ae()-Ax,l=nm<3*(t.hand.skipFrames||0);t.skipAllowed&&Ot.hands.length===t.hand.maxDetected?Ot.hands=await Promise.all(Ot.boxes.map(d=>bx(e,d,t))):t.skipAllowed&&o&&l&&Ot.hands.length>0?Ot.hands=await Promise.all(Ot.boxes.map(d=>bx(e,d,t))):(Ot.boxes=await dxe(e,t),Ax=ae(),Ot.hands=await Promise.all(Ot.boxes.map(d=>bx(e,d,t))),nm=0);let u=[...Ot.boxes];if(Ot.boxes.length=0,t.cacheSensitivity>0)for(let d=0;d<Ot.hands.length;d++){let c=iI(Ot.hands[d].keypoints,Wr);if(c.box[2]/(e.shape[2]||1)>.05&&c.box[3]/(e.shape[1]||1)>.05&&Ot.hands[d].fingerScore&&Ot.hands[d].fingerScore>(t.hand.minConfidence||0)){let p=P0(c.box,sT),h=P0(c.boxRaw,sT);Ot.boxes.push({...u[d],box:p,boxRaw:h})}}for(let d=0;d<Ot.hands.length;d++){let c=js(Ot.hands[d].keypoints,Wr);Ot.hands[d].box=c.box,Ot.hands[d].boxRaw=c.boxRaw}i(Ot.hands)})}var fr=(e=null)=>({face:[],body:[],hand:[],gesture:[],object:[],persons:[],performance:{},timestamp:0,width:0,height:0,error:e});var xc={};vr(xc,{connected:()=>sm,horizontal:()=>wx,kpt:()=>rm,relative:()=>Ix,vertical:()=>kx});var rm=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],wx=[["leftEye","rightEye"],["leftEar","rightEar"],["leftShoulder","rightShoulder"],["leftElbow","rightElbow"],["leftWrist","rightWrist"],["leftHip","rightHip"],["leftKnee","rightKnee"],["leftAnkle","rightAnkle"]],kx=[["leftKnee","leftShoulder"],["rightKnee","rightShoulder"],["leftAnkle","leftKnee"],["rightAnkle","rightKnee"]],Ix=[[["leftHip","rightHip"],["leftShoulder","rightShoulder"]],[["leftElbow","rightElbow"],["leftShoulder","rightShoulder"]]],sm={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var Ae=fr(),Sx=0;function dT(e,t){var i,o,l,u,d,c,p,h,m,f,g,y,x,A,b,w,S,C,N,M,F,E,T,D,O,W;let a=ae();if(!e)return fr();let n=Date.now()-e.timestamp,r=n<1e3?8-Math.log(n+1):1;if(e.canvas&&(Ae.canvas=e.canvas),e.error&&(Ae.error=e.error),!Ae.body||e.body.length!==Ae.body.length)Ae.body=JSON.parse(JSON.stringify(e.body));else for(let $=0;$<e.body.length;$++){let U=e.body[$].box.map((Z,X)=>((r-1)*Ae.body[$].box[X]+Z)/r),G=e.body[$].boxRaw.map((Z,X)=>((r-1)*Ae.body[$].boxRaw[X]+Z)/r),q=e.body[$].keypoints.map((Z,X)=>{var re,ee,ge,ie,be,Ce,Ee,Le,qe;return{score:Z.score,part:Z.part,position:[Ae.body[$].keypoints[X]?((r-1)*(Ae.body[$].keypoints[X].position[0]||0)+(Z.position[0]||0))/r:Z.position[0],Ae.body[$].keypoints[X]?((r-1)*(Ae.body[$].keypoints[X].position[1]||0)+(Z.position[1]||0))/r:Z.position[1],Ae.body[$].keypoints[X]?((r-1)*(Ae.body[$].keypoints[X].position[2]||0)+(Z.position[2]||0))/r:Z.position[2]],positionRaw:[Ae.body[$].keypoints[X]?((r-1)*(Ae.body[$].keypoints[X].positionRaw[0]||0)+(Z.positionRaw[0]||0))/r:Z.positionRaw[0],Ae.body[$].keypoints[X]?((r-1)*(Ae.body[$].keypoints[X].positionRaw[1]||0)+(Z.positionRaw[1]||0))/r:Z.positionRaw[1],Ae.body[$].keypoints[X]?((r-1)*(Ae.body[$].keypoints[X].positionRaw[2]||0)+(Z.positionRaw[2]||0))/r:Z.positionRaw[2]],distance:[Ae.body[$].keypoints[X]?((r-1)*(((re=Ae.body[$].keypoints[X].distance)==null?void 0:re[0])||0)+(((ee=Z.distance)==null?void 0:ee[0])||0))/r:(ge=Z.distance)==null?void 0:ge[0],Ae.body[$].keypoints[X]?((r-1)*(((ie=Ae.body[$].keypoints[X].distance)==null?void 0:ie[1])||0)+(((be=Z.distance)==null?void 0:be[1])||0))/r:(Ce=Z.distance)==null?void 0:Ce[1],Ae.body[$].keypoints[X]?((r-1)*(((Ee=Ae.body[$].keypoints[X].distance)==null?void 0:Ee[2])||0)+(((Le=Z.distance)==null?void 0:Le[2])||0))/r:(qe=Z.distance)==null?void 0:qe[2]]}}),H={},V={connected:{}};(i=t.body.modelPath)!=null&&i.includes("efficientpose")?V=z0:(o=t.body.modelPath)!=null&&o.includes("blazepose")?V=$0:(l=t.body.modelPath)!=null&&l.includes("movenet")&&(V=xc);for(let[Z,X]of Object.entries(V.connected)){let re=[];for(let ee=0;ee<X.length-1;ee++){let ge=q.find(be=>be.part===X[ee]),ie=q.find(be=>be.part===X[ee+1]);ge&&ie&&re.push([ge.position,ie.position])}H[Z]=re}Ae.body[$]={...e.body[$],box:U,boxRaw:G,keypoints:q,annotations:H}}if(!Ae.hand||e.hand.length!==Ae.hand.length)Ae.hand=JSON.parse(JSON.stringify(e.hand));else for(let $=0;$<e.hand.length;$++){let U=e.hand[$].box.map((V,Z)=>((r-1)*Ae.hand[$].box[Z]+V)/r),G=e.hand[$].boxRaw.map((V,Z)=>((r-1)*Ae.hand[$].boxRaw[Z]+V)/r);Ae.hand[$].keypoints.length!==e.hand[$].keypoints.length&&(Ae.hand[$].keypoints=e.hand[$].keypoints);let q=e.hand[$].keypoints&&e.hand[$].keypoints.length>0?e.hand[$].keypoints.map((V,Z)=>V.map((X,re)=>((r-1)*(Ae.hand[$].keypoints[Z][re]||1)+(X||0))/r)):[],H={};if(Object.keys(Ae.hand[$].annotations).length!==Object.keys(e.hand[$].annotations).length)Ae.hand[$].annotations=e.hand[$].annotations,H=Ae.hand[$].annotations;else if(e.hand[$].annotations)for(let V of Object.keys(e.hand[$].annotations))H[V]=(c=(d=(u=e.hand[$])==null?void 0:u.annotations)==null?void 0:d[V])!=null&&c[0]?e.hand[$].annotations[V].map((Z,X)=>Z.map((re,ee)=>((r-1)*Ae.hand[$].annotations[V][X][ee]+re)/r)):null;Ae.hand[$]={...e.hand[$],box:U,boxRaw:G,keypoints:q,annotations:H}}if(!Ae.face||e.face.length!==Ae.face.length)Ae.face=JSON.parse(JSON.stringify(e.face));else for(let $=0;$<e.face.length;$++){let U=e.face[$].box.map((H,V)=>((r-1)*Ae.face[$].box[V]+H)/r),G=e.face[$].boxRaw.map((H,V)=>((r-1)*Ae.face[$].boxRaw[V]+H)/r),q=e.face[$].annotations;if(Object.keys(Ae.face[$].annotations).length!==Object.keys(e.face[$].annotations).length)Ae.face[$].annotations=e.face[$].annotations,q=Ae.face[$].annotations;else if(e.face[$].annotations)for(let H of Object.keys(e.face[$].annotations))q[H]=(m=(h=(p=e.face[$])==null?void 0:p.annotations)==null?void 0:h[H])!=null&&m[0]?e.face[$].annotations[H].map((V,Z)=>V.map((X,re)=>((r-1)*Ae.face[$].annotations[H][Z][re]+X)/r)):null;if(e.face[$].rotation){let H={matrix:[0,0,0,0,0,0,0,0,0],angle:{roll:0,yaw:0,pitch:0},gaze:{bearing:0,strength:0}};H.matrix=(f=e.face[$].rotation)==null?void 0:f.matrix,H.angle={roll:((r-1)*(((y=(g=Ae.face[$].rotation)==null?void 0:g.angle)==null?void 0:y.roll)||0)+(((A=(x=e.face[$].rotation)==null?void 0:x.angle)==null?void 0:A.roll)||0))/r,yaw:((r-1)*(((w=(b=Ae.face[$].rotation)==null?void 0:b.angle)==null?void 0:w.yaw)||0)+(((C=(S=e.face[$].rotation)==null?void 0:S.angle)==null?void 0:C.yaw)||0))/r,pitch:((r-1)*(((M=(N=Ae.face[$].rotation)==null?void 0:N.angle)==null?void 0:M.pitch)||0)+(((E=(F=e.face[$].rotation)==null?void 0:F.angle)==null?void 0:E.pitch)||0))/r},H.gaze={bearing:((r-1)*(((T=Ae.face[$].rotation)==null?void 0:T.gaze.bearing)||0)+(((D=e.face[$].rotation)==null?void 0:D.gaze.bearing)||0))/r,strength:((r-1)*(((O=Ae.face[$].rotation)==null?void 0:O.gaze.strength)||0)+(((W=e.face[$].rotation)==null?void 0:W.gaze.strength)||0))/r},Ae.face[$]={...e.face[$],rotation:H,box:U,boxRaw:G,annotations:q}}else Ae.face[$]={...e.face[$],box:U,boxRaw:G,annotations:q}}if(!Ae.object||e.object.length!==Ae.object.length)Ae.object=JSON.parse(JSON.stringify(e.object));else for(let $=0;$<e.object.length;$++){let U=e.object[$].box.map((q,H)=>((r-1)*Ae.object[$].box[H]+q)/r),G=e.object[$].boxRaw.map((q,H)=>((r-1)*Ae.object[$].boxRaw[H]+q)/r);Ae.object[$]={...e.object[$],box:U,boxRaw:G}}if(e.persons){let $=e.persons;if(!Ae.persons||$.length!==Ae.persons.length)Ae.persons=JSON.parse(JSON.stringify($));else for(let U=0;U<$.length;U++)Ae.persons[U].box=$[U].box.map((G,q)=>((r-1)*Ae.persons[U].box[q]+G)/r)}e.gesture&&(Ae.gesture=e.gesture),Ae.width=e.width,Ae.height=e.height;let s=ae();return Sx=ne.perfadd?Sx+Math.round(s-a):Math.round(s-a),e.performance&&(Ae.performance={...e.performance,interpolate:Sx}),Ae}var Aa;async function Tx(e){return!Aa||ne.initial?Aa=await $e(e.segmentation.modelPath):e.debug&&K("cached model:",Aa.modelUrl),Aa}async function pT(e,t){var r;if(Aa||(Aa=await Tx(t)),!(Aa!=null&&Aa.executor)||!((r=Aa==null?void 0:Aa.inputs)!=null&&r[0].shape))return null;let a={};a.resize=fe.resizeBilinear(e,[Aa.inputs[0].shape?Aa.inputs[0].shape[1]:0,Aa.inputs[0].shape?Aa.inputs[0].shape[2]:0],!1),a.norm=ve(a.resize,ze.tf255),a.res=Aa.execute(a.norm),a.squeeze=Oe(a.res,[0]),[a.bgRaw,a.fgRaw]=Na(a.squeeze,2),a.fg=Yh(a.fgRaw),a.mul=te(a.fg,ze.tf255),a.expand=Bt(a.mul,2),a.output=fe.resizeBilinear(a.expand,[e.shape[1]||0,e.shape[2]||0]);let n;switch(t.segmentation.mode||"default"){case"default":a.input=Oe(e),a.concat=lt([a.input,a.output],-1),n=Ue(a.concat,"int32");break;case"alpha":n=Ue(a.output,"int32");break;default:n=Ve(0)}return Object.keys(a).forEach(s=>J(a[s])),n}var im={};vr(im,{distance:()=>Cx,find:()=>hxe,similarity:()=>cxe});function Cx(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 hT=(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 cxe(e,t,a={order:2,multiplier:25,min:.2,max:.8}){let n=Cx(e,t,a);return hT(n,a.order||2,a.min||0,a.max||1)}function hxe(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?Cx(e,t[i],a):Number.MAX_SAFE_INTEGER;if(o<n&&(n=o,r=i),n<(a.threshold||0))break}let s=hT(n,a.order||2,a.min||0,a.max||1);return{index:r,distance:n,similarity:s}}var Vx={};vr(Vx,{Models:()=>vc,validateModel:()=>hm});var mT=.005,un={keypoints:[],padding:[[0,0],[0,0],[0,0],[0,0]]};function Nx(e){for(let t of wx){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 kx){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 Ix){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 fT(e){for(let t=0;t<e.length;t++)if(e[t]&&un.keypoints[t]){let a=[Math.abs(e[t].positionRaw[0]-un.keypoints[t].positionRaw[0]),Math.abs(e[t].positionRaw[1]-un.keypoints[t].positionRaw[1])];a[0]<mT&&a[1]<mT?e[t]=un.keypoints[t]:un.keypoints[t]=e[t]}else un.keypoints[t]=e[t];return e}function gT(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;un.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=ur(e,un.padding),a.resize=fe.resizeBilinear(a.pad,[t,t]);let n=Ue(a.resize,"int32");return Object.keys(a).forEach(i=>J(a[i])),n}function yT(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]+un.padding[2][0]+un.padding[2][1])/t[0]-un.padding[2][0],n.position[1]*(t[1]+un.padding[1][0]+un.padding[1][1])/t[1]-un.padding[1][0]],n.positionRaw=[n.position[0]/t[0],n.position[1]/t[1]];let a=js(e.keypoints.map(n=>n.position),t);return e.box=a.box,e.boxRaw=a.boxRaw,e}var jt,om=0,Rx=Number.MAX_SAFE_INTEGER,Fl={boxes:[],bodies:[],last:0};async function xT(e){var t;return ne.initial&&(jt=null),jt?e.debug&&K("cached model:",jt.modelUrl):(T0(["size"],e),jt=await $e(e.body.modelPath)),om=jt!=null&&jt.executor&&((t=jt==null?void 0:jt.inputs)!=null&&t[0].shape)?jt.inputs[0].shape[2]:0,om<64&&(om=256),B().flagRegistry.WEBGL_USE_SHAPES_UNIFORMS&&B().set("WEBGL_USE_SHAPES_UNIFORMS",!1),jt}function fxe(e,t,a){let n=e[0][0],r=[],s=0;for(let d=0;d<n.length;d++)if(s=n[d][2],s>t.body.minConfidence){let c=[n[d][1],n[d][0]];r.push({score:Math.round(100*s)/100,part:rm[d],positionRaw:c,position:[Math.round((a.shape[2]||0)*c[0]),Math.round((a.shape[1]||0)*c[1])]})}s=r.reduce((d,c)=>c.score>d?c.score:d,0);let i=[],o=js(r.map(d=>d.position),[a.shape[2],a.shape[1]]),l={};for(let[d,c]of Object.entries(sm)){let p=[];for(let h=0;h<c.length-1;h++){let m=r.find(g=>g.part===c[h]),f=r.find(g=>g.part===c[h+1]);m&&f&&m.score>(t.body.minConfidence||0)&&f.score>(t.body.minConfidence||0)&&p.push([m.position,f.position])}l[d]=p}let u={id:0,score:s,box:o.box,boxRaw:o.boxRaw,keypoints:r,annotations:l};return Nx(u),i.push(u),i}function gxe(e,t,a){let n=[];for(let r=0;r<e[0].length;r++){let s=e[0][r],i=Math.round(100*s[55])/100;if(i>t.body.minConfidence){let o=[];for(let p=0;p<17;p++){let h=s[3*p+2];if(h>t.body.minConfidence){let m=[s[3*p+1],s[3*p+0]];o.push({part:rm[p],score:Math.round(100*h)/100,positionRaw:m,position:[Math.round((a.shape[2]||0)*m[0]),Math.round((a.shape[1]||0)*m[1])]})}}let l=[s[52],s[51],s[54]-s[52],s[53]-s[51]],u=[Math.trunc(l[0]*(a.shape[2]||0)),Math.trunc(l[1]*(a.shape[1]||0)),Math.trunc(l[2]*(a.shape[2]||0)),Math.trunc(l[3]*(a.shape[1]||0))],d={};for(let[p,h]of Object.entries(sm)){let m=[];for(let f=0;f<h.length-1;f++){let g=o.find(x=>x.part===h[f]),y=o.find(x=>x.part===h[f+1]);g&&y&&g.score>(t.body.minConfidence||0)&&y.score>(t.body.minConfidence||0)&&m.push([g.position,y.position])}d[p]=m}let c={id:r,score:i,box:u,boxRaw:l,keypoints:[...o],annotations:d};Nx(c),n.push(c)}}return n.sort((r,s)=>s.score-r.score),n.length>t.body.maxDetected&&(n.length=t.body.maxDetected),n}async function Ex(e,t){var r;if(!(jt!=null&&jt.executor)||!((r=jt==null?void 0:jt.inputs)!=null&&r[0].shape))return[];t.skipAllowed||(Fl.boxes.length=0),Rx++;let a=(t.body.skipTime||0)>ae()-Fl.last,n=Rx<(t.body.skipFrames||0);return t.skipAllowed&&a&&n?Fl.bodies:new Promise(async s=>{let i={};Rx=0,i.input=gT(e,om),i.res=jt==null?void 0:jt.execute(i.input),Fl.last=ae();let o=await i.res.array();Fl.bodies=i.res.shape[2]===17?fxe(o,t,e):gxe(o,t,e);for(let l of Fl.bodies)yT(l,[e.shape[2]||1,e.shape[1]||1]),fT(l.keypoints);Object.keys(i).forEach(l=>J(i[l])),s(Fl.bodies)})}var On,lm=[],bT=0,Mx=Number.MAX_SAFE_INTEGER,dm=0,um=2.5;async function vT(e){if(!On||ne.initial){On=await $e(e.object.modelPath);let t=On!=null&&On.executor?Object.values(On.modelSignature.inputs):void 0;dm=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):416}else e.debug&&K("cached model:",On.modelUrl);return On}async function yxe(e,t,a){var u,d;let n=0,r=[],s=dm;for(let c of[1,2,4]){let p=c*13,h=Oe(e.find(A=>A.shape[1]===p**2&&(A.shape[2]||0)===ud.length)),m=await h.array(),f=Oe(e.find(A=>A.shape[1]===p**2&&(A.shape[2]||0)<ud.length)),g=Q(f,[-1,4,(((u=f.shape)==null?void 0:u[1])||0)/4]),y=or(g,2),x=await y.array();for(let A=0;A<h.shape[0];A++)for(let b=0;b<(((d=h.shape)==null?void 0:d[1])||0);b++){let w=m[A][b];if(w>(a.object.minConfidence||0)&&b!==61){let S=(.5+Math.trunc(A%p))/p,C=(.5+Math.trunc(A/p))/p,N=x[A].map($=>$*(p/c/s)),[M,F]=[S-um/c*N[0],C-um/c*N[1]],[E,T]=[S+um/c*N[2]-M,C+um/c*N[3]-F],D=[M,F,E,T];D=D.map($=>Math.max(0,Math.min($,1)));let O=[D[0]*t[0],D[1]*t[1],D[2]*t[0],D[3]*t[1]],W={id:n++,score:Math.round(100*w)/100,class:b+1,label:ud[b].label,box:O.map($=>Math.trunc($)),boxRaw:D};r.push(W)}}J([h,f,g,y])}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 fe.nonMaxSuppressionAsync(i,o,a.object.maxDetected||0,a.object.iouThreshold,a.object.minConfidence);l=Array.from(await c.data()),J(c)}return r=r.filter((c,p)=>l.includes(p)).sort((c,p)=>p.score-c.score),r}async function Fx(e,t){if(!(On!=null&&On.executor))return[];let a=(t.object.skipTime||0)>ae()-bT,n=Mx<(t.object.skipFrames||0);return t.skipAllowed&&a&&n&&lm.length>0?(Mx++,lm):(Mx=0,!ne.kernels.includes("mod")||!ne.kernels.includes("sparsetodense")?lm:new Promise(async r=>{let s=[e.shape[2]||0,e.shape[1]||0],i=fe.resizeBilinear(e,[dm,dm],!1),o=ve(i,ze.tf255),l=Si(o,[0,3,1,2]),u;t.object.enabled&&(u=On.execute(l)),bT=ae();let d=await yxe(u,s,t);lm=d,J([i,o,l,...u]),r(d)}))}var bc=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],xxe=bc.length,Ac=bc.reduce((e,t,a)=>(e[t]=a,e),{}),Axe=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]],Wwe=Axe.map(([e,t])=>[Ac[e],Ac[t]]),kT=[["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 IT(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 ST(e,[t,a],[n,r]){let s=t/n,i=a/r,o=(u,d)=>({id:d,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:p,position:h})=>({score:c,part:p,position:[Math.trunc(h.x*i),Math.trunc(h.y*s)],positionRaw:[h.x/n,h.y/n]})),annotations:{}});return e.map((u,d)=>o(u,d))}var pm=class{constructor(t,a){he(this,"priorityQueue");he(this,"numberOfElements");he(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 $x(e,t,a,n){return{y:n.get(e,t,a),x:n.get(e,t,a+xxe)}}function Dx(e,t,a){let{heatmapY:n,heatmapX:r,id:s}=e,{y:i,x:o}=$x(n,r,s,a);return{x:e.heatmapX*t+o,y:e.heatmapY*t+i}}function Px(e,t,a){return e<t?t:e>a?a:e}function TT(e,t,a,n){let r=a-e,s=n-t;return r*r+s*s}function _x(e,t){return{x:e.x+t.x,y:e.y+t.y}}var dn,vxe=["MobilenetV1/offset_2/BiasAdd","MobilenetV1/heatmap_2/BiasAdd","MobilenetV1/displacement_fwd_2/BiasAdd","MobilenetV1/displacement_bwd_2/BiasAdd"],cm=1,xd=16,wxe=50**2;function CT(e,t,a,n,r,s,i=2){let o=y=>({y:s.get(y.y,y.x,e),x:s.get(y.y,y.x,s.shape[2]/2+e)}),l=(y,x,A)=>({y:Px(Math.round(y.y/xd),0,x-1),x:Px(Math.round(y.x/xd),0,A-1)}),[u,d]=n.shape,c=l(t.position,u,d),p=o(c),m=_x(t.position,p);for(let y=0;y<i;y++){let x=l(m,u,d),A=$x(x.y,x.x,a,r);m=_x({x:x.x*xd,y:x.y*xd},{x:A.x,y:A.y})}let f=l(m,u,d),g=n.get(f.y,f.x,a);return{position:m,part:bc[a],score:g}}function kxe(e,t,a,n,r){let s=kT.map(([p,h])=>[Ac[p],Ac[h]]),i=s.map(([,p])=>p),o=s.map(([p])=>p),l=t.shape[2],u=i.length,d=new Array(l),c=Dx(e.part,xd,a);d[e.part.id]={score:e.score,part:bc[e.part.id],position:c};for(let p=u-1;p>=0;--p){let h=i[p],m=o[p];d[h]&&!d[m]&&(d[m]=CT(p,d[h],m,t,a,r))}for(let p=0;p<u;++p){let h=o[p],m=i[p];d[h]&&!d[m]&&(d[m]=CT(p,d[h],m,t,a,n))}return d}function Ixe(e,t,a,n,r){let[s,i]=r.shape,o=!0,l=Math.max(a-cm,0),u=Math.min(a+cm+1,s);for(let d=l;d<u;++d){let c=Math.max(n-cm,0),p=Math.min(n+cm+1,i);for(let h=c;h<p;++h)if(r.get(d,h,e)>t){o=!1;break}if(!o)break}return o}function Sxe(e,t){let[a,n,r]=t.shape,s=new pm(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||Ixe(l,u,i,o,t)&&s.enqueue({score:u,part:{heatmapY:i,heatmapX:o,id:l}})}return s}function NT(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?TT(a,t,s.y,s.x)<=wxe:!1})}function Txe(e,t){return t.reduce((n,{position:r,score:s},i)=>(NT(e,r,i)||(n+=s),n),0)/t.length}function Cxe(e,t,a,n,r,s){let i=[],o=Sxe(s,t);for(;i.length<r&&!o.empty();){let l=o.dequeue(),u=Dx(l.part,xd,e);if(NT(i,u,l.part.id))continue;let d=kxe(l,t,e,a,n);d=d.filter(h=>h.score>s);let c=Txe(i,d),p=IT(d);c>s&&i.push({keypoints:d,box:p,score:Math.round(100*c)/100})}return i}async function Ox(e,t){if(!(dn!=null&&dn.executor))return[];let a=Pe(()=>{if(!dn.inputs[0].shape)return[];let i=fe.resizeBilinear(e,[dn.inputs[0].shape[2],dn.inputs[0].shape[1]]),o=xe(ve(Ue(i,"float32"),127.5),1),u=dn.execute(o,vxe).map(d=>Oe(d,[0]));return u[1]=za(u[1]),u}),n=await Promise.all(a.map(i=>i.buffer()));for(let i of a)J(i);let r=Cxe(n[0],n[1],n[2],n[3],t.body.maxDetected,t.body.minConfidence);return dn.inputs[0].shape?ST(r,[e.shape[1],e.shape[2]],[dn.inputs[0].shape[2],dn.inputs[0].shape[1]]):[]}async function RT(e){return!dn||ne.initial?dn=await $e(e.body.modelPath):e.debug&&K("cached model:",dn.modelUrl),dn}var gr,Nxe=["fgr","pha","r1o","r2o","r3o","r4o"],qt={},Lx=0;function FT(e){J([qt.r1i,qt.r2i,qt.r3i,qt.r4i,qt.downsample_ratio]),qt.r1i=Ve(0),qt.r2i=Ve(0),qt.r3i=Ve(0),qt.r4i=Ve(0),Lx=e.segmentation.ratio||.5,qt.downsample_ratio=Ve(Lx)}async function Wx(e){return!gr||ne.initial?gr=await $e(e.segmentation.modelPath):e.debug&&K("cached model:",gr.modelUrl),FT(e),gr}var MT=e=>Pe(()=>{let t=Oe(e,[0]),a=te(t,ze.tf255);return Ue(a,"int32")});function zx(e,t){let a=e?MT(e):lr([t.shape[1]||0,t.shape[2]||0,3],255,"int32"),n=t?MT(t):lr([e.shape[1]||0,e.shape[2]||0,1],255,"int32"),r=lt([a,n],-1);return J([a,n]),r}function Rxe(e){return Pe(()=>{let t={};return t.unstack=Na(e,-1),t.concat=lt(t.unstack,1),t.split=Sa(t.concat,4,1),t.stack=lt(t.split,2),t.squeeze=Oe(t.stack,[0]),t.expand=Bt(t.squeeze,-1),t.add=we(t.expand,1),t.mul=te(t.add,127.5),t.cast=Ue(t.mul,"int32"),t.tile=Qr(t.cast,[1,1,3]),t.alpha=lr([t.tile.shape[0]||0,t.tile.shape[1]||0,1],255,"int32"),lt([t.tile,t.alpha],-1)})}async function $T(e,t){if(gr||(gr=await Wx(t)),!(gr!=null&&gr.executor))return null;qt.src=ve(e,255),Lx!==t.segmentation.ratio&&FT(t);let[a,n,r,s,i,o]=await gr.executeAsync(qt,Nxe),l;switch(t.segmentation.mode||"default"){case"default":l=zx(a,n);break;case"alpha":l=zx(null,n);break;case"foreground":l=zx(a,null);break;case"state":l=Rxe(r);break;default:l=Ve(0)}return J([qt.src,a,n,qt.r1i,qt.r2i,qt.r3i,qt.r4i]),[qt.r1i,qt.r2i,qt.r3i,qt.r4i]=[r,s,i,o],l}var ba;async function Bx(e){return!ba||ne.initial?ba=await $e(e.segmentation.modelPath):e.debug&&K("cached model:",ba.modelUrl),ba}async function PT(e,t){var r;if(ba||(ba=await Bx(t)),!(ba!=null&&ba.executor)||!((r=ba==null?void 0:ba.inputs)!=null&&r[0].shape))return null;let a={};a.resize=fe.resizeBilinear(e,[ba.inputs[0].shape?ba.inputs[0].shape[1]:0,ba.inputs[0].shape?ba.inputs[0].shape[2]:0],!1),a.norm=ve(a.resize,ze.tf255),a.res=ba.execute(a.norm),a.squeeze=Oe(a.res,[0]),a.alpha=fe.resizeBilinear(a.squeeze,[e.shape[1]||0,e.shape[2]||0]),a.mul=te(a.alpha,ze.tf255);let n;switch(t.segmentation.mode||"default"){case"default":a.input=Oe(e),a.concat=lt([a.input,a.mul],-1),n=Ue(a.concat,"int32");break;case"alpha":n=Ue(a.mul,"int32");break;default:n=Ve(0)}return Object.keys(a).forEach(s=>J(a[s])),n}function hm(e,t,a){var u,d;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((d=l==null?void 0:l.graph)!=null&&d.nodes)for(let c of Object.values(l.graph.nodes)){let p=c.op.toLowerCase();s.includes(p)||s.push(p)}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 vc=class{constructor(t){he(this,"instance");he(this,"models",{});this.models={},this.instance=t}stats(){let t=0,a=0,n=0;for(let s of Object.values(ya))t+=s.sizeFromManifest,a+=s.sizeLoadedWeights,n+=s.sizeDesired;let r=n>0?a/n:0;return{numLoadedModels:Object.values(ya).length,numDefinedModels:Object.keys(this.models).length,percentageLoaded:r,totalSizeFromManifest:t,totalSizeWeights:a,totalSizeLoading:n,modelStats:Object.values(ya)}}reset(){for(let t of Object.keys(this.models))this.models[t]=null}async load(t){var n,r,s,i,o,l,u,d,c,p,h,m,f,g,y,x,A,b,w,S,C,N,M,F,E,T,D;ne.initial&&this.reset(),t&&(this.instance=t);let a={};a.blazeface=this.instance.config.face.enabled&&!this.models.blazeface?EI(this.instance.config):null,a.antispoof=this.instance.config.face.enabled&&((n=this.instance.config.face.antispoof)!=null&&n.enabled)&&!this.models.antispoof?tS(this.instance.config):null,a.liveness=this.instance.config.face.enabled&&((r=this.instance.config.face.liveness)!=null&&r.enabled)&&!this.models.liveness?sS(this.instance.config):null,a.faceres=this.instance.config.face.enabled&&((s=this.instance.config.face.description)!=null&&s.enabled)&&!this.models.faceres?YI(this.instance.config):null,a.emotion=this.instance.config.face.enabled&&((i=this.instance.config.face.emotion)!=null&&i.enabled)&&!this.models.emotion?jI(this.instance.config):null,a.iris=this.instance.config.face.enabled&&((o=this.instance.config.face.iris)!=null&&o.enabled)&&!((l=this.instance.config.face.attention)!=null&&l.enabled)&&!this.models.iris?_I(this.instance.config):null,a.facemesh=this.instance.config.face.enabled&&((u=this.instance.config.face.mesh)!=null&&u.enabled)&&!this.models.facemesh?BI(this.instance.config):null,a.gear=this.instance.config.face.enabled&&((d=this.instance.config.face.gear)!=null&&d.enabled)&&!this.models.gear?uS(this.instance.config):null,a.ssrnetage=this.instance.config.face.enabled&&((c=this.instance.config.face.ssrnet)!=null&&c.enabled)&&!this.models.ssrnetage?hS(this.instance.config):null,a.ssrnetgender=this.instance.config.face.enabled&&((p=this.instance.config.face.ssrnet)!=null&&p.enabled)&&!this.models.ssrnetgender?yS(this.instance.config):null,a.mobilefacenet=this.instance.config.face.enabled&&((h=this.instance.config.face.mobilefacenet)!=null&&h.enabled)&&!this.models.mobilefacenet?wS(this.instance.config):null,a.insightface=this.instance.config.face.enabled&&((m=this.instance.config.face.insightface)!=null&&m.enabled)&&!this.models.insightface?CS(this.instance.config):null,a.blazepose=this.instance.config.body.enabled&&!this.models.blazepose&&((f=this.instance.config.body.modelPath)!=null&&f.includes("blazepose"))?pI(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?dI(this.instance.config):null,a.efficientpose=this.instance.config.body.enabled&&!this.models.efficientpose&&((g=this.instance.config.body.modelPath)!=null&&g.includes("efficientpose"))?yI(this.instance.config):null,a.movenet=this.instance.config.body.enabled&&!this.models.movenet&&((y=this.instance.config.body.modelPath)!=null&&y.includes("movenet"))?xT(this.instance.config):null,a.posenet=this.instance.config.body.enabled&&!this.models.posenet&&((x=this.instance.config.body.modelPath)!=null&&x.includes("posenet"))?RT(this.instance.config):null,a.handtrack=this.instance.config.hand.enabled&&!this.models.handtrack&&((b=(A=this.instance.config.hand.detector)==null?void 0:A.modelPath)!=null&&b.includes("handtrack"))?oT(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&&S.includes("handtrack"))?lT(this.instance.config):null,this.instance.config.hand.enabled&&!this.models.handdetect&&((N=(C=this.instance.config.hand.detector)==null?void 0:C.modelPath)!=null&&N.includes("handdetect"))&&(a.handdetect=tT(this.instance.config),a.handskeleton=aT(this.instance.config)),a.centernet=this.instance.config.object.enabled&&!this.models.centernet&&((M=this.instance.config.object.modelPath)!=null&&M.includes("centernet"))?mI(this.instance.config):null,a.nanodet=this.instance.config.object.enabled&&!this.models.nanodet&&((F=this.instance.config.object.modelPath)!=null&&F.includes("nanodet"))?vT(this.instance.config):null,a.selfie=this.instance.config.segmentation.enabled&&!this.models.selfie&&((E=this.instance.config.segmentation.modelPath)!=null&&E.includes("selfie"))?Bx(this.instance.config):null,a.meet=this.instance.config.segmentation.enabled&&!this.models.meet&&((T=this.instance.config.segmentation.modelPath)!=null&&T.includes("meet"))?Tx(this.instance.config):null,a.rvm=this.instance.config.segmentation.enabled&&!this.models.rvm&&((D=this.instance.config.segmentation.modelPath)!=null&&D.includes("rvm"))?Wx(this.instance.config):null;for(let[O,W]of Object.entries(a))W!=null&&W.then&&W.then($=>this.models[O]=$);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(ya).find(r=>r.startsWith(a.name));n&&(a.size=ya[n].sizeLoadedWeights,a.url=ya[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=hm(this.instance,n,a);r&&t.push(r)}return t}};function OT(e,t,a,n,r){var o,l,u,d,c,p;let s=0,i=[];for(let h of e){let m={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]&&(m.body=b);if(m.body)for(let b of a)b.box[0]+b.box[2]>m.body.box[0]&&b.box[0]+b.box[2]<m.body.box[0]+m.body.box[2]&&b.box[1]+b.box[3]>m.body.box[1]&&b.box[1]+b.box[3]<m.body.box[1]+m.body.box[3]&&m.hands&&(m.hands.left=b),b.box[0]<m.body.box[0]+m.body.box[2]&&b.box[0]>m.body.box[0]&&b.box[1]+b.box[3]>m.body.box[1]&&b.box[1]+b.box[3]<m.body.box[1]+m.body.box[3]&&m.hands&&(m.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=m.body)==null?void 0:o.id)||b.hand!==void 0&&b.hand===((l=m.hands.left)==null?void 0:l.id)||b.hand!==void 0&&b.hand===((u=m.hands.right)==null?void 0:u.id))&&m.gestures.push(b);let f=[],g=[],y=b=>{b&&b.length===4&&(f.push(b[0],b[0]+b[2]),g.push(b[1],b[1]+b[3]))};y(m.face.box),y((d=m.body)==null?void 0:d.box),y((c=m.hands.left)==null?void 0:c.box),y((p=m.hands.right)==null?void 0:p.box);let x=Math.min(...f),A=Math.min(...g);m.box=[x,A,Math.max(...f)-x,Math.max(...g)-A],r!=null&&r[1]&&(r!=null&&r[2])&&(m.boxRaw=[m.box[0]/r[2],m.box[1]/r[1],m.box[2]/r[2],m.box[3]/r[1]]),i.push(m)}return i}var mm=`
|
|
/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==`,fm=`
|
|
/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 Fxe(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(mm);break;case"body":case"full":a=await t(fm);break;default:a=null}if(a){let r=await createImageBitmap(a);n=await e.detect(r,e.config),r.close()}return n}async function $xe(e){return new Promise(t=>{let a;switch(e.config.warmup){case"face":a="data:image/jpeg;base64,"+mm;break;case"full":case"body":a="data:image/jpeg;base64,"+fm;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=Dn(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 Dxe(e){let t=r=>Buffer.from(r,"base64"),a;e.config.warmup==="face"?a=t(mm):a=t(fm);let n;if("node"in Ye&&ea()==="tensorflow"){let r=py.decodeJpeg(a),s=Bt(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 Pxe(e){let t;return typeof createImageBitmap=="function"?t=await Fxe(e):typeof Image!="undefined"||ne.Canvas!==void 0?t=await $xe(e):t=await Dxe(e),t}async function _xe(e){var o,l,u,d;if(!B().flagRegistry.ENGINE_COMPILE_ONLY)return;let t=ea(),a=Gn();if(t!=="webgl"&&t!=="humangl"||!(a!=null&&a.checkCompileCompletion))return;B().set("ENGINE_COMPILE_ONLY",!0);let n=St().state.numTensors,r=[];for(let[c,p]of Object.entries(e.models.models)){if(!p)continue;let h=p!=null&&p.modelSignature&&((l=(o=p==null?void 0:p.inputs)==null?void 0:o[0])!=null&&l.shape)?[...p.inputs[0].shape]:[1,64,64,3],m=p!=null&&p.modelSignature&&((d=(u=p==null?void 0:p.inputs)==null?void 0:u[0])!=null&&d.dtype)?p.inputs[0].dtype:"float32";for(let g=0;g<h.length;g++)h[g]===-1&&(h[g]=g===0?1:64);let f=An(h,m);try{let g=p.execute(f);r.push(c),Array.isArray(g)?g.forEach(y=>J(y)):J(g)}catch(g){e.config.debug&&K("compile fail model:",c)}J(f)}let s=await a.checkCompileCompletionAsync();a.getUniformLocations(),e.config.debug&&K("compile pass:",{models:r,kernels:s.length}),B().set("ENGINE_COMPILE_ONLY",!1);let i=St().state.numTensors;i-n>0&&K("tensor leak:",i-n)}async function zT(e,t){await hc(e,!1);let a=ae();return e.state="warmup",t&&(e.config=Mt(e.config,t)),!e.config.warmup||e.config.warmup.length===0||e.config.warmup==="none"?fr():new Promise(async n=>{await e.models.load(),await _xe(e);let r=await Pxe(e),s=ae();e.config.debug&&K("warmup",e.config.warmup,Math.round(s-a),"ms"),e.emit("warmup"),n(r)})}var Ad,wc,kc,gm,ri,Ux=class{constructor(t){he(this,"version");he(this,"config");he(this,"result");he(this,"state");he(this,"process");he(this,"tf");he(this,"env",ne);he(this,"draw",F0);he(this,"match",im);he(this,"models");he(this,"events");he(this,"faceTriangulation");he(this,"faceUVMap");he(this,"performance");Yn(this,Ad,void 0);Yn(this,wc,void 0);Yn(this,kc,void 0);he(this,"analyze",(...t)=>{if(!Xa(this,wc))return;let a=this.tf.engine().state.numTensors,n=Xa(this,Ad);wr(this,Ad,a);let r=a-n;r!==0&&K(...t,r)});Yn(this,gm,t=>{if(!Xa(this,kc))return null;if(!t)return"input is not defined";if(this.env.node&&!(t instanceof yt))return"input must be a tensor";try{this.tf.getBackend()}catch(a){return"backend not loaded"}return null});he(this,"webcam",new S0);he(this,"emit",t=>{var a;(a=this.events)!=null&&a.dispatchEvent&&this.events.dispatchEvent(new Event(t))});Yn(this,ri,{});let a=(lc.tfjs||m3).replace(/-(.*)/,"");yl.wasmPath=`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${a}/dist/`,yl.modelBasePath=ne.browser?"../models/":"file://models/",this.version=yy,Object.defineProperty(this,"version",{value:yy}),this.config=JSON.parse(JSON.stringify(yl)),Object.seal(this.config),this.config.cacheModels=typeof indexedDB!="undefined",t&&(this.config=Mt(this.config,t)),K9(this.config),this.tf=Ye,this.state="idle",wr(this,Ad,0),wr(this,wc,!1),wr(this,kc,!1),this.performance={},this.events=typeof EventTarget!="undefined"?new EventTarget:void 0,this.models=new vc(this),Iy(),this.result=fr(),this.process={tensor:null,canvas:null},this.faceTriangulation=VI,this.faceUVMap=UI,hm(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(yl)),this.config.backend=t,fy(),ne.initial=!0}validate(t){let a=cy(yl,t||this.config);return a.length===0&&(this.config=Mt(this.config,t)),a}now(){return ae()}image(t,a=!1){return k0(t,this.config,a)}async segmentation(t,a){var s,i,o;if(a&&(this.config=Mt(this.config,a)),!this.config.segmentation.enabled)return null;let n=await k0(t,this.config);if(!n.tensor)return null;let r=null;return(s=this.config.segmentation.modelPath)!=null&&s.includes("rvm")&&(r=await $T(n.tensor,this.config)),(i=this.config.segmentation.modelPath)!=null&&i.includes("meet")&&(r=await pT(n.tensor,this.config)),(o=this.config.segmentation.modelPath)!=null&&o.includes("selfie")&&(r=await PT(n.tensor,this.config)),J(n.tensor),r}compare(t,a){return X9(this.config,t,a)}async init(){await hc(this,!0),await this.tf.ready(),fy()}async load(t){this.state="load";let a=ae(),n=Object.values(this.models.models).filter(i=>i).length;t&&(this.config=Mt(this.config,t)),this.env.initial&&(await hc(this,!1)||K("error: backend check failed"),await Vp(),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(ae()-a);s>(this.performance.loadModels||0)&&(this.performance.loadModels=this.env.perfadd?(this.performance.loadModels||0)+s:s)}next(t=this.result){return dT(t,this.config)}async warmup(t){let a=ae(),n=await zT(this,t),r=ae();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,y,x,A,b,w,S,C,N,M,F,E,T,D,O,W,$,U,G,q,H;this.state="config";let r;this.config=Mt(this.config,a),this.state="check";let s=Xa(this,gm).call(this,t);s&&(K(s,t),this.emit("error"),n(fr(s)));let i=ae();await this.load(),r=ae(),this.state="image";let o=await k0(t,this.config);if(this.process=o,this.performance.inputProcess=this.env.perfadd?(this.performance.inputProcess||0)+Math.trunc(ae()-r):Math.trunc(ae()-r),this.analyze("Get Image:"),!o.tensor){this.config.debug&&K("could not convert input to tensor"),this.emit("error"),n(fr("could not convert input to tensor"));return}this.emit("image"),r=ae(),this.config.skipAllowed=await q9(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(ae()-r):Math.trunc(ae()-r),this.analyze("Check Changed:");let l=[],u=[],d=[],c=[];this.state="detect:face",this.config.async?(l=this.config.face.enabled?cx(this,o.tensor):[],this.performance.face&&delete this.performance.face):(r=ae(),l=this.config.face.enabled?await cx(this,o.tensor):[],this.performance.face=this.env.perfadd?(this.performance.face||0)+Math.trunc(ae()-r):Math.trunc(ae()-r)),this.config.async&&(this.config.body.maxDetected===-1||this.config.hand.maxDetected===-1)&&(l=await l),this.analyze("Start Body:"),this.state="detect:body";let p=this.config.body.maxDetected===-1?Mt(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?Ox(o.tensor,p):[]:(y=this.config.body.modelPath)!=null&&y.includes("blazepose")?u=this.config.body.enabled?Ry(o.tensor,p):[]:(x=this.config.body.modelPath)!=null&&x.includes("efficientpose")?u=this.config.body.enabled?_y(o.tensor,p):[]:(A=this.config.body.modelPath)!=null&&A.includes("movenet")&&(u=this.config.body.enabled?Ex(o.tensor,p):[]),this.performance.body&&delete this.performance.body):(r=ae(),(b=this.config.body.modelPath)!=null&&b.includes("posenet")?u=this.config.body.enabled?await Ox(o.tensor,p):[]:(w=this.config.body.modelPath)!=null&&w.includes("blazepose")?u=this.config.body.enabled?await Ry(o.tensor,p):[]:(S=this.config.body.modelPath)!=null&&S.includes("efficientpose")?u=this.config.body.enabled?await _y(o.tensor,p):[]:(C=this.config.body.modelPath)!=null&&C.includes("movenet")&&(u=this.config.body.enabled?await Ex(o.tensor,p):[]),this.performance.body=this.env.perfadd?(this.performance.body||0)+Math.trunc(ae()-r):Math.trunc(ae()-r)),this.analyze("End Body:"),this.analyze("Start Hand:"),this.state="detect:hand";let h=this.config.hand.maxDetected===-1?Mt(this.config,{hand:{maxDetected:this.config.face.enabled?2*l.length:1}}):this.config;this.config.async?((M=(N=this.config.hand.detector)==null?void 0:N.modelPath)!=null&&M.includes("handdetect")?d=this.config.hand.enabled?xx(o.tensor,h):[]:(E=(F=this.config.hand.detector)==null?void 0:F.modelPath)!=null&&E.includes("handtrack")&&(d=this.config.hand.enabled?vx(o.tensor,h):[]),this.performance.hand&&delete this.performance.hand):(r=ae(),(D=(T=this.config.hand.detector)==null?void 0:T.modelPath)!=null&&D.includes("handdetect")?d=this.config.hand.enabled?await xx(o.tensor,h):[]:(W=(O=this.config.hand.detector)==null?void 0:O.modelPath)!=null&&W.includes("handtrack")&&(d=this.config.hand.enabled?await vx(o.tensor,h):[]),this.performance.hand=this.env.perfadd?(this.performance.hand||0)+Math.trunc(ae()-r):Math.trunc(ae()-r)),this.analyze("End Hand:"),this.analyze("Start Object:"),this.state="detect:object",this.config.async?(($=this.config.object.modelPath)!=null&&$.includes("nanodet")?c=this.config.object.enabled?Fx(o.tensor,this.config):[]:(U=this.config.object.modelPath)!=null&&U.includes("centernet")&&(c=this.config.object.enabled?Fy(o.tensor,this.config):[]),this.performance.object&&delete this.performance.object):(r=ae(),(G=this.config.object.modelPath)!=null&&G.includes("nanodet")?c=this.config.object.enabled?await Fx(o.tensor,this.config):[]:(q=this.config.object.modelPath)!=null&&q.includes("centernet")&&(c=this.config.object.enabled?await Fy(o.tensor,this.config):[]),this.performance.object=this.env.perfadd?(this.performance.object||0)+Math.trunc(ae()-r):Math.trunc(ae()-r)),this.analyze("End Object:"),this.state="detect:await",this.config.async&&([l,u,d,c]=await Promise.all([l,u,d,c])),this.state="detect:gesture";let m=[];this.config.gesture.enabled&&(r=ae(),m=[...WS(l),...LS(u),...VS(d),...BS(l)],this.config.async?this.performance.gesture&&delete this.performance.gesture:this.performance.gesture=this.env.perfadd?(this.performance.gesture||0)+Math.trunc(ae()-r):Math.trunc(ae()-r)),this.performance.total=this.env.perfadd?(this.performance.total||0)+Math.trunc(ae()-i):Math.trunc(ae()-i);let f=((H=this.process.tensor)==null?void 0:H.shape)||[0,0,0,0];this.result={face:l,body:u,hand:d,gesture:m,object:c,performance:this.performance,canvas:this.process.canvas,timestamp:Date.now(),error:null,width:f[2],height:f[1],get persons(){return OT(l,u,d,m,f)}},J(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?(Xa(this,ri)[t.id]||(this.config.debug&&K("video start",t.id),Xa(this,ri)[t.id]=!0),!t.paused&&Xa(this,ri)[t.id]&&t.readyState>=2&&await this.detect(t),n>0&&await this.sleep(n),Xa(this,ri)[t.id]&&requestAnimationFrame(()=>this.video(t,a,n))):(this.config.debug&&K("video stop",t.id),Xa(this,ri)[t.id]=!1)}};Ad=new WeakMap,wc=new WeakMap,kc=new WeakMap,gm=new WeakMap,ri=new WeakMap;return kC(zxe);})();
|